org.el (org-use-tag-inheritance): Fix typo in docstring
[org-mode.git] / lisp / org.el
blob826e96fe406cbca732509d023b77271f8e73ccbb
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2013 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 (load "org-loaddefs.el" t t)
83 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
84 ;; some places -- e.g. see the macro org-with-limited-levels.
86 ;; In Org buffers, the value of `outline-regexp' is that of
87 ;; `org-outline-regexp'. The only function still directly relying on
88 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
89 ;; job when `orgstruct-mode' is active.
90 (defvar org-outline-regexp "\\*+ "
91 "Regexp to match Org headlines.")
93 (defvar org-outline-regexp-bol "^\\*+ "
94 "Regexp to match Org headlines.
95 This is similar to `org-outline-regexp' but additionally makes
96 sure that we are at the beginning of the line.")
98 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
99 "Matches an headline, putting stars and text into groups.
100 Stars are put in group 1 and the trimmed body in group 2.")
102 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
103 (when (fboundp 'defvaralias)
104 (unless (boundp 'calendar-view-holidays-initially-flag)
105 (defvaralias 'calendar-view-holidays-initially-flag
106 'view-calendar-holidays-initially))
107 (unless (boundp 'calendar-view-diary-initially-flag)
108 (defvaralias 'calendar-view-diary-initially-flag
109 'view-diary-entries-initially))
110 (unless (boundp 'diary-fancy-buffer)
111 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
113 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
114 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
115 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
116 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
117 (declare-function org-at-clock-log-p "org-clock" ())
118 (declare-function org-clock-timestamps-up "org-clock" ())
119 (declare-function org-clock-timestamps-down "org-clock" ())
120 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
122 (declare-function orgtbl-mode "org-table" (&optional arg))
123 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
124 (declare-function org-beamer-mode "org-beamer" ())
125 (declare-function org-table-edit-field "org-table" (arg))
126 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
127 (declare-function org-id-get-create "org-id" (&optional force))
128 (declare-function org-id-find-id-file "org-id" (id))
129 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
130 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
131 (declare-function org-table-align "org-table" ())
132 (declare-function org-table-paste-rectangle "org-table" ())
133 (declare-function org-table-maybe-eval-formula "org-table" ())
134 (declare-function org-table-maybe-recalculate-line "org-table" ())
136 ;; load languages based on value of `org-babel-load-languages'
137 (defvar org-babel-load-languages)
139 ;;;###autoload
140 (defun org-babel-do-load-languages (sym value)
141 "Load the languages defined in `org-babel-load-languages'."
142 (set-default sym value)
143 (mapc (lambda (pair)
144 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
145 (if active
146 (progn
147 (require (intern (concat "ob-" lang))))
148 (progn
149 (funcall 'fmakunbound
150 (intern (concat "org-babel-execute:" lang)))
151 (funcall 'fmakunbound
152 (intern (concat "org-babel-expand-body:" lang)))))))
153 org-babel-load-languages))
155 (defcustom org-babel-load-languages '((emacs-lisp . t))
156 "Languages which can be evaluated in Org-mode buffers.
157 This list can be used to load support for any of the languages
158 below, note that each language will depend on a different set of
159 system executables and/or Emacs modes. When a language is
160 \"loaded\", then code blocks in that language can be evaluated
161 with `org-babel-execute-src-block' bound by default to C-c
162 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
163 be set to remove code block evaluation from the C-c C-c
164 keybinding. By default only Emacs Lisp (which has no
165 requirements) is loaded."
166 :group 'org-babel
167 :set 'org-babel-do-load-languages
168 :version "24.1"
169 :type '(alist :tag "Babel Languages"
170 :key-type
171 (choice
172 (const :tag "Awk" awk)
173 (const :tag "C" C)
174 (const :tag "R" R)
175 (const :tag "Asymptote" asymptote)
176 (const :tag "Calc" calc)
177 (const :tag "Clojure" clojure)
178 (const :tag "CSS" css)
179 (const :tag "Ditaa" ditaa)
180 (const :tag "Dot" dot)
181 (const :tag "Emacs Lisp" emacs-lisp)
182 (const :tag "Fortran" fortran)
183 (const :tag "Gnuplot" gnuplot)
184 (const :tag "Haskell" haskell)
185 (const :tag "IO" io)
186 (const :tag "Java" java)
187 (const :tag "Javascript" js)
188 (const :tag "LaTeX" latex)
189 (const :tag "Ledger" ledger)
190 (const :tag "Lilypond" lilypond)
191 (const :tag "Lisp" lisp)
192 (const :tag "Maxima" maxima)
193 (const :tag "Matlab" matlab)
194 (const :tag "Mscgen" mscgen)
195 (const :tag "Ocaml" ocaml)
196 (const :tag "Octave" octave)
197 (const :tag "Org" org)
198 (const :tag "Perl" perl)
199 (const :tag "Pico Lisp" picolisp)
200 (const :tag "PlantUML" plantuml)
201 (const :tag "Python" python)
202 (const :tag "Ruby" ruby)
203 (const :tag "Sass" sass)
204 (const :tag "Scala" scala)
205 (const :tag "Scheme" scheme)
206 (const :tag "Screen" screen)
207 (const :tag "Shell Script" sh)
208 (const :tag "Shen" shen)
209 (const :tag "Sql" sql)
210 (const :tag "Sqlite" sqlite))
211 :value-type (boolean :tag "Activate" :value t)))
213 ;;;; Customization variables
214 (defcustom org-clone-delete-id nil
215 "Remove ID property of clones of a subtree.
216 When non-nil, clones of a subtree don't inherit the ID property.
217 Otherwise they inherit the ID property with a new unique
218 identifier."
219 :type 'boolean
220 :version "24.1"
221 :group 'org-id)
223 ;;; Version
224 (require 'org-compat)
225 (org-check-version)
227 ;;;###autoload
228 (defun org-version (&optional here full message)
229 "Show the org-mode version in the echo area.
230 With prefix argument HERE, insert it at point.
231 When FULL is non-nil, use a verbose version string.
232 When MESSAGE is non-nil, display a message with the version."
233 (interactive "P")
234 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
235 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs.el")))
236 (org-trash (or
237 (and (fboundp 'org-release) (fboundp 'org-git-version))
238 (load (concat org-dir "org-version.el")
239 'noerror 'nomessage 'nosuffix)))
240 (org-version (org-release))
241 (git-version (org-git-version))
242 (version (format "Org-mode version %s (%s @ %s)"
243 org-version
244 git-version
245 (if org-install-dir
246 (if (string= org-dir org-install-dir)
247 org-install-dir
248 (concat "mixed installation! " org-install-dir " and " org-dir))
249 "org-loaddefs.el can not be found!")))
250 (_version (if full version org-version)))
251 (if (org-called-interactively-p 'interactive)
252 (if here
253 (insert version)
254 (message version))
255 (if message (message _version))
256 _version)))
258 (defconst org-version (org-version))
260 ;;; Compatibility constants
262 ;;; The custom variables
264 (defgroup org nil
265 "Outline-based notes management and organizer."
266 :tag "Org"
267 :group 'outlines
268 :group 'calendar)
270 (defcustom org-mode-hook nil
271 "Mode hook for Org-mode, run after the mode was turned on."
272 :group 'org
273 :type 'hook)
275 (defcustom org-load-hook nil
276 "Hook that is run after org.el has been loaded."
277 :group 'org
278 :type 'hook)
280 (defcustom org-log-buffer-setup-hook nil
281 "Hook that is run after an Org log buffer is created."
282 :group 'org
283 :version "24.1"
284 :type 'hook)
286 (defvar org-modules) ; defined below
287 (defvar org-modules-loaded nil
288 "Have the modules been loaded already?")
290 (defun org-load-modules-maybe (&optional force)
291 "Load all extensions listed in `org-modules'."
292 (when (or force (not org-modules-loaded))
293 (mapc (lambda (ext)
294 (condition-case nil (require ext)
295 (error (message "Problems while trying to load feature `%s'" ext))))
296 org-modules)
297 (setq org-modules-loaded t)))
299 (defun org-set-modules (var value)
300 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
301 (set var value)
302 (when (featurep 'org)
303 (org-load-modules-maybe 'force)))
305 (when (org-bound-and-true-p org-modules)
306 (let ((a (member 'org-infojs org-modules)))
307 (and a (setcar a 'org-jsinfo))))
309 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
310 "Modules that should always be loaded together with org.el.
311 If a description starts with <C>, the file is not part of Emacs
312 and loading it will require that you have downloaded and properly installed
313 the org-mode distribution.
315 You can also use this system to load external packages (i.e. neither Org
316 core modules, nor modules from the CONTRIB directory). Just add symbols
317 to the end of the list. If the package is called org-xyz.el, then you need
318 to add the symbol `xyz', and the package must have a call to
320 (provide 'org-xyz)"
321 :group 'org
322 :set 'org-set-modules
323 :type
324 '(set :greedy t
325 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
326 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
327 (const :tag " crypt: Encryption of subtrees" org-crypt)
328 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
329 (const :tag " docview: Links to doc-view buffers" org-docview)
330 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
331 (const :tag " id: Global IDs for identifying entries" org-id)
332 (const :tag " info: Links to Info nodes" org-info)
333 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
334 (const :tag " habit: Track your consistency with habits" org-habit)
335 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
336 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
337 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
338 (const :tag " mew Links to Mew folders/messages" org-mew)
339 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
340 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
341 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
342 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
343 (const :tag " vm: Links to VM folders/messages" org-vm)
344 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
345 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
346 (const :tag " mouse: Additional mouse support" org-mouse)
347 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
349 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
350 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
351 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
352 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
353 (const :tag "C collector: Collect properties into tables" org-collector)
354 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
355 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
356 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
357 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
358 (const :tag "C eval: Include command output as text" org-eval)
359 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
360 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
361 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
362 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
363 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
365 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
367 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
368 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
369 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
370 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
371 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
372 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
373 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
374 (const :tag "C mtags: Support for muse-like tags" org-mtags)
375 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
376 (const :tag "C registry: A registry for Org-mode links" org-registry)
377 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
378 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
379 (const :tag "C secretary: Team management with org-mode" org-secretary)
380 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
381 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
382 (const :tag "C track: Keep up with Org-mode development" org-track)
383 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
384 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
385 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
387 (defcustom org-support-shift-select nil
388 "Non-nil means make shift-cursor commands select text when possible.
390 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
391 start selecting a region, or enlarge regions started in this way.
392 In Org-mode, in special contexts, these same keys are used for
393 other purposes, important enough to compete with shift selection.
394 Org tries to balance these needs by supporting `shift-select-mode'
395 outside these special contexts, under control of this variable.
397 The default of this variable is nil, to avoid confusing behavior. Shifted
398 cursor keys will then execute Org commands in the following contexts:
399 - on a headline, changing TODO state (left/right) and priority (up/down)
400 - on a time stamp, changing the time
401 - in a plain list item, changing the bullet type
402 - in a property definition line, switching between allowed values
403 - in the BEGIN line of a clock table (changing the time block).
404 Outside these contexts, the commands will throw an error.
406 When this variable is t and the cursor is not in a special
407 context, Org-mode will support shift-selection for making and
408 enlarging regions. To make this more effective, the bullet
409 cycling will no longer happen anywhere in an item line, but only
410 if the cursor is exactly on the bullet.
412 If you set this variable to the symbol `always', then the keys
413 will not be special in headlines, property lines, and item lines,
414 to make shift selection work there as well. If this is what you
415 want, you can use the following alternative commands: `C-c C-t'
416 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
417 can be used to switch TODO sets, `C-c -' to cycle item bullet
418 types, and properties can be edited by hand or in column view.
420 However, when the cursor is on a timestamp, shift-cursor commands
421 will still edit the time stamp - this is just too good to give up.
423 XEmacs user should have this variable set to nil, because
424 `shift-select-mode' is in Emacs 23 or later only."
425 :group 'org
426 :type '(choice
427 (const :tag "Never" nil)
428 (const :tag "When outside special context" t)
429 (const :tag "Everywhere except timestamps" always)))
431 (defcustom org-loop-over-headlines-in-active-region nil
432 "Shall some commands act upon headlines in the active region?
434 When set to `t', some commands will be performed in all headlines
435 within the active region.
437 When set to `start-level', some commands will be performed in all
438 headlines within the active region, provided that these headlines
439 are of the same level than the first one.
441 When set to a string, those commands will be performed on the
442 matching headlines within the active region. Such string must be
443 a tags/property/todo match as it is used in the agenda tags view.
445 The list of commands is: `org-schedule', `org-deadline',
446 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
447 `org-archive-to-archive-sibling'. The archiving commands skip
448 already archived entries."
449 :type '(choice (const :tag "Don't loop" nil)
450 (const :tag "All headlines in active region" t)
451 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
452 (string :tag "Tags/Property/Todo matcher"))
453 :version "24.1"
454 :group 'org-todo
455 :group 'org-archive)
457 (defgroup org-startup nil
458 "Options concerning startup of Org-mode."
459 :tag "Org Startup"
460 :group 'org)
462 (defcustom org-startup-folded t
463 "Non-nil means entering Org-mode will switch to OVERVIEW.
464 This can also be configured on a per-file basis by adding one of
465 the following lines anywhere in the buffer:
467 #+STARTUP: fold (or `overview', this is equivalent)
468 #+STARTUP: nofold (or `showall', this is equivalent)
469 #+STARTUP: content
470 #+STARTUP: showeverything"
471 :group 'org-startup
472 :type '(choice
473 (const :tag "nofold: show all" nil)
474 (const :tag "fold: overview" t)
475 (const :tag "content: all headlines" content)
476 (const :tag "show everything, even drawers" showeverything)))
478 (defcustom org-startup-truncated t
479 "Non-nil means entering Org-mode will set `truncate-lines'.
480 This is useful since some lines containing links can be very long and
481 uninteresting. Also tables look terrible when wrapped."
482 :group 'org-startup
483 :type 'boolean)
485 (defcustom org-startup-indented nil
486 "Non-nil means turn on `org-indent-mode' on startup.
487 This can also be configured on a per-file basis by adding one of
488 the following lines anywhere in the buffer:
490 #+STARTUP: indent
491 #+STARTUP: noindent"
492 :group 'org-structure
493 :type '(choice
494 (const :tag "Not" nil)
495 (const :tag "Globally (slow on startup in large files)" t)))
497 (defcustom org-use-sub-superscripts t
498 "Non-nil means interpret \"_\" and \"^\" for export.
499 When this option is turned on, you can use TeX-like syntax for sub- and
500 superscripts. Several characters after \"_\" or \"^\" will be
501 considered as a single item - so grouping with {} is normally not
502 needed. For example, the following things will be parsed as single
503 sub- or superscripts.
505 10^24 or 10^tau several digits will be considered 1 item.
506 10^-12 or 10^-tau a leading sign with digits or a word
507 x^2-y^3 will be read as x^2 - y^3, because items are
508 terminated by almost any nonword/nondigit char.
509 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
511 Still, ambiguity is possible - so when in doubt use {} to enclose the
512 sub/superscript. If you set this variable to the symbol `{}',
513 the braces are *required* in order to trigger interpretations as
514 sub/superscript. This can be helpful in documents that need \"_\"
515 frequently in plain text.
517 Not all export backends support this, but HTML does.
519 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
520 :group 'org-startup
521 :group 'org-export-translation
522 :version "24.1"
523 :type '(choice
524 (const :tag "Always interpret" t)
525 (const :tag "Only with braces" {})
526 (const :tag "Never interpret" nil)))
528 (if (fboundp 'defvaralias)
529 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
532 (defcustom org-startup-with-beamer-mode nil
533 "Non-nil means turn on `org-beamer-mode' on startup.
534 This can also be configured on a per-file basis by adding one of
535 the following lines anywhere in the buffer:
537 #+STARTUP: beamer"
538 :group 'org-startup
539 :version "24.1"
540 :type 'boolean)
542 (defcustom org-startup-align-all-tables nil
543 "Non-nil means align all tables when visiting a file.
544 This is useful when the column width in tables is forced with <N> cookies
545 in table fields. Such tables will look correct only after the first re-align.
546 This can also be configured on a per-file basis by adding one of
547 the following lines anywhere in the buffer:
548 #+STARTUP: align
549 #+STARTUP: noalign"
550 :group 'org-startup
551 :type 'boolean)
553 (defcustom org-startup-with-inline-images nil
554 "Non-nil means show inline images when loading a new Org file.
555 This can also be configured on a per-file basis by adding one of
556 the following lines anywhere in the buffer:
557 #+STARTUP: inlineimages
558 #+STARTUP: noinlineimages"
559 :group 'org-startup
560 :version "24.1"
561 :type 'boolean)
563 (defcustom org-insert-mode-line-in-empty-file nil
564 "Non-nil means insert the first line setting Org-mode in empty files.
565 When the function `org-mode' is called interactively in an empty file, this
566 normally means that the file name does not automatically trigger Org-mode.
567 To ensure that the file will always be in Org-mode in the future, a
568 line enforcing Org-mode will be inserted into the buffer, if this option
569 has been set."
570 :group 'org-startup
571 :type 'boolean)
573 (defcustom org-replace-disputed-keys nil
574 "Non-nil means use alternative key bindings for some keys.
575 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
576 These keys are also used by other packages like shift-selection-mode'
577 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
578 If you want to use Org-mode together with one of these other modes,
579 or more generally if you would like to move some Org-mode commands to
580 other keys, set this variable and configure the keys with the variable
581 `org-disputed-keys'.
583 This option is only relevant at load-time of Org-mode, and must be set
584 *before* org.el is loaded. Changing it requires a restart of Emacs to
585 become effective."
586 :group 'org-startup
587 :type 'boolean)
589 (defcustom org-use-extra-keys nil
590 "Non-nil means use extra key sequence definitions for certain commands.
591 This happens automatically if you run XEmacs or if `window-system'
592 is nil. This variable lets you do the same manually. You must
593 set it before loading org.
595 Example: on Carbon Emacs 22 running graphically, with an external
596 keyboard on a Powerbook, the default way of setting M-left might
597 not work for either Alt or ESC. Setting this variable will make
598 it work for ESC."
599 :group 'org-startup
600 :type 'boolean)
602 (if (fboundp 'defvaralias)
603 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
605 (defcustom org-disputed-keys
606 '(([(shift up)] . [(meta p)])
607 ([(shift down)] . [(meta n)])
608 ([(shift left)] . [(meta -)])
609 ([(shift right)] . [(meta +)])
610 ([(control shift right)] . [(meta shift +)])
611 ([(control shift left)] . [(meta shift -)]))
612 "Keys for which Org-mode and other modes compete.
613 This is an alist, cars are the default keys, second element specifies
614 the alternative to use when `org-replace-disputed-keys' is t.
616 Keys can be specified in any syntax supported by `define-key'.
617 The value of this option takes effect only at Org-mode's startup,
618 therefore you'll have to restart Emacs to apply it after changing."
619 :group 'org-startup
620 :type 'alist)
622 (defun org-key (key)
623 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
624 Or return the original if not disputed.
625 Also apply the translations defined in `org-xemacs-key-equivalents'."
626 (when org-replace-disputed-keys
627 (let* ((nkey (key-description key))
628 (x (org-find-if (lambda (x)
629 (equal (key-description (car x)) nkey))
630 org-disputed-keys)))
631 (setq key (if x (cdr x) key))))
632 (when (featurep 'xemacs)
633 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
634 key)
636 (defun org-find-if (predicate seq)
637 (catch 'exit
638 (while seq
639 (if (funcall predicate (car seq))
640 (throw 'exit (car seq))
641 (pop seq)))))
643 (defun org-defkey (keymap key def)
644 "Define a key, possibly translated, as returned by `org-key'."
645 (define-key keymap (org-key key) def))
647 (defcustom org-ellipsis nil
648 "The ellipsis to use in the Org-mode outline.
649 When nil, just use the standard three dots. When a string, use that instead,
650 When a face, use the standard 3 dots, but with the specified face.
651 The change affects only Org-mode (which will then use its own display table).
652 Changing this requires executing `M-x org-mode' in a buffer to become
653 effective."
654 :group 'org-startup
655 :type '(choice (const :tag "Default" nil)
656 (face :tag "Face" :value org-warning)
657 (string :tag "String" :value "...#")))
659 (defvar org-display-table nil
660 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
662 (defgroup org-keywords nil
663 "Keywords in Org-mode."
664 :tag "Org Keywords"
665 :group 'org)
667 (defcustom org-deadline-string "DEADLINE:"
668 "String to mark deadline entries.
669 A deadline is this string, followed by a time stamp. Should be a word,
670 terminated by a colon. You can insert a schedule keyword and
671 a timestamp with \\[org-deadline].
672 Changes become only effective after restarting Emacs."
673 :group 'org-keywords
674 :type 'string)
676 (defcustom org-scheduled-string "SCHEDULED:"
677 "String to mark scheduled TODO entries.
678 A schedule is this string, followed by a time stamp. Should be a word,
679 terminated by a colon. You can insert a schedule keyword and
680 a timestamp with \\[org-schedule].
681 Changes become only effective after restarting Emacs."
682 :group 'org-keywords
683 :type 'string)
685 (defcustom org-closed-string "CLOSED:"
686 "String used as the prefix for timestamps logging closing a TODO entry."
687 :group 'org-keywords
688 :type 'string)
690 (defcustom org-clock-string "CLOCK:"
691 "String used as prefix for timestamps clocking work hours on an item."
692 :group 'org-keywords
693 :type 'string)
695 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
696 org-scheduled-string "\\|"
697 org-deadline-string "\\|"
698 org-closed-string "\\|"
699 org-clock-string "\\)")
700 "Matches a line with planning or clock info.")
702 (defcustom org-comment-string "COMMENT"
703 "Entries starting with this keyword will never be exported.
704 An entry can be toggled between COMMENT and normal with
705 \\[org-toggle-comment].
706 Changes become only effective after restarting Emacs."
707 :group 'org-keywords
708 :type 'string)
710 (defcustom org-quote-string "QUOTE"
711 "Entries starting with this keyword will be exported in fixed-width font.
712 Quoting applies only to the text in the entry following the headline, and does
713 not extend beyond the next headline, even if that is lower level.
714 An entry can be toggled between QUOTE and normal with
715 \\[org-toggle-fixed-width-section]."
716 :group 'org-keywords
717 :type 'string)
719 (defconst org-repeat-re
720 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
721 "Regular expression for specifying repeated events.
722 After a match, group 1 contains the repeat expression.")
724 (defgroup org-structure nil
725 "Options concerning the general structure of Org-mode files."
726 :tag "Org Structure"
727 :group 'org)
729 (defgroup org-reveal-location nil
730 "Options about how to make context of a location visible."
731 :tag "Org Reveal Location"
732 :group 'org-structure)
734 (defconst org-context-choice
735 '(choice
736 (const :tag "Always" t)
737 (const :tag "Never" nil)
738 (repeat :greedy t :tag "Individual contexts"
739 (cons
740 (choice :tag "Context"
741 (const agenda)
742 (const org-goto)
743 (const occur-tree)
744 (const tags-tree)
745 (const link-search)
746 (const mark-goto)
747 (const bookmark-jump)
748 (const isearch)
749 (const default))
750 (boolean))))
751 "Contexts for the reveal options.")
753 (defcustom org-show-hierarchy-above '((default . t))
754 "Non-nil means show full hierarchy when revealing a location.
755 Org-mode often shows locations in an org-mode file which might have
756 been invisible before. When this is set, the hierarchy of headings
757 above the exposed location is shown.
758 Turning this off for example for sparse trees makes them very compact.
759 Instead of t, this can also be an alist specifying this option for different
760 contexts. Valid contexts are
761 agenda when exposing an entry from the agenda
762 org-goto when using the command `org-goto' on key C-c C-j
763 occur-tree when using the command `org-occur' on key C-c /
764 tags-tree when constructing a sparse tree based on tags matches
765 link-search when exposing search matches associated with a link
766 mark-goto when exposing the jump goal of a mark
767 bookmark-jump when exposing a bookmark location
768 isearch when exiting from an incremental search
769 default default for all contexts not set explicitly"
770 :group 'org-reveal-location
771 :type org-context-choice)
773 (defcustom org-show-following-heading '((default . nil))
774 "Non-nil means show following heading when revealing a location.
775 Org-mode often shows locations in an org-mode file which might have
776 been invisible before. When this is set, the heading following the
777 match is shown.
778 Turning this off for example for sparse trees makes them very compact,
779 but makes it harder to edit the location of the match. In such a case,
780 use the command \\[org-reveal] to show more context.
781 Instead of t, this can also be an alist specifying this option for different
782 contexts. See `org-show-hierarchy-above' for valid contexts."
783 :group 'org-reveal-location
784 :type org-context-choice)
786 (defcustom org-show-siblings '((default . nil) (isearch t))
787 "Non-nil means show all sibling heading when revealing a location.
788 Org-mode often shows locations in an org-mode file which might have
789 been invisible before. When this is set, the sibling of the current entry
790 heading are all made visible. If `org-show-hierarchy-above' is t,
791 the same happens on each level of the hierarchy above the current entry.
793 By default this is on for the isearch context, off for all other contexts.
794 Turning this off for example for sparse trees makes them very compact,
795 but makes it harder to edit the location of the match. In such a case,
796 use the command \\[org-reveal] to show more context.
797 Instead of t, this can also be an alist specifying this option for different
798 contexts. See `org-show-hierarchy-above' for valid contexts."
799 :group 'org-reveal-location
800 :type org-context-choice)
802 (defcustom org-show-entry-below '((default . nil))
803 "Non-nil means show the entry below a headline when revealing a location.
804 Org-mode often shows locations in an org-mode file which might have
805 been invisible before. When this is set, the text below the headline that is
806 exposed is also shown.
808 By default this is off for all contexts.
809 Instead of t, this can also be an alist specifying this option for different
810 contexts. See `org-show-hierarchy-above' for valid contexts."
811 :group 'org-reveal-location
812 :type org-context-choice)
814 (defcustom org-indirect-buffer-display 'other-window
815 "How should indirect tree buffers be displayed?
816 This applies to indirect buffers created with the commands
817 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
818 Valid values are:
819 current-window Display in the current window
820 other-window Just display in another window.
821 dedicated-frame Create one new frame, and re-use it each time.
822 new-frame Make a new frame each time. Note that in this case
823 previously-made indirect buffers are kept, and you need to
824 kill these buffers yourself."
825 :group 'org-structure
826 :group 'org-agenda-windows
827 :type '(choice
828 (const :tag "In current window" current-window)
829 (const :tag "In current frame, other window" other-window)
830 (const :tag "Each time a new frame" new-frame)
831 (const :tag "One dedicated frame" dedicated-frame)))
833 (defcustom org-use-speed-commands nil
834 "Non-nil means activate single letter commands at beginning of a headline.
835 This may also be a function to test for appropriate locations where speed
836 commands should be active."
837 :group 'org-structure
838 :type '(choice
839 (const :tag "Never" nil)
840 (const :tag "At beginning of headline stars" t)
841 (function)))
843 (defcustom org-speed-commands-user nil
844 "Alist of additional speed commands.
845 This list will be checked before `org-speed-commands-default'
846 when the variable `org-use-speed-commands' is non-nil
847 and when the cursor is at the beginning of a headline.
848 The car if each entry is a string with a single letter, which must
849 be assigned to `self-insert-command' in the global map.
850 The cdr is either a command to be called interactively, a function
851 to be called, or a form to be evaluated.
852 An entry that is just a list with a single string will be interpreted
853 as a descriptive headline that will be added when listing the speed
854 commands in the Help buffer using the `?' speed command."
855 :group 'org-structure
856 :type '(repeat :value ("k" . ignore)
857 (choice :value ("k" . ignore)
858 (list :tag "Descriptive Headline" (string :tag "Headline"))
859 (cons :tag "Letter and Command"
860 (string :tag "Command letter")
861 (choice
862 (function)
863 (sexp))))))
865 (defgroup org-cycle nil
866 "Options concerning visibility cycling in Org-mode."
867 :tag "Org Cycle"
868 :group 'org-structure)
870 (defcustom org-cycle-skip-children-state-if-no-children t
871 "Non-nil means skip CHILDREN state in entries that don't have any."
872 :group 'org-cycle
873 :type 'boolean)
875 (defcustom org-cycle-max-level nil
876 "Maximum level which should still be subject to visibility cycling.
877 Levels higher than this will, for cycling, be treated as text, not a headline.
878 When `org-odd-levels-only' is set, a value of N in this variable actually
879 means 2N-1 stars as the limiting headline.
880 When nil, cycle all levels.
881 Note that the limiting level of cycling is also influenced by
882 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
883 `org-inlinetask-min-level' is, cycling will be limited to levels one less
884 than its value."
885 :group 'org-cycle
886 :type '(choice
887 (const :tag "No limit" nil)
888 (integer :tag "Maximum level")))
890 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
891 "Names of drawers. Drawers are not opened by cycling on the headline above.
892 Drawers only open with a TAB on the drawer line itself. A drawer looks like
893 this:
894 :DRAWERNAME:
895 .....
896 :END:
897 The drawer \"PROPERTIES\" is special for capturing properties through
898 the property API.
900 Drawers can be defined on the per-file basis with a line like:
902 #+DRAWERS: HIDDEN STATE PROPERTIES"
903 :group 'org-structure
904 :group 'org-cycle
905 :type '(repeat (string :tag "Drawer Name")))
907 (defcustom org-hide-block-startup nil
908 "Non-nil means entering Org-mode will fold all blocks.
909 This can also be set in on a per-file basis with
911 #+STARTUP: hideblocks
912 #+STARTUP: showblocks"
913 :group 'org-startup
914 :group 'org-cycle
915 :type 'boolean)
917 (defcustom org-cycle-global-at-bob nil
918 "Cycle globally if cursor is at beginning of buffer and not at a headline.
919 This makes it possible to do global cycling without having to use S-TAB or
920 \\[universal-argument] TAB. For this special case to work, the first line
921 of the buffer must not be a headline -- it may be empty or some other text.
922 When used in this way, `org-cycle-hook' is disabled temporarily to make
923 sure the cursor stays at the beginning of the buffer. When this option is
924 nil, don't do anything special at the beginning of the buffer."
925 :group 'org-cycle
926 :type 'boolean)
928 (defcustom org-cycle-level-after-item/entry-creation t
929 "Non-nil means cycle entry level or item indentation in new empty entries.
931 When the cursor is at the end of an empty headline, i.e with only stars
932 and maybe a TODO keyword, TAB will then switch the entry to become a child,
933 and then all possible ancestor states, before returning to the original state.
934 This makes data entry extremely fast: M-RET to create a new headline,
935 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
937 When the cursor is at the end of an empty plain list item, one TAB will
938 make it a subitem, two or more tabs will back up to make this an item
939 higher up in the item hierarchy."
940 :group 'org-cycle
941 :type 'boolean)
943 (defcustom org-cycle-emulate-tab t
944 "Where should `org-cycle' emulate TAB.
945 nil Never
946 white Only in completely white lines
947 whitestart Only at the beginning of lines, before the first non-white char
948 t Everywhere except in headlines
949 exc-hl-bol Everywhere except at the start of a headline
950 If TAB is used in a place where it does not emulate TAB, the current subtree
951 visibility is cycled."
952 :group 'org-cycle
953 :type '(choice (const :tag "Never" nil)
954 (const :tag "Only in completely white lines" white)
955 (const :tag "Before first char in a line" whitestart)
956 (const :tag "Everywhere except in headlines" t)
957 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
960 (defcustom org-cycle-separator-lines 2
961 "Number of empty lines needed to keep an empty line between collapsed trees.
962 If you leave an empty line between the end of a subtree and the following
963 headline, this empty line is hidden when the subtree is folded.
964 Org-mode will leave (exactly) one empty line visible if the number of
965 empty lines is equal or larger to the number given in this variable.
966 So the default 2 means at least 2 empty lines after the end of a subtree
967 are needed to produce free space between a collapsed subtree and the
968 following headline.
970 If the number is negative, and the number of empty lines is at least -N,
971 all empty lines are shown.
973 Special case: when 0, never leave empty lines in collapsed view."
974 :group 'org-cycle
975 :type 'integer)
976 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
978 (defcustom org-pre-cycle-hook nil
979 "Hook that is run before visibility cycling is happening.
980 The function(s) in this hook must accept a single argument which indicates
981 the new state that will be set right after running this hook. The
982 argument is a symbol. Before a global state change, it can have the values
983 `overview', `content', or `all'. Before a local state change, it can have
984 the values `folded', `children', or `subtree'."
985 :group 'org-cycle
986 :type 'hook)
988 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
989 org-cycle-hide-drawers
990 org-cycle-show-empty-lines
991 org-optimize-window-after-visibility-change)
992 "Hook that is run after `org-cycle' has changed the buffer visibility.
993 The function(s) in this hook must accept a single argument which indicates
994 the new state that was set by the most recent `org-cycle' command. The
995 argument is a symbol. After a global state change, it can have the values
996 `overview', `contents', or `all'. After a local state change, it can have
997 the values `folded', `children', or `subtree'."
998 :group 'org-cycle
999 :type 'hook)
1001 (defgroup org-edit-structure nil
1002 "Options concerning structure editing in Org-mode."
1003 :tag "Org Edit Structure"
1004 :group 'org-structure)
1006 (defcustom org-odd-levels-only nil
1007 "Non-nil means skip even levels and only use odd levels for the outline.
1008 This has the effect that two stars are being added/taken away in
1009 promotion/demotion commands. It also influences how levels are
1010 handled by the exporters.
1011 Changing it requires restart of `font-lock-mode' to become effective
1012 for fontification also in regions already fontified.
1013 You may also set this on a per-file basis by adding one of the following
1014 lines to the buffer:
1016 #+STARTUP: odd
1017 #+STARTUP: oddeven"
1018 :group 'org-edit-structure
1019 :group 'org-appearance
1020 :type 'boolean)
1022 (defcustom org-adapt-indentation t
1023 "Non-nil means adapt indentation to outline node level.
1025 When this variable is set, Org assumes that you write outlines by
1026 indenting text in each node to align with the headline (after the stars).
1027 The following issues are influenced by this variable:
1029 - When this is set and the *entire* text in an entry is indented, the
1030 indentation is increased by one space in a demotion command, and
1031 decreased by one in a promotion command. If any line in the entry
1032 body starts with text at column 0, indentation is not changed at all.
1034 - Property drawers and planning information is inserted indented when
1035 this variable s set. When nil, they will not be indented.
1037 - TAB indents a line relative to context. The lines below a headline
1038 will be indented when this variable is set.
1040 Note that this is all about true indentation, by adding and removing
1041 space characters. See also `org-indent.el' which does level-dependent
1042 indentation in a virtual way, i.e. at display time in Emacs."
1043 :group 'org-edit-structure
1044 :type 'boolean)
1046 (defcustom org-special-ctrl-a/e nil
1047 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1049 When t, `C-a' will bring back the cursor to the beginning of the
1050 headline text, i.e. after the stars and after a possible TODO
1051 keyword. In an item, this will be the position after bullet and
1052 check-box, if any. When the cursor is already at that position,
1053 another `C-a' will bring it to the beginning of the line.
1055 `C-e' will jump to the end of the headline, ignoring the presence
1056 of tags in the headline. A second `C-e' will then jump to the
1057 true end of the line, after any tags. This also means that, when
1058 this variable is non-nil, `C-e' also will never jump beyond the
1059 end of the heading of a folded section, i.e. not after the
1060 ellipses.
1062 When set to the symbol `reversed', the first `C-a' or `C-e' works
1063 normally, going to the true line boundary first. Only a directly
1064 following, identical keypress will bring the cursor to the
1065 special positions.
1067 This may also be a cons cell where the behavior for `C-a' and
1068 `C-e' is set separately."
1069 :group 'org-edit-structure
1070 :type '(choice
1071 (const :tag "off" nil)
1072 (const :tag "on: after stars/bullet and before tags first" t)
1073 (const :tag "reversed: true line boundary first" reversed)
1074 (cons :tag "Set C-a and C-e separately"
1075 (choice :tag "Special C-a"
1076 (const :tag "off" nil)
1077 (const :tag "on: after stars/bullet first" t)
1078 (const :tag "reversed: before stars/bullet first" reversed))
1079 (choice :tag "Special C-e"
1080 (const :tag "off" nil)
1081 (const :tag "on: before tags first" t)
1082 (const :tag "reversed: after tags first" reversed)))))
1083 (if (fboundp 'defvaralias)
1084 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1086 (defcustom org-special-ctrl-k nil
1087 "Non-nil means `C-k' will behave specially in headlines.
1088 When nil, `C-k' will call the default `kill-line' command.
1089 When t, the following will happen while the cursor is in the headline:
1091 - When the cursor is at the beginning of a headline, kill the entire
1092 line and possible the folded subtree below the line.
1093 - When in the middle of the headline text, kill the headline up to the tags.
1094 - When after the headline text, kill the tags."
1095 :group 'org-edit-structure
1096 :type 'boolean)
1098 (defcustom org-ctrl-k-protect-subtree nil
1099 "Non-nil means, do not delete a hidden subtree with C-k.
1100 When set to the symbol `error', simply throw an error when C-k is
1101 used to kill (part-of) a headline that has hidden text behind it.
1102 Any other non-nil value will result in a query to the user, if it is
1103 OK to kill that hidden subtree. When nil, kill without remorse."
1104 :group 'org-edit-structure
1105 :version "24.1"
1106 :type '(choice
1107 (const :tag "Do not protect hidden subtrees" nil)
1108 (const :tag "Protect hidden subtrees with a security query" t)
1109 (const :tag "Never kill a hidden subtree with C-k" error)))
1111 (defcustom org-catch-invisible-edits nil
1112 "Check if in invisible region before inserting or deleting a character.
1113 Valid values are:
1115 nil Do not check, so just do invisible edits.
1116 error Throw an error and do nothing.
1117 show Make point visible, and do the requested edit.
1118 show-and-error Make point visible, then throw an error and abort the edit.
1119 smart Make point visible, and do insertion/deletion if it is
1120 adjacent to visible text and the change feels predictable.
1121 Never delete a previously invisible character or add in the
1122 middle or right after an invisible region. Basically, this
1123 allows insertion and backward-delete right before ellipses.
1124 FIXME: maybe in this case we should not even show?"
1125 :group 'org-edit-structure
1126 :version "24.1"
1127 :type '(choice
1128 (const :tag "Do not check" nil)
1129 (const :tag "Throw error when trying to edit" error)
1130 (const :tag "Unhide, but do not do the edit" show-and-error)
1131 (const :tag "Show invisible part and do the edit" show)
1132 (const :tag "Be smart and do the right thing" smart)))
1134 (defcustom org-yank-folded-subtrees t
1135 "Non-nil means when yanking subtrees, fold them.
1136 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1137 it starts with a heading and all other headings in it are either children
1138 or siblings, then fold all the subtrees. However, do this only if no
1139 text after the yank would be swallowed into a folded tree by this action."
1140 :group 'org-edit-structure
1141 :type 'boolean)
1143 (defcustom org-yank-adjusted-subtrees nil
1144 "Non-nil means when yanking subtrees, adjust the level.
1145 With this setting, `org-paste-subtree' is used to insert the subtree, see
1146 this function for details."
1147 :group 'org-edit-structure
1148 :type 'boolean)
1150 (defcustom org-M-RET-may-split-line '((default . t))
1151 "Non-nil means M-RET will split the line at the cursor position.
1152 When nil, it will go to the end of the line before making a
1153 new line.
1154 You may also set this option in a different way for different
1155 contexts. Valid contexts are:
1157 headline when creating a new headline
1158 item when creating a new item
1159 table in a table field
1160 default the value to be used for all contexts not explicitly
1161 customized"
1162 :group 'org-structure
1163 :group 'org-table
1164 :type '(choice
1165 (const :tag "Always" t)
1166 (const :tag "Never" nil)
1167 (repeat :greedy t :tag "Individual contexts"
1168 (cons
1169 (choice :tag "Context"
1170 (const headline)
1171 (const item)
1172 (const table)
1173 (const default))
1174 (boolean)))))
1177 (defcustom org-insert-heading-respect-content nil
1178 "Non-nil means insert new headings after the current subtree.
1179 When nil, the new heading is created directly after the current line.
1180 The commands \\[org-insert-heading-respect-content] and
1181 \\[org-insert-todo-heading-respect-content] turn this variable on
1182 for the duration of the command."
1183 :group 'org-structure
1184 :type 'boolean)
1186 (defcustom org-blank-before-new-entry '((heading . auto)
1187 (plain-list-item . auto))
1188 "Should `org-insert-heading' leave a blank line before new heading/item?
1189 The value is an alist, with `heading' and `plain-list-item' as CAR,
1190 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1191 which case Org will look at the surrounding headings/items and try to
1192 make an intelligent decision whether to insert a blank line or not.
1194 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1195 set, the setting here is ignored and no empty line is inserted, to avoid
1196 breaking the list structure."
1197 :group 'org-edit-structure
1198 :type '(list
1199 (cons (const heading)
1200 (choice (const :tag "Never" nil)
1201 (const :tag "Always" t)
1202 (const :tag "Auto" auto)))
1203 (cons (const plain-list-item)
1204 (choice (const :tag "Never" nil)
1205 (const :tag "Always" t)
1206 (const :tag "Auto" auto)))))
1208 (defcustom org-insert-heading-hook nil
1209 "Hook being run after inserting a new heading."
1210 :group 'org-edit-structure
1211 :type 'hook)
1213 (defcustom org-enable-fixed-width-editor t
1214 "Non-nil means lines starting with \":\" are treated as fixed-width.
1215 This currently only means they are never auto-wrapped.
1216 When nil, such lines will be treated like ordinary lines.
1217 See also the QUOTE keyword."
1218 :group 'org-edit-structure
1219 :type 'boolean)
1221 (defcustom org-goto-auto-isearch t
1222 "Non-nil means typing characters in `org-goto' starts incremental search.
1223 When nil, you can use these keybindings to navigate the buffer:
1225 q Quit the org-goto interface
1226 n Go to the next visible heading
1227 p Go to the previous visible heading
1228 f Go one heading forward on same level
1229 b Go one heading backward on same level
1230 u Go one heading up"
1231 :group 'org-edit-structure
1232 :type 'boolean)
1234 (defgroup org-sparse-trees nil
1235 "Options concerning sparse trees in Org-mode."
1236 :tag "Org Sparse Trees"
1237 :group 'org-structure)
1239 (defcustom org-highlight-sparse-tree-matches t
1240 "Non-nil means highlight all matches that define a sparse tree.
1241 The highlights will automatically disappear the next time the buffer is
1242 changed by an edit command."
1243 :group 'org-sparse-trees
1244 :type 'boolean)
1246 (defcustom org-remove-highlights-with-change t
1247 "Non-nil means any change to the buffer will remove temporary highlights.
1248 Such highlights are created by `org-occur' and `org-clock-display'.
1249 When nil, `C-c C-c needs to be used to get rid of the highlights.
1250 The highlights created by `org-preview-latex-fragment' always need
1251 `C-c C-c' to be removed."
1252 :group 'org-sparse-trees
1253 :group 'org-time
1254 :type 'boolean)
1257 (defcustom org-occur-hook '(org-first-headline-recenter)
1258 "Hook that is run after `org-occur' has constructed a sparse tree.
1259 This can be used to recenter the window to show as much of the structure
1260 as possible."
1261 :group 'org-sparse-trees
1262 :type 'hook)
1264 (defgroup org-imenu-and-speedbar nil
1265 "Options concerning imenu and speedbar in Org-mode."
1266 :tag "Org Imenu and Speedbar"
1267 :group 'org-structure)
1269 (defcustom org-imenu-depth 2
1270 "The maximum level for Imenu access to Org-mode headlines.
1271 This also applied for speedbar access."
1272 :group 'org-imenu-and-speedbar
1273 :type 'integer)
1275 (defgroup org-table nil
1276 "Options concerning tables in Org-mode."
1277 :tag "Org Table"
1278 :group 'org)
1280 (defcustom org-enable-table-editor 'optimized
1281 "Non-nil means lines starting with \"|\" are handled by the table editor.
1282 When nil, such lines will be treated like ordinary lines.
1284 When equal to the symbol `optimized', the table editor will be optimized to
1285 do the following:
1286 - Automatic overwrite mode in front of whitespace in table fields.
1287 This makes the structure of the table stay in tact as long as the edited
1288 field does not exceed the column width.
1289 - Minimize the number of realigns. Normally, the table is aligned each time
1290 TAB or RET are pressed to move to another field. With optimization this
1291 happens only if changes to a field might have changed the column width.
1292 Optimization requires replacing the functions `self-insert-command',
1293 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1294 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1295 very good at guessing when a re-align will be necessary, but you can always
1296 force one with \\[org-ctrl-c-ctrl-c].
1298 If you would like to use the optimized version in Org-mode, but the
1299 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1301 This variable can be used to turn on and off the table editor during a session,
1302 but in order to toggle optimization, a restart is required.
1304 See also the variable `org-table-auto-blank-field'."
1305 :group 'org-table
1306 :type '(choice
1307 (const :tag "off" nil)
1308 (const :tag "on" t)
1309 (const :tag "on, optimized" optimized)))
1311 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1312 (version<= emacs-version "24.1"))
1313 "Non-nil means cluster self-insert commands for undo when possible.
1314 If this is set, then, like in the Emacs command loop, 20 consecutive
1315 characters will be undone together.
1316 This is configurable, because there is some impact on typing performance."
1317 :group 'org-table
1318 :type 'boolean)
1320 (defcustom org-table-tab-recognizes-table.el t
1321 "Non-nil means TAB will automatically notice a table.el table.
1322 When it sees such a table, it moves point into it and - if necessary -
1323 calls `table-recognize-table'."
1324 :group 'org-table-editing
1325 :type 'boolean)
1327 (defgroup org-link nil
1328 "Options concerning links in Org-mode."
1329 :tag "Org Link"
1330 :group 'org)
1332 (defvar org-link-abbrev-alist-local nil
1333 "Buffer-local version of `org-link-abbrev-alist', which see.
1334 The value of this is taken from the #+LINK lines.")
1335 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1337 (defcustom org-link-abbrev-alist nil
1338 "Alist of link abbreviations.
1339 The car of each element is a string, to be replaced at the start of a link.
1340 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1341 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1343 [[linkkey:tag][description]]
1345 The 'linkkey' must be a word word, starting with a letter, followed
1346 by letters, numbers, '-' or '_'.
1348 If REPLACE is a string, the tag will simply be appended to create the link.
1349 If the string contains \"%s\", the tag will be inserted there. If the string
1350 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1351 at that point (see the function `url-hexify-string'). If the string contains
1352 the specifier \"%(my-function)\", then the custom function `my-function' will
1353 be invoked: this function takes the tag as its only argument and must return
1354 a string.
1356 REPLACE may also be a function that will be called with the tag as the
1357 only argument to create the link, which should be returned as a string.
1359 See the manual for examples."
1360 :group 'org-link
1361 :type '(repeat
1362 (cons
1363 (string :tag "Protocol")
1364 (choice
1365 (string :tag "Format")
1366 (function)))))
1368 (defcustom org-descriptive-links t
1369 "Non-nil means Org will display descriptive links.
1370 E.g. [[http://orgmode.org][Org website]] will be displayed as
1371 \"Org Website\", hiding the link itself and just displaying its
1372 description. When set to `nil', Org will display the full links
1373 literally.
1375 You can interactively set the value of this variable by calling
1376 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1377 :group 'org-link
1378 :type 'boolean)
1380 (defcustom org-link-file-path-type 'adaptive
1381 "How the path name in file links should be stored.
1382 Valid values are:
1384 relative Relative to the current directory, i.e. the directory of the file
1385 into which the link is being inserted.
1386 absolute Absolute path, if possible with ~ for home directory.
1387 noabbrev Absolute path, no abbreviation of home directory.
1388 adaptive Use relative path for files in the current directory and sub-
1389 directories of it. For other files, use an absolute path."
1390 :group 'org-link
1391 :type '(choice
1392 (const relative)
1393 (const absolute)
1394 (const noabbrev)
1395 (const adaptive)))
1397 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1398 "Types of links that should be activated in Org-mode files.
1399 This is a list of symbols, each leading to the activation of a certain link
1400 type. In principle, it does not hurt to turn on most link types - there may
1401 be a small gain when turning off unused link types. The types are:
1403 bracket The recommended [[link][description]] or [[link]] links with hiding.
1404 angle Links in angular brackets that may contain whitespace like
1405 <bbdb:Carsten Dominik>.
1406 plain Plain links in normal text, no whitespace, like http://google.com.
1407 radio Text that is matched by a radio target, see manual for details.
1408 tag Tag settings in a headline (link to tag search).
1409 date Time stamps (link to calendar).
1410 footnote Footnote labels.
1412 Changing this variable requires a restart of Emacs to become effective."
1413 :group 'org-link
1414 :type '(set :greedy t
1415 (const :tag "Double bracket links" bracket)
1416 (const :tag "Angular bracket links" angle)
1417 (const :tag "Plain text links" plain)
1418 (const :tag "Radio target matches" radio)
1419 (const :tag "Tags" tag)
1420 (const :tag "Timestamps" date)
1421 (const :tag "Footnotes" footnote)))
1423 (defcustom org-make-link-description-function nil
1424 "Function to use for generating link descriptions from links.
1425 When nil, the link location will be used. This function must take
1426 two parameters: the first one is the link, the second one is the
1427 description generated by `org-insert-link'. The function should
1428 return the description to use."
1429 :group 'org-link
1430 :type 'function)
1432 (defgroup org-link-store nil
1433 "Options concerning storing links in Org-mode."
1434 :tag "Org Store Link"
1435 :group 'org-link)
1437 (defcustom org-url-hexify-p t
1438 "When non-nil, hexify URL when creating a link."
1439 :type 'boolean
1440 :version "24.3"
1441 :group 'org-link-store)
1443 (defcustom org-email-link-description-format "Email %c: %.30s"
1444 "Format of the description part of a link to an email or usenet message.
1445 The following %-escapes will be replaced by corresponding information:
1447 %F full \"From\" field
1448 %f name, taken from \"From\" field, address if no name
1449 %T full \"To\" field
1450 %t first name in \"To\" field, address if no name
1451 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1452 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1453 %s subject
1454 %d date
1455 %m message-id.
1457 You may use normal field width specification between the % and the letter.
1458 This is for example useful to limit the length of the subject.
1460 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1461 :group 'org-link-store
1462 :type 'string)
1464 (defcustom org-from-is-user-regexp
1465 (let (r1 r2)
1466 (when (and user-mail-address (not (string= user-mail-address "")))
1467 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1468 (when (and user-full-name (not (string= user-full-name "")))
1469 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1470 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1471 "Regexp matched against the \"From:\" header of an email or usenet message.
1472 It should match if the message is from the user him/herself."
1473 :group 'org-link-store
1474 :type 'regexp)
1476 (defcustom org-context-in-file-links t
1477 "Non-nil means file links from `org-store-link' contain context.
1478 A search string will be added to the file name with :: as separator and
1479 used to find the context when the link is activated by the command
1480 `org-open-at-point'. When this option is t, the entire active region
1481 will be placed in the search string of the file link. If set to a
1482 positive integer, only the first n lines of context will be stored.
1484 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1485 negates this setting for the duration of the command."
1486 :group 'org-link-store
1487 :type '(choice boolean integer))
1489 (defcustom org-keep-stored-link-after-insertion nil
1490 "Non-nil means keep link in list for entire session.
1492 The command `org-store-link' adds a link pointing to the current
1493 location to an internal list. These links accumulate during a session.
1494 The command `org-insert-link' can be used to insert links into any
1495 Org-mode file (offering completion for all stored links). When this
1496 option is nil, every link which has been inserted once using \\[org-insert-link]
1497 will be removed from the list, to make completing the unused links
1498 more efficient."
1499 :group 'org-link-store
1500 :type 'boolean)
1502 (defgroup org-link-follow nil
1503 "Options concerning following links in Org-mode."
1504 :tag "Org Follow Link"
1505 :group 'org-link)
1507 (defcustom org-link-translation-function nil
1508 "Function to translate links with different syntax to Org syntax.
1509 This can be used to translate links created for example by the Planner
1510 or emacs-wiki packages to Org syntax.
1511 The function must accept two parameters, a TYPE containing the link
1512 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1513 which is everything after the link protocol. It should return a cons
1514 with possibly modified values of type and path.
1515 Org contains a function for this, so if you set this variable to
1516 `org-translate-link-from-planner', you should be able follow many
1517 links created by planner."
1518 :group 'org-link-follow
1519 :type 'function)
1521 (defcustom org-follow-link-hook nil
1522 "Hook that is run after a link has been followed."
1523 :group 'org-link-follow
1524 :type 'hook)
1526 (defcustom org-tab-follows-link nil
1527 "Non-nil means on links TAB will follow the link.
1528 Needs to be set before org.el is loaded.
1529 This really should not be used, it does not make sense, and the
1530 implementation is bad."
1531 :group 'org-link-follow
1532 :type 'boolean)
1534 (defcustom org-return-follows-link nil
1535 "Non-nil means on links RET will follow the link."
1536 :group 'org-link-follow
1537 :type 'boolean)
1539 (defcustom org-mouse-1-follows-link
1540 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1541 "Non-nil means mouse-1 on a link will follow the link.
1542 A longer mouse click will still set point. Does not work on XEmacs.
1543 Needs to be set before org.el is loaded."
1544 :group 'org-link-follow
1545 :type 'boolean)
1547 (defcustom org-mark-ring-length 4
1548 "Number of different positions to be recorded in the ring.
1549 Changing this requires a restart of Emacs to work correctly."
1550 :group 'org-link-follow
1551 :type 'integer)
1553 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1554 "Non-nil means internal links in Org files must exactly match a headline.
1555 When nil, the link search tries to match a phrase with all words
1556 in the search text."
1557 :group 'org-link-follow
1558 :version "24.1"
1559 :type '(choice
1560 (const :tag "Use fuzzy text search" nil)
1561 (const :tag "Match only exact headline" t)
1562 (const :tag "Match exact headline or query to create it"
1563 query-to-create)))
1565 (defcustom org-link-frame-setup
1566 '((vm . vm-visit-folder-other-frame)
1567 (vm-imap . vm-visit-imap-folder-other-frame)
1568 (gnus . org-gnus-no-new-news)
1569 (file . find-file-other-window)
1570 (wl . wl-other-frame))
1571 "Setup the frame configuration for following links.
1572 When following a link with Emacs, it may often be useful to display
1573 this link in another window or frame. This variable can be used to
1574 set this up for the different types of links.
1575 For VM, use any of
1576 `vm-visit-folder'
1577 `vm-visit-folder-other-window'
1578 `vm-visit-folder-other-frame'
1579 For Gnus, use any of
1580 `gnus'
1581 `gnus-other-frame'
1582 `org-gnus-no-new-news'
1583 For FILE, use any of
1584 `find-file'
1585 `find-file-other-window'
1586 `find-file-other-frame'
1587 For Wanderlust use any of
1588 `wl'
1589 `wl-other-frame'
1590 For the calendar, use the variable `calendar-setup'.
1591 For BBDB, it is currently only possible to display the matches in
1592 another window."
1593 :group 'org-link-follow
1594 :type '(list
1595 (cons (const vm)
1596 (choice
1597 (const vm-visit-folder)
1598 (const vm-visit-folder-other-window)
1599 (const vm-visit-folder-other-frame)))
1600 (cons (const gnus)
1601 (choice
1602 (const gnus)
1603 (const gnus-other-frame)
1604 (const org-gnus-no-new-news)))
1605 (cons (const file)
1606 (choice
1607 (const find-file)
1608 (const find-file-other-window)
1609 (const find-file-other-frame)))
1610 (cons (const wl)
1611 (choice
1612 (const wl)
1613 (const wl-other-frame)))))
1615 (defcustom org-display-internal-link-with-indirect-buffer nil
1616 "Non-nil means use indirect buffer to display infile links.
1617 Activating internal links (from one location in a file to another location
1618 in the same file) normally just jumps to the location. When the link is
1619 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1620 is displayed in
1621 another window. When this option is set, the other window actually displays
1622 an indirect buffer clone of the current buffer, to avoid any visibility
1623 changes to the current buffer."
1624 :group 'org-link-follow
1625 :type 'boolean)
1627 (defcustom org-open-non-existing-files nil
1628 "Non-nil means `org-open-file' will open non-existing files.
1629 When nil, an error will be generated.
1630 This variable applies only to external applications because they
1631 might choke on non-existing files. If the link is to a file that
1632 will be opened in Emacs, the variable is ignored."
1633 :group 'org-link-follow
1634 :type 'boolean)
1636 (defcustom org-open-directory-means-index-dot-org nil
1637 "Non-nil means a link to a directory really means to index.org.
1638 When nil, following a directory link will run dired or open a finder/explorer
1639 window on that directory."
1640 :group 'org-link-follow
1641 :type 'boolean)
1643 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1644 "Function and arguments to call for following mailto links.
1645 This is a list with the first element being a Lisp function, and the
1646 remaining elements being arguments to the function. In string arguments,
1647 %a will be replaced by the address, and %s will be replaced by the subject
1648 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1649 :group 'org-link-follow
1650 :type '(choice
1651 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1652 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1653 (const :tag "message-mail" (message-mail "%a" "%s"))
1654 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1656 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1657 "Non-nil means ask for confirmation before executing shell links.
1658 Shell links can be dangerous: just think about a link
1660 [[shell:rm -rf ~/*][Google Search]]
1662 This link would show up in your Org-mode document as \"Google Search\",
1663 but really it would remove your entire home directory.
1664 Therefore we advise against setting this variable to nil.
1665 Just change it to `y-or-n-p' if you want to confirm with a
1666 single keystroke rather than having to type \"yes\"."
1667 :group 'org-link-follow
1668 :type '(choice
1669 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1670 (const :tag "with y-or-n (faster)" y-or-n-p)
1671 (const :tag "no confirmation (dangerous)" nil)))
1672 (put 'org-confirm-shell-link-function
1673 'safe-local-variable
1674 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1676 (defcustom org-confirm-shell-link-not-regexp ""
1677 "A regexp to skip confirmation for shell links."
1678 :group 'org-link-follow
1679 :version "24.1"
1680 :type 'regexp)
1682 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1683 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1684 Elisp links can be dangerous: just think about a link
1686 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1688 This link would show up in your Org-mode document as \"Google Search\",
1689 but really it would remove your entire home directory.
1690 Therefore we advise against setting this variable to nil.
1691 Just change it to `y-or-n-p' if you want to confirm with a
1692 single keystroke rather than having to type \"yes\"."
1693 :group 'org-link-follow
1694 :type '(choice
1695 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1696 (const :tag "with y-or-n (faster)" y-or-n-p)
1697 (const :tag "no confirmation (dangerous)" nil)))
1698 (put 'org-confirm-shell-link-function
1699 'safe-local-variable
1700 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1702 (defcustom org-confirm-elisp-link-not-regexp ""
1703 "A regexp to skip confirmation for Elisp links."
1704 :group 'org-link-follow
1705 :version "24.1"
1706 :type 'regexp)
1708 (defconst org-file-apps-defaults-gnu
1709 '((remote . emacs)
1710 (system . mailcap)
1711 (t . mailcap))
1712 "Default file applications on a UNIX or GNU/Linux system.
1713 See `org-file-apps'.")
1715 (defconst org-file-apps-defaults-macosx
1716 '((remote . emacs)
1717 (t . "open %s")
1718 (system . "open %s")
1719 ("ps.gz" . "gv %s")
1720 ("eps.gz" . "gv %s")
1721 ("dvi" . "xdvi %s")
1722 ("fig" . "xfig %s"))
1723 "Default file applications on a MacOS X system.
1724 The system \"open\" is known as a default, but we use X11 applications
1725 for some files for which the OS does not have a good default.
1726 See `org-file-apps'.")
1728 (defconst org-file-apps-defaults-windowsnt
1729 (list
1730 '(remote . emacs)
1731 (cons t
1732 (list (if (featurep 'xemacs)
1733 'mswindows-shell-execute
1734 'w32-shell-execute)
1735 "open" 'file))
1736 (cons 'system
1737 (list (if (featurep 'xemacs)
1738 'mswindows-shell-execute
1739 'w32-shell-execute)
1740 "open" 'file)))
1741 "Default file applications on a Windows NT system.
1742 The system \"open\" is used for most files.
1743 See `org-file-apps'.")
1745 (defcustom org-file-apps
1747 (auto-mode . emacs)
1748 ("\\.mm\\'" . default)
1749 ("\\.x?html?\\'" . default)
1750 ("\\.pdf\\'" . default)
1752 "External applications for opening `file:path' items in a document.
1753 Org-mode uses system defaults for different file types, but
1754 you can use this variable to set the application for a given file
1755 extension. The entries in this list are cons cells where the car identifies
1756 files and the cdr the corresponding command. Possible values for the
1757 file identifier are
1758 \"string\" A string as a file identifier can be interpreted in different
1759 ways, depending on its contents:
1761 - Alphanumeric characters only:
1762 Match links with this file extension.
1763 Example: (\"pdf\" . \"evince %s\")
1764 to open PDFs with evince.
1766 - Regular expression: Match links where the
1767 filename matches the regexp. If you want to
1768 use groups here, use shy groups.
1770 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1771 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1772 to open *.html and *.xhtml with firefox.
1774 - Regular expression which contains (non-shy) groups:
1775 Match links where the whole link, including \"::\", and
1776 anything after that, matches the regexp.
1777 In a custom command string, %1, %2, etc. are replaced with
1778 the parts of the link that were matched by the groups.
1779 For backwards compatibility, if a command string is given
1780 that does not use any of the group matches, this case is
1781 handled identically to the second one (i.e. match against
1782 file name only).
1783 In a custom lisp form, you can access the group matches with
1784 (match-string n link).
1786 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1787 to open [[file:document.pdf::5]] with evince at page 5.
1789 `directory' Matches a directory
1790 `remote' Matches a remote file, accessible through tramp or efs.
1791 Remote files most likely should be visited through Emacs
1792 because external applications cannot handle such paths.
1793 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1794 so all files Emacs knows how to handle. Using this with
1795 command `emacs' will open most files in Emacs. Beware that this
1796 will also open html files inside Emacs, unless you add
1797 (\"html\" . default) to the list as well.
1798 t Default for files not matched by any of the other options.
1799 `system' The system command to open files, like `open' on Windows
1800 and Mac OS X, and mailcap under GNU/Linux. This is the command
1801 that will be selected if you call `C-c C-o' with a double
1802 \\[universal-argument] \\[universal-argument] prefix.
1804 Possible values for the command are:
1805 `emacs' The file will be visited by the current Emacs process.
1806 `default' Use the default application for this file type, which is the
1807 association for t in the list, most likely in the system-specific
1808 part.
1809 This can be used to overrule an unwanted setting in the
1810 system-specific variable.
1811 `system' Use the system command for opening files, like \"open\".
1812 This command is specified by the entry whose car is `system'.
1813 Most likely, the system-specific version of this variable
1814 does define this command, but you can overrule/replace it
1815 here.
1816 string A command to be executed by a shell; %s will be replaced
1817 by the path to the file.
1818 sexp A Lisp form which will be evaluated. The file path will
1819 be available in the Lisp variable `file'.
1820 For more examples, see the system specific constants
1821 `org-file-apps-defaults-macosx'
1822 `org-file-apps-defaults-windowsnt'
1823 `org-file-apps-defaults-gnu'."
1824 :group 'org-link-follow
1825 :type '(repeat
1826 (cons (choice :value ""
1827 (string :tag "Extension")
1828 (const :tag "System command to open files" system)
1829 (const :tag "Default for unrecognized files" t)
1830 (const :tag "Remote file" remote)
1831 (const :tag "Links to a directory" directory)
1832 (const :tag "Any files that have Emacs modes"
1833 auto-mode))
1834 (choice :value ""
1835 (const :tag "Visit with Emacs" emacs)
1836 (const :tag "Use default" default)
1837 (const :tag "Use the system command" system)
1838 (string :tag "Command")
1839 (sexp :tag "Lisp form")))))
1841 (defcustom org-doi-server-url "http://dx.doi.org/"
1842 "The URL of the DOI server."
1843 :type 'string
1844 :version "24.3"
1845 :group 'org-link-follow)
1847 (defgroup org-refile nil
1848 "Options concerning refiling entries in Org-mode."
1849 :tag "Org Refile"
1850 :group 'org)
1852 (defcustom org-directory "~/org"
1853 "Directory with org files.
1854 This is just a default location to look for Org files. There is no need
1855 at all to put your files into this directory. It is only used in the
1856 following situations:
1858 1. When a capture template specifies a target file that is not an
1859 absolute path. The path will then be interpreted relative to
1860 `org-directory'
1861 2. When a capture note is filed away in an interactive way (when exiting the
1862 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1863 with `org-directory' as the default path."
1864 :group 'org-refile
1865 :group 'org-remember
1866 :group 'org-capture
1867 :type 'directory)
1869 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1870 "Default target for storing notes.
1871 Used as a fall back file for org-remember.el and org-capture.el, for
1872 templates that do not specify a target file."
1873 :group 'org-refile
1874 :group 'org-remember
1875 :group 'org-capture
1876 :type '(choice
1877 (const :tag "Default from remember-data-file" nil)
1878 file))
1880 (defcustom org-goto-interface 'outline
1881 "The default interface to be used for `org-goto'.
1882 Allowed values are:
1883 outline The interface shows an outline of the relevant file
1884 and the correct heading is found by moving through
1885 the outline or by searching with incremental search.
1886 outline-path-completion Headlines in the current buffer are offered via
1887 completion. This is the interface also used by
1888 the refile command."
1889 :group 'org-refile
1890 :type '(choice
1891 (const :tag "Outline" outline)
1892 (const :tag "Outline-path-completion" outline-path-completion)))
1894 (defcustom org-goto-max-level 5
1895 "Maximum target level when running `org-goto' with refile interface."
1896 :group 'org-refile
1897 :type 'integer)
1899 (defcustom org-reverse-note-order nil
1900 "Non-nil means store new notes at the beginning of a file or entry.
1901 When nil, new notes will be filed to the end of a file or entry.
1902 This can also be a list with cons cells of regular expressions that
1903 are matched against file names, and values."
1904 :group 'org-remember
1905 :group 'org-capture
1906 :group 'org-refile
1907 :type '(choice
1908 (const :tag "Reverse always" t)
1909 (const :tag "Reverse never" nil)
1910 (repeat :tag "By file name regexp"
1911 (cons regexp boolean))))
1913 (defcustom org-log-refile nil
1914 "Information to record when a task is refiled.
1916 Possible values are:
1918 nil Don't add anything
1919 time Add a time stamp to the task
1920 note Prompt for a note and add it with template `org-log-note-headings'
1922 This option can also be set with on a per-file-basis with
1924 #+STARTUP: nologrefile
1925 #+STARTUP: logrefile
1926 #+STARTUP: lognoterefile
1928 You can have local logging settings for a subtree by setting the LOGGING
1929 property to one or more of these keywords.
1931 When bulk-refiling from the agenda, the value `note' is forbidden and
1932 will temporarily be changed to `time'."
1933 :group 'org-refile
1934 :group 'org-progress
1935 :version "24.1"
1936 :type '(choice
1937 (const :tag "No logging" nil)
1938 (const :tag "Record timestamp" time)
1939 (const :tag "Record timestamp with note." note)))
1941 (defcustom org-refile-targets nil
1942 "Targets for refiling entries with \\[org-refile].
1943 This is a list of cons cells. Each cell contains:
1944 - a specification of the files to be considered, either a list of files,
1945 or a symbol whose function or variable value will be used to retrieve
1946 a file name or a list of file names. If you use `org-agenda-files' for
1947 that, all agenda files will be scanned for targets. Nil means consider
1948 headings in the current buffer.
1949 - A specification of how to find candidate refile targets. This may be
1950 any of:
1951 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1952 This tag has to be present in all target headlines, inheritance will
1953 not be considered.
1954 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1955 todo keyword.
1956 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1957 headlines that are refiling targets.
1958 - a cons cell (:level . N). Any headline of level N is considered a target.
1959 Note that, when `org-odd-levels-only' is set, level corresponds to
1960 order in hierarchy, not to the number of stars.
1961 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1962 Note that, when `org-odd-levels-only' is set, level corresponds to
1963 order in hierarchy, not to the number of stars.
1965 Each element of this list generates a set of possible targets.
1966 The union of these sets is presented (with completion) to
1967 the user by `org-refile'.
1969 You can set the variable `org-refile-target-verify-function' to a function
1970 to verify each headline found by the simple criteria above.
1972 When this variable is nil, all top-level headlines in the current buffer
1973 are used, equivalent to the value `((nil . (:level . 1))'."
1974 :group 'org-refile
1975 :type '(repeat
1976 (cons
1977 (choice :value org-agenda-files
1978 (const :tag "All agenda files" org-agenda-files)
1979 (const :tag "Current buffer" nil)
1980 (function) (variable) (file))
1981 (choice :tag "Identify target headline by"
1982 (cons :tag "Specific tag" (const :value :tag) (string))
1983 (cons :tag "TODO keyword" (const :value :todo) (string))
1984 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1985 (cons :tag "Level number" (const :value :level) (integer))
1986 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1988 (defcustom org-refile-target-verify-function nil
1989 "Function to verify if the headline at point should be a refile target.
1990 The function will be called without arguments, with point at the
1991 beginning of the headline. It should return t and leave point
1992 where it is if the headline is a valid target for refiling.
1994 If the target should not be selected, the function must return nil.
1995 In addition to this, it may move point to a place from where the search
1996 should be continued. For example, the function may decide that the entire
1997 subtree of the current entry should be excluded and move point to the end
1998 of the subtree."
1999 :group 'org-refile
2000 :type 'function)
2002 (defcustom org-refile-use-cache nil
2003 "Non-nil means cache refile targets to speed up the process.
2004 The cache for a particular file will be updated automatically when
2005 the buffer has been killed, or when any of the marker used for flagging
2006 refile targets no longer points at a live buffer.
2007 If you have added new entries to a buffer that might themselves be targets,
2008 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2009 find that easier, `C-u C-u C-u C-c C-w'."
2010 :group 'org-refile
2011 :version "24.1"
2012 :type 'boolean)
2014 (defcustom org-refile-use-outline-path nil
2015 "Non-nil means provide refile targets as paths.
2016 So a level 3 headline will be available as level1/level2/level3.
2018 When the value is `file', also include the file name (without directory)
2019 into the path. In this case, you can also stop the completion after
2020 the file name, to get entries inserted as top level in the file.
2022 When `full-file-path', include the full file path."
2023 :group 'org-refile
2024 :type '(choice
2025 (const :tag "Not" nil)
2026 (const :tag "Yes" t)
2027 (const :tag "Start with file name" file)
2028 (const :tag "Start with full file path" full-file-path)))
2030 (defcustom org-outline-path-complete-in-steps t
2031 "Non-nil means complete the outline path in hierarchical steps.
2032 When Org-mode uses the refile interface to select an outline path
2033 \(see variable `org-refile-use-outline-path'), the completion of
2034 the path can be done is a single go, or if can be done in steps down
2035 the headline hierarchy. Going in steps is probably the best if you
2036 do not use a special completion package like `ido' or `icicles'.
2037 However, when using these packages, going in one step can be very
2038 fast, while still showing the whole path to the entry."
2039 :group 'org-refile
2040 :type 'boolean)
2042 (defcustom org-refile-allow-creating-parent-nodes nil
2043 "Non-nil means allow to create new nodes as refile targets.
2044 New nodes are then created by adding \"/new node name\" to the completion
2045 of an existing node. When the value of this variable is `confirm',
2046 new node creation must be confirmed by the user (recommended)
2047 When nil, the completion must match an existing entry.
2049 Note that, if the new heading is not seen by the criteria
2050 listed in `org-refile-targets', multiple instances of the same
2051 heading would be created by trying again to file under the new
2052 heading."
2053 :group 'org-refile
2054 :type '(choice
2055 (const :tag "Never" nil)
2056 (const :tag "Always" t)
2057 (const :tag "Prompt for confirmation" confirm)))
2059 (defcustom org-refile-active-region-within-subtree nil
2060 "Non-nil means also refile active region within a subtree.
2062 By default `org-refile' doesn't allow refiling regions if they
2063 don't contain a set of subtrees, but it might be convenient to
2064 do so sometimes: in that case, the first line of the region is
2065 converted to a headline before refiling."
2066 :group 'org-refile
2067 :version "24.1"
2068 :type 'boolean)
2070 (defgroup org-todo nil
2071 "Options concerning TODO items in Org-mode."
2072 :tag "Org TODO"
2073 :group 'org)
2075 (defgroup org-progress nil
2076 "Options concerning Progress logging in Org-mode."
2077 :tag "Org Progress"
2078 :group 'org-time)
2080 (defvar org-todo-interpretation-widgets
2081 '((:tag "Sequence (cycling hits every state)" sequence)
2082 (:tag "Type (cycling directly to DONE)" type))
2083 "The available interpretation symbols for customizing `org-todo-keywords'.
2084 Interested libraries should add to this list.")
2086 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2087 "List of TODO entry keyword sequences and their interpretation.
2088 \\<org-mode-map>This is a list of sequences.
2090 Each sequence starts with a symbol, either `sequence' or `type',
2091 indicating if the keywords should be interpreted as a sequence of
2092 action steps, or as different types of TODO items. The first
2093 keywords are states requiring action - these states will select a headline
2094 for inclusion into the global TODO list Org-mode produces. If one of
2095 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2096 signify that no further action is necessary. If \"|\" is not found,
2097 the last keyword is treated as the only DONE state of the sequence.
2099 The command \\[org-todo] cycles an entry through these states, and one
2100 additional state where no keyword is present. For details about this
2101 cycling, see the manual.
2103 TODO keywords and interpretation can also be set on a per-file basis with
2104 the special #+SEQ_TODO and #+TYP_TODO lines.
2106 Each keyword can optionally specify a character for fast state selection
2107 \(in combination with the variable `org-use-fast-todo-selection')
2108 and specifiers for state change logging, using the same syntax that
2109 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2110 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2111 indicates to record a time stamp each time this state is selected.
2113 Each keyword may also specify if a timestamp or a note should be
2114 recorded when entering or leaving the state, by adding additional
2115 characters in the parenthesis after the keyword. This looks like this:
2116 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2117 record only the time of the state change. With X and Y being either
2118 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2119 Y when leaving the state if and only if the *target* state does not
2120 define X. You may omit any of the fast-selection key or X or /Y,
2121 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2123 For backward compatibility, this variable may also be just a list
2124 of keywords. In this case the interpretation (sequence or type) will be
2125 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2126 :group 'org-todo
2127 :group 'org-keywords
2128 :type '(choice
2129 (repeat :tag "Old syntax, just keywords"
2130 (string :tag "Keyword"))
2131 (repeat :tag "New syntax"
2132 (cons
2133 (choice
2134 :tag "Interpretation"
2135 ;;Quick and dirty way to see
2136 ;;`org-todo-interpretations'. This takes the
2137 ;;place of item arguments
2138 :convert-widget
2139 (lambda (widget)
2140 (widget-put widget
2141 :args (mapcar
2142 #'(lambda (x)
2143 (widget-convert
2144 (cons 'const x)))
2145 org-todo-interpretation-widgets))
2146 widget))
2147 (repeat
2148 (string :tag "Keyword"))))))
2150 (defvar org-todo-keywords-1 nil
2151 "All TODO and DONE keywords active in a buffer.")
2152 (make-variable-buffer-local 'org-todo-keywords-1)
2153 (defvar org-todo-keywords-for-agenda nil)
2154 (defvar org-done-keywords-for-agenda nil)
2155 (defvar org-drawers-for-agenda nil)
2156 (defvar org-todo-keyword-alist-for-agenda nil)
2157 (defvar org-tag-alist-for-agenda nil)
2158 (defvar org-agenda-contributing-files nil)
2159 (defvar org-not-done-keywords nil)
2160 (make-variable-buffer-local 'org-not-done-keywords)
2161 (defvar org-done-keywords nil)
2162 (make-variable-buffer-local 'org-done-keywords)
2163 (defvar org-todo-heads nil)
2164 (make-variable-buffer-local 'org-todo-heads)
2165 (defvar org-todo-sets nil)
2166 (make-variable-buffer-local 'org-todo-sets)
2167 (defvar org-todo-log-states nil)
2168 (make-variable-buffer-local 'org-todo-log-states)
2169 (defvar org-todo-kwd-alist nil)
2170 (make-variable-buffer-local 'org-todo-kwd-alist)
2171 (defvar org-todo-key-alist nil)
2172 (make-variable-buffer-local 'org-todo-key-alist)
2173 (defvar org-todo-key-trigger nil)
2174 (make-variable-buffer-local 'org-todo-key-trigger)
2176 (defcustom org-todo-interpretation 'sequence
2177 "Controls how TODO keywords are interpreted.
2178 This variable is in principle obsolete and is only used for
2179 backward compatibility, if the interpretation of todo keywords is
2180 not given already in `org-todo-keywords'. See that variable for
2181 more information."
2182 :group 'org-todo
2183 :group 'org-keywords
2184 :type '(choice (const sequence)
2185 (const type)))
2187 (defcustom org-use-fast-todo-selection t
2188 "Non-nil means use the fast todo selection scheme with C-c C-t.
2189 This variable describes if and under what circumstances the cycling
2190 mechanism for TODO keywords will be replaced by a single-key, direct
2191 selection scheme.
2193 When nil, fast selection is never used.
2195 When the symbol `prefix', it will be used when `org-todo' is called
2196 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2197 `C-u t' in an agenda buffer.
2199 When t, fast selection is used by default. In this case, the prefix
2200 argument forces cycling instead.
2202 In all cases, the special interface is only used if access keys have
2203 actually been assigned by the user, i.e. if keywords in the configuration
2204 are followed by a letter in parenthesis, like TODO(t)."
2205 :group 'org-todo
2206 :type '(choice
2207 (const :tag "Never" nil)
2208 (const :tag "By default" t)
2209 (const :tag "Only with C-u C-c C-t" prefix)))
2211 (defcustom org-provide-todo-statistics t
2212 "Non-nil means update todo statistics after insert and toggle.
2213 ALL-HEADLINES means update todo statistics by including headlines
2214 with no TODO keyword as well, counting them as not done.
2215 A list of TODO keywords means the same, but skip keywords that are
2216 not in this list.
2218 When this is set, todo statistics is updated in the parent of the
2219 current entry each time a todo state is changed."
2220 :group 'org-todo
2221 :type '(choice
2222 (const :tag "Yes, only for TODO entries" t)
2223 (const :tag "Yes, including all entries" 'all-headlines)
2224 (repeat :tag "Yes, for TODOs in this list"
2225 (string :tag "TODO keyword"))
2226 (other :tag "No TODO statistics" nil)))
2228 (defcustom org-hierarchical-todo-statistics t
2229 "Non-nil means TODO statistics covers just direct children.
2230 When nil, all entries in the subtree are considered.
2231 This has only an effect if `org-provide-todo-statistics' is set.
2232 To set this to nil for only a single subtree, use a COOKIE_DATA
2233 property and include the word \"recursive\" into the value."
2234 :group 'org-todo
2235 :type 'boolean)
2237 (defcustom org-after-todo-state-change-hook nil
2238 "Hook which is run after the state of a TODO item was changed.
2239 The new state (a string with a TODO keyword, or nil) is available in the
2240 Lisp variable `org-state'."
2241 :group 'org-todo
2242 :type 'hook)
2244 (defvar org-blocker-hook nil
2245 "Hook for functions that are allowed to block a state change.
2247 Functions in this hook should not modify the buffer.
2248 Each function gets as its single argument a property list,
2249 see `org-trigger-hook' for more information about this list.
2251 If any of the functions in this hook returns nil, the state change
2252 is blocked.")
2254 (defvar org-trigger-hook nil
2255 "Hook for functions that are triggered by a state change.
2257 Each function gets as its single argument a property list with at
2258 least the following elements:
2260 (:type type-of-change :position pos-at-entry-start
2261 :from old-state :to new-state)
2263 Depending on the type, more properties may be present.
2265 This mechanism is currently implemented for:
2267 TODO state changes
2268 ------------------
2269 :type todo-state-change
2270 :from previous state (keyword as a string), or nil, or a symbol
2271 'todo' or 'done', to indicate the general type of state.
2272 :to new state, like in :from")
2274 (defcustom org-enforce-todo-dependencies nil
2275 "Non-nil means undone TODO entries will block switching the parent to DONE.
2276 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2277 be blocked if any prior sibling is not yet done.
2278 Finally, if the parent is blocked because of ordered siblings of its own,
2279 the child will also be blocked."
2280 :set (lambda (var val)
2281 (set var val)
2282 (if val
2283 (add-hook 'org-blocker-hook
2284 'org-block-todo-from-children-or-siblings-or-parent)
2285 (remove-hook 'org-blocker-hook
2286 'org-block-todo-from-children-or-siblings-or-parent)))
2287 :group 'org-todo
2288 :type 'boolean)
2290 (defcustom org-enforce-todo-checkbox-dependencies nil
2291 "Non-nil means unchecked boxes will block switching the parent to DONE.
2292 When this is nil, checkboxes have no influence on switching TODO states.
2293 When non-nil, you first need to check off all check boxes before the TODO
2294 entry can be switched to DONE.
2295 This variable needs to be set before org.el is loaded, and you need to
2296 restart Emacs after a change to make the change effective. The only way
2297 to change is while Emacs is running is through the customize interface."
2298 :set (lambda (var val)
2299 (set var val)
2300 (if val
2301 (add-hook 'org-blocker-hook
2302 'org-block-todo-from-checkboxes)
2303 (remove-hook 'org-blocker-hook
2304 'org-block-todo-from-checkboxes)))
2305 :group 'org-todo
2306 :type 'boolean)
2308 (defcustom org-treat-insert-todo-heading-as-state-change nil
2309 "Non-nil means inserting a TODO heading is treated as state change.
2310 So when the command \\[org-insert-todo-heading] is used, state change
2311 logging will apply if appropriate. When nil, the new TODO item will
2312 be inserted directly, and no logging will take place."
2313 :group 'org-todo
2314 :type 'boolean)
2316 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2317 "Non-nil means switching TODO states with S-cursor counts as state change.
2318 This is the default behavior. However, setting this to nil allows a
2319 convenient way to select a TODO state and bypass any logging associated
2320 with that."
2321 :group 'org-todo
2322 :type 'boolean)
2324 (defcustom org-todo-state-tags-triggers nil
2325 "Tag changes that should be triggered by TODO state changes.
2326 This is a list. Each entry is
2328 (state-change (tag . flag) .......)
2330 State-change can be a string with a state, and empty string to indicate the
2331 state that has no TODO keyword, or it can be one of the symbols `todo'
2332 or `done', meaning any not-done or done state, respectively."
2333 :group 'org-todo
2334 :group 'org-tags
2335 :type '(repeat
2336 (cons (choice :tag "When changing to"
2337 (const :tag "Not-done state" todo)
2338 (const :tag "Done state" done)
2339 (string :tag "State"))
2340 (repeat
2341 (cons :tag "Tag action"
2342 (string :tag "Tag")
2343 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2345 (defcustom org-log-done nil
2346 "Information to record when a task moves to the DONE state.
2348 Possible values are:
2350 nil Don't add anything, just change the keyword
2351 time Add a time stamp to the task
2352 note Prompt for a note and add it with template `org-log-note-headings'
2354 This option can also be set with on a per-file-basis with
2356 #+STARTUP: nologdone
2357 #+STARTUP: logdone
2358 #+STARTUP: lognotedone
2360 You can have local logging settings for a subtree by setting the LOGGING
2361 property to one or more of these keywords."
2362 :group 'org-todo
2363 :group 'org-progress
2364 :type '(choice
2365 (const :tag "No logging" nil)
2366 (const :tag "Record CLOSED timestamp" time)
2367 (const :tag "Record CLOSED timestamp with note." note)))
2369 ;; Normalize old uses of org-log-done.
2370 (cond
2371 ((eq org-log-done t) (setq org-log-done 'time))
2372 ((and (listp org-log-done) (memq 'done org-log-done))
2373 (setq org-log-done 'note)))
2375 (defcustom org-log-reschedule nil
2376 "Information to record when the scheduling date of a tasks is modified.
2378 Possible values are:
2380 nil Don't add anything, just change the date
2381 time Add a time stamp to the task
2382 note Prompt for a note and add it with template `org-log-note-headings'
2384 This option can also be set with on a per-file-basis with
2386 #+STARTUP: nologreschedule
2387 #+STARTUP: logreschedule
2388 #+STARTUP: lognotereschedule"
2389 :group 'org-todo
2390 :group 'org-progress
2391 :type '(choice
2392 (const :tag "No logging" nil)
2393 (const :tag "Record timestamp" time)
2394 (const :tag "Record timestamp with note." note)))
2396 (defcustom org-log-redeadline nil
2397 "Information to record when the deadline date of a tasks is modified.
2399 Possible values are:
2401 nil Don't add anything, just change the date
2402 time Add a time stamp to the task
2403 note Prompt for a note and add it with template `org-log-note-headings'
2405 This option can also be set with on a per-file-basis with
2407 #+STARTUP: nologredeadline
2408 #+STARTUP: logredeadline
2409 #+STARTUP: lognoteredeadline
2411 You can have local logging settings for a subtree by setting the LOGGING
2412 property to one or more of these keywords."
2413 :group 'org-todo
2414 :group 'org-progress
2415 :type '(choice
2416 (const :tag "No logging" nil)
2417 (const :tag "Record timestamp" time)
2418 (const :tag "Record timestamp with note." note)))
2420 (defcustom org-log-note-clock-out nil
2421 "Non-nil means record a note when clocking out of an item.
2422 This can also be configured on a per-file basis by adding one of
2423 the following lines anywhere in the buffer:
2425 #+STARTUP: lognoteclock-out
2426 #+STARTUP: nolognoteclock-out"
2427 :group 'org-todo
2428 :group 'org-progress
2429 :type 'boolean)
2431 (defcustom org-log-done-with-time t
2432 "Non-nil means the CLOSED time stamp will contain date and time.
2433 When nil, only the date will be recorded."
2434 :group 'org-progress
2435 :type 'boolean)
2437 (defcustom org-log-note-headings
2438 '((done . "CLOSING NOTE %t")
2439 (state . "State %-12s from %-12S %t")
2440 (note . "Note taken on %t")
2441 (reschedule . "Rescheduled from %S on %t")
2442 (delschedule . "Not scheduled, was %S on %t")
2443 (redeadline . "New deadline from %S on %t")
2444 (deldeadline . "Removed deadline, was %S on %t")
2445 (refile . "Refiled on %t")
2446 (clock-out . ""))
2447 "Headings for notes added to entries.
2448 The value is an alist, with the car being a symbol indicating the note
2449 context, and the cdr is the heading to be used. The heading may also be the
2450 empty string.
2451 %t in the heading will be replaced by a time stamp.
2452 %T will be an active time stamp instead the default inactive one
2453 %d will be replaced by a short-format time stamp.
2454 %D will be replaced by an active short-format time stamp.
2455 %s will be replaced by the new TODO state, in double quotes.
2456 %S will be replaced by the old TODO state, in double quotes.
2457 %u will be replaced by the user name.
2458 %U will be replaced by the full user name.
2460 In fact, it is not a good idea to change the `state' entry, because
2461 agenda log mode depends on the format of these entries."
2462 :group 'org-todo
2463 :group 'org-progress
2464 :type '(list :greedy t
2465 (cons (const :tag "Heading when closing an item" done) string)
2466 (cons (const :tag
2467 "Heading when changing todo state (todo sequence only)"
2468 state) string)
2469 (cons (const :tag "Heading when just taking a note" note) string)
2470 (cons (const :tag "Heading when clocking out" clock-out) string)
2471 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2472 (cons (const :tag "Heading when rescheduling" reschedule) string)
2473 (cons (const :tag "Heading when changing deadline" redeadline) string)
2474 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2475 (cons (const :tag "Heading when refiling" refile) string)))
2477 (unless (assq 'note org-log-note-headings)
2478 (push '(note . "%t") org-log-note-headings))
2480 (defcustom org-log-into-drawer nil
2481 "Non-nil means insert state change notes and time stamps into a drawer.
2482 When nil, state changes notes will be inserted after the headline and
2483 any scheduling and clock lines, but not inside a drawer.
2485 The value of this variable should be the name of the drawer to use.
2486 LOGBOOK is proposed as the default drawer for this purpose, you can
2487 also set this to a string to define the drawer of your choice.
2489 A value of t is also allowed, representing \"LOGBOOK\".
2491 If this variable is set, `org-log-state-notes-insert-after-drawers'
2492 will be ignored.
2494 You can set the property LOG_INTO_DRAWER to overrule this setting for
2495 a subtree."
2496 :group 'org-todo
2497 :group 'org-progress
2498 :type '(choice
2499 (const :tag "Not into a drawer" nil)
2500 (const :tag "LOGBOOK" t)
2501 (string :tag "Other")))
2503 (if (fboundp 'defvaralias)
2504 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2506 (defun org-log-into-drawer ()
2507 "Return the value of `org-log-into-drawer', but let properties overrule.
2508 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2509 used instead of the default value."
2510 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2511 (cond
2512 ((not p) org-log-into-drawer)
2513 ((equal p "nil") nil)
2514 ((equal p "t") "LOGBOOK")
2515 (t p))))
2517 (defcustom org-log-state-notes-insert-after-drawers nil
2518 "Non-nil means insert state change notes after any drawers in entry.
2519 Only the drawers that *immediately* follow the headline and the
2520 deadline/scheduled line are skipped.
2521 When nil, insert notes right after the heading and perhaps the line
2522 with deadline/scheduling if present.
2524 This variable will have no effect if `org-log-into-drawer' is
2525 set."
2526 :group 'org-todo
2527 :group 'org-progress
2528 :type 'boolean)
2530 (defcustom org-log-states-order-reversed t
2531 "Non-nil means the latest state note will be directly after heading.
2532 When nil, the state change notes will be ordered according to time."
2533 :group 'org-todo
2534 :group 'org-progress
2535 :type 'boolean)
2537 (defcustom org-todo-repeat-to-state nil
2538 "The TODO state to which a repeater should return the repeating task.
2539 By default this is the first task in a TODO sequence, or the previous state
2540 in a TODO_TYP set. But you can specify another task here.
2541 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2542 :group 'org-todo
2543 :version "24.1"
2544 :type '(choice (const :tag "Head of sequence" nil)
2545 (string :tag "Specific state")))
2547 (defcustom org-log-repeat 'time
2548 "Non-nil means record moving through the DONE state when triggering repeat.
2549 An auto-repeating task is immediately switched back to TODO when
2550 marked DONE. If you are not logging state changes (by adding \"@\"
2551 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2552 record a closing note, there will be no record of the task moving
2553 through DONE. This variable forces taking a note anyway.
2555 nil Don't force a record
2556 time Record a time stamp
2557 note Prompt for a note and add it with template `org-log-note-headings'
2559 This option can also be set with on a per-file-basis with
2561 #+STARTUP: nologrepeat
2562 #+STARTUP: logrepeat
2563 #+STARTUP: lognoterepeat
2565 You can have local logging settings for a subtree by setting the LOGGING
2566 property to one or more of these keywords."
2567 :group 'org-todo
2568 :group 'org-progress
2569 :type '(choice
2570 (const :tag "Don't force a record" nil)
2571 (const :tag "Force recording the DONE state" time)
2572 (const :tag "Force recording a note with the DONE state" note)))
2575 (defgroup org-priorities nil
2576 "Priorities in Org-mode."
2577 :tag "Org Priorities"
2578 :group 'org-todo)
2580 (defcustom org-enable-priority-commands t
2581 "Non-nil means priority commands are active.
2582 When nil, these commands will be disabled, so that you never accidentally
2583 set a priority."
2584 :group 'org-priorities
2585 :type 'boolean)
2587 (defcustom org-highest-priority ?A
2588 "The highest priority of TODO items. A character like ?A, ?B etc.
2589 Must have a smaller ASCII number than `org-lowest-priority'."
2590 :group 'org-priorities
2591 :type 'character)
2593 (defcustom org-lowest-priority ?C
2594 "The lowest priority of TODO items. A character like ?A, ?B etc.
2595 Must have a larger ASCII number than `org-highest-priority'."
2596 :group 'org-priorities
2597 :type 'character)
2599 (defcustom org-default-priority ?B
2600 "The default priority of TODO items.
2601 This is the priority an item gets if no explicit priority is given.
2602 When starting to cycle on an empty priority the first step in the cycle
2603 depends on `org-priority-start-cycle-with-default'. The resulting first
2604 step priority must not exceed the range from `org-highest-priority' to
2605 `org-lowest-priority' which means that `org-default-priority' has to be
2606 in this range exclusive or inclusive the range boundaries. Else the
2607 first step refuses to set the default and the second will fall back
2608 to (depending on the command used) the highest or lowest priority."
2609 :group 'org-priorities
2610 :type 'character)
2612 (defcustom org-priority-start-cycle-with-default t
2613 "Non-nil means start with default priority when starting to cycle.
2614 When this is nil, the first step in the cycle will be (depending on the
2615 command used) one higher or lower than the default priority.
2616 See also `org-default-priority'."
2617 :group 'org-priorities
2618 :type 'boolean)
2620 (defcustom org-get-priority-function nil
2621 "Function to extract the priority from a string.
2622 The string is normally the headline. If this is nil Org computes the
2623 priority from the priority cookie like [#A] in the headline. It returns
2624 an integer, increasing by 1000 for each priority level.
2625 The user can set a different function here, which should take a string
2626 as an argument and return the numeric priority."
2627 :group 'org-priorities
2628 :version "24.1"
2629 :type 'function)
2631 (defgroup org-time nil
2632 "Options concerning time stamps and deadlines in Org-mode."
2633 :tag "Org Time"
2634 :group 'org)
2636 (defcustom org-insert-labeled-timestamps-at-point nil
2637 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2638 When nil, these labeled time stamps are forces into the second line of an
2639 entry, just after the headline. When scheduling from the global TODO list,
2640 the time stamp will always be forced into the second line."
2641 :group 'org-time
2642 :type 'boolean)
2644 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2645 "Formats for `format-time-string' which are used for time stamps.
2646 It is not recommended to change this constant.")
2648 (defcustom org-time-stamp-rounding-minutes '(0 5)
2649 "Number of minutes to round time stamps to.
2650 These are two values, the first applies when first creating a time stamp.
2651 The second applies when changing it with the commands `S-up' and `S-down'.
2652 When changing the time stamp, this means that it will change in steps
2653 of N minutes, as given by the second value.
2655 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2656 numbers should be factors of 60, so for example 5, 10, 15.
2658 When this is larger than 1, you can still force an exact time stamp by using
2659 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2660 and by using a prefix arg to `S-up/down' to specify the exact number
2661 of minutes to shift."
2662 :group 'org-time
2663 :get #'(lambda (var) ; Make sure both elements are there
2664 (if (integerp (default-value var))
2665 (list (default-value var) 5)
2666 (default-value var)))
2667 :type '(list
2668 (integer :tag "when inserting times")
2669 (integer :tag "when modifying times")))
2671 ;; Normalize old customizations of this variable.
2672 (when (integerp org-time-stamp-rounding-minutes)
2673 (setq org-time-stamp-rounding-minutes
2674 (list org-time-stamp-rounding-minutes
2675 org-time-stamp-rounding-minutes)))
2677 (defcustom org-display-custom-times nil
2678 "Non-nil means overlay custom formats over all time stamps.
2679 The formats are defined through the variable `org-time-stamp-custom-formats'.
2680 To turn this on on a per-file basis, insert anywhere in the file:
2681 #+STARTUP: customtime"
2682 :group 'org-time
2683 :set 'set-default
2684 :type 'sexp)
2685 (make-variable-buffer-local 'org-display-custom-times)
2687 (defcustom org-time-stamp-custom-formats
2688 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2689 "Custom formats for time stamps. See `format-time-string' for the syntax.
2690 These are overlaid over the default ISO format if the variable
2691 `org-display-custom-times' is set. Time like %H:%M should be at the
2692 end of the second format. The custom formats are also honored by export
2693 commands, if custom time display is turned on at the time of export."
2694 :group 'org-time
2695 :type 'sexp)
2697 (defun org-time-stamp-format (&optional long inactive)
2698 "Get the right format for a time string."
2699 (let ((f (if long (cdr org-time-stamp-formats)
2700 (car org-time-stamp-formats))))
2701 (if inactive
2702 (concat "[" (substring f 1 -1) "]")
2703 f)))
2705 (defcustom org-time-clocksum-format "%d:%02d"
2706 "The format string used when creating CLOCKSUM lines.
2707 This is also used when org-mode generates a time duration."
2708 :group 'org-time
2709 :type 'string)
2711 (defcustom org-time-clocksum-use-fractional nil
2712 "If non-nil, \\[org-clock-display] uses fractional times.
2713 org-mode generates a time duration."
2714 :group 'org-time
2715 :type 'boolean)
2717 (defcustom org-time-clocksum-fractional-format "%.2f"
2718 "The format string used when creating CLOCKSUM lines, or when
2719 org-mode generates a time duration."
2720 :group 'org-time
2721 :type 'string)
2723 (defcustom org-deadline-warning-days 14
2724 "No. of days before expiration during which a deadline becomes active.
2725 This variable governs the display in sparse trees and in the agenda.
2726 When 0 or negative, it means use this number (the absolute value of it)
2727 even if a deadline has a different individual lead time specified.
2729 Custom commands can set this variable in the options section."
2730 :group 'org-time
2731 :group 'org-agenda-daily/weekly
2732 :type 'integer)
2734 (defcustom org-read-date-prefer-future t
2735 "Non-nil means assume future for incomplete date input from user.
2736 This affects the following situations:
2737 1. The user gives a month but not a year.
2738 For example, if it is April and you enter \"feb 2\", this will be read
2739 as Feb 2, *next* year. \"May 5\", however, will be this year.
2740 2. The user gives a day, but no month.
2741 For example, if today is the 15th, and you enter \"3\", Org-mode will
2742 read this as the third of *next* month. However, if you enter \"17\",
2743 it will be considered as *this* month.
2745 If you set this variable to the symbol `time', then also the following
2746 will work:
2748 3. If the user gives a time.
2749 If the time is before now, it will be interpreted as tomorrow.
2751 Currently none of this works for ISO week specifications.
2753 When this option is nil, the current day, month and year will always be
2754 used as defaults.
2756 See also `org-agenda-jump-prefer-future'."
2757 :group 'org-time
2758 :type '(choice
2759 (const :tag "Never" nil)
2760 (const :tag "Check month and day" t)
2761 (const :tag "Check month, day, and time" time)))
2763 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2764 "Should the agenda jump command prefer the future for incomplete dates?
2765 The default is to do the same as configured in `org-read-date-prefer-future'.
2766 But you can also set a deviating value here.
2767 This may t or nil, or the symbol `org-read-date-prefer-future'."
2768 :group 'org-agenda
2769 :group 'org-time
2770 :version "24.1"
2771 :type '(choice
2772 (const :tag "Use org-read-date-prefer-future"
2773 org-read-date-prefer-future)
2774 (const :tag "Never" nil)
2775 (const :tag "Always" t)))
2777 (defcustom org-read-date-force-compatible-dates t
2778 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2780 Depending on the system Emacs is running on, certain dates cannot
2781 be represented with the type used internally to represent time.
2782 Dates between 1970-1-1 and 2038-1-1 can always be represented
2783 correctly. Some systems allow for earlier dates, some for later,
2784 some for both. One way to find out it to insert any date into an
2785 Org buffer, putting the cursor on the year and hitting S-up and
2786 S-down to test the range.
2788 When this variable is set to t, the date/time prompt will not let
2789 you specify dates outside the 1970-2037 range, so it is certain that
2790 these dates will work in whatever version of Emacs you are
2791 running, and also that you can move a file from one Emacs implementation
2792 to another. WHenever Org is forcing the year for you, it will display
2793 a message and beep.
2795 When this variable is nil, Org will check if the date is
2796 representable in the specific Emacs implementation you are using.
2797 If not, it will force a year, usually the current year, and beep
2798 to remind you. Currently this setting is not recommended because
2799 the likelihood that you will open your Org files in an Emacs that
2800 has limited date range is not negligible.
2802 A workaround for this problem is to use diary sexp dates for time
2803 stamps outside of this range."
2804 :group 'org-time
2805 :version "24.1"
2806 :type 'boolean)
2808 (defcustom org-read-date-display-live t
2809 "Non-nil means display current interpretation of date prompt live.
2810 This display will be in an overlay, in the minibuffer."
2811 :group 'org-time
2812 :type 'boolean)
2814 (defcustom org-read-date-popup-calendar t
2815 "Non-nil means pop up a calendar when prompting for a date.
2816 In the calendar, the date can be selected with mouse-1. However, the
2817 minibuffer will also be active, and you can simply enter the date as well.
2818 When nil, only the minibuffer will be available."
2819 :group 'org-time
2820 :type 'boolean)
2821 (if (fboundp 'defvaralias)
2822 (defvaralias 'org-popup-calendar-for-date-prompt
2823 'org-read-date-popup-calendar))
2825 (defcustom org-read-date-minibuffer-setup-hook nil
2826 "Hook to be used to set up keys for the date/time interface.
2827 Add key definitions to `minibuffer-local-map', which will be a temporary
2828 copy."
2829 :group 'org-time
2830 :type 'hook)
2832 (defcustom org-extend-today-until 0
2833 "The hour when your day really ends. Must be an integer.
2834 This has influence for the following applications:
2835 - When switching the agenda to \"today\". It it is still earlier than
2836 the time given here, the day recognized as TODAY is actually yesterday.
2837 - When a date is read from the user and it is still before the time given
2838 here, the current date and time will be assumed to be yesterday, 23:59.
2839 Also, timestamps inserted in capture templates follow this rule.
2841 IMPORTANT: This is a feature whose implementation is and likely will
2842 remain incomplete. Really, it is only here because past midnight seems to
2843 be the favorite working time of John Wiegley :-)"
2844 :group 'org-time
2845 :type 'integer)
2847 (defcustom org-use-effective-time nil
2848 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2849 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2850 \"effective time\" of any timestamps between midnight and 8am will be
2851 23:59 of the previous day."
2852 :group 'org-time
2853 :version "24.1"
2854 :type 'boolean)
2856 (defcustom org-edit-timestamp-down-means-later nil
2857 "Non-nil means S-down will increase the time in a time stamp.
2858 When nil, S-up will increase."
2859 :group 'org-time
2860 :type 'boolean)
2862 (defcustom org-calendar-follow-timestamp-change t
2863 "Non-nil means make the calendar window follow timestamp changes.
2864 When a timestamp is modified and the calendar window is visible, it will be
2865 moved to the new date."
2866 :group 'org-time
2867 :type 'boolean)
2869 (defgroup org-tags nil
2870 "Options concerning tags in Org-mode."
2871 :tag "Org Tags"
2872 :group 'org)
2874 (defcustom org-tag-alist nil
2875 "List of tags allowed in Org-mode files.
2876 When this list is nil, Org-mode will base TAG input on what is already in the
2877 buffer.
2878 The value of this variable is an alist, the car of each entry must be a
2879 keyword as a string, the cdr may be a character that is used to select
2880 that tag through the fast-tag-selection interface.
2881 See the manual for details."
2882 :group 'org-tags
2883 :type '(repeat
2884 (choice
2885 (cons (string :tag "Tag name")
2886 (character :tag "Access char"))
2887 (list :tag "Start radio group"
2888 (const :startgroup)
2889 (option (string :tag "Group description")))
2890 (list :tag "End radio group"
2891 (const :endgroup)
2892 (option (string :tag "Group description")))
2893 (const :tag "New line" (:newline)))))
2895 (defcustom org-tag-persistent-alist nil
2896 "List of tags that will always appear in all Org-mode files.
2897 This is in addition to any in buffer settings or customizations
2898 of `org-tag-alist'.
2899 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2900 The value of this variable is an alist, the car of each entry must be a
2901 keyword as a string, the cdr may be a character that is used to select
2902 that tag through the fast-tag-selection interface.
2903 See the manual for details.
2904 To disable these tags on a per-file basis, insert anywhere in the file:
2905 #+STARTUP: noptag"
2906 :group 'org-tags
2907 :type '(repeat
2908 (choice
2909 (cons (string :tag "Tag name")
2910 (character :tag "Access char"))
2911 (const :tag "Start radio group" (:startgroup))
2912 (const :tag "End radio group" (:endgroup))
2913 (const :tag "New line" (:newline)))))
2915 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2916 "If non-nil, always offer completion for all tags of all agenda files.
2917 Instead of customizing this variable directly, you might want to
2918 set it locally for capture buffers, because there no list of
2919 tags in that file can be created dynamically (there are none).
2921 (add-hook 'org-capture-mode-hook
2922 (lambda ()
2923 (set (make-local-variable
2924 'org-complete-tags-always-offer-all-agenda-tags)
2925 t)))"
2926 :group 'org-tags
2927 :version "24.1"
2928 :type 'boolean)
2930 (defvar org-file-tags nil
2931 "List of tags that can be inherited by all entries in the file.
2932 The tags will be inherited if the variable `org-use-tag-inheritance'
2933 says they should be.
2934 This variable is populated from #+FILETAGS lines.")
2936 (defcustom org-use-fast-tag-selection 'auto
2937 "Non-nil means use fast tag selection scheme.
2938 This is a special interface to select and deselect tags with single keys.
2939 When nil, fast selection is never used.
2940 When the symbol `auto', fast selection is used if and only if selection
2941 characters for tags have been configured, either through the variable
2942 `org-tag-alist' or through a #+TAGS line in the buffer.
2943 When t, fast selection is always used and selection keys are assigned
2944 automatically if necessary."
2945 :group 'org-tags
2946 :type '(choice
2947 (const :tag "Always" t)
2948 (const :tag "Never" nil)
2949 (const :tag "When selection characters are configured" 'auto)))
2951 (defcustom org-fast-tag-selection-single-key nil
2952 "Non-nil means fast tag selection exits after first change.
2953 When nil, you have to press RET to exit it.
2954 During fast tag selection, you can toggle this flag with `C-c'.
2955 This variable can also have the value `expert'. In this case, the window
2956 displaying the tags menu is not even shown, until you press C-c again."
2957 :group 'org-tags
2958 :type '(choice
2959 (const :tag "No" nil)
2960 (const :tag "Yes" t)
2961 (const :tag "Expert" expert)))
2963 (defvar org-fast-tag-selection-include-todo nil
2964 "Non-nil means fast tags selection interface will also offer TODO states.
2965 This is an undocumented feature, you should not rely on it.")
2967 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2968 "The column to which tags should be indented in a headline.
2969 If this number is positive, it specifies the column. If it is negative,
2970 it means that the tags should be flushright to that column. For example,
2971 -80 works well for a normal 80 character screen.
2972 When 0, place tags directly after headline text, with only one space in
2973 between."
2974 :group 'org-tags
2975 :type 'integer)
2977 (defcustom org-auto-align-tags t
2978 "Non-nil keeps tags aligned when modifying headlines.
2979 Some operations (i.e. demoting) change the length of a headline and
2980 therefore shift the tags around. With this option turned on, after
2981 each such operation the tags are again aligned to `org-tags-column'."
2982 :group 'org-tags
2983 :type 'boolean)
2985 (defcustom org-use-tag-inheritance t
2986 "Non-nil means tags in levels apply also for sublevels.
2987 When nil, only the tags directly given in a specific line apply there.
2988 This may also be a list of tags that should be inherited, or a regexp that
2989 matches tags that should be inherited. Additional control is possible
2990 with the variable `org-tags-exclude-from-inheritance' which gives an
2991 explicit list of tags to be excluded from inheritance, even if the value of
2992 `org-use-tag-inheritance' would select it for inheritance.
2994 If this option is t, a match early-on in a tree can lead to a large
2995 number of matches in the subtree when constructing the agenda or creating
2996 a sparse tree. If you only want to see the first match in a tree during
2997 a search, check out the variable `org-tags-match-list-sublevels'."
2998 :group 'org-tags
2999 :type '(choice
3000 (const :tag "Not" nil)
3001 (const :tag "Always" t)
3002 (repeat :tag "Specific tags" (string :tag "Tag"))
3003 (regexp :tag "Tags matched by regexp")))
3005 (defcustom org-tags-exclude-from-inheritance nil
3006 "List of tags that should never be inherited.
3007 This is a way to exclude a few tags from inheritance. For way to do
3008 the opposite, to actively allow inheritance for selected tags,
3009 see the variable `org-use-tag-inheritance'."
3010 :group 'org-tags
3011 :type '(repeat (string :tag "Tag")))
3013 (defun org-tag-inherit-p (tag)
3014 "Check if TAG is one that should be inherited."
3015 (cond
3016 ((member tag org-tags-exclude-from-inheritance) nil)
3017 ((eq org-use-tag-inheritance t) t)
3018 ((not org-use-tag-inheritance) nil)
3019 ((stringp org-use-tag-inheritance)
3020 (string-match org-use-tag-inheritance tag))
3021 ((listp org-use-tag-inheritance)
3022 (member tag org-use-tag-inheritance))
3023 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3025 (defcustom org-tags-match-list-sublevels t
3026 "Non-nil means list also sublevels of headlines matching a search.
3027 This variable applies to tags/property searches, and also to stuck
3028 projects because this search is based on a tags match as well.
3030 When set to the symbol `indented', sublevels are indented with
3031 leading dots.
3033 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3034 the sublevels of a headline matching a tag search often also match
3035 the same search. Listing all of them can create very long lists.
3036 Setting this variable to nil causes subtrees of a match to be skipped.
3038 This variable is semi-obsolete and probably should always be true. It
3039 is better to limit inheritance to certain tags using the variables
3040 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3041 :group 'org-tags
3042 :type '(choice
3043 (const :tag "No, don't list them" nil)
3044 (const :tag "Yes, do list them" t)
3045 (const :tag "List them, indented with leading dots" indented)))
3047 (defcustom org-tags-sort-function nil
3048 "When set, tags are sorted using this function as a comparator."
3049 :group 'org-tags
3050 :type '(choice
3051 (const :tag "No sorting" nil)
3052 (const :tag "Alphabetical" string<)
3053 (const :tag "Reverse alphabetical" string>)
3054 (function :tag "Custom function" nil)))
3056 (defvar org-tags-history nil
3057 "History of minibuffer reads for tags.")
3058 (defvar org-last-tags-completion-table nil
3059 "The last used completion table for tags.")
3060 (defvar org-after-tags-change-hook nil
3061 "Hook that is run after the tags in a line have changed.")
3063 (defgroup org-properties nil
3064 "Options concerning properties in Org-mode."
3065 :tag "Org Properties"
3066 :group 'org)
3068 (defcustom org-property-format "%-10s %s"
3069 "How property key/value pairs should be formatted by `indent-line'.
3070 When `indent-line' hits a property definition, it will format the line
3071 according to this format, mainly to make sure that the values are
3072 lined-up with respect to each other."
3073 :group 'org-properties
3074 :type 'string)
3076 (defcustom org-properties-postprocess-alist nil
3077 "Alist of properties and functions to adjust inserted values.
3078 Elements of this alist must be of the form
3080 ([string] [function])
3082 where [string] must be a property name and [function] must be a
3083 lambda expression: this lambda expression must take one argument,
3084 the value to adjust, and return the new value as a string.
3086 For example, this element will allow the property \"Remaining\"
3087 to be updated wrt the relation between the \"Effort\" property
3088 and the clock summary:
3090 ((\"Remaining\" (lambda(value)
3091 (let ((clocksum (org-clock-sum-current-item))
3092 (effort (org-duration-string-to-minutes
3093 (org-entry-get (point) \"Effort\"))))
3094 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3095 :group 'org-properties
3096 :version "24.1"
3097 :type '(alist :key-type (string :tag "Property")
3098 :value-type (function :tag "Function")))
3100 (defcustom org-use-property-inheritance nil
3101 "Non-nil means properties apply also for sublevels.
3103 This setting is chiefly used during property searches. Turning it on can
3104 cause significant overhead when doing a search, which is why it is not
3105 on by default.
3107 When nil, only the properties directly given in the current entry count.
3108 When t, every property is inherited. The value may also be a list of
3109 properties that should have inheritance, or a regular expression matching
3110 properties that should be inherited.
3112 However, note that some special properties use inheritance under special
3113 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3114 and the properties ending in \"_ALL\" when they are used as descriptor
3115 for valid values of a property.
3117 Note for programmers:
3118 When querying an entry with `org-entry-get', you can control if inheritance
3119 should be used. By default, `org-entry-get' looks only at the local
3120 properties. You can request inheritance by setting the inherit argument
3121 to t (to force inheritance) or to `selective' (to respect the setting
3122 in this variable)."
3123 :group 'org-properties
3124 :type '(choice
3125 (const :tag "Not" nil)
3126 (const :tag "Always" t)
3127 (repeat :tag "Specific properties" (string :tag "Property"))
3128 (regexp :tag "Properties matched by regexp")))
3130 (defun org-property-inherit-p (property)
3131 "Check if PROPERTY is one that should be inherited."
3132 (cond
3133 ((eq org-use-property-inheritance t) t)
3134 ((not org-use-property-inheritance) nil)
3135 ((stringp org-use-property-inheritance)
3136 (string-match org-use-property-inheritance property))
3137 ((listp org-use-property-inheritance)
3138 (member property org-use-property-inheritance))
3139 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3141 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3142 "The default column format, if no other format has been defined.
3143 This variable can be set on the per-file basis by inserting a line
3145 #+COLUMNS: %25ITEM ....."
3146 :group 'org-properties
3147 :type 'string)
3149 (defcustom org-columns-ellipses ".."
3150 "The ellipses to be used when a field in column view is truncated.
3151 When this is the empty string, as many characters as possible are shown,
3152 but then there will be no visual indication that the field has been truncated.
3153 When this is a string of length N, the last N characters of a truncated
3154 field are replaced by this string. If the column is narrower than the
3155 ellipses string, only part of the ellipses string will be shown."
3156 :group 'org-properties
3157 :type 'string)
3159 (defcustom org-columns-modify-value-for-display-function nil
3160 "Function that modifies values for display in column view.
3161 For example, it can be used to cut out a certain part from a time stamp.
3162 The function must take 2 arguments:
3164 column-title The title of the column (*not* the property name)
3165 value The value that should be modified.
3167 The function should return the value that should be displayed,
3168 or nil if the normal value should be used."
3169 :group 'org-properties
3170 :type 'function)
3172 (defcustom org-effort-property "Effort"
3173 "The property that is being used to keep track of effort estimates.
3174 Effort estimates given in this property need to have the format H:MM."
3175 :group 'org-properties
3176 :group 'org-progress
3177 :type '(string :tag "Property"))
3179 (defconst org-global-properties-fixed
3180 '(("VISIBILITY_ALL" . "folded children content all")
3181 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3182 "List of property/value pairs that can be inherited by any entry.
3184 These are fixed values, for the preset properties. The user variable
3185 that can be used to add to this list is `org-global-properties'.
3187 The entries in this list are cons cells where the car is a property
3188 name and cdr is a string with the value. If the value represents
3189 multiple items like an \"_ALL\" property, separate the items by
3190 spaces.")
3192 (defcustom org-global-properties nil
3193 "List of property/value pairs that can be inherited by any entry.
3195 This list will be combined with the constant `org-global-properties-fixed'.
3197 The entries in this list are cons cells where the car is a property
3198 name and cdr is a string with the value.
3200 You can set buffer-local values for the same purpose in the variable
3201 `org-file-properties' this by adding lines like
3203 #+PROPERTY: NAME VALUE"
3204 :group 'org-properties
3205 :type '(repeat
3206 (cons (string :tag "Property")
3207 (string :tag "Value"))))
3209 (defvar org-file-properties nil
3210 "List of property/value pairs that can be inherited by any entry.
3211 Valid for the current buffer.
3212 This variable is populated from #+PROPERTY lines.")
3213 (make-variable-buffer-local 'org-file-properties)
3215 (defgroup org-agenda nil
3216 "Options concerning agenda views in Org-mode."
3217 :tag "Org Agenda"
3218 :group 'org)
3220 (defvar org-category nil
3221 "Variable used by org files to set a category for agenda display.
3222 Such files should use a file variable to set it, for example
3224 # -*- mode: org; org-category: \"ELisp\"
3226 or contain a special line
3228 #+CATEGORY: ELisp
3230 If the file does not specify a category, then file's base name
3231 is used instead.")
3232 (make-variable-buffer-local 'org-category)
3233 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3235 (defcustom org-agenda-files nil
3236 "The files to be used for agenda display.
3237 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3238 \\[org-remove-file]. You can also use customize to edit the list.
3240 If an entry is a directory, all files in that directory that are matched by
3241 `org-agenda-file-regexp' will be part of the file list.
3243 If the value of the variable is not a list but a single file name, then
3244 the list of agenda files is actually stored and maintained in that file, one
3245 agenda file per line. In this file paths can be given relative to
3246 `org-directory'. Tilde expansion and environment variable substitution
3247 are also made."
3248 :group 'org-agenda
3249 :type '(choice
3250 (repeat :tag "List of files and directories" file)
3251 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3253 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3254 "Regular expression to match files for `org-agenda-files'.
3255 If any element in the list in that variable contains a directory instead
3256 of a normal file, all files in that directory that are matched by this
3257 regular expression will be included."
3258 :group 'org-agenda
3259 :type 'regexp)
3261 (defcustom org-agenda-text-search-extra-files nil
3262 "List of extra files to be searched by text search commands.
3263 These files will be search in addition to the agenda files by the
3264 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3265 Note that these files will only be searched for text search commands,
3266 not for the other agenda views like todo lists, tag searches or the weekly
3267 agenda. This variable is intended to list notes and possibly archive files
3268 that should also be searched by these two commands.
3269 In fact, if the first element in the list is the symbol `agenda-archives',
3270 than all archive files of all agenda files will be added to the search
3271 scope."
3272 :group 'org-agenda
3273 :type '(set :greedy t
3274 (const :tag "Agenda Archives" agenda-archives)
3275 (repeat :inline t (file))))
3277 (if (fboundp 'defvaralias)
3278 (defvaralias 'org-agenda-multi-occur-extra-files
3279 'org-agenda-text-search-extra-files))
3281 (defcustom org-agenda-skip-unavailable-files nil
3282 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3283 A nil value means to remove them, after a query, from the list."
3284 :group 'org-agenda
3285 :type 'boolean)
3287 (defcustom org-calendar-to-agenda-key [?c]
3288 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3289 The command `org-calendar-goto-agenda' will be bound to this key. The
3290 default is the character `c' because then `c' can be used to switch back and
3291 forth between agenda and calendar."
3292 :group 'org-agenda
3293 :type 'sexp)
3295 (defcustom org-calendar-insert-diary-entry-key [?i]
3296 "The key to be installed in `calendar-mode-map' for adding diary entries.
3297 This option is irrelevant until `org-agenda-diary-file' has been configured
3298 to point to an Org-mode file. When that is the case, the command
3299 `org-agenda-diary-entry' will be bound to the key given here, by default
3300 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3301 if you want to continue doing this, you need to change this to a different
3302 key."
3303 :group 'org-agenda
3304 :type 'sexp)
3306 (defcustom org-agenda-diary-file 'diary-file
3307 "File to which to add new entries with the `i' key in agenda and calendar.
3308 When this is the symbol `diary-file', the functionality in the Emacs
3309 calendar will be used to add entries to the `diary-file'. But when this
3310 points to a file, `org-agenda-diary-entry' will be used instead."
3311 :group 'org-agenda
3312 :type '(choice
3313 (const :tag "The standard Emacs diary file" diary-file)
3314 (file :tag "Special Org file diary entries")))
3316 (eval-after-load "calendar"
3317 '(progn
3318 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3319 'org-calendar-goto-agenda)
3320 (add-hook 'calendar-mode-hook
3321 (lambda ()
3322 (unless (eq org-agenda-diary-file 'diary-file)
3323 (define-key calendar-mode-map
3324 org-calendar-insert-diary-entry-key
3325 'org-agenda-diary-entry))))))
3327 (defgroup org-latex nil
3328 "Options for embedding LaTeX code into Org-mode."
3329 :tag "Org LaTeX"
3330 :group 'org)
3332 (defcustom org-format-latex-options
3333 '(:foreground default :background default :scale 1.0
3334 :html-foreground "Black" :html-background "Transparent"
3335 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3336 "Options for creating images from LaTeX fragments.
3337 This is a property list with the following properties:
3338 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3339 `default' means use the foreground of the default face.
3340 :background the background color, or \"Transparent\".
3341 `default' means use the background of the default face.
3342 :scale a scaling factor for the size of the images, to get more pixels
3343 :html-foreground, :html-background, :html-scale
3344 the same numbers for HTML export.
3345 :matchers a list indicating which matchers should be used to
3346 find LaTeX fragments. Valid members of this list are:
3347 \"begin\" find environments
3348 \"$1\" find single characters surrounded by $.$
3349 \"$\" find math expressions surrounded by $...$
3350 \"$$\" find math expressions surrounded by $$....$$
3351 \"\\(\" find math expressions surrounded by \\(...\\)
3352 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3353 :group 'org-latex
3354 :type 'plist)
3356 (defcustom org-format-latex-signal-error t
3357 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3358 When nil, just push out a message."
3359 :group 'org-latex
3360 :version "24.1"
3361 :type 'boolean)
3363 (defcustom org-latex-to-mathml-jar-file nil
3364 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3365 Use this to specify additional executable file say a jar file.
3367 When using MathToWeb as the converter, specify the full-path to
3368 your mathtoweb.jar file."
3369 :group 'org-latex
3370 :version "24.1"
3371 :type '(choice
3372 (const :tag "None" nil)
3373 (file :tag "JAR file" :must-match t)))
3375 (defcustom org-latex-to-mathml-convert-command nil
3376 "Command to convert LaTeX fragments to MathML.
3377 Replace format-specifiers in the command as noted below and use
3378 `shell-command' to convert LaTeX to MathML.
3379 %j: Executable file in fully expanded form as specified by
3380 `org-latex-to-mathml-jar-file'.
3381 %I: Input LaTeX file in fully expanded form
3382 %o: Output MathML file
3383 This command is used by `org-create-math-formula'.
3385 When using MathToWeb as the converter, set this to
3386 \"java -jar %j -unicode -force -df %o %I\"."
3387 :group 'org-latex
3388 :version "24.1"
3389 :type '(choice
3390 (const :tag "None" nil)
3391 (string :tag "\nShell command")))
3393 (defcustom org-latex-create-formula-image-program 'dvipng
3394 "Program to convert LaTeX fragments with.
3396 dvipng Process the LaTeX fragments to dvi file, then convert
3397 dvi files to png files using dvipng.
3398 This will also include processing of non-math environments.
3399 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3400 to convert pdf files to png files"
3401 :group 'org-latex
3402 :version "24.1"
3403 :type '(choice
3404 (const :tag "dvipng" dvipng)
3405 (const :tag "imagemagick" imagemagick)))
3407 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3408 "Path to store latex preview images. A relative path here creates many
3409 directories relative to the processed org files paths. An absolute path
3410 puts all preview images at the same place."
3411 :group 'org-latex
3412 :version "24.3"
3413 :type 'string)
3415 (defun org-format-latex-mathml-available-p ()
3416 "Return t if `org-latex-to-mathml-convert-command' is usable."
3417 (save-match-data
3418 (when (and (boundp 'org-latex-to-mathml-convert-command)
3419 org-latex-to-mathml-convert-command)
3420 (let ((executable (car (split-string
3421 org-latex-to-mathml-convert-command))))
3422 (when (executable-find executable)
3423 (if (string-match
3424 "%j" org-latex-to-mathml-convert-command)
3425 (file-readable-p org-latex-to-mathml-jar-file)
3426 t))))))
3428 (defcustom org-format-latex-header "\\documentclass{article}
3429 \\usepackage[usenames]{color}
3430 \\usepackage{amsmath}
3431 \\usepackage[mathscr]{eucal}
3432 \\pagestyle{empty} % do not remove
3433 \[PACKAGES]
3434 \[DEFAULT-PACKAGES]
3435 % The settings below are copied from fullpage.sty
3436 \\setlength{\\textwidth}{\\paperwidth}
3437 \\addtolength{\\textwidth}{-3cm}
3438 \\setlength{\\oddsidemargin}{1.5cm}
3439 \\addtolength{\\oddsidemargin}{-2.54cm}
3440 \\setlength{\\evensidemargin}{\\oddsidemargin}
3441 \\setlength{\\textheight}{\\paperheight}
3442 \\addtolength{\\textheight}{-\\headheight}
3443 \\addtolength{\\textheight}{-\\headsep}
3444 \\addtolength{\\textheight}{-\\footskip}
3445 \\addtolength{\\textheight}{-3cm}
3446 \\setlength{\\topmargin}{1.5cm}
3447 \\addtolength{\\topmargin}{-2.54cm}"
3448 "The document header used for processing LaTeX fragments.
3449 It is imperative that this header make sure that no page number
3450 appears on the page. The package defined in the variables
3451 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3452 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3453 will be appended."
3454 :group 'org-latex
3455 :type 'string)
3457 (defvar org-format-latex-header-extra nil)
3459 (defun org-set-packages-alist (var val)
3460 "Set the packages alist and make sure it has 3 elements per entry."
3461 (set var (mapcar (lambda (x)
3462 (if (and (consp x) (= (length x) 2))
3463 (list (car x) (nth 1 x) t)
3465 val)))
3467 (defun org-get-packages-alist (var)
3469 "Get the packages alist and make sure it has 3 elements per entry."
3470 (mapcar (lambda (x)
3471 (if (and (consp x) (= (length x) 2))
3472 (list (car x) (nth 1 x) t)
3474 (default-value var)))
3476 ;; The following variables are defined here because is it also used
3477 ;; when formatting latex fragments. Originally it was part of the
3478 ;; LaTeX exporter, which is why the name includes "export".
3479 (defcustom org-export-latex-default-packages-alist
3480 '(("AUTO" "inputenc" t)
3481 ("T1" "fontenc" t)
3482 ("" "fixltx2e" nil)
3483 ("" "graphicx" t)
3484 ("" "longtable" nil)
3485 ("" "float" nil)
3486 ("" "wrapfig" nil)
3487 ("" "soul" t)
3488 ("" "textcomp" t)
3489 ("" "marvosym" t)
3490 ("" "wasysym" t)
3491 ("" "latexsym" t)
3492 ("" "amssymb" t)
3493 ("" "hyperref" nil)
3494 "\\tolerance=1000"
3496 "Alist of default packages to be inserted in the header.
3497 Change this only if one of the packages here causes an incompatibility
3498 with another package you are using.
3499 The packages in this list are needed by one part or another of Org-mode
3500 to function properly.
3502 - inputenc, fontenc: for basic font and character selection
3503 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3504 for interpreting the entities in `org-entities'. You can skip some of these
3505 packages if you don't use any of the symbols in it.
3506 - graphicx: for including images
3507 - float, wrapfig: for figure placement
3508 - longtable: for long tables
3509 - hyperref: for cross references
3511 Therefore you should not modify this variable unless you know what you
3512 are doing. The one reason to change it anyway is that you might be loading
3513 some other package that conflicts with one of the default packages.
3514 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3515 If SNIPPET-FLAG is t, the package also needs to be included when
3516 compiling LaTeX snippets into images for inclusion into HTML."
3517 :group 'org-export-latex
3518 :set 'org-set-packages-alist
3519 :get 'org-get-packages-alist
3520 :version "24.1"
3521 :type '(repeat
3522 (choice
3523 (list :tag "options/package pair"
3524 (string :tag "options")
3525 (string :tag "package")
3526 (boolean :tag "Snippet"))
3527 (string :tag "A line of LaTeX"))))
3529 (defcustom org-export-latex-packages-alist nil
3530 "Alist of packages to be inserted in every LaTeX header.
3531 These will be inserted after `org-export-latex-default-packages-alist'.
3532 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3533 SNIPPET-FLAG, when t, indicates that this package is also needed when
3534 turning LaTeX snippets into images for inclusion into HTML.
3535 Make sure that you only list packages here which:
3536 - you want in every file
3537 - do not conflict with the default packages in
3538 `org-export-latex-default-packages-alist'
3539 - do not conflict with the setup in `org-format-latex-header'."
3540 :group 'org-export-latex
3541 :set 'org-set-packages-alist
3542 :get 'org-get-packages-alist
3543 :type '(repeat
3544 (choice
3545 (list :tag "options/package pair"
3546 (string :tag "options")
3547 (string :tag "package")
3548 (boolean :tag "Snippet"))
3549 (string :tag "A line of LaTeX"))))
3552 (defgroup org-appearance nil
3553 "Settings for Org-mode appearance."
3554 :tag "Org Appearance"
3555 :group 'org)
3557 (defcustom org-level-color-stars-only nil
3558 "Non-nil means fontify only the stars in each headline.
3559 When nil, the entire headline is fontified.
3560 Changing it requires restart of `font-lock-mode' to become effective
3561 also in regions already fontified."
3562 :group 'org-appearance
3563 :type 'boolean)
3565 (defcustom org-hide-leading-stars nil
3566 "Non-nil means hide the first N-1 stars in a headline.
3567 This works by using the face `org-hide' for these stars. This
3568 face is white for a light background, and black for a dark
3569 background. You may have to customize the face `org-hide' to
3570 make this work.
3571 Changing it requires restart of `font-lock-mode' to become effective
3572 also in regions already fontified.
3573 You may also set this on a per-file basis by adding one of the following
3574 lines to the buffer:
3576 #+STARTUP: hidestars
3577 #+STARTUP: showstars"
3578 :group 'org-appearance
3579 :type 'boolean)
3581 (defcustom org-hidden-keywords nil
3582 "List of symbols corresponding to keywords to be hidden the org buffer.
3583 For example, a value '(title) for this list will make the document's title
3584 appear in the buffer without the initial #+TITLE: keyword."
3585 :group 'org-appearance
3586 :version "24.1"
3587 :type '(set (const :tag "#+AUTHOR" author)
3588 (const :tag "#+DATE" date)
3589 (const :tag "#+EMAIL" email)
3590 (const :tag "#+TITLE" title)))
3592 (defcustom org-custom-properties nil
3593 "List of properties (as strings) with a special meaning.
3594 The default use of these custom properties is to let the user
3595 hide them with `org-toggle-custom-properties-visibility'."
3596 :group 'org-properties
3597 :group 'org-appearance
3598 :version "24.3"
3599 :type '(repeat (string :tag "Property Name")))
3601 (defcustom org-fontify-done-headline nil
3602 "Non-nil means change the face of a headline if it is marked DONE.
3603 Normally, only the TODO/DONE keyword indicates the state of a headline.
3604 When this is non-nil, the headline after the keyword is set to the
3605 `org-headline-done' as an additional indication."
3606 :group 'org-appearance
3607 :type 'boolean)
3609 (defcustom org-fontify-emphasized-text t
3610 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3611 Changing this variable requires a restart of Emacs to take effect."
3612 :group 'org-appearance
3613 :type 'boolean)
3615 (defcustom org-fontify-whole-heading-line nil
3616 "Non-nil means fontify the whole line for headings.
3617 This is useful when setting a background color for the
3618 org-level-* faces."
3619 :group 'org-appearance
3620 :type 'boolean)
3622 (defcustom org-highlight-latex-fragments-and-specials nil
3623 "Non-nil means fontify what is treated specially by the exporters."
3624 :group 'org-appearance
3625 :type 'boolean)
3627 (defcustom org-hide-emphasis-markers nil
3628 "Non-nil mean font-lock should hide the emphasis marker characters."
3629 :group 'org-appearance
3630 :type 'boolean)
3632 (defcustom org-pretty-entities nil
3633 "Non-nil means show entities as UTF8 characters.
3634 When nil, the \\name form remains in the buffer."
3635 :group 'org-appearance
3636 :version "24.1"
3637 :type 'boolean)
3639 (defcustom org-pretty-entities-include-sub-superscripts t
3640 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3641 :group 'org-appearance
3642 :version "24.1"
3643 :type 'boolean)
3645 (defvar org-emph-re nil
3646 "Regular expression for matching emphasis.
3647 After a match, the match groups contain these elements:
3648 0 The match of the full regular expression, including the characters
3649 before and after the proper match
3650 1 The character before the proper match, or empty at beginning of line
3651 2 The proper match, including the leading and trailing markers
3652 3 The leading marker like * or /, indicating the type of highlighting
3653 4 The text between the emphasis markers, not including the markers
3654 5 The character after the match, empty at the end of a line")
3655 (defvar org-verbatim-re nil
3656 "Regular expression for matching verbatim text.")
3657 (defvar org-emphasis-regexp-components) ; defined just below
3658 (defvar org-emphasis-alist) ; defined just below
3659 (defun org-set-emph-re (var val)
3660 "Set variable and compute the emphasis regular expression."
3661 (set var val)
3662 (when (and (boundp 'org-emphasis-alist)
3663 (boundp 'org-emphasis-regexp-components)
3664 org-emphasis-alist org-emphasis-regexp-components)
3665 (let* ((e org-emphasis-regexp-components)
3666 (pre (car e))
3667 (post (nth 1 e))
3668 (border (nth 2 e))
3669 (body (nth 3 e))
3670 (nl (nth 4 e))
3671 (body1 (concat body "*?"))
3672 (markers (mapconcat 'car org-emphasis-alist ""))
3673 (vmarkers (mapconcat
3674 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3675 org-emphasis-alist "")))
3676 ;; make sure special characters appear at the right position in the class
3677 (if (string-match "\\^" markers)
3678 (setq markers (concat (replace-match "" t t markers) "^")))
3679 (if (string-match "-" markers)
3680 (setq markers (concat (replace-match "" t t markers) "-")))
3681 (if (string-match "\\^" vmarkers)
3682 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3683 (if (string-match "-" vmarkers)
3684 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3685 (if (> nl 0)
3686 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3687 (int-to-string nl) "\\}")))
3688 ;; Make the regexp
3689 (setq org-emph-re
3690 (concat "\\([" pre "]\\|^\\)"
3691 "\\("
3692 "\\([" markers "]\\)"
3693 "\\("
3694 "[^" border "]\\|"
3695 "[^" border "]"
3696 body1
3697 "[^" border "]"
3698 "\\)"
3699 "\\3\\)"
3700 "\\([" post "]\\|$\\)"))
3701 (setq org-verbatim-re
3702 (concat "\\([" pre "]\\|^\\)"
3703 "\\("
3704 "\\([" vmarkers "]\\)"
3705 "\\("
3706 "[^" border "]\\|"
3707 "[^" border "]"
3708 body1
3709 "[^" border "]"
3710 "\\)"
3711 "\\3\\)"
3712 "\\([" post "]\\|$\\)")))))
3714 (defcustom org-emphasis-regexp-components
3715 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3716 "Components used to build the regular expression for emphasis.
3717 This is a list with five entries. Terminology: In an emphasis string
3718 like \" *strong word* \", we call the initial space PREMATCH, the final
3719 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3720 and \"trong wor\" is the body. The different components in this variable
3721 specify what is allowed/forbidden in each part:
3723 pre Chars allowed as prematch. Beginning of line will be allowed too.
3724 post Chars allowed as postmatch. End of line will be allowed too.
3725 border The chars *forbidden* as border characters.
3726 body-regexp A regexp like \".\" to match a body character. Don't use
3727 non-shy groups here, and don't allow newline here.
3728 newline The maximum number of newlines allowed in an emphasis exp.
3730 Use customize to modify this, or restart Emacs after changing it."
3731 :group 'org-appearance
3732 :set 'org-set-emph-re
3733 :type '(list
3734 (sexp :tag "Allowed chars in pre ")
3735 (sexp :tag "Allowed chars in post ")
3736 (sexp :tag "Forbidden chars in border ")
3737 (sexp :tag "Regexp for body ")
3738 (integer :tag "number of newlines allowed")
3739 (option (boolean :tag "Please ignore this button"))))
3741 (defcustom org-emphasis-alist
3742 `(("*" bold "<b>" "</b>")
3743 ("/" italic "<i>" "</i>")
3744 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3745 ("=" org-code "<code>" "</code>" verbatim)
3746 ("~" org-verbatim "<code>" "</code>" verbatim)
3747 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3748 "<del>" "</del>")
3750 "Special syntax for emphasized text.
3751 Text starting and ending with a special character will be emphasized, for
3752 example *bold*, _underlined_ and /italic/. This variable sets the marker
3753 characters, the face to be used by font-lock for highlighting in Org-mode
3754 Emacs buffers, and the HTML tags to be used for this.
3755 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3756 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3757 Use customize to modify this, or restart Emacs after changing it."
3758 :group 'org-appearance
3759 :set 'org-set-emph-re
3760 :type '(repeat
3761 (list
3762 (string :tag "Marker character")
3763 (choice
3764 (face :tag "Font-lock-face")
3765 (plist :tag "Face property list"))
3766 (string :tag "HTML start tag")
3767 (string :tag "HTML end tag")
3768 (option (const verbatim)))))
3770 (defvar org-protecting-blocks
3771 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3772 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3773 This is needed for font-lock setup.")
3775 ;;; Miscellaneous options
3777 (defgroup org-completion nil
3778 "Completion in Org-mode."
3779 :tag "Org Completion"
3780 :group 'org)
3782 (defcustom org-completion-use-ido nil
3783 "Non-nil means use ido completion wherever possible.
3784 Note that `ido-mode' must be active for this variable to be relevant.
3785 If you decide to turn this variable on, you might well want to turn off
3786 `org-outline-path-complete-in-steps'.
3787 See also `org-completion-use-iswitchb'."
3788 :group 'org-completion
3789 :type 'boolean)
3791 (defcustom org-completion-use-iswitchb nil
3792 "Non-nil means use iswitchb completion wherever possible.
3793 Note that `iswitchb-mode' must be active for this variable to be relevant.
3794 If you decide to turn this variable on, you might well want to turn off
3795 `org-outline-path-complete-in-steps'.
3796 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3797 :group 'org-completion
3798 :type 'boolean)
3800 (defcustom org-completion-fallback-command 'hippie-expand
3801 "The expansion command called by \\[pcomplete] in normal context.
3802 Normal means, no org-mode-specific context."
3803 :group 'org-completion
3804 :type 'function)
3806 ;;; Functions and variables from their packages
3807 ;; Declared here to avoid compiler warnings
3809 ;; XEmacs only
3810 (defvar outline-mode-menu-heading)
3811 (defvar outline-mode-menu-show)
3812 (defvar outline-mode-menu-hide)
3813 (defvar zmacs-regions) ; XEmacs regions
3815 ;; Emacs only
3816 (defvar mark-active)
3818 ;; Various packages
3819 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3820 (declare-function calendar-forward-day "cal-move" (arg))
3821 (declare-function calendar-goto-date "cal-move" (date))
3822 (declare-function calendar-goto-today "cal-move" ())
3823 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3824 (defvar calc-embedded-close-formula)
3825 (defvar calc-embedded-open-formula)
3826 (declare-function cdlatex-tab "ext:cdlatex" ())
3827 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3828 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3829 (defvar font-lock-unfontify-region-function)
3830 (declare-function iswitchb-read-buffer "iswitchb"
3831 (prompt &optional default require-match start matches-set))
3832 (defvar iswitchb-temp-buflist)
3833 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3834 (defvar org-agenda-tags-todo-honor-ignore-options)
3835 (declare-function org-agenda-skip "org-agenda" ())
3836 (declare-function
3837 org-agenda-format-item "org-agenda"
3838 (extra txt &optional category tags dotime noprefix remove-re habitp))
3839 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3840 (declare-function org-agenda-change-all-lines "org-agenda"
3841 (newhead hdmarker &optional fixface just-this))
3842 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3843 (declare-function org-agenda-maybe-redo "org-agenda" ())
3844 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3845 (beg end))
3846 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3847 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3848 "org-agenda" (&optional end))
3849 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3850 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3851 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3852 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3853 (declare-function org-indent-mode "org-indent" (&optional arg))
3854 (declare-function parse-time-string "parse-time" (string))
3855 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3856 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3857 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3858 (defvar remember-data-file)
3859 (defvar texmathp-why)
3860 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3861 (declare-function table--at-cell-p "table" (position &optional object at-column))
3863 (defvar w3m-current-url)
3864 (defvar w3m-current-title)
3866 (defvar org-latex-regexps)
3868 ;;; Autoload and prepare some org modules
3870 ;; Some table stuff that needs to be defined here, because it is used
3871 ;; by the functions setting up org-mode or checking for table context.
3873 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3874 "Detect an org-type or table-type table.")
3875 (defconst org-table-line-regexp "^[ \t]*|"
3876 "Detect an org-type table line.")
3877 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3878 "Detect an org-type table line.")
3879 (defconst org-table-hline-regexp "^[ \t]*|-"
3880 "Detect an org-type table hline.")
3881 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3882 "Detect a table-type table hline.")
3883 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3884 "Detect the first line outside a table when searching from within it.
3885 This works for both table types.")
3887 ;; Autoload the functions in org-table.el that are needed by functions here.
3889 (eval-and-compile
3890 (org-autoload "org-table"
3891 '(org-table-begin org-table-blank-field org-table-end)))
3893 ;;;###autoload
3894 (defun turn-on-orgtbl ()
3895 "Unconditionally turn on `orgtbl-mode'."
3896 (require 'org-table)
3897 (orgtbl-mode 1))
3899 (defun org-at-table-p (&optional table-type)
3900 "Return t if the cursor is inside an org-type table.
3901 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3902 (if org-enable-table-editor
3903 (save-excursion
3904 (beginning-of-line 1)
3905 (looking-at (if table-type org-table-any-line-regexp
3906 org-table-line-regexp)))
3907 nil))
3908 (defsubst org-table-p () (org-at-table-p))
3910 (defun org-at-table.el-p ()
3911 "Return t if and only if we are at a table.el table."
3912 (and (org-at-table-p 'any)
3913 (save-excursion
3914 (goto-char (org-table-begin 'any))
3915 (looking-at org-table1-hline-regexp))))
3916 (defun org-table-recognize-table.el ()
3917 "If there is a table.el table nearby, recognize it and move into it."
3918 (if org-table-tab-recognizes-table.el
3919 (if (org-at-table.el-p)
3920 (progn
3921 (beginning-of-line 1)
3922 (if (looking-at org-table-dataline-regexp)
3924 (if (looking-at org-table1-hline-regexp)
3925 (progn
3926 (beginning-of-line 2)
3927 (if (looking-at org-table-any-border-regexp)
3928 (beginning-of-line -1)))))
3929 (if (re-search-forward "|" (org-table-end t) t)
3930 (progn
3931 (require 'table)
3932 (if (table--at-cell-p (point))
3934 (message "recognizing table.el table...")
3935 (table-recognize-table)
3936 (message "recognizing table.el table...done")))
3937 (error "This should not happen"))
3939 nil)
3940 nil))
3942 (defun org-at-table-hline-p ()
3943 "Return t if the cursor is inside a hline in a table."
3944 (if org-enable-table-editor
3945 (save-excursion
3946 (beginning-of-line 1)
3947 (looking-at org-table-hline-regexp))
3948 nil))
3950 (defvar org-table-clean-did-remove-column nil)
3952 (defun org-table-map-tables (function &optional quietly)
3953 "Apply FUNCTION to the start of all tables in the buffer."
3954 (save-excursion
3955 (save-restriction
3956 (widen)
3957 (goto-char (point-min))
3958 (while (re-search-forward org-table-any-line-regexp nil t)
3959 (unless quietly
3960 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3961 (beginning-of-line 1)
3962 (when (and (looking-at org-table-line-regexp)
3963 ;; Exclude tables in src/example/verbatim/clocktable blocks
3964 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
3965 (save-excursion (funcall function))
3966 (or (looking-at org-table-line-regexp)
3967 (forward-char 1)))
3968 (re-search-forward org-table-any-border-regexp nil 1))))
3969 (unless quietly (message "Mapping tables: done")))
3971 ;; Declare and autoload functions from org-exp.el & Co
3973 (declare-function org-default-export-plist "org-exp")
3974 (declare-function org-infile-export-plist "org-exp")
3975 (declare-function org-get-current-options "org-exp")
3977 ;; Declare and autoload functions from org-agenda.el
3979 (eval-and-compile
3980 (org-autoload "org-agenda"
3981 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3983 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
3984 (declare-function org-clock-update-mode-line "org-clock" ())
3985 (declare-function org-resolve-clocks "org-clock"
3986 (&optional also-non-dangling-p prompt last-valid))
3987 (defvar org-clock-start-time)
3988 (defvar org-clock-marker (make-marker)
3989 "Marker recording the last clock-in.")
3990 (defvar org-clock-hd-marker (make-marker)
3991 "Marker recording the last clock-in, but the headline position.")
3992 (defvar org-clock-heading ""
3993 "The heading of the current clock entry.")
3994 (defun org-clock-is-active ()
3995 "Return non-nil if clock is currently running.
3996 The return value is actually the clock marker."
3997 (marker-buffer org-clock-marker))
3999 (eval-and-compile
4000 (org-autoload "org-clock" '(org-clock-remove-overlays
4001 org-clock-update-time-maybe
4002 org-clocktable-shift)))
4004 (defun org-check-running-clock ()
4005 "Check if the current buffer contains the running clock.
4006 If yes, offer to stop it and to save the buffer with the changes."
4007 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4008 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4009 (buffer-name))))
4010 (org-clock-out)
4011 (when (y-or-n-p "Save changed buffer?")
4012 (save-buffer))))
4014 (defun org-clocktable-try-shift (dir n)
4015 "Check if this line starts a clock table, if yes, shift the time block."
4016 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4017 (org-clocktable-shift dir n)))
4019 ;;;###autoload
4020 (defun org-clock-persistence-insinuate ()
4021 "Set up hooks for clock persistence."
4022 (require 'org-clock)
4023 (add-hook 'org-mode-hook 'org-clock-load)
4024 (add-hook 'kill-emacs-hook 'org-clock-save))
4026 ;; Define the variable already here, to make sure we have it.
4027 (defvar org-indent-mode nil
4028 "Non-nil if Org-Indent mode is enabled.
4029 Use the command `org-indent-mode' to change this variable.")
4031 ;; Autoload archiving code
4032 ;; The stuff that is needed for cycling and tags has to be defined here.
4034 (defgroup org-archive nil
4035 "Options concerning archiving in Org-mode."
4036 :tag "Org Archive"
4037 :group 'org-structure)
4039 (defcustom org-archive-location "%s_archive::"
4040 "The location where subtrees should be archived.
4042 The value of this variable is a string, consisting of two parts,
4043 separated by a double-colon. The first part is a filename and
4044 the second part is a headline.
4046 When the filename is omitted, archiving happens in the same file.
4047 %s in the filename will be replaced by the current file
4048 name (without the directory part). Archiving to a different file
4049 is useful to keep archived entries from contributing to the
4050 Org-mode Agenda.
4052 The archived entries will be filed as subtrees of the specified
4053 headline. When the headline is omitted, the subtrees are simply
4054 filed away at the end of the file, as top-level entries. Also in
4055 the heading you can use %s to represent the file name, this can be
4056 useful when using the same archive for a number of different files.
4058 Here are a few examples:
4059 \"%s_archive::\"
4060 If the current file is Projects.org, archive in file
4061 Projects.org_archive, as top-level trees. This is the default.
4063 \"::* Archived Tasks\"
4064 Archive in the current file, under the top-level headline
4065 \"* Archived Tasks\".
4067 \"~/org/archive.org::\"
4068 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4070 \"~/org/archive.org::* From %s\"
4071 Archive in file ~/org/archive.org (absolute path), under headlines
4072 \"From FILENAME\" where file name is the current file name.
4074 \"~/org/datetree.org::datetree/* Finished Tasks\"
4075 The \"datetree/\" string is special, signifying to archive
4076 items to the datetree. Items are placed in either the CLOSED
4077 date of the item, or the current date if there is no CLOSED date.
4078 The heading will be a subentry to the current date. There doesn't
4079 need to be a heading, but there always needs to be a slash after
4080 datetree. For example, to store archived items directly in the
4081 datetree, use \"~/org/datetree.org::datetree/\".
4083 \"basement::** Finished Tasks\"
4084 Archive in file ./basement (relative path), as level 3 trees
4085 below the level 2 heading \"** Finished Tasks\".
4087 You may set this option on a per-file basis by adding to the buffer a
4088 line like
4090 #+ARCHIVE: basement::** Finished Tasks
4092 You may also define it locally for a subtree by setting an ARCHIVE property
4093 in the entry. If such a property is found in an entry, or anywhere up
4094 the hierarchy, it will be used."
4095 :group 'org-archive
4096 :type 'string)
4098 (defcustom org-archive-tag "ARCHIVE"
4099 "The tag that marks a subtree as archived.
4100 An archived subtree does not open during visibility cycling, and does
4101 not contribute to the agenda listings.
4102 After changing this, font-lock must be restarted in the relevant buffers to
4103 get the proper fontification."
4104 :group 'org-archive
4105 :group 'org-keywords
4106 :type 'string)
4108 (defcustom org-agenda-skip-archived-trees t
4109 "Non-nil means the agenda will skip any items located in archived trees.
4110 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4111 variable is no longer recommended, you should leave it at the value t.
4112 Instead, use the key `v' to cycle the archives-mode in the agenda."
4113 :group 'org-archive
4114 :group 'org-agenda-skip
4115 :type 'boolean)
4117 (defcustom org-columns-skip-archived-trees t
4118 "Non-nil means ignore archived trees when creating column view."
4119 :group 'org-archive
4120 :group 'org-properties
4121 :type 'boolean)
4123 (defcustom org-cycle-open-archived-trees nil
4124 "Non-nil means `org-cycle' will open archived trees.
4125 An archived tree is a tree marked with the tag ARCHIVE.
4126 When nil, archived trees will stay folded. You can still open them with
4127 normal outline commands like `show-all', but not with the cycling commands."
4128 :group 'org-archive
4129 :group 'org-cycle
4130 :type 'boolean)
4132 (defcustom org-sparse-tree-open-archived-trees nil
4133 "Non-nil means sparse tree construction shows matches in archived trees.
4134 When nil, matches in these trees are highlighted, but the trees are kept in
4135 collapsed state."
4136 :group 'org-archive
4137 :group 'org-sparse-trees
4138 :type 'boolean)
4140 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4141 "The default date type when building a sparse tree.
4142 When this is nil, a date is a scheduled or a deadline timestamp.
4143 Otherwise, these types are allowed:
4145 all: all timestamps
4146 active: only active timestamps (<...>)
4147 inactive: only inactive timestamps (<...)
4148 scheduled: only scheduled timestamps
4149 deadline: only deadline timestamps"
4150 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4151 (const :tag "All timestamps" all)
4152 (const :tag "Only active timestamps" active)
4153 (const :tag "Only inactive timestamps" inactive)
4154 (const :tag "Only scheduled timestamps" scheduled)
4155 (const :tag "Only deadline timestamps" deadline))
4156 :version "24.3"
4157 :group 'org-sparse-trees)
4159 (defun org-cycle-hide-archived-subtrees (state)
4160 "Re-hide all archived subtrees after a visibility state change."
4161 (when (and (not org-cycle-open-archived-trees)
4162 (not (memq state '(overview folded))))
4163 (save-excursion
4164 (let* ((globalp (memq state '(contents all)))
4165 (beg (if globalp (point-min) (point)))
4166 (end (if globalp (point-max) (org-end-of-subtree t))))
4167 (org-hide-archived-subtrees beg end)
4168 (goto-char beg)
4169 (if (looking-at (concat ".*:" org-archive-tag ":"))
4170 (message "%s" (substitute-command-keys
4171 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4173 (defun org-force-cycle-archived ()
4174 "Cycle subtree even if it is archived."
4175 (interactive)
4176 (setq this-command 'org-cycle)
4177 (let ((org-cycle-open-archived-trees t))
4178 (call-interactively 'org-cycle)))
4180 (defun org-hide-archived-subtrees (beg end)
4181 "Re-hide all archived subtrees after a visibility state change."
4182 (save-excursion
4183 (let* ((re (concat ":" org-archive-tag ":")))
4184 (goto-char beg)
4185 (while (re-search-forward re end t)
4186 (when (org-at-heading-p)
4187 (org-flag-subtree t)
4188 (org-end-of-subtree t))))))
4190 (declare-function outline-end-of-heading "outline" ())
4191 (declare-function outline-flag-region "outline" (from to flag))
4192 (defun org-flag-subtree (flag)
4193 (save-excursion
4194 (org-back-to-heading t)
4195 (outline-end-of-heading)
4196 (outline-flag-region (point)
4197 (progn (org-end-of-subtree t) (point))
4198 flag)))
4200 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4202 (eval-and-compile
4203 (org-autoload "org-archive"
4204 '(org-add-archive-files)))
4206 ;; Autoload Column View Code
4208 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4209 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4210 (declare-function org-columns-compute "org-colview" (property))
4212 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4213 '(org-columns-number-to-string
4214 org-columns-get-format-and-top-level
4215 org-columns-compute
4216 org-columns-remove-overlays))
4218 ;; Autoload ID code
4220 (declare-function org-id-store-link "org-id")
4221 (declare-function org-id-locations-load "org-id")
4222 (declare-function org-id-locations-save "org-id")
4223 (defvar org-id-track-globally)
4224 (org-autoload "org-id"
4225 '(org-id-new
4226 org-id-copy
4227 org-id-get-with-outline-path-completion
4228 org-id-get-with-outline-drilling))
4230 ;;; Variables for pre-computed regular expressions, all buffer local
4232 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4233 "Matches first line of a hidden block.")
4234 (make-variable-buffer-local 'org-drawer-regexp)
4235 (defvar org-todo-regexp nil
4236 "Matches any of the TODO state keywords.")
4237 (make-variable-buffer-local 'org-todo-regexp)
4238 (defvar org-not-done-regexp nil
4239 "Matches any of the TODO state keywords except the last one.")
4240 (make-variable-buffer-local 'org-not-done-regexp)
4241 (defvar org-not-done-heading-regexp nil
4242 "Matches a TODO headline that is not done.")
4243 (make-variable-buffer-local 'org-not-done-regexp)
4244 (defvar org-todo-line-regexp nil
4245 "Matches a headline and puts TODO state into group 2 if present.")
4246 (make-variable-buffer-local 'org-todo-line-regexp)
4247 (defvar org-complex-heading-regexp nil
4248 "Matches a headline and puts everything into groups:
4249 group 1: the stars
4250 group 2: The todo keyword, maybe
4251 group 3: Priority cookie
4252 group 4: True headline
4253 group 5: Tags")
4254 (make-variable-buffer-local 'org-complex-heading-regexp)
4255 (defvar org-complex-heading-regexp-format nil
4256 "Printf format to make regexp to match an exact headline.
4257 This regexp will match the headline of any node which has the
4258 exact headline text that is put into the format, but may have any
4259 TODO state, priority and tags.")
4260 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4261 (defvar org-todo-line-tags-regexp nil
4262 "Matches a headline and puts TODO state into group 2 if present.
4263 Also put tags into group 4 if tags are present.")
4264 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4265 (defvar org-ds-keyword-length 12
4266 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4267 (make-variable-buffer-local 'org-ds-keyword-length)
4268 (defvar org-deadline-regexp nil
4269 "Matches the DEADLINE keyword.")
4270 (make-variable-buffer-local 'org-deadline-regexp)
4271 (defvar org-deadline-time-regexp nil
4272 "Matches the DEADLINE keyword together with a time stamp.")
4273 (make-variable-buffer-local 'org-deadline-time-regexp)
4274 (defvar org-deadline-line-regexp nil
4275 "Matches the DEADLINE keyword and the rest of the line.")
4276 (make-variable-buffer-local 'org-deadline-line-regexp)
4277 (defvar org-scheduled-regexp nil
4278 "Matches the SCHEDULED keyword.")
4279 (make-variable-buffer-local 'org-scheduled-regexp)
4280 (defvar org-scheduled-time-regexp nil
4281 "Matches the SCHEDULED keyword together with a time stamp.")
4282 (make-variable-buffer-local 'org-scheduled-time-regexp)
4283 (defvar org-closed-time-regexp nil
4284 "Matches the CLOSED keyword together with a time stamp.")
4285 (make-variable-buffer-local 'org-closed-time-regexp)
4287 (defvar org-keyword-time-regexp nil
4288 "Matches any of the 4 keywords, together with the time stamp.")
4289 (make-variable-buffer-local 'org-keyword-time-regexp)
4290 (defvar org-keyword-time-not-clock-regexp nil
4291 "Matches any of the 3 keywords, together with the time stamp.")
4292 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4293 (defvar org-maybe-keyword-time-regexp nil
4294 "Matches a timestamp, possibly preceded by a keyword.")
4295 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4296 (defvar org-all-time-keywords nil
4297 "List of time keywords.")
4298 (make-variable-buffer-local 'org-all-time-keywords)
4300 (defconst org-plain-time-of-day-regexp
4301 (concat
4302 "\\(\\<[012]?[0-9]"
4303 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4304 "\\(--?"
4305 "\\(\\<[012]?[0-9]"
4306 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4307 "\\)?")
4308 "Regular expression to match a plain time or time range.
4309 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4310 groups carry important information:
4311 0 the full match
4312 1 the first time, range or not
4313 8 the second time, if it is a range.")
4315 (defconst org-plain-time-extension-regexp
4316 (concat
4317 "\\(\\<[012]?[0-9]"
4318 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4319 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4320 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4321 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4322 groups carry important information:
4323 0 the full match
4324 7 hours of duration
4325 9 minutes of duration")
4327 (defconst org-stamp-time-of-day-regexp
4328 (concat
4329 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4330 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4331 "\\(--?"
4332 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4333 "Regular expression to match a timestamp time or time range.
4334 After a match, the following groups carry important information:
4335 0 the full match
4336 1 date plus weekday, for back referencing to make sure both times are on the same day
4337 2 the first time, range or not
4338 4 the second time, if it is a range.")
4340 (defconst org-startup-options
4341 '(("fold" org-startup-folded t)
4342 ("overview" org-startup-folded t)
4343 ("nofold" org-startup-folded nil)
4344 ("showall" org-startup-folded nil)
4345 ("showeverything" org-startup-folded showeverything)
4346 ("content" org-startup-folded content)
4347 ("indent" org-startup-indented t)
4348 ("noindent" org-startup-indented nil)
4349 ("hidestars" org-hide-leading-stars t)
4350 ("showstars" org-hide-leading-stars nil)
4351 ("odd" org-odd-levels-only t)
4352 ("oddeven" org-odd-levels-only nil)
4353 ("align" org-startup-align-all-tables t)
4354 ("noalign" org-startup-align-all-tables nil)
4355 ("inlineimages" org-startup-with-inline-images t)
4356 ("noinlineimages" org-startup-with-inline-images nil)
4357 ("customtime" org-display-custom-times t)
4358 ("logdone" org-log-done time)
4359 ("lognotedone" org-log-done note)
4360 ("nologdone" org-log-done nil)
4361 ("lognoteclock-out" org-log-note-clock-out t)
4362 ("nolognoteclock-out" org-log-note-clock-out nil)
4363 ("logrepeat" org-log-repeat state)
4364 ("lognoterepeat" org-log-repeat note)
4365 ("nologrepeat" org-log-repeat nil)
4366 ("logreschedule" org-log-reschedule time)
4367 ("lognotereschedule" org-log-reschedule note)
4368 ("nologreschedule" org-log-reschedule nil)
4369 ("logredeadline" org-log-redeadline time)
4370 ("lognoteredeadline" org-log-redeadline note)
4371 ("nologredeadline" org-log-redeadline nil)
4372 ("logrefile" org-log-refile time)
4373 ("lognoterefile" org-log-refile note)
4374 ("nologrefile" org-log-refile nil)
4375 ("fninline" org-footnote-define-inline t)
4376 ("nofninline" org-footnote-define-inline nil)
4377 ("fnlocal" org-footnote-section nil)
4378 ("fnauto" org-footnote-auto-label t)
4379 ("fnprompt" org-footnote-auto-label nil)
4380 ("fnconfirm" org-footnote-auto-label confirm)
4381 ("fnplain" org-footnote-auto-label plain)
4382 ("fnadjust" org-footnote-auto-adjust t)
4383 ("nofnadjust" org-footnote-auto-adjust nil)
4384 ("constcgs" constants-unit-system cgs)
4385 ("constSI" constants-unit-system SI)
4386 ("noptag" org-tag-persistent-alist nil)
4387 ("hideblocks" org-hide-block-startup t)
4388 ("nohideblocks" org-hide-block-startup nil)
4389 ("beamer" org-startup-with-beamer-mode t)
4390 ("entitiespretty" org-pretty-entities t)
4391 ("entitiesplain" org-pretty-entities nil))
4392 "Variable associated with STARTUP options for org-mode.
4393 Each element is a list of three items: the startup options (as written
4394 in the #+STARTUP line), the corresponding variable, and the value to set
4395 this variable to if the option is found. An optional forth element PUSH
4396 means to push this value onto the list in the variable.")
4398 (defun org-update-property-plist (key val props)
4399 "Update PROPS with KEY and VAL."
4400 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4401 (key (if appending (substring key 0 (- (length key) 1)) key))
4402 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4403 (previous (cdr (assoc key props))))
4404 (if appending
4405 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4406 (cons (cons key val) remainder))))
4408 (defconst org-block-regexp
4409 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4410 "Regular expression for hiding blocks.")
4411 (defconst org-heading-keyword-regexp-format
4412 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4413 "Printf format for a regexp matching an headline with some keyword.
4414 This regexp will match the headline of any node which has the
4415 exact keyword that is put into the format. The keyword isn't in
4416 any group by default, but the stars and the body are.")
4417 (defconst org-heading-keyword-maybe-regexp-format
4418 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4419 "Printf format for a regexp matching an headline, possibly with some keyword.
4420 This regexp can match any headline with the specified keyword, or
4421 without a keyword. The keyword isn't in any group by default,
4422 but the stars and the body are.")
4424 (defun org-set-regexps-and-options ()
4425 "Precompute regular expressions for current buffer."
4426 (when (derived-mode-p 'org-mode)
4427 (org-set-local 'org-todo-kwd-alist nil)
4428 (org-set-local 'org-todo-key-alist nil)
4429 (org-set-local 'org-todo-key-trigger nil)
4430 (org-set-local 'org-todo-keywords-1 nil)
4431 (org-set-local 'org-done-keywords nil)
4432 (org-set-local 'org-todo-heads nil)
4433 (org-set-local 'org-todo-sets nil)
4434 (org-set-local 'org-todo-log-states nil)
4435 (org-set-local 'org-file-properties nil)
4436 (org-set-local 'org-file-tags nil)
4437 (let ((re (org-make-options-regexp
4438 '("CATEGORY" "TODO" "COLUMNS"
4439 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4440 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4441 "OPTIONS")
4442 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4443 (splitre "[ \t]+")
4444 (scripts org-use-sub-superscripts)
4445 kwds kws0 kwsa key log value cat arch tags const links hw dws
4446 tail sep kws1 prio props ftags drawers beamer-p
4447 ext-setup-or-nil setup-contents (start 0))
4448 (save-excursion
4449 (save-restriction
4450 (widen)
4451 (goto-char (point-min))
4452 (while (or (and ext-setup-or-nil
4453 (string-match re ext-setup-or-nil start)
4454 (setq start (match-end 0)))
4455 (and (setq ext-setup-or-nil nil start 0)
4456 (re-search-forward re nil t)))
4457 (setq key (upcase (match-string 1 ext-setup-or-nil))
4458 value (org-match-string-no-properties 2 ext-setup-or-nil))
4459 (if (stringp value) (setq value (org-trim value)))
4460 (cond
4461 ((equal key "CATEGORY")
4462 (setq cat value))
4463 ((member key '("SEQ_TODO" "TODO"))
4464 (push (cons 'sequence (org-split-string value splitre)) kwds))
4465 ((equal key "TYP_TODO")
4466 (push (cons 'type (org-split-string value splitre)) kwds))
4467 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4468 ;; general TODO-like setup
4469 (push (cons (intern (downcase (match-string 1 key)))
4470 (org-split-string value splitre)) kwds))
4471 ((equal key "TAGS")
4472 (setq tags (append tags (if tags '("\\n") nil)
4473 (org-split-string value splitre))))
4474 ((equal key "COLUMNS")
4475 (org-set-local 'org-columns-default-format value))
4476 ((equal key "LINK")
4477 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4478 (push (cons (match-string 1 value)
4479 (org-trim (match-string 2 value)))
4480 links)))
4481 ((equal key "PRIORITIES")
4482 (setq prio (org-split-string value " +")))
4483 ((equal key "PROPERTY")
4484 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4485 (setq props (org-update-property-plist (match-string 1 value)
4486 (match-string 2 value)
4487 props))))
4488 ((equal key "FILETAGS")
4489 (when (string-match "\\S-" value)
4490 (setq ftags
4491 (append
4492 ftags
4493 (apply 'append
4494 (mapcar (lambda (x) (org-split-string x ":"))
4495 (org-split-string value)))))))
4496 ((equal key "DRAWERS")
4497 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4498 ((equal key "CONSTANTS")
4499 (setq const (append const (org-split-string value splitre))))
4500 ((equal key "STARTUP")
4501 (let ((opts (org-split-string value splitre))
4502 l var val)
4503 (while (setq l (pop opts))
4504 (when (setq l (assoc l org-startup-options))
4505 (setq var (nth 1 l) val (nth 2 l))
4506 (if (not (nth 3 l))
4507 (set (make-local-variable var) val)
4508 (if (not (listp (symbol-value var)))
4509 (set (make-local-variable var) nil))
4510 (set (make-local-variable var) (symbol-value var))
4511 (add-to-list var val))))))
4512 ((equal key "ARCHIVE")
4513 (setq arch value)
4514 (remove-text-properties 0 (length arch)
4515 '(face t fontified t) arch))
4516 ((equal key "LATEX_CLASS")
4517 (setq beamer-p (equal value "beamer")))
4518 ((equal key "OPTIONS")
4519 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4520 (setq scripts (read (match-string 2 value)))))
4521 ((equal key "SETUPFILE")
4522 (setq setup-contents (org-file-contents
4523 (expand-file-name
4524 (org-remove-double-quotes value))
4525 'noerror))
4526 (if (not ext-setup-or-nil)
4527 (setq ext-setup-or-nil setup-contents start 0)
4528 (setq ext-setup-or-nil
4529 (concat (substring ext-setup-or-nil 0 start)
4530 "\n" setup-contents "\n"
4531 (substring ext-setup-or-nil start)))))))
4532 ;; search for property blocks
4533 (goto-char (point-min))
4534 (while (re-search-forward org-block-regexp nil t)
4535 (when (equal "PROPERTY" (upcase (match-string 1)))
4536 (setq value (replace-regexp-in-string
4537 "[\n\r]" " " (match-string 4)))
4538 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4539 (setq props (org-update-property-plist (match-string 1 value)
4540 (match-string 2 value)
4541 props)))))))
4542 (org-set-local 'org-use-sub-superscripts scripts)
4543 (when cat
4544 (org-set-local 'org-category (intern cat))
4545 (push (cons "CATEGORY" cat) props))
4546 (when prio
4547 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4548 (setq prio (mapcar 'string-to-char prio))
4549 (org-set-local 'org-highest-priority (nth 0 prio))
4550 (org-set-local 'org-lowest-priority (nth 1 prio))
4551 (org-set-local 'org-default-priority (nth 2 prio)))
4552 (and props (org-set-local 'org-file-properties (nreverse props)))
4553 (and ftags (org-set-local 'org-file-tags
4554 (mapcar 'org-add-prop-inherited ftags)))
4555 (and drawers (org-set-local 'org-drawers drawers))
4556 (and arch (org-set-local 'org-archive-location arch))
4557 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4558 ;; Process the TODO keywords
4559 (unless kwds
4560 ;; Use the global values as if they had been given locally.
4561 (setq kwds (default-value 'org-todo-keywords))
4562 (if (stringp (car kwds))
4563 (setq kwds (list (cons org-todo-interpretation
4564 (default-value 'org-todo-keywords)))))
4565 (setq kwds (reverse kwds)))
4566 (setq kwds (nreverse kwds))
4567 (let (inter kws kw)
4568 (while (setq kws (pop kwds))
4569 (let ((kws (or
4570 (run-hook-with-args-until-success
4571 'org-todo-setup-filter-hook kws)
4572 kws)))
4573 (setq inter (pop kws) sep (member "|" kws)
4574 kws0 (delete "|" (copy-sequence kws))
4575 kwsa nil
4576 kws1 (mapcar
4577 (lambda (x)
4578 ;; 1 2
4579 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4580 (progn
4581 (setq kw (match-string 1 x)
4582 key (and (match-end 2) (match-string 2 x))
4583 log (org-extract-log-state-settings x))
4584 (push (cons kw (and key (string-to-char key))) kwsa)
4585 (and log (push log org-todo-log-states))
4587 (error "Invalid TODO keyword %s" x)))
4588 kws0)
4589 kwsa (if kwsa (append '((:startgroup))
4590 (nreverse kwsa)
4591 '((:endgroup))))
4592 hw (car kws1)
4593 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4594 tail (list inter hw (car dws) (org-last dws))))
4595 (add-to-list 'org-todo-heads hw 'append)
4596 (push kws1 org-todo-sets)
4597 (setq org-done-keywords (append org-done-keywords dws nil))
4598 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4599 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4600 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4601 (setq org-todo-sets (nreverse org-todo-sets)
4602 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4603 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4604 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4605 ;; Process the constants
4606 (when const
4607 (let (e cst)
4608 (while (setq e (pop const))
4609 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4610 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4611 (setq org-table-formula-constants-local cst)))
4613 ;; Process the tags.
4614 (when tags
4615 (let (e tgs)
4616 (while (setq e (pop tags))
4617 (cond
4618 ((equal e "{") (push '(:startgroup) tgs))
4619 ((equal e "}") (push '(:endgroup) tgs))
4620 ((equal e "\\n") (push '(:newline) tgs))
4621 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4622 (push (cons (match-string 1 e)
4623 (string-to-char (match-string 2 e)))
4624 tgs))
4625 (t (push (list e) tgs))))
4626 (org-set-local 'org-tag-alist nil)
4627 (while (setq e (pop tgs))
4628 (or (and (stringp (car e))
4629 (assoc (car e) org-tag-alist))
4630 (push e org-tag-alist)))))
4632 ;; Compute the regular expressions and other local variables.
4633 ;; Using `org-outline-regexp-bol' would complicate them much,
4634 ;; because of the fixed white space at the end of that string.
4635 (if (not org-done-keywords)
4636 (setq org-done-keywords (and org-todo-keywords-1
4637 (list (org-last org-todo-keywords-1)))))
4638 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4639 (length org-scheduled-string)
4640 (length org-clock-string)
4641 (length org-closed-string)))
4642 org-drawer-regexp
4643 (concat "^[ \t]*:\\("
4644 (mapconcat 'regexp-quote org-drawers "\\|")
4645 "\\):[ \t]*$")
4646 org-not-done-keywords
4647 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4648 org-todo-regexp
4649 (concat "\\("
4650 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4651 "\\)")
4652 org-not-done-regexp
4653 (concat "\\("
4654 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4655 "\\)")
4656 org-not-done-heading-regexp
4657 (format org-heading-keyword-regexp-format org-not-done-regexp)
4658 org-todo-line-regexp
4659 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4660 org-complex-heading-regexp
4661 (concat "^\\(\\*+\\)"
4662 "\\(?: +" org-todo-regexp "\\)?"
4663 "\\(?: +\\(\\[#.\\]\\)\\)?"
4664 "\\(?: +\\(.*?\\)\\)??"
4665 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4666 "[ \t]*$")
4667 org-complex-heading-regexp-format
4668 (concat "^\\(\\*+\\)"
4669 "\\(?: +" org-todo-regexp "\\)?"
4670 "\\(?: +\\(\\[#.\\]\\)\\)?"
4671 "\\(?: +"
4672 ;; Stats cookies can be stuck to body.
4673 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4674 "\\(%s\\)"
4675 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4676 "\\)"
4677 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4678 "[ \t]*$")
4679 org-todo-line-tags-regexp
4680 (concat "^\\(\\*+\\)"
4681 "\\(?: +" org-todo-regexp "\\)?"
4682 "\\(?: +\\(.*?\\)\\)??"
4683 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4684 "[ \t]*$")
4685 org-deadline-regexp (concat "\\<" org-deadline-string)
4686 org-deadline-time-regexp
4687 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4688 org-deadline-line-regexp
4689 (concat "\\<\\(" org-deadline-string "\\).*")
4690 org-scheduled-regexp
4691 (concat "\\<" org-scheduled-string)
4692 org-scheduled-time-regexp
4693 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4694 org-closed-time-regexp
4695 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4696 org-keyword-time-regexp
4697 (concat "\\<\\(" org-scheduled-string
4698 "\\|" org-deadline-string
4699 "\\|" org-closed-string
4700 "\\|" org-clock-string "\\)"
4701 " *[[<]\\([^]>]+\\)[]>]")
4702 org-keyword-time-not-clock-regexp
4703 (concat "\\<\\(" org-scheduled-string
4704 "\\|" org-deadline-string
4705 "\\|" org-closed-string
4706 "\\)"
4707 " *[[<]\\([^]>]+\\)[]>]")
4708 org-maybe-keyword-time-regexp
4709 (concat "\\(\\<\\(" org-scheduled-string
4710 "\\|" org-deadline-string
4711 "\\|" org-closed-string
4712 "\\|" org-clock-string "\\)\\)?"
4713 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4714 org-all-time-keywords
4715 (mapcar (lambda (w) (substring w 0 -1))
4716 (list org-scheduled-string org-deadline-string
4717 org-clock-string org-closed-string))
4719 (org-compute-latex-and-specials-regexp)
4720 (org-set-font-lock-defaults))))
4722 (defun org-file-contents (file &optional noerror)
4723 "Return the contents of FILE, as a string."
4724 (if (or (not file)
4725 (not (file-readable-p file)))
4726 (if noerror
4727 (progn
4728 (message "Cannot read file \"%s\"" file)
4729 (ding) (sit-for 2)
4731 (error "Cannot read file \"%s\"" file))
4732 (with-temp-buffer
4733 (insert-file-contents file)
4734 (buffer-string))))
4736 (defun org-extract-log-state-settings (x)
4737 "Extract the log state setting from a TODO keyword string.
4738 This will extract info from a string like \"WAIT(w@/!)\"."
4739 (let (kw key log1 log2)
4740 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4741 (setq kw (match-string 1 x)
4742 key (and (match-end 2) (match-string 2 x))
4743 log1 (and (match-end 3) (match-string 3 x))
4744 log2 (and (match-end 4) (match-string 4 x)))
4745 (and (or log1 log2)
4746 (list kw
4747 (and log1 (if (equal log1 "!") 'time 'note))
4748 (and log2 (if (equal log2 "!") 'time 'note)))))))
4750 (defun org-remove-keyword-keys (list)
4751 "Remove a pair of parenthesis at the end of each string in LIST."
4752 (mapcar (lambda (x)
4753 (if (string-match "(.*)$" x)
4754 (substring x 0 (match-beginning 0))
4756 list))
4758 (defun org-assign-fast-keys (alist)
4759 "Assign fast keys to a keyword-key alist.
4760 Respect keys that are already there."
4761 (let (new e (alt ?0))
4762 (while (setq e (pop alist))
4763 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4764 (cdr e)) ;; Key already assigned.
4765 (push e new)
4766 (let ((clist (string-to-list (downcase (car e))))
4767 (used (append new alist)))
4768 (when (= (car clist) ?@)
4769 (pop clist))
4770 (while (and clist (rassoc (car clist) used))
4771 (pop clist))
4772 (unless clist
4773 (while (rassoc alt used)
4774 (incf alt)))
4775 (push (cons (car e) (or (car clist) alt)) new))))
4776 (nreverse new)))
4778 ;;; Some variables used in various places
4780 (defvar org-window-configuration nil
4781 "Used in various places to store a window configuration.")
4782 (defvar org-selected-window nil
4783 "Used in various places to store a window configuration.")
4784 (defvar org-finish-function nil
4785 "Function to be called when `C-c C-c' is used.
4786 This is for getting out of special buffers like capture.")
4789 ;; FIXME: Occasionally check by commenting these, to make sure
4790 ;; no other functions uses these, forgetting to let-bind them.
4791 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4792 (defvar org-last-state)
4793 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4795 ;; Defined somewhere in this file, but used before definition.
4796 (defvar org-entities) ;; defined in org-entities.el
4797 (defvar org-struct-menu)
4798 (defvar org-org-menu)
4799 (defvar org-tbl-menu)
4801 ;;;; Define the Org-mode
4803 ;; We use a before-change function to check if a table might need
4804 ;; an update.
4805 (defvar org-table-may-need-update t
4806 "Indicates that a table might need an update.
4807 This variable is set by `org-before-change-function'.
4808 `org-table-align' sets it back to nil.")
4809 (defun org-before-change-function (beg end)
4810 "Every change indicates that a table might need an update."
4811 (setq org-table-may-need-update t))
4812 (defvar org-mode-map)
4813 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4814 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4815 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4816 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4817 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4818 (defvar org-table-buffer-is-an nil)
4820 (defvar bidi-paragraph-direction)
4821 (defvar buffer-face-mode-face)
4823 (require 'outline)
4824 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4825 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or upgrade to newer allout, for example by switching to Emacs 22"))
4826 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4828 ;; Other stuff we need.
4829 (require 'time-date)
4830 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4831 (require 'easymenu)
4832 (require 'overlay)
4834 (require 'org-macs)
4835 (require 'org-entities)
4836 ;; (require 'org-compat) moved higher up in the file before it is first used
4837 (require 'org-faces)
4838 (require 'org-list)
4839 (require 'org-pcomplete)
4840 (require 'org-src)
4841 (require 'org-footnote)
4843 ;; babel
4844 (require 'ob)
4845 (require 'ob-table)
4846 (require 'ob-lob)
4847 (require 'ob-ref)
4848 (require 'ob-tangle)
4849 (require 'ob-comint)
4850 (require 'ob-keys)
4852 ;;;###autoload
4853 (define-derived-mode org-mode outline-mode "Org"
4854 "Outline-based notes management and organizer, alias
4855 \"Carsten's outline-mode for keeping track of everything.\"
4857 Org-mode develops organizational tasks around a NOTES file which
4858 contains information about projects as plain text. Org-mode is
4859 implemented on top of outline-mode, which is ideal to keep the content
4860 of large files well structured. It supports ToDo items, deadlines and
4861 time stamps, which magically appear in the diary listing of the Emacs
4862 calendar. Tables are easily created with a built-in table editor.
4863 Plain text URL-like links connect to websites, emails (VM), Usenet
4864 messages (Gnus), BBDB entries, and any files related to the project.
4865 For printing and sharing of notes, an Org-mode file (or a part of it)
4866 can be exported as a structured ASCII or HTML file.
4868 The following commands are available:
4870 \\{org-mode-map}"
4872 ;; Get rid of Outline menus, they are not needed
4873 ;; Need to do this here because define-derived-mode sets up
4874 ;; the keymap so late. Still, it is a waste to call this each time
4875 ;; we switch another buffer into org-mode.
4876 (if (featurep 'xemacs)
4877 (when (boundp 'outline-mode-menu-heading)
4878 ;; Assume this is Greg's port, it uses easymenu
4879 (easy-menu-remove outline-mode-menu-heading)
4880 (easy-menu-remove outline-mode-menu-show)
4881 (easy-menu-remove outline-mode-menu-hide))
4882 (define-key org-mode-map [menu-bar headings] 'undefined)
4883 (define-key org-mode-map [menu-bar hide] 'undefined)
4884 (define-key org-mode-map [menu-bar show] 'undefined))
4886 (org-load-modules-maybe)
4887 (easy-menu-add org-org-menu)
4888 (easy-menu-add org-tbl-menu)
4889 (org-install-agenda-files-menu)
4890 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4891 (add-to-invisibility-spec '(org-cwidth))
4892 (add-to-invisibility-spec '(org-hide-block . t))
4893 (when (featurep 'xemacs)
4894 (org-set-local 'line-move-ignore-invisible t))
4895 (org-set-local 'outline-regexp org-outline-regexp)
4896 (org-set-local 'outline-level 'org-outline-level)
4897 (setq bidi-paragraph-direction 'left-to-right)
4898 (when (and org-ellipsis
4899 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4900 (fboundp 'make-glyph-code))
4901 (unless org-display-table
4902 (setq org-display-table (make-display-table)))
4903 (set-display-table-slot
4904 org-display-table 4
4905 (vconcat (mapcar
4906 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4907 org-ellipsis)))
4908 (if (stringp org-ellipsis) org-ellipsis "..."))))
4909 (setq buffer-display-table org-display-table))
4910 (org-set-regexps-and-options)
4911 (when (and org-tag-faces (not org-tags-special-faces-re))
4912 ;; tag faces set outside customize.... force initialization.
4913 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4914 ;; Calc embedded
4915 (org-set-local 'calc-embedded-open-mode "# ")
4916 (modify-syntax-entry ?@ "w")
4917 (if org-startup-truncated (setq truncate-lines t))
4918 (org-set-local 'font-lock-unfontify-region-function
4919 'org-unfontify-region)
4920 ;; Activate before-change-function
4921 (org-set-local 'org-table-may-need-update t)
4922 (org-add-hook 'before-change-functions 'org-before-change-function nil
4923 'local)
4924 ;; Check for running clock before killing a buffer
4925 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4926 ;; Indentation.
4927 (org-set-local 'indent-line-function 'org-indent-line)
4928 (org-set-local 'indent-region-function 'org-indent-region)
4929 ;; Initialize radio targets.
4930 (org-update-radio-target-regexp)
4931 ;; Filling and auto-filling.
4932 (org-setup-filling)
4933 ;; Comments.
4934 (org-setup-comments-handling)
4935 ;; Beginning/end of defun
4936 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
4937 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
4938 ;; Next error for sparse trees
4939 (org-set-local 'next-error-function 'org-occur-next-match)
4940 ;; Make sure dependence stuff works reliably, even for users who set it
4941 ;; too late :-(
4942 (if org-enforce-todo-dependencies
4943 (add-hook 'org-blocker-hook
4944 'org-block-todo-from-children-or-siblings-or-parent)
4945 (remove-hook 'org-blocker-hook
4946 'org-block-todo-from-children-or-siblings-or-parent))
4947 (if org-enforce-todo-checkbox-dependencies
4948 (add-hook 'org-blocker-hook
4949 'org-block-todo-from-checkboxes)
4950 (remove-hook 'org-blocker-hook
4951 'org-block-todo-from-checkboxes))
4953 ;; Align options lines
4954 (org-set-local
4955 'align-mode-rules-list
4956 '((org-in-buffer-settings
4957 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4958 (modes . '(org-mode)))))
4960 ;; Imenu
4961 (org-set-local 'imenu-create-index-function
4962 'org-imenu-get-tree)
4964 ;; Make isearch reveal context
4965 (if (or (featurep 'xemacs)
4966 (not (boundp 'outline-isearch-open-invisible-function)))
4967 ;; Emacs 21 and XEmacs make use of the hook
4968 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4969 ;; Emacs 22 deals with this through a special variable
4970 (org-set-local 'outline-isearch-open-invisible-function
4971 (lambda (&rest ignore) (org-show-context 'isearch))))
4973 ;; Turn on org-beamer-mode?
4974 (and org-startup-with-beamer-mode (org-beamer-mode))
4976 ;; Setup the pcomplete hooks
4977 (set (make-local-variable 'pcomplete-command-completion-function)
4978 'org-pcomplete-initial)
4979 (set (make-local-variable 'pcomplete-command-name-function)
4980 'org-command-at-point)
4981 (set (make-local-variable 'pcomplete-default-completion-function)
4982 'ignore)
4983 (set (make-local-variable 'pcomplete-parse-arguments-function)
4984 'org-parse-arguments)
4985 (set (make-local-variable 'pcomplete-termination-string) "")
4986 (when (>= emacs-major-version 23)
4987 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
4989 ;; If empty file that did not turn on org-mode automatically, make it to.
4990 (if (and org-insert-mode-line-in-empty-file
4991 (org-called-interactively-p 'any)
4992 (= (point-min) (point-max)))
4993 (insert "# -*- mode: org -*-\n\n"))
4994 (unless org-inhibit-startup
4995 (when org-startup-align-all-tables
4996 (let ((bmp (buffer-modified-p)))
4997 (org-table-map-tables 'org-table-align 'quietly)
4998 (set-buffer-modified-p bmp)))
4999 (when org-startup-with-inline-images
5000 (org-display-inline-images))
5001 (when org-startup-indented
5002 (require 'org-indent)
5003 (org-indent-mode 1))
5004 (unless org-inhibit-startup-visibility-stuff
5005 (org-set-startup-visibility)))
5006 ;; Try to set org-hide correctly
5007 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5009 (when (fboundp 'abbrev-table-put)
5010 (abbrev-table-put org-mode-abbrev-table
5011 :parents (list text-mode-abbrev-table)))
5013 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5016 (defun org-find-invisible-foreground ()
5017 (let ((candidates (remove
5018 "unspecified-bg"
5019 (nconc
5020 (list (face-background 'default)
5021 (face-background 'org-default))
5022 (mapcar
5023 (lambda (alist)
5024 (when (boundp alist)
5025 (cdr (assoc 'background-color (symbol-value alist)))))
5026 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5027 (list (face-foreground 'org-hide))))))
5028 (car (remove nil candidates))))
5030 (defun org-current-time ()
5031 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5032 (if (> (car org-time-stamp-rounding-minutes) 1)
5033 (let ((r (car org-time-stamp-rounding-minutes))
5034 (time (decode-time)))
5035 (apply 'encode-time
5036 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5037 (nthcdr 2 time))))
5038 (current-time)))
5040 (defun org-today ()
5041 "Return today date, considering `org-extend-today-until'."
5042 (time-to-days
5043 (time-subtract (current-time)
5044 (list 0 (* 3600 org-extend-today-until) 0))))
5046 ;;;; Font-Lock stuff, including the activators
5048 (defvar org-mouse-map (make-sparse-keymap))
5049 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5050 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5051 (when org-mouse-1-follows-link
5052 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5053 (when org-tab-follows-link
5054 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5055 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5057 (require 'font-lock)
5059 (defconst org-non-link-chars "]\t\n\r<>")
5060 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5061 "shell" "elisp" "doi" "message"))
5062 (defvar org-link-types-re nil
5063 "Matches a link that has a url-like prefix like \"http:\"")
5064 (defvar org-link-re-with-space nil
5065 "Matches a link with spaces, optional angular brackets around it.")
5066 (defvar org-link-re-with-space2 nil
5067 "Matches a link with spaces, optional angular brackets around it.")
5068 (defvar org-link-re-with-space3 nil
5069 "Matches a link with spaces, only for internal part in bracket links.")
5070 (defvar org-angle-link-re nil
5071 "Matches link with angular brackets, spaces are allowed.")
5072 (defvar org-plain-link-re nil
5073 "Matches plain link, without spaces.")
5074 (defvar org-bracket-link-regexp nil
5075 "Matches a link in double brackets.")
5076 (defvar org-bracket-link-analytic-regexp nil
5077 "Regular expression used to analyze links.
5078 Here is what the match groups contain after a match:
5079 1: http:
5080 2: http
5081 3: path
5082 4: [desc]
5083 5: desc")
5084 (defvar org-bracket-link-analytic-regexp++ nil
5085 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5086 (defvar org-any-link-re nil
5087 "Regular expression matching any link.")
5089 (defcustom org-match-sexp-depth 3
5090 "Number of stacked braces for sub/superscript matching.
5091 This has to be set before loading org.el to be effective."
5092 :group 'org-export-translation ; ??????????????????????????/
5093 :type 'integer)
5095 (defun org-create-multibrace-regexp (left right n)
5096 "Create a regular expression which will match a balanced sexp.
5097 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5098 as single character strings.
5099 The regexp returned will match the entire expression including the
5100 delimiters. It will also define a single group which contains the
5101 match except for the outermost delimiters. The maximum depth of
5102 stacked delimiters is N. Escaping delimiters is not possible."
5103 (let* ((nothing (concat "[^" left right "]*?"))
5104 (or "\\|")
5105 (re nothing)
5106 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5107 (while (> n 1)
5108 (setq n (1- n)
5109 re (concat re or next)
5110 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5111 (concat left "\\(" re "\\)" right)))
5113 (defvar org-match-substring-regexp
5114 (concat
5115 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5116 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5117 "\\|"
5118 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5119 "\\|"
5120 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5121 "The regular expression matching a sub- or superscript.")
5123 (defvar org-match-substring-with-braces-regexp
5124 (concat
5125 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5126 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5127 "\\)")
5128 "The regular expression matching a sub- or superscript, forcing braces.")
5130 (defun org-make-link-regexps ()
5131 "Update the link regular expressions.
5132 This should be called after the variable `org-link-types' has changed."
5133 (setq org-link-types-re
5134 (concat
5135 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5136 org-link-re-with-space
5137 (concat
5138 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5139 "\\([^" org-non-link-chars " ]"
5140 "[^" org-non-link-chars "]*"
5141 "[^" org-non-link-chars " ]\\)>?")
5142 org-link-re-with-space2
5143 (concat
5144 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5145 "\\([^" org-non-link-chars " ]"
5146 "[^\t\n\r]*"
5147 "[^" org-non-link-chars " ]\\)>?")
5148 org-link-re-with-space3
5149 (concat
5150 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5151 "\\([^" org-non-link-chars " ]"
5152 "[^\t\n\r]*\\)")
5153 org-angle-link-re
5154 (concat
5155 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5156 "\\([^" org-non-link-chars " ]"
5157 "[^" org-non-link-chars "]*"
5158 "\\)>")
5159 org-plain-link-re
5160 (concat
5161 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5162 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5163 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5164 org-bracket-link-regexp
5165 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5166 org-bracket-link-analytic-regexp
5167 (concat
5168 "\\[\\["
5169 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5170 "\\([^]]+\\)"
5171 "\\]"
5172 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5173 "\\]")
5174 org-bracket-link-analytic-regexp++
5175 (concat
5176 "\\[\\["
5177 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5178 "\\([^]]+\\)"
5179 "\\]"
5180 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5181 "\\]")
5182 org-any-link-re
5183 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5184 org-angle-link-re "\\)\\|\\("
5185 org-plain-link-re "\\)")))
5187 (org-make-link-regexps)
5189 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5190 "Regular expression for fast time stamp matching.")
5191 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5192 "Regular expression for fast time stamp matching.")
5193 (defconst org-ts-regexp0
5194 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5195 "Regular expression matching time strings for analysis.
5196 This one does not require the space after the date, so it can be used
5197 on a string that terminates immediately after the date.")
5198 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5199 "Regular expression matching time strings for analysis.")
5200 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5201 "Regular expression matching time stamps, with groups.")
5202 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5203 "Regular expression matching time stamps (also [..]), with groups.")
5204 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5205 "Regular expression matching a time stamp range.")
5206 (defconst org-tr-regexp-both
5207 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5208 "Regular expression matching a time stamp range.")
5209 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5210 org-ts-regexp "\\)?")
5211 "Regular expression matching a time stamp or time stamp range.")
5212 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5213 org-ts-regexp-both "\\)?")
5214 "Regular expression matching a time stamp or time stamp range.
5215 The time stamps may be either active or inactive.")
5217 (defvar org-emph-face nil)
5219 (defun org-do-emphasis-faces (limit)
5220 "Run through the buffer and add overlays to emphasized strings."
5221 (let (rtn a)
5222 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5223 (if (not (= (char-after (match-beginning 3))
5224 (char-after (match-beginning 4))))
5225 (progn
5226 (setq rtn t)
5227 (setq a (assoc (match-string 3) org-emphasis-alist))
5228 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5229 'face
5230 (nth 1 a))
5231 (and (nth 4 a)
5232 (org-remove-flyspell-overlays-in
5233 (match-beginning 0) (match-end 0)))
5234 (add-text-properties (match-beginning 2) (match-end 2)
5235 '(font-lock-multiline t org-emphasis t))
5236 (when org-hide-emphasis-markers
5237 (add-text-properties (match-end 4) (match-beginning 5)
5238 '(invisible org-link))
5239 (add-text-properties (match-beginning 3) (match-end 3)
5240 '(invisible org-link)))))
5241 (backward-char 1))
5242 rtn))
5244 (defun org-emphasize (&optional char)
5245 "Insert or change an emphasis, i.e. a font like bold or italic.
5246 If there is an active region, change that region to a new emphasis.
5247 If there is no region, just insert the marker characters and position
5248 the cursor between them.
5249 CHAR should be either the marker character, or the first character of the
5250 HTML tag associated with that emphasis. If CHAR is a space, the means
5251 to remove the emphasis of the selected region.
5252 If char is not given (for example in an interactive call) it
5253 will be prompted for."
5254 (interactive)
5255 (let ((eal org-emphasis-alist) e det
5256 (erc org-emphasis-regexp-components)
5257 (prompt "")
5258 (string "") beg end move tag c s)
5259 (if (org-region-active-p)
5260 (setq beg (region-beginning) end (region-end)
5261 string (buffer-substring beg end))
5262 (setq move t))
5264 (while (setq e (pop eal))
5265 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5266 c (aref tag 0))
5267 (push (cons c (string-to-char (car e))) det)
5268 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5269 (substring tag 1)))))
5270 (setq det (nreverse det))
5271 (unless char
5272 (message "%s" (concat "Emphasis marker or tag:" prompt))
5273 (setq char (read-char-exclusive)))
5274 (setq char (or (cdr (assoc char det)) char))
5275 (if (equal char ?\ )
5276 (setq s "" move nil)
5277 (unless (assoc (char-to-string char) org-emphasis-alist)
5278 (error "No such emphasis marker: \"%c\"" char))
5279 (setq s (char-to-string char)))
5280 (while (and (> (length string) 1)
5281 (equal (substring string 0 1) (substring string -1))
5282 (assoc (substring string 0 1) org-emphasis-alist))
5283 (setq string (substring string 1 -1)))
5284 (setq string (concat s string s))
5285 (if beg (delete-region beg end))
5286 (unless (or (bolp)
5287 (string-match (concat "[" (nth 0 erc) "\n]")
5288 (char-to-string (char-before (point)))))
5289 (insert " "))
5290 (unless (or (eobp)
5291 (string-match (concat "[" (nth 1 erc) "\n]")
5292 (char-to-string (char-after (point)))))
5293 (insert " ") (backward-char 1))
5294 (insert string)
5295 (and move (backward-char 1))))
5297 (defconst org-nonsticky-props
5298 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5300 (defsubst org-rear-nonsticky-at (pos)
5301 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5303 (defun org-activate-plain-links (limit)
5304 "Run through the buffer and add overlays to links."
5305 (catch 'exit
5306 (let (f)
5307 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5308 (not (org-in-src-block-p)))
5309 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5310 (setq f (get-text-property (match-beginning 0) 'face))
5311 (unless (or (org-in-src-block-p)
5312 (eq f 'org-tag)
5313 (and (listp f) (memq 'org-tag f)))
5314 (add-text-properties (match-beginning 0) (match-end 0)
5315 (list 'mouse-face 'highlight
5316 'face 'org-link
5317 'keymap org-mouse-map))
5318 (org-rear-nonsticky-at (match-end 0)))
5319 t))))
5321 (defun org-activate-code (limit)
5322 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5323 (progn
5324 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5325 (remove-text-properties (match-beginning 0) (match-end 0)
5326 '(display t invisible t intangible t))
5327 t)))
5329 (defcustom org-src-fontify-natively nil
5330 "When non-nil, fontify code in code blocks."
5331 :type 'boolean
5332 :version "24.1"
5333 :group 'org-appearance
5334 :group 'org-babel)
5336 (defcustom org-allow-promoting-top-level-subtree nil
5337 "When non-nil, allow promoting a top level subtree.
5338 The leading star of the top level headline will be replaced
5339 by a #."
5340 :type 'boolean
5341 :version "24.1"
5342 :group 'org-appearance)
5344 (defun org-fontify-meta-lines-and-blocks (limit)
5345 (condition-case nil
5346 (org-fontify-meta-lines-and-blocks-1 limit)
5347 (error (message "org-mode fontification error"))))
5349 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5350 "Fontify #+ lines and blocks, in the correct ways."
5351 (let ((case-fold-search t))
5352 (if (re-search-forward
5353 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5354 limit t)
5355 (let ((beg (match-beginning 0))
5356 (block-start (match-end 0))
5357 (block-end nil)
5358 (lang (match-string 7))
5359 (beg1 (line-beginning-position 2))
5360 (dc1 (downcase (match-string 2)))
5361 (dc3 (downcase (match-string 3)))
5362 end end1 quoting block-type ovl)
5363 (cond
5364 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5365 ;; a single line of backend-specific content
5366 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5367 (remove-text-properties (match-beginning 0) (match-end 0)
5368 '(display t invisible t intangible t))
5369 (add-text-properties (match-beginning 1) (match-end 3)
5370 '(font-lock-fontified t face org-meta-line))
5371 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5372 '(font-lock-fontified t face org-block))
5373 ; for backend-specific code
5375 ((and (match-end 4) (equal dc3 "+begin"))
5376 ;; Truly a block
5377 (setq block-type (downcase (match-string 5))
5378 quoting (member block-type org-protecting-blocks))
5379 (when (re-search-forward
5380 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5381 nil t) ;; on purpose, we look further than LIMIT
5382 (setq end (min (point-max) (match-end 0))
5383 end1 (min (point-max) (1- (match-beginning 0))))
5384 (setq block-end (match-beginning 0))
5385 (when quoting
5386 (remove-text-properties beg end
5387 '(display t invisible t intangible t)))
5388 (add-text-properties
5389 beg end
5390 '(font-lock-fontified t font-lock-multiline t))
5391 (add-text-properties beg beg1 '(face org-meta-line))
5392 (add-text-properties end1 (min (point-max) (1+ end))
5393 '(face org-meta-line)) ; for end_src
5394 (cond
5395 ((and lang (not (string= lang "")) org-src-fontify-natively)
5396 (org-src-font-lock-fontify-block lang block-start block-end)
5397 ;; remove old background overlays
5398 (mapc (lambda (ov)
5399 (if (eq (overlay-get ov 'face) 'org-block-background)
5400 (delete-overlay ov)))
5401 (overlays-at (/ (+ beg1 block-end) 2)))
5402 ;; add a background overlay
5403 (setq ovl (make-overlay beg1 block-end))
5404 (overlay-put ovl 'face 'org-block-background)
5405 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5406 (quoting
5407 (add-text-properties beg1 (min (point-max) (1+ end1))
5408 '(face org-block))) ; end of source block
5409 ((not org-fontify-quote-and-verse-blocks))
5410 ((string= block-type "quote")
5411 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5412 ((string= block-type "verse")
5413 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5414 (add-text-properties beg beg1 '(face org-block-begin-line))
5415 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5416 '(face org-block-end-line))
5418 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5419 (add-text-properties
5420 beg (match-end 3)
5421 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5422 '(font-lock-fontified t invisible t)
5423 '(font-lock-fontified t face org-document-info-keyword)))
5424 (add-text-properties
5425 (match-beginning 6) (1+ (match-end 6))
5426 (if (string-equal dc1 "+title:")
5427 '(font-lock-fontified t face org-document-title)
5428 '(font-lock-fontified t face org-document-info))))
5429 ((or (equal dc1 "+results")
5430 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5431 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5432 "+call:" "+header:" "+headers:" "+name:"))
5433 (and (match-end 4) (equal dc3 "+attr")))
5434 (add-text-properties
5435 beg (match-end 0)
5436 '(font-lock-fontified t face org-meta-line))
5438 ((member dc3 '(" " ""))
5439 (add-text-properties
5440 beg (match-end 0)
5441 '(font-lock-fontified t face font-lock-comment-face)))
5442 ((not (member (char-after beg) '(?\ ?\t)))
5443 ;; just any other in-buffer setting, but not indented
5444 (add-text-properties
5445 beg (match-end 0)
5446 '(font-lock-fontified t face org-meta-line))
5448 (t nil))))))
5450 (defun org-activate-angle-links (limit)
5451 "Run through the buffer and add overlays to links."
5452 (if (and (re-search-forward org-angle-link-re limit t)
5453 (not (org-in-src-block-p)))
5454 (progn
5455 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5456 (add-text-properties (match-beginning 0) (match-end 0)
5457 (list 'mouse-face 'highlight
5458 'keymap org-mouse-map))
5459 (org-rear-nonsticky-at (match-end 0))
5460 t)))
5462 (defun org-activate-footnote-links (limit)
5463 "Run through the buffer and add overlays to footnotes."
5464 (let ((fn (org-footnote-next-reference-or-definition limit)))
5465 (when fn
5466 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5467 (org-remove-flyspell-overlays-in beg end)
5468 (add-text-properties beg end
5469 (list 'mouse-face 'highlight
5470 'keymap org-mouse-map
5471 'help-echo
5472 (if (= (point-at-bol) beg)
5473 "Footnote definition"
5474 "Footnote reference")
5475 'font-lock-fontified t
5476 'font-lock-multiline t
5477 'face 'org-footnote))))))
5479 (defun org-activate-bracket-links (limit)
5480 "Run through the buffer and add overlays to bracketed links."
5481 (if (and (re-search-forward org-bracket-link-regexp limit t)
5482 (not (org-in-src-block-p)))
5483 (let* ((help (concat "LINK: "
5484 (org-match-string-no-properties 1)))
5485 ;; FIXME: above we should remove the escapes.
5486 ;; but that requires another match, protecting match data,
5487 ;; a lot of overhead for font-lock.
5488 (ip (org-maybe-intangible
5489 (list 'invisible 'org-link
5490 'keymap org-mouse-map 'mouse-face 'highlight
5491 'font-lock-multiline t 'help-echo help)))
5492 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5493 'font-lock-multiline t 'help-echo help)))
5494 ;; We need to remove the invisible property here. Table narrowing
5495 ;; may have made some of this invisible.
5496 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5497 (remove-text-properties (match-beginning 0) (match-end 0)
5498 '(invisible nil))
5499 (if (match-end 3)
5500 (progn
5501 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5502 (org-rear-nonsticky-at (match-beginning 3))
5503 (add-text-properties (match-beginning 3) (match-end 3) vp)
5504 (org-rear-nonsticky-at (match-end 3))
5505 (add-text-properties (match-end 3) (match-end 0) ip)
5506 (org-rear-nonsticky-at (match-end 0)))
5507 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5508 (org-rear-nonsticky-at (match-beginning 1))
5509 (add-text-properties (match-beginning 1) (match-end 1) vp)
5510 (org-rear-nonsticky-at (match-end 1))
5511 (add-text-properties (match-end 1) (match-end 0) ip)
5512 (org-rear-nonsticky-at (match-end 0)))
5513 t)))
5515 (defun org-activate-dates (limit)
5516 "Run through the buffer and add overlays to dates."
5517 (if (re-search-forward org-tsr-regexp-both limit t)
5518 (progn
5519 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5520 (add-text-properties (match-beginning 0) (match-end 0)
5521 (list 'mouse-face 'highlight
5522 'keymap org-mouse-map))
5523 (org-rear-nonsticky-at (match-end 0))
5524 (when org-display-custom-times
5525 (if (match-end 3)
5526 (org-display-custom-time (match-beginning 3) (match-end 3)))
5527 (org-display-custom-time (match-beginning 1) (match-end 1)))
5528 t)))
5530 (defvar org-target-link-regexp nil
5531 "Regular expression matching radio targets in plain text.")
5532 (make-variable-buffer-local 'org-target-link-regexp)
5533 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5534 "Regular expression matching a link target.")
5535 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5536 "Regular expression matching a radio target.")
5537 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5538 "Regular expression matching any target.")
5540 (defun org-activate-target-links (limit)
5541 "Run through the buffer and add overlays to target matches."
5542 (when org-target-link-regexp
5543 (let ((case-fold-search t))
5544 (if (re-search-forward org-target-link-regexp limit t)
5545 (progn
5546 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5547 (add-text-properties (match-beginning 0) (match-end 0)
5548 (list 'mouse-face 'highlight
5549 'keymap org-mouse-map
5550 'help-echo "Radio target link"
5551 'org-linked-text t))
5552 (org-rear-nonsticky-at (match-end 0))
5553 t)))))
5555 (defun org-update-radio-target-regexp ()
5556 "Find all radio targets in this file and update the regular expression."
5557 (interactive)
5558 (when (memq 'radio org-activate-links)
5559 (setq org-target-link-regexp
5560 (org-make-target-link-regexp (org-all-targets 'radio)))
5561 (org-restart-font-lock)))
5563 (defun org-hide-wide-columns (limit)
5564 (let (s e)
5565 (setq s (text-property-any (point) (or limit (point-max))
5566 'org-cwidth t))
5567 (when s
5568 (setq e (next-single-property-change s 'org-cwidth))
5569 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5570 (goto-char e)
5571 t)))
5573 (defvar org-latex-and-specials-regexp nil
5574 "Regular expression for highlighting export special stuff.")
5575 (defvar org-match-substring-regexp)
5576 (defvar org-match-substring-with-braces-regexp)
5578 ;; This should be with the exporter code, but we also use if for font-locking
5579 (defconst org-export-html-special-string-regexps
5580 '(("\\\\-" . "&shy;")
5581 ("---\\([^-]\\)" . "&mdash;\\1")
5582 ("--\\([^-]\\)" . "&ndash;\\1")
5583 ("\\.\\.\\." . "&hellip;"))
5584 "Regular expressions for special string conversion.")
5587 (defun org-compute-latex-and-specials-regexp ()
5588 "Compute regular expression for stuff treated specially by exporters."
5589 (if (not org-highlight-latex-fragments-and-specials)
5590 (org-set-local 'org-latex-and-specials-regexp nil)
5591 (require 'org-exp)
5592 (let*
5593 ((matchers (plist-get org-format-latex-options :matchers))
5594 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5595 org-latex-regexps)))
5596 (org-export-allow-BIND nil)
5597 (options (org-combine-plists (org-default-export-plist)
5598 (org-infile-export-plist)))
5599 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5600 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5601 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5602 (org-export-html-expand (plist-get options :expand-quoted-html))
5603 (org-export-with-special-strings (plist-get options :special-strings))
5604 (re-sub
5605 (cond
5606 ((equal org-export-with-sub-superscripts '{})
5607 (list org-match-substring-with-braces-regexp))
5608 (org-export-with-sub-superscripts
5609 (list org-match-substring-regexp))))
5610 (re-latex
5611 (if org-export-with-LaTeX-fragments
5612 (mapcar (lambda (x) (nth 1 x)) latexs)))
5613 (re-macros
5614 (if org-export-with-TeX-macros
5615 (list (concat "\\\\"
5616 (regexp-opt
5617 (append
5619 (delq nil
5620 (mapcar 'car-safe
5621 (append org-entities-user
5622 org-entities)))
5623 (if (boundp 'org-latex-entities)
5624 (mapcar (lambda (x)
5625 (or (car-safe x) x))
5626 org-latex-entities)
5627 nil))
5628 'words))) ; FIXME
5630 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5631 (re-special (if org-export-with-special-strings
5632 (mapcar (lambda (x) (car x))
5633 org-export-html-special-string-regexps)))
5634 (re-rest
5635 (delq nil
5636 (list
5637 (if org-export-html-expand "@<[^>\n]+>")
5638 ))))
5639 (org-set-local
5640 'org-latex-and-specials-regexp
5641 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5642 re-rest) "\\|")))))
5644 (defun org-do-latex-and-special-faces (limit)
5645 "Run through the buffer and add overlays to links."
5646 (when org-latex-and-specials-regexp
5647 (let (rtn d)
5648 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5649 limit t))
5650 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5651 'face))
5652 '(org-code org-verbatim underline)))
5653 (progn
5654 (setq rtn t
5655 d (cond ((member (char-after (1+ (match-beginning 0)))
5656 '(?_ ?^)) 1)
5657 (t 0)))
5658 (font-lock-prepend-text-property
5659 (+ d (match-beginning 0)) (match-end 0)
5660 'face 'org-latex-and-export-specials)
5661 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5662 '(font-lock-multiline t)))))
5663 rtn)))
5665 (defun org-restart-font-lock ()
5666 "Restart `font-lock-mode', to force refontification."
5667 (when (and (boundp 'font-lock-mode) font-lock-mode)
5668 (font-lock-mode -1)
5669 (font-lock-mode 1)))
5671 (defun org-all-targets (&optional radio)
5672 "Return a list of all targets in this file.
5673 With optional argument RADIO, only find radio targets."
5674 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5675 rtn)
5676 (save-excursion
5677 (goto-char (point-min))
5678 (while (re-search-forward re nil t)
5679 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5680 rtn)))
5682 (defun org-make-target-link-regexp (targets)
5683 "Make regular expression matching all strings in TARGETS.
5684 The regular expression finds the targets also if there is a line break
5685 between words."
5686 (and targets
5687 (concat
5688 "\\<\\("
5689 (mapconcat
5690 (lambda (x)
5691 (setq x (regexp-quote x))
5692 (while (string-match " +" x)
5693 (setq x (replace-match "\\s-+" t t x)))
5695 targets
5696 "\\|")
5697 "\\)\\>")))
5699 (defun org-activate-tags (limit)
5700 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5701 (progn
5702 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5703 (add-text-properties (match-beginning 1) (match-end 1)
5704 (list 'mouse-face 'highlight
5705 'keymap org-mouse-map))
5706 (org-rear-nonsticky-at (match-end 1))
5707 t)))
5709 (defun org-outline-level ()
5710 "Compute the outline level of the heading at point.
5711 This function assumes that the cursor is at the beginning of a line matched
5712 by `outline-regexp'. Otherwise it returns garbage.
5713 If this is called at a normal headline, the level is the number of stars.
5714 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5715 (save-excursion
5716 (looking-at org-outline-regexp)
5717 (1- (- (match-end 0) (match-beginning 0)))))
5719 (defvar org-font-lock-keywords nil)
5721 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5722 "Regular expression matching a property line.")
5724 (defvar org-font-lock-hook nil
5725 "Functions to be called for special font lock stuff.")
5727 (defvar org-font-lock-set-keywords-hook nil
5728 "Functions that can manipulate `org-font-lock-extra-keywords'.
5729 This is called after `org-font-lock-extra-keywords' is defined, but before
5730 it is installed to be used by font lock. This can be useful if something
5731 needs to be inserted at a specific position in the font-lock sequence.")
5733 (defun org-font-lock-hook (limit)
5734 "Run `org-font-lock-hook' within LIMIT."
5735 (run-hook-with-args 'org-font-lock-hook limit))
5737 (defun org-set-font-lock-defaults ()
5738 "Set font lock defaults for the current buffer."
5739 (let* ((em org-fontify-emphasized-text)
5740 (lk org-activate-links)
5741 (org-font-lock-extra-keywords
5742 (list
5743 ;; Call the hook
5744 '(org-font-lock-hook)
5745 ;; Headlines
5746 `(,(if org-fontify-whole-heading-line
5747 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5748 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5749 (1 (org-get-level-face 1))
5750 (2 (org-get-level-face 2))
5751 (3 (org-get-level-face 3)))
5752 ;; Table lines
5753 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5754 (1 'org-table t))
5755 ;; Table internals
5756 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5757 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5758 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5759 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5760 ;; Drawers
5761 (list org-drawer-regexp '(0 'org-special-keyword t))
5762 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5763 ;; Properties
5764 (list org-property-re
5765 '(1 'org-special-keyword t)
5766 '(3 'org-property-value t))
5767 ;; Links
5768 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5769 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5770 (if (memq 'plain lk) '(org-activate-plain-links))
5771 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5772 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5773 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5774 (if (memq 'footnote lk) '(org-activate-footnote-links))
5775 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5776 '(org-hide-wide-columns (0 nil append))
5777 ;; TODO keyword
5778 (list (format org-heading-keyword-regexp-format
5779 org-todo-regexp)
5780 '(2 (org-get-todo-face 2) t))
5781 ;; DONE
5782 (if org-fontify-done-headline
5783 (list (format org-heading-keyword-regexp-format
5784 (concat
5785 "\\(?:"
5786 (mapconcat 'regexp-quote org-done-keywords "\\|")
5787 "\\)"))
5788 '(2 'org-headline-done t))
5789 nil)
5790 ;; Priorities
5791 '(org-font-lock-add-priority-faces)
5792 ;; Tags
5793 '(org-font-lock-add-tag-faces)
5794 ;; Special keywords
5795 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5796 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5797 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5798 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5799 ;; Emphasis
5800 (if em
5801 (if (featurep 'xemacs)
5802 '(org-do-emphasis-faces (0 nil append))
5803 '(org-do-emphasis-faces)))
5804 ;; Checkboxes
5805 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5806 1 'org-checkbox prepend)
5807 (if (cdr (assq 'checkbox org-list-automatic-rules))
5808 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5809 (0 (org-get-checkbox-statistics-face) t)))
5810 ;; Description list items
5811 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5812 1 'org-list-dt prepend)
5813 ;; ARCHIVEd headings
5814 (list (concat
5815 org-outline-regexp-bol
5816 "\\(.*:" org-archive-tag ":.*\\)")
5817 '(1 'org-archived prepend))
5818 ;; Specials
5819 '(org-do-latex-and-special-faces)
5820 '(org-fontify-entities)
5821 '(org-raise-scripts)
5822 ;; Code
5823 '(org-activate-code (1 'org-code t))
5824 ;; COMMENT
5825 (list (format org-heading-keyword-regexp-format
5826 (concat "\\("
5827 org-comment-string "\\|" org-quote-string
5828 "\\)"))
5829 '(2 'org-special-keyword t))
5830 ;; Blocks and meta lines
5831 '(org-fontify-meta-lines-and-blocks)
5833 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5834 (run-hooks 'org-font-lock-set-keywords-hook)
5835 ;; Now set the full font-lock-keywords
5836 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5837 (org-set-local 'font-lock-defaults
5838 '(org-font-lock-keywords t nil nil backward-paragraph))
5839 (kill-local-variable 'font-lock-keywords) nil))
5841 (defun org-toggle-pretty-entities ()
5842 "Toggle the composition display of entities as UTF8 characters."
5843 (interactive)
5844 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5845 (org-restart-font-lock)
5846 (if org-pretty-entities
5847 (message "Entities are displayed as UTF8 characters")
5848 (save-restriction
5849 (widen)
5850 (org-decompose-region (point-min) (point-max))
5851 (message "Entities are displayed plain"))))
5853 (defvar org-custom-properties-overlays nil
5854 "List of overlays used for custom properties.")
5855 (make-variable-buffer-local 'org-custom-properties-overlays)
5857 (defun org-toggle-custom-properties-visibility ()
5858 "Display or hide properties in `org-custom-properties'."
5859 (interactive)
5860 (if org-custom-properties-overlays
5861 (progn (mapc 'delete-overlay org-custom-properties-overlays)
5862 (setq org-custom-properties-overlays nil))
5863 (unless (not org-custom-properties)
5864 (save-excursion
5865 (save-restriction
5866 (widen)
5867 (goto-char (point-min))
5868 (while (re-search-forward org-property-re nil t)
5869 (mapc (lambda(p)
5870 (when (equal p (substring (match-string 1) 1 -1))
5871 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
5872 (overlay-put o 'invisible t)
5873 (overlay-put o 'org-custom-property t)
5874 (push o org-custom-properties-overlays))))
5875 org-custom-properties)))))))
5877 (defun org-fontify-entities (limit)
5878 "Find an entity to fontify."
5879 (let (ee)
5880 (when org-pretty-entities
5881 (catch 'match
5882 (while (re-search-forward
5883 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
5884 limit t)
5885 (if (and (not (org-in-indented-comment-line))
5886 (setq ee (org-entity-get (match-string 1)))
5887 (= (length (nth 6 ee)) 1))
5888 (let*
5889 ((end (if (equal (match-string 2) "{}")
5890 (match-end 2)
5891 (match-end 1))))
5892 (add-text-properties
5893 (match-beginning 0) end
5894 (list 'font-lock-fontified t))
5895 (compose-region (match-beginning 0) end
5896 (nth 6 ee) nil)
5897 (backward-char 1)
5898 (throw 'match t))))
5899 nil))))
5901 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5902 "Fontify string S like in Org-mode."
5903 (with-temp-buffer
5904 (insert s)
5905 (let ((org-odd-levels-only odd-levels))
5906 (org-mode)
5907 (font-lock-fontify-buffer)
5908 (buffer-string))))
5910 (defvar org-m nil)
5911 (defvar org-l nil)
5912 (defvar org-f nil)
5913 (defun org-get-level-face (n)
5914 "Get the right face for match N in font-lock matching of headlines."
5915 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5916 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5917 (if org-cycle-level-faces
5918 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5919 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5920 (cond
5921 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5922 ((eq n 2) org-f)
5923 (t (if org-level-color-stars-only nil org-f))))
5926 (defun org-get-todo-face (kwd)
5927 "Get the right face for a TODO keyword KWD.
5928 If KWD is a number, get the corresponding match group."
5929 (if (numberp kwd) (setq kwd (match-string kwd)))
5930 (or (org-face-from-face-or-color
5931 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5932 (and (member kwd org-done-keywords) 'org-done)
5933 'org-todo))
5935 (defun org-face-from-face-or-color (context inherit face-or-color)
5936 "Create a face list that inherits INHERIT, but sets the foreground color.
5937 When FACE-OR-COLOR is not a string, just return it."
5938 (if (stringp face-or-color)
5939 (list :inherit inherit
5940 (cdr (assoc context org-faces-easy-properties))
5941 face-or-color)
5942 face-or-color))
5944 (defun org-font-lock-add-tag-faces (limit)
5945 "Add the special tag faces."
5946 (when (and org-tag-faces org-tags-special-faces-re)
5947 (while (re-search-forward org-tags-special-faces-re limit t)
5948 (add-text-properties (match-beginning 1) (match-end 1)
5949 (list 'face (org-get-tag-face 1)
5950 'font-lock-fontified t))
5951 (backward-char 1))))
5953 (defun org-font-lock-add-priority-faces (limit)
5954 "Add the special priority faces."
5955 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5956 (when (save-match-data (org-at-heading-p))
5957 (add-text-properties
5958 (match-beginning 0) (match-end 0)
5959 (list 'face (or (org-face-from-face-or-color
5960 'priority 'org-special-keyword
5961 (cdr (assoc (char-after (match-beginning 1))
5962 org-priority-faces)))
5963 'org-special-keyword)
5964 'font-lock-fontified t)))))
5966 (defun org-get-tag-face (kwd)
5967 "Get the right face for a TODO keyword KWD.
5968 If KWD is a number, get the corresponding match group."
5969 (if (numberp kwd) (setq kwd (match-string kwd)))
5970 (or (org-face-from-face-or-color
5971 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5972 'org-tag))
5974 (defun org-unfontify-region (beg end &optional maybe_loudly)
5975 "Remove fontification and activation overlays from links."
5976 (font-lock-default-unfontify-region beg end)
5977 (let* ((buffer-undo-list t)
5978 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5979 (inhibit-modification-hooks t)
5980 deactivate-mark buffer-file-name buffer-file-truename)
5981 (org-decompose-region beg end)
5982 (remove-text-properties beg end
5983 '(mouse-face t keymap t org-linked-text t
5984 invisible t intangible t
5985 org-no-flyspell t org-emphasis t))
5986 (org-remove-font-lock-display-properties beg end)))
5988 (defconst org-script-display '(((raise -0.3) (height 0.7))
5989 ((raise 0.3) (height 0.7))
5990 ((raise -0.5))
5991 ((raise 0.5)))
5992 "Display properties for showing superscripts and subscripts.")
5994 (defun org-remove-font-lock-display-properties (beg end)
5995 "Remove specific display properties that have been added by font lock.
5996 The will remove the raise properties that are used to show superscripts
5997 and subscripts."
5998 (let (next prop)
5999 (while (< beg end)
6000 (setq next (next-single-property-change beg 'display nil end)
6001 prop (get-text-property beg 'display))
6002 (if (member prop org-script-display)
6003 (put-text-property beg next 'display nil))
6004 (setq beg next))))
6006 (defun org-raise-scripts (limit)
6007 "Add raise properties to sub/superscripts."
6008 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6009 (if (re-search-forward
6010 (if (eq org-use-sub-superscripts t)
6011 org-match-substring-regexp
6012 org-match-substring-with-braces-regexp)
6013 limit t)
6014 (let* ((pos (point)) table-p comment-p
6015 (mpos (match-beginning 3))
6016 (emph-p (get-text-property mpos 'org-emphasis))
6017 (link-p (get-text-property mpos 'mouse-face))
6018 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6019 (goto-char (point-at-bol))
6020 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6021 comment-p (org-looking-at-p "[ \t]*#"))
6022 (goto-char pos)
6023 ;; FIXME: Should we go back one character here, for a_b^c
6024 ;; (goto-char (1- pos)) ;????????????????????
6025 (if (or comment-p emph-p link-p keyw-p)
6027 (put-text-property (match-beginning 3) (match-end 0)
6028 'display
6029 (if (equal (char-after (match-beginning 2)) ?^)
6030 (nth (if table-p 3 1) org-script-display)
6031 (nth (if table-p 2 0) org-script-display)))
6032 (add-text-properties (match-beginning 2) (match-end 2)
6033 (list 'invisible t
6034 'org-dwidth t 'org-dwidth-n 1))
6035 (if (and (eq (char-after (match-beginning 3)) ?{)
6036 (eq (char-before (match-end 3)) ?}))
6037 (progn
6038 (add-text-properties
6039 (match-beginning 3) (1+ (match-beginning 3))
6040 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6041 (add-text-properties
6042 (1- (match-end 3)) (match-end 3)
6043 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6044 t)))))
6046 ;;;; Visibility cycling, including org-goto and indirect buffer
6048 ;;; Cycling
6050 (defvar org-cycle-global-status nil)
6051 (make-variable-buffer-local 'org-cycle-global-status)
6052 (defvar org-cycle-subtree-status nil)
6053 (make-variable-buffer-local 'org-cycle-subtree-status)
6055 (defvar org-inlinetask-min-level)
6057 ;;;###autoload
6058 (defun org-cycle (&optional arg)
6059 "TAB-action and visibility cycling for Org-mode.
6061 This is the command invoked in Org-mode by the TAB key. Its main purpose
6062 is outline visibility cycling, but it also invokes other actions
6063 in special contexts.
6065 - When this function is called with a prefix argument, rotate the entire
6066 buffer through 3 states (global cycling)
6067 1. OVERVIEW: Show only top-level headlines.
6068 2. CONTENTS: Show all headlines of all levels, but no body text.
6069 3. SHOW ALL: Show everything.
6070 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6071 determined by the variable `org-startup-folded', and by any VISIBILITY
6072 properties in the buffer.
6073 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6074 including any drawers.
6076 - When inside a table, re-align the table and move to the next field.
6078 - When point is at the beginning of a headline, rotate the subtree started
6079 by this line through 3 different states (local cycling)
6080 1. FOLDED: Only the main headline is shown.
6081 2. CHILDREN: The main headline and the direct children are shown.
6082 From this state, you can move to one of the children
6083 and zoom in further.
6084 3. SUBTREE: Show the entire subtree, including body text.
6085 If there is no subtree, switch directly from CHILDREN to FOLDED.
6087 - When point is at the beginning of an empty headline and the variable
6088 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6089 of the headline by demoting and promoting it to likely levels. This
6090 speeds up creation document structure by pressing TAB once or several
6091 times right after creating a new headline.
6093 - When there is a numeric prefix, go up to a heading with level ARG, do
6094 a `show-subtree' and return to the previous cursor position. If ARG
6095 is negative, go up that many levels.
6097 - When point is not at the beginning of a headline, execute the global
6098 binding for TAB, which is re-indenting the line. See the option
6099 `org-cycle-emulate-tab' for details.
6101 - Special case: if point is at the beginning of the buffer and there is
6102 no headline in line 1, this function will act as if called with prefix arg
6103 (C-u TAB, same as S-TAB) also when called without prefix arg.
6104 But only if also the variable `org-cycle-global-at-bob' is t."
6105 (interactive "P")
6106 (org-load-modules-maybe)
6107 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6108 (and org-cycle-level-after-item/entry-creation
6109 (or (org-cycle-level)
6110 (org-cycle-item-indentation))))
6111 (let* ((limit-level
6112 (or org-cycle-max-level
6113 (and (boundp 'org-inlinetask-min-level)
6114 org-inlinetask-min-level
6115 (1- org-inlinetask-min-level))))
6116 (nstars (and limit-level
6117 (if org-odd-levels-only
6118 (and limit-level (1- (* limit-level 2)))
6119 limit-level)))
6120 (org-outline-regexp
6121 (if (not (derived-mode-p 'org-mode))
6122 outline-regexp
6123 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6124 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6125 (not (looking-at org-outline-regexp))))
6126 (org-cycle-hook
6127 (if bob-special
6128 (delq 'org-optimize-window-after-visibility-change
6129 (copy-sequence org-cycle-hook))
6130 org-cycle-hook))
6131 (pos (point)))
6133 (if (or bob-special (equal arg '(4)))
6134 ;; special case: use global cycling
6135 (setq arg t))
6137 (cond
6139 ((equal arg '(16))
6140 (setq last-command 'dummy)
6141 (org-set-startup-visibility)
6142 (message "Startup visibility, plus VISIBILITY properties"))
6144 ((equal arg '(64))
6145 (show-all)
6146 (message "Entire buffer visible, including drawers"))
6148 ;; Table: enter it or move to the next field.
6149 ((org-at-table-p 'any)
6150 (if (org-at-table.el-p)
6151 (message "Use C-c ' to edit table.el tables")
6152 (if arg (org-table-edit-field t)
6153 (org-table-justify-field-maybe)
6154 (call-interactively 'org-table-next-field))))
6156 ((run-hook-with-args-until-success
6157 'org-tab-after-check-for-table-hook))
6159 ;; Global cycling: delegate to `org-cycle-internal-global'.
6160 ((eq arg t) (org-cycle-internal-global))
6162 ;; Drawers: delegate to `org-flag-drawer'.
6163 ((and org-drawers org-drawer-regexp
6164 (save-excursion
6165 (beginning-of-line 1)
6166 (looking-at org-drawer-regexp)))
6167 (org-flag-drawer ; toggle block visibility
6168 (not (get-char-property (match-end 0) 'invisible))))
6170 ;; Show-subtree, ARG levels up from here.
6171 ((integerp arg)
6172 (save-excursion
6173 (org-back-to-heading)
6174 (outline-up-heading (if (< arg 0) (- arg)
6175 (- (funcall outline-level) arg)))
6176 (org-show-subtree)))
6178 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6179 ((and (featurep 'org-inlinetask)
6180 (org-inlinetask-at-task-p)
6181 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6182 (org-inlinetask-toggle-visibility))
6184 ((org-try-cdlatex-tab))
6186 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6187 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6188 (save-excursion (beginning-of-line 1)
6189 (looking-at org-outline-regexp)))
6190 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6191 (org-cycle-internal-local))
6193 ;; From there: TAB emulation and template completion.
6194 (buffer-read-only (org-back-to-heading))
6196 ((run-hook-with-args-until-success
6197 'org-tab-after-check-for-cycling-hook))
6199 ((org-try-structure-completion))
6201 ((run-hook-with-args-until-success
6202 'org-tab-before-tab-emulation-hook))
6204 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6205 (or (not (bolp))
6206 (not (looking-at org-outline-regexp))))
6207 (call-interactively (global-key-binding "\t")))
6209 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6210 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6211 (or (and (eq org-cycle-emulate-tab 'white)
6212 (= (match-end 0) (point-at-eol)))
6213 (and (eq org-cycle-emulate-tab 'whitestart)
6214 (>= (match-end 0) pos))))
6216 (eq org-cycle-emulate-tab t))
6217 (call-interactively (global-key-binding "\t")))
6219 (t (save-excursion
6220 (org-back-to-heading)
6221 (org-cycle)))))))
6223 (defun org-cycle-internal-global ()
6224 "Do the global cycling action."
6225 ;; Hack to avoid display of messages for .org attachments in Gnus
6226 (let ((ga (string-match "\\*fontification" (buffer-name))))
6227 (cond
6228 ((and (eq last-command this-command)
6229 (eq org-cycle-global-status 'overview))
6230 ;; We just created the overview - now do table of contents
6231 ;; This can be slow in very large buffers, so indicate action
6232 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6233 (unless ga (message "CONTENTS..."))
6234 (org-content)
6235 (unless ga (message "CONTENTS...done"))
6236 (setq org-cycle-global-status 'contents)
6237 (run-hook-with-args 'org-cycle-hook 'contents))
6239 ((and (eq last-command this-command)
6240 (eq org-cycle-global-status 'contents))
6241 ;; We just showed the table of contents - now show everything
6242 (run-hook-with-args 'org-pre-cycle-hook 'all)
6243 (show-all)
6244 (unless ga (message "SHOW ALL"))
6245 (setq org-cycle-global-status 'all)
6246 (run-hook-with-args 'org-cycle-hook 'all))
6249 ;; Default action: go to overview
6250 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6251 (org-overview)
6252 (unless ga (message "OVERVIEW"))
6253 (setq org-cycle-global-status 'overview)
6254 (run-hook-with-args 'org-cycle-hook 'overview)))))
6256 (defun org-cycle-internal-local ()
6257 "Do the local cycling action."
6258 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6259 ;; First, determine end of headline (EOH), end of subtree or item
6260 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6261 (save-excursion
6262 (if (org-at-item-p)
6263 (progn
6264 (beginning-of-line)
6265 (setq struct (org-list-struct))
6266 (setq eoh (point-at-eol))
6267 (setq eos (org-list-get-item-end-before-blank (point) struct))
6268 (setq has-children (org-list-has-child-p (point) struct)))
6269 (org-back-to-heading)
6270 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6271 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6272 (setq has-children
6273 (or (save-excursion
6274 (let ((level (funcall outline-level)))
6275 (outline-next-heading)
6276 (and (org-at-heading-p t)
6277 (> (funcall outline-level) level))))
6278 (save-excursion
6279 (org-list-search-forward (org-item-beginning-re) eos t)))))
6280 ;; Determine end invisible part of buffer (EOL)
6281 (beginning-of-line 2)
6282 ;; XEmacs doesn't have `next-single-char-property-change'
6283 (if (featurep 'xemacs)
6284 (while (and (not (eobp)) ;; this is like `next-line'
6285 (get-char-property (1- (point)) 'invisible))
6286 (beginning-of-line 2))
6287 (while (and (not (eobp)) ;; this is like `next-line'
6288 (get-char-property (1- (point)) 'invisible))
6289 (goto-char (next-single-char-property-change (point) 'invisible))
6290 (and (eolp) (beginning-of-line 2))))
6291 (setq eol (point)))
6292 ;; Find out what to do next and set `this-command'
6293 (cond
6294 ((= eos eoh)
6295 ;; Nothing is hidden behind this heading
6296 (unless (org-before-first-heading-p)
6297 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6298 (message "EMPTY ENTRY")
6299 (setq org-cycle-subtree-status nil)
6300 (save-excursion
6301 (goto-char eos)
6302 (outline-next-heading)
6303 (if (outline-invisible-p) (org-flag-heading nil))))
6304 ((and (or (>= eol eos)
6305 (not (string-match "\\S-" (buffer-substring eol eos))))
6306 (or has-children
6307 (not (setq children-skipped
6308 org-cycle-skip-children-state-if-no-children))))
6309 ;; Entire subtree is hidden in one line: children view
6310 (unless (org-before-first-heading-p)
6311 (run-hook-with-args 'org-pre-cycle-hook 'children))
6312 (if (org-at-item-p)
6313 (org-list-set-item-visibility (point-at-bol) struct 'children)
6314 (org-show-entry)
6315 (org-with-limited-levels (show-children))
6316 ;; FIXME: This slows down the func way too much.
6317 ;; How keep drawers hidden in subtree anyway?
6318 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6319 ;; (org-cycle-hide-drawers 'subtree))
6321 ;; Fold every list in subtree to top-level items.
6322 (when (eq org-cycle-include-plain-lists 'integrate)
6323 (save-excursion
6324 (org-back-to-heading)
6325 (while (org-list-search-forward (org-item-beginning-re) eos t)
6326 (beginning-of-line 1)
6327 (let* ((struct (org-list-struct))
6328 (prevs (org-list-prevs-alist struct))
6329 (end (org-list-get-bottom-point struct)))
6330 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6331 (org-list-get-all-items (point) struct prevs))
6332 (goto-char end))))))
6333 (message "CHILDREN")
6334 (save-excursion
6335 (goto-char eos)
6336 (outline-next-heading)
6337 (if (outline-invisible-p) (org-flag-heading nil)))
6338 (setq org-cycle-subtree-status 'children)
6339 (unless (org-before-first-heading-p)
6340 (run-hook-with-args 'org-cycle-hook 'children)))
6341 ((or children-skipped
6342 (and (eq last-command this-command)
6343 (eq org-cycle-subtree-status 'children)))
6344 ;; We just showed the children, or no children are there,
6345 ;; now show everything.
6346 (unless (org-before-first-heading-p)
6347 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6348 (outline-flag-region eoh eos nil)
6349 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6350 (setq org-cycle-subtree-status 'subtree)
6351 (unless (org-before-first-heading-p)
6352 (run-hook-with-args 'org-cycle-hook 'subtree)))
6354 ;; Default action: hide the subtree.
6355 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6356 (outline-flag-region eoh eos t)
6357 (message "FOLDED")
6358 (setq org-cycle-subtree-status 'folded)
6359 (unless (org-before-first-heading-p)
6360 (run-hook-with-args 'org-cycle-hook 'folded))))))
6362 ;;;###autoload
6363 (defun org-global-cycle (&optional arg)
6364 "Cycle the global visibility. For details see `org-cycle'.
6365 With \\[universal-argument] prefix arg, switch to startup visibility.
6366 With a numeric prefix, show all headlines up to that level."
6367 (interactive "P")
6368 (let ((org-cycle-include-plain-lists
6369 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6370 (cond
6371 ((integerp arg)
6372 (show-all)
6373 (hide-sublevels arg)
6374 (setq org-cycle-global-status 'contents))
6375 ((equal arg '(4))
6376 (org-set-startup-visibility)
6377 (message "Startup visibility, plus VISIBILITY properties."))
6379 (org-cycle '(4))))))
6381 (defun org-set-startup-visibility ()
6382 "Set the visibility required by startup options and properties."
6383 (cond
6384 ((eq org-startup-folded t)
6385 (org-cycle '(4)))
6386 ((eq org-startup-folded 'content)
6387 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6388 (org-cycle '(4)) (org-cycle '(4)))))
6389 (unless (eq org-startup-folded 'showeverything)
6390 (if org-hide-block-startup (org-hide-block-all))
6391 (org-set-visibility-according-to-property 'no-cleanup)
6392 (org-cycle-hide-archived-subtrees 'all)
6393 (org-cycle-hide-drawers 'all)
6394 (org-cycle-show-empty-lines t)))
6396 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6397 "Switch subtree visibilities according to :VISIBILITY: property."
6398 (interactive)
6399 (let (org-show-entry-below state)
6400 (save-excursion
6401 (goto-char (point-min))
6402 (while (re-search-forward
6403 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6404 nil t)
6405 (setq state (match-string 1))
6406 (save-excursion
6407 (org-back-to-heading t)
6408 (hide-subtree)
6409 (org-reveal)
6410 (cond
6411 ((equal state '("fold" "folded"))
6412 (hide-subtree))
6413 ((equal state "children")
6414 (org-show-hidden-entry)
6415 (show-children))
6416 ((equal state "content")
6417 (save-excursion
6418 (save-restriction
6419 (org-narrow-to-subtree)
6420 (org-content))))
6421 ((member state '("all" "showall"))
6422 (show-subtree)))))
6423 (unless no-cleanup
6424 (org-cycle-hide-archived-subtrees 'all)
6425 (org-cycle-hide-drawers 'all)
6426 (org-cycle-show-empty-lines 'all)))))
6428 ;; This function uses outline-regexp instead of the more fundamental
6429 ;; org-outline-regexp so that org-cycle-global works outside of Org
6430 ;; buffers, where outline-regexp is needed.
6431 (defun org-overview ()
6432 "Switch to overview mode, showing only top-level headlines.
6433 Really, this shows all headlines with level equal or greater than the level
6434 of the first headline in the buffer. This is important, because if the
6435 first headline is not level one, then (hide-sublevels 1) gives confusing
6436 results."
6437 (interactive)
6438 (let ((level (save-excursion
6439 (goto-char (point-min))
6440 (if (re-search-forward (concat "^" outline-regexp) nil t)
6441 (progn
6442 (goto-char (match-beginning 0))
6443 (funcall outline-level))))))
6444 (and level (hide-sublevels level))))
6446 (defun org-content (&optional arg)
6447 "Show all headlines in the buffer, like a table of contents.
6448 With numerical argument N, show content up to level N."
6449 (interactive "P")
6450 (save-excursion
6451 ;; Visit all headings and show their offspring
6452 (and (integerp arg) (org-overview))
6453 (goto-char (point-max))
6454 (catch 'exit
6455 (while (and (progn (condition-case nil
6456 (outline-previous-visible-heading 1)
6457 (error (goto-char (point-min))))
6459 (looking-at org-outline-regexp))
6460 (if (integerp arg)
6461 (show-children (1- arg))
6462 (show-branches))
6463 (if (bobp) (throw 'exit nil))))))
6466 (defun org-optimize-window-after-visibility-change (state)
6467 "Adjust the window after a change in outline visibility.
6468 This function is the default value of the hook `org-cycle-hook'."
6469 (when (get-buffer-window (current-buffer))
6470 (cond
6471 ((eq state 'content) nil)
6472 ((eq state 'all) nil)
6473 ((eq state 'folded) nil)
6474 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6475 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6477 (defun org-remove-empty-overlays-at (pos)
6478 "Remove outline overlays that do not contain non-white stuff."
6479 (mapc
6480 (lambda (o)
6481 (and (eq 'outline (overlay-get o 'invisible))
6482 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6483 (overlay-end o))))
6484 (delete-overlay o)))
6485 (overlays-at pos)))
6487 (defun org-clean-visibility-after-subtree-move ()
6488 "Fix visibility issues after moving a subtree."
6489 ;; First, find a reasonable region to look at:
6490 ;; Start two siblings above, end three below
6491 (let* ((beg (save-excursion
6492 (and (org-get-last-sibling)
6493 (org-get-last-sibling))
6494 (point)))
6495 (end (save-excursion
6496 (and (org-get-next-sibling)
6497 (org-get-next-sibling)
6498 (org-get-next-sibling))
6499 (if (org-at-heading-p)
6500 (point-at-eol)
6501 (point))))
6502 (level (looking-at "\\*+"))
6503 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6504 (save-excursion
6505 (save-restriction
6506 (narrow-to-region beg end)
6507 (when re
6508 ;; Properly fold already folded siblings
6509 (goto-char (point-min))
6510 (while (re-search-forward re nil t)
6511 (if (and (not (outline-invisible-p))
6512 (save-excursion
6513 (goto-char (point-at-eol)) (outline-invisible-p)))
6514 (hide-entry))))
6515 (org-cycle-show-empty-lines 'overview)
6516 (org-cycle-hide-drawers 'overview)))))
6518 (defun org-cycle-show-empty-lines (state)
6519 "Show empty lines above all visible headlines.
6520 The region to be covered depends on STATE when called through
6521 `org-cycle-hook'. Lisp program can use t for STATE to get the
6522 entire buffer covered. Note that an empty line is only shown if there
6523 are at least `org-cycle-separator-lines' empty lines before the headline."
6524 (when (not (= org-cycle-separator-lines 0))
6525 (save-excursion
6526 (let* ((n (abs org-cycle-separator-lines))
6527 (re (cond
6528 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6529 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6530 (t (let ((ns (number-to-string (- n 2))))
6531 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6532 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6533 beg end b e)
6534 (cond
6535 ((memq state '(overview contents t))
6536 (setq beg (point-min) end (point-max)))
6537 ((memq state '(children folded))
6538 (setq beg (point) end (progn (org-end-of-subtree t t)
6539 (beginning-of-line 2)
6540 (point)))))
6541 (when beg
6542 (goto-char beg)
6543 (while (re-search-forward re end t)
6544 (unless (get-char-property (match-end 1) 'invisible)
6545 (setq e (match-end 1))
6546 (if (< org-cycle-separator-lines 0)
6547 (setq b (save-excursion
6548 (goto-char (match-beginning 0))
6549 (org-back-over-empty-lines)
6550 (if (save-excursion
6551 (goto-char (max (point-min) (1- (point))))
6552 (org-at-heading-p))
6553 (1- (point))
6554 (point))))
6555 (setq b (match-beginning 1)))
6556 (outline-flag-region b e nil)))))))
6557 ;; Never hide empty lines at the end of the file.
6558 (save-excursion
6559 (goto-char (point-max))
6560 (outline-previous-heading)
6561 (outline-end-of-heading)
6562 (if (and (looking-at "[ \t\n]+")
6563 (= (match-end 0) (point-max)))
6564 (outline-flag-region (point) (match-end 0) nil))))
6566 (defun org-show-empty-lines-in-parent ()
6567 "Move to the parent and re-show empty lines before visible headlines."
6568 (save-excursion
6569 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6570 (org-cycle-show-empty-lines context))))
6572 (defun org-files-list ()
6573 "Return `org-agenda-files' list, plus all open org-mode files.
6574 This is useful for operations that need to scan all of a user's
6575 open and agenda-wise Org files."
6576 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6577 (dolist (buf (buffer-list))
6578 (with-current-buffer buf
6579 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6580 (let ((file (expand-file-name (buffer-file-name))))
6581 (unless (member file files)
6582 (push file files))))))
6583 files))
6585 (defsubst org-entry-beginning-position ()
6586 "Return the beginning position of the current entry."
6587 (save-excursion (outline-back-to-heading t) (point)))
6589 (defsubst org-entry-end-position ()
6590 "Return the end position of the current entry."
6591 (save-excursion (outline-next-heading) (point)))
6593 (defun org-cycle-hide-drawers (state)
6594 "Re-hide all drawers after a visibility state change."
6595 (when (and (derived-mode-p 'org-mode)
6596 (not (memq state '(overview folded contents))))
6597 (save-excursion
6598 (let* ((globalp (memq state '(contents all)))
6599 (beg (if globalp (point-min) (point)))
6600 (end (if globalp (point-max)
6601 (if (eq state 'children)
6602 (save-excursion (outline-next-heading) (point))
6603 (org-end-of-subtree t)))))
6604 (goto-char beg)
6605 (while (re-search-forward org-drawer-regexp end t)
6606 (org-flag-drawer t))))))
6608 (defun org-flag-drawer (flag)
6609 "When FLAG is non-nil, hide the drawer we are within.
6610 Otherwise make it visible."
6611 (save-excursion
6612 (beginning-of-line 1)
6613 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6614 (let ((b (match-end 0)))
6615 (if (re-search-forward
6616 "^[ \t]*:END:"
6617 (save-excursion (outline-next-heading) (point)) t)
6618 (outline-flag-region b (point-at-eol) flag)
6619 (error ":END: line missing at position %s" b))))))
6621 (defun org-subtree-end-visible-p ()
6622 "Is the end of the current subtree visible?"
6623 (pos-visible-in-window-p
6624 (save-excursion (org-end-of-subtree t) (point))))
6626 (defun org-first-headline-recenter (&optional N)
6627 "Move cursor to the first headline and recenter the headline.
6628 Optional argument N means put the headline into the Nth line of the window."
6629 (goto-char (point-min))
6630 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6631 (beginning-of-line)
6632 (recenter (prefix-numeric-value N))))
6634 ;;; Saving and restoring visibility
6636 (defun org-outline-overlay-data (&optional use-markers)
6637 "Return a list of the locations of all outline overlays.
6638 These are overlays with the `invisible' property value `outline'.
6639 The return value is a list of cons cells, with start and stop
6640 positions for each overlay.
6641 If USE-MARKERS is set, return the positions as markers."
6642 (let (beg end)
6643 (save-excursion
6644 (save-restriction
6645 (widen)
6646 (delq nil
6647 (mapcar (lambda (o)
6648 (when (eq (overlay-get o 'invisible) 'outline)
6649 (setq beg (overlay-start o)
6650 end (overlay-end o))
6651 (and beg end (> end beg)
6652 (if use-markers
6653 (cons (move-marker (make-marker) beg)
6654 (move-marker (make-marker) end))
6655 (cons beg end)))))
6656 (overlays-in (point-min) (point-max))))))))
6658 (defun org-set-outline-overlay-data (data)
6659 "Create visibility overlays for all positions in DATA.
6660 DATA should have been made by `org-outline-overlay-data'."
6661 (let (o)
6662 (save-excursion
6663 (save-restriction
6664 (widen)
6665 (show-all)
6666 (mapc (lambda (c)
6667 (outline-flag-region (car c) (cdr c) t))
6668 data)))))
6670 ;;; Folding of blocks
6672 (defvar org-hide-block-overlays nil
6673 "Overlays hiding blocks.")
6674 (make-variable-buffer-local 'org-hide-block-overlays)
6676 (defun org-block-map (function &optional start end)
6677 "Call FUNCTION at the head of all source blocks in the current buffer.
6678 Optional arguments START and END can be used to limit the range."
6679 (let ((start (or start (point-min)))
6680 (end (or end (point-max))))
6681 (save-excursion
6682 (goto-char start)
6683 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6684 (save-excursion
6685 (save-match-data
6686 (goto-char (match-beginning 0))
6687 (funcall function)))))))
6689 (defun org-hide-block-toggle-all ()
6690 "Toggle the visibility of all blocks in the current buffer."
6691 (org-block-map #'org-hide-block-toggle))
6693 (defun org-hide-block-all ()
6694 "Fold all blocks in the current buffer."
6695 (interactive)
6696 (org-show-block-all)
6697 (org-block-map #'org-hide-block-toggle-maybe))
6699 (defun org-show-block-all ()
6700 "Unfold all blocks in the current buffer."
6701 (interactive)
6702 (mapc 'delete-overlay org-hide-block-overlays)
6703 (setq org-hide-block-overlays nil))
6705 (defun org-hide-block-toggle-maybe ()
6706 "Toggle visibility of block at point."
6707 (interactive)
6708 (let ((case-fold-search t))
6709 (if (save-excursion
6710 (beginning-of-line 1)
6711 (looking-at org-block-regexp))
6712 (progn (org-hide-block-toggle)
6713 t) ;; to signal that we took action
6714 nil))) ;; to signal that we did not
6716 (defun org-hide-block-toggle (&optional force)
6717 "Toggle the visibility of the current block."
6718 (interactive)
6719 (save-excursion
6720 (beginning-of-line)
6721 (if (re-search-forward org-block-regexp nil t)
6722 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6723 (end (match-end 0)) ;; end of entire body
6725 (if (memq t (mapcar (lambda (overlay)
6726 (eq (overlay-get overlay 'invisible)
6727 'org-hide-block))
6728 (overlays-at start)))
6729 (if (or (not force) (eq force 'off))
6730 (mapc (lambda (ov)
6731 (when (member ov org-hide-block-overlays)
6732 (setq org-hide-block-overlays
6733 (delq ov org-hide-block-overlays)))
6734 (when (eq (overlay-get ov 'invisible)
6735 'org-hide-block)
6736 (delete-overlay ov)))
6737 (overlays-at start)))
6738 (setq ov (make-overlay start end))
6739 (overlay-put ov 'invisible 'org-hide-block)
6740 ;; make the block accessible to isearch
6741 (overlay-put
6742 ov 'isearch-open-invisible
6743 (lambda (ov)
6744 (when (member ov org-hide-block-overlays)
6745 (setq org-hide-block-overlays
6746 (delq ov org-hide-block-overlays)))
6747 (when (eq (overlay-get ov 'invisible)
6748 'org-hide-block)
6749 (delete-overlay ov))))
6750 (push ov org-hide-block-overlays)))
6751 (error "Not looking at a source block"))))
6753 ;; org-tab-after-check-for-cycling-hook
6754 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6755 ;; Remove overlays when changing major mode
6756 (add-hook 'org-mode-hook
6757 (lambda () (org-add-hook 'change-major-mode-hook
6758 'org-show-block-all 'append 'local)))
6760 ;;; Org-goto
6762 (defvar org-goto-window-configuration nil)
6763 (defvar org-goto-marker nil)
6764 (defvar org-goto-map)
6765 (defun org-goto-map ()
6766 "Set the keymap `org-goto'."
6767 (setq org-goto-map
6768 (let ((map (make-sparse-keymap)))
6769 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
6770 mouse-drag-region universal-argument org-occur))
6771 cmd)
6772 (while (setq cmd (pop cmds))
6773 (substitute-key-definition cmd cmd map global-map)))
6774 (suppress-keymap map)
6775 (org-defkey map "\C-m" 'org-goto-ret)
6776 (org-defkey map [(return)] 'org-goto-ret)
6777 (org-defkey map [(left)] 'org-goto-left)
6778 (org-defkey map [(right)] 'org-goto-right)
6779 (org-defkey map [(control ?g)] 'org-goto-quit)
6780 (org-defkey map "\C-i" 'org-cycle)
6781 (org-defkey map [(tab)] 'org-cycle)
6782 (org-defkey map [(down)] 'outline-next-visible-heading)
6783 (org-defkey map [(up)] 'outline-previous-visible-heading)
6784 (if org-goto-auto-isearch
6785 (if (fboundp 'define-key-after)
6786 (define-key-after map [t] 'org-goto-local-auto-isearch)
6787 nil)
6788 (org-defkey map "q" 'org-goto-quit)
6789 (org-defkey map "n" 'outline-next-visible-heading)
6790 (org-defkey map "p" 'outline-previous-visible-heading)
6791 (org-defkey map "f" 'outline-forward-same-level)
6792 (org-defkey map "b" 'outline-backward-same-level)
6793 (org-defkey map "u" 'outline-up-heading))
6794 (org-defkey map "/" 'org-occur)
6795 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6796 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6797 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6798 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6799 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6800 map)))
6802 (defconst org-goto-help
6803 "Browse buffer copy, to find location or copy text.%s
6804 RET=jump to location C-g=quit and return to previous location
6805 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6807 (defvar org-goto-start-pos) ; dynamically scoped parameter
6809 ;; FIXME: Docstring does not mention both interfaces
6810 (defun org-goto (&optional alternative-interface)
6811 "Look up a different location in the current file, keeping current visibility.
6813 When you want look-up or go to a different location in a
6814 document, the fastest way is often to fold the entire buffer and
6815 then dive into the tree. This method has the disadvantage, that
6816 the previous location will be folded, which may not be what you
6817 want.
6819 This command works around this by showing a copy of the current
6820 buffer in an indirect buffer, in overview mode. You can dive
6821 into the tree in that copy, use org-occur and incremental search
6822 to find a location. When pressing RET or `Q', the command
6823 returns to the original buffer in which the visibility is still
6824 unchanged. After RET it will also jump to the location selected
6825 in the indirect buffer and expose the headline hierarchy above.
6827 With a prefix argument, use the alternative interface: e.g. if
6828 `org-goto-interface' is 'outline use 'outline-path-completion."
6829 (interactive "P")
6830 (org-goto-map)
6831 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6832 (org-refile-use-outline-path t)
6833 (org-refile-target-verify-function nil)
6834 (interface
6835 (if (not alternative-interface)
6836 org-goto-interface
6837 (if (eq org-goto-interface 'outline)
6838 'outline-path-completion
6839 'outline)))
6840 (org-goto-start-pos (point))
6841 (selected-point
6842 (if (eq interface 'outline)
6843 (car (org-get-location (current-buffer) org-goto-help))
6844 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6845 (org-refile-check-position pa)
6846 (nth 3 pa)))))
6847 (if selected-point
6848 (progn
6849 (org-mark-ring-push org-goto-start-pos)
6850 (goto-char selected-point)
6851 (if (or (outline-invisible-p) (org-invisible-p2))
6852 (org-show-context 'org-goto)))
6853 (message "Quit"))))
6855 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6856 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6857 (defvar org-goto-local-auto-isearch-map) ; defined below
6859 (defun org-get-location (buf help)
6860 "Let the user select a location in the Org-mode buffer BUF.
6861 This function uses a recursive edit. It returns the selected position
6862 or nil."
6863 (org-no-popups
6864 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6865 (isearch-hide-immediately nil)
6866 (isearch-search-fun-function
6867 (lambda () 'org-goto-local-search-headings))
6868 (org-goto-selected-point org-goto-exit-command))
6869 (save-excursion
6870 (save-window-excursion
6871 (delete-other-windows)
6872 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6873 (org-pop-to-buffer-same-window
6874 (condition-case nil
6875 (make-indirect-buffer (current-buffer) "*org-goto*")
6876 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6877 (with-output-to-temp-buffer "*Org Help*"
6878 (princ (format help (if org-goto-auto-isearch
6879 " Just type for auto-isearch."
6880 " n/p/f/b/u to navigate, q to quit."))))
6881 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
6882 (setq buffer-read-only nil)
6883 (let ((org-startup-truncated t)
6884 (org-startup-folded nil)
6885 (org-startup-align-all-tables nil))
6886 (org-mode)
6887 (org-overview))
6888 (setq buffer-read-only t)
6889 (if (and (boundp 'org-goto-start-pos)
6890 (integer-or-marker-p org-goto-start-pos))
6891 (let ((org-show-hierarchy-above t)
6892 (org-show-siblings t)
6893 (org-show-following-heading t))
6894 (goto-char org-goto-start-pos)
6895 (and (outline-invisible-p) (org-show-context)))
6896 (goto-char (point-min)))
6897 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6898 (message "Select location and press RET")
6899 (use-local-map org-goto-map)
6900 (recursive-edit)))
6901 (kill-buffer "*org-goto*")
6902 (cons org-goto-selected-point org-goto-exit-command))))
6904 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6905 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6906 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6907 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6909 (defun org-goto-local-search-headings (string bound noerror)
6910 "Search and make sure that any matches are in headlines."
6911 (catch 'return
6912 (while (if isearch-forward
6913 (search-forward string bound noerror)
6914 (search-backward string bound noerror))
6915 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6916 (and (member :headline context)
6917 (not (member :tags context))))
6918 (throw 'return (point))))))
6920 (defun org-goto-local-auto-isearch ()
6921 "Start isearch."
6922 (interactive)
6923 (goto-char (point-min))
6924 (let ((keys (this-command-keys)))
6925 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6926 (isearch-mode t)
6927 (isearch-process-search-char (string-to-char keys)))))
6929 (defun org-goto-ret (&optional arg)
6930 "Finish `org-goto' by going to the new location."
6931 (interactive "P")
6932 (setq org-goto-selected-point (point)
6933 org-goto-exit-command 'return)
6934 (throw 'exit nil))
6936 (defun org-goto-left ()
6937 "Finish `org-goto' by going to the new location."
6938 (interactive)
6939 (if (org-at-heading-p)
6940 (progn
6941 (beginning-of-line 1)
6942 (setq org-goto-selected-point (point)
6943 org-goto-exit-command 'left)
6944 (throw 'exit nil))
6945 (error "Not on a heading")))
6947 (defun org-goto-right ()
6948 "Finish `org-goto' by going to the new location."
6949 (interactive)
6950 (if (org-at-heading-p)
6951 (progn
6952 (setq org-goto-selected-point (point)
6953 org-goto-exit-command 'right)
6954 (throw 'exit nil))
6955 (error "Not on a heading")))
6957 (defun org-goto-quit ()
6958 "Finish `org-goto' without cursor motion."
6959 (interactive)
6960 (setq org-goto-selected-point nil)
6961 (setq org-goto-exit-command 'quit)
6962 (throw 'exit nil))
6964 ;;; Indirect buffer display of subtrees
6966 (defvar org-indirect-dedicated-frame nil
6967 "This is the frame being used for indirect tree display.")
6968 (defvar org-last-indirect-buffer nil)
6970 (defun org-tree-to-indirect-buffer (&optional arg)
6971 "Create indirect buffer and narrow it to current subtree.
6972 With a numerical prefix ARG, go up to this level and then take that tree.
6973 If ARG is negative, go up that many levels.
6975 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6976 indirect buffer previously made with this command, to avoid proliferation of
6977 indirect buffers. However, when you call the command with a \
6978 \\[universal-argument] prefix, or
6979 when `org-indirect-buffer-display' is `new-frame', the last buffer
6980 is kept so that you can work with several indirect buffers at the same time.
6981 If `org-indirect-buffer-display' is `dedicated-frame', the \
6982 \\[universal-argument] prefix also
6983 requests that a new frame be made for the new buffer, so that the dedicated
6984 frame is not changed."
6985 (interactive "P")
6986 (let ((cbuf (current-buffer))
6987 (cwin (selected-window))
6988 (pos (point))
6989 beg end level heading ibuf)
6990 (save-excursion
6991 (org-back-to-heading t)
6992 (when (numberp arg)
6993 (setq level (org-outline-level))
6994 (if (< arg 0) (setq arg (+ level arg)))
6995 (while (> (setq level (org-outline-level)) arg)
6996 (org-up-heading-safe)))
6997 (setq beg (point)
6998 heading (org-get-heading))
6999 (org-end-of-subtree t t)
7000 (if (org-at-heading-p) (backward-char 1))
7001 (setq end (point)))
7002 (if (and (buffer-live-p org-last-indirect-buffer)
7003 (not (eq org-indirect-buffer-display 'new-frame))
7004 (not arg))
7005 (kill-buffer org-last-indirect-buffer))
7006 (setq ibuf (org-get-indirect-buffer cbuf)
7007 org-last-indirect-buffer ibuf)
7008 (cond
7009 ((or (eq org-indirect-buffer-display 'new-frame)
7010 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7011 (select-frame (make-frame))
7012 (delete-other-windows)
7013 (org-pop-to-buffer-same-window ibuf)
7014 (org-set-frame-title heading))
7015 ((eq org-indirect-buffer-display 'dedicated-frame)
7016 (raise-frame
7017 (select-frame (or (and org-indirect-dedicated-frame
7018 (frame-live-p org-indirect-dedicated-frame)
7019 org-indirect-dedicated-frame)
7020 (setq org-indirect-dedicated-frame (make-frame)))))
7021 (delete-other-windows)
7022 (org-pop-to-buffer-same-window ibuf)
7023 (org-set-frame-title (concat "Indirect: " heading)))
7024 ((eq org-indirect-buffer-display 'current-window)
7025 (org-pop-to-buffer-same-window ibuf))
7026 ((eq org-indirect-buffer-display 'other-window)
7027 (pop-to-buffer ibuf))
7028 (t (error "Invalid value")))
7029 (if (featurep 'xemacs)
7030 (save-excursion (org-mode) (turn-on-font-lock)))
7031 (narrow-to-region beg end)
7032 (show-all)
7033 (goto-char pos)
7034 (run-hook-with-args 'org-cycle-hook 'all)
7035 (and (window-live-p cwin) (select-window cwin))))
7037 (defun org-get-indirect-buffer (&optional buffer)
7038 (setq buffer (or buffer (current-buffer)))
7039 (let ((n 1) (base (buffer-name buffer)) bname)
7040 (while (buffer-live-p
7041 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7042 (setq n (1+ n)))
7043 (condition-case nil
7044 (make-indirect-buffer buffer bname 'clone)
7045 (error (make-indirect-buffer buffer bname)))))
7047 (defun org-set-frame-title (title)
7048 "Set the title of the current frame to the string TITLE."
7049 ;; FIXME: how to name a single frame in XEmacs???
7050 (unless (featurep 'xemacs)
7051 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7053 ;;;; Structure editing
7055 ;;; Inserting headlines
7057 (defun org-previous-line-empty-p ()
7058 (save-excursion
7059 (and (not (bobp))
7060 (or (beginning-of-line 0) t)
7061 (save-match-data
7062 (looking-at "[ \t]*$")))))
7064 (defun org-insert-heading (&optional force-heading invisible-ok)
7065 "Insert a new heading or item with same depth at point.
7066 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7067 If point is at the beginning of a headline, insert a sibling before the
7068 current headline. If point is not at the beginning, split the line,
7069 create the new headline with the text in the current line after point
7070 \(but see also the variable `org-M-RET-may-split-line').
7072 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7073 This is important for non-interactive uses of the command."
7074 (interactive "P")
7075 (if (or (= (buffer-size) 0)
7076 (and (not (save-excursion
7077 (and (ignore-errors (org-back-to-heading invisible-ok))
7078 (org-at-heading-p))))
7079 (or force-heading (not (org-in-item-p)))))
7080 (progn
7081 (insert "\n* ")
7082 (run-hooks 'org-insert-heading-hook))
7083 (when (or force-heading (not (org-insert-item)))
7084 (let* ((empty-line-p nil)
7085 (level nil)
7086 (on-heading (org-at-heading-p))
7087 (head (save-excursion
7088 (condition-case nil
7089 (progn
7090 (org-back-to-heading invisible-ok)
7091 (when (and (not on-heading)
7092 (featurep 'org-inlinetask)
7093 (integerp org-inlinetask-min-level)
7094 (>= (length (match-string 0))
7095 org-inlinetask-min-level))
7096 ;; Find a heading level before the inline task
7097 (while (and (setq level (org-up-heading-safe))
7098 (>= level org-inlinetask-min-level)))
7099 (if (org-at-heading-p)
7100 (org-back-to-heading invisible-ok)
7101 (error "This should not happen")))
7102 (setq empty-line-p (org-previous-line-empty-p))
7103 (match-string 0))
7104 (error "*"))))
7105 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7106 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7107 pos hide-previous previous-pos)
7108 (cond
7109 ((and (org-at-heading-p) (bolp)
7110 (or (bobp)
7111 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7112 ;; insert before the current line
7113 (open-line (if blank 2 1)))
7114 ((and (bolp)
7115 (not org-insert-heading-respect-content)
7116 (or (bobp)
7117 (save-excursion
7118 (backward-char 1) (not (outline-invisible-p)))))
7119 ;; insert right here
7120 nil)
7122 ;; somewhere in the line
7123 (save-excursion
7124 (setq previous-pos (point-at-bol))
7125 (end-of-line)
7126 (setq hide-previous (outline-invisible-p)))
7127 (and org-insert-heading-respect-content (org-show-subtree))
7128 (let ((split
7129 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7130 (save-excursion
7131 (let ((p (point)))
7132 (goto-char (point-at-bol))
7133 (and (looking-at org-complex-heading-regexp)
7134 (match-beginning 4)
7135 (> p (match-beginning 4)))))))
7136 tags pos)
7137 (cond
7138 (org-insert-heading-respect-content
7139 (org-end-of-subtree nil t)
7140 (when (featurep 'org-inlinetask)
7141 (while (and (not (eobp))
7142 (looking-at "\\(\\*+\\)[ \t]+")
7143 (>= (length (match-string 1))
7144 org-inlinetask-min-level))
7145 (org-end-of-subtree nil t)))
7146 (or (bolp) (newline))
7147 (or (org-previous-line-empty-p)
7148 (and blank (newline)))
7149 (open-line 1))
7150 ((org-at-heading-p)
7151 (when hide-previous
7152 (show-children)
7153 (org-show-entry))
7154 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7155 (setq tags (and (match-end 2) (match-string 2)))
7156 (and (match-end 1)
7157 (delete-region (match-beginning 1) (match-end 1)))
7158 (setq pos (point-at-bol))
7159 (or split (end-of-line 1))
7160 (delete-horizontal-space)
7161 (if (string-match "\\`\\*+\\'"
7162 (buffer-substring (point-at-bol) (point)))
7163 (insert " "))
7164 (newline (if blank 2 1))
7165 (when tags
7166 (save-excursion
7167 (goto-char pos)
7168 (end-of-line 1)
7169 (insert " " tags)
7170 (org-set-tags nil 'align))))
7172 (or split (end-of-line 1))
7173 (newline (if blank 2 1)))))))
7174 (insert head) (just-one-space)
7175 (setq pos (point))
7176 (end-of-line 1)
7177 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7178 (when (and org-insert-heading-respect-content hide-previous)
7179 (save-excursion
7180 (goto-char previous-pos)
7181 (hide-subtree)))
7182 (run-hooks 'org-insert-heading-hook)))))
7184 (defun org-get-heading (&optional no-tags no-todo)
7185 "Return the heading of the current entry, without the stars.
7186 When NO-TAGS is non-nil, don't include tags.
7187 When NO-TODO is non-nil, don't include TODO keywords."
7188 (save-excursion
7189 (org-back-to-heading t)
7190 (cond
7191 ((and no-tags no-todo)
7192 (looking-at org-complex-heading-regexp)
7193 (match-string 4))
7194 (no-tags
7195 (looking-at (concat org-outline-regexp
7196 "\\(.*?\\)"
7197 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7198 (match-string 1))
7199 (no-todo
7200 (looking-at org-todo-line-regexp)
7201 (match-string 3))
7202 (t (looking-at org-heading-regexp)
7203 (match-string 2)))))
7205 (defun org-heading-components ()
7206 "Return the components of the current heading.
7207 This is a list with the following elements:
7208 - the level as an integer
7209 - the reduced level, different if `org-odd-levels-only' is set.
7210 - the TODO keyword, or nil
7211 - the priority character, like ?A, or nil if no priority is given
7212 - the headline text itself, or the tags string if no headline text
7213 - the tags string, or nil."
7214 (save-excursion
7215 (org-back-to-heading t)
7216 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7217 (list (length (match-string 1))
7218 (org-reduced-level (length (match-string 1)))
7219 (org-match-string-no-properties 2)
7220 (and (match-end 3) (aref (match-string 3) 2))
7221 (org-match-string-no-properties 4)
7222 (org-match-string-no-properties 5)))))
7224 (defun org-get-entry ()
7225 "Get the entry text, after heading, entire subtree."
7226 (save-excursion
7227 (org-back-to-heading t)
7228 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7230 (defun org-insert-heading-after-current ()
7231 "Insert a new heading with same level as current, after current subtree."
7232 (interactive)
7233 (org-back-to-heading)
7234 (org-insert-heading)
7235 (org-move-subtree-down)
7236 (end-of-line 1))
7238 (defun org-insert-heading-respect-content ()
7239 (interactive)
7240 (let ((org-insert-heading-respect-content t))
7241 (org-insert-heading t)))
7243 (defun org-insert-todo-heading-respect-content (&optional force-state)
7244 (interactive "P")
7245 (let ((org-insert-heading-respect-content t))
7246 (org-insert-todo-heading force-state t)))
7248 (defun org-insert-todo-heading (arg &optional force-heading)
7249 "Insert a new heading with the same level and TODO state as current heading.
7250 If the heading has no TODO state, or if the state is DONE, use the first
7251 state (TODO by default). Also with prefix arg, force first state."
7252 (interactive "P")
7253 (when (or force-heading (not (org-insert-item 'checkbox)))
7254 (org-insert-heading force-heading)
7255 (save-excursion
7256 (org-back-to-heading)
7257 (outline-previous-heading)
7258 (looking-at org-todo-line-regexp))
7259 (let*
7260 ((new-mark-x
7261 (if (or arg
7262 (not (match-beginning 2))
7263 (member (match-string 2) org-done-keywords))
7264 (car org-todo-keywords-1)
7265 (match-string 2)))
7266 (new-mark
7268 (run-hook-with-args-until-success
7269 'org-todo-get-default-hook new-mark-x nil)
7270 new-mark-x)))
7271 (beginning-of-line 1)
7272 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7273 (if org-treat-insert-todo-heading-as-state-change
7274 (org-todo new-mark)
7275 (insert new-mark " "))))
7276 (when org-provide-todo-statistics
7277 (org-update-parent-todo-statistics))))
7279 (defun org-insert-subheading (arg)
7280 "Insert a new subheading and demote it.
7281 Works for outline headings and for plain lists alike."
7282 (interactive "P")
7283 (org-insert-heading arg)
7284 (cond
7285 ((org-at-heading-p) (org-do-demote))
7286 ((org-at-item-p) (org-indent-item))))
7288 (defun org-insert-todo-subheading (arg)
7289 "Insert a new subheading with TODO keyword or checkbox and demote it.
7290 Works for outline headings and for plain lists alike."
7291 (interactive "P")
7292 (org-insert-todo-heading arg)
7293 (cond
7294 ((org-at-heading-p) (org-do-demote))
7295 ((org-at-item-p) (org-indent-item))))
7297 ;;; Promotion and Demotion
7299 (defvar org-after-demote-entry-hook nil
7300 "Hook run after an entry has been demoted.
7301 The cursor will be at the beginning of the entry.
7302 When a subtree is being demoted, the hook will be called for each node.")
7304 (defvar org-after-promote-entry-hook nil
7305 "Hook run after an entry has been promoted.
7306 The cursor will be at the beginning of the entry.
7307 When a subtree is being promoted, the hook will be called for each node.")
7309 (defun org-promote-subtree ()
7310 "Promote the entire subtree.
7311 See also `org-promote'."
7312 (interactive)
7313 (save-excursion
7314 (org-with-limited-levels (org-map-tree 'org-promote)))
7315 (org-fix-position-after-promote))
7317 (defun org-demote-subtree ()
7318 "Demote the entire subtree. See `org-demote'.
7319 See also `org-promote'."
7320 (interactive)
7321 (save-excursion
7322 (org-with-limited-levels (org-map-tree 'org-demote)))
7323 (org-fix-position-after-promote))
7326 (defun org-do-promote ()
7327 "Promote the current heading higher up the tree.
7328 If the region is active in `transient-mark-mode', promote all headings
7329 in the region."
7330 (interactive)
7331 (save-excursion
7332 (if (org-region-active-p)
7333 (org-map-region 'org-promote (region-beginning) (region-end))
7334 (org-promote)))
7335 (org-fix-position-after-promote))
7337 (defun org-do-demote ()
7338 "Demote the current heading lower down the tree.
7339 If the region is active in `transient-mark-mode', demote all headings
7340 in the region."
7341 (interactive)
7342 (save-excursion
7343 (if (org-region-active-p)
7344 (org-map-region 'org-demote (region-beginning) (region-end))
7345 (org-demote)))
7346 (org-fix-position-after-promote))
7348 (defun org-fix-position-after-promote ()
7349 "Make sure that after pro/demotion cursor position is right."
7350 (let ((pos (point)))
7351 (when (save-excursion
7352 (beginning-of-line 1)
7353 (looking-at org-todo-line-regexp)
7354 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7355 (cond ((eobp) (insert " "))
7356 ((eolp) (insert " "))
7357 ((equal (char-after) ?\ ) (forward-char 1))))))
7359 (defun org-current-level ()
7360 "Return the level of the current entry, or nil if before the first headline.
7361 The level is the number of stars at the beginning of the headline."
7362 (save-excursion
7363 (org-with-limited-levels
7364 (if (ignore-errors (org-back-to-heading t))
7365 (funcall outline-level)))))
7367 (defun org-get-previous-line-level ()
7368 "Return the outline depth of the last headline before the current line.
7369 Returns 0 for the first headline in the buffer, and nil if before the
7370 first headline."
7371 (let ((current-level (org-current-level))
7372 (prev-level (when (> (line-number-at-pos) 1)
7373 (save-excursion
7374 (beginning-of-line 0)
7375 (org-current-level)))))
7376 (cond ((null current-level) nil) ; Before first headline
7377 ((null prev-level) 0) ; At first headline
7378 (prev-level))))
7380 (defun org-reduced-level (l)
7381 "Compute the effective level of a heading.
7382 This takes into account the setting of `org-odd-levels-only'."
7383 (cond
7384 ((zerop l) 0)
7385 (org-odd-levels-only (1+ (floor (/ l 2))))
7386 (t l)))
7388 (defun org-level-increment ()
7389 "Return the number of stars that will be added or removed at a
7390 time to headlines when structure editing, based on the value of
7391 `org-odd-levels-only'."
7392 (if org-odd-levels-only 2 1))
7394 (defun org-get-valid-level (level &optional change)
7395 "Rectify a level change under the influence of `org-odd-levels-only'
7396 LEVEL is a current level, CHANGE is by how much the level should be
7397 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7398 even level numbers will become the next higher odd number."
7399 (if org-odd-levels-only
7400 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7401 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7402 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7403 (max 1 (+ level (or change 0)))))
7405 (org-define-obsolete-function-alias 'org-get-legal-level 'org-get-valid-level "23.1")
7407 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7408 ;; ̀org-with-limited-levels'
7409 (defun org-promote ()
7410 "Promote the current heading higher up the tree.
7411 If the region is active in `transient-mark-mode', promote all headings
7412 in the region."
7413 (org-back-to-heading t)
7414 (let* ((level (save-match-data (funcall outline-level)))
7415 (after-change-functions (remove 'flyspell-after-change-function
7416 after-change-functions))
7417 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7418 (diff (abs (- level (length up-head) -1))))
7419 (cond ((and (= level 1) org-called-with-limited-levels
7420 org-allow-promoting-top-level-subtree)
7421 (replace-match "# " nil t))
7422 ((= level 1)
7423 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7424 (t (replace-match up-head nil t)))
7425 ;; Fixup tag positioning
7426 (unless (= level 1)
7427 (and org-auto-align-tags (org-set-tags nil t))
7428 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7429 (run-hooks 'org-after-promote-entry-hook)))
7431 (defun org-demote ()
7432 "Demote the current heading lower down the tree.
7433 If the region is active in `transient-mark-mode', demote all headings
7434 in the region."
7435 (org-back-to-heading t)
7436 (let* ((level (save-match-data (funcall outline-level)))
7437 (after-change-functions (remove 'flyspell-after-change-function
7438 after-change-functions))
7439 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7440 (diff (abs (- level (length down-head) -1))))
7441 (replace-match down-head nil t)
7442 ;; Fixup tag positioning
7443 (and org-auto-align-tags (org-set-tags nil t))
7444 (if org-adapt-indentation (org-fixup-indentation diff))
7445 (run-hooks 'org-after-demote-entry-hook)))
7447 (defun org-cycle-level ()
7448 "Cycle the level of an empty headline through possible states.
7449 This goes first to child, then to parent, level, then up the hierarchy.
7450 After top level, it switches back to sibling level."
7451 (interactive)
7452 (let ((org-adapt-indentation nil))
7453 (when (org-point-at-end-of-empty-headline)
7454 (setq this-command 'org-cycle-level) ; Only needed for caching
7455 (let ((cur-level (org-current-level))
7456 (prev-level (org-get-previous-line-level)))
7457 (cond
7458 ;; If first headline in file, promote to top-level.
7459 ((= prev-level 0)
7460 (loop repeat (/ (- cur-level 1) (org-level-increment))
7461 do (org-do-promote)))
7462 ;; If same level as prev, demote one.
7463 ((= prev-level cur-level)
7464 (org-do-demote))
7465 ;; If parent is top-level, promote to top level if not already.
7466 ((= prev-level 1)
7467 (loop repeat (/ (- cur-level 1) (org-level-increment))
7468 do (org-do-promote)))
7469 ;; If top-level, return to prev-level.
7470 ((= cur-level 1)
7471 (loop repeat (/ (- prev-level 1) (org-level-increment))
7472 do (org-do-demote)))
7473 ;; If less than prev-level, promote one.
7474 ((< cur-level prev-level)
7475 (org-do-promote))
7476 ;; If deeper than prev-level, promote until higher than
7477 ;; prev-level.
7478 ((> cur-level prev-level)
7479 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7480 do (org-do-promote))))
7481 t))))
7483 (defun org-map-tree (fun)
7484 "Call FUN for every heading underneath the current one."
7485 (org-back-to-heading)
7486 (let ((level (funcall outline-level)))
7487 (save-excursion
7488 (funcall fun)
7489 (while (and (progn
7490 (outline-next-heading)
7491 (> (funcall outline-level) level))
7492 (not (eobp)))
7493 (funcall fun)))))
7495 (defun org-map-region (fun beg end)
7496 "Call FUN for every heading between BEG and END."
7497 (let ((org-ignore-region t))
7498 (save-excursion
7499 (setq end (copy-marker end))
7500 (goto-char beg)
7501 (if (and (re-search-forward org-outline-regexp-bol nil t)
7502 (< (point) end))
7503 (funcall fun))
7504 (while (and (progn
7505 (outline-next-heading)
7506 (< (point) end))
7507 (not (eobp)))
7508 (funcall fun)))))
7510 (defvar org-property-end-re) ; silence byte-compiler
7511 (defun org-fixup-indentation (diff)
7512 "Change the indentation in the current entry by DIFF.
7513 However, if any line in the current entry has no indentation, or if it
7514 would end up with no indentation after the change, nothing at all is done."
7515 (save-excursion
7516 (let ((end (save-excursion (outline-next-heading)
7517 (point-marker)))
7518 (prohibit (if (> diff 0)
7519 "^\\S-"
7520 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7521 col)
7522 (unless (save-excursion (end-of-line 1)
7523 (re-search-forward prohibit end t))
7524 (while (and (< (point) end)
7525 (re-search-forward "^[ \t]+" end t))
7526 (goto-char (match-end 0))
7527 (setq col (current-column))
7528 (if (< diff 0) (replace-match ""))
7529 (org-indent-to-column (+ diff col))))
7530 (move-marker end nil))))
7532 (defun org-convert-to-odd-levels ()
7533 "Convert an org-mode file with all levels allowed to one with odd levels.
7534 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7535 level 5 etc."
7536 (interactive)
7537 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7538 (let ((outline-level 'org-outline-level)
7539 (org-odd-levels-only nil) n)
7540 (save-excursion
7541 (goto-char (point-min))
7542 (while (re-search-forward "^\\*\\*+ " nil t)
7543 (setq n (- (length (match-string 0)) 2))
7544 (while (>= (setq n (1- n)) 0)
7545 (org-demote))
7546 (end-of-line 1))))))
7548 (defun org-convert-to-oddeven-levels ()
7549 "Convert an org-mode file with only odd levels to one with odd/even levels.
7550 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7551 file contains a section with an even level, conversion would
7552 destroy the structure of the file. An error is signaled in this
7553 case."
7554 (interactive)
7555 (goto-char (point-min))
7556 ;; First check if there are no even levels
7557 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7558 (org-show-context t)
7559 (error "Not all levels are odd in this file. Conversion not possible"))
7560 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7561 (let ((outline-regexp org-outline-regexp)
7562 (outline-level 'org-outline-level)
7563 (org-odd-levels-only nil) n)
7564 (save-excursion
7565 (goto-char (point-min))
7566 (while (re-search-forward "^\\*\\*+ " nil t)
7567 (setq n (/ (1- (length (match-string 0))) 2))
7568 (while (>= (setq n (1- n)) 0)
7569 (org-promote))
7570 (end-of-line 1))))))
7572 (defun org-tr-level (n)
7573 "Make N odd if required."
7574 (if org-odd-levels-only (1+ (/ n 2)) n))
7576 ;;; Vertical tree motion, cutting and pasting of subtrees
7578 (defun org-move-subtree-up (&optional arg)
7579 "Move the current subtree up past ARG headlines of the same level."
7580 (interactive "p")
7581 (org-move-subtree-down (- (prefix-numeric-value arg))))
7583 (defun org-move-subtree-down (&optional arg)
7584 "Move the current subtree down past ARG headlines of the same level."
7585 (interactive "p")
7586 (setq arg (prefix-numeric-value arg))
7587 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7588 'org-get-last-sibling))
7589 (ins-point (make-marker))
7590 (cnt (abs arg))
7591 (col (current-column))
7592 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7593 ;; Select the tree
7594 (org-back-to-heading)
7595 (setq beg0 (point))
7596 (save-excursion
7597 (setq ne-beg (org-back-over-empty-lines))
7598 (setq beg (point)))
7599 (save-match-data
7600 (save-excursion (outline-end-of-heading)
7601 (setq folded (outline-invisible-p)))
7602 (outline-end-of-subtree))
7603 (outline-next-heading)
7604 (setq ne-end (org-back-over-empty-lines))
7605 (setq end (point))
7606 (goto-char beg0)
7607 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7608 ;; include less whitespace
7609 (save-excursion
7610 (goto-char beg)
7611 (forward-line (- ne-beg ne-end))
7612 (setq beg (point))))
7613 ;; Find insertion point, with error handling
7614 (while (> cnt 0)
7615 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7616 (progn (goto-char beg0)
7617 (error "Cannot move past superior level or buffer limit")))
7618 (setq cnt (1- cnt)))
7619 (if (> arg 0)
7620 ;; Moving forward - still need to move over subtree
7621 (progn (org-end-of-subtree t t)
7622 (save-excursion
7623 (org-back-over-empty-lines)
7624 (or (bolp) (newline)))))
7625 (setq ne-ins (org-back-over-empty-lines))
7626 (move-marker ins-point (point))
7627 (setq txt (buffer-substring beg end))
7628 (org-save-markers-in-region beg end)
7629 (delete-region beg end)
7630 (org-remove-empty-overlays-at beg)
7631 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7632 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7633 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7634 (let ((bbb (point)))
7635 (insert-before-markers txt)
7636 (org-reinstall-markers-in-region bbb)
7637 (move-marker ins-point bbb))
7638 (or (bolp) (insert "\n"))
7639 (setq ins-end (point))
7640 (goto-char ins-point)
7641 (org-skip-whitespace)
7642 (when (and (< arg 0)
7643 (org-first-sibling-p)
7644 (> ne-ins ne-beg))
7645 ;; Move whitespace back to beginning
7646 (save-excursion
7647 (goto-char ins-end)
7648 (let ((kill-whole-line t))
7649 (kill-line (- ne-ins ne-beg)) (point)))
7650 (insert (make-string (- ne-ins ne-beg) ?\n)))
7651 (move-marker ins-point nil)
7652 (if folded
7653 (hide-subtree)
7654 (org-show-entry)
7655 (show-children)
7656 (org-cycle-hide-drawers 'children))
7657 (org-clean-visibility-after-subtree-move)
7658 ;; move back to the initial column we were at
7659 (move-to-column col)))
7661 (defvar org-subtree-clip ""
7662 "Clipboard for cut and paste of subtrees.
7663 This is actually only a copy of the kill, because we use the normal kill
7664 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7666 (defvar org-subtree-clip-folded nil
7667 "Was the last copied subtree folded?
7668 This is used to fold the tree back after pasting.")
7670 (defun org-cut-subtree (&optional n)
7671 "Cut the current subtree into the clipboard.
7672 With prefix arg N, cut this many sequential subtrees.
7673 This is a short-hand for marking the subtree and then cutting it."
7674 (interactive "p")
7675 (org-copy-subtree n 'cut))
7677 (defun org-copy-subtree (&optional n cut force-store-markers)
7678 "Cut the current subtree into the clipboard.
7679 With prefix arg N, cut this many sequential subtrees.
7680 This is a short-hand for marking the subtree and then copying it.
7681 If CUT is non-nil, actually cut the subtree.
7682 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7683 of some markers in the region, even if CUT is non-nil. This is
7684 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7685 (interactive "p")
7686 (let (beg end folded (beg0 (point)))
7687 (if (org-called-interactively-p 'any)
7688 (org-back-to-heading nil) ; take what looks like a subtree
7689 (org-back-to-heading t)) ; take what is really there
7690 (setq beg (point))
7691 (skip-chars-forward " \t\r\n")
7692 (save-match-data
7693 (save-excursion (outline-end-of-heading)
7694 (setq folded (outline-invisible-p)))
7695 (condition-case nil
7696 (org-forward-heading-same-level (1- n) t)
7697 (error nil))
7698 (org-end-of-subtree t t))
7699 (setq end (point))
7700 (goto-char beg0)
7701 (when (> end beg)
7702 (setq org-subtree-clip-folded folded)
7703 (when (or cut force-store-markers)
7704 (org-save-markers-in-region beg end))
7705 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7706 (setq org-subtree-clip (current-kill 0))
7707 (message "%s: Subtree(s) with %d characters"
7708 (if cut "Cut" "Copied")
7709 (length org-subtree-clip)))))
7711 (defun org-paste-subtree (&optional level tree for-yank)
7712 "Paste the clipboard as a subtree, with modification of headline level.
7713 The entire subtree is promoted or demoted in order to match a new headline
7714 level.
7716 If the cursor is at the beginning of a headline, the same level as
7717 that headline is used to paste the tree
7719 If not, the new level is derived from the *visible* headings
7720 before and after the insertion point, and taken to be the inferior headline
7721 level of the two. So if the previous visible heading is level 3 and the
7722 next is level 4 (or vice versa), level 4 will be used for insertion.
7723 This makes sure that the subtree remains an independent subtree and does
7724 not swallow low level entries.
7726 You can also force a different level, either by using a numeric prefix
7727 argument, or by inserting the heading marker by hand. For example, if the
7728 cursor is after \"*****\", then the tree will be shifted to level 5.
7730 If optional TREE is given, use this text instead of the kill ring.
7732 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7733 move back over whitespace before inserting, and move point to the end of
7734 the inserted text when done."
7735 (interactive "P")
7736 (setq tree (or tree (and kill-ring (current-kill 0))))
7737 (unless (org-kill-is-subtree-p tree)
7738 (error "%s"
7739 (substitute-command-keys
7740 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7741 (org-with-limited-levels
7742 (let* ((visp (not (outline-invisible-p)))
7743 (txt tree)
7744 (^re_ "\\(\\*+\\)[ \t]*")
7745 (old-level (if (string-match org-outline-regexp-bol txt)
7746 (- (match-end 0) (match-beginning 0) 1)
7747 -1))
7748 (force-level (cond (level (prefix-numeric-value level))
7749 ((and (looking-at "[ \t]*$")
7750 (string-match
7751 "^\\*+$" (buffer-substring
7752 (point-at-bol) (point))))
7753 (- (match-end 1) (match-beginning 1)))
7754 ((and (bolp)
7755 (looking-at org-outline-regexp))
7756 (- (match-end 0) (point) 1))))
7757 (previous-level (save-excursion
7758 (condition-case nil
7759 (progn
7760 (outline-previous-visible-heading 1)
7761 (if (looking-at ^re_)
7762 (- (match-end 0) (match-beginning 0) 1)
7764 (error 1))))
7765 (next-level (save-excursion
7766 (condition-case nil
7767 (progn
7768 (or (looking-at org-outline-regexp)
7769 (outline-next-visible-heading 1))
7770 (if (looking-at ^re_)
7771 (- (match-end 0) (match-beginning 0) 1)
7773 (error 1))))
7774 (new-level (or force-level (max previous-level next-level)))
7775 (shift (if (or (= old-level -1)
7776 (= new-level -1)
7777 (= old-level new-level))
7779 (- new-level old-level)))
7780 (delta (if (> shift 0) -1 1))
7781 (func (if (> shift 0) 'org-demote 'org-promote))
7782 (org-odd-levels-only nil)
7783 beg end newend)
7784 ;; Remove the forced level indicator
7785 (if force-level
7786 (delete-region (point-at-bol) (point)))
7787 ;; Paste
7788 (beginning-of-line (if (bolp) 1 2))
7789 (setq beg (point))
7790 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7791 (insert-before-markers txt)
7792 (unless (string-match "\n\\'" txt) (insert "\n"))
7793 (setq newend (point))
7794 (org-reinstall-markers-in-region beg)
7795 (setq end (point))
7796 (goto-char beg)
7797 (skip-chars-forward " \t\n\r")
7798 (setq beg (point))
7799 (if (and (outline-invisible-p) visp)
7800 (save-excursion (outline-show-heading)))
7801 ;; Shift if necessary
7802 (unless (= shift 0)
7803 (save-restriction
7804 (narrow-to-region beg end)
7805 (while (not (= shift 0))
7806 (org-map-region func (point-min) (point-max))
7807 (setq shift (+ delta shift)))
7808 (goto-char (point-min))
7809 (setq newend (point-max))))
7810 (when (or (org-called-interactively-p 'interactive) for-yank)
7811 (message "Clipboard pasted as level %d subtree" new-level))
7812 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7813 kill-ring
7814 (eq org-subtree-clip (current-kill 0))
7815 org-subtree-clip-folded)
7816 ;; The tree was folded before it was killed/copied
7817 (hide-subtree))
7818 (and for-yank (goto-char newend)))))
7820 (defun org-kill-is-subtree-p (&optional txt)
7821 "Check if the current kill is an outline subtree, or a set of trees.
7822 Returns nil if kill does not start with a headline, or if the first
7823 headline level is not the largest headline level in the tree.
7824 So this will actually accept several entries of equal levels as well,
7825 which is OK for `org-paste-subtree'.
7826 If optional TXT is given, check this string instead of the current kill."
7827 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7828 (re (org-get-limited-outline-regexp))
7829 (^re (concat "^" re))
7830 (start-level (and kill
7831 (string-match
7832 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7833 kill)
7834 (- (match-end 2) (match-beginning 2) 1)))
7835 (start (1+ (or (match-beginning 2) -1))))
7836 (if (not start-level)
7837 (progn
7838 nil) ;; does not even start with a heading
7839 (catch 'exit
7840 (while (setq start (string-match ^re kill (1+ start)))
7841 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7842 (throw 'exit nil)))
7843 t))))
7845 (defvar org-markers-to-move nil
7846 "Markers that should be moved with a cut-and-paste operation.
7847 Those markers are stored together with their positions relative to
7848 the start of the region.")
7850 (defun org-save-markers-in-region (beg end)
7851 "Check markers in region.
7852 If these markers are between BEG and END, record their position relative
7853 to BEG, so that after moving the block of text, we can put the markers back
7854 into place.
7855 This function gets called just before an entry or tree gets cut from the
7856 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7857 called immediately, to move the markers with the entries."
7858 (setq org-markers-to-move nil)
7859 (when (featurep 'org-clock)
7860 (org-clock-save-markers-for-cut-and-paste beg end))
7861 (when (featurep 'org-agenda)
7862 (org-agenda-save-markers-for-cut-and-paste beg end)))
7864 (defun org-check-and-save-marker (marker beg end)
7865 "Check if MARKER is between BEG and END.
7866 If yes, remember the marker and the distance to BEG."
7867 (when (and (marker-buffer marker)
7868 (equal (marker-buffer marker) (current-buffer)))
7869 (if (and (>= marker beg) (< marker end))
7870 (push (cons marker (- marker beg)) org-markers-to-move))))
7872 (defun org-reinstall-markers-in-region (beg)
7873 "Move all remembered markers to their position relative to BEG."
7874 (mapc (lambda (x)
7875 (move-marker (car x) (+ beg (cdr x))))
7876 org-markers-to-move)
7877 (setq org-markers-to-move nil))
7879 (defun org-narrow-to-subtree ()
7880 "Narrow buffer to the current subtree."
7881 (interactive)
7882 (save-excursion
7883 (save-match-data
7884 (org-with-limited-levels
7885 (narrow-to-region
7886 (progn (org-back-to-heading t) (point))
7887 (progn (org-end-of-subtree t t)
7888 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7889 (point)))))))
7891 (defun org-narrow-to-block ()
7892 "Narrow buffer to the current block."
7893 (interactive)
7894 (let* ((case-fold-search t)
7895 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7896 "^[ \t]*#\\+end_.*")))
7897 (if blockp
7898 (narrow-to-region (car blockp) (cdr blockp))
7899 (error "Not in a block"))))
7901 (eval-when-compile
7902 (defvar org-property-drawer-re))
7904 (defvar org-property-start-re) ;; defined below
7905 (defun org-clone-subtree-with-time-shift (n &optional shift)
7906 "Clone the task (subtree) at point N times.
7907 The clones will be inserted as siblings.
7909 In interactive use, the user will be prompted for the number of
7910 clones to be produced, and for a time SHIFT, which may be a
7911 repeater as used in time stamps, for example `+3d'.
7913 When a valid repeater is given and the entry contains any time
7914 stamps, the clones will become a sequence in time, with time
7915 stamps in the subtree shifted for each clone produced. If SHIFT
7916 is nil or the empty string, time stamps will be left alone. The
7917 ID property of the original subtree is removed.
7919 If the original subtree did contain time stamps with a repeater,
7920 the following will happen:
7921 - the repeater will be removed in each clone
7922 - an additional clone will be produced, with the current, unshifted
7923 date(s) in the entry.
7924 - the original entry will be placed *after* all the clones, with
7925 repeater intact.
7926 - the start days in the repeater in the original entry will be shifted
7927 to past the last clone.
7928 In this way you can spell out a number of instances of a repeating task,
7929 and still retain the repeater to cover future instances of the task."
7930 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7931 (let (beg end template task idprop
7932 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7933 (drawer-re org-drawer-regexp))
7934 (if (not (and (integerp n) (> n 0)))
7935 (error "Invalid number of replications %s" n))
7936 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7937 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
7938 shift)))
7939 (error "Invalid shift specification %s" shift))
7940 (when doshift
7941 (setq shift-n (string-to-number (match-string 1 shift))
7942 shift-what (cdr (assoc (match-string 2 shift)
7943 '(("d" . day) ("w" . week)
7944 ("m" . month) ("y" . year))))))
7945 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7946 (setq nmin 1 nmax n)
7947 (org-back-to-heading t)
7948 (setq beg (point))
7949 (setq idprop (org-entry-get nil "ID"))
7950 (org-end-of-subtree t t)
7951 (or (bolp) (insert "\n"))
7952 (setq end (point))
7953 (setq template (buffer-substring beg end))
7954 (when (and doshift
7955 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
7956 (delete-region beg end)
7957 (setq end beg)
7958 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7959 (goto-char end)
7960 (loop for n from nmin to nmax do
7961 ;; prepare clone
7962 (with-temp-buffer
7963 (insert template)
7964 (org-mode)
7965 (goto-char (point-min))
7966 (org-show-subtree)
7967 (and idprop (if org-clone-delete-id
7968 (org-entry-delete nil "ID")
7969 (org-id-get-create t)))
7970 (unless (= n 0)
7971 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
7972 (kill-whole-line))
7973 (goto-char (point-min))
7974 (while (re-search-forward drawer-re nil t)
7975 (mapc (lambda (d)
7976 (org-remove-empty-drawer-at d (point))) org-drawers)))
7977 (goto-char (point-min))
7978 (when doshift
7979 (while (re-search-forward org-ts-regexp-both nil t)
7980 (org-timestamp-change (* n shift-n) shift-what))
7981 (unless (= n n-no-remove)
7982 (goto-char (point-min))
7983 (while (re-search-forward org-ts-regexp nil t)
7984 (save-excursion
7985 (goto-char (match-beginning 0))
7986 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
7987 (delete-region (match-beginning 1) (match-end 1)))))))
7988 (setq task (buffer-string)))
7989 (insert task))
7990 (goto-char beg)))
7992 ;;; Outline Sorting
7994 (defun org-sort (with-case)
7995 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
7996 Optional argument WITH-CASE means sort case-sensitively."
7997 (interactive "P")
7998 (cond
7999 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8000 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8002 (org-call-with-arg 'org-sort-entries with-case))))
8004 (defun org-sort-remove-invisible (s)
8005 (remove-text-properties 0 (length s) org-rm-props s)
8006 (while (string-match org-bracket-link-regexp s)
8007 (setq s (replace-match (if (match-end 2)
8008 (match-string 3 s)
8009 (match-string 1 s)) t t s)))
8012 (defvar org-priority-regexp) ; defined later in the file
8014 (defvar org-after-sorting-entries-or-items-hook nil
8015 "Hook that is run after a bunch of entries or items have been sorted.
8016 When children are sorted, the cursor is in the parent line when this
8017 hook gets called. When a region or a plain list is sorted, the cursor
8018 will be in the first entry of the sorted region/list.")
8020 (defun org-sort-entries
8021 (&optional with-case sorting-type getkey-func compare-func property)
8022 "Sort entries on a certain level of an outline tree.
8023 If there is an active region, the entries in the region are sorted.
8024 Else, if the cursor is before the first entry, sort the top-level items.
8025 Else, the children of the entry at point are sorted.
8027 Sorting can be alphabetically, numerically, by date/time as given by
8028 a time stamp, by a property or by priority.
8030 The command prompts for the sorting type unless it has been given to the
8031 function through the SORTING-TYPE argument, which needs to be a character,
8032 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8033 precise meaning of each character:
8035 n Numerically, by converting the beginning of the entry/item to a number.
8036 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8037 o By order of TODO keywords.
8038 t By date/time, either the first active time stamp in the entry, or, if
8039 none exist, by the first inactive one.
8040 s By the scheduled date/time.
8041 d By deadline date/time.
8042 c By creation time, which is assumed to be the first inactive time stamp
8043 at the beginning of a line.
8044 p By priority according to the cookie.
8045 r By the value of a property.
8047 Capital letters will reverse the sort order.
8049 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8050 called with point at the beginning of the record. It must return either
8051 a string or a number that should serve as the sorting key for that record.
8053 Comparing entries ignores case by default. However, with an optional argument
8054 WITH-CASE, the sorting considers case as well."
8055 (interactive "P")
8056 (let ((case-func (if with-case 'identity 'downcase))
8057 (cmstr
8058 ;; The clock marker is lost when using `sort-subr', let's
8059 ;; store the clocking string.
8060 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8061 (save-excursion
8062 (goto-char org-clock-marker)
8063 (looking-back "^.*") (match-string-no-properties 0))))
8064 start beg end stars re re2
8065 txt what tmp)
8066 ;; Find beginning and end of region to sort
8067 (cond
8068 ((org-region-active-p)
8069 ;; we will sort the region
8070 (setq end (region-end)
8071 what "region")
8072 (goto-char (region-beginning))
8073 (if (not (org-at-heading-p)) (outline-next-heading))
8074 (setq start (point)))
8075 ((or (org-at-heading-p)
8076 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8077 ;; we will sort the children of the current headline
8078 (org-back-to-heading)
8079 (setq start (point)
8080 end (progn (org-end-of-subtree t t)
8081 (or (bolp) (insert "\n"))
8082 (org-back-over-empty-lines)
8083 (point))
8084 what "children")
8085 (goto-char start)
8086 (show-subtree)
8087 (outline-next-heading))
8089 ;; we will sort the top-level entries in this file
8090 (goto-char (point-min))
8091 (or (org-at-heading-p) (outline-next-heading))
8092 (setq start (point))
8093 (goto-char (point-max))
8094 (beginning-of-line 1)
8095 (when (looking-at ".*?\\S-")
8096 ;; File ends in a non-white line
8097 (end-of-line 1)
8098 (insert "\n"))
8099 (setq end (point-max))
8100 (setq what "top-level")
8101 (goto-char start)
8102 (show-all)))
8104 (setq beg (point))
8105 (if (>= beg end) (error "Nothing to sort"))
8107 (looking-at "\\(\\*+\\)")
8108 (setq stars (match-string 1)
8109 re (concat "^" (regexp-quote stars) " +")
8110 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8111 txt (buffer-substring beg end))
8112 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8113 (if (and (not (equal stars "*")) (string-match re2 txt))
8114 (error "Region to sort contains a level above the first entry"))
8116 (unless sorting-type
8117 (message
8118 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8119 [t]ime [s]cheduled [d]eadline [c]reated
8120 A/N/P/R/O/F/T/S/D/C means reversed:"
8121 what)
8122 (setq sorting-type (read-char-exclusive))
8124 (and (= (downcase sorting-type) ?f)
8125 (setq getkey-func
8126 (org-icompleting-read "Sort using function: "
8127 obarray 'fboundp t nil nil))
8128 (setq getkey-func (intern getkey-func)))
8130 (and (= (downcase sorting-type) ?r)
8131 (setq property
8132 (org-icompleting-read "Property: "
8133 (mapcar 'list (org-buffer-property-keys t))
8134 nil t))))
8136 (message "Sorting entries...")
8138 (save-restriction
8139 (narrow-to-region start end)
8140 (let ((dcst (downcase sorting-type))
8141 (case-fold-search nil)
8142 (now (current-time)))
8143 (sort-subr
8144 (/= dcst sorting-type)
8145 ;; This function moves to the beginning character of the "record" to
8146 ;; be sorted.
8147 (lambda nil
8148 (if (re-search-forward re nil t)
8149 (goto-char (match-beginning 0))
8150 (goto-char (point-max))))
8151 ;; This function moves to the last character of the "record" being
8152 ;; sorted.
8153 (lambda nil
8154 (save-match-data
8155 (condition-case nil
8156 (outline-forward-same-level 1)
8157 (error
8158 (goto-char (point-max))))))
8159 ;; This function returns the value that gets sorted against.
8160 (lambda nil
8161 (cond
8162 ((= dcst ?n)
8163 (if (looking-at org-complex-heading-regexp)
8164 (string-to-number (match-string 4))
8165 nil))
8166 ((= dcst ?a)
8167 (if (looking-at org-complex-heading-regexp)
8168 (funcall case-func (match-string 4))
8169 nil))
8170 ((= dcst ?t)
8171 (let ((end (save-excursion (outline-next-heading) (point))))
8172 (if (or (re-search-forward org-ts-regexp end t)
8173 (re-search-forward org-ts-regexp-both end t))
8174 (org-time-string-to-seconds (match-string 0))
8175 (org-float-time now))))
8176 ((= dcst ?c)
8177 (let ((end (save-excursion (outline-next-heading) (point))))
8178 (if (re-search-forward
8179 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8180 end t)
8181 (org-time-string-to-seconds (match-string 0))
8182 (org-float-time now))))
8183 ((= dcst ?s)
8184 (let ((end (save-excursion (outline-next-heading) (point))))
8185 (if (re-search-forward org-scheduled-time-regexp end t)
8186 (org-time-string-to-seconds (match-string 1))
8187 (org-float-time now))))
8188 ((= dcst ?d)
8189 (let ((end (save-excursion (outline-next-heading) (point))))
8190 (if (re-search-forward org-deadline-time-regexp end t)
8191 (org-time-string-to-seconds (match-string 1))
8192 (org-float-time now))))
8193 ((= dcst ?p)
8194 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8195 (string-to-char (match-string 2))
8196 org-default-priority))
8197 ((= dcst ?r)
8198 (or (org-entry-get nil property) ""))
8199 ((= dcst ?o)
8200 (if (looking-at org-complex-heading-regexp)
8201 (- 9999 (length (member (match-string 2)
8202 org-todo-keywords-1)))))
8203 ((= dcst ?f)
8204 (if getkey-func
8205 (progn
8206 (setq tmp (funcall getkey-func))
8207 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8208 tmp)
8209 (error "Invalid key function `%s'" getkey-func)))
8210 (t (error "Invalid sorting type `%c'" sorting-type))))
8212 (cond
8213 ((= dcst ?a) 'string<)
8214 ((= dcst ?f) compare-func)
8215 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8216 (run-hooks 'org-after-sorting-entries-or-items-hook)
8217 ;; Reset the clock marker if needed
8218 (when cmstr
8219 (save-excursion
8220 (goto-char start)
8221 (search-forward cmstr nil t)
8222 (move-marker org-clock-marker (point))))
8223 (message "Sorting entries...done")))
8225 (defun org-do-sort (table what &optional with-case sorting-type)
8226 "Sort TABLE of WHAT according to SORTING-TYPE.
8227 The user will be prompted for the SORTING-TYPE if the call to this
8228 function does not specify it. WHAT is only for the prompt, to indicate
8229 what is being sorted. The sorting key will be extracted from
8230 the car of the elements of the table.
8231 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8232 (unless sorting-type
8233 (message
8234 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8235 what)
8236 (setq sorting-type (read-char-exclusive)))
8237 (let ((dcst (downcase sorting-type))
8238 extractfun comparefun)
8239 ;; Define the appropriate functions
8240 (cond
8241 ((= dcst ?n)
8242 (setq extractfun 'string-to-number
8243 comparefun (if (= dcst sorting-type) '< '>)))
8244 ((= dcst ?a)
8245 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8246 (lambda(x) (downcase (org-sort-remove-invisible x))))
8247 comparefun (if (= dcst sorting-type)
8248 'string<
8249 (lambda (a b) (and (not (string< a b))
8250 (not (string= a b)))))))
8251 ((= dcst ?t)
8252 (setq extractfun
8253 (lambda (x)
8254 (if (or (string-match org-ts-regexp x)
8255 (string-match org-ts-regexp-both x))
8256 (org-float-time
8257 (org-time-string-to-time (match-string 0 x)))
8259 comparefun (if (= dcst sorting-type) '< '>)))
8260 (t (error "Invalid sorting type `%c'" sorting-type)))
8262 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8263 table)
8264 (lambda (a b) (funcall comparefun (car a) (car b))))))
8267 ;;; The orgstruct minor mode
8269 ;; Define a minor mode which can be used in other modes in order to
8270 ;; integrate the org-mode structure editing commands.
8272 ;; This is really a hack, because the org-mode structure commands use
8273 ;; keys which normally belong to the major mode. Here is how it
8274 ;; works: The minor mode defines all the keys necessary to operate the
8275 ;; structure commands, but wraps the commands into a function which
8276 ;; tests if the cursor is currently at a headline or a plain list
8277 ;; item. If that is the case, the structure command is used,
8278 ;; temporarily setting many Org-mode variables like regular
8279 ;; expressions for filling etc. However, when any of those keys is
8280 ;; used at a different location, function uses `key-binding' to look
8281 ;; up if the key has an associated command in another currently active
8282 ;; keymap (minor modes, major mode, global), and executes that
8283 ;; command. There might be problems if any of the keys is otherwise
8284 ;; used as a prefix key.
8286 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8287 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8288 ;; addresses this by checking explicitly for both bindings.
8290 (defvar orgstruct-mode-map (make-sparse-keymap)
8291 "Keymap for the minor `orgstruct-mode'.")
8293 (defvar org-local-vars nil
8294 "List of local variables, for use by `orgstruct-mode'.")
8296 ;;;###autoload
8297 (define-minor-mode orgstruct-mode
8298 "Toggle the minor mode `orgstruct-mode'.
8299 This mode is for using Org-mode structure commands in other
8300 modes. The following keys behave as if Org-mode were active, if
8301 the cursor is on a headline, or on a plain list item (both as
8302 defined by Org-mode).
8304 M-up Move entry/item up
8305 M-down Move entry/item down
8306 M-left Promote
8307 M-right Demote
8308 M-S-up Move entry/item up
8309 M-S-down Move entry/item down
8310 M-S-left Promote subtree
8311 M-S-right Demote subtree
8312 M-q Fill paragraph and items like in Org-mode
8313 C-c ^ Sort entries
8314 C-c - Cycle list bullet
8315 TAB Cycle item visibility
8316 M-RET Insert new heading/item
8317 S-M-RET Insert new TODO heading / Checkbox item
8318 C-c C-c Set tags / toggle checkbox"
8319 nil " OrgStruct" nil
8320 (org-load-modules-maybe)
8321 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8323 ;;;###autoload
8324 (defun turn-on-orgstruct ()
8325 "Unconditionally turn on `orgstruct-mode'."
8326 (orgstruct-mode 1))
8328 (defvar org-fb-vars nil)
8329 (make-variable-buffer-local 'org-fb-vars)
8330 (defun orgstruct++-mode (&optional arg)
8331 "Toggle `orgstruct-mode', the enhanced version of it.
8332 In addition to setting orgstruct-mode, this also exports all
8333 indentation and autofilling variables from org-mode into the
8334 buffer. It will also recognize item context in multiline items."
8335 (interactive "P")
8336 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8337 (if (< arg 1)
8338 (progn (orgstruct-mode -1)
8339 (mapc (lambda(v)
8340 (org-set-local (car v)
8341 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8342 org-fb-vars))
8343 (orgstruct-mode 1)
8344 (setq org-fb-vars nil)
8345 (let (var val)
8346 (mapc
8347 (lambda (x)
8348 (when (string-match
8349 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8350 (symbol-name (car x)))
8351 (setq var (car x) val (nth 1 x))
8352 (push (list var `(quote ,(eval var))) org-fb-vars)
8353 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8354 org-local-vars)
8355 (org-set-local 'orgstruct-is-++ t))))
8357 (defvar orgstruct-is-++ nil
8358 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8359 (make-variable-buffer-local 'orgstruct-is-++)
8361 ;;;###autoload
8362 (defun turn-on-orgstruct++ ()
8363 "Unconditionally turn on `orgstruct++-mode'."
8364 (orgstruct++-mode 1))
8366 (defun orgstruct-error ()
8367 "Error when there is no default binding for a structure key."
8368 (interactive)
8369 (error "This key has no function outside structure elements"))
8371 (defun orgstruct-setup ()
8372 "Setup orgstruct keymaps."
8373 (let ((nfunc 0)
8374 (bindings
8375 (list
8376 '([(meta up)] org-metaup)
8377 '([(meta down)] org-metadown)
8378 '([(meta left)] org-metaleft)
8379 '([(meta right)] org-metaright)
8380 '([(meta shift up)] org-shiftmetaup)
8381 '([(meta shift down)] org-shiftmetadown)
8382 '([(meta shift left)] org-shiftmetaleft)
8383 '([(meta shift right)] org-shiftmetaright)
8384 '([?\e (up)] org-metaup)
8385 '([?\e (down)] org-metadown)
8386 '([?\e (left)] org-metaleft)
8387 '([?\e (right)] org-metaright)
8388 '([?\e (shift up)] org-shiftmetaup)
8389 '([?\e (shift down)] org-shiftmetadown)
8390 '([?\e (shift left)] org-shiftmetaleft)
8391 '([?\e (shift right)] org-shiftmetaright)
8392 '([(shift up)] org-shiftup)
8393 '([(shift down)] org-shiftdown)
8394 '([(shift left)] org-shiftleft)
8395 '([(shift right)] org-shiftright)
8396 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8397 '("\M-q" fill-paragraph)
8398 '("\C-c^" org-sort)
8399 '("\C-c-" org-cycle-list-bullet)))
8400 elt key fun cmd)
8401 (while (setq elt (pop bindings))
8402 (setq nfunc (1+ nfunc))
8403 (setq key (org-key (car elt))
8404 fun (nth 1 elt)
8405 cmd (orgstruct-make-binding fun nfunc key))
8406 (org-defkey orgstruct-mode-map key cmd))
8408 ;; Prevent an error for users who forgot to make autoloads
8409 (require 'org-element)
8411 ;; Special treatment needed for TAB and RET
8412 (org-defkey orgstruct-mode-map [(tab)]
8413 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8414 (org-defkey orgstruct-mode-map "\C-i"
8415 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8417 (org-defkey orgstruct-mode-map "\M-\C-m"
8418 (orgstruct-make-binding 'org-insert-heading 105
8419 "\M-\C-m" [(meta return)]))
8420 (org-defkey orgstruct-mode-map [(meta return)]
8421 (orgstruct-make-binding 'org-insert-heading 106
8422 [(meta return)] "\M-\C-m"))
8424 (org-defkey orgstruct-mode-map [(shift meta return)]
8425 (orgstruct-make-binding 'org-insert-todo-heading 107
8426 [(meta return)] "\M-\C-m"))
8428 (org-defkey orgstruct-mode-map "\e\C-m"
8429 (orgstruct-make-binding 'org-insert-heading 108
8430 "\e\C-m" [?\e (return)]))
8431 (org-defkey orgstruct-mode-map [?\e (return)]
8432 (orgstruct-make-binding 'org-insert-heading 109
8433 [?\e (return)] "\e\C-m"))
8434 (org-defkey orgstruct-mode-map [?\e (shift return)]
8435 (orgstruct-make-binding 'org-insert-todo-heading 110
8436 [?\e (return)] "\e\C-m"))
8438 (unless org-local-vars
8439 (setq org-local-vars (org-get-local-variables)))
8443 (defun orgstruct-make-binding (fun n &rest keys)
8444 "Create a function for binding in the structure minor mode.
8445 FUN is the command to call inside a table. N is used to create a unique
8446 command name. KEYS are keys that should be checked in for a command
8447 to execute outside of tables."
8448 (eval
8449 (list 'defun
8450 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8451 '(arg)
8452 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8453 "Outside of structure, run the binding of `"
8454 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8455 "'.")
8456 '(interactive "p")
8457 (list 'if
8458 `(org-context-p 'headline 'item
8459 (and orgstruct-is-++
8460 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8461 'item-body))
8462 (list 'org-run-like-in-org-mode (list 'quote fun))
8463 (list 'let '(orgstruct-mode)
8464 (list 'call-interactively
8465 (append '(or)
8466 (mapcar (lambda (k)
8467 (list 'key-binding k))
8468 keys)
8469 '('orgstruct-error))))))))
8471 (defun org-contextualize-keys (alist contexts)
8472 "Return valid elements in ALIST depending on CONTEXTS.
8474 `org-agenda-custom-commands' or `org-capture-templates' are the
8475 values used for ALIST, and `org-agenda-custom-commands-contexts'
8476 or `org-capture-templates-contexts' are the associated contexts
8477 definitions."
8478 (let ((contexts
8479 ;; normalize contexts
8480 (mapcar
8481 (lambda(c) (cond ((listp (cadr c))
8482 (list (car c) (car c) (cadr c)))
8483 ((string= "" (cadr c))
8484 (list (car c) (car c) (caddr c)))
8485 (t c))) contexts))
8486 (a alist) c r s)
8487 ;; loop over all commands or templates
8488 (while (setq c (pop a))
8489 (let (vrules repl)
8490 (cond
8491 ((not (assoc (car c) contexts))
8492 (push c r))
8493 ((and (assoc (car c) contexts)
8494 (setq vrules (org-contextualize-validate-key
8495 (car c) contexts)))
8496 (mapc (lambda (vr)
8497 (when (not (equal (car vr) (cadr vr)))
8498 (setq repl vr))) vrules)
8499 (if (not repl) (push c r)
8500 (push (cadr repl) s)
8501 (push
8502 (cons (car c)
8503 (cdr (or (assoc (cadr repl) alist)
8504 (error "Undefined key `%s' as contextual replacement for `%s'"
8505 (cadr repl) (car c)))))
8506 r))))))
8507 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8508 (delq
8510 (delete-dups
8511 (mapcar (lambda (x)
8512 (let ((tpl (car x)))
8513 (when (not (delq
8515 (mapcar (lambda(y)
8516 (equal y tpl)) s))) x)))
8517 (reverse r))))))
8519 (defun org-contextualize-validate-key (key contexts)
8520 "Check CONTEXTS for agenda or capture KEY."
8521 (let (r rr res)
8522 (while (setq r (pop contexts))
8523 (mapc
8524 (lambda (rr)
8525 (when
8526 (and (equal key (car r))
8527 (if (functionp rr) (funcall rr)
8528 (or (and (eq (car rr) 'in-file)
8529 (buffer-file-name)
8530 (string-match (cdr rr) (buffer-file-name)))
8531 (and (eq (car rr) 'in-mode)
8532 (string-match (cdr rr) (symbol-name major-mode)))
8533 (when (and (eq (car rr) 'not-in-file)
8534 (buffer-file-name))
8535 (not (string-match (cdr rr) (buffer-file-name))))
8536 (when (eq (car rr) 'not-in-mode)
8537 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8538 (push r res)))
8539 (car (last r))))
8540 (delete-dups (delq nil res))))
8542 (defun org-context-p (&rest contexts)
8543 "Check if local context is any of CONTEXTS.
8544 Possible values in the list of contexts are `table', `headline', and `item'."
8545 (let ((pos (point)))
8546 (goto-char (point-at-bol))
8547 (prog1 (or (and (memq 'table contexts)
8548 (looking-at "[ \t]*|"))
8549 (and (memq 'headline contexts)
8550 (looking-at org-outline-regexp))
8551 (and (memq 'item contexts)
8552 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8553 (and (memq 'item-body contexts)
8554 (org-in-item-p)))
8555 (goto-char pos))))
8557 (defun org-get-local-variables ()
8558 "Return a list of all local variables in an Org mode buffer."
8559 (let (varlist)
8560 (with-current-buffer (get-buffer-create "*Org tmp*")
8561 (erase-buffer)
8562 (org-mode)
8563 (setq varlist (buffer-local-variables)))
8564 (kill-buffer "*Org tmp*")
8565 (delq nil
8566 (mapcar
8567 (lambda (x)
8568 (setq x
8569 (if (symbolp x)
8570 (list x)
8571 (list (car x) (list 'quote (cdr x)))))
8572 (if (string-match
8573 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8574 (symbol-name (car x)))
8575 x nil))
8576 varlist))))
8578 (defun org-clone-local-variables (from-buffer &optional regexp)
8579 "Clone local variables from FROM-BUFFER.
8580 Optional argument REGEXP selects variables to clone."
8581 (mapc
8582 (lambda (pair)
8583 (and (symbolp (car pair))
8584 (or (null regexp)
8585 (string-match regexp (symbol-name (car pair))))
8586 (set (make-local-variable (car pair))
8587 (cdr pair))))
8588 (buffer-local-variables from-buffer)))
8590 ;;;###autoload
8591 (defun org-run-like-in-org-mode (cmd)
8592 "Run a command, pretending that the current buffer is in Org-mode.
8593 This will temporarily bind local variables that are typically bound in
8594 Org-mode to the values they have in Org-mode, and then interactively
8595 call CMD."
8596 (org-load-modules-maybe)
8597 (unless org-local-vars
8598 (setq org-local-vars (org-get-local-variables)))
8599 (eval (list 'let org-local-vars
8600 (list 'call-interactively (list 'quote cmd)))))
8602 ;;;; Archiving
8604 (defun org-get-category (&optional pos force-refresh)
8605 "Get the category applying to position POS."
8606 (save-match-data
8607 (if force-refresh (org-refresh-category-properties))
8608 (let ((pos (or pos (point))))
8609 (or (get-text-property pos 'org-category)
8610 (progn (org-refresh-category-properties)
8611 (get-text-property pos 'org-category))))))
8613 (defun org-refresh-category-properties ()
8614 "Refresh category text properties in the buffer."
8615 (let ((case-fold-search t)
8616 (inhibit-read-only t)
8617 (def-cat (cond
8618 ((null org-category)
8619 (if buffer-file-name
8620 (file-name-sans-extension
8621 (file-name-nondirectory buffer-file-name))
8622 "???"))
8623 ((symbolp org-category) (symbol-name org-category))
8624 (t org-category)))
8625 beg end cat pos optionp)
8626 (org-unmodified
8627 (save-excursion
8628 (save-restriction
8629 (widen)
8630 (goto-char (point-min))
8631 (put-text-property (point) (point-max) 'org-category def-cat)
8632 (while (re-search-forward
8633 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8634 (setq pos (match-end 0)
8635 optionp (equal (char-after (match-beginning 0)) ?#)
8636 cat (org-trim (match-string 2)))
8637 (if optionp
8638 (setq beg (point-at-bol) end (point-max))
8639 (org-back-to-heading t)
8640 (setq beg (point) end (org-end-of-subtree t t)))
8641 (put-text-property beg end 'org-category cat)
8642 (put-text-property beg end 'org-category-position beg)
8643 (goto-char pos)))))))
8645 (defun org-refresh-properties (dprop tprop)
8646 "Refresh buffer text properties.
8647 DPROP is the drawer property and TPROP is the corresponding text
8648 property to set."
8649 (let ((case-fold-search t)
8650 (inhibit-read-only t) p)
8651 (org-unmodified
8652 (save-excursion
8653 (save-restriction
8654 (widen)
8655 (goto-char (point-min))
8656 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
8657 (setq p (org-match-string-no-properties 1))
8658 (save-excursion
8659 (org-back-to-heading t)
8660 (put-text-property
8661 (point-at-bol) (point-at-eol) tprop p))))))))
8664 ;;;; Link Stuff
8666 ;;; Link abbreviations
8668 (defun org-link-expand-abbrev (link)
8669 "Apply replacements as defined in `org-link-abbrev-alist'."
8670 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8671 (let* ((key (match-string 1 link))
8672 (as (or (assoc key org-link-abbrev-alist-local)
8673 (assoc key org-link-abbrev-alist)))
8674 (tag (and (match-end 2) (match-string 3 link)))
8675 rpl)
8676 (if (not as)
8677 link
8678 (setq rpl (cdr as))
8679 (cond
8680 ((symbolp rpl) (funcall rpl tag))
8681 ((string-match "%(\\([^)]+\\))" rpl)
8682 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8683 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8684 ((string-match "%h" rpl)
8685 (replace-match (url-hexify-string (or tag "")) t t rpl))
8686 (t (concat rpl tag)))))
8687 link))
8689 ;;; Storing and inserting links
8691 (defvar org-insert-link-history nil
8692 "Minibuffer history for links inserted with `org-insert-link'.")
8694 (defvar org-stored-links nil
8695 "Contains the links stored with `org-store-link'.")
8697 (defvar org-store-link-plist nil
8698 "Plist with info about the most recently link created with `org-store-link'.")
8700 (defvar org-link-protocols nil
8701 "Link protocols added to Org-mode using `org-add-link-type'.")
8703 (defvar org-store-link-functions nil
8704 "List of functions that are called to create and store a link.
8705 Each function will be called in turn until one returns a non-nil
8706 value. Each function should check if it is responsible for creating
8707 this link (for example by looking at the major mode).
8708 If not, it must exit and return nil.
8709 If yes, it should return a non-nil value after a calling
8710 `org-store-link-props' with a list of properties and values.
8711 Special properties are:
8713 :type The link prefix, like \"http\". This must be given.
8714 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8715 This is obligatory as well.
8716 :description Optional default description for the second pair
8717 of brackets in an Org-mode link. The user can still change
8718 this when inserting this link into an Org-mode buffer.
8720 In addition to these, any additional properties can be specified
8721 and then used in capture templates.")
8723 (defun org-add-link-type (type &optional follow export)
8724 "Add TYPE to the list of `org-link-types'.
8725 Re-compute all regular expressions depending on `org-link-types'
8727 FOLLOW and EXPORT are two functions.
8729 FOLLOW should take the link path as the single argument and do whatever
8730 is necessary to follow the link, for example find a file or display
8731 a mail message.
8733 EXPORT should format the link path for export to one of the export formats.
8734 It should be a function accepting three arguments:
8736 path the path of the link, the text after the prefix (like \"http:\")
8737 desc the description of the link, if any, or a description added by
8738 org-export-normalize-links if there is none
8739 format the export format, a symbol like `html' or `latex' or `ascii'..
8741 The function may use the FORMAT information to return different values
8742 depending on the format. The return value will be put literally into
8743 the exported file. If the return value is nil, this means Org should
8744 do what it normally does with links which do not have EXPORT defined.
8746 Org-mode has a built-in default for exporting links. If you are happy with
8747 this default, there is no need to define an export function for the link
8748 type. For a simple example of an export function, see `org-bbdb.el'."
8749 (add-to-list 'org-link-types type t)
8750 (org-make-link-regexps)
8751 (if (assoc type org-link-protocols)
8752 (setcdr (assoc type org-link-protocols) (list follow export))
8753 (push (list type follow export) org-link-protocols)))
8755 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8756 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
8758 ;;;###autoload
8759 (defun org-store-link (arg)
8760 "\\<org-mode-map>Store an org-link to the current location.
8761 This link is added to `org-stored-links' and can later be inserted
8762 into an org-buffer with \\[org-insert-link].
8764 For some link types, a prefix arg is interpreted:
8765 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8766 For file links, arg negates `org-context-in-file-links'."
8767 (interactive "P")
8768 (org-load-modules-maybe)
8769 (setq org-store-link-plist nil) ; reset
8770 (org-with-limited-levels
8771 (let (link cpltxt desc description search txt custom-id agenda-link)
8772 (cond
8774 ((run-hook-with-args-until-success 'org-store-link-functions)
8775 (setq link (plist-get org-store-link-plist :link)
8776 desc (or (plist-get org-store-link-plist :description) link)))
8778 ((org-src-edit-buffer-p)
8779 (let (label gc)
8780 (while (or (not label)
8781 (save-excursion
8782 (save-restriction
8783 (widen)
8784 (goto-char (point-min))
8785 (re-search-forward
8786 (regexp-quote (format org-coderef-label-format label))
8787 nil t))))
8788 (when label (message "Label exists already") (sit-for 2))
8789 (setq label (read-string "Code line label: " label)))
8790 (end-of-line 1)
8791 (setq link (format org-coderef-label-format label))
8792 (setq gc (- 79 (length link)))
8793 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8794 (insert link)
8795 (setq link (concat "(" label ")") desc nil)))
8797 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8798 ;; We are in the agenda, link to referenced location
8799 (let ((m (or (get-text-property (point) 'org-hd-marker)
8800 (get-text-property (point) 'org-marker))))
8801 (when m
8802 (org-with-point-at m
8803 (setq agenda-link
8804 (if (org-called-interactively-p 'any)
8805 (call-interactively 'org-store-link)
8806 (org-store-link nil)))))))
8808 ((eq major-mode 'calendar-mode)
8809 (let ((cd (calendar-cursor-to-date)))
8810 (setq link
8811 (format-time-string
8812 (car org-time-stamp-formats)
8813 (apply 'encode-time
8814 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8815 nil nil nil))))
8816 (org-store-link-props :type "calendar" :date cd)))
8818 ((eq major-mode 'help-mode)
8819 (setq link (concat "help:" (save-excursion
8820 (goto-char (point-min))
8821 (looking-at "^[^ ]+")
8822 (match-string 0))))
8823 (org-store-link-props :type "help"))
8825 ((eq major-mode 'w3-mode)
8826 (setq cpltxt (if (and (buffer-name)
8827 (not (string-match "Untitled" (buffer-name))))
8828 (buffer-name)
8829 (url-view-url t))
8830 link (url-view-url t))
8831 (org-store-link-props :type "w3" :url (url-view-url t)))
8833 ((eq major-mode 'w3m-mode)
8834 (setq cpltxt (or w3m-current-title w3m-current-url)
8835 link w3m-current-url)
8836 (org-store-link-props :type "w3m" :url (url-view-url t)))
8838 ((setq search (run-hook-with-args-until-success
8839 'org-create-file-search-functions))
8840 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8841 "::" search))
8842 (setq cpltxt (or description link)))
8844 ((eq major-mode 'image-mode)
8845 (setq cpltxt (concat "file:"
8846 (abbreviate-file-name buffer-file-name))
8847 link cpltxt)
8848 (org-store-link-props :type "image" :file buffer-file-name))
8850 ((eq major-mode 'dired-mode)
8851 ;; link to the file in the current line
8852 (let ((file (dired-get-filename nil t)))
8853 (setq file (if file
8854 (abbreviate-file-name
8855 (expand-file-name (dired-get-filename nil t)))
8856 ;; otherwise, no file so use current directory.
8857 default-directory))
8858 (setq cpltxt (concat "file:" file)
8859 link cpltxt)))
8861 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8862 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8863 (cond
8864 ((org-in-regexp "<<\\(.*?\\)>>")
8865 (setq cpltxt
8866 (concat "file:"
8867 (abbreviate-file-name
8868 (buffer-file-name (buffer-base-buffer)))
8869 "::" (match-string 1))
8870 link cpltxt))
8871 ((and (featurep 'org-id)
8872 (or (eq org-id-link-to-org-use-id t)
8873 (and (org-called-interactively-p 'any)
8874 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
8875 (and (eq org-id-link-to-org-use-id
8876 'create-if-interactive-and-no-custom-id)
8877 (not custom-id))))
8878 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
8879 ;; We can make a link using the ID.
8880 (setq link (condition-case nil
8881 (prog1 (org-id-store-link)
8882 (setq desc (plist-get org-store-link-plist :description)))
8883 (error
8884 ;; probably before first headline, link to file only
8885 (concat "file:"
8886 (abbreviate-file-name
8887 (buffer-file-name (buffer-base-buffer))))))))
8889 ;; Just link to current headline
8890 (setq cpltxt (concat "file:"
8891 (abbreviate-file-name
8892 (buffer-file-name (buffer-base-buffer)))))
8893 ;; Add a context search string
8894 (when (org-xor org-context-in-file-links arg)
8895 (setq txt (cond
8896 ((org-at-heading-p) nil)
8897 ((org-region-active-p)
8898 (buffer-substring (region-beginning) (region-end)))))
8899 (when (or (null txt) (string-match "\\S-" txt))
8900 (setq cpltxt
8901 (concat cpltxt "::"
8902 (condition-case nil
8903 (org-make-org-heading-search-string txt)
8904 (error "")))
8905 desc (or (nth 4 (ignore-errors
8906 (org-heading-components))) "NONE"))))
8907 (if (string-match "::\\'" cpltxt)
8908 (setq cpltxt (substring cpltxt 0 -2)))
8909 (setq link cpltxt))))
8911 ((buffer-file-name (buffer-base-buffer))
8912 ;; Just link to this file here.
8913 (setq cpltxt (concat "file:"
8914 (abbreviate-file-name
8915 (buffer-file-name (buffer-base-buffer)))))
8916 ;; Add a context string
8917 (when (org-xor org-context-in-file-links arg)
8918 (setq txt (if (org-region-active-p)
8919 (buffer-substring (region-beginning) (region-end))
8920 (buffer-substring (point-at-bol) (point-at-eol))))
8921 ;; Only use search option if there is some text.
8922 (when (string-match "\\S-" txt)
8923 (setq cpltxt
8924 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8925 desc "NONE")))
8926 (setq link cpltxt))
8928 ((org-called-interactively-p 'interactive)
8929 (error "Cannot link to a buffer which is not visiting a file"))
8931 (t (setq link nil)))
8933 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8934 (setq link (or link cpltxt)
8935 desc (or desc cpltxt))
8936 (if (equal desc "NONE") (setq desc nil))
8938 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8939 (progn
8940 (setq org-stored-links
8941 (cons (list link desc) org-stored-links))
8942 (message "Stored: %s" (or desc link))
8943 (when custom-id
8944 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8945 "::#" custom-id))
8946 (setq org-stored-links
8947 (cons (list link desc) org-stored-links))))
8948 (or agenda-link (and link (org-make-link-string link desc)))))))
8950 (defun org-store-link-props (&rest plist)
8951 "Store link properties, extract names and addresses."
8952 (let (x adr)
8953 (when (setq x (plist-get plist :from))
8954 (setq adr (mail-extract-address-components x))
8955 (setq plist (plist-put plist :fromname (car adr)))
8956 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8957 (when (setq x (plist-get plist :to))
8958 (setq adr (mail-extract-address-components x))
8959 (setq plist (plist-put plist :toname (car adr)))
8960 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8961 (let ((from (plist-get plist :from))
8962 (to (plist-get plist :to)))
8963 (when (and from to org-from-is-user-regexp)
8964 (setq plist
8965 (plist-put plist :fromto
8966 (if (string-match org-from-is-user-regexp from)
8967 (concat "to %t")
8968 (concat "from %f"))))))
8969 (setq org-store-link-plist plist))
8971 (defun org-add-link-props (&rest plist)
8972 "Add these properties to the link property list."
8973 (let (key value)
8974 (while plist
8975 (setq key (pop plist) value (pop plist))
8976 (setq org-store-link-plist
8977 (plist-put org-store-link-plist key value)))))
8979 (defun org-email-link-description (&optional fmt)
8980 "Return the description part of an email link.
8981 This takes information from `org-store-link-plist' and formats it
8982 according to FMT (default from `org-email-link-description-format')."
8983 (setq fmt (or fmt org-email-link-description-format))
8984 (let* ((p org-store-link-plist)
8985 (to (plist-get p :toaddress))
8986 (from (plist-get p :fromaddress))
8987 (table
8988 (list
8989 (cons "%c" (plist-get p :fromto))
8990 (cons "%F" (plist-get p :from))
8991 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8992 (cons "%T" (plist-get p :to))
8993 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8994 (cons "%s" (plist-get p :subject))
8995 (cons "%d" (plist-get p :date))
8996 (cons "%m" (plist-get p :message-id)))))
8997 (when (string-match "%c" fmt)
8998 ;; Check if the user wrote this message
8999 (if (and org-from-is-user-regexp from to
9000 (save-match-data (string-match org-from-is-user-regexp from)))
9001 (setq fmt (replace-match "to %t" t t fmt))
9002 (setq fmt (replace-match "from %f" t t fmt))))
9003 (org-replace-escapes fmt table)))
9005 (defun org-make-org-heading-search-string (&optional string heading)
9006 "Make search string for STRING or current headline."
9007 (interactive)
9008 (let ((s (or string (org-get-heading)))
9009 (lines org-context-in-file-links))
9010 (unless (and string (not heading))
9011 ;; We are using a headline, clean up garbage in there.
9012 (if (string-match org-todo-regexp s)
9013 (setq s (replace-match "" t t s)))
9014 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
9015 (setq s (replace-match "" t t s)))
9016 (setq s (org-trim s))
9017 (if (string-match (concat "^\\(" org-quote-string "\\|"
9018 org-comment-string "\\)") s)
9019 (setq s (replace-match "" t t s)))
9020 (while (string-match org-ts-regexp s)
9021 (setq s (replace-match "" t t s))))
9022 (or string (setq s (concat "*" s))) ; Add * for headlines
9023 (when (and string (integerp lines) (> lines 0))
9024 (let ((slines (org-split-string s "\n")))
9025 (when (< lines (length slines))
9026 (setq s (mapconcat
9027 'identity
9028 (reverse (nthcdr (- (length slines) lines)
9029 (reverse slines))) "\n")))))
9030 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9032 (defun org-make-link-string (link &optional description)
9033 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9034 (unless (string-match "\\S-" link)
9035 (error "Empty link"))
9036 (when (and description
9037 (stringp description)
9038 (not (string-match "\\S-" description)))
9039 (setq description nil))
9040 (when (stringp description)
9041 ;; Remove brackets from the description, they are fatal.
9042 (while (string-match "\\[" description)
9043 (setq description (replace-match "{" t t description)))
9044 (while (string-match "\\]" description)
9045 (setq description (replace-match "}" t t description))))
9046 (when (equal link description)
9047 ;; No description needed, it is identical
9048 (setq description nil))
9049 (when (and (not description)
9050 (not (string-match (org-image-file-name-regexp) link))
9051 (not (equal link (org-link-escape link))))
9052 (setq description (org-extract-attributes link)))
9053 (setq link
9054 (cond ((string-match (org-image-file-name-regexp) link) link)
9055 ((string-match org-link-types-re link)
9056 (concat (match-string 1 link)
9057 (org-link-escape (substring link (match-end 1)))))
9058 (t (org-link-escape link))))
9059 (concat "[[" link "]"
9060 (if description (concat "[" description "]") "")
9061 "]"))
9063 (defconst org-link-escape-chars
9064 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9065 "List of characters that should be escaped in link.
9066 This is the list that is used for internal purposes.")
9068 (defconst org-link-escape-chars-browser
9069 '(?\ )
9070 "List of escapes for characters that are problematic in links.
9071 This is the list that is used before handing over to the browser.")
9073 (defun org-link-escape (text &optional table merge)
9074 "Return percent escaped representation of TEXT.
9075 TEXT is a string with the text to escape.
9076 Optional argument TABLE is a list with characters that should be
9077 escaped. When nil, `org-link-escape-chars' is used.
9078 If optional argument MERGE is set, merge TABLE into
9079 `org-link-escape-chars'."
9080 (cond
9081 ((and table merge)
9082 (mapc (lambda (defchr)
9083 (unless (member defchr table)
9084 (setq table (cons defchr table)))) org-link-escape-chars))
9085 ((null table)
9086 (setq table org-link-escape-chars)))
9087 (mapconcat
9088 (lambda (char)
9089 (if (or (member char table)
9090 (and (or (< char 32) (= char 37) (> char 126))
9091 org-url-hexify-p))
9092 (mapconcat (lambda (sequence-element)
9093 (format "%%%.2X" sequence-element))
9094 (or (encode-coding-char char 'utf-8)
9095 (error "Unable to percent escape character: %s"
9096 (char-to-string char))) "")
9097 (char-to-string char))) text ""))
9099 (defun org-link-unescape (str)
9100 "Unhex hexified Unicode strings as returned from the JavaScript function
9101 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9102 (unless (and (null str) (string= "" str))
9103 (let ((pos 0) (case-fold-search t) unhexed)
9104 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9105 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9106 (setq str (replace-match unhexed t t str))
9107 (setq pos (+ pos (length unhexed))))))
9108 str)
9110 (defun org-link-unescape-compound (hex)
9111 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9112 Note: this function also decodes single byte encodings like
9113 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9114 (save-match-data
9115 (let* ((bytes (cdr (split-string hex "%")))
9116 (ret "")
9117 (eat 0)
9118 (sum 0))
9119 (while bytes
9120 (let* ((val (string-to-number (pop bytes) 16))
9121 (shift-xor
9122 (if (= 0 eat)
9123 (cond
9124 ((>= val 252) (cons 6 252))
9125 ((>= val 248) (cons 5 248))
9126 ((>= val 240) (cons 4 240))
9127 ((>= val 224) (cons 3 224))
9128 ((>= val 192) (cons 2 192))
9129 (t (cons 0 0)))
9130 (cons 6 128))))
9131 (if (>= val 192) (setq eat (car shift-xor)))
9132 (setq val (logxor val (cdr shift-xor)))
9133 (setq sum (+ (lsh sum (car shift-xor)) val))
9134 (if (> eat 0) (setq eat (- eat 1)))
9135 (cond
9136 ((= 0 eat) ;multi byte
9137 (setq ret (concat ret (org-char-to-string sum)))
9138 (setq sum 0))
9139 ((not bytes) ; single byte(s)
9140 (setq ret (org-link-unescape-single-byte-sequence hex))))
9141 )) ;; end (while bytes
9142 ret )))
9144 (defun org-link-unescape-single-byte-sequence (hex)
9145 "Unhexify hex-encoded single byte character sequences."
9146 (mapconcat (lambda (byte)
9147 (char-to-string (string-to-number byte 16)))
9148 (cdr (split-string hex "%")) ""))
9150 (defun org-xor (a b)
9151 "Exclusive or."
9152 (if a (not b) b))
9154 (defun org-fixup-message-id-for-http (s)
9155 "Replace special characters in a message id, so it can be used in an http query."
9156 (when (string-match "%" s)
9157 (setq s (mapconcat (lambda (c)
9158 (if (eq c ?%)
9159 "%25"
9160 (char-to-string c)))
9161 s "")))
9162 (while (string-match "<" s)
9163 (setq s (replace-match "%3C" t t s)))
9164 (while (string-match ">" s)
9165 (setq s (replace-match "%3E" t t s)))
9166 (while (string-match "@" s)
9167 (setq s (replace-match "%40" t t s)))
9170 (defun org-link-prettify (link)
9171 "Return a human-readable representation of LINK.
9172 The car of LINK must be a raw link the cdr of LINK must be either
9173 a link description or nil."
9174 (let ((desc (or (cadr link) "<no description>")))
9175 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9176 "<" (car link) ">")))
9178 ;;;###autoload
9179 (defun org-insert-link-global ()
9180 "Insert a link like Org-mode does.
9181 This command can be called in any mode to insert a link in Org-mode syntax."
9182 (interactive)
9183 (org-load-modules-maybe)
9184 (org-run-like-in-org-mode 'org-insert-link))
9186 (defun org-insert-all-links (&optional keep)
9187 "Insert all links in `org-stored-links'."
9188 (interactive "P")
9189 (let ((links (copy-sequence org-stored-links)) l)
9190 (while (setq l (if keep (pop links) (pop org-stored-links)))
9191 (insert "- ")
9192 (org-insert-link nil (car l) (cadr l))
9193 (insert "\n"))))
9195 (defun org-link-fontify-links-to-this-file ()
9196 "Fontify links to the current file in `org-stored-links'."
9197 (let ((f (buffer-file-name)) a b)
9198 (setq a (mapcar (lambda(l)
9199 (let ((ll (car l)))
9200 (when (and (string-match "^file:\\(.+\\)::" ll)
9201 (equal f (expand-file-name (match-string 1 ll))))
9202 ll)))
9203 org-stored-links))
9204 (when (featurep 'org-id)
9205 (setq b (mapcar (lambda(l)
9206 (let ((ll (car l)))
9207 (when (and (string-match "^id:\\(.+\\)$" ll)
9208 (equal f (expand-file-name
9209 (or (org-id-find-id-file
9210 (match-string 1 ll)) ""))))
9211 ll)))
9212 org-stored-links)))
9213 (mapcar (lambda(l)
9214 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9215 (delq nil (append a b)))))
9217 (defvar org-link-links-in-this-file nil)
9218 (defun org-insert-link (&optional complete-file link-location default-description)
9219 "Insert a link. At the prompt, enter the link.
9221 Completion can be used to insert any of the link protocol prefixes like
9222 http or ftp in use.
9224 The history can be used to select a link previously stored with
9225 `org-store-link'. When the empty string is entered (i.e. if you just
9226 press RET at the prompt), the link defaults to the most recently
9227 stored link. As SPC triggers completion in the minibuffer, you need to
9228 use M-SPC or C-q SPC to force the insertion of a space character.
9230 You will also be prompted for a description, and if one is given, it will
9231 be displayed in the buffer instead of the link.
9233 If there is already a link at point, this command will allow you to edit link
9234 and description parts.
9236 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9237 be selected using completion. The path to the file will be relative to the
9238 current directory if the file is in the current directory or a subdirectory.
9239 Otherwise, the link will be the absolute path as completed in the minibuffer
9240 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9241 option `org-link-file-path-type'.
9243 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9244 the current directory or below.
9246 With three \\[universal-argument] prefixes, negate the meaning of
9247 `org-keep-stored-link-after-insertion'.
9249 If `org-make-link-description-function' is non-nil, this function will be
9250 called with the link target, and the result will be the default
9251 link description.
9253 If the LINK-LOCATION parameter is non-nil, this value will be
9254 used as the link location instead of reading one interactively.
9256 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9257 be used as the default description."
9258 (interactive "P")
9259 (let* ((wcf (current-window-configuration))
9260 (region (if (org-region-active-p)
9261 (buffer-substring (region-beginning) (region-end))))
9262 (remove (and region (list (region-beginning) (region-end))))
9263 (desc region)
9264 tmphist ; byte-compile incorrectly complains about this
9265 (link link-location)
9266 (abbrevs org-link-abbrev-alist-local)
9267 entry file all-prefixes auto-desc)
9268 (cond
9269 (link-location) ; specified by arg, just use it.
9270 ((org-in-regexp org-bracket-link-regexp 1)
9271 ;; We do have a link at point, and we are going to edit it.
9272 (setq remove (list (match-beginning 0) (match-end 0)))
9273 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9274 (setq link (read-string "Link: "
9275 (org-link-unescape
9276 (org-match-string-no-properties 1)))))
9277 ((or (org-in-regexp org-angle-link-re)
9278 (org-in-regexp org-plain-link-re))
9279 ;; Convert to bracket link
9280 (setq remove (list (match-beginning 0) (match-end 0))
9281 link (read-string "Link: "
9282 (org-remove-angle-brackets (match-string 0)))))
9283 ((member complete-file '((4) (16)))
9284 ;; Completing read for file names.
9285 (setq link (org-file-complete-link complete-file)))
9287 ;; Read link, with completion for stored links.
9288 (org-link-fontify-links-to-this-file)
9289 (org-switch-to-buffer-other-window "*Org Links*")
9290 (with-current-buffer "*Org Links*"
9291 (erase-buffer)
9292 (insert "Insert a link.
9293 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9294 (when org-stored-links
9295 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9296 (insert (mapconcat 'org-link-prettify
9297 (reverse org-stored-links) "\n")))
9298 (goto-char (point-min)))
9299 (let ((cw (selected-window)))
9300 (select-window (get-buffer-window "*Org Links*" 'visible))
9301 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9302 (unless (pos-visible-in-window-p (point-max))
9303 (org-fit-window-to-buffer))
9304 (and (window-live-p cw) (select-window cw)))
9305 ;; Fake a link history, containing the stored links.
9306 (setq tmphist (append (mapcar 'car org-stored-links)
9307 org-insert-link-history))
9308 (setq all-prefixes (append (mapcar 'car abbrevs)
9309 (mapcar 'car org-link-abbrev-alist)
9310 org-link-types))
9311 (unwind-protect
9312 (progn
9313 (setq link
9314 (let ((org-completion-use-ido nil)
9315 (org-completion-use-iswitchb nil))
9316 (org-completing-read
9317 "Link: "
9318 (append
9319 (mapcar (lambda (x) (list (concat x ":")))
9320 all-prefixes)
9321 (mapcar 'car org-stored-links)
9322 (mapcar 'cadr org-stored-links))
9323 nil nil nil
9324 'tmphist
9325 (caar org-stored-links))))
9326 (if (not (string-match "\\S-" link))
9327 (error "No link selected"))
9328 (mapc (lambda(l)
9329 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9330 org-stored-links)
9331 (if (or (member link all-prefixes)
9332 (and (equal ":" (substring link -1))
9333 (member (substring link 0 -1) all-prefixes)
9334 (setq link (substring link 0 -1))))
9335 (setq link (org-link-try-special-completion link))))
9336 (set-window-configuration wcf)
9337 (kill-buffer "*Org Links*"))
9338 (setq entry (assoc link org-stored-links))
9339 (or entry (push link org-insert-link-history))
9340 (setq desc (or desc (nth 1 entry)))))
9342 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9343 (not org-keep-stored-link-after-insertion))
9344 (setq org-stored-links (delq (assoc link org-stored-links)
9345 org-stored-links)))
9347 (if (string-match org-plain-link-re link)
9348 ;; URL-like link, normalize the use of angular brackets.
9349 (setq link (org-remove-angle-brackets link)))
9351 ;; Check if we are linking to the current file with a search
9352 ;; option If yes, simplify the link by using only the search
9353 ;; option.
9354 (when (and buffer-file-name
9355 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9356 (let* ((path (match-string 1 link))
9357 (case-fold-search nil)
9358 (search (match-string 2 link)))
9359 (save-match-data
9360 (if (equal (file-truename buffer-file-name) (file-truename path))
9361 ;; We are linking to this same file, with a search option
9362 (setq link search)))))
9364 ;; Check if we can/should use a relative path. If yes, simplify the link
9365 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9366 (let* ((type (match-string 1 link))
9367 (path (match-string 2 link))
9368 (origpath path)
9369 (case-fold-search nil))
9370 (cond
9371 ((or (eq org-link-file-path-type 'absolute)
9372 (equal complete-file '(16)))
9373 (setq path (abbreviate-file-name (expand-file-name path))))
9374 ((eq org-link-file-path-type 'noabbrev)
9375 (setq path (expand-file-name path)))
9376 ((eq org-link-file-path-type 'relative)
9377 (setq path (file-relative-name path)))
9379 (save-match-data
9380 (if (string-match (concat "^" (regexp-quote
9381 (expand-file-name
9382 (file-name-as-directory
9383 default-directory))))
9384 (expand-file-name path))
9385 ;; We are linking a file with relative path name.
9386 (setq path (substring (expand-file-name path)
9387 (match-end 0)))
9388 (setq path (abbreviate-file-name (expand-file-name path)))))))
9389 (setq link (concat type path))
9390 (if (equal desc origpath)
9391 (setq desc path))))
9393 (if org-make-link-description-function
9394 (setq desc
9395 (or (condition-case nil
9396 (funcall org-make-link-description-function link desc)
9397 (error (progn (message "Can't get link description from `%s'"
9398 (symbol-name org-make-link-description-function))
9399 (sit-for 2) nil)))
9400 (read-string "Description: " default-description)))
9401 (if default-description (setq desc default-description)
9402 (setq desc (or (and auto-desc desc)
9403 (read-string "Description: " desc)))))
9405 (unless (string-match "\\S-" desc) (setq desc nil))
9406 (if remove (apply 'delete-region remove))
9407 (insert (org-make-link-string link desc))))
9409 (defun org-link-try-special-completion (type)
9410 "If there is completion support for link type TYPE, offer it."
9411 (let ((fun (intern (concat "org-" type "-complete-link"))))
9412 (if (functionp fun)
9413 (funcall fun)
9414 (read-string "Link (no completion support): " (concat type ":")))))
9416 (defun org-file-complete-link (&optional arg)
9417 "Create a file link using completion."
9418 (let (file link)
9419 (setq file (read-file-name "File: "))
9420 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9421 (pwd1 (file-name-as-directory (abbreviate-file-name
9422 (expand-file-name ".")))))
9423 (cond
9424 ((equal arg '(16))
9425 (setq link (concat
9426 "file:"
9427 (abbreviate-file-name (expand-file-name file)))))
9428 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9429 (setq link (concat "file:" (match-string 1 file))))
9430 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9431 (expand-file-name file))
9432 (setq link (concat
9433 "file:" (match-string 1 (expand-file-name file)))))
9434 (t (setq link (concat "file:" file)))))
9435 link))
9437 (defun org-completing-read (&rest args)
9438 "Completing-read with SPACE being a normal character."
9439 (let ((enable-recursive-minibuffers t)
9440 (minibuffer-local-completion-map
9441 (copy-keymap minibuffer-local-completion-map)))
9442 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9443 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9444 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9445 (apply 'org-icompleting-read args)))
9447 (defun org-completing-read-no-i (&rest args)
9448 (let (org-completion-use-ido org-completion-use-iswitchb)
9449 (apply 'org-completing-read args)))
9451 (defun org-iswitchb-completing-read (prompt choices &rest args)
9452 "Use iswitch as a completing-read replacement to choose from choices.
9453 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9454 from."
9455 (let* ((iswitchb-use-virtual-buffers nil)
9456 (iswitchb-make-buflist-hook
9457 (lambda ()
9458 (setq iswitchb-temp-buflist choices))))
9459 (iswitchb-read-buffer prompt)))
9461 (defun org-icompleting-read (&rest args)
9462 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9463 (org-without-partial-completion
9464 (if (and org-completion-use-ido
9465 (fboundp 'ido-completing-read)
9466 (boundp 'ido-mode) ido-mode
9467 (listp (second args)))
9468 (let ((ido-enter-matching-directory nil))
9469 (apply 'ido-completing-read (concat (car args))
9470 (if (consp (car (nth 1 args)))
9471 (mapcar 'car (nth 1 args))
9472 (nth 1 args))
9473 (cddr args)))
9474 (if (and org-completion-use-iswitchb
9475 (boundp 'iswitchb-mode) iswitchb-mode
9476 (listp (second args)))
9477 (apply 'org-iswitchb-completing-read (concat (car args))
9478 (if (consp (car (nth 1 args)))
9479 (mapcar 'car (nth 1 args))
9480 (nth 1 args))
9481 (cddr args))
9482 (apply 'completing-read args)))))
9484 (defun org-extract-attributes (s)
9485 "Extract the attributes cookie from a string and set as text property."
9486 (let (a attr (start 0) key value)
9487 (save-match-data
9488 (when (string-match "{{\\([^}]+\\)}}$" s)
9489 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9490 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9491 (setq key (match-string 1 a) value (match-string 2 a)
9492 start (match-end 0)
9493 attr (plist-put attr (intern key) value))))
9494 (org-add-props s nil 'org-attr attr))
9497 (defun org-extract-attributes-from-string (tag)
9498 (let (key value attr)
9499 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9500 (setq key (match-string 1 tag) value (match-string 2 tag)
9501 tag (replace-match "" t t tag)
9502 attr (plist-put attr (intern key) value)))
9503 (cons tag attr)))
9505 (defun org-attributes-to-string (plist)
9506 "Format a property list into an HTML attribute list."
9507 (let ((s "") key value)
9508 (while plist
9509 (setq key (pop plist) value (pop plist))
9510 (and value
9511 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9514 ;;; Opening/following a link
9516 (defvar org-link-search-failed nil)
9518 (defvar org-open-link-functions nil
9519 "Hook for functions finding a plain text link.
9520 These functions must take a single argument, the link content.
9521 They will be called for links that look like [[link text][description]]
9522 when LINK TEXT does not have a protocol like \"http:\" and does not look
9523 like a filename (e.g. \"./blue.png\").
9525 These functions will be called *before* Org attempts to resolve the
9526 link by doing text searches in the current buffer - so if you want a
9527 link \"[[target]]\" to still find \"<<target>>\", your function should
9528 handle this as a special case.
9530 When the function does handle the link, it must return a non-nil value.
9531 If it decides that it is not responsible for this link, it must return
9532 nil to indicate that that Org-mode can continue with other options
9533 like exact and fuzzy text search.")
9535 (defun org-next-link ()
9536 "Move forward to the next link.
9537 If the link is in hidden text, expose it."
9538 (interactive)
9539 (when (and org-link-search-failed (eq this-command last-command))
9540 (goto-char (point-min))
9541 (message "Link search wrapped back to beginning of buffer"))
9542 (setq org-link-search-failed nil)
9543 (let* ((pos (point))
9544 (ct (org-context))
9545 (a (assoc :link ct)))
9546 (if a (goto-char (nth 2 a)))
9547 (if (re-search-forward org-any-link-re nil t)
9548 (progn
9549 (goto-char (match-beginning 0))
9550 (if (outline-invisible-p) (org-show-context)))
9551 (goto-char pos)
9552 (setq org-link-search-failed t)
9553 (error "No further link found"))))
9555 (defun org-previous-link ()
9556 "Move backward to the previous link.
9557 If the link is in hidden text, expose it."
9558 (interactive)
9559 (when (and org-link-search-failed (eq this-command last-command))
9560 (goto-char (point-max))
9561 (message "Link search wrapped back to end of buffer"))
9562 (setq org-link-search-failed nil)
9563 (let* ((pos (point))
9564 (ct (org-context))
9565 (a (assoc :link ct)))
9566 (if a (goto-char (nth 1 a)))
9567 (if (re-search-backward org-any-link-re nil t)
9568 (progn
9569 (goto-char (match-beginning 0))
9570 (if (outline-invisible-p) (org-show-context)))
9571 (goto-char pos)
9572 (setq org-link-search-failed t)
9573 (error "No further link found"))))
9575 (defun org-translate-link (s)
9576 "Translate a link string if a translation function has been defined."
9577 (if (and org-link-translation-function
9578 (fboundp org-link-translation-function)
9579 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9580 (progn
9581 (setq s (funcall org-link-translation-function
9582 (match-string 1 s) (match-string 2 s)))
9583 (concat (car s) ":" (cdr s)))
9586 (defun org-translate-link-from-planner (type path)
9587 "Translate a link from Emacs Planner syntax so that Org can follow it.
9588 This is still an experimental function, your mileage may vary."
9589 (cond
9590 ((member type '("http" "https" "news" "ftp"))
9591 ;; standard Internet links are the same.
9592 nil)
9593 ((and (equal type "irc") (string-match "^//" path))
9594 ;; Planner has two / at the beginning of an irc link, we have 1.
9595 ;; We should have zero, actually....
9596 (setq path (substring path 1)))
9597 ((and (equal type "lisp") (string-match "^/" path))
9598 ;; Planner has a slash, we do not.
9599 (setq type "elisp" path (substring path 1)))
9600 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9601 ;; A typical message link. Planner has the id after the final slash,
9602 ;; we separate it with a hash mark
9603 (setq path (concat (match-string 1 path) "#"
9604 (org-remove-angle-brackets (match-string 2 path)))))
9606 (cons type path))
9608 (defun org-find-file-at-mouse (ev)
9609 "Open file link or URL at mouse."
9610 (interactive "e")
9611 (mouse-set-point ev)
9612 (org-open-at-point 'in-emacs))
9614 (defun org-open-at-mouse (ev)
9615 "Open file link or URL at mouse.
9616 See the docstring of `org-open-file' for details."
9617 (interactive "e")
9618 (mouse-set-point ev)
9619 (if (eq major-mode 'org-agenda-mode)
9620 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9621 (org-open-at-point))
9623 (defvar org-window-config-before-follow-link nil
9624 "The window configuration before following a link.
9625 This is saved in case the need arises to restore it.")
9627 (defvar org-open-link-marker (make-marker)
9628 "Marker pointing to the location where `org-open-at-point; was called.")
9630 ;;;###autoload
9631 (defun org-open-at-point-global ()
9632 "Follow a link like Org-mode does.
9633 This command can be called in any mode to follow a link that has
9634 Org-mode syntax."
9635 (interactive)
9636 (org-run-like-in-org-mode 'org-open-at-point))
9638 ;;;###autoload
9639 (defun org-open-link-from-string (s &optional arg reference-buffer)
9640 "Open a link in the string S, as if it was in Org-mode."
9641 (interactive "sLink: \nP")
9642 (let ((reference-buffer (or reference-buffer (current-buffer))))
9643 (with-temp-buffer
9644 (let ((org-inhibit-startup (not reference-buffer)))
9645 (org-mode)
9646 (insert s)
9647 (goto-char (point-min))
9648 (when reference-buffer
9649 (setq org-link-abbrev-alist-local
9650 (with-current-buffer reference-buffer
9651 org-link-abbrev-alist-local)))
9652 (org-open-at-point arg reference-buffer)))))
9654 (defvar org-open-at-point-functions nil
9655 "Hook that is run when following a link at point.
9657 Functions in this hook must return t if they identify and follow
9658 a link at point. If they don't find anything interesting at point,
9659 they must return nil.")
9661 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9662 (defun org-open-at-point (&optional arg reference-buffer)
9663 "Open link at or after point.
9664 If there is no link at point, this function will search forward up to
9665 the end of the current line.
9666 Normally, files will be opened by an appropriate application. If the
9667 optional prefix argument ARG is non-nil, Emacs will visit the file.
9668 With a double prefix argument, try to open outside of Emacs, in the
9669 application the system uses for this file type."
9670 (interactive "P")
9671 ;; if in a code block, then open the block's results
9672 (unless (call-interactively #'org-babel-open-src-block-result)
9673 (org-load-modules-maybe)
9674 (move-marker org-open-link-marker (point))
9675 (setq org-window-config-before-follow-link (current-window-configuration))
9676 (org-remove-occur-highlights nil nil t)
9677 (cond
9678 ((and (org-at-heading-p)
9679 (not (org-at-timestamp-p t))
9680 (not (org-in-regexp
9681 (concat org-plain-link-re "\\|"
9682 org-bracket-link-regexp "\\|"
9683 org-angle-link-re "\\|"
9684 "[ \t]:[^ \t\n]+:[ \t]*$")))
9685 (not (get-text-property (point) 'org-linked-text)))
9686 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
9687 (lk (car lkall))
9688 (lkend (cdr lkall)))
9689 (when lk
9690 (prog1 (search-forward lk nil lkend)
9691 (goto-char (match-beginning 0))
9692 (org-open-at-point))))
9693 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9694 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9695 ((and (org-at-timestamp-p t)
9696 (not (org-in-regexp org-bracket-link-regexp)))
9697 (org-follow-timestamp-link))
9698 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9699 (not (org-in-regexp org-any-link-re)))
9700 (org-footnote-action))
9702 (let (type path link line search (pos (point)))
9703 (catch 'match
9704 (save-excursion
9705 (skip-chars-forward "^]\n\r")
9706 (when (org-in-regexp org-bracket-link-regexp 1)
9707 (setq link (org-extract-attributes
9708 (org-link-unescape (org-match-string-no-properties 1))))
9709 (while (string-match " *\n *" link)
9710 (setq link (replace-match " " t t link)))
9711 (setq link (org-link-expand-abbrev link))
9712 (cond
9713 ((or (file-name-absolute-p link)
9714 (string-match "^\\.\\.?/" link))
9715 (setq type "file" path link))
9716 ((string-match org-link-re-with-space3 link)
9717 (setq type (match-string 1 link) path (match-string 2 link)))
9718 ((string-match "^help:+\\(.+\\)" link)
9719 (setq type "help" path (match-string 1 link)))
9720 (t (setq type "thisfile" path link)))
9721 (throw 'match t)))
9723 (when (get-text-property (point) 'org-linked-text)
9724 (setq type "thisfile"
9725 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9726 (1+ (point)) (point))
9727 path (buffer-substring
9728 (or (previous-single-property-change pos 'org-linked-text)
9729 (point-min))
9730 (or (next-single-property-change pos 'org-linked-text)
9731 (point-max))))
9732 (throw 'match t))
9734 (save-excursion
9735 (let ((plinkpos (org-in-regexp org-plain-link-re)))
9736 (when (or (org-in-regexp org-angle-link-re)
9737 (and plinkpos (goto-char (car plinkpos))
9738 (save-match-data (not (looking-back "\\[\\[")))))
9739 (setq type (match-string 1)
9740 path (org-link-unescape (match-string 2)))
9741 (throw 'match t))))
9742 (save-excursion
9743 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9744 (setq type "tags"
9745 path (match-string 1))
9746 (while (string-match ":" path)
9747 (setq path (replace-match "+" t t path)))
9748 (throw 'match t)))
9749 (when (org-in-regexp "<\\([^><\n]+\\)>")
9750 (setq type "tree-match"
9751 path (match-string 1))
9752 (throw 'match t)))
9753 (unless path
9754 (user-error "No link found"))
9756 ;; switch back to reference buffer
9757 ;; needed when if called in a temporary buffer through
9758 ;; org-open-link-from-string
9759 (with-current-buffer (or reference-buffer (current-buffer))
9761 ;; Remove any trailing spaces in path
9762 (if (string-match " +\\'" path)
9763 (setq path (replace-match "" t t path)))
9764 (if (and org-link-translation-function
9765 (fboundp org-link-translation-function))
9766 ;; Check if we need to translate the link
9767 (let ((tmp (funcall org-link-translation-function type path)))
9768 (setq type (car tmp) path (cdr tmp))))
9770 (cond
9772 ((assoc type org-link-protocols)
9773 (funcall (nth 1 (assoc type org-link-protocols)) path))
9775 ((equal type "help")
9776 (let ((f-or-v (intern path)))
9777 (cond ((fboundp f-or-v)
9778 (describe-function f-or-v))
9779 ((boundp f-or-v)
9780 (describe-variable f-or-v))
9781 (t (error "Not a known function or variable")))))
9783 ((equal type "mailto")
9784 (let ((cmd (car org-link-mailto-program))
9785 (args (cdr org-link-mailto-program)) args1
9786 (address path) (subject "") a)
9787 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9788 (setq address (match-string 1 path)
9789 subject (org-link-escape (match-string 2 path))))
9790 (while args
9791 (cond
9792 ((not (stringp (car args))) (push (pop args) args1))
9793 (t (setq a (pop args))
9794 (if (string-match "%a" a)
9795 (setq a (replace-match address t t a)))
9796 (if (string-match "%s" a)
9797 (setq a (replace-match subject t t a)))
9798 (push a args1))))
9799 (apply cmd (nreverse args1))))
9801 ((member type '("http" "https" "ftp" "news"))
9802 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9803 (org-link-escape
9804 path org-link-escape-chars-browser)
9805 path))))
9807 ((string= type "doi")
9808 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9809 (org-link-escape
9810 path org-link-escape-chars-browser)
9811 path))))
9813 ((member type '("message"))
9814 (browse-url (concat type ":" path)))
9816 ((string= type "tags")
9817 (org-tags-view arg path))
9819 ((string= type "tree-match")
9820 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9822 ((string= type "file")
9823 (if (string-match "::\\([0-9]+\\)\\'" path)
9824 (setq line (string-to-number (match-string 1 path))
9825 path (substring path 0 (match-beginning 0)))
9826 (if (string-match "::\\(.+\\)\\'" path)
9827 (setq search (match-string 1 path)
9828 path (substring path 0 (match-beginning 0)))))
9829 (if (string-match "[*?{]" (file-name-nondirectory path))
9830 (dired path)
9831 (org-open-file path arg line search)))
9833 ((string= type "shell")
9834 (let ((buf (generate-new-buffer "*Org Shell Output"))
9835 (cmd path))
9836 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9837 (string-match org-confirm-shell-link-not-regexp cmd))
9838 (not org-confirm-shell-link-function)
9839 (funcall org-confirm-shell-link-function
9840 (format "Execute \"%s\" in shell? "
9841 (org-add-props cmd nil
9842 'face 'org-warning))))
9843 (progn
9844 (message "Executing %s" cmd)
9845 (shell-command cmd buf)
9846 (if (featurep 'midnight)
9847 (setq clean-buffer-list-kill-buffer-names
9848 (cons buf clean-buffer-list-kill-buffer-names))))
9849 (error "Abort"))))
9851 ((string= type "elisp")
9852 (let ((cmd path))
9853 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9854 (string-match org-confirm-elisp-link-not-regexp cmd))
9855 (not org-confirm-elisp-link-function)
9856 (funcall org-confirm-elisp-link-function
9857 (format "Execute \"%s\" as elisp? "
9858 (org-add-props cmd nil
9859 'face 'org-warning))))
9860 (message "%s => %s" cmd
9861 (if (equal (string-to-char cmd) ?\()
9862 (eval (read cmd))
9863 (call-interactively (read cmd))))
9864 (error "Abort"))))
9866 ((and (string= type "thisfile")
9867 (run-hook-with-args-until-success
9868 'org-open-link-functions path)))
9870 ((string= type "thisfile")
9871 (if arg
9872 (switch-to-buffer-other-window
9873 (org-get-buffer-for-internal-link (current-buffer)))
9874 (org-mark-ring-push))
9875 (let ((cmd `(org-link-search
9876 ,path
9877 ,(cond ((equal arg '(4)) ''occur)
9878 ((equal arg '(16)) ''org-occur))
9879 ,pos)))
9880 (condition-case nil (let ((org-link-search-inhibit-query t))
9881 (eval cmd))
9882 (error (progn (widen) (eval cmd))))))
9884 (t (browse-url-at-point)))))))
9885 (move-marker org-open-link-marker nil)
9886 (run-hook-with-args 'org-follow-link-hook)))
9888 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
9889 "Offer links in the current entry and return the selected link.
9890 If there is only one link, return it.
9891 If NTH is an integer, return the NTH link found.
9892 If ZERO is a string, check also this string for a link, and if
9893 there is one, return it."
9894 (with-current-buffer buffer
9895 (save-excursion
9896 (save-restriction
9897 (widen)
9898 (goto-char marker)
9899 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9900 "\\(" org-angle-link-re "\\)\\|"
9901 "\\(" org-plain-link-re "\\)"))
9902 (cnt ?0)
9903 (in-emacs (if (integerp nth) nil nth))
9904 have-zero end links link c)
9905 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9906 (push (match-string 0 zero) links)
9907 (setq cnt (1- cnt) have-zero t))
9908 (save-excursion
9909 (org-back-to-heading t)
9910 (setq end (save-excursion (outline-next-heading) (point)))
9911 (while (re-search-forward re end t)
9912 (push (match-string 0) links))
9913 (setq links (org-uniquify (reverse links))))
9914 (cond
9915 ((null links)
9916 (message "No links"))
9917 ((equal (length links) 1)
9918 (setq link (car links)))
9919 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9920 (setq link (nth (if have-zero nth (1- nth)) links)))
9921 (t ; we have to select a link
9922 (save-excursion
9923 (save-window-excursion
9924 (delete-other-windows)
9925 (with-output-to-temp-buffer "*Select Link*"
9926 (mapc (lambda (l)
9927 (if (not (string-match org-bracket-link-regexp l))
9928 (princ (format "[%c] %s\n" (incf cnt)
9929 (org-remove-angle-brackets l)))
9930 (if (match-end 3)
9931 (princ (format "[%c] %s (%s)\n" (incf cnt)
9932 (match-string 3 l) (match-string 1 l)))
9933 (princ (format "[%c] %s\n" (incf cnt)
9934 (match-string 1 l))))))
9935 links))
9936 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9937 (message "Select link to open, RET to open all:")
9938 (setq c (read-char-exclusive))
9939 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9940 (when (equal c ?q) (error "Abort"))
9941 (if (equal c ?\C-m)
9942 (setq link links)
9943 (setq nth (- c ?0))
9944 (if have-zero (setq nth (1+ nth)))
9945 (unless (and (integerp nth) (>= (length links) nth))
9946 (error "Invalid link selection"))
9947 (setq link (nth (1- nth) links)))))
9948 (cons link end))))))
9950 ;; Add special file links that specify the way of opening
9952 (org-add-link-type "file+sys" 'org-open-file-with-system)
9953 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9954 (defun org-open-file-with-system (path)
9955 "Open file at PATH using the system way of opening it."
9956 (org-open-file path 'system))
9957 (defun org-open-file-with-emacs (path)
9958 "Open file at PATH in Emacs."
9959 (org-open-file path 'emacs))
9960 (defun org-remove-file-link-modifiers ()
9961 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9962 (goto-char (point-min))
9963 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9964 (org-if-unprotected
9965 (replace-match "file:" t t))))
9966 (eval-after-load "org-exp"
9967 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9968 'org-remove-file-link-modifiers))
9970 ;;; File search
9972 (defvar org-create-file-search-functions nil
9973 "List of functions to construct the right search string for a file link.
9974 These functions are called in turn with point at the location to
9975 which the link should point.
9977 A function in the hook should first test if it would like to
9978 handle this file type, for example by checking the `major-mode'
9979 or the file extension. If it decides not to handle this file, it
9980 should just return nil to give other functions a chance. If it
9981 does handle the file, it must return the search string to be used
9982 when following the link. The search string will be part of the
9983 file link, given after a double colon, and `org-open-at-point'
9984 will automatically search for it. If special measures must be
9985 taken to make the search successful, another function should be
9986 added to the companion hook `org-execute-file-search-functions',
9987 which see.
9989 A function in this hook may also use `setq' to set the variable
9990 `description' to provide a suggestion for the descriptive text to
9991 be used for this link when it gets inserted into an Org-mode
9992 buffer with \\[org-insert-link].")
9994 (defvar org-execute-file-search-functions nil
9995 "List of functions to execute a file search triggered by a link.
9997 Functions added to this hook must accept a single argument, the
9998 search string that was part of the file link, the part after the
9999 double colon. The function must first check if it would like to
10000 handle this search, for example by checking the `major-mode' or
10001 the file extension. If it decides not to handle this search, it
10002 should just return nil to give other functions a chance. If it
10003 does handle the search, it must return a non-nil value to keep
10004 other functions from trying.
10006 Each function can access the current prefix argument through the
10007 variable `current-prefix-argument'. Note that a single prefix is
10008 used to force opening a link in Emacs, so it may be good to only
10009 use a numeric or double prefix to guide the search function.
10011 In case this is needed, a function in this hook can also restore
10012 the window configuration before `org-open-at-point' was called using:
10014 (set-window-configuration org-window-config-before-follow-link)")
10016 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10017 (defun org-link-search (s &optional type avoid-pos stealth)
10018 "Search for a link search option.
10019 If S is surrounded by forward slashes, it is interpreted as a
10020 regular expression. In org-mode files, this will create an `org-occur'
10021 sparse tree. In ordinary files, `occur' will be used to list matches.
10022 If the current buffer is in `dired-mode', grep will be used to search
10023 in all files. If AVOID-POS is given, ignore matches near that position.
10025 When optional argument STEALTH is non-nil, do not modify
10026 visibility around point, thus ignoring
10027 `org-show-hierarchy-above', `org-show-following-heading' and
10028 `org-show-siblings' variables."
10029 (let ((case-fold-search t)
10030 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10031 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10032 (append '(("") (" ") ("\t") ("\n"))
10033 org-emphasis-alist)
10034 "\\|") "\\)"))
10035 (pos (point))
10036 (pre nil) (post nil)
10037 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10038 (cond
10039 ;; First check if there are any special search functions
10040 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10041 ;; Now try the builtin stuff
10042 ((and (equal (string-to-char s0) ?#)
10043 (> (length s0) 1)
10044 (save-excursion
10045 (goto-char (point-min))
10046 (and
10047 (re-search-forward
10048 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10049 (setq type 'dedicated
10050 pos (match-beginning 0))))
10051 ;; There is an exact target for this
10052 (goto-char pos)
10053 (org-back-to-heading t)))
10054 ((save-excursion
10055 (goto-char (point-min))
10056 (and
10057 (re-search-forward
10058 (concat "<<" (regexp-quote s0) ">>") nil t)
10059 (setq type 'dedicated
10060 pos (match-beginning 0))))
10061 ;; There is an exact target for this
10062 (goto-char pos))
10063 ((save-excursion
10064 (goto-char (point-min))
10065 (and
10066 (re-search-forward
10067 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10068 (setq type 'dedicated pos (match-beginning 0))))
10069 ;; Found an invisible target.
10070 (goto-char pos))
10071 ((save-excursion
10072 (goto-char (point-min))
10073 (and
10074 (re-search-forward
10075 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10076 (setq type 'dedicated pos (match-beginning 0))))
10077 ;; Found an element with a matching #+name affiliated keyword.
10078 (goto-char pos))
10079 ((and (string-match "^(\\(.*\\))$" s0)
10080 (save-excursion
10081 (goto-char (point-min))
10082 (and
10083 (re-search-forward
10084 (concat "[^[]" (regexp-quote
10085 (format org-coderef-label-format
10086 (match-string 1 s0))))
10087 nil t)
10088 (setq type 'dedicated
10089 pos (1+ (match-beginning 0))))))
10090 ;; There is a coderef target for this
10091 (goto-char pos))
10092 ((string-match "^/\\(.*\\)/$" s)
10093 ;; A regular expression
10094 (cond
10095 ((derived-mode-p 'org-mode)
10096 (org-occur (match-string 1 s)))
10097 ;;((eq major-mode 'dired-mode)
10098 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10099 (t (org-do-occur (match-string 1 s)))))
10100 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10101 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10102 (goto-char (point-min))
10103 (cond
10104 ((let (case-fold-search)
10105 (re-search-forward (format org-complex-heading-regexp-format
10106 (regexp-quote s))
10107 nil t))
10108 ;; OK, found a match
10109 (setq type 'dedicated)
10110 (goto-char (match-beginning 0)))
10111 ((and (not org-link-search-inhibit-query)
10112 (eq org-link-search-must-match-exact-headline 'query-to-create)
10113 (y-or-n-p "No match - create this as a new heading? "))
10114 (goto-char (point-max))
10115 (or (bolp) (newline))
10116 (insert "* " s "\n")
10117 (beginning-of-line 0))
10119 (goto-char pos)
10120 (error "No match"))))
10122 ;; A normal search string
10123 (when (equal (string-to-char s) ?*)
10124 ;; Anchor on headlines, post may include tags.
10125 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10126 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10127 s (substring s 1)))
10128 (remove-text-properties
10129 0 (length s)
10130 '(face nil mouse-face nil keymap nil fontified nil) s)
10131 ;; Make a series of regular expressions to find a match
10132 (setq words (org-split-string s "[ \n\r\t]+")
10134 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10135 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10136 "\\)" markers)
10137 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10138 re2a (concat "[ \t\r\n]" re2a_)
10139 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10140 re4 (concat "[^a-zA-Z_]" re4_)
10142 re1 (concat pre re2 post)
10143 re3 (concat pre (if pre re4_ re4) post)
10144 re5 (concat pre ".*" re4)
10145 re2 (concat pre re2)
10146 re2a (concat pre (if pre re2a_ re2a))
10147 re4 (concat pre (if pre re4_ re4))
10148 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10149 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10150 re5 "\\)"
10152 (cond
10153 ((eq type 'org-occur) (org-occur reall))
10154 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10155 (t (goto-char (point-min))
10156 (setq type 'fuzzy)
10157 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10158 (org-search-not-self 1 re1 nil t)
10159 (org-search-not-self 1 re2 nil t)
10160 (org-search-not-self 1 re2a nil t)
10161 (org-search-not-self 1 re3 nil t)
10162 (org-search-not-self 1 re4 nil t)
10163 (org-search-not-self 1 re5 nil t)
10165 (goto-char (match-beginning 1))
10166 (goto-char pos)
10167 (error "No match"))))))
10168 (and (derived-mode-p 'org-mode)
10169 (not stealth)
10170 (org-show-context 'link-search))
10171 type))
10173 (defun org-search-not-self (group &rest args)
10174 "Execute `re-search-forward', but only accept matches that do not
10175 enclose the position of `org-open-link-marker'."
10176 (let ((m org-open-link-marker))
10177 (catch 'exit
10178 (while (apply 're-search-forward args)
10179 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10180 (goto-char (match-end group))
10181 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10182 (> (match-beginning 0) (marker-position m))
10183 (< (match-end 0) (marker-position m)))
10184 (save-match-data
10185 (or (not (org-in-regexp
10186 org-bracket-link-analytic-regexp 1))
10187 (not (match-end 4)) ; no description
10188 (and (<= (match-beginning 4) (point))
10189 (>= (match-end 4) (point))))))
10190 (throw 'exit (point))))))))
10192 (defun org-get-buffer-for-internal-link (buffer)
10193 "Return a buffer to be used for displaying the link target of internal links."
10194 (cond
10195 ((not org-display-internal-link-with-indirect-buffer)
10196 buffer)
10197 ((string-match "(Clone)$" (buffer-name buffer))
10198 (message "Buffer is already a clone, not making another one")
10199 ;; we also do not modify visibility in this case
10200 buffer)
10201 (t ; make a new indirect buffer for displaying the link
10202 (let* ((bn (buffer-name buffer))
10203 (ibn (concat bn "(Clone)"))
10204 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10205 (with-current-buffer ib (org-overview))
10206 ib))))
10208 (defun org-do-occur (regexp &optional cleanup)
10209 "Call the Emacs command `occur'.
10210 If CLEANUP is non-nil, remove the printout of the regular expression
10211 in the *Occur* buffer. This is useful if the regex is long and not useful
10212 to read."
10213 (occur regexp)
10214 (when cleanup
10215 (let ((cwin (selected-window)) win beg end)
10216 (when (setq win (get-buffer-window "*Occur*"))
10217 (select-window win))
10218 (goto-char (point-min))
10219 (when (re-search-forward "match[a-z]+" nil t)
10220 (setq beg (match-end 0))
10221 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10222 (setq end (1- (match-beginning 0)))))
10223 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10224 (goto-char (point-min))
10225 (select-window cwin))))
10227 ;;; The mark ring for links jumps
10229 (defvar org-mark-ring nil
10230 "Mark ring for positions before jumps in Org-mode.")
10231 (defvar org-mark-ring-last-goto nil
10232 "Last position in the mark ring used to go back.")
10233 ;; Fill and close the ring
10234 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10235 (loop for i from 1 to org-mark-ring-length do
10236 (push (make-marker) org-mark-ring))
10237 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10238 org-mark-ring)
10240 (defun org-mark-ring-push (&optional pos buffer)
10241 "Put the current position or POS into the mark ring and rotate it."
10242 (interactive)
10243 (setq pos (or pos (point)))
10244 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10245 (move-marker (car org-mark-ring)
10246 (or pos (point))
10247 (or buffer (current-buffer)))
10248 (message "%s"
10249 (substitute-command-keys
10250 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10252 (defun org-mark-ring-goto (&optional n)
10253 "Jump to the previous position in the mark ring.
10254 With prefix arg N, jump back that many stored positions. When
10255 called several times in succession, walk through the entire ring.
10256 Org-mode commands jumping to a different position in the current file,
10257 or to another Org-mode file, automatically push the old position
10258 onto the ring."
10259 (interactive "p")
10260 (let (p m)
10261 (if (eq last-command this-command)
10262 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10263 (setq p org-mark-ring))
10264 (setq org-mark-ring-last-goto p)
10265 (setq m (car p))
10266 (org-pop-to-buffer-same-window (marker-buffer m))
10267 (goto-char m)
10268 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10270 (defun org-remove-angle-brackets (s)
10271 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10272 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10274 (defun org-add-angle-brackets (s)
10275 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10276 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10278 (defun org-remove-double-quotes (s)
10279 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10280 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10283 ;;; Following specific links
10285 (defun org-follow-timestamp-link ()
10286 "Open an agenda view for the time-stamp date/range at point."
10287 (cond
10288 ((org-at-date-range-p t)
10289 (let ((org-agenda-start-on-weekday)
10290 (t1 (match-string 1))
10291 (t2 (match-string 2)) tt1 tt2)
10292 (setq tt1 (time-to-days (org-time-string-to-time t1))
10293 tt2 (time-to-days (org-time-string-to-time t2)))
10294 (let ((org-agenda-buffer-tmp-name
10295 (format "*Org Agenda(a:%s)"
10296 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10297 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10298 ((org-at-timestamp-p t)
10299 (let ((org-agenda-buffer-tmp-name
10300 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10301 (org-agenda-list nil (time-to-days (org-time-string-to-time
10302 (substring (match-string 1) 0 10)))
10303 1)))
10304 (t (error "This should not happen"))))
10307 ;;; Following file links
10308 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10309 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10310 (declare-function mailcap-mime-info
10311 "mailcap" (string &optional request no-decode))
10312 (defvar org-wait nil)
10313 (defun org-open-file (path &optional in-emacs line search)
10314 "Open the file at PATH.
10315 First, this expands any special file name abbreviations. Then the
10316 configuration variable `org-file-apps' is checked if it contains an
10317 entry for this file type, and if yes, the corresponding command is launched.
10319 If no application is found, Emacs simply visits the file.
10321 With optional prefix argument IN-EMACS, Emacs will visit the file.
10322 With a double \\[universal-argument] \\[universal-argument] \
10323 prefix arg, Org tries to avoid opening in Emacs
10324 and to use an external application to visit the file.
10326 Optional LINE specifies a line to go to, optional SEARCH a string
10327 to search for. If LINE or SEARCH is given, the file will be
10328 opened in Emacs, unless an entry from org-file-apps that makes
10329 use of groups in a regexp matches.
10331 If you want to change the way frames are used when following a
10332 link, please customize `org-link-frame-setup'.
10334 If the file does not exist, an error is thrown."
10335 (let* ((file (if (equal path "")
10336 buffer-file-name
10337 (substitute-in-file-name (expand-file-name path))))
10338 (file-apps (append org-file-apps (org-default-apps)))
10339 (apps (org-remove-if
10340 'org-file-apps-entry-match-against-dlink-p file-apps))
10341 (apps-dlink (org-remove-if-not
10342 'org-file-apps-entry-match-against-dlink-p file-apps))
10343 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10344 (dirp (if remp nil (file-directory-p file)))
10345 (file (if (and dirp org-open-directory-means-index-dot-org)
10346 (concat (file-name-as-directory file) "index.org")
10347 file))
10348 (a-m-a-p (assq 'auto-mode apps))
10349 (dfile (downcase file))
10350 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10351 (link (cond ((and (eq line nil)
10352 (eq search nil))
10353 file)
10354 (line
10355 (concat file "::" (number-to-string line)))
10356 (search
10357 (concat file "::" search))))
10358 (dlink (downcase link))
10359 (old-buffer (current-buffer))
10360 (old-pos (point))
10361 (old-mode major-mode)
10362 ext cmd link-match-data)
10363 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10364 (setq ext (match-string 1 dfile))
10365 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10366 (setq ext (match-string 1 dfile))))
10367 (cond
10368 ((member in-emacs '((16) system))
10369 (setq cmd (cdr (assoc 'system apps))))
10370 (in-emacs (setq cmd 'emacs))
10372 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10373 (and dirp (cdr (assoc 'directory apps)))
10374 ; first, try matching against apps-dlink
10375 ; if we get a match here, store the match data for later
10376 (let ((match (assoc-default dlink apps-dlink
10377 'string-match)))
10378 (if match
10379 (progn (setq link-match-data (match-data))
10380 match)
10381 (progn (setq in-emacs (or in-emacs line search))
10382 nil))) ; if we have no match in apps-dlink,
10383 ; always open the file in emacs if line or search
10384 ; is given (for backwards compatibility)
10385 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10386 'string-match)
10387 (cdr (assoc ext apps))
10388 (cdr (assoc t apps))))))
10389 (when (eq cmd 'system)
10390 (setq cmd (cdr (assoc 'system apps))))
10391 (when (eq cmd 'default)
10392 (setq cmd (cdr (assoc t apps))))
10393 (when (eq cmd 'mailcap)
10394 (require 'mailcap)
10395 (mailcap-parse-mailcaps)
10396 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10397 (command (mailcap-mime-info mime-type)))
10398 (if (stringp command)
10399 (setq cmd command)
10400 (setq cmd 'emacs))))
10401 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10402 (not (file-exists-p file))
10403 (not org-open-non-existing-files))
10404 (error "No such file: %s" file))
10405 (cond
10406 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10407 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10408 (while (string-match "['\"]%s['\"]" cmd)
10409 (setq cmd (replace-match "%s" t t cmd)))
10410 (while (string-match "%s" cmd)
10411 (setq cmd (replace-match
10412 (save-match-data
10413 (shell-quote-argument
10414 (convert-standard-filename file)))
10415 t t cmd)))
10417 ;; Replace "%1", "%2" etc. in command with group matches from regex
10418 (save-match-data
10419 (let ((match-index 1)
10420 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10421 (set-match-data link-match-data)
10422 (while (<= match-index number-of-groups)
10423 (let ((regex (concat "%" (number-to-string match-index)))
10424 (replace-with (match-string match-index dlink)))
10425 (while (string-match regex cmd)
10426 (setq cmd (replace-match replace-with t t cmd))))
10427 (setq match-index (+ match-index 1)))))
10429 (save-window-excursion
10430 (start-process-shell-command cmd nil cmd)
10431 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10433 ((or (stringp cmd)
10434 (eq cmd 'emacs))
10435 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10436 (widen)
10437 (if line (org-goto-line line)
10438 (if search (org-link-search search))))
10439 ((consp cmd)
10440 (let ((file (convert-standard-filename file)))
10441 (save-match-data
10442 (set-match-data link-match-data)
10443 (eval cmd))))
10444 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10445 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10446 (or (not (equal old-buffer (current-buffer)))
10447 (not (equal old-pos (point))))
10448 (org-mark-ring-push old-pos old-buffer))))
10450 (defun org-file-apps-entry-match-against-dlink-p (entry)
10451 "This function returns non-nil if `entry' uses a regular
10452 expression which should be matched against the whole link by
10453 org-open-file.
10455 It assumes that is the case when the entry uses a regular
10456 expression which has at least one grouping construct and the
10457 action is either a lisp form or a command string containing
10458 '%1', i.e. using at least one subexpression match as a
10459 parameter."
10460 (let ((selector (car entry))
10461 (action (cdr entry)))
10462 (if (stringp selector)
10463 (and (> (regexp-opt-depth selector) 0)
10464 (or (and (stringp action)
10465 (string-match "%[0-9]" action))
10466 (consp action)))
10467 nil)))
10469 (defun org-default-apps ()
10470 "Return the default applications for this operating system."
10471 (cond
10472 ((eq system-type 'darwin)
10473 org-file-apps-defaults-macosx)
10474 ((eq system-type 'windows-nt)
10475 org-file-apps-defaults-windowsnt)
10476 (t org-file-apps-defaults-gnu)))
10478 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10479 "Convert extensions to regular expressions in the cars of LIST.
10480 Also, weed out any non-string entries, because the return value is used
10481 only for regexp matching.
10482 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10483 point to the symbol `emacs', indicating that the file should
10484 be opened in Emacs."
10485 (append
10486 (delq nil
10487 (mapcar (lambda (x)
10488 (if (not (stringp (car x)))
10490 (if (string-match "\\W" (car x))
10492 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10493 list))
10494 (if add-auto-mode
10495 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10497 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10498 (defun org-file-remote-p (file)
10499 "Test whether FILE specifies a location on a remote system.
10500 Return non-nil if the location is indeed remote.
10502 For example, the filename \"/user@host:/foo\" specifies a location
10503 on the system \"/user@host:\"."
10504 (cond ((fboundp 'file-remote-p)
10505 (file-remote-p file))
10506 ((fboundp 'tramp-handle-file-remote-p)
10507 (tramp-handle-file-remote-p file))
10508 ((and (boundp 'ange-ftp-name-format)
10509 (string-match (car ange-ftp-name-format) file))
10510 t)))
10513 ;;;; Refiling
10515 (defun org-get-org-file ()
10516 "Read a filename, with default directory `org-directory'."
10517 (let ((default (or org-default-notes-file remember-data-file)))
10518 (read-file-name (format "File name [%s]: " default)
10519 (file-name-as-directory org-directory)
10520 default)))
10522 (defun org-notes-order-reversed-p ()
10523 "Check if the current file should receive notes in reversed order."
10524 (cond
10525 ((not org-reverse-note-order) nil)
10526 ((eq t org-reverse-note-order) t)
10527 ((not (listp org-reverse-note-order)) nil)
10528 (t (catch 'exit
10529 (let ((all org-reverse-note-order)
10530 entry)
10531 (while (setq entry (pop all))
10532 (if (string-match (car entry) buffer-file-name)
10533 (throw 'exit (cdr entry))))
10534 nil)))))
10536 (defvar org-refile-target-table nil
10537 "The list of refile targets, created by `org-refile'.")
10539 (defvar org-agenda-new-buffers nil
10540 "Buffers created to visit agenda files.")
10542 (defvar org-refile-cache nil
10543 "Cache for refile targets.")
10545 (defvar org-refile-markers nil
10546 "All the markers used for caching refile locations.")
10548 (defun org-refile-marker (pos)
10549 "Get a new refile marker, but only if caching is in use."
10550 (if (not org-refile-use-cache)
10552 (let ((m (make-marker)))
10553 (move-marker m pos)
10554 (push m org-refile-markers)
10555 m)))
10557 (defun org-refile-cache-clear ()
10558 "Clear the refile cache and disable all the markers."
10559 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10560 (setq org-refile-markers nil)
10561 (setq org-refile-cache nil)
10562 (message "Refile cache has been cleared"))
10564 (defun org-refile-cache-check-set (set)
10565 "Check if all the markers in the cache still have live buffers."
10566 (let (marker)
10567 (catch 'exit
10568 (while (and set (setq marker (nth 3 (pop set))))
10569 ;; if org-refile-use-outline-path is 'file, marker may be nil
10570 (when (and marker (null (marker-buffer marker)))
10571 (message "not found") (sit-for 3)
10572 (throw 'exit nil)))
10573 t)))
10575 (defun org-refile-cache-put (set &rest identifiers)
10576 "Push the refile targets SET into the cache, under IDENTIFIERS."
10577 (let* ((key (sha1 (prin1-to-string identifiers)))
10578 (entry (assoc key org-refile-cache)))
10579 (if entry
10580 (setcdr entry set)
10581 (push (cons key set) org-refile-cache))))
10583 (defun org-refile-cache-get (&rest identifiers)
10584 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10585 (cond
10586 ((not org-refile-cache) nil)
10587 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10589 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10590 org-refile-cache))))
10591 (and set (org-refile-cache-check-set set) set)))))
10593 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10594 "Produce a table with refile targets."
10595 (let ((case-fold-search nil)
10596 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10597 (entries (or org-refile-targets '((nil . (:level . 1)))))
10598 targets tgs txt re files f desc descre fast-path-p level pos0)
10599 (message "Getting targets...")
10600 (with-current-buffer (or default-buffer (current-buffer))
10601 (while (setq entry (pop entries))
10602 (setq files (car entry) desc (cdr entry))
10603 (setq fast-path-p nil)
10604 (cond
10605 ((null files) (setq files (list (current-buffer))))
10606 ((eq files 'org-agenda-files)
10607 (setq files (org-agenda-files 'unrestricted)))
10608 ((and (symbolp files) (fboundp files))
10609 (setq files (funcall files)))
10610 ((and (symbolp files) (boundp files))
10611 (setq files (symbol-value files))))
10612 (if (stringp files) (setq files (list files)))
10613 (cond
10614 ((eq (car desc) :tag)
10615 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10616 ((eq (car desc) :todo)
10617 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10618 ((eq (car desc) :regexp)
10619 (setq descre (cdr desc)))
10620 ((eq (car desc) :level)
10621 (setq descre (concat "^\\*\\{" (number-to-string
10622 (if org-odd-levels-only
10623 (1- (* 2 (cdr desc)))
10624 (cdr desc)))
10625 "\\}[ \t]")))
10626 ((eq (car desc) :maxlevel)
10627 (setq fast-path-p t)
10628 (setq descre (concat "^\\*\\{1," (number-to-string
10629 (if org-odd-levels-only
10630 (1- (* 2 (cdr desc)))
10631 (cdr desc)))
10632 "\\}[ \t]")))
10633 (t (error "Bad refiling target description %s" desc)))
10634 (while (setq f (pop files))
10635 (with-current-buffer
10636 (if (bufferp f) f (org-get-agenda-file-buffer f))
10638 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10639 (progn
10640 (if (bufferp f) (setq f (buffer-file-name
10641 (buffer-base-buffer f))))
10642 (setq f (and f (expand-file-name f)))
10643 (if (eq org-refile-use-outline-path 'file)
10644 (push (list (file-name-nondirectory f) f nil nil) tgs))
10645 (save-excursion
10646 (save-restriction
10647 (widen)
10648 (goto-char (point-min))
10649 (while (re-search-forward descre nil t)
10650 (goto-char (setq pos0 (point-at-bol)))
10651 (catch 'next
10652 (when org-refile-target-verify-function
10653 (save-match-data
10654 (or (funcall org-refile-target-verify-function)
10655 (throw 'next t))))
10656 (when (and (looking-at org-complex-heading-regexp)
10657 (not (member (match-string 4) excluded-entries))
10658 (match-string 4))
10659 (setq level (org-reduced-level
10660 (- (match-end 1) (match-beginning 1)))
10661 txt (org-link-display-format (match-string 4))
10662 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10663 re (format org-complex-heading-regexp-format
10664 (regexp-quote (match-string 4))))
10665 (when org-refile-use-outline-path
10666 (setq txt (mapconcat
10667 'org-protect-slash
10668 (append
10669 (if (eq org-refile-use-outline-path
10670 'file)
10671 (list (file-name-nondirectory
10672 (buffer-file-name
10673 (buffer-base-buffer))))
10674 (if (eq org-refile-use-outline-path
10675 'full-file-path)
10676 (list (buffer-file-name
10677 (buffer-base-buffer)))))
10678 (org-get-outline-path fast-path-p
10679 level txt)
10680 (list txt))
10681 "/")))
10682 (push (list txt f re (org-refile-marker (point)))
10683 tgs)))
10684 (when (= (point) pos0)
10685 ;; verification function has not moved point
10686 (goto-char (point-at-eol))))))))
10687 (when org-refile-use-cache
10688 (org-refile-cache-put tgs (buffer-file-name) descre))
10689 (setq targets (append tgs targets))
10690 ))))
10691 (message "Getting targets...done")
10692 (nreverse targets)))
10694 (defun org-protect-slash (s)
10695 (while (string-match "/" s)
10696 (setq s (replace-match "\\" t t s)))
10699 (defvar org-olpa (make-vector 20 nil))
10701 (defun org-get-outline-path (&optional fastp level heading)
10702 "Return the outline path to the current entry, as a list.
10704 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10705 routine which makes outline path derivations for an entire file,
10706 avoiding backtracing. Refile target collection makes use of that."
10707 (if fastp
10708 (progn
10709 (if (> level 19)
10710 (error "Outline path failure, more than 19 levels"))
10711 (loop for i from level upto 19 do
10712 (aset org-olpa i nil))
10713 (prog1
10714 (delq nil (append org-olpa nil))
10715 (aset org-olpa level heading)))
10716 (let (rtn case-fold-search)
10717 (save-excursion
10718 (save-restriction
10719 (widen)
10720 (while (org-up-heading-safe)
10721 (when (looking-at org-complex-heading-regexp)
10722 (push (org-match-string-no-properties 4) rtn)))
10723 rtn)))))
10725 (defun org-format-outline-path (path &optional width prefix)
10726 "Format the outline path PATH for display.
10727 Width is the maximum number of characters that is available.
10728 Prefix is a prefix to be included in the returned string,
10729 such as the file name."
10730 (setq width (or width 79))
10731 (if prefix (setq width (- width (length prefix))))
10732 (if (not path)
10733 (or prefix "")
10734 (let* ((nsteps (length path))
10735 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10736 (maxwidth (if (<= total-width width)
10737 10000 ;; everything fits
10738 ;; we need to shorten the level headings
10739 (/ (- width nsteps) nsteps)))
10740 (org-odd-levels-only nil)
10741 (n 0)
10742 (total (1+ (length prefix))))
10743 (setq maxwidth (max maxwidth 10))
10744 (concat prefix
10745 (mapconcat
10746 (lambda (h)
10747 (setq n (1+ n))
10748 (if (and (= n nsteps) (< maxwidth 10000))
10749 (setq maxwidth (- total-width total)))
10750 (if (< (length h) maxwidth)
10751 (progn (setq total (+ total (length h) 1)) h)
10752 (setq h (substring h 0 (- maxwidth 2))
10753 total (+ total maxwidth 1))
10754 (if (string-match "[ \t]+\\'" h)
10755 (setq h (substring h 0 (match-beginning 0))))
10756 (setq h (concat h "..")))
10757 (org-add-props h nil 'face
10758 (nth (% (1- n) org-n-level-faces)
10759 org-level-faces))
10761 path "/")))))
10763 (defun org-display-outline-path (&optional file current)
10764 "Display the current outline path in the echo area."
10765 (interactive "P")
10766 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10767 (case-fold-search nil)
10768 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10769 (if current (setq path (append path
10770 (save-excursion
10771 (org-back-to-heading t)
10772 (if (looking-at org-complex-heading-regexp)
10773 (list (match-string 4)))))))
10774 (message "%s"
10775 (org-format-outline-path
10776 path
10777 (1- (frame-width))
10778 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10780 (defvar org-refile-history nil
10781 "History for refiling operations.")
10783 (defvar org-after-refile-insert-hook nil
10784 "Hook run after `org-refile' has inserted its stuff at the new location.
10785 Note that this is still *before* the stuff will be removed from
10786 the *old* location.")
10788 (defvar org-capture-last-stored-marker)
10789 (defun org-refile (&optional goto default-buffer rfloc)
10790 "Move the entry or entries at point to another heading.
10791 The list of target headings is compiled using the information in
10792 `org-refile-targets', which see.
10794 At the target location, the entry is filed as a subitem of the target
10795 heading. Depending on `org-reverse-note-order', the new subitem will
10796 either be the first or the last subitem.
10798 If there is an active region, all entries in that region will be moved.
10799 However, the region must fulfill the requirement that the first heading
10800 is the first one sets the top-level of the moved text - at most siblings
10801 below it are allowed.
10803 With prefix arg GOTO, the command will only visit the target location
10804 and not actually move anything.
10806 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10807 go to the location where the last refiling operation has put the subtree.
10808 With a prefix argument of `2', refile to the running clock.
10810 RFLOC can be a refile location obtained in a different way.
10812 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10814 If you are using target caching (see `org-refile-use-cache'),
10815 you have to clear the target cache in order to find new targets.
10816 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10817 prefix argument (`C-u C-u C-u C-c C-w')."
10819 (interactive "P")
10820 (if (member goto '(0 (64)))
10821 (org-refile-cache-clear)
10822 (let* ((cbuf (current-buffer))
10823 (regionp (org-region-active-p))
10824 (region-start (and regionp (region-beginning)))
10825 (region-end (and regionp (region-end)))
10826 (region-length (and regionp (- region-end region-start)))
10827 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10828 pos it nbuf file re level reversed)
10829 (setq last-command nil)
10830 (when regionp
10831 (goto-char region-start)
10832 (or (bolp) (goto-char (point-at-bol)))
10833 (setq region-start (point))
10834 (unless (or (org-kill-is-subtree-p
10835 (buffer-substring region-start region-end))
10836 (prog1 org-refile-active-region-within-subtree
10837 (org-toggle-heading)))
10838 (error "The region is not a (sequence of) subtree(s)")))
10839 (if (equal goto '(16))
10840 (org-refile-goto-last-stored)
10841 (when (or
10842 (and (equal goto 2)
10843 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10844 (prog1
10845 (setq it (list (or org-clock-heading "running clock")
10846 (buffer-file-name
10847 (marker-buffer org-clock-hd-marker))
10849 (marker-position org-clock-hd-marker)))
10850 (setq goto nil)))
10851 (setq it (or rfloc
10852 (let (heading-text)
10853 (save-excursion
10854 (unless goto
10855 (org-back-to-heading t)
10856 (setq heading-text
10857 (nth 4 (org-heading-components))))
10858 (org-refile-get-location
10859 (cond (goto "Goto")
10860 (regionp "Refile region to")
10861 (t (concat "Refile subtree \""
10862 heading-text "\" to")))
10863 default-buffer
10864 (and (not (equal '(4) goto))
10865 org-refile-allow-creating-parent-nodes)
10866 goto))))))
10867 (setq file (nth 1 it)
10868 re (nth 2 it)
10869 pos (nth 3 it))
10870 (if (and (not goto)
10872 (equal (buffer-file-name) file)
10873 (if regionp
10874 (and (>= pos region-start)
10875 (<= pos region-end))
10876 (and (>= pos (point))
10877 (< pos (save-excursion
10878 (org-end-of-subtree t t))))))
10879 (error "Cannot refile to position inside the tree or region"))
10881 (setq nbuf (or (find-buffer-visiting file)
10882 (find-file-noselect file)))
10883 (if goto
10884 (progn
10885 (org-pop-to-buffer-same-window nbuf)
10886 (goto-char pos)
10887 (org-show-context 'org-goto))
10888 (if regionp
10889 (progn
10890 (org-kill-new (buffer-substring region-start region-end))
10891 (org-save-markers-in-region region-start region-end))
10892 (org-copy-subtree 1 nil t))
10893 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10894 (find-file-noselect file)))
10895 (setq reversed (org-notes-order-reversed-p))
10896 (save-excursion
10897 (save-restriction
10898 (widen)
10899 (if pos
10900 (progn
10901 (goto-char pos)
10902 (looking-at org-outline-regexp)
10903 (setq level (org-get-valid-level (funcall outline-level) 1))
10904 (goto-char
10905 (if reversed
10906 (or (outline-next-heading) (point-max))
10907 (or (save-excursion (org-get-next-sibling))
10908 (org-end-of-subtree t t)
10909 (point-max)))))
10910 (setq level 1)
10911 (if (not reversed)
10912 (goto-char (point-max))
10913 (goto-char (point-min))
10914 (or (outline-next-heading) (goto-char (point-max)))))
10915 (if (not (bolp)) (newline))
10916 (org-paste-subtree level)
10917 (when org-log-refile
10918 (org-add-log-setup 'refile nil nil 'findpos
10919 org-log-refile)
10920 (unless (eq org-log-refile 'note)
10921 (save-excursion (org-add-log-note))))
10922 (and org-auto-align-tags
10923 (let ((org-loop-over-headlines-in-active-region nil))
10924 (org-set-tags nil t)))
10925 (with-demoted-errors
10926 (bookmark-set "org-refile-last-stored"))
10927 ;; If we are refiling for capture, make sure that the
10928 ;; last-capture pointers point here
10929 (when (org-bound-and-true-p org-refile-for-capture)
10930 (with-demoted-errors
10931 (bookmark-set "org-capture-last-stored-marker"))
10932 (move-marker org-capture-last-stored-marker (point)))
10933 (if (fboundp 'deactivate-mark) (deactivate-mark))
10934 (run-hooks 'org-after-refile-insert-hook))))
10935 (if regionp
10936 (delete-region (point) (+ (point) region-length))
10937 (org-cut-subtree))
10938 (when (featurep 'org-inlinetask)
10939 (org-inlinetask-remove-END-maybe))
10940 (setq org-markers-to-move nil)
10941 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10943 (defun org-refile-goto-last-stored ()
10944 "Go to the location where the last refile was stored."
10945 (interactive)
10946 (bookmark-jump "org-refile-last-stored")
10947 (message "This is the location of the last refile"))
10949 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10950 no-exclude)
10951 "Prompt the user for a refile location, using PROMPT.
10952 PROMPT should not be suffixed with a colon and a space, because
10953 this function appends the default value from
10954 `org-refile-history' automatically, if that is not empty.
10955 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10956 this is used for the GOTO interface."
10957 (let ((org-refile-targets org-refile-targets)
10958 (org-refile-use-outline-path org-refile-use-outline-path)
10959 excluded-entries)
10960 (when (and (derived-mode-p 'org-mode)
10961 (not org-refile-use-cache)
10962 (not no-exclude))
10963 (org-map-tree
10964 (lambda()
10965 (setq excluded-entries
10966 (append excluded-entries (list (org-get-heading t t)))))))
10967 (setq org-refile-target-table
10968 (org-refile-get-targets default-buffer excluded-entries)))
10969 (unless org-refile-target-table
10970 (error "No refile targets"))
10971 (let* ((prompt (concat prompt
10972 (and (car org-refile-history)
10973 (concat " (default " (car org-refile-history) ")"))
10974 ": "))
10975 (cbuf (current-buffer))
10976 (partial-completion-mode nil)
10977 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10978 (cfunc (if (and org-refile-use-outline-path
10979 org-outline-path-complete-in-steps)
10980 'org-olpath-completing-read
10981 'org-icompleting-read))
10982 (extra (if org-refile-use-outline-path "/" ""))
10983 (filename (and cfn (expand-file-name cfn)))
10984 (tbl (mapcar
10985 (lambda (x)
10986 (if (and (not (member org-refile-use-outline-path
10987 '(file full-file-path)))
10988 (not (equal filename (nth 1 x))))
10989 (cons (concat (car x) extra " ("
10990 (file-name-nondirectory (nth 1 x)) ")")
10991 (cdr x))
10992 (cons (concat (car x) extra) (cdr x))))
10993 org-refile-target-table))
10994 (completion-ignore-case t)
10995 pa answ parent-target child parent old-hist)
10996 (setq old-hist org-refile-history)
10997 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10998 nil 'org-refile-history (car org-refile-history)))
10999 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11000 (org-refile-check-position pa)
11001 (if pa
11002 (progn
11003 (when (or (not org-refile-history)
11004 (not (eq old-hist org-refile-history))
11005 (not (equal (car pa) (car org-refile-history))))
11006 (setq org-refile-history
11007 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11008 org-refile-history
11009 (cdr org-refile-history))))
11010 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11011 (pop org-refile-history)))
11013 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11014 (progn
11015 (setq parent (match-string 1 answ)
11016 child (match-string 2 answ))
11017 (setq parent-target (or (assoc parent tbl)
11018 (assoc (concat parent "/") tbl)))
11019 (when (and parent-target
11020 (or (eq new-nodes t)
11021 (and (eq new-nodes 'confirm)
11022 (y-or-n-p (format "Create new node \"%s\"? "
11023 child)))))
11024 (org-refile-new-child parent-target child)))
11025 (error "Invalid target location")))))
11027 (declare-function org-string-nw-p "org-macs" (s))
11028 (defun org-refile-check-position (refile-pointer)
11029 "Check if the refile pointer matches the headline to which it points."
11030 (let* ((file (nth 1 refile-pointer))
11031 (re (nth 2 refile-pointer))
11032 (pos (nth 3 refile-pointer))
11033 buffer)
11034 (if (and (not (markerp pos)) (not file))
11035 (error "Please save the buffer to a file before refiling")
11036 (when (org-string-nw-p re)
11037 (setq buffer (if (markerp pos)
11038 (marker-buffer pos)
11039 (or (find-buffer-visiting file)
11040 (find-file-noselect file))))
11041 (with-current-buffer buffer
11042 (save-excursion
11043 (save-restriction
11044 (widen)
11045 (goto-char pos)
11046 (beginning-of-line 1)
11047 (unless (org-looking-at-p re)
11048 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11050 (defun org-refile-new-child (parent-target child)
11051 "Use refile target PARENT-TARGET to add new CHILD below it."
11052 (unless parent-target
11053 (error "Cannot find parent for new node"))
11054 (let ((file (nth 1 parent-target))
11055 (pos (nth 3 parent-target))
11056 level)
11057 (with-current-buffer (or (find-buffer-visiting file)
11058 (find-file-noselect file))
11059 (save-excursion
11060 (save-restriction
11061 (widen)
11062 (if pos
11063 (goto-char pos)
11064 (goto-char (point-max))
11065 (if (not (bolp)) (newline)))
11066 (when (looking-at org-outline-regexp)
11067 (setq level (funcall outline-level))
11068 (org-end-of-subtree t t))
11069 (org-back-over-empty-lines)
11070 (insert "\n" (make-string
11071 (if pos (org-get-valid-level level 1) 1) ?*)
11072 " " child "\n")
11073 (beginning-of-line 0)
11074 (list (concat (car parent-target) "/" child) file "" (point)))))))
11076 (defun org-olpath-completing-read (prompt collection &rest args)
11077 "Read an outline path like a file name."
11078 (let ((thetable collection)
11079 (org-completion-use-ido nil) ; does not work with ido.
11080 (org-completion-use-iswitchb nil)) ; or iswitchb
11081 (apply
11082 'org-icompleting-read prompt
11083 (lambda (string predicate &optional flag)
11084 (let (rtn r f (l (length string)))
11085 (cond
11086 ((eq flag nil)
11087 ;; try completion
11088 (try-completion string thetable))
11089 ((eq flag t)
11090 ;; all-completions
11091 (setq rtn (all-completions string thetable predicate))
11092 (mapcar
11093 (lambda (x)
11094 (setq r (substring x l))
11095 (if (string-match " ([^)]*)$" x)
11096 (setq f (match-string 0 x))
11097 (setq f ""))
11098 (if (string-match "/" r)
11099 (concat string (substring r 0 (match-end 0)) f)
11101 rtn))
11102 ((eq flag 'lambda)
11103 ;; exact match?
11104 (assoc string thetable)))))
11105 args)))
11107 ;;;; Dynamic blocks
11109 (defun org-find-dblock (name)
11110 "Find the first dynamic block with name NAME in the buffer.
11111 If not found, stay at current position and return nil."
11112 (let ((case-fold-search t) pos)
11113 (save-excursion
11114 (goto-char (point-min))
11115 (setq pos (and (re-search-forward
11116 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11117 (match-beginning 0))))
11118 (if pos (goto-char pos))
11119 pos))
11121 (defconst org-dblock-start-re
11122 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11123 "Matches the start line of a dynamic block, with parameters.")
11125 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11126 "Matches the end of a dynamic block.")
11128 (defun org-create-dblock (plist)
11129 "Create a dynamic block section, with parameters taken from PLIST.
11130 PLIST must contain a :name entry which is used as name of the block."
11131 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11132 (end-of-line 1)
11133 (newline))
11134 (let ((col (current-column))
11135 (name (plist-get plist :name)))
11136 (insert "#+BEGIN: " name)
11137 (while plist
11138 (if (eq (car plist) :name)
11139 (setq plist (cddr plist))
11140 (insert " " (prin1-to-string (pop plist)))))
11141 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11142 (beginning-of-line -2)))
11144 (defun org-prepare-dblock ()
11145 "Prepare dynamic block for refresh.
11146 This empties the block, puts the cursor at the insert position and returns
11147 the property list including an extra property :name with the block name."
11148 (unless (looking-at org-dblock-start-re)
11149 (error "Not at a dynamic block"))
11150 (let* ((begdel (1+ (match-end 0)))
11151 (name (org-no-properties (match-string 1)))
11152 (params (append (list :name name)
11153 (read (concat "(" (match-string 3) ")")))))
11154 (save-excursion
11155 (beginning-of-line 1)
11156 (skip-chars-forward " \t")
11157 (setq params (plist-put params :indentation-column (current-column))))
11158 (unless (re-search-forward org-dblock-end-re nil t)
11159 (error "Dynamic block not terminated"))
11160 (setq params
11161 (append params
11162 (list :content (buffer-substring
11163 begdel (match-beginning 0)))))
11164 (delete-region begdel (match-beginning 0))
11165 (goto-char begdel)
11166 (open-line 1)
11167 params))
11169 (defun org-map-dblocks (&optional command)
11170 "Apply COMMAND to all dynamic blocks in the current buffer.
11171 If COMMAND is not given, use `org-update-dblock'."
11172 (let ((cmd (or command 'org-update-dblock)))
11173 (save-excursion
11174 (goto-char (point-min))
11175 (while (re-search-forward org-dblock-start-re nil t)
11176 (goto-char (match-beginning 0))
11177 (save-excursion
11178 (condition-case nil
11179 (funcall cmd)
11180 (error (message "Error during update of dynamic block"))))
11181 (unless (re-search-forward org-dblock-end-re nil t)
11182 (error "Dynamic block not terminated"))))))
11184 (defun org-dblock-update (&optional arg)
11185 "User command for updating dynamic blocks.
11186 Update the dynamic block at point. With prefix ARG, update all dynamic
11187 blocks in the buffer."
11188 (interactive "P")
11189 (if arg
11190 (org-update-all-dblocks)
11191 (or (looking-at org-dblock-start-re)
11192 (org-beginning-of-dblock))
11193 (org-update-dblock)))
11195 (defun org-update-dblock ()
11196 "Update the dynamic block at point.
11197 This means to empty the block, parse for parameters and then call
11198 the correct writing function."
11199 (interactive)
11200 (save-window-excursion
11201 (let* ((pos (point))
11202 (line (org-current-line))
11203 (params (org-prepare-dblock))
11204 (name (plist-get params :name))
11205 (indent (plist-get params :indentation-column))
11206 (cmd (intern (concat "org-dblock-write:" name))))
11207 (message "Updating dynamic block `%s' at line %d..." name line)
11208 (funcall cmd params)
11209 (message "Updating dynamic block `%s' at line %d...done" name line)
11210 (goto-char pos)
11211 (when (and indent (> indent 0))
11212 (setq indent (make-string indent ?\ ))
11213 (save-excursion
11214 (org-beginning-of-dblock)
11215 (forward-line 1)
11216 (while (not (looking-at org-dblock-end-re))
11217 (insert indent)
11218 (beginning-of-line 2))
11219 (when (looking-at org-dblock-end-re)
11220 (and (looking-at "[ \t]+")
11221 (replace-match ""))
11222 (insert indent)))))))
11224 (defun org-beginning-of-dblock ()
11225 "Find the beginning of the dynamic block at point.
11226 Error if there is no such block at point."
11227 (let ((pos (point))
11228 beg)
11229 (end-of-line 1)
11230 (if (and (re-search-backward org-dblock-start-re nil t)
11231 (setq beg (match-beginning 0))
11232 (re-search-forward org-dblock-end-re nil t)
11233 (> (match-end 0) pos))
11234 (goto-char beg)
11235 (goto-char pos)
11236 (error "Not in a dynamic block"))))
11238 (defun org-update-all-dblocks ()
11239 "Update all dynamic blocks in the buffer.
11240 This function can be used in a hook."
11241 (interactive)
11242 (when (derived-mode-p 'org-mode)
11243 (org-map-dblocks 'org-update-dblock)))
11246 ;;;; Completion
11248 (defconst org-additional-option-like-keywords
11249 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11250 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11251 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11252 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11253 "BEGIN:" "END:"
11254 "ORGTBL" "TBLFM:" "TBLNAME:"
11255 "BEGIN_EXAMPLE" "END_EXAMPLE"
11256 "BEGIN_VERBATIM" "END_VERBATIM"
11257 "BEGIN_QUOTE" "END_QUOTE"
11258 "BEGIN_VERSE" "END_VERSE"
11259 "BEGIN_CENTER" "END_CENTER"
11260 "BEGIN_SRC" "END_SRC"
11261 "BEGIN_RESULT" "END_RESULT"
11262 "BEGIN_lstlisting" "END_lstlisting"
11263 "NAME:" "RESULTS:"
11264 "HEADER:" "HEADERS:"
11265 "COLUMNS:" "PROPERTY:"
11266 "CAPTION:" "LABEL:"
11267 "SETUPFILE:"
11268 "INCLUDE:" "INDEX:"
11269 "BIND:"
11270 "MACRO:"))
11272 (defconst org-options-keywords
11273 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11274 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11275 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11276 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11277 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11278 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11279 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11281 (defconst org-additional-option-like-keywords-for-flyspell
11282 (delete-dups
11283 (split-string
11284 (mapconcat (lambda(k)
11285 (replace-regexp-in-string
11286 "_\\|:" " "
11287 (concat k " " (downcase k) " " (upcase k))))
11288 (append org-options-keywords org-additional-option-like-keywords)
11289 " ")
11290 " +" t)))
11292 (defcustom org-structure-template-alist
11293 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11294 "<src lang=\"?\">\n\n</src>")
11295 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11296 "<example>\n?\n</example>")
11297 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11298 "<quote>\n?\n</quote>")
11299 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11300 "<verse>\n?\n</verse>")
11301 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11302 "<verbatim>\n?\n</verbatim>")
11303 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11304 "<center>\n?\n</center>")
11305 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11306 "<literal style=\"latex\">\n?\n</literal>")
11307 ("L" "#+LaTeX: "
11308 "<literal style=\"latex\">?</literal>")
11309 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11310 "<literal style=\"html\">\n?\n</literal>")
11311 ("H" "#+HTML: "
11312 "<literal style=\"html\">?</literal>")
11313 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11314 ("A" "#+ASCII: ")
11315 ("i" "#+INDEX: ?"
11316 "#+INDEX: ?")
11317 ("I" "#+INCLUDE: %file ?"
11318 "<include file=%file markup=\"?\">"))
11319 "Structure completion elements.
11320 This is a list of abbreviation keys and values. The value gets inserted
11321 if you type `<' followed by the key and then press the completion key,
11322 usually `M-TAB'. %file will be replaced by a file name after prompting
11323 for the file using completion. The cursor will be placed at the position
11324 of the `?` in the template.
11325 There are two templates for each key, the first uses the original Org syntax,
11326 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11327 the default when the /org-mtags.el/ module has been loaded. See also the
11328 variable `org-mtags-prefer-muse-templates'."
11329 :group 'org-completion
11330 :type '(repeat
11331 (string :tag "Key")
11332 (string :tag "Template")
11333 (string :tag "Muse Template")))
11335 (defun org-try-structure-completion ()
11336 "Try to complete a structure template before point.
11337 This looks for strings like \"<e\" on an otherwise empty line and
11338 expands them."
11339 (let ((l (buffer-substring (point-at-bol) (point)))
11341 (when (and (looking-at "[ \t]*$")
11342 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11343 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11344 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11345 (match-beginning 1)) a)
11346 t)))
11348 (defun org-complete-expand-structure-template (start cell)
11349 "Expand a structure template."
11350 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11351 (rpl (nth (if musep 2 1) cell))
11352 (ind ""))
11353 (delete-region start (point))
11354 (when (string-match "\\`#\\+" rpl)
11355 (cond
11356 ((bolp))
11357 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11358 (setq ind (buffer-substring (point-at-bol) (point))))
11359 (t (newline))))
11360 (setq start (point))
11361 (if (string-match "%file" rpl)
11362 (setq rpl (replace-match
11363 (concat
11364 "\""
11365 (save-match-data
11366 (abbreviate-file-name (read-file-name "Include file: ")))
11367 "\"")
11368 t t rpl)))
11369 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11370 (concat "\n" ind)))
11371 (insert rpl)
11372 (if (re-search-backward "\\?" start t) (delete-char 1))))
11374 ;;;; TODO, DEADLINE, Comments
11376 (defun org-toggle-comment ()
11377 "Change the COMMENT state of an entry."
11378 (interactive)
11379 (save-excursion
11380 (org-back-to-heading)
11381 (let (case-fold-search)
11382 (cond
11383 ((looking-at (format org-heading-keyword-regexp-format
11384 org-comment-string))
11385 (goto-char (match-end 1))
11386 (looking-at (concat " +" org-comment-string))
11387 (replace-match "" t t)
11388 (when (eolp) (insert " ")))
11389 ((looking-at org-outline-regexp)
11390 (goto-char (match-end 0))
11391 (insert org-comment-string " "))))))
11393 (defvar org-last-todo-state-is-todo nil
11394 "This is non-nil when the last TODO state change led to a TODO state.
11395 If the last change removed the TODO tag or switched to DONE, then
11396 this is nil.")
11398 (defvar org-setting-tags nil) ; dynamically skipped
11400 (defvar org-todo-setup-filter-hook nil
11401 "Hook for functions that pre-filter todo specs.
11402 Each function takes a todo spec and returns either nil or the spec
11403 transformed into canonical form." )
11405 (defvar org-todo-get-default-hook nil
11406 "Hook for functions that get a default item for todo.
11407 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11408 nil or a string to be used for the todo mark." )
11410 (defvar org-agenda-headline-snapshot-before-repeat)
11412 (defun org-current-effective-time ()
11413 "Return current time adjusted for `org-extend-today-until' variable."
11414 (let* ((ct (org-current-time))
11415 (dct (decode-time ct))
11416 (ct1
11417 (if (and org-use-effective-time
11418 (< (nth 2 dct) org-extend-today-until))
11419 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11420 ct)))
11421 ct1))
11423 (defun org-todo-yesterday (&optional arg)
11424 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11425 (interactive "P")
11426 (if (eq major-mode 'org-agenda-mode)
11427 (apply 'org-agenda-todo-yesterday arg)
11428 (let* ((hour (third (decode-time
11429 (org-current-time))))
11430 (org-extend-today-until (1+ hour)))
11431 (org-todo arg))))
11433 (defun org-todo (&optional arg)
11434 "Change the TODO state of an item.
11435 The state of an item is given by a keyword at the start of the heading,
11436 like
11437 *** TODO Write paper
11438 *** DONE Call mom
11440 The different keywords are specified in the variable `org-todo-keywords'.
11441 By default the available states are \"TODO\" and \"DONE\".
11442 So for this example: when the item starts with TODO, it is changed to DONE.
11443 When it starts with DONE, the DONE is removed. And when neither TODO nor
11444 DONE are present, add TODO at the beginning of the heading.
11446 With \\[universal-argument] prefix arg, use completion to determine the new \
11447 state.
11448 With numeric prefix arg, switch to that state.
11449 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11450 keywords (nextset).
11451 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11452 With a numeric prefix arg of 0, inhibit note taking for the change.
11454 For calling through lisp, arg is also interpreted in the following way:
11455 'none -> empty state
11456 \"\"(empty string) -> switch to empty state
11457 'done -> switch to DONE
11458 'nextset -> switch to the next set of keywords
11459 'previousset -> switch to the previous set of keywords
11460 \"WAITING\" -> switch to the specified keyword, but only if it
11461 really is a member of `org-todo-keywords'."
11462 (interactive "P")
11463 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11464 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11465 'region-start-level 'region))
11466 org-loop-over-headlines-in-active-region)
11467 (org-map-entries
11468 `(org-todo ,arg)
11469 org-loop-over-headlines-in-active-region
11470 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11471 (if (equal arg '(16)) (setq arg 'nextset))
11472 (let ((org-blocker-hook org-blocker-hook)
11473 commentp
11474 case-fold-search)
11475 (when (equal arg '(64))
11476 (setq arg nil org-blocker-hook nil))
11477 (when (and org-blocker-hook
11478 (or org-inhibit-blocking
11479 (org-entry-get nil "NOBLOCKING")))
11480 (setq org-blocker-hook nil))
11481 (save-excursion
11482 (catch 'exit
11483 (org-back-to-heading t)
11484 (when (looking-at (concat "^\\*+ " org-comment-string))
11485 (org-toggle-comment)
11486 (setq commentp t))
11487 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11488 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11489 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11490 (let* ((match-data (match-data))
11491 (startpos (point-at-bol))
11492 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11493 (org-log-done org-log-done)
11494 (org-log-repeat org-log-repeat)
11495 (org-todo-log-states org-todo-log-states)
11496 (org-inhibit-logging
11497 (if (equal arg 0)
11498 (progn (setq arg nil) 'note) org-inhibit-logging))
11499 (this (match-string 1))
11500 (hl-pos (match-beginning 0))
11501 (head (org-get-todo-sequence-head this))
11502 (ass (assoc head org-todo-kwd-alist))
11503 (interpret (nth 1 ass))
11504 (done-word (nth 3 ass))
11505 (final-done-word (nth 4 ass))
11506 (org-last-state (or this ""))
11507 (completion-ignore-case t)
11508 (member (member this org-todo-keywords-1))
11509 (tail (cdr member))
11510 (org-state (cond
11511 ((and org-todo-key-trigger
11512 (or (and (equal arg '(4))
11513 (eq org-use-fast-todo-selection 'prefix))
11514 (and (not arg) org-use-fast-todo-selection
11515 (not (eq org-use-fast-todo-selection
11516 'prefix)))))
11517 ;; Use fast selection
11518 (org-fast-todo-selection))
11519 ((and (equal arg '(4))
11520 (or (not org-use-fast-todo-selection)
11521 (not org-todo-key-trigger)))
11522 ;; Read a state with completion
11523 (org-icompleting-read
11524 "State: " (mapcar (lambda(x) (list x))
11525 org-todo-keywords-1)
11526 nil t))
11527 ((eq arg 'right)
11528 (if this
11529 (if tail (car tail) nil)
11530 (car org-todo-keywords-1)))
11531 ((eq arg 'left)
11532 (if (equal member org-todo-keywords-1)
11534 (if this
11535 (nth (- (length org-todo-keywords-1)
11536 (length tail) 2)
11537 org-todo-keywords-1)
11538 (org-last org-todo-keywords-1))))
11539 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11540 (setq arg nil))) ; hack to fall back to cycling
11541 (arg
11542 ;; user or caller requests a specific state
11543 (cond
11544 ((equal arg "") nil)
11545 ((eq arg 'none) nil)
11546 ((eq arg 'done) (or done-word (car org-done-keywords)))
11547 ((eq arg 'nextset)
11548 (or (car (cdr (member head org-todo-heads)))
11549 (car org-todo-heads)))
11550 ((eq arg 'previousset)
11551 (let ((org-todo-heads (reverse org-todo-heads)))
11552 (or (car (cdr (member head org-todo-heads)))
11553 (car org-todo-heads))))
11554 ((car (member arg org-todo-keywords-1)))
11555 ((stringp arg)
11556 (error "State `%s' not valid in this file" arg))
11557 ((nth (1- (prefix-numeric-value arg))
11558 org-todo-keywords-1))))
11559 ((null member) (or head (car org-todo-keywords-1)))
11560 ((equal this final-done-word) nil) ;; -> make empty
11561 ((null tail) nil) ;; -> first entry
11562 ((memq interpret '(type priority))
11563 (if (eq this-command last-command)
11564 (car tail)
11565 (if (> (length tail) 0)
11566 (or done-word (car org-done-keywords))
11567 nil)))
11569 (car tail))))
11570 (org-state (or
11571 (run-hook-with-args-until-success
11572 'org-todo-get-default-hook org-state org-last-state)
11573 org-state))
11574 (next (if org-state (concat " " org-state " ") " "))
11575 (change-plist (list :type 'todo-state-change :from this :to org-state
11576 :position startpos))
11577 dolog now-done-p)
11578 (when org-blocker-hook
11579 (setq org-last-todo-state-is-todo
11580 (not (member this org-done-keywords)))
11581 (unless (save-excursion
11582 (save-match-data
11583 (org-with-wide-buffer
11584 (run-hook-with-args-until-failure
11585 'org-blocker-hook change-plist))))
11586 (if (org-called-interactively-p 'interactive)
11587 (error "TODO state change from %s to %s blocked" this org-state)
11588 ;; fail silently
11589 (message "TODO state change from %s to %s blocked" this org-state)
11590 (throw 'exit nil))))
11591 (store-match-data match-data)
11592 (replace-match next t t)
11593 (unless (pos-visible-in-window-p hl-pos)
11594 (message "TODO state changed to %s" (org-trim next)))
11595 (unless head
11596 (setq head (org-get-todo-sequence-head org-state)
11597 ass (assoc head org-todo-kwd-alist)
11598 interpret (nth 1 ass)
11599 done-word (nth 3 ass)
11600 final-done-word (nth 4 ass)))
11601 (when (memq arg '(nextset previousset))
11602 (message "Keyword-Set %d/%d: %s"
11603 (- (length org-todo-sets) -1
11604 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11605 (length org-todo-sets)
11606 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11607 (setq org-last-todo-state-is-todo
11608 (not (member org-state org-done-keywords)))
11609 (setq now-done-p (and (member org-state org-done-keywords)
11610 (not (member this org-done-keywords))))
11611 (and logging (org-local-logging logging))
11612 (when (and (or org-todo-log-states org-log-done)
11613 (not (eq org-inhibit-logging t))
11614 (not (memq arg '(nextset previousset))))
11615 ;; we need to look at recording a time and note
11616 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11617 (nth 2 (assoc this org-todo-log-states))))
11618 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11619 (setq dolog 'time))
11620 (when (and org-state
11621 (member org-state org-not-done-keywords)
11622 (not (member this org-not-done-keywords)))
11623 ;; This is now a todo state and was not one before
11624 ;; If there was a CLOSED time stamp, get rid of it.
11625 (org-add-planning-info nil nil 'closed))
11626 (when (and now-done-p org-log-done)
11627 ;; It is now done, and it was not done before
11628 (org-add-planning-info 'closed (org-current-effective-time))
11629 (if (and (not dolog) (eq 'note org-log-done))
11630 (org-add-log-setup 'done org-state this 'findpos 'note)))
11631 (when (and org-state dolog)
11632 ;; This is a non-nil state, and we need to log it
11633 (org-add-log-setup 'state org-state this 'findpos dolog)))
11634 ;; Fixup tag positioning
11635 (org-todo-trigger-tag-changes org-state)
11636 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11637 (when org-provide-todo-statistics
11638 (org-update-parent-todo-statistics))
11639 (run-hooks 'org-after-todo-state-change-hook)
11640 (if (and arg (not (member org-state org-done-keywords)))
11641 (setq head (org-get-todo-sequence-head org-state)))
11642 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11643 ;; Do we need to trigger a repeat?
11644 (when now-done-p
11645 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11646 ;; This is for the agenda, take a snapshot of the headline.
11647 (save-match-data
11648 (setq org-agenda-headline-snapshot-before-repeat
11649 (org-get-heading))))
11650 (org-auto-repeat-maybe org-state))
11651 ;; Fixup cursor location if close to the keyword
11652 (if (and (outline-on-heading-p)
11653 (not (bolp))
11654 (save-excursion (beginning-of-line 1)
11655 (looking-at org-todo-line-regexp))
11656 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11657 (progn
11658 (goto-char (or (match-end 2) (match-end 1)))
11659 (and (looking-at " ") (just-one-space))))
11660 (when org-trigger-hook
11661 (save-excursion
11662 (run-hook-with-args 'org-trigger-hook change-plist)))
11663 (when commentp (org-toggle-comment))))))))
11665 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11666 "Block turning an entry into a TODO, using the hierarchy.
11667 This checks whether the current task should be blocked from state
11668 changes. Such blocking occurs when:
11670 1. The task has children which are not all in a completed state.
11672 2. A task has a parent with the property :ORDERED:, and there
11673 are siblings prior to the current task with incomplete
11674 status.
11676 3. The parent of the task is blocked because it has siblings that should
11677 be done first, or is child of a block grandparent TODO entry."
11679 (if (not org-enforce-todo-dependencies)
11680 t ; if locally turned off don't block
11681 (catch 'dont-block
11682 ;; If this is not a todo state change, or if this entry is already DONE,
11683 ;; do not block
11684 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11685 (member (plist-get change-plist :from)
11686 (cons 'done org-done-keywords))
11687 (member (plist-get change-plist :to)
11688 (cons 'todo org-not-done-keywords))
11689 (not (plist-get change-plist :to)))
11690 (throw 'dont-block t))
11691 ;; If this task has children, and any are undone, it's blocked
11692 (save-excursion
11693 (org-back-to-heading t)
11694 (let ((this-level (funcall outline-level)))
11695 (outline-next-heading)
11696 (let ((child-level (funcall outline-level)))
11697 (while (and (not (eobp))
11698 (> child-level this-level))
11699 ;; this todo has children, check whether they are all
11700 ;; completed
11701 (if (and (not (org-entry-is-done-p))
11702 (org-entry-is-todo-p))
11703 (throw 'dont-block nil))
11704 (outline-next-heading)
11705 (setq child-level (funcall outline-level))))))
11706 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11707 ;; any previous siblings are undone, it's blocked
11708 (save-excursion
11709 (org-back-to-heading t)
11710 (let* ((pos (point))
11711 (parent-pos (and (org-up-heading-safe) (point))))
11712 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11713 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11714 (forward-line 1)
11715 (re-search-forward org-not-done-heading-regexp pos t))
11716 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11717 ;; Search further up the hierarchy, to see if an ancestor is blocked
11718 (while t
11719 (goto-char parent-pos)
11720 (if (not (looking-at org-not-done-heading-regexp))
11721 (throw 'dont-block t)) ; do not block, parent is not a TODO
11722 (setq pos (point))
11723 (setq parent-pos (and (org-up-heading-safe) (point)))
11724 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11725 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11726 (forward-line 1)
11727 (re-search-forward org-not-done-heading-regexp pos t))
11728 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11730 (defcustom org-track-ordered-property-with-tag nil
11731 "Should the ORDERED property also be shown as a tag?
11732 The ORDERED property decides if an entry should require subtasks to be
11733 completed in sequence. Since a property is not very visible, setting
11734 this option means that toggling the ORDERED property with the command
11735 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11736 not relevant for the behavior, but it makes things more visible.
11738 Note that toggling the tag with tags commands will not change the property
11739 and therefore not influence behavior!
11741 This can be t, meaning the tag ORDERED should be used, It can also be a
11742 string to select a different tag for this task."
11743 :group 'org-todo
11744 :type '(choice
11745 (const :tag "No tracking" nil)
11746 (const :tag "Track with ORDERED tag" t)
11747 (string :tag "Use other tag")))
11749 (defun org-toggle-ordered-property ()
11750 "Toggle the ORDERED property of the current entry.
11751 For better visibility, you can track the value of this property with a tag.
11752 See variable `org-track-ordered-property-with-tag'."
11753 (interactive)
11754 (let* ((t1 org-track-ordered-property-with-tag)
11755 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11756 (save-excursion
11757 (org-back-to-heading)
11758 (if (org-entry-get nil "ORDERED")
11759 (progn
11760 (org-delete-property "ORDERED")
11761 (and tag (org-toggle-tag tag 'off))
11762 (message "Subtasks can be completed in arbitrary order"))
11763 (org-entry-put nil "ORDERED" "t")
11764 (and tag (org-toggle-tag tag 'on))
11765 (message "Subtasks must be completed in sequence")))))
11767 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11768 (defun org-block-todo-from-checkboxes (change-plist)
11769 "Block turning an entry into a TODO, using checkboxes.
11770 This checks whether the current task should be blocked from state
11771 changes because there are unchecked boxes in this entry."
11772 (if (not org-enforce-todo-checkbox-dependencies)
11773 t ; if locally turned off don't block
11774 (catch 'dont-block
11775 ;; If this is not a todo state change, or if this entry is already DONE,
11776 ;; do not block
11777 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11778 (member (plist-get change-plist :from)
11779 (cons 'done org-done-keywords))
11780 (member (plist-get change-plist :to)
11781 (cons 'todo org-not-done-keywords))
11782 (not (plist-get change-plist :to)))
11783 (throw 'dont-block t))
11784 ;; If this task has checkboxes that are not checked, it's blocked
11785 (save-excursion
11786 (org-back-to-heading t)
11787 (let ((beg (point)) end)
11788 (outline-next-heading)
11789 (setq end (point))
11790 (goto-char beg)
11791 (if (org-list-search-forward
11792 (concat (org-item-beginning-re)
11793 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11794 "\\[[- ]\\]")
11795 end t)
11796 (progn
11797 (if (boundp 'org-blocked-by-checkboxes)
11798 (setq org-blocked-by-checkboxes t))
11799 (throw 'dont-block nil)))))
11800 t))) ; do not block
11802 (defun org-entry-blocked-p ()
11803 "Is the current entry blocked?"
11804 (org-with-buffer-modified-unmodified
11805 (if (org-entry-get nil "NOBLOCKING")
11806 nil ;; Never block this entry
11807 (not
11808 (run-hook-with-args-until-failure
11809 'org-blocker-hook
11810 (list :type 'todo-state-change
11811 :position (point)
11812 :from 'todo
11813 :to 'done))))))
11815 (defun org-update-statistics-cookies (all)
11816 "Update the statistics cookie, either from TODO or from checkboxes.
11817 This should be called with the cursor in a line with a statistics cookie."
11818 (interactive "P")
11819 (if all
11820 (progn
11821 (org-update-checkbox-count 'all)
11822 (org-map-entries 'org-update-parent-todo-statistics))
11823 (if (not (org-at-heading-p))
11824 (org-update-checkbox-count)
11825 (let ((pos (point-marker))
11826 end l1 l2)
11827 (ignore-errors (org-back-to-heading t))
11828 (if (not (org-at-heading-p))
11829 (org-update-checkbox-count)
11830 (setq l1 (org-outline-level))
11831 (setq end (save-excursion
11832 (outline-next-heading)
11833 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11834 (point)))
11835 (if (and (save-excursion
11836 (re-search-forward
11837 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11838 (not (save-excursion (re-search-forward
11839 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11840 (org-update-checkbox-count)
11841 (if (and l2 (> l2 l1))
11842 (progn
11843 (goto-char end)
11844 (org-update-parent-todo-statistics))
11845 (goto-char pos)
11846 (beginning-of-line 1)
11847 (while (re-search-forward
11848 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11849 (point-at-eol) t)
11850 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11851 (goto-char pos)
11852 (move-marker pos nil)))))
11854 (defvar org-entry-property-inherited-from) ;; defined below
11855 (defun org-update-parent-todo-statistics ()
11856 "Update any statistics cookie in the parent of the current headline.
11857 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11858 the entire subtree and this will travel up the hierarchy and update
11859 statistics everywhere."
11860 (let* ((prop (save-excursion (org-up-heading-safe)
11861 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11862 (recursive (or (not org-hierarchical-todo-statistics)
11863 (and prop (string-match "\\<recursive\\>" prop))))
11864 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11866 (first t)
11867 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11868 level ltoggle l1 new ndel
11869 (cnt-all 0) (cnt-done 0) is-percent kwd
11870 checkbox-beg ov ovs ove cookie-present)
11871 (catch 'exit
11872 (save-excursion
11873 (beginning-of-line 1)
11874 (setq ltoggle (funcall outline-level))
11875 ;; Three situations are to consider:
11877 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11878 ;; to the top-level ancestor on the headline;
11880 ;; 2. If parent has "recursive" property, repeat up to the
11881 ;; headline setting that property, taking inheritance into
11882 ;; account;
11884 ;; 3. Else, move up to direct parent and proceed only once.
11885 (while (and (setq level (org-up-heading-safe))
11886 (or recursive first)
11887 (>= (point) lim))
11888 (setq first nil cookie-present nil)
11889 (unless (and level
11890 (not (string-match
11891 "\\<checkbox\\>"
11892 (downcase (or (org-entry-get nil "COOKIE_DATA")
11893 "")))))
11894 (throw 'exit nil))
11895 (while (re-search-forward box-re (point-at-eol) t)
11896 (setq cnt-all 0 cnt-done 0 cookie-present t)
11897 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11898 (save-match-data
11899 (unless (outline-next-heading) (throw 'exit nil))
11900 (while (and (looking-at org-complex-heading-regexp)
11901 (> (setq l1 (length (match-string 1))) level))
11902 (setq kwd (and (or recursive (= l1 ltoggle))
11903 (match-string 2)))
11904 (if (or (eq org-provide-todo-statistics 'all-headlines)
11905 (and (listp org-provide-todo-statistics)
11906 (or (member kwd org-provide-todo-statistics)
11907 (member kwd org-done-keywords))))
11908 (setq cnt-all (1+ cnt-all))
11909 (if (eq org-provide-todo-statistics t)
11910 (and kwd (setq cnt-all (1+ cnt-all)))))
11911 (and (member kwd org-done-keywords)
11912 (setq cnt-done (1+ cnt-done)))
11913 (outline-next-heading)))
11914 (setq new
11915 (if is-percent
11916 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11917 (format "[%d/%d]" cnt-done cnt-all))
11918 ndel (- (match-end 0) checkbox-beg))
11919 ;; handle overlays when updating cookie from column view
11920 (when (setq ov (car (overlays-at checkbox-beg)))
11921 (setq ovs (overlay-start ov) ove (overlay-end ov))
11922 (delete-overlay ov))
11923 (goto-char checkbox-beg)
11924 (insert new)
11925 (delete-region (point) (+ (point) ndel))
11926 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11927 (when ov (move-overlay ov ovs ove)))
11928 (when cookie-present
11929 (run-hook-with-args 'org-after-todo-statistics-hook
11930 cnt-done (- cnt-all cnt-done))))))
11931 (run-hooks 'org-todo-statistics-hook)))
11933 (defvar org-after-todo-statistics-hook nil
11934 "Hook that is called after a TODO statistics cookie has been updated.
11935 Each function is called with two arguments: the number of not-done entries
11936 and the number of done entries.
11938 For example, the following function, when added to this hook, will switch
11939 an entry to DONE when all children are done, and back to TODO when new
11940 entries are set to a TODO status. Note that this hook is only called
11941 when there is a statistics cookie in the headline!
11943 (defun org-summary-todo (n-done n-not-done)
11944 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11945 (let (org-log-done org-log-states) ; turn off logging
11946 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11949 (defvar org-todo-statistics-hook nil
11950 "Hook that is run whenever Org thinks TODO statistics should be updated.
11951 This hook runs even if there is no statistics cookie present, in which case
11952 `org-after-todo-statistics-hook' would not run.")
11954 (defun org-todo-trigger-tag-changes (state)
11955 "Apply the changes defined in `org-todo-state-tags-triggers'."
11956 (let ((l org-todo-state-tags-triggers)
11957 changes)
11958 (when (or (not state) (equal state ""))
11959 (setq changes (append changes (cdr (assoc "" l)))))
11960 (when (and (stringp state) (> (length state) 0))
11961 (setq changes (append changes (cdr (assoc state l)))))
11962 (when (member state org-not-done-keywords)
11963 (setq changes (append changes (cdr (assoc 'todo l)))))
11964 (when (member state org-done-keywords)
11965 (setq changes (append changes (cdr (assoc 'done l)))))
11966 (dolist (c changes)
11967 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11969 (defun org-local-logging (value)
11970 "Get logging settings from a property VALUE."
11971 (let* (words w a)
11972 ;; directly set the variables, they are already local.
11973 (setq org-log-done nil
11974 org-log-repeat nil
11975 org-todo-log-states nil)
11976 (setq words (org-split-string value))
11977 (while (setq w (pop words))
11978 (cond
11979 ((setq a (assoc w org-startup-options))
11980 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11981 (set (nth 1 a) (nth 2 a))))
11982 ((setq a (org-extract-log-state-settings w))
11983 (and (member (car a) org-todo-keywords-1)
11984 (push a org-todo-log-states)))))))
11986 (defun org-get-todo-sequence-head (kwd)
11987 "Return the head of the TODO sequence to which KWD belongs.
11988 If KWD is not set, check if there is a text property remembering the
11989 right sequence."
11990 (let (p)
11991 (cond
11992 ((not kwd)
11993 (or (get-text-property (point-at-bol) 'org-todo-head)
11994 (progn
11995 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11996 nil (point-at-eol)))
11997 (get-text-property p 'org-todo-head))))
11998 ((not (member kwd org-todo-keywords-1))
11999 (car org-todo-keywords-1))
12000 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12002 (defun org-fast-todo-selection ()
12003 "Fast TODO keyword selection with single keys.
12004 Returns the new TODO keyword, or nil if no state change should occur."
12005 (let* ((fulltable org-todo-key-alist)
12006 (done-keywords org-done-keywords) ;; needed for the faces.
12007 (maxlen (apply 'max (mapcar
12008 (lambda (x)
12009 (if (stringp (car x)) (string-width (car x)) 0))
12010 fulltable)))
12011 (expert nil)
12012 (fwidth (+ maxlen 3 1 3))
12013 (ncol (/ (- (window-width) 4) fwidth))
12014 tg cnt e c tbl
12015 groups ingroup)
12016 (save-excursion
12017 (save-window-excursion
12018 (if expert
12019 (set-buffer (get-buffer-create " *Org todo*"))
12020 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12021 (erase-buffer)
12022 (org-set-local 'org-done-keywords done-keywords)
12023 (setq tbl fulltable cnt 0)
12024 (while (setq e (pop tbl))
12025 (cond
12026 ((equal e '(:startgroup))
12027 (push '() groups) (setq ingroup t)
12028 (when (not (= cnt 0))
12029 (setq cnt 0)
12030 (insert "\n"))
12031 (insert "{ "))
12032 ((equal e '(:endgroup))
12033 (setq ingroup nil cnt 0)
12034 (insert "}\n"))
12035 ((equal e '(:newline))
12036 (when (not (= cnt 0))
12037 (setq cnt 0)
12038 (insert "\n")
12039 (setq e (car tbl))
12040 (while (equal (car tbl) '(:newline))
12041 (insert "\n")
12042 (setq tbl (cdr tbl)))))
12044 (setq tg (car e) c (cdr e))
12045 (if ingroup (push tg (car groups)))
12046 (setq tg (org-add-props tg nil 'face
12047 (org-get-todo-face tg)))
12048 (if (and (= cnt 0) (not ingroup)) (insert " "))
12049 (insert "[" c "] " tg (make-string
12050 (- fwidth 4 (length tg)) ?\ ))
12051 (when (= (setq cnt (1+ cnt)) ncol)
12052 (insert "\n")
12053 (if ingroup (insert " "))
12054 (setq cnt 0)))))
12055 (insert "\n")
12056 (goto-char (point-min))
12057 (if (not expert) (org-fit-window-to-buffer))
12058 (message "[a-z..]:Set [SPC]:clear")
12059 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12060 (cond
12061 ((or (= c ?\C-g)
12062 (and (= c ?q) (not (rassoc c fulltable))))
12063 (setq quit-flag t))
12064 ((= c ?\ ) nil)
12065 ((setq e (rassoc c fulltable) tg (car e))
12067 (t (setq quit-flag t)))))))
12069 (defun org-entry-is-todo-p ()
12070 (member (org-get-todo-state) org-not-done-keywords))
12072 (defun org-entry-is-done-p ()
12073 (member (org-get-todo-state) org-done-keywords))
12075 (defun org-get-todo-state ()
12076 (save-excursion
12077 (org-back-to-heading t)
12078 (and (looking-at org-todo-line-regexp)
12079 (match-end 2)
12080 (match-string 2))))
12082 (defun org-at-date-range-p (&optional inactive-ok)
12083 "Is the cursor inside a date range?"
12084 (interactive)
12085 (save-excursion
12086 (catch 'exit
12087 (let ((pos (point)))
12088 (skip-chars-backward "^[<\r\n")
12089 (skip-chars-backward "<[")
12090 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12091 (>= (match-end 0) pos)
12092 (throw 'exit t))
12093 (skip-chars-backward "^<[\r\n")
12094 (skip-chars-backward "<[")
12095 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12096 (>= (match-end 0) pos)
12097 (throw 'exit t)))
12098 nil)))
12100 (defun org-get-repeat (&optional tagline)
12101 "Check if there is a deadline/schedule with repeater in this entry."
12102 (save-match-data
12103 (save-excursion
12104 (org-back-to-heading t)
12105 (and (re-search-forward (if tagline
12106 (concat tagline "\\s-*" org-repeat-re)
12107 org-repeat-re)
12108 (org-entry-end-position) t)
12109 (match-string-no-properties 1)))))
12111 (defvar org-last-changed-timestamp)
12112 (defvar org-last-inserted-timestamp)
12113 (defvar org-log-post-message)
12114 (defvar org-log-note-purpose)
12115 (defvar org-log-note-how)
12116 (defvar org-log-note-extra)
12117 (defun org-auto-repeat-maybe (done-word)
12118 "Check if the current headline contains a repeated deadline/schedule.
12119 If yes, set TODO state back to what it was and change the base date
12120 of repeating deadline/scheduled time stamps to new date.
12121 This function is run automatically after each state change to a DONE state."
12122 ;; last-state is dynamically scoped into this function
12123 (let* ((repeat (org-get-repeat))
12124 (aa (assoc org-last-state org-todo-kwd-alist))
12125 (interpret (nth 1 aa))
12126 (head (nth 2 aa))
12127 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12128 (msg "Entry repeats: ")
12129 (org-log-done nil)
12130 (org-todo-log-states nil)
12131 re type n what ts time to-state)
12132 (when repeat
12133 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12134 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12135 org-todo-repeat-to-state))
12136 (unless (and to-state (member to-state org-todo-keywords-1))
12137 (setq to-state (if (eq interpret 'type) org-last-state head)))
12138 (org-todo to-state)
12139 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12140 (org-entry-put nil "LAST_REPEAT" (format-time-string
12141 (org-time-stamp-format t t))))
12142 (when org-log-repeat
12143 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12144 (memq 'org-add-log-note post-command-hook))
12145 ;; OK, we are already setup for some record
12146 (if (eq org-log-repeat 'note)
12147 ;; make sure we take a note, not only a time stamp
12148 (setq org-log-note-how 'note))
12149 ;; Set up for taking a record
12150 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12151 org-last-state
12152 'findpos org-log-repeat)))
12153 (org-back-to-heading t)
12154 (org-add-planning-info nil nil 'closed)
12155 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12156 org-deadline-time-regexp "\\)\\|\\("
12157 org-ts-regexp "\\)"))
12158 (while (re-search-forward
12159 re (save-excursion (outline-next-heading) (point)) t)
12160 (setq type (if (match-end 1) org-scheduled-string
12161 (if (match-end 3) org-deadline-string "Plain:"))
12162 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12163 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12164 (setq n (string-to-number (match-string 2 ts))
12165 what (match-string 3 ts))
12166 (if (equal what "w") (setq n (* n 7) what "d"))
12167 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12168 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12169 ;; Preparation, see if we need to modify the start date for the change
12170 (when (match-end 1)
12171 (setq time (save-match-data (org-time-string-to-time ts)))
12172 (cond
12173 ((equal (match-string 1 ts) ".")
12174 ;; Shift starting date to today
12175 (org-timestamp-change
12176 (- (org-today) (time-to-days time))
12177 'day))
12178 ((equal (match-string 1 ts) "+")
12179 (let ((nshiftmax 10) (nshift 0))
12180 (while (or (= nshift 0)
12181 (<= (time-to-days time)
12182 (time-to-days (current-time))))
12183 (when (= (incf nshift) nshiftmax)
12184 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12185 (error "Abort")))
12186 (org-timestamp-change n (cdr (assoc what whata)))
12187 (org-at-timestamp-p t)
12188 (setq ts (match-string 1))
12189 (setq time (save-match-data (org-time-string-to-time ts)))))
12190 (org-timestamp-change (- n) (cdr (assoc what whata)))
12191 ;; rematch, so that we have everything in place for the real shift
12192 (org-at-timestamp-p t)
12193 (setq ts (match-string 1))
12194 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12195 (org-timestamp-change n (cdr (assoc what whata)))
12196 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12197 (setq org-log-post-message msg)
12198 (message "%s" msg))))
12200 (defun org-show-todo-tree (arg)
12201 "Make a compact tree which shows all headlines marked with TODO.
12202 The tree will show the lines where the regexp matches, and all higher
12203 headlines above the match.
12204 With a \\[universal-argument] prefix, prompt for a regexp to match.
12205 With a numeric prefix N, construct a sparse tree for the Nth element
12206 of `org-todo-keywords-1'."
12207 (interactive "P")
12208 (let ((case-fold-search nil)
12209 (kwd-re
12210 (cond ((null arg) org-not-done-regexp)
12211 ((equal arg '(4))
12212 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12213 (mapcar 'list org-todo-keywords-1))))
12214 (concat "\\("
12215 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12216 "\\)\\>")))
12217 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12218 (regexp-quote (nth (1- (prefix-numeric-value arg))
12219 org-todo-keywords-1)))
12220 (t (error "Invalid prefix argument: %s" arg)))))
12221 (message "%d TODO entries found"
12222 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12224 (defun org-deadline (&optional remove time)
12225 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12226 With argument REMOVE, remove any deadline from the item.
12227 With argument TIME, set the deadline at the corresponding date. TIME
12228 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12229 (interactive "P")
12230 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12231 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12232 'region-start-level 'region))
12233 org-loop-over-headlines-in-active-region)
12234 (org-map-entries
12235 `(org-deadline ',remove ,time)
12236 org-loop-over-headlines-in-active-region
12237 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12238 (let* ((old-date (org-entry-get nil "DEADLINE"))
12239 (repeater (and old-date
12240 (string-match
12241 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12242 old-date)
12243 (match-string 1 old-date))))
12244 (if remove
12245 (progn
12246 (when (and old-date org-log-redeadline)
12247 (org-add-log-setup 'deldeadline nil old-date 'findpos
12248 org-log-redeadline))
12249 (org-remove-timestamp-with-keyword org-deadline-string)
12250 (message "Item no longer has a deadline."))
12251 (org-add-planning-info 'deadline time 'closed)
12252 (when (and old-date org-log-redeadline
12253 (not (equal old-date
12254 (substring org-last-inserted-timestamp 1 -1))))
12255 (org-add-log-setup 'redeadline nil old-date 'findpos
12256 org-log-redeadline))
12257 (when repeater
12258 (save-excursion
12259 (org-back-to-heading t)
12260 (when (re-search-forward (concat org-deadline-string " "
12261 org-last-inserted-timestamp)
12262 (save-excursion
12263 (outline-next-heading) (point)) t)
12264 (goto-char (1- (match-end 0)))
12265 (insert " " repeater)
12266 (setq org-last-inserted-timestamp
12267 (concat (substring org-last-inserted-timestamp 0 -1)
12268 " " repeater
12269 (substring org-last-inserted-timestamp -1))))))
12270 (message "Deadline on %s" org-last-inserted-timestamp)))))
12272 (defun org-schedule (&optional remove time)
12273 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12274 With argument REMOVE, remove any scheduling date from the item.
12275 With argument TIME, scheduled at the corresponding date. TIME can
12276 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12277 (interactive "P")
12278 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12279 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12280 'region-start-level 'region))
12281 org-loop-over-headlines-in-active-region)
12282 (org-map-entries
12283 `(org-schedule ',remove ,time)
12284 org-loop-over-headlines-in-active-region
12285 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12286 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12287 (repeater (and old-date
12288 (string-match
12289 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12290 old-date)
12291 (match-string 1 old-date))))
12292 (if remove
12293 (progn
12294 (when (and old-date org-log-reschedule)
12295 (org-add-log-setup 'delschedule nil old-date 'findpos
12296 org-log-reschedule))
12297 (org-remove-timestamp-with-keyword org-scheduled-string)
12298 (message "Item is no longer scheduled."))
12299 (org-add-planning-info 'scheduled time 'closed)
12300 (when (and old-date org-log-reschedule
12301 (not (equal old-date
12302 (substring org-last-inserted-timestamp 1 -1))))
12303 (org-add-log-setup 'reschedule nil old-date 'findpos
12304 org-log-reschedule))
12305 (when repeater
12306 (save-excursion
12307 (org-back-to-heading t)
12308 (when (re-search-forward (concat org-scheduled-string " "
12309 org-last-inserted-timestamp)
12310 (save-excursion
12311 (outline-next-heading) (point)) t)
12312 (goto-char (1- (match-end 0)))
12313 (insert " " repeater)
12314 (setq org-last-inserted-timestamp
12315 (concat (substring org-last-inserted-timestamp 0 -1)
12316 " " repeater
12317 (substring org-last-inserted-timestamp -1))))))
12318 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12320 (defun org-get-scheduled-time (pom &optional inherit)
12321 "Get the scheduled time as a time tuple, of a format suitable
12322 for calling org-schedule with, or if there is no scheduling,
12323 returns nil."
12324 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12325 (when time
12326 (apply 'encode-time (org-parse-time-string time)))))
12328 (defun org-get-deadline-time (pom &optional inherit)
12329 "Get the deadline as a time tuple, of a format suitable for
12330 calling org-deadline with, or if there is no scheduling, returns
12331 nil."
12332 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12333 (when time
12334 (apply 'encode-time (org-parse-time-string time)))))
12336 (defun org-remove-timestamp-with-keyword (keyword)
12337 "Remove all time stamps with KEYWORD in the current entry."
12338 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12339 beg)
12340 (save-excursion
12341 (org-back-to-heading t)
12342 (setq beg (point))
12343 (outline-next-heading)
12344 (while (re-search-backward re beg t)
12345 (replace-match "")
12346 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12347 (equal (char-before) ?\ ))
12348 (backward-delete-char 1)
12349 (if (string-match "^[ \t]*$" (buffer-substring
12350 (point-at-bol) (point-at-eol)))
12351 (delete-region (point-at-bol)
12352 (min (point-max) (1+ (point-at-eol))))))))))
12354 (defun org-add-planning-info (what &optional time &rest remove)
12355 "Insert new timestamp with keyword in the line directly after the headline.
12356 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12357 If non is given, the user is prompted for a date.
12358 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12359 be removed."
12360 (interactive)
12361 (let (org-time-was-given org-end-time-was-given ts
12362 end default-time default-input)
12364 (catch 'exit
12365 (when (and (memq what '(scheduled deadline))
12366 (or (not time)
12367 (and (stringp time)
12368 (string-match "^[-+]+[0-9]" time))))
12369 ;; Try to get a default date/time from existing timestamp
12370 (save-excursion
12371 (org-back-to-heading t)
12372 (setq end (save-excursion (outline-next-heading) (point)))
12373 (when (re-search-forward (if (eq what 'scheduled)
12374 org-scheduled-time-regexp
12375 org-deadline-time-regexp)
12376 end t)
12377 (setq ts (match-string 1)
12378 default-time
12379 (apply 'encode-time (org-parse-time-string ts))
12380 default-input (and ts (org-get-compact-tod ts))))))
12381 (when what
12382 (setq time
12383 (if (stringp time)
12384 ;; This is a string (relative or absolute), set proper date
12385 (apply 'encode-time
12386 (org-read-date-analyze
12387 time default-time (decode-time default-time)))
12388 ;; If necessary, get the time from the user
12389 (or time (org-read-date nil 'to-time nil nil
12390 default-time default-input)))))
12392 (when (and org-insert-labeled-timestamps-at-point
12393 (member what '(scheduled deadline)))
12394 (insert
12395 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12396 (org-insert-time-stamp time org-time-was-given
12397 nil nil nil (list org-end-time-was-given))
12398 (setq what nil))
12399 (save-excursion
12400 (save-restriction
12401 (let (col list elt ts buffer-invisibility-spec)
12402 (org-back-to-heading t)
12403 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12404 (goto-char (match-end 1))
12405 (setq col (current-column))
12406 (goto-char (match-end 0))
12407 (if (eobp) (insert "\n") (forward-char 1))
12408 (when (and (not what)
12409 (not (looking-at
12410 (concat "[ \t]*"
12411 org-keyword-time-not-clock-regexp))))
12412 ;; Nothing to add, nothing to remove...... :-)
12413 (throw 'exit nil))
12414 (if (and (not (looking-at org-outline-regexp))
12415 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12416 "[^\r\n]*"))
12417 (not (equal (match-string 1) org-clock-string)))
12418 (narrow-to-region (match-beginning 0) (match-end 0))
12419 (insert-before-markers "\n")
12420 (backward-char 1)
12421 (narrow-to-region (point) (point))
12422 (and org-adapt-indentation (org-indent-to-column col)))
12423 ;; Check if we have to remove something.
12424 (setq list (cons what remove))
12425 (while list
12426 (setq elt (pop list))
12427 (when (or (and (eq elt 'scheduled)
12428 (re-search-forward org-scheduled-time-regexp nil t))
12429 (and (eq elt 'deadline)
12430 (re-search-forward org-deadline-time-regexp nil t))
12431 (and (eq elt 'closed)
12432 (re-search-forward org-closed-time-regexp nil t)))
12433 (replace-match "")
12434 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12435 (and (looking-at "[ \t]+") (replace-match ""))
12436 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12437 (when what
12438 (insert
12439 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12440 (cond ((eq what 'scheduled) org-scheduled-string)
12441 ((eq what 'deadline) org-deadline-string)
12442 ((eq what 'closed) org-closed-string))
12443 " ")
12444 (setq ts (org-insert-time-stamp
12445 time
12446 (or org-time-was-given
12447 (and (eq what 'closed) org-log-done-with-time))
12448 (eq what 'closed)
12449 nil nil (list org-end-time-was-given)))
12450 (insert
12451 (if (not (or (bolp) (eq (char-before) ?\ )
12452 (memq (char-after) '(32 10))
12453 (eobp))) " " ""))
12454 (end-of-line 1))
12455 (goto-char (point-min))
12456 (widen)
12457 (if (and (looking-at "[ \t]*\n")
12458 (equal (char-before) ?\n))
12459 (delete-region (1- (point)) (point-at-eol)))
12460 ts))))))
12462 (defvar org-log-note-marker (make-marker))
12463 (defvar org-log-note-purpose nil)
12464 (defvar org-log-note-state nil)
12465 (defvar org-log-note-previous-state nil)
12466 (defvar org-log-note-how nil)
12467 (defvar org-log-note-extra nil)
12468 (defvar org-log-note-window-configuration nil)
12469 (defvar org-log-note-return-to (make-marker))
12470 (defvar org-log-note-effective-time nil
12471 "Remembered current time so that dynamically scoped
12472 `org-extend-today-until' affects tha timestamps in state change
12473 log")
12475 (defvar org-log-post-message nil
12476 "Message to be displayed after a log note has been stored.
12477 The auto-repeater uses this.")
12479 (defun org-add-note ()
12480 "Add a note to the current entry.
12481 This is done in the same way as adding a state change note."
12482 (interactive)
12483 (org-add-log-setup 'note nil nil 'findpos nil))
12485 (defvar org-property-end-re)
12486 (defun org-add-log-setup (&optional purpose state prev-state
12487 findpos how extra)
12488 "Set up the post command hook to take a note.
12489 If this is about to TODO state change, the new state is expected in STATE.
12490 When FINDPOS is non-nil, find the correct position for the note in
12491 the current entry. If not, assume that it can be inserted at point.
12492 HOW is an indicator what kind of note should be created.
12493 EXTRA is additional text that will be inserted into the notes buffer."
12494 (let* ((org-log-into-drawer (org-log-into-drawer))
12495 (drawer (cond ((stringp org-log-into-drawer)
12496 org-log-into-drawer)
12497 (org-log-into-drawer "LOGBOOK"))))
12498 (save-restriction
12499 (save-excursion
12500 (when findpos
12501 (org-back-to-heading t)
12502 (narrow-to-region (point) (save-excursion
12503 (outline-next-heading) (point)))
12504 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12505 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12506 "[^\r\n]*\\)?"))
12507 (goto-char (match-end 0))
12508 (cond
12509 (drawer
12510 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12511 nil t)
12512 (progn
12513 (goto-char (match-end 0))
12514 (or org-log-states-order-reversed
12515 (and (re-search-forward org-property-end-re nil t)
12516 (goto-char (1- (match-beginning 0))))))
12517 (insert "\n:" drawer ":\n:END:")
12518 (beginning-of-line 0)
12519 (org-indent-line)
12520 (beginning-of-line 2)
12521 (org-indent-line)
12522 (end-of-line 0)))
12523 ((and org-log-state-notes-insert-after-drawers
12524 (save-excursion
12525 (forward-line) (looking-at org-drawer-regexp)))
12526 (forward-line)
12527 (while (looking-at org-drawer-regexp)
12528 (goto-char (match-end 0))
12529 (re-search-forward org-property-end-re (point-max) t)
12530 (forward-line))
12531 (forward-line -1)))
12532 (unless org-log-states-order-reversed
12533 (and (= (char-after) ?\n) (forward-char 1))
12534 (org-skip-over-state-notes)
12535 (skip-chars-backward " \t\n\r")))
12536 (move-marker org-log-note-marker (point))
12537 (setq org-log-note-purpose purpose
12538 org-log-note-state state
12539 org-log-note-previous-state prev-state
12540 org-log-note-how how
12541 org-log-note-extra extra
12542 org-log-note-effective-time (org-current-effective-time))
12543 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12545 (defun org-skip-over-state-notes ()
12546 "Skip past the list of State notes in an entry."
12547 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12548 (when (ignore-errors (goto-char (org-in-item-p)))
12549 (let* ((struct (org-list-struct))
12550 (prevs (org-list-prevs-alist struct)))
12551 (while (looking-at "[ \t]*- State")
12552 (goto-char (or (org-list-get-next-item (point) struct prevs)
12553 (org-list-get-item-end (point) struct)))))))
12555 (defun org-add-log-note (&optional purpose)
12556 "Pop up a window for taking a note, and add this note later at point."
12557 (remove-hook 'post-command-hook 'org-add-log-note)
12558 (setq org-log-note-window-configuration (current-window-configuration))
12559 (delete-other-windows)
12560 (move-marker org-log-note-return-to (point))
12561 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12562 (goto-char org-log-note-marker)
12563 (org-switch-to-buffer-other-window "*Org Note*")
12564 (erase-buffer)
12565 (if (memq org-log-note-how '(time state))
12566 (let (current-prefix-arg) (org-store-log-note))
12567 (let ((org-inhibit-startup t)) (org-mode))
12568 (insert (format "# Insert note for %s.
12569 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12570 (cond
12571 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12572 ((eq org-log-note-purpose 'done) "closed todo item")
12573 ((eq org-log-note-purpose 'state)
12574 (format "state change from \"%s\" to \"%s\""
12575 (or org-log-note-previous-state "")
12576 (or org-log-note-state "")))
12577 ((eq org-log-note-purpose 'reschedule)
12578 "rescheduling")
12579 ((eq org-log-note-purpose 'delschedule)
12580 "no longer scheduled")
12581 ((eq org-log-note-purpose 'redeadline)
12582 "changing deadline")
12583 ((eq org-log-note-purpose 'deldeadline)
12584 "removing deadline")
12585 ((eq org-log-note-purpose 'refile)
12586 "refiling")
12587 ((eq org-log-note-purpose 'note)
12588 "this entry")
12589 (t (error "This should not happen")))))
12590 (if org-log-note-extra (insert org-log-note-extra))
12591 (org-set-local 'org-finish-function 'org-store-log-note)
12592 (run-hooks 'org-log-buffer-setup-hook)))
12594 (defvar org-note-abort nil) ; dynamically scoped
12595 (defun org-store-log-note ()
12596 "Finish taking a log note, and insert it to where it belongs."
12597 (let ((txt (buffer-string))
12598 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12599 lines ind bul)
12600 (kill-buffer (current-buffer))
12601 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12602 (setq txt (replace-match "" t t txt)))
12603 (if (string-match "\\s-+\\'" txt)
12604 (setq txt (replace-match "" t t txt)))
12605 (setq lines (org-split-string txt "\n"))
12606 (when (and note (string-match "\\S-" note))
12607 (setq note
12608 (org-replace-escapes
12609 note
12610 (list (cons "%u" (user-login-name))
12611 (cons "%U" user-full-name)
12612 (cons "%t" (format-time-string
12613 (org-time-stamp-format 'long 'inactive)
12614 org-log-note-effective-time))
12615 (cons "%T" (format-time-string
12616 (org-time-stamp-format 'long nil)
12617 org-log-note-effective-time))
12618 (cons "%d" (format-time-string
12619 (org-time-stamp-format nil 'inactive)
12620 org-log-note-effective-time))
12621 (cons "%D" (format-time-string
12622 (org-time-stamp-format nil nil)
12623 org-log-note-effective-time))
12624 (cons "%s" (if org-log-note-state
12625 (concat "\"" org-log-note-state "\"")
12626 ""))
12627 (cons "%S" (if org-log-note-previous-state
12628 (concat "\"" org-log-note-previous-state "\"")
12629 "\"\"")))))
12630 (if lines (setq note (concat note " \\\\")))
12631 (push note lines))
12632 (when (or current-prefix-arg org-note-abort)
12633 (when org-log-into-drawer
12634 (org-remove-empty-drawer-at
12635 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12636 org-log-note-marker))
12637 (setq lines nil))
12638 (when lines
12639 (with-current-buffer (marker-buffer org-log-note-marker)
12640 (save-excursion
12641 (goto-char org-log-note-marker)
12642 (move-marker org-log-note-marker nil)
12643 (end-of-line 1)
12644 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12645 (setq ind (save-excursion
12646 (if (ignore-errors (goto-char (org-in-item-p)))
12647 (let ((struct (org-list-struct)))
12648 (org-list-get-ind
12649 (org-list-get-top-point struct) struct))
12650 (skip-chars-backward " \r\t\n")
12651 (cond
12652 ((and (org-at-heading-p)
12653 org-adapt-indentation)
12654 (1+ (org-current-level)))
12655 ((org-at-heading-p) 0)
12656 (t (org-get-indentation))))))
12657 (setq bul (org-list-bullet-string "-"))
12658 (org-indent-line-to ind)
12659 (insert bul (pop lines))
12660 (let ((ind-body (+ (length bul) ind)))
12661 (while lines
12662 (insert "\n")
12663 (org-indent-line-to ind-body)
12664 (insert (pop lines))))
12665 (message "Note stored")
12666 (org-back-to-heading t)
12667 (org-cycle-hide-drawers 'children)))))
12668 (set-window-configuration org-log-note-window-configuration)
12669 (with-current-buffer (marker-buffer org-log-note-return-to)
12670 (goto-char org-log-note-return-to))
12671 (move-marker org-log-note-return-to nil)
12672 (and org-log-post-message (message "%s" org-log-post-message)))
12674 (defun org-remove-empty-drawer-at (drawer pos)
12675 "Remove an empty drawer DRAWER at position POS.
12676 POS may also be a marker."
12677 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12678 (save-excursion
12679 (save-restriction
12680 (widen)
12681 (goto-char pos)
12682 (if (org-in-regexp
12683 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12684 (replace-match ""))))))
12686 (defvar org-ts-type nil)
12687 (defun org-sparse-tree (&optional arg type)
12688 "Create a sparse tree, prompt for the details.
12689 This command can create sparse trees. You first need to select the type
12690 of match used to create the tree:
12692 t Show all TODO entries.
12693 T Show entries with a specific TODO keyword.
12694 m Show entries selected by a tags/property match.
12695 p Enter a property name and its value (both with completion on existing
12696 names/values) and show entries with that property.
12697 r Show entries matching a regular expression (`/' can be used as well).
12698 b Show deadlines and scheduled items before a date.
12699 a Show deadlines and scheduled items after a date.
12700 d Show deadlines due within `org-deadline-warning-days'.
12701 D Show deadlines and scheduled items between a date range."
12702 (interactive "P")
12703 (let (ans kwd value ts-type)
12704 (setq type (or type org-sparse-tree-default-date-type))
12705 (setq org-ts-type type)
12706 (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"
12707 (cond ((eq type 'all) "all timestamps")
12708 ((eq type 'scheduled) "only scheduled")
12709 ((eq type 'deadline) "only deadline")
12710 ((eq type 'active) "only active timestamps")
12711 ((eq type 'inactive) "only inactive timestamps")
12712 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12713 (t "scheduled/deadline")))
12714 (setq ans (read-char-exclusive))
12715 (cond
12716 ((equal ans ?c)
12717 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12718 ((equal ans ?d)
12719 (call-interactively 'org-check-deadlines))
12720 ((equal ans ?b)
12721 (call-interactively 'org-check-before-date))
12722 ((equal ans ?a)
12723 (call-interactively 'org-check-after-date))
12724 ((equal ans ?D)
12725 (call-interactively 'org-check-dates-range))
12726 ((equal ans ?t)
12727 (call-interactively 'org-show-todo-tree))
12728 ((equal ans ?T)
12729 (org-show-todo-tree '(4)))
12730 ((member ans '(?T ?m))
12731 (call-interactively 'org-match-sparse-tree))
12732 ((member ans '(?p ?P))
12733 (setq kwd (org-icompleting-read "Property: "
12734 (mapcar 'list (org-buffer-property-keys))))
12735 (setq value (org-icompleting-read "Value: "
12736 (mapcar 'list (org-property-values kwd))))
12737 (unless (string-match "\\`{.*}\\'" value)
12738 (setq value (concat "\"" value "\"")))
12739 (org-match-sparse-tree arg (concat kwd "=" value)))
12740 ((member ans '(?r ?R ?/))
12741 (call-interactively 'org-occur))
12742 (t (error "No such sparse tree command \"%c\"" ans)))))
12744 (defvar org-occur-highlights nil
12745 "List of overlays used for occur matches.")
12746 (make-variable-buffer-local 'org-occur-highlights)
12747 (defvar org-occur-parameters nil
12748 "Parameters of the active org-occur calls.
12749 This is a list, each call to org-occur pushes as cons cell,
12750 containing the regular expression and the callback, onto the list.
12751 The list can contain several entries if `org-occur' has been called
12752 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12753 will only contain one set of parameters. When the highlights are
12754 removed (for example with `C-c C-c', or with the next edit (depending
12755 on `org-remove-highlights-with-change'), this variable is emptied
12756 as well.")
12757 (make-variable-buffer-local 'org-occur-parameters)
12759 (defun org-occur (regexp &optional keep-previous callback)
12760 "Make a compact tree which shows all matches of REGEXP.
12761 The tree will show the lines where the regexp matches, and all higher
12762 headlines above the match. It will also show the heading after the match,
12763 to make sure editing the matching entry is easy.
12764 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12765 call to `org-occur' will be kept, to allow stacking of calls to this
12766 command.
12767 If CALLBACK is non-nil, it is a function which is called to confirm
12768 that the match should indeed be shown."
12769 (interactive "sRegexp: \nP")
12770 (when (equal regexp "")
12771 (error "Regexp cannot be empty"))
12772 (unless keep-previous
12773 (org-remove-occur-highlights nil nil t))
12774 (push (cons regexp callback) org-occur-parameters)
12775 (let ((cnt 0))
12776 (save-excursion
12777 (goto-char (point-min))
12778 (if (or (not keep-previous) ; do not want to keep
12779 (not org-occur-highlights)) ; no previous matches
12780 ;; hide everything
12781 (org-overview))
12782 (while (re-search-forward regexp nil t)
12783 (when (or (not callback)
12784 (save-match-data (funcall callback)))
12785 (setq cnt (1+ cnt))
12786 (when org-highlight-sparse-tree-matches
12787 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12788 (org-show-context 'occur-tree))))
12789 (when org-remove-highlights-with-change
12790 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12791 nil 'local))
12792 (unless org-sparse-tree-open-archived-trees
12793 (org-hide-archived-subtrees (point-min) (point-max)))
12794 (run-hooks 'org-occur-hook)
12795 (if (org-called-interactively-p 'interactive)
12796 (message "%d match(es) for regexp %s" cnt regexp))
12797 cnt))
12799 (defun org-occur-next-match (&optional n reset)
12800 "Function for `next-error-function' to find sparse tree matches.
12801 N is the number of matches to move, when negative move backwards.
12802 RESET is entirely ignored - this function always goes back to the
12803 starting point when no match is found."
12804 (let* ((limit (if (< n 0) (point-min) (point-max)))
12805 (search-func (if (< n 0)
12806 'previous-single-char-property-change
12807 'next-single-char-property-change))
12808 (n (abs n))
12809 (pos (point))
12811 (catch 'exit
12812 (while (setq p1 (funcall search-func (point) 'org-type))
12813 (when (equal p1 limit)
12814 (goto-char pos)
12815 (error "No more matches"))
12816 (when (equal (get-char-property p1 'org-type) 'org-occur)
12817 (setq n (1- n))
12818 (when (= n 0)
12819 (goto-char p1)
12820 (throw 'exit (point))))
12821 (goto-char p1))
12822 (goto-char p1)
12823 (error "No more matches"))))
12825 (defun org-show-context (&optional key)
12826 "Make sure point and context are visible.
12827 How much context is shown depends upon the variables
12828 `org-show-hierarchy-above', `org-show-following-heading',
12829 `org-show-entry-below' and `org-show-siblings'."
12830 (let ((heading-p (org-at-heading-p t))
12831 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12832 (following-p (org-get-alist-option org-show-following-heading key))
12833 (entry-p (org-get-alist-option org-show-entry-below key))
12834 (siblings-p (org-get-alist-option org-show-siblings key)))
12835 (catch 'exit
12836 ;; Show heading or entry text
12837 (if (and heading-p (not entry-p))
12838 (org-flag-heading nil) ; only show the heading
12839 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12840 (org-show-hidden-entry))) ; show entire entry
12841 (when following-p
12842 ;; Show next sibling, or heading below text
12843 (save-excursion
12844 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12845 (org-flag-heading nil))))
12846 (when siblings-p (org-show-siblings))
12847 (when hierarchy-p
12848 ;; show all higher headings, possibly with siblings
12849 (save-excursion
12850 (while (and (condition-case nil
12851 (progn (org-up-heading-all 1) t)
12852 (error nil))
12853 (not (bobp)))
12854 (org-flag-heading nil)
12855 (when siblings-p (org-show-siblings))))))))
12857 (defvar org-reveal-start-hook nil
12858 "Hook run before revealing a location.")
12860 (defun org-reveal (&optional siblings)
12861 "Show current entry, hierarchy above it, and the following headline.
12862 This can be used to show a consistent set of context around locations
12863 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12864 not t for the search context.
12866 With optional argument SIBLINGS, on each level of the hierarchy all
12867 siblings are shown. This repairs the tree structure to what it would
12868 look like when opened with hierarchical calls to `org-cycle'.
12869 With double optional argument \\[universal-argument] \\[universal-argument], \
12870 go to the parent and show the
12871 entire tree."
12872 (interactive "P")
12873 (run-hooks 'org-reveal-start-hook)
12874 (let ((org-show-hierarchy-above t)
12875 (org-show-following-heading t)
12876 (org-show-siblings (if siblings t org-show-siblings)))
12877 (org-show-context nil))
12878 (when (equal siblings '(16))
12879 (save-excursion
12880 (when (org-up-heading-safe)
12881 (org-show-subtree)
12882 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12884 (defun org-highlight-new-match (beg end)
12885 "Highlight from BEG to END and mark the highlight is an occur headline."
12886 (let ((ov (make-overlay beg end)))
12887 (overlay-put ov 'face 'secondary-selection)
12888 (overlay-put ov 'org-type 'org-occur)
12889 (push ov org-occur-highlights)))
12891 (defun org-remove-occur-highlights (&optional beg end noremove)
12892 "Remove the occur highlights from the buffer.
12893 BEG and END are ignored. If NOREMOVE is nil, remove this function
12894 from the `before-change-functions' in the current buffer."
12895 (interactive)
12896 (unless org-inhibit-highlight-removal
12897 (mapc 'delete-overlay org-occur-highlights)
12898 (setq org-occur-highlights nil)
12899 (setq org-occur-parameters nil)
12900 (unless noremove
12901 (remove-hook 'before-change-functions
12902 'org-remove-occur-highlights 'local))))
12904 ;;;; Priorities
12906 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12907 "Regular expression matching the priority indicator.")
12909 (defvar org-remove-priority-next-time nil)
12911 (defun org-priority-up ()
12912 "Increase the priority of the current item."
12913 (interactive)
12914 (org-priority 'up))
12916 (defun org-priority-down ()
12917 "Decrease the priority of the current item."
12918 (interactive)
12919 (org-priority 'down))
12921 (defun org-priority (&optional action show)
12922 "Change the priority of an item.
12923 ACTION can be `set', `up', `down', or a character."
12924 (interactive "P")
12925 (if (equal action '(4))
12926 (org-show-priority)
12927 (unless org-enable-priority-commands
12928 (error "Priority commands are disabled"))
12929 (setq action (or action 'set))
12930 (let (current new news have remove)
12931 (save-excursion
12932 (org-back-to-heading t)
12933 (if (looking-at org-priority-regexp)
12934 (setq current (string-to-char (match-string 2))
12935 have t))
12936 (cond
12937 ((eq action 'remove)
12938 (setq remove t new ?\ ))
12939 ((or (eq action 'set)
12940 (if (featurep 'xemacs) (characterp action) (integerp action)))
12941 (if (not (eq action 'set))
12942 (setq new action)
12943 (message "Priority %c-%c, SPC to remove: "
12944 org-highest-priority org-lowest-priority)
12945 (save-match-data
12946 (setq new (read-char-exclusive))))
12947 (if (and (= (upcase org-highest-priority) org-highest-priority)
12948 (= (upcase org-lowest-priority) org-lowest-priority))
12949 (setq new (upcase new)))
12950 (cond ((equal new ?\ ) (setq remove t))
12951 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12952 (error "Priority must be between `%c' and `%c'"
12953 org-highest-priority org-lowest-priority))))
12954 ((eq action 'up)
12955 (setq new (if have
12956 (1- current) ; normal cycling
12957 ;; last priority was empty
12958 (if (eq last-command this-command)
12959 org-lowest-priority ; wrap around empty to lowest
12960 ;; default
12961 (if org-priority-start-cycle-with-default
12962 org-default-priority
12963 (1- org-default-priority))))))
12964 ((eq action 'down)
12965 (setq new (if have
12966 (1+ current) ; normal cycling
12967 ;; last priority was empty
12968 (if (eq last-command this-command)
12969 org-highest-priority ; wrap around empty to highest
12970 ;; default
12971 (if org-priority-start-cycle-with-default
12972 org-default-priority
12973 (1+ org-default-priority))))))
12974 (t (error "Invalid action")))
12975 (if (or (< (upcase new) org-highest-priority)
12976 (> (upcase new) org-lowest-priority))
12977 (if (and (memq action '(up down))
12978 (not have) (not (eq last-command this-command)))
12979 ;; `new' is from default priority
12980 (error
12981 "The default can not be set, see `org-default-priority' why")
12982 ;; normal cycling: `new' is beyond highest/lowest priority
12983 ;; and is wrapped around to the empty priority
12984 (setq remove t)))
12985 (setq news (format "%c" new))
12986 (if have
12987 (if remove
12988 (replace-match "" t t nil 1)
12989 (replace-match news t t nil 2))
12990 (if remove
12991 (error "No priority cookie found in line")
12992 (let ((case-fold-search nil))
12993 (looking-at org-todo-line-regexp))
12994 (if (match-end 2)
12995 (progn
12996 (goto-char (match-end 2))
12997 (insert " [#" news "]"))
12998 (goto-char (match-beginning 3))
12999 (insert "[#" news "] "))))
13000 (org-preserve-lc (org-set-tags nil 'align)))
13001 (if remove
13002 (message "Priority removed")
13003 (message "Priority of current item set to %s" news)))))
13005 (defun org-show-priority ()
13006 "Show the priority of the current item.
13007 This priority is composed of the main priority given with the [#A] cookies,
13008 and by additional input from the age of a schedules or deadline entry."
13009 (interactive)
13010 (let ((pri (if (eq major-mode 'org-agenda-mode)
13011 (org-get-at-bol 'priority)
13012 (save-excursion
13013 (save-match-data
13014 (beginning-of-line)
13015 (and (looking-at org-heading-regexp)
13016 (org-get-priority (match-string 0))))))))
13017 (message "Priority is %d" (if pri pri -1000))))
13019 (defun org-get-priority (s)
13020 "Find priority cookie and return priority."
13021 (save-match-data
13022 (if (functionp org-get-priority-function)
13023 (funcall org-get-priority-function)
13024 (if (not (string-match org-priority-regexp s))
13025 (* 1000 (- org-lowest-priority org-default-priority))
13026 (* 1000 (- org-lowest-priority
13027 (string-to-char (match-string 2 s))))))))
13029 ;;;; Tags
13031 (defvar org-agenda-archives-mode)
13032 (defvar org-map-continue-from nil
13033 "Position from where mapping should continue.
13034 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13036 (defvar org-scanner-tags nil
13037 "The current tag list while the tags scanner is running.")
13038 (defvar org-trust-scanner-tags nil
13039 "Should `org-get-tags-at' use the tags for the scanner.
13040 This is for internal dynamical scoping only.
13041 When this is non-nil, the function `org-get-tags-at' will return the value
13042 of `org-scanner-tags' instead of building the list by itself. This
13043 can lead to large speed-ups when the tags scanner is used in a file with
13044 many entries, and when the list of tags is retrieved, for example to
13045 obtain a list of properties. Building the tags list for each entry in such
13046 a file becomes an N^2 operation - but with this variable set, it scales
13047 as N.")
13049 (defun org-scan-tags (action matcher todo-only &optional start-level)
13050 "Scan headline tags with inheritance and produce output ACTION.
13052 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13053 or `agenda' to produce an entry list for an agenda view. It can also be
13054 a Lisp form or a function that should be called at each matched headline, in
13055 this case the return value is a list of all return values from these calls.
13057 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13058 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13059 only lines with a not-done TODO keyword are included in the output.
13060 This should be the same variable that was scoped into
13061 and set by `org-make-tags-matcher' when it constructed MATCHER.
13063 START-LEVEL can be a string with asterisks, reducing the scope to
13064 headlines matching this string."
13065 (require 'org-agenda)
13066 (let* ((re (concat "^"
13067 (if start-level
13068 ;; Get the correct level to match
13069 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13070 org-outline-regexp)
13071 " *\\(\\<\\("
13072 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13073 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13074 (props (list 'face 'default
13075 'done-face 'org-agenda-done
13076 'undone-face 'default
13077 'mouse-face 'highlight
13078 'org-not-done-regexp org-not-done-regexp
13079 'org-todo-regexp org-todo-regexp
13080 'org-complex-heading-regexp org-complex-heading-regexp
13081 'help-echo
13082 (format "mouse-2 or RET jump to org file %s"
13083 (abbreviate-file-name
13084 (or (buffer-file-name (buffer-base-buffer))
13085 (buffer-name (buffer-base-buffer)))))))
13086 (case-fold-search nil)
13087 (org-map-continue-from nil)
13088 lspos tags tags-list
13089 (tags-alist (list (cons 0 org-file-tags)))
13090 (llast 0) rtn rtn1 level category i txt
13091 todo marker entry priority)
13092 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13093 (setq action (list 'lambda nil action)))
13094 (save-excursion
13095 (goto-char (point-min))
13096 (when (eq action 'sparse-tree)
13097 (org-overview)
13098 (org-remove-occur-highlights))
13099 (while (re-search-forward re nil t)
13100 (setq org-map-continue-from nil)
13101 (catch :skip
13102 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13103 tags (if (match-end 4) (org-match-string-no-properties 4)))
13104 (goto-char (setq lspos (match-beginning 0)))
13105 (setq level (org-reduced-level (funcall outline-level))
13106 category (org-get-category))
13107 (setq i llast llast level)
13108 ;; remove tag lists from same and sublevels
13109 (while (>= i level)
13110 (when (setq entry (assoc i tags-alist))
13111 (setq tags-alist (delete entry tags-alist)))
13112 (setq i (1- i)))
13113 ;; add the next tags
13114 (when tags
13115 (setq tags (org-split-string tags ":")
13116 tags-alist
13117 (cons (cons level tags) tags-alist)))
13118 ;; compile tags for current headline
13119 (setq tags-list
13120 (if org-use-tag-inheritance
13121 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13122 tags)
13123 org-scanner-tags tags-list)
13124 (when org-use-tag-inheritance
13125 (setcdr (car tags-alist)
13126 (mapcar (lambda (x)
13127 (setq x (copy-sequence x))
13128 (org-add-prop-inherited x))
13129 (cdar tags-alist))))
13130 (when (and tags org-use-tag-inheritance
13131 (or (not (eq t org-use-tag-inheritance))
13132 org-tags-exclude-from-inheritance))
13133 ;; selective inheritance, remove uninherited ones
13134 (setcdr (car tags-alist)
13135 (org-remove-uninherited-tags (cdar tags-alist))))
13136 (when (and
13138 ;; eval matcher only when the todo condition is OK
13139 (and (or (not todo-only) (member todo org-not-done-keywords))
13140 (let ((case-fold-search t) (org-trust-scanner-tags t))
13141 (eval matcher)))
13143 ;; Call the skipper, but return t if it does not skip,
13144 ;; so that the `and' form continues evaluating
13145 (progn
13146 (unless (eq action 'sparse-tree) (org-agenda-skip))
13149 ;; Check if timestamps are deselecting this entry
13150 (or (not todo-only)
13151 (and (member todo org-not-done-keywords)
13152 (or (not org-agenda-tags-todo-honor-ignore-options)
13153 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13155 ;; select this headline
13156 (cond
13157 ((eq action 'sparse-tree)
13158 (and org-highlight-sparse-tree-matches
13159 (org-get-heading) (match-end 0)
13160 (org-highlight-new-match
13161 (match-beginning 1) (match-end 1)))
13162 (org-show-context 'tags-tree))
13163 ((eq action 'agenda)
13164 (setq txt (org-agenda-format-item
13166 (concat
13167 (if (eq org-tags-match-list-sublevels 'indented)
13168 (make-string (1- level) ?.) "")
13169 (org-get-heading))
13170 category
13171 tags-list)
13172 priority (org-get-priority txt))
13173 (goto-char lspos)
13174 (setq marker (org-agenda-new-marker))
13175 (org-add-props txt props
13176 'org-marker marker 'org-hd-marker marker 'org-category category
13177 'todo-state todo
13178 'priority priority 'type "tagsmatch")
13179 (push txt rtn))
13180 ((functionp action)
13181 (setq org-map-continue-from nil)
13182 (save-excursion
13183 (setq rtn1 (funcall action))
13184 (push rtn1 rtn)))
13185 (t (error "Invalid action")))
13187 ;; if we are to skip sublevels, jump to end of subtree
13188 (unless org-tags-match-list-sublevels
13189 (org-end-of-subtree t)
13190 (backward-char 1))))
13191 ;; Get the correct position from where to continue
13192 (if org-map-continue-from
13193 (goto-char org-map-continue-from)
13194 (and (= (point) lspos) (end-of-line 1)))))
13195 (when (and (eq action 'sparse-tree)
13196 (not org-sparse-tree-open-archived-trees))
13197 (org-hide-archived-subtrees (point-min) (point-max)))
13198 (nreverse rtn)))
13200 (defun org-remove-uninherited-tags (tags)
13201 "Remove all tags that are not inherited from the list TAGS."
13202 (cond
13203 ((eq org-use-tag-inheritance t)
13204 (if org-tags-exclude-from-inheritance
13205 (org-delete-all org-tags-exclude-from-inheritance tags)
13206 tags))
13207 ((not org-use-tag-inheritance) nil)
13208 ((stringp org-use-tag-inheritance)
13209 (delq nil (mapcar
13210 (lambda (x)
13211 (if (and (string-match org-use-tag-inheritance x)
13212 (not (member x org-tags-exclude-from-inheritance)))
13213 x nil))
13214 tags)))
13215 ((listp org-use-tag-inheritance)
13216 (delq nil (mapcar
13217 (lambda (x)
13218 (if (member x org-use-tag-inheritance) x nil))
13219 tags)))))
13221 (defun org-match-sparse-tree (&optional todo-only match)
13222 "Create a sparse tree according to tags string MATCH.
13223 MATCH can contain positive and negative selection of tags, like
13224 \"+WORK+URGENT-WITHBOSS\".
13225 If optional argument TODO-ONLY is non-nil, only select lines that are
13226 also TODO lines."
13227 (interactive "P")
13228 (org-agenda-prepare-buffers (list (current-buffer)))
13229 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13231 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13233 (defvar org-cached-props nil)
13234 (defun org-cached-entry-get (pom property)
13235 (if (or (eq t org-use-property-inheritance)
13236 (and (stringp org-use-property-inheritance)
13237 (string-match org-use-property-inheritance property))
13238 (and (listp org-use-property-inheritance)
13239 (member property org-use-property-inheritance)))
13240 ;; Caching is not possible, check it directly
13241 (org-entry-get pom property 'inherit)
13242 ;; Get all properties, so that we can do complicated checks easily
13243 (cdr (assoc property (or org-cached-props
13244 (setq org-cached-props
13245 (org-entry-properties pom)))))))
13247 (defun org-global-tags-completion-table (&optional files)
13248 "Return the list of all tags in all agenda buffer/files.
13249 Optional FILES argument is a list of files which can be used
13250 instead of the agenda files."
13251 (save-excursion
13252 (org-uniquify
13253 (delq nil
13254 (apply 'append
13255 (mapcar
13256 (lambda (file)
13257 (set-buffer (find-file-noselect file))
13258 (append (org-get-buffer-tags)
13259 (mapcar (lambda (x) (if (stringp (car-safe x))
13260 (list (car-safe x)) nil))
13261 org-tag-alist)))
13262 (if (and files (car files))
13263 files
13264 (org-agenda-files))))))))
13266 (defun org-make-tags-matcher (match)
13267 "Create the TAGS/TODO matcher form for the selection string MATCH.
13269 The variable `todo-only' is scoped dynamically into this function.
13270 It will be set to t if the matcher restricts matching to TODO entries,
13271 otherwise will not be touched.
13273 Returns a cons of the selection string MATCH and the constructed
13274 lisp form implementing the matcher. The matcher is to be evaluated
13275 at an Org entry, with point on the headline, and returns t if the
13276 entry matches the selection string MATCH. The returned lisp form
13277 references two variables with information about the entry, which
13278 must be bound around the form's evaluation: todo, the TODO keyword
13279 at the entry (or nil of none); and tags-list, the list of all tags
13280 at the entry including inherited ones. Additionally, the category
13281 of the entry (if any) must be specified as the text property
13282 'org-category on the headline.
13284 See also `org-scan-tags'.
13286 (declare (special todo-only))
13287 (unless (boundp 'todo-only)
13288 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13289 (unless match
13290 ;; Get a new match request, with completion
13291 (let ((org-last-tags-completion-table
13292 (org-global-tags-completion-table)))
13293 (setq match (org-completing-read-no-i
13294 "Match: " 'org-tags-completion-function nil nil nil
13295 'org-tags-history))))
13297 ;; Parse the string and create a lisp form
13298 (let ((match0 match)
13299 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13300 minus tag mm
13301 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13302 orterms term orlist re-p str-p level-p level-op time-p
13303 prop-p pn pv po gv rest)
13304 (if (string-match "/+" match)
13305 ;; match contains also a todo-matching request
13306 (progn
13307 (setq tagsmatch (substring match 0 (match-beginning 0))
13308 todomatch (substring match (match-end 0)))
13309 (if (string-match "^!" todomatch)
13310 (setq todo-only t todomatch (substring todomatch 1)))
13311 (if (string-match "^\\s-*$" todomatch)
13312 (setq todomatch nil)))
13313 ;; only matching tags
13314 (setq tagsmatch match todomatch nil))
13316 ;; Make the tags matcher
13317 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13318 (setq tagsmatcher t)
13319 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13320 (while (setq term (pop orterms))
13321 (while (and (equal (substring term -1) "\\") orterms)
13322 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13323 (while (string-match re term)
13324 (setq rest (substring term (match-end 0))
13325 minus (and (match-end 1)
13326 (equal (match-string 1 term) "-"))
13327 tag (save-match-data (replace-regexp-in-string
13328 "\\\\-" "-"
13329 (match-string 2 term)))
13330 re-p (equal (string-to-char tag) ?{)
13331 level-p (match-end 4)
13332 prop-p (match-end 5)
13333 mm (cond
13334 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13335 (level-p
13336 (setq level-op (org-op-to-function (match-string 3 term)))
13337 `(,level-op level ,(string-to-number
13338 (match-string 4 term))))
13339 (prop-p
13340 (setq pn (match-string 5 term)
13341 po (match-string 6 term)
13342 pv (match-string 7 term)
13343 re-p (equal (string-to-char pv) ?{)
13344 str-p (equal (string-to-char pv) ?\")
13345 time-p (save-match-data
13346 (string-match "^\"[[<].*[]>]\"$" pv))
13347 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13348 (if time-p (setq pv (org-matcher-time pv)))
13349 (setq po (org-op-to-function po (if time-p 'time str-p)))
13350 (cond
13351 ((equal pn "CATEGORY")
13352 (setq gv '(get-text-property (point) 'org-category)))
13353 ((equal pn "TODO")
13354 (setq gv 'todo))
13356 (setq gv `(org-cached-entry-get nil ,pn))))
13357 (if re-p
13358 (if (eq po 'org<>)
13359 `(not (string-match ,pv (or ,gv "")))
13360 `(string-match ,pv (or ,gv "")))
13361 (if str-p
13362 `(,po (or ,gv "") ,pv)
13363 `(,po (string-to-number (or ,gv ""))
13364 ,(string-to-number pv) ))))
13365 (t `(member ,tag tags-list)))
13366 mm (if minus (list 'not mm) mm)
13367 term rest)
13368 (push mm tagsmatcher))
13369 (push (if (> (length tagsmatcher) 1)
13370 (cons 'and tagsmatcher)
13371 (car tagsmatcher))
13372 orlist)
13373 (setq tagsmatcher nil))
13374 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13375 (setq tagsmatcher
13376 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13377 ;; Make the todo matcher
13378 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13379 (setq todomatcher t)
13380 (setq orterms (org-split-string todomatch "|") orlist nil)
13381 (while (setq term (pop orterms))
13382 (while (string-match re term)
13383 (setq minus (and (match-end 1)
13384 (equal (match-string 1 term) "-"))
13385 kwd (match-string 2 term)
13386 re-p (equal (string-to-char kwd) ?{)
13387 term (substring term (match-end 0))
13388 mm (if re-p
13389 `(string-match ,(substring kwd 1 -1) todo)
13390 (list 'equal 'todo kwd))
13391 mm (if minus (list 'not mm) mm))
13392 (push mm todomatcher))
13393 (push (if (> (length todomatcher) 1)
13394 (cons 'and todomatcher)
13395 (car todomatcher))
13396 orlist)
13397 (setq todomatcher nil))
13398 (setq todomatcher (if (> (length orlist) 1)
13399 (cons 'or orlist) (car orlist))))
13401 ;; Return the string and lisp forms of the matcher
13402 (setq matcher (if todomatcher
13403 (list 'and tagsmatcher todomatcher)
13404 tagsmatcher))
13405 (when todo-only
13406 (setq matcher (list 'and '(member todo org-not-done-keywords)
13407 matcher)))
13408 (cons match0 matcher)))
13410 (defun org-op-to-function (op &optional stringp)
13411 "Turn an operator into the appropriate function."
13412 (setq op
13413 (cond
13414 ((equal op "<" ) '(< string< org-time<))
13415 ((equal op ">" ) '(> org-string> org-time>))
13416 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13417 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13418 ((member op '("=" "==")) '(= string= org-time=))
13419 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13420 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13422 (defun org<> (a b) (not (= a b)))
13423 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13424 (defun org-string>= (a b) (not (string< a b)))
13425 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13426 (defun org-string<> (a b) (not (string= a b)))
13427 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13428 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13429 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13430 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13431 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13432 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13433 (defun org-2ft (s)
13434 "Convert S to a floating point time.
13435 If S is already a number, just return it. If it is a string, parse
13436 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13437 (cond
13438 ((numberp s) s)
13439 ((stringp s)
13440 (condition-case nil
13441 (float-time (apply 'encode-time (org-parse-time-string s)))
13442 (error 0.)))
13443 (t 0.)))
13445 (defun org-time-today ()
13446 "Time in seconds today at 0:00.
13447 Returns the float number of seconds since the beginning of the
13448 epoch to the beginning of today (00:00)."
13449 (float-time (apply 'encode-time
13450 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13452 (defun org-matcher-time (s)
13453 "Interpret a time comparison value."
13454 (save-match-data
13455 (cond
13456 ((string= s "<now>") (float-time))
13457 ((string= s "<today>") (org-time-today))
13458 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13459 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13460 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13461 (+ (org-time-today)
13462 (* (string-to-number (match-string 1 s))
13463 (cdr (assoc (match-string 2 s)
13464 '(("d" . 86400.0) ("w" . 604800.0)
13465 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13466 (t (org-2ft s)))))
13468 (defun org-match-any-p (re list)
13469 "Does re match any element of list?"
13470 (setq list (mapcar (lambda (x) (string-match re x)) list))
13471 (delq nil list))
13473 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13474 (defvar org-tags-overlay (make-overlay 1 1))
13475 (org-detach-overlay org-tags-overlay)
13477 (defun org-get-local-tags-at (&optional pos)
13478 "Get a list of tags defined in the current headline."
13479 (org-get-tags-at pos 'local))
13481 (defun org-get-local-tags ()
13482 "Get a list of tags defined in the current headline."
13483 (org-get-tags-at nil 'local))
13485 (defun org-get-tags-at (&optional pos local)
13486 "Get a list of all headline tags applicable at POS.
13487 POS defaults to point. If tags are inherited, the list contains
13488 the targets in the same sequence as the headlines appear, i.e.
13489 the tags of the current headline come last.
13490 When LOCAL is non-nil, only return tags from the current headline,
13491 ignore inherited ones."
13492 (interactive)
13493 (if (and org-trust-scanner-tags
13494 (or (not pos) (equal pos (point)))
13495 (not local))
13496 org-scanner-tags
13497 (let (tags ltags lastpos parent)
13498 (save-excursion
13499 (save-restriction
13500 (widen)
13501 (goto-char (or pos (point)))
13502 (save-match-data
13503 (catch 'done
13504 (condition-case nil
13505 (progn
13506 (org-back-to-heading t)
13507 (while (not (equal lastpos (point)))
13508 (setq lastpos (point))
13509 (when (looking-at
13510 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13511 (setq ltags (org-split-string
13512 (org-match-string-no-properties 1) ":"))
13513 (when parent
13514 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13515 (setq tags (append
13516 (if parent
13517 (org-remove-uninherited-tags ltags)
13518 ltags)
13519 tags)))
13520 (or org-use-tag-inheritance (throw 'done t))
13521 (if local (throw 'done t))
13522 (or (org-up-heading-safe) (error nil))
13523 (setq parent t)))
13524 (error nil)))))
13525 (if local
13526 tags
13527 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13529 (defun org-add-prop-inherited (s)
13530 (add-text-properties 0 (length s) '(inherited t) s)
13533 (defun org-toggle-tag (tag &optional onoff)
13534 "Toggle the tag TAG for the current line.
13535 If ONOFF is `on' or `off', don't toggle but set to this state."
13536 (let (res current)
13537 (save-excursion
13538 (org-back-to-heading t)
13539 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13540 (point-at-eol) t)
13541 (progn
13542 (setq current (match-string 1))
13543 (replace-match ""))
13544 (setq current ""))
13545 (setq current (nreverse (org-split-string current ":")))
13546 (cond
13547 ((eq onoff 'on)
13548 (setq res t)
13549 (or (member tag current) (push tag current)))
13550 ((eq onoff 'off)
13551 (or (not (member tag current)) (setq current (delete tag current))))
13552 (t (if (member tag current)
13553 (setq current (delete tag current))
13554 (setq res t)
13555 (push tag current))))
13556 (end-of-line 1)
13557 (if current
13558 (progn
13559 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13560 (org-set-tags nil t))
13561 (delete-horizontal-space))
13562 (run-hooks 'org-after-tags-change-hook))
13563 res))
13565 (defun org-align-tags-here (to-col)
13566 ;; Assumes that this is a headline
13567 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13568 (beginning-of-line 1)
13569 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13570 (< pos (match-beginning 2)))
13571 (progn
13572 (setq tags-l (- (match-end 2) (match-beginning 2)))
13573 (goto-char (match-beginning 1))
13574 (insert " ")
13575 (delete-region (point) (1+ (match-beginning 2)))
13576 (setq ncol (max (current-column)
13577 (1+ col)
13578 (if (> to-col 0)
13579 to-col
13580 (- (abs to-col) tags-l))))
13581 (setq p (point))
13582 (insert (make-string (- ncol (current-column)) ?\ ))
13583 (setq ncol (current-column))
13584 (when indent-tabs-mode (tabify p (point-at-eol)))
13585 (org-move-to-column (min ncol col) t))
13586 (goto-char pos))))
13588 (defun org-set-tags-command (&optional arg just-align)
13589 "Call the set-tags command for the current entry."
13590 (interactive "P")
13591 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13592 (org-set-tags arg just-align)
13593 (save-excursion
13594 (org-back-to-heading t)
13595 (org-set-tags arg just-align))))
13597 (defun org-set-tags-to (data)
13598 "Set the tags of the current entry to DATA, replacing the current tags.
13599 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13600 If DATA is nil or the empty string, any tags will be removed."
13601 (interactive "sTags: ")
13602 (setq data
13603 (cond
13604 ((eq data nil) "")
13605 ((equal data "") "")
13606 ((stringp data)
13607 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13608 ":"))
13609 ((listp data)
13610 (concat ":" (mapconcat 'identity data ":") ":"))))
13611 (when data
13612 (save-excursion
13613 (org-back-to-heading t)
13614 (when (looking-at org-complex-heading-regexp)
13615 (if (match-end 5)
13616 (progn
13617 (goto-char (match-beginning 5))
13618 (insert data)
13619 (delete-region (point) (point-at-eol))
13620 (org-set-tags nil 'align))
13621 (goto-char (point-at-eol))
13622 (insert " " data)
13623 (org-set-tags nil 'align)))
13624 (beginning-of-line 1)
13625 (if (looking-at ".*?\\([ \t]+\\)$")
13626 (delete-region (match-beginning 1) (match-end 1))))))
13628 (defun org-align-all-tags ()
13629 "Align the tags i all headings."
13630 (interactive)
13631 (save-excursion
13632 (or (ignore-errors (org-back-to-heading t))
13633 (outline-next-heading))
13634 (if (org-at-heading-p)
13635 (org-set-tags t)
13636 (message "No headings"))))
13638 (defvar org-indent-indentation-per-level)
13639 (defun org-set-tags (&optional arg just-align)
13640 "Set the tags for the current headline.
13641 With prefix ARG, realign all tags in headings in the current buffer."
13642 (interactive "P")
13643 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13644 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13645 'region-start-level 'region))
13646 org-loop-over-headlines-in-active-region)
13647 (org-map-entries
13648 ;; We don't use ARG and JUST-ALIGN here these args are not
13649 ;; useful when looping over headlines
13650 `(org-set-tags)
13651 org-loop-over-headlines-in-active-region
13652 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13653 (let* ((re org-outline-regexp-bol)
13654 (current (unless arg (org-get-tags-string)))
13655 (col (current-column))
13656 (org-setting-tags t)
13657 table current-tags inherited-tags ; computed below when needed
13658 tags p0 c0 c1 rpl di tc level)
13659 (if arg
13660 (save-excursion
13661 (goto-char (point-min))
13662 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13663 (while (re-search-forward re nil t)
13664 (org-set-tags nil t)
13665 (end-of-line 1)))
13666 (message "All tags realigned to column %d" org-tags-column))
13667 (if just-align
13668 (setq tags current)
13669 ;; Get a new set of tags from the user
13670 (save-excursion
13671 (setq table (append org-tag-persistent-alist
13672 (or org-tag-alist (org-get-buffer-tags))
13673 (and
13674 org-complete-tags-always-offer-all-agenda-tags
13675 (org-global-tags-completion-table
13676 (org-agenda-files))))
13677 org-last-tags-completion-table table
13678 current-tags (org-split-string current ":")
13679 inherited-tags (nreverse
13680 (nthcdr (length current-tags)
13681 (nreverse (org-get-tags-at))))
13682 tags
13683 (if (or (eq t org-use-fast-tag-selection)
13684 (and org-use-fast-tag-selection
13685 (delq nil (mapcar 'cdr table))))
13686 (org-fast-tag-selection
13687 current-tags inherited-tags table
13688 (if org-fast-tag-selection-include-todo
13689 org-todo-key-alist))
13690 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13691 (org-trim
13692 (org-icompleting-read "Tags: "
13693 'org-tags-completion-function
13694 nil nil current 'org-tags-history))))))
13695 (while (string-match "[-+&]+" tags)
13696 ;; No boolean logic, just a list
13697 (setq tags (replace-match ":" t t tags))))
13699 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13701 (if org-tags-sort-function
13702 (setq tags (mapconcat 'identity
13703 (sort (org-split-string
13704 tags (org-re "[^[:alnum:]_@#%]+"))
13705 org-tags-sort-function) ":")))
13707 (if (string-match "\\`[\t ]*\\'" tags)
13708 (setq tags "")
13709 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13710 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13712 ;; Insert new tags at the correct column
13713 (beginning-of-line 1)
13714 (setq level (or (and (looking-at org-outline-regexp)
13715 (- (match-end 0) (point) 1))
13717 (cond
13718 ((and (equal current "") (equal tags "")))
13719 ((re-search-forward
13720 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13721 (point-at-eol) t)
13722 (if (equal tags "")
13723 (setq rpl "")
13724 (goto-char (match-beginning 0))
13725 (setq c0 (current-column)
13726 ;; compute offset for the case of org-indent-mode active
13727 di (if org-indent-mode
13728 (* (1- org-indent-indentation-per-level) (1- level))
13730 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13731 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13732 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13733 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13734 (replace-match rpl t t)
13735 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13736 tags)
13737 (t (error "Tags alignment failed")))
13738 (org-move-to-column col)
13739 (unless just-align
13740 (run-hooks 'org-after-tags-change-hook))))))
13742 (defun org-change-tag-in-region (beg end tag off)
13743 "Add or remove TAG for each entry in the region.
13744 This works in the agenda, and also in an org-mode buffer."
13745 (interactive
13746 (list (region-beginning) (region-end)
13747 (let ((org-last-tags-completion-table
13748 (if (derived-mode-p 'org-mode)
13749 (org-get-buffer-tags)
13750 (org-global-tags-completion-table))))
13751 (org-icompleting-read
13752 "Tag: " 'org-tags-completion-function nil nil nil
13753 'org-tags-history))
13754 (progn
13755 (message "[s]et or [r]emove? ")
13756 (equal (read-char-exclusive) ?r))))
13757 (if (fboundp 'deactivate-mark) (deactivate-mark))
13758 (let ((agendap (equal major-mode 'org-agenda-mode))
13759 l1 l2 m buf pos newhead (cnt 0))
13760 (goto-char end)
13761 (setq l2 (1- (org-current-line)))
13762 (goto-char beg)
13763 (setq l1 (org-current-line))
13764 (loop for l from l1 to l2 do
13765 (org-goto-line l)
13766 (setq m (get-text-property (point) 'org-hd-marker))
13767 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13768 (and agendap m))
13769 (setq buf (if agendap (marker-buffer m) (current-buffer))
13770 pos (if agendap m (point)))
13771 (with-current-buffer buf
13772 (save-excursion
13773 (save-restriction
13774 (goto-char pos)
13775 (setq cnt (1+ cnt))
13776 (org-toggle-tag tag (if off 'off 'on))
13777 (setq newhead (org-get-heading)))))
13778 (and agendap (org-agenda-change-all-lines newhead m))))
13779 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13781 (defun org-tags-completion-function (string predicate &optional flag)
13782 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13783 (confirm (lambda (x) (stringp (car x)))))
13784 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13785 (setq s1 (match-string 1 string)
13786 s2 (match-string 2 string))
13787 (setq s1 "" s2 string))
13788 (cond
13789 ((eq flag nil)
13790 ;; try completion
13791 (setq rtn (try-completion s2 ctable confirm))
13792 (if (stringp rtn)
13793 (setq rtn
13794 (concat s1 s2 (substring rtn (length s2))
13795 (if (and org-add-colon-after-tag-completion
13796 (assoc rtn ctable))
13797 ":" ""))))
13798 rtn)
13799 ((eq flag t)
13800 ;; all-completions
13801 (all-completions s2 ctable confirm)
13803 ((eq flag 'lambda)
13804 ;; exact match?
13805 (assoc s2 ctable)))
13808 (defun org-fast-tag-insert (kwd tags face &optional end)
13809 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13810 (insert (format "%-12s" (concat kwd ":"))
13811 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13812 (or end "")))
13814 (defun org-fast-tag-show-exit (flag)
13815 (save-excursion
13816 (org-goto-line 3)
13817 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13818 (replace-match ""))
13819 (when flag
13820 (end-of-line 1)
13821 (org-move-to-column (- (window-width) 19) t)
13822 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13824 (defun org-set-current-tags-overlay (current prefix)
13825 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13826 (if (featurep 'xemacs)
13827 (org-overlay-display org-tags-overlay (concat prefix s)
13828 'secondary-selection)
13829 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13830 (org-overlay-display org-tags-overlay (concat prefix s)))))
13832 (defvar org-last-tag-selection-key nil)
13833 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13834 "Fast tag selection with single keys.
13835 CURRENT is the current list of tags in the headline, INHERITED is the
13836 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13837 possibly with grouping information. TODO-TABLE is a similar table with
13838 TODO keywords, should these have keys assigned to them.
13839 If the keys are nil, a-z are automatically assigned.
13840 Returns the new tags string, or nil to not change the current settings."
13841 (let* ((fulltable (append table todo-table))
13842 (maxlen (apply 'max (mapcar
13843 (lambda (x)
13844 (if (stringp (car x)) (string-width (car x)) 0))
13845 fulltable)))
13846 (buf (current-buffer))
13847 (expert (eq org-fast-tag-selection-single-key 'expert))
13848 (buffer-tags nil)
13849 (fwidth (+ maxlen 3 1 3))
13850 (ncol (/ (- (window-width) 4) fwidth))
13851 (i-face 'org-done)
13852 (c-face 'org-todo)
13853 tg cnt e c char c1 c2 ntable tbl rtn
13854 ov-start ov-end ov-prefix
13855 (exit-after-next org-fast-tag-selection-single-key)
13856 (done-keywords org-done-keywords)
13857 groups ingroup)
13858 (save-excursion
13859 (beginning-of-line 1)
13860 (if (looking-at
13861 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13862 (setq ov-start (match-beginning 1)
13863 ov-end (match-end 1)
13864 ov-prefix "")
13865 (setq ov-start (1- (point-at-eol))
13866 ov-end (1+ ov-start))
13867 (skip-chars-forward "^\n\r")
13868 (setq ov-prefix
13869 (concat
13870 (buffer-substring (1- (point)) (point))
13871 (if (> (current-column) org-tags-column)
13873 (make-string (- org-tags-column (current-column)) ?\ ))))))
13874 (move-overlay org-tags-overlay ov-start ov-end)
13875 (save-window-excursion
13876 (if expert
13877 (set-buffer (get-buffer-create " *Org tags*"))
13878 (delete-other-windows)
13879 (split-window-vertically)
13880 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13881 (erase-buffer)
13882 (org-set-local 'org-done-keywords done-keywords)
13883 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13884 (org-fast-tag-insert "Current" current c-face "\n\n")
13885 (org-fast-tag-show-exit exit-after-next)
13886 (org-set-current-tags-overlay current ov-prefix)
13887 (setq tbl fulltable char ?a cnt 0)
13888 (while (setq e (pop tbl))
13889 (cond
13890 ((equal (car e) :startgroup)
13891 (push '() groups) (setq ingroup t)
13892 (when (not (= cnt 0))
13893 (setq cnt 0)
13894 (insert "\n"))
13895 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13896 ((equal (car e) :endgroup)
13897 (setq ingroup nil cnt 0)
13898 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13899 ((equal e '(:newline))
13900 (when (not (= cnt 0))
13901 (setq cnt 0)
13902 (insert "\n")
13903 (setq e (car tbl))
13904 (while (equal (car tbl) '(:newline))
13905 (insert "\n")
13906 (setq tbl (cdr tbl)))))
13908 (setq tg (copy-sequence (car e)) c2 nil)
13909 (if (cdr e)
13910 (setq c (cdr e))
13911 ;; automatically assign a character.
13912 (setq c1 (string-to-char
13913 (downcase (substring
13914 tg (if (= (string-to-char tg) ?@) 1 0)))))
13915 (if (or (rassoc c1 ntable) (rassoc c1 table))
13916 (while (or (rassoc char ntable) (rassoc char table))
13917 (setq char (1+ char)))
13918 (setq c2 c1))
13919 (setq c (or c2 char)))
13920 (if ingroup (push tg (car groups)))
13921 (setq tg (org-add-props tg nil 'face
13922 (cond
13923 ((not (assoc tg table))
13924 (org-get-todo-face tg))
13925 ((member tg current) c-face)
13926 ((member tg inherited) i-face))))
13927 (if (and (= cnt 0) (not ingroup)) (insert " "))
13928 (insert "[" c "] " tg (make-string
13929 (- fwidth 4 (length tg)) ?\ ))
13930 (push (cons tg c) ntable)
13931 (when (= (setq cnt (1+ cnt)) ncol)
13932 (insert "\n")
13933 (if ingroup (insert " "))
13934 (setq cnt 0)))))
13935 (setq ntable (nreverse ntable))
13936 (insert "\n")
13937 (goto-char (point-min))
13938 (if (not expert) (org-fit-window-to-buffer))
13939 (setq rtn
13940 (catch 'exit
13941 (while t
13942 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13943 (if (not groups) "no " "")
13944 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13945 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13946 (setq org-last-tag-selection-key c)
13947 (cond
13948 ((= c ?\r) (throw 'exit t))
13949 ((= c ?!)
13950 (setq groups (not groups))
13951 (goto-char (point-min))
13952 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13953 ((= c ?\C-c)
13954 (if (not expert)
13955 (org-fast-tag-show-exit
13956 (setq exit-after-next (not exit-after-next)))
13957 (setq expert nil)
13958 (delete-other-windows)
13959 (set-window-buffer (split-window-vertically) " *Org tags*")
13960 (org-switch-to-buffer-other-window " *Org tags*")
13961 (org-fit-window-to-buffer)))
13962 ((or (= c ?\C-g)
13963 (and (= c ?q) (not (rassoc c ntable))))
13964 (org-detach-overlay org-tags-overlay)
13965 (setq quit-flag t))
13966 ((= c ?\ )
13967 (setq current nil)
13968 (if exit-after-next (setq exit-after-next 'now)))
13969 ((= c ?\t)
13970 (condition-case nil
13971 (setq tg (org-icompleting-read
13972 "Tag: "
13973 (or buffer-tags
13974 (with-current-buffer buf
13975 (org-get-buffer-tags)))))
13976 (quit (setq tg "")))
13977 (when (string-match "\\S-" tg)
13978 (add-to-list 'buffer-tags (list tg))
13979 (if (member tg current)
13980 (setq current (delete tg current))
13981 (push tg current)))
13982 (if exit-after-next (setq exit-after-next 'now)))
13983 ((setq e (rassoc c todo-table) tg (car e))
13984 (with-current-buffer buf
13985 (save-excursion (org-todo tg)))
13986 (if exit-after-next (setq exit-after-next 'now)))
13987 ((setq e (rassoc c ntable) tg (car e))
13988 (if (member tg current)
13989 (setq current (delete tg current))
13990 (loop for g in groups do
13991 (if (member tg g)
13992 (mapc (lambda (x)
13993 (setq current (delete x current)))
13994 g)))
13995 (push tg current))
13996 (if exit-after-next (setq exit-after-next 'now))))
13998 ;; Create a sorted list
13999 (setq current
14000 (sort current
14001 (lambda (a b)
14002 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14003 (if (eq exit-after-next 'now) (throw 'exit t))
14004 (goto-char (point-min))
14005 (beginning-of-line 2)
14006 (delete-region (point) (point-at-eol))
14007 (org-fast-tag-insert "Current" current c-face)
14008 (org-set-current-tags-overlay current ov-prefix)
14009 (while (re-search-forward
14010 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14011 (setq tg (match-string 1))
14012 (add-text-properties
14013 (match-beginning 1) (match-end 1)
14014 (list 'face
14015 (cond
14016 ((member tg current) c-face)
14017 ((member tg inherited) i-face)
14018 (t (get-text-property (match-beginning 1) 'face))))))
14019 (goto-char (point-min)))))
14020 (org-detach-overlay org-tags-overlay)
14021 (if rtn
14022 (mapconcat 'identity current ":")
14023 nil))))
14025 (defun org-get-tags-string ()
14026 "Get the TAGS string in the current headline."
14027 (unless (org-at-heading-p t)
14028 (error "Not on a heading"))
14029 (save-excursion
14030 (beginning-of-line 1)
14031 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14032 (org-match-string-no-properties 1)
14033 "")))
14035 (defun org-get-tags ()
14036 "Get the list of tags specified in the current headline."
14037 (org-split-string (org-get-tags-string) ":"))
14039 (defun org-get-buffer-tags ()
14040 "Get a table of all tags used in the buffer, for completion."
14041 (let (tags)
14042 (save-excursion
14043 (goto-char (point-min))
14044 (while (re-search-forward
14045 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14046 (when (equal (char-after (point-at-bol 0)) ?*)
14047 (mapc (lambda (x) (add-to-list 'tags x))
14048 (org-split-string (org-match-string-no-properties 1) ":")))))
14049 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14050 (mapcar 'list tags)))
14052 ;;;; The mapping API
14054 (defun org-map-entries (func &optional match scope &rest skip)
14055 "Call FUNC at each headline selected by MATCH in SCOPE.
14057 FUNC is a function or a lisp form. The function will be called without
14058 arguments, with the cursor positioned at the beginning of the headline.
14059 The return values of all calls to the function will be collected and
14060 returned as a list.
14062 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14063 does not need to preserve point. After evaluation, the cursor will be
14064 moved to the end of the line (presumably of the headline of the
14065 processed entry) and search continues from there. Under some
14066 circumstances, this may not produce the wanted results. For example,
14067 if you have removed (e.g. archived) the current (sub)tree it could
14068 mean that the next entry will be skipped entirely. In such cases, you
14069 can specify the position from where search should continue by making
14070 FUNC set the variable `org-map-continue-from' to the desired buffer
14071 position.
14073 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14074 Only headlines that are matched by this query will be considered during
14075 the iteration. When MATCH is nil or t, all headlines will be
14076 visited by the iteration.
14078 SCOPE determines the scope of this command. It can be any of:
14080 nil The current buffer, respecting the restriction if any
14081 tree The subtree started with the entry at point
14082 region The entries within the active region, if any
14083 region-start-level
14084 The entries within the active region, but only those at
14085 the same level than the first one.
14086 file The current buffer, without restriction
14087 file-with-archives
14088 The current buffer, and any archives associated with it
14089 agenda All agenda files
14090 agenda-with-archives
14091 All agenda files with any archive files associated with them
14092 \(file1 file2 ...)
14093 If this is a list, all files in the list will be scanned
14095 The remaining args are treated as settings for the skipping facilities of
14096 the scanner. The following items can be given here:
14098 archive skip trees with the archive tag.
14099 comment skip trees with the COMMENT keyword
14100 function or Emacs Lisp form:
14101 will be used as value for `org-agenda-skip-function', so whenever
14102 the function returns t, FUNC will not be called for that
14103 entry and search will continue from the point where the
14104 function leaves it.
14106 If your function needs to retrieve the tags including inherited tags
14107 at the *current* entry, you can use the value of the variable
14108 `org-scanner-tags' which will be much faster than getting the value
14109 with `org-get-tags-at'. If your function gets properties with
14110 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14111 to t around the call to `org-entry-properties' to get the same speedup.
14112 Note that if your function moves around to retrieve tags and properties at
14113 a *different* entry, you cannot use these techniques."
14114 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14115 (not (org-region-active-p)))
14116 (let* ((org-agenda-archives-mode nil) ; just to make sure
14117 (org-agenda-skip-archived-trees (memq 'archive skip))
14118 (org-agenda-skip-comment-trees (memq 'comment skip))
14119 (org-agenda-skip-function
14120 (car (org-delete-all '(comment archive) skip)))
14121 (org-tags-match-list-sublevels t)
14122 (start-level (eq scope 'region-start-level))
14123 matcher file res
14124 org-todo-keywords-for-agenda
14125 org-done-keywords-for-agenda
14126 org-todo-keyword-alist-for-agenda
14127 org-drawers-for-agenda
14128 org-tag-alist-for-agenda
14129 todo-only)
14131 (cond
14132 ((eq match t) (setq matcher t))
14133 ((eq match nil) (setq matcher t))
14134 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14136 (save-excursion
14137 (save-restriction
14138 (cond ((eq scope 'tree)
14139 (org-back-to-heading t)
14140 (org-narrow-to-subtree)
14141 (setq scope nil))
14142 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14143 (org-region-active-p))
14144 ;; If needed, set start-level to a string like "2"
14145 (when start-level
14146 (save-excursion
14147 (goto-char (region-beginning))
14148 (unless (org-at-heading-p) (outline-next-heading))
14149 (setq start-level (org-current-level))))
14150 (narrow-to-region (region-beginning)
14151 (save-excursion
14152 (goto-char (region-end))
14153 (unless (and (bolp) (org-at-heading-p))
14154 (outline-next-heading))
14155 (point)))
14156 (setq scope nil)))
14158 (if (not scope)
14159 (progn
14160 (org-agenda-prepare-buffers
14161 (list (buffer-file-name (current-buffer))))
14162 (setq res (org-scan-tags func matcher todo-only start-level)))
14163 ;; Get the right scope
14164 (cond
14165 ((and scope (listp scope) (symbolp (car scope)))
14166 (setq scope (eval scope)))
14167 ((eq scope 'agenda)
14168 (setq scope (org-agenda-files t)))
14169 ((eq scope 'agenda-with-archives)
14170 (setq scope (org-agenda-files t))
14171 (setq scope (org-add-archive-files scope)))
14172 ((eq scope 'file)
14173 (setq scope (list (buffer-file-name))))
14174 ((eq scope 'file-with-archives)
14175 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14176 (org-agenda-prepare-buffers scope)
14177 (while (setq file (pop scope))
14178 (with-current-buffer (org-find-base-buffer-visiting file)
14179 (save-excursion
14180 (save-restriction
14181 (widen)
14182 (goto-char (point-min))
14183 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14184 res)))
14186 ;;;; Properties
14188 ;;; Setting and retrieving properties
14190 (defconst org-special-properties
14191 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14192 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14193 "The special properties valid in Org-mode.
14195 These are properties that are not defined in the property drawer,
14196 but in some other way.")
14198 (defconst org-default-properties
14199 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14200 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14201 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14202 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14203 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14204 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14205 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14206 "Some properties that are used by Org-mode for various purposes.
14207 Being in this list makes sure that they are offered for completion.")
14209 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14210 "Regular expression matching the first line of a property drawer.")
14212 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14213 "Regular expression matching the last line of a property drawer.")
14215 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14216 "Regular expression matching the first line of a property drawer.")
14218 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14219 "Regular expression matching the first line of a property drawer.")
14221 (defconst org-property-drawer-re
14222 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14223 org-property-end-re "\\)\n?")
14224 "Matches an entire property drawer.")
14226 (defconst org-clock-drawer-re
14227 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14228 org-property-end-re "\\)\n?")
14229 "Matches an entire clock drawer.")
14231 (defsubst org-re-property (property)
14232 "Return a regexp matching a PROPERTY line.
14233 Match group 1 will be set to the value."
14234 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14236 (defsubst org-re-property-keyword (property)
14237 "Return a regexp matching a PROPERTY line, possibly with no
14238 value for the property."
14239 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14241 (defun org-property-action ()
14242 "Do an action on properties."
14243 (interactive)
14244 (let (c)
14245 (org-at-property-p)
14246 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14247 (setq c (read-char-exclusive))
14248 (cond
14249 ((equal c ?s)
14250 (call-interactively 'org-set-property))
14251 ((equal c ?d)
14252 (call-interactively 'org-delete-property))
14253 ((equal c ?D)
14254 (call-interactively 'org-delete-property-globally))
14255 ((equal c ?c)
14256 (call-interactively 'org-compute-property-at-point))
14257 (t (error "No such property action %c" c)))))
14259 (defun org-inc-effort ()
14260 "Increment the value of the effort property in the current entry."
14261 (interactive)
14262 (org-set-effort nil t))
14264 (defun org-set-effort (&optional value increment)
14265 "Set the effort property of the current entry.
14266 With numerical prefix arg, use the nth allowed value, 0 stands for the
14267 10th allowed value.
14269 When INCREMENT is non-nil, set the property to the next allowed value."
14270 (interactive "P")
14271 (if (equal value 0) (setq value 10))
14272 (let* ((completion-ignore-case t)
14273 (prop org-effort-property)
14274 (cur (org-entry-get nil prop))
14275 (allowed (org-property-get-allowed-values nil prop 'table))
14276 (existing (mapcar 'list (org-property-values prop)))
14278 (val (cond
14279 ((stringp value) value)
14280 ((and allowed (integerp value))
14281 (or (car (nth (1- value) allowed))
14282 (car (org-last allowed))))
14283 ((and allowed increment)
14284 (or (caadr (member (list cur) allowed))
14285 (error "Allowed effort values are not set")))
14286 (allowed
14287 (message "Select 1-9,0, [RET%s]: %s"
14288 (if cur (concat "=" cur) "")
14289 (mapconcat 'car allowed " "))
14290 (setq rpl (read-char-exclusive))
14291 (if (equal rpl ?\r)
14293 (setq rpl (- rpl ?0))
14294 (if (equal rpl 0) (setq rpl 10))
14295 (if (and (> rpl 0) (<= rpl (length allowed)))
14296 (car (nth (1- rpl) allowed))
14297 (org-completing-read "Effort: " allowed nil))))
14299 (let (org-completion-use-ido org-completion-use-iswitchb)
14300 (org-completing-read
14301 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14302 (concat "[" cur "]") "")
14303 ": ")
14304 existing nil nil "" nil cur))))))
14305 (unless (equal (org-entry-get nil prop) val)
14306 (org-entry-put nil prop val))
14307 (save-excursion
14308 (org-back-to-heading t)
14309 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14310 (message "%s is now %s" prop val)))
14312 (defun org-at-property-p ()
14313 "Is cursor inside a property drawer?"
14314 (save-excursion
14315 (beginning-of-line 1)
14316 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14317 (save-match-data ;; Used by calling procedures
14318 (let ((p (point))
14319 (range (unless (org-before-first-heading-p)
14320 (org-get-property-block))))
14321 (and range (<= (car range) p) (< p (cdr range))))))))
14323 (defun org-get-property-block (&optional beg end force)
14324 "Return the (beg . end) range of the body of the property drawer.
14325 BEG and END are the beginning and end of the current subtree, or of
14326 the part before the first headline. If they are not given, they will
14327 be found. If the drawer does not exist and FORCE is non-nil, create
14328 the drawer."
14329 (catch 'exit
14330 (save-excursion
14331 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14332 (progn (org-back-to-heading t) (point))))
14333 (end (or end (and (not (outline-next-heading)) (point-max))
14334 (point))))
14335 (goto-char beg)
14336 (if (re-search-forward org-property-start-re end t)
14337 (setq beg (1+ (match-end 0)))
14338 (if force
14339 (save-excursion
14340 (org-insert-property-drawer)
14341 (setq end (progn (outline-next-heading) (point))))
14342 (throw 'exit nil))
14343 (goto-char beg)
14344 (if (re-search-forward org-property-start-re end t)
14345 (setq beg (1+ (match-end 0)))))
14346 (if (re-search-forward org-property-end-re end t)
14347 (setq end (match-beginning 0))
14348 (or force (throw 'exit nil))
14349 (goto-char beg)
14350 (setq end beg)
14351 (org-indent-line)
14352 (insert ":END:\n"))
14353 (cons beg end)))))
14355 (defun org-entry-properties (&optional pom which specific)
14356 "Get all properties of the entry at point-or-marker POM.
14357 This includes the TODO keyword, the tags, time strings for deadline,
14358 scheduled, and clocking, and any additional properties defined in the
14359 entry. The return value is an alist, keys may occur multiple times
14360 if the property key was used several times.
14361 POM may also be nil, in which case the current entry is used.
14362 If WHICH is nil or `all', get all properties. If WHICH is
14363 `special' or `standard', only get that subclass. If WHICH
14364 is a string only get exactly this property. SPECIFIC can be a string, the
14365 specific property we are interested in. Specifying it can speed
14366 things up because then unnecessary parsing is avoided."
14367 (setq which (or which 'all))
14368 (org-with-point-at pom
14369 (let ((clockstr (substring org-clock-string 0 -1))
14370 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14371 (case-fold-search nil)
14372 beg end range props sum-props key key1 value string clocksum clocksumt)
14373 (save-excursion
14374 (when (condition-case nil
14375 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14376 (error nil))
14377 (setq beg (point))
14378 (setq sum-props (get-text-property (point) 'org-summaries))
14379 (setq clocksum (get-text-property (point) :org-clock-minutes)
14380 clocksumt (get-text-property (point) :org-clock-minutes-today))
14381 (outline-next-heading)
14382 (setq end (point))
14383 (when (memq which '(all special))
14384 ;; Get the special properties, like TODO and tags
14385 (goto-char beg)
14386 (when (and (or (not specific) (string= specific "TODO"))
14387 (looking-at org-todo-line-regexp) (match-end 2))
14388 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14389 (when (and (or (not specific) (string= specific "PRIORITY"))
14390 (looking-at org-priority-regexp))
14391 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14392 (when (or (not specific) (string= specific "FILE"))
14393 (push (cons "FILE" buffer-file-name) props))
14394 (when (and (or (not specific) (string= specific "TAGS"))
14395 (setq value (org-get-tags-string))
14396 (string-match "\\S-" value))
14397 (push (cons "TAGS" value) props))
14398 (when (and (or (not specific) (string= specific "ALLTAGS"))
14399 (setq value (org-get-tags-at)))
14400 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14401 ":"))
14402 props))
14403 (when (or (not specific) (string= specific "BLOCKED"))
14404 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14405 (when (or (not specific)
14406 (member specific
14407 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14408 "TIMESTAMP" "TIMESTAMP_IA")))
14409 (catch 'match
14410 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14411 (setq key (if (match-end 1)
14412 (substring (org-match-string-no-properties 1)
14413 0 -1))
14414 string (if (equal key clockstr)
14415 (org-trim
14416 (buffer-substring-no-properties
14417 (match-beginning 3) (goto-char
14418 (point-at-eol))))
14419 (substring (org-match-string-no-properties 3)
14420 1 -1)))
14421 ;; Get the correct property name from the key. This is
14422 ;; necessary if the user has configured time keywords.
14423 (setq key1 (concat key ":"))
14424 (cond
14425 ((not key)
14426 (setq key
14427 (if (= (char-after (match-beginning 3)) ?\[)
14428 "TIMESTAMP_IA" "TIMESTAMP")))
14429 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14430 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14431 ((equal key1 org-closed-string) (setq key "CLOSED"))
14432 ((equal key1 org-clock-string) (setq key "CLOCK")))
14433 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14434 (progn
14435 (push (cons key string) props)
14436 ;; no need to search further if match is found
14437 (throw 'match t))
14438 (when (or (equal key "CLOCK") (not (assoc key props)))
14439 (push (cons key string) props)))))))
14441 (when (memq which '(all standard))
14442 ;; Get the standard properties, like :PROP: ...
14443 (setq range (org-get-property-block beg end))
14444 (when range
14445 (goto-char (car range))
14446 (while (re-search-forward
14447 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14448 (cdr range) t)
14449 (setq key (org-match-string-no-properties 1)
14450 value (org-trim (or (org-match-string-no-properties 2) "")))
14451 (unless (member key excluded)
14452 (push (cons key (or value "")) props)))))
14453 (if clocksum
14454 (push (cons "CLOCKSUM"
14455 (org-columns-number-to-string (/ (float clocksum) 60.)
14456 'add_times))
14457 props))
14458 (if clocksumt
14459 (push (cons "CLOCKSUM_T"
14460 (org-columns-number-to-string (/ (float clocksumt) 60.)
14461 'add_times))
14462 props))
14463 (unless (assoc "CATEGORY" props)
14464 (push (cons "CATEGORY" (org-get-category)) props))
14465 (append sum-props (nreverse props)))))))
14467 (defun org-entry-get (pom property &optional inherit literal-nil)
14468 "Get value of PROPERTY for entry or content at point-or-marker POM.
14469 If INHERIT is non-nil and the entry does not have the property,
14470 then also check higher levels of the hierarchy.
14471 If INHERIT is the symbol `selective', use inheritance only if the setting
14472 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14473 If the property is present but empty, the return value is the empty string.
14474 If the property is not present at all, nil is returned.
14476 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14477 do not interpret it as the list atom nil. This is used for inheritance
14478 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14479 (org-with-point-at pom
14480 (if (and inherit (if (eq inherit 'selective)
14481 (org-property-inherit-p property)
14483 (org-entry-get-with-inheritance property literal-nil)
14484 (if (member property org-special-properties)
14485 ;; We need a special property. Use `org-entry-properties' to
14486 ;; retrieve it, but specify the wanted property
14487 (cdr (assoc property (org-entry-properties nil 'special property)))
14488 (let* ((range (org-get-property-block))
14489 (props (list (or (assoc property org-file-properties)
14490 (assoc property org-global-properties)
14491 (assoc property org-global-properties-fixed))))
14492 (ap (lambda (key)
14493 (when (re-search-forward
14494 (org-re-property key) (cdr range) t)
14495 (setq props
14496 (org-update-property-plist
14498 (if (match-end 1)
14499 (org-match-string-no-properties 1) "")
14500 props)))))
14501 val)
14502 (when (and range (goto-char (car range)))
14503 (funcall ap property)
14504 (goto-char (car range))
14505 (while (funcall ap (concat property "+")))
14506 (setq val (cdr (assoc property props)))
14507 (when val (if literal-nil val (org-not-nil val)))))))))
14509 (defun org-property-or-variable-value (var &optional inherit)
14510 "Check if there is a property fixing the value of VAR.
14511 If yes, return this value. If not, return the current value of the variable."
14512 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14513 (if (and prop (stringp prop) (string-match "\\S-" prop))
14514 (read prop)
14515 (symbol-value var))))
14517 (defun org-entry-delete (pom property)
14518 "Delete the property PROPERTY from entry at point-or-marker POM."
14519 (org-with-point-at pom
14520 (if (member property org-special-properties)
14521 nil ; cannot delete these properties.
14522 (let ((range (org-get-property-block)))
14523 (if (and range
14524 (goto-char (car range))
14525 (re-search-forward
14526 (org-re-property property)
14527 (cdr range) t))
14528 (progn
14529 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14531 nil)))))
14533 ;; Multi-values properties are properties that contain multiple values
14534 ;; These values are assumed to be single words, separated by whitespace.
14535 (defun org-entry-add-to-multivalued-property (pom property value)
14536 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14537 (let* ((old (org-entry-get pom property))
14538 (values (and old (org-split-string old "[ \t]"))))
14539 (setq value (org-entry-protect-space value))
14540 (unless (member value values)
14541 (setq values (cons value values))
14542 (org-entry-put pom property
14543 (mapconcat 'identity values " ")))))
14545 (defun org-entry-remove-from-multivalued-property (pom property value)
14546 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14547 (let* ((old (org-entry-get pom property))
14548 (values (and old (org-split-string old "[ \t]"))))
14549 (setq value (org-entry-protect-space value))
14550 (when (member value values)
14551 (setq values (delete value values))
14552 (org-entry-put pom property
14553 (mapconcat 'identity values " ")))))
14555 (defun org-entry-member-in-multivalued-property (pom property value)
14556 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14557 (let* ((old (org-entry-get pom property))
14558 (values (and old (org-split-string old "[ \t]"))))
14559 (setq value (org-entry-protect-space value))
14560 (member value values)))
14562 (defun org-entry-get-multivalued-property (pom property)
14563 "Return a list of values in a multivalued property."
14564 (let* ((value (org-entry-get pom property))
14565 (values (and value (org-split-string value "[ \t]"))))
14566 (mapcar 'org-entry-restore-space values)))
14568 (defun org-entry-put-multivalued-property (pom property &rest values)
14569 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14570 VALUES should be a list of strings. Spaces will be protected."
14571 (org-entry-put pom property
14572 (mapconcat 'org-entry-protect-space values " "))
14573 (let* ((value (org-entry-get pom property))
14574 (values (and value (org-split-string value "[ \t]"))))
14575 (mapcar 'org-entry-restore-space values)))
14577 (defun org-entry-protect-space (s)
14578 "Protect spaces and newline in string S."
14579 (while (string-match " " s)
14580 (setq s (replace-match "%20" t t s)))
14581 (while (string-match "\n" s)
14582 (setq s (replace-match "%0A" t t s)))
14585 (defun org-entry-restore-space (s)
14586 "Restore spaces and newline in string S."
14587 (while (string-match "%20" s)
14588 (setq s (replace-match " " t t s)))
14589 (while (string-match "%0A" s)
14590 (setq s (replace-match "\n" t t s)))
14593 (defvar org-entry-property-inherited-from (make-marker)
14594 "Marker pointing to the entry from where a property was inherited.
14595 Each call to `org-entry-get-with-inheritance' will set this marker to the
14596 location of the entry where the inheritance search matched. If there was
14597 no match, the marker will point nowhere.
14598 Note that also `org-entry-get' calls this function, if the INHERIT flag
14599 is set.")
14601 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14602 "Get PROPERTY of entry or content at point, search higher levels if needed.
14603 The search will stop at the first ancestor which has the property defined.
14604 If the value found is \"nil\", return nil to show that the property
14605 should be considered as undefined (this is the meaning of nil here).
14606 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14607 (move-marker org-entry-property-inherited-from nil)
14608 (let (tmp)
14609 (save-excursion
14610 (save-restriction
14611 (widen)
14612 (catch 'ex
14613 (while t
14614 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14615 (or (ignore-errors (org-back-to-heading t))
14616 (goto-char (point-min)))
14617 (move-marker org-entry-property-inherited-from (point))
14618 (throw 'ex tmp))
14619 (or (ignore-errors (org-up-heading-safe))
14620 (throw 'ex nil))))))
14621 (setq tmp (or tmp
14622 (cdr (assoc property org-file-properties))
14623 (cdr (assoc property org-global-properties))
14624 (cdr (assoc property org-global-properties-fixed))))
14625 (if literal-nil tmp (org-not-nil tmp))))
14627 (defvar org-property-changed-functions nil
14628 "Hook called when the value of a property has changed.
14629 Each hook function should accept two arguments, the name of the property
14630 and the new value.")
14632 (defun org-entry-put (pom property value)
14633 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14634 (org-with-point-at pom
14635 (org-back-to-heading t)
14636 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14637 range)
14638 (cond
14639 ((equal property "TODO")
14640 (when (and (stringp value) (string-match "\\S-" value)
14641 (not (member value org-todo-keywords-1)))
14642 (error "\"%s\" is not a valid TODO state" value))
14643 (if (or (not value)
14644 (not (string-match "\\S-" value)))
14645 (setq value 'none))
14646 (org-todo value)
14647 (org-set-tags nil 'align))
14648 ((equal property "PRIORITY")
14649 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14650 (string-to-char value) ?\ ))
14651 (org-set-tags nil 'align))
14652 ((equal property "SCHEDULED")
14653 (if (re-search-forward org-scheduled-time-regexp end t)
14654 (cond
14655 ((eq value 'earlier) (org-timestamp-change -1 'day))
14656 ((eq value 'later) (org-timestamp-change 1 'day))
14657 (t (call-interactively 'org-schedule)))
14658 (call-interactively 'org-schedule)))
14659 ((equal property "DEADLINE")
14660 (if (re-search-forward org-deadline-time-regexp end t)
14661 (cond
14662 ((eq value 'earlier) (org-timestamp-change -1 'day))
14663 ((eq value 'later) (org-timestamp-change 1 'day))
14664 (t (call-interactively 'org-deadline)))
14665 (call-interactively 'org-deadline)))
14666 ((member property org-special-properties)
14667 (error "The %s property can not yet be set with `org-entry-put'"
14668 property))
14669 (t ; a non-special property
14670 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14671 (setq range (org-get-property-block beg end 'force))
14672 (goto-char (car range))
14673 (if (re-search-forward
14674 (org-re-property-keyword property) (cdr range) t)
14675 (progn
14676 (delete-region (match-beginning 0) (match-end 0))
14677 (goto-char (match-beginning 0)))
14678 (goto-char (cdr range))
14679 (insert "\n")
14680 (backward-char 1)
14681 (org-indent-line))
14682 (insert ":" property ":")
14683 (and value (insert " " value))
14684 (org-indent-line)))))
14685 (run-hook-with-args 'org-property-changed-functions property value)))
14687 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14688 "Get all property keys in the current buffer.
14689 With INCLUDE-SPECIALS, also list the special properties that reflect things
14690 like tags and TODO state.
14691 With INCLUDE-DEFAULTS, also include properties that has special meaning
14692 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14693 and others.
14694 With INCLUDE-COLUMNS, also include property names given in COLUMN
14695 formats in the current buffer."
14696 (let (rtn range cfmt s p)
14697 (save-excursion
14698 (save-restriction
14699 (widen)
14700 (goto-char (point-min))
14701 (while (re-search-forward org-property-start-re nil t)
14702 (setq range (org-get-property-block))
14703 (goto-char (car range))
14704 (while (re-search-forward
14705 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14706 (cdr range) t)
14707 (add-to-list 'rtn (org-match-string-no-properties 1)))
14708 (outline-next-heading))))
14710 (when include-specials
14711 (setq rtn (append org-special-properties rtn)))
14713 (when include-defaults
14714 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14715 (add-to-list 'rtn org-effort-property))
14717 (when include-columns
14718 (save-excursion
14719 (save-restriction
14720 (widen)
14721 (goto-char (point-min))
14722 (while (re-search-forward
14723 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14724 nil t)
14725 (setq cfmt (match-string 2) s 0)
14726 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14727 cfmt s)
14728 (setq s (match-end 0)
14729 p (match-string 1 cfmt))
14730 (unless (or (equal p "ITEM")
14731 (member p org-special-properties))
14732 (add-to-list 'rtn (match-string 1 cfmt))))))))
14734 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14736 (defun org-property-values (key)
14737 "Return a list of all values of property KEY in the current buffer."
14738 (save-excursion
14739 (save-restriction
14740 (widen)
14741 (goto-char (point-min))
14742 (let ((re (org-re-property key))
14743 values)
14744 (while (re-search-forward re nil t)
14745 (add-to-list 'values (org-trim (match-string 1))))
14746 (delete "" values)))))
14748 (defun org-insert-property-drawer ()
14749 "Insert a property drawer into the current entry."
14750 (org-back-to-heading t)
14751 (looking-at org-outline-regexp)
14752 (let ((indent (if org-adapt-indentation
14753 (- (match-end 0) (match-beginning 0))
14755 (beg (point))
14756 (re (concat "^[ \t]*" org-keyword-time-regexp))
14757 end hiddenp)
14758 (outline-next-heading)
14759 (setq end (point))
14760 (goto-char beg)
14761 (while (re-search-forward re end t))
14762 (setq hiddenp (outline-invisible-p))
14763 (end-of-line 1)
14764 (and (equal (char-after) ?\n) (forward-char 1))
14765 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14766 (if (member (match-string 1) '("CLOCK:" ":END:"))
14767 ;; just skip this line
14768 (beginning-of-line 2)
14769 ;; Drawer start, find the end
14770 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14771 (beginning-of-line 1)))
14772 (org-skip-over-state-notes)
14773 (skip-chars-backward " \t\n\r")
14774 (if (eq (char-before) ?*) (forward-char 1))
14775 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14776 (beginning-of-line 0)
14777 (org-indent-to-column indent)
14778 (beginning-of-line 2)
14779 (org-indent-to-column indent)
14780 (beginning-of-line 0)
14781 (if hiddenp
14782 (save-excursion
14783 (org-back-to-heading t)
14784 (hide-entry))
14785 (org-flag-drawer t))))
14787 (defun org-insert-drawer (&optional arg drawer)
14788 "Insert a drawer at point.
14790 Optional argument DRAWER, when non-nil, is a string representing
14791 drawer's name. Otherwise, the user is prompted for a name.
14793 If a region is active, insert the drawer around that region
14794 instead.
14796 Point is left between drawer's boundaries."
14797 (interactive "P")
14798 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14799 "LOGBOOK"))
14800 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14801 ;; internally by Org. They are meant to be inserted
14802 ;; automatically.
14803 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14804 ;; Remove system drawers from list. Note: For some reason,
14805 ;; `org-completing-read' ignores the predicate while
14806 ;; `completing-read' handles it fine.
14807 (drawer (if arg "PROPERTIES"
14808 (or drawer
14809 (completing-read
14810 "Drawer: " org-drawers
14811 (lambda (d) (not (member d system-drawers))))))))
14812 (cond
14813 ;; With C-u, fall back on `org-insert-property-drawer'
14814 (arg (org-insert-property-drawer))
14815 ;; With an active region, insert a drawer at point.
14816 ((not (org-region-active-p))
14817 (progn
14818 (unless (bolp) (insert "\n"))
14819 (insert (format ":%s:\n\n:END:\n" drawer))
14820 (forward-line -2)))
14821 ;; Otherwise, insert the drawer at point
14823 (let ((rbeg (region-beginning))
14824 (rend (copy-marker (region-end))))
14825 (unwind-protect
14826 (progn
14827 (goto-char rbeg)
14828 (beginning-of-line)
14829 (when (save-excursion
14830 (re-search-forward org-outline-regexp-bol rend t))
14831 (error "Drawers cannot contain headlines"))
14832 ;; Position point at the beginning of the first
14833 ;; non-blank line in region. Insert drawer's opening
14834 ;; there, then indent it.
14835 (org-skip-whitespace)
14836 (beginning-of-line)
14837 (insert ":" drawer ":\n")
14838 (forward-line -1)
14839 (indent-for-tab-command)
14840 ;; Move point to the beginning of the first blank line
14841 ;; after the last non-blank line in region. Insert
14842 ;; drawer's closing, then indent it.
14843 (goto-char rend)
14844 (skip-chars-backward " \r\t\n")
14845 (insert "\n:END:")
14846 (deactivate-mark t)
14847 (indent-for-tab-command)
14848 (unless (eolp) (insert "\n")))
14849 ;; Clear marker, whatever the outcome of insertion is.
14850 (set-marker rend nil)))))))
14852 (defvar org-property-set-functions-alist nil
14853 "Property set function alist.
14854 Each entry should have the following format:
14856 (PROPERTY . READ-FUNCTION)
14858 The read function will be called with the same argument as
14859 `org-completing-read'.")
14861 (defun org-set-property-function (property)
14862 "Get the function that should be used to set PROPERTY.
14863 This is computed according to `org-property-set-functions-alist'."
14864 (or (cdr (assoc property org-property-set-functions-alist))
14865 'org-completing-read))
14867 (defun org-read-property-value (property)
14868 "Read PROPERTY value from user."
14869 (let* ((completion-ignore-case t)
14870 (allowed (org-property-get-allowed-values nil property 'table))
14871 (cur (org-entry-get nil property))
14872 (prompt (concat property " value"
14873 (if (and cur (string-match "\\S-" cur))
14874 (concat " [" cur "]") "") ": "))
14875 (set-function (org-set-property-function property))
14876 (val (if allowed
14877 (funcall set-function prompt allowed nil
14878 (not (get-text-property 0 'org-unrestricted
14879 (caar allowed))))
14880 (let (org-completion-use-ido org-completion-use-iswitchb)
14881 (funcall set-function prompt
14882 (mapcar 'list (org-property-values property))
14883 nil nil "" nil cur)))))
14884 (if (equal val "")
14886 val)))
14888 (defvar org-last-set-property nil)
14889 (defun org-read-property-name ()
14890 "Read a property name."
14891 (let* ((completion-ignore-case t)
14892 (keys (org-buffer-property-keys nil t t))
14893 (default-prop (or (save-excursion
14894 (save-match-data
14895 (beginning-of-line)
14896 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14897 (null (string= (match-string 1) "END"))
14898 (match-string 1))))
14899 org-last-set-property))
14900 (property (org-icompleting-read
14901 (concat "Property"
14902 (if default-prop (concat " [" default-prop "]") "")
14903 ": ")
14904 (mapcar 'list keys)
14905 nil nil nil nil
14906 default-prop
14908 (if (member property keys)
14909 property
14910 (or (cdr (assoc (downcase property)
14911 (mapcar (lambda (x) (cons (downcase x) x))
14912 keys)))
14913 property))))
14915 (defun org-set-property (property value)
14916 "In the current entry, set PROPERTY to VALUE.
14917 When called interactively, this will prompt for a property name, offering
14918 completion on existing and default properties. And then it will prompt
14919 for a value, offering completion either on allowed values (via an inherited
14920 xxx_ALL property) or on existing values in other instances of this property
14921 in the current file."
14922 (interactive (list nil nil))
14923 (let* ((property (or property (org-read-property-name)))
14924 (value (or value (org-read-property-value property)))
14925 (fn (cdr (assoc property org-properties-postprocess-alist))))
14926 (setq org-last-set-property property)
14927 ;; Possibly postprocess the inserted value:
14928 (when fn (setq value (funcall fn value)))
14929 (unless (equal (org-entry-get nil property) value)
14930 (org-entry-put nil property value))))
14932 (defun org-delete-property (property)
14933 "In the current entry, delete PROPERTY."
14934 (interactive
14935 (let* ((completion-ignore-case t)
14936 (prop (org-icompleting-read "Property: "
14937 (org-entry-properties nil 'standard))))
14938 (list prop)))
14939 (message "Property %s %s" property
14940 (if (org-entry-delete nil property)
14941 "deleted"
14942 "was not present in the entry")))
14944 (defun org-delete-property-globally (property)
14945 "Remove PROPERTY globally, from all entries."
14946 (interactive
14947 (let* ((completion-ignore-case t)
14948 (prop (org-icompleting-read
14949 "Globally remove property: "
14950 (mapcar 'list (org-buffer-property-keys)))))
14951 (list prop)))
14952 (save-excursion
14953 (save-restriction
14954 (widen)
14955 (goto-char (point-min))
14956 (let ((cnt 0))
14957 (while (re-search-forward
14958 (org-re-property property)
14959 nil t)
14960 (setq cnt (1+ cnt))
14961 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14962 (message "Property \"%s\" removed from %d entries" property cnt)))))
14964 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14966 (defun org-compute-property-at-point ()
14967 "Compute the property at point.
14968 This looks for an enclosing column format, extracts the operator and
14969 then applies it to the property in the column format's scope."
14970 (interactive)
14971 (unless (org-at-property-p)
14972 (error "Not at a property"))
14973 (let ((prop (org-match-string-no-properties 2)))
14974 (org-columns-get-format-and-top-level)
14975 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14976 (error "No operator defined for property %s" prop))
14977 (org-columns-compute prop)))
14979 (defvar org-property-allowed-value-functions nil
14980 "Hook for functions supplying allowed values for a specific property.
14981 The functions must take a single argument, the name of the property, and
14982 return a flat list of allowed values. If \":ETC\" is one of
14983 the values, this means that these values are intended as defaults for
14984 completion, but that other values should be allowed too.
14985 The functions must return nil if they are not responsible for this
14986 property.")
14988 (defun org-property-get-allowed-values (pom property &optional table)
14989 "Get allowed values for the property PROPERTY.
14990 When TABLE is non-nil, return an alist that can directly be used for
14991 completion."
14992 (let (vals)
14993 (cond
14994 ((equal property "TODO")
14995 (setq vals (org-with-point-at pom
14996 (append org-todo-keywords-1 '("")))))
14997 ((equal property "PRIORITY")
14998 (let ((n org-lowest-priority))
14999 (while (>= n org-highest-priority)
15000 (push (char-to-string n) vals)
15001 (setq n (1- n)))))
15002 ((member property org-special-properties))
15003 ((setq vals (run-hook-with-args-until-success
15004 'org-property-allowed-value-functions property)))
15006 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15007 (when (and vals (string-match "\\S-" vals))
15008 (setq vals (car (read-from-string (concat "(" vals ")"))))
15009 (setq vals (mapcar (lambda (x)
15010 (cond ((stringp x) x)
15011 ((numberp x) (number-to-string x))
15012 ((symbolp x) (symbol-name x))
15013 (t "???")))
15014 vals)))))
15015 (when (member ":ETC" vals)
15016 (setq vals (remove ":ETC" vals))
15017 (org-add-props (car vals) '(org-unrestricted t)))
15018 (if table (mapcar 'list vals) vals)))
15020 (defun org-property-previous-allowed-value (&optional previous)
15021 "Switch to the next allowed value for this property."
15022 (interactive)
15023 (org-property-next-allowed-value t))
15025 (defun org-property-next-allowed-value (&optional previous)
15026 "Switch to the next allowed value for this property."
15027 (interactive)
15028 (unless (org-at-property-p)
15029 (error "Not at a property"))
15030 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15031 (key (match-string 2))
15032 (value (match-string 3))
15033 (allowed (or (org-property-get-allowed-values (point) key)
15034 (and (member value '("[ ]" "[-]" "[X]"))
15035 '("[ ]" "[X]"))))
15036 nval)
15037 (unless allowed
15038 (error "Allowed values for this property have not been defined"))
15039 (if previous (setq allowed (reverse allowed)))
15040 (if (member value allowed)
15041 (setq nval (car (cdr (member value allowed)))))
15042 (setq nval (or nval (car allowed)))
15043 (if (equal nval value)
15044 (error "Only one allowed value for this property"))
15045 (org-at-property-p)
15046 (replace-match (concat " :" key ": " nval) t t)
15047 (org-indent-line)
15048 (beginning-of-line 1)
15049 (skip-chars-forward " \t")
15050 (when (equal prop org-effort-property)
15051 (save-excursion
15052 (org-back-to-heading t)
15053 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval)))
15054 (run-hook-with-args 'org-property-changed-functions key nval)))
15056 (defun org-find-olp (path &optional this-buffer)
15057 "Return a marker pointing to the entry at outline path OLP.
15058 If anything goes wrong, throw an error.
15059 You can wrap this call to catch the error like this:
15061 (condition-case msg
15062 (org-mobile-locate-entry (match-string 4))
15063 (error (nth 1 msg)))
15065 The return value will then be either a string with the error message,
15066 or a marker if everything is OK.
15068 If THIS-BUFFER is set, the outline path does not contain a file,
15069 only headings."
15070 (let* ((file (if this-buffer buffer-file-name (pop path)))
15071 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15072 (level 1)
15073 (lmin 1)
15074 (lmax 1)
15075 limit re end found pos heading cnt flevel)
15076 (unless buffer (error "File not found :%s" file))
15077 (with-current-buffer buffer
15078 (save-excursion
15079 (save-restriction
15080 (widen)
15081 (setq limit (point-max))
15082 (goto-char (point-min))
15083 (while (setq heading (pop path))
15084 (setq re (format org-complex-heading-regexp-format
15085 (regexp-quote heading)))
15086 (setq cnt 0 pos (point))
15087 (while (re-search-forward re end t)
15088 (setq level (- (match-end 1) (match-beginning 1)))
15089 (if (and (>= level lmin) (<= level lmax))
15090 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15091 (when (= cnt 0) (error "Heading not found on level %d: %s"
15092 lmax heading))
15093 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15094 lmax heading))
15095 (goto-char found)
15096 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15097 (setq end (save-excursion (org-end-of-subtree t t))))
15098 (when (org-at-heading-p)
15099 (point-marker)))))))
15101 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15102 "Find node HEADING in BUFFER.
15103 Return a marker to the heading if it was found, or nil if not.
15104 If POS-ONLY is set, return just the position instead of a marker.
15106 The heading text must match exact, but it may have a TODO keyword,
15107 a priority cookie and tags in the standard locations."
15108 (with-current-buffer (or buffer (current-buffer))
15109 (save-excursion
15110 (save-restriction
15111 (widen)
15112 (goto-char (point-min))
15113 (let (case-fold-search)
15114 (if (re-search-forward
15115 (format org-complex-heading-regexp-format
15116 (regexp-quote heading)) nil t)
15117 (if pos-only
15118 (match-beginning 0)
15119 (move-marker (make-marker) (match-beginning 0)))))))))
15121 (defun org-find-exact-heading-in-directory (heading &optional dir)
15122 "Find Org node headline HEADING in all .org files in directory DIR.
15123 When the target headline is found, return a marker to this location."
15124 (let ((files (directory-files (or dir default-directory)
15125 nil "\\`[^.#].*\\.org\\'"))
15126 file visiting m buffer)
15127 (catch 'found
15128 (while (setq file (pop files))
15129 (message "trying %s" file)
15130 (setq visiting (org-find-base-buffer-visiting file))
15131 (setq buffer (or visiting (find-file-noselect file)))
15132 (setq m (org-find-exact-headline-in-buffer
15133 heading buffer))
15134 (when (and (not m) (not visiting)) (kill-buffer buffer))
15135 (and m (throw 'found m))))))
15137 (defun org-find-entry-with-id (ident)
15138 "Locate the entry that contains the ID property with exact value IDENT.
15139 IDENT can be a string, a symbol or a number, this function will search for
15140 the string representation of it.
15141 Return the position where this entry starts, or nil if there is no such entry."
15142 (interactive "sID: ")
15143 (let ((id (cond
15144 ((stringp ident) ident)
15145 ((symbol-name ident) (symbol-name ident))
15146 ((numberp ident) (number-to-string ident))
15147 (t (error "IDENT %s must be a string, symbol or number" ident))))
15148 (case-fold-search nil))
15149 (save-excursion
15150 (save-restriction
15151 (widen)
15152 (goto-char (point-min))
15153 (when (re-search-forward
15154 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15155 nil t)
15156 (org-back-to-heading t)
15157 (point))))))
15159 ;;;; Timestamps
15161 (defvar org-last-changed-timestamp nil)
15162 (defvar org-last-inserted-timestamp nil
15163 "The last time stamp inserted with `org-insert-time-stamp'.")
15164 (defvar org-time-was-given) ; dynamically scoped parameter
15165 (defvar org-end-time-was-given) ; dynamically scoped parameter
15166 (defvar org-ts-what) ; dynamically scoped parameter
15168 (defun org-time-stamp (arg &optional inactive)
15169 "Prompt for a date/time and insert a time stamp.
15170 If the user specifies a time like HH:MM or if this command is
15171 called with at least one prefix argument, the time stamp contains
15172 the date and the time. Otherwise, only the date is be included.
15174 All parts of a date not specified by the user is filled in from
15175 the current date/time. So if you just press return without
15176 typing anything, the time stamp will represent the current
15177 date/time.
15179 If there is already a timestamp at the cursor, it will be
15180 modified.
15182 With two universal prefix arguments, insert an active timestamp
15183 with the current time without prompting the user."
15184 (interactive "P")
15185 (let* ((ts nil)
15186 (default-time
15187 ;; Default time is either today, or, when entering a range,
15188 ;; the range start.
15189 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15190 (save-excursion
15191 (re-search-backward
15192 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15193 (- (point) 20) t)))
15194 (apply 'encode-time (org-parse-time-string (match-string 1)))
15195 (current-time)))
15196 (default-input (and ts (org-get-compact-tod ts)))
15197 (repeater (save-excursion
15198 (save-match-data
15199 (beginning-of-line)
15200 (when (re-search-forward
15201 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15202 (save-excursion (progn (end-of-line) (point))) t)
15203 (match-string 0)))))
15204 org-time-was-given org-end-time-was-given time)
15205 (cond
15206 ((and (org-at-timestamp-p t)
15207 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15208 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15209 (insert "--")
15210 (setq time (let ((this-command this-command))
15211 (org-read-date arg 'totime nil nil
15212 default-time default-input inactive)))
15213 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15214 ((org-at-timestamp-p t)
15215 (setq time (let ((this-command this-command))
15216 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15217 (when (org-at-timestamp-p t) ; just to get the match data
15218 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15219 (replace-match "")
15220 (setq org-last-changed-timestamp
15221 (org-insert-time-stamp
15222 time (or org-time-was-given arg)
15223 inactive nil nil (list org-end-time-was-given)))
15224 (when repeater (goto-char (1- (point))) (insert " " repeater)
15225 (setq org-last-changed-timestamp
15226 (concat (substring org-last-inserted-timestamp 0 -1)
15227 " " repeater ">"))))
15228 (message "Timestamp updated"))
15229 ((equal arg '(16))
15230 (org-insert-time-stamp (current-time) t))
15232 (setq time (let ((this-command this-command))
15233 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15234 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15235 nil nil (list org-end-time-was-given))))))
15237 ;; FIXME: can we use this for something else, like computing time differences?
15238 (defun org-get-compact-tod (s)
15239 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15240 (let* ((t1 (match-string 1 s))
15241 (h1 (string-to-number (match-string 2 s)))
15242 (m1 (string-to-number (match-string 3 s)))
15243 (t2 (and (match-end 4) (match-string 5 s)))
15244 (h2 (and t2 (string-to-number (match-string 6 s))))
15245 (m2 (and t2 (string-to-number (match-string 7 s))))
15246 dh dm)
15247 (if (not t2)
15249 (setq dh (- h2 h1) dm (- m2 m1))
15250 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15251 (concat t1 "+" (number-to-string dh)
15252 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15254 (defun org-time-stamp-inactive (&optional arg)
15255 "Insert an inactive time stamp.
15256 An inactive time stamp is enclosed in square brackets instead of angle
15257 brackets. It is inactive in the sense that it does not trigger agenda entries,
15258 does not link to the calendar and cannot be changed with the S-cursor keys.
15259 So these are more for recording a certain time/date."
15260 (interactive "P")
15261 (org-time-stamp arg 'inactive))
15263 (defvar org-date-ovl (make-overlay 1 1))
15264 (overlay-put org-date-ovl 'face 'org-date-selected)
15265 (org-detach-overlay org-date-ovl)
15267 (defvar org-ans1) ; dynamically scoped parameter
15268 (defvar org-ans2) ; dynamically scoped parameter
15270 (defvar org-plain-time-of-day-regexp) ; defined below
15272 (defvar org-overriding-default-time nil) ; dynamically scoped
15273 (defvar org-read-date-overlay nil)
15274 (defvar org-dcst nil) ; dynamically scoped
15275 (defvar org-read-date-history nil)
15276 (defvar org-read-date-final-answer nil)
15277 (defvar org-read-date-analyze-futurep nil)
15278 (defvar org-read-date-analyze-forced-year nil)
15279 (defvar org-read-date-inactive)
15281 (defun org-read-date (&optional org-with-time to-time from-string prompt
15282 default-time default-input inactive)
15283 "Read a date, possibly a time, and make things smooth for the user.
15284 The prompt will suggest to enter an ISO date, but you can also enter anything
15285 which will at least partially be understood by `parse-time-string'.
15286 Unrecognized parts of the date will default to the current day, month, year,
15287 hour and minute. If this command is called to replace a timestamp at point,
15288 or to enter the second timestamp of a range, the default time is taken
15289 from the existing stamp. Furthermore, the command prefers the future,
15290 so if you are giving a date where the year is not given, and the day-month
15291 combination is already past in the current year, it will assume you
15292 mean next year. For details, see the manual. A few examples:
15294 3-2-5 --> 2003-02-05
15295 feb 15 --> currentyear-02-15
15296 2/15 --> currentyear-02-15
15297 sep 12 9 --> 2009-09-12
15298 12:45 --> today 12:45
15299 22 sept 0:34 --> currentyear-09-22 0:34
15300 12 --> currentyear-currentmonth-12
15301 Fri --> nearest Friday (today or later)
15302 etc.
15304 Furthermore you can specify a relative date by giving, as the *first* thing
15305 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15306 change in days weeks, months, years.
15307 With a single plus or minus, the date is relative to today. With a double
15308 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15309 +4d --> four days from today
15310 +4 --> same as above
15311 +2w --> two weeks from today
15312 ++5 --> five days from default date
15314 The function understands only English month and weekday abbreviations.
15316 While prompting, a calendar is popped up - you can also select the
15317 date with the mouse (button 1). The calendar shows a period of three
15318 months. To scroll it to other months, use the keys `>' and `<'.
15319 If you don't like the calendar, turn it off with
15320 \(setq org-read-date-popup-calendar nil)
15322 With optional argument TO-TIME, the date will immediately be converted
15323 to an internal time.
15324 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15325 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15326 still enter a time, and this function will inform the calling routine
15327 about this change. The calling routine may then choose to change the
15328 format used to insert the time stamp into the buffer to include the time.
15329 With optional argument FROM-STRING, read from this string instead from
15330 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15331 the time/date that is used for everything that is not specified by the
15332 user."
15333 (require 'parse-time)
15334 (let* ((org-time-stamp-rounding-minutes
15335 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15336 (org-dcst org-display-custom-times)
15337 (ct (org-current-time))
15338 (org-def (or org-overriding-default-time default-time ct))
15339 (org-defdecode (decode-time org-def))
15340 (dummy (progn
15341 (when (< (nth 2 org-defdecode) org-extend-today-until)
15342 (setcar (nthcdr 2 org-defdecode) -1)
15343 (setcar (nthcdr 1 org-defdecode) 59)
15344 (setq org-def (apply 'encode-time org-defdecode)
15345 org-defdecode (decode-time org-def)))))
15346 (mouse-autoselect-window nil) ; Don't let the mouse jump
15347 (calendar-frame-setup nil)
15348 (calendar-setup nil)
15349 (calendar-move-hook nil)
15350 (calendar-view-diary-initially-flag nil)
15351 (calendar-view-holidays-initially-flag nil)
15352 (timestr (format-time-string
15353 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15354 (prompt (concat (if prompt (concat prompt " ") "")
15355 (format "Date+time [%s]: " timestr)))
15356 ans (org-ans0 "") org-ans1 org-ans2 final)
15358 (cond
15359 (from-string (setq ans from-string))
15360 (org-read-date-popup-calendar
15361 (save-excursion
15362 (save-window-excursion
15363 (calendar)
15364 (org-eval-in-calendar '(setq cursor-type nil) t)
15365 (unwind-protect
15366 (progn
15367 (calendar-forward-day (- (time-to-days org-def)
15368 (calendar-absolute-from-gregorian
15369 (calendar-current-date))))
15370 (org-eval-in-calendar nil t)
15371 (let* ((old-map (current-local-map))
15372 (map (copy-keymap calendar-mode-map))
15373 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15374 (org-defkey map (kbd "RET") 'org-calendar-select)
15375 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15376 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15377 (org-defkey minibuffer-local-map [(meta shift left)]
15378 (lambda () (interactive)
15379 (org-eval-in-calendar '(calendar-backward-month 1))))
15380 (org-defkey minibuffer-local-map [(meta shift right)]
15381 (lambda () (interactive)
15382 (org-eval-in-calendar '(calendar-forward-month 1))))
15383 (org-defkey minibuffer-local-map [(meta shift up)]
15384 (lambda () (interactive)
15385 (org-eval-in-calendar '(calendar-backward-year 1))))
15386 (org-defkey minibuffer-local-map [(meta shift down)]
15387 (lambda () (interactive)
15388 (org-eval-in-calendar '(calendar-forward-year 1))))
15389 (org-defkey minibuffer-local-map [?\e (shift left)]
15390 (lambda () (interactive)
15391 (org-eval-in-calendar '(calendar-backward-month 1))))
15392 (org-defkey minibuffer-local-map [?\e (shift right)]
15393 (lambda () (interactive)
15394 (org-eval-in-calendar '(calendar-forward-month 1))))
15395 (org-defkey minibuffer-local-map [?\e (shift up)]
15396 (lambda () (interactive)
15397 (org-eval-in-calendar '(calendar-backward-year 1))))
15398 (org-defkey minibuffer-local-map [?\e (shift down)]
15399 (lambda () (interactive)
15400 (org-eval-in-calendar '(calendar-forward-year 1))))
15401 (org-defkey minibuffer-local-map [(shift up)]
15402 (lambda () (interactive)
15403 (org-eval-in-calendar '(calendar-backward-week 1))))
15404 (org-defkey minibuffer-local-map [(shift down)]
15405 (lambda () (interactive)
15406 (org-eval-in-calendar '(calendar-forward-week 1))))
15407 (org-defkey minibuffer-local-map [(shift left)]
15408 (lambda () (interactive)
15409 (org-eval-in-calendar '(calendar-backward-day 1))))
15410 (org-defkey minibuffer-local-map [(shift right)]
15411 (lambda () (interactive)
15412 (org-eval-in-calendar '(calendar-forward-day 1))))
15413 (org-defkey minibuffer-local-map ">"
15414 (lambda () (interactive)
15415 (org-eval-in-calendar '(scroll-calendar-left 1))))
15416 (org-defkey minibuffer-local-map "<"
15417 (lambda () (interactive)
15418 (org-eval-in-calendar '(scroll-calendar-right 1))))
15419 (org-defkey minibuffer-local-map "\C-v"
15420 (lambda () (interactive)
15421 (org-eval-in-calendar
15422 '(calendar-scroll-left-three-months 1))))
15423 (org-defkey minibuffer-local-map "\M-v"
15424 (lambda () (interactive)
15425 (org-eval-in-calendar
15426 '(calendar-scroll-right-three-months 1))))
15427 (run-hooks 'org-read-date-minibuffer-setup-hook)
15428 (unwind-protect
15429 (progn
15430 (use-local-map map)
15431 (setq org-read-date-inactive inactive)
15432 (add-hook 'post-command-hook 'org-read-date-display)
15433 (setq org-ans0 (read-string prompt default-input
15434 'org-read-date-history nil))
15435 ;; org-ans0: from prompt
15436 ;; org-ans1: from mouse click
15437 ;; org-ans2: from calendar motion
15438 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15439 (remove-hook 'post-command-hook 'org-read-date-display)
15440 (use-local-map old-map)
15441 (when org-read-date-overlay
15442 (delete-overlay org-read-date-overlay)
15443 (setq org-read-date-overlay nil)))))
15444 (bury-buffer "*Calendar*")))))
15446 (t ; Naked prompt only
15447 (unwind-protect
15448 (setq ans (read-string prompt default-input
15449 'org-read-date-history timestr))
15450 (when org-read-date-overlay
15451 (delete-overlay org-read-date-overlay)
15452 (setq org-read-date-overlay nil)))))
15454 (setq final (org-read-date-analyze ans org-def org-defdecode))
15456 (when org-read-date-analyze-forced-year
15457 (message "Year was forced into %s"
15458 (if org-read-date-force-compatible-dates
15459 "compatible range (1970-2037)"
15460 "range representable on this machine"))
15461 (ding))
15463 ;; One round trip to get rid of 34th of August and stuff like that....
15464 (setq final (decode-time (apply 'encode-time final)))
15466 (setq org-read-date-final-answer ans)
15468 (if to-time
15469 (apply 'encode-time final)
15470 (if (and (boundp 'org-time-was-given) org-time-was-given)
15471 (format "%04d-%02d-%02d %02d:%02d"
15472 (nth 5 final) (nth 4 final) (nth 3 final)
15473 (nth 2 final) (nth 1 final))
15474 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15476 (defvar org-def)
15477 (defvar org-defdecode)
15478 (defvar org-with-time)
15479 (defun org-read-date-display ()
15480 "Display the current date prompt interpretation in the minibuffer."
15481 (when org-read-date-display-live
15482 (when org-read-date-overlay
15483 (delete-overlay org-read-date-overlay))
15484 (when (minibufferp (current-buffer))
15485 (save-excursion
15486 (end-of-line 1)
15487 (while (not (equal (buffer-substring
15488 (max (point-min) (- (point) 4)) (point))
15489 " "))
15490 (insert " ")))
15491 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15492 " " (or org-ans1 org-ans2)))
15493 (org-end-time-was-given nil)
15494 (f (org-read-date-analyze ans org-def org-defdecode))
15495 (fmts (if org-dcst
15496 org-time-stamp-custom-formats
15497 org-time-stamp-formats))
15498 (fmt (if (or org-with-time
15499 (and (boundp 'org-time-was-given) org-time-was-given))
15500 (cdr fmts)
15501 (car fmts)))
15502 (txt (format-time-string fmt (apply 'encode-time f)))
15503 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15504 (txt (concat "=> " txt)))
15505 (when (and org-end-time-was-given
15506 (string-match org-plain-time-of-day-regexp txt))
15507 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15508 org-end-time-was-given
15509 (substring txt (match-end 0)))))
15510 (when org-read-date-analyze-futurep
15511 (setq txt (concat txt " (=>F)")))
15512 (setq org-read-date-overlay
15513 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15514 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15516 (defun org-read-date-analyze (ans org-def org-defdecode)
15517 "Analyze the combined answer of the date prompt."
15518 ;; FIXME: cleanup and comment
15519 (let ((nowdecode (decode-time (current-time)))
15520 delta deltan deltaw deltadef year month day
15521 hour minute second wday pm h2 m2 tl wday1
15522 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15523 (setq org-read-date-analyze-futurep nil
15524 org-read-date-analyze-forced-year nil)
15525 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15526 (setq ans "+0"))
15528 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15529 (setq ans (replace-match "" t t ans)
15530 deltan (car delta)
15531 deltaw (nth 1 delta)
15532 deltadef (nth 2 delta)))
15534 ;; Check if there is an iso week date in there. If yes, store the
15535 ;; info and postpone interpreting it until the rest of the parsing
15536 ;; is done.
15537 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15538 (setq iso-year (if (match-end 1)
15539 (org-small-year-to-year
15540 (string-to-number (match-string 1 ans))))
15541 iso-weekday (if (match-end 3)
15542 (string-to-number (match-string 3 ans)))
15543 iso-week (string-to-number (match-string 2 ans)))
15544 (setq ans (replace-match "" t t ans)))
15546 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15547 (when (string-match
15548 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15549 (setq year (if (match-end 2)
15550 (string-to-number (match-string 2 ans))
15551 (progn (setq kill-year t)
15552 (string-to-number (format-time-string "%Y"))))
15553 month (string-to-number (match-string 3 ans))
15554 day (string-to-number (match-string 4 ans)))
15555 (if (< year 100) (setq year (+ 2000 year)))
15556 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15557 t nil ans)))
15559 ;; Help matching dotted european dates
15560 (when (string-match
15561 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15562 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15563 (setq kill-year t)
15564 (string-to-number (format-time-string "%Y")))
15565 day (string-to-number (match-string 1 ans))
15566 month (string-to-number (match-string 2 ans))
15567 ans (replace-match (format "%04d-%02d-%02d" year month day)
15568 t nil ans)))
15570 ;; Help matching american dates, like 5/30 or 5/30/7
15571 (when (string-match
15572 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15573 (setq year (if (match-end 4)
15574 (string-to-number (match-string 4 ans))
15575 (progn (setq kill-year t)
15576 (string-to-number (format-time-string "%Y"))))
15577 month (string-to-number (match-string 1 ans))
15578 day (string-to-number (match-string 2 ans)))
15579 (if (< year 100) (setq year (+ 2000 year)))
15580 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15581 t nil ans)))
15582 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15583 ;; If there is a time with am/pm, and *no* time without it, we convert
15584 ;; so that matching will be successful.
15585 (loop for i from 1 to 2 do ; twice, for end time as well
15586 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15587 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15588 (setq hour (string-to-number (match-string 1 ans))
15589 minute (if (match-end 3)
15590 (string-to-number (match-string 3 ans))
15592 pm (equal ?p
15593 (string-to-char (downcase (match-string 4 ans)))))
15594 (if (and (= hour 12) (not pm))
15595 (setq hour 0)
15596 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15597 (setq ans (replace-match (format "%02d:%02d" hour minute)
15598 t t ans))))
15600 ;; Check if a time range is given as a duration
15601 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15602 (setq hour (string-to-number (match-string 1 ans))
15603 h2 (+ hour (string-to-number (match-string 3 ans)))
15604 minute (string-to-number (match-string 2 ans))
15605 m2 (+ minute (if (match-end 5) (string-to-number
15606 (match-string 5 ans))0)))
15607 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15608 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15609 t t ans)))
15611 ;; Check if there is a time range
15612 (when (boundp 'org-end-time-was-given)
15613 (setq org-time-was-given nil)
15614 (when (and (string-match org-plain-time-of-day-regexp ans)
15615 (match-end 8))
15616 (setq org-end-time-was-given (match-string 8 ans))
15617 (setq ans (concat (substring ans 0 (match-beginning 7))
15618 (substring ans (match-end 7))))))
15620 (setq tl (parse-time-string ans)
15621 day (or (nth 3 tl) (nth 3 org-defdecode))
15622 month (or (nth 4 tl)
15623 (if (and org-read-date-prefer-future
15624 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15625 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15626 (nth 4 org-defdecode)))
15627 year (or (and (not kill-year) (nth 5 tl))
15628 (if (and org-read-date-prefer-future
15629 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15630 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15631 (nth 5 org-defdecode)))
15632 hour (or (nth 2 tl) (nth 2 org-defdecode))
15633 minute (or (nth 1 tl) (nth 1 org-defdecode))
15634 second (or (nth 0 tl) 0)
15635 wday (nth 6 tl))
15637 (when (and (eq org-read-date-prefer-future 'time)
15638 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15639 (equal day (nth 3 nowdecode))
15640 (equal month (nth 4 nowdecode))
15641 (equal year (nth 5 nowdecode))
15642 (nth 2 tl)
15643 (or (< (nth 2 tl) (nth 2 nowdecode))
15644 (and (= (nth 2 tl) (nth 2 nowdecode))
15645 (nth 1 tl)
15646 (< (nth 1 tl) (nth 1 nowdecode)))))
15647 (setq day (1+ day)
15648 futurep t))
15650 ;; Special date definitions below
15651 (cond
15652 (iso-week
15653 ;; There was an iso week
15654 (require 'cal-iso)
15655 (setq futurep nil)
15656 (setq year (or iso-year year)
15657 day (or iso-weekday wday 1)
15658 wday nil ; to make sure that the trigger below does not match
15659 iso-date (calendar-gregorian-from-absolute
15660 (calendar-absolute-from-iso
15661 (list iso-week day year))))
15662 ; FIXME: Should we also push ISO weeks into the future?
15663 ; (when (and org-read-date-prefer-future
15664 ; (not iso-year)
15665 ; (< (calendar-absolute-from-gregorian iso-date)
15666 ; (time-to-days (current-time))))
15667 ; (setq year (1+ year)
15668 ; iso-date (calendar-gregorian-from-absolute
15669 ; (calendar-absolute-from-iso
15670 ; (list iso-week day year)))))
15671 (setq month (car iso-date)
15672 year (nth 2 iso-date)
15673 day (nth 1 iso-date)))
15674 (deltan
15675 (setq futurep nil)
15676 (unless deltadef
15677 (let ((now (decode-time (current-time))))
15678 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15679 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15680 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15681 ((equal deltaw "m") (setq month (+ month deltan)))
15682 ((equal deltaw "y") (setq year (+ year deltan)))))
15683 ((and wday (not (nth 3 tl)))
15684 ;; Weekday was given, but no day, so pick that day in the week
15685 ;; on or after the derived date.
15686 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15687 (unless (equal wday wday1)
15688 (setq day (+ day (% (- wday wday1 -7) 7))))))
15689 (if (and (boundp 'org-time-was-given)
15690 (nth 2 tl))
15691 (setq org-time-was-given t))
15692 (if (< year 100) (setq year (+ 2000 year)))
15693 ;; Check of the date is representable
15694 (if org-read-date-force-compatible-dates
15695 (progn
15696 (if (< year 1970)
15697 (setq year 1970 org-read-date-analyze-forced-year t))
15698 (if (> year 2037)
15699 (setq year 2037 org-read-date-analyze-forced-year t)))
15700 (condition-case nil
15701 (ignore (encode-time second minute hour day month year))
15702 (error
15703 (setq year (nth 5 org-defdecode))
15704 (setq org-read-date-analyze-forced-year t))))
15705 (setq org-read-date-analyze-futurep futurep)
15706 (list second minute hour day month year)))
15708 (defvar parse-time-weekdays)
15709 (defun org-read-date-get-relative (s today default)
15710 "Check string S for special relative date string.
15711 TODAY and DEFAULT are internal times, for today and for a default.
15712 Return shift list (N what def-flag)
15713 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15714 N is the number of WHATs to shift.
15715 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15716 the DEFAULT date rather than TODAY."
15717 (require 'parse-time)
15718 (when (and
15719 (string-match
15720 (concat
15721 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15722 "\\([0-9]+\\)?"
15723 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15724 "\\([ \t]\\|$\\)") s)
15725 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15726 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15727 (string-to-char (substring (match-string 1 s) -1))
15728 ?+))
15729 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15730 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15731 (what (if (match-end 3) (match-string 3 s) "d"))
15732 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15733 (date (if rel default today))
15734 (wday (nth 6 (decode-time date)))
15735 delta)
15736 (if wday1
15737 (progn
15738 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15739 (if (= dir ?-) (setq delta (- delta 7)))
15740 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15741 (list delta "d" rel))
15742 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15744 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15745 "Turn a user-specified date into the internal representation.
15746 The internal representation needed by the calendar is (month day year).
15747 This is a wrapper to handle the brain-dead convention in calendar that
15748 user function argument order change dependent on argument order."
15749 (if (boundp 'calendar-date-style)
15750 (cond
15751 ((eq calendar-date-style 'american)
15752 (list arg1 arg2 arg3))
15753 ((eq calendar-date-style 'european)
15754 (list arg2 arg1 arg3))
15755 ((eq calendar-date-style 'iso)
15756 (list arg2 arg3 arg1)))
15757 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15758 (if (org-bound-and-true-p european-calendar-style)
15759 (list arg2 arg1 arg3)
15760 (list arg1 arg2 arg3)))))
15762 (defun org-eval-in-calendar (form &optional keepdate)
15763 "Eval FORM in the calendar window and return to current window.
15764 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15765 otherwise stick to the current value of `org-ans2'."
15766 (let ((sf (selected-frame))
15767 (sw (selected-window)))
15768 (select-window (get-buffer-window "*Calendar*" t))
15769 (eval form)
15770 (when (and (not keepdate) (calendar-cursor-to-date))
15771 (let* ((date (calendar-cursor-to-date))
15772 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15773 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15774 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15775 (select-window sw)
15776 (org-select-frame-set-input-focus sf)))
15778 (defun org-calendar-select ()
15779 "Return to `org-read-date' with the date currently selected.
15780 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15781 (interactive)
15782 (when (calendar-cursor-to-date)
15783 (let* ((date (calendar-cursor-to-date))
15784 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15785 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15786 (if (active-minibuffer-window) (exit-minibuffer))))
15788 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15789 "Insert a date stamp for the date given by the internal TIME.
15790 WITH-HM means use the stamp format that includes the time of the day.
15791 INACTIVE means use square brackets instead of angular ones, so that the
15792 stamp will not contribute to the agenda.
15793 PRE and POST are optional strings to be inserted before and after the
15794 stamp.
15795 The command returns the inserted time stamp."
15796 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15797 stamp)
15798 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15799 (insert-before-markers (or pre ""))
15800 (when (listp extra)
15801 (setq extra (car extra))
15802 (if (and (stringp extra)
15803 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15804 (setq extra (format "-%02d:%02d"
15805 (string-to-number (match-string 1 extra))
15806 (string-to-number (match-string 2 extra))))
15807 (setq extra nil)))
15808 (when extra
15809 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15810 (insert-before-markers (setq stamp (format-time-string fmt time)))
15811 (insert-before-markers (or post ""))
15812 (setq org-last-inserted-timestamp stamp)))
15814 (defun org-toggle-time-stamp-overlays ()
15815 "Toggle the use of custom time stamp formats."
15816 (interactive)
15817 (setq org-display-custom-times (not org-display-custom-times))
15818 (unless org-display-custom-times
15819 (let ((p (point-min)) (bmp (buffer-modified-p)))
15820 (while (setq p (next-single-property-change p 'display))
15821 (if (and (get-text-property p 'display)
15822 (eq (get-text-property p 'face) 'org-date))
15823 (remove-text-properties
15824 p (setq p (next-single-property-change p 'display))
15825 '(display t))))
15826 (set-buffer-modified-p bmp)))
15827 (if (featurep 'xemacs)
15828 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15829 (org-restart-font-lock)
15830 (setq org-table-may-need-update t)
15831 (if org-display-custom-times
15832 (message "Time stamps are overlaid with custom format")
15833 (message "Time stamp overlays removed")))
15835 (defun org-display-custom-time (beg end)
15836 "Overlay modified time stamp format over timestamp between BEG and END."
15837 (let* ((ts (buffer-substring beg end))
15838 t1 w1 with-hm tf time str w2 (off 0))
15839 (save-match-data
15840 (setq t1 (org-parse-time-string ts t))
15841 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15842 (setq off (- (match-end 0) (match-beginning 0)))))
15843 (setq end (- end off))
15844 (setq w1 (- end beg)
15845 with-hm (and (nth 1 t1) (nth 2 t1))
15846 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15847 time (org-fix-decoded-time t1)
15848 str (org-add-props
15849 (format-time-string
15850 (substring tf 1 -1) (apply 'encode-time time))
15851 nil 'mouse-face 'highlight)
15852 w2 (length str))
15853 (if (not (= w2 w1))
15854 (add-text-properties (1+ beg) (+ 2 beg)
15855 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15856 (if (featurep 'xemacs)
15857 (progn
15858 (put-text-property beg end 'invisible t)
15859 (put-text-property beg end 'end-glyph (make-glyph str)))
15860 (put-text-property beg end 'display str))))
15862 (defun org-translate-time (string)
15863 "Translate all timestamps in STRING to custom format.
15864 But do this only if the variable `org-display-custom-times' is set."
15865 (when org-display-custom-times
15866 (save-match-data
15867 (let* ((start 0)
15868 (re org-ts-regexp-both)
15869 t1 with-hm inactive tf time str beg end)
15870 (while (setq start (string-match re string start))
15871 (setq beg (match-beginning 0)
15872 end (match-end 0)
15873 t1 (save-match-data
15874 (org-parse-time-string (substring string beg end) t))
15875 with-hm (and (nth 1 t1) (nth 2 t1))
15876 inactive (equal (substring string beg (1+ beg)) "[")
15877 tf (funcall (if with-hm 'cdr 'car)
15878 org-time-stamp-custom-formats)
15879 time (org-fix-decoded-time t1)
15880 str (format-time-string
15881 (concat
15882 (if inactive "[" "<") (substring tf 1 -1)
15883 (if inactive "]" ">"))
15884 (apply 'encode-time time))
15885 string (replace-match str t t string)
15886 start (+ start (length str)))))))
15887 string)
15889 (defun org-fix-decoded-time (time)
15890 "Set 0 instead of nil for the first 6 elements of time.
15891 Don't touch the rest."
15892 (let ((n 0))
15893 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15895 (defun org-days-to-time (timestamp-string)
15896 "Difference between TIMESTAMP-STRING and now in days."
15897 (- (time-to-days (org-time-string-to-time timestamp-string))
15898 (time-to-days (current-time))))
15900 (defun org-deadline-close (timestamp-string &optional ndays)
15901 "Is the time in TIMESTAMP-STRING close to the current date?"
15902 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15903 (and (< (org-days-to-time timestamp-string) ndays)
15904 (not (org-entry-is-done-p))))
15906 (defun org-get-wdays (ts)
15907 "Get the deadline lead time appropriate for timestring TS."
15908 (cond
15909 ((<= org-deadline-warning-days 0)
15910 ;; 0 or negative, enforce this value no matter what
15911 (- org-deadline-warning-days))
15912 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15913 ;; lead time is specified.
15914 (floor (* (string-to-number (match-string 1 ts))
15915 (cdr (assoc (match-string 2 ts)
15916 '(("d" . 1) ("w" . 7)
15917 ("m" . 30.4) ("y" . 365.25)))))))
15918 ;; go for the default.
15919 (t org-deadline-warning-days)))
15921 (defun org-calendar-select-mouse (ev)
15922 "Return to `org-read-date' with the date currently selected.
15923 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15924 (interactive "e")
15925 (mouse-set-point ev)
15926 (when (calendar-cursor-to-date)
15927 (let* ((date (calendar-cursor-to-date))
15928 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15929 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15930 (if (active-minibuffer-window) (exit-minibuffer))))
15932 (defun org-check-deadlines (ndays)
15933 "Check if there are any deadlines due or past due.
15934 A deadline is considered due if it happens within `org-deadline-warning-days'
15935 days from today's date. If the deadline appears in an entry marked DONE,
15936 it is not shown. The prefix arg NDAYS can be used to test that many
15937 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15938 (interactive "P")
15939 (let* ((org-warn-days
15940 (cond
15941 ((equal ndays '(4)) 100000)
15942 (ndays (prefix-numeric-value ndays))
15943 (t (abs org-deadline-warning-days))))
15944 (case-fold-search nil)
15945 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15946 (callback
15947 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15949 (message "%d deadlines past-due or due within %d days"
15950 (org-occur regexp nil callback)
15951 org-warn-days)))
15953 (defsubst org-re-timestamp (type)
15954 "Return a regexp for timestamp TYPE.
15955 Allowed values for TYPE are:
15957 all: all timestamps
15958 active: only active timestamps (<...>)
15959 inactive: only inactive timestamps ([...])
15960 scheduled: only scheduled timestamps
15961 deadline: only deadline timestamps
15963 When TYPE is nil, fall back on returning a regexp that matches
15964 both scheduled and deadline timestamps."
15965 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
15966 ((eq type 'active) org-ts-regexp)
15967 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
15968 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
15969 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15970 ((eq type 'scheduled-or-deadline)
15971 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
15973 (defun org-check-before-date (date)
15974 "Check if there are deadlines or scheduled entries before DATE."
15975 (interactive (list (org-read-date)))
15976 (let ((case-fold-search nil)
15977 (regexp (org-re-timestamp org-ts-type))
15978 (callback
15979 (lambda () (time-less-p
15980 (org-time-string-to-time (match-string 1))
15981 (org-time-string-to-time date)))))
15982 (message "%d entries before %s"
15983 (org-occur regexp nil callback) date)))
15985 (defun org-check-after-date (date)
15986 "Check if there are deadlines or scheduled entries after DATE."
15987 (interactive (list (org-read-date)))
15988 (let ((case-fold-search nil)
15989 (regexp (org-re-timestamp org-ts-type))
15990 (callback
15991 (lambda () (not
15992 (time-less-p
15993 (org-time-string-to-time (match-string 1))
15994 (org-time-string-to-time date))))))
15995 (message "%d entries after %s"
15996 (org-occur regexp nil callback) date)))
15998 (defun org-check-dates-range (start-date end-date)
15999 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16000 (interactive (list (org-read-date nil nil nil "Range starts")
16001 (org-read-date nil nil nil "Range end")))
16002 (let ((case-fold-search nil)
16003 (regexp (org-re-timestamp org-ts-type))
16004 (callback
16005 (lambda ()
16006 (let ((match (match-string 1)))
16007 (and
16008 (not (time-less-p
16009 (org-time-string-to-time match)
16010 (org-time-string-to-time start-date)))
16011 (time-less-p
16012 (org-time-string-to-time match)
16013 (org-time-string-to-time end-date)))))))
16014 (message "%d entries between %s and %s"
16015 (org-occur regexp nil callback) start-date end-date)))
16017 (defun org-evaluate-time-range (&optional to-buffer)
16018 "Evaluate a time range by computing the difference between start and end.
16019 Normally the result is just printed in the echo area, but with prefix arg
16020 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16021 If the time range is actually in a table, the result is inserted into the
16022 next column.
16023 For time difference computation, a year is assumed to be exactly 365
16024 days in order to avoid rounding problems."
16025 (interactive "P")
16027 (org-clock-update-time-maybe)
16028 (save-excursion
16029 (unless (org-at-date-range-p t)
16030 (goto-char (point-at-bol))
16031 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16032 (if (not (org-at-date-range-p t))
16033 (error "Not at a time-stamp range, and none found in current line")))
16034 (let* ((ts1 (match-string 1))
16035 (ts2 (match-string 2))
16036 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16037 (match-end (match-end 0))
16038 (time1 (org-time-string-to-time ts1))
16039 (time2 (org-time-string-to-time ts2))
16040 (t1 (org-float-time time1))
16041 (t2 (org-float-time time2))
16042 (diff (abs (- t2 t1)))
16043 (negative (< (- t2 t1) 0))
16044 ;; (ys (floor (* 365 24 60 60)))
16045 (ds (* 24 60 60))
16046 (hs (* 60 60))
16047 (fy "%dy %dd %02d:%02d")
16048 (fy1 "%dy %dd")
16049 (fd "%dd %02d:%02d")
16050 (fd1 "%dd")
16051 (fh "%02d:%02d")
16052 y d h m align)
16053 (if havetime
16054 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16056 d (floor (/ diff ds)) diff (mod diff ds)
16057 h (floor (/ diff hs)) diff (mod diff hs)
16058 m (floor (/ diff 60)))
16059 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16061 d (floor (+ (/ diff ds) 0.5))
16062 h 0 m 0))
16063 (if (not to-buffer)
16064 (message "%s" (org-make-tdiff-string y d h m))
16065 (if (org-at-table-p)
16066 (progn
16067 (goto-char match-end)
16068 (setq align t)
16069 (and (looking-at " *|") (goto-char (match-end 0))))
16070 (goto-char match-end))
16071 (if (looking-at
16072 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16073 (replace-match ""))
16074 (if negative (insert " -"))
16075 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16076 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16077 (insert " " (format fh h m))))
16078 (if align (org-table-align))
16079 (message "Time difference inserted")))))
16081 (defun org-make-tdiff-string (y d h m)
16082 (let ((fmt "")
16083 (l nil))
16084 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16085 l (push y l)))
16086 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16087 l (push d l)))
16088 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16089 l (push h l)))
16090 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16091 l (push m l)))
16092 (apply 'format fmt (nreverse l))))
16094 (defun org-time-string-to-time (s &optional buffer pos)
16095 "Convert a timestamp string into internal time."
16096 (condition-case errdata
16097 (apply 'encode-time (org-parse-time-string s))
16098 (error (error "Bad timestamp `%s'%s\nError was: %s"
16099 s (if (not (and buffer pos))
16101 (format " at %d in buffer `%s'" pos buffer))
16102 (cdr errdata)))))
16104 (defun org-time-string-to-seconds (s)
16105 "Convert a timestamp string to a number of seconds."
16106 (org-float-time (org-time-string-to-time s)))
16108 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16109 "Convert a time stamp to an absolute day number.
16110 If there is a specifier for a cyclic time stamp, get the closest date to
16111 DAYNR.
16112 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16113 The variable date is bound by the calendar when this is called."
16114 (cond
16115 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16116 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16117 daynr
16118 (+ daynr 1000)))
16119 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16120 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16121 (time-to-days (current-time))) (match-string 0 s)
16122 prefer show-all))
16123 (t (time-to-days
16124 (condition-case errdata
16125 (apply 'encode-time (org-parse-time-string s))
16126 (error (error "Bad timestamp `%s'%s\nError was: %s"
16127 s (if (not (and buffer pos))
16129 (format " at %d in buffer `%s'" pos buffer))
16130 (cdr errdata))))))))
16132 (defun org-days-to-iso-week (days)
16133 "Return the iso week number."
16134 (require 'cal-iso)
16135 (car (calendar-iso-from-absolute days)))
16137 (defun org-small-year-to-year (year)
16138 "Convert 2-digit years into 4-digit years.
16139 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16140 The year 2000 cannot be abbreviated. Any year larger than 99
16141 is returned unchanged."
16142 (if (< year 38)
16143 (setq year (+ 2000 year))
16144 (if (< year 100)
16145 (setq year (+ 1900 year))))
16146 year)
16148 (defun org-time-from-absolute (d)
16149 "Return the time corresponding to date D.
16150 D may be an absolute day number, or a calendar-type list (month day year)."
16151 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16152 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16154 (defun org-calendar-holiday ()
16155 "List of holidays, for Diary display in Org-mode."
16156 (require 'holidays)
16157 (let ((hl (funcall
16158 (if (fboundp 'calendar-check-holidays)
16159 'calendar-check-holidays 'check-calendar-holidays) date)))
16160 (if hl (mapconcat 'identity hl "; "))))
16162 (defun org-diary-sexp-entry (sexp entry date)
16163 "Process a SEXP diary ENTRY for DATE."
16164 (require 'diary-lib)
16165 (let ((result (if calendar-debug-sexp
16166 (let ((stack-trace-on-error t))
16167 (eval (car (read-from-string sexp))))
16168 (condition-case nil
16169 (eval (car (read-from-string sexp)))
16170 (error
16171 (beep)
16172 (message "Bad sexp at line %d in %s: %s"
16173 (org-current-line)
16174 (buffer-file-name) sexp)
16175 (sleep-for 2))))))
16176 (cond ((stringp result) (split-string result "; "))
16177 ((and (consp result)
16178 (not (consp (cdr result)))
16179 (stringp (cdr result))) (cdr result))
16180 ((and (consp result)
16181 (stringp (car result))) result)
16182 (result entry))))
16184 (defun org-diary-to-ical-string (frombuf)
16185 "Get iCalendar entries from diary entries in buffer FROMBUF.
16186 This uses the icalendar.el library."
16187 (let* ((tmpdir (if (featurep 'xemacs)
16188 (temp-directory)
16189 temporary-file-directory))
16190 (tmpfile (make-temp-name
16191 (expand-file-name "orgics" tmpdir)))
16192 buf rtn b e)
16193 (with-current-buffer frombuf
16194 (icalendar-export-region (point-min) (point-max) tmpfile)
16195 (setq buf (find-buffer-visiting tmpfile))
16196 (set-buffer buf)
16197 (goto-char (point-min))
16198 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16199 (setq b (match-beginning 0)))
16200 (goto-char (point-max))
16201 (if (re-search-backward "^END:VEVENT" nil t)
16202 (setq e (match-end 0)))
16203 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16204 (kill-buffer buf)
16205 (delete-file tmpfile)
16206 rtn))
16208 (defun org-closest-date (start current change prefer show-all)
16209 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16210 When PREFER is `past', return a date that is either CURRENT or past.
16211 When PREFER is `future', return a date that is either CURRENT or future.
16212 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16213 ;; Make the proper lists from the dates
16214 (catch 'exit
16215 (let ((a1 '(("h" . hour)
16216 ("d" . day)
16217 ("w" . week)
16218 ("m" . month)
16219 ("y" . year)))
16220 (shour (nth 2 (org-parse-time-string start)))
16221 dn dw sday cday n1 n2 n0
16222 d m y y1 y2 date1 date2 nmonths nm ny m2)
16224 (setq start (org-date-to-gregorian start)
16225 current (org-date-to-gregorian
16226 (if show-all
16227 current
16228 (time-to-days (current-time))))
16229 sday (calendar-absolute-from-gregorian start)
16230 cday (calendar-absolute-from-gregorian current))
16232 (if (<= cday sday) (throw 'exit sday))
16234 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16235 (setq dn (string-to-number (match-string 1 change))
16236 dw (cdr (assoc (match-string 2 change) a1)))
16237 (error "Invalid change specifier: %s" change))
16238 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16239 (cond
16240 ((eq dw 'hour)
16241 (let ((missing-hours
16242 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16243 dn)))
16244 (setq n1 (if (zerop missing-hours) cday
16245 (- cday (1+ (floor (/ missing-hours 24)))))
16246 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16247 ((eq dw 'day)
16248 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16249 n2 (+ n1 dn)))
16250 ((eq dw 'year)
16251 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16252 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16253 (setq date1 (list m d y1)
16254 n1 (calendar-absolute-from-gregorian date1)
16255 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16256 n2 (calendar-absolute-from-gregorian date2)))
16257 ((eq dw 'month)
16258 ;; approx number of month between the two dates
16259 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16260 ;; How often does dn fit in there?
16261 (setq d (nth 1 start) m (car start) y (nth 2 start)
16262 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16263 m (+ m nm)
16264 ny (floor (/ m 12))
16265 y (+ y ny)
16266 m (- m (* ny 12)))
16267 (while (> m 12) (setq m (- m 12) y (1+ y)))
16268 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16269 (setq m2 (+ m dn) y2 y)
16270 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16271 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16272 (while (<= n2 cday)
16273 (setq n1 n2 m m2 y y2)
16274 (setq m2 (+ m dn) y2 y)
16275 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16276 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16277 ;; Make sure n1 is the earlier date
16278 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16279 (if show-all
16280 (cond
16281 ((eq prefer 'past) (if (= cday n2) n2 n1))
16282 ((eq prefer 'future) (if (= cday n1) n1 n2))
16283 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16284 (cond
16285 ((eq prefer 'past) (if (= cday n2) n2 n1))
16286 ((eq prefer 'future) (if (= cday n1) n1 n2))
16287 (t (if (= cday n1) n1 n2)))))))
16289 (defun org-date-to-gregorian (date)
16290 "Turn any specification of DATE into a Gregorian date for the calendar."
16291 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16292 ((and (listp date) (= (length date) 3)) date)
16293 ((stringp date)
16294 (setq date (org-parse-time-string date))
16295 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16296 ((listp date)
16297 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16299 (defun org-parse-time-string (s &optional nodefault)
16300 "Parse the standard Org-mode time string.
16301 This should be a lot faster than the normal `parse-time-string'.
16302 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16303 hour and minute fields will be nil if not given."
16304 (if (string-match org-ts-regexp0 s)
16305 (list 0
16306 (if (or (match-beginning 8) (not nodefault))
16307 (string-to-number (or (match-string 8 s) "0")))
16308 (if (or (match-beginning 7) (not nodefault))
16309 (string-to-number (or (match-string 7 s) "0")))
16310 (string-to-number (match-string 4 s))
16311 (string-to-number (match-string 3 s))
16312 (string-to-number (match-string 2 s))
16313 nil nil nil)
16314 (error "Not a standard Org-mode time string: %s" s)))
16316 (defun org-timestamp-up (&optional arg)
16317 "Increase the date item at the cursor by one.
16318 If the cursor is on the year, change the year. If it is on the month,
16319 the day or the time, change that.
16320 With prefix ARG, change by that many units."
16321 (interactive "p")
16322 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16324 (defun org-timestamp-down (&optional arg)
16325 "Decrease the date item at the cursor by one.
16326 If the cursor is on the year, change the year. If it is on the month,
16327 the day or the time, change that.
16328 With prefix ARG, change by that many units."
16329 (interactive "p")
16330 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16332 (defun org-timestamp-up-day (&optional arg)
16333 "Increase the date in the time stamp by one day.
16334 With prefix ARG, change that many days."
16335 (interactive "p")
16336 (if (and (not (org-at-timestamp-p t))
16337 (org-at-heading-p))
16338 (org-todo 'up)
16339 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16341 (defun org-timestamp-down-day (&optional arg)
16342 "Decrease the date in the time stamp by one day.
16343 With prefix ARG, change that many days."
16344 (interactive "p")
16345 (if (and (not (org-at-timestamp-p t))
16346 (org-at-heading-p))
16347 (org-todo 'down)
16348 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16350 (defun org-at-timestamp-p (&optional inactive-ok)
16351 "Determine if the cursor is in or at a timestamp."
16352 (interactive)
16353 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16354 (pos (point))
16355 (ans (or (looking-at tsr)
16356 (save-excursion
16357 (skip-chars-backward "^[<\n\r\t")
16358 (if (> (point) (point-min)) (backward-char 1))
16359 (and (looking-at tsr)
16360 (> (- (match-end 0) pos) -1))))))
16361 (and ans
16362 (boundp 'org-ts-what)
16363 (setq org-ts-what
16364 (cond
16365 ((= pos (match-beginning 0)) 'bracket)
16366 ;; Point is considered to be "on the bracket" whether
16367 ;; it's really on it or right after it.
16368 ((= pos (1- (match-end 0))) 'bracket)
16369 ((= pos (match-end 0)) 'after)
16370 ((org-pos-in-match-range pos 2) 'year)
16371 ((org-pos-in-match-range pos 3) 'month)
16372 ((org-pos-in-match-range pos 7) 'hour)
16373 ((org-pos-in-match-range pos 8) 'minute)
16374 ((or (org-pos-in-match-range pos 4)
16375 (org-pos-in-match-range pos 5)) 'day)
16376 ((and (> pos (or (match-end 8) (match-end 5)))
16377 (< pos (match-end 0)))
16378 (- pos (or (match-end 8) (match-end 5))))
16379 (t 'day))))
16380 ans))
16382 (defun org-toggle-timestamp-type ()
16383 "Toggle the type (<active> or [inactive]) of a time stamp."
16384 (interactive)
16385 (when (org-at-timestamp-p t)
16386 (let ((beg (match-beginning 0)) (end (match-end 0))
16387 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16388 (save-excursion
16389 (goto-char beg)
16390 (while (re-search-forward "[][<>]" end t)
16391 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16392 t t)))
16393 (message "Timestamp is now %sactive"
16394 (if (equal (char-after beg) ?<) "" "in")))))
16396 (defvar org-clock-history) ; defined in org-clock.el
16397 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16398 (defun org-timestamp-change (n &optional what updown)
16399 "Change the date in the time stamp at point.
16400 The date will be changed by N times WHAT. WHAT can be `day', `month',
16401 `year', `minute', `second'. If WHAT is not given, the cursor position
16402 in the timestamp determines what will be changed."
16403 (let ((origin (point)) origin-cat
16404 with-hm inactive
16405 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16406 org-ts-what
16407 extra rem
16408 ts time time0 fixnext clrgx)
16409 (if (not (org-at-timestamp-p t))
16410 (error "Not at a timestamp"))
16411 (if (and (not what) (eq org-ts-what 'bracket))
16412 (org-toggle-timestamp-type)
16413 ;; Point isn't on brackets. Remember the part of the time-stamp
16414 ;; the point was in. Indeed, size of time-stamps may change,
16415 ;; but point must be kept in the same category nonetheless.
16416 (setq origin-cat org-ts-what)
16417 (if (and (not what) (not (eq org-ts-what 'day))
16418 org-display-custom-times
16419 (get-text-property (point) 'display)
16420 (not (get-text-property (1- (point)) 'display)))
16421 (setq org-ts-what 'day))
16422 (setq org-ts-what (or what org-ts-what)
16423 inactive (= (char-after (match-beginning 0)) ?\[)
16424 ts (match-string 0))
16425 (replace-match "")
16426 (if (string-match
16427 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16429 (setq extra (match-string 1 ts)))
16430 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16431 (setq with-hm t))
16432 (setq time0 (org-parse-time-string ts))
16433 (when (and updown
16434 (eq org-ts-what 'minute)
16435 (not current-prefix-arg))
16436 ;; This looks like s-up and s-down. Change by one rounding step.
16437 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16438 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16439 (setcar (cdr time0) (+ (nth 1 time0)
16440 (if (> n 0) (- rem) (- dm rem))))))
16441 (setq time
16442 (encode-time (or (car time0) 0)
16443 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16444 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16445 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16446 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16447 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16448 (nthcdr 6 time0)))
16449 (when (and (member org-ts-what '(hour minute))
16450 extra
16451 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16452 (setq extra (org-modify-ts-extra
16453 extra
16454 (if (eq org-ts-what 'hour) 2 5)
16455 n dm)))
16456 (when (integerp org-ts-what)
16457 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16458 (if (eq what 'calendar)
16459 (let ((cal-date (org-get-date-from-calendar)))
16460 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16461 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16462 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16463 (setcar time0 (or (car time0) 0))
16464 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16465 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16466 (setq time (apply 'encode-time time0))))
16467 ;; Insert the new time-stamp, and ensure point stays in the same
16468 ;; category as before (i.e. not after the last position in that
16469 ;; category).
16470 (let ((pos (point)))
16471 ;; Stay before inserted string. `save-excursion' is of no use.
16472 (setq org-last-changed-timestamp
16473 (org-insert-time-stamp time with-hm inactive nil nil extra))
16474 (goto-char pos))
16475 (save-match-data
16476 (looking-at org-ts-regexp3)
16477 (goto-char (cond
16478 ;; `day' category ends before `hour' if any, or at
16479 ;; the end of the day name.
16480 ((eq origin-cat 'day)
16481 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16482 ((eq origin-cat 'hour) (min (match-end 7) origin))
16483 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16484 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16485 ;; `year' and `month' have both fixed size: point
16486 ;; couldn't have moved into another part.
16487 (t origin))))
16488 ;; Update clock if on a CLOCK line.
16489 (org-clock-update-time-maybe)
16490 ;; Maybe adjust the closest clock in `org-clock-history'
16491 (when org-clock-adjust-closest
16492 (if (not (and (org-at-clock-log-p)
16493 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16494 org-clock-history))))))
16495 (message "No clock to adjust")
16496 (cond ((save-excursion ; fix previous clock?
16497 (re-search-backward org-ts-regexp0 nil t)
16498 (org-looking-back (concat org-clock-string " \\[")))
16499 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16500 ((save-excursion ; fix next clock?
16501 (re-search-backward org-ts-regexp0 nil t)
16502 (looking-at (concat org-ts-regexp0 "\\] =>")))
16503 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16504 (save-window-excursion
16505 ;; Find closest clock to point, adjust the previous/next one in history
16506 (let* ((p (save-excursion (org-back-to-heading t)))
16507 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16508 (clfixnth
16509 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16510 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16511 (if (not clfixpos)
16512 (message "No clock to adjust")
16513 (save-excursion
16514 (org-goto-marker-or-bmk clfixpos)
16515 (org-show-subtree)
16516 (when (re-search-forward clrgx nil t)
16517 (goto-char (match-beginning 1))
16518 (let (org-clock-adjust-closest)
16519 (org-timestamp-change n org-ts-what updown))
16520 (message "Clock adjusted in %s for heading: %s"
16521 (file-name-nondirectory (buffer-file-name))
16522 (org-get-heading t t)))))))))
16523 ;; Try to recenter the calendar window, if any.
16524 (if (and org-calendar-follow-timestamp-change
16525 (get-buffer-window "*Calendar*" t)
16526 (memq org-ts-what '(day month year)))
16527 (org-recenter-calendar (time-to-days time))))))
16529 (defun org-modify-ts-extra (s pos n dm)
16530 "Change the different parts of the lead-time and repeat fields in timestamp."
16531 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16532 ng h m new rem)
16533 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16534 (cond
16535 ((or (org-pos-in-match-range pos 2)
16536 (org-pos-in-match-range pos 3))
16537 (setq m (string-to-number (match-string 3 s))
16538 h (string-to-number (match-string 2 s)))
16539 (if (org-pos-in-match-range pos 2)
16540 (setq h (+ h n))
16541 (setq n (* dm (org-no-warnings (signum n))))
16542 (when (not (= 0 (setq rem (% m dm))))
16543 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16544 (setq m (+ m n)))
16545 (if (< m 0) (setq m (+ m 60) h (1- h)))
16546 (if (> m 59) (setq m (- m 60) h (1+ h)))
16547 (setq h (min 24 (max 0 h)))
16548 (setq ng 1 new (format "-%02d:%02d" h m)))
16549 ((org-pos-in-match-range pos 6)
16550 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16551 ((org-pos-in-match-range pos 5)
16552 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16554 ((org-pos-in-match-range pos 9)
16555 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16556 ((org-pos-in-match-range pos 8)
16557 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16559 (when ng
16560 (setq s (concat
16561 (substring s 0 (match-beginning ng))
16563 (substring s (match-end ng))))))
16566 (defun org-recenter-calendar (date)
16567 "If the calendar is visible, recenter it to DATE."
16568 (let ((cwin (get-buffer-window "*Calendar*" t)))
16569 (when cwin
16570 (let ((calendar-move-hook nil))
16571 (with-selected-window cwin
16572 (calendar-goto-date (if (listp date) date
16573 (calendar-gregorian-from-absolute date))))))))
16575 (defun org-goto-calendar (&optional arg)
16576 "Go to the Emacs calendar at the current date.
16577 If there is a time stamp in the current line, go to that date.
16578 A prefix ARG can be used to force the current date."
16579 (interactive "P")
16580 (let ((tsr org-ts-regexp) diff
16581 (calendar-move-hook nil)
16582 (calendar-view-holidays-initially-flag nil)
16583 (calendar-view-diary-initially-flag nil))
16584 (if (or (org-at-timestamp-p)
16585 (save-excursion
16586 (beginning-of-line 1)
16587 (looking-at (concat ".*" tsr))))
16588 (let ((d1 (time-to-days (current-time)))
16589 (d2 (time-to-days
16590 (org-time-string-to-time (match-string 1)))))
16591 (setq diff (- d2 d1))))
16592 (calendar)
16593 (calendar-goto-today)
16594 (if (and diff (not arg)) (calendar-forward-day diff))))
16596 (defun org-get-date-from-calendar ()
16597 "Return a list (month day year) of date at point in calendar."
16598 (with-current-buffer "*Calendar*"
16599 (save-match-data
16600 (calendar-cursor-to-date))))
16602 (defun org-date-from-calendar ()
16603 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16604 If there is already a time stamp at the cursor position, update it."
16605 (interactive)
16606 (if (org-at-timestamp-p t)
16607 (org-timestamp-change 0 'calendar)
16608 (let ((cal-date (org-get-date-from-calendar)))
16609 (org-insert-time-stamp
16610 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16612 (defun org-minutes-to-hh:mm-string (m)
16613 "Compute H:MM from a number of minutes."
16614 (let ((h (/ m 60)))
16615 (setq m (- m (* 60 h)))
16616 (format org-time-clocksum-format h m)))
16618 (defun org-hh:mm-string-to-minutes (s)
16619 "Convert a string H:MM to a number of minutes.
16620 If the string is just a number, interpret it as minutes.
16621 In fact, the first hh:mm or number in the string will be taken,
16622 there can be extra stuff in the string.
16623 If no number is found, the return value is 0."
16624 (cond
16625 ((integerp s) s)
16626 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16627 (+ (* (string-to-number (match-string 1 s)) 60)
16628 (string-to-number (match-string 2 s))))
16629 ((string-match "\\([0-9]+\\)" s)
16630 (string-to-number (match-string 1 s)))
16631 (t 0)))
16633 (defcustom org-effort-durations
16634 `(("h" . 60)
16635 ("d" . ,(* 60 8))
16636 ("w" . ,(* 60 8 5))
16637 ("m" . ,(* 60 8 5 4))
16638 ("y" . ,(* 60 8 5 40)))
16639 "Conversion factor to minutes for an effort modifier.
16641 Each entry has the form (MODIFIER . MINUTES).
16643 In an effort string, a number followed by MODIFIER is multiplied
16644 by the specified number of MINUTES to obtain an effort in
16645 minutes.
16647 For example, if the value of this variable is ((\"hours\" . 60)), then an
16648 effort string \"2hours\" is equivalent to 120 minutes."
16649 :group 'org-agenda
16650 :version "24.1"
16651 :type '(alist :key-type (string :tag "Modifier")
16652 :value-type (number :tag "Minutes")))
16654 (defun org-duration-string-to-minutes (s &optional output-to-string)
16655 "Convert a duration string S to minutes.
16657 A bare number is interpreted as minutes, modifiers can be set by
16658 customizing `org-effort-durations' (which see).
16660 Entries containing a colon are interpreted as H:MM by
16661 `org-hh:mm-string-to-minutes'."
16662 (let ((result 0)
16663 (re (concat "\\([0-9.]+\\) *\\("
16664 (regexp-opt (mapcar 'car org-effort-durations))
16665 "\\)")))
16666 (while (string-match re s)
16667 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16668 (string-to-number (match-string 1 s))))
16669 (setq s (replace-match "" nil t s)))
16670 (setq result (floor result))
16671 (incf result (org-hh:mm-string-to-minutes s))
16672 (if output-to-string (number-to-string result) result)))
16674 ;;;; Files
16676 (defun org-save-all-org-buffers ()
16677 "Save all Org-mode buffers without user confirmation."
16678 (interactive)
16679 (message "Saving all Org-mode buffers...")
16680 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16681 (when (featurep 'org-id) (org-id-locations-save))
16682 (message "Saving all Org-mode buffers... done"))
16684 (defun org-revert-all-org-buffers ()
16685 "Revert all Org-mode buffers.
16686 Prompt for confirmation when there are unsaved changes.
16687 Be sure you know what you are doing before letting this function
16688 overwrite your changes.
16690 This function is useful in a setup where one tracks org files
16691 with a version control system, to revert on one machine after pulling
16692 changes from another. I believe the procedure must be like this:
16694 1. M-x org-save-all-org-buffers
16695 2. Pull changes from the other machine, resolve conflicts
16696 3. M-x org-revert-all-org-buffers"
16697 (interactive)
16698 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16699 (error "Abort"))
16700 (save-excursion
16701 (save-window-excursion
16702 (mapc
16703 (lambda (b)
16704 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16705 (with-current-buffer b buffer-file-name))
16706 (org-pop-to-buffer-same-window b)
16707 (revert-buffer t 'no-confirm)))
16708 (buffer-list))
16709 (when (and (featurep 'org-id) org-id-track-globally)
16710 (org-id-locations-load)))))
16712 ;;;; Agenda files
16714 ;;;###autoload
16715 (defun org-switchb (&optional arg)
16716 "Switch between Org buffers.
16717 With one prefix argument, restrict available buffers to files.
16718 With two prefix arguments, restrict available buffers to agenda files.
16720 Defaults to `iswitchb' for buffer name completion.
16721 Set `org-completion-use-ido' to make it use ido instead."
16722 (interactive "P")
16723 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16724 ((equal arg '(16)) (org-buffer-list 'agenda))
16725 (t (org-buffer-list))))
16726 (org-completion-use-iswitchb org-completion-use-iswitchb)
16727 (org-completion-use-ido org-completion-use-ido))
16728 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16729 (setq org-completion-use-iswitchb t))
16730 (org-pop-to-buffer-same-window
16731 (org-icompleting-read "Org buffer: "
16732 (mapcar 'list (mapcar 'buffer-name blist))
16733 nil t))))
16735 ;;; Define some older names previously used for this functionality
16736 ;;;###autoload
16737 (defalias 'org-ido-switchb 'org-switchb)
16738 ;;;###autoload
16739 (defalias 'org-iswitchb 'org-switchb)
16741 (defun org-buffer-list (&optional predicate exclude-tmp)
16742 "Return a list of Org buffers.
16743 PREDICATE can be `export', `files' or `agenda'.
16745 export restrict the list to Export buffers.
16746 files restrict the list to buffers visiting Org files.
16747 agenda restrict the list to buffers visiting agenda files.
16749 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16750 (let* ((bfn nil)
16751 (agenda-files (and (eq predicate 'agenda)
16752 (mapcar 'file-truename (org-agenda-files t))))
16753 (filter
16754 (cond
16755 ((eq predicate 'files)
16756 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16757 ((eq predicate 'export)
16758 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16759 ((eq predicate 'agenda)
16760 (lambda (b)
16761 (with-current-buffer b
16762 (and (derived-mode-p 'org-mode)
16763 (setq bfn (buffer-file-name b))
16764 (member (file-truename bfn) agenda-files)))))
16765 (t (lambda (b) (with-current-buffer b
16766 (or (derived-mode-p 'org-mode)
16767 (string-match "\*Org .*Export"
16768 (buffer-name b)))))))))
16769 (delq nil
16770 (mapcar
16771 (lambda(b)
16772 (if (and (funcall filter b)
16773 (or (not exclude-tmp)
16774 (not (string-match "tmp" (buffer-name b)))))
16776 nil))
16777 (buffer-list)))))
16779 (defun org-agenda-files (&optional unrestricted archives)
16780 "Get the list of agenda files.
16781 Optional UNRESTRICTED means return the full list even if a restriction
16782 is currently in place.
16783 When ARCHIVES is t, include all archive files that are really being
16784 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16785 `org-agenda-archives-mode' is t."
16786 (let ((files
16787 (cond
16788 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16789 ((stringp org-agenda-files) (org-read-agenda-file-list))
16790 ((listp org-agenda-files) org-agenda-files)
16791 (t (error "Invalid value of `org-agenda-files'")))))
16792 (setq files (apply 'append
16793 (mapcar (lambda (f)
16794 (if (file-directory-p f)
16795 (directory-files
16796 f t org-agenda-file-regexp)
16797 (list f)))
16798 files)))
16799 (when org-agenda-skip-unavailable-files
16800 (setq files (delq nil
16801 (mapcar (function
16802 (lambda (file)
16803 (and (file-readable-p file) file)))
16804 files))))
16805 (when (or (eq archives t)
16806 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16807 (setq files (org-add-archive-files files)))
16808 files))
16810 (defun org-agenda-file-p (&optional file)
16811 "Return non-nil, if FILE is an agenda file.
16812 If FILE is omitted, use the file associated with the current
16813 buffer."
16814 (member (or file (buffer-file-name))
16815 (org-agenda-files t)))
16817 (defun org-edit-agenda-file-list ()
16818 "Edit the list of agenda files.
16819 Depending on setup, this either uses customize to edit the variable
16820 `org-agenda-files', or it visits the file that is holding the list. In the
16821 latter case, the buffer is set up in a way that saving it automatically kills
16822 the buffer and restores the previous window configuration."
16823 (interactive)
16824 (if (stringp org-agenda-files)
16825 (let ((cw (current-window-configuration)))
16826 (find-file org-agenda-files)
16827 (org-set-local 'org-window-configuration cw)
16828 (org-add-hook 'after-save-hook
16829 (lambda ()
16830 (set-window-configuration
16831 (prog1 org-window-configuration
16832 (kill-buffer (current-buffer))))
16833 (org-install-agenda-files-menu)
16834 (message "New agenda file list installed"))
16835 nil 'local)
16836 (message "%s" (substitute-command-keys
16837 "Edit list and finish with \\[save-buffer]")))
16838 (customize-variable 'org-agenda-files)))
16840 (defun org-store-new-agenda-file-list (list)
16841 "Set new value for the agenda file list and save it correctly."
16842 (if (stringp org-agenda-files)
16843 (let ((fe (org-read-agenda-file-list t)) b u)
16844 (while (setq b (find-buffer-visiting org-agenda-files))
16845 (kill-buffer b))
16846 (with-temp-file org-agenda-files
16847 (insert
16848 (mapconcat
16849 (lambda (f) ;; Keep un-expanded entries.
16850 (if (setq u (assoc f fe))
16851 (cdr u)
16853 list "\n")
16854 "\n")))
16855 (let ((org-mode-hook nil) (org-inhibit-startup t)
16856 (org-insert-mode-line-in-empty-file nil))
16857 (setq org-agenda-files list)
16858 (customize-save-variable 'org-agenda-files org-agenda-files))))
16860 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16861 "Read the list of agenda files from a file.
16862 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16863 filenames, used by `org-store-new-agenda-file-list' to write back
16864 un-expanded file names."
16865 (when (file-directory-p org-agenda-files)
16866 (error "`org-agenda-files' cannot be a single directory"))
16867 (when (stringp org-agenda-files)
16868 (with-temp-buffer
16869 (insert-file-contents org-agenda-files)
16870 (mapcar
16871 (lambda (f)
16872 (let ((e (expand-file-name (substitute-in-file-name f)
16873 org-directory)))
16874 (if pair-with-expansion
16875 (cons e f)
16876 e)))
16877 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16879 ;;;###autoload
16880 (defun org-cycle-agenda-files ()
16881 "Cycle through the files in `org-agenda-files'.
16882 If the current buffer visits an agenda file, find the next one in the list.
16883 If the current buffer does not, find the first agenda file."
16884 (interactive)
16885 (let* ((fs (org-agenda-files t))
16886 (files (append fs (list (car fs))))
16887 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16888 file)
16889 (unless files (error "No agenda files"))
16890 (catch 'exit
16891 (while (setq file (pop files))
16892 (if (equal (file-truename file) tcf)
16893 (when (car files)
16894 (find-file (car files))
16895 (throw 'exit t))))
16896 (find-file (car fs)))
16897 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16899 (defun org-agenda-file-to-front (&optional to-end)
16900 "Move/add the current file to the top of the agenda file list.
16901 If the file is not present in the list, it is added to the front. If it is
16902 present, it is moved there. With optional argument TO-END, add/move to the
16903 end of the list."
16904 (interactive "P")
16905 (let ((org-agenda-skip-unavailable-files nil)
16906 (file-alist (mapcar (lambda (x)
16907 (cons (file-truename x) x))
16908 (org-agenda-files t)))
16909 (ctf (file-truename
16910 (or buffer-file-name
16911 (error "Please save the current buffer to a file"))))
16912 x had)
16913 (setq x (assoc ctf file-alist) had x)
16915 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16916 (if to-end
16917 (setq file-alist (append (delq x file-alist) (list x)))
16918 (setq file-alist (cons x (delq x file-alist))))
16919 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16920 (org-install-agenda-files-menu)
16921 (message "File %s to %s of agenda file list"
16922 (if had "moved" "added") (if to-end "end" "front"))))
16924 (defun org-remove-file (&optional file)
16925 "Remove current file from the list of files in variable `org-agenda-files'.
16926 These are the files which are being checked for agenda entries.
16927 Optional argument FILE means use this file instead of the current."
16928 (interactive)
16929 (let* ((org-agenda-skip-unavailable-files nil)
16930 (file (or file buffer-file-name
16931 (error "Current buffer does not visit a file")))
16932 (true-file (file-truename file))
16933 (afile (abbreviate-file-name file))
16934 (files (delq nil (mapcar
16935 (lambda (x)
16936 (if (equal true-file
16937 (file-truename x))
16938 nil x))
16939 (org-agenda-files t)))))
16940 (if (not (= (length files) (length (org-agenda-files t))))
16941 (progn
16942 (org-store-new-agenda-file-list files)
16943 (org-install-agenda-files-menu)
16944 (message "Removed file: %s" afile))
16945 (message "File was not in list: %s (not removed)" afile))))
16947 (defun org-file-menu-entry (file)
16948 (vector file (list 'find-file file) t))
16950 (defun org-check-agenda-file (file)
16951 "Make sure FILE exists. If not, ask user what to do."
16952 (when (not (file-exists-p file))
16953 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
16954 (abbreviate-file-name file))
16955 (let ((r (downcase (read-char-exclusive))))
16956 (cond
16957 ((equal r ?r)
16958 (org-remove-file file)
16959 (throw 'nextfile t))
16960 (t (error "Abort"))))))
16962 (defun org-get-agenda-file-buffer (file)
16963 "Get a buffer visiting FILE. If the buffer needs to be created, add
16964 it to the list of buffers which might be released later."
16965 (let ((buf (org-find-base-buffer-visiting file)))
16966 (if buf
16967 buf ; just return it
16968 ;; Make a new buffer and remember it
16969 (setq buf (find-file-noselect file))
16970 (if buf (push buf org-agenda-new-buffers))
16971 buf)))
16973 (defun org-release-buffers (blist)
16974 "Release all buffers in list, asking the user for confirmation when needed.
16975 When a buffer is unmodified, it is just killed. When modified, it is saved
16976 \(if the user agrees) and then killed."
16977 (let (buf file)
16978 (while (setq buf (pop blist))
16979 (setq file (buffer-file-name buf))
16980 (when (and (buffer-modified-p buf)
16981 file
16982 (y-or-n-p (format "Save file %s? " file)))
16983 (with-current-buffer buf (save-buffer)))
16984 (kill-buffer buf))))
16986 (defun org-agenda-prepare-buffers (files)
16987 "Create buffers for all agenda files, protect archived trees and comments."
16988 (interactive)
16989 (let ((pa '(:org-archived t))
16990 (pc '(:org-comment t))
16991 (pall '(:org-archived t :org-comment t))
16992 (inhibit-read-only t)
16993 (rea (concat ":" org-archive-tag ":"))
16994 bmp file re)
16995 (save-excursion
16996 (save-restriction
16997 (while (setq file (pop files))
16998 (catch 'nextfile
16999 (if (bufferp file)
17000 (set-buffer file)
17001 (org-check-agenda-file file)
17002 (set-buffer (org-get-agenda-file-buffer file)))
17003 (widen)
17004 (setq bmp (buffer-modified-p))
17005 (org-refresh-category-properties)
17006 (org-refresh-properties org-effort-property 'org-effort)
17007 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17008 (setq org-todo-keywords-for-agenda
17009 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17010 (setq org-done-keywords-for-agenda
17011 (append org-done-keywords-for-agenda org-done-keywords))
17012 (setq org-todo-keyword-alist-for-agenda
17013 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17014 (setq org-drawers-for-agenda
17015 (append org-drawers-for-agenda org-drawers))
17016 (setq org-tag-alist-for-agenda
17017 (append org-tag-alist-for-agenda org-tag-alist))
17019 (save-excursion
17020 (remove-text-properties (point-min) (point-max) pall)
17021 (when org-agenda-skip-archived-trees
17022 (goto-char (point-min))
17023 (while (re-search-forward rea nil t)
17024 (if (org-at-heading-p t)
17025 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17026 (goto-char (point-min))
17027 (setq re (format org-heading-keyword-regexp-format
17028 org-comment-string))
17029 (while (re-search-forward re nil t)
17030 (add-text-properties
17031 (match-beginning 0) (org-end-of-subtree t) pc)))
17032 (set-buffer-modified-p bmp)))))
17033 (setq org-todo-keywords-for-agenda
17034 (org-uniquify org-todo-keywords-for-agenda))
17035 (setq org-todo-keyword-alist-for-agenda
17036 (org-uniquify org-todo-keyword-alist-for-agenda)
17037 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17039 ;;;; Embedded LaTeX
17041 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17042 "Keymap for the minor `org-cdlatex-mode'.")
17044 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17045 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17046 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17047 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17048 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17050 (defvar org-cdlatex-texmathp-advice-is-done nil
17051 "Flag remembering if we have applied the advice to texmathp already.")
17053 (define-minor-mode org-cdlatex-mode
17054 "Toggle the minor `org-cdlatex-mode'.
17055 This mode supports entering LaTeX environment and math in LaTeX fragments
17056 in Org-mode.
17057 \\{org-cdlatex-mode-map}"
17058 nil " OCDL" nil
17059 (when org-cdlatex-mode
17060 (require 'cdlatex)
17061 (run-hooks 'cdlatex-mode-hook)
17062 (cdlatex-compute-tables))
17063 (unless org-cdlatex-texmathp-advice-is-done
17064 (setq org-cdlatex-texmathp-advice-is-done t)
17065 (defadvice texmathp (around org-math-always-on activate)
17066 "Always return t in org-mode buffers.
17067 This is because we want to insert math symbols without dollars even outside
17068 the LaTeX math segments. If Orgmode thinks that point is actually inside
17069 an embedded LaTeX fragment, let texmathp do its job.
17070 \\[org-cdlatex-mode-map]"
17071 (interactive)
17072 (let (p)
17073 (cond
17074 ((not (derived-mode-p 'org-mode)) ad-do-it)
17075 ((eq this-command 'cdlatex-math-symbol)
17076 (setq ad-return-value t
17077 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17079 (let ((p (org-inside-LaTeX-fragment-p)))
17080 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17081 (setq ad-return-value t
17082 texmathp-why '("Org-mode embedded math" . 0))
17083 (if p ad-do-it)))))))))
17085 (defun turn-on-org-cdlatex ()
17086 "Unconditionally turn on `org-cdlatex-mode'."
17087 (org-cdlatex-mode 1))
17089 (defun org-inside-LaTeX-fragment-p ()
17090 "Test if point is inside a LaTeX fragment.
17091 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17092 sequence appearing also before point.
17093 Even though the matchers for math are configurable, this function assumes
17094 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17095 delimiters are skipped when they have been removed by customization.
17096 The return value is nil, or a cons cell with the delimiter and the
17097 position of this delimiter.
17099 This function does a reasonably good job, but can locally be fooled by
17100 for example currency specifications. For example it will assume being in
17101 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17102 fragments that are properly closed, but during editing, we have to live
17103 with the uncertainty caused by missing closing delimiters. This function
17104 looks only before point, not after."
17105 (catch 'exit
17106 (let ((pos (point))
17107 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17108 (lim (progn
17109 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17110 (point)))
17111 dd-on str (start 0) m re)
17112 (goto-char pos)
17113 (when dodollar
17114 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17115 re (nth 1 (assoc "$" org-latex-regexps)))
17116 (while (string-match re str start)
17117 (cond
17118 ((= (match-end 0) (length str))
17119 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17120 ((= (match-end 0) (- (length str) 5))
17121 (throw 'exit nil))
17122 (t (setq start (match-end 0))))))
17123 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17124 (goto-char pos)
17125 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17126 (and (match-beginning 2) (throw 'exit nil))
17127 ;; count $$
17128 (while (re-search-backward "\\$\\$" lim t)
17129 (setq dd-on (not dd-on)))
17130 (goto-char pos)
17131 (if dd-on (cons "$$" m))))))
17133 (defun org-inside-latex-macro-p ()
17134 "Is point inside a LaTeX macro or its arguments?"
17135 (save-match-data
17136 (org-in-regexp
17137 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17139 (defun org-try-cdlatex-tab ()
17140 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17141 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17142 - inside a LaTeX fragment, or
17143 - after the first word in a line, where an abbreviation expansion could
17144 insert a LaTeX environment."
17145 (when org-cdlatex-mode
17146 (cond
17147 ;; Before any word on the line: No expansion possible.
17148 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17149 ;; Just after first word on the line: Expand it. Make sure it
17150 ;; cannot happen on headlines, though.
17151 ((save-excursion
17152 (skip-chars-backward "a-zA-Z0-9*")
17153 (skip-chars-backward " \t")
17154 (and (bolp) (not (org-at-heading-p))))
17155 (cdlatex-tab) t)
17156 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17158 (defun org-cdlatex-underscore-caret (&optional arg)
17159 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17160 Revert to the normal definition outside of these fragments."
17161 (interactive "P")
17162 (if (org-inside-LaTeX-fragment-p)
17163 (call-interactively 'cdlatex-sub-superscript)
17164 (let (org-cdlatex-mode)
17165 (call-interactively (key-binding (vector last-input-event))))))
17167 (defun org-cdlatex-math-modify (&optional arg)
17168 "Execute `cdlatex-math-modify' in LaTeX fragments.
17169 Revert to the normal definition outside of these fragments."
17170 (interactive "P")
17171 (if (org-inside-LaTeX-fragment-p)
17172 (call-interactively 'cdlatex-math-modify)
17173 (let (org-cdlatex-mode)
17174 (call-interactively (key-binding (vector last-input-event))))))
17176 (defvar org-latex-fragment-image-overlays nil
17177 "List of overlays carrying the images of latex fragments.")
17178 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17180 (defun org-remove-latex-fragment-image-overlays ()
17181 "Remove all overlays with LaTeX fragment images in current buffer."
17182 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17183 (setq org-latex-fragment-image-overlays nil))
17185 (defun org-preview-latex-fragment (&optional subtree)
17186 "Preview the LaTeX fragment at point, or all locally or globally.
17187 If the cursor is in a LaTeX fragment, create the image and overlay
17188 it over the source code. If there is no fragment at point, display
17189 all fragments in the current text, from one headline to the next. With
17190 prefix SUBTREE, display all fragments in the current subtree. With a
17191 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17192 the cursor is before the first headline,
17193 display all fragments in the buffer.
17194 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17195 (interactive "P")
17196 (unless buffer-file-name
17197 (error "Can't preview LaTeX fragment in a non-file buffer"))
17198 (org-remove-latex-fragment-image-overlays)
17199 (save-excursion
17200 (save-restriction
17201 (let (beg end at msg)
17202 (cond
17203 ((or (equal subtree '(16))
17204 (not (save-excursion
17205 (re-search-backward org-outline-regexp-bol nil t))))
17206 (setq beg (point-min) end (point-max)
17207 msg "Creating images for buffer...%s"))
17208 ((equal subtree '(4))
17209 (org-back-to-heading)
17210 (setq beg (point) end (org-end-of-subtree t)
17211 msg "Creating images for subtree...%s"))
17213 (if (setq at (org-inside-LaTeX-fragment-p))
17214 (goto-char (max (point-min) (- (cdr at) 2)))
17215 (org-back-to-heading))
17216 (setq beg (point) end (progn (outline-next-heading) (point))
17217 msg (if at "Creating image...%s"
17218 "Creating images for entry...%s"))))
17219 (message msg "")
17220 (narrow-to-region beg end)
17221 (goto-char beg)
17222 (org-format-latex
17223 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17224 (file-name-nondirectory
17225 buffer-file-name)))
17226 default-directory 'overlays msg at 'forbuffer
17227 org-latex-create-formula-image-program)
17228 (message msg "done. Use `C-c C-c' to remove images.")))))
17230 (defvar org-latex-regexps
17231 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17232 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17233 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17234 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17235 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17236 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17237 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17238 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17239 "Regular expressions for matching embedded LaTeX.")
17241 (defvar org-export-have-math nil) ;; dynamic scoping
17242 (defun org-format-latex (prefix &optional dir overlays msg at
17243 forbuffer processing-type)
17244 "Replace LaTeX fragments with links to an image, and produce images.
17245 Some of the options can be changed using the variable
17246 `org-format-latex-options'."
17247 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17248 (let* ((prefixnodir (file-name-nondirectory prefix))
17249 (absprefix (expand-file-name prefix dir))
17250 (todir (file-name-directory absprefix))
17251 (opt org-format-latex-options)
17252 (matchers (plist-get opt :matchers))
17253 (re-list org-latex-regexps)
17254 (org-format-latex-header-extra
17255 (plist-get (org-infile-export-plist) :latex-header-extra))
17256 (cnt 0) txt hash link beg end re e checkdir
17257 executables-checked string
17258 m n block-type block linkfile movefile ov)
17259 ;; Check the different regular expressions
17260 (while (setq e (pop re-list))
17261 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17262 block (if block-type "\n\n" ""))
17263 (when (member m matchers)
17264 (goto-char (point-min))
17265 (while (re-search-forward re nil t)
17266 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17267 (not (get-text-property (match-beginning n)
17268 'org-protected))
17269 (or (not overlays)
17270 (not (eq (get-char-property (match-beginning n)
17271 'org-overlay-type)
17272 'org-latex-overlay))))
17273 (setq org-export-have-math t)
17274 (cond
17275 ((eq processing-type 'verbatim)
17276 ;; Leave the text verbatim, just protect it
17277 (add-text-properties (match-beginning n) (match-end n)
17278 '(org-protected t)))
17279 ((eq processing-type 'mathjax)
17280 ;; Prepare for MathJax processing
17281 (setq string (match-string n))
17282 (if (member m '("$" "$1"))
17283 (save-excursion
17284 (delete-region (match-beginning n) (match-end n))
17285 (goto-char (match-beginning n))
17286 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17287 "\\)")
17288 '(org-protected t))))
17289 (add-text-properties (match-beginning n) (match-end n)
17290 '(org-protected t))))
17291 ((or (eq processing-type 'dvipng)
17292 (eq processing-type 'imagemagick))
17293 ;; Process to an image
17294 (setq txt (match-string n)
17295 beg (match-beginning n) end (match-end n)
17296 cnt (1+ cnt))
17297 (let (print-length print-level) ; make sure full list is printed
17298 (setq hash (sha1 (prin1-to-string
17299 (list org-format-latex-header
17300 org-format-latex-header-extra
17301 org-export-latex-default-packages-alist
17302 org-export-latex-packages-alist
17303 org-format-latex-options
17304 forbuffer txt)))
17305 linkfile (format "%s_%s.png" prefix hash)
17306 movefile (format "%s_%s.png" absprefix hash)))
17307 (setq link (concat block "[[file:" linkfile "]]" block))
17308 (if msg (message msg cnt))
17309 (goto-char beg)
17310 (unless checkdir ; make sure the directory exists
17311 (setq checkdir t)
17312 (or (file-directory-p todir) (make-directory todir t)))
17313 (cond
17314 ((eq processing-type 'dvipng)
17315 (unless executables-checked
17316 (org-check-external-command
17317 "latex" "needed to convert LaTeX fragments to images")
17318 (org-check-external-command
17319 "dvipng" "needed to convert LaTeX fragments to images")
17320 (setq executables-checked t))
17321 (unless (file-exists-p movefile)
17322 (org-create-formula-image-with-dvipng
17323 txt movefile opt forbuffer)))
17324 ((eq processing-type 'imagemagick)
17325 (unless executables-checked
17326 (org-check-external-command
17327 "convert" "you need to install imagemagick")
17328 (setq executables-checked t))
17329 (unless (file-exists-p movefile)
17330 (org-create-formula-image-with-imagemagick
17331 txt movefile opt forbuffer))))
17332 (if overlays
17333 (progn
17334 (mapc (lambda (o)
17335 (if (eq (overlay-get o 'org-overlay-type)
17336 'org-latex-overlay)
17337 (delete-overlay o)))
17338 (overlays-in beg end))
17339 (setq ov (make-overlay beg end))
17340 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17341 (if (featurep 'xemacs)
17342 (progn
17343 (overlay-put ov 'invisible t)
17344 (overlay-put
17345 ov 'end-glyph
17346 (make-glyph (vector 'png :file movefile))))
17347 (overlay-put
17348 ov 'display
17349 (list 'image :type 'png :file movefile :ascent 'center)))
17350 (push ov org-latex-fragment-image-overlays)
17351 (goto-char end))
17352 (delete-region beg end)
17353 (insert (org-add-props link
17354 (list 'org-latex-src
17355 (replace-regexp-in-string
17356 "\"" "" txt)
17357 'org-latex-src-embed-type
17358 (if block-type 'paragraph 'character))))))
17359 ((eq processing-type 'mathml)
17360 ;; Process to MathML
17361 (unless executables-checked
17362 (unless (save-match-data (org-format-latex-mathml-available-p))
17363 (error "LaTeX to MathML converter not configured"))
17364 (setq executables-checked t))
17365 (setq txt (match-string n)
17366 beg (match-beginning n) end (match-end n)
17367 cnt (1+ cnt))
17368 (if msg (message msg cnt))
17369 (goto-char beg)
17370 (delete-region beg end)
17371 (insert (org-format-latex-as-mathml
17372 txt block-type prefix dir)))
17374 (error "Unknown conversion type %s for latex fragments"
17375 processing-type)))))))))
17377 (defun org-create-math-formula (latex-frag &optional mathml-file)
17378 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17379 Use `org-latex-to-mathml-convert-command'. If the conversion is
17380 sucessful, return the portion between \"<math...> </math>\"
17381 elements otherwise return nil. When MATHML-FILE is specified,
17382 write the results in to that file. When invoked as an
17383 interactive command, prompt for LATEX-FRAG, with initial value
17384 set to the current active region and echo the results for user
17385 inspection."
17386 (interactive (list (let ((frag (when (org-region-active-p)
17387 (buffer-substring-no-properties
17388 (region-beginning) (region-end)))))
17389 (read-string "LaTeX Fragment: " frag nil frag))))
17390 (unless latex-frag (error "Invalid latex-frag"))
17391 (let* ((tmp-in-file (file-relative-name
17392 (make-temp-name (expand-file-name "ltxmathml-in"))))
17393 (ignore (write-region latex-frag nil tmp-in-file))
17394 (tmp-out-file (file-relative-name
17395 (make-temp-name (expand-file-name "ltxmathml-out"))))
17396 (cmd (format-spec
17397 org-latex-to-mathml-convert-command
17398 `((?j . ,(shell-quote-argument
17399 (expand-file-name org-latex-to-mathml-jar-file)))
17400 (?I . ,(shell-quote-argument tmp-in-file))
17401 (?o . ,(shell-quote-argument tmp-out-file)))))
17402 mathml shell-command-output)
17403 (when (org-called-interactively-p 'any)
17404 (unless (org-format-latex-mathml-available-p)
17405 (error "LaTeX to MathML converter not configured")))
17406 (message "Running %s" cmd)
17407 (setq shell-command-output (shell-command-to-string cmd))
17408 (setq mathml
17409 (when (file-readable-p tmp-out-file)
17410 (with-current-buffer (find-file-noselect tmp-out-file t)
17411 (goto-char (point-min))
17412 (when (re-search-forward
17413 (concat
17414 (regexp-quote
17415 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17416 "\\(.\\|\n\\)*"
17417 (regexp-quote "</math>")) nil t)
17418 (prog1 (match-string 0) (kill-buffer))))))
17419 (cond
17420 (mathml
17421 (setq mathml
17422 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17423 (when mathml-file
17424 (write-region mathml nil mathml-file))
17425 (when (org-called-interactively-p 'any)
17426 (message mathml)))
17427 ((message "LaTeX to MathML conversion failed")
17428 (message shell-command-output)))
17429 (delete-file tmp-in-file)
17430 (when (file-exists-p tmp-out-file)
17431 (delete-file tmp-out-file))
17432 mathml))
17434 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17435 prefix &optional dir)
17436 "Use `org-create-math-formula' but check local cache first."
17437 (let* ((absprefix (expand-file-name prefix dir))
17438 (print-length nil) (print-level nil)
17439 (formula-id (concat
17440 "formula-"
17441 (sha1
17442 (prin1-to-string
17443 (list latex-frag
17444 org-latex-to-mathml-convert-command)))))
17445 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17446 (formula-cache-dir (file-name-directory formula-cache)))
17448 (unless (file-directory-p formula-cache-dir)
17449 (make-directory formula-cache-dir t))
17451 (unless (file-exists-p formula-cache)
17452 (org-create-math-formula latex-frag formula-cache))
17454 (if (file-exists-p formula-cache)
17455 ;; Successful conversion. Return the link to MathML file.
17456 (org-add-props
17457 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17458 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17459 'org-latex-src-embed-type (if latex-frag-type
17460 'paragraph 'character)))
17461 ;; Failed conversion. Return the LaTeX fragment verbatim
17462 (add-text-properties
17463 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17464 latex-frag)))
17466 ;; This function borrows from Ganesh Swami's latex2png.el
17467 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17468 "This calls dvipng."
17469 (require 'org-latex)
17470 (let* ((tmpdir (if (featurep 'xemacs)
17471 (temp-directory)
17472 temporary-file-directory))
17473 (texfilebase (make-temp-name
17474 (expand-file-name "orgtex" tmpdir)))
17475 (texfile (concat texfilebase ".tex"))
17476 (dvifile (concat texfilebase ".dvi"))
17477 (pngfile (concat texfilebase ".png"))
17478 (fnh (if (featurep 'xemacs)
17479 (font-height (face-font 'default))
17480 (face-attribute 'default :height nil)))
17481 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17482 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17483 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17484 "Black"))
17485 (bg (or (plist-get options (if buffer :background :html-background))
17486 "Transparent")))
17487 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17488 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17489 (with-temp-file texfile
17490 (insert (org-splice-latex-header
17491 org-format-latex-header
17492 org-export-latex-default-packages-alist
17493 org-export-latex-packages-alist t
17494 org-format-latex-header-extra))
17495 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17496 (require 'org-latex)
17497 (org-export-latex-fix-inputenc))
17498 (let ((dir default-directory))
17499 (condition-case nil
17500 (progn
17501 (cd tmpdir)
17502 (call-process "latex" nil nil nil texfile))
17503 (error nil))
17504 (cd dir))
17505 (if (not (file-exists-p dvifile))
17506 (progn (message "Failed to create dvi file from %s" texfile) nil)
17507 (condition-case nil
17508 (if (featurep 'xemacs)
17509 (call-process "dvipng" nil nil nil
17510 "-fg" fg "-bg" bg
17511 "-T" "tight"
17512 "-o" pngfile
17513 dvifile)
17514 (call-process "dvipng" nil nil nil
17515 "-fg" fg "-bg" bg
17516 "-D" dpi
17517 ;;"-x" scale "-y" scale
17518 "-T" "tight"
17519 "-o" pngfile
17520 dvifile))
17521 (error nil))
17522 (if (not (file-exists-p pngfile))
17523 (if org-format-latex-signal-error
17524 (error "Failed to create png file from %s" texfile)
17525 (message "Failed to create png file from %s" texfile)
17526 nil)
17527 ;; Use the requested file name and clean up
17528 (copy-file pngfile tofile 'replace)
17529 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17530 (if (file-exists-p (concat texfilebase e))
17531 (delete-file (concat texfilebase e))))
17532 pngfile))))
17534 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17535 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17536 "This calls convert, which is included into imagemagick."
17537 (require 'org-latex)
17538 (let* ((tmpdir (if (featurep 'xemacs)
17539 (temp-directory)
17540 temporary-file-directory))
17541 (texfilebase (make-temp-name
17542 (expand-file-name "orgtex" tmpdir)))
17543 (texfile (concat texfilebase ".tex"))
17544 (pdffile (concat texfilebase ".pdf"))
17545 (pngfile (concat texfilebase ".png"))
17546 (fnh (if (featurep 'xemacs)
17547 (font-height (face-font 'default))
17548 (face-attribute 'default :height nil)))
17549 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17550 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17551 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17552 "black"))
17553 (bg (or (plist-get options (if buffer :background :html-background))
17554 "white")))
17555 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17556 (setq fg (org-latex-color-format fg)))
17557 (if (eq bg 'default) (setq bg (org-latex-color :background))
17558 (setq bg (org-latex-color-format
17559 (if (string= bg "Transparent")(setq bg "white")))))
17560 (with-temp-file texfile
17561 (insert (org-splice-latex-header
17562 org-format-latex-header
17563 org-export-latex-default-packages-alist
17564 org-export-latex-packages-alist t
17565 org-format-latex-header-extra))
17566 (insert "\n\\begin{document}\n"
17567 "\\definecolor{fg}{rgb}{" fg "}\n"
17568 "\\definecolor{bg}{rgb}{" bg "}\n"
17569 "\n\\pagecolor{bg}\n"
17570 "\n{\\color{fg}\n"
17571 string
17572 "\n}\n"
17573 "\n\\end{document}\n" )
17574 (require 'org-latex)
17575 (org-export-latex-fix-inputenc))
17576 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17577 (condition-case nil
17578 (progn
17579 (cd tmpdir)
17580 (setq cmds org-latex-to-pdf-process)
17581 (while cmds
17582 (setq latex-frags-cmds (pop cmds))
17583 (if (listp latex-frags-cmds)
17584 (setq cmds nil)
17585 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17586 (while latex-frags-cmds
17587 (setq cmd (pop latex-frags-cmds))
17588 (while (string-match "%b" cmd)
17589 (setq cmd (replace-match
17590 (save-match-data
17591 (shell-quote-argument texfile))
17592 t t cmd)))
17593 (while (string-match "%f" cmd)
17594 (setq cmd (replace-match
17595 (save-match-data
17596 (shell-quote-argument (file-name-nondirectory texfile)))
17597 t t cmd)))
17598 (while (string-match "%o" cmd)
17599 (setq cmd (replace-match
17600 (save-match-data
17601 (shell-quote-argument (file-name-directory texfile)))
17602 t t cmd)))
17603 (setq cmd (split-string cmd))
17604 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17605 (error nil))
17606 (cd dir))
17607 (if (not (file-exists-p pdffile))
17608 (progn (message "Failed to create pdf file from %s" texfile) nil)
17609 (condition-case nil
17610 (if (featurep 'xemacs)
17611 (call-process "convert" nil nil nil
17612 "-density" "96"
17613 "-trim"
17614 "-antialias"
17615 pdffile
17616 "-quality" "100"
17617 ;; "-sharpen" "0x1.0"
17618 pngfile)
17619 (call-process "convert" nil nil nil
17620 "-density" dpi
17621 "-trim"
17622 "-antialias"
17623 pdffile
17624 "-quality" "100"
17625 ; "-sharpen" "0x1.0"
17626 pngfile))
17627 (error nil))
17628 (if (not (file-exists-p pngfile))
17629 (if org-format-latex-signal-error
17630 (error "Failed to create png file from %s" texfile)
17631 (message "Failed to create png file from %s" texfile)
17632 nil)
17633 ;; Use the requested file name and clean up
17634 (copy-file pngfile tofile 'replace)
17635 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17636 (if (file-exists-p (concat texfilebase e))
17637 (delete-file (concat texfilebase e))))
17638 pngfile))))
17640 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17641 "Fill a LaTeX header template TPL.
17642 In the template, the following place holders will be recognized:
17644 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17645 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17646 [PACKAGES] \\usepackage statements for PKG
17647 [NO-PACKAGES] do not include PKG
17648 [EXTRA] the string EXTRA
17649 [NO-EXTRA] do not include EXTRA
17651 For backward compatibility, if both the positive and the negative place
17652 holder is missing, the positive one (without the \"NO-\") will be
17653 assumed to be present at the end of the template.
17654 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17655 EXTRA is a string.
17656 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17657 (let (rpl (end ""))
17658 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17659 (setq rpl (if (or (match-end 1) (not def-pkg))
17660 "" (org-latex-packages-to-string def-pkg snippets-p t))
17661 tpl (replace-match rpl t t tpl))
17662 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17664 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17665 (setq rpl (if (or (match-end 1) (not pkg))
17666 "" (org-latex-packages-to-string pkg snippets-p t))
17667 tpl (replace-match rpl t t tpl))
17668 (if pkg (setq end
17669 (concat end "\n"
17670 (org-latex-packages-to-string pkg snippets-p)))))
17672 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17673 (setq rpl (if (or (match-end 1) (not extra))
17674 "" (concat extra "\n"))
17675 tpl (replace-match rpl t t tpl))
17676 (if (and extra (string-match "\\S-" extra))
17677 (setq end (concat end "\n" extra))))
17679 (if (string-match "\\S-" end)
17680 (concat tpl "\n" end)
17681 tpl)))
17683 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17684 "Turn an alist of packages into a string with the \\usepackage macros."
17685 (setq pkg (mapconcat (lambda(p)
17686 (cond
17687 ((stringp p) p)
17688 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17689 (format "%% Package %s omitted" (cadr p)))
17690 ((equal "" (car p))
17691 (format "\\usepackage{%s}" (cadr p)))
17693 (format "\\usepackage[%s]{%s}"
17694 (car p) (cadr p)))))
17696 "\n"))
17697 (if newline (concat pkg "\n") pkg))
17699 (defun org-dvipng-color (attr)
17700 "Return a RGB color specification for dvipng."
17701 (apply 'format "rgb %s %s %s"
17702 (mapcar 'org-normalize-color
17703 (if (featurep 'xemacs)
17704 (color-rgb-components
17705 (face-property 'default
17706 (cond ((eq attr :foreground) 'foreground)
17707 ((eq attr :background) 'background))))
17708 (color-values (face-attribute 'default attr nil))))))
17710 (defun org-latex-color (attr)
17711 "Return a RGB color for the LaTeX color package."
17712 (apply 'format "%s,%s,%s"
17713 (mapcar 'org-normalize-color
17714 (if (featurep 'xemacs)
17715 (color-rgb-components
17716 (face-property 'default
17717 (cond ((eq attr :foreground) 'foreground)
17718 ((eq attr :background) 'background))))
17719 (color-values (face-attribute 'default attr nil))))))
17721 (defun org-latex-color-format (color-name)
17722 "Convert COLOR-NAME to a RGB color value."
17723 (apply 'format "%s,%s,%s"
17724 (mapcar 'org-normalize-color
17725 (color-values color-name))))
17727 (defun org-normalize-color (value)
17728 "Return string to be used as color value for an RGB component."
17729 (format "%g" (/ value 65535.0)))
17731 ;; Image display
17734 (defvar org-inline-image-overlays nil)
17735 (make-variable-buffer-local 'org-inline-image-overlays)
17737 (defun org-toggle-inline-images (&optional include-linked)
17738 "Toggle the display of inline images.
17739 INCLUDE-LINKED is passed to `org-display-inline-images'."
17740 (interactive "P")
17741 (if org-inline-image-overlays
17742 (progn
17743 (org-remove-inline-images)
17744 (message "Inline image display turned off"))
17745 (org-display-inline-images include-linked)
17746 (if org-inline-image-overlays
17747 (message "%d images displayed inline"
17748 (length org-inline-image-overlays))
17749 (message "No images to display inline"))))
17751 (defun org-redisplay-inline-images ()
17752 "Refresh the display of inline images."
17753 (interactive)
17754 (if (not org-inline-image-overlays)
17755 (org-toggle-inline-images)
17756 (org-toggle-inline-images)
17757 (org-toggle-inline-images)))
17759 (defun org-display-inline-images (&optional include-linked refresh beg end)
17760 "Display inline images.
17761 Normally only links without a description part are inlined, because this
17762 is how it will work for export. When INCLUDE-LINKED is set, also links
17763 with a description part will be inlined. This can be nice for a quick
17764 look at those images, but it does not reflect what exported files will look
17765 like.
17766 When REFRESH is set, refresh existing images between BEG and END.
17767 This will create new image displays only if necessary.
17768 BEG and END default to the buffer boundaries."
17769 (interactive "P")
17770 (unless refresh
17771 (org-remove-inline-images)
17772 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17773 (save-excursion
17774 (save-restriction
17775 (widen)
17776 (setq beg (or beg (point-min)) end (or end (point-max)))
17777 (goto-char beg)
17778 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17779 (substring (org-image-file-name-regexp) 0 -2)
17780 "\\)\\]" (if include-linked "" "\\]")))
17781 old file ov img)
17782 (while (re-search-forward re end t)
17783 (setq old (get-char-property-and-overlay (match-beginning 1)
17784 'org-image-overlay))
17785 (setq file (expand-file-name
17786 (concat (or (match-string 3) "") (match-string 4))))
17787 (when (file-exists-p file)
17788 (if (and (car-safe old) refresh)
17789 (image-refresh (overlay-get (cdr old) 'display))
17790 (setq img (save-match-data (create-image file)))
17791 (when img
17792 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17793 (overlay-put ov 'display img)
17794 (overlay-put ov 'face 'default)
17795 (overlay-put ov 'org-image-overlay t)
17796 (overlay-put ov 'modification-hooks
17797 (list 'org-display-inline-remove-overlay))
17798 (push ov org-inline-image-overlays)))))))))
17800 (org-define-obsolete-function-alias
17801 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
17803 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
17804 "Remove inline-display overlay if a corresponding region is modified."
17805 (let ((inhibit-modification-hooks t))
17806 (when (and ov after)
17807 (delete ov org-inline-image-overlays)
17808 (delete-overlay ov))))
17810 (defun org-remove-inline-images ()
17811 "Remove inline display of images."
17812 (interactive)
17813 (mapc 'delete-overlay org-inline-image-overlays)
17814 (setq org-inline-image-overlays nil))
17816 ;;;; Key bindings
17818 ;; Outline functions from `outline-mode-prefix-map'
17819 ;; that can be remapped in Org:
17820 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17821 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17822 (define-key org-mode-map [remap outline-forward-same-level]
17823 'org-forward-heading-same-level)
17824 (define-key org-mode-map [remap outline-backward-same-level]
17825 'org-backward-heading-same-level)
17826 (define-key org-mode-map [remap show-branches]
17827 'org-kill-note-or-show-branches)
17828 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17829 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17830 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17832 ;; Outline functions from `outline-mode-prefix-map' that can not
17833 ;; be remapped in Org:
17835 ;; - the column "key binding" shows whether the Outline function is still
17836 ;; available in Org mode on the same key that it has been bound to in
17837 ;; Outline mode:
17838 ;; - "overridden": key used for a different functionality in Org mode
17839 ;; - else: key still bound to the same Outline function in Org mode
17841 ;; | Outline function | key binding | Org replacement |
17842 ;; |------------------------------------+-------------+-----------------------|
17843 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17844 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17845 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17846 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
17847 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17848 ;; | `show-entry' | overridden | no replacement |
17849 ;; | `show-children' | `C-c C-i' | visibility cycling |
17850 ;; | `show-branches' | `C-c C-k' | still same function |
17851 ;; | `show-subtree' | overridden | visibility cycling |
17852 ;; | `show-all' | overridden | no replacement |
17853 ;; | `hide-subtree' | overridden | visibility cycling |
17854 ;; | `hide-body' | overridden | no replacement |
17855 ;; | `hide-entry' | overridden | visibility cycling |
17856 ;; | `hide-leaves' | overridden | no replacement |
17857 ;; | `hide-sublevels' | overridden | no replacement |
17858 ;; | `hide-other' | overridden | no replacement |
17860 ;; Make `C-c C-x' a prefix key
17861 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17863 ;; TAB key with modifiers
17864 (org-defkey org-mode-map "\C-i" 'org-cycle)
17865 (org-defkey org-mode-map [(tab)] 'org-cycle)
17866 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17867 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17868 ;; The following line is necessary under Suse GNU/Linux
17869 (unless (featurep 'xemacs)
17870 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17871 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17872 (define-key org-mode-map [backtab] 'org-shifttab)
17874 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17875 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17876 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17878 ;; Cursor keys with modifiers
17879 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17880 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17881 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17882 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17884 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17885 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17886 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17887 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17889 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17890 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17891 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17892 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17894 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17895 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17896 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17897 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17899 ;; Babel keys
17900 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17901 (mapc (lambda (pair)
17902 (define-key org-babel-map (car pair) (cdr pair)))
17903 org-babel-key-bindings)
17905 ;;; Extra keys for tty access.
17906 ;; We only set them when really needed because otherwise the
17907 ;; menus don't show the simple keys
17909 (when (or org-use-extra-keys
17910 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17911 (not window-system))
17912 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17913 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17914 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17915 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17916 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17917 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17918 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17919 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17920 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17921 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17922 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17923 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17924 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17925 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17926 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17927 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17928 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17929 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17930 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17931 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17932 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17933 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17934 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17935 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17936 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17937 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17938 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17939 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17941 ;; All the other keys
17943 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17944 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17945 (if (boundp 'narrow-map)
17946 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17947 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17948 (if (boundp 'narrow-map)
17949 (org-defkey narrow-map "b" 'org-narrow-to-block)
17950 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17951 (if (boundp 'narrow-map)
17952 (org-defkey narrow-map "e" 'org-narrow-to-element)
17953 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
17954 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
17955 (org-defkey org-mode-map "\M-}" 'org-forward-element)
17956 (org-defkey org-mode-map "\M-{" 'org-backward-element)
17957 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
17958 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
17959 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
17960 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
17961 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17962 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17963 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17964 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
17965 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17966 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17967 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17968 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17969 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17970 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17971 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17972 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17973 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17974 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17975 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17976 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17977 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17978 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17979 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17980 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17981 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17982 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17983 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17984 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17985 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17986 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
17987 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17988 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17989 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17990 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17991 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17992 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17993 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17994 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17995 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17996 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17997 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17998 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17999 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18000 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18001 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18002 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18003 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18004 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18005 (org-defkey org-mode-map "\C-c^" 'org-sort)
18006 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18007 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18008 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18009 (org-defkey org-mode-map "\C-m" 'org-return)
18010 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18011 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18012 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18013 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18014 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18015 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18016 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18017 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18018 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18019 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18020 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18021 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18022 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18023 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18024 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18025 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18026 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18027 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18028 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18029 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18030 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18031 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18032 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18034 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18035 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18036 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18038 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18039 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18040 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18041 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18042 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18043 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18044 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18045 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18046 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18047 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18048 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18049 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18050 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18051 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18052 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18053 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18054 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18055 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18056 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18057 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18058 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18059 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18061 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18062 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18063 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18064 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18065 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18067 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18069 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18071 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18072 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18074 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18077 (when (featurep 'xemacs)
18078 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18081 (defconst org-speed-commands-default
18083 ("Outline Navigation")
18084 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18085 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18086 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18087 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18088 ("u" . (org-speed-move-safe 'outline-up-heading))
18089 ("j" . org-goto)
18090 ("g" . (org-refile t))
18091 ("Outline Visibility")
18092 ("c" . org-cycle)
18093 ("C" . org-shifttab)
18094 (" " . org-display-outline-path)
18095 ("=" . org-columns)
18096 ("Outline Structure Editing")
18097 ("U" . org-shiftmetaup)
18098 ("D" . org-shiftmetadown)
18099 ("r" . org-metaright)
18100 ("l" . org-metaleft)
18101 ("R" . org-shiftmetaright)
18102 ("L" . org-shiftmetaleft)
18103 ("i" . (progn (forward-char 1) (call-interactively
18104 'org-insert-heading-respect-content)))
18105 ("^" . org-sort)
18106 ("w" . org-refile)
18107 ("a" . org-archive-subtree-default-with-confirmation)
18108 ("." . org-mark-subtree)
18109 ("#" . org-toggle-comment)
18110 ("Clock Commands")
18111 ("I" . org-clock-in)
18112 ("O" . org-clock-out)
18113 ("Meta Data Editing")
18114 ("t" . org-todo)
18115 ("," . (org-priority))
18116 ("0" . (org-priority ?\ ))
18117 ("1" . (org-priority ?A))
18118 ("2" . (org-priority ?B))
18119 ("3" . (org-priority ?C))
18120 (":" . org-set-tags-command)
18121 ("e" . org-set-effort)
18122 ("E" . org-inc-effort)
18123 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18124 (org-entry-put (point) "APPT_WARNTIME" m)))
18125 ("Agenda Views etc")
18126 ("v" . org-agenda)
18127 ("/" . org-sparse-tree)
18128 ("Misc")
18129 ("o" . org-open-at-point)
18130 ("?" . org-speed-command-help)
18131 ("<" . (org-agenda-set-restriction-lock 'subtree))
18132 (">" . (org-agenda-remove-restriction-lock))
18134 "The default speed commands.")
18136 (defun org-print-speed-command (e)
18137 (if (> (length (car e)) 1)
18138 (progn
18139 (princ "\n")
18140 (princ (car e))
18141 (princ "\n")
18142 (princ (make-string (length (car e)) ?-))
18143 (princ "\n"))
18144 (princ (car e))
18145 (princ " ")
18146 (if (symbolp (cdr e))
18147 (princ (symbol-name (cdr e)))
18148 (prin1 (cdr e)))
18149 (princ "\n")))
18151 (defun org-speed-command-help ()
18152 "Show the available speed commands."
18153 (interactive)
18154 (if (not org-use-speed-commands)
18155 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18156 (with-output-to-temp-buffer "*Help*"
18157 (princ "User-defined Speed commands\n===========================\n")
18158 (mapc 'org-print-speed-command org-speed-commands-user)
18159 (princ "\n")
18160 (princ "Built-in Speed commands\n=======================\n")
18161 (mapc 'org-print-speed-command org-speed-commands-default))
18162 (with-current-buffer "*Help*"
18163 (setq truncate-lines t))))
18165 (defun org-speed-move-safe (cmd)
18166 "Execute CMD, but make sure that the cursor always ends up in a headline.
18167 If not, return to the original position and throw an error."
18168 (interactive)
18169 (let ((pos (point)))
18170 (call-interactively cmd)
18171 (unless (and (bolp) (org-at-heading-p))
18172 (goto-char pos)
18173 (error "Boundary reached while executing %s" cmd))))
18175 (defvar org-self-insert-command-undo-counter 0)
18177 (defvar org-table-auto-blank-field) ; defined in org-table.el
18178 (defvar org-speed-command nil)
18180 (org-define-obsolete-function-alias
18181 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18183 (defun org-speed-command-activate (keys)
18184 "Hook for activating single-letter speed commands.
18185 `org-speed-commands-default' specifies a minimal command set.
18186 Use `org-speed-commands-user' for further customization."
18187 (when (or (and (bolp) (looking-at org-outline-regexp))
18188 (and (functionp org-use-speed-commands)
18189 (funcall org-use-speed-commands)))
18190 (cdr (assoc keys (append org-speed-commands-user
18191 org-speed-commands-default)))))
18193 (org-define-obsolete-function-alias
18194 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18196 (defun org-babel-speed-command-activate (keys)
18197 "Hook for activating single-letter code block commands."
18198 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18199 (cdr (assoc keys org-babel-key-bindings))))
18201 (defcustom org-speed-command-hook
18202 '(org-speed-command-default-hook org-babel-speed-command-hook)
18203 "Hook for activating speed commands at strategic locations.
18204 Hook functions are called in sequence until a valid handler is
18205 found.
18207 Each hook takes a single argument, a user-pressed command key
18208 which is also a `self-insert-command' from the global map.
18210 Within the hook, examine the cursor position and the command key
18211 and return nil or a valid handler as appropriate. Handler could
18212 be one of an interactive command, a function, or a form.
18214 Set `org-use-speed-commands' to non-nil value to enable this
18215 hook. The default setting is `org-speed-command-activate'."
18216 :group 'org-structure
18217 :version "24.1"
18218 :type 'hook)
18220 (defun org-self-insert-command (N)
18221 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18222 If the cursor is in a table looking at whitespace, the whitespace is
18223 overwritten, and the table is not marked as requiring realignment."
18224 (interactive "p")
18225 (org-check-before-invisible-edit 'insert)
18226 (cond
18227 ((and org-use-speed-commands
18228 (setq org-speed-command
18229 (run-hook-with-args-until-success
18230 'org-speed-command-hook (this-command-keys))))
18231 (cond
18232 ((commandp org-speed-command)
18233 (setq this-command org-speed-command)
18234 (call-interactively org-speed-command))
18235 ((functionp org-speed-command)
18236 (funcall org-speed-command))
18237 ((and org-speed-command (listp org-speed-command))
18238 (eval org-speed-command))
18239 (t (let (org-use-speed-commands)
18240 (call-interactively 'org-self-insert-command)))))
18241 ((and
18242 (org-table-p)
18243 (progn
18244 ;; check if we blank the field, and if that triggers align
18245 (and (featurep 'org-table) org-table-auto-blank-field
18246 (member last-command
18247 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18248 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18249 ;; got extra space, this field does not determine column width
18250 (let (org-table-may-need-update) (org-table-blank-field))
18251 ;; no extra space, this field may determine column width
18252 (org-table-blank-field)))
18254 (eq N 1)
18255 (looking-at "[^|\n]* |"))
18256 (let (org-table-may-need-update)
18257 (goto-char (1- (match-end 0)))
18258 (backward-delete-char 1)
18259 (goto-char (match-beginning 0))
18260 (self-insert-command N)))
18262 (setq org-table-may-need-update t)
18263 (self-insert-command N)
18264 (org-fix-tags-on-the-fly)
18265 (if org-self-insert-cluster-for-undo
18266 (if (not (eq last-command 'org-self-insert-command))
18267 (setq org-self-insert-command-undo-counter 1)
18268 (if (>= org-self-insert-command-undo-counter 20)
18269 (setq org-self-insert-command-undo-counter 1)
18270 (and (> org-self-insert-command-undo-counter 0)
18271 buffer-undo-list (listp buffer-undo-list)
18272 (not (cadr buffer-undo-list)) ; remove nil entry
18273 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18274 (setq org-self-insert-command-undo-counter
18275 (1+ org-self-insert-command-undo-counter))))))))
18277 (defun org-check-before-invisible-edit (kind)
18278 "Check is editing if kind KIND would be dangerous with invisible text around.
18279 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18280 ;; First, try to get out of here as quickly as possible, to reduce overhead
18281 (if (and org-catch-invisible-edits
18282 (or (not (boundp 'visible-mode)) (not visible-mode))
18283 (or (get-char-property (point) 'invisible)
18284 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18285 ;; OK, we need to take a closer look
18286 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18287 (invisible-before-point (if (bobp) nil (get-char-property
18288 (1- (point)) 'invisible)))
18289 (border-and-ok-direction
18291 ;; Check if we are acting predictably before invisible text
18292 (and invisible-at-point (not invisible-before-point)
18293 (memq kind '(insert delete-backward)))
18294 ;; Check if we are acting predictably after invisible text
18295 ;; This works not well, and I have turned it off. It seems
18296 ;; better to always show and stop after invisible text.
18297 ;; (and (not invisible-at-point) invisible-before-point
18298 ;; (memq kind '(insert delete)))
18300 (when (or (memq invisible-at-point '(outline org-hide-block t))
18301 (memq invisible-before-point '(outline org-hide-block t)))
18302 (if (eq org-catch-invisible-edits 'error)
18303 (error "Editing in invisible areas is prohibited - make visible first"))
18304 (if (and org-custom-properties-overlays
18305 (y-or-n-p "Display invisible properties in this buffer? "))
18306 (org-toggle-custom-properties-visibility)
18307 ;; Make the area visible
18308 (save-excursion
18309 (if invisible-before-point
18310 (goto-char (previous-single-char-property-change
18311 (point) 'invisible)))
18312 (org-cycle))
18313 (cond
18314 ((eq org-catch-invisible-edits 'show)
18315 ;; That's it, we do the edit after showing
18316 (message
18317 "Unfolding invisible region around point before editing")
18318 (sit-for 1))
18319 ((and (eq org-catch-invisible-edits 'smart)
18320 border-and-ok-direction)
18321 (message "Unfolding invisible region around point before editing"))
18323 ;; Don't do the edit, make the user repeat it in full visibility
18324 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18326 (defun org-fix-tags-on-the-fly ()
18327 (when (and (equal (char-after (point-at-bol)) ?*)
18328 (org-at-heading-p))
18329 (org-align-tags-here org-tags-column)))
18331 (defun org-delete-backward-char (N)
18332 "Like `delete-backward-char', insert whitespace at field end in tables.
18333 When deleting backwards, in tables this function will insert whitespace in
18334 front of the next \"|\" separator, to keep the table aligned. The table will
18335 still be marked for re-alignment if the field did fill the entire column,
18336 because, in this case the deletion might narrow the column."
18337 (interactive "p")
18338 (save-match-data
18339 (org-check-before-invisible-edit 'delete-backward)
18340 (if (and (org-table-p)
18341 (eq N 1)
18342 (string-match "|" (buffer-substring (point-at-bol) (point)))
18343 (looking-at ".*?|"))
18344 (let ((pos (point))
18345 (noalign (looking-at "[^|\n\r]* |"))
18346 (c org-table-may-need-update))
18347 (backward-delete-char N)
18348 (if (not overwrite-mode)
18349 (progn
18350 (skip-chars-forward "^|")
18351 (insert " ")
18352 (goto-char (1- pos))))
18353 ;; noalign: if there were two spaces at the end, this field
18354 ;; does not determine the width of the column.
18355 (if noalign (setq org-table-may-need-update c)))
18356 (backward-delete-char N)
18357 (org-fix-tags-on-the-fly))))
18359 (defun org-delete-char (N)
18360 "Like `delete-char', but insert whitespace at field end in tables.
18361 When deleting characters, in tables this function will insert whitespace in
18362 front of the next \"|\" separator, to keep the table aligned. The table will
18363 still be marked for re-alignment if the field did fill the entire column,
18364 because, in this case the deletion might narrow the column."
18365 (interactive "p")
18366 (save-match-data
18367 (org-check-before-invisible-edit 'delete)
18368 (if (and (org-table-p)
18369 (not (bolp))
18370 (not (= (char-after) ?|))
18371 (eq N 1))
18372 (if (looking-at ".*?|")
18373 (let ((pos (point))
18374 (noalign (looking-at "[^|\n\r]* |"))
18375 (c org-table-may-need-update))
18376 (replace-match (concat
18377 (substring (match-string 0) 1 -1)
18378 " |"))
18379 (goto-char pos)
18380 ;; noalign: if there were two spaces at the end, this field
18381 ;; does not determine the width of the column.
18382 (if noalign (setq org-table-may-need-update c)))
18383 (delete-char N))
18384 (delete-char N)
18385 (org-fix-tags-on-the-fly))))
18387 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18388 (put 'org-self-insert-command 'delete-selection t)
18389 (put 'orgtbl-self-insert-command 'delete-selection t)
18390 (put 'org-delete-char 'delete-selection 'supersede)
18391 (put 'org-delete-backward-char 'delete-selection 'supersede)
18392 (put 'org-yank 'delete-selection 'yank)
18394 ;; Make `flyspell-mode' delay after some commands
18395 (put 'org-self-insert-command 'flyspell-delayed t)
18396 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18397 (put 'org-delete-char 'flyspell-delayed t)
18398 (put 'org-delete-backward-char 'flyspell-delayed t)
18400 ;; Make pabbrev-mode expand after org-mode commands
18401 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18402 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18404 ;; How to do this: Measure non-white length of current string
18405 ;; If equal to column width, we should realign.
18407 (defun org-remap (map &rest commands)
18408 "In MAP, remap the functions given in COMMANDS.
18409 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18410 (let (new old)
18411 (while commands
18412 (setq old (pop commands) new (pop commands))
18413 (if (fboundp 'command-remapping)
18414 (org-defkey map (vector 'remap old) new)
18415 (substitute-key-definition old new map global-map)))))
18417 (when (eq org-enable-table-editor 'optimized)
18418 ;; If the user wants maximum table support, we need to hijack
18419 ;; some standard editing functions
18420 (org-remap org-mode-map
18421 'self-insert-command 'org-self-insert-command
18422 'delete-char 'org-delete-char
18423 'delete-backward-char 'org-delete-backward-char)
18424 (org-defkey org-mode-map "|" 'org-force-self-insert))
18426 (defvar org-ctrl-c-ctrl-c-hook nil
18427 "Hook for functions attaching themselves to `C-c C-c'.
18429 This can be used to add additional functionality to the C-c C-c
18430 key which executes context-dependent commands. This hook is run
18431 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18432 run after the last test.
18434 Each function will be called with no arguments. The function
18435 must check if the context is appropriate for it to act. If yes,
18436 it should do its thing and then return a non-nil value. If the
18437 context is wrong, just do nothing and return nil.")
18439 (defvar org-ctrl-c-ctrl-c-final-hook nil
18440 "Hook for functions attaching themselves to `C-c C-c'.
18442 This can be used to add additional functionality to the C-c C-c
18443 key which executes context-dependent commands. This hook is run
18444 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18445 before the first test.
18447 Each function will be called with no arguments. The function
18448 must check if the context is appropriate for it to act. If yes,
18449 it should do its thing and then return a non-nil value. If the
18450 context is wrong, just do nothing and return nil.")
18452 (defvar org-tab-first-hook nil
18453 "Hook for functions to attach themselves to TAB.
18454 See `org-ctrl-c-ctrl-c-hook' for more information.
18455 This hook runs as the first action when TAB is pressed, even before
18456 `org-cycle' messes around with the `outline-regexp' to cater for
18457 inline tasks and plain list item folding.
18458 If any function in this hook returns t, any other actions that
18459 would have been caused by TAB (such as table field motion or visibility
18460 cycling) will not occur.")
18462 (defvar org-tab-after-check-for-table-hook nil
18463 "Hook for functions to attach themselves to TAB.
18464 See `org-ctrl-c-ctrl-c-hook' for more information.
18465 This hook runs after it has been established that the cursor is not in a
18466 table, but before checking if the cursor is in a headline or if global cycling
18467 should be done.
18468 If any function in this hook returns t, not other actions like visibility
18469 cycling will be done.")
18471 (defvar org-tab-after-check-for-cycling-hook nil
18472 "Hook for functions to attach themselves to TAB.
18473 See `org-ctrl-c-ctrl-c-hook' for more information.
18474 This hook runs after it has been established that not table field motion and
18475 not visibility should be done because of current context. This is probably
18476 the place where a package like yasnippets can hook in.")
18478 (defvar org-tab-before-tab-emulation-hook nil
18479 "Hook for functions to attach themselves to TAB.
18480 See `org-ctrl-c-ctrl-c-hook' for more information.
18481 This hook runs after every other options for TAB have been exhausted, but
18482 before indentation and \t insertion takes place.")
18484 (defvar org-metaleft-hook nil
18485 "Hook for functions attaching themselves to `M-left'.
18486 See `org-ctrl-c-ctrl-c-hook' for more information.")
18487 (defvar org-metaright-hook nil
18488 "Hook for functions attaching themselves to `M-right'.
18489 See `org-ctrl-c-ctrl-c-hook' for more information.")
18490 (defvar org-metaup-hook nil
18491 "Hook for functions attaching themselves to `M-up'.
18492 See `org-ctrl-c-ctrl-c-hook' for more information.")
18493 (defvar org-metadown-hook nil
18494 "Hook for functions attaching themselves to `M-down'.
18495 See `org-ctrl-c-ctrl-c-hook' for more information.")
18496 (defvar org-shiftmetaleft-hook nil
18497 "Hook for functions attaching themselves to `M-S-left'.
18498 See `org-ctrl-c-ctrl-c-hook' for more information.")
18499 (defvar org-shiftmetaright-hook nil
18500 "Hook for functions attaching themselves to `M-S-right'.
18501 See `org-ctrl-c-ctrl-c-hook' for more information.")
18502 (defvar org-shiftmetaup-hook nil
18503 "Hook for functions attaching themselves to `M-S-up'.
18504 See `org-ctrl-c-ctrl-c-hook' for more information.")
18505 (defvar org-shiftmetadown-hook nil
18506 "Hook for functions attaching themselves to `M-S-down'.
18507 See `org-ctrl-c-ctrl-c-hook' for more information.")
18508 (defvar org-metareturn-hook nil
18509 "Hook for functions attaching themselves to `M-RET'.
18510 See `org-ctrl-c-ctrl-c-hook' for more information.")
18511 (defvar org-shiftup-hook nil
18512 "Hook for functions attaching themselves to `S-up'.
18513 See `org-ctrl-c-ctrl-c-hook' for more information.")
18514 (defvar org-shiftup-final-hook nil
18515 "Hook for functions attaching themselves to `S-up'.
18516 This one runs after all other options except shift-select have been excluded.
18517 See `org-ctrl-c-ctrl-c-hook' for more information.")
18518 (defvar org-shiftdown-hook nil
18519 "Hook for functions attaching themselves to `S-down'.
18520 See `org-ctrl-c-ctrl-c-hook' for more information.")
18521 (defvar org-shiftdown-final-hook nil
18522 "Hook for functions attaching themselves to `S-down'.
18523 This one runs after all other options except shift-select have been excluded.
18524 See `org-ctrl-c-ctrl-c-hook' for more information.")
18525 (defvar org-shiftleft-hook nil
18526 "Hook for functions attaching themselves to `S-left'.
18527 See `org-ctrl-c-ctrl-c-hook' for more information.")
18528 (defvar org-shiftleft-final-hook nil
18529 "Hook for functions attaching themselves to `S-left'.
18530 This one runs after all other options except shift-select have been excluded.
18531 See `org-ctrl-c-ctrl-c-hook' for more information.")
18532 (defvar org-shiftright-hook nil
18533 "Hook for functions attaching themselves to `S-right'.
18534 See `org-ctrl-c-ctrl-c-hook' for more information.")
18535 (defvar org-shiftright-final-hook nil
18536 "Hook for functions attaching themselves to `S-right'.
18537 This one runs after all other options except shift-select have been excluded.
18538 See `org-ctrl-c-ctrl-c-hook' for more information.")
18540 (defun org-modifier-cursor-error ()
18541 "Throw an error, a modified cursor command was applied in wrong context."
18542 (error "This command is active in special context like tables, headlines or items"))
18544 (defun org-shiftselect-error ()
18545 "Throw an error because Shift-Cursor command was applied in wrong context."
18546 (if (and (boundp 'shift-select-mode) shift-select-mode)
18547 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18548 (error "This command works only in special context like headlines or timestamps")))
18550 (defun org-call-for-shift-select (cmd)
18551 (let ((this-command-keys-shift-translated t))
18552 (call-interactively cmd)))
18554 (defun org-shifttab (&optional arg)
18555 "Global visibility cycling or move to previous table field.
18556 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18557 on context.
18558 See the individual commands for more information."
18559 (interactive "P")
18560 (cond
18561 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18562 ((integerp arg)
18563 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18564 (message "Content view to level: %d" arg)
18565 (org-content (prefix-numeric-value arg2))
18566 (setq org-cycle-global-status 'overview)))
18567 (t (call-interactively 'org-global-cycle))))
18569 (defun org-shiftmetaleft ()
18570 "Promote subtree or delete table column.
18571 Calls `org-promote-subtree', `org-outdent-item-tree', or
18572 `org-table-delete-column', depending on context. See the
18573 individual commands for more information."
18574 (interactive)
18575 (cond
18576 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18577 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18578 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18579 ((if (not (org-region-active-p)) (org-at-item-p)
18580 (save-excursion (goto-char (region-beginning))
18581 (org-at-item-p)))
18582 (call-interactively 'org-outdent-item-tree))
18583 (t (org-modifier-cursor-error))))
18585 (defun org-shiftmetaright ()
18586 "Demote subtree or insert table column.
18587 Calls `org-demote-subtree', `org-indent-item-tree', or
18588 `org-table-insert-column', depending on context. See the
18589 individual commands for more information."
18590 (interactive)
18591 (cond
18592 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18593 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18594 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18595 ((if (not (org-region-active-p)) (org-at-item-p)
18596 (save-excursion (goto-char (region-beginning))
18597 (org-at-item-p)))
18598 (call-interactively 'org-indent-item-tree))
18599 (t (org-modifier-cursor-error))))
18601 (defun org-shiftmetaup (&optional arg)
18602 "Move subtree up or kill table row.
18603 Calls `org-move-subtree-up' or `org-table-kill-row' or
18604 `org-move-item-up' or `org-timestamp-up', depending on context.
18605 See the individual commands for more information."
18606 (interactive "P")
18607 (cond
18608 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18609 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18610 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18611 ((org-at-item-p) (call-interactively 'org-move-item-up))
18612 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18613 (call-interactively 'org-timestamp-up)))
18614 (t (org-modifier-cursor-error))))
18616 (defun org-shiftmetadown (&optional arg)
18617 "Move subtree down or insert table row.
18618 Calls `org-move-subtree-down' or `org-table-insert-row' or
18619 `org-move-item-down' or `org-timestamp-up', depending on context.
18620 See the individual commands for more information."
18621 (interactive "P")
18622 (cond
18623 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18624 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18625 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18626 ((org-at-item-p) (call-interactively 'org-move-item-down))
18627 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18628 (call-interactively 'org-timestamp-down)))
18629 (t (org-modifier-cursor-error))))
18631 (defsubst org-hidden-tree-error ()
18632 (error
18633 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18635 (defun org-metaleft (&optional arg)
18636 "Promote heading or move table column to left.
18637 Calls `org-do-promote' or `org-table-move-column', depending on context.
18638 With no specific context, calls the Emacs default `backward-word'.
18639 See the individual commands for more information."
18640 (interactive "P")
18641 (cond
18642 ((run-hook-with-args-until-success 'org-metaleft-hook))
18643 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18644 ((org-with-limited-levels
18645 (or (org-at-heading-p)
18646 (and (org-region-active-p)
18647 (save-excursion
18648 (goto-char (region-beginning))
18649 (org-at-heading-p)))))
18650 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18651 (call-interactively 'org-do-promote))
18652 ;; At an inline task.
18653 ((org-at-heading-p)
18654 (call-interactively 'org-inlinetask-promote))
18655 ((or (org-at-item-p)
18656 (and (org-region-active-p)
18657 (save-excursion
18658 (goto-char (region-beginning))
18659 (org-at-item-p))))
18660 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18661 (call-interactively 'org-outdent-item))
18662 (t (call-interactively 'backward-word))))
18664 (defun org-metaright (&optional arg)
18665 "Demote a subtree, a list item or move table column to right.
18666 In front of a drawer or a block keyword, indent it correctly.
18667 With no specific context, calls the Emacs default `forward-word'.
18668 See the individual commands for more information."
18669 (interactive "P")
18670 (cond
18671 ((run-hook-with-args-until-success 'org-metaright-hook))
18672 ((org-at-table-p) (call-interactively 'org-table-move-column))
18673 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18674 ((org-at-block-p) (call-interactively 'org-indent-block))
18675 ((org-with-limited-levels
18676 (or (org-at-heading-p)
18677 (and (org-region-active-p)
18678 (save-excursion
18679 (goto-char (region-beginning))
18680 (org-at-heading-p)))))
18681 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18682 (call-interactively 'org-do-demote))
18683 ;; At an inline task.
18684 ((org-at-heading-p)
18685 (call-interactively 'org-inlinetask-demote))
18686 ((or (org-at-item-p)
18687 (and (org-region-active-p)
18688 (save-excursion
18689 (goto-char (region-beginning))
18690 (org-at-item-p))))
18691 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18692 (call-interactively 'org-indent-item))
18693 (t (call-interactively 'forward-word))))
18695 (defun org-check-for-hidden (what)
18696 "Check if there are hidden headlines/items in the current visual line.
18697 WHAT can be either `headlines' or `items'. If the current line is
18698 an outline or item heading and it has a folded subtree below it,
18699 this function returns t, nil otherwise."
18700 (let ((re (cond
18701 ((eq what 'headlines) org-outline-regexp-bol)
18702 ((eq what 'items) (org-item-beginning-re))
18703 (t (error "This should not happen"))))
18704 beg end)
18705 (save-excursion
18706 (catch 'exit
18707 (unless (org-region-active-p)
18708 (setq beg (point-at-bol))
18709 (beginning-of-line 2)
18710 (while (and (not (eobp)) ;; this is like `next-line'
18711 (get-char-property (1- (point)) 'invisible))
18712 (beginning-of-line 2))
18713 (setq end (point))
18714 (goto-char beg)
18715 (goto-char (point-at-eol))
18716 (setq end (max end (point)))
18717 (while (re-search-forward re end t)
18718 (if (get-char-property (match-beginning 0) 'invisible)
18719 (throw 'exit t))))
18720 nil))))
18722 (autoload 'org-element-at-point "org-element")
18723 (autoload 'org-element-type "org-element")
18725 (declare-function org-element-at-point "org-element" (&optional keep-trail))
18726 (declare-function org-element-type "org-element" (element))
18727 (declare-function org-element-contents "org-element" (element))
18728 (declare-function org-element-property "org-element" (property element))
18729 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
18730 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
18731 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
18732 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
18733 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
18735 (defun org-metaup (&optional arg)
18736 "Move subtree up or move table row up.
18737 Calls `org-move-subtree-up' or `org-table-move-row' or
18738 `org-move-item-up', depending on context. See the individual commands
18739 for more information."
18740 (interactive "P")
18741 (cond
18742 ((run-hook-with-args-until-success 'org-metaup-hook))
18743 ((org-region-active-p)
18744 (let* ((a (min (region-beginning) (region-end)))
18745 (b (1- (max (region-beginning) (region-end))))
18746 (c (save-excursion (goto-char a)
18747 (move-beginning-of-line 0)))
18748 (d (save-excursion (goto-char a)
18749 (move-end-of-line 0) (point))))
18750 (transpose-regions a b c d)
18751 (goto-char c)))
18752 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18753 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18754 ((org-at-item-p) (call-interactively 'org-move-item-up))
18755 (t (org-drag-element-backward))))
18757 (defun org-metadown (&optional arg)
18758 "Move subtree down or move table row down.
18759 Calls `org-move-subtree-down' or `org-table-move-row' or
18760 `org-move-item-down', depending on context. See the individual
18761 commands for more information."
18762 (interactive "P")
18763 (cond
18764 ((run-hook-with-args-until-success 'org-metadown-hook))
18765 ((org-region-active-p)
18766 (let* ((a (min (region-beginning) (region-end)))
18767 (b (max (region-beginning) (region-end)))
18768 (c (save-excursion (goto-char b)
18769 (move-beginning-of-line 1)))
18770 (d (save-excursion (goto-char b)
18771 (move-end-of-line 1) (1+ (point)))))
18772 (transpose-regions a b c d)
18773 (goto-char d)))
18774 ((org-at-table-p) (call-interactively 'org-table-move-row))
18775 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18776 ((org-at-item-p) (call-interactively 'org-move-item-down))
18777 (t (org-drag-element-forward))))
18779 (defun org-shiftup (&optional arg)
18780 "Increase item in timestamp or increase priority of current headline.
18781 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18782 depending on context. See the individual commands for more information."
18783 (interactive "P")
18784 (cond
18785 ((run-hook-with-args-until-success 'org-shiftup-hook))
18786 ((and org-support-shift-select (org-region-active-p))
18787 (org-call-for-shift-select 'previous-line))
18788 ((org-at-timestamp-p t)
18789 (call-interactively (if org-edit-timestamp-down-means-later
18790 'org-timestamp-down 'org-timestamp-up)))
18791 ((and (not (eq org-support-shift-select 'always))
18792 org-enable-priority-commands
18793 (org-at-heading-p))
18794 (call-interactively 'org-priority-up))
18795 ((and (not org-support-shift-select) (org-at-item-p))
18796 (call-interactively 'org-previous-item))
18797 ((org-clocktable-try-shift 'up arg))
18798 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18799 (org-support-shift-select
18800 (org-call-for-shift-select 'previous-line))
18801 (t (org-shiftselect-error))))
18803 (defun org-shiftdown (&optional arg)
18804 "Decrease item in timestamp or decrease priority of current headline.
18805 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18806 depending on context. See the individual commands for more information."
18807 (interactive "P")
18808 (cond
18809 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18810 ((and org-support-shift-select (org-region-active-p))
18811 (org-call-for-shift-select 'next-line))
18812 ((org-at-timestamp-p t)
18813 (call-interactively (if org-edit-timestamp-down-means-later
18814 'org-timestamp-up 'org-timestamp-down)))
18815 ((and (not (eq org-support-shift-select 'always))
18816 org-enable-priority-commands
18817 (org-at-heading-p))
18818 (call-interactively 'org-priority-down))
18819 ((and (not org-support-shift-select) (org-at-item-p))
18820 (call-interactively 'org-next-item))
18821 ((org-clocktable-try-shift 'down arg))
18822 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18823 (org-support-shift-select
18824 (org-call-for-shift-select 'next-line))
18825 (t (org-shiftselect-error))))
18827 (defun org-shiftright (&optional arg)
18828 "Cycle the thing at point or in the current line, depending on context.
18829 Depending on context, this does one of the following:
18831 - switch a timestamp at point one day into the future
18832 - on a headline, switch to the next TODO keyword.
18833 - on an item, switch entire list to the next bullet type
18834 - on a property line, switch to the next allowed value
18835 - on a clocktable definition line, move time block into the future"
18836 (interactive "P")
18837 (cond
18838 ((run-hook-with-args-until-success 'org-shiftright-hook))
18839 ((and org-support-shift-select (org-region-active-p))
18840 (org-call-for-shift-select 'forward-char))
18841 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18842 ((and (not (eq org-support-shift-select 'always))
18843 (org-at-heading-p))
18844 (let ((org-inhibit-logging
18845 (not org-treat-S-cursor-todo-selection-as-state-change))
18846 (org-inhibit-blocking
18847 (not org-treat-S-cursor-todo-selection-as-state-change)))
18848 (org-call-with-arg 'org-todo 'right)))
18849 ((or (and org-support-shift-select
18850 (not (eq org-support-shift-select 'always))
18851 (org-at-item-bullet-p))
18852 (and (not org-support-shift-select) (org-at-item-p)))
18853 (org-call-with-arg 'org-cycle-list-bullet nil))
18854 ((and (not (eq org-support-shift-select 'always))
18855 (org-at-property-p))
18856 (call-interactively 'org-property-next-allowed-value))
18857 ((org-clocktable-try-shift 'right arg))
18858 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18859 (org-support-shift-select
18860 (org-call-for-shift-select 'forward-char))
18861 (t (org-shiftselect-error))))
18863 (defun org-shiftleft (&optional arg)
18864 "Cycle the thing at point or in the current line, depending on context.
18865 Depending on context, this does one of the following:
18867 - switch a timestamp at point one day into the past
18868 - on a headline, switch to the previous TODO keyword.
18869 - on an item, switch entire list to the previous bullet type
18870 - on a property line, switch to the previous allowed value
18871 - on a clocktable definition line, move time block into the past"
18872 (interactive "P")
18873 (cond
18874 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18875 ((and org-support-shift-select (org-region-active-p))
18876 (org-call-for-shift-select 'backward-char))
18877 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18878 ((and (not (eq org-support-shift-select 'always))
18879 (org-at-heading-p))
18880 (let ((org-inhibit-logging
18881 (not org-treat-S-cursor-todo-selection-as-state-change))
18882 (org-inhibit-blocking
18883 (not org-treat-S-cursor-todo-selection-as-state-change)))
18884 (org-call-with-arg 'org-todo 'left)))
18885 ((or (and org-support-shift-select
18886 (not (eq org-support-shift-select 'always))
18887 (org-at-item-bullet-p))
18888 (and (not org-support-shift-select) (org-at-item-p)))
18889 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18890 ((and (not (eq org-support-shift-select 'always))
18891 (org-at-property-p))
18892 (call-interactively 'org-property-previous-allowed-value))
18893 ((org-clocktable-try-shift 'left arg))
18894 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18895 (org-support-shift-select
18896 (org-call-for-shift-select 'backward-char))
18897 (t (org-shiftselect-error))))
18899 (defun org-shiftcontrolright ()
18900 "Switch to next TODO set."
18901 (interactive)
18902 (cond
18903 ((and org-support-shift-select (org-region-active-p))
18904 (org-call-for-shift-select 'forward-word))
18905 ((and (not (eq org-support-shift-select 'always))
18906 (org-at-heading-p))
18907 (org-call-with-arg 'org-todo 'nextset))
18908 (org-support-shift-select
18909 (org-call-for-shift-select 'forward-word))
18910 (t (org-shiftselect-error))))
18912 (defun org-shiftcontrolleft ()
18913 "Switch to previous TODO set."
18914 (interactive)
18915 (cond
18916 ((and org-support-shift-select (org-region-active-p))
18917 (org-call-for-shift-select 'backward-word))
18918 ((and (not (eq org-support-shift-select 'always))
18919 (org-at-heading-p))
18920 (org-call-with-arg 'org-todo 'previousset))
18921 (org-support-shift-select
18922 (org-call-for-shift-select 'backward-word))
18923 (t (org-shiftselect-error))))
18925 (defun org-shiftcontrolup ()
18926 "Change timestamps synchronously up in CLOCK log lines."
18927 (interactive)
18928 (cond ((and (not org-support-shift-select)
18929 (org-at-clock-log-p)
18930 (org-at-timestamp-p t))
18931 (org-clock-timestamps-up))
18932 (t (org-shiftselect-error))))
18934 (defun org-shiftcontroldown ()
18935 "Change timestamps synchronously down in CLOCK log lines."
18936 (interactive)
18937 (cond ((and (not org-support-shift-select)
18938 (org-at-clock-log-p)
18939 (org-at-timestamp-p t))
18940 (org-clock-timestamps-down))
18941 (t (org-shiftselect-error))))
18943 (defun org-ctrl-c-ret ()
18944 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18945 (interactive)
18946 (cond
18947 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18948 (t (call-interactively 'org-insert-heading))))
18950 (defun org-find-visible ()
18951 (let ((s (point)))
18952 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18953 (get-char-property s 'invisible)))
18955 (defun org-find-invisible ()
18956 (let ((s (point)))
18957 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18958 (not (get-char-property s 'invisible))))
18961 (defun org-copy-visible (beg end)
18962 "Copy the visible parts of the region."
18963 (interactive "r")
18964 (let (snippets s)
18965 (save-excursion
18966 (save-restriction
18967 (narrow-to-region beg end)
18968 (setq s (goto-char (point-min)))
18969 (while (not (= (point) (point-max)))
18970 (goto-char (org-find-invisible))
18971 (push (buffer-substring s (point)) snippets)
18972 (setq s (goto-char (org-find-visible))))))
18973 (kill-new (apply 'concat (nreverse snippets)))))
18975 (defun org-copy-special ()
18976 "Copy region in table or copy current subtree.
18977 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18978 See the individual commands for more information."
18979 (interactive)
18980 (call-interactively
18981 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18983 (defun org-cut-special ()
18984 "Cut region in table or cut current subtree.
18985 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18986 See the individual commands for more information."
18987 (interactive)
18988 (call-interactively
18989 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18991 (defun org-paste-special (arg)
18992 "Paste rectangular region into table, or past subtree relative to level.
18993 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18994 See the individual commands for more information."
18995 (interactive "P")
18996 (if (org-at-table-p)
18997 (org-table-paste-rectangle)
18998 (org-paste-subtree arg)))
19000 (defsubst org-in-fixed-width-region-p ()
19001 "Is point in a fixed-width region?"
19002 (save-match-data
19003 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19005 (defun org-edit-special (&optional arg)
19006 "Call a special editor for the stuff at point.
19007 When at a table, call the formula editor with `org-table-edit-formulas'.
19008 When in a source code block, call `org-edit-src-code'.
19009 When in a fixed-width region, call `org-edit-fixed-width-region'.
19010 When in an #+include line, visit the included file.
19011 On a link, call `ffap' to visit the link at point.
19012 Otherwise, return a user error."
19013 (interactive)
19014 ;; possibly prep session before editing source
19015 (when (and (org-in-src-block-p) arg)
19016 (let* ((info (org-babel-get-src-block-info))
19017 (lang (nth 0 info))
19018 (params (nth 2 info))
19019 (session (cdr (assoc :session params))))
19020 (when (and info session) ;; we are in a source-code block with a session
19021 (funcall
19022 (intern (concat "org-babel-prep-session:" lang)) session params))))
19023 (cond ;; proceed with `org-edit-special'
19024 ((save-excursion
19025 (beginning-of-line 1)
19026 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19027 (find-file (org-trim (match-string 1))))
19028 ((or (org-at-table-p)
19029 (save-excursion
19030 (beginning-of-line 1)
19031 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19032 (call-interactively 'org-table-edit-formulas))
19033 ((or (org-in-block-p '("src" "example" "latex" "html"))
19034 (org-at-table.el-p))
19035 (org-edit-src-code))
19036 ((org-in-fixed-width-region-p) (org-edit-fixed-width-region))
19037 ((org-at-regexp-p org-any-link-re) (call-interactively 'ffap))
19038 (t (user-error "No special environment to edit here"))))
19040 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19041 (defun org-ctrl-c-ctrl-c (&optional arg)
19042 "Set tags in headline, or update according to changed information at point.
19044 This command does many different things, depending on context:
19046 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19047 this is what we do.
19049 - If the cursor is on a statistics cookie, update it.
19051 - If the cursor is in a headline, prompt for tags and insert them
19052 into the current line, aligned to `org-tags-column'. When called
19053 with prefix arg, realign all tags in the current buffer.
19055 - If the cursor is in one of the special #+KEYWORD lines, this
19056 triggers scanning the buffer for these lines and updating the
19057 information.
19059 - If the cursor is inside a table, realign the table. This command
19060 works even if the automatic table editor has been turned off.
19062 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19063 the entire table.
19065 - If the cursor is at a footnote reference or definition, jump to
19066 the corresponding definition or references, respectively.
19068 - If the cursor is a the beginning of a dynamic block, update it.
19070 - If the current buffer is a capture buffer, close note and file it.
19072 - If the cursor is on a <<<target>>>, update radio targets and
19073 corresponding links in this buffer.
19075 - If the cursor is on a numbered item in a plain list, renumber the
19076 ordered list.
19078 - If the cursor is on a checkbox, toggle it.
19080 - If the cursor is on a code block, evaluate it. The variable
19081 `org-confirm-babel-evaluate' can be used to control prompting
19082 before code block evaluation, by default every code block
19083 evaluation requires confirmation. Code block evaluation can be
19084 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19085 (interactive "P")
19086 (let ((org-enable-table-editor t))
19087 (cond
19088 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19089 org-occur-highlights
19090 org-latex-fragment-image-overlays)
19091 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19092 (org-remove-occur-highlights)
19093 (org-remove-latex-fragment-image-overlays)
19094 (message "Temporary highlights/overlays removed from current buffer"))
19095 ((and (local-variable-p 'org-finish-function (current-buffer))
19096 (fboundp org-finish-function))
19097 (funcall org-finish-function))
19098 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19099 ((org-in-regexp org-ts-regexp-both)
19100 (org-timestamp-change 0 'day))
19101 ((or (looking-at org-property-start-re)
19102 (org-at-property-p))
19103 (call-interactively 'org-property-action))
19104 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19105 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19106 (or (org-at-heading-p) (org-at-item-p)))
19107 (call-interactively 'org-update-statistics-cookies))
19108 ((org-at-heading-p) (call-interactively 'org-set-tags))
19109 ((org-at-table.el-p)
19110 (message "Use C-c ' to edit table.el tables"))
19111 ((org-at-table-p)
19112 (org-table-maybe-eval-formula)
19113 (if arg
19114 (call-interactively 'org-table-recalculate)
19115 (org-table-maybe-recalculate-line))
19116 (call-interactively 'org-table-align)
19117 (orgtbl-send-table 'maybe))
19118 ((or (org-footnote-at-reference-p)
19119 (org-footnote-at-definition-p))
19120 (call-interactively 'org-footnote-action))
19121 ((org-at-item-checkbox-p)
19122 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19123 ;; list only if at top item.
19124 (let* ((cbox (match-string 1))
19125 (struct (org-list-struct))
19126 (old-struct (copy-tree struct))
19127 (parents (org-list-parents-alist struct))
19128 (orderedp (org-entry-get nil "ORDERED"))
19129 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19130 block-item)
19131 ;; Use a light version of `org-toggle-checkbox' to avoid
19132 ;; computing list structure twice.
19133 (let ((new-box (cond
19134 ((equal arg '(16)) "[-]")
19135 ((equal arg '(4)) nil)
19136 ((equal "[X]" cbox) "[ ]")
19137 (t "[X]"))))
19138 (if (and firstp arg)
19139 ;; If at first item of sub-list, remove check-box from
19140 ;; every item at the same level.
19141 (mapc
19142 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19143 (org-list-get-all-items
19144 (point-at-bol) struct (org-list-prevs-alist struct)))
19145 (org-list-set-checkbox (point-at-bol) struct new-box)))
19146 ;; Replicate `org-list-write-struct', while grabbing a return
19147 ;; value from `org-list-struct-fix-box'.
19148 (org-list-struct-fix-ind struct parents 2)
19149 (org-list-struct-fix-item-end struct)
19150 (let ((prevs (org-list-prevs-alist struct)))
19151 (org-list-struct-fix-bul struct prevs)
19152 (org-list-struct-fix-ind struct parents)
19153 (setq block-item
19154 (org-list-struct-fix-box struct parents prevs orderedp)))
19155 (if (equal struct old-struct)
19156 (user-error "Cannot toggle this checkbox (unchecked subitems?)")
19157 (org-list-struct-apply-struct struct old-struct)
19158 (org-update-checkbox-count-maybe))
19159 (when block-item
19160 (message
19161 "Checkboxes were removed due to unchecked box at line %d"
19162 (org-current-line block-item)))
19163 (when firstp (org-list-send-list 'maybe))))
19164 ((org-at-item-p)
19165 ;; Cursor at an item: repair list. Do checkbox related actions
19166 ;; only if function was called with an argument. Send list only
19167 ;; if at top item.
19168 (let* ((struct (org-list-struct))
19169 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19170 old-struct)
19171 (when arg
19172 (setq old-struct (copy-tree struct))
19173 (if firstp
19174 ;; If at first item of sub-list, add check-box to every
19175 ;; item at the same level.
19176 (mapc
19177 (lambda (pos)
19178 (unless (org-list-get-checkbox pos struct)
19179 (org-list-set-checkbox pos struct "[ ]")))
19180 (org-list-get-all-items
19181 (point-at-bol) struct (org-list-prevs-alist struct)))
19182 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19183 (org-list-write-struct
19184 struct (org-list-parents-alist struct) old-struct)
19185 (when arg (org-update-checkbox-count-maybe))
19186 (when firstp (org-list-send-list 'maybe))))
19187 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19188 ;; Dynamic block
19189 (beginning-of-line 1)
19190 (save-excursion (org-update-dblock)))
19191 ((save-excursion
19192 (let ((case-fold-search t))
19193 (beginning-of-line 1)
19194 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19195 (cond
19196 ((or (equal (match-string 1) "TBLFM")
19197 (equal (match-string 1) "tblfm"))
19198 ;; Recalculate the table before this line
19199 (save-excursion
19200 (beginning-of-line 1)
19201 (skip-chars-backward " \r\n\t")
19202 (if (org-at-table-p)
19203 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19205 (let ((org-inhibit-startup-visibility-stuff t)
19206 (org-startup-align-all-tables nil))
19207 (when (boundp 'org-table-coordinate-overlays)
19208 (mapc 'delete-overlay org-table-coordinate-overlays)
19209 (setq org-table-coordinate-overlays nil))
19210 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19211 (message "Local setup has been refreshed"))))
19212 ((org-clock-update-time-maybe))
19214 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19215 (error "C-c C-c can do nothing useful at this location"))))))
19217 (defun org-mode-restart ()
19218 "Restart Org-mode, to scan again for special lines.
19219 Also updates the keyword regular expressions."
19220 (interactive)
19221 (org-mode)
19222 (message "Org-mode restarted"))
19224 (defun org-kill-note-or-show-branches ()
19225 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19226 (interactive)
19227 (if (not org-finish-function)
19228 (progn
19229 (hide-subtree)
19230 (call-interactively 'show-branches))
19231 (let ((org-note-abort t))
19232 (funcall org-finish-function))))
19234 (defun org-return (&optional indent)
19235 "Goto next table row or insert a newline.
19236 Calls `org-table-next-row' or `newline', depending on context.
19237 See the individual commands for more information."
19238 (interactive)
19239 (let (org-ts-what)
19240 (cond
19241 ((or (bobp) (org-in-src-block-p))
19242 (if indent (newline-and-indent) (newline)))
19243 ((org-at-table-p)
19244 (org-table-justify-field-maybe)
19245 (call-interactively 'org-table-next-row))
19246 ;; when `newline-and-indent' is called within a list, make sure
19247 ;; text moved stays inside the item.
19248 ((and (org-in-item-p) indent)
19249 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19250 (progn
19251 (save-match-data (newline))
19252 (org-indent-line-to (length (match-string 0))))
19253 (let ((ind (org-get-indentation)))
19254 (newline)
19255 (if (org-looking-back org-list-end-re)
19256 (org-indent-line)
19257 (org-indent-line-to ind)))))
19258 ((and org-return-follows-link
19259 (org-at-timestamp-p t)
19260 (not (eq org-ts-what 'after)))
19261 (org-follow-timestamp-link))
19262 ((and org-return-follows-link
19263 (let ((tprop (get-text-property (point) 'face)))
19264 (or (eq tprop 'org-link)
19265 (and (listp tprop) (memq 'org-link tprop)))))
19266 (call-interactively 'org-open-at-point))
19267 ((and (org-at-heading-p)
19268 (looking-at
19269 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19270 (org-show-entry)
19271 (end-of-line 1)
19272 (newline))
19273 (t (if indent (newline-and-indent) (newline))))))
19275 (defun org-return-indent ()
19276 "Goto next table row or insert a newline and indent.
19277 Calls `org-table-next-row' or `newline-and-indent', depending on
19278 context. See the individual commands for more information."
19279 (interactive)
19280 (org-return t))
19282 (defun org-ctrl-c-star ()
19283 "Compute table, or change heading status of lines.
19284 Calls `org-table-recalculate' or `org-toggle-heading',
19285 depending on context."
19286 (interactive)
19287 (cond
19288 ((org-at-table-p)
19289 (call-interactively 'org-table-recalculate))
19291 ;; Convert all lines in region to list items
19292 (call-interactively 'org-toggle-heading))))
19294 (defun org-ctrl-c-minus ()
19295 "Insert separator line in table or modify bullet status of line.
19296 Also turns a plain line or a region of lines into list items.
19297 Calls `org-table-insert-hline', `org-toggle-item', or
19298 `org-cycle-list-bullet', depending on context."
19299 (interactive)
19300 (cond
19301 ((org-at-table-p)
19302 (call-interactively 'org-table-insert-hline))
19303 ((org-region-active-p)
19304 (call-interactively 'org-toggle-item))
19305 ((org-in-item-p)
19306 (call-interactively 'org-cycle-list-bullet))
19308 (call-interactively 'org-toggle-item))))
19310 (defun org-toggle-item (arg)
19311 "Convert headings or normal lines to items, items to normal lines.
19312 If there is no active region, only the current line is considered.
19314 If the first non blank line in the region is an headline, convert
19315 all headlines to items, shifting text accordingly.
19317 If it is an item, convert all items to normal lines.
19319 If it is normal text, change region into an item. With a prefix
19320 argument ARG, change each line in region into an item."
19321 (interactive "P")
19322 (let ((shift-text
19323 (function
19324 ;; Shift text in current section to IND, from point to END.
19325 ;; The function leaves point to END line.
19326 (lambda (ind end)
19327 (let ((min-i 1000) (end (copy-marker end)))
19328 ;; First determine the minimum indentation (MIN-I) of
19329 ;; the text.
19330 (save-excursion
19331 (catch 'exit
19332 (while (< (point) end)
19333 (let ((i (org-get-indentation)))
19334 (cond
19335 ;; Skip blank lines and inline tasks.
19336 ((looking-at "^[ \t]*$"))
19337 ((looking-at org-outline-regexp-bol))
19338 ;; We can't find less than 0 indentation.
19339 ((zerop i) (throw 'exit (setq min-i 0)))
19340 ((< i min-i) (setq min-i i))))
19341 (forward-line))))
19342 ;; Then indent each line so that a line indented to
19343 ;; MIN-I becomes indented to IND. Ignore blank lines
19344 ;; and inline tasks in the process.
19345 (let ((delta (- ind min-i)))
19346 (while (< (point) end)
19347 (unless (or (looking-at "^[ \t]*$")
19348 (looking-at org-outline-regexp-bol))
19349 (org-indent-line-to (+ (org-get-indentation) delta)))
19350 (forward-line)))))))
19351 (skip-blanks
19352 (function
19353 ;; Return beginning of first non-blank line, starting from
19354 ;; line at POS.
19355 (lambda (pos)
19356 (save-excursion
19357 (goto-char pos)
19358 (skip-chars-forward " \r\t\n")
19359 (point-at-bol)))))
19360 beg end)
19361 ;; Determine boundaries of changes.
19362 (if (org-region-active-p)
19363 (setq beg (funcall skip-blanks (region-beginning))
19364 end (copy-marker (region-end)))
19365 (setq beg (funcall skip-blanks (point-at-bol))
19366 end (copy-marker (point-at-eol))))
19367 ;; Depending on the starting line, choose an action on the text
19368 ;; between BEG and END.
19369 (org-with-limited-levels
19370 (save-excursion
19371 (goto-char beg)
19372 (cond
19373 ;; Case 1. Start at an item: de-itemize. Note that it only
19374 ;; happens when a region is active: `org-ctrl-c-minus'
19375 ;; would call `org-cycle-list-bullet' otherwise.
19376 ((org-at-item-p)
19377 (while (< (point) end)
19378 (when (org-at-item-p)
19379 (skip-chars-forward " \t")
19380 (delete-region (point) (match-end 0)))
19381 (forward-line)))
19382 ;; Case 2. Start at an heading: convert to items.
19383 ((org-at-heading-p)
19384 (let* ((bul (org-list-bullet-string "-"))
19385 (bul-len (length bul))
19386 ;; Indentation of the first heading. It should be
19387 ;; relative to the indentation of its parent, if any.
19388 (start-ind (save-excursion
19389 (cond
19390 ((not org-adapt-indentation) 0)
19391 ((not (outline-previous-heading)) 0)
19392 (t (length (match-string 0))))))
19393 ;; Level of first heading. Further headings will be
19394 ;; compared to it to determine hierarchy in the list.
19395 (ref-level (org-reduced-level (org-outline-level))))
19396 (while (< (point) end)
19397 (let* ((level (org-reduced-level (org-outline-level)))
19398 (delta (max 0 (- level ref-level))))
19399 ;; If current headline is less indented than the first
19400 ;; one, set it as reference, in order to preserve
19401 ;; subtrees.
19402 (when (< level ref-level) (setq ref-level level))
19403 (replace-match bul t t)
19404 (org-indent-line-to (+ start-ind (* delta bul-len)))
19405 ;; Ensure all text down to END (or SECTION-END) belongs
19406 ;; to the newly created item.
19407 (let ((section-end (save-excursion
19408 (or (outline-next-heading) (point)))))
19409 (forward-line)
19410 (funcall shift-text
19411 (+ start-ind (* (1+ delta) bul-len))
19412 (min end section-end)))))))
19413 ;; Case 3. Normal line with ARG: turn each non-item line into
19414 ;; an item.
19415 (arg
19416 (while (< (point) end)
19417 (unless (or (org-at-heading-p) (org-at-item-p))
19418 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19419 (replace-match
19420 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19421 (forward-line)))
19422 ;; Case 4. Normal line without ARG: make the first line of
19423 ;; region an item, and shift indentation of others
19424 ;; lines to set them as item's body.
19425 (t (let* ((bul (org-list-bullet-string "-"))
19426 (bul-len (length bul))
19427 (ref-ind (org-get-indentation)))
19428 (skip-chars-forward " \t")
19429 (insert bul)
19430 (forward-line)
19431 (while (< (point) end)
19432 ;; Ensure that lines less indented than first one
19433 ;; still get included in item body.
19434 (funcall shift-text
19435 (+ ref-ind bul-len)
19436 (min end (save-excursion (or (outline-next-heading)
19437 (point)))))
19438 (forward-line)))))))))
19440 (defun org-toggle-heading (&optional nstars)
19441 "Convert headings to normal text, or items or text to headings.
19442 If there is no active region, only the current line is considered.
19444 With a \\[universal-argument] prefix, convert the whole list at
19445 point into heading.
19447 In a region:
19449 - If the first non blank line is an headline, remove the stars
19450 from all headlines in the region.
19452 - If it is a normal line turn each and every normal line (i.e. not an
19453 heading or an item) in the region into a heading.
19455 - If it is a plain list item, turn all plain list items into headings.
19457 When converting a line into a heading, the number of stars is chosen
19458 such that the lines become children of the current entry. However,
19459 when a prefix argument is given, its value determines the number of
19460 stars to add."
19461 (interactive "P")
19462 (let ((skip-blanks
19463 (function
19464 ;; Return beginning of first non-blank line, starting from
19465 ;; line at POS.
19466 (lambda (pos)
19467 (save-excursion
19468 (goto-char pos)
19469 (while (org-at-comment-p) (forward-line))
19470 (skip-chars-forward " \r\t\n")
19471 (point-at-bol)))))
19472 beg end toggled)
19473 ;; Determine boundaries of changes. If a universal prefix has
19474 ;; been given, put the list in a region. If region ends at a bol,
19475 ;; do not consider the last line to be in the region.
19477 (when (and current-prefix-arg (org-at-item-p))
19478 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19479 (org-mark-element))
19481 (if (org-region-active-p)
19482 (setq beg (funcall skip-blanks (region-beginning))
19483 end (copy-marker (save-excursion
19484 (goto-char (region-end))
19485 (if (bolp) (point) (point-at-eol)))))
19486 (setq beg (funcall skip-blanks (point-at-bol))
19487 end (copy-marker (point-at-eol))))
19488 ;; Ensure inline tasks don't count as headings.
19489 (org-with-limited-levels
19490 (save-excursion
19491 (goto-char beg)
19492 (cond
19493 ;; Case 1. Started at an heading: de-star headings.
19494 ((org-at-heading-p)
19495 (while (< (point) end)
19496 (when (org-at-heading-p t)
19497 (looking-at org-outline-regexp) (replace-match "")
19498 (setq toggled t))
19499 (forward-line)))
19500 ;; Case 2. Started at an item: change items into headlines.
19501 ;; One star will be added by `org-list-to-subtree'.
19502 ((org-at-item-p)
19503 (let* ((stars (make-string
19504 (if nstars
19505 ;; subtract the star that will be added again by
19506 ;; `org-list-to-subtree'
19507 (1- (prefix-numeric-value current-prefix-arg))
19508 (or (org-current-level) 0))
19509 ?*))
19510 (add-stars
19511 (cond (nstars "") ; stars from prefix only
19512 ((equal stars "") "") ; before first heading
19513 (org-odd-levels-only "*") ; inside heading, odd
19514 (t "")))) ; inside heading, oddeven
19515 (while (< (point) end)
19516 (when (org-at-item-p)
19517 ;; Pay attention to cases when region ends before list.
19518 (let* ((struct (org-list-struct))
19519 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19520 (save-restriction
19521 (narrow-to-region (point) list-end)
19522 (insert
19523 (org-list-to-subtree
19524 (org-list-parse-list t)
19525 '(:istart (concat stars add-stars (funcall get-stars depth))
19526 :icount (concat stars add-stars (funcall get-stars depth)))))))
19527 (setq toggled t))
19528 (forward-line))))
19529 ;; Case 3. Started at normal text: make every line an heading,
19530 ;; skipping headlines and items.
19531 (t (let* ((stars (make-string
19532 (if nstars
19533 (prefix-numeric-value current-prefix-arg)
19534 (or (org-current-level) 0))
19535 ?*))
19536 (add-stars
19537 (cond (nstars "") ; stars from prefix only
19538 ((equal stars "") "*") ; before first heading
19539 (org-odd-levels-only "**") ; inside heading, odd
19540 (t "*"))) ; inside heading, oddeven
19541 (rpl (concat stars add-stars " ")))
19542 (while (< (point) end)
19543 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19544 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19545 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19546 (forward-line)))))))
19547 (unless toggled (message "Cannot toggle heading from here"))))
19549 (defun org-meta-return (&optional arg)
19550 "Insert a new heading or wrap a region in a table.
19551 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19552 See the individual commands for more information."
19553 (interactive "P")
19554 (cond
19555 ((run-hook-with-args-until-success 'org-metareturn-hook))
19556 ((or (org-at-drawer-p) (org-at-property-p))
19557 (newline-and-indent))
19558 ((org-at-table-p)
19559 (call-interactively 'org-table-wrap-region))
19560 (t (call-interactively 'org-insert-heading))))
19562 ;;; Menu entries
19564 (defsubst org-in-subtree-not-table-p ()
19565 "Are we in a subtree and not in a table?"
19566 (and (not (org-before-first-heading-p))
19567 (not (org-at-table-p))))
19569 ;; Define the Org-mode menus
19570 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19571 '("Tbl"
19572 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19573 ["Next Field" org-cycle (org-at-table-p)]
19574 ["Previous Field" org-shifttab (org-at-table-p)]
19575 ["Next Row" org-return (org-at-table-p)]
19576 "--"
19577 ["Blank Field" org-table-blank-field (org-at-table-p)]
19578 ["Edit Field" org-table-edit-field (org-at-table-p)]
19579 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19580 "--"
19581 ("Column"
19582 ["Move Column Left" org-metaleft (org-at-table-p)]
19583 ["Move Column Right" org-metaright (org-at-table-p)]
19584 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19585 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19586 ("Row"
19587 ["Move Row Up" org-metaup (org-at-table-p)]
19588 ["Move Row Down" org-metadown (org-at-table-p)]
19589 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19590 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19591 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19592 "--"
19593 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19594 ("Rectangle"
19595 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19596 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19597 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19598 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19599 "--"
19600 ("Calculate"
19601 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19602 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19603 ["Edit Formulas" org-edit-special (org-at-table-p)]
19604 "--"
19605 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19606 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19607 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19608 "--"
19609 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19610 "--"
19611 ["Sum Column/Rectangle" org-table-sum
19612 (or (org-at-table-p) (org-region-active-p))]
19613 ["Which Column?" org-table-current-column (org-at-table-p)])
19614 ["Debug Formulas"
19615 org-table-toggle-formula-debugger
19616 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19617 ["Show Col/Row Numbers"
19618 org-table-toggle-coordinate-overlays
19619 :style toggle
19620 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19621 "--"
19622 ["Create" org-table-create (and (not (org-at-table-p))
19623 org-enable-table-editor)]
19624 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19625 ["Import from File" org-table-import (not (org-at-table-p))]
19626 ["Export to File" org-table-export (org-at-table-p)]
19627 "--"
19628 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19630 (easy-menu-define org-org-menu org-mode-map "Org menu"
19631 '("Org"
19632 ("Show/Hide"
19633 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19634 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19635 ["Sparse Tree..." org-sparse-tree t]
19636 ["Reveal Context" org-reveal t]
19637 ["Show All" show-all t]
19638 "--"
19639 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19640 "--"
19641 ["New Heading" org-insert-heading t]
19642 ("Navigate Headings"
19643 ["Up" outline-up-heading t]
19644 ["Next" outline-next-visible-heading t]
19645 ["Previous" outline-previous-visible-heading t]
19646 ["Next Same Level" outline-forward-same-level t]
19647 ["Previous Same Level" outline-backward-same-level t]
19648 "--"
19649 ["Jump" org-goto t])
19650 ("Edit Structure"
19651 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
19652 "--"
19653 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
19654 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
19655 "--"
19656 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
19657 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
19658 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19659 "--"
19660 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19661 "--"
19662 ["Copy visible text" org-copy-visible t]
19663 "--"
19664 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
19665 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
19666 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
19667 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
19668 "--"
19669 ["Sort Region/Children" org-sort t]
19670 "--"
19671 ["Convert to odd levels" org-convert-to-odd-levels t]
19672 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19673 ("Editing"
19674 ["Emphasis..." org-emphasize t]
19675 ["Edit Source Example" org-edit-special t]
19676 "--"
19677 ["Footnote new/jump" org-footnote-action t]
19678 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19679 ("Archive"
19680 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
19681 "--"
19682 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
19683 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
19684 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
19686 "--"
19687 ("Hyperlinks"
19688 ["Store Link (Global)" org-store-link t]
19689 ["Find existing link to here" org-occur-link-in-agenda-files t]
19690 ["Insert Link" org-insert-link t]
19691 ["Follow Link" org-open-at-point t]
19692 "--"
19693 ["Next link" org-next-link t]
19694 ["Previous link" org-previous-link t]
19695 "--"
19696 ["Descriptive Links"
19697 org-toggle-link-display
19698 :style radio
19699 :selected org-descriptive-links
19701 ["Literal Links"
19702 org-toggle-link-display
19703 :style radio
19704 :selected (not org-descriptive-links)])
19705 "--"
19706 ("TODO Lists"
19707 ["TODO/DONE/-" org-todo t]
19708 ("Select keyword"
19709 ["Next keyword" org-shiftright (org-at-heading-p)]
19710 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19711 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19712 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19713 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19714 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19715 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19716 "--"
19717 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19718 :selected org-enforce-todo-dependencies :style toggle :active t]
19719 "Settings for tree at point"
19720 ["Do Children sequentially" org-toggle-ordered-property :style radio
19721 :selected (org-entry-get nil "ORDERED")
19722 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19723 ["Do Children parallel" org-toggle-ordered-property :style radio
19724 :selected (not (org-entry-get nil "ORDERED"))
19725 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19726 "--"
19727 ["Set Priority" org-priority t]
19728 ["Priority Up" org-shiftup t]
19729 ["Priority Down" org-shiftdown t]
19730 "--"
19731 ["Get news from all feeds" org-feed-update-all t]
19732 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19733 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19734 ("TAGS and Properties"
19735 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
19736 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19737 "--"
19738 ["Set property" org-set-property (not (org-before-first-heading-p))]
19739 ["Column view of properties" org-columns t]
19740 ["Insert Column View DBlock" org-insert-columns-dblock t])
19741 ("Dates and Scheduling"
19742 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
19743 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
19744 ("Change Date"
19745 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
19746 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
19747 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
19748 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
19749 ["Compute Time Range" org-evaluate-time-range t]
19750 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
19751 ["Deadline" org-deadline (not (org-before-first-heading-p))]
19752 "--"
19753 ["Custom time format" org-toggle-time-stamp-overlays
19754 :style radio :selected org-display-custom-times]
19755 "--"
19756 ["Goto Calendar" org-goto-calendar t]
19757 ["Date from Calendar" org-date-from-calendar t]
19758 "--"
19759 ["Start/Restart Timer" org-timer-start t]
19760 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19761 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19762 ["Insert Timer String" org-timer t]
19763 ["Insert Timer Item" org-timer-item t])
19764 ("Logging work"
19765 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19766 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19767 ["Clock out" org-clock-out t]
19768 ["Clock cancel" org-clock-cancel t]
19769 "--"
19770 ["Mark as default task" org-clock-mark-default-task t]
19771 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19772 ["Goto running clock" org-clock-goto t]
19773 "--"
19774 ["Display times" org-clock-display t]
19775 ["Create clock table" org-clock-report t]
19776 "--"
19777 ["Record DONE time"
19778 (progn (setq org-log-done (not org-log-done))
19779 (message "Switching to %s will %s record a timestamp"
19780 (car org-done-keywords)
19781 (if org-log-done "automatically" "not")))
19782 :style toggle :selected org-log-done])
19783 "--"
19784 ["Agenda Command..." org-agenda t]
19785 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19786 ("File List for Agenda")
19787 ("Special views current file"
19788 ["TODO Tree" org-show-todo-tree t]
19789 ["Check Deadlines" org-check-deadlines t]
19790 ["Timeline" org-timeline t]
19791 ["Tags/Property tree" org-match-sparse-tree t])
19792 "--"
19793 ["Export/Publish..." org-export t]
19794 ("LaTeX"
19795 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19796 :selected org-cdlatex-mode]
19797 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19798 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19799 ["Modify math symbol" org-cdlatex-math-modify
19800 (org-inside-LaTeX-fragment-p)]
19801 ["Insert citation" org-reftex-citation t]
19802 "--"
19803 ["Template for BEAMER" (progn (require 'org-beamer)
19804 (org-insert-beamer-options-template)) t])
19805 "--"
19806 ("MobileOrg"
19807 ["Push Files and Views" org-mobile-push t]
19808 ["Get Captured and Flagged" org-mobile-pull t]
19809 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19810 "--"
19811 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19812 "--"
19813 ("Documentation"
19814 ["Show Version" org-version t]
19815 ["Info Documentation" org-info t])
19816 ("Customize"
19817 ["Browse Org Group" org-customize t]
19818 "--"
19819 ["Expand This Menu" org-create-customize-menu
19820 (fboundp 'customize-menu-create)])
19821 ["Send bug report" org-submit-bug-report t]
19822 "--"
19823 ("Refresh/Reload"
19824 ["Refresh setup current buffer" org-mode-restart t]
19825 ["Reload Org (after update)" org-reload t]
19826 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19829 (defun org-info (&optional node)
19830 "Read documentation for Org-mode in the info system.
19831 With optional NODE, go directly to that node."
19832 (interactive)
19833 (info (format "(org)%s" (or node ""))))
19835 ;;;###autoload
19836 (defun org-submit-bug-report ()
19837 "Submit a bug report on Org-mode via mail.
19839 Don't hesitate to report any problems or inaccurate documentation.
19841 If you don't have setup sending mail from (X)Emacs, please copy the
19842 output buffer into your mail program, as it gives us important
19843 information about your Org-mode version and configuration."
19844 (interactive)
19845 (require 'reporter)
19846 (org-load-modules-maybe)
19847 (org-require-autoloaded-modules)
19848 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19849 (reporter-submit-bug-report
19850 "emacs-orgmode@gnu.org"
19851 (org-version nil 'full)
19852 (let (list)
19853 (save-window-excursion
19854 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19855 (delete-other-windows)
19856 (erase-buffer)
19857 (insert "You are about to submit a bug report to the Org-mode mailing list.
19859 We would like to add your full Org-mode and Outline configuration to the
19860 bug report. This greatly simplifies the work of the maintainer and
19861 other experts on the mailing list.
19863 HOWEVER, some variables you have customized may contain private
19864 information. The names of customers, colleagues, or friends, might
19865 appear in the form of file names, tags, todo states, or search strings.
19866 If you answer yes to the prompt, you might want to check and remove
19867 such private information before sending the email.")
19868 (add-text-properties (point-min) (point-max) '(face org-warning))
19869 (when (yes-or-no-p "Include your Org-mode configuration ")
19870 (mapatoms
19871 (lambda (v)
19872 (and (boundp v)
19873 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19874 (or (and (symbol-value v)
19875 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19876 (and
19877 (get v 'custom-type) (get v 'standard-value)
19878 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19879 (push v list)))))
19880 (kill-buffer (get-buffer "*Warn about privacy*"))
19881 list))
19882 nil nil
19883 "Remember to cover the basics, that is, what you expected to happen and
19884 what in fact did happen. You don't know how to make a good report? See
19886 http://orgmode.org/manual/Feedback.html#Feedback
19888 Your bug report will be posted to the Org-mode mailing list.
19889 ------------------------------------------------------------------------")
19890 (save-excursion
19891 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19892 (replace-match "\\1Bug: \\3 [\\2]")))))
19895 (defun org-install-agenda-files-menu ()
19896 (let ((bl (buffer-list)))
19897 (save-excursion
19898 (while bl
19899 (set-buffer (pop bl))
19900 (if (derived-mode-p 'org-mode) (setq bl nil)))
19901 (when (derived-mode-p 'org-mode)
19902 (easy-menu-change
19903 '("Org") "File List for Agenda"
19904 (append
19905 (list
19906 ["Edit File List" (org-edit-agenda-file-list) t]
19907 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19908 ["Remove Current File from List" org-remove-file t]
19909 ["Cycle through agenda files" org-cycle-agenda-files t]
19910 ["Occur in all agenda files" org-occur-in-agenda-files t]
19911 "--")
19912 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19914 ;;;; Documentation
19916 (defun org-require-autoloaded-modules ()
19917 (interactive)
19918 (mapc 'require
19919 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19920 org-docbook org-exp org-html org-icalendar
19921 org-id org-latex
19922 org-publish org-remember org-table
19923 org-timer org-xoxo)))
19925 ;;;###autoload
19926 (defun org-reload (&optional uncompiled)
19927 "Reload all org lisp files.
19928 With prefix arg UNCOMPILED, load the uncompiled versions."
19929 (interactive "P")
19930 (require 'find-func)
19931 (let* ((file-re "^org\\(-.*\\)?\\.el")
19932 (dir-org (file-name-directory (org-find-library-dir "org")))
19933 (dir-org-contrib (ignore-errors
19934 (file-name-directory
19935 (org-find-library-dir "org-contribdir"))))
19936 (babel-files
19937 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19938 (append (list nil "comint" "eval" "exp" "keys"
19939 "lob" "ref" "table" "tangle")
19940 (delq nil
19941 (mapcar
19942 (lambda (lang)
19943 (when (cdr lang) (symbol-name (car lang))))
19944 org-babel-load-languages)))))
19945 (files
19946 (append babel-files
19947 (and dir-org-contrib
19948 (directory-files dir-org-contrib t file-re))
19949 (directory-files dir-org t file-re)))
19950 (remove-re (concat (if (featurep 'xemacs)
19951 "org-colview" "org-colview-xemacs")
19952 "\\'")))
19953 (setq files (mapcar 'file-name-sans-extension files))
19954 (setq files (mapcar
19955 (lambda (x) (if (string-match remove-re x) nil x))
19956 files))
19957 (setq files (delq nil files))
19958 (mapc
19959 (lambda (f)
19960 (when (featurep (intern (file-name-nondirectory f)))
19961 (if (and (not uncompiled)
19962 (file-exists-p (concat f ".elc")))
19963 (load (concat f ".elc") nil nil 'nosuffix)
19964 (load (concat f ".el") nil nil 'nosuffix))))
19965 files)
19966 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
19967 (org-version nil 'full 'message))
19969 ;;;###autoload
19970 (defun org-customize ()
19971 "Call the customize function with org as argument."
19972 (interactive)
19973 (org-load-modules-maybe)
19974 (org-require-autoloaded-modules)
19975 (customize-browse 'org))
19977 (defun org-create-customize-menu ()
19978 "Create a full customization menu for Org-mode, insert it into the menu."
19979 (interactive)
19980 (org-load-modules-maybe)
19981 (org-require-autoloaded-modules)
19982 (if (fboundp 'customize-menu-create)
19983 (progn
19984 (easy-menu-change
19985 '("Org") "Customize"
19986 `(["Browse Org group" org-customize t]
19987 "--"
19988 ,(customize-menu-create 'org)
19989 ["Set" Custom-set t]
19990 ["Save" Custom-save t]
19991 ["Reset to Current" Custom-reset-current t]
19992 ["Reset to Saved" Custom-reset-saved t]
19993 ["Reset to Standard Settings" Custom-reset-standard t]))
19994 (message "\"Org\"-menu now contains full customization menu"))
19995 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19997 ;;;; Miscellaneous stuff
19999 ;;; Generally useful functions
20001 (defun org-get-at-bol (property)
20002 "Get text property PROPERTY at beginning of line."
20003 (get-text-property (point-at-bol) property))
20005 (defun org-find-text-property-in-string (prop s)
20006 "Return the first non-nil value of property PROP in string S."
20007 (or (get-text-property 0 prop s)
20008 (get-text-property (or (next-single-property-change 0 prop s) 0)
20009 prop s)))
20011 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20012 "Display the given MESSAGE as a warning."
20013 (if (fboundp 'display-warning)
20014 (display-warning 'org message
20015 (if (featurep 'xemacs) 'warning :warning))
20016 (let ((buf (get-buffer-create "*Org warnings*")))
20017 (with-current-buffer buf
20018 (goto-char (point-max))
20019 (insert "Warning (Org): " message)
20020 (unless (bolp)
20021 (newline)))
20022 (display-buffer buf)
20023 (sit-for 0))))
20025 (defun org-eval (form)
20026 "Eval FORM and return result."
20027 (condition-case error
20028 (eval form)
20029 (error (format "%%![Error: %s]" error))))
20031 (defun org-in-clocktable-p ()
20032 "Check if the cursor is in a clocktable."
20033 (let ((pos (point)) start)
20034 (save-excursion
20035 (end-of-line 1)
20036 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20037 (setq start (match-beginning 0))
20038 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20039 (>= (match-end 0) pos)
20040 start))))
20042 (defun org-in-commented-line ()
20043 "Is point in a line starting with `#'?"
20044 (equal (char-after (point-at-bol)) ?#))
20046 (defun org-in-indented-comment-line ()
20047 "Is point in a line starting with `#' after some white space?"
20048 (save-excursion
20049 (save-match-data
20050 (goto-char (point-at-bol))
20051 (looking-at "[ \t]*#"))))
20053 (defun org-in-verbatim-emphasis ()
20054 (save-match-data
20055 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20057 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20058 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20059 (if (and marker (marker-buffer marker)
20060 (buffer-live-p (marker-buffer marker)))
20061 (progn
20062 (org-pop-to-buffer-same-window (marker-buffer marker))
20063 (if (or (> marker (point-max)) (< marker (point-min)))
20064 (widen))
20065 (goto-char marker)
20066 (org-show-context 'org-goto))
20067 (if bookmark
20068 (bookmark-jump bookmark)
20069 (error "Cannot find location"))))
20071 (defun org-quote-csv-field (s)
20072 "Quote field for inclusion in CSV material."
20073 (if (string-match "[\",]" s)
20074 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20077 (defun org-force-self-insert (N)
20078 "Needed to enforce self-insert under remapping."
20079 (interactive "p")
20080 (self-insert-command N))
20082 (defun org-string-width (s)
20083 "Compute width of string, ignoring invisible characters.
20084 This ignores character with invisibility property `org-link', and also
20085 characters with property `org-cwidth', because these will become invisible
20086 upon the next fontification round."
20087 (let (b l)
20088 (when (or (eq t buffer-invisibility-spec)
20089 (assq 'org-link buffer-invisibility-spec))
20090 (while (setq b (text-property-any 0 (length s)
20091 'invisible 'org-link s))
20092 (setq s (concat (substring s 0 b)
20093 (substring s (or (next-single-property-change
20094 b 'invisible s) (length s)))))))
20095 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20096 (setq s (concat (substring s 0 b)
20097 (substring s (or (next-single-property-change
20098 b 'org-cwidth s) (length s))))))
20099 (setq l (string-width s) b -1)
20100 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20101 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20104 (defun org-shorten-string (s maxlength)
20105 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20106 If the string is shorter or has length MAXLENGTH, just return the
20107 original string. If it is longer, the functions finds a space in the
20108 string, breaks this string off at that locations and adds three dots
20109 as ellipsis. Including the ellipsis, the string will not be longer
20110 than MAXLENGTH. If finding a good breaking point in the string does
20111 not work, the string is just chopped off in the middle of a word
20112 if necessary."
20113 (if (<= (length s) maxlength)
20115 (let* ((n (max (- maxlength 4) 1))
20116 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20117 (if (string-match re s)
20118 (concat (match-string 1 s) "...")
20119 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20121 (defun org-get-indentation (&optional line)
20122 "Get the indentation of the current line, interpreting tabs.
20123 When LINE is given, assume it represents a line and compute its indentation."
20124 (if line
20125 (if (string-match "^ *" (org-remove-tabs line))
20126 (match-end 0))
20127 (save-excursion
20128 (beginning-of-line 1)
20129 (skip-chars-forward " \t")
20130 (current-column))))
20132 (defun org-get-string-indentation (s)
20133 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20134 (let ((n -1) (i 0) (w tab-width) c)
20135 (catch 'exit
20136 (while (< (setq n (1+ n)) (length s))
20137 (setq c (aref s n))
20138 (cond ((= c ?\ ) (setq i (1+ i)))
20139 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20140 (t (throw 'exit t)))))
20143 (defun org-remove-tabs (s &optional width)
20144 "Replace tabulators in S with spaces.
20145 Assumes that s is a single line, starting in column 0."
20146 (setq width (or width tab-width))
20147 (while (string-match "\t" s)
20148 (setq s (replace-match
20149 (make-string
20150 (- (* width (/ (+ (match-beginning 0) width) width))
20151 (match-beginning 0)) ?\ )
20152 t t s)))
20155 (defun org-fix-indentation (line ind)
20156 "Fix indentation in LINE.
20157 IND is a cons cell with target and minimum indentation.
20158 If the current indentation in LINE is smaller than the minimum,
20159 leave it alone. If it is larger than ind, set it to the target."
20160 (let* ((l (org-remove-tabs line))
20161 (i (org-get-indentation l))
20162 (i1 (car ind)) (i2 (cdr ind)))
20163 (if (>= i i2) (setq l (substring line i2)))
20164 (if (> i1 0)
20165 (concat (make-string i1 ?\ ) l)
20166 l)))
20168 (defun org-remove-indentation (code &optional n)
20169 "Remove the maximum common indentation from the lines in CODE.
20170 N may optionally be the number of spaces to remove."
20171 (with-temp-buffer
20172 (insert code)
20173 (org-do-remove-indentation n)
20174 (buffer-string)))
20176 (defun org-do-remove-indentation (&optional n)
20177 "Remove the maximum common indentation from the buffer."
20178 (untabify (point-min) (point-max))
20179 (let ((min 10000) re)
20180 (if n
20181 (setq min n)
20182 (goto-char (point-min))
20183 (while (re-search-forward "^ *[^ \n]" nil t)
20184 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20185 (unless (or (= min 0) (= min 10000))
20186 (setq re (format "^ \\{%d\\}" min))
20187 (goto-char (point-min))
20188 (while (re-search-forward re nil t)
20189 (replace-match "")
20190 (end-of-line 1))
20191 min)))
20193 (defun org-fill-template (template alist)
20194 "Find each %key of ALIST in TEMPLATE and replace it."
20195 (let ((case-fold-search nil)
20196 entry key value)
20197 (setq alist (sort (copy-sequence alist)
20198 (lambda (a b) (< (length (car a)) (length (car b))))))
20199 (while (setq entry (pop alist))
20200 (setq template
20201 (replace-regexp-in-string
20202 (concat "%" (regexp-quote (car entry)))
20203 (or (cdr entry) "") template t t)))
20204 template))
20206 (defun org-base-buffer (buffer)
20207 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20208 (if (not buffer)
20209 buffer
20210 (or (buffer-base-buffer buffer)
20211 buffer)))
20213 (defun org-trim (s)
20214 "Remove whitespace at beginning and end of string."
20215 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20216 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20219 (defun org-wrap (string &optional width lines)
20220 "Wrap string to either a number of lines, or a width in characters.
20221 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20222 that costs. If there is a word longer than WIDTH, the text is actually
20223 wrapped to the length of that word.
20224 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20225 many lines, whatever width that takes.
20226 The return value is a list of lines, without newlines at the end."
20227 (let* ((words (org-split-string string "[ \t\n]+"))
20228 (maxword (apply 'max (mapcar 'org-string-width words)))
20229 w ll)
20230 (cond (width
20231 (org-do-wrap words (max maxword width)))
20232 (lines
20233 (setq w maxword)
20234 (setq ll (org-do-wrap words maxword))
20235 (if (<= (length ll) lines)
20237 (setq ll words)
20238 (while (> (length ll) lines)
20239 (setq w (1+ w))
20240 (setq ll (org-do-wrap words w)))
20241 ll))
20242 (t (error "Cannot wrap this")))))
20244 (defun org-do-wrap (words width)
20245 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20246 (let (lines line)
20247 (while words
20248 (setq line (pop words))
20249 (while (and words (< (+ (length line) (length (car words))) width))
20250 (setq line (concat line " " (pop words))))
20251 (setq lines (push line lines)))
20252 (nreverse lines)))
20254 (defun org-split-string (string &optional separators)
20255 "Splits STRING into substrings at SEPARATORS.
20256 No empty strings are returned if there are matches at the beginning
20257 and end of string."
20258 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20259 (start 0)
20260 notfirst
20261 (list nil))
20262 (while (and (string-match rexp string
20263 (if (and notfirst
20264 (= start (match-beginning 0))
20265 (< start (length string)))
20266 (1+ start) start))
20267 (< (match-beginning 0) (length string)))
20268 (setq notfirst t)
20269 (or (eq (match-beginning 0) 0)
20270 (and (eq (match-beginning 0) (match-end 0))
20271 (eq (match-beginning 0) start))
20272 (setq list
20273 (cons (substring string start (match-beginning 0))
20274 list)))
20275 (setq start (match-end 0)))
20276 (or (eq start (length string))
20277 (setq list
20278 (cons (substring string start)
20279 list)))
20280 (nreverse list)))
20282 (defun org-quote-vert (s)
20283 "Replace \"|\" with \"\\vert\"."
20284 (while (string-match "|" s)
20285 (setq s (replace-match "\\vert" t t s)))
20288 (defun org-uuidgen-p (s)
20289 "Is S an ID created by UUIDGEN?"
20290 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20292 (defun org-in-src-block-p (&optional inside)
20293 "Whether point is in a code source block.
20294 When INSIDE is non-nil, don't consider we are within a src block
20295 when point is at #+BEGIN_SRC or #+END_SRC."
20296 (let ((case-fold-search t) ov)
20297 (or (and (setq ov (overlays-at (point)))
20298 (memq 'org-block-background
20299 (overlay-properties (car ov))))
20300 (and (not inside)
20301 (save-match-data
20302 (save-excursion
20303 (beginning-of-line)
20304 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20306 (defun org-context ()
20307 "Return a list of contexts of the current cursor position.
20308 If several contexts apply, all are returned.
20309 Each context entry is a list with a symbol naming the context, and
20310 two positions indicating start and end of the context. Possible
20311 contexts are:
20313 :headline anywhere in a headline
20314 :headline-stars on the leading stars in a headline
20315 :todo-keyword on a TODO keyword (including DONE) in a headline
20316 :tags on the TAGS in a headline
20317 :priority on the priority cookie in a headline
20318 :item on the first line of a plain list item
20319 :item-bullet on the bullet/number of a plain list item
20320 :checkbox on the checkbox in a plain list item
20321 :table in an org-mode table
20322 :table-special on a special filed in a table
20323 :table-table in a table.el table
20324 :clocktable in a clocktable
20325 :src-block in a source block
20326 :link on a hyperlink
20327 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20328 :target on a <<target>>
20329 :radio-target on a <<<radio-target>>>
20330 :latex-fragment on a LaTeX fragment
20331 :latex-preview on a LaTeX fragment with overlaid preview image
20333 This function expects the position to be visible because it uses font-lock
20334 faces as a help to recognize the following contexts: :table-special, :link,
20335 and :keyword."
20336 (let* ((f (get-text-property (point) 'face))
20337 (faces (if (listp f) f (list f)))
20338 (case-fold-search t)
20339 (p (point)) clist o)
20340 ;; First the large context
20341 (cond
20342 ((org-at-heading-p t)
20343 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20344 (when (progn
20345 (beginning-of-line 1)
20346 (looking-at org-todo-line-tags-regexp))
20347 (push (org-point-in-group p 1 :headline-stars) clist)
20348 (push (org-point-in-group p 2 :todo-keyword) clist)
20349 (push (org-point-in-group p 4 :tags) clist))
20350 (goto-char p)
20351 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20352 (if (looking-at "\\[#[A-Z0-9]\\]")
20353 (push (org-point-in-group p 0 :priority) clist)))
20355 ((org-at-item-p)
20356 (push (org-point-in-group p 2 :item-bullet) clist)
20357 (push (list :item (point-at-bol)
20358 (save-excursion (org-end-of-item) (point)))
20359 clist)
20360 (and (org-at-item-checkbox-p)
20361 (push (org-point-in-group p 0 :checkbox) clist)))
20363 ((org-at-table-p)
20364 (push (list :table (org-table-begin) (org-table-end)) clist)
20365 (if (memq 'org-formula faces)
20366 (push (list :table-special
20367 (previous-single-property-change p 'face)
20368 (next-single-property-change p 'face)) clist)))
20369 ((org-at-table-p 'any)
20370 (push (list :table-table) clist)))
20371 (goto-char p)
20373 (let ((case-fold-search t))
20374 ;; New the "medium" contexts: clocktables, source blocks
20375 (cond ((org-in-clocktable-p)
20376 (push (list :clocktable
20377 (and (or (looking-at "#\\+BEGIN: clocktable")
20378 (search-backward "#+BEGIN: clocktable" nil t))
20379 (match-beginning 0))
20380 (and (re-search-forward "#\\+END:?" nil t)
20381 (match-end 0))) clist))
20382 ((org-in-src-block-p)
20383 (push (list :src-block
20384 (and (or (looking-at "#\\+BEGIN_SRC")
20385 (search-backward "#+BEGIN_SRC" nil t))
20386 (match-beginning 0))
20387 (and (search-forward "#+END_SRC" nil t)
20388 (match-beginning 0))) clist))))
20389 (goto-char p)
20391 ;; Now the small context
20392 (cond
20393 ((org-at-timestamp-p)
20394 (push (org-point-in-group p 0 :timestamp) clist))
20395 ((memq 'org-link faces)
20396 (push (list :link
20397 (previous-single-property-change p 'face)
20398 (next-single-property-change p 'face)) clist))
20399 ((memq 'org-special-keyword faces)
20400 (push (list :keyword
20401 (previous-single-property-change p 'face)
20402 (next-single-property-change p 'face)) clist))
20403 ((org-at-target-p)
20404 (push (org-point-in-group p 0 :target) clist)
20405 (goto-char (1- (match-beginning 0)))
20406 (if (looking-at org-radio-target-regexp)
20407 (push (org-point-in-group p 0 :radio-target) clist))
20408 (goto-char p))
20409 ((setq o (car (delq nil
20410 (mapcar
20411 (lambda (x)
20412 (if (memq x org-latex-fragment-image-overlays) x))
20413 (overlays-at (point))))))
20414 (push (list :latex-fragment
20415 (overlay-start o) (overlay-end o)) clist)
20416 (push (list :latex-preview
20417 (overlay-start o) (overlay-end o)) clist))
20418 ((org-inside-LaTeX-fragment-p)
20419 ;; FIXME: positions wrong.
20420 (push (list :latex-fragment (point) (point)) clist)))
20422 (setq clist (nreverse (delq nil clist)))
20423 clist))
20425 ;; FIXME: Compare with at-regexp-p Do we need both?
20426 (defun org-in-regexp (re &optional nlines visually)
20427 "Check if point is inside a match of regexp.
20428 Normally only the current line is checked, but you can include NLINES extra
20429 lines both before and after point into the search.
20430 If VISUALLY is set, require that the cursor is not after the match but
20431 really on, so that the block visually is on the match."
20432 (catch 'exit
20433 (let ((pos (point))
20434 (eol (point-at-eol (+ 1 (or nlines 0))))
20435 (inc (if visually 1 0)))
20436 (save-excursion
20437 (beginning-of-line (- 1 (or nlines 0)))
20438 (while (re-search-forward re eol t)
20439 (if (and (<= (match-beginning 0) pos)
20440 (>= (+ inc (match-end 0)) pos))
20441 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20443 (defun org-at-regexp-p (regexp)
20444 "Is point inside a match of REGEXP in the current line?"
20445 (catch 'exit
20446 (save-excursion
20447 (let ((pos (point)) (end (point-at-eol)))
20448 (beginning-of-line 1)
20449 (while (re-search-forward regexp end t)
20450 (if (and (<= (match-beginning 0) pos)
20451 (>= (match-end 0) pos))
20452 (throw 'exit t)))
20453 nil))))
20455 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20456 "Non-nil when point is between matches of START-RE and END-RE.
20458 Also return a non-nil value when point is on one of the matches.
20460 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20461 buffer positions. Default values are the positions of headlines
20462 surrounding the point.
20464 The functions returns a cons cell whose car (resp. cdr) is the
20465 position before START-RE (resp. after END-RE)."
20466 (save-match-data
20467 (let ((pos (point))
20468 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20469 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20470 beg end)
20471 (save-excursion
20472 ;; Point is on a block when on START-RE or if START-RE can be
20473 ;; found before it...
20474 (and (or (org-at-regexp-p start-re)
20475 (re-search-backward start-re limit-up t))
20476 (setq beg (match-beginning 0))
20477 ;; ... and END-RE after it...
20478 (goto-char (match-end 0))
20479 (re-search-forward end-re limit-down t)
20480 (> (setq end (match-end 0)) pos)
20481 ;; ... without another START-RE in-between.
20482 (goto-char (match-beginning 0))
20483 (not (re-search-backward start-re (1+ beg) t))
20484 ;; Return value.
20485 (cons beg end))))))
20487 (defun org-in-block-p (names)
20488 "Non-nil when point belongs to a block whose name belongs to NAMES.
20490 NAMES is a list of strings containing names of blocks.
20492 Return first block name matched, or nil. Beware that in case of
20493 nested blocks, the returned name may not belong to the closest
20494 block from point."
20495 (save-match-data
20496 (catch 'exit
20497 (let ((case-fold-search t)
20498 (lim-up (save-excursion (outline-previous-heading)))
20499 (lim-down (save-excursion (outline-next-heading))))
20500 (mapc (lambda (name)
20501 (let ((n (regexp-quote name)))
20502 (when (org-between-regexps-p
20503 (concat "^[ \t]*#\\+begin_" n)
20504 (concat "^[ \t]*#\\+end_" n)
20505 lim-up lim-down)
20506 (throw 'exit n))))
20507 names))
20508 nil)))
20510 (defun org-occur-in-agenda-files (regexp &optional nlines)
20511 "Call `multi-occur' with buffers for all agenda files."
20512 (interactive "sOrg-files matching: \np")
20513 (let* ((files (org-agenda-files))
20514 (tnames (mapcar 'file-truename files))
20515 (extra org-agenda-text-search-extra-files)
20517 (when (eq (car extra) 'agenda-archives)
20518 (setq extra (cdr extra))
20519 (setq files (org-add-archive-files files)))
20520 (while (setq f (pop extra))
20521 (unless (member (file-truename f) tnames)
20522 (add-to-list 'files f 'append)
20523 (add-to-list 'tnames (file-truename f) 'append)))
20524 (multi-occur
20525 (mapcar (lambda (x)
20526 (with-current-buffer
20527 (or (get-file-buffer x) (find-file-noselect x))
20528 (widen)
20529 (current-buffer)))
20530 files)
20531 regexp)))
20533 (if (boundp 'occur-mode-find-occurrence-hook)
20534 ;; Emacs 23
20535 (add-hook 'occur-mode-find-occurrence-hook
20536 (lambda ()
20537 (when (derived-mode-p 'org-mode)
20538 (org-reveal))))
20539 ;; Emacs 22
20540 (defadvice occur-mode-goto-occurrence
20541 (after org-occur-reveal activate)
20542 (and (derived-mode-p 'org-mode) (org-reveal)))
20543 (defadvice occur-mode-goto-occurrence-other-window
20544 (after org-occur-reveal activate)
20545 (and (derived-mode-p 'org-mode) (org-reveal)))
20546 (defadvice occur-mode-display-occurrence
20547 (after org-occur-reveal activate)
20548 (when (derived-mode-p 'org-mode)
20549 (let ((pos (occur-mode-find-occurrence)))
20550 (with-current-buffer (marker-buffer pos)
20551 (save-excursion
20552 (goto-char pos)
20553 (org-reveal)))))))
20555 (defun org-occur-link-in-agenda-files ()
20556 "Create a link and search for it in the agendas.
20557 The link is not stored in `org-stored-links', it is just created
20558 for the search purpose."
20559 (interactive)
20560 (let ((link (condition-case nil
20561 (org-store-link nil)
20562 (error "Unable to create a link to here"))))
20563 (org-occur-in-agenda-files (regexp-quote link))))
20565 (defun org-uniquify (list)
20566 "Remove duplicate elements from LIST."
20567 (let (res)
20568 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20569 res))
20571 (defun org-delete-all (elts list)
20572 "Remove all elements in ELTS from LIST."
20573 (while elts
20574 (setq list (delete (pop elts) list)))
20575 list)
20577 (defun org-count (cl-item cl-seq)
20578 "Count the number of occurrences of ITEM in SEQ.
20579 Taken from `count' in cl-seq.el with all keyword arguments removed."
20580 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20581 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20582 (while (< cl-start cl-end)
20583 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20584 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20585 (setq cl-start (1+ cl-start)))
20586 cl-count))
20588 (defun org-remove-if (predicate seq)
20589 "Remove everything from SEQ that fulfills PREDICATE."
20590 (let (res e)
20591 (while seq
20592 (setq e (pop seq))
20593 (if (not (funcall predicate e)) (push e res)))
20594 (nreverse res)))
20596 (defun org-remove-if-not (predicate seq)
20597 "Remove everything from SEQ that does not fulfill PREDICATE."
20598 (let (res e)
20599 (while seq
20600 (setq e (pop seq))
20601 (if (funcall predicate e) (push e res)))
20602 (nreverse res)))
20604 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20605 "Reduce two-argument FUNCTION across SEQ.
20606 Taken from `reduce' in cl-seq.el with all keyword arguments but
20607 \":initial-value\" removed."
20608 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20609 (cadr (memq :initial-value cl-keys)))
20610 (cl-seq (pop cl-seq))
20611 (t (funcall cl-func)))))
20612 (while cl-seq
20613 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20614 cl-accum))
20616 (defun org-back-over-empty-lines ()
20617 "Move backwards over whitespace, to the beginning of the first empty line.
20618 Returns the number of empty lines passed."
20619 (let ((pos (point)))
20620 (if (cdr (assoc 'heading org-blank-before-new-entry))
20621 (skip-chars-backward " \t\n\r")
20622 (unless (eobp)
20623 (forward-line -1)))
20624 (beginning-of-line 2)
20625 (goto-char (min (point) pos))
20626 (count-lines (point) pos)))
20628 (defun org-skip-whitespace ()
20629 (skip-chars-forward " \t\n\r"))
20631 (defun org-point-in-group (point group &optional context)
20632 "Check if POINT is in match-group GROUP.
20633 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20634 match. If the match group does not exist or point is not inside it,
20635 return nil."
20636 (and (match-beginning group)
20637 (>= point (match-beginning group))
20638 (<= point (match-end group))
20639 (if context
20640 (list context (match-beginning group) (match-end group))
20641 t)))
20643 (defun org-switch-to-buffer-other-window (&rest args)
20644 "Switch to buffer in a second window on the current frame.
20645 In particular, do not allow pop-up frames.
20646 Returns the newly created buffer."
20647 (org-no-popups
20648 (apply 'switch-to-buffer-other-window args)))
20650 (defun org-combine-plists (&rest plists)
20651 "Create a single property list from all plists in PLISTS.
20652 The process starts by copying the first list, and then setting properties
20653 from the other lists. Settings in the last list are the most significant
20654 ones and overrule settings in the other lists."
20655 (let ((rtn (copy-sequence (pop plists)))
20656 p v ls)
20657 (while plists
20658 (setq ls (pop plists))
20659 (while ls
20660 (setq p (pop ls) v (pop ls))
20661 (setq rtn (plist-put rtn p v))))
20662 rtn))
20664 (defun org-replace-escapes (string table)
20665 "Replace %-escapes in STRING with values in TABLE.
20666 TABLE is an association list with keys like \"%a\" and string values.
20667 The sequences in STRING may contain normal field width and padding information,
20668 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20669 so values can contain further %-escapes if they are define later in TABLE."
20670 (let ((tbl (copy-alist table))
20671 (case-fold-search nil)
20672 (pchg 0)
20673 e re rpl)
20674 (while (setq e (pop tbl))
20675 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20676 (when (and (cdr e) (string-match re (cdr e)))
20677 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20678 (safe "SREF"))
20679 (add-text-properties 0 3 (list 'sref sref) safe)
20680 (setcdr e (replace-match safe t t (cdr e)))))
20681 (while (string-match re string)
20682 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20683 (cdr e)))
20684 (setq string (replace-match rpl t t string))))
20685 (while (setq pchg (next-property-change pchg string))
20686 (let ((sref (get-text-property pchg 'sref string)))
20687 (when (and sref (string-match "SREF" string pchg))
20688 (setq string (replace-match sref t t string)))))
20689 string))
20691 (defun org-sublist (list start end)
20692 "Return a section of LIST, from START to END.
20693 Counting starts at 1."
20694 (let (rtn (c start))
20695 (setq list (nthcdr (1- start) list))
20696 (while (and list (<= c end))
20697 (push (pop list) rtn)
20698 (setq c (1+ c)))
20699 (nreverse rtn)))
20701 (defun org-find-base-buffer-visiting (file)
20702 "Like `find-buffer-visiting' but always return the base buffer and
20703 not an indirect buffer."
20704 (let ((buf (or (get-file-buffer file)
20705 (find-buffer-visiting file))))
20706 (if buf
20707 (or (buffer-base-buffer buf) buf)
20708 nil)))
20710 (defun org-image-file-name-regexp (&optional extensions)
20711 "Return regexp matching the file names of images.
20712 If EXTENSIONS is given, only match these."
20713 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20714 (image-file-name-regexp)
20715 (let ((image-file-name-extensions
20716 (or extensions
20717 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20718 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20719 (concat "\\."
20720 (regexp-opt (nconc (mapcar 'upcase
20721 image-file-name-extensions)
20722 image-file-name-extensions)
20724 "\\'"))))
20726 (defun org-file-image-p (file &optional extensions)
20727 "Return non-nil if FILE is an image."
20728 (save-match-data
20729 (string-match (org-image-file-name-regexp extensions) file)))
20731 (defun org-get-cursor-date ()
20732 "Return the date at cursor in as a time.
20733 This works in the calendar and in the agenda, anywhere else it just
20734 returns the current time."
20735 (let (date day defd)
20736 (cond
20737 ((eq major-mode 'calendar-mode)
20738 (setq date (calendar-cursor-to-date)
20739 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20740 ((eq major-mode 'org-agenda-mode)
20741 (setq day (get-text-property (point) 'day))
20742 (if day
20743 (setq date (calendar-gregorian-from-absolute day)
20744 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20745 (nth 2 date))))))
20746 (or defd (current-time))))
20748 (defun org-mark-subtree (&optional up)
20749 "Mark the current subtree.
20750 This puts point at the start of the current subtree, and mark at
20751 the end. If a numeric prefix UP is given, move up into the
20752 hierarchy of headlines by UP levels before marking the subtree."
20753 (interactive "P")
20754 (org-with-limited-levels
20755 (cond ((org-at-heading-p) (beginning-of-line))
20756 ((org-before-first-heading-p) (error "Not in a subtree"))
20757 (t (outline-previous-visible-heading 1))))
20758 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
20759 (if (org-called-interactively-p 'any)
20760 (call-interactively 'org-mark-element)
20761 (org-mark-element)))
20763 ;;; Indentation
20765 (defun org-indent-line ()
20766 "Indent line depending on context."
20767 (interactive)
20768 (let* ((pos (point))
20769 (itemp (org-at-item-p))
20770 (case-fold-search t)
20771 (org-drawer-regexp (or org-drawer-regexp "\000"))
20772 (inline-task-p (and (featurep 'org-inlinetask)
20773 (org-inlinetask-in-task-p)))
20774 (inline-re (and inline-task-p
20775 (org-inlinetask-outline-regexp)))
20776 column)
20777 (if (and orgstruct-is-++ (eq pos (point)))
20778 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
20779 (indent-according-to-mode))
20780 (beginning-of-line 1)
20781 (cond
20782 ;; Headings
20783 ((looking-at org-outline-regexp) (setq column 0))
20784 ;; Included files
20785 ((looking-at "#\\+include:") (setq column 0))
20786 ;; Footnote definition
20787 ((looking-at org-footnote-definition-re) (setq column 0))
20788 ;; Literal examples
20789 ((looking-at "[ \t]*:\\( \\|$\\)")
20790 (setq column (org-get-indentation))) ; do nothing
20791 ;; Lists
20792 ((ignore-errors (goto-char (org-in-item-p)))
20793 (setq column (if itemp
20794 (org-get-indentation)
20795 (org-list-item-body-column (point))))
20796 (goto-char pos))
20797 ;; Drawers
20798 ((and (looking-at "[ \t]*:END:")
20799 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20800 (save-excursion
20801 (goto-char (1- (match-beginning 1)))
20802 (setq column (current-column))))
20803 ;; Special blocks
20804 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20805 (save-excursion
20806 (re-search-backward
20807 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20808 (setq column (org-get-indentation (match-string 0))))
20809 ((and (not (looking-at "[ \t]*#\\+begin_"))
20810 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20811 (save-excursion
20812 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20813 (setq column
20814 (cond ((equal (downcase (match-string 1)) "src")
20815 ;; src blocks: let `org-edit-src-exit' handle them
20816 (org-get-indentation))
20817 ((equal (downcase (match-string 1)) "example")
20818 (max (org-get-indentation)
20819 (org-get-indentation (match-string 0))))
20821 (org-get-indentation (match-string 0))))))
20822 ;; This line has nothing special, look at the previous relevant
20823 ;; line to compute indentation
20825 (beginning-of-line 0)
20826 (while (and (not (bobp))
20827 (not (looking-at org-table-line-regexp))
20828 (not (looking-at org-drawer-regexp))
20829 ;; When point started in an inline task, do not move
20830 ;; above task starting line.
20831 (not (and inline-task-p (looking-at inline-re)))
20832 ;; Skip drawers, blocks, empty lines, verbatim,
20833 ;; comments, tables, footnotes definitions, lists,
20834 ;; inline tasks.
20835 (or (and (looking-at "[ \t]*:END:")
20836 (re-search-backward org-drawer-regexp nil t))
20837 (and (looking-at "[ \t]*#\\+end_")
20838 (re-search-backward "[ \t]*#\\+begin_"nil t))
20839 (looking-at "[ \t]*[\n:#|]")
20840 (looking-at org-footnote-definition-re)
20841 (and (ignore-errors (goto-char (org-in-item-p)))
20842 (goto-char
20843 (org-list-get-top-point (org-list-struct))))
20844 (and (not inline-task-p)
20845 (featurep 'org-inlinetask)
20846 (org-inlinetask-in-task-p)
20847 (or (org-inlinetask-goto-beginning) t))))
20848 (beginning-of-line 0))
20849 (cond
20850 ;; There was an heading above.
20851 ((looking-at "\\*+[ \t]+")
20852 (if (not org-adapt-indentation)
20853 (setq column 0)
20854 (goto-char (match-end 0))
20855 (setq column (current-column))))
20856 ;; A drawer had started and is unfinished
20857 ((looking-at org-drawer-regexp)
20858 (goto-char (1- (match-beginning 1)))
20859 (setq column (current-column)))
20860 ;; Else, nothing noticeable found: get indentation and go on.
20861 (t (setq column (org-get-indentation))))))
20862 ;; Now apply indentation and move cursor accordingly
20863 (goto-char pos)
20864 (if (<= (current-column) (current-indentation))
20865 (org-indent-line-to column)
20866 (save-excursion (org-indent-line-to column)))
20867 ;; Special polishing for properties, see `org-property-format'
20868 (setq column (current-column))
20869 (beginning-of-line 1)
20870 (if (looking-at
20871 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20872 (replace-match (concat (match-string 1)
20873 (format org-property-format
20874 (match-string 2) (match-string 3)))
20875 t t))
20876 (org-move-to-column column))))
20878 (defun org-indent-drawer ()
20879 "Indent the drawer at point."
20880 (interactive)
20881 (let ((p (point))
20882 (e (and (save-excursion (re-search-forward ":END:" nil t))
20883 (match-end 0)))
20884 (folded
20885 (save-excursion
20886 (end-of-line)
20887 (when (overlays-at (point))
20888 (member 'invisible (overlay-properties
20889 (car (overlays-at (point)))))))))
20890 (when folded (org-cycle))
20891 (indent-for-tab-command)
20892 (while (and (move-beginning-of-line 2) (< (point) e))
20893 (indent-for-tab-command))
20894 (goto-char p)
20895 (when folded (org-cycle)))
20896 (message "Drawer at point indented"))
20898 (defun org-indent-block ()
20899 "Indent the block at point."
20900 (interactive)
20901 (let ((p (point))
20902 (case-fold-search t)
20903 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20904 (match-end 0)))
20905 (folded
20906 (save-excursion
20907 (end-of-line)
20908 (when (overlays-at (point))
20909 (member 'invisible (overlay-properties
20910 (car (overlays-at (point)))))))))
20911 (when folded (org-cycle))
20912 (indent-for-tab-command)
20913 (while (and (move-beginning-of-line 2) (< (point) e))
20914 (indent-for-tab-command))
20915 (goto-char p)
20916 (when folded (org-cycle)))
20917 (message "Block at point indented"))
20919 (defun org-indent-region (start end)
20920 "Indent region."
20921 (interactive "r")
20922 (save-excursion
20923 (let ((line-end (org-current-line end)))
20924 (goto-char start)
20925 (while (< (org-current-line) line-end)
20926 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
20927 (t (call-interactively 'org-indent-line)))
20928 (move-beginning-of-line 2)))))
20931 ;;; Filling
20933 ;; We use our own fill-paragraph and auto-fill functions.
20935 ;; `org-fill-paragraph' relies on adaptive filling and context
20936 ;; checking. Appropriate `fill-prefix' is computed with
20937 ;; `org-adaptive-fill-function'.
20939 ;; `org-auto-fill-function' takes care of auto-filling. It calls
20940 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
20941 ;; `org-adaptive-fill-function' value. Internally,
20942 ;; `org-comment-line-break-function' breaks the line.
20944 ;; `org-setup-filling' installs filling and auto-filling related
20945 ;; variables during `org-mode' initialization.
20947 (defun org-setup-filling ()
20948 (interactive)
20949 ;; Prevent auto-fill from inserting unwanted new items.
20950 (when (boundp 'fill-nobreak-predicate)
20951 (org-set-local
20952 'fill-nobreak-predicate
20953 (org-uniquify
20954 (append fill-nobreak-predicate
20955 '(org-fill-paragraph-separate-nobreak-p
20956 org-fill-line-break-nobreak-p)))))
20957 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20958 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
20959 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20960 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
20962 (defvar org-element-paragraph-separate) ; org-element.el
20963 (defun org-fill-paragraph-separate-nobreak-p ()
20964 "Non-nil when a line break at point would insert a new item."
20965 (looking-at (substring org-element-paragraph-separate 1)))
20967 (defun org-fill-line-break-nobreak-p ()
20968 "Non-nil when a line break at point would create an Org line break."
20969 (save-excursion
20970 (skip-chars-backward "[ \t]")
20971 (skip-chars-backward "\\\\")
20972 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
20974 (declare-function message-in-body-p "message" ())
20975 (defvar org-element--affiliated-re) ; From org-element.el
20976 (defun org-adaptive-fill-function ()
20977 "Compute a fill prefix for the current line.
20978 Return fill prefix, as a string, or nil if current line isn't
20979 meant to be filled."
20980 (let (prefix)
20981 (when (and (derived-mode-p 'message-mode) (message-in-body-p))
20982 (save-excursion
20983 (beginning-of-line)
20984 (cond ((looking-at message-cite-prefix-regexp)
20985 (setq prefix (match-string-no-properties 0)))
20986 ((looking-at org-outline-regexp)
20987 (setq prefix "")))))
20988 (or prefix
20989 (org-with-wide-buffer
20990 (let* ((p (line-beginning-position))
20991 (element (save-excursion (beginning-of-line) (org-element-at-point)))
20992 (type (org-element-type element))
20993 (post-affiliated
20994 (save-excursion
20995 (goto-char (org-element-property :begin element))
20996 (while (looking-at org-element--affiliated-re) (forward-line))
20997 (point))))
20998 (unless (< p post-affiliated)
20999 (case type
21000 (comment (looking-at "[ \t]*# ?") (match-string 0))
21001 (footnote-definition "")
21002 ((item plain-list)
21003 (make-string (org-list-item-body-column post-affiliated) ? ))
21004 (paragraph
21005 ;; Fill prefix is usually the same as the current line,
21006 ;; except if the paragraph is at the beginning of an item.
21007 (let ((parent (org-element-property :parent element)))
21008 (cond ((eq (org-element-type parent) 'item)
21009 (make-string (org-list-item-body-column
21010 (org-element-property :begin parent))
21011 ? ))
21012 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21013 (match-string 0))
21014 (t ""))))
21015 (comment-block
21016 ;; Only fill contents if P is within block boundaries.
21017 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21018 (forward-line)
21019 (point)))
21020 (cend (save-excursion
21021 (goto-char (org-element-property :end element))
21022 (skip-chars-backward " \r\t\n")
21023 (line-beginning-position))))
21024 (when (and (>= p cbeg) (< p cend))
21025 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21026 (match-string 0)
21027 "")))))))))))
21029 (declare-function message-goto-body "message" ())
21030 (defvar message-cite-prefix-regexp) ; From message.el
21031 (defvar org-element-all-objects) ; From org-element.el
21032 (defun org-fill-paragraph (&optional justify)
21033 "Fill element at point, when applicable.
21035 This function only applies to comment blocks, comments, example
21036 blocks and paragraphs. Also, as a special case, re-align table
21037 when point is at one.
21039 If JUSTIFY is non-nil (interactively, with prefix argument),
21040 justify as well. If `sentence-end-double-space' is non-nil, then
21041 period followed by one space does not end a sentence, so don't
21042 break a line there. The variable `fill-column' controls the
21043 width for filling.
21045 For convenience, when point is at a plain list, an item or
21046 a footnote definition, try to fill the first paragraph within."
21047 (interactive)
21048 (if (and (derived-mode-p 'message-mode)
21049 (or (not (message-in-body-p))
21050 (save-excursion (move-beginning-of-line 1)
21051 (looking-at message-cite-prefix-regexp))))
21052 ;; First ensure filling is correct in message-mode.
21053 (let ((fill-paragraph-function
21054 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21055 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21056 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21057 (paragraph-separate
21058 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21059 (fill-paragraph nil))
21060 (save-excursion
21061 ;; Move to end of line in order to get the first paragraph
21062 ;; within a plain list or a footnote definition.
21063 (end-of-line)
21064 (let ((element (org-element-at-point)))
21065 ;; First check if point is in a blank line at the beginning of
21066 ;; the buffer. In that case, ignore filling.
21067 (if (< (point) (org-element-property :begin element)) t
21068 (case (org-element-type element)
21069 ;; Use major mode filling function is src blocks.
21070 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21071 ;; Align Org tables, leave table.el tables as-is.
21072 (table-row (org-table-align) t)
21073 (table
21074 (when (eq (org-element-property :type element) 'org)
21075 (org-table-align))
21077 (paragraph
21078 ;; Paragraphs may contain `line-break' type objects.
21079 (let ((beg (max (point-min)
21080 (org-element-property :contents-begin element)))
21081 (end (min (point-max)
21082 (org-element-property :contents-end element))))
21083 ;; Do nothing if point is at an affiliated keyword.
21084 (if (< (point) beg) t
21085 (when (derived-mode-p 'message-mode)
21086 ;; In `message-mode', do not fill following
21087 ;; citation in current paragraph nor text before
21088 ;; message body.
21089 (let ((body-start (save-excursion (message-goto-body))))
21090 (when body-start (setq beg (max body-start beg))))
21091 (when (save-excursion
21092 (re-search-forward
21093 (concat "^" message-cite-prefix-regexp) end t))
21094 (setq end (match-beginning 0))))
21095 ;; Fill paragraph, taking line breaks into
21096 ;; consideration. For that, slice the paragraph
21097 ;; using line breaks as separators, and fill the
21098 ;; parts in reverse order to avoid messing with
21099 ;; markers.
21100 (save-excursion
21101 (goto-char end)
21102 (mapc
21103 (lambda (pos)
21104 (fill-region-as-paragraph pos (point) justify)
21105 (goto-char pos))
21106 ;; Find the list of ending positions for line
21107 ;; breaks in the current paragraph. Add paragraph
21108 ;; beginning to include first slice.
21109 (nreverse
21110 (cons
21112 (org-element-map
21113 (org-element--parse-objects
21114 beg end nil org-element-all-objects)
21115 'line-break
21116 (lambda (lb) (org-element-property :end lb)))))))
21117 t)))
21118 ;; Contents of `comment-block' type elements should be
21119 ;; filled as plain text, but only if point is within block
21120 ;; markers.
21121 (comment-block
21122 (let* ((case-fold-search t)
21123 (beg (save-excursion
21124 (goto-char (org-element-property :begin element))
21125 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21126 (forward-line)
21127 (point)))
21128 (end (save-excursion
21129 (goto-char (org-element-property :end element))
21130 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21131 (line-beginning-position))))
21132 (when (and (>= (point) beg) (< (point) end))
21133 (fill-region-as-paragraph
21134 (save-excursion
21135 (end-of-line)
21136 (re-search-backward "^[ \t]*$" beg 'move)
21137 (line-beginning-position))
21138 (save-excursion
21139 (beginning-of-line)
21140 (re-search-forward "^[ \t]*$" end 'move)
21141 (line-beginning-position))
21142 justify)))
21144 ;; Fill comments.
21145 (comment (fill-comment-paragraph justify))
21146 ;; Ignore every other element.
21147 (otherwise t)))))))
21149 (defun org-auto-fill-function ()
21150 "Auto-fill function."
21151 ;; Check if auto-filling is meaningful.
21152 (let ((fc (current-fill-column)))
21153 (when (and fc (> (current-column) fc))
21154 (let* ((fill-prefix (org-adaptive-fill-function))
21155 ;; Enforce empty fill prefix, if required. Otherwise, it
21156 ;; will be computed again.
21157 (adaptive-fill-mode (not (equal fill-prefix ""))))
21158 (when fill-prefix (do-auto-fill))))))
21160 (defun org-comment-line-break-function (&optional soft)
21161 "Break line at point and indent, continuing comment if within one.
21162 The inserted newline is marked hard if variable
21163 `use-hard-newlines' is true, unless optional argument SOFT is
21164 non-nil."
21165 (if soft (insert-and-inherit ?\n) (newline 1))
21166 (save-excursion (forward-char -1) (delete-horizontal-space))
21167 (delete-horizontal-space)
21168 (indent-to-left-margin)
21169 (insert-before-markers-and-inherit fill-prefix))
21172 ;;; Comments
21174 ;; Org comments syntax is quite complex. It requires the entire line
21175 ;; to be just a comment. Also, even with the right syntax at the
21176 ;; beginning of line, some some elements (i.e. verse-block or
21177 ;; example-block) don't accept comments. Usual Emacs comment commands
21178 ;; cannot cope with those requirements. Therefore, Org replaces them.
21180 ;; Org still relies on `comment-dwim', but cannot trust
21181 ;; `comment-only-p'. So, `comment-region-function' and
21182 ;; `uncomment-region-function' both point
21183 ;; to`org-comment-or-uncomment-region'. Eventually,
21184 ;; `org-insert-comment' takes care of insertion of comments at the
21185 ;; beginning of line.
21187 ;; `org-setup-comments-handling' install comments related variables
21188 ;; during `org-mode' initialization.
21190 (defun org-setup-comments-handling ()
21191 (interactive)
21192 (org-set-local 'comment-use-syntax nil)
21193 (org-set-local 'comment-start "# ")
21194 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21195 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21196 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21197 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21199 (defun org-insert-comment ()
21200 "Insert an empty comment above current line.
21201 If the line is empty, insert comment at its beginning."
21202 (beginning-of-line)
21203 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21204 (org-indent-line)
21205 (insert "# "))
21207 (defvar comment-empty-lines) ; From newcomment.el.
21208 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21209 "Comment or uncomment each non-blank line in the region.
21210 Uncomment each non-blank line between BEG and END if it only
21211 contains commented lines. Otherwise, comment them."
21212 (save-restriction
21213 ;; Restrict region
21214 (narrow-to-region (save-excursion (goto-char beg)
21215 (skip-chars-forward " \r\t\n" end)
21216 (line-beginning-position))
21217 (save-excursion (goto-char end)
21218 (skip-chars-backward " \r\t\n" beg)
21219 (line-end-position)))
21220 (let ((uncommentp
21221 ;; UNCOMMENTP is non-nil when every non blank line between
21222 ;; BEG and END is a comment.
21223 (save-excursion
21224 (goto-char (point-min))
21225 (while (and (not (eobp))
21226 (let ((element (org-element-at-point)))
21227 (and (eq (org-element-type element) 'comment)
21228 (goto-char (min (point-max)
21229 (org-element-property
21230 :end element)))))))
21231 (eobp))))
21232 (if uncommentp
21233 ;; Only blank lines and comments in region: uncomment it.
21234 (save-excursion
21235 (goto-char (point-min))
21236 (while (not (eobp))
21237 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21238 (replace-match "" nil nil nil 1))
21239 (forward-line)))
21240 ;; Comment each line in region.
21241 (let ((min-indent (point-max)))
21242 ;; First find the minimum indentation across all lines.
21243 (save-excursion
21244 (goto-char (point-min))
21245 (while (and (not (eobp)) (not (zerop min-indent)))
21246 (unless (looking-at "[ \t]*$")
21247 (setq min-indent (min min-indent (current-indentation))))
21248 (forward-line)))
21249 ;; Then loop over all lines.
21250 (save-excursion
21251 (goto-char (point-min))
21252 (while (not (eobp))
21253 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21254 (org-move-to-column min-indent t)
21255 (insert comment-start))
21256 (forward-line))))))))
21259 ;;; Other stuff.
21261 (defun org-toggle-fixed-width-section (arg)
21262 "Toggle the fixed-width export.
21263 If there is no active region, the QUOTE keyword at the current headline is
21264 inserted or removed. When present, it causes the text between this headline
21265 and the next to be exported as fixed-width text, and unmodified.
21266 If there is an active region, this command adds or removes a colon as the
21267 first character of this line. If the first character of a line is a colon,
21268 this line is also exported in fixed-width font."
21269 (interactive "P")
21270 (let* ((cc 0)
21271 (regionp (org-region-active-p))
21272 (beg (if regionp (region-beginning) (point)))
21273 (end (if regionp (region-end)))
21274 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21275 (case-fold-search nil)
21276 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21277 off)
21278 (if regionp
21279 (save-excursion
21280 (goto-char beg)
21281 (setq cc (current-column))
21282 (beginning-of-line 1)
21283 (setq off (looking-at re))
21284 (while (> nlines 0)
21285 (setq nlines (1- nlines))
21286 (beginning-of-line 1)
21287 (cond
21288 (arg
21289 (org-move-to-column cc t)
21290 (insert ": \n")
21291 (forward-line -1))
21292 ((and off (looking-at re))
21293 (replace-match "" t t nil 1))
21294 ((not off) (org-move-to-column cc t) (insert ": ")))
21295 (forward-line 1)))
21296 (save-excursion
21297 (org-back-to-heading)
21298 (cond
21299 ((looking-at (format org-heading-keyword-regexp-format
21300 org-quote-string))
21301 (goto-char (match-end 1))
21302 (looking-at (concat " +" org-quote-string))
21303 (replace-match "" t t)
21304 (when (eolp) (insert " ")))
21305 ((looking-at org-outline-regexp)
21306 (goto-char (match-end 0))
21307 (insert org-quote-string " ")))))))
21309 (defun org-reftex-citation ()
21310 "Use reftex-citation to insert a citation into the buffer.
21311 This looks for a line like
21313 #+BIBLIOGRAPHY: foo plain option:-d
21315 and derives from it that foo.bib is the bibliography file relevant
21316 for this document. It then installs the necessary environment for RefTeX
21317 to work in this buffer and calls `reftex-citation' to insert a citation
21318 into the buffer.
21320 Export of such citations to both LaTeX and HTML is handled by the contributed
21321 package org-exp-bibtex by Taru Karttunen."
21322 (interactive)
21323 (let ((reftex-docstruct-symbol 'rds)
21324 (reftex-cite-format "\\cite{%l}")
21325 rds bib)
21326 (save-excursion
21327 (save-restriction
21328 (widen)
21329 (let ((case-fold-search t)
21330 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21331 (if (not (save-excursion
21332 (or (re-search-forward re nil t)
21333 (re-search-backward re nil t))))
21334 (error "No bibliography defined in file")
21335 (setq bib (concat (match-string 1) ".bib")
21336 rds (list (list 'bib bib)))))))
21337 (call-interactively 'reftex-citation)))
21339 ;;;; Functions extending outline functionality
21341 (defun org-beginning-of-line (&optional arg)
21342 "Go to the beginning of the current line. If that is invisible, continue
21343 to a visible line beginning. This makes the function of C-a more intuitive.
21344 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21345 first attempt, and only move to after the tags when the cursor is already
21346 beyond the end of the headline."
21347 (interactive "P")
21348 (let ((pos (point))
21349 (special (if (consp org-special-ctrl-a/e)
21350 (car org-special-ctrl-a/e)
21351 org-special-ctrl-a/e))
21352 refpos)
21353 (if (org-bound-and-true-p visual-line-mode)
21354 (beginning-of-visual-line 1)
21355 (beginning-of-line 1))
21356 (if (and arg (fboundp 'move-beginning-of-line))
21357 (call-interactively 'move-beginning-of-line)
21358 (if (bobp)
21360 (backward-char 1)
21361 (if (org-truely-invisible-p)
21362 (while (and (not (bobp)) (org-truely-invisible-p))
21363 (backward-char 1)
21364 (beginning-of-line 1))
21365 (forward-char 1))))
21366 (when special
21367 (cond
21368 ((and (looking-at org-complex-heading-regexp)
21369 (= (char-after (match-end 1)) ?\ ))
21370 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21371 (point-at-eol)))
21372 (goto-char
21373 (if (eq special t)
21374 (cond ((> pos refpos) refpos)
21375 ((= pos (point)) refpos)
21376 (t (point)))
21377 (cond ((> pos (point)) (point))
21378 ((not (eq last-command this-command)) (point))
21379 (t refpos)))))
21380 ((org-at-item-p)
21381 ;; Being at an item and not looking at an the item means point
21382 ;; was previously moved to beginning of a visual line, which
21383 ;; doesn't contain the item. Therefore, do nothing special,
21384 ;; just stay here.
21385 (when (looking-at org-list-full-item-re)
21386 ;; Set special position at first white space character after
21387 ;; bullet, and check-box, if any.
21388 (let ((after-bullet
21389 (let ((box (match-end 3)))
21390 (if (not box) (match-end 1)
21391 (let ((after (char-after box)))
21392 (if (and after (= after ? )) (1+ box) box))))))
21393 ;; Special case: Move point to special position when
21394 ;; currently after it or at beginning of line.
21395 (if (eq special t)
21396 (when (or (> pos after-bullet) (= (point) pos))
21397 (goto-char after-bullet))
21398 ;; Reversed case: Move point to special position when
21399 ;; point was already at beginning of line and command is
21400 ;; repeated.
21401 (when (and (= (point) pos) (eq last-command this-command))
21402 (goto-char after-bullet))))))))
21403 (org-no-warnings
21404 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21406 (defun org-end-of-line (&optional arg)
21407 "Go to the end of the line.
21408 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
21409 tags on the first attempt, and only move to after the tags when
21410 the cursor is already beyond the end of the headline."
21411 (interactive "P")
21412 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
21413 org-special-ctrl-a/e))
21414 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
21415 'end-of-visual-line)
21416 ((fboundp 'move-end-of-line) 'move-end-of-line)
21417 (t 'end-of-line))))
21418 (if (or (not special) arg) (call-interactively move-fun)
21419 (let* ((element (save-excursion (beginning-of-line)
21420 (org-element-at-point)))
21421 (type (org-element-type element)))
21422 (cond
21423 ((memq type '(headline inlinetask))
21424 (let ((pos (point)))
21425 (beginning-of-line 1)
21426 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21427 (if (eq special t)
21428 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
21429 (goto-char (match-beginning 1))
21430 (goto-char (match-end 0)))
21431 (if (or (< pos (match-end 0))
21432 (not (eq this-command last-command)))
21433 (goto-char (match-end 0))
21434 (goto-char (match-beginning 1))))
21435 (call-interactively move-fun))))
21436 ((org-element-property :hiddenp element)
21437 ;; If element is hidden, `move-end-of-line' would put point
21438 ;; after it. Use `end-of-line' to stay on current line.
21439 (call-interactively 'end-of-line))
21440 (t (call-interactively move-fun)))))
21441 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21443 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21444 (define-key org-mode-map "\C-e" 'org-end-of-line)
21446 (defun org-backward-sentence (&optional arg)
21447 "Go to beginning of sentence, or beginning of table field.
21448 This will call `backward-sentence' or `org-table-beginning-of-field',
21449 depending on context."
21450 (interactive "P")
21451 (cond
21452 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21453 (t (call-interactively 'backward-sentence))))
21455 (defun org-forward-sentence (&optional arg)
21456 "Go to end of sentence, or end of table field.
21457 This will call `forward-sentence' or `org-table-end-of-field',
21458 depending on context."
21459 (interactive "P")
21460 (cond
21461 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21462 (t (call-interactively 'forward-sentence))))
21464 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21465 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21467 (defun org-kill-line (&optional arg)
21468 "Kill line, to tags or end of line."
21469 (interactive "P")
21470 (cond
21471 ((or (not org-special-ctrl-k)
21472 (bolp)
21473 (not (org-at-heading-p)))
21474 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21475 org-ctrl-k-protect-subtree)
21476 (if (or (eq org-ctrl-k-protect-subtree 'error)
21477 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21478 (error "C-k aborted - would kill hidden subtree")))
21479 (call-interactively
21480 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
21481 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21482 (kill-region (point) (match-beginning 1))
21483 (org-set-tags nil t))
21484 (t (kill-region (point) (point-at-eol)))))
21486 (define-key org-mode-map "\C-k" 'org-kill-line)
21488 (defun org-yank (&optional arg)
21489 "Yank. If the kill is a subtree, treat it specially.
21490 This command will look at the current kill and check if is a single
21491 subtree, or a series of subtrees[1]. If it passes the test, and if the
21492 cursor is at the beginning of a line or after the stars of a currently
21493 empty headline, then the yank is handled specially. How exactly depends
21494 on the value of the following variables, both set by default.
21496 org-yank-folded-subtrees
21497 When set, the subtree(s) will be folded after insertion, but only
21498 if doing so would now swallow text after the yanked text.
21500 org-yank-adjusted-subtrees
21501 When set, the subtree will be promoted or demoted in order to
21502 fit into the local outline tree structure, which means that the level
21503 will be adjusted so that it becomes the smaller one of the two
21504 *visible* surrounding headings.
21506 Any prefix to this command will cause `yank' to be called directly with
21507 no special treatment. In particular, a simple \\[universal-argument] prefix \
21508 will just
21509 plainly yank the text as it is.
21511 \[1] The test checks if the first non-white line is a heading
21512 and if there are no other headings with fewer stars."
21513 (interactive "P")
21514 (org-yank-generic 'yank arg))
21516 (defun org-yank-generic (command arg)
21517 "Perform some yank-like command.
21519 This function implements the behavior described in the `org-yank'
21520 documentation. However, it has been generalized to work for any
21521 interactive command with similar behavior."
21523 ;; pretend to be command COMMAND
21524 (setq this-command command)
21526 (if arg
21527 (call-interactively command)
21529 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21530 (and (org-kill-is-subtree-p)
21531 (or (bolp)
21532 (and (looking-at "[ \t]*$")
21533 (string-match
21534 "\\`\\*+\\'"
21535 (buffer-substring (point-at-bol) (point)))))))
21536 swallowp)
21537 (cond
21538 ((and subtreep org-yank-folded-subtrees)
21539 (let ((beg (point))
21540 end)
21541 (if (and subtreep org-yank-adjusted-subtrees)
21542 (org-paste-subtree nil nil 'for-yank)
21543 (call-interactively command))
21545 (setq end (point))
21546 (goto-char beg)
21547 (when (and (bolp) subtreep
21548 (not (setq swallowp
21549 (org-yank-folding-would-swallow-text beg end))))
21550 (org-with-limited-levels
21551 (or (looking-at org-outline-regexp)
21552 (re-search-forward org-outline-regexp-bol end t))
21553 (while (and (< (point) end) (looking-at org-outline-regexp))
21554 (hide-subtree)
21555 (org-cycle-show-empty-lines 'folded)
21556 (condition-case nil
21557 (outline-forward-same-level 1)
21558 (error (goto-char end))))))
21559 (when swallowp
21560 (message
21561 "Inserted text not folded because that would swallow text"))
21563 (goto-char end)
21564 (skip-chars-forward " \t\n\r")
21565 (beginning-of-line 1)
21566 (push-mark beg 'nomsg)))
21567 ((and subtreep org-yank-adjusted-subtrees)
21568 (let ((beg (point-at-bol)))
21569 (org-paste-subtree nil nil 'for-yank)
21570 (push-mark beg 'nomsg)))
21572 (call-interactively command))))))
21574 (defun org-yank-folding-would-swallow-text (beg end)
21575 "Would hide-subtree at BEG swallow any text after END?"
21576 (let (level)
21577 (org-with-limited-levels
21578 (save-excursion
21579 (goto-char beg)
21580 (when (or (looking-at org-outline-regexp)
21581 (re-search-forward org-outline-regexp-bol end t))
21582 (setq level (org-outline-level)))
21583 (goto-char end)
21584 (skip-chars-forward " \t\r\n\v\f")
21585 (if (or (eobp)
21586 (and (bolp) (looking-at org-outline-regexp)
21587 (<= (org-outline-level) level)))
21588 nil ; Nothing would be swallowed
21589 t))))) ; something would swallow
21591 (define-key org-mode-map "\C-y" 'org-yank)
21593 (defun org-truely-invisible-p ()
21594 "Check if point is at a character currently not visible.
21595 This version does not only check the character property, but also
21596 `visible-mode'."
21597 ;; Early versions of noutline don't have `outline-invisible-p'.
21598 (if (org-bound-and-true-p visible-mode)
21600 (outline-invisible-p)))
21602 (defun org-invisible-p2 ()
21603 "Check if point is at a character currently not visible."
21604 (save-excursion
21605 (if (and (eolp) (not (bobp))) (backward-char 1))
21606 ;; Early versions of noutline don't have `outline-invisible-p'.
21607 (outline-invisible-p)))
21609 (defun org-back-to-heading (&optional invisible-ok)
21610 "Call `outline-back-to-heading', but provide a better error message."
21611 (condition-case nil
21612 (outline-back-to-heading invisible-ok)
21613 (error (error "Before first headline at position %d in buffer %s"
21614 (point) (current-buffer)))))
21616 (defun org-before-first-heading-p ()
21617 "Before first heading?"
21618 (save-excursion
21619 (end-of-line)
21620 (null (re-search-backward org-outline-regexp-bol nil t))))
21622 (defun org-at-heading-p (&optional ignored)
21623 (outline-on-heading-p t))
21624 ;; Compatibility alias with Org versions < 7.8.03
21625 (defalias 'org-on-heading-p 'org-at-heading-p)
21627 (defun org-at-comment-p nil
21628 "Is cursor in a line starting with a # character?"
21629 (save-excursion
21630 (beginning-of-line)
21631 (looking-at "^#")))
21633 (defun org-at-drawer-p nil
21634 "Is cursor at a drawer keyword?"
21635 (save-excursion
21636 (move-beginning-of-line 1)
21637 (looking-at org-drawer-regexp)))
21639 (defun org-at-block-p nil
21640 "Is cursor at a block keyword?"
21641 (save-excursion
21642 (move-beginning-of-line 1)
21643 (looking-at org-block-regexp)))
21645 (defun org-point-at-end-of-empty-headline ()
21646 "If point is at the end of an empty headline, return t, else nil.
21647 If the heading only contains a TODO keyword, it is still still considered
21648 empty."
21649 (and (looking-at "[ \t]*$")
21650 (when org-todo-line-regexp
21651 (save-excursion
21652 (beginning-of-line 1)
21653 (let ((case-fold-search nil))
21654 (looking-at org-todo-line-regexp)
21655 (string= (match-string 3) ""))))))
21657 (defun org-at-heading-or-item-p ()
21658 (or (org-at-heading-p) (org-at-item-p)))
21660 (defun org-at-target-p ()
21661 (or (org-in-regexp org-radio-target-regexp)
21662 (org-in-regexp org-target-regexp)))
21663 ;; Compatibility alias with Org versions < 7.8.03
21664 (defalias 'org-on-target-p 'org-at-target-p)
21666 (defun org-up-heading-all (arg)
21667 "Move to the heading line of which the present line is a subheading.
21668 This function considers both visible and invisible heading lines.
21669 With argument, move up ARG levels."
21670 (if (fboundp 'outline-up-heading-all)
21671 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21672 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21674 (defun org-up-heading-safe ()
21675 "Move to the heading line of which the present line is a subheading.
21676 This version will not throw an error. It will return the level of the
21677 headline found, or nil if no higher level is found.
21679 Also, this function will be a lot faster than `outline-up-heading',
21680 because it relies on stars being the outline starters. This can really
21681 make a significant difference in outlines with very many siblings."
21682 (let (start-level re)
21683 (org-back-to-heading t)
21684 (setq start-level (funcall outline-level))
21685 (if (equal start-level 1)
21687 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21688 (if (re-search-backward re nil t)
21689 (funcall outline-level)))))
21691 (defun org-first-sibling-p ()
21692 "Is this heading the first child of its parents?"
21693 (interactive)
21694 (let ((re org-outline-regexp-bol)
21695 level l)
21696 (unless (org-at-heading-p t)
21697 (error "Not at a heading"))
21698 (setq level (funcall outline-level))
21699 (save-excursion
21700 (if (not (re-search-backward re nil t))
21702 (setq l (funcall outline-level))
21703 (< l level)))))
21705 (defun org-goto-sibling (&optional previous)
21706 "Goto the next sibling, even if it is invisible.
21707 When PREVIOUS is set, go to the previous sibling instead. Returns t
21708 when a sibling was found. When none is found, return nil and don't
21709 move point."
21710 (let ((fun (if previous 're-search-backward 're-search-forward))
21711 (pos (point))
21712 (re org-outline-regexp-bol)
21713 level l)
21714 (when (condition-case nil (org-back-to-heading t) (error nil))
21715 (setq level (funcall outline-level))
21716 (catch 'exit
21717 (or previous (forward-char 1))
21718 (while (funcall fun re nil t)
21719 (setq l (funcall outline-level))
21720 (when (< l level) (goto-char pos) (throw 'exit nil))
21721 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21722 (goto-char pos)
21723 nil))))
21725 (defun org-show-siblings ()
21726 "Show all siblings of the current headline."
21727 (save-excursion
21728 (while (org-goto-sibling) (org-flag-heading nil)))
21729 (save-excursion
21730 (while (org-goto-sibling 'previous)
21731 (org-flag-heading nil))))
21733 (defun org-goto-first-child ()
21734 "Goto the first child, even if it is invisible.
21735 Return t when a child was found. Otherwise don't move point and
21736 return nil."
21737 (let (level (pos (point)) (re org-outline-regexp-bol))
21738 (when (condition-case nil (org-back-to-heading t) (error nil))
21739 (setq level (outline-level))
21740 (forward-char 1)
21741 (if (and (re-search-forward re nil t) (> (outline-level) level))
21742 (progn (goto-char (match-beginning 0)) t)
21743 (goto-char pos) nil))))
21745 (defun org-show-hidden-entry ()
21746 "Show an entry where even the heading is hidden."
21747 (save-excursion
21748 (org-show-entry)))
21750 (defun org-flag-heading (flag &optional entry)
21751 "Flag the current heading. FLAG non-nil means make invisible.
21752 When ENTRY is non-nil, show the entire entry."
21753 (save-excursion
21754 (org-back-to-heading t)
21755 ;; Check if we should show the entire entry
21756 (if entry
21757 (progn
21758 (org-show-entry)
21759 (save-excursion
21760 (and (outline-next-heading)
21761 (org-flag-heading nil))))
21762 (outline-flag-region (max (point-min) (1- (point)))
21763 (save-excursion (outline-end-of-heading) (point))
21764 flag))))
21766 (defun org-get-next-sibling ()
21767 "Move to next heading of the same level, and return point.
21768 If there is no such heading, return nil.
21769 This is like outline-next-sibling, but invisible headings are ok."
21770 (let ((level (funcall outline-level)))
21771 (outline-next-heading)
21772 (while (and (not (eobp)) (> (funcall outline-level) level))
21773 (outline-next-heading))
21774 (if (or (eobp) (< (funcall outline-level) level))
21776 (point))))
21778 (defun org-get-last-sibling ()
21779 "Move to previous heading of the same level, and return point.
21780 If there is no such heading, return nil."
21781 (let ((opoint (point))
21782 (level (funcall outline-level)))
21783 (outline-previous-heading)
21784 (when (and (/= (point) opoint) (outline-on-heading-p t))
21785 (while (and (> (funcall outline-level) level)
21786 (not (bobp)))
21787 (outline-previous-heading))
21788 (if (< (funcall outline-level) level)
21790 (point)))))
21792 (defun org-end-of-subtree (&optional invisible-ok to-heading)
21793 "Goto to the end of a subtree."
21794 ;; This contains an exact copy of the original function, but it uses
21795 ;; `org-back-to-heading', to make it work also in invisible
21796 ;; trees. And is uses an invisible-ok argument.
21797 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21798 ;; Furthermore, when used inside Org, finding the end of a large subtree
21799 ;; with many children and grandchildren etc, this can be much faster
21800 ;; than the outline version.
21801 (org-back-to-heading invisible-ok)
21802 (let ((first t)
21803 (level (funcall outline-level)))
21804 (if (and (derived-mode-p 'org-mode) (< level 1000))
21805 ;; A true heading (not a plain list item), in Org-mode
21806 ;; This means we can easily find the end by looking
21807 ;; only for the right number of stars. Using a regexp to do
21808 ;; this is so much faster than using a Lisp loop.
21809 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21810 (forward-char 1)
21811 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21812 ;; something else, do it the slow way
21813 (while (and (not (eobp))
21814 (or first (> (funcall outline-level) level)))
21815 (setq first nil)
21816 (outline-next-heading)))
21817 (unless to-heading
21818 (if (memq (preceding-char) '(?\n ?\^M))
21819 (progn
21820 ;; Go to end of line before heading
21821 (forward-char -1)
21822 (if (memq (preceding-char) '(?\n ?\^M))
21823 ;; leave blank line before heading
21824 (forward-char -1))))))
21825 (point))
21827 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21828 "Use Org version in org-mode, for dramatic speed-up."
21829 (if (derived-mode-p 'org-mode)
21830 (progn
21831 (org-end-of-subtree nil t)
21832 (unless (eobp) (backward-char 1)))
21833 ad-do-it))
21835 (defun org-end-of-meta-data-and-drawers ()
21836 "Jump to the first text after meta data and drawers in the current entry.
21837 This will move over empty lines, lines with planning time stamps,
21838 clocking lines, and drawers."
21839 (org-back-to-heading t)
21840 (let ((end (save-excursion (outline-next-heading) (point)))
21841 (re (concat "\\(" org-drawer-regexp "\\)"
21842 "\\|" "[ \t]*" org-keyword-time-regexp)))
21843 (forward-line 1)
21844 (while (re-search-forward re end t)
21845 (if (not (match-end 1))
21846 ;; empty or planning line
21847 (forward-line 1)
21848 ;; a drawer, find the end
21849 (re-search-forward "^[ \t]*:END:" end 'move)
21850 (forward-line 1)))
21851 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21852 (point)))
21854 (defun org-forward-heading-same-level (arg &optional invisible-ok)
21855 "Move forward to the arg'th subheading at same level as this one.
21856 Stop at the first and last subheadings of a superior heading.
21857 Normally this only looks at visible headings, but when INVISIBLE-OK is
21858 non-nil it will also look at invisible ones."
21859 (interactive "p")
21860 (org-back-to-heading invisible-ok)
21861 (org-at-heading-p)
21862 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21863 (re (format "^\\*\\{1,%d\\} " level))
21865 (forward-char 1)
21866 (while (> arg 0)
21867 (while (and (re-search-forward re nil 'move)
21868 (setq l (- (match-end 0) (match-beginning 0) 1))
21869 (= l level)
21870 (not invisible-ok)
21871 (progn (backward-char 1) (outline-invisible-p)))
21872 (if (< l level) (setq arg 1)))
21873 (setq arg (1- arg)))
21874 (beginning-of-line 1)))
21876 (defun org-backward-heading-same-level (arg &optional invisible-ok)
21877 "Move backward to the arg'th subheading at same level as this one.
21878 Stop at the first and last subheadings of a superior heading."
21879 (interactive "p")
21880 (org-back-to-heading)
21881 (org-at-heading-p)
21882 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21883 (re (format "^\\*\\{1,%d\\} " level))
21885 (while (> arg 0)
21886 (while (and (re-search-backward re nil 'move)
21887 (setq l (- (match-end 0) (match-beginning 0) 1))
21888 (= l level)
21889 (not invisible-ok)
21890 (outline-invisible-p))
21891 (if (< l level) (setq arg 1)))
21892 (setq arg (1- arg)))))
21894 (defun org-forward-element ()
21895 "Move forward by one element.
21896 Move to the next element at the same level, when possible."
21897 (interactive)
21898 (cond ((eobp) (error "Cannot move further down"))
21899 ((org-with-limited-levels (org-at-heading-p))
21900 (let ((origin (point)))
21901 (org-forward-heading-same-level 1)
21902 (unless (org-with-limited-levels (org-at-heading-p))
21903 (goto-char origin)
21904 (error "Cannot move further down"))))
21906 (let* ((elem (org-element-at-point))
21907 (end (org-element-property :end elem))
21908 (parent (org-element-property :parent elem)))
21909 (if (and parent (= (org-element-property :contents-end parent) end))
21910 (goto-char (org-element-property :end parent))
21911 (goto-char end))))))
21913 (defun org-backward-element ()
21914 "Move backward by one element.
21915 Move to the previous element at the same level, when possible."
21916 (interactive)
21917 (cond ((bobp) (error "Cannot move further up"))
21918 ((org-with-limited-levels (org-at-heading-p))
21919 ;; At an headline, move to the previous one, if any, or stay
21920 ;; here.
21921 (let ((origin (point)))
21922 (org-backward-heading-same-level 1)
21923 (unless (org-with-limited-levels (org-at-heading-p))
21924 (goto-char origin)
21925 (error "Cannot move further up"))))
21927 (let* ((trail (org-element-at-point 'keep-trail))
21928 (elem (car trail))
21929 (prev-elem (nth 1 trail))
21930 (beg (org-element-property :begin elem)))
21931 (cond
21932 ;; Move to beginning of current element if point isn't
21933 ;; there already.
21934 ((/= (point) beg) (goto-char beg))
21935 (prev-elem (goto-char (org-element-property :begin prev-elem)))
21936 ((org-before-first-heading-p) (goto-char (point-min)))
21937 (t (org-back-to-heading)))))))
21939 (defun org-up-element ()
21940 "Move to upper element."
21941 (interactive)
21942 (if (org-with-limited-levels (org-at-heading-p))
21943 (unless (org-up-heading-safe) (error "No surrounding element"))
21944 (let* ((elem (org-element-at-point))
21945 (parent (org-element-property :parent elem)))
21946 (if parent (goto-char (org-element-property :begin parent))
21947 (if (org-with-limited-levels (org-before-first-heading-p))
21948 (error "No surrounding element")
21949 (org-with-limited-levels (org-back-to-heading)))))))
21951 (defvar org-element-greater-elements)
21952 (defun org-down-element ()
21953 "Move to inner element."
21954 (interactive)
21955 (let ((element (org-element-at-point)))
21956 (cond
21957 ((memq (org-element-type element) '(plain-list table))
21958 (goto-char (org-element-property :contents-begin element))
21959 (forward-char))
21960 ((memq (org-element-type element) org-element-greater-elements)
21961 ;; If contents are hidden, first disclose them.
21962 (when (org-element-property :hiddenp element) (org-cycle))
21963 (goto-char (or (org-element-property :contents-begin element)
21964 (error "No content for this element"))))
21965 (t (error "No inner element")))))
21967 (defun org-drag-element-backward ()
21968 "Move backward element at point."
21969 (interactive)
21970 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
21971 (let* ((trail (org-element-at-point 'keep-trail))
21972 (elem (car trail))
21973 (prev-elem (nth 1 trail)))
21974 ;; Error out if no previous element or previous element is
21975 ;; a parent of the current one.
21976 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
21977 (error "Cannot drag element backward")
21978 (let ((pos (point)))
21979 (org-element-swap-A-B prev-elem elem)
21980 (goto-char (+ (org-element-property :begin prev-elem)
21981 (- pos (org-element-property :begin elem)))))))))
21983 (defun org-drag-element-forward ()
21984 "Move forward element at point."
21985 (interactive)
21986 (let* ((pos (point))
21987 (elem (org-element-at-point)))
21988 (when (= (point-max) (org-element-property :end elem))
21989 (error "Cannot drag element forward"))
21990 (goto-char (org-element-property :end elem))
21991 (let ((next-elem (org-element-at-point)))
21992 (when (or (org-element-nested-p elem next-elem)
21993 (and (eq (org-element-type next-elem) 'headline)
21994 (not (eq (org-element-type elem) 'headline))))
21995 (goto-char pos)
21996 (error "Cannot drag element forward"))
21997 ;; Compute new position of point: it's shifted by NEXT-ELEM
21998 ;; body's length (without final blanks) and by the length of
21999 ;; blanks between ELEM and NEXT-ELEM.
22000 (let ((size-next (- (save-excursion
22001 (goto-char (org-element-property :end next-elem))
22002 (skip-chars-backward " \r\t\n")
22003 (forward-line)
22004 ;; Small correction if buffer doesn't end
22005 ;; with a newline character.
22006 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22007 (org-element-property :begin next-elem)))
22008 (size-blank (- (org-element-property :end elem)
22009 (save-excursion
22010 (goto-char (org-element-property :end elem))
22011 (skip-chars-backward " \r\t\n")
22012 (forward-line)
22013 (point)))))
22014 (org-element-swap-A-B elem next-elem)
22015 (goto-char (+ pos size-next size-blank))))))
22017 (defun org-mark-element ()
22018 "Put point at beginning of this element, mark at end.
22020 Interactively, if this command is repeated or (in Transient Mark
22021 mode) if the mark is active, it marks the next element after the
22022 ones already marked."
22023 (interactive)
22024 (let (deactivate-mark)
22025 (if (and (org-called-interactively-p 'any)
22026 (or (and (eq last-command this-command) (mark t))
22027 (and transient-mark-mode mark-active)))
22028 (set-mark
22029 (save-excursion
22030 (goto-char (mark))
22031 (goto-char (org-element-property :end (org-element-at-point)))))
22032 (let ((element (org-element-at-point)))
22033 (end-of-line)
22034 (push-mark (org-element-property :end element) t t)
22035 (goto-char (org-element-property :begin element))))))
22037 (defun org-narrow-to-element ()
22038 "Narrow buffer to current element."
22039 (interactive)
22040 (let ((elem (org-element-at-point)))
22041 (cond
22042 ((eq (car elem) 'headline)
22043 (narrow-to-region
22044 (org-element-property :begin elem)
22045 (org-element-property :end elem)))
22046 ((memq (car elem) org-element-greater-elements)
22047 (narrow-to-region
22048 (org-element-property :contents-begin elem)
22049 (org-element-property :contents-end elem)))
22051 (narrow-to-region
22052 (org-element-property :begin elem)
22053 (org-element-property :end elem))))))
22055 (defun org-transpose-element ()
22056 "Transpose current and previous elements, keeping blank lines between.
22057 Point is moved after both elements."
22058 (interactive)
22059 (org-skip-whitespace)
22060 (let ((end (org-element-property :end (org-element-at-point))))
22061 (org-drag-element-backward)
22062 (goto-char end)))
22064 (defun org-unindent-buffer ()
22065 "Un-indent the visible part of the buffer.
22066 Relative indentation (between items, inside blocks, etc.) isn't
22067 modified."
22068 (interactive)
22069 (unless (eq major-mode 'org-mode)
22070 (error "Cannot un-indent a buffer not in Org mode"))
22071 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22072 unindent-tree ; For byte-compiler.
22073 (unindent-tree
22074 (function
22075 (lambda (contents)
22076 (mapc
22077 (lambda (element)
22078 (if (memq (org-element-type element) '(headline section))
22079 (funcall unindent-tree (org-element-contents element))
22080 (save-excursion
22081 (save-restriction
22082 (narrow-to-region
22083 (org-element-property :begin element)
22084 (org-element-property :end element))
22085 (org-do-remove-indentation)))))
22086 (reverse contents))))))
22087 (funcall unindent-tree (org-element-contents parse-tree))))
22089 (defun org-show-subtree ()
22090 "Show everything after this heading at deeper levels."
22091 (interactive)
22092 (outline-flag-region
22093 (point)
22094 (save-excursion
22095 (org-end-of-subtree t t))
22096 nil))
22098 (defun org-show-entry ()
22099 "Show the body directly following this heading.
22100 Show the heading too, if it is currently invisible."
22101 (interactive)
22102 (save-excursion
22103 (condition-case nil
22104 (progn
22105 (org-back-to-heading t)
22106 (outline-flag-region
22107 (max (point-min) (1- (point)))
22108 (save-excursion
22109 (if (re-search-forward
22110 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22111 (match-beginning 1)
22112 (point-max)))
22113 nil)
22114 (org-cycle-hide-drawers 'children))
22115 (error nil))))
22117 (defun org-make-options-regexp (kwds &optional extra)
22118 "Make a regular expression for keyword lines."
22119 (concat
22120 "^#\\+\\("
22121 (mapconcat 'regexp-quote kwds "\\|")
22122 (if extra (concat "\\|" extra))
22123 "\\):[ \t]*\\(.*\\)"))
22125 ;; Make isearch reveal the necessary context
22126 (defun org-isearch-end ()
22127 "Reveal context after isearch exits."
22128 (when isearch-success ; only if search was successful
22129 (if (featurep 'xemacs)
22130 ;; Under XEmacs, the hook is run in the correct place,
22131 ;; we directly show the context.
22132 (org-show-context 'isearch)
22133 ;; In Emacs the hook runs *before* restoring the overlays.
22134 ;; So we have to use a one-time post-command-hook to do this.
22135 ;; (Emacs 22 has a special variable, see function `org-mode')
22136 (unless (and (boundp 'isearch-mode-end-hook-quit)
22137 isearch-mode-end-hook-quit)
22138 ;; Only when the isearch was not quitted.
22139 (org-add-hook 'post-command-hook 'org-isearch-post-command
22140 'append 'local)))))
22142 (defun org-isearch-post-command ()
22143 "Remove self from hook, and show context."
22144 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22145 (org-show-context 'isearch))
22148 ;;;; Integration with and fixes for other packages
22150 ;;; Imenu support
22152 (defvar org-imenu-markers nil
22153 "All markers currently used by Imenu.")
22154 (make-variable-buffer-local 'org-imenu-markers)
22156 (defun org-imenu-new-marker (&optional pos)
22157 "Return a new marker for use by Imenu, and remember the marker."
22158 (let ((m (make-marker)))
22159 (move-marker m (or pos (point)))
22160 (push m org-imenu-markers)
22163 (defun org-imenu-get-tree ()
22164 "Produce the index for Imenu."
22165 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22166 (setq org-imenu-markers nil)
22167 (let* ((n org-imenu-depth)
22168 (re (concat "^" (org-get-limited-outline-regexp)))
22169 (subs (make-vector (1+ n) nil))
22170 (last-level 0)
22171 m level head)
22172 (save-excursion
22173 (save-restriction
22174 (widen)
22175 (goto-char (point-max))
22176 (while (re-search-backward re nil t)
22177 (setq level (org-reduced-level (funcall outline-level)))
22178 (when (and (<= level n)
22179 (looking-at org-complex-heading-regexp))
22180 (setq head (org-link-display-format
22181 (org-match-string-no-properties 4))
22182 m (org-imenu-new-marker))
22183 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22184 (if (>= level last-level)
22185 (push (cons head m) (aref subs level))
22186 (push (cons head (aref subs (1+ level))) (aref subs level))
22187 (loop for i from (1+ level) to n do (aset subs i nil)))
22188 (setq last-level level)))))
22189 (aref subs 1)))
22191 (eval-after-load "imenu"
22192 '(progn
22193 (add-hook 'imenu-after-jump-hook
22194 (lambda ()
22195 (if (derived-mode-p 'org-mode)
22196 (org-show-context 'org-goto))))))
22198 (defun org-link-display-format (link)
22199 "Replace a link with either the description, or the link target
22200 if no description is present"
22201 (save-match-data
22202 (if (string-match org-bracket-link-analytic-regexp link)
22203 (replace-match (if (match-end 5)
22204 (match-string 5 link)
22205 (concat (match-string 1 link)
22206 (match-string 3 link)))
22207 nil t link)
22208 link)))
22210 (defun org-toggle-link-display ()
22211 "Toggle the literal or descriptive display of links."
22212 (interactive)
22213 (if org-descriptive-links
22214 (progn (org-remove-from-invisibility-spec '(org-link))
22215 (org-restart-font-lock)
22216 (setq org-descriptive-links nil))
22217 (progn (add-to-invisibility-spec '(org-link))
22218 (org-restart-font-lock)
22219 (setq org-descriptive-links t))))
22221 ;; Speedbar support
22223 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22224 "Overlay marking the agenda restriction line in speedbar.")
22225 (overlay-put org-speedbar-restriction-lock-overlay
22226 'face 'org-agenda-restriction-lock)
22227 (overlay-put org-speedbar-restriction-lock-overlay
22228 'help-echo "Agendas are currently limited to this item.")
22229 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22231 (defun org-speedbar-set-agenda-restriction ()
22232 "Restrict future agenda commands to the location at point in speedbar.
22233 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22234 (interactive)
22235 (require 'org-agenda)
22236 (let (p m tp np dir txt)
22237 (cond
22238 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22239 'org-imenu t))
22240 (setq m (get-text-property p 'org-imenu-marker))
22241 (with-current-buffer (marker-buffer m)
22242 (goto-char m)
22243 (org-agenda-set-restriction-lock 'subtree)))
22244 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22245 'speedbar-function 'speedbar-find-file))
22246 (setq tp (previous-single-property-change
22247 (1+ p) 'speedbar-function)
22248 np (next-single-property-change
22249 tp 'speedbar-function)
22250 dir (speedbar-line-directory)
22251 txt (buffer-substring-no-properties (or tp (point-min))
22252 (or np (point-max))))
22253 (with-current-buffer (find-file-noselect
22254 (let ((default-directory dir))
22255 (expand-file-name txt)))
22256 (unless (derived-mode-p 'org-mode)
22257 (error "Cannot restrict to non-Org-mode file"))
22258 (org-agenda-set-restriction-lock 'file)))
22259 (t (error "Don't know how to restrict Org-mode's agenda")))
22260 (move-overlay org-speedbar-restriction-lock-overlay
22261 (point-at-bol) (point-at-eol))
22262 (setq current-prefix-arg nil)
22263 (org-agenda-maybe-redo)))
22265 (eval-after-load "speedbar"
22266 '(progn
22267 (speedbar-add-supported-extension ".org")
22268 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22269 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22270 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22271 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22272 (add-hook 'speedbar-visiting-tag-hook
22273 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22275 ;;; Fixes and Hacks for problems with other packages
22277 ;; Make flyspell not check words in links, to not mess up our keymap
22278 (defun org-mode-flyspell-verify ()
22279 "Don't let flyspell put overlays at active buttons, or on
22280 {todo,all-time,additional-option-like}-keywords."
22281 (let ((pos (max (1- (point)) (point-min)))
22282 (word (thing-at-point 'word)))
22283 (and (not (get-text-property pos 'keymap))
22284 (not (get-text-property pos 'org-no-flyspell))
22285 (not (member word org-todo-keywords-1))
22286 (not (member word org-all-time-keywords))
22287 (not (member word org-options-keywords))
22288 (not (member word (mapcar 'car org-startup-options)))
22289 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22291 (defun org-remove-flyspell-overlays-in (beg end)
22292 "Remove flyspell overlays in region."
22293 (and (org-bound-and-true-p flyspell-mode)
22294 (fboundp 'flyspell-delete-region-overlays)
22295 (flyspell-delete-region-overlays beg end))
22296 (add-text-properties beg end '(org-no-flyspell t)))
22298 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22299 (eval-after-load "bookmark"
22300 '(if (boundp 'bookmark-after-jump-hook)
22301 ;; We can use the hook
22302 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22303 ;; Hook not available, use advice
22304 (defadvice bookmark-jump (after org-make-visible activate)
22305 "Make the position visible."
22306 (org-bookmark-jump-unhide))))
22308 ;; Make sure saveplace shows the location if it was hidden
22309 (eval-after-load "saveplace"
22310 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22311 "Make the position visible."
22312 (org-bookmark-jump-unhide)))
22314 ;; Make sure ecb shows the location if it was hidden
22315 (eval-after-load "ecb"
22316 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22317 "Make hierarchy visible when jumping into location from ECB tree buffer."
22318 (if (derived-mode-p 'org-mode)
22319 (org-show-context))))
22321 (defun org-bookmark-jump-unhide ()
22322 "Unhide the current position, to show the bookmark location."
22323 (and (derived-mode-p 'org-mode)
22324 (or (outline-invisible-p)
22325 (save-excursion (goto-char (max (point-min) (1- (point))))
22326 (outline-invisible-p)))
22327 (org-show-context 'bookmark-jump)))
22329 ;; Make session.el ignore our circular variable
22330 (eval-after-load "session"
22331 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22333 ;;;; Experimental code
22335 (defun org-closed-in-range ()
22336 "Sparse tree of items closed in a certain time range.
22337 Still experimental, may disappear in the future."
22338 (interactive)
22339 ;; Get the time interval from the user.
22340 (let* ((time1 (org-float-time
22341 (org-read-date nil 'to-time nil "Starting date: ")))
22342 (time2 (org-float-time
22343 (org-read-date nil 'to-time nil "End date:")))
22344 ;; callback function
22345 (callback (lambda ()
22346 (let ((time
22347 (org-float-time
22348 (apply 'encode-time
22349 (org-parse-time-string
22350 (match-string 1))))))
22351 ;; check if time in interval
22352 (and (>= time time1) (<= time time2))))))
22353 ;; make tree, check each match with the callback
22354 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22356 ;;;; Finish up
22358 (provide 'org)
22360 (run-hooks 'org-load-hook)
22362 ;;; org.el ends here