org.el (org-set-font-lock-defaults): Don't activate links in source code blocks and...
[org-mode/org-tableheadings.git] / lisp / org.el
blob0000798305e39d0953215fbf3a42c959b800c9cf
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2012 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 (load "org-loaddefs.el" t t)
83 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
84 ;; some places -- e.g. see the macro org-with-limited-levels.
86 ;; In Org buffers, the value of `outline-regexp' is that of
87 ;; `org-outline-regexp'. The only function still directly relying on
88 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
89 ;; job when `orgstruct-mode' is active.
90 (defvar org-outline-regexp "\\*+ "
91 "Regexp to match Org headlines.")
93 (defvar org-outline-regexp-bol "^\\*+ "
94 "Regexp to match Org headlines.
95 This is similar to `org-outline-regexp' but additionally makes
96 sure that we are at the beginning of the line.")
98 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
99 "Matches an headline, putting stars and text into groups.
100 Stars are put in group 1 and the trimmed body in group 2.")
102 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
103 (when (fboundp 'defvaralias)
104 (unless (boundp 'calendar-view-holidays-initially-flag)
105 (defvaralias 'calendar-view-holidays-initially-flag
106 'view-calendar-holidays-initially))
107 (unless (boundp 'calendar-view-diary-initially-flag)
108 (defvaralias 'calendar-view-diary-initially-flag
109 'view-diary-entries-initially))
110 (unless (boundp 'diary-fancy-buffer)
111 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
113 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
114 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
115 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
116 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
117 (declare-function org-at-clock-log-p "org-clock" ())
118 (declare-function org-clock-timestamps-up "org-clock" ())
119 (declare-function org-clock-timestamps-down "org-clock" ())
120 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
122 (declare-function orgtbl-mode "org-table" (&optional arg))
123 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
124 (declare-function org-beamer-mode "org-beamer" ())
125 (declare-function org-table-edit-field "org-table" (arg))
126 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
127 (declare-function org-id-get-create "org-id" (&optional force))
128 (declare-function org-id-find-id-file "org-id" (id))
129 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
130 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
131 (declare-function org-table-align "org-table" ())
132 (declare-function org-table-paste-rectangle "org-table" ())
133 (declare-function org-table-maybe-eval-formula "org-table" ())
134 (declare-function org-table-maybe-recalculate-line "org-table" ())
136 ;; load languages based on value of `org-babel-load-languages'
137 (defvar org-babel-load-languages)
139 ;;;###autoload
140 (defun org-babel-do-load-languages (sym value)
141 "Load the languages defined in `org-babel-load-languages'."
142 (set-default sym value)
143 (mapc (lambda (pair)
144 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
145 (if active
146 (progn
147 (require (intern (concat "ob-" lang))))
148 (progn
149 (funcall 'fmakunbound
150 (intern (concat "org-babel-execute:" lang)))
151 (funcall 'fmakunbound
152 (intern (concat "org-babel-expand-body:" lang)))))))
153 org-babel-load-languages))
155 (defcustom org-babel-load-languages '((emacs-lisp . t))
156 "Languages which can be evaluated in Org-mode buffers.
157 This list can be used to load support for any of the languages
158 below, note that each language will depend on a different set of
159 system executables and/or Emacs modes. When a language is
160 \"loaded\", then code blocks in that language can be evaluated
161 with `org-babel-execute-src-block' bound by default to C-c
162 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
163 be set to remove code block evaluation from the C-c C-c
164 keybinding. By default only Emacs Lisp (which has no
165 requirements) is loaded."
166 :group 'org-babel
167 :set 'org-babel-do-load-languages
168 :version "24.1"
169 :type '(alist :tag "Babel Languages"
170 :key-type
171 (choice
172 (const :tag "Awk" awk)
173 (const :tag "C" C)
174 (const :tag "R" R)
175 (const :tag "Asymptote" asymptote)
176 (const :tag "Calc" calc)
177 (const :tag "Clojure" clojure)
178 (const :tag "CSS" css)
179 (const :tag "Ditaa" ditaa)
180 (const :tag "Dot" dot)
181 (const :tag "Emacs Lisp" emacs-lisp)
182 (const :tag "Fortran" fortran)
183 (const :tag "Gnuplot" gnuplot)
184 (const :tag "Haskell" haskell)
185 (const :tag "IO" io)
186 (const :tag "Java" java)
187 (const :tag "Javascript" js)
188 (const :tag "LaTeX" latex)
189 (const :tag "Ledger" ledger)
190 (const :tag "Lilypond" lilypond)
191 (const :tag "Lisp" lisp)
192 (const :tag "Maxima" maxima)
193 (const :tag "Matlab" matlab)
194 (const :tag "Mscgen" mscgen)
195 (const :tag "Ocaml" ocaml)
196 (const :tag "Octave" octave)
197 (const :tag "Org" org)
198 (const :tag "Perl" perl)
199 (const :tag "Pico Lisp" picolisp)
200 (const :tag "PlantUML" plantuml)
201 (const :tag "Python" python)
202 (const :tag "Ruby" ruby)
203 (const :tag "Sass" sass)
204 (const :tag "Scala" scala)
205 (const :tag "Scheme" scheme)
206 (const :tag "Screen" screen)
207 (const :tag "Shell Script" sh)
208 (const :tag "Shen" shen)
209 (const :tag "Sql" sql)
210 (const :tag "Sqlite" sqlite))
211 :value-type (boolean :tag "Activate" :value t)))
213 ;;;; Customization variables
214 (defcustom org-clone-delete-id nil
215 "Remove ID property of clones of a subtree.
216 When non-nil, clones of a subtree don't inherit the ID property.
217 Otherwise they inherit the ID property with a new unique
218 identifier."
219 :type 'boolean
220 :version "24.1"
221 :group 'org-id)
223 ;;; Version
224 (require 'org-compat)
225 (org-check-version)
227 ;;;###autoload
228 (defun org-version (&optional here full message)
229 "Show the org-mode version in the echo area.
230 With prefix argument HERE, insert it at point.
231 When FULL is non-nil, use a verbose version string.
232 When MESSAGE is non-nil, display a message with the version."
233 (interactive "P")
234 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
235 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs.el")))
236 (org-trash (or
237 (and (fboundp 'org-release) (fboundp 'org-git-version))
238 (load (concat org-dir "org-version.el")
239 'noerror 'nomessage 'nosuffix)))
240 (org-version (org-release))
241 (git-version (org-git-version))
242 (version (format "Org-mode version %s (%s @ %s)"
243 org-version
244 git-version
245 (if org-install-dir
246 (if (string= org-dir org-install-dir)
247 org-install-dir
248 (concat "mixed installation! " org-install-dir " and " org-dir))
249 "org-loaddefs.el can not be found!")))
250 (_version (if full version org-version)))
251 (if (org-called-interactively-p 'interactive)
252 (if here
253 (insert version)
254 (message version))
255 (if message (message _version))
256 _version)))
258 (defconst org-version (org-version))
260 ;;; Compatibility constants
262 ;;; The custom variables
264 (defgroup org nil
265 "Outline-based notes management and organizer."
266 :tag "Org"
267 :group 'outlines
268 :group 'calendar)
270 (defcustom org-mode-hook nil
271 "Mode hook for Org-mode, run after the mode was turned on."
272 :group 'org
273 :type 'hook)
275 (defcustom org-load-hook nil
276 "Hook that is run after org.el has been loaded."
277 :group 'org
278 :type 'hook)
280 (defcustom org-log-buffer-setup-hook nil
281 "Hook that is run after an Org log buffer is created."
282 :group 'org
283 :version "24.1"
284 :type 'hook)
286 (defvar org-modules) ; defined below
287 (defvar org-modules-loaded nil
288 "Have the modules been loaded already?")
290 (defun org-load-modules-maybe (&optional force)
291 "Load all extensions listed in `org-modules'."
292 (when (or force (not org-modules-loaded))
293 (mapc (lambda (ext)
294 (condition-case nil (require ext)
295 (error (message "Problems while trying to load feature `%s'" ext))))
296 org-modules)
297 (setq org-modules-loaded t)))
299 (defun org-set-modules (var value)
300 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
301 (set var value)
302 (when (featurep 'org)
303 (org-load-modules-maybe 'force)))
305 (when (org-bound-and-true-p org-modules)
306 (let ((a (member 'org-infojs org-modules)))
307 (and a (setcar a 'org-jsinfo))))
309 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
310 "Modules that should always be loaded together with org.el.
311 If a description starts with <C>, the file is not part of Emacs
312 and loading it will require that you have downloaded and properly installed
313 the org-mode distribution.
315 You can also use this system to load external packages (i.e. neither Org
316 core modules, nor modules from the CONTRIB directory). Just add symbols
317 to the end of the list. If the package is called org-xyz.el, then you need
318 to add the symbol `xyz', and the package must have a call to
320 (provide 'org-xyz)"
321 :group 'org
322 :set 'org-set-modules
323 :type
324 '(set :greedy t
325 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
326 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
327 (const :tag " crypt: Encryption of subtrees" org-crypt)
328 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
329 (const :tag " docview: Links to doc-view buffers" org-docview)
330 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
331 (const :tag " id: Global IDs for identifying entries" org-id)
332 (const :tag " info: Links to Info nodes" org-info)
333 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
334 (const :tag " habit: Track your consistency with habits" org-habit)
335 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
336 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
337 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
338 (const :tag " mew Links to Mew folders/messages" org-mew)
339 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
340 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
341 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
342 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
343 (const :tag " vm: Links to VM folders/messages" org-vm)
344 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
345 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
346 (const :tag " mouse: Additional mouse support" org-mouse)
347 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
349 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
350 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
351 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
352 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
353 (const :tag "C collector: Collect properties into tables" org-collector)
354 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
355 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
356 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
357 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
358 (const :tag "C eval: Include command output as text" org-eval)
359 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
360 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
361 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
362 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
363 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
365 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
367 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
368 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
369 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
370 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
371 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
372 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
373 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
374 (const :tag "C mtags: Support for muse-like tags" org-mtags)
375 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
376 (const :tag "C registry: A registry for Org-mode links" org-registry)
377 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
378 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
379 (const :tag "C secretary: Team management with org-mode" org-secretary)
380 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
381 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
382 (const :tag "C track: Keep up with Org-mode development" org-track)
383 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
384 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
385 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
387 (defcustom org-support-shift-select nil
388 "Non-nil means make shift-cursor commands select text when possible.
390 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
391 start selecting a region, or enlarge regions started in this way.
392 In Org-mode, in special contexts, these same keys are used for
393 other purposes, important enough to compete with shift selection.
394 Org tries to balance these needs by supporting `shift-select-mode'
395 outside these special contexts, under control of this variable.
397 The default of this variable is nil, to avoid confusing behavior. Shifted
398 cursor keys will then execute Org commands in the following contexts:
399 - on a headline, changing TODO state (left/right) and priority (up/down)
400 - on a time stamp, changing the time
401 - in a plain list item, changing the bullet type
402 - in a property definition line, switching between allowed values
403 - in the BEGIN line of a clock table (changing the time block).
404 Outside these contexts, the commands will throw an error.
406 When this variable is t and the cursor is not in a special
407 context, Org-mode will support shift-selection for making and
408 enlarging regions. To make this more effective, the bullet
409 cycling will no longer happen anywhere in an item line, but only
410 if the cursor is exactly on the bullet.
412 If you set this variable to the symbol `always', then the keys
413 will not be special in headlines, property lines, and item lines,
414 to make shift selection work there as well. If this is what you
415 want, you can use the following alternative commands: `C-c C-t'
416 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
417 can be used to switch TODO sets, `C-c -' to cycle item bullet
418 types, and properties can be edited by hand or in column view.
420 However, when the cursor is on a timestamp, shift-cursor commands
421 will still edit the time stamp - this is just too good to give up.
423 XEmacs user should have this variable set to nil, because
424 `shift-select-mode' is in Emacs 23 or later only."
425 :group 'org
426 :type '(choice
427 (const :tag "Never" nil)
428 (const :tag "When outside special context" t)
429 (const :tag "Everywhere except timestamps" always)))
431 (defcustom org-loop-over-headlines-in-active-region nil
432 "Shall some commands act upon headlines in the active region?
434 When set to `t', some commands will be performed in all headlines
435 within the active region.
437 When set to `start-level', some commands will be performed in all
438 headlines within the active region, provided that these headlines
439 are of the same level than the first one.
441 When set to a string, those commands will be performed on the
442 matching headlines within the active region. Such string must be
443 a tags/property/todo match as it is used in the agenda tags view.
445 The list of commands is: `org-schedule', `org-deadline',
446 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
447 `org-archive-to-archive-sibling'. The archiving commands skip
448 already archived entries."
449 :type '(choice (const :tag "Don't loop" nil)
450 (const :tag "All headlines in active region" t)
451 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
452 (string :tag "Tags/Property/Todo matcher"))
453 :version "24.1"
454 :group 'org-todo
455 :group 'org-archive)
457 (defgroup org-startup nil
458 "Options concerning startup of Org-mode."
459 :tag "Org Startup"
460 :group 'org)
462 (defcustom org-startup-folded t
463 "Non-nil means entering Org-mode will switch to OVERVIEW.
464 This can also be configured on a per-file basis by adding one of
465 the following lines anywhere in the buffer:
467 #+STARTUP: fold (or `overview', this is equivalent)
468 #+STARTUP: nofold (or `showall', this is equivalent)
469 #+STARTUP: content
470 #+STARTUP: showeverything"
471 :group 'org-startup
472 :type '(choice
473 (const :tag "nofold: show all" nil)
474 (const :tag "fold: overview" t)
475 (const :tag "content: all headlines" content)
476 (const :tag "show everything, even drawers" showeverything)))
478 (defcustom org-startup-truncated t
479 "Non-nil means entering Org-mode will set `truncate-lines'.
480 This is useful since some lines containing links can be very long and
481 uninteresting. Also tables look terrible when wrapped."
482 :group 'org-startup
483 :type 'boolean)
485 (defcustom org-startup-indented nil
486 "Non-nil means turn on `org-indent-mode' on startup.
487 This can also be configured on a per-file basis by adding one of
488 the following lines anywhere in the buffer:
490 #+STARTUP: indent
491 #+STARTUP: noindent"
492 :group 'org-structure
493 :type '(choice
494 (const :tag "Not" nil)
495 (const :tag "Globally (slow on startup in large files)" t)))
497 (defcustom org-use-sub-superscripts t
498 "Non-nil means interpret \"_\" and \"^\" for export.
499 When this option is turned on, you can use TeX-like syntax for sub- and
500 superscripts. Several characters after \"_\" or \"^\" will be
501 considered as a single item - so grouping with {} is normally not
502 needed. For example, the following things will be parsed as single
503 sub- or superscripts.
505 10^24 or 10^tau several digits will be considered 1 item.
506 10^-12 or 10^-tau a leading sign with digits or a word
507 x^2-y^3 will be read as x^2 - y^3, because items are
508 terminated by almost any nonword/nondigit char.
509 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
511 Still, ambiguity is possible - so when in doubt use {} to enclose the
512 sub/superscript. If you set this variable to the symbol `{}',
513 the braces are *required* in order to trigger interpretations as
514 sub/superscript. This can be helpful in documents that need \"_\"
515 frequently in plain text.
517 Not all export backends support this, but HTML does.
519 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
520 :group 'org-startup
521 :group 'org-export-translation
522 :version "24.1"
523 :type '(choice
524 (const :tag "Always interpret" t)
525 (const :tag "Only with braces" {})
526 (const :tag "Never interpret" nil)))
528 (if (fboundp 'defvaralias)
529 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
532 (defcustom org-startup-with-beamer-mode nil
533 "Non-nil means turn on `org-beamer-mode' on startup.
534 This can also be configured on a per-file basis by adding one of
535 the following lines anywhere in the buffer:
537 #+STARTUP: beamer"
538 :group 'org-startup
539 :version "24.1"
540 :type 'boolean)
542 (defcustom org-startup-align-all-tables nil
543 "Non-nil means align all tables when visiting a file.
544 This is useful when the column width in tables is forced with <N> cookies
545 in table fields. Such tables will look correct only after the first re-align.
546 This can also be configured on a per-file basis by adding one of
547 the following lines anywhere in the buffer:
548 #+STARTUP: align
549 #+STARTUP: noalign"
550 :group 'org-startup
551 :type 'boolean)
553 (defcustom org-startup-with-inline-images nil
554 "Non-nil means show inline images when loading a new Org file.
555 This can also be configured on a per-file basis by adding one of
556 the following lines anywhere in the buffer:
557 #+STARTUP: inlineimages
558 #+STARTUP: noinlineimages"
559 :group 'org-startup
560 :version "24.1"
561 :type 'boolean)
563 (defcustom org-insert-mode-line-in-empty-file nil
564 "Non-nil means insert the first line setting Org-mode in empty files.
565 When the function `org-mode' is called interactively in an empty file, this
566 normally means that the file name does not automatically trigger Org-mode.
567 To ensure that the file will always be in Org-mode in the future, a
568 line enforcing Org-mode will be inserted into the buffer, if this option
569 has been set."
570 :group 'org-startup
571 :type 'boolean)
573 (defcustom org-replace-disputed-keys nil
574 "Non-nil means use alternative key bindings for some keys.
575 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
576 These keys are also used by other packages like shift-selection-mode'
577 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
578 If you want to use Org-mode together with one of these other modes,
579 or more generally if you would like to move some Org-mode commands to
580 other keys, set this variable and configure the keys with the variable
581 `org-disputed-keys'.
583 This option is only relevant at load-time of Org-mode, and must be set
584 *before* org.el is loaded. Changing it requires a restart of Emacs to
585 become effective."
586 :group 'org-startup
587 :type 'boolean)
589 (defcustom org-use-extra-keys nil
590 "Non-nil means use extra key sequence definitions for certain commands.
591 This happens automatically if you run XEmacs or if `window-system'
592 is nil. This variable lets you do the same manually. You must
593 set it before loading org.
595 Example: on Carbon Emacs 22 running graphically, with an external
596 keyboard on a Powerbook, the default way of setting M-left might
597 not work for either Alt or ESC. Setting this variable will make
598 it work for ESC."
599 :group 'org-startup
600 :type 'boolean)
602 (if (fboundp 'defvaralias)
603 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
605 (defcustom org-disputed-keys
606 '(([(shift up)] . [(meta p)])
607 ([(shift down)] . [(meta n)])
608 ([(shift left)] . [(meta -)])
609 ([(shift right)] . [(meta +)])
610 ([(control shift right)] . [(meta shift +)])
611 ([(control shift left)] . [(meta shift -)]))
612 "Keys for which Org-mode and other modes compete.
613 This is an alist, cars are the default keys, second element specifies
614 the alternative to use when `org-replace-disputed-keys' is t.
616 Keys can be specified in any syntax supported by `define-key'.
617 The value of this option takes effect only at Org-mode's startup,
618 therefore you'll have to restart Emacs to apply it after changing."
619 :group 'org-startup
620 :type 'alist)
622 (defun org-key (key)
623 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
624 Or return the original if not disputed.
625 Also apply the translations defined in `org-xemacs-key-equivalents'."
626 (when org-replace-disputed-keys
627 (let* ((nkey (key-description key))
628 (x (org-find-if (lambda (x)
629 (equal (key-description (car x)) nkey))
630 org-disputed-keys)))
631 (setq key (if x (cdr x) key))))
632 (when (featurep 'xemacs)
633 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
634 key)
636 (defun org-find-if (predicate seq)
637 (catch 'exit
638 (while seq
639 (if (funcall predicate (car seq))
640 (throw 'exit (car seq))
641 (pop seq)))))
643 (defun org-defkey (keymap key def)
644 "Define a key, possibly translated, as returned by `org-key'."
645 (define-key keymap (org-key key) def))
647 (defcustom org-ellipsis nil
648 "The ellipsis to use in the Org-mode outline.
649 When nil, just use the standard three dots. When a string, use that instead,
650 When a face, use the standard 3 dots, but with the specified face.
651 The change affects only Org-mode (which will then use its own display table).
652 Changing this requires executing `M-x org-mode' in a buffer to become
653 effective."
654 :group 'org-startup
655 :type '(choice (const :tag "Default" nil)
656 (face :tag "Face" :value org-warning)
657 (string :tag "String" :value "...#")))
659 (defvar org-display-table nil
660 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
662 (defgroup org-keywords nil
663 "Keywords in Org-mode."
664 :tag "Org Keywords"
665 :group 'org)
667 (defcustom org-deadline-string "DEADLINE:"
668 "String to mark deadline entries.
669 A deadline is this string, followed by a time stamp. Should be a word,
670 terminated by a colon. You can insert a schedule keyword and
671 a timestamp with \\[org-deadline].
672 Changes become only effective after restarting Emacs."
673 :group 'org-keywords
674 :type 'string)
676 (defcustom org-scheduled-string "SCHEDULED:"
677 "String to mark scheduled TODO entries.
678 A schedule is this string, followed by a time stamp. Should be a word,
679 terminated by a colon. You can insert a schedule keyword and
680 a timestamp with \\[org-schedule].
681 Changes become only effective after restarting Emacs."
682 :group 'org-keywords
683 :type 'string)
685 (defcustom org-closed-string "CLOSED:"
686 "String used as the prefix for timestamps logging closing a TODO entry."
687 :group 'org-keywords
688 :type 'string)
690 (defcustom org-clock-string "CLOCK:"
691 "String used as prefix for timestamps clocking work hours on an item."
692 :group 'org-keywords
693 :type 'string)
695 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
696 org-scheduled-string "\\|"
697 org-deadline-string "\\|"
698 org-closed-string "\\|"
699 org-clock-string "\\)")
700 "Matches a line with planning or clock info.")
702 (defcustom org-comment-string "COMMENT"
703 "Entries starting with this keyword will never be exported.
704 An entry can be toggled between COMMENT and normal with
705 \\[org-toggle-comment].
706 Changes become only effective after restarting Emacs."
707 :group 'org-keywords
708 :type 'string)
710 (defcustom org-quote-string "QUOTE"
711 "Entries starting with this keyword will be exported in fixed-width font.
712 Quoting applies only to the text in the entry following the headline, and does
713 not extend beyond the next headline, even if that is lower level.
714 An entry can be toggled between QUOTE and normal with
715 \\[org-toggle-fixed-width-section]."
716 :group 'org-keywords
717 :type 'string)
719 (defconst org-repeat-re
720 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
721 "Regular expression for specifying repeated events.
722 After a match, group 1 contains the repeat expression.")
724 (defgroup org-structure nil
725 "Options concerning the general structure of Org-mode files."
726 :tag "Org Structure"
727 :group 'org)
729 (defgroup org-reveal-location nil
730 "Options about how to make context of a location visible."
731 :tag "Org Reveal Location"
732 :group 'org-structure)
734 (defconst org-context-choice
735 '(choice
736 (const :tag "Always" t)
737 (const :tag "Never" nil)
738 (repeat :greedy t :tag "Individual contexts"
739 (cons
740 (choice :tag "Context"
741 (const agenda)
742 (const org-goto)
743 (const occur-tree)
744 (const tags-tree)
745 (const link-search)
746 (const mark-goto)
747 (const bookmark-jump)
748 (const isearch)
749 (const default))
750 (boolean))))
751 "Contexts for the reveal options.")
753 (defcustom org-show-hierarchy-above '((default . t))
754 "Non-nil means show full hierarchy when revealing a location.
755 Org-mode often shows locations in an org-mode file which might have
756 been invisible before. When this is set, the hierarchy of headings
757 above the exposed location is shown.
758 Turning this off for example for sparse trees makes them very compact.
759 Instead of t, this can also be an alist specifying this option for different
760 contexts. Valid contexts are
761 agenda when exposing an entry from the agenda
762 org-goto when using the command `org-goto' on key C-c C-j
763 occur-tree when using the command `org-occur' on key C-c /
764 tags-tree when constructing a sparse tree based on tags matches
765 link-search when exposing search matches associated with a link
766 mark-goto when exposing the jump goal of a mark
767 bookmark-jump when exposing a bookmark location
768 isearch when exiting from an incremental search
769 default default for all contexts not set explicitly"
770 :group 'org-reveal-location
771 :type org-context-choice)
773 (defcustom org-show-following-heading '((default . nil))
774 "Non-nil means show following heading when revealing a location.
775 Org-mode often shows locations in an org-mode file which might have
776 been invisible before. When this is set, the heading following the
777 match is shown.
778 Turning this off for example for sparse trees makes them very compact,
779 but makes it harder to edit the location of the match. In such a case,
780 use the command \\[org-reveal] to show more context.
781 Instead of t, this can also be an alist specifying this option for different
782 contexts. See `org-show-hierarchy-above' for valid contexts."
783 :group 'org-reveal-location
784 :type org-context-choice)
786 (defcustom org-show-siblings '((default . nil) (isearch t))
787 "Non-nil means show all sibling heading when revealing a location.
788 Org-mode often shows locations in an org-mode file which might have
789 been invisible before. When this is set, the sibling of the current entry
790 heading are all made visible. If `org-show-hierarchy-above' is t,
791 the same happens on each level of the hierarchy above the current entry.
793 By default this is on for the isearch context, off for all other contexts.
794 Turning this off for example for sparse trees makes them very compact,
795 but makes it harder to edit the location of the match. In such a case,
796 use the command \\[org-reveal] to show more context.
797 Instead of t, this can also be an alist specifying this option for different
798 contexts. See `org-show-hierarchy-above' for valid contexts."
799 :group 'org-reveal-location
800 :type org-context-choice)
802 (defcustom org-show-entry-below '((default . nil))
803 "Non-nil means show the entry below a headline when revealing a location.
804 Org-mode often shows locations in an org-mode file which might have
805 been invisible before. When this is set, the text below the headline that is
806 exposed is also shown.
808 By default this is off for all contexts.
809 Instead of t, this can also be an alist specifying this option for different
810 contexts. See `org-show-hierarchy-above' for valid contexts."
811 :group 'org-reveal-location
812 :type org-context-choice)
814 (defcustom org-indirect-buffer-display 'other-window
815 "How should indirect tree buffers be displayed?
816 This applies to indirect buffers created with the commands
817 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
818 Valid values are:
819 current-window Display in the current window
820 other-window Just display in another window.
821 dedicated-frame Create one new frame, and re-use it each time.
822 new-frame Make a new frame each time. Note that in this case
823 previously-made indirect buffers are kept, and you need to
824 kill these buffers yourself."
825 :group 'org-structure
826 :group 'org-agenda-windows
827 :type '(choice
828 (const :tag "In current window" current-window)
829 (const :tag "In current frame, other window" other-window)
830 (const :tag "Each time a new frame" new-frame)
831 (const :tag "One dedicated frame" dedicated-frame)))
833 (defcustom org-use-speed-commands nil
834 "Non-nil means activate single letter commands at beginning of a headline.
835 This may also be a function to test for appropriate locations where speed
836 commands should be active."
837 :group 'org-structure
838 :type '(choice
839 (const :tag "Never" nil)
840 (const :tag "At beginning of headline stars" t)
841 (function)))
843 (defcustom org-speed-commands-user nil
844 "Alist of additional speed commands.
845 This list will be checked before `org-speed-commands-default'
846 when the variable `org-use-speed-commands' is non-nil
847 and when the cursor is at the beginning of a headline.
848 The car if each entry is a string with a single letter, which must
849 be assigned to `self-insert-command' in the global map.
850 The cdr is either a command to be called interactively, a function
851 to be called, or a form to be evaluated.
852 An entry that is just a list with a single string will be interpreted
853 as a descriptive headline that will be added when listing the speed
854 commands in the Help buffer using the `?' speed command."
855 :group 'org-structure
856 :type '(repeat :value ("k" . ignore)
857 (choice :value ("k" . ignore)
858 (list :tag "Descriptive Headline" (string :tag "Headline"))
859 (cons :tag "Letter and Command"
860 (string :tag "Command letter")
861 (choice
862 (function)
863 (sexp))))))
865 (defgroup org-cycle nil
866 "Options concerning visibility cycling in Org-mode."
867 :tag "Org Cycle"
868 :group 'org-structure)
870 (defcustom org-cycle-skip-children-state-if-no-children t
871 "Non-nil means skip CHILDREN state in entries that don't have any."
872 :group 'org-cycle
873 :type 'boolean)
875 (defcustom org-cycle-max-level nil
876 "Maximum level which should still be subject to visibility cycling.
877 Levels higher than this will, for cycling, be treated as text, not a headline.
878 When `org-odd-levels-only' is set, a value of N in this variable actually
879 means 2N-1 stars as the limiting headline.
880 When nil, cycle all levels.
881 Note that the limiting level of cycling is also influenced by
882 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
883 `org-inlinetask-min-level' is, cycling will be limited to levels one less
884 than its value."
885 :group 'org-cycle
886 :type '(choice
887 (const :tag "No limit" nil)
888 (integer :tag "Maximum level")))
890 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
891 "Names of drawers. Drawers are not opened by cycling on the headline above.
892 Drawers only open with a TAB on the drawer line itself. A drawer looks like
893 this:
894 :DRAWERNAME:
895 .....
896 :END:
897 The drawer \"PROPERTIES\" is special for capturing properties through
898 the property API.
900 Drawers can be defined on the per-file basis with a line like:
902 #+DRAWERS: HIDDEN STATE PROPERTIES"
903 :group 'org-structure
904 :group 'org-cycle
905 :type '(repeat (string :tag "Drawer Name")))
907 (defcustom org-hide-block-startup nil
908 "Non-nil means entering Org-mode will fold all blocks.
909 This can also be set in on a per-file basis with
911 #+STARTUP: hideblocks
912 #+STARTUP: showblocks"
913 :group 'org-startup
914 :group 'org-cycle
915 :type 'boolean)
917 (defcustom org-cycle-global-at-bob nil
918 "Cycle globally if cursor is at beginning of buffer and not at a headline.
919 This makes it possible to do global cycling without having to use S-TAB or
920 \\[universal-argument] TAB. For this special case to work, the first line
921 of the buffer must not be a headline -- it may be empty or some other text.
922 When used in this way, `org-cycle-hook' is disabled temporarily to make
923 sure the cursor stays at the beginning of the buffer. When this option is
924 nil, don't do anything special at the beginning of the buffer."
925 :group 'org-cycle
926 :type 'boolean)
928 (defcustom org-cycle-level-after-item/entry-creation t
929 "Non-nil means cycle entry level or item indentation in new empty entries.
931 When the cursor is at the end of an empty headline, i.e with only stars
932 and maybe a TODO keyword, TAB will then switch the entry to become a child,
933 and then all possible ancestor states, before returning to the original state.
934 This makes data entry extremely fast: M-RET to create a new headline,
935 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
937 When the cursor is at the end of an empty plain list item, one TAB will
938 make it a subitem, two or more tabs will back up to make this an item
939 higher up in the item hierarchy."
940 :group 'org-cycle
941 :type 'boolean)
943 (defcustom org-cycle-emulate-tab t
944 "Where should `org-cycle' emulate TAB.
945 nil Never
946 white Only in completely white lines
947 whitestart Only at the beginning of lines, before the first non-white char
948 t Everywhere except in headlines
949 exc-hl-bol Everywhere except at the start of a headline
950 If TAB is used in a place where it does not emulate TAB, the current subtree
951 visibility is cycled."
952 :group 'org-cycle
953 :type '(choice (const :tag "Never" nil)
954 (const :tag "Only in completely white lines" white)
955 (const :tag "Before first char in a line" whitestart)
956 (const :tag "Everywhere except in headlines" t)
957 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
960 (defcustom org-cycle-separator-lines 2
961 "Number of empty lines needed to keep an empty line between collapsed trees.
962 If you leave an empty line between the end of a subtree and the following
963 headline, this empty line is hidden when the subtree is folded.
964 Org-mode will leave (exactly) one empty line visible if the number of
965 empty lines is equal or larger to the number given in this variable.
966 So the default 2 means at least 2 empty lines after the end of a subtree
967 are needed to produce free space between a collapsed subtree and the
968 following headline.
970 If the number is negative, and the number of empty lines is at least -N,
971 all empty lines are shown.
973 Special case: when 0, never leave empty lines in collapsed view."
974 :group 'org-cycle
975 :type 'integer)
976 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
978 (defcustom org-pre-cycle-hook nil
979 "Hook that is run before visibility cycling is happening.
980 The function(s) in this hook must accept a single argument which indicates
981 the new state that will be set right after running this hook. The
982 argument is a symbol. Before a global state change, it can have the values
983 `overview', `content', or `all'. Before a local state change, it can have
984 the values `folded', `children', or `subtree'."
985 :group 'org-cycle
986 :type 'hook)
988 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
989 org-cycle-hide-drawers
990 org-cycle-show-empty-lines
991 org-optimize-window-after-visibility-change)
992 "Hook that is run after `org-cycle' has changed the buffer visibility.
993 The function(s) in this hook must accept a single argument which indicates
994 the new state that was set by the most recent `org-cycle' command. The
995 argument is a symbol. After a global state change, it can have the values
996 `overview', `contents', or `all'. After a local state change, it can have
997 the values `folded', `children', or `subtree'."
998 :group 'org-cycle
999 :type 'hook)
1001 (defgroup org-edit-structure nil
1002 "Options concerning structure editing in Org-mode."
1003 :tag "Org Edit Structure"
1004 :group 'org-structure)
1006 (defcustom org-odd-levels-only nil
1007 "Non-nil means skip even levels and only use odd levels for the outline.
1008 This has the effect that two stars are being added/taken away in
1009 promotion/demotion commands. It also influences how levels are
1010 handled by the exporters.
1011 Changing it requires restart of `font-lock-mode' to become effective
1012 for fontification also in regions already fontified.
1013 You may also set this on a per-file basis by adding one of the following
1014 lines to the buffer:
1016 #+STARTUP: odd
1017 #+STARTUP: oddeven"
1018 :group 'org-edit-structure
1019 :group 'org-appearance
1020 :type 'boolean)
1022 (defcustom org-adapt-indentation t
1023 "Non-nil means adapt indentation to outline node level.
1025 When this variable is set, Org assumes that you write outlines by
1026 indenting text in each node to align with the headline (after the stars).
1027 The following issues are influenced by this variable:
1029 - When this is set and the *entire* text in an entry is indented, the
1030 indentation is increased by one space in a demotion command, and
1031 decreased by one in a promotion command. If any line in the entry
1032 body starts with text at column 0, indentation is not changed at all.
1034 - Property drawers and planning information is inserted indented when
1035 this variable s set. When nil, they will not be indented.
1037 - TAB indents a line relative to context. The lines below a headline
1038 will be indented when this variable is set.
1040 Note that this is all about true indentation, by adding and removing
1041 space characters. See also `org-indent.el' which does level-dependent
1042 indentation in a virtual way, i.e. at display time in Emacs."
1043 :group 'org-edit-structure
1044 :type 'boolean)
1046 (defcustom org-special-ctrl-a/e nil
1047 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1049 When t, `C-a' will bring back the cursor to the beginning of the
1050 headline text, i.e. after the stars and after a possible TODO
1051 keyword. In an item, this will be the position after bullet and
1052 check-box, if any. When the cursor is already at that position,
1053 another `C-a' will bring it to the beginning of the line.
1055 `C-e' will jump to the end of the headline, ignoring the presence
1056 of tags in the headline. A second `C-e' will then jump to the
1057 true end of the line, after any tags. This also means that, when
1058 this variable is non-nil, `C-e' also will never jump beyond the
1059 end of the heading of a folded section, i.e. not after the
1060 ellipses.
1062 When set to the symbol `reversed', the first `C-a' or `C-e' works
1063 normally, going to the true line boundary first. Only a directly
1064 following, identical keypress will bring the cursor to the
1065 special positions.
1067 This may also be a cons cell where the behavior for `C-a' and
1068 `C-e' is set separately."
1069 :group 'org-edit-structure
1070 :type '(choice
1071 (const :tag "off" nil)
1072 (const :tag "on: after stars/bullet and before tags first" t)
1073 (const :tag "reversed: true line boundary first" reversed)
1074 (cons :tag "Set C-a and C-e separately"
1075 (choice :tag "Special C-a"
1076 (const :tag "off" nil)
1077 (const :tag "on: after stars/bullet first" t)
1078 (const :tag "reversed: before stars/bullet first" reversed))
1079 (choice :tag "Special C-e"
1080 (const :tag "off" nil)
1081 (const :tag "on: before tags first" t)
1082 (const :tag "reversed: after tags first" reversed)))))
1083 (if (fboundp 'defvaralias)
1084 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1086 (defcustom org-special-ctrl-k nil
1087 "Non-nil means `C-k' will behave specially in headlines.
1088 When nil, `C-k' will call the default `kill-line' command.
1089 When t, the following will happen while the cursor is in the headline:
1091 - When the cursor is at the beginning of a headline, kill the entire
1092 line and possible the folded subtree below the line.
1093 - When in the middle of the headline text, kill the headline up to the tags.
1094 - When after the headline text, kill the tags."
1095 :group 'org-edit-structure
1096 :type 'boolean)
1098 (defcustom org-ctrl-k-protect-subtree nil
1099 "Non-nil means, do not delete a hidden subtree with C-k.
1100 When set to the symbol `error', simply throw an error when C-k is
1101 used to kill (part-of) a headline that has hidden text behind it.
1102 Any other non-nil value will result in a query to the user, if it is
1103 OK to kill that hidden subtree. When nil, kill without remorse."
1104 :group 'org-edit-structure
1105 :version "24.1"
1106 :type '(choice
1107 (const :tag "Do not protect hidden subtrees" nil)
1108 (const :tag "Protect hidden subtrees with a security query" t)
1109 (const :tag "Never kill a hidden subtree with C-k" error)))
1111 (defcustom org-catch-invisible-edits nil
1112 "Check if in invisible region before inserting or deleting a character.
1113 Valid values are:
1115 nil Do not check, so just do invisible edits.
1116 error Throw an error and do nothing.
1117 show Make point visible, and do the requested edit.
1118 show-and-error Make point visible, then throw an error and abort the edit.
1119 smart Make point visible, and do insertion/deletion if it is
1120 adjacent to visible text and the change feels predictable.
1121 Never delete a previously invisible character or add in the
1122 middle or right after an invisible region. Basically, this
1123 allows insertion and backward-delete right before ellipses.
1124 FIXME: maybe in this case we should not even show?"
1125 :group 'org-edit-structure
1126 :version "24.1"
1127 :type '(choice
1128 (const :tag "Do not check" nil)
1129 (const :tag "Throw error when trying to edit" error)
1130 (const :tag "Unhide, but do not do the edit" show-and-error)
1131 (const :tag "Show invisible part and do the edit" show)
1132 (const :tag "Be smart and do the right thing" smart)))
1134 (defcustom org-yank-folded-subtrees t
1135 "Non-nil means when yanking subtrees, fold them.
1136 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1137 it starts with a heading and all other headings in it are either children
1138 or siblings, then fold all the subtrees. However, do this only if no
1139 text after the yank would be swallowed into a folded tree by this action."
1140 :group 'org-edit-structure
1141 :type 'boolean)
1143 (defcustom org-yank-adjusted-subtrees nil
1144 "Non-nil means when yanking subtrees, adjust the level.
1145 With this setting, `org-paste-subtree' is used to insert the subtree, see
1146 this function for details."
1147 :group 'org-edit-structure
1148 :type 'boolean)
1150 (defcustom org-M-RET-may-split-line '((default . t))
1151 "Non-nil means M-RET will split the line at the cursor position.
1152 When nil, it will go to the end of the line before making a
1153 new line.
1154 You may also set this option in a different way for different
1155 contexts. Valid contexts are:
1157 headline when creating a new headline
1158 item when creating a new item
1159 table in a table field
1160 default the value to be used for all contexts not explicitly
1161 customized"
1162 :group 'org-structure
1163 :group 'org-table
1164 :type '(choice
1165 (const :tag "Always" t)
1166 (const :tag "Never" nil)
1167 (repeat :greedy t :tag "Individual contexts"
1168 (cons
1169 (choice :tag "Context"
1170 (const headline)
1171 (const item)
1172 (const table)
1173 (const default))
1174 (boolean)))))
1177 (defcustom org-insert-heading-respect-content nil
1178 "Non-nil means insert new headings after the current subtree.
1179 When nil, the new heading is created directly after the current line.
1180 The commands \\[org-insert-heading-respect-content] and
1181 \\[org-insert-todo-heading-respect-content] turn this variable on
1182 for the duration of the command."
1183 :group 'org-structure
1184 :type 'boolean)
1186 (defcustom org-blank-before-new-entry '((heading . auto)
1187 (plain-list-item . auto))
1188 "Should `org-insert-heading' leave a blank line before new heading/item?
1189 The value is an alist, with `heading' and `plain-list-item' as CAR,
1190 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1191 which case Org will look at the surrounding headings/items and try to
1192 make an intelligent decision whether to insert a blank line or not.
1194 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1195 set, the setting here is ignored and no empty line is inserted, to avoid
1196 breaking the list structure."
1197 :group 'org-edit-structure
1198 :type '(list
1199 (cons (const heading)
1200 (choice (const :tag "Never" nil)
1201 (const :tag "Always" t)
1202 (const :tag "Auto" auto)))
1203 (cons (const plain-list-item)
1204 (choice (const :tag "Never" nil)
1205 (const :tag "Always" t)
1206 (const :tag "Auto" auto)))))
1208 (defcustom org-insert-heading-hook nil
1209 "Hook being run after inserting a new heading."
1210 :group 'org-edit-structure
1211 :type 'hook)
1213 (defcustom org-enable-fixed-width-editor t
1214 "Non-nil means lines starting with \":\" are treated as fixed-width.
1215 This currently only means they are never auto-wrapped.
1216 When nil, such lines will be treated like ordinary lines.
1217 See also the QUOTE keyword."
1218 :group 'org-edit-structure
1219 :type 'boolean)
1221 (defcustom org-goto-auto-isearch t
1222 "Non-nil means typing characters in `org-goto' starts incremental search."
1223 :group 'org-edit-structure
1224 :type 'boolean)
1226 (defgroup org-sparse-trees nil
1227 "Options concerning sparse trees in Org-mode."
1228 :tag "Org Sparse Trees"
1229 :group 'org-structure)
1231 (defcustom org-highlight-sparse-tree-matches t
1232 "Non-nil means highlight all matches that define a sparse tree.
1233 The highlights will automatically disappear the next time the buffer is
1234 changed by an edit command."
1235 :group 'org-sparse-trees
1236 :type 'boolean)
1238 (defcustom org-remove-highlights-with-change t
1239 "Non-nil means any change to the buffer will remove temporary highlights.
1240 Such highlights are created by `org-occur' and `org-clock-display'.
1241 When nil, `C-c C-c needs to be used to get rid of the highlights.
1242 The highlights created by `org-preview-latex-fragment' always need
1243 `C-c C-c' to be removed."
1244 :group 'org-sparse-trees
1245 :group 'org-time
1246 :type 'boolean)
1249 (defcustom org-occur-hook '(org-first-headline-recenter)
1250 "Hook that is run after `org-occur' has constructed a sparse tree.
1251 This can be used to recenter the window to show as much of the structure
1252 as possible."
1253 :group 'org-sparse-trees
1254 :type 'hook)
1256 (defgroup org-imenu-and-speedbar nil
1257 "Options concerning imenu and speedbar in Org-mode."
1258 :tag "Org Imenu and Speedbar"
1259 :group 'org-structure)
1261 (defcustom org-imenu-depth 2
1262 "The maximum level for Imenu access to Org-mode headlines.
1263 This also applied for speedbar access."
1264 :group 'org-imenu-and-speedbar
1265 :type 'integer)
1267 (defgroup org-table nil
1268 "Options concerning tables in Org-mode."
1269 :tag "Org Table"
1270 :group 'org)
1272 (defcustom org-enable-table-editor 'optimized
1273 "Non-nil means lines starting with \"|\" are handled by the table editor.
1274 When nil, such lines will be treated like ordinary lines.
1276 When equal to the symbol `optimized', the table editor will be optimized to
1277 do the following:
1278 - Automatic overwrite mode in front of whitespace in table fields.
1279 This makes the structure of the table stay in tact as long as the edited
1280 field does not exceed the column width.
1281 - Minimize the number of realigns. Normally, the table is aligned each time
1282 TAB or RET are pressed to move to another field. With optimization this
1283 happens only if changes to a field might have changed the column width.
1284 Optimization requires replacing the functions `self-insert-command',
1285 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1286 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1287 very good at guessing when a re-align will be necessary, but you can always
1288 force one with \\[org-ctrl-c-ctrl-c].
1290 If you would like to use the optimized version in Org-mode, but the
1291 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1293 This variable can be used to turn on and off the table editor during a session,
1294 but in order to toggle optimization, a restart is required.
1296 See also the variable `org-table-auto-blank-field'."
1297 :group 'org-table
1298 :type '(choice
1299 (const :tag "off" nil)
1300 (const :tag "on" t)
1301 (const :tag "on, optimized" optimized)))
1303 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1304 (version<= emacs-version "24.1"))
1305 "Non-nil means cluster self-insert commands for undo when possible.
1306 If this is set, then, like in the Emacs command loop, 20 consecutive
1307 characters will be undone together.
1308 This is configurable, because there is some impact on typing performance."
1309 :group 'org-table
1310 :type 'boolean)
1312 (defcustom org-table-tab-recognizes-table.el t
1313 "Non-nil means TAB will automatically notice a table.el table.
1314 When it sees such a table, it moves point into it and - if necessary -
1315 calls `table-recognize-table'."
1316 :group 'org-table-editing
1317 :type 'boolean)
1319 (defgroup org-link nil
1320 "Options concerning links in Org-mode."
1321 :tag "Org Link"
1322 :group 'org)
1324 (defvar org-link-abbrev-alist-local nil
1325 "Buffer-local version of `org-link-abbrev-alist', which see.
1326 The value of this is taken from the #+LINK lines.")
1327 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1329 (defcustom org-link-abbrev-alist nil
1330 "Alist of link abbreviations.
1331 The car of each element is a string, to be replaced at the start of a link.
1332 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1333 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1335 [[linkkey:tag][description]]
1337 The 'linkkey' must be a word word, starting with a letter, followed
1338 by letters, numbers, '-' or '_'.
1340 If REPLACE is a string, the tag will simply be appended to create the link.
1341 If the string contains \"%s\", the tag will be inserted there. If the string
1342 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1343 at that point (see the function `url-hexify-string'). If the string contains
1344 the specifier \"%(my-function)\", then the custom function `my-function' will
1345 be invoked: this function takes the tag as its only argument and must return
1346 a string.
1348 REPLACE may also be a function that will be called with the tag as the
1349 only argument to create the link, which should be returned as a string.
1351 See the manual for examples."
1352 :group 'org-link
1353 :type '(repeat
1354 (cons
1355 (string :tag "Protocol")
1356 (choice
1357 (string :tag "Format")
1358 (function)))))
1360 (defcustom org-descriptive-links t
1361 "Non-nil means Org will display descriptive links.
1362 E.g. [[http://orgmode.org][Org website]] will be displayed as
1363 \"Org Website\", hiding the link itself and just displaying its
1364 description. When set to `nil', Org will display the full links
1365 literally.
1367 You can interactively set the value of this variable by calling
1368 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1369 :group 'org-link
1370 :type 'boolean)
1372 (defcustom org-link-file-path-type 'adaptive
1373 "How the path name in file links should be stored.
1374 Valid values are:
1376 relative Relative to the current directory, i.e. the directory of the file
1377 into which the link is being inserted.
1378 absolute Absolute path, if possible with ~ for home directory.
1379 noabbrev Absolute path, no abbreviation of home directory.
1380 adaptive Use relative path for files in the current directory and sub-
1381 directories of it. For other files, use an absolute path."
1382 :group 'org-link
1383 :type '(choice
1384 (const relative)
1385 (const absolute)
1386 (const noabbrev)
1387 (const adaptive)))
1389 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1390 "Types of links that should be activated in Org-mode files.
1391 This is a list of symbols, each leading to the activation of a certain link
1392 type. In principle, it does not hurt to turn on most link types - there may
1393 be a small gain when turning off unused link types. The types are:
1395 bracket The recommended [[link][description]] or [[link]] links with hiding.
1396 angle Links in angular brackets that may contain whitespace like
1397 <bbdb:Carsten Dominik>.
1398 plain Plain links in normal text, no whitespace, like http://google.com.
1399 radio Text that is matched by a radio target, see manual for details.
1400 tag Tag settings in a headline (link to tag search).
1401 date Time stamps (link to calendar).
1402 footnote Footnote labels.
1404 Changing this variable requires a restart of Emacs to become effective."
1405 :group 'org-link
1406 :type '(set :greedy t
1407 (const :tag "Double bracket links" bracket)
1408 (const :tag "Angular bracket links" angle)
1409 (const :tag "Plain text links" plain)
1410 (const :tag "Radio target matches" radio)
1411 (const :tag "Tags" tag)
1412 (const :tag "Timestamps" date)
1413 (const :tag "Footnotes" footnote)))
1415 (defcustom org-make-link-description-function nil
1416 "Function to use for generating link descriptions from links.
1417 When nil, the link location will be used. This function must take
1418 two parameters: the first one is the link, the second one is the
1419 description generated by `org-insert-link'. The function should
1420 return the description to use."
1421 :group 'org-link
1422 :type 'function)
1424 (defgroup org-link-store nil
1425 "Options concerning storing links in Org-mode."
1426 :tag "Org Store Link"
1427 :group 'org-link)
1429 (defcustom org-url-hexify-p t
1430 "When non-nil, hexify URL when creating a link."
1431 :type 'boolean
1432 :version "24.3"
1433 :group 'org-link-store)
1435 (defcustom org-email-link-description-format "Email %c: %.30s"
1436 "Format of the description part of a link to an email or usenet message.
1437 The following %-escapes will be replaced by corresponding information:
1439 %F full \"From\" field
1440 %f name, taken from \"From\" field, address if no name
1441 %T full \"To\" field
1442 %t first name in \"To\" field, address if no name
1443 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1444 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1445 %s subject
1446 %d date
1447 %m message-id.
1449 You may use normal field width specification between the % and the letter.
1450 This is for example useful to limit the length of the subject.
1452 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1453 :group 'org-link-store
1454 :type 'string)
1456 (defcustom org-from-is-user-regexp
1457 (let (r1 r2)
1458 (when (and user-mail-address (not (string= user-mail-address "")))
1459 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1460 (when (and user-full-name (not (string= user-full-name "")))
1461 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1462 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1463 "Regexp matched against the \"From:\" header of an email or usenet message.
1464 It should match if the message is from the user him/herself."
1465 :group 'org-link-store
1466 :type 'regexp)
1468 (defcustom org-context-in-file-links t
1469 "Non-nil means file links from `org-store-link' contain context.
1470 A search string will be added to the file name with :: as separator and
1471 used to find the context when the link is activated by the command
1472 `org-open-at-point'. When this option is t, the entire active region
1473 will be placed in the search string of the file link. If set to a
1474 positive integer, only the first n lines of context will be stored.
1476 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1477 negates this setting for the duration of the command."
1478 :group 'org-link-store
1479 :type '(choice boolean integer))
1481 (defcustom org-keep-stored-link-after-insertion nil
1482 "Non-nil means keep link in list for entire session.
1484 The command `org-store-link' adds a link pointing to the current
1485 location to an internal list. These links accumulate during a session.
1486 The command `org-insert-link' can be used to insert links into any
1487 Org-mode file (offering completion for all stored links). When this
1488 option is nil, every link which has been inserted once using \\[org-insert-link]
1489 will be removed from the list, to make completing the unused links
1490 more efficient."
1491 :group 'org-link-store
1492 :type 'boolean)
1494 (defgroup org-link-follow nil
1495 "Options concerning following links in Org-mode."
1496 :tag "Org Follow Link"
1497 :group 'org-link)
1499 (defcustom org-link-translation-function nil
1500 "Function to translate links with different syntax to Org syntax.
1501 This can be used to translate links created for example by the Planner
1502 or emacs-wiki packages to Org syntax.
1503 The function must accept two parameters, a TYPE containing the link
1504 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1505 which is everything after the link protocol. It should return a cons
1506 with possibly modified values of type and path.
1507 Org contains a function for this, so if you set this variable to
1508 `org-translate-link-from-planner', you should be able follow many
1509 links created by planner."
1510 :group 'org-link-follow
1511 :type 'function)
1513 (defcustom org-follow-link-hook nil
1514 "Hook that is run after a link has been followed."
1515 :group 'org-link-follow
1516 :type 'hook)
1518 (defcustom org-tab-follows-link nil
1519 "Non-nil means on links TAB will follow the link.
1520 Needs to be set before org.el is loaded.
1521 This really should not be used, it does not make sense, and the
1522 implementation is bad."
1523 :group 'org-link-follow
1524 :type 'boolean)
1526 (defcustom org-return-follows-link nil
1527 "Non-nil means on links RET will follow the link."
1528 :group 'org-link-follow
1529 :type 'boolean)
1531 (defcustom org-mouse-1-follows-link
1532 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1533 "Non-nil means mouse-1 on a link will follow the link.
1534 A longer mouse click will still set point. Does not work on XEmacs.
1535 Needs to be set before org.el is loaded."
1536 :group 'org-link-follow
1537 :type 'boolean)
1539 (defcustom org-mark-ring-length 4
1540 "Number of different positions to be recorded in the ring.
1541 Changing this requires a restart of Emacs to work correctly."
1542 :group 'org-link-follow
1543 :type 'integer)
1545 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1546 "Non-nil means internal links in Org files must exactly match a headline.
1547 When nil, the link search tries to match a phrase with all words
1548 in the search text."
1549 :group 'org-link-follow
1550 :version "24.1"
1551 :type '(choice
1552 (const :tag "Use fuzzy text search" nil)
1553 (const :tag "Match only exact headline" t)
1554 (const :tag "Match exact headline or query to create it"
1555 query-to-create)))
1557 (defcustom org-link-frame-setup
1558 '((vm . vm-visit-folder-other-frame)
1559 (vm-imap . vm-visit-imap-folder-other-frame)
1560 (gnus . org-gnus-no-new-news)
1561 (file . find-file-other-window)
1562 (wl . wl-other-frame))
1563 "Setup the frame configuration for following links.
1564 When following a link with Emacs, it may often be useful to display
1565 this link in another window or frame. This variable can be used to
1566 set this up for the different types of links.
1567 For VM, use any of
1568 `vm-visit-folder'
1569 `vm-visit-folder-other-window'
1570 `vm-visit-folder-other-frame'
1571 For Gnus, use any of
1572 `gnus'
1573 `gnus-other-frame'
1574 `org-gnus-no-new-news'
1575 For FILE, use any of
1576 `find-file'
1577 `find-file-other-window'
1578 `find-file-other-frame'
1579 For Wanderlust use any of
1580 `wl'
1581 `wl-other-frame'
1582 For the calendar, use the variable `calendar-setup'.
1583 For BBDB, it is currently only possible to display the matches in
1584 another window."
1585 :group 'org-link-follow
1586 :type '(list
1587 (cons (const vm)
1588 (choice
1589 (const vm-visit-folder)
1590 (const vm-visit-folder-other-window)
1591 (const vm-visit-folder-other-frame)))
1592 (cons (const gnus)
1593 (choice
1594 (const gnus)
1595 (const gnus-other-frame)
1596 (const org-gnus-no-new-news)))
1597 (cons (const file)
1598 (choice
1599 (const find-file)
1600 (const find-file-other-window)
1601 (const find-file-other-frame)))
1602 (cons (const wl)
1603 (choice
1604 (const wl)
1605 (const wl-other-frame)))))
1607 (defcustom org-display-internal-link-with-indirect-buffer nil
1608 "Non-nil means use indirect buffer to display infile links.
1609 Activating internal links (from one location in a file to another location
1610 in the same file) normally just jumps to the location. When the link is
1611 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1612 is displayed in
1613 another window. When this option is set, the other window actually displays
1614 an indirect buffer clone of the current buffer, to avoid any visibility
1615 changes to the current buffer."
1616 :group 'org-link-follow
1617 :type 'boolean)
1619 (defcustom org-open-non-existing-files nil
1620 "Non-nil means `org-open-file' will open non-existing files.
1621 When nil, an error will be generated.
1622 This variable applies only to external applications because they
1623 might choke on non-existing files. If the link is to a file that
1624 will be opened in Emacs, the variable is ignored."
1625 :group 'org-link-follow
1626 :type 'boolean)
1628 (defcustom org-open-directory-means-index-dot-org nil
1629 "Non-nil means a link to a directory really means to index.org.
1630 When nil, following a directory link will run dired or open a finder/explorer
1631 window on that directory."
1632 :group 'org-link-follow
1633 :type 'boolean)
1635 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1636 "Function and arguments to call for following mailto links.
1637 This is a list with the first element being a Lisp function, and the
1638 remaining elements being arguments to the function. In string arguments,
1639 %a will be replaced by the address, and %s will be replaced by the subject
1640 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1641 :group 'org-link-follow
1642 :type '(choice
1643 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1644 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1645 (const :tag "message-mail" (message-mail "%a" "%s"))
1646 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1648 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1649 "Non-nil means ask for confirmation before executing shell links.
1650 Shell links can be dangerous: just think about a link
1652 [[shell:rm -rf ~/*][Google Search]]
1654 This link would show up in your Org-mode document as \"Google Search\",
1655 but really it would remove your entire home directory.
1656 Therefore we advise against setting this variable to nil.
1657 Just change it to `y-or-n-p' if you want to confirm with a
1658 single keystroke rather than having to type \"yes\"."
1659 :group 'org-link-follow
1660 :type '(choice
1661 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1662 (const :tag "with y-or-n (faster)" y-or-n-p)
1663 (const :tag "no confirmation (dangerous)" nil)))
1664 (put 'org-confirm-shell-link-function
1665 'safe-local-variable
1666 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1668 (defcustom org-confirm-shell-link-not-regexp ""
1669 "A regexp to skip confirmation for shell links."
1670 :group 'org-link-follow
1671 :version "24.1"
1672 :type 'regexp)
1674 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1675 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1676 Elisp links can be dangerous: just think about a link
1678 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1680 This link would show up in your Org-mode document as \"Google Search\",
1681 but really it would remove your entire home directory.
1682 Therefore we advise against setting this variable to nil.
1683 Just change it to `y-or-n-p' if you want to confirm with a
1684 single keystroke rather than having to type \"yes\"."
1685 :group 'org-link-follow
1686 :type '(choice
1687 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1688 (const :tag "with y-or-n (faster)" y-or-n-p)
1689 (const :tag "no confirmation (dangerous)" nil)))
1690 (put 'org-confirm-shell-link-function
1691 'safe-local-variable
1692 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1694 (defcustom org-confirm-elisp-link-not-regexp ""
1695 "A regexp to skip confirmation for Elisp links."
1696 :group 'org-link-follow
1697 :version "24.1"
1698 :type 'regexp)
1700 (defconst org-file-apps-defaults-gnu
1701 '((remote . emacs)
1702 (system . mailcap)
1703 (t . mailcap))
1704 "Default file applications on a UNIX or GNU/Linux system.
1705 See `org-file-apps'.")
1707 (defconst org-file-apps-defaults-macosx
1708 '((remote . emacs)
1709 (t . "open %s")
1710 (system . "open %s")
1711 ("ps.gz" . "gv %s")
1712 ("eps.gz" . "gv %s")
1713 ("dvi" . "xdvi %s")
1714 ("fig" . "xfig %s"))
1715 "Default file applications on a MacOS X system.
1716 The system \"open\" is known as a default, but we use X11 applications
1717 for some files for which the OS does not have a good default.
1718 See `org-file-apps'.")
1720 (defconst org-file-apps-defaults-windowsnt
1721 (list
1722 '(remote . emacs)
1723 (cons t
1724 (list (if (featurep 'xemacs)
1725 'mswindows-shell-execute
1726 'w32-shell-execute)
1727 "open" 'file))
1728 (cons 'system
1729 (list (if (featurep 'xemacs)
1730 'mswindows-shell-execute
1731 'w32-shell-execute)
1732 "open" 'file)))
1733 "Default file applications on a Windows NT system.
1734 The system \"open\" is used for most files.
1735 See `org-file-apps'.")
1737 (defcustom org-file-apps
1739 (auto-mode . emacs)
1740 ("\\.mm\\'" . default)
1741 ("\\.x?html?\\'" . default)
1742 ("\\.pdf\\'" . default)
1744 "External applications for opening `file:path' items in a document.
1745 Org-mode uses system defaults for different file types, but
1746 you can use this variable to set the application for a given file
1747 extension. The entries in this list are cons cells where the car identifies
1748 files and the cdr the corresponding command. Possible values for the
1749 file identifier are
1750 \"string\" A string as a file identifier can be interpreted in different
1751 ways, depending on its contents:
1753 - Alphanumeric characters only:
1754 Match links with this file extension.
1755 Example: (\"pdf\" . \"evince %s\")
1756 to open PDFs with evince.
1758 - Regular expression: Match links where the
1759 filename matches the regexp. If you want to
1760 use groups here, use shy groups.
1762 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1763 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1764 to open *.html and *.xhtml with firefox.
1766 - Regular expression which contains (non-shy) groups:
1767 Match links where the whole link, including \"::\", and
1768 anything after that, matches the regexp.
1769 In a custom command string, %1, %2, etc. are replaced with
1770 the parts of the link that were matched by the groups.
1771 For backwards compatibility, if a command string is given
1772 that does not use any of the group matches, this case is
1773 handled identically to the second one (i.e. match against
1774 file name only).
1775 In a custom lisp form, you can access the group matches with
1776 (match-string n link).
1778 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1779 to open [[file:document.pdf::5]] with evince at page 5.
1781 `directory' Matches a directory
1782 `remote' Matches a remote file, accessible through tramp or efs.
1783 Remote files most likely should be visited through Emacs
1784 because external applications cannot handle such paths.
1785 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1786 so all files Emacs knows how to handle. Using this with
1787 command `emacs' will open most files in Emacs. Beware that this
1788 will also open html files inside Emacs, unless you add
1789 (\"html\" . default) to the list as well.
1790 t Default for files not matched by any of the other options.
1791 `system' The system command to open files, like `open' on Windows
1792 and Mac OS X, and mailcap under GNU/Linux. This is the command
1793 that will be selected if you call `C-c C-o' with a double
1794 \\[universal-argument] \\[universal-argument] prefix.
1796 Possible values for the command are:
1797 `emacs' The file will be visited by the current Emacs process.
1798 `default' Use the default application for this file type, which is the
1799 association for t in the list, most likely in the system-specific
1800 part.
1801 This can be used to overrule an unwanted setting in the
1802 system-specific variable.
1803 `system' Use the system command for opening files, like \"open\".
1804 This command is specified by the entry whose car is `system'.
1805 Most likely, the system-specific version of this variable
1806 does define this command, but you can overrule/replace it
1807 here.
1808 string A command to be executed by a shell; %s will be replaced
1809 by the path to the file.
1810 sexp A Lisp form which will be evaluated. The file path will
1811 be available in the Lisp variable `file'.
1812 For more examples, see the system specific constants
1813 `org-file-apps-defaults-macosx'
1814 `org-file-apps-defaults-windowsnt'
1815 `org-file-apps-defaults-gnu'."
1816 :group 'org-link-follow
1817 :type '(repeat
1818 (cons (choice :value ""
1819 (string :tag "Extension")
1820 (const :tag "System command to open files" system)
1821 (const :tag "Default for unrecognized files" t)
1822 (const :tag "Remote file" remote)
1823 (const :tag "Links to a directory" directory)
1824 (const :tag "Any files that have Emacs modes"
1825 auto-mode))
1826 (choice :value ""
1827 (const :tag "Visit with Emacs" emacs)
1828 (const :tag "Use default" default)
1829 (const :tag "Use the system command" system)
1830 (string :tag "Command")
1831 (sexp :tag "Lisp form")))))
1833 (defcustom org-doi-server-url "http://dx.doi.org/"
1834 "The URL of the DOI server."
1835 :type 'string
1836 :version "24.3"
1837 :group 'org-link-follow)
1839 (defgroup org-refile nil
1840 "Options concerning refiling entries in Org-mode."
1841 :tag "Org Refile"
1842 :group 'org)
1844 (defcustom org-directory "~/org"
1845 "Directory with org files.
1846 This is just a default location to look for Org files. There is no need
1847 at all to put your files into this directory. It is only used in the
1848 following situations:
1850 1. When a capture template specifies a target file that is not an
1851 absolute path. The path will then be interpreted relative to
1852 `org-directory'
1853 2. When a capture note is filed away in an interactive way (when exiting the
1854 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1855 with `org-directory' as the default path."
1856 :group 'org-refile
1857 :group 'org-remember
1858 :group 'org-capture
1859 :type 'directory)
1861 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1862 "Default target for storing notes.
1863 Used as a fall back file for org-remember.el and org-capture.el, for
1864 templates that do not specify a target file."
1865 :group 'org-refile
1866 :group 'org-remember
1867 :group 'org-capture
1868 :type '(choice
1869 (const :tag "Default from remember-data-file" nil)
1870 file))
1872 (defcustom org-goto-interface 'outline
1873 "The default interface to be used for `org-goto'.
1874 Allowed values are:
1875 outline The interface shows an outline of the relevant file
1876 and the correct heading is found by moving through
1877 the outline or by searching with incremental search.
1878 outline-path-completion Headlines in the current buffer are offered via
1879 completion. This is the interface also used by
1880 the refile command."
1881 :group 'org-refile
1882 :type '(choice
1883 (const :tag "Outline" outline)
1884 (const :tag "Outline-path-completion" outline-path-completion)))
1886 (defcustom org-goto-max-level 5
1887 "Maximum target level when running `org-goto' with refile interface."
1888 :group 'org-refile
1889 :type 'integer)
1891 (defcustom org-reverse-note-order nil
1892 "Non-nil means store new notes at the beginning of a file or entry.
1893 When nil, new notes will be filed to the end of a file or entry.
1894 This can also be a list with cons cells of regular expressions that
1895 are matched against file names, and values."
1896 :group 'org-remember
1897 :group 'org-capture
1898 :group 'org-refile
1899 :type '(choice
1900 (const :tag "Reverse always" t)
1901 (const :tag "Reverse never" nil)
1902 (repeat :tag "By file name regexp"
1903 (cons regexp boolean))))
1905 (defcustom org-log-refile nil
1906 "Information to record when a task is refiled.
1908 Possible values are:
1910 nil Don't add anything
1911 time Add a time stamp to the task
1912 note Prompt for a note and add it with template `org-log-note-headings'
1914 This option can also be set with on a per-file-basis with
1916 #+STARTUP: nologrefile
1917 #+STARTUP: logrefile
1918 #+STARTUP: lognoterefile
1920 You can have local logging settings for a subtree by setting the LOGGING
1921 property to one or more of these keywords.
1923 When bulk-refiling from the agenda, the value `note' is forbidden and
1924 will temporarily be changed to `time'."
1925 :group 'org-refile
1926 :group 'org-progress
1927 :version "24.1"
1928 :type '(choice
1929 (const :tag "No logging" nil)
1930 (const :tag "Record timestamp" time)
1931 (const :tag "Record timestamp with note." note)))
1933 (defcustom org-refile-targets nil
1934 "Targets for refiling entries with \\[org-refile].
1935 This is a list of cons cells. Each cell contains:
1936 - a specification of the files to be considered, either a list of files,
1937 or a symbol whose function or variable value will be used to retrieve
1938 a file name or a list of file names. If you use `org-agenda-files' for
1939 that, all agenda files will be scanned for targets. Nil means consider
1940 headings in the current buffer.
1941 - A specification of how to find candidate refile targets. This may be
1942 any of:
1943 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1944 This tag has to be present in all target headlines, inheritance will
1945 not be considered.
1946 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1947 todo keyword.
1948 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1949 headlines that are refiling targets.
1950 - a cons cell (:level . N). Any headline of level N is considered a target.
1951 Note that, when `org-odd-levels-only' is set, level corresponds to
1952 order in hierarchy, not to the number of stars.
1953 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1954 Note that, when `org-odd-levels-only' is set, level corresponds to
1955 order in hierarchy, not to the number of stars.
1957 Each element of this list generates a set of possible targets.
1958 The union of these sets is presented (with completion) to
1959 the user by `org-refile'.
1961 You can set the variable `org-refile-target-verify-function' to a function
1962 to verify each headline found by the simple criteria above.
1964 When this variable is nil, all top-level headlines in the current buffer
1965 are used, equivalent to the value `((nil . (:level . 1))'."
1966 :group 'org-refile
1967 :type '(repeat
1968 (cons
1969 (choice :value org-agenda-files
1970 (const :tag "All agenda files" org-agenda-files)
1971 (const :tag "Current buffer" nil)
1972 (function) (variable) (file))
1973 (choice :tag "Identify target headline by"
1974 (cons :tag "Specific tag" (const :value :tag) (string))
1975 (cons :tag "TODO keyword" (const :value :todo) (string))
1976 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1977 (cons :tag "Level number" (const :value :level) (integer))
1978 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1980 (defcustom org-refile-target-verify-function nil
1981 "Function to verify if the headline at point should be a refile target.
1982 The function will be called without arguments, with point at the
1983 beginning of the headline. It should return t and leave point
1984 where it is if the headline is a valid target for refiling.
1986 If the target should not be selected, the function must return nil.
1987 In addition to this, it may move point to a place from where the search
1988 should be continued. For example, the function may decide that the entire
1989 subtree of the current entry should be excluded and move point to the end
1990 of the subtree."
1991 :group 'org-refile
1992 :type 'function)
1994 (defcustom org-refile-use-cache nil
1995 "Non-nil means cache refile targets to speed up the process.
1996 The cache for a particular file will be updated automatically when
1997 the buffer has been killed, or when any of the marker used for flagging
1998 refile targets no longer points at a live buffer.
1999 If you have added new entries to a buffer that might themselves be targets,
2000 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2001 find that easier, `C-u C-u C-u C-c C-w'."
2002 :group 'org-refile
2003 :version "24.1"
2004 :type 'boolean)
2006 (defcustom org-refile-use-outline-path nil
2007 "Non-nil means provide refile targets as paths.
2008 So a level 3 headline will be available as level1/level2/level3.
2010 When the value is `file', also include the file name (without directory)
2011 into the path. In this case, you can also stop the completion after
2012 the file name, to get entries inserted as top level in the file.
2014 When `full-file-path', include the full file path."
2015 :group 'org-refile
2016 :type '(choice
2017 (const :tag "Not" nil)
2018 (const :tag "Yes" t)
2019 (const :tag "Start with file name" file)
2020 (const :tag "Start with full file path" full-file-path)))
2022 (defcustom org-outline-path-complete-in-steps t
2023 "Non-nil means complete the outline path in hierarchical steps.
2024 When Org-mode uses the refile interface to select an outline path
2025 \(see variable `org-refile-use-outline-path'), the completion of
2026 the path can be done is a single go, or if can be done in steps down
2027 the headline hierarchy. Going in steps is probably the best if you
2028 do not use a special completion package like `ido' or `icicles'.
2029 However, when using these packages, going in one step can be very
2030 fast, while still showing the whole path to the entry."
2031 :group 'org-refile
2032 :type 'boolean)
2034 (defcustom org-refile-allow-creating-parent-nodes nil
2035 "Non-nil means allow to create new nodes as refile targets.
2036 New nodes are then created by adding \"/new node name\" to the completion
2037 of an existing node. When the value of this variable is `confirm',
2038 new node creation must be confirmed by the user (recommended)
2039 When nil, the completion must match an existing entry.
2041 Note that, if the new heading is not seen by the criteria
2042 listed in `org-refile-targets', multiple instances of the same
2043 heading would be created by trying again to file under the new
2044 heading."
2045 :group 'org-refile
2046 :type '(choice
2047 (const :tag "Never" nil)
2048 (const :tag "Always" t)
2049 (const :tag "Prompt for confirmation" confirm)))
2051 (defcustom org-refile-active-region-within-subtree nil
2052 "Non-nil means also refile active region within a subtree.
2054 By default `org-refile' doesn't allow refiling regions if they
2055 don't contain a set of subtrees, but it might be convenient to
2056 do so sometimes: in that case, the first line of the region is
2057 converted to a headline before refiling."
2058 :group 'org-refile
2059 :version "24.1"
2060 :type 'boolean)
2062 (defgroup org-todo nil
2063 "Options concerning TODO items in Org-mode."
2064 :tag "Org TODO"
2065 :group 'org)
2067 (defgroup org-progress nil
2068 "Options concerning Progress logging in Org-mode."
2069 :tag "Org Progress"
2070 :group 'org-time)
2072 (defvar org-todo-interpretation-widgets
2073 '((:tag "Sequence (cycling hits every state)" sequence)
2074 (:tag "Type (cycling directly to DONE)" type))
2075 "The available interpretation symbols for customizing `org-todo-keywords'.
2076 Interested libraries should add to this list.")
2078 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2079 "List of TODO entry keyword sequences and their interpretation.
2080 \\<org-mode-map>This is a list of sequences.
2082 Each sequence starts with a symbol, either `sequence' or `type',
2083 indicating if the keywords should be interpreted as a sequence of
2084 action steps, or as different types of TODO items. The first
2085 keywords are states requiring action - these states will select a headline
2086 for inclusion into the global TODO list Org-mode produces. If one of
2087 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2088 signify that no further action is necessary. If \"|\" is not found,
2089 the last keyword is treated as the only DONE state of the sequence.
2091 The command \\[org-todo] cycles an entry through these states, and one
2092 additional state where no keyword is present. For details about this
2093 cycling, see the manual.
2095 TODO keywords and interpretation can also be set on a per-file basis with
2096 the special #+SEQ_TODO and #+TYP_TODO lines.
2098 Each keyword can optionally specify a character for fast state selection
2099 \(in combination with the variable `org-use-fast-todo-selection')
2100 and specifiers for state change logging, using the same syntax that
2101 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2102 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2103 indicates to record a time stamp each time this state is selected.
2105 Each keyword may also specify if a timestamp or a note should be
2106 recorded when entering or leaving the state, by adding additional
2107 characters in the parenthesis after the keyword. This looks like this:
2108 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2109 record only the time of the state change. With X and Y being either
2110 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2111 Y when leaving the state if and only if the *target* state does not
2112 define X. You may omit any of the fast-selection key or X or /Y,
2113 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2115 For backward compatibility, this variable may also be just a list
2116 of keywords. In this case the interpretation (sequence or type) will be
2117 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2118 :group 'org-todo
2119 :group 'org-keywords
2120 :type '(choice
2121 (repeat :tag "Old syntax, just keywords"
2122 (string :tag "Keyword"))
2123 (repeat :tag "New syntax"
2124 (cons
2125 (choice
2126 :tag "Interpretation"
2127 ;;Quick and dirty way to see
2128 ;;`org-todo-interpretations'. This takes the
2129 ;;place of item arguments
2130 :convert-widget
2131 (lambda (widget)
2132 (widget-put widget
2133 :args (mapcar
2134 #'(lambda (x)
2135 (widget-convert
2136 (cons 'const x)))
2137 org-todo-interpretation-widgets))
2138 widget))
2139 (repeat
2140 (string :tag "Keyword"))))))
2142 (defvar org-todo-keywords-1 nil
2143 "All TODO and DONE keywords active in a buffer.")
2144 (make-variable-buffer-local 'org-todo-keywords-1)
2145 (defvar org-todo-keywords-for-agenda nil)
2146 (defvar org-done-keywords-for-agenda nil)
2147 (defvar org-drawers-for-agenda nil)
2148 (defvar org-todo-keyword-alist-for-agenda nil)
2149 (defvar org-tag-alist-for-agenda nil)
2150 (defvar org-agenda-contributing-files nil)
2151 (defvar org-not-done-keywords nil)
2152 (make-variable-buffer-local 'org-not-done-keywords)
2153 (defvar org-done-keywords nil)
2154 (make-variable-buffer-local 'org-done-keywords)
2155 (defvar org-todo-heads nil)
2156 (make-variable-buffer-local 'org-todo-heads)
2157 (defvar org-todo-sets nil)
2158 (make-variable-buffer-local 'org-todo-sets)
2159 (defvar org-todo-log-states nil)
2160 (make-variable-buffer-local 'org-todo-log-states)
2161 (defvar org-todo-kwd-alist nil)
2162 (make-variable-buffer-local 'org-todo-kwd-alist)
2163 (defvar org-todo-key-alist nil)
2164 (make-variable-buffer-local 'org-todo-key-alist)
2165 (defvar org-todo-key-trigger nil)
2166 (make-variable-buffer-local 'org-todo-key-trigger)
2168 (defcustom org-todo-interpretation 'sequence
2169 "Controls how TODO keywords are interpreted.
2170 This variable is in principle obsolete and is only used for
2171 backward compatibility, if the interpretation of todo keywords is
2172 not given already in `org-todo-keywords'. See that variable for
2173 more information."
2174 :group 'org-todo
2175 :group 'org-keywords
2176 :type '(choice (const sequence)
2177 (const type)))
2179 (defcustom org-use-fast-todo-selection t
2180 "Non-nil means use the fast todo selection scheme with C-c C-t.
2181 This variable describes if and under what circumstances the cycling
2182 mechanism for TODO keywords will be replaced by a single-key, direct
2183 selection scheme.
2185 When nil, fast selection is never used.
2187 When the symbol `prefix', it will be used when `org-todo' is called
2188 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2189 `C-u t' in an agenda buffer.
2191 When t, fast selection is used by default. In this case, the prefix
2192 argument forces cycling instead.
2194 In all cases, the special interface is only used if access keys have
2195 actually been assigned by the user, i.e. if keywords in the configuration
2196 are followed by a letter in parenthesis, like TODO(t)."
2197 :group 'org-todo
2198 :type '(choice
2199 (const :tag "Never" nil)
2200 (const :tag "By default" t)
2201 (const :tag "Only with C-u C-c C-t" prefix)))
2203 (defcustom org-provide-todo-statistics t
2204 "Non-nil means update todo statistics after insert and toggle.
2205 ALL-HEADLINES means update todo statistics by including headlines
2206 with no TODO keyword as well, counting them as not done.
2207 A list of TODO keywords means the same, but skip keywords that are
2208 not in this list.
2210 When this is set, todo statistics is updated in the parent of the
2211 current entry each time a todo state is changed."
2212 :group 'org-todo
2213 :type '(choice
2214 (const :tag "Yes, only for TODO entries" t)
2215 (const :tag "Yes, including all entries" 'all-headlines)
2216 (repeat :tag "Yes, for TODOs in this list"
2217 (string :tag "TODO keyword"))
2218 (other :tag "No TODO statistics" nil)))
2220 (defcustom org-hierarchical-todo-statistics t
2221 "Non-nil means TODO statistics covers just direct children.
2222 When nil, all entries in the subtree are considered.
2223 This has only an effect if `org-provide-todo-statistics' is set.
2224 To set this to nil for only a single subtree, use a COOKIE_DATA
2225 property and include the word \"recursive\" into the value."
2226 :group 'org-todo
2227 :type 'boolean)
2229 (defcustom org-after-todo-state-change-hook nil
2230 "Hook which is run after the state of a TODO item was changed.
2231 The new state (a string with a TODO keyword, or nil) is available in the
2232 Lisp variable `org-state'."
2233 :group 'org-todo
2234 :type 'hook)
2236 (defvar org-blocker-hook nil
2237 "Hook for functions that are allowed to block a state change.
2239 Each function gets as its single argument a property list, see
2240 `org-trigger-hook' for more information about this list.
2242 If any of the functions in this hook returns nil, the state change
2243 is blocked.")
2245 (defvar org-trigger-hook nil
2246 "Hook for functions that are triggered by a state change.
2248 Each function gets as its single argument a property list with at least
2249 the following elements:
2251 (:type type-of-change :position pos-at-entry-start
2252 :from old-state :to new-state)
2254 Depending on the type, more properties may be present.
2256 This mechanism is currently implemented for:
2258 TODO state changes
2259 ------------------
2260 :type todo-state-change
2261 :from previous state (keyword as a string), or nil, or a symbol
2262 'todo' or 'done', to indicate the general type of state.
2263 :to new state, like in :from")
2265 (defcustom org-enforce-todo-dependencies nil
2266 "Non-nil means undone TODO entries will block switching the parent to DONE.
2267 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2268 be blocked if any prior sibling is not yet done.
2269 Finally, if the parent is blocked because of ordered siblings of its own,
2270 the child will also be blocked."
2271 :set (lambda (var val)
2272 (set var val)
2273 (if val
2274 (add-hook 'org-blocker-hook
2275 'org-block-todo-from-children-or-siblings-or-parent)
2276 (remove-hook 'org-blocker-hook
2277 'org-block-todo-from-children-or-siblings-or-parent)))
2278 :group 'org-todo
2279 :type 'boolean)
2281 (defcustom org-enforce-todo-checkbox-dependencies nil
2282 "Non-nil means unchecked boxes will block switching the parent to DONE.
2283 When this is nil, checkboxes have no influence on switching TODO states.
2284 When non-nil, you first need to check off all check boxes before the TODO
2285 entry can be switched to DONE.
2286 This variable needs to be set before org.el is loaded, and you need to
2287 restart Emacs after a change to make the change effective. The only way
2288 to change is while Emacs is running is through the customize interface."
2289 :set (lambda (var val)
2290 (set var val)
2291 (if val
2292 (add-hook 'org-blocker-hook
2293 'org-block-todo-from-checkboxes)
2294 (remove-hook 'org-blocker-hook
2295 'org-block-todo-from-checkboxes)))
2296 :group 'org-todo
2297 :type 'boolean)
2299 (defcustom org-treat-insert-todo-heading-as-state-change nil
2300 "Non-nil means inserting a TODO heading is treated as state change.
2301 So when the command \\[org-insert-todo-heading] is used, state change
2302 logging will apply if appropriate. When nil, the new TODO item will
2303 be inserted directly, and no logging will take place."
2304 :group 'org-todo
2305 :type 'boolean)
2307 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2308 "Non-nil means switching TODO states with S-cursor counts as state change.
2309 This is the default behavior. However, setting this to nil allows a
2310 convenient way to select a TODO state and bypass any logging associated
2311 with that."
2312 :group 'org-todo
2313 :type 'boolean)
2315 (defcustom org-todo-state-tags-triggers nil
2316 "Tag changes that should be triggered by TODO state changes.
2317 This is a list. Each entry is
2319 (state-change (tag . flag) .......)
2321 State-change can be a string with a state, and empty string to indicate the
2322 state that has no TODO keyword, or it can be one of the symbols `todo'
2323 or `done', meaning any not-done or done state, respectively."
2324 :group 'org-todo
2325 :group 'org-tags
2326 :type '(repeat
2327 (cons (choice :tag "When changing to"
2328 (const :tag "Not-done state" todo)
2329 (const :tag "Done state" done)
2330 (string :tag "State"))
2331 (repeat
2332 (cons :tag "Tag action"
2333 (string :tag "Tag")
2334 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2336 (defcustom org-log-done nil
2337 "Information to record when a task moves to the DONE state.
2339 Possible values are:
2341 nil Don't add anything, just change the keyword
2342 time Add a time stamp to the task
2343 note Prompt for a note and add it with template `org-log-note-headings'
2345 This option can also be set with on a per-file-basis with
2347 #+STARTUP: nologdone
2348 #+STARTUP: logdone
2349 #+STARTUP: lognotedone
2351 You can have local logging settings for a subtree by setting the LOGGING
2352 property to one or more of these keywords."
2353 :group 'org-todo
2354 :group 'org-progress
2355 :type '(choice
2356 (const :tag "No logging" nil)
2357 (const :tag "Record CLOSED timestamp" time)
2358 (const :tag "Record CLOSED timestamp with note." note)))
2360 ;; Normalize old uses of org-log-done.
2361 (cond
2362 ((eq org-log-done t) (setq org-log-done 'time))
2363 ((and (listp org-log-done) (memq 'done org-log-done))
2364 (setq org-log-done 'note)))
2366 (defcustom org-log-reschedule nil
2367 "Information to record when the scheduling date of a tasks is modified.
2369 Possible values are:
2371 nil Don't add anything, just change the date
2372 time Add a time stamp to the task
2373 note Prompt for a note and add it with template `org-log-note-headings'
2375 This option can also be set with on a per-file-basis with
2377 #+STARTUP: nologreschedule
2378 #+STARTUP: logreschedule
2379 #+STARTUP: lognotereschedule"
2380 :group 'org-todo
2381 :group 'org-progress
2382 :type '(choice
2383 (const :tag "No logging" nil)
2384 (const :tag "Record timestamp" time)
2385 (const :tag "Record timestamp with note." note)))
2387 (defcustom org-log-redeadline nil
2388 "Information to record when the deadline date of a tasks is modified.
2390 Possible values are:
2392 nil Don't add anything, just change the date
2393 time Add a time stamp to the task
2394 note Prompt for a note and add it with template `org-log-note-headings'
2396 This option can also be set with on a per-file-basis with
2398 #+STARTUP: nologredeadline
2399 #+STARTUP: logredeadline
2400 #+STARTUP: lognoteredeadline
2402 You can have local logging settings for a subtree by setting the LOGGING
2403 property to one or more of these keywords."
2404 :group 'org-todo
2405 :group 'org-progress
2406 :type '(choice
2407 (const :tag "No logging" nil)
2408 (const :tag "Record timestamp" time)
2409 (const :tag "Record timestamp with note." note)))
2411 (defcustom org-log-note-clock-out nil
2412 "Non-nil means record a note when clocking out of an item.
2413 This can also be configured on a per-file basis by adding one of
2414 the following lines anywhere in the buffer:
2416 #+STARTUP: lognoteclock-out
2417 #+STARTUP: nolognoteclock-out"
2418 :group 'org-todo
2419 :group 'org-progress
2420 :type 'boolean)
2422 (defcustom org-log-done-with-time t
2423 "Non-nil means the CLOSED time stamp will contain date and time.
2424 When nil, only the date will be recorded."
2425 :group 'org-progress
2426 :type 'boolean)
2428 (defcustom org-log-note-headings
2429 '((done . "CLOSING NOTE %t")
2430 (state . "State %-12s from %-12S %t")
2431 (note . "Note taken on %t")
2432 (reschedule . "Rescheduled from %S on %t")
2433 (delschedule . "Not scheduled, was %S on %t")
2434 (redeadline . "New deadline from %S on %t")
2435 (deldeadline . "Removed deadline, was %S on %t")
2436 (refile . "Refiled on %t")
2437 (clock-out . ""))
2438 "Headings for notes added to entries.
2439 The value is an alist, with the car being a symbol indicating the note
2440 context, and the cdr is the heading to be used. The heading may also be the
2441 empty string.
2442 %t in the heading will be replaced by a time stamp.
2443 %T will be an active time stamp instead the default inactive one
2444 %d will be replaced by a short-format time stamp.
2445 %D will be replaced by an active short-format time stamp.
2446 %s will be replaced by the new TODO state, in double quotes.
2447 %S will be replaced by the old TODO state, in double quotes.
2448 %u will be replaced by the user name.
2449 %U will be replaced by the full user name.
2451 In fact, it is not a good idea to change the `state' entry, because
2452 agenda log mode depends on the format of these entries."
2453 :group 'org-todo
2454 :group 'org-progress
2455 :type '(list :greedy t
2456 (cons (const :tag "Heading when closing an item" done) string)
2457 (cons (const :tag
2458 "Heading when changing todo state (todo sequence only)"
2459 state) string)
2460 (cons (const :tag "Heading when just taking a note" note) string)
2461 (cons (const :tag "Heading when clocking out" clock-out) string)
2462 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2463 (cons (const :tag "Heading when rescheduling" reschedule) string)
2464 (cons (const :tag "Heading when changing deadline" redeadline) string)
2465 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2466 (cons (const :tag "Heading when refiling" refile) string)))
2468 (unless (assq 'note org-log-note-headings)
2469 (push '(note . "%t") org-log-note-headings))
2471 (defcustom org-log-into-drawer nil
2472 "Non-nil means insert state change notes and time stamps into a drawer.
2473 When nil, state changes notes will be inserted after the headline and
2474 any scheduling and clock lines, but not inside a drawer.
2476 The value of this variable should be the name of the drawer to use.
2477 LOGBOOK is proposed as the default drawer for this purpose, you can
2478 also set this to a string to define the drawer of your choice.
2480 A value of t is also allowed, representing \"LOGBOOK\".
2482 If this variable is set, `org-log-state-notes-insert-after-drawers'
2483 will be ignored.
2485 You can set the property LOG_INTO_DRAWER to overrule this setting for
2486 a subtree."
2487 :group 'org-todo
2488 :group 'org-progress
2489 :type '(choice
2490 (const :tag "Not into a drawer" nil)
2491 (const :tag "LOGBOOK" t)
2492 (string :tag "Other")))
2494 (if (fboundp 'defvaralias)
2495 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2497 (defun org-log-into-drawer ()
2498 "Return the value of `org-log-into-drawer', but let properties overrule.
2499 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2500 used instead of the default value."
2501 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2502 (cond
2503 ((not p) org-log-into-drawer)
2504 ((equal p "nil") nil)
2505 ((equal p "t") "LOGBOOK")
2506 (t p))))
2508 (defcustom org-log-state-notes-insert-after-drawers nil
2509 "Non-nil means insert state change notes after any drawers in entry.
2510 Only the drawers that *immediately* follow the headline and the
2511 deadline/scheduled line are skipped.
2512 When nil, insert notes right after the heading and perhaps the line
2513 with deadline/scheduling if present.
2515 This variable will have no effect if `org-log-into-drawer' is
2516 set."
2517 :group 'org-todo
2518 :group 'org-progress
2519 :type 'boolean)
2521 (defcustom org-log-states-order-reversed t
2522 "Non-nil means the latest state note will be directly after heading.
2523 When nil, the state change notes will be ordered according to time."
2524 :group 'org-todo
2525 :group 'org-progress
2526 :type 'boolean)
2528 (defcustom org-todo-repeat-to-state nil
2529 "The TODO state to which a repeater should return the repeating task.
2530 By default this is the first task in a TODO sequence, or the previous state
2531 in a TODO_TYP set. But you can specify another task here.
2532 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2533 :group 'org-todo
2534 :version "24.1"
2535 :type '(choice (const :tag "Head of sequence" nil)
2536 (string :tag "Specific state")))
2538 (defcustom org-log-repeat 'time
2539 "Non-nil means record moving through the DONE state when triggering repeat.
2540 An auto-repeating task is immediately switched back to TODO when
2541 marked DONE. If you are not logging state changes (by adding \"@\"
2542 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2543 record a closing note, there will be no record of the task moving
2544 through DONE. This variable forces taking a note anyway.
2546 nil Don't force a record
2547 time Record a time stamp
2548 note Prompt for a note and add it with template `org-log-note-headings'
2550 This option can also be set with on a per-file-basis with
2552 #+STARTUP: nologrepeat
2553 #+STARTUP: logrepeat
2554 #+STARTUP: lognoterepeat
2556 You can have local logging settings for a subtree by setting the LOGGING
2557 property to one or more of these keywords."
2558 :group 'org-todo
2559 :group 'org-progress
2560 :type '(choice
2561 (const :tag "Don't force a record" nil)
2562 (const :tag "Force recording the DONE state" time)
2563 (const :tag "Force recording a note with the DONE state" note)))
2566 (defgroup org-priorities nil
2567 "Priorities in Org-mode."
2568 :tag "Org Priorities"
2569 :group 'org-todo)
2571 (defcustom org-enable-priority-commands t
2572 "Non-nil means priority commands are active.
2573 When nil, these commands will be disabled, so that you never accidentally
2574 set a priority."
2575 :group 'org-priorities
2576 :type 'boolean)
2578 (defcustom org-highest-priority ?A
2579 "The highest priority of TODO items. A character like ?A, ?B etc.
2580 Must have a smaller ASCII number than `org-lowest-priority'."
2581 :group 'org-priorities
2582 :type 'character)
2584 (defcustom org-lowest-priority ?C
2585 "The lowest priority of TODO items. A character like ?A, ?B etc.
2586 Must have a larger ASCII number than `org-highest-priority'."
2587 :group 'org-priorities
2588 :type 'character)
2590 (defcustom org-default-priority ?B
2591 "The default priority of TODO items.
2592 This is the priority an item gets if no explicit priority is given.
2593 When starting to cycle on an empty priority the first step in the cycle
2594 depends on `org-priority-start-cycle-with-default'. The resulting first
2595 step priority must not exceed the range from `org-highest-priority' to
2596 `org-lowest-priority' which means that `org-default-priority' has to be
2597 in this range exclusive or inclusive the range boundaries. Else the
2598 first step refuses to set the default and the second will fall back
2599 to (depending on the command used) the highest or lowest priority."
2600 :group 'org-priorities
2601 :type 'character)
2603 (defcustom org-priority-start-cycle-with-default t
2604 "Non-nil means start with default priority when starting to cycle.
2605 When this is nil, the first step in the cycle will be (depending on the
2606 command used) one higher or lower than the default priority.
2607 See also `org-default-priority'."
2608 :group 'org-priorities
2609 :type 'boolean)
2611 (defcustom org-get-priority-function nil
2612 "Function to extract the priority from a string.
2613 The string is normally the headline. If this is nil Org computes the
2614 priority from the priority cookie like [#A] in the headline. It returns
2615 an integer, increasing by 1000 for each priority level.
2616 The user can set a different function here, which should take a string
2617 as an argument and return the numeric priority."
2618 :group 'org-priorities
2619 :version "24.1"
2620 :type 'function)
2622 (defgroup org-time nil
2623 "Options concerning time stamps and deadlines in Org-mode."
2624 :tag "Org Time"
2625 :group 'org)
2627 (defcustom org-insert-labeled-timestamps-at-point nil
2628 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2629 When nil, these labeled time stamps are forces into the second line of an
2630 entry, just after the headline. When scheduling from the global TODO list,
2631 the time stamp will always be forced into the second line."
2632 :group 'org-time
2633 :type 'boolean)
2635 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2636 "Formats for `format-time-string' which are used for time stamps.
2637 It is not recommended to change this constant.")
2639 (defcustom org-time-stamp-rounding-minutes '(0 5)
2640 "Number of minutes to round time stamps to.
2641 These are two values, the first applies when first creating a time stamp.
2642 The second applies when changing it with the commands `S-up' and `S-down'.
2643 When changing the time stamp, this means that it will change in steps
2644 of N minutes, as given by the second value.
2646 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2647 numbers should be factors of 60, so for example 5, 10, 15.
2649 When this is larger than 1, you can still force an exact time stamp by using
2650 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2651 and by using a prefix arg to `S-up/down' to specify the exact number
2652 of minutes to shift."
2653 :group 'org-time
2654 :get #'(lambda (var) ; Make sure both elements are there
2655 (if (integerp (default-value var))
2656 (list (default-value var) 5)
2657 (default-value var)))
2658 :type '(list
2659 (integer :tag "when inserting times")
2660 (integer :tag "when modifying times")))
2662 ;; Normalize old customizations of this variable.
2663 (when (integerp org-time-stamp-rounding-minutes)
2664 (setq org-time-stamp-rounding-minutes
2665 (list org-time-stamp-rounding-minutes
2666 org-time-stamp-rounding-minutes)))
2668 (defcustom org-display-custom-times nil
2669 "Non-nil means overlay custom formats over all time stamps.
2670 The formats are defined through the variable `org-time-stamp-custom-formats'.
2671 To turn this on on a per-file basis, insert anywhere in the file:
2672 #+STARTUP: customtime"
2673 :group 'org-time
2674 :set 'set-default
2675 :type 'sexp)
2676 (make-variable-buffer-local 'org-display-custom-times)
2678 (defcustom org-time-stamp-custom-formats
2679 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2680 "Custom formats for time stamps. See `format-time-string' for the syntax.
2681 These are overlaid over the default ISO format if the variable
2682 `org-display-custom-times' is set. Time like %H:%M should be at the
2683 end of the second format. The custom formats are also honored by export
2684 commands, if custom time display is turned on at the time of export."
2685 :group 'org-time
2686 :type 'sexp)
2688 (defun org-time-stamp-format (&optional long inactive)
2689 "Get the right format for a time string."
2690 (let ((f (if long (cdr org-time-stamp-formats)
2691 (car org-time-stamp-formats))))
2692 (if inactive
2693 (concat "[" (substring f 1 -1) "]")
2694 f)))
2696 (defcustom org-time-clocksum-format "%d:%02d"
2697 "The format string used when creating CLOCKSUM lines.
2698 This is also used when org-mode generates a time duration."
2699 :group 'org-time
2700 :type 'string)
2702 (defcustom org-time-clocksum-use-fractional nil
2703 "If non-nil, \\[org-clock-display] uses fractional times.
2704 org-mode generates a time duration."
2705 :group 'org-time
2706 :type 'boolean)
2708 (defcustom org-time-clocksum-fractional-format "%.2f"
2709 "The format string used when creating CLOCKSUM lines, or when
2710 org-mode generates a time duration."
2711 :group 'org-time
2712 :type 'string)
2714 (defcustom org-deadline-warning-days 14
2715 "No. of days before expiration during which a deadline becomes active.
2716 This variable governs the display in sparse trees and in the agenda.
2717 When 0 or negative, it means use this number (the absolute value of it)
2718 even if a deadline has a different individual lead time specified.
2720 Custom commands can set this variable in the options section."
2721 :group 'org-time
2722 :group 'org-agenda-daily/weekly
2723 :type 'integer)
2725 (defcustom org-read-date-prefer-future t
2726 "Non-nil means assume future for incomplete date input from user.
2727 This affects the following situations:
2728 1. The user gives a month but not a year.
2729 For example, if it is April and you enter \"feb 2\", this will be read
2730 as Feb 2, *next* year. \"May 5\", however, will be this year.
2731 2. The user gives a day, but no month.
2732 For example, if today is the 15th, and you enter \"3\", Org-mode will
2733 read this as the third of *next* month. However, if you enter \"17\",
2734 it will be considered as *this* month.
2736 If you set this variable to the symbol `time', then also the following
2737 will work:
2739 3. If the user gives a time.
2740 If the time is before now, it will be interpreted as tomorrow.
2742 Currently none of this works for ISO week specifications.
2744 When this option is nil, the current day, month and year will always be
2745 used as defaults.
2747 See also `org-agenda-jump-prefer-future'."
2748 :group 'org-time
2749 :type '(choice
2750 (const :tag "Never" nil)
2751 (const :tag "Check month and day" t)
2752 (const :tag "Check month, day, and time" time)))
2754 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2755 "Should the agenda jump command prefer the future for incomplete dates?
2756 The default is to do the same as configured in `org-read-date-prefer-future'.
2757 But you can also set a deviating value here.
2758 This may t or nil, or the symbol `org-read-date-prefer-future'."
2759 :group 'org-agenda
2760 :group 'org-time
2761 :version "24.1"
2762 :type '(choice
2763 (const :tag "Use org-read-date-prefer-future"
2764 org-read-date-prefer-future)
2765 (const :tag "Never" nil)
2766 (const :tag "Always" t)))
2768 (defcustom org-read-date-force-compatible-dates t
2769 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2771 Depending on the system Emacs is running on, certain dates cannot
2772 be represented with the type used internally to represent time.
2773 Dates between 1970-1-1 and 2038-1-1 can always be represented
2774 correctly. Some systems allow for earlier dates, some for later,
2775 some for both. One way to find out it to insert any date into an
2776 Org buffer, putting the cursor on the year and hitting S-up and
2777 S-down to test the range.
2779 When this variable is set to t, the date/time prompt will not let
2780 you specify dates outside the 1970-2037 range, so it is certain that
2781 these dates will work in whatever version of Emacs you are
2782 running, and also that you can move a file from one Emacs implementation
2783 to another. WHenever Org is forcing the year for you, it will display
2784 a message and beep.
2786 When this variable is nil, Org will check if the date is
2787 representable in the specific Emacs implementation you are using.
2788 If not, it will force a year, usually the current year, and beep
2789 to remind you. Currently this setting is not recommended because
2790 the likelihood that you will open your Org files in an Emacs that
2791 has limited date range is not negligible.
2793 A workaround for this problem is to use diary sexp dates for time
2794 stamps outside of this range."
2795 :group 'org-time
2796 :version "24.1"
2797 :type 'boolean)
2799 (defcustom org-read-date-display-live t
2800 "Non-nil means display current interpretation of date prompt live.
2801 This display will be in an overlay, in the minibuffer."
2802 :group 'org-time
2803 :type 'boolean)
2805 (defcustom org-read-date-popup-calendar t
2806 "Non-nil means pop up a calendar when prompting for a date.
2807 In the calendar, the date can be selected with mouse-1. However, the
2808 minibuffer will also be active, and you can simply enter the date as well.
2809 When nil, only the minibuffer will be available."
2810 :group 'org-time
2811 :type 'boolean)
2812 (if (fboundp 'defvaralias)
2813 (defvaralias 'org-popup-calendar-for-date-prompt
2814 'org-read-date-popup-calendar))
2816 (defcustom org-read-date-minibuffer-setup-hook nil
2817 "Hook to be used to set up keys for the date/time interface.
2818 Add key definitions to `minibuffer-local-map', which will be a temporary
2819 copy."
2820 :group 'org-time
2821 :type 'hook)
2823 (defcustom org-extend-today-until 0
2824 "The hour when your day really ends. Must be an integer.
2825 This has influence for the following applications:
2826 - When switching the agenda to \"today\". It it is still earlier than
2827 the time given here, the day recognized as TODAY is actually yesterday.
2828 - When a date is read from the user and it is still before the time given
2829 here, the current date and time will be assumed to be yesterday, 23:59.
2830 Also, timestamps inserted in capture templates follow this rule.
2832 IMPORTANT: This is a feature whose implementation is and likely will
2833 remain incomplete. Really, it is only here because past midnight seems to
2834 be the favorite working time of John Wiegley :-)"
2835 :group 'org-time
2836 :type 'integer)
2838 (defcustom org-use-effective-time nil
2839 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2840 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2841 \"effective time\" of any timestamps between midnight and 8am will be
2842 23:59 of the previous day."
2843 :group 'org-time
2844 :version "24.1"
2845 :type 'boolean)
2847 (defcustom org-edit-timestamp-down-means-later nil
2848 "Non-nil means S-down will increase the time in a time stamp.
2849 When nil, S-up will increase."
2850 :group 'org-time
2851 :type 'boolean)
2853 (defcustom org-calendar-follow-timestamp-change t
2854 "Non-nil means make the calendar window follow timestamp changes.
2855 When a timestamp is modified and the calendar window is visible, it will be
2856 moved to the new date."
2857 :group 'org-time
2858 :type 'boolean)
2860 (defgroup org-tags nil
2861 "Options concerning tags in Org-mode."
2862 :tag "Org Tags"
2863 :group 'org)
2865 (defcustom org-tag-alist nil
2866 "List of tags allowed in Org-mode files.
2867 When this list is nil, Org-mode will base TAG input on what is already in the
2868 buffer.
2869 The value of this variable is an alist, the car of each entry must be a
2870 keyword as a string, the cdr may be a character that is used to select
2871 that tag through the fast-tag-selection interface.
2872 See the manual for details."
2873 :group 'org-tags
2874 :type '(repeat
2875 (choice
2876 (cons (string :tag "Tag name")
2877 (character :tag "Access char"))
2878 (list :tag "Start radio group"
2879 (const :startgroup)
2880 (option (string :tag "Group description")))
2881 (list :tag "End radio group"
2882 (const :endgroup)
2883 (option (string :tag "Group description")))
2884 (const :tag "New line" (:newline)))))
2886 (defcustom org-tag-persistent-alist nil
2887 "List of tags that will always appear in all Org-mode files.
2888 This is in addition to any in buffer settings or customizations
2889 of `org-tag-alist'.
2890 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2891 The value of this variable is an alist, the car of each entry must be a
2892 keyword as a string, the cdr may be a character that is used to select
2893 that tag through the fast-tag-selection interface.
2894 See the manual for details.
2895 To disable these tags on a per-file basis, insert anywhere in the file:
2896 #+STARTUP: noptag"
2897 :group 'org-tags
2898 :type '(repeat
2899 (choice
2900 (cons (string :tag "Tag name")
2901 (character :tag "Access char"))
2902 (const :tag "Start radio group" (:startgroup))
2903 (const :tag "End radio group" (:endgroup))
2904 (const :tag "New line" (:newline)))))
2906 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2907 "If non-nil, always offer completion for all tags of all agenda files.
2908 Instead of customizing this variable directly, you might want to
2909 set it locally for capture buffers, because there no list of
2910 tags in that file can be created dynamically (there are none).
2912 (add-hook 'org-capture-mode-hook
2913 (lambda ()
2914 (set (make-local-variable
2915 'org-complete-tags-always-offer-all-agenda-tags)
2916 t)))"
2917 :group 'org-tags
2918 :version "24.1"
2919 :type 'boolean)
2921 (defvar org-file-tags nil
2922 "List of tags that can be inherited by all entries in the file.
2923 The tags will be inherited if the variable `org-use-tag-inheritance'
2924 says they should be.
2925 This variable is populated from #+FILETAGS lines.")
2927 (defcustom org-use-fast-tag-selection 'auto
2928 "Non-nil means use fast tag selection scheme.
2929 This is a special interface to select and deselect tags with single keys.
2930 When nil, fast selection is never used.
2931 When the symbol `auto', fast selection is used if and only if selection
2932 characters for tags have been configured, either through the variable
2933 `org-tag-alist' or through a #+TAGS line in the buffer.
2934 When t, fast selection is always used and selection keys are assigned
2935 automatically if necessary."
2936 :group 'org-tags
2937 :type '(choice
2938 (const :tag "Always" t)
2939 (const :tag "Never" nil)
2940 (const :tag "When selection characters are configured" 'auto)))
2942 (defcustom org-fast-tag-selection-single-key nil
2943 "Non-nil means fast tag selection exits after first change.
2944 When nil, you have to press RET to exit it.
2945 During fast tag selection, you can toggle this flag with `C-c'.
2946 This variable can also have the value `expert'. In this case, the window
2947 displaying the tags menu is not even shown, until you press C-c again."
2948 :group 'org-tags
2949 :type '(choice
2950 (const :tag "No" nil)
2951 (const :tag "Yes" t)
2952 (const :tag "Expert" expert)))
2954 (defvar org-fast-tag-selection-include-todo nil
2955 "Non-nil means fast tags selection interface will also offer TODO states.
2956 This is an undocumented feature, you should not rely on it.")
2958 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2959 "The column to which tags should be indented in a headline.
2960 If this number is positive, it specifies the column. If it is negative,
2961 it means that the tags should be flushright to that column. For example,
2962 -80 works well for a normal 80 character screen.
2963 When 0, place tags directly after headline text, with only one space in
2964 between."
2965 :group 'org-tags
2966 :type 'integer)
2968 (defcustom org-auto-align-tags t
2969 "Non-nil keeps tags aligned when modifying headlines.
2970 Some operations (i.e. demoting) change the length of a headline and
2971 therefore shift the tags around. With this option turned on, after
2972 each such operation the tags are again aligned to `org-tags-column'."
2973 :group 'org-tags
2974 :type 'boolean)
2976 (defcustom org-use-tag-inheritance t
2977 "Non-nil means tags in levels apply also for sublevels.
2978 When nil, only the tags directly given in a specific line apply there.
2979 This may also be a list of tags that should be inherited, or a regexp that
2980 matches tags that should be inherited. Additional control is possible
2981 with the variable `org-tags-exclude-from-inheritance' which gives an
2982 explicit list of tags to be excluded from inheritance., even if the value of
2983 `org-use-tag-inheritance' would select it for inheritance.
2985 If this option is t, a match early-on in a tree can lead to a large
2986 number of matches in the subtree when constructing the agenda or creating
2987 a sparse tree. If you only want to see the first match in a tree during
2988 a search, check out the variable `org-tags-match-list-sublevels'."
2989 :group 'org-tags
2990 :type '(choice
2991 (const :tag "Not" nil)
2992 (const :tag "Always" t)
2993 (repeat :tag "Specific tags" (string :tag "Tag"))
2994 (regexp :tag "Tags matched by regexp")))
2996 (defcustom org-tags-exclude-from-inheritance nil
2997 "List of tags that should never be inherited.
2998 This is a way to exclude a few tags from inheritance. For way to do
2999 the opposite, to actively allow inheritance for selected tags,
3000 see the variable `org-use-tag-inheritance'."
3001 :group 'org-tags
3002 :type '(repeat (string :tag "Tag")))
3004 (defun org-tag-inherit-p (tag)
3005 "Check if TAG is one that should be inherited."
3006 (cond
3007 ((member tag org-tags-exclude-from-inheritance) nil)
3008 ((eq org-use-tag-inheritance t) t)
3009 ((not org-use-tag-inheritance) nil)
3010 ((stringp org-use-tag-inheritance)
3011 (string-match org-use-tag-inheritance tag))
3012 ((listp org-use-tag-inheritance)
3013 (member tag org-use-tag-inheritance))
3014 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3016 (defcustom org-tags-match-list-sublevels t
3017 "Non-nil means list also sublevels of headlines matching a search.
3018 This variable applies to tags/property searches, and also to stuck
3019 projects because this search is based on a tags match as well.
3021 When set to the symbol `indented', sublevels are indented with
3022 leading dots.
3024 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3025 the sublevels of a headline matching a tag search often also match
3026 the same search. Listing all of them can create very long lists.
3027 Setting this variable to nil causes subtrees of a match to be skipped.
3029 This variable is semi-obsolete and probably should always be true. It
3030 is better to limit inheritance to certain tags using the variables
3031 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3032 :group 'org-tags
3033 :type '(choice
3034 (const :tag "No, don't list them" nil)
3035 (const :tag "Yes, do list them" t)
3036 (const :tag "List them, indented with leading dots" indented)))
3038 (defcustom org-tags-sort-function nil
3039 "When set, tags are sorted using this function as a comparator."
3040 :group 'org-tags
3041 :type '(choice
3042 (const :tag "No sorting" nil)
3043 (const :tag "Alphabetical" string<)
3044 (const :tag "Reverse alphabetical" string>)
3045 (function :tag "Custom function" nil)))
3047 (defvar org-tags-history nil
3048 "History of minibuffer reads for tags.")
3049 (defvar org-last-tags-completion-table nil
3050 "The last used completion table for tags.")
3051 (defvar org-after-tags-change-hook nil
3052 "Hook that is run after the tags in a line have changed.")
3054 (defgroup org-properties nil
3055 "Options concerning properties in Org-mode."
3056 :tag "Org Properties"
3057 :group 'org)
3059 (defcustom org-property-format "%-10s %s"
3060 "How property key/value pairs should be formatted by `indent-line'.
3061 When `indent-line' hits a property definition, it will format the line
3062 according to this format, mainly to make sure that the values are
3063 lined-up with respect to each other."
3064 :group 'org-properties
3065 :type 'string)
3067 (defcustom org-properties-postprocess-alist nil
3068 "Alist of properties and functions to adjust inserted values.
3069 Elements of this alist must be of the form
3071 ([string] [function])
3073 where [string] must be a property name and [function] must be a
3074 lambda expression: this lambda expression must take one argument,
3075 the value to adjust, and return the new value as a string.
3077 For example, this element will allow the property \"Remaining\"
3078 to be updated wrt the relation between the \"Effort\" property
3079 and the clock summary:
3081 ((\"Remaining\" (lambda(value)
3082 (let ((clocksum (org-clock-sum-current-item))
3083 (effort (org-duration-string-to-minutes
3084 (org-entry-get (point) \"Effort\"))))
3085 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3086 :group 'org-properties
3087 :version "24.1"
3088 :type '(alist :key-type (string :tag "Property")
3089 :value-type (function :tag "Function")))
3091 (defcustom org-use-property-inheritance nil
3092 "Non-nil means properties apply also for sublevels.
3094 This setting is chiefly used during property searches. Turning it on can
3095 cause significant overhead when doing a search, which is why it is not
3096 on by default.
3098 When nil, only the properties directly given in the current entry count.
3099 When t, every property is inherited. The value may also be a list of
3100 properties that should have inheritance, or a regular expression matching
3101 properties that should be inherited.
3103 However, note that some special properties use inheritance under special
3104 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3105 and the properties ending in \"_ALL\" when they are used as descriptor
3106 for valid values of a property.
3108 Note for programmers:
3109 When querying an entry with `org-entry-get', you can control if inheritance
3110 should be used. By default, `org-entry-get' looks only at the local
3111 properties. You can request inheritance by setting the inherit argument
3112 to t (to force inheritance) or to `selective' (to respect the setting
3113 in this variable)."
3114 :group 'org-properties
3115 :type '(choice
3116 (const :tag "Not" nil)
3117 (const :tag "Always" t)
3118 (repeat :tag "Specific properties" (string :tag "Property"))
3119 (regexp :tag "Properties matched by regexp")))
3121 (defun org-property-inherit-p (property)
3122 "Check if PROPERTY is one that should be inherited."
3123 (cond
3124 ((eq org-use-property-inheritance t) t)
3125 ((not org-use-property-inheritance) nil)
3126 ((stringp org-use-property-inheritance)
3127 (string-match org-use-property-inheritance property))
3128 ((listp org-use-property-inheritance)
3129 (member property org-use-property-inheritance))
3130 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3132 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3133 "The default column format, if no other format has been defined.
3134 This variable can be set on the per-file basis by inserting a line
3136 #+COLUMNS: %25ITEM ....."
3137 :group 'org-properties
3138 :type 'string)
3140 (defcustom org-columns-ellipses ".."
3141 "The ellipses to be used when a field in column view is truncated.
3142 When this is the empty string, as many characters as possible are shown,
3143 but then there will be no visual indication that the field has been truncated.
3144 When this is a string of length N, the last N characters of a truncated
3145 field are replaced by this string. If the column is narrower than the
3146 ellipses string, only part of the ellipses string will be shown."
3147 :group 'org-properties
3148 :type 'string)
3150 (defcustom org-columns-modify-value-for-display-function nil
3151 "Function that modifies values for display in column view.
3152 For example, it can be used to cut out a certain part from a time stamp.
3153 The function must take 2 arguments:
3155 column-title The title of the column (*not* the property name)
3156 value The value that should be modified.
3158 The function should return the value that should be displayed,
3159 or nil if the normal value should be used."
3160 :group 'org-properties
3161 :type 'function)
3163 (defcustom org-effort-property "Effort"
3164 "The property that is being used to keep track of effort estimates.
3165 Effort estimates given in this property need to have the format H:MM."
3166 :group 'org-properties
3167 :group 'org-progress
3168 :type '(string :tag "Property"))
3170 (defconst org-global-properties-fixed
3171 '(("VISIBILITY_ALL" . "folded children content all")
3172 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3173 "List of property/value pairs that can be inherited by any entry.
3175 These are fixed values, for the preset properties. The user variable
3176 that can be used to add to this list is `org-global-properties'.
3178 The entries in this list are cons cells where the car is a property
3179 name and cdr is a string with the value. If the value represents
3180 multiple items like an \"_ALL\" property, separate the items by
3181 spaces.")
3183 (defcustom org-global-properties nil
3184 "List of property/value pairs that can be inherited by any entry.
3186 This list will be combined with the constant `org-global-properties-fixed'.
3188 The entries in this list are cons cells where the car is a property
3189 name and cdr is a string with the value.
3191 You can set buffer-local values for the same purpose in the variable
3192 `org-file-properties' this by adding lines like
3194 #+PROPERTY: NAME VALUE"
3195 :group 'org-properties
3196 :type '(repeat
3197 (cons (string :tag "Property")
3198 (string :tag "Value"))))
3200 (defvar org-file-properties nil
3201 "List of property/value pairs that can be inherited by any entry.
3202 Valid for the current buffer.
3203 This variable is populated from #+PROPERTY lines.")
3204 (make-variable-buffer-local 'org-file-properties)
3206 (defgroup org-agenda nil
3207 "Options concerning agenda views in Org-mode."
3208 :tag "Org Agenda"
3209 :group 'org)
3211 (defvar org-category nil
3212 "Variable used by org files to set a category for agenda display.
3213 Such files should use a file variable to set it, for example
3215 # -*- mode: org; org-category: \"ELisp\"
3217 or contain a special line
3219 #+CATEGORY: ELisp
3221 If the file does not specify a category, then file's base name
3222 is used instead.")
3223 (make-variable-buffer-local 'org-category)
3224 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3226 (defcustom org-agenda-files nil
3227 "The files to be used for agenda display.
3228 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3229 \\[org-remove-file]. You can also use customize to edit the list.
3231 If an entry is a directory, all files in that directory that are matched by
3232 `org-agenda-file-regexp' will be part of the file list.
3234 If the value of the variable is not a list but a single file name, then
3235 the list of agenda files is actually stored and maintained in that file, one
3236 agenda file per line. In this file paths can be given relative to
3237 `org-directory'. Tilde expansion and environment variable substitution
3238 are also made."
3239 :group 'org-agenda
3240 :type '(choice
3241 (repeat :tag "List of files and directories" file)
3242 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3244 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3245 "Regular expression to match files for `org-agenda-files'.
3246 If any element in the list in that variable contains a directory instead
3247 of a normal file, all files in that directory that are matched by this
3248 regular expression will be included."
3249 :group 'org-agenda
3250 :type 'regexp)
3252 (defcustom org-agenda-text-search-extra-files nil
3253 "List of extra files to be searched by text search commands.
3254 These files will be search in addition to the agenda files by the
3255 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3256 Note that these files will only be searched for text search commands,
3257 not for the other agenda views like todo lists, tag searches or the weekly
3258 agenda. This variable is intended to list notes and possibly archive files
3259 that should also be searched by these two commands.
3260 In fact, if the first element in the list is the symbol `agenda-archives',
3261 than all archive files of all agenda files will be added to the search
3262 scope."
3263 :group 'org-agenda
3264 :type '(set :greedy t
3265 (const :tag "Agenda Archives" agenda-archives)
3266 (repeat :inline t (file))))
3268 (if (fboundp 'defvaralias)
3269 (defvaralias 'org-agenda-multi-occur-extra-files
3270 'org-agenda-text-search-extra-files))
3272 (defcustom org-agenda-skip-unavailable-files nil
3273 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3274 A nil value means to remove them, after a query, from the list."
3275 :group 'org-agenda
3276 :type 'boolean)
3278 (defcustom org-calendar-to-agenda-key [?c]
3279 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3280 The command `org-calendar-goto-agenda' will be bound to this key. The
3281 default is the character `c' because then `c' can be used to switch back and
3282 forth between agenda and calendar."
3283 :group 'org-agenda
3284 :type 'sexp)
3286 (defcustom org-calendar-insert-diary-entry-key [?i]
3287 "The key to be installed in `calendar-mode-map' for adding diary entries.
3288 This option is irrelevant until `org-agenda-diary-file' has been configured
3289 to point to an Org-mode file. When that is the case, the command
3290 `org-agenda-diary-entry' will be bound to the key given here, by default
3291 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3292 if you want to continue doing this, you need to change this to a different
3293 key."
3294 :group 'org-agenda
3295 :type 'sexp)
3297 (defcustom org-agenda-diary-file 'diary-file
3298 "File to which to add new entries with the `i' key in agenda and calendar.
3299 When this is the symbol `diary-file', the functionality in the Emacs
3300 calendar will be used to add entries to the `diary-file'. But when this
3301 points to a file, `org-agenda-diary-entry' will be used instead."
3302 :group 'org-agenda
3303 :type '(choice
3304 (const :tag "The standard Emacs diary file" diary-file)
3305 (file :tag "Special Org file diary entries")))
3307 (eval-after-load "calendar"
3308 '(progn
3309 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3310 'org-calendar-goto-agenda)
3311 (add-hook 'calendar-mode-hook
3312 (lambda ()
3313 (unless (eq org-agenda-diary-file 'diary-file)
3314 (define-key calendar-mode-map
3315 org-calendar-insert-diary-entry-key
3316 'org-agenda-diary-entry))))))
3318 (defgroup org-latex nil
3319 "Options for embedding LaTeX code into Org-mode."
3320 :tag "Org LaTeX"
3321 :group 'org)
3323 (defcustom org-format-latex-options
3324 '(:foreground default :background default :scale 1.0
3325 :html-foreground "Black" :html-background "Transparent"
3326 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3327 "Options for creating images from LaTeX fragments.
3328 This is a property list with the following properties:
3329 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3330 `default' means use the foreground of the default face.
3331 :background the background color, or \"Transparent\".
3332 `default' means use the background of the default face.
3333 :scale a scaling factor for the size of the images, to get more pixels
3334 :html-foreground, :html-background, :html-scale
3335 the same numbers for HTML export.
3336 :matchers a list indicating which matchers should be used to
3337 find LaTeX fragments. Valid members of this list are:
3338 \"begin\" find environments
3339 \"$1\" find single characters surrounded by $.$
3340 \"$\" find math expressions surrounded by $...$
3341 \"$$\" find math expressions surrounded by $$....$$
3342 \"\\(\" find math expressions surrounded by \\(...\\)
3343 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3344 :group 'org-latex
3345 :type 'plist)
3347 (defcustom org-format-latex-signal-error t
3348 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3349 When nil, just push out a message."
3350 :group 'org-latex
3351 :version "24.1"
3352 :type 'boolean)
3354 (defcustom org-latex-to-mathml-jar-file nil
3355 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3356 Use this to specify additional executable file say a jar file.
3358 When using MathToWeb as the converter, specify the full-path to
3359 your mathtoweb.jar file."
3360 :group 'org-latex
3361 :version "24.1"
3362 :type '(choice
3363 (const :tag "None" nil)
3364 (file :tag "JAR file" :must-match t)))
3366 (defcustom org-latex-to-mathml-convert-command nil
3367 "Command to convert LaTeX fragments to MathML.
3368 Replace format-specifiers in the command as noted below and use
3369 `shell-command' to convert LaTeX to MathML.
3370 %j: Executable file in fully expanded form as specified by
3371 `org-latex-to-mathml-jar-file'.
3372 %I: Input LaTeX file in fully expanded form
3373 %o: Output MathML file
3374 This command is used by `org-create-math-formula'.
3376 When using MathToWeb as the converter, set this to
3377 \"java -jar %j -unicode -force -df %o %I\"."
3378 :group 'org-latex
3379 :version "24.1"
3380 :type '(choice
3381 (const :tag "None" nil)
3382 (string :tag "\nShell command")))
3384 (defcustom org-latex-create-formula-image-program 'dvipng
3385 "Program to convert LaTeX fragments with.
3387 dvipng Process the LaTeX fragments to dvi file, then convert
3388 dvi files to png files using dvipng.
3389 This will also include processing of non-math environments.
3390 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3391 to convert pdf files to png files"
3392 :group 'org-latex
3393 :version "24.1"
3394 :type '(choice
3395 (const :tag "dvipng" dvipng)
3396 (const :tag "imagemagick" imagemagick)))
3398 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3399 "Path to store latex preview images. A relative path here creates many
3400 directories relative to the processed org files paths. An absolute path
3401 puts all preview images at the same place."
3402 :group 'org-latex
3403 :version "24.3"
3404 :type 'string)
3406 (defun org-format-latex-mathml-available-p ()
3407 "Return t if `org-latex-to-mathml-convert-command' is usable."
3408 (save-match-data
3409 (when (and (boundp 'org-latex-to-mathml-convert-command)
3410 org-latex-to-mathml-convert-command)
3411 (let ((executable (car (split-string
3412 org-latex-to-mathml-convert-command))))
3413 (when (executable-find executable)
3414 (if (string-match
3415 "%j" org-latex-to-mathml-convert-command)
3416 (file-readable-p org-latex-to-mathml-jar-file)
3417 t))))))
3419 (defcustom org-format-latex-header "\\documentclass{article}
3420 \\usepackage[usenames]{color}
3421 \\usepackage{amsmath}
3422 \\usepackage[mathscr]{eucal}
3423 \\pagestyle{empty} % do not remove
3424 \[PACKAGES]
3425 \[DEFAULT-PACKAGES]
3426 % The settings below are copied from fullpage.sty
3427 \\setlength{\\textwidth}{\\paperwidth}
3428 \\addtolength{\\textwidth}{-3cm}
3429 \\setlength{\\oddsidemargin}{1.5cm}
3430 \\addtolength{\\oddsidemargin}{-2.54cm}
3431 \\setlength{\\evensidemargin}{\\oddsidemargin}
3432 \\setlength{\\textheight}{\\paperheight}
3433 \\addtolength{\\textheight}{-\\headheight}
3434 \\addtolength{\\textheight}{-\\headsep}
3435 \\addtolength{\\textheight}{-\\footskip}
3436 \\addtolength{\\textheight}{-3cm}
3437 \\setlength{\\topmargin}{1.5cm}
3438 \\addtolength{\\topmargin}{-2.54cm}"
3439 "The document header used for processing LaTeX fragments.
3440 It is imperative that this header make sure that no page number
3441 appears on the page. The package defined in the variables
3442 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3443 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3444 will be appended."
3445 :group 'org-latex
3446 :type 'string)
3448 (defvar org-format-latex-header-extra nil)
3450 (defun org-set-packages-alist (var val)
3451 "Set the packages alist and make sure it has 3 elements per entry."
3452 (set var (mapcar (lambda (x)
3453 (if (and (consp x) (= (length x) 2))
3454 (list (car x) (nth 1 x) t)
3456 val)))
3458 (defun org-get-packages-alist (var)
3460 "Get the packages alist and make sure it has 3 elements per entry."
3461 (mapcar (lambda (x)
3462 (if (and (consp x) (= (length x) 2))
3463 (list (car x) (nth 1 x) t)
3465 (default-value var)))
3467 ;; The following variables are defined here because is it also used
3468 ;; when formatting latex fragments. Originally it was part of the
3469 ;; LaTeX exporter, which is why the name includes "export".
3470 (defcustom org-export-latex-default-packages-alist
3471 '(("AUTO" "inputenc" t)
3472 ("T1" "fontenc" t)
3473 ("" "fixltx2e" nil)
3474 ("" "graphicx" t)
3475 ("" "longtable" nil)
3476 ("" "float" nil)
3477 ("" "wrapfig" nil)
3478 ("" "soul" t)
3479 ("" "textcomp" t)
3480 ("" "marvosym" t)
3481 ("" "wasysym" t)
3482 ("" "latexsym" t)
3483 ("" "amssymb" t)
3484 ("" "hyperref" nil)
3485 "\\tolerance=1000"
3487 "Alist of default packages to be inserted in the header.
3488 Change this only if one of the packages here causes an incompatibility
3489 with another package you are using.
3490 The packages in this list are needed by one part or another of Org-mode
3491 to function properly.
3493 - inputenc, fontenc: for basic font and character selection
3494 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3495 for interpreting the entities in `org-entities'. You can skip some of these
3496 packages if you don't use any of the symbols in it.
3497 - graphicx: for including images
3498 - float, wrapfig: for figure placement
3499 - longtable: for long tables
3500 - hyperref: for cross references
3502 Therefore you should not modify this variable unless you know what you
3503 are doing. The one reason to change it anyway is that you might be loading
3504 some other package that conflicts with one of the default packages.
3505 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3506 If SNIPPET-FLAG is t, the package also needs to be included when
3507 compiling LaTeX snippets into images for inclusion into HTML."
3508 :group 'org-export-latex
3509 :set 'org-set-packages-alist
3510 :get 'org-get-packages-alist
3511 :version "24.1"
3512 :type '(repeat
3513 (choice
3514 (list :tag "options/package pair"
3515 (string :tag "options")
3516 (string :tag "package")
3517 (boolean :tag "Snippet"))
3518 (string :tag "A line of LaTeX"))))
3520 (defcustom org-export-latex-packages-alist nil
3521 "Alist of packages to be inserted in every LaTeX header.
3522 These will be inserted after `org-export-latex-default-packages-alist'.
3523 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3524 SNIPPET-FLAG, when t, indicates that this package is also needed when
3525 turning LaTeX snippets into images for inclusion into HTML.
3526 Make sure that you only list packages here which:
3527 - you want in every file
3528 - do not conflict with the default packages in
3529 `org-export-latex-default-packages-alist'
3530 - do not conflict with the setup in `org-format-latex-header'."
3531 :group 'org-export-latex
3532 :set 'org-set-packages-alist
3533 :get 'org-get-packages-alist
3534 :type '(repeat
3535 (choice
3536 (list :tag "options/package pair"
3537 (string :tag "options")
3538 (string :tag "package")
3539 (boolean :tag "Snippet"))
3540 (string :tag "A line of LaTeX"))))
3543 (defgroup org-appearance nil
3544 "Settings for Org-mode appearance."
3545 :tag "Org Appearance"
3546 :group 'org)
3548 (defcustom org-level-color-stars-only nil
3549 "Non-nil means fontify only the stars in each headline.
3550 When nil, the entire headline is fontified.
3551 Changing it requires restart of `font-lock-mode' to become effective
3552 also in regions already fontified."
3553 :group 'org-appearance
3554 :type 'boolean)
3556 (defcustom org-hide-leading-stars nil
3557 "Non-nil means hide the first N-1 stars in a headline.
3558 This works by using the face `org-hide' for these stars. This
3559 face is white for a light background, and black for a dark
3560 background. You may have to customize the face `org-hide' to
3561 make this work.
3562 Changing it requires restart of `font-lock-mode' to become effective
3563 also in regions already fontified.
3564 You may also set this on a per-file basis by adding one of the following
3565 lines to the buffer:
3567 #+STARTUP: hidestars
3568 #+STARTUP: showstars"
3569 :group 'org-appearance
3570 :type 'boolean)
3572 (defcustom org-hidden-keywords nil
3573 "List of symbols corresponding to keywords to be hidden the org buffer.
3574 For example, a value '(title) for this list will make the document's title
3575 appear in the buffer without the initial #+TITLE: keyword."
3576 :group 'org-appearance
3577 :version "24.1"
3578 :type '(set (const :tag "#+AUTHOR" author)
3579 (const :tag "#+DATE" date)
3580 (const :tag "#+EMAIL" email)
3581 (const :tag "#+TITLE" title)))
3583 (defcustom org-custom-properties nil
3584 "List of properties (as strings) with a special meaning.
3585 The default use of these custom properties is to let the user
3586 hide them with `org-toggle-custom-properties-visibility'."
3587 :group 'org-properties
3588 :group 'org-appearance
3589 :version "24.3"
3590 :type '(repeat (string :tag "Property Name")))
3592 (defcustom org-fontify-done-headline nil
3593 "Non-nil means change the face of a headline if it is marked DONE.
3594 Normally, only the TODO/DONE keyword indicates the state of a headline.
3595 When this is non-nil, the headline after the keyword is set to the
3596 `org-headline-done' as an additional indication."
3597 :group 'org-appearance
3598 :type 'boolean)
3600 (defcustom org-fontify-emphasized-text t
3601 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3602 Changing this variable requires a restart of Emacs to take effect."
3603 :group 'org-appearance
3604 :type 'boolean)
3606 (defcustom org-fontify-whole-heading-line nil
3607 "Non-nil means fontify the whole line for headings.
3608 This is useful when setting a background color for the
3609 org-level-* faces."
3610 :group 'org-appearance
3611 :type 'boolean)
3613 (defcustom org-highlight-latex-fragments-and-specials nil
3614 "Non-nil means fontify what is treated specially by the exporters."
3615 :group 'org-appearance
3616 :type 'boolean)
3618 (defcustom org-hide-emphasis-markers nil
3619 "Non-nil mean font-lock should hide the emphasis marker characters."
3620 :group 'org-appearance
3621 :type 'boolean)
3623 (defcustom org-pretty-entities nil
3624 "Non-nil means show entities as UTF8 characters.
3625 When nil, the \\name form remains in the buffer."
3626 :group 'org-appearance
3627 :version "24.1"
3628 :type 'boolean)
3630 (defcustom org-pretty-entities-include-sub-superscripts t
3631 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3632 :group 'org-appearance
3633 :version "24.1"
3634 :type 'boolean)
3636 (defvar org-emph-re nil
3637 "Regular expression for matching emphasis.
3638 After a match, the match groups contain these elements:
3639 0 The match of the full regular expression, including the characters
3640 before and after the proper match
3641 1 The character before the proper match, or empty at beginning of line
3642 2 The proper match, including the leading and trailing markers
3643 3 The leading marker like * or /, indicating the type of highlighting
3644 4 The text between the emphasis markers, not including the markers
3645 5 The character after the match, empty at the end of a line")
3646 (defvar org-verbatim-re nil
3647 "Regular expression for matching verbatim text.")
3648 (defvar org-emphasis-regexp-components) ; defined just below
3649 (defvar org-emphasis-alist) ; defined just below
3650 (defun org-set-emph-re (var val)
3651 "Set variable and compute the emphasis regular expression."
3652 (set var val)
3653 (when (and (boundp 'org-emphasis-alist)
3654 (boundp 'org-emphasis-regexp-components)
3655 org-emphasis-alist org-emphasis-regexp-components)
3656 (let* ((e org-emphasis-regexp-components)
3657 (pre (car e))
3658 (post (nth 1 e))
3659 (border (nth 2 e))
3660 (body (nth 3 e))
3661 (nl (nth 4 e))
3662 (body1 (concat body "*?"))
3663 (markers (mapconcat 'car org-emphasis-alist ""))
3664 (vmarkers (mapconcat
3665 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3666 org-emphasis-alist "")))
3667 ;; make sure special characters appear at the right position in the class
3668 (if (string-match "\\^" markers)
3669 (setq markers (concat (replace-match "" t t markers) "^")))
3670 (if (string-match "-" markers)
3671 (setq markers (concat (replace-match "" t t markers) "-")))
3672 (if (string-match "\\^" vmarkers)
3673 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3674 (if (string-match "-" vmarkers)
3675 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3676 (if (> nl 0)
3677 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3678 (int-to-string nl) "\\}")))
3679 ;; Make the regexp
3680 (setq org-emph-re
3681 (concat "\\([" pre "]\\|^\\)"
3682 "\\("
3683 "\\([" markers "]\\)"
3684 "\\("
3685 "[^" border "]\\|"
3686 "[^" border "]"
3687 body1
3688 "[^" border "]"
3689 "\\)"
3690 "\\3\\)"
3691 "\\([" post "]\\|$\\)"))
3692 (setq org-verbatim-re
3693 (concat "\\([" pre "]\\|^\\)"
3694 "\\("
3695 "\\([" vmarkers "]\\)"
3696 "\\("
3697 "[^" border "]\\|"
3698 "[^" border "]"
3699 body1
3700 "[^" border "]"
3701 "\\)"
3702 "\\3\\)"
3703 "\\([" post "]\\|$\\)")))))
3705 (defcustom org-emphasis-regexp-components
3706 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3707 "Components used to build the regular expression for emphasis.
3708 This is a list with five entries. Terminology: In an emphasis string
3709 like \" *strong word* \", we call the initial space PREMATCH, the final
3710 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3711 and \"trong wor\" is the body. The different components in this variable
3712 specify what is allowed/forbidden in each part:
3714 pre Chars allowed as prematch. Beginning of line will be allowed too.
3715 post Chars allowed as postmatch. End of line will be allowed too.
3716 border The chars *forbidden* as border characters.
3717 body-regexp A regexp like \".\" to match a body character. Don't use
3718 non-shy groups here, and don't allow newline here.
3719 newline The maximum number of newlines allowed in an emphasis exp.
3721 Use customize to modify this, or restart Emacs after changing it."
3722 :group 'org-appearance
3723 :set 'org-set-emph-re
3724 :type '(list
3725 (sexp :tag "Allowed chars in pre ")
3726 (sexp :tag "Allowed chars in post ")
3727 (sexp :tag "Forbidden chars in border ")
3728 (sexp :tag "Regexp for body ")
3729 (integer :tag "number of newlines allowed")
3730 (option (boolean :tag "Please ignore this button"))))
3732 (defcustom org-emphasis-alist
3733 `(("*" bold "<b>" "</b>")
3734 ("/" italic "<i>" "</i>")
3735 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3736 ("=" org-code "<code>" "</code>" verbatim)
3737 ("~" org-verbatim "<code>" "</code>" verbatim)
3738 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3739 "<del>" "</del>")
3741 "Special syntax for emphasized text.
3742 Text starting and ending with a special character will be emphasized, for
3743 example *bold*, _underlined_ and /italic/. This variable sets the marker
3744 characters, the face to be used by font-lock for highlighting in Org-mode
3745 Emacs buffers, and the HTML tags to be used for this.
3746 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3747 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3748 Use customize to modify this, or restart Emacs after changing it."
3749 :group 'org-appearance
3750 :set 'org-set-emph-re
3751 :type '(repeat
3752 (list
3753 (string :tag "Marker character")
3754 (choice
3755 (face :tag "Font-lock-face")
3756 (plist :tag "Face property list"))
3757 (string :tag "HTML start tag")
3758 (string :tag "HTML end tag")
3759 (option (const verbatim)))))
3761 (defvar org-protecting-blocks
3762 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3763 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3764 This is needed for font-lock setup.")
3766 ;;; Miscellaneous options
3768 (defgroup org-completion nil
3769 "Completion in Org-mode."
3770 :tag "Org Completion"
3771 :group 'org)
3773 (defcustom org-completion-use-ido nil
3774 "Non-nil means use ido completion wherever possible.
3775 Note that `ido-mode' must be active for this variable to be relevant.
3776 If you decide to turn this variable on, you might well want to turn off
3777 `org-outline-path-complete-in-steps'.
3778 See also `org-completion-use-iswitchb'."
3779 :group 'org-completion
3780 :type 'boolean)
3782 (defcustom org-completion-use-iswitchb nil
3783 "Non-nil means use iswitchb completion wherever possible.
3784 Note that `iswitchb-mode' must be active for this variable to be relevant.
3785 If you decide to turn this variable on, you might well want to turn off
3786 `org-outline-path-complete-in-steps'.
3787 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3788 :group 'org-completion
3789 :type 'boolean)
3791 (defcustom org-completion-fallback-command 'hippie-expand
3792 "The expansion command called by \\[pcomplete] in normal context.
3793 Normal means, no org-mode-specific context."
3794 :group 'org-completion
3795 :type 'function)
3797 ;;; Functions and variables from their packages
3798 ;; Declared here to avoid compiler warnings
3800 ;; XEmacs only
3801 (defvar outline-mode-menu-heading)
3802 (defvar outline-mode-menu-show)
3803 (defvar outline-mode-menu-hide)
3804 (defvar zmacs-regions) ; XEmacs regions
3806 ;; Emacs only
3807 (defvar mark-active)
3809 ;; Various packages
3810 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3811 (declare-function calendar-forward-day "cal-move" (arg))
3812 (declare-function calendar-goto-date "cal-move" (date))
3813 (declare-function calendar-goto-today "cal-move" ())
3814 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3815 (defvar calc-embedded-close-formula)
3816 (defvar calc-embedded-open-formula)
3817 (declare-function cdlatex-tab "ext:cdlatex" ())
3818 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3819 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3820 (defvar font-lock-unfontify-region-function)
3821 (declare-function iswitchb-read-buffer "iswitchb"
3822 (prompt &optional default require-match start matches-set))
3823 (defvar iswitchb-temp-buflist)
3824 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3825 (defvar org-agenda-tags-todo-honor-ignore-options)
3826 (declare-function org-agenda-skip "org-agenda" ())
3827 (declare-function
3828 org-agenda-format-item "org-agenda"
3829 (extra txt &optional category tags dotime noprefix remove-re habitp))
3830 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3831 (declare-function org-agenda-change-all-lines "org-agenda"
3832 (newhead hdmarker &optional fixface just-this))
3833 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3834 (declare-function org-agenda-maybe-redo "org-agenda" ())
3835 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3836 (beg end))
3837 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3838 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3839 "org-agenda" (&optional end))
3840 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3841 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3842 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3843 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3844 (declare-function org-indent-mode "org-indent" (&optional arg))
3845 (declare-function parse-time-string "parse-time" (string))
3846 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3847 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3848 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3849 (defvar remember-data-file)
3850 (defvar texmathp-why)
3851 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3852 (declare-function table--at-cell-p "table" (position &optional object at-column))
3854 (defvar w3m-current-url)
3855 (defvar w3m-current-title)
3857 (defvar org-latex-regexps)
3859 ;;; Autoload and prepare some org modules
3861 ;; Some table stuff that needs to be defined here, because it is used
3862 ;; by the functions setting up org-mode or checking for table context.
3864 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3865 "Detect an org-type or table-type table.")
3866 (defconst org-table-line-regexp "^[ \t]*|"
3867 "Detect an org-type table line.")
3868 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3869 "Detect an org-type table line.")
3870 (defconst org-table-hline-regexp "^[ \t]*|-"
3871 "Detect an org-type table hline.")
3872 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3873 "Detect a table-type table hline.")
3874 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3875 "Detect the first line outside a table when searching from within it.
3876 This works for both table types.")
3878 ;; Autoload the functions in org-table.el that are needed by functions here.
3880 (eval-and-compile
3881 (org-autoload "org-table"
3882 '(org-table-begin org-table-blank-field org-table-end)))
3884 ;;;###autoload
3885 (defun turn-on-orgtbl ()
3886 "Unconditionally turn on `orgtbl-mode'."
3887 (require 'org-table)
3888 (orgtbl-mode 1))
3890 (defun org-at-table-p (&optional table-type)
3891 "Return t if the cursor is inside an org-type table.
3892 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3893 (if org-enable-table-editor
3894 (save-excursion
3895 (beginning-of-line 1)
3896 (looking-at (if table-type org-table-any-line-regexp
3897 org-table-line-regexp)))
3898 nil))
3899 (defsubst org-table-p () (org-at-table-p))
3901 (defun org-at-table.el-p ()
3902 "Return t if and only if we are at a table.el table."
3903 (and (org-at-table-p 'any)
3904 (save-excursion
3905 (goto-char (org-table-begin 'any))
3906 (looking-at org-table1-hline-regexp))))
3907 (defun org-table-recognize-table.el ()
3908 "If there is a table.el table nearby, recognize it and move into it."
3909 (if org-table-tab-recognizes-table.el
3910 (if (org-at-table.el-p)
3911 (progn
3912 (beginning-of-line 1)
3913 (if (looking-at org-table-dataline-regexp)
3915 (if (looking-at org-table1-hline-regexp)
3916 (progn
3917 (beginning-of-line 2)
3918 (if (looking-at org-table-any-border-regexp)
3919 (beginning-of-line -1)))))
3920 (if (re-search-forward "|" (org-table-end t) t)
3921 (progn
3922 (require 'table)
3923 (if (table--at-cell-p (point))
3925 (message "recognizing table.el table...")
3926 (table-recognize-table)
3927 (message "recognizing table.el table...done")))
3928 (error "This should not happen"))
3930 nil)
3931 nil))
3933 (defun org-at-table-hline-p ()
3934 "Return t if the cursor is inside a hline in a table."
3935 (if org-enable-table-editor
3936 (save-excursion
3937 (beginning-of-line 1)
3938 (looking-at org-table-hline-regexp))
3939 nil))
3941 (defvar org-table-clean-did-remove-column nil)
3943 (defun org-table-map-tables (function &optional quietly)
3944 "Apply FUNCTION to the start of all tables in the buffer."
3945 (save-excursion
3946 (save-restriction
3947 (widen)
3948 (goto-char (point-min))
3949 (while (re-search-forward org-table-any-line-regexp nil t)
3950 (unless quietly
3951 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3952 (beginning-of-line 1)
3953 (when (and (looking-at org-table-line-regexp)
3954 ;; Exclude tables in src/example/verbatim/clocktable blocks
3955 (not (org-in-block-p '("src" "example"))))
3956 (save-excursion (funcall function))
3957 (or (looking-at org-table-line-regexp)
3958 (forward-char 1)))
3959 (re-search-forward org-table-any-border-regexp nil 1))))
3960 (unless quietly (message "Mapping tables: done")))
3962 ;; Declare and autoload functions from org-exp.el & Co
3964 (declare-function org-default-export-plist "org-exp")
3965 (declare-function org-infile-export-plist "org-exp")
3966 (declare-function org-get-current-options "org-exp")
3968 ;; Declare and autoload functions from org-agenda.el
3970 (eval-and-compile
3971 (org-autoload "org-agenda"
3972 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3974 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
3975 (declare-function org-clock-update-mode-line "org-clock" ())
3976 (declare-function org-resolve-clocks "org-clock"
3977 (&optional also-non-dangling-p prompt last-valid))
3978 (defvar org-clock-start-time)
3979 (defvar org-clock-marker (make-marker)
3980 "Marker recording the last clock-in.")
3981 (defvar org-clock-hd-marker (make-marker)
3982 "Marker recording the last clock-in, but the headline position.")
3983 (defvar org-clock-heading ""
3984 "The heading of the current clock entry.")
3985 (defun org-clock-is-active ()
3986 "Return non-nil if clock is currently running.
3987 The return value is actually the clock marker."
3988 (marker-buffer org-clock-marker))
3990 (eval-and-compile
3991 (org-autoload "org-clock" '(org-clock-remove-overlays
3992 org-clock-update-time-maybe
3993 org-clocktable-shift)))
3995 (defun org-check-running-clock ()
3996 "Check if the current buffer contains the running clock.
3997 If yes, offer to stop it and to save the buffer with the changes."
3998 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3999 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4000 (buffer-name))))
4001 (org-clock-out)
4002 (when (y-or-n-p "Save changed buffer?")
4003 (save-buffer))))
4005 (defun org-clocktable-try-shift (dir n)
4006 "Check if this line starts a clock table, if yes, shift the time block."
4007 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4008 (org-clocktable-shift dir n)))
4010 ;;;###autoload
4011 (defun org-clock-persistence-insinuate ()
4012 "Set up hooks for clock persistence."
4013 (require 'org-clock)
4014 (add-hook 'org-mode-hook 'org-clock-load)
4015 (add-hook 'kill-emacs-hook 'org-clock-save))
4017 ;; Define the variable already here, to make sure we have it.
4018 (defvar org-indent-mode nil
4019 "Non-nil if Org-Indent mode is enabled.
4020 Use the command `org-indent-mode' to change this variable.")
4022 ;; Autoload archiving code
4023 ;; The stuff that is needed for cycling and tags has to be defined here.
4025 (defgroup org-archive nil
4026 "Options concerning archiving in Org-mode."
4027 :tag "Org Archive"
4028 :group 'org-structure)
4030 (defcustom org-archive-location "%s_archive::"
4031 "The location where subtrees should be archived.
4033 The value of this variable is a string, consisting of two parts,
4034 separated by a double-colon. The first part is a filename and
4035 the second part is a headline.
4037 When the filename is omitted, archiving happens in the same file.
4038 %s in the filename will be replaced by the current file
4039 name (without the directory part). Archiving to a different file
4040 is useful to keep archived entries from contributing to the
4041 Org-mode Agenda.
4043 The archived entries will be filed as subtrees of the specified
4044 headline. When the headline is omitted, the subtrees are simply
4045 filed away at the end of the file, as top-level entries. Also in
4046 the heading you can use %s to represent the file name, this can be
4047 useful when using the same archive for a number of different files.
4049 Here are a few examples:
4050 \"%s_archive::\"
4051 If the current file is Projects.org, archive in file
4052 Projects.org_archive, as top-level trees. This is the default.
4054 \"::* Archived Tasks\"
4055 Archive in the current file, under the top-level headline
4056 \"* Archived Tasks\".
4058 \"~/org/archive.org::\"
4059 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4061 \"~/org/archive.org::* From %s\"
4062 Archive in file ~/org/archive.org (absolute path), under headlines
4063 \"From FILENAME\" where file name is the current file name.
4065 \"~/org/datetree.org::datetree/* Finished Tasks\"
4066 The \"datetree/\" string is special, signifying to archive
4067 items to the datetree. Items are placed in either the CLOSED
4068 date of the item, or the current date if there is no CLOSED date.
4069 The heading will be a subentry to the current date. There doesn't
4070 need to be a heading, but there always needs to be a slash after
4071 datetree. For example, to store archived items directly in the
4072 datetree, use \"~/org/datetree.org::datetree/\".
4074 \"basement::** Finished Tasks\"
4075 Archive in file ./basement (relative path), as level 3 trees
4076 below the level 2 heading \"** Finished Tasks\".
4078 You may set this option on a per-file basis by adding to the buffer a
4079 line like
4081 #+ARCHIVE: basement::** Finished Tasks
4083 You may also define it locally for a subtree by setting an ARCHIVE property
4084 in the entry. If such a property is found in an entry, or anywhere up
4085 the hierarchy, it will be used."
4086 :group 'org-archive
4087 :type 'string)
4089 (defcustom org-archive-tag "ARCHIVE"
4090 "The tag that marks a subtree as archived.
4091 An archived subtree does not open during visibility cycling, and does
4092 not contribute to the agenda listings.
4093 After changing this, font-lock must be restarted in the relevant buffers to
4094 get the proper fontification."
4095 :group 'org-archive
4096 :group 'org-keywords
4097 :type 'string)
4099 (defcustom org-agenda-skip-archived-trees t
4100 "Non-nil means the agenda will skip any items located in archived trees.
4101 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4102 variable is no longer recommended, you should leave it at the value t.
4103 Instead, use the key `v' to cycle the archives-mode in the agenda."
4104 :group 'org-archive
4105 :group 'org-agenda-skip
4106 :type 'boolean)
4108 (defcustom org-columns-skip-archived-trees t
4109 "Non-nil means ignore archived trees when creating column view."
4110 :group 'org-archive
4111 :group 'org-properties
4112 :type 'boolean)
4114 (defcustom org-cycle-open-archived-trees nil
4115 "Non-nil means `org-cycle' will open archived trees.
4116 An archived tree is a tree marked with the tag ARCHIVE.
4117 When nil, archived trees will stay folded. You can still open them with
4118 normal outline commands like `show-all', but not with the cycling commands."
4119 :group 'org-archive
4120 :group 'org-cycle
4121 :type 'boolean)
4123 (defcustom org-sparse-tree-open-archived-trees nil
4124 "Non-nil means sparse tree construction shows matches in archived trees.
4125 When nil, matches in these trees are highlighted, but the trees are kept in
4126 collapsed state."
4127 :group 'org-archive
4128 :group 'org-sparse-trees
4129 :type 'boolean)
4131 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4132 "The default date type when building a sparse tree.
4133 When this is nil, a date is a scheduled or a deadline timestamp.
4134 Otherwise, these types are allowed:
4136 all: all timestamps
4137 active: only active timestamps (<...>)
4138 inactive: only inactive timestamps (<...)
4139 scheduled: only scheduled timestamps
4140 deadline: only deadline timestamps"
4141 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4142 (const :tag "All timestamps" all)
4143 (const :tag "Only active timestamps" active)
4144 (const :tag "Only inactive timestamps" inactive)
4145 (const :tag "Only scheduled timestamps" scheduled)
4146 (const :tag "Only deadline timestamps" deadline))
4147 :version "24.3"
4148 :group 'org-sparse-trees)
4150 (defun org-cycle-hide-archived-subtrees (state)
4151 "Re-hide all archived subtrees after a visibility state change."
4152 (when (and (not org-cycle-open-archived-trees)
4153 (not (memq state '(overview folded))))
4154 (save-excursion
4155 (let* ((globalp (memq state '(contents all)))
4156 (beg (if globalp (point-min) (point)))
4157 (end (if globalp (point-max) (org-end-of-subtree t))))
4158 (org-hide-archived-subtrees beg end)
4159 (goto-char beg)
4160 (if (looking-at (concat ".*:" org-archive-tag ":"))
4161 (message "%s" (substitute-command-keys
4162 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4164 (defun org-force-cycle-archived ()
4165 "Cycle subtree even if it is archived."
4166 (interactive)
4167 (setq this-command 'org-cycle)
4168 (let ((org-cycle-open-archived-trees t))
4169 (call-interactively 'org-cycle)))
4171 (defun org-hide-archived-subtrees (beg end)
4172 "Re-hide all archived subtrees after a visibility state change."
4173 (save-excursion
4174 (let* ((re (concat ":" org-archive-tag ":")))
4175 (goto-char beg)
4176 (while (re-search-forward re end t)
4177 (when (org-at-heading-p)
4178 (org-flag-subtree t)
4179 (org-end-of-subtree t))))))
4181 (declare-function outline-end-of-heading "outline" ())
4182 (declare-function outline-flag-region "outline" (from to flag))
4183 (defun org-flag-subtree (flag)
4184 (save-excursion
4185 (org-back-to-heading t)
4186 (outline-end-of-heading)
4187 (outline-flag-region (point)
4188 (progn (org-end-of-subtree t) (point))
4189 flag)))
4191 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4193 (eval-and-compile
4194 (org-autoload "org-archive"
4195 '(org-add-archive-files)))
4197 ;; Autoload Column View Code
4199 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4200 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4201 (declare-function org-columns-compute "org-colview" (property))
4203 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4204 '(org-columns-number-to-string
4205 org-columns-get-format-and-top-level
4206 org-columns-compute
4207 org-columns-remove-overlays))
4209 ;; Autoload ID code
4211 (declare-function org-id-store-link "org-id")
4212 (declare-function org-id-locations-load "org-id")
4213 (declare-function org-id-locations-save "org-id")
4214 (defvar org-id-track-globally)
4215 (org-autoload "org-id"
4216 '(org-id-new
4217 org-id-copy
4218 org-id-get-with-outline-path-completion
4219 org-id-get-with-outline-drilling))
4221 ;;; Variables for pre-computed regular expressions, all buffer local
4223 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4224 "Matches first line of a hidden block.")
4225 (make-variable-buffer-local 'org-drawer-regexp)
4226 (defvar org-todo-regexp nil
4227 "Matches any of the TODO state keywords.")
4228 (make-variable-buffer-local 'org-todo-regexp)
4229 (defvar org-not-done-regexp nil
4230 "Matches any of the TODO state keywords except the last one.")
4231 (make-variable-buffer-local 'org-not-done-regexp)
4232 (defvar org-not-done-heading-regexp nil
4233 "Matches a TODO headline that is not done.")
4234 (make-variable-buffer-local 'org-not-done-regexp)
4235 (defvar org-todo-line-regexp nil
4236 "Matches a headline and puts TODO state into group 2 if present.")
4237 (make-variable-buffer-local 'org-todo-line-regexp)
4238 (defvar org-complex-heading-regexp nil
4239 "Matches a headline and puts everything into groups:
4240 group 1: the stars
4241 group 2: The todo keyword, maybe
4242 group 3: Priority cookie
4243 group 4: True headline
4244 group 5: Tags")
4245 (make-variable-buffer-local 'org-complex-heading-regexp)
4246 (defvar org-complex-heading-regexp-format nil
4247 "Printf format to make regexp to match an exact headline.
4248 This regexp will match the headline of any node which has the
4249 exact headline text that is put into the format, but may have any
4250 TODO state, priority and tags.")
4251 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4252 (defvar org-todo-line-tags-regexp nil
4253 "Matches a headline and puts TODO state into group 2 if present.
4254 Also put tags into group 4 if tags are present.")
4255 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4256 (defvar org-ds-keyword-length 12
4257 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4258 (make-variable-buffer-local 'org-ds-keyword-length)
4259 (defvar org-deadline-regexp nil
4260 "Matches the DEADLINE keyword.")
4261 (make-variable-buffer-local 'org-deadline-regexp)
4262 (defvar org-deadline-time-regexp nil
4263 "Matches the DEADLINE keyword together with a time stamp.")
4264 (make-variable-buffer-local 'org-deadline-time-regexp)
4265 (defvar org-deadline-line-regexp nil
4266 "Matches the DEADLINE keyword and the rest of the line.")
4267 (make-variable-buffer-local 'org-deadline-line-regexp)
4268 (defvar org-scheduled-regexp nil
4269 "Matches the SCHEDULED keyword.")
4270 (make-variable-buffer-local 'org-scheduled-regexp)
4271 (defvar org-scheduled-time-regexp nil
4272 "Matches the SCHEDULED keyword together with a time stamp.")
4273 (make-variable-buffer-local 'org-scheduled-time-regexp)
4274 (defvar org-closed-time-regexp nil
4275 "Matches the CLOSED keyword together with a time stamp.")
4276 (make-variable-buffer-local 'org-closed-time-regexp)
4278 (defvar org-keyword-time-regexp nil
4279 "Matches any of the 4 keywords, together with the time stamp.")
4280 (make-variable-buffer-local 'org-keyword-time-regexp)
4281 (defvar org-keyword-time-not-clock-regexp nil
4282 "Matches any of the 3 keywords, together with the time stamp.")
4283 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4284 (defvar org-maybe-keyword-time-regexp nil
4285 "Matches a timestamp, possibly preceded by a keyword.")
4286 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4287 (defvar org-all-time-keywords nil
4288 "List of time keywords.")
4289 (make-variable-buffer-local 'org-all-time-keywords)
4291 (defconst org-plain-time-of-day-regexp
4292 (concat
4293 "\\(\\<[012]?[0-9]"
4294 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4295 "\\(--?"
4296 "\\(\\<[012]?[0-9]"
4297 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4298 "\\)?")
4299 "Regular expression to match a plain time or time range.
4300 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4301 groups carry important information:
4302 0 the full match
4303 1 the first time, range or not
4304 8 the second time, if it is a range.")
4306 (defconst org-plain-time-extension-regexp
4307 (concat
4308 "\\(\\<[012]?[0-9]"
4309 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4310 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4311 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4312 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4313 groups carry important information:
4314 0 the full match
4315 7 hours of duration
4316 9 minutes of duration")
4318 (defconst org-stamp-time-of-day-regexp
4319 (concat
4320 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4321 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4322 "\\(--?"
4323 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4324 "Regular expression to match a timestamp time or time range.
4325 After a match, the following groups carry important information:
4326 0 the full match
4327 1 date plus weekday, for back referencing to make sure both times are on the same day
4328 2 the first time, range or not
4329 4 the second time, if it is a range.")
4331 (defconst org-startup-options
4332 '(("fold" org-startup-folded t)
4333 ("overview" org-startup-folded t)
4334 ("nofold" org-startup-folded nil)
4335 ("showall" org-startup-folded nil)
4336 ("showeverything" org-startup-folded showeverything)
4337 ("content" org-startup-folded content)
4338 ("indent" org-startup-indented t)
4339 ("noindent" org-startup-indented nil)
4340 ("hidestars" org-hide-leading-stars t)
4341 ("showstars" org-hide-leading-stars nil)
4342 ("odd" org-odd-levels-only t)
4343 ("oddeven" org-odd-levels-only nil)
4344 ("align" org-startup-align-all-tables t)
4345 ("noalign" org-startup-align-all-tables nil)
4346 ("inlineimages" org-startup-with-inline-images t)
4347 ("noinlineimages" org-startup-with-inline-images nil)
4348 ("customtime" org-display-custom-times t)
4349 ("logdone" org-log-done time)
4350 ("lognotedone" org-log-done note)
4351 ("nologdone" org-log-done nil)
4352 ("lognoteclock-out" org-log-note-clock-out t)
4353 ("nolognoteclock-out" org-log-note-clock-out nil)
4354 ("logrepeat" org-log-repeat state)
4355 ("lognoterepeat" org-log-repeat note)
4356 ("nologrepeat" org-log-repeat nil)
4357 ("logreschedule" org-log-reschedule time)
4358 ("lognotereschedule" org-log-reschedule note)
4359 ("nologreschedule" org-log-reschedule nil)
4360 ("logredeadline" org-log-redeadline time)
4361 ("lognoteredeadline" org-log-redeadline note)
4362 ("nologredeadline" org-log-redeadline nil)
4363 ("logrefile" org-log-refile time)
4364 ("lognoterefile" org-log-refile note)
4365 ("nologrefile" org-log-refile nil)
4366 ("fninline" org-footnote-define-inline t)
4367 ("nofninline" org-footnote-define-inline nil)
4368 ("fnlocal" org-footnote-section nil)
4369 ("fnauto" org-footnote-auto-label t)
4370 ("fnprompt" org-footnote-auto-label nil)
4371 ("fnconfirm" org-footnote-auto-label confirm)
4372 ("fnplain" org-footnote-auto-label plain)
4373 ("fnadjust" org-footnote-auto-adjust t)
4374 ("nofnadjust" org-footnote-auto-adjust nil)
4375 ("constcgs" constants-unit-system cgs)
4376 ("constSI" constants-unit-system SI)
4377 ("noptag" org-tag-persistent-alist nil)
4378 ("hideblocks" org-hide-block-startup t)
4379 ("nohideblocks" org-hide-block-startup nil)
4380 ("beamer" org-startup-with-beamer-mode t)
4381 ("entitiespretty" org-pretty-entities t)
4382 ("entitiesplain" org-pretty-entities nil))
4383 "Variable associated with STARTUP options for org-mode.
4384 Each element is a list of three items: the startup options (as written
4385 in the #+STARTUP line), the corresponding variable, and the value to set
4386 this variable to if the option is found. An optional forth element PUSH
4387 means to push this value onto the list in the variable.")
4389 (defun org-update-property-plist (key val props)
4390 "Update PROPS with KEY and VAL."
4391 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4392 (key (if appending (substring key 0 (- (length key) 1)) key))
4393 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4394 (previous (cdr (assoc key props))))
4395 (if appending
4396 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4397 (cons (cons key val) remainder))))
4399 (defconst org-block-regexp
4400 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4401 "Regular expression for hiding blocks.")
4402 (defconst org-heading-keyword-regexp-format
4403 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4404 "Printf format for a regexp matching an headline with some keyword.
4405 This regexp will match the headline of any node which has the
4406 exact keyword that is put into the format. The keyword isn't in
4407 any group by default, but the stars and the body are.")
4408 (defconst org-heading-keyword-maybe-regexp-format
4409 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4410 "Printf format for a regexp matching an headline, possibly with some keyword.
4411 This regexp can match any headline with the specified keyword, or
4412 without a keyword. The keyword isn't in any group by default,
4413 but the stars and the body are.")
4415 (defun org-set-regexps-and-options ()
4416 "Precompute regular expressions for current buffer."
4417 (when (derived-mode-p 'org-mode)
4418 (org-set-local 'org-todo-kwd-alist nil)
4419 (org-set-local 'org-todo-key-alist nil)
4420 (org-set-local 'org-todo-key-trigger nil)
4421 (org-set-local 'org-todo-keywords-1 nil)
4422 (org-set-local 'org-done-keywords nil)
4423 (org-set-local 'org-todo-heads nil)
4424 (org-set-local 'org-todo-sets nil)
4425 (org-set-local 'org-todo-log-states nil)
4426 (org-set-local 'org-file-properties nil)
4427 (org-set-local 'org-file-tags nil)
4428 (let ((re (org-make-options-regexp
4429 '("CATEGORY" "TODO" "COLUMNS"
4430 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4431 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4432 "OPTIONS")
4433 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4434 (splitre "[ \t]+")
4435 (scripts org-use-sub-superscripts)
4436 kwds kws0 kwsa key log value cat arch tags const links hw dws
4437 tail sep kws1 prio props ftags drawers beamer-p
4438 ext-setup-or-nil setup-contents (start 0))
4439 (save-excursion
4440 (save-restriction
4441 (widen)
4442 (goto-char (point-min))
4443 (while (or (and ext-setup-or-nil
4444 (string-match re ext-setup-or-nil start)
4445 (setq start (match-end 0)))
4446 (and (setq ext-setup-or-nil nil start 0)
4447 (re-search-forward re nil t)))
4448 (setq key (upcase (match-string 1 ext-setup-or-nil))
4449 value (org-match-string-no-properties 2 ext-setup-or-nil))
4450 (if (stringp value) (setq value (org-trim value)))
4451 (cond
4452 ((equal key "CATEGORY")
4453 (setq cat value))
4454 ((member key '("SEQ_TODO" "TODO"))
4455 (push (cons 'sequence (org-split-string value splitre)) kwds))
4456 ((equal key "TYP_TODO")
4457 (push (cons 'type (org-split-string value splitre)) kwds))
4458 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4459 ;; general TODO-like setup
4460 (push (cons (intern (downcase (match-string 1 key)))
4461 (org-split-string value splitre)) kwds))
4462 ((equal key "TAGS")
4463 (setq tags (append tags (if tags '("\\n") nil)
4464 (org-split-string value splitre))))
4465 ((equal key "COLUMNS")
4466 (org-set-local 'org-columns-default-format value))
4467 ((equal key "LINK")
4468 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4469 (push (cons (match-string 1 value)
4470 (org-trim (match-string 2 value)))
4471 links)))
4472 ((equal key "PRIORITIES")
4473 (setq prio (org-split-string value " +")))
4474 ((equal key "PROPERTY")
4475 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4476 (setq props (org-update-property-plist (match-string 1 value)
4477 (match-string 2 value)
4478 props))))
4479 ((equal key "FILETAGS")
4480 (when (string-match "\\S-" value)
4481 (setq ftags
4482 (append
4483 ftags
4484 (apply 'append
4485 (mapcar (lambda (x) (org-split-string x ":"))
4486 (org-split-string value)))))))
4487 ((equal key "DRAWERS")
4488 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4489 ((equal key "CONSTANTS")
4490 (setq const (append const (org-split-string value splitre))))
4491 ((equal key "STARTUP")
4492 (let ((opts (org-split-string value splitre))
4493 l var val)
4494 (while (setq l (pop opts))
4495 (when (setq l (assoc l org-startup-options))
4496 (setq var (nth 1 l) val (nth 2 l))
4497 (if (not (nth 3 l))
4498 (set (make-local-variable var) val)
4499 (if (not (listp (symbol-value var)))
4500 (set (make-local-variable var) nil))
4501 (set (make-local-variable var) (symbol-value var))
4502 (add-to-list var val))))))
4503 ((equal key "ARCHIVE")
4504 (setq arch value)
4505 (remove-text-properties 0 (length arch)
4506 '(face t fontified t) arch))
4507 ((equal key "LATEX_CLASS")
4508 (setq beamer-p (equal value "beamer")))
4509 ((equal key "OPTIONS")
4510 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4511 (setq scripts (read (match-string 2 value)))))
4512 ((equal key "SETUPFILE")
4513 (setq setup-contents (org-file-contents
4514 (expand-file-name
4515 (org-remove-double-quotes value))
4516 'noerror))
4517 (if (not ext-setup-or-nil)
4518 (setq ext-setup-or-nil setup-contents start 0)
4519 (setq ext-setup-or-nil
4520 (concat (substring ext-setup-or-nil 0 start)
4521 "\n" setup-contents "\n"
4522 (substring ext-setup-or-nil start)))))))
4523 ;; search for property blocks
4524 (goto-char (point-min))
4525 (while (re-search-forward org-block-regexp nil t)
4526 (when (equal "PROPERTY" (upcase (match-string 1)))
4527 (setq value (replace-regexp-in-string
4528 "[\n\r]" " " (match-string 4)))
4529 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4530 (setq props (org-update-property-plist (match-string 1 value)
4531 (match-string 2 value)
4532 props)))))))
4533 (org-set-local 'org-use-sub-superscripts scripts)
4534 (when cat
4535 (org-set-local 'org-category (intern cat))
4536 (push (cons "CATEGORY" cat) props))
4537 (when prio
4538 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4539 (setq prio (mapcar 'string-to-char prio))
4540 (org-set-local 'org-highest-priority (nth 0 prio))
4541 (org-set-local 'org-lowest-priority (nth 1 prio))
4542 (org-set-local 'org-default-priority (nth 2 prio)))
4543 (and props (org-set-local 'org-file-properties (nreverse props)))
4544 (and ftags (org-set-local 'org-file-tags
4545 (mapcar 'org-add-prop-inherited ftags)))
4546 (and drawers (org-set-local 'org-drawers drawers))
4547 (and arch (org-set-local 'org-archive-location arch))
4548 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4549 ;; Process the TODO keywords
4550 (unless kwds
4551 ;; Use the global values as if they had been given locally.
4552 (setq kwds (default-value 'org-todo-keywords))
4553 (if (stringp (car kwds))
4554 (setq kwds (list (cons org-todo-interpretation
4555 (default-value 'org-todo-keywords)))))
4556 (setq kwds (reverse kwds)))
4557 (setq kwds (nreverse kwds))
4558 (let (inter kws kw)
4559 (while (setq kws (pop kwds))
4560 (let ((kws (or
4561 (run-hook-with-args-until-success
4562 'org-todo-setup-filter-hook kws)
4563 kws)))
4564 (setq inter (pop kws) sep (member "|" kws)
4565 kws0 (delete "|" (copy-sequence kws))
4566 kwsa nil
4567 kws1 (mapcar
4568 (lambda (x)
4569 ;; 1 2
4570 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4571 (progn
4572 (setq kw (match-string 1 x)
4573 key (and (match-end 2) (match-string 2 x))
4574 log (org-extract-log-state-settings x))
4575 (push (cons kw (and key (string-to-char key))) kwsa)
4576 (and log (push log org-todo-log-states))
4578 (error "Invalid TODO keyword %s" x)))
4579 kws0)
4580 kwsa (if kwsa (append '((:startgroup))
4581 (nreverse kwsa)
4582 '((:endgroup))))
4583 hw (car kws1)
4584 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4585 tail (list inter hw (car dws) (org-last dws))))
4586 (add-to-list 'org-todo-heads hw 'append)
4587 (push kws1 org-todo-sets)
4588 (setq org-done-keywords (append org-done-keywords dws nil))
4589 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4590 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4591 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4592 (setq org-todo-sets (nreverse org-todo-sets)
4593 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4594 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4595 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4596 ;; Process the constants
4597 (when const
4598 (let (e cst)
4599 (while (setq e (pop const))
4600 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4601 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4602 (setq org-table-formula-constants-local cst)))
4604 ;; Process the tags.
4605 (when tags
4606 (let (e tgs)
4607 (while (setq e (pop tags))
4608 (cond
4609 ((equal e "{") (push '(:startgroup) tgs))
4610 ((equal e "}") (push '(:endgroup) tgs))
4611 ((equal e "\\n") (push '(:newline) tgs))
4612 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4613 (push (cons (match-string 1 e)
4614 (string-to-char (match-string 2 e)))
4615 tgs))
4616 (t (push (list e) tgs))))
4617 (org-set-local 'org-tag-alist nil)
4618 (while (setq e (pop tgs))
4619 (or (and (stringp (car e))
4620 (assoc (car e) org-tag-alist))
4621 (push e org-tag-alist)))))
4623 ;; Compute the regular expressions and other local variables.
4624 ;; Using `org-outline-regexp-bol' would complicate them much,
4625 ;; because of the fixed white space at the end of that string.
4626 (if (not org-done-keywords)
4627 (setq org-done-keywords (and org-todo-keywords-1
4628 (list (org-last org-todo-keywords-1)))))
4629 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4630 (length org-scheduled-string)
4631 (length org-clock-string)
4632 (length org-closed-string)))
4633 org-drawer-regexp
4634 (concat "^[ \t]*:\\("
4635 (mapconcat 'regexp-quote org-drawers "\\|")
4636 "\\):[ \t]*$")
4637 org-not-done-keywords
4638 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4639 org-todo-regexp
4640 (concat "\\("
4641 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4642 "\\)")
4643 org-not-done-regexp
4644 (concat "\\("
4645 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4646 "\\)")
4647 org-not-done-heading-regexp
4648 (format org-heading-keyword-regexp-format org-not-done-regexp)
4649 org-todo-line-regexp
4650 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4651 org-complex-heading-regexp
4652 (concat "^\\(\\*+\\)"
4653 "\\(?: +" org-todo-regexp "\\)?"
4654 "\\(?: +\\(\\[#.\\]\\)\\)?"
4655 "\\(?: +\\(.*?\\)\\)??"
4656 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4657 "[ \t]*$")
4658 org-complex-heading-regexp-format
4659 (concat "^\\(\\*+\\)"
4660 "\\(?: +" org-todo-regexp "\\)?"
4661 "\\(?: +\\(\\[#.\\]\\)\\)?"
4662 "\\(?: +"
4663 ;; Stats cookies can be stuck to body.
4664 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4665 "\\(%s\\)"
4666 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4667 "\\)"
4668 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4669 "[ \t]*$")
4670 org-todo-line-tags-regexp
4671 (concat "^\\(\\*+\\)"
4672 "\\(?: +" org-todo-regexp "\\)?"
4673 "\\(?: +\\(.*?\\)\\)??"
4674 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4675 "[ \t]*$")
4676 org-deadline-regexp (concat "\\<" org-deadline-string)
4677 org-deadline-time-regexp
4678 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4679 org-deadline-line-regexp
4680 (concat "\\<\\(" org-deadline-string "\\).*")
4681 org-scheduled-regexp
4682 (concat "\\<" org-scheduled-string)
4683 org-scheduled-time-regexp
4684 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4685 org-closed-time-regexp
4686 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4687 org-keyword-time-regexp
4688 (concat "\\<\\(" org-scheduled-string
4689 "\\|" org-deadline-string
4690 "\\|" org-closed-string
4691 "\\|" org-clock-string "\\)"
4692 " *[[<]\\([^]>]+\\)[]>]")
4693 org-keyword-time-not-clock-regexp
4694 (concat "\\<\\(" org-scheduled-string
4695 "\\|" org-deadline-string
4696 "\\|" org-closed-string
4697 "\\)"
4698 " *[[<]\\([^]>]+\\)[]>]")
4699 org-maybe-keyword-time-regexp
4700 (concat "\\(\\<\\(" org-scheduled-string
4701 "\\|" org-deadline-string
4702 "\\|" org-closed-string
4703 "\\|" org-clock-string "\\)\\)?"
4704 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4705 org-all-time-keywords
4706 (mapcar (lambda (w) (substring w 0 -1))
4707 (list org-scheduled-string org-deadline-string
4708 org-clock-string org-closed-string))
4710 (org-compute-latex-and-specials-regexp)
4711 (org-set-font-lock-defaults))))
4713 (defun org-file-contents (file &optional noerror)
4714 "Return the contents of FILE, as a string."
4715 (if (or (not file)
4716 (not (file-readable-p file)))
4717 (if noerror
4718 (progn
4719 (message "Cannot read file \"%s\"" file)
4720 (ding) (sit-for 2)
4722 (error "Cannot read file \"%s\"" file))
4723 (with-temp-buffer
4724 (insert-file-contents file)
4725 (buffer-string))))
4727 (defun org-extract-log-state-settings (x)
4728 "Extract the log state setting from a TODO keyword string.
4729 This will extract info from a string like \"WAIT(w@/!)\"."
4730 (let (kw key log1 log2)
4731 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4732 (setq kw (match-string 1 x)
4733 key (and (match-end 2) (match-string 2 x))
4734 log1 (and (match-end 3) (match-string 3 x))
4735 log2 (and (match-end 4) (match-string 4 x)))
4736 (and (or log1 log2)
4737 (list kw
4738 (and log1 (if (equal log1 "!") 'time 'note))
4739 (and log2 (if (equal log2 "!") 'time 'note)))))))
4741 (defun org-remove-keyword-keys (list)
4742 "Remove a pair of parenthesis at the end of each string in LIST."
4743 (mapcar (lambda (x)
4744 (if (string-match "(.*)$" x)
4745 (substring x 0 (match-beginning 0))
4747 list))
4749 (defun org-assign-fast-keys (alist)
4750 "Assign fast keys to a keyword-key alist.
4751 Respect keys that are already there."
4752 (let (new e (alt ?0))
4753 (while (setq e (pop alist))
4754 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4755 (cdr e)) ;; Key already assigned.
4756 (push e new)
4757 (let ((clist (string-to-list (downcase (car e))))
4758 (used (append new alist)))
4759 (when (= (car clist) ?@)
4760 (pop clist))
4761 (while (and clist (rassoc (car clist) used))
4762 (pop clist))
4763 (unless clist
4764 (while (rassoc alt used)
4765 (incf alt)))
4766 (push (cons (car e) (or (car clist) alt)) new))))
4767 (nreverse new)))
4769 ;;; Some variables used in various places
4771 (defvar org-window-configuration nil
4772 "Used in various places to store a window configuration.")
4773 (defvar org-selected-window nil
4774 "Used in various places to store a window configuration.")
4775 (defvar org-finish-function nil
4776 "Function to be called when `C-c C-c' is used.
4777 This is for getting out of special buffers like capture.")
4780 ;; FIXME: Occasionally check by commenting these, to make sure
4781 ;; no other functions uses these, forgetting to let-bind them.
4782 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4783 (defvar org-last-state)
4784 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4786 ;; Defined somewhere in this file, but used before definition.
4787 (defvar org-entities) ;; defined in org-entities.el
4788 (defvar org-struct-menu)
4789 (defvar org-org-menu)
4790 (defvar org-tbl-menu)
4792 ;;;; Define the Org-mode
4794 ;; We use a before-change function to check if a table might need
4795 ;; an update.
4796 (defvar org-table-may-need-update t
4797 "Indicates that a table might need an update.
4798 This variable is set by `org-before-change-function'.
4799 `org-table-align' sets it back to nil.")
4800 (defun org-before-change-function (beg end)
4801 "Every change indicates that a table might need an update."
4802 (setq org-table-may-need-update t))
4803 (defvar org-mode-map)
4804 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4805 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4806 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4807 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4808 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4809 (defvar org-table-buffer-is-an nil)
4811 (defvar bidi-paragraph-direction)
4812 (defvar buffer-face-mode-face)
4814 (require 'outline)
4815 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4816 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or upgrade to newer allout, for example by switching to Emacs 22"))
4817 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4819 ;; Other stuff we need.
4820 (require 'time-date)
4821 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4822 (require 'easymenu)
4823 (require 'overlay)
4825 (require 'org-macs)
4826 (require 'org-entities)
4827 ;; (require 'org-compat) moved higher up in the file before it is first used
4828 (require 'org-faces)
4829 (require 'org-list)
4830 (require 'org-pcomplete)
4831 (require 'org-src)
4832 (require 'org-footnote)
4834 ;; babel
4835 (require 'ob)
4836 (require 'ob-table)
4837 (require 'ob-lob)
4838 (require 'ob-ref)
4839 (require 'ob-tangle)
4840 (require 'ob-comint)
4841 (require 'ob-keys)
4843 ;;;###autoload
4844 (define-derived-mode org-mode outline-mode "Org"
4845 "Outline-based notes management and organizer, alias
4846 \"Carsten's outline-mode for keeping track of everything.\"
4848 Org-mode develops organizational tasks around a NOTES file which
4849 contains information about projects as plain text. Org-mode is
4850 implemented on top of outline-mode, which is ideal to keep the content
4851 of large files well structured. It supports ToDo items, deadlines and
4852 time stamps, which magically appear in the diary listing of the Emacs
4853 calendar. Tables are easily created with a built-in table editor.
4854 Plain text URL-like links connect to websites, emails (VM), Usenet
4855 messages (Gnus), BBDB entries, and any files related to the project.
4856 For printing and sharing of notes, an Org-mode file (or a part of it)
4857 can be exported as a structured ASCII or HTML file.
4859 The following commands are available:
4861 \\{org-mode-map}"
4863 ;; Get rid of Outline menus, they are not needed
4864 ;; Need to do this here because define-derived-mode sets up
4865 ;; the keymap so late. Still, it is a waste to call this each time
4866 ;; we switch another buffer into org-mode.
4867 (if (featurep 'xemacs)
4868 (when (boundp 'outline-mode-menu-heading)
4869 ;; Assume this is Greg's port, it uses easymenu
4870 (easy-menu-remove outline-mode-menu-heading)
4871 (easy-menu-remove outline-mode-menu-show)
4872 (easy-menu-remove outline-mode-menu-hide))
4873 (define-key org-mode-map [menu-bar headings] 'undefined)
4874 (define-key org-mode-map [menu-bar hide] 'undefined)
4875 (define-key org-mode-map [menu-bar show] 'undefined))
4877 (org-load-modules-maybe)
4878 (easy-menu-add org-org-menu)
4879 (easy-menu-add org-tbl-menu)
4880 (org-install-agenda-files-menu)
4881 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4882 (add-to-invisibility-spec '(org-cwidth))
4883 (add-to-invisibility-spec '(org-hide-block . t))
4884 (when (featurep 'xemacs)
4885 (org-set-local 'line-move-ignore-invisible t))
4886 (org-set-local 'outline-regexp org-outline-regexp)
4887 (org-set-local 'outline-level 'org-outline-level)
4888 (setq bidi-paragraph-direction 'left-to-right)
4889 (when (and org-ellipsis
4890 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4891 (fboundp 'make-glyph-code))
4892 (unless org-display-table
4893 (setq org-display-table (make-display-table)))
4894 (set-display-table-slot
4895 org-display-table 4
4896 (vconcat (mapcar
4897 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4898 org-ellipsis)))
4899 (if (stringp org-ellipsis) org-ellipsis "..."))))
4900 (setq buffer-display-table org-display-table))
4901 (org-set-regexps-and-options)
4902 (when (and org-tag-faces (not org-tags-special-faces-re))
4903 ;; tag faces set outside customize.... force initialization.
4904 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4905 ;; Calc embedded
4906 (org-set-local 'calc-embedded-open-mode "# ")
4907 (modify-syntax-entry ?@ "w")
4908 (if org-startup-truncated (setq truncate-lines t))
4909 (org-set-local 'font-lock-unfontify-region-function
4910 'org-unfontify-region)
4911 ;; Activate before-change-function
4912 (org-set-local 'org-table-may-need-update t)
4913 (org-add-hook 'before-change-functions 'org-before-change-function nil
4914 'local)
4915 ;; Check for running clock before killing a buffer
4916 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4917 ;; Indentation.
4918 (org-set-local 'indent-line-function 'org-indent-line)
4919 (org-set-local 'indent-region-function 'org-indent-region)
4920 ;; Initialize radio targets.
4921 (org-update-radio-target-regexp)
4922 ;; Filling and auto-filling.
4923 (org-setup-filling)
4924 ;; Comments.
4925 (org-setup-comments-handling)
4926 ;; Beginning/end of defun
4927 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
4928 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
4929 ;; Next error for sparse trees
4930 (org-set-local 'next-error-function 'org-occur-next-match)
4931 ;; Make sure dependence stuff works reliably, even for users who set it
4932 ;; too late :-(
4933 (if org-enforce-todo-dependencies
4934 (add-hook 'org-blocker-hook
4935 'org-block-todo-from-children-or-siblings-or-parent)
4936 (remove-hook 'org-blocker-hook
4937 'org-block-todo-from-children-or-siblings-or-parent))
4938 (if org-enforce-todo-checkbox-dependencies
4939 (add-hook 'org-blocker-hook
4940 'org-block-todo-from-checkboxes)
4941 (remove-hook 'org-blocker-hook
4942 'org-block-todo-from-checkboxes))
4944 ;; Align options lines
4945 (org-set-local
4946 'align-mode-rules-list
4947 '((org-in-buffer-settings
4948 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4949 (modes . '(org-mode)))))
4951 ;; Imenu
4952 (org-set-local 'imenu-create-index-function
4953 'org-imenu-get-tree)
4955 ;; Make isearch reveal context
4956 (if (or (featurep 'xemacs)
4957 (not (boundp 'outline-isearch-open-invisible-function)))
4958 ;; Emacs 21 and XEmacs make use of the hook
4959 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4960 ;; Emacs 22 deals with this through a special variable
4961 (org-set-local 'outline-isearch-open-invisible-function
4962 (lambda (&rest ignore) (org-show-context 'isearch))))
4964 ;; Turn on org-beamer-mode?
4965 (and org-startup-with-beamer-mode (org-beamer-mode))
4967 ;; Setup the pcomplete hooks
4968 (set (make-local-variable 'pcomplete-command-completion-function)
4969 'org-pcomplete-initial)
4970 (set (make-local-variable 'pcomplete-command-name-function)
4971 'org-command-at-point)
4972 (set (make-local-variable 'pcomplete-default-completion-function)
4973 'ignore)
4974 (set (make-local-variable 'pcomplete-parse-arguments-function)
4975 'org-parse-arguments)
4976 (set (make-local-variable 'pcomplete-termination-string) "")
4977 (when (>= emacs-major-version 23)
4978 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
4980 ;; If empty file that did not turn on org-mode automatically, make it to.
4981 (if (and org-insert-mode-line-in-empty-file
4982 (org-called-interactively-p 'any)
4983 (= (point-min) (point-max)))
4984 (insert "# -*- mode: org -*-\n\n"))
4985 (unless org-inhibit-startup
4986 (when org-startup-align-all-tables
4987 (let ((bmp (buffer-modified-p)))
4988 (org-table-map-tables 'org-table-align 'quietly)
4989 (set-buffer-modified-p bmp)))
4990 (when org-startup-with-inline-images
4991 (org-display-inline-images))
4992 (when org-startup-indented
4993 (require 'org-indent)
4994 (org-indent-mode 1))
4995 (unless org-inhibit-startup-visibility-stuff
4996 (org-set-startup-visibility)))
4997 ;; Try to set org-hide correctly
4998 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5000 (when (fboundp 'abbrev-table-put)
5001 (abbrev-table-put org-mode-abbrev-table
5002 :parents (list text-mode-abbrev-table)))
5004 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5007 (defun org-find-invisible-foreground ()
5008 (let ((candidates (remove
5009 "unspecified-bg"
5010 (nconc
5011 (list (face-background 'default)
5012 (face-background 'org-default))
5013 (mapcar
5014 (lambda (alist)
5015 (when (boundp alist)
5016 (cdr (assoc 'background-color (symbol-value alist)))))
5017 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5018 (list (face-foreground 'org-hide))))))
5019 (car (remove nil candidates))))
5021 (defun org-current-time ()
5022 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5023 (if (> (car org-time-stamp-rounding-minutes) 1)
5024 (let ((r (car org-time-stamp-rounding-minutes))
5025 (time (decode-time)))
5026 (apply 'encode-time
5027 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5028 (nthcdr 2 time))))
5029 (current-time)))
5031 (defun org-today ()
5032 "Return today date, considering `org-extend-today-until'."
5033 (time-to-days
5034 (time-subtract (current-time)
5035 (list 0 (* 3600 org-extend-today-until) 0))))
5037 ;;;; Font-Lock stuff, including the activators
5039 (defvar org-mouse-map (make-sparse-keymap))
5040 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5041 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5042 (when org-mouse-1-follows-link
5043 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5044 (when org-tab-follows-link
5045 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5046 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5048 (require 'font-lock)
5050 (defconst org-non-link-chars "]\t\n\r<>")
5051 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5052 "shell" "elisp" "doi" "message"))
5053 (defvar org-link-types-re nil
5054 "Matches a link that has a url-like prefix like \"http:\"")
5055 (defvar org-link-re-with-space nil
5056 "Matches a link with spaces, optional angular brackets around it.")
5057 (defvar org-link-re-with-space2 nil
5058 "Matches a link with spaces, optional angular brackets around it.")
5059 (defvar org-link-re-with-space3 nil
5060 "Matches a link with spaces, only for internal part in bracket links.")
5061 (defvar org-angle-link-re nil
5062 "Matches link with angular brackets, spaces are allowed.")
5063 (defvar org-plain-link-re nil
5064 "Matches plain link, without spaces.")
5065 (defvar org-bracket-link-regexp nil
5066 "Matches a link in double brackets.")
5067 (defvar org-bracket-link-analytic-regexp nil
5068 "Regular expression used to analyze links.
5069 Here is what the match groups contain after a match:
5070 1: http:
5071 2: http
5072 3: path
5073 4: [desc]
5074 5: desc")
5075 (defvar org-bracket-link-analytic-regexp++ nil
5076 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5077 (defvar org-any-link-re nil
5078 "Regular expression matching any link.")
5080 (defcustom org-match-sexp-depth 3
5081 "Number of stacked braces for sub/superscript matching.
5082 This has to be set before loading org.el to be effective."
5083 :group 'org-export-translation ; ??????????????????????????/
5084 :type 'integer)
5086 (defun org-create-multibrace-regexp (left right n)
5087 "Create a regular expression which will match a balanced sexp.
5088 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5089 as single character strings.
5090 The regexp returned will match the entire expression including the
5091 delimiters. It will also define a single group which contains the
5092 match except for the outermost delimiters. The maximum depth of
5093 stacked delimiters is N. Escaping delimiters is not possible."
5094 (let* ((nothing (concat "[^" left right "]*?"))
5095 (or "\\|")
5096 (re nothing)
5097 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5098 (while (> n 1)
5099 (setq n (1- n)
5100 re (concat re or next)
5101 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5102 (concat left "\\(" re "\\)" right)))
5104 (defvar org-match-substring-regexp
5105 (concat
5106 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5107 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5108 "\\|"
5109 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5110 "\\|"
5111 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5112 "The regular expression matching a sub- or superscript.")
5114 (defvar org-match-substring-with-braces-regexp
5115 (concat
5116 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5117 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5118 "\\)")
5119 "The regular expression matching a sub- or superscript, forcing braces.")
5121 (defun org-make-link-regexps ()
5122 "Update the link regular expressions.
5123 This should be called after the variable `org-link-types' has changed."
5124 (setq org-link-types-re
5125 (concat
5126 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5127 org-link-re-with-space
5128 (concat
5129 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5130 "\\([^" org-non-link-chars " ]"
5131 "[^" org-non-link-chars "]*"
5132 "[^" org-non-link-chars " ]\\)>?")
5133 org-link-re-with-space2
5134 (concat
5135 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5136 "\\([^" org-non-link-chars " ]"
5137 "[^\t\n\r]*"
5138 "[^" org-non-link-chars " ]\\)>?")
5139 org-link-re-with-space3
5140 (concat
5141 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5142 "\\([^" org-non-link-chars " ]"
5143 "[^\t\n\r]*\\)")
5144 org-angle-link-re
5145 (concat
5146 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5147 "\\([^" org-non-link-chars " ]"
5148 "[^" org-non-link-chars "]*"
5149 "\\)>")
5150 org-plain-link-re
5151 (concat
5152 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5153 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5154 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5155 org-bracket-link-regexp
5156 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5157 org-bracket-link-analytic-regexp
5158 (concat
5159 "\\[\\["
5160 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5161 "\\([^]]+\\)"
5162 "\\]"
5163 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5164 "\\]")
5165 org-bracket-link-analytic-regexp++
5166 (concat
5167 "\\[\\["
5168 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5169 "\\([^]]+\\)"
5170 "\\]"
5171 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5172 "\\]")
5173 org-any-link-re
5174 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5175 org-angle-link-re "\\)\\|\\("
5176 org-plain-link-re "\\)")))
5178 (org-make-link-regexps)
5180 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5181 "Regular expression for fast time stamp matching.")
5182 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5183 "Regular expression for fast time stamp matching.")
5184 (defconst org-ts-regexp0
5185 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5186 "Regular expression matching time strings for analysis.
5187 This one does not require the space after the date, so it can be used
5188 on a string that terminates immediately after the date.")
5189 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5190 "Regular expression matching time strings for analysis.")
5191 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5192 "Regular expression matching time stamps, with groups.")
5193 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5194 "Regular expression matching time stamps (also [..]), with groups.")
5195 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5196 "Regular expression matching a time stamp range.")
5197 (defconst org-tr-regexp-both
5198 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5199 "Regular expression matching a time stamp range.")
5200 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5201 org-ts-regexp "\\)?")
5202 "Regular expression matching a time stamp or time stamp range.")
5203 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5204 org-ts-regexp-both "\\)?")
5205 "Regular expression matching a time stamp or time stamp range.
5206 The time stamps may be either active or inactive.")
5208 (defvar org-emph-face nil)
5210 (defun org-do-emphasis-faces (limit)
5211 "Run through the buffer and add overlays to emphasized strings."
5212 (let (rtn a)
5213 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5214 (if (not (= (char-after (match-beginning 3))
5215 (char-after (match-beginning 4))))
5216 (progn
5217 (setq rtn t)
5218 (setq a (assoc (match-string 3) org-emphasis-alist))
5219 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5220 'face
5221 (nth 1 a))
5222 (and (nth 4 a)
5223 (org-remove-flyspell-overlays-in
5224 (match-beginning 0) (match-end 0)))
5225 (add-text-properties (match-beginning 2) (match-end 2)
5226 '(font-lock-multiline t org-emphasis t))
5227 (when org-hide-emphasis-markers
5228 (add-text-properties (match-end 4) (match-beginning 5)
5229 '(invisible org-link))
5230 (add-text-properties (match-beginning 3) (match-end 3)
5231 '(invisible org-link)))))
5232 (backward-char 1))
5233 rtn))
5235 (defun org-emphasize (&optional char)
5236 "Insert or change an emphasis, i.e. a font like bold or italic.
5237 If there is an active region, change that region to a new emphasis.
5238 If there is no region, just insert the marker characters and position
5239 the cursor between them.
5240 CHAR should be either the marker character, or the first character of the
5241 HTML tag associated with that emphasis. If CHAR is a space, the means
5242 to remove the emphasis of the selected region.
5243 If char is not given (for example in an interactive call) it
5244 will be prompted for."
5245 (interactive)
5246 (let ((eal org-emphasis-alist) e det
5247 (erc org-emphasis-regexp-components)
5248 (prompt "")
5249 (string "") beg end move tag c s)
5250 (if (org-region-active-p)
5251 (setq beg (region-beginning) end (region-end)
5252 string (buffer-substring beg end))
5253 (setq move t))
5255 (while (setq e (pop eal))
5256 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5257 c (aref tag 0))
5258 (push (cons c (string-to-char (car e))) det)
5259 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5260 (substring tag 1)))))
5261 (setq det (nreverse det))
5262 (unless char
5263 (message "%s" (concat "Emphasis marker or tag:" prompt))
5264 (setq char (read-char-exclusive)))
5265 (setq char (or (cdr (assoc char det)) char))
5266 (if (equal char ?\ )
5267 (setq s "" move nil)
5268 (unless (assoc (char-to-string char) org-emphasis-alist)
5269 (error "No such emphasis marker: \"%c\"" char))
5270 (setq s (char-to-string char)))
5271 (while (and (> (length string) 1)
5272 (equal (substring string 0 1) (substring string -1))
5273 (assoc (substring string 0 1) org-emphasis-alist))
5274 (setq string (substring string 1 -1)))
5275 (setq string (concat s string s))
5276 (if beg (delete-region beg end))
5277 (unless (or (bolp)
5278 (string-match (concat "[" (nth 0 erc) "\n]")
5279 (char-to-string (char-before (point)))))
5280 (insert " "))
5281 (unless (or (eobp)
5282 (string-match (concat "[" (nth 1 erc) "\n]")
5283 (char-to-string (char-after (point)))))
5284 (insert " ") (backward-char 1))
5285 (insert string)
5286 (and move (backward-char 1))))
5288 (defconst org-nonsticky-props
5289 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5291 (defsubst org-rear-nonsticky-at (pos)
5292 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5294 (defun org-activate-plain-links (limit)
5295 "Run through the buffer and add overlays to links."
5296 (catch 'exit
5297 (let (f)
5298 (when (re-search-forward (concat org-plain-link-re) limit t)
5299 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5300 (setq f (get-text-property (match-beginning 0) 'face))
5301 (if (or (eq f 'org-tag)
5302 (and (listp f) (memq 'org-tag f)))
5304 (add-text-properties (match-beginning 0) (match-end 0)
5305 (list 'mouse-face 'highlight
5306 'face 'org-link
5307 'keymap org-mouse-map))
5308 (org-rear-nonsticky-at (match-end 0)))
5309 t))))
5311 (defun org-activate-code (limit)
5312 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5313 (progn
5314 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5315 (remove-text-properties (match-beginning 0) (match-end 0)
5316 '(display t invisible t intangible t))
5317 t)))
5319 (defcustom org-src-fontify-natively nil
5320 "When non-nil, fontify code in code blocks."
5321 :type 'boolean
5322 :version "24.1"
5323 :group 'org-appearance
5324 :group 'org-babel)
5326 (defcustom org-allow-promoting-top-level-subtree nil
5327 "When non-nil, allow promoting a top level subtree.
5328 The leading star of the top level headline will be replaced
5329 by a #."
5330 :type 'boolean
5331 :version "24.1"
5332 :group 'org-appearance)
5334 (defun org-fontify-meta-lines-and-blocks (limit)
5335 (condition-case nil
5336 (org-fontify-meta-lines-and-blocks-1 limit)
5337 (error (message "org-mode fontification error"))))
5339 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5340 "Fontify #+ lines and blocks, in the correct ways."
5341 (let ((case-fold-search t))
5342 (if (re-search-forward
5343 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5344 limit t)
5345 (let ((beg (match-beginning 0))
5346 (block-start (match-end 0))
5347 (block-end nil)
5348 (lang (match-string 7))
5349 (beg1 (line-beginning-position 2))
5350 (dc1 (downcase (match-string 2)))
5351 (dc3 (downcase (match-string 3)))
5352 end end1 quoting block-type ovl)
5353 (cond
5354 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5355 ;; a single line of backend-specific content
5356 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5357 (remove-text-properties (match-beginning 0) (match-end 0)
5358 '(display t invisible t intangible t))
5359 (add-text-properties (match-beginning 1) (match-end 3)
5360 '(font-lock-fontified t face org-meta-line))
5361 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5362 '(font-lock-fontified t face org-block))
5363 ; for backend-specific code
5365 ((and (match-end 4) (equal dc3 "+begin"))
5366 ;; Truly a block
5367 (setq block-type (downcase (match-string 5))
5368 quoting (member block-type org-protecting-blocks))
5369 (when (re-search-forward
5370 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5371 nil t) ;; on purpose, we look further than LIMIT
5372 (setq end (min (point-max) (match-end 0))
5373 end1 (min (point-max) (1- (match-beginning 0))))
5374 (setq block-end (match-beginning 0))
5375 (when quoting
5376 (remove-text-properties beg end
5377 '(display t invisible t intangible t)))
5378 (add-text-properties
5379 beg end
5380 '(font-lock-fontified t font-lock-multiline t))
5381 (add-text-properties beg beg1 '(face org-meta-line))
5382 (add-text-properties end1 (min (point-max) (1+ end))
5383 '(face org-meta-line)) ; for end_src
5384 (cond
5385 ((and lang (not (string= lang "")) org-src-fontify-natively)
5386 (org-src-font-lock-fontify-block lang block-start block-end)
5387 ;; remove old background overlays
5388 (mapc (lambda (ov)
5389 (if (eq (overlay-get ov 'face) 'org-block-background)
5390 (delete-overlay ov)))
5391 (overlays-at (/ (+ beg1 block-end) 2)))
5392 ;; add a background overlay
5393 (setq ovl (make-overlay beg1 block-end))
5394 (overlay-put ovl 'face 'org-block-background)
5395 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5396 (quoting
5397 (add-text-properties beg1 (min (point-max) (1+ end1))
5398 '(face org-block))) ; end of source block
5399 ((not org-fontify-quote-and-verse-blocks))
5400 ((string= block-type "quote")
5401 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5402 ((string= block-type "verse")
5403 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5404 (add-text-properties beg beg1 '(face org-block-begin-line))
5405 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5406 '(face org-block-end-line))
5408 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5409 (add-text-properties
5410 beg (match-end 3)
5411 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5412 '(font-lock-fontified t invisible t)
5413 '(font-lock-fontified t face org-document-info-keyword)))
5414 (add-text-properties
5415 (match-beginning 6) (match-end 6)
5416 (if (string-equal dc1 "+title:")
5417 '(font-lock-fontified t face org-document-title)
5418 '(font-lock-fontified t face org-document-info))))
5419 ((or (equal dc1 "+results")
5420 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5421 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5422 "+call:" "+header:" "+headers:" "+name:"))
5423 (and (match-end 4) (equal dc3 "+attr")))
5424 (add-text-properties
5425 beg (match-end 0)
5426 '(font-lock-fontified t face org-meta-line))
5428 ((member dc3 '(" " ""))
5429 (add-text-properties
5430 beg (match-end 0)
5431 '(font-lock-fontified t face font-lock-comment-face)))
5432 ((not (member (char-after beg) '(?\ ?\t)))
5433 ;; just any other in-buffer setting, but not indented
5434 (add-text-properties
5435 beg (match-end 0)
5436 '(font-lock-fontified t face org-meta-line))
5438 (t nil))))))
5440 (defun org-activate-angle-links (limit)
5441 "Run through the buffer and add overlays to links."
5442 (if (re-search-forward org-angle-link-re limit t)
5443 (progn
5444 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5445 (add-text-properties (match-beginning 0) (match-end 0)
5446 (list 'mouse-face 'highlight
5447 'keymap org-mouse-map))
5448 (org-rear-nonsticky-at (match-end 0))
5449 t)))
5451 (defun org-activate-footnote-links (limit)
5452 "Run through the buffer and add overlays to footnotes."
5453 (let ((fn (org-footnote-next-reference-or-definition limit)))
5454 (when fn
5455 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5456 (org-remove-flyspell-overlays-in beg end)
5457 (add-text-properties beg end
5458 (list 'mouse-face 'highlight
5459 'keymap org-mouse-map
5460 'help-echo
5461 (if (= (point-at-bol) beg)
5462 "Footnote definition"
5463 "Footnote reference")
5464 'font-lock-fontified t
5465 'font-lock-multiline t
5466 'face 'org-footnote))))))
5468 (defun org-activate-bracket-links (limit)
5469 "Run through the buffer and add overlays to bracketed links."
5470 (if (re-search-forward org-bracket-link-regexp limit t)
5471 (let* ((help (concat "LINK: "
5472 (org-match-string-no-properties 1)))
5473 ;; FIXME: above we should remove the escapes.
5474 ;; but that requires another match, protecting match data,
5475 ;; a lot of overhead for font-lock.
5476 (ip (org-maybe-intangible
5477 (list 'invisible 'org-link
5478 'keymap org-mouse-map 'mouse-face 'highlight
5479 'font-lock-multiline t 'help-echo help)))
5480 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5481 'font-lock-multiline t 'help-echo help)))
5482 ;; We need to remove the invisible property here. Table narrowing
5483 ;; may have made some of this invisible.
5484 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5485 (remove-text-properties (match-beginning 0) (match-end 0)
5486 '(invisible nil))
5487 (if (match-end 3)
5488 (progn
5489 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5490 (org-rear-nonsticky-at (match-beginning 3))
5491 (add-text-properties (match-beginning 3) (match-end 3) vp)
5492 (org-rear-nonsticky-at (match-end 3))
5493 (add-text-properties (match-end 3) (match-end 0) ip)
5494 (org-rear-nonsticky-at (match-end 0)))
5495 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5496 (org-rear-nonsticky-at (match-beginning 1))
5497 (add-text-properties (match-beginning 1) (match-end 1) vp)
5498 (org-rear-nonsticky-at (match-end 1))
5499 (add-text-properties (match-end 1) (match-end 0) ip)
5500 (org-rear-nonsticky-at (match-end 0)))
5501 t)))
5503 (defun org-activate-dates (limit)
5504 "Run through the buffer and add overlays to dates."
5505 (if (re-search-forward org-tsr-regexp-both limit t)
5506 (progn
5507 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5508 (add-text-properties (match-beginning 0) (match-end 0)
5509 (list 'mouse-face 'highlight
5510 'keymap org-mouse-map))
5511 (org-rear-nonsticky-at (match-end 0))
5512 (when org-display-custom-times
5513 (if (match-end 3)
5514 (org-display-custom-time (match-beginning 3) (match-end 3)))
5515 (org-display-custom-time (match-beginning 1) (match-end 1)))
5516 t)))
5518 (defvar org-target-link-regexp nil
5519 "Regular expression matching radio targets in plain text.")
5520 (make-variable-buffer-local 'org-target-link-regexp)
5521 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5522 "Regular expression matching a link target.")
5523 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5524 "Regular expression matching a radio target.")
5525 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5526 "Regular expression matching any target.")
5528 (defun org-activate-target-links (limit)
5529 "Run through the buffer and add overlays to target matches."
5530 (when org-target-link-regexp
5531 (let ((case-fold-search t))
5532 (if (re-search-forward org-target-link-regexp limit t)
5533 (progn
5534 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5535 (add-text-properties (match-beginning 0) (match-end 0)
5536 (list 'mouse-face 'highlight
5537 'keymap org-mouse-map
5538 'help-echo "Radio target link"
5539 'org-linked-text t))
5540 (org-rear-nonsticky-at (match-end 0))
5541 t)))))
5543 (defun org-update-radio-target-regexp ()
5544 "Find all radio targets in this file and update the regular expression."
5545 (interactive)
5546 (when (memq 'radio org-activate-links)
5547 (setq org-target-link-regexp
5548 (org-make-target-link-regexp (org-all-targets 'radio)))
5549 (org-restart-font-lock)))
5551 (defun org-hide-wide-columns (limit)
5552 (let (s e)
5553 (setq s (text-property-any (point) (or limit (point-max))
5554 'org-cwidth t))
5555 (when s
5556 (setq e (next-single-property-change s 'org-cwidth))
5557 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5558 (goto-char e)
5559 t)))
5561 (defvar org-latex-and-specials-regexp nil
5562 "Regular expression for highlighting export special stuff.")
5563 (defvar org-match-substring-regexp)
5564 (defvar org-match-substring-with-braces-regexp)
5566 ;; This should be with the exporter code, but we also use if for font-locking
5567 (defconst org-export-html-special-string-regexps
5568 '(("\\\\-" . "&shy;")
5569 ("---\\([^-]\\)" . "&mdash;\\1")
5570 ("--\\([^-]\\)" . "&ndash;\\1")
5571 ("\\.\\.\\." . "&hellip;"))
5572 "Regular expressions for special string conversion.")
5575 (defun org-compute-latex-and-specials-regexp ()
5576 "Compute regular expression for stuff treated specially by exporters."
5577 (if (not org-highlight-latex-fragments-and-specials)
5578 (org-set-local 'org-latex-and-specials-regexp nil)
5579 (require 'org-exp)
5580 (let*
5581 ((matchers (plist-get org-format-latex-options :matchers))
5582 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5583 org-latex-regexps)))
5584 (org-export-allow-BIND nil)
5585 (options (org-combine-plists (org-default-export-plist)
5586 (org-infile-export-plist)))
5587 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5588 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5589 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5590 (org-export-html-expand (plist-get options :expand-quoted-html))
5591 (org-export-with-special-strings (plist-get options :special-strings))
5592 (re-sub
5593 (cond
5594 ((equal org-export-with-sub-superscripts '{})
5595 (list org-match-substring-with-braces-regexp))
5596 (org-export-with-sub-superscripts
5597 (list org-match-substring-regexp))))
5598 (re-latex
5599 (if org-export-with-LaTeX-fragments
5600 (mapcar (lambda (x) (nth 1 x)) latexs)))
5601 (re-macros
5602 (if org-export-with-TeX-macros
5603 (list (concat "\\\\"
5604 (regexp-opt
5605 (append
5607 (delq nil
5608 (mapcar 'car-safe
5609 (append org-entities-user
5610 org-entities)))
5611 (if (boundp 'org-latex-entities)
5612 (mapcar (lambda (x)
5613 (or (car-safe x) x))
5614 org-latex-entities)
5615 nil))
5616 'words))) ; FIXME
5618 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5619 (re-special (if org-export-with-special-strings
5620 (mapcar (lambda (x) (car x))
5621 org-export-html-special-string-regexps)))
5622 (re-rest
5623 (delq nil
5624 (list
5625 (if org-export-html-expand "@<[^>\n]+>")
5626 ))))
5627 (org-set-local
5628 'org-latex-and-specials-regexp
5629 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5630 re-rest) "\\|")))))
5632 (defun org-do-latex-and-special-faces (limit)
5633 "Run through the buffer and add overlays to links."
5634 (when org-latex-and-specials-regexp
5635 (let (rtn d)
5636 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5637 limit t))
5638 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5639 'face))
5640 '(org-code org-verbatim underline)))
5641 (progn
5642 (setq rtn t
5643 d (cond ((member (char-after (1+ (match-beginning 0)))
5644 '(?_ ?^)) 1)
5645 (t 0)))
5646 (font-lock-prepend-text-property
5647 (+ d (match-beginning 0)) (match-end 0)
5648 'face 'org-latex-and-export-specials)
5649 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5650 '(font-lock-multiline t)))))
5651 rtn)))
5653 (defun org-restart-font-lock ()
5654 "Restart `font-lock-mode', to force refontification."
5655 (when (and (boundp 'font-lock-mode) font-lock-mode)
5656 (font-lock-mode -1)
5657 (font-lock-mode 1)))
5659 (defun org-all-targets (&optional radio)
5660 "Return a list of all targets in this file.
5661 With optional argument RADIO, only find radio targets."
5662 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5663 rtn)
5664 (save-excursion
5665 (goto-char (point-min))
5666 (while (re-search-forward re nil t)
5667 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5668 rtn)))
5670 (defun org-make-target-link-regexp (targets)
5671 "Make regular expression matching all strings in TARGETS.
5672 The regular expression finds the targets also if there is a line break
5673 between words."
5674 (and targets
5675 (concat
5676 "\\<\\("
5677 (mapconcat
5678 (lambda (x)
5679 (setq x (regexp-quote x))
5680 (while (string-match " +" x)
5681 (setq x (replace-match "\\s-+" t t x)))
5683 targets
5684 "\\|")
5685 "\\)\\>")))
5687 (defun org-activate-tags (limit)
5688 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5689 (progn
5690 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5691 (add-text-properties (match-beginning 1) (match-end 1)
5692 (list 'mouse-face 'highlight
5693 'keymap org-mouse-map))
5694 (org-rear-nonsticky-at (match-end 1))
5695 t)))
5697 (defun org-outline-level ()
5698 "Compute the outline level of the heading at point.
5699 This function assumes that the cursor is at the beginning of a line matched
5700 by `outline-regexp'. Otherwise it returns garbage.
5701 If this is called at a normal headline, the level is the number of stars.
5702 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5703 (save-excursion
5704 (looking-at org-outline-regexp)
5705 (1- (- (match-end 0) (match-beginning 0)))))
5707 (defvar org-font-lock-keywords nil)
5709 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5710 "Regular expression matching a property line.")
5712 (defvar org-font-lock-hook nil
5713 "Functions to be called for special font lock stuff.")
5715 (defvar org-font-lock-set-keywords-hook nil
5716 "Functions that can manipulate `org-font-lock-extra-keywords'.
5717 This is called after `org-font-lock-extra-keywords' is defined, but before
5718 it is installed to be used by font lock. This can be useful if something
5719 needs to be inserted at a specific position in the font-lock sequence.")
5721 (defun org-font-lock-hook (limit)
5722 "Run `org-font-lock-hook' within LIMIT."
5723 (run-hook-with-args 'org-font-lock-hook limit))
5725 (defun org-set-font-lock-defaults ()
5726 "Set font lock defaults for the current buffer."
5727 (let* ((em org-fontify-emphasized-text)
5728 (lk org-activate-links)
5729 (org-font-lock-extra-keywords
5730 (list
5731 ;; Call the hook
5732 '(org-font-lock-hook)
5733 ;; Headlines
5734 `(,(if org-fontify-whole-heading-line
5735 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5736 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5737 (1 (org-get-level-face 1))
5738 (2 (org-get-level-face 2))
5739 (3 (org-get-level-face 3)))
5740 ;; Table lines
5741 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5742 (1 'org-table t))
5743 ;; Table internals
5744 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5745 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5746 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5747 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5748 ;; Drawers
5749 (list org-drawer-regexp '(0 'org-special-keyword t))
5750 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5751 ;; Properties
5752 (list org-property-re
5753 '(1 'org-special-keyword t)
5754 '(3 'org-property-value t))
5755 ;; Links
5756 (unless (or (org-in-src-block-p t) (org-in-fixed-width-region-p))
5757 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5758 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5759 (if (memq 'plain lk) '(org-activate-plain-links))
5760 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5761 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5762 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5763 (if (memq 'footnote lk) '(org-activate-footnote-links)))
5764 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5765 '(org-hide-wide-columns (0 nil append))
5766 ;; TODO keyword
5767 (list (format org-heading-keyword-regexp-format
5768 org-todo-regexp)
5769 '(2 (org-get-todo-face 2) t))
5770 ;; DONE
5771 (if org-fontify-done-headline
5772 (list (format org-heading-keyword-regexp-format
5773 (concat
5774 "\\(?:"
5775 (mapconcat 'regexp-quote org-done-keywords "\\|")
5776 "\\)"))
5777 '(2 'org-headline-done t))
5778 nil)
5779 ;; Priorities
5780 '(org-font-lock-add-priority-faces)
5781 ;; Tags
5782 '(org-font-lock-add-tag-faces)
5783 ;; Special keywords
5784 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5785 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5786 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5787 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5788 ;; Emphasis
5789 (if em
5790 (if (featurep 'xemacs)
5791 '(org-do-emphasis-faces (0 nil append))
5792 '(org-do-emphasis-faces)))
5793 ;; Checkboxes
5794 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5795 1 'org-checkbox prepend)
5796 (if (cdr (assq 'checkbox org-list-automatic-rules))
5797 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5798 (0 (org-get-checkbox-statistics-face) t)))
5799 ;; Description list items
5800 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5801 1 'org-list-dt prepend)
5802 ;; ARCHIVEd headings
5803 (list (concat
5804 org-outline-regexp-bol
5805 "\\(.*:" org-archive-tag ":.*\\)")
5806 '(1 'org-archived prepend))
5807 ;; Specials
5808 '(org-do-latex-and-special-faces)
5809 '(org-fontify-entities)
5810 '(org-raise-scripts)
5811 ;; Code
5812 '(org-activate-code (1 'org-code t))
5813 ;; COMMENT
5814 (list (format org-heading-keyword-regexp-format
5815 (concat "\\("
5816 org-comment-string "\\|" org-quote-string
5817 "\\)"))
5818 '(2 'org-special-keyword t))
5819 ;; Blocks and meta lines
5820 '(org-fontify-meta-lines-and-blocks)
5822 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5823 (run-hooks 'org-font-lock-set-keywords-hook)
5824 ;; Now set the full font-lock-keywords
5825 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5826 (org-set-local 'font-lock-defaults
5827 '(org-font-lock-keywords t nil nil backward-paragraph))
5828 (kill-local-variable 'font-lock-keywords) nil))
5830 (defun org-toggle-pretty-entities ()
5831 "Toggle the composition display of entities as UTF8 characters."
5832 (interactive)
5833 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5834 (org-restart-font-lock)
5835 (if org-pretty-entities
5836 (message "Entities are displayed as UTF8 characters")
5837 (save-restriction
5838 (widen)
5839 (org-decompose-region (point-min) (point-max))
5840 (message "Entities are displayed plain"))))
5842 (defvar org-custom-properties-overlays nil
5843 "List of overlays used for custom properties.")
5844 (make-variable-buffer-local 'org-custom-properties-overlays)
5846 (defun org-toggle-custom-properties-visibility ()
5847 "Display or hide properties in `org-custom-properties'."
5848 (interactive)
5849 (if org-custom-properties-overlays
5850 (progn (mapc 'delete-overlay org-custom-properties-overlays)
5851 (setq org-custom-properties-overlays nil))
5852 (unless (not org-custom-properties)
5853 (save-excursion
5854 (save-restriction
5855 (widen)
5856 (goto-char (point-min))
5857 (while (re-search-forward org-property-re nil t)
5858 (mapc (lambda(p)
5859 (when (equal p (substring (match-string 1) 1 -1))
5860 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
5861 (overlay-put o 'invisible t)
5862 (overlay-put o 'org-custom-property t)
5863 (push o org-custom-properties-overlays))))
5864 org-custom-properties)))))))
5866 (defun org-fontify-entities (limit)
5867 "Find an entity to fontify."
5868 (let (ee)
5869 (when org-pretty-entities
5870 (catch 'match
5871 (while (re-search-forward
5872 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
5873 limit t)
5874 (if (and (not (org-in-indented-comment-line))
5875 (setq ee (org-entity-get (match-string 1)))
5876 (= (length (nth 6 ee)) 1))
5877 (let*
5878 ((end (if (equal (match-string 2) "{}")
5879 (match-end 2)
5880 (match-end 1))))
5881 (add-text-properties
5882 (match-beginning 0) end
5883 (list 'font-lock-fontified t))
5884 (compose-region (match-beginning 0) end
5885 (nth 6 ee) nil)
5886 (backward-char 1)
5887 (throw 'match t))))
5888 nil))))
5890 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5891 "Fontify string S like in Org-mode."
5892 (with-temp-buffer
5893 (insert s)
5894 (let ((org-odd-levels-only odd-levels))
5895 (org-mode)
5896 (font-lock-fontify-buffer)
5897 (buffer-string))))
5899 (defvar org-m nil)
5900 (defvar org-l nil)
5901 (defvar org-f nil)
5902 (defun org-get-level-face (n)
5903 "Get the right face for match N in font-lock matching of headlines."
5904 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5905 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5906 (if org-cycle-level-faces
5907 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5908 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5909 (cond
5910 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5911 ((eq n 2) org-f)
5912 (t (if org-level-color-stars-only nil org-f))))
5915 (defun org-get-todo-face (kwd)
5916 "Get the right face for a TODO keyword KWD.
5917 If KWD is a number, get the corresponding match group."
5918 (if (numberp kwd) (setq kwd (match-string kwd)))
5919 (or (org-face-from-face-or-color
5920 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5921 (and (member kwd org-done-keywords) 'org-done)
5922 'org-todo))
5924 (defun org-face-from-face-or-color (context inherit face-or-color)
5925 "Create a face list that inherits INHERIT, but sets the foreground color.
5926 When FACE-OR-COLOR is not a string, just return it."
5927 (if (stringp face-or-color)
5928 (list :inherit inherit
5929 (cdr (assoc context org-faces-easy-properties))
5930 face-or-color)
5931 face-or-color))
5933 (defun org-font-lock-add-tag-faces (limit)
5934 "Add the special tag faces."
5935 (when (and org-tag-faces org-tags-special-faces-re)
5936 (while (re-search-forward org-tags-special-faces-re limit t)
5937 (add-text-properties (match-beginning 1) (match-end 1)
5938 (list 'face (org-get-tag-face 1)
5939 'font-lock-fontified t))
5940 (backward-char 1))))
5942 (defun org-font-lock-add-priority-faces (limit)
5943 "Add the special priority faces."
5944 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5945 (when (save-match-data (org-at-heading-p))
5946 (add-text-properties
5947 (match-beginning 0) (match-end 0)
5948 (list 'face (or (org-face-from-face-or-color
5949 'priority 'org-special-keyword
5950 (cdr (assoc (char-after (match-beginning 1))
5951 org-priority-faces)))
5952 'org-special-keyword)
5953 'font-lock-fontified t)))))
5955 (defun org-get-tag-face (kwd)
5956 "Get the right face for a TODO keyword KWD.
5957 If KWD is a number, get the corresponding match group."
5958 (if (numberp kwd) (setq kwd (match-string kwd)))
5959 (or (org-face-from-face-or-color
5960 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5961 'org-tag))
5963 (defun org-unfontify-region (beg end &optional maybe_loudly)
5964 "Remove fontification and activation overlays from links."
5965 (font-lock-default-unfontify-region beg end)
5966 (let* ((buffer-undo-list t)
5967 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5968 (inhibit-modification-hooks t)
5969 deactivate-mark buffer-file-name buffer-file-truename)
5970 (org-decompose-region beg end)
5971 (remove-text-properties beg end
5972 '(mouse-face t keymap t org-linked-text t
5973 invisible t intangible t
5974 org-no-flyspell t org-emphasis t))
5975 (org-remove-font-lock-display-properties beg end)))
5977 (defconst org-script-display '(((raise -0.3) (height 0.7))
5978 ((raise 0.3) (height 0.7))
5979 ((raise -0.5))
5980 ((raise 0.5)))
5981 "Display properties for showing superscripts and subscripts.")
5983 (defun org-remove-font-lock-display-properties (beg end)
5984 "Remove specific display properties that have been added by font lock.
5985 The will remove the raise properties that are used to show superscripts
5986 and subscripts."
5987 (let (next prop)
5988 (while (< beg end)
5989 (setq next (next-single-property-change beg 'display nil end)
5990 prop (get-text-property beg 'display))
5991 (if (member prop org-script-display)
5992 (put-text-property beg next 'display nil))
5993 (setq beg next))))
5995 (defun org-raise-scripts (limit)
5996 "Add raise properties to sub/superscripts."
5997 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
5998 (if (re-search-forward
5999 (if (eq org-use-sub-superscripts t)
6000 org-match-substring-regexp
6001 org-match-substring-with-braces-regexp)
6002 limit t)
6003 (let* ((pos (point)) table-p comment-p
6004 (mpos (match-beginning 3))
6005 (emph-p (get-text-property mpos 'org-emphasis))
6006 (link-p (get-text-property mpos 'mouse-face))
6007 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6008 (goto-char (point-at-bol))
6009 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6010 comment-p (org-looking-at-p "[ \t]*#"))
6011 (goto-char pos)
6012 ;; FIXME: Should we go back one character here, for a_b^c
6013 ;; (goto-char (1- pos)) ;????????????????????
6014 (if (or comment-p emph-p link-p keyw-p)
6016 (put-text-property (match-beginning 3) (match-end 0)
6017 'display
6018 (if (equal (char-after (match-beginning 2)) ?^)
6019 (nth (if table-p 3 1) org-script-display)
6020 (nth (if table-p 2 0) org-script-display)))
6021 (add-text-properties (match-beginning 2) (match-end 2)
6022 (list 'invisible t
6023 'org-dwidth t 'org-dwidth-n 1))
6024 (if (and (eq (char-after (match-beginning 3)) ?{)
6025 (eq (char-before (match-end 3)) ?}))
6026 (progn
6027 (add-text-properties
6028 (match-beginning 3) (1+ (match-beginning 3))
6029 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6030 (add-text-properties
6031 (1- (match-end 3)) (match-end 3)
6032 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6033 t)))))
6035 ;;;; Visibility cycling, including org-goto and indirect buffer
6037 ;;; Cycling
6039 (defvar org-cycle-global-status nil)
6040 (make-variable-buffer-local 'org-cycle-global-status)
6041 (defvar org-cycle-subtree-status nil)
6042 (make-variable-buffer-local 'org-cycle-subtree-status)
6044 (defvar org-inlinetask-min-level)
6046 ;;;###autoload
6047 (defun org-cycle (&optional arg)
6048 "TAB-action and visibility cycling for Org-mode.
6050 This is the command invoked in Org-mode by the TAB key. Its main purpose
6051 is outline visibility cycling, but it also invokes other actions
6052 in special contexts.
6054 - When this function is called with a prefix argument, rotate the entire
6055 buffer through 3 states (global cycling)
6056 1. OVERVIEW: Show only top-level headlines.
6057 2. CONTENTS: Show all headlines of all levels, but no body text.
6058 3. SHOW ALL: Show everything.
6059 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6060 determined by the variable `org-startup-folded', and by any VISIBILITY
6061 properties in the buffer.
6062 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6063 including any drawers.
6065 - When inside a table, re-align the table and move to the next field.
6067 - When point is at the beginning of a headline, rotate the subtree started
6068 by this line through 3 different states (local cycling)
6069 1. FOLDED: Only the main headline is shown.
6070 2. CHILDREN: The main headline and the direct children are shown.
6071 From this state, you can move to one of the children
6072 and zoom in further.
6073 3. SUBTREE: Show the entire subtree, including body text.
6074 If there is no subtree, switch directly from CHILDREN to FOLDED.
6076 - When point is at the beginning of an empty headline and the variable
6077 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6078 of the headline by demoting and promoting it to likely levels. This
6079 speeds up creation document structure by pressing TAB once or several
6080 times right after creating a new headline.
6082 - When there is a numeric prefix, go up to a heading with level ARG, do
6083 a `show-subtree' and return to the previous cursor position. If ARG
6084 is negative, go up that many levels.
6086 - When point is not at the beginning of a headline, execute the global
6087 binding for TAB, which is re-indenting the line. See the option
6088 `org-cycle-emulate-tab' for details.
6090 - Special case: if point is at the beginning of the buffer and there is
6091 no headline in line 1, this function will act as if called with prefix arg
6092 (C-u TAB, same as S-TAB) also when called without prefix arg.
6093 But only if also the variable `org-cycle-global-at-bob' is t."
6094 (interactive "P")
6095 (org-load-modules-maybe)
6096 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6097 (and org-cycle-level-after-item/entry-creation
6098 (or (org-cycle-level)
6099 (org-cycle-item-indentation))))
6100 (let* ((limit-level
6101 (or org-cycle-max-level
6102 (and (boundp 'org-inlinetask-min-level)
6103 org-inlinetask-min-level
6104 (1- org-inlinetask-min-level))))
6105 (nstars (and limit-level
6106 (if org-odd-levels-only
6107 (and limit-level (1- (* limit-level 2)))
6108 limit-level)))
6109 (org-outline-regexp
6110 (if (not (derived-mode-p 'org-mode))
6111 outline-regexp
6112 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6113 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6114 (not (looking-at org-outline-regexp))))
6115 (org-cycle-hook
6116 (if bob-special
6117 (delq 'org-optimize-window-after-visibility-change
6118 (copy-sequence org-cycle-hook))
6119 org-cycle-hook))
6120 (pos (point)))
6122 (if (or bob-special (equal arg '(4)))
6123 ;; special case: use global cycling
6124 (setq arg t))
6126 (cond
6128 ((equal arg '(16))
6129 (setq last-command 'dummy)
6130 (org-set-startup-visibility)
6131 (message "Startup visibility, plus VISIBILITY properties"))
6133 ((equal arg '(64))
6134 (show-all)
6135 (message "Entire buffer visible, including drawers"))
6137 ;; Table: enter it or move to the next field.
6138 ((org-at-table-p 'any)
6139 (if (org-at-table.el-p)
6140 (message "Use C-c ' to edit table.el tables")
6141 (if arg (org-table-edit-field t)
6142 (org-table-justify-field-maybe)
6143 (call-interactively 'org-table-next-field))))
6145 ((run-hook-with-args-until-success
6146 'org-tab-after-check-for-table-hook))
6148 ;; Global cycling: delegate to `org-cycle-internal-global'.
6149 ((eq arg t) (org-cycle-internal-global))
6151 ;; Drawers: delegate to `org-flag-drawer'.
6152 ((and org-drawers org-drawer-regexp
6153 (save-excursion
6154 (beginning-of-line 1)
6155 (looking-at org-drawer-regexp)))
6156 (org-flag-drawer ; toggle block visibility
6157 (not (get-char-property (match-end 0) 'invisible))))
6159 ;; Show-subtree, ARG levels up from here.
6160 ((integerp arg)
6161 (save-excursion
6162 (org-back-to-heading)
6163 (outline-up-heading (if (< arg 0) (- arg)
6164 (- (funcall outline-level) arg)))
6165 (org-show-subtree)))
6167 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6168 ((and (featurep 'org-inlinetask)
6169 (org-inlinetask-at-task-p)
6170 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6171 (org-inlinetask-toggle-visibility))
6173 ((org-try-cdlatex-tab))
6175 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6176 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6177 (save-excursion (beginning-of-line 1)
6178 (looking-at org-outline-regexp)))
6179 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6180 (org-cycle-internal-local))
6182 ;; From there: TAB emulation and template completion.
6183 (buffer-read-only (org-back-to-heading))
6185 ((run-hook-with-args-until-success
6186 'org-tab-after-check-for-cycling-hook))
6188 ((org-try-structure-completion))
6190 ((run-hook-with-args-until-success
6191 'org-tab-before-tab-emulation-hook))
6193 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6194 (or (not (bolp))
6195 (not (looking-at org-outline-regexp))))
6196 (call-interactively (global-key-binding "\t")))
6198 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6199 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6200 (or (and (eq org-cycle-emulate-tab 'white)
6201 (= (match-end 0) (point-at-eol)))
6202 (and (eq org-cycle-emulate-tab 'whitestart)
6203 (>= (match-end 0) pos))))
6205 (eq org-cycle-emulate-tab t))
6206 (call-interactively (global-key-binding "\t")))
6208 (t (save-excursion
6209 (org-back-to-heading)
6210 (org-cycle)))))))
6212 (defun org-cycle-internal-global ()
6213 "Do the global cycling action."
6214 ;; Hack to avoid display of messages for .org attachments in Gnus
6215 (let ((ga (string-match "\\*fontification" (buffer-name))))
6216 (cond
6217 ((and (eq last-command this-command)
6218 (eq org-cycle-global-status 'overview))
6219 ;; We just created the overview - now do table of contents
6220 ;; This can be slow in very large buffers, so indicate action
6221 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6222 (unless ga (message "CONTENTS..."))
6223 (org-content)
6224 (unless ga (message "CONTENTS...done"))
6225 (setq org-cycle-global-status 'contents)
6226 (run-hook-with-args 'org-cycle-hook 'contents))
6228 ((and (eq last-command this-command)
6229 (eq org-cycle-global-status 'contents))
6230 ;; We just showed the table of contents - now show everything
6231 (run-hook-with-args 'org-pre-cycle-hook 'all)
6232 (show-all)
6233 (unless ga (message "SHOW ALL"))
6234 (setq org-cycle-global-status 'all)
6235 (run-hook-with-args 'org-cycle-hook 'all))
6238 ;; Default action: go to overview
6239 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6240 (org-overview)
6241 (unless ga (message "OVERVIEW"))
6242 (setq org-cycle-global-status 'overview)
6243 (run-hook-with-args 'org-cycle-hook 'overview)))))
6245 (defun org-cycle-internal-local ()
6246 "Do the local cycling action."
6247 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6248 ;; First, determine end of headline (EOH), end of subtree or item
6249 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6250 (save-excursion
6251 (if (org-at-item-p)
6252 (progn
6253 (beginning-of-line)
6254 (setq struct (org-list-struct))
6255 (setq eoh (point-at-eol))
6256 (setq eos (org-list-get-item-end-before-blank (point) struct))
6257 (setq has-children (org-list-has-child-p (point) struct)))
6258 (org-back-to-heading)
6259 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6260 (setq eos (save-excursion
6261 (org-end-of-subtree t)
6262 (unless (eobp)
6263 (skip-chars-forward " \t\n"))
6264 (if (eobp) (point) (1- (point)))))
6265 (setq has-children
6266 (or (save-excursion
6267 (let ((level (funcall outline-level)))
6268 (outline-next-heading)
6269 (and (org-at-heading-p t)
6270 (> (funcall outline-level) level))))
6271 (save-excursion
6272 (org-list-search-forward (org-item-beginning-re) eos t)))))
6273 ;; Determine end invisible part of buffer (EOL)
6274 (beginning-of-line 2)
6275 ;; XEmacs doesn't have `next-single-char-property-change'
6276 (if (featurep 'xemacs)
6277 (while (and (not (eobp)) ;; this is like `next-line'
6278 (get-char-property (1- (point)) 'invisible))
6279 (beginning-of-line 2))
6280 (while (and (not (eobp)) ;; this is like `next-line'
6281 (get-char-property (1- (point)) 'invisible))
6282 (goto-char (next-single-char-property-change (point) 'invisible))
6283 (and (eolp) (beginning-of-line 2))))
6284 (setq eol (point)))
6285 ;; Find out what to do next and set `this-command'
6286 (cond
6287 ((= eos eoh)
6288 ;; Nothing is hidden behind this heading
6289 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6290 (message "EMPTY ENTRY")
6291 (setq org-cycle-subtree-status nil)
6292 (save-excursion
6293 (goto-char eos)
6294 (outline-next-heading)
6295 (if (outline-invisible-p) (org-flag-heading nil))))
6296 ((and (or (>= eol eos)
6297 (not (string-match "\\S-" (buffer-substring eol eos))))
6298 (or has-children
6299 (not (setq children-skipped
6300 org-cycle-skip-children-state-if-no-children))))
6301 ;; Entire subtree is hidden in one line: children view
6302 (run-hook-with-args 'org-pre-cycle-hook 'children)
6303 (if (org-at-item-p)
6304 (org-list-set-item-visibility (point-at-bol) struct 'children)
6305 (org-show-entry)
6306 (org-with-limited-levels (show-children))
6307 ;; FIXME: This slows down the func way too much.
6308 ;; How keep drawers hidden in subtree anyway?
6309 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6310 ;; (org-cycle-hide-drawers 'subtree))
6312 ;; Fold every list in subtree to top-level items.
6313 (when (eq org-cycle-include-plain-lists 'integrate)
6314 (save-excursion
6315 (org-back-to-heading)
6316 (while (org-list-search-forward (org-item-beginning-re) eos t)
6317 (beginning-of-line 1)
6318 (let* ((struct (org-list-struct))
6319 (prevs (org-list-prevs-alist struct))
6320 (end (org-list-get-bottom-point struct)))
6321 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6322 (org-list-get-all-items (point) struct prevs))
6323 (goto-char end))))))
6324 (message "CHILDREN")
6325 (save-excursion
6326 (goto-char eos)
6327 (outline-next-heading)
6328 (if (outline-invisible-p) (org-flag-heading nil)))
6329 (setq org-cycle-subtree-status 'children)
6330 (run-hook-with-args 'org-cycle-hook 'children))
6331 ((or children-skipped
6332 (and (eq last-command this-command)
6333 (eq org-cycle-subtree-status 'children)))
6334 ;; We just showed the children, or no children are there,
6335 ;; now show everything.
6336 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6337 (outline-flag-region eoh eos nil)
6338 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6339 (setq org-cycle-subtree-status 'subtree)
6340 (run-hook-with-args 'org-cycle-hook 'subtree))
6342 ;; Default action: hide the subtree.
6343 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6344 (outline-flag-region eoh eos t)
6345 (message "FOLDED")
6346 (setq org-cycle-subtree-status 'folded)
6347 (run-hook-with-args 'org-cycle-hook 'folded)))))
6349 ;;;###autoload
6350 (defun org-global-cycle (&optional arg)
6351 "Cycle the global visibility. For details see `org-cycle'.
6352 With \\[universal-argument] prefix arg, switch to startup visibility.
6353 With a numeric prefix, show all headlines up to that level."
6354 (interactive "P")
6355 (let ((org-cycle-include-plain-lists
6356 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6357 (cond
6358 ((integerp arg)
6359 (show-all)
6360 (hide-sublevels arg)
6361 (setq org-cycle-global-status 'contents))
6362 ((equal arg '(4))
6363 (org-set-startup-visibility)
6364 (message "Startup visibility, plus VISIBILITY properties."))
6366 (org-cycle '(4))))))
6368 (defun org-set-startup-visibility ()
6369 "Set the visibility required by startup options and properties."
6370 (cond
6371 ((eq org-startup-folded t)
6372 (org-cycle '(4)))
6373 ((eq org-startup-folded 'content)
6374 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6375 (org-cycle '(4)) (org-cycle '(4)))))
6376 (unless (eq org-startup-folded 'showeverything)
6377 (if org-hide-block-startup (org-hide-block-all))
6378 (org-set-visibility-according-to-property 'no-cleanup)
6379 (org-cycle-hide-archived-subtrees 'all)
6380 (org-cycle-hide-drawers 'all)
6381 (org-cycle-show-empty-lines t)))
6383 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6384 "Switch subtree visibilities according to :VISIBILITY: property."
6385 (interactive)
6386 (let (org-show-entry-below state)
6387 (save-excursion
6388 (goto-char (point-min))
6389 (while (re-search-forward
6390 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6391 nil t)
6392 (setq state (match-string 1))
6393 (save-excursion
6394 (org-back-to-heading t)
6395 (hide-subtree)
6396 (org-reveal)
6397 (cond
6398 ((equal state '("fold" "folded"))
6399 (hide-subtree))
6400 ((equal state "children")
6401 (org-show-hidden-entry)
6402 (show-children))
6403 ((equal state "content")
6404 (save-excursion
6405 (save-restriction
6406 (org-narrow-to-subtree)
6407 (org-content))))
6408 ((member state '("all" "showall"))
6409 (show-subtree)))))
6410 (unless no-cleanup
6411 (org-cycle-hide-archived-subtrees 'all)
6412 (org-cycle-hide-drawers 'all)
6413 (org-cycle-show-empty-lines 'all)))))
6415 ;; This function uses outline-regexp instead of the more fundamental
6416 ;; org-outline-regexp so that org-cycle-global works outside of Org
6417 ;; buffers, where outline-regexp is needed.
6418 (defun org-overview ()
6419 "Switch to overview mode, showing only top-level headlines.
6420 Really, this shows all headlines with level equal or greater than the level
6421 of the first headline in the buffer. This is important, because if the
6422 first headline is not level one, then (hide-sublevels 1) gives confusing
6423 results."
6424 (interactive)
6425 (let ((level (save-excursion
6426 (goto-char (point-min))
6427 (if (re-search-forward (concat "^" outline-regexp) nil t)
6428 (progn
6429 (goto-char (match-beginning 0))
6430 (funcall outline-level))))))
6431 (and level (hide-sublevels level))))
6433 (defun org-content (&optional arg)
6434 "Show all headlines in the buffer, like a table of contents.
6435 With numerical argument N, show content up to level N."
6436 (interactive "P")
6437 (save-excursion
6438 ;; Visit all headings and show their offspring
6439 (and (integerp arg) (org-overview))
6440 (goto-char (point-max))
6441 (catch 'exit
6442 (while (and (progn (condition-case nil
6443 (outline-previous-visible-heading 1)
6444 (error (goto-char (point-min))))
6446 (looking-at org-outline-regexp))
6447 (if (integerp arg)
6448 (show-children (1- arg))
6449 (show-branches))
6450 (if (bobp) (throw 'exit nil))))))
6453 (defun org-optimize-window-after-visibility-change (state)
6454 "Adjust the window after a change in outline visibility.
6455 This function is the default value of the hook `org-cycle-hook'."
6456 (when (get-buffer-window (current-buffer))
6457 (cond
6458 ((eq state 'content) nil)
6459 ((eq state 'all) nil)
6460 ((eq state 'folded) nil)
6461 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6462 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6464 (defun org-remove-empty-overlays-at (pos)
6465 "Remove outline overlays that do not contain non-white stuff."
6466 (mapc
6467 (lambda (o)
6468 (and (eq 'outline (overlay-get o 'invisible))
6469 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6470 (overlay-end o))))
6471 (delete-overlay o)))
6472 (overlays-at pos)))
6474 (defun org-clean-visibility-after-subtree-move ()
6475 "Fix visibility issues after moving a subtree."
6476 ;; First, find a reasonable region to look at:
6477 ;; Start two siblings above, end three below
6478 (let* ((beg (save-excursion
6479 (and (org-get-last-sibling)
6480 (org-get-last-sibling))
6481 (point)))
6482 (end (save-excursion
6483 (and (org-get-next-sibling)
6484 (org-get-next-sibling)
6485 (org-get-next-sibling))
6486 (if (org-at-heading-p)
6487 (point-at-eol)
6488 (point))))
6489 (level (looking-at "\\*+"))
6490 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6491 (save-excursion
6492 (save-restriction
6493 (narrow-to-region beg end)
6494 (when re
6495 ;; Properly fold already folded siblings
6496 (goto-char (point-min))
6497 (while (re-search-forward re nil t)
6498 (if (and (not (outline-invisible-p))
6499 (save-excursion
6500 (goto-char (point-at-eol)) (outline-invisible-p)))
6501 (hide-entry))))
6502 (org-cycle-show-empty-lines 'overview)
6503 (org-cycle-hide-drawers 'overview)))))
6505 (defun org-cycle-show-empty-lines (state)
6506 "Show empty lines above all visible headlines.
6507 The region to be covered depends on STATE when called through
6508 `org-cycle-hook'. Lisp program can use t for STATE to get the
6509 entire buffer covered. Note that an empty line is only shown if there
6510 are at least `org-cycle-separator-lines' empty lines before the headline."
6511 (when (not (= org-cycle-separator-lines 0))
6512 (save-excursion
6513 (let* ((n (abs org-cycle-separator-lines))
6514 (re (cond
6515 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6516 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6517 (t (let ((ns (number-to-string (- n 2))))
6518 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6519 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6520 beg end b e)
6521 (cond
6522 ((memq state '(overview contents t))
6523 (setq beg (point-min) end (point-max)))
6524 ((memq state '(children folded))
6525 (setq beg (point) end (progn (org-end-of-subtree t t)
6526 (beginning-of-line 2)
6527 (point)))))
6528 (when beg
6529 (goto-char beg)
6530 (while (re-search-forward re end t)
6531 (unless (get-char-property (match-end 1) 'invisible)
6532 (setq e (match-end 1))
6533 (if (< org-cycle-separator-lines 0)
6534 (setq b (save-excursion
6535 (goto-char (match-beginning 0))
6536 (org-back-over-empty-lines)
6537 (if (save-excursion
6538 (goto-char (max (point-min) (1- (point))))
6539 (org-at-heading-p))
6540 (1- (point))
6541 (point))))
6542 (setq b (match-beginning 1)))
6543 (outline-flag-region b e nil)))))))
6544 ;; Never hide empty lines at the end of the file.
6545 (save-excursion
6546 (goto-char (point-max))
6547 (outline-previous-heading)
6548 (outline-end-of-heading)
6549 (if (and (looking-at "[ \t\n]+")
6550 (= (match-end 0) (point-max)))
6551 (outline-flag-region (point) (match-end 0) nil))))
6553 (defun org-show-empty-lines-in-parent ()
6554 "Move to the parent and re-show empty lines before visible headlines."
6555 (save-excursion
6556 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6557 (org-cycle-show-empty-lines context))))
6559 (defun org-files-list ()
6560 "Return `org-agenda-files' list, plus all open org-mode files.
6561 This is useful for operations that need to scan all of a user's
6562 open and agenda-wise Org files."
6563 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6564 (dolist (buf (buffer-list))
6565 (with-current-buffer buf
6566 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6567 (let ((file (expand-file-name (buffer-file-name))))
6568 (unless (member file files)
6569 (push file files))))))
6570 files))
6572 (defsubst org-entry-beginning-position ()
6573 "Return the beginning position of the current entry."
6574 (save-excursion (outline-back-to-heading t) (point)))
6576 (defsubst org-entry-end-position ()
6577 "Return the end position of the current entry."
6578 (save-excursion (outline-next-heading) (point)))
6580 (defun org-cycle-hide-drawers (state)
6581 "Re-hide all drawers after a visibility state change."
6582 (when (and (derived-mode-p 'org-mode)
6583 (not (memq state '(overview folded contents))))
6584 (save-excursion
6585 (let* ((globalp (memq state '(contents all)))
6586 (beg (if globalp (point-min) (point)))
6587 (end (if globalp (point-max)
6588 (if (eq state 'children)
6589 (save-excursion (outline-next-heading) (point))
6590 (org-end-of-subtree t)))))
6591 (goto-char beg)
6592 (while (re-search-forward org-drawer-regexp end t)
6593 (org-flag-drawer t))))))
6595 (defun org-flag-drawer (flag)
6596 "When FLAG is non-nil, hide the drawer we are within.
6597 Otherwise make it visible."
6598 (save-excursion
6599 (beginning-of-line 1)
6600 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6601 (let ((b (match-end 0)))
6602 (if (re-search-forward
6603 "^[ \t]*:END:"
6604 (save-excursion (outline-next-heading) (point)) t)
6605 (outline-flag-region b (point-at-eol) flag)
6606 (error ":END: line missing at position %s" b))))))
6608 (defun org-subtree-end-visible-p ()
6609 "Is the end of the current subtree visible?"
6610 (pos-visible-in-window-p
6611 (save-excursion (org-end-of-subtree t) (point))))
6613 (defun org-first-headline-recenter (&optional N)
6614 "Move cursor to the first headline and recenter the headline.
6615 Optional argument N means put the headline into the Nth line of the window."
6616 (goto-char (point-min))
6617 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6618 (beginning-of-line)
6619 (recenter (prefix-numeric-value N))))
6621 ;;; Saving and restoring visibility
6623 (defun org-outline-overlay-data (&optional use-markers)
6624 "Return a list of the locations of all outline overlays.
6625 These are overlays with the `invisible' property value `outline'.
6626 The return value is a list of cons cells, with start and stop
6627 positions for each overlay.
6628 If USE-MARKERS is set, return the positions as markers."
6629 (let (beg end)
6630 (save-excursion
6631 (save-restriction
6632 (widen)
6633 (delq nil
6634 (mapcar (lambda (o)
6635 (when (eq (overlay-get o 'invisible) 'outline)
6636 (setq beg (overlay-start o)
6637 end (overlay-end o))
6638 (and beg end (> end beg)
6639 (if use-markers
6640 (cons (move-marker (make-marker) beg)
6641 (move-marker (make-marker) end))
6642 (cons beg end)))))
6643 (overlays-in (point-min) (point-max))))))))
6645 (defun org-set-outline-overlay-data (data)
6646 "Create visibility overlays for all positions in DATA.
6647 DATA should have been made by `org-outline-overlay-data'."
6648 (let (o)
6649 (save-excursion
6650 (save-restriction
6651 (widen)
6652 (show-all)
6653 (mapc (lambda (c)
6654 (outline-flag-region (car c) (cdr c) t))
6655 data)))))
6657 ;;; Folding of blocks
6659 (defvar org-hide-block-overlays nil
6660 "Overlays hiding blocks.")
6661 (make-variable-buffer-local 'org-hide-block-overlays)
6663 (defun org-block-map (function &optional start end)
6664 "Call FUNCTION at the head of all source blocks in the current buffer.
6665 Optional arguments START and END can be used to limit the range."
6666 (let ((start (or start (point-min)))
6667 (end (or end (point-max))))
6668 (save-excursion
6669 (goto-char start)
6670 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6671 (save-excursion
6672 (save-match-data
6673 (goto-char (match-beginning 0))
6674 (funcall function)))))))
6676 (defun org-hide-block-toggle-all ()
6677 "Toggle the visibility of all blocks in the current buffer."
6678 (org-block-map #'org-hide-block-toggle))
6680 (defun org-hide-block-all ()
6681 "Fold all blocks in the current buffer."
6682 (interactive)
6683 (org-show-block-all)
6684 (org-block-map #'org-hide-block-toggle-maybe))
6686 (defun org-show-block-all ()
6687 "Unfold all blocks in the current buffer."
6688 (interactive)
6689 (mapc 'delete-overlay org-hide-block-overlays)
6690 (setq org-hide-block-overlays nil))
6692 (defun org-hide-block-toggle-maybe ()
6693 "Toggle visibility of block at point."
6694 (interactive)
6695 (let ((case-fold-search t))
6696 (if (save-excursion
6697 (beginning-of-line 1)
6698 (looking-at org-block-regexp))
6699 (progn (org-hide-block-toggle)
6700 t) ;; to signal that we took action
6701 nil))) ;; to signal that we did not
6703 (defun org-hide-block-toggle (&optional force)
6704 "Toggle the visibility of the current block."
6705 (interactive)
6706 (save-excursion
6707 (beginning-of-line)
6708 (if (re-search-forward org-block-regexp nil t)
6709 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6710 (end (match-end 0)) ;; end of entire body
6712 (if (memq t (mapcar (lambda (overlay)
6713 (eq (overlay-get overlay 'invisible)
6714 'org-hide-block))
6715 (overlays-at start)))
6716 (if (or (not force) (eq force 'off))
6717 (mapc (lambda (ov)
6718 (when (member ov org-hide-block-overlays)
6719 (setq org-hide-block-overlays
6720 (delq ov org-hide-block-overlays)))
6721 (when (eq (overlay-get ov 'invisible)
6722 'org-hide-block)
6723 (delete-overlay ov)))
6724 (overlays-at start)))
6725 (setq ov (make-overlay start end))
6726 (overlay-put ov 'invisible 'org-hide-block)
6727 ;; make the block accessible to isearch
6728 (overlay-put
6729 ov 'isearch-open-invisible
6730 (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 (push ov org-hide-block-overlays)))
6738 (error "Not looking at a source block"))))
6740 ;; org-tab-after-check-for-cycling-hook
6741 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6742 ;; Remove overlays when changing major mode
6743 (add-hook 'org-mode-hook
6744 (lambda () (org-add-hook 'change-major-mode-hook
6745 'org-show-block-all 'append 'local)))
6747 ;;; Org-goto
6749 (defvar org-goto-window-configuration nil)
6750 (defvar org-goto-marker nil)
6751 (defvar org-goto-map
6752 (let ((map (make-sparse-keymap)))
6753 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6754 (while (setq cmd (pop cmds))
6755 (substitute-key-definition cmd cmd map global-map)))
6756 (suppress-keymap map)
6757 (org-defkey map "\C-m" 'org-goto-ret)
6758 (org-defkey map [(return)] 'org-goto-ret)
6759 (org-defkey map [(left)] 'org-goto-left)
6760 (org-defkey map [(right)] 'org-goto-right)
6761 (org-defkey map [(control ?g)] 'org-goto-quit)
6762 (org-defkey map "\C-i" 'org-cycle)
6763 (org-defkey map [(tab)] 'org-cycle)
6764 (org-defkey map [(down)] 'outline-next-visible-heading)
6765 (org-defkey map [(up)] 'outline-previous-visible-heading)
6766 (if org-goto-auto-isearch
6767 (if (fboundp 'define-key-after)
6768 (define-key-after map [t] 'org-goto-local-auto-isearch)
6769 nil)
6770 (org-defkey map "q" 'org-goto-quit)
6771 (org-defkey map "n" 'outline-next-visible-heading)
6772 (org-defkey map "p" 'outline-previous-visible-heading)
6773 (org-defkey map "f" 'outline-forward-same-level)
6774 (org-defkey map "b" 'outline-backward-same-level)
6775 (org-defkey map "u" 'outline-up-heading))
6776 (org-defkey map "/" 'org-occur)
6777 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6778 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6779 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6780 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6781 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6782 map))
6784 (defconst org-goto-help
6785 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6786 RET=jump to location [Q]uit and return to previous location
6787 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6789 (defvar org-goto-start-pos) ; dynamically scoped parameter
6791 ;; FIXME: Docstring does not mention both interfaces
6792 (defun org-goto (&optional alternative-interface)
6793 "Look up a different location in the current file, keeping current visibility.
6795 When you want look-up or go to a different location in a
6796 document, the fastest way is often to fold the entire buffer and
6797 then dive into the tree. This method has the disadvantage, that
6798 the previous location will be folded, which may not be what you
6799 want.
6801 This command works around this by showing a copy of the current
6802 buffer in an indirect buffer, in overview mode. You can dive
6803 into the tree in that copy, use org-occur and incremental search
6804 to find a location. When pressing RET or `Q', the command
6805 returns to the original buffer in which the visibility is still
6806 unchanged. After RET it will also jump to the location selected
6807 in the indirect buffer and expose the headline hierarchy above.
6809 With a prefix argument, use the alternative interface: e.g. if
6810 `org-goto-interface' is 'outline use 'outline-path-completion."
6811 (interactive "P")
6812 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6813 (org-refile-use-outline-path t)
6814 (org-refile-target-verify-function nil)
6815 (interface
6816 (if (not alternative-interface)
6817 org-goto-interface
6818 (if (eq org-goto-interface 'outline)
6819 'outline-path-completion
6820 'outline)))
6821 (org-goto-start-pos (point))
6822 (selected-point
6823 (if (eq interface 'outline)
6824 (car (org-get-location (current-buffer) org-goto-help))
6825 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6826 (org-refile-check-position pa)
6827 (nth 3 pa)))))
6828 (if selected-point
6829 (progn
6830 (org-mark-ring-push org-goto-start-pos)
6831 (goto-char selected-point)
6832 (if (or (outline-invisible-p) (org-invisible-p2))
6833 (org-show-context 'org-goto)))
6834 (message "Quit"))))
6836 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6837 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6838 (defvar org-goto-local-auto-isearch-map) ; defined below
6840 (defun org-get-location (buf help)
6841 "Let the user select a location in the Org-mode buffer BUF.
6842 This function uses a recursive edit. It returns the selected position
6843 or nil."
6844 (org-no-popups
6845 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6846 (isearch-hide-immediately nil)
6847 (isearch-search-fun-function
6848 (lambda () 'org-goto-local-search-headings))
6849 (org-goto-selected-point org-goto-exit-command))
6850 (save-excursion
6851 (save-window-excursion
6852 (delete-other-windows)
6853 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6854 (org-pop-to-buffer-same-window
6855 (condition-case nil
6856 (make-indirect-buffer (current-buffer) "*org-goto*")
6857 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6858 (with-output-to-temp-buffer "*Help*"
6859 (princ help))
6860 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6861 (setq buffer-read-only nil)
6862 (let ((org-startup-truncated t)
6863 (org-startup-folded nil)
6864 (org-startup-align-all-tables nil))
6865 (org-mode)
6866 (org-overview))
6867 (setq buffer-read-only t)
6868 (if (and (boundp 'org-goto-start-pos)
6869 (integer-or-marker-p org-goto-start-pos))
6870 (let ((org-show-hierarchy-above t)
6871 (org-show-siblings t)
6872 (org-show-following-heading t))
6873 (goto-char org-goto-start-pos)
6874 (and (outline-invisible-p) (org-show-context)))
6875 (goto-char (point-min)))
6876 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6877 (message "Select location and press RET")
6878 (use-local-map org-goto-map)
6879 (recursive-edit)
6881 (kill-buffer "*org-goto*")
6882 (cons org-goto-selected-point org-goto-exit-command))))
6884 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6885 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6886 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6887 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6889 (defun org-goto-local-search-headings (string bound noerror)
6890 "Search and make sure that any matches are in headlines."
6891 (catch 'return
6892 (while (if isearch-forward
6893 (search-forward string bound noerror)
6894 (search-backward string bound noerror))
6895 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6896 (and (member :headline context)
6897 (not (member :tags context))))
6898 (throw 'return (point))))))
6900 (defun org-goto-local-auto-isearch ()
6901 "Start isearch."
6902 (interactive)
6903 (goto-char (point-min))
6904 (let ((keys (this-command-keys)))
6905 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6906 (isearch-mode t)
6907 (isearch-process-search-char (string-to-char keys)))))
6909 (defun org-goto-ret (&optional arg)
6910 "Finish `org-goto' by going to the new location."
6911 (interactive "P")
6912 (setq org-goto-selected-point (point)
6913 org-goto-exit-command 'return)
6914 (throw 'exit nil))
6916 (defun org-goto-left ()
6917 "Finish `org-goto' by going to the new location."
6918 (interactive)
6919 (if (org-at-heading-p)
6920 (progn
6921 (beginning-of-line 1)
6922 (setq org-goto-selected-point (point)
6923 org-goto-exit-command 'left)
6924 (throw 'exit nil))
6925 (error "Not on a heading")))
6927 (defun org-goto-right ()
6928 "Finish `org-goto' by going to the new location."
6929 (interactive)
6930 (if (org-at-heading-p)
6931 (progn
6932 (setq org-goto-selected-point (point)
6933 org-goto-exit-command 'right)
6934 (throw 'exit nil))
6935 (error "Not on a heading")))
6937 (defun org-goto-quit ()
6938 "Finish `org-goto' without cursor motion."
6939 (interactive)
6940 (setq org-goto-selected-point nil)
6941 (setq org-goto-exit-command 'quit)
6942 (throw 'exit nil))
6944 ;;; Indirect buffer display of subtrees
6946 (defvar org-indirect-dedicated-frame nil
6947 "This is the frame being used for indirect tree display.")
6948 (defvar org-last-indirect-buffer nil)
6950 (defun org-tree-to-indirect-buffer (&optional arg)
6951 "Create indirect buffer and narrow it to current subtree.
6952 With a numerical prefix ARG, go up to this level and then take that tree.
6953 If ARG is negative, go up that many levels.
6955 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6956 indirect buffer previously made with this command, to avoid proliferation of
6957 indirect buffers. However, when you call the command with a \
6958 \\[universal-argument] prefix, or
6959 when `org-indirect-buffer-display' is `new-frame', the last buffer
6960 is kept so that you can work with several indirect buffers at the same time.
6961 If `org-indirect-buffer-display' is `dedicated-frame', the \
6962 \\[universal-argument] prefix also
6963 requests that a new frame be made for the new buffer, so that the dedicated
6964 frame is not changed."
6965 (interactive "P")
6966 (let ((cbuf (current-buffer))
6967 (cwin (selected-window))
6968 (pos (point))
6969 beg end level heading ibuf)
6970 (save-excursion
6971 (org-back-to-heading t)
6972 (when (numberp arg)
6973 (setq level (org-outline-level))
6974 (if (< arg 0) (setq arg (+ level arg)))
6975 (while (> (setq level (org-outline-level)) arg)
6976 (org-up-heading-safe)))
6977 (setq beg (point)
6978 heading (org-get-heading))
6979 (org-end-of-subtree t t)
6980 (if (org-at-heading-p) (backward-char 1))
6981 (setq end (point)))
6982 (if (and (buffer-live-p org-last-indirect-buffer)
6983 (not (eq org-indirect-buffer-display 'new-frame))
6984 (not arg))
6985 (kill-buffer org-last-indirect-buffer))
6986 (setq ibuf (org-get-indirect-buffer cbuf)
6987 org-last-indirect-buffer ibuf)
6988 (cond
6989 ((or (eq org-indirect-buffer-display 'new-frame)
6990 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6991 (select-frame (make-frame))
6992 (delete-other-windows)
6993 (org-pop-to-buffer-same-window ibuf)
6994 (org-set-frame-title heading))
6995 ((eq org-indirect-buffer-display 'dedicated-frame)
6996 (raise-frame
6997 (select-frame (or (and org-indirect-dedicated-frame
6998 (frame-live-p org-indirect-dedicated-frame)
6999 org-indirect-dedicated-frame)
7000 (setq org-indirect-dedicated-frame (make-frame)))))
7001 (delete-other-windows)
7002 (org-pop-to-buffer-same-window ibuf)
7003 (org-set-frame-title (concat "Indirect: " heading)))
7004 ((eq org-indirect-buffer-display 'current-window)
7005 (org-pop-to-buffer-same-window ibuf))
7006 ((eq org-indirect-buffer-display 'other-window)
7007 (pop-to-buffer ibuf))
7008 (t (error "Invalid value")))
7009 (if (featurep 'xemacs)
7010 (save-excursion (org-mode) (turn-on-font-lock)))
7011 (narrow-to-region beg end)
7012 (show-all)
7013 (goto-char pos)
7014 (run-hook-with-args 'org-cycle-hook 'all)
7015 (and (window-live-p cwin) (select-window cwin))))
7017 (defun org-get-indirect-buffer (&optional buffer)
7018 (setq buffer (or buffer (current-buffer)))
7019 (let ((n 1) (base (buffer-name buffer)) bname)
7020 (while (buffer-live-p
7021 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7022 (setq n (1+ n)))
7023 (condition-case nil
7024 (make-indirect-buffer buffer bname 'clone)
7025 (error (make-indirect-buffer buffer bname)))))
7027 (defun org-set-frame-title (title)
7028 "Set the title of the current frame to the string TITLE."
7029 ;; FIXME: how to name a single frame in XEmacs???
7030 (unless (featurep 'xemacs)
7031 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7033 ;;;; Structure editing
7035 ;;; Inserting headlines
7037 (defun org-previous-line-empty-p ()
7038 (save-excursion
7039 (and (not (bobp))
7040 (or (beginning-of-line 0) t)
7041 (save-match-data
7042 (looking-at "[ \t]*$")))))
7044 (defun org-insert-heading (&optional force-heading invisible-ok)
7045 "Insert a new heading or item with same depth at point.
7046 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7047 If point is at the beginning of a headline, insert a sibling before the
7048 current headline. If point is not at the beginning, split the line,
7049 create the new headline with the text in the current line after point
7050 \(but see also the variable `org-M-RET-may-split-line').
7052 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7053 This is important for non-interactive uses of the command."
7054 (interactive "P")
7055 (if (or (= (buffer-size) 0)
7056 (and (not (save-excursion
7057 (and (ignore-errors (org-back-to-heading invisible-ok))
7058 (org-at-heading-p))))
7059 (or force-heading (not (org-in-item-p)))))
7060 (progn
7061 (insert "\n* ")
7062 (run-hooks 'org-insert-heading-hook))
7063 (when (or force-heading (not (org-insert-item)))
7064 (let* ((empty-line-p nil)
7065 (level nil)
7066 (on-heading (org-at-heading-p))
7067 (head (save-excursion
7068 (condition-case nil
7069 (progn
7070 (org-back-to-heading invisible-ok)
7071 (when (and (not on-heading)
7072 (featurep 'org-inlinetask)
7073 (integerp org-inlinetask-min-level)
7074 (>= (length (match-string 0))
7075 org-inlinetask-min-level))
7076 ;; Find a heading level before the inline task
7077 (while (and (setq level (org-up-heading-safe))
7078 (>= level org-inlinetask-min-level)))
7079 (if (org-at-heading-p)
7080 (org-back-to-heading invisible-ok)
7081 (error "This should not happen")))
7082 (setq empty-line-p (org-previous-line-empty-p))
7083 (match-string 0))
7084 (error "*"))))
7085 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7086 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7087 pos hide-previous previous-pos)
7088 (cond
7089 ((and (org-at-heading-p) (bolp)
7090 (or (bobp)
7091 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7092 ;; insert before the current line
7093 (open-line (if blank 2 1)))
7094 ((and (bolp)
7095 (not org-insert-heading-respect-content)
7096 (or (bobp)
7097 (save-excursion
7098 (backward-char 1) (not (outline-invisible-p)))))
7099 ;; insert right here
7100 nil)
7102 ;; somewhere in the line
7103 (save-excursion
7104 (setq previous-pos (point-at-bol))
7105 (end-of-line)
7106 (setq hide-previous (outline-invisible-p)))
7107 (and org-insert-heading-respect-content (org-show-subtree))
7108 (let ((split
7109 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7110 (save-excursion
7111 (let ((p (point)))
7112 (goto-char (point-at-bol))
7113 (and (looking-at org-complex-heading-regexp)
7114 (match-beginning 4)
7115 (> p (match-beginning 4)))))))
7116 tags pos)
7117 (cond
7118 (org-insert-heading-respect-content
7119 (org-end-of-subtree nil t)
7120 (when (featurep 'org-inlinetask)
7121 (while (and (not (eobp))
7122 (looking-at "\\(\\*+\\)[ \t]+")
7123 (>= (length (match-string 1))
7124 org-inlinetask-min-level))
7125 (org-end-of-subtree nil t)))
7126 (or (bolp) (newline))
7127 (or (org-previous-line-empty-p)
7128 (and blank (newline)))
7129 (open-line 1))
7130 ((org-at-heading-p)
7131 (when hide-previous
7132 (show-children)
7133 (org-show-entry))
7134 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7135 (setq tags (and (match-end 2) (match-string 2)))
7136 (and (match-end 1)
7137 (delete-region (match-beginning 1) (match-end 1)))
7138 (setq pos (point-at-bol))
7139 (or split (end-of-line 1))
7140 (delete-horizontal-space)
7141 (if (string-match "\\`\\*+\\'"
7142 (buffer-substring (point-at-bol) (point)))
7143 (insert " "))
7144 (newline (if blank 2 1))
7145 (when tags
7146 (save-excursion
7147 (goto-char pos)
7148 (end-of-line 1)
7149 (insert " " tags)
7150 (org-set-tags nil 'align))))
7152 (or split (end-of-line 1))
7153 (newline (if blank 2 1)))))))
7154 (insert head) (just-one-space)
7155 (setq pos (point))
7156 (end-of-line 1)
7157 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7158 (when (and org-insert-heading-respect-content hide-previous)
7159 (save-excursion
7160 (goto-char previous-pos)
7161 (hide-subtree)))
7162 (run-hooks 'org-insert-heading-hook)))))
7164 (defun org-get-heading (&optional no-tags no-todo)
7165 "Return the heading of the current entry, without the stars.
7166 When NO-TAGS is non-nil, don't include tags.
7167 When NO-TODO is non-nil, don't include TODO keywords."
7168 (save-excursion
7169 (org-back-to-heading t)
7170 (cond
7171 ((and no-tags no-todo)
7172 (looking-at org-complex-heading-regexp)
7173 (match-string 4))
7174 (no-tags
7175 (looking-at (concat org-outline-regexp
7176 "\\(.*?\\)"
7177 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7178 (match-string 1))
7179 (no-todo
7180 (looking-at org-todo-line-regexp)
7181 (match-string 3))
7182 (t (looking-at org-heading-regexp)
7183 (match-string 2)))))
7185 (defun org-heading-components ()
7186 "Return the components of the current heading.
7187 This is a list with the following elements:
7188 - the level as an integer
7189 - the reduced level, different if `org-odd-levels-only' is set.
7190 - the TODO keyword, or nil
7191 - the priority character, like ?A, or nil if no priority is given
7192 - the headline text itself, or the tags string if no headline text
7193 - the tags string, or nil."
7194 (save-excursion
7195 (org-back-to-heading t)
7196 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7197 (list (length (match-string 1))
7198 (org-reduced-level (length (match-string 1)))
7199 (org-match-string-no-properties 2)
7200 (and (match-end 3) (aref (match-string 3) 2))
7201 (org-match-string-no-properties 4)
7202 (org-match-string-no-properties 5)))))
7204 (defun org-get-entry ()
7205 "Get the entry text, after heading, entire subtree."
7206 (save-excursion
7207 (org-back-to-heading t)
7208 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7210 (defun org-insert-heading-after-current ()
7211 "Insert a new heading with same level as current, after current subtree."
7212 (interactive)
7213 (org-back-to-heading)
7214 (org-insert-heading)
7215 (org-move-subtree-down)
7216 (end-of-line 1))
7218 (defun org-insert-heading-respect-content ()
7219 (interactive)
7220 (let ((org-insert-heading-respect-content t))
7221 (org-insert-heading t)))
7223 (defun org-insert-todo-heading-respect-content (&optional force-state)
7224 (interactive "P")
7225 (let ((org-insert-heading-respect-content t))
7226 (org-insert-todo-heading force-state t)))
7228 (defun org-insert-todo-heading (arg &optional force-heading)
7229 "Insert a new heading with the same level and TODO state as current heading.
7230 If the heading has no TODO state, or if the state is DONE, use the first
7231 state (TODO by default). Also with prefix arg, force first state."
7232 (interactive "P")
7233 (when (or force-heading (not (org-insert-item 'checkbox)))
7234 (org-insert-heading force-heading)
7235 (save-excursion
7236 (org-back-to-heading)
7237 (outline-previous-heading)
7238 (looking-at org-todo-line-regexp))
7239 (let*
7240 ((new-mark-x
7241 (if (or arg
7242 (not (match-beginning 2))
7243 (member (match-string 2) org-done-keywords))
7244 (car org-todo-keywords-1)
7245 (match-string 2)))
7246 (new-mark
7248 (run-hook-with-args-until-success
7249 'org-todo-get-default-hook new-mark-x nil)
7250 new-mark-x)))
7251 (beginning-of-line 1)
7252 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7253 (if org-treat-insert-todo-heading-as-state-change
7254 (org-todo new-mark)
7255 (insert new-mark " "))))
7256 (when org-provide-todo-statistics
7257 (org-update-parent-todo-statistics))))
7259 (defun org-insert-subheading (arg)
7260 "Insert a new subheading and demote it.
7261 Works for outline headings and for plain lists alike."
7262 (interactive "P")
7263 (org-insert-heading arg)
7264 (cond
7265 ((org-at-heading-p) (org-do-demote))
7266 ((org-at-item-p) (org-indent-item))))
7268 (defun org-insert-todo-subheading (arg)
7269 "Insert a new subheading with TODO keyword or checkbox and demote it.
7270 Works for outline headings and for plain lists alike."
7271 (interactive "P")
7272 (org-insert-todo-heading arg)
7273 (cond
7274 ((org-at-heading-p) (org-do-demote))
7275 ((org-at-item-p) (org-indent-item))))
7277 ;;; Promotion and Demotion
7279 (defvar org-after-demote-entry-hook nil
7280 "Hook run after an entry has been demoted.
7281 The cursor will be at the beginning of the entry.
7282 When a subtree is being demoted, the hook will be called for each node.")
7284 (defvar org-after-promote-entry-hook nil
7285 "Hook run after an entry has been promoted.
7286 The cursor will be at the beginning of the entry.
7287 When a subtree is being promoted, the hook will be called for each node.")
7289 (defun org-promote-subtree ()
7290 "Promote the entire subtree.
7291 See also `org-promote'."
7292 (interactive)
7293 (save-excursion
7294 (org-with-limited-levels (org-map-tree 'org-promote)))
7295 (org-fix-position-after-promote))
7297 (defun org-demote-subtree ()
7298 "Demote the entire subtree. See `org-demote'.
7299 See also `org-promote'."
7300 (interactive)
7301 (save-excursion
7302 (org-with-limited-levels (org-map-tree 'org-demote)))
7303 (org-fix-position-after-promote))
7306 (defun org-do-promote ()
7307 "Promote the current heading higher up the tree.
7308 If the region is active in `transient-mark-mode', promote all headings
7309 in the region."
7310 (interactive)
7311 (save-excursion
7312 (if (org-region-active-p)
7313 (org-map-region 'org-promote (region-beginning) (region-end))
7314 (org-promote)))
7315 (org-fix-position-after-promote))
7317 (defun org-do-demote ()
7318 "Demote the current heading lower down the tree.
7319 If the region is active in `transient-mark-mode', demote all headings
7320 in the region."
7321 (interactive)
7322 (save-excursion
7323 (if (org-region-active-p)
7324 (org-map-region 'org-demote (region-beginning) (region-end))
7325 (org-demote)))
7326 (org-fix-position-after-promote))
7328 (defun org-fix-position-after-promote ()
7329 "Make sure that after pro/demotion cursor position is right."
7330 (let ((pos (point)))
7331 (when (save-excursion
7332 (beginning-of-line 1)
7333 (looking-at org-todo-line-regexp)
7334 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7335 (cond ((eobp) (insert " "))
7336 ((eolp) (insert " "))
7337 ((equal (char-after) ?\ ) (forward-char 1))))))
7339 (defun org-current-level ()
7340 "Return the level of the current entry, or nil if before the first headline.
7341 The level is the number of stars at the beginning of the headline."
7342 (save-excursion
7343 (org-with-limited-levels
7344 (if (ignore-errors (org-back-to-heading t))
7345 (funcall outline-level)))))
7347 (defun org-get-previous-line-level ()
7348 "Return the outline depth of the last headline before the current line.
7349 Returns 0 for the first headline in the buffer, and nil if before the
7350 first headline."
7351 (let ((current-level (org-current-level))
7352 (prev-level (when (> (line-number-at-pos) 1)
7353 (save-excursion
7354 (beginning-of-line 0)
7355 (org-current-level)))))
7356 (cond ((null current-level) nil) ; Before first headline
7357 ((null prev-level) 0) ; At first headline
7358 (prev-level))))
7360 (defun org-reduced-level (l)
7361 "Compute the effective level of a heading.
7362 This takes into account the setting of `org-odd-levels-only'."
7363 (cond
7364 ((zerop l) 0)
7365 (org-odd-levels-only (1+ (floor (/ l 2))))
7366 (t l)))
7368 (defun org-level-increment ()
7369 "Return the number of stars that will be added or removed at a
7370 time to headlines when structure editing, based on the value of
7371 `org-odd-levels-only'."
7372 (if org-odd-levels-only 2 1))
7374 (defun org-get-valid-level (level &optional change)
7375 "Rectify a level change under the influence of `org-odd-levels-only'
7376 LEVEL is a current level, CHANGE is by how much the level should be
7377 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7378 even level numbers will become the next higher odd number."
7379 (if org-odd-levels-only
7380 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7381 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7382 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7383 (max 1 (+ level (or change 0)))))
7385 (if (boundp 'define-obsolete-function-alias)
7386 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7387 (define-obsolete-function-alias 'org-get-legal-level
7388 'org-get-valid-level)
7389 (define-obsolete-function-alias 'org-get-legal-level
7390 'org-get-valid-level "23.1")))
7392 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7393 ;; ̀org-with-limited-levels'
7394 (defun org-promote ()
7395 "Promote the current heading higher up the tree.
7396 If the region is active in `transient-mark-mode', promote all headings
7397 in the region."
7398 (org-back-to-heading t)
7399 (let* ((level (save-match-data (funcall outline-level)))
7400 (after-change-functions (remove 'flyspell-after-change-function
7401 after-change-functions))
7402 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7403 (diff (abs (- level (length up-head) -1))))
7404 (cond ((and (= level 1) org-called-with-limited-levels
7405 org-allow-promoting-top-level-subtree)
7406 (replace-match "# " nil t))
7407 ((= level 1)
7408 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7409 (t (replace-match up-head nil t)))
7410 ;; Fixup tag positioning
7411 (unless (= level 1)
7412 (and org-auto-align-tags (org-set-tags nil t))
7413 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7414 (run-hooks 'org-after-promote-entry-hook)))
7416 (defun org-demote ()
7417 "Demote the current heading lower down the tree.
7418 If the region is active in `transient-mark-mode', demote all headings
7419 in the region."
7420 (org-back-to-heading t)
7421 (let* ((level (save-match-data (funcall outline-level)))
7422 (after-change-functions (remove 'flyspell-after-change-function
7423 after-change-functions))
7424 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7425 (diff (abs (- level (length down-head) -1))))
7426 (replace-match down-head nil t)
7427 ;; Fixup tag positioning
7428 (and org-auto-align-tags (org-set-tags nil t))
7429 (if org-adapt-indentation (org-fixup-indentation diff))
7430 (run-hooks 'org-after-demote-entry-hook)))
7432 (defun org-cycle-level ()
7433 "Cycle the level of an empty headline through possible states.
7434 This goes first to child, then to parent, level, then up the hierarchy.
7435 After top level, it switches back to sibling level."
7436 (interactive)
7437 (let ((org-adapt-indentation nil))
7438 (when (org-point-at-end-of-empty-headline)
7439 (setq this-command 'org-cycle-level) ; Only needed for caching
7440 (let ((cur-level (org-current-level))
7441 (prev-level (org-get-previous-line-level)))
7442 (cond
7443 ;; If first headline in file, promote to top-level.
7444 ((= prev-level 0)
7445 (loop repeat (/ (- cur-level 1) (org-level-increment))
7446 do (org-do-promote)))
7447 ;; If same level as prev, demote one.
7448 ((= prev-level cur-level)
7449 (org-do-demote))
7450 ;; If parent is top-level, promote to top level if not already.
7451 ((= prev-level 1)
7452 (loop repeat (/ (- cur-level 1) (org-level-increment))
7453 do (org-do-promote)))
7454 ;; If top-level, return to prev-level.
7455 ((= cur-level 1)
7456 (loop repeat (/ (- prev-level 1) (org-level-increment))
7457 do (org-do-demote)))
7458 ;; If less than prev-level, promote one.
7459 ((< cur-level prev-level)
7460 (org-do-promote))
7461 ;; If deeper than prev-level, promote until higher than
7462 ;; prev-level.
7463 ((> cur-level prev-level)
7464 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7465 do (org-do-promote))))
7466 t))))
7468 (defun org-map-tree (fun)
7469 "Call FUN for every heading underneath the current one."
7470 (org-back-to-heading)
7471 (let ((level (funcall outline-level)))
7472 (save-excursion
7473 (funcall fun)
7474 (while (and (progn
7475 (outline-next-heading)
7476 (> (funcall outline-level) level))
7477 (not (eobp)))
7478 (funcall fun)))))
7480 (defun org-map-region (fun beg end)
7481 "Call FUN for every heading between BEG and END."
7482 (let ((org-ignore-region t))
7483 (save-excursion
7484 (setq end (copy-marker end))
7485 (goto-char beg)
7486 (if (and (re-search-forward org-outline-regexp-bol nil t)
7487 (< (point) end))
7488 (funcall fun))
7489 (while (and (progn
7490 (outline-next-heading)
7491 (< (point) end))
7492 (not (eobp)))
7493 (funcall fun)))))
7495 (defvar org-property-end-re) ; silence byte-compiler
7496 (defun org-fixup-indentation (diff)
7497 "Change the indentation in the current entry by DIFF.
7498 However, if any line in the current entry has no indentation, or if it
7499 would end up with no indentation after the change, nothing at all is done."
7500 (save-excursion
7501 (let ((end (save-excursion (outline-next-heading)
7502 (point-marker)))
7503 (prohibit (if (> diff 0)
7504 "^\\S-"
7505 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7506 col)
7507 (unless (save-excursion (end-of-line 1)
7508 (re-search-forward prohibit end t))
7509 (while (and (< (point) end)
7510 (re-search-forward "^[ \t]+" end t))
7511 (goto-char (match-end 0))
7512 (setq col (current-column))
7513 (if (< diff 0) (replace-match ""))
7514 (org-indent-to-column (+ diff col))))
7515 (move-marker end nil))))
7517 (defun org-convert-to-odd-levels ()
7518 "Convert an org-mode file with all levels allowed to one with odd levels.
7519 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7520 level 5 etc."
7521 (interactive)
7522 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7523 (let ((outline-level 'org-outline-level)
7524 (org-odd-levels-only nil) n)
7525 (save-excursion
7526 (goto-char (point-min))
7527 (while (re-search-forward "^\\*\\*+ " nil t)
7528 (setq n (- (length (match-string 0)) 2))
7529 (while (>= (setq n (1- n)) 0)
7530 (org-demote))
7531 (end-of-line 1))))))
7533 (defun org-convert-to-oddeven-levels ()
7534 "Convert an org-mode file with only odd levels to one with odd/even levels.
7535 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7536 file contains a section with an even level, conversion would
7537 destroy the structure of the file. An error is signaled in this
7538 case."
7539 (interactive)
7540 (goto-char (point-min))
7541 ;; First check if there are no even levels
7542 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7543 (org-show-context t)
7544 (error "Not all levels are odd in this file. Conversion not possible"))
7545 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7546 (let ((outline-regexp org-outline-regexp)
7547 (outline-level 'org-outline-level)
7548 (org-odd-levels-only nil) n)
7549 (save-excursion
7550 (goto-char (point-min))
7551 (while (re-search-forward "^\\*\\*+ " nil t)
7552 (setq n (/ (1- (length (match-string 0))) 2))
7553 (while (>= (setq n (1- n)) 0)
7554 (org-promote))
7555 (end-of-line 1))))))
7557 (defun org-tr-level (n)
7558 "Make N odd if required."
7559 (if org-odd-levels-only (1+ (/ n 2)) n))
7561 ;;; Vertical tree motion, cutting and pasting of subtrees
7563 (defun org-move-subtree-up (&optional arg)
7564 "Move the current subtree up past ARG headlines of the same level."
7565 (interactive "p")
7566 (org-move-subtree-down (- (prefix-numeric-value arg))))
7568 (defun org-move-subtree-down (&optional arg)
7569 "Move the current subtree down past ARG headlines of the same level."
7570 (interactive "p")
7571 (setq arg (prefix-numeric-value arg))
7572 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7573 'org-get-last-sibling))
7574 (ins-point (make-marker))
7575 (cnt (abs arg))
7576 (col (current-column))
7577 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7578 ;; Select the tree
7579 (org-back-to-heading)
7580 (setq beg0 (point))
7581 (save-excursion
7582 (setq ne-beg (org-back-over-empty-lines))
7583 (setq beg (point)))
7584 (save-match-data
7585 (save-excursion (outline-end-of-heading)
7586 (setq folded (outline-invisible-p)))
7587 (outline-end-of-subtree))
7588 (outline-next-heading)
7589 (setq ne-end (org-back-over-empty-lines))
7590 (setq end (point))
7591 (goto-char beg0)
7592 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7593 ;; include less whitespace
7594 (save-excursion
7595 (goto-char beg)
7596 (forward-line (- ne-beg ne-end))
7597 (setq beg (point))))
7598 ;; Find insertion point, with error handling
7599 (while (> cnt 0)
7600 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7601 (progn (goto-char beg0)
7602 (error "Cannot move past superior level or buffer limit")))
7603 (setq cnt (1- cnt)))
7604 (if (> arg 0)
7605 ;; Moving forward - still need to move over subtree
7606 (progn (org-end-of-subtree t t)
7607 (save-excursion
7608 (org-back-over-empty-lines)
7609 (or (bolp) (newline)))))
7610 (setq ne-ins (org-back-over-empty-lines))
7611 (move-marker ins-point (point))
7612 (setq txt (buffer-substring beg end))
7613 (org-save-markers-in-region beg end)
7614 (delete-region beg end)
7615 (org-remove-empty-overlays-at beg)
7616 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7617 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7618 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7619 (let ((bbb (point)))
7620 (insert-before-markers txt)
7621 (org-reinstall-markers-in-region bbb)
7622 (move-marker ins-point bbb))
7623 (or (bolp) (insert "\n"))
7624 (setq ins-end (point))
7625 (goto-char ins-point)
7626 (org-skip-whitespace)
7627 (when (and (< arg 0)
7628 (org-first-sibling-p)
7629 (> ne-ins ne-beg))
7630 ;; Move whitespace back to beginning
7631 (save-excursion
7632 (goto-char ins-end)
7633 (let ((kill-whole-line t))
7634 (kill-line (- ne-ins ne-beg)) (point)))
7635 (insert (make-string (- ne-ins ne-beg) ?\n)))
7636 (move-marker ins-point nil)
7637 (if folded
7638 (hide-subtree)
7639 (org-show-entry)
7640 (show-children)
7641 (org-cycle-hide-drawers 'children))
7642 (org-clean-visibility-after-subtree-move)
7643 ;; move back to the initial column we were at
7644 (move-to-column col)))
7646 (defvar org-subtree-clip ""
7647 "Clipboard for cut and paste of subtrees.
7648 This is actually only a copy of the kill, because we use the normal kill
7649 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7651 (defvar org-subtree-clip-folded nil
7652 "Was the last copied subtree folded?
7653 This is used to fold the tree back after pasting.")
7655 (defun org-cut-subtree (&optional n)
7656 "Cut the current subtree into the clipboard.
7657 With prefix arg N, cut this many sequential subtrees.
7658 This is a short-hand for marking the subtree and then cutting it."
7659 (interactive "p")
7660 (org-copy-subtree n 'cut))
7662 (defun org-copy-subtree (&optional n cut force-store-markers)
7663 "Cut the current subtree into the clipboard.
7664 With prefix arg N, cut this many sequential subtrees.
7665 This is a short-hand for marking the subtree and then copying it.
7666 If CUT is non-nil, actually cut the subtree.
7667 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7668 of some markers in the region, even if CUT is non-nil. This is
7669 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7670 (interactive "p")
7671 (let (beg end folded (beg0 (point)))
7672 (if (org-called-interactively-p 'any)
7673 (org-back-to-heading nil) ; take what looks like a subtree
7674 (org-back-to-heading t)) ; take what is really there
7675 (org-back-over-empty-lines)
7676 (setq beg (point))
7677 (skip-chars-forward " \t\r\n")
7678 (save-match-data
7679 (save-excursion (outline-end-of-heading)
7680 (setq folded (outline-invisible-p)))
7681 (condition-case nil
7682 (org-forward-heading-same-level (1- n) t)
7683 (error nil))
7684 (org-end-of-subtree t t))
7685 (org-back-over-empty-lines)
7686 (setq end (point))
7687 (goto-char beg0)
7688 (when (> end beg)
7689 (setq org-subtree-clip-folded folded)
7690 (when (or cut force-store-markers)
7691 (org-save-markers-in-region beg end))
7692 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7693 (setq org-subtree-clip (current-kill 0))
7694 (message "%s: Subtree(s) with %d characters"
7695 (if cut "Cut" "Copied")
7696 (length org-subtree-clip)))))
7698 (defun org-paste-subtree (&optional level tree for-yank)
7699 "Paste the clipboard as a subtree, with modification of headline level.
7700 The entire subtree is promoted or demoted in order to match a new headline
7701 level.
7703 If the cursor is at the beginning of a headline, the same level as
7704 that headline is used to paste the tree
7706 If not, the new level is derived from the *visible* headings
7707 before and after the insertion point, and taken to be the inferior headline
7708 level of the two. So if the previous visible heading is level 3 and the
7709 next is level 4 (or vice versa), level 4 will be used for insertion.
7710 This makes sure that the subtree remains an independent subtree and does
7711 not swallow low level entries.
7713 You can also force a different level, either by using a numeric prefix
7714 argument, or by inserting the heading marker by hand. For example, if the
7715 cursor is after \"*****\", then the tree will be shifted to level 5.
7717 If optional TREE is given, use this text instead of the kill ring.
7719 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7720 move back over whitespace before inserting, and move point to the end of
7721 the inserted text when done."
7722 (interactive "P")
7723 (setq tree (or tree (and kill-ring (current-kill 0))))
7724 (unless (org-kill-is-subtree-p tree)
7725 (error "%s"
7726 (substitute-command-keys
7727 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7728 (org-with-limited-levels
7729 (let* ((visp (not (outline-invisible-p)))
7730 (txt tree)
7731 (^re_ "\\(\\*+\\)[ \t]*")
7732 (old-level (if (string-match org-outline-regexp-bol txt)
7733 (- (match-end 0) (match-beginning 0) 1)
7734 -1))
7735 (force-level (cond (level (prefix-numeric-value level))
7736 ((and (looking-at "[ \t]*$")
7737 (string-match
7738 "^\\*+$" (buffer-substring
7739 (point-at-bol) (point))))
7740 (- (match-end 1) (match-beginning 1)))
7741 ((and (bolp)
7742 (looking-at org-outline-regexp))
7743 (- (match-end 0) (point) 1))))
7744 (previous-level (save-excursion
7745 (condition-case nil
7746 (progn
7747 (outline-previous-visible-heading 1)
7748 (if (looking-at ^re_)
7749 (- (match-end 0) (match-beginning 0) 1)
7751 (error 1))))
7752 (next-level (save-excursion
7753 (condition-case nil
7754 (progn
7755 (or (looking-at org-outline-regexp)
7756 (outline-next-visible-heading 1))
7757 (if (looking-at ^re_)
7758 (- (match-end 0) (match-beginning 0) 1)
7760 (error 1))))
7761 (new-level (or force-level (max previous-level next-level)))
7762 (shift (if (or (= old-level -1)
7763 (= new-level -1)
7764 (= old-level new-level))
7766 (- new-level old-level)))
7767 (delta (if (> shift 0) -1 1))
7768 (func (if (> shift 0) 'org-demote 'org-promote))
7769 (org-odd-levels-only nil)
7770 beg end newend)
7771 ;; Remove the forced level indicator
7772 (if force-level
7773 (delete-region (point-at-bol) (point)))
7774 ;; Paste
7775 (beginning-of-line (if (bolp) 1 2))
7776 (unless for-yank (org-back-over-empty-lines))
7777 (setq beg (point))
7778 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7779 (insert-before-markers txt)
7780 (unless (string-match "\n\\'" txt) (insert "\n"))
7781 (setq newend (point))
7782 (org-reinstall-markers-in-region beg)
7783 (setq end (point))
7784 (goto-char beg)
7785 (skip-chars-forward " \t\n\r")
7786 (setq beg (point))
7787 (if (and (outline-invisible-p) visp)
7788 (save-excursion (outline-show-heading)))
7789 ;; Shift if necessary
7790 (unless (= shift 0)
7791 (save-restriction
7792 (narrow-to-region beg end)
7793 (while (not (= shift 0))
7794 (org-map-region func (point-min) (point-max))
7795 (setq shift (+ delta shift)))
7796 (goto-char (point-min))
7797 (setq newend (point-max))))
7798 (when (or (org-called-interactively-p 'interactive) for-yank)
7799 (message "Clipboard pasted as level %d subtree" new-level))
7800 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7801 kill-ring
7802 (eq org-subtree-clip (current-kill 0))
7803 org-subtree-clip-folded)
7804 ;; The tree was folded before it was killed/copied
7805 (hide-subtree))
7806 (and for-yank (goto-char newend)))))
7808 (defun org-kill-is-subtree-p (&optional txt)
7809 "Check if the current kill is an outline subtree, or a set of trees.
7810 Returns nil if kill does not start with a headline, or if the first
7811 headline level is not the largest headline level in the tree.
7812 So this will actually accept several entries of equal levels as well,
7813 which is OK for `org-paste-subtree'.
7814 If optional TXT is given, check this string instead of the current kill."
7815 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7816 (re (org-get-limited-outline-regexp))
7817 (^re (concat "^" re))
7818 (start-level (and kill
7819 (string-match
7820 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7821 kill)
7822 (- (match-end 2) (match-beginning 2) 1)))
7823 (start (1+ (or (match-beginning 2) -1))))
7824 (if (not start-level)
7825 (progn
7826 nil) ;; does not even start with a heading
7827 (catch 'exit
7828 (while (setq start (string-match ^re kill (1+ start)))
7829 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7830 (throw 'exit nil)))
7831 t))))
7833 (defvar org-markers-to-move nil
7834 "Markers that should be moved with a cut-and-paste operation.
7835 Those markers are stored together with their positions relative to
7836 the start of the region.")
7838 (defun org-save-markers-in-region (beg end)
7839 "Check markers in region.
7840 If these markers are between BEG and END, record their position relative
7841 to BEG, so that after moving the block of text, we can put the markers back
7842 into place.
7843 This function gets called just before an entry or tree gets cut from the
7844 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7845 called immediately, to move the markers with the entries."
7846 (setq org-markers-to-move nil)
7847 (when (featurep 'org-clock)
7848 (org-clock-save-markers-for-cut-and-paste beg end))
7849 (when (featurep 'org-agenda)
7850 (org-agenda-save-markers-for-cut-and-paste beg end)))
7852 (defun org-check-and-save-marker (marker beg end)
7853 "Check if MARKER is between BEG and END.
7854 If yes, remember the marker and the distance to BEG."
7855 (when (and (marker-buffer marker)
7856 (equal (marker-buffer marker) (current-buffer)))
7857 (if (and (>= marker beg) (< marker end))
7858 (push (cons marker (- marker beg)) org-markers-to-move))))
7860 (defun org-reinstall-markers-in-region (beg)
7861 "Move all remembered markers to their position relative to BEG."
7862 (mapc (lambda (x)
7863 (move-marker (car x) (+ beg (cdr x))))
7864 org-markers-to-move)
7865 (setq org-markers-to-move nil))
7867 (defun org-narrow-to-subtree ()
7868 "Narrow buffer to the current subtree."
7869 (interactive)
7870 (save-excursion
7871 (save-match-data
7872 (org-with-limited-levels
7873 (narrow-to-region
7874 (progn (org-back-to-heading t) (point))
7875 (progn (org-end-of-subtree t t)
7876 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7877 (point)))))))
7879 (defun org-narrow-to-block ()
7880 "Narrow buffer to the current block."
7881 (interactive)
7882 (let* ((case-fold-search t)
7883 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7884 "^[ \t]*#\\+end_.*")))
7885 (if blockp
7886 (narrow-to-region (car blockp) (cdr blockp))
7887 (error "Not in a block"))))
7889 (eval-when-compile
7890 (defvar org-property-drawer-re))
7892 (defvar org-property-start-re) ;; defined below
7893 (defun org-clone-subtree-with-time-shift (n &optional shift)
7894 "Clone the task (subtree) at point N times.
7895 The clones will be inserted as siblings.
7897 In interactive use, the user will be prompted for the number of
7898 clones to be produced, and for a time SHIFT, which may be a
7899 repeater as used in time stamps, for example `+3d'.
7901 When a valid repeater is given and the entry contains any time
7902 stamps, the clones will become a sequence in time, with time
7903 stamps in the subtree shifted for each clone produced. If SHIFT
7904 is nil or the empty string, time stamps will be left alone. The
7905 ID property of the original subtree is removed.
7907 If the original subtree did contain time stamps with a repeater,
7908 the following will happen:
7909 - the repeater will be removed in each clone
7910 - an additional clone will be produced, with the current, unshifted
7911 date(s) in the entry.
7912 - the original entry will be placed *after* all the clones, with
7913 repeater intact.
7914 - the start days in the repeater in the original entry will be shifted
7915 to past the last clone.
7916 In this way you can spell out a number of instances of a repeating task,
7917 and still retain the repeater to cover future instances of the task."
7918 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7919 (let (beg end template task idprop
7920 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7921 (drawer-re org-drawer-regexp))
7922 (if (not (and (integerp n) (> n 0)))
7923 (error "Invalid number of replications %s" n))
7924 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7925 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
7926 shift)))
7927 (error "Invalid shift specification %s" shift))
7928 (when doshift
7929 (setq shift-n (string-to-number (match-string 1 shift))
7930 shift-what (cdr (assoc (match-string 2 shift)
7931 '(("d" . day) ("w" . week)
7932 ("m" . month) ("y" . year))))))
7933 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7934 (setq nmin 1 nmax n)
7935 (org-back-to-heading t)
7936 (setq beg (point))
7937 (setq idprop (org-entry-get nil "ID"))
7938 (org-end-of-subtree t t)
7939 (or (bolp) (insert "\n"))
7940 (setq end (point))
7941 (setq template (buffer-substring beg end))
7942 (when (and doshift
7943 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
7944 (delete-region beg end)
7945 (setq end beg)
7946 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7947 (goto-char end)
7948 (loop for n from nmin to nmax do
7949 ;; prepare clone
7950 (with-temp-buffer
7951 (insert template)
7952 (org-mode)
7953 (goto-char (point-min))
7954 (org-show-subtree)
7955 (and idprop (if org-clone-delete-id
7956 (org-entry-delete nil "ID")
7957 (org-id-get-create t)))
7958 (unless (= n 0)
7959 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
7960 (kill-whole-line))
7961 (goto-char (point-min))
7962 (while (re-search-forward drawer-re nil t)
7963 (mapc (lambda (d)
7964 (org-remove-empty-drawer-at d (point))) org-drawers)))
7965 (goto-char (point-min))
7966 (when doshift
7967 (while (re-search-forward org-ts-regexp-both nil t)
7968 (org-timestamp-change (* n shift-n) shift-what))
7969 (unless (= n n-no-remove)
7970 (goto-char (point-min))
7971 (while (re-search-forward org-ts-regexp nil t)
7972 (save-excursion
7973 (goto-char (match-beginning 0))
7974 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
7975 (delete-region (match-beginning 1) (match-end 1)))))))
7976 (setq task (buffer-string)))
7977 (insert task))
7978 (goto-char beg)))
7980 ;;; Outline Sorting
7982 (defun org-sort (with-case)
7983 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
7984 Optional argument WITH-CASE means sort case-sensitively."
7985 (interactive "P")
7986 (cond
7987 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
7988 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
7990 (org-call-with-arg 'org-sort-entries with-case))))
7992 (defun org-sort-remove-invisible (s)
7993 (remove-text-properties 0 (length s) org-rm-props s)
7994 (while (string-match org-bracket-link-regexp s)
7995 (setq s (replace-match (if (match-end 2)
7996 (match-string 3 s)
7997 (match-string 1 s)) t t s)))
8000 (defvar org-priority-regexp) ; defined later in the file
8002 (defvar org-after-sorting-entries-or-items-hook nil
8003 "Hook that is run after a bunch of entries or items have been sorted.
8004 When children are sorted, the cursor is in the parent line when this
8005 hook gets called. When a region or a plain list is sorted, the cursor
8006 will be in the first entry of the sorted region/list.")
8008 (defun org-sort-entries
8009 (&optional with-case sorting-type getkey-func compare-func property)
8010 "Sort entries on a certain level of an outline tree.
8011 If there is an active region, the entries in the region are sorted.
8012 Else, if the cursor is before the first entry, sort the top-level items.
8013 Else, the children of the entry at point are sorted.
8015 Sorting can be alphabetically, numerically, by date/time as given by
8016 a time stamp, by a property or by priority.
8018 The command prompts for the sorting type unless it has been given to the
8019 function through the SORTING-TYPE argument, which needs to be a character,
8020 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8021 precise meaning of each character:
8023 n Numerically, by converting the beginning of the entry/item to a number.
8024 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8025 o By order of TODO keywords.
8026 t By date/time, either the first active time stamp in the entry, or, if
8027 none exist, by the first inactive one.
8028 s By the scheduled date/time.
8029 d By deadline date/time.
8030 c By creation time, which is assumed to be the first inactive time stamp
8031 at the beginning of a line.
8032 p By priority according to the cookie.
8033 r By the value of a property.
8035 Capital letters will reverse the sort order.
8037 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8038 called with point at the beginning of the record. It must return either
8039 a string or a number that should serve as the sorting key for that record.
8041 Comparing entries ignores case by default. However, with an optional argument
8042 WITH-CASE, the sorting considers case as well."
8043 (interactive "P")
8044 (let ((case-func (if with-case 'identity 'downcase))
8045 (cmstr
8046 ;; The clock marker is lost when using `sort-subr', let's
8047 ;; store the clocking string.
8048 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8049 (save-excursion
8050 (goto-char org-clock-marker)
8051 (looking-back "^.*") (match-string-no-properties 0))))
8052 start beg end stars re re2
8053 txt what tmp)
8054 ;; Find beginning and end of region to sort
8055 (cond
8056 ((org-region-active-p)
8057 ;; we will sort the region
8058 (setq end (region-end)
8059 what "region")
8060 (goto-char (region-beginning))
8061 (if (not (org-at-heading-p)) (outline-next-heading))
8062 (setq start (point)))
8063 ((or (org-at-heading-p)
8064 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8065 ;; we will sort the children of the current headline
8066 (org-back-to-heading)
8067 (setq start (point)
8068 end (progn (org-end-of-subtree t t)
8069 (or (bolp) (insert "\n"))
8070 (org-back-over-empty-lines)
8071 (point))
8072 what "children")
8073 (goto-char start)
8074 (show-subtree)
8075 (outline-next-heading))
8077 ;; we will sort the top-level entries in this file
8078 (goto-char (point-min))
8079 (or (org-at-heading-p) (outline-next-heading))
8080 (setq start (point))
8081 (goto-char (point-max))
8082 (beginning-of-line 1)
8083 (when (looking-at ".*?\\S-")
8084 ;; File ends in a non-white line
8085 (end-of-line 1)
8086 (insert "\n"))
8087 (setq end (point-max))
8088 (setq what "top-level")
8089 (goto-char start)
8090 (show-all)))
8092 (setq beg (point))
8093 (if (>= beg end) (error "Nothing to sort"))
8095 (looking-at "\\(\\*+\\)")
8096 (setq stars (match-string 1)
8097 re (concat "^" (regexp-quote stars) " +")
8098 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8099 txt (buffer-substring beg end))
8100 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8101 (if (and (not (equal stars "*")) (string-match re2 txt))
8102 (error "Region to sort contains a level above the first entry"))
8104 (unless sorting-type
8105 (message
8106 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8107 [t]ime [s]cheduled [d]eadline [c]reated
8108 A/N/P/R/O/F/T/S/D/C means reversed:"
8109 what)
8110 (setq sorting-type (read-char-exclusive))
8112 (and (= (downcase sorting-type) ?f)
8113 (setq getkey-func
8114 (org-icompleting-read "Sort using function: "
8115 obarray 'fboundp t nil nil))
8116 (setq getkey-func (intern getkey-func)))
8118 (and (= (downcase sorting-type) ?r)
8119 (setq property
8120 (org-icompleting-read "Property: "
8121 (mapcar 'list (org-buffer-property-keys t))
8122 nil t))))
8124 (message "Sorting entries...")
8126 (save-restriction
8127 (narrow-to-region start end)
8128 (let ((dcst (downcase sorting-type))
8129 (case-fold-search nil)
8130 (now (current-time)))
8131 (sort-subr
8132 (/= dcst sorting-type)
8133 ;; This function moves to the beginning character of the "record" to
8134 ;; be sorted.
8135 (lambda nil
8136 (if (re-search-forward re nil t)
8137 (goto-char (match-beginning 0))
8138 (goto-char (point-max))))
8139 ;; This function moves to the last character of the "record" being
8140 ;; sorted.
8141 (lambda nil
8142 (save-match-data
8143 (condition-case nil
8144 (outline-forward-same-level 1)
8145 (error
8146 (goto-char (point-max))))))
8147 ;; This function returns the value that gets sorted against.
8148 (lambda nil
8149 (cond
8150 ((= dcst ?n)
8151 (if (looking-at org-complex-heading-regexp)
8152 (string-to-number (match-string 4))
8153 nil))
8154 ((= dcst ?a)
8155 (if (looking-at org-complex-heading-regexp)
8156 (funcall case-func (match-string 4))
8157 nil))
8158 ((= dcst ?t)
8159 (let ((end (save-excursion (outline-next-heading) (point))))
8160 (if (or (re-search-forward org-ts-regexp end t)
8161 (re-search-forward org-ts-regexp-both end t))
8162 (org-time-string-to-seconds (match-string 0))
8163 (org-float-time now))))
8164 ((= dcst ?c)
8165 (let ((end (save-excursion (outline-next-heading) (point))))
8166 (if (re-search-forward
8167 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8168 end t)
8169 (org-time-string-to-seconds (match-string 0))
8170 (org-float-time now))))
8171 ((= dcst ?s)
8172 (let ((end (save-excursion (outline-next-heading) (point))))
8173 (if (re-search-forward org-scheduled-time-regexp end t)
8174 (org-time-string-to-seconds (match-string 1))
8175 (org-float-time now))))
8176 ((= dcst ?d)
8177 (let ((end (save-excursion (outline-next-heading) (point))))
8178 (if (re-search-forward org-deadline-time-regexp end t)
8179 (org-time-string-to-seconds (match-string 1))
8180 (org-float-time now))))
8181 ((= dcst ?p)
8182 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8183 (string-to-char (match-string 2))
8184 org-default-priority))
8185 ((= dcst ?r)
8186 (or (org-entry-get nil property) ""))
8187 ((= dcst ?o)
8188 (if (looking-at org-complex-heading-regexp)
8189 (- 9999 (length (member (match-string 2)
8190 org-todo-keywords-1)))))
8191 ((= dcst ?f)
8192 (if getkey-func
8193 (progn
8194 (setq tmp (funcall getkey-func))
8195 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8196 tmp)
8197 (error "Invalid key function `%s'" getkey-func)))
8198 (t (error "Invalid sorting type `%c'" sorting-type))))
8200 (cond
8201 ((= dcst ?a) 'string<)
8202 ((= dcst ?f) compare-func)
8203 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8204 (run-hooks 'org-after-sorting-entries-or-items-hook)
8205 ;; Reset the clock marker if needed
8206 (when cmstr
8207 (save-excursion
8208 (goto-char start)
8209 (search-forward cmstr nil t)
8210 (move-marker org-clock-marker (point))))
8211 (message "Sorting entries...done")))
8213 (defun org-do-sort (table what &optional with-case sorting-type)
8214 "Sort TABLE of WHAT according to SORTING-TYPE.
8215 The user will be prompted for the SORTING-TYPE if the call to this
8216 function does not specify it. WHAT is only for the prompt, to indicate
8217 what is being sorted. The sorting key will be extracted from
8218 the car of the elements of the table.
8219 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8220 (unless sorting-type
8221 (message
8222 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8223 what)
8224 (setq sorting-type (read-char-exclusive)))
8225 (let ((dcst (downcase sorting-type))
8226 extractfun comparefun)
8227 ;; Define the appropriate functions
8228 (cond
8229 ((= dcst ?n)
8230 (setq extractfun 'string-to-number
8231 comparefun (if (= dcst sorting-type) '< '>)))
8232 ((= dcst ?a)
8233 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8234 (lambda(x) (downcase (org-sort-remove-invisible x))))
8235 comparefun (if (= dcst sorting-type)
8236 'string<
8237 (lambda (a b) (and (not (string< a b))
8238 (not (string= a b)))))))
8239 ((= dcst ?t)
8240 (setq extractfun
8241 (lambda (x)
8242 (if (or (string-match org-ts-regexp x)
8243 (string-match org-ts-regexp-both x))
8244 (org-float-time
8245 (org-time-string-to-time (match-string 0 x)))
8247 comparefun (if (= dcst sorting-type) '< '>)))
8248 (t (error "Invalid sorting type `%c'" sorting-type)))
8250 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8251 table)
8252 (lambda (a b) (funcall comparefun (car a) (car b))))))
8255 ;;; The orgstruct minor mode
8257 ;; Define a minor mode which can be used in other modes in order to
8258 ;; integrate the org-mode structure editing commands.
8260 ;; This is really a hack, because the org-mode structure commands use
8261 ;; keys which normally belong to the major mode. Here is how it
8262 ;; works: The minor mode defines all the keys necessary to operate the
8263 ;; structure commands, but wraps the commands into a function which
8264 ;; tests if the cursor is currently at a headline or a plain list
8265 ;; item. If that is the case, the structure command is used,
8266 ;; temporarily setting many Org-mode variables like regular
8267 ;; expressions for filling etc. However, when any of those keys is
8268 ;; used at a different location, function uses `key-binding' to look
8269 ;; up if the key has an associated command in another currently active
8270 ;; keymap (minor modes, major mode, global), and executes that
8271 ;; command. There might be problems if any of the keys is otherwise
8272 ;; used as a prefix key.
8274 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8275 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8276 ;; addresses this by checking explicitly for both bindings.
8278 (defvar orgstruct-mode-map (make-sparse-keymap)
8279 "Keymap for the minor `orgstruct-mode'.")
8281 (defvar org-local-vars nil
8282 "List of local variables, for use by `orgstruct-mode'.")
8284 ;;;###autoload
8285 (define-minor-mode orgstruct-mode
8286 "Toggle the minor mode `orgstruct-mode'.
8287 This mode is for using Org-mode structure commands in other
8288 modes. The following keys behave as if Org-mode were active, if
8289 the cursor is on a headline, or on a plain list item (both as
8290 defined by Org-mode).
8292 M-up Move entry/item up
8293 M-down Move entry/item down
8294 M-left Promote
8295 M-right Demote
8296 M-S-up Move entry/item up
8297 M-S-down Move entry/item down
8298 M-S-left Promote subtree
8299 M-S-right Demote subtree
8300 M-q Fill paragraph and items like in Org-mode
8301 C-c ^ Sort entries
8302 C-c - Cycle list bullet
8303 TAB Cycle item visibility
8304 M-RET Insert new heading/item
8305 S-M-RET Insert new TODO heading / Checkbox item
8306 C-c C-c Set tags / toggle checkbox"
8307 nil " OrgStruct" nil
8308 (org-load-modules-maybe)
8309 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8311 ;;;###autoload
8312 (defun turn-on-orgstruct ()
8313 "Unconditionally turn on `orgstruct-mode'."
8314 (orgstruct-mode 1))
8316 (defvar org-fb-vars nil)
8317 (make-variable-buffer-local 'org-fb-vars)
8318 (defun orgstruct++-mode (&optional arg)
8319 "Toggle `orgstruct-mode', the enhanced version of it.
8320 In addition to setting orgstruct-mode, this also exports all
8321 indentation and autofilling variables from org-mode into the
8322 buffer. It will also recognize item context in multiline items."
8323 (interactive "P")
8324 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8325 (if (< arg 1)
8326 (progn (orgstruct-mode -1)
8327 (mapc (lambda(v)
8328 (org-set-local (car v)
8329 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8330 org-fb-vars))
8331 (orgstruct-mode 1)
8332 (setq org-fb-vars nil)
8333 (let (var val)
8334 (mapc
8335 (lambda (x)
8336 (when (string-match
8337 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8338 (symbol-name (car x)))
8339 (setq var (car x) val (nth 1 x))
8340 (push (list var `(quote ,(eval var))) org-fb-vars)
8341 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8342 org-local-vars)
8343 (org-set-local 'orgstruct-is-++ t))))
8345 (defvar orgstruct-is-++ nil
8346 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8347 (make-variable-buffer-local 'orgstruct-is-++)
8349 ;;;###autoload
8350 (defun turn-on-orgstruct++ ()
8351 "Unconditionally turn on `orgstruct++-mode'."
8352 (orgstruct++-mode 1))
8354 (defun orgstruct-error ()
8355 "Error when there is no default binding for a structure key."
8356 (interactive)
8357 (error "This key has no function outside structure elements"))
8359 (defun orgstruct-setup ()
8360 "Setup orgstruct keymaps."
8361 (let ((nfunc 0)
8362 (bindings
8363 (list
8364 '([(meta up)] org-metaup)
8365 '([(meta down)] org-metadown)
8366 '([(meta left)] org-metaleft)
8367 '([(meta right)] org-metaright)
8368 '([(meta shift up)] org-shiftmetaup)
8369 '([(meta shift down)] org-shiftmetadown)
8370 '([(meta shift left)] org-shiftmetaleft)
8371 '([(meta shift right)] org-shiftmetaright)
8372 '([?\e (up)] org-metaup)
8373 '([?\e (down)] org-metadown)
8374 '([?\e (left)] org-metaleft)
8375 '([?\e (right)] org-metaright)
8376 '([?\e (shift up)] org-shiftmetaup)
8377 '([?\e (shift down)] org-shiftmetadown)
8378 '([?\e (shift left)] org-shiftmetaleft)
8379 '([?\e (shift right)] org-shiftmetaright)
8380 '([(shift up)] org-shiftup)
8381 '([(shift down)] org-shiftdown)
8382 '([(shift left)] org-shiftleft)
8383 '([(shift right)] org-shiftright)
8384 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8385 '("\M-q" fill-paragraph)
8386 '("\C-c^" org-sort)
8387 '("\C-c-" org-cycle-list-bullet)))
8388 elt key fun cmd)
8389 (while (setq elt (pop bindings))
8390 (setq nfunc (1+ nfunc))
8391 (setq key (org-key (car elt))
8392 fun (nth 1 elt)
8393 cmd (orgstruct-make-binding fun nfunc key))
8394 (org-defkey orgstruct-mode-map key cmd))
8396 ;; Prevent an error for users who forgot to make autoloads
8397 (require 'org-element)
8399 ;; Special treatment needed for TAB and RET
8400 (org-defkey orgstruct-mode-map [(tab)]
8401 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8402 (org-defkey orgstruct-mode-map "\C-i"
8403 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8405 (org-defkey orgstruct-mode-map "\M-\C-m"
8406 (orgstruct-make-binding 'org-insert-heading 105
8407 "\M-\C-m" [(meta return)]))
8408 (org-defkey orgstruct-mode-map [(meta return)]
8409 (orgstruct-make-binding 'org-insert-heading 106
8410 [(meta return)] "\M-\C-m"))
8412 (org-defkey orgstruct-mode-map [(shift meta return)]
8413 (orgstruct-make-binding 'org-insert-todo-heading 107
8414 [(meta return)] "\M-\C-m"))
8416 (org-defkey orgstruct-mode-map "\e\C-m"
8417 (orgstruct-make-binding 'org-insert-heading 108
8418 "\e\C-m" [?\e (return)]))
8419 (org-defkey orgstruct-mode-map [?\e (return)]
8420 (orgstruct-make-binding 'org-insert-heading 109
8421 [?\e (return)] "\e\C-m"))
8422 (org-defkey orgstruct-mode-map [?\e (shift return)]
8423 (orgstruct-make-binding 'org-insert-todo-heading 110
8424 [?\e (return)] "\e\C-m"))
8426 (unless org-local-vars
8427 (setq org-local-vars (org-get-local-variables)))
8431 (defun orgstruct-make-binding (fun n &rest keys)
8432 "Create a function for binding in the structure minor mode.
8433 FUN is the command to call inside a table. N is used to create a unique
8434 command name. KEYS are keys that should be checked in for a command
8435 to execute outside of tables."
8436 (eval
8437 (list 'defun
8438 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8439 '(arg)
8440 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8441 "Outside of structure, run the binding of `"
8442 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8443 "'.")
8444 '(interactive "p")
8445 (list 'if
8446 `(org-context-p 'headline 'item
8447 (and orgstruct-is-++
8448 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8449 'item-body))
8450 (list 'org-run-like-in-org-mode (list 'quote fun))
8451 (list 'let '(orgstruct-mode)
8452 (list 'call-interactively
8453 (append '(or)
8454 (mapcar (lambda (k)
8455 (list 'key-binding k))
8456 keys)
8457 '('orgstruct-error))))))))
8459 (defun org-contextualize-keys (alist contexts)
8460 "Return valid elements in ALIST depending on CONTEXTS.
8462 `org-agenda-custom-commands' or `org-capture-templates' are the
8463 values used for ALIST, and `org-agenda-custom-commands-contexts'
8464 or `org-capture-templates-contexts' are the associated contexts
8465 definitions."
8466 (let ((contexts
8467 ;; normalize contexts
8468 (mapcar
8469 (lambda(c) (cond ((listp (cadr c))
8470 (list (car c) (car c) (cadr c)))
8471 ((string= "" (cadr c))
8472 (list (car c) (car c) (caddr c)))
8473 (t c))) contexts))
8474 (a alist) c r s)
8475 ;; loop over all commands or templates
8476 (while (setq c (pop a))
8477 (let (vrules repl)
8478 (cond
8479 ((not (assoc (car c) contexts))
8480 (push c r))
8481 ((and (assoc (car c) contexts)
8482 (setq vrules (org-contextualize-validate-key
8483 (car c) contexts)))
8484 (mapc (lambda (vr)
8485 (when (not (equal (car vr) (cadr vr)))
8486 (setq repl vr))) vrules)
8487 (if (not repl) (push c r)
8488 (push (cadr repl) s)
8489 (push
8490 (cons (car c)
8491 (cdr (or (assoc (cadr repl) alist)
8492 (error "Undefined key `%s' as contextual replacement for `%s'"
8493 (cadr repl) (car c)))))
8494 r))))))
8495 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8496 (delq
8498 (delete-dups
8499 (mapcar (lambda (x)
8500 (let ((tpl (car x)))
8501 (when (not (delq
8503 (mapcar (lambda(y)
8504 (equal y tpl)) s))) x)))
8505 (reverse r))))))
8507 (defun org-contextualize-validate-key (key contexts)
8508 "Check CONTEXTS for agenda or capture KEY."
8509 (let (r rr res)
8510 (while (setq r (pop contexts))
8511 (mapc
8512 (lambda (rr)
8513 (when
8514 (and (equal key (car r))
8515 (if (functionp rr) (funcall rr)
8516 (or (and (eq (car rr) 'in-file)
8517 (buffer-file-name)
8518 (string-match (cdr rr) (buffer-file-name)))
8519 (and (eq (car rr) 'in-mode)
8520 (string-match (cdr rr) (symbol-name major-mode)))
8521 (when (and (eq (car rr) 'not-in-file)
8522 (buffer-file-name))
8523 (not (string-match (cdr rr) (buffer-file-name))))
8524 (when (eq (car rr) 'not-in-mode)
8525 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8526 (push r res)))
8527 (car (last r))))
8528 (delete-dups (delq nil res))))
8530 (defun org-context-p (&rest contexts)
8531 "Check if local context is any of CONTEXTS.
8532 Possible values in the list of contexts are `table', `headline', and `item'."
8533 (let ((pos (point)))
8534 (goto-char (point-at-bol))
8535 (prog1 (or (and (memq 'table contexts)
8536 (looking-at "[ \t]*|"))
8537 (and (memq 'headline contexts)
8538 (looking-at org-outline-regexp))
8539 (and (memq 'item contexts)
8540 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8541 (and (memq 'item-body contexts)
8542 (org-in-item-p)))
8543 (goto-char pos))))
8545 (defun org-get-local-variables ()
8546 "Return a list of all local variables in an Org mode buffer."
8547 (let (varlist)
8548 (with-current-buffer (get-buffer-create "*Org tmp*")
8549 (erase-buffer)
8550 (org-mode)
8551 (setq varlist (buffer-local-variables)))
8552 (kill-buffer "*Org tmp*")
8553 (delq nil
8554 (mapcar
8555 (lambda (x)
8556 (setq x
8557 (if (symbolp x)
8558 (list x)
8559 (list (car x) (list 'quote (cdr x)))))
8560 (if (string-match
8561 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8562 (symbol-name (car x)))
8563 x nil))
8564 varlist))))
8566 (defun org-clone-local-variables (from-buffer &optional regexp)
8567 "Clone local variables from FROM-BUFFER.
8568 Optional argument REGEXP selects variables to clone."
8569 (mapc
8570 (lambda (pair)
8571 (and (symbolp (car pair))
8572 (or (null regexp)
8573 (string-match regexp (symbol-name (car pair))))
8574 (set (make-local-variable (car pair))
8575 (cdr pair))))
8576 (buffer-local-variables from-buffer)))
8578 ;;;###autoload
8579 (defun org-run-like-in-org-mode (cmd)
8580 "Run a command, pretending that the current buffer is in Org-mode.
8581 This will temporarily bind local variables that are typically bound in
8582 Org-mode to the values they have in Org-mode, and then interactively
8583 call CMD."
8584 (org-load-modules-maybe)
8585 (unless org-local-vars
8586 (setq org-local-vars (org-get-local-variables)))
8587 (eval (list 'let org-local-vars
8588 (list 'call-interactively (list 'quote cmd)))))
8590 ;;;; Archiving
8592 (defun org-get-category (&optional pos force-refresh)
8593 "Get the category applying to position POS."
8594 (save-match-data
8595 (if force-refresh (org-refresh-category-properties))
8596 (let ((pos (or pos (point))))
8597 (or (get-text-property pos 'org-category)
8598 (progn (org-refresh-category-properties)
8599 (get-text-property pos 'org-category))))))
8601 (defun org-refresh-category-properties ()
8602 "Refresh category text properties in the buffer."
8603 (let ((case-fold-search t)
8604 (inhibit-read-only t)
8605 (def-cat (cond
8606 ((null org-category)
8607 (if buffer-file-name
8608 (file-name-sans-extension
8609 (file-name-nondirectory buffer-file-name))
8610 "???"))
8611 ((symbolp org-category) (symbol-name org-category))
8612 (t org-category)))
8613 beg end cat pos optionp)
8614 (org-unmodified
8615 (save-excursion
8616 (save-restriction
8617 (widen)
8618 (goto-char (point-min))
8619 (put-text-property (point) (point-max) 'org-category def-cat)
8620 (while (re-search-forward
8621 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8622 (setq pos (match-end 0)
8623 optionp (equal (char-after (match-beginning 0)) ?#)
8624 cat (org-trim (match-string 2)))
8625 (if optionp
8626 (setq beg (point-at-bol) end (point-max))
8627 (org-back-to-heading t)
8628 (setq beg (point) end (org-end-of-subtree t t)))
8629 (put-text-property beg end 'org-category cat)
8630 (put-text-property beg end 'org-category-position beg)
8631 (goto-char pos)))))))
8634 ;;;; Link Stuff
8636 ;;; Link abbreviations
8638 (defun org-link-expand-abbrev (link)
8639 "Apply replacements as defined in `org-link-abbrev-alist'."
8640 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8641 (let* ((key (match-string 1 link))
8642 (as (or (assoc key org-link-abbrev-alist-local)
8643 (assoc key org-link-abbrev-alist)))
8644 (tag (and (match-end 2) (match-string 3 link)))
8645 rpl)
8646 (if (not as)
8647 link
8648 (setq rpl (cdr as))
8649 (cond
8650 ((symbolp rpl) (funcall rpl tag))
8651 ((string-match "%(\\([^)]+\\))" rpl)
8652 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8653 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8654 ((string-match "%h" rpl)
8655 (replace-match (url-hexify-string (or tag "")) t t rpl))
8656 (t (concat rpl tag)))))
8657 link))
8659 ;;; Storing and inserting links
8661 (defvar org-insert-link-history nil
8662 "Minibuffer history for links inserted with `org-insert-link'.")
8664 (defvar org-stored-links nil
8665 "Contains the links stored with `org-store-link'.")
8667 (defvar org-store-link-plist nil
8668 "Plist with info about the most recently link created with `org-store-link'.")
8670 (defvar org-link-protocols nil
8671 "Link protocols added to Org-mode using `org-add-link-type'.")
8673 (defvar org-store-link-functions nil
8674 "List of functions that are called to create and store a link.
8675 Each function will be called in turn until one returns a non-nil
8676 value. Each function should check if it is responsible for creating
8677 this link (for example by looking at the major mode).
8678 If not, it must exit and return nil.
8679 If yes, it should return a non-nil value after a calling
8680 `org-store-link-props' with a list of properties and values.
8681 Special properties are:
8683 :type The link prefix, like \"http\". This must be given.
8684 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8685 This is obligatory as well.
8686 :description Optional default description for the second pair
8687 of brackets in an Org-mode link. The user can still change
8688 this when inserting this link into an Org-mode buffer.
8690 In addition to these, any additional properties can be specified
8691 and then used in capture templates.")
8693 (defun org-add-link-type (type &optional follow export)
8694 "Add TYPE to the list of `org-link-types'.
8695 Re-compute all regular expressions depending on `org-link-types'
8697 FOLLOW and EXPORT are two functions.
8699 FOLLOW should take the link path as the single argument and do whatever
8700 is necessary to follow the link, for example find a file or display
8701 a mail message.
8703 EXPORT should format the link path for export to one of the export formats.
8704 It should be a function accepting three arguments:
8706 path the path of the link, the text after the prefix (like \"http:\")
8707 desc the description of the link, if any, or a description added by
8708 org-export-normalize-links if there is none
8709 format the export format, a symbol like `html' or `latex' or `ascii'..
8711 The function may use the FORMAT information to return different values
8712 depending on the format. The return value will be put literally into
8713 the exported file. If the return value is nil, this means Org should
8714 do what it normally does with links which do not have EXPORT defined.
8716 Org-mode has a built-in default for exporting links. If you are happy with
8717 this default, there is no need to define an export function for the link
8718 type. For a simple example of an export function, see `org-bbdb.el'."
8719 (add-to-list 'org-link-types type t)
8720 (org-make-link-regexps)
8721 (if (assoc type org-link-protocols)
8722 (setcdr (assoc type org-link-protocols) (list follow export))
8723 (push (list type follow export) org-link-protocols)))
8725 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8726 (defvar org-link-to-org-use-id) ; Defined in org-id.el
8728 ;;;###autoload
8729 (defun org-store-link (arg)
8730 "\\<org-mode-map>Store an org-link to the current location.
8731 This link is added to `org-stored-links' and can later be inserted
8732 into an org-buffer with \\[org-insert-link].
8734 For some link types, a prefix arg is interpreted:
8735 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8736 For file links, arg negates `org-context-in-file-links'."
8737 (interactive "P")
8738 (org-load-modules-maybe)
8739 (setq org-store-link-plist nil) ; reset
8740 (org-with-limited-levels
8741 (let (link cpltxt desc description search txt custom-id agenda-link)
8742 (cond
8744 ((run-hook-with-args-until-success 'org-store-link-functions)
8745 (setq link (plist-get org-store-link-plist :link)
8746 desc (or (plist-get org-store-link-plist :description) link)))
8748 ((org-src-edit-buffer-p)
8749 (let (label gc)
8750 (while (or (not label)
8751 (save-excursion
8752 (save-restriction
8753 (widen)
8754 (goto-char (point-min))
8755 (re-search-forward
8756 (regexp-quote (format org-coderef-label-format label))
8757 nil t))))
8758 (when label (message "Label exists already") (sit-for 2))
8759 (setq label (read-string "Code line label: " label)))
8760 (end-of-line 1)
8761 (setq link (format org-coderef-label-format label))
8762 (setq gc (- 79 (length link)))
8763 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8764 (insert link)
8765 (setq link (concat "(" label ")") desc nil)))
8767 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8768 ;; We are in the agenda, link to referenced location
8769 (let ((m (or (get-text-property (point) 'org-hd-marker)
8770 (get-text-property (point) 'org-marker))))
8771 (when m
8772 (org-with-point-at m
8773 (setq agenda-link
8774 (if (org-called-interactively-p 'any)
8775 (call-interactively 'org-store-link)
8776 (org-store-link nil)))))))
8778 ((eq major-mode 'calendar-mode)
8779 (let ((cd (calendar-cursor-to-date)))
8780 (setq link
8781 (format-time-string
8782 (car org-time-stamp-formats)
8783 (apply 'encode-time
8784 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8785 nil nil nil))))
8786 (org-store-link-props :type "calendar" :date cd)))
8788 ((eq major-mode 'help-mode)
8789 (setq link (concat "help:" (save-excursion
8790 (goto-char (point-min))
8791 (looking-at "^[^ ]+")
8792 (match-string 0))))
8793 (org-store-link-props :type "help"))
8795 ((eq major-mode 'w3-mode)
8796 (setq cpltxt (if (and (buffer-name)
8797 (not (string-match "Untitled" (buffer-name))))
8798 (buffer-name)
8799 (url-view-url t))
8800 link (url-view-url t))
8801 (org-store-link-props :type "w3" :url (url-view-url t)))
8803 ((eq major-mode 'w3m-mode)
8804 (setq cpltxt (or w3m-current-title w3m-current-url)
8805 link w3m-current-url)
8806 (org-store-link-props :type "w3m" :url (url-view-url t)))
8808 ((setq search (run-hook-with-args-until-success
8809 'org-create-file-search-functions))
8810 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8811 "::" search))
8812 (setq cpltxt (or description link)))
8814 ((eq major-mode 'image-mode)
8815 (setq cpltxt (concat "file:"
8816 (abbreviate-file-name buffer-file-name))
8817 link cpltxt)
8818 (org-store-link-props :type "image" :file buffer-file-name))
8820 ((eq major-mode 'dired-mode)
8821 ;; link to the file in the current line
8822 (let ((file (dired-get-filename nil t)))
8823 (setq file (if file
8824 (abbreviate-file-name
8825 (expand-file-name (dired-get-filename nil t)))
8826 ;; otherwise, no file so use current directory.
8827 default-directory))
8828 (setq cpltxt (concat "file:" file)
8829 link cpltxt)))
8831 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8832 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8833 (cond
8834 ((org-in-regexp "<<\\(.*?\\)>>")
8835 (setq cpltxt
8836 (concat "file:"
8837 (abbreviate-file-name
8838 (buffer-file-name (buffer-base-buffer)))
8839 "::" (match-string 1))
8840 link cpltxt))
8841 ((and (featurep 'org-id)
8842 (or (eq org-link-to-org-use-id t)
8843 (and (org-called-interactively-p 'any)
8844 (or (eq org-link-to-org-use-id 'create-if-interactive)
8845 (and (eq org-link-to-org-use-id
8846 'create-if-interactive-and-no-custom-id)
8847 (not custom-id))))
8848 (and org-link-to-org-use-id (org-entry-get nil "ID"))))
8849 ;; We can make a link using the ID.
8850 (setq link (condition-case nil
8851 (prog1 (org-id-store-link)
8852 (setq desc (plist-get org-store-link-plist :description)))
8853 (error
8854 ;; probably before first headline, link to file only
8855 (concat "file:"
8856 (abbreviate-file-name
8857 (buffer-file-name (buffer-base-buffer))))))))
8859 ;; Just link to current headline
8860 (setq cpltxt (concat "file:"
8861 (abbreviate-file-name
8862 (buffer-file-name (buffer-base-buffer)))))
8863 ;; Add a context search string
8864 (when (org-xor org-context-in-file-links arg)
8865 (setq txt (cond
8866 ((org-at-heading-p) nil)
8867 ((org-region-active-p)
8868 (buffer-substring (region-beginning) (region-end)))))
8869 (when (or (null txt) (string-match "\\S-" txt))
8870 (setq cpltxt
8871 (concat cpltxt "::"
8872 (condition-case nil
8873 (org-make-org-heading-search-string txt)
8874 (error "")))
8875 desc (or (nth 4 (ignore-errors
8876 (org-heading-components))) "NONE"))))
8877 (if (string-match "::\\'" cpltxt)
8878 (setq cpltxt (substring cpltxt 0 -2)))
8879 (setq link cpltxt))))
8881 ((buffer-file-name (buffer-base-buffer))
8882 ;; Just link to this file here.
8883 (setq cpltxt (concat "file:"
8884 (abbreviate-file-name
8885 (buffer-file-name (buffer-base-buffer)))))
8886 ;; Add a context string
8887 (when (org-xor org-context-in-file-links arg)
8888 (setq txt (if (org-region-active-p)
8889 (buffer-substring (region-beginning) (region-end))
8890 (buffer-substring (point-at-bol) (point-at-eol))))
8891 ;; Only use search option if there is some text.
8892 (when (string-match "\\S-" txt)
8893 (setq cpltxt
8894 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8895 desc "NONE")))
8896 (setq link cpltxt))
8898 ((org-called-interactively-p 'interactive)
8899 (error "Cannot link to a buffer which is not visiting a file"))
8901 (t (setq link nil)))
8903 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8904 (setq link (or link cpltxt)
8905 desc (or desc cpltxt))
8906 (if (equal desc "NONE") (setq desc nil))
8908 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8909 (progn
8910 (setq org-stored-links
8911 (cons (list link desc) org-stored-links))
8912 (message "Stored: %s" (or desc link))
8913 (when custom-id
8914 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8915 "::#" custom-id))
8916 (setq org-stored-links
8917 (cons (list link desc) org-stored-links))))
8918 (or agenda-link (and link (org-make-link-string link desc)))))))
8920 (defun org-store-link-props (&rest plist)
8921 "Store link properties, extract names and addresses."
8922 (let (x adr)
8923 (when (setq x (plist-get plist :from))
8924 (setq adr (mail-extract-address-components x))
8925 (setq plist (plist-put plist :fromname (car adr)))
8926 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8927 (when (setq x (plist-get plist :to))
8928 (setq adr (mail-extract-address-components x))
8929 (setq plist (plist-put plist :toname (car adr)))
8930 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8931 (let ((from (plist-get plist :from))
8932 (to (plist-get plist :to)))
8933 (when (and from to org-from-is-user-regexp)
8934 (setq plist
8935 (plist-put plist :fromto
8936 (if (string-match org-from-is-user-regexp from)
8937 (concat "to %t")
8938 (concat "from %f"))))))
8939 (setq org-store-link-plist plist))
8941 (defun org-add-link-props (&rest plist)
8942 "Add these properties to the link property list."
8943 (let (key value)
8944 (while plist
8945 (setq key (pop plist) value (pop plist))
8946 (setq org-store-link-plist
8947 (plist-put org-store-link-plist key value)))))
8949 (defun org-email-link-description (&optional fmt)
8950 "Return the description part of an email link.
8951 This takes information from `org-store-link-plist' and formats it
8952 according to FMT (default from `org-email-link-description-format')."
8953 (setq fmt (or fmt org-email-link-description-format))
8954 (let* ((p org-store-link-plist)
8955 (to (plist-get p :toaddress))
8956 (from (plist-get p :fromaddress))
8957 (table
8958 (list
8959 (cons "%c" (plist-get p :fromto))
8960 (cons "%F" (plist-get p :from))
8961 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8962 (cons "%T" (plist-get p :to))
8963 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8964 (cons "%s" (plist-get p :subject))
8965 (cons "%d" (plist-get p :date))
8966 (cons "%m" (plist-get p :message-id)))))
8967 (when (string-match "%c" fmt)
8968 ;; Check if the user wrote this message
8969 (if (and org-from-is-user-regexp from to
8970 (save-match-data (string-match org-from-is-user-regexp from)))
8971 (setq fmt (replace-match "to %t" t t fmt))
8972 (setq fmt (replace-match "from %f" t t fmt))))
8973 (org-replace-escapes fmt table)))
8975 (defun org-make-org-heading-search-string (&optional string heading)
8976 "Make search string for STRING or current headline."
8977 (interactive)
8978 (let ((s (or string (org-get-heading)))
8979 (lines org-context-in-file-links))
8980 (unless (and string (not heading))
8981 ;; We are using a headline, clean up garbage in there.
8982 (if (string-match org-todo-regexp s)
8983 (setq s (replace-match "" t t s)))
8984 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8985 (setq s (replace-match "" t t s)))
8986 (setq s (org-trim s))
8987 (if (string-match (concat "^\\(" org-quote-string "\\|"
8988 org-comment-string "\\)") s)
8989 (setq s (replace-match "" t t s)))
8990 (while (string-match org-ts-regexp s)
8991 (setq s (replace-match "" t t s))))
8992 (or string (setq s (concat "*" s))) ; Add * for headlines
8993 (when (and string (integerp lines) (> lines 0))
8994 (let ((slines (org-split-string s "\n")))
8995 (when (< lines (length slines))
8996 (setq s (mapconcat
8997 'identity
8998 (reverse (nthcdr (- (length slines) lines)
8999 (reverse slines))) "\n")))))
9000 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9002 (defun org-make-link-string (link &optional description)
9003 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9004 (unless (string-match "\\S-" link)
9005 (error "Empty link"))
9006 (when (and description
9007 (stringp description)
9008 (not (string-match "\\S-" description)))
9009 (setq description nil))
9010 (when (stringp description)
9011 ;; Remove brackets from the description, they are fatal.
9012 (while (string-match "\\[" description)
9013 (setq description (replace-match "{" t t description)))
9014 (while (string-match "\\]" description)
9015 (setq description (replace-match "}" t t description))))
9016 (when (equal link description)
9017 ;; No description needed, it is identical
9018 (setq description nil))
9019 (when (and (not description)
9020 (not (string-match (org-image-file-name-regexp) link))
9021 (not (equal link (org-link-escape link))))
9022 (setq description (org-extract-attributes link)))
9023 (setq link
9024 (cond ((string-match (org-image-file-name-regexp) link) link)
9025 ((string-match org-link-types-re link)
9026 (concat (match-string 1 link)
9027 (org-link-escape (substring link (match-end 1)))))
9028 (t (org-link-escape link))))
9029 (concat "[[" link "]"
9030 (if description (concat "[" description "]") "")
9031 "]"))
9033 (defconst org-link-escape-chars
9034 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9035 "List of characters that should be escaped in link.
9036 This is the list that is used for internal purposes.")
9038 (defconst org-link-escape-chars-browser
9039 '(?\ )
9040 "List of escapes for characters that are problematic in links.
9041 This is the list that is used before handing over to the browser.")
9043 (defun org-link-escape (text &optional table merge)
9044 "Return percent escaped representation of TEXT.
9045 TEXT is a string with the text to escape.
9046 Optional argument TABLE is a list with characters that should be
9047 escaped. When nil, `org-link-escape-chars' is used.
9048 If optional argument MERGE is set, merge TABLE into
9049 `org-link-escape-chars'."
9050 (cond
9051 ((and table merge)
9052 (mapc (lambda (defchr)
9053 (unless (member defchr table)
9054 (setq table (cons defchr table)))) org-link-escape-chars))
9055 ((null table)
9056 (setq table org-link-escape-chars)))
9057 (mapconcat
9058 (lambda (char)
9059 (if (or (member char table)
9060 (and (or (< char 32) (= char 37) (> char 126))
9061 org-url-hexify-p))
9062 (mapconcat (lambda (sequence-element)
9063 (format "%%%.2X" sequence-element))
9064 (or (encode-coding-char char 'utf-8)
9065 (error "Unable to percent escape character: %s"
9066 (char-to-string char))) "")
9067 (char-to-string char))) text ""))
9069 (defun org-link-unescape (str)
9070 "Unhex hexified Unicode strings as returned from the JavaScript function
9071 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9072 (unless (and (null str) (string= "" str))
9073 (let ((pos 0) (case-fold-search t) unhexed)
9074 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9075 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9076 (setq str (replace-match unhexed t t str))
9077 (setq pos (+ pos (length unhexed))))))
9078 str)
9080 (defun org-link-unescape-compound (hex)
9081 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9082 Note: this function also decodes single byte encodings like
9083 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9084 (save-match-data
9085 (let* ((bytes (cdr (split-string hex "%")))
9086 (ret "")
9087 (eat 0)
9088 (sum 0))
9089 (while bytes
9090 (let* ((val (string-to-number (pop bytes) 16))
9091 (shift-xor
9092 (if (= 0 eat)
9093 (cond
9094 ((>= val 252) (cons 6 252))
9095 ((>= val 248) (cons 5 248))
9096 ((>= val 240) (cons 4 240))
9097 ((>= val 224) (cons 3 224))
9098 ((>= val 192) (cons 2 192))
9099 (t (cons 0 0)))
9100 (cons 6 128))))
9101 (if (>= val 192) (setq eat (car shift-xor)))
9102 (setq val (logxor val (cdr shift-xor)))
9103 (setq sum (+ (lsh sum (car shift-xor)) val))
9104 (if (> eat 0) (setq eat (- eat 1)))
9105 (cond
9106 ((= 0 eat) ;multi byte
9107 (setq ret (concat ret (org-char-to-string sum)))
9108 (setq sum 0))
9109 ((not bytes) ; single byte(s)
9110 (setq ret (org-link-unescape-single-byte-sequence hex))))
9111 )) ;; end (while bytes
9112 ret )))
9114 (defun org-link-unescape-single-byte-sequence (hex)
9115 "Unhexify hex-encoded single byte character sequences."
9116 (mapconcat (lambda (byte)
9117 (char-to-string (string-to-number byte 16)))
9118 (cdr (split-string hex "%")) ""))
9120 (defun org-xor (a b)
9121 "Exclusive or."
9122 (if a (not b) b))
9124 (defun org-fixup-message-id-for-http (s)
9125 "Replace special characters in a message id, so it can be used in an http query."
9126 (when (string-match "%" s)
9127 (setq s (mapconcat (lambda (c)
9128 (if (eq c ?%)
9129 "%25"
9130 (char-to-string c)))
9131 s "")))
9132 (while (string-match "<" s)
9133 (setq s (replace-match "%3C" t t s)))
9134 (while (string-match ">" s)
9135 (setq s (replace-match "%3E" t t s)))
9136 (while (string-match "@" s)
9137 (setq s (replace-match "%40" t t s)))
9140 (defun org-link-prettify (link)
9141 "Return a human-readable representation of LINK.
9142 The car of LINK must be a raw link the cdr of LINK must be either
9143 a link description or nil."
9144 (let ((desc (or (cadr link) "<no description>")))
9145 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9146 "<" (car link) ">")))
9148 ;;;###autoload
9149 (defun org-insert-link-global ()
9150 "Insert a link like Org-mode does.
9151 This command can be called in any mode to insert a link in Org-mode syntax."
9152 (interactive)
9153 (org-load-modules-maybe)
9154 (org-run-like-in-org-mode 'org-insert-link))
9156 (defun org-insert-all-links (&optional keep)
9157 "Insert all links in `org-stored-links'."
9158 (interactive "P")
9159 (let ((links (copy-sequence org-stored-links)) l)
9160 (while (setq l (if keep (pop links) (pop org-stored-links)))
9161 (insert "- ")
9162 (org-insert-link nil (car l) (cadr l))
9163 (insert "\n"))))
9165 (defun org-link-fontify-links-to-this-file ()
9166 "Fontify links to the current file in `org-stored-links'."
9167 (let ((f (buffer-file-name)) a b)
9168 (setq a (mapcar (lambda(l)
9169 (let ((ll (car l)))
9170 (when (and (string-match "^file:\\(.+\\)::" ll)
9171 (equal f (expand-file-name (match-string 1 ll))))
9172 ll)))
9173 org-stored-links))
9174 (when (featurep 'org-id)
9175 (setq b (mapcar (lambda(l)
9176 (let ((ll (car l)))
9177 (when (and (string-match "^id:\\(.+\\)$" ll)
9178 (equal f (expand-file-name
9179 (or (org-id-find-id-file
9180 (match-string 1 ll)) ""))))
9181 ll)))
9182 org-stored-links)))
9183 (mapcar (lambda(l)
9184 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9185 (delq nil (append a b)))))
9187 (defvar org-link-links-in-this-file nil)
9188 (defun org-insert-link (&optional complete-file link-location default-description)
9189 "Insert a link. At the prompt, enter the link.
9191 Completion can be used to insert any of the link protocol prefixes like
9192 http or ftp in use.
9194 The history can be used to select a link previously stored with
9195 `org-store-link'. When the empty string is entered (i.e. if you just
9196 press RET at the prompt), the link defaults to the most recently
9197 stored link. As SPC triggers completion in the minibuffer, you need to
9198 use M-SPC or C-q SPC to force the insertion of a space character.
9200 You will also be prompted for a description, and if one is given, it will
9201 be displayed in the buffer instead of the link.
9203 If there is already a link at point, this command will allow you to edit link
9204 and description parts.
9206 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9207 be selected using completion. The path to the file will be relative to the
9208 current directory if the file is in the current directory or a subdirectory.
9209 Otherwise, the link will be the absolute path as completed in the minibuffer
9210 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9211 option `org-link-file-path-type'.
9213 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9214 the current directory or below.
9216 With three \\[universal-argument] prefixes, negate the meaning of
9217 `org-keep-stored-link-after-insertion'.
9219 If `org-make-link-description-function' is non-nil, this function will be
9220 called with the link target, and the result will be the default
9221 link description.
9223 If the LINK-LOCATION parameter is non-nil, this value will be
9224 used as the link location instead of reading one interactively.
9226 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9227 be used as the default description."
9228 (interactive "P")
9229 (let* ((wcf (current-window-configuration))
9230 (region (if (org-region-active-p)
9231 (buffer-substring (region-beginning) (region-end))))
9232 (remove (and region (list (region-beginning) (region-end))))
9233 (desc region)
9234 tmphist ; byte-compile incorrectly complains about this
9235 (link link-location)
9236 (abbrevs org-link-abbrev-alist-local)
9237 entry file all-prefixes auto-desc)
9238 (cond
9239 (link-location) ; specified by arg, just use it.
9240 ((org-in-regexp org-bracket-link-regexp 1)
9241 ;; We do have a link at point, and we are going to edit it.
9242 (setq remove (list (match-beginning 0) (match-end 0)))
9243 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9244 (setq link (read-string "Link: "
9245 (org-link-unescape
9246 (org-match-string-no-properties 1)))))
9247 ((or (org-in-regexp org-angle-link-re)
9248 (org-in-regexp org-plain-link-re))
9249 ;; Convert to bracket link
9250 (setq remove (list (match-beginning 0) (match-end 0))
9251 link (read-string "Link: "
9252 (org-remove-angle-brackets (match-string 0)))))
9253 ((member complete-file '((4) (16)))
9254 ;; Completing read for file names.
9255 (setq link (org-file-complete-link complete-file)))
9257 ;; Read link, with completion for stored links.
9258 (org-link-fontify-links-to-this-file)
9259 (org-switch-to-buffer-other-window "*Org Links*")
9260 (with-current-buffer "*Org Links*"
9261 (erase-buffer)
9262 (insert "Insert a link.
9263 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9264 (when org-stored-links
9265 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9266 (insert (mapconcat 'org-link-prettify
9267 (reverse org-stored-links) "\n")))
9268 (goto-char (point-min)))
9269 (let ((cw (selected-window)))
9270 (select-window (get-buffer-window "*Org Links*" 'visible))
9271 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9272 (unless (pos-visible-in-window-p (point-max))
9273 (org-fit-window-to-buffer))
9274 (and (window-live-p cw) (select-window cw)))
9275 ;; Fake a link history, containing the stored links.
9276 (setq tmphist (append (mapcar 'car org-stored-links)
9277 org-insert-link-history))
9278 (setq all-prefixes (append (mapcar 'car abbrevs)
9279 (mapcar 'car org-link-abbrev-alist)
9280 org-link-types))
9281 (unwind-protect
9282 (progn
9283 (setq link
9284 (let ((org-completion-use-ido nil)
9285 (org-completion-use-iswitchb nil))
9286 (org-completing-read
9287 "Link: "
9288 (append
9289 (mapcar (lambda (x) (list (concat x ":")))
9290 all-prefixes)
9291 (mapcar 'car org-stored-links)
9292 (mapcar 'cadr org-stored-links))
9293 nil nil nil
9294 'tmphist
9295 (caar org-stored-links))))
9296 (if (not (string-match "\\S-" link))
9297 (error "No link selected"))
9298 (mapc (lambda(l)
9299 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9300 org-stored-links)
9301 (if (or (member link all-prefixes)
9302 (and (equal ":" (substring link -1))
9303 (member (substring link 0 -1) all-prefixes)
9304 (setq link (substring link 0 -1))))
9305 (setq link (org-link-try-special-completion link))))
9306 (set-window-configuration wcf)
9307 (kill-buffer "*Org Links*"))
9308 (setq entry (assoc link org-stored-links))
9309 (or entry (push link org-insert-link-history))
9310 (setq desc (or desc (nth 1 entry)))))
9312 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9313 (not org-keep-stored-link-after-insertion))
9314 (setq org-stored-links (delq (assoc link org-stored-links)
9315 org-stored-links)))
9317 (if (string-match org-plain-link-re link)
9318 ;; URL-like link, normalize the use of angular brackets.
9319 (setq link (org-remove-angle-brackets link)))
9321 ;; Check if we are linking to the current file with a search option
9322 ;; If yes, simplify the link by using only the search option.
9323 (when (and buffer-file-name
9324 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9325 (let* ((path (match-string 1 link))
9326 (case-fold-search nil)
9327 (search (match-string 2 link)))
9328 (save-match-data
9329 (if (equal (file-truename buffer-file-name) (file-truename path))
9330 ;; We are linking to this same file, with a search option
9331 (setq link search)))))
9333 ;; Check if we can/should use a relative path. If yes, simplify the link
9334 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9335 (let* ((type (match-string 1 link))
9336 (path (match-string 2 link))
9337 (origpath path)
9338 (case-fold-search nil))
9339 (cond
9340 ((or (eq org-link-file-path-type 'absolute)
9341 (equal complete-file '(16)))
9342 (setq path (abbreviate-file-name (expand-file-name path))))
9343 ((eq org-link-file-path-type 'noabbrev)
9344 (setq path (expand-file-name path)))
9345 ((eq org-link-file-path-type 'relative)
9346 (setq path (file-relative-name path)))
9348 (save-match-data
9349 (if (string-match (concat "^" (regexp-quote
9350 (expand-file-name
9351 (file-name-as-directory
9352 default-directory))))
9353 (expand-file-name path))
9354 ;; We are linking a file with relative path name.
9355 (setq path (substring (expand-file-name path)
9356 (match-end 0)))
9357 (setq path (abbreviate-file-name (expand-file-name path)))))))
9358 (setq link (concat type path))
9359 (if (equal desc origpath)
9360 (setq desc path))))
9362 (if org-make-link-description-function
9363 (setq desc
9364 (or (condition-case nil
9365 (funcall org-make-link-description-function link desc)
9366 (error (progn (message "Can't get link description from `%s'"
9367 (symbol-name org-make-link-description-function))
9368 (sit-for 2) nil)))
9369 (read-string "Description: " default-description)))
9370 (if default-description (setq desc default-description)
9371 (setq desc (or (and auto-desc desc)
9372 (read-string "Description: " desc)))))
9374 (unless (string-match "\\S-" desc) (setq desc nil))
9375 (if remove (apply 'delete-region remove))
9376 (insert (org-make-link-string link desc))))
9378 (defun org-link-try-special-completion (type)
9379 "If there is completion support for link type TYPE, offer it."
9380 (let ((fun (intern (concat "org-" type "-complete-link"))))
9381 (if (functionp fun)
9382 (funcall fun)
9383 (read-string "Link (no completion support): " (concat type ":")))))
9385 (defun org-file-complete-link (&optional arg)
9386 "Create a file link using completion."
9387 (let (file link)
9388 (setq file (read-file-name "File: "))
9389 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9390 (pwd1 (file-name-as-directory (abbreviate-file-name
9391 (expand-file-name ".")))))
9392 (cond
9393 ((equal arg '(16))
9394 (setq link (concat
9395 "file:"
9396 (abbreviate-file-name (expand-file-name file)))))
9397 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9398 (setq link (concat "file:" (match-string 1 file))))
9399 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9400 (expand-file-name file))
9401 (setq link (concat
9402 "file:" (match-string 1 (expand-file-name file)))))
9403 (t (setq link (concat "file:" file)))))
9404 link))
9406 (defun org-completing-read (&rest args)
9407 "Completing-read with SPACE being a normal character."
9408 (let ((enable-recursive-minibuffers t)
9409 (minibuffer-local-completion-map
9410 (copy-keymap minibuffer-local-completion-map)))
9411 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9412 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9413 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9414 (apply 'org-icompleting-read args)))
9416 (defun org-completing-read-no-i (&rest args)
9417 (let (org-completion-use-ido org-completion-use-iswitchb)
9418 (apply 'org-completing-read args)))
9420 (defun org-iswitchb-completing-read (prompt choices &rest args)
9421 "Use iswitch as a completing-read replacement to choose from choices.
9422 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9423 from."
9424 (let* ((iswitchb-use-virtual-buffers nil)
9425 (iswitchb-make-buflist-hook
9426 (lambda ()
9427 (setq iswitchb-temp-buflist choices))))
9428 (iswitchb-read-buffer prompt)))
9430 (defun org-icompleting-read (&rest args)
9431 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9432 (org-without-partial-completion
9433 (if (and org-completion-use-ido
9434 (fboundp 'ido-completing-read)
9435 (boundp 'ido-mode) ido-mode
9436 (listp (second args)))
9437 (let ((ido-enter-matching-directory nil))
9438 (apply 'ido-completing-read (concat (car args))
9439 (if (consp (car (nth 1 args)))
9440 (mapcar 'car (nth 1 args))
9441 (nth 1 args))
9442 (cddr args)))
9443 (if (and org-completion-use-iswitchb
9444 (boundp 'iswitchb-mode) iswitchb-mode
9445 (listp (second args)))
9446 (apply 'org-iswitchb-completing-read (concat (car args))
9447 (if (consp (car (nth 1 args)))
9448 (mapcar 'car (nth 1 args))
9449 (nth 1 args))
9450 (cddr args))
9451 (apply 'completing-read args)))))
9453 (defun org-extract-attributes (s)
9454 "Extract the attributes cookie from a string and set as text property."
9455 (let (a attr (start 0) key value)
9456 (save-match-data
9457 (when (string-match "{{\\([^}]+\\)}}$" s)
9458 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9459 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9460 (setq key (match-string 1 a) value (match-string 2 a)
9461 start (match-end 0)
9462 attr (plist-put attr (intern key) value))))
9463 (org-add-props s nil 'org-attr attr))
9466 (defun org-extract-attributes-from-string (tag)
9467 (let (key value attr)
9468 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9469 (setq key (match-string 1 tag) value (match-string 2 tag)
9470 tag (replace-match "" t t tag)
9471 attr (plist-put attr (intern key) value)))
9472 (cons tag attr)))
9474 (defun org-attributes-to-string (plist)
9475 "Format a property list into an HTML attribute list."
9476 (let ((s "") key value)
9477 (while plist
9478 (setq key (pop plist) value (pop plist))
9479 (and value
9480 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9483 ;;; Opening/following a link
9485 (defvar org-link-search-failed nil)
9487 (defvar org-open-link-functions nil
9488 "Hook for functions finding a plain text link.
9489 These functions must take a single argument, the link content.
9490 They will be called for links that look like [[link text][description]]
9491 when LINK TEXT does not have a protocol like \"http:\" and does not look
9492 like a filename (e.g. \"./blue.png\").
9494 These functions will be called *before* Org attempts to resolve the
9495 link by doing text searches in the current buffer - so if you want a
9496 link \"[[target]]\" to still find \"<<target>>\", your function should
9497 handle this as a special case.
9499 When the function does handle the link, it must return a non-nil value.
9500 If it decides that it is not responsible for this link, it must return
9501 nil to indicate that that Org-mode can continue with other options
9502 like exact and fuzzy text search.")
9504 (defun org-next-link ()
9505 "Move forward to the next link.
9506 If the link is in hidden text, expose it."
9507 (interactive)
9508 (when (and org-link-search-failed (eq this-command last-command))
9509 (goto-char (point-min))
9510 (message "Link search wrapped back to beginning of buffer"))
9511 (setq org-link-search-failed nil)
9512 (let* ((pos (point))
9513 (ct (org-context))
9514 (a (assoc :link ct)))
9515 (if a (goto-char (nth 2 a)))
9516 (if (re-search-forward org-any-link-re nil t)
9517 (progn
9518 (goto-char (match-beginning 0))
9519 (if (outline-invisible-p) (org-show-context)))
9520 (goto-char pos)
9521 (setq org-link-search-failed t)
9522 (error "No further link found"))))
9524 (defun org-previous-link ()
9525 "Move backward to the previous link.
9526 If the link is in hidden text, expose it."
9527 (interactive)
9528 (when (and org-link-search-failed (eq this-command last-command))
9529 (goto-char (point-max))
9530 (message "Link search wrapped back to end of buffer"))
9531 (setq org-link-search-failed nil)
9532 (let* ((pos (point))
9533 (ct (org-context))
9534 (a (assoc :link ct)))
9535 (if a (goto-char (nth 1 a)))
9536 (if (re-search-backward org-any-link-re nil t)
9537 (progn
9538 (goto-char (match-beginning 0))
9539 (if (outline-invisible-p) (org-show-context)))
9540 (goto-char pos)
9541 (setq org-link-search-failed t)
9542 (error "No further link found"))))
9544 (defun org-translate-link (s)
9545 "Translate a link string if a translation function has been defined."
9546 (if (and org-link-translation-function
9547 (fboundp org-link-translation-function)
9548 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9549 (progn
9550 (setq s (funcall org-link-translation-function
9551 (match-string 1 s) (match-string 2 s)))
9552 (concat (car s) ":" (cdr s)))
9555 (defun org-translate-link-from-planner (type path)
9556 "Translate a link from Emacs Planner syntax so that Org can follow it.
9557 This is still an experimental function, your mileage may vary."
9558 (cond
9559 ((member type '("http" "https" "news" "ftp"))
9560 ;; standard Internet links are the same.
9561 nil)
9562 ((and (equal type "irc") (string-match "^//" path))
9563 ;; Planner has two / at the beginning of an irc link, we have 1.
9564 ;; We should have zero, actually....
9565 (setq path (substring path 1)))
9566 ((and (equal type "lisp") (string-match "^/" path))
9567 ;; Planner has a slash, we do not.
9568 (setq type "elisp" path (substring path 1)))
9569 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9570 ;; A typical message link. Planner has the id after the final slash,
9571 ;; we separate it with a hash mark
9572 (setq path (concat (match-string 1 path) "#"
9573 (org-remove-angle-brackets (match-string 2 path)))))
9575 (cons type path))
9577 (defun org-find-file-at-mouse (ev)
9578 "Open file link or URL at mouse."
9579 (interactive "e")
9580 (mouse-set-point ev)
9581 (org-open-at-point 'in-emacs))
9583 (defun org-open-at-mouse (ev)
9584 "Open file link or URL at mouse.
9585 See the docstring of `org-open-file' for details."
9586 (interactive "e")
9587 (mouse-set-point ev)
9588 (if (eq major-mode 'org-agenda-mode)
9589 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9590 (org-open-at-point))
9592 (defvar org-window-config-before-follow-link nil
9593 "The window configuration before following a link.
9594 This is saved in case the need arises to restore it.")
9596 (defvar org-open-link-marker (make-marker)
9597 "Marker pointing to the location where `org-open-at-point; was called.")
9599 ;;;###autoload
9600 (defun org-open-at-point-global ()
9601 "Follow a link like Org-mode does.
9602 This command can be called in any mode to follow a link that has
9603 Org-mode syntax."
9604 (interactive)
9605 (org-run-like-in-org-mode 'org-open-at-point))
9607 ;;;###autoload
9608 (defun org-open-link-from-string (s &optional arg reference-buffer)
9609 "Open a link in the string S, as if it was in Org-mode."
9610 (interactive "sLink: \nP")
9611 (let ((reference-buffer (or reference-buffer (current-buffer))))
9612 (with-temp-buffer
9613 (let ((org-inhibit-startup (not reference-buffer)))
9614 (org-mode)
9615 (insert s)
9616 (goto-char (point-min))
9617 (when reference-buffer
9618 (setq org-link-abbrev-alist-local
9619 (with-current-buffer reference-buffer
9620 org-link-abbrev-alist-local)))
9621 (org-open-at-point arg reference-buffer)))))
9623 (defvar org-open-at-point-functions nil
9624 "Hook that is run when following a link at point.
9626 Functions in this hook must return t if they identify and follow
9627 a link at point. If they don't find anything interesting at point,
9628 they must return nil.")
9630 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9631 (defun org-open-at-point (&optional arg reference-buffer)
9632 "Open link at or after point.
9633 If there is no link at point, this function will search forward up to
9634 the end of the current line.
9635 Normally, files will be opened by an appropriate application. If the
9636 optional prefix argument ARG is non-nil, Emacs will visit the file.
9637 With a double prefix argument, try to open outside of Emacs, in the
9638 application the system uses for this file type."
9639 (interactive "P")
9640 ;; if in a code block, then open the block's results
9641 (unless (call-interactively #'org-babel-open-src-block-result)
9642 (org-load-modules-maybe)
9643 (move-marker org-open-link-marker (point))
9644 (setq org-window-config-before-follow-link (current-window-configuration))
9645 (org-remove-occur-highlights nil nil t)
9646 (cond
9647 ((and (org-at-heading-p)
9648 (not (org-at-timestamp-p t))
9649 (not (org-in-regexp
9650 (concat org-plain-link-re "\\|"
9651 org-bracket-link-regexp "\\|"
9652 org-angle-link-re "\\|"
9653 "[ \t]:[^ \t\n]+:[ \t]*$")))
9654 (not (get-text-property (point) 'org-linked-text)))
9655 (or (org-offer-links-in-entry arg)
9656 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9657 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9658 ((and (org-at-timestamp-p t)
9659 (not (org-in-regexp org-bracket-link-regexp)))
9660 (org-follow-timestamp-link))
9661 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9662 (not (org-in-regexp org-any-link-re)))
9663 (org-footnote-action))
9665 (let (type path link line search (pos (point)))
9666 (catch 'match
9667 (save-excursion
9668 (skip-chars-forward "^]\n\r")
9669 (when (org-in-regexp org-bracket-link-regexp 1)
9670 (setq link (org-extract-attributes
9671 (org-link-unescape (org-match-string-no-properties 1))))
9672 (while (string-match " *\n *" link)
9673 (setq link (replace-match " " t t link)))
9674 (setq link (org-link-expand-abbrev link))
9675 (cond
9676 ((or (file-name-absolute-p link)
9677 (string-match "^\\.\\.?/" link))
9678 (setq type "file" path link))
9679 ((string-match org-link-re-with-space3 link)
9680 (setq type (match-string 1 link) path (match-string 2 link)))
9681 ((string-match "^help:+\\(.+\\)" link)
9682 (setq type "help" path (match-string 1 link)))
9683 (t (setq type "thisfile" path link)))
9684 (throw 'match t)))
9686 (when (get-text-property (point) 'org-linked-text)
9687 (setq type "thisfile"
9688 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9689 (1+ (point)) (point))
9690 path (buffer-substring
9691 (or (previous-single-property-change pos 'org-linked-text)
9692 (point-min))
9693 (or (next-single-property-change pos 'org-linked-text)
9694 (point-max))))
9695 (throw 'match t))
9697 (save-excursion
9698 (let ((plinkpos (org-in-regexp org-plain-link-re)))
9699 (when (or (org-in-regexp org-angle-link-re)
9700 (and plinkpos (goto-char (car plinkpos))
9701 (save-match-data (not (looking-back "\\[\\[")))))
9702 (setq type (match-string 1)
9703 path (org-link-unescape (match-string 2)))
9704 (throw 'match t))))
9705 (save-excursion
9706 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9707 (setq type "tags"
9708 path (match-string 1))
9709 (while (string-match ":" path)
9710 (setq path (replace-match "+" t t path)))
9711 (throw 'match t)))
9712 (when (org-in-regexp "<\\([^><\n]+\\)>")
9713 (setq type "tree-match"
9714 path (match-string 1))
9715 (throw 'match t)))
9716 (unless path
9717 (user-error "No link found"))
9719 ;; switch back to reference buffer
9720 ;; needed when if called in a temporary buffer through
9721 ;; org-open-link-from-string
9722 (with-current-buffer (or reference-buffer (current-buffer))
9724 ;; Remove any trailing spaces in path
9725 (if (string-match " +\\'" path)
9726 (setq path (replace-match "" t t path)))
9727 (if (and org-link-translation-function
9728 (fboundp org-link-translation-function))
9729 ;; Check if we need to translate the link
9730 (let ((tmp (funcall org-link-translation-function type path)))
9731 (setq type (car tmp) path (cdr tmp))))
9733 (cond
9735 ((assoc type org-link-protocols)
9736 (funcall (nth 1 (assoc type org-link-protocols)) path))
9738 ((equal type "help")
9739 (let ((f-or-v (intern path)))
9740 (cond ((fboundp f-or-v)
9741 (describe-function f-or-v))
9742 ((boundp f-or-v)
9743 (describe-variable f-or-v))
9744 (t (error "Not a known function or variable")))))
9746 ((equal type "mailto")
9747 (let ((cmd (car org-link-mailto-program))
9748 (args (cdr org-link-mailto-program)) args1
9749 (address path) (subject "") a)
9750 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9751 (setq address (match-string 1 path)
9752 subject (org-link-escape (match-string 2 path))))
9753 (while args
9754 (cond
9755 ((not (stringp (car args))) (push (pop args) args1))
9756 (t (setq a (pop args))
9757 (if (string-match "%a" a)
9758 (setq a (replace-match address t t a)))
9759 (if (string-match "%s" a)
9760 (setq a (replace-match subject t t a)))
9761 (push a args1))))
9762 (apply cmd (nreverse args1))))
9764 ((member type '("http" "https" "ftp" "news"))
9765 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9766 (org-link-escape
9767 path org-link-escape-chars-browser)
9768 path))))
9770 ((string= type "doi")
9771 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9772 (org-link-escape
9773 path org-link-escape-chars-browser)
9774 path))))
9776 ((member type '("message"))
9777 (browse-url (concat type ":" path)))
9779 ((string= type "tags")
9780 (org-tags-view arg path))
9782 ((string= type "tree-match")
9783 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9785 ((string= type "file")
9786 (if (string-match "::\\([0-9]+\\)\\'" path)
9787 (setq line (string-to-number (match-string 1 path))
9788 path (substring path 0 (match-beginning 0)))
9789 (if (string-match "::\\(.+\\)\\'" path)
9790 (setq search (match-string 1 path)
9791 path (substring path 0 (match-beginning 0)))))
9792 (if (string-match "[*?{]" (file-name-nondirectory path))
9793 (dired path)
9794 (org-open-file path arg line search)))
9796 ((string= type "shell")
9797 (let ((buf (generate-new-buffer "*Org Shell Output"))
9798 (cmd path))
9799 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9800 (string-match org-confirm-shell-link-not-regexp cmd))
9801 (not org-confirm-shell-link-function)
9802 (funcall org-confirm-shell-link-function
9803 (format "Execute \"%s\" in shell? "
9804 (org-add-props cmd nil
9805 'face 'org-warning))))
9806 (progn
9807 (message "Executing %s" cmd)
9808 (shell-command cmd buf)
9809 (if (featurep 'midnight)
9810 (setq clean-buffer-list-kill-buffer-names
9811 (cons buf clean-buffer-list-kill-buffer-names))))
9812 (error "Abort"))))
9814 ((string= type "elisp")
9815 (let ((cmd path))
9816 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9817 (string-match org-confirm-elisp-link-not-regexp cmd))
9818 (not org-confirm-elisp-link-function)
9819 (funcall org-confirm-elisp-link-function
9820 (format "Execute \"%s\" as elisp? "
9821 (org-add-props cmd nil
9822 'face 'org-warning))))
9823 (message "%s => %s" cmd
9824 (if (equal (string-to-char cmd) ?\()
9825 (eval (read cmd))
9826 (call-interactively (read cmd))))
9827 (error "Abort"))))
9829 ((and (string= type "thisfile")
9830 (run-hook-with-args-until-success
9831 'org-open-link-functions path)))
9833 ((string= type "thisfile")
9834 (if arg
9835 (switch-to-buffer-other-window
9836 (org-get-buffer-for-internal-link (current-buffer)))
9837 (org-mark-ring-push))
9838 (let ((cmd `(org-link-search
9839 ,path
9840 ,(cond ((equal arg '(4)) ''occur)
9841 ((equal arg '(16)) ''org-occur))
9842 ,pos)))
9843 (condition-case nil (let ((org-link-search-inhibit-query t))
9844 (eval cmd))
9845 (error (progn (widen) (eval cmd))))))
9847 (t (browse-url-at-point)))))))
9848 (move-marker org-open-link-marker nil)
9849 (run-hook-with-args 'org-follow-link-hook)))
9851 (defun org-offer-links-in-entry (&optional nth zero)
9852 "Offer links in the current entry and follow the selected link.
9853 If there is only one link, follow it immediately as well.
9854 If NTH is an integer, immediately pick the NTH link found.
9855 If ZERO is a string, check also this string for a link, and if
9856 there is one, offer it as link number zero."
9857 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9858 "\\(" org-angle-link-re "\\)\\|"
9859 "\\(" org-plain-link-re "\\)"))
9860 (cnt ?0)
9861 (in-emacs (if (integerp nth) nil nth))
9862 have-zero end links link c)
9863 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9864 (push (match-string 0 zero) links)
9865 (setq cnt (1- cnt) have-zero t))
9866 (save-excursion
9867 (org-back-to-heading t)
9868 (setq end (save-excursion (outline-next-heading) (point)))
9869 (while (re-search-forward re end t)
9870 (push (match-string 0) links))
9871 (setq links (org-uniquify (reverse links))))
9873 (cond
9874 ((null links)
9875 (message "No links"))
9876 ((equal (length links) 1)
9877 (setq link (list (car links))))
9878 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9879 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9880 (t ; we have to select a link
9881 (save-excursion
9882 (save-window-excursion
9883 (delete-other-windows)
9884 (with-output-to-temp-buffer "*Select Link*"
9885 (mapc (lambda (l)
9886 (if (not (string-match org-bracket-link-regexp l))
9887 (princ (format "[%c] %s\n" (incf cnt)
9888 (org-remove-angle-brackets l)))
9889 (if (match-end 3)
9890 (princ (format "[%c] %s (%s)\n" (incf cnt)
9891 (match-string 3 l) (match-string 1 l)))
9892 (princ (format "[%c] %s\n" (incf cnt)
9893 (match-string 1 l))))))
9894 links))
9895 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9896 (message "Select link to open, RET to open all:")
9897 (setq c (read-char-exclusive))
9898 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9899 (when (equal c ?q) (error "Abort"))
9900 (if (equal c ?\C-m)
9901 (setq link links)
9902 (setq nth (- c ?0))
9903 (if have-zero (setq nth (1+ nth)))
9904 (unless (and (integerp nth) (>= (length links) nth))
9905 (error "Invalid link selection"))
9906 (setq link (list (nth (1- nth) links))))))
9907 (if link
9908 (let ((buf (current-buffer)))
9909 (dolist (l link)
9910 (org-open-link-from-string l in-emacs buf))
9912 nil)))
9914 ;; Add special file links that specify the way of opening
9916 (org-add-link-type "file+sys" 'org-open-file-with-system)
9917 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9918 (defun org-open-file-with-system (path)
9919 "Open file at PATH using the system way of opening it."
9920 (org-open-file path 'system))
9921 (defun org-open-file-with-emacs (path)
9922 "Open file at PATH in Emacs."
9923 (org-open-file path 'emacs))
9924 (defun org-remove-file-link-modifiers ()
9925 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9926 (goto-char (point-min))
9927 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9928 (org-if-unprotected
9929 (replace-match "file:" t t))))
9930 (eval-after-load "org-exp"
9931 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9932 'org-remove-file-link-modifiers))
9934 ;;;; Time estimates
9936 (defun org-get-effort (&optional pom)
9937 "Get the effort estimate for the current entry."
9938 (org-entry-get pom org-effort-property))
9940 ;;; File search
9942 (defvar org-create-file-search-functions nil
9943 "List of functions to construct the right search string for a file link.
9944 These functions are called in turn with point at the location to
9945 which the link should point.
9947 A function in the hook should first test if it would like to
9948 handle this file type, for example by checking the `major-mode'
9949 or the file extension. If it decides not to handle this file, it
9950 should just return nil to give other functions a chance. If it
9951 does handle the file, it must return the search string to be used
9952 when following the link. The search string will be part of the
9953 file link, given after a double colon, and `org-open-at-point'
9954 will automatically search for it. If special measures must be
9955 taken to make the search successful, another function should be
9956 added to the companion hook `org-execute-file-search-functions',
9957 which see.
9959 A function in this hook may also use `setq' to set the variable
9960 `description' to provide a suggestion for the descriptive text to
9961 be used for this link when it gets inserted into an Org-mode
9962 buffer with \\[org-insert-link].")
9964 (defvar org-execute-file-search-functions nil
9965 "List of functions to execute a file search triggered by a link.
9967 Functions added to this hook must accept a single argument, the
9968 search string that was part of the file link, the part after the
9969 double colon. The function must first check if it would like to
9970 handle this search, for example by checking the `major-mode' or
9971 the file extension. If it decides not to handle this search, it
9972 should just return nil to give other functions a chance. If it
9973 does handle the search, it must return a non-nil value to keep
9974 other functions from trying.
9976 Each function can access the current prefix argument through the
9977 variable `current-prefix-argument'. Note that a single prefix is
9978 used to force opening a link in Emacs, so it may be good to only
9979 use a numeric or double prefix to guide the search function.
9981 In case this is needed, a function in this hook can also restore
9982 the window configuration before `org-open-at-point' was called using:
9984 (set-window-configuration org-window-config-before-follow-link)")
9986 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9987 (defun org-link-search (s &optional type avoid-pos stealth)
9988 "Search for a link search option.
9989 If S is surrounded by forward slashes, it is interpreted as a
9990 regular expression. In org-mode files, this will create an `org-occur'
9991 sparse tree. In ordinary files, `occur' will be used to list matches.
9992 If the current buffer is in `dired-mode', grep will be used to search
9993 in all files. If AVOID-POS is given, ignore matches near that position.
9995 When optional argument STEALTH is non-nil, do not modify
9996 visibility around point, thus ignoring
9997 `org-show-hierarchy-above', `org-show-following-heading' and
9998 `org-show-siblings' variables."
9999 (let ((case-fold-search t)
10000 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10001 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10002 (append '(("") (" ") ("\t") ("\n"))
10003 org-emphasis-alist)
10004 "\\|") "\\)"))
10005 (pos (point))
10006 (pre nil) (post nil)
10007 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10008 (cond
10009 ;; First check if there are any special search functions
10010 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10011 ;; Now try the builtin stuff
10012 ((and (equal (string-to-char s0) ?#)
10013 (> (length s0) 1)
10014 (save-excursion
10015 (goto-char (point-min))
10016 (and
10017 (re-search-forward
10018 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10019 (setq type 'dedicated
10020 pos (match-beginning 0))))
10021 ;; There is an exact target for this
10022 (goto-char pos)
10023 (org-back-to-heading t)))
10024 ((save-excursion
10025 (goto-char (point-min))
10026 (and
10027 (re-search-forward
10028 (concat "<<" (regexp-quote s0) ">>") nil t)
10029 (setq type 'dedicated
10030 pos (match-beginning 0))))
10031 ;; There is an exact target for this
10032 (goto-char pos))
10033 ((save-excursion
10034 (goto-char (point-min))
10035 (and
10036 (re-search-forward
10037 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10038 (setq type 'dedicated pos (match-beginning 0))))
10039 ;; Found an invisible target.
10040 (goto-char pos))
10041 ((save-excursion
10042 (goto-char (point-min))
10043 (and
10044 (re-search-forward
10045 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10046 (setq type 'dedicated pos (match-beginning 0))))
10047 ;; Found an element with a matching #+name affiliated keyword.
10048 (goto-char pos))
10049 ((and (string-match "^(\\(.*\\))$" s0)
10050 (save-excursion
10051 (goto-char (point-min))
10052 (and
10053 (re-search-forward
10054 (concat "[^[]" (regexp-quote
10055 (format org-coderef-label-format
10056 (match-string 1 s0))))
10057 nil t)
10058 (setq type 'dedicated
10059 pos (1+ (match-beginning 0))))))
10060 ;; There is a coderef target for this
10061 (goto-char pos))
10062 ((string-match "^/\\(.*\\)/$" s)
10063 ;; A regular expression
10064 (cond
10065 ((derived-mode-p 'org-mode)
10066 (org-occur (match-string 1 s)))
10067 ;;((eq major-mode 'dired-mode)
10068 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10069 (t (org-do-occur (match-string 1 s)))))
10070 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10071 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10072 (goto-char (point-min))
10073 (cond
10074 ((let (case-fold-search)
10075 (re-search-forward (format org-complex-heading-regexp-format
10076 (regexp-quote s))
10077 nil t))
10078 ;; OK, found a match
10079 (setq type 'dedicated)
10080 (goto-char (match-beginning 0)))
10081 ((and (not org-link-search-inhibit-query)
10082 (eq org-link-search-must-match-exact-headline 'query-to-create)
10083 (y-or-n-p "No match - create this as a new heading? "))
10084 (goto-char (point-max))
10085 (or (bolp) (newline))
10086 (insert "* " s "\n")
10087 (beginning-of-line 0))
10089 (goto-char pos)
10090 (error "No match"))))
10092 ;; A normal search string
10093 (when (equal (string-to-char s) ?*)
10094 ;; Anchor on headlines, post may include tags.
10095 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10096 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10097 s (substring s 1)))
10098 (remove-text-properties
10099 0 (length s)
10100 '(face nil mouse-face nil keymap nil fontified nil) s)
10101 ;; Make a series of regular expressions to find a match
10102 (setq words (org-split-string s "[ \n\r\t]+")
10104 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10105 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10106 "\\)" markers)
10107 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10108 re2a (concat "[ \t\r\n]" re2a_)
10109 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10110 re4 (concat "[^a-zA-Z_]" re4_)
10112 re1 (concat pre re2 post)
10113 re3 (concat pre (if pre re4_ re4) post)
10114 re5 (concat pre ".*" re4)
10115 re2 (concat pre re2)
10116 re2a (concat pre (if pre re2a_ re2a))
10117 re4 (concat pre (if pre re4_ re4))
10118 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10119 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10120 re5 "\\)"
10122 (cond
10123 ((eq type 'org-occur) (org-occur reall))
10124 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10125 (t (goto-char (point-min))
10126 (setq type 'fuzzy)
10127 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10128 (org-search-not-self 1 re1 nil t)
10129 (org-search-not-self 1 re2 nil t)
10130 (org-search-not-self 1 re2a nil t)
10131 (org-search-not-self 1 re3 nil t)
10132 (org-search-not-self 1 re4 nil t)
10133 (org-search-not-self 1 re5 nil t)
10135 (goto-char (match-beginning 1))
10136 (goto-char pos)
10137 (error "No match"))))))
10138 (and (derived-mode-p 'org-mode)
10139 (not stealth)
10140 (org-show-context 'link-search))
10141 type))
10143 (defun org-search-not-self (group &rest args)
10144 "Execute `re-search-forward', but only accept matches that do not
10145 enclose the position of `org-open-link-marker'."
10146 (let ((m org-open-link-marker))
10147 (catch 'exit
10148 (while (apply 're-search-forward args)
10149 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10150 (goto-char (match-end group))
10151 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10152 (> (match-beginning 0) (marker-position m))
10153 (< (match-end 0) (marker-position m)))
10154 (save-match-data
10155 (or (not (org-in-regexp
10156 org-bracket-link-analytic-regexp 1))
10157 (not (match-end 4)) ; no description
10158 (and (<= (match-beginning 4) (point))
10159 (>= (match-end 4) (point))))))
10160 (throw 'exit (point))))))))
10162 (defun org-get-buffer-for-internal-link (buffer)
10163 "Return a buffer to be used for displaying the link target of internal links."
10164 (cond
10165 ((not org-display-internal-link-with-indirect-buffer)
10166 buffer)
10167 ((string-match "(Clone)$" (buffer-name buffer))
10168 (message "Buffer is already a clone, not making another one")
10169 ;; we also do not modify visibility in this case
10170 buffer)
10171 (t ; make a new indirect buffer for displaying the link
10172 (let* ((bn (buffer-name buffer))
10173 (ibn (concat bn "(Clone)"))
10174 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10175 (with-current-buffer ib (org-overview))
10176 ib))))
10178 (defun org-do-occur (regexp &optional cleanup)
10179 "Call the Emacs command `occur'.
10180 If CLEANUP is non-nil, remove the printout of the regular expression
10181 in the *Occur* buffer. This is useful if the regex is long and not useful
10182 to read."
10183 (occur regexp)
10184 (when cleanup
10185 (let ((cwin (selected-window)) win beg end)
10186 (when (setq win (get-buffer-window "*Occur*"))
10187 (select-window win))
10188 (goto-char (point-min))
10189 (when (re-search-forward "match[a-z]+" nil t)
10190 (setq beg (match-end 0))
10191 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10192 (setq end (1- (match-beginning 0)))))
10193 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10194 (goto-char (point-min))
10195 (select-window cwin))))
10197 ;;; The mark ring for links jumps
10199 (defvar org-mark-ring nil
10200 "Mark ring for positions before jumps in Org-mode.")
10201 (defvar org-mark-ring-last-goto nil
10202 "Last position in the mark ring used to go back.")
10203 ;; Fill and close the ring
10204 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10205 (loop for i from 1 to org-mark-ring-length do
10206 (push (make-marker) org-mark-ring))
10207 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10208 org-mark-ring)
10210 (defun org-mark-ring-push (&optional pos buffer)
10211 "Put the current position or POS into the mark ring and rotate it."
10212 (interactive)
10213 (setq pos (or pos (point)))
10214 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10215 (move-marker (car org-mark-ring)
10216 (or pos (point))
10217 (or buffer (current-buffer)))
10218 (message "%s"
10219 (substitute-command-keys
10220 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10222 (defun org-mark-ring-goto (&optional n)
10223 "Jump to the previous position in the mark ring.
10224 With prefix arg N, jump back that many stored positions. When
10225 called several times in succession, walk through the entire ring.
10226 Org-mode commands jumping to a different position in the current file,
10227 or to another Org-mode file, automatically push the old position
10228 onto the ring."
10229 (interactive "p")
10230 (let (p m)
10231 (if (eq last-command this-command)
10232 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10233 (setq p org-mark-ring))
10234 (setq org-mark-ring-last-goto p)
10235 (setq m (car p))
10236 (org-pop-to-buffer-same-window (marker-buffer m))
10237 (goto-char m)
10238 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10240 (defun org-remove-angle-brackets (s)
10241 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10242 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10244 (defun org-add-angle-brackets (s)
10245 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10246 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10248 (defun org-remove-double-quotes (s)
10249 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10250 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10253 ;;; Following specific links
10255 (defun org-follow-timestamp-link ()
10256 "Open an agenda view for the time-stamp date/range at point."
10257 (cond
10258 ((org-at-date-range-p t)
10259 (let ((org-agenda-start-on-weekday)
10260 (t1 (match-string 1))
10261 (t2 (match-string 2)) tt1 tt2)
10262 (setq tt1 (time-to-days (org-time-string-to-time t1))
10263 tt2 (time-to-days (org-time-string-to-time t2)))
10264 (let ((org-agenda-buffer-tmp-name
10265 (format "*Org Agenda(a:%s)"
10266 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10267 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10268 ((org-at-timestamp-p t)
10269 (let ((org-agenda-buffer-tmp-name
10270 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10271 (org-agenda-list nil (time-to-days (org-time-string-to-time
10272 (substring (match-string 1) 0 10)))
10273 1)))
10274 (t (error "This should not happen"))))
10277 ;;; Following file links
10278 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10279 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10280 (declare-function mailcap-mime-info
10281 "mailcap" (string &optional request no-decode))
10282 (defvar org-wait nil)
10283 (defun org-open-file (path &optional in-emacs line search)
10284 "Open the file at PATH.
10285 First, this expands any special file name abbreviations. Then the
10286 configuration variable `org-file-apps' is checked if it contains an
10287 entry for this file type, and if yes, the corresponding command is launched.
10289 If no application is found, Emacs simply visits the file.
10291 With optional prefix argument IN-EMACS, Emacs will visit the file.
10292 With a double \\[universal-argument] \\[universal-argument] \
10293 prefix arg, Org tries to avoid opening in Emacs
10294 and to use an external application to visit the file.
10296 Optional LINE specifies a line to go to, optional SEARCH a string
10297 to search for. If LINE or SEARCH is given, the file will be
10298 opened in Emacs, unless an entry from org-file-apps that makes
10299 use of groups in a regexp matches.
10301 If you want to change the way frames are used when following a
10302 link, please customize `org-link-frame-setup'.
10304 If the file does not exist, an error is thrown."
10305 (let* ((file (if (equal path "")
10306 buffer-file-name
10307 (substitute-in-file-name (expand-file-name path))))
10308 (file-apps (append org-file-apps (org-default-apps)))
10309 (apps (org-remove-if
10310 'org-file-apps-entry-match-against-dlink-p file-apps))
10311 (apps-dlink (org-remove-if-not
10312 'org-file-apps-entry-match-against-dlink-p file-apps))
10313 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10314 (dirp (if remp nil (file-directory-p file)))
10315 (file (if (and dirp org-open-directory-means-index-dot-org)
10316 (concat (file-name-as-directory file) "index.org")
10317 file))
10318 (a-m-a-p (assq 'auto-mode apps))
10319 (dfile (downcase file))
10320 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10321 (link (cond ((and (eq line nil)
10322 (eq search nil))
10323 file)
10324 (line
10325 (concat file "::" (number-to-string line)))
10326 (search
10327 (concat file "::" search))))
10328 (dlink (downcase link))
10329 (old-buffer (current-buffer))
10330 (old-pos (point))
10331 (old-mode major-mode)
10332 ext cmd link-match-data)
10333 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10334 (setq ext (match-string 1 dfile))
10335 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10336 (setq ext (match-string 1 dfile))))
10337 (cond
10338 ((member in-emacs '((16) system))
10339 (setq cmd (cdr (assoc 'system apps))))
10340 (in-emacs (setq cmd 'emacs))
10342 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10343 (and dirp (cdr (assoc 'directory apps)))
10344 ; first, try matching against apps-dlink
10345 ; if we get a match here, store the match data for later
10346 (let ((match (assoc-default dlink apps-dlink
10347 'string-match)))
10348 (if match
10349 (progn (setq link-match-data (match-data))
10350 match)
10351 (progn (setq in-emacs (or in-emacs line search))
10352 nil))) ; if we have no match in apps-dlink,
10353 ; always open the file in emacs if line or search
10354 ; is given (for backwards compatibility)
10355 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10356 'string-match)
10357 (cdr (assoc ext apps))
10358 (cdr (assoc t apps))))))
10359 (when (eq cmd 'system)
10360 (setq cmd (cdr (assoc 'system apps))))
10361 (when (eq cmd 'default)
10362 (setq cmd (cdr (assoc t apps))))
10363 (when (eq cmd 'mailcap)
10364 (require 'mailcap)
10365 (mailcap-parse-mailcaps)
10366 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10367 (command (mailcap-mime-info mime-type)))
10368 (if (stringp command)
10369 (setq cmd command)
10370 (setq cmd 'emacs))))
10371 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10372 (not (file-exists-p file))
10373 (not org-open-non-existing-files))
10374 (error "No such file: %s" file))
10375 (cond
10376 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10377 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10378 (while (string-match "['\"]%s['\"]" cmd)
10379 (setq cmd (replace-match "%s" t t cmd)))
10380 (while (string-match "%s" cmd)
10381 (setq cmd (replace-match
10382 (save-match-data
10383 (shell-quote-argument
10384 (convert-standard-filename file)))
10385 t t cmd)))
10387 ;; Replace "%1", "%2" etc. in command with group matches from regex
10388 (save-match-data
10389 (let ((match-index 1)
10390 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10391 (set-match-data link-match-data)
10392 (while (<= match-index number-of-groups)
10393 (let ((regex (concat "%" (number-to-string match-index)))
10394 (replace-with (match-string match-index dlink)))
10395 (while (string-match regex cmd)
10396 (setq cmd (replace-match replace-with t t cmd))))
10397 (setq match-index (+ match-index 1)))))
10399 (save-window-excursion
10400 (start-process-shell-command cmd nil cmd)
10401 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10403 ((or (stringp cmd)
10404 (eq cmd 'emacs))
10405 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10406 (widen)
10407 (if line (org-goto-line line)
10408 (if search (org-link-search search))))
10409 ((consp cmd)
10410 (let ((file (convert-standard-filename file)))
10411 (save-match-data
10412 (set-match-data link-match-data)
10413 (eval cmd))))
10414 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10415 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10416 (or (not (equal old-buffer (current-buffer)))
10417 (not (equal old-pos (point))))
10418 (org-mark-ring-push old-pos old-buffer))))
10420 (defun org-file-apps-entry-match-against-dlink-p (entry)
10421 "This function returns non-nil if `entry' uses a regular
10422 expression which should be matched against the whole link by
10423 org-open-file.
10425 It assumes that is the case when the entry uses a regular
10426 expression which has at least one grouping construct and the
10427 action is either a lisp form or a command string containing
10428 '%1', i.e. using at least one subexpression match as a
10429 parameter."
10430 (let ((selector (car entry))
10431 (action (cdr entry)))
10432 (if (stringp selector)
10433 (and (> (regexp-opt-depth selector) 0)
10434 (or (and (stringp action)
10435 (string-match "%[0-9]" action))
10436 (consp action)))
10437 nil)))
10439 (defun org-default-apps ()
10440 "Return the default applications for this operating system."
10441 (cond
10442 ((eq system-type 'darwin)
10443 org-file-apps-defaults-macosx)
10444 ((eq system-type 'windows-nt)
10445 org-file-apps-defaults-windowsnt)
10446 (t org-file-apps-defaults-gnu)))
10448 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10449 "Convert extensions to regular expressions in the cars of LIST.
10450 Also, weed out any non-string entries, because the return value is used
10451 only for regexp matching.
10452 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10453 point to the symbol `emacs', indicating that the file should
10454 be opened in Emacs."
10455 (append
10456 (delq nil
10457 (mapcar (lambda (x)
10458 (if (not (stringp (car x)))
10460 (if (string-match "\\W" (car x))
10462 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10463 list))
10464 (if add-auto-mode
10465 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10467 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10468 (defun org-file-remote-p (file)
10469 "Test whether FILE specifies a location on a remote system.
10470 Return non-nil if the location is indeed remote.
10472 For example, the filename \"/user@host:/foo\" specifies a location
10473 on the system \"/user@host:\"."
10474 (cond ((fboundp 'file-remote-p)
10475 (file-remote-p file))
10476 ((fboundp 'tramp-handle-file-remote-p)
10477 (tramp-handle-file-remote-p file))
10478 ((and (boundp 'ange-ftp-name-format)
10479 (string-match (car ange-ftp-name-format) file))
10480 t)))
10483 ;;;; Refiling
10485 (defun org-get-org-file ()
10486 "Read a filename, with default directory `org-directory'."
10487 (let ((default (or org-default-notes-file remember-data-file)))
10488 (read-file-name (format "File name [%s]: " default)
10489 (file-name-as-directory org-directory)
10490 default)))
10492 (defun org-notes-order-reversed-p ()
10493 "Check if the current file should receive notes in reversed order."
10494 (cond
10495 ((not org-reverse-note-order) nil)
10496 ((eq t org-reverse-note-order) t)
10497 ((not (listp org-reverse-note-order)) nil)
10498 (t (catch 'exit
10499 (let ((all org-reverse-note-order)
10500 entry)
10501 (while (setq entry (pop all))
10502 (if (string-match (car entry) buffer-file-name)
10503 (throw 'exit (cdr entry))))
10504 nil)))))
10506 (defvar org-refile-target-table nil
10507 "The list of refile targets, created by `org-refile'.")
10509 (defvar org-agenda-new-buffers nil
10510 "Buffers created to visit agenda files.")
10512 (defvar org-refile-cache nil
10513 "Cache for refile targets.")
10515 (defvar org-refile-markers nil
10516 "All the markers used for caching refile locations.")
10518 (defun org-refile-marker (pos)
10519 "Get a new refile marker, but only if caching is in use."
10520 (if (not org-refile-use-cache)
10522 (let ((m (make-marker)))
10523 (move-marker m pos)
10524 (push m org-refile-markers)
10525 m)))
10527 (defun org-refile-cache-clear ()
10528 "Clear the refile cache and disable all the markers."
10529 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10530 (setq org-refile-markers nil)
10531 (setq org-refile-cache nil)
10532 (message "Refile cache has been cleared"))
10534 (defun org-refile-cache-check-set (set)
10535 "Check if all the markers in the cache still have live buffers."
10536 (let (marker)
10537 (catch 'exit
10538 (while (and set (setq marker (nth 3 (pop set))))
10539 ;; if org-refile-use-outline-path is 'file, marker may be nil
10540 (when (and marker (null (marker-buffer marker)))
10541 (message "not found") (sit-for 3)
10542 (throw 'exit nil)))
10543 t)))
10545 (defun org-refile-cache-put (set &rest identifiers)
10546 "Push the refile targets SET into the cache, under IDENTIFIERS."
10547 (let* ((key (sha1 (prin1-to-string identifiers)))
10548 (entry (assoc key org-refile-cache)))
10549 (if entry
10550 (setcdr entry set)
10551 (push (cons key set) org-refile-cache))))
10553 (defun org-refile-cache-get (&rest identifiers)
10554 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10555 (cond
10556 ((not org-refile-cache) nil)
10557 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10559 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10560 org-refile-cache))))
10561 (and set (org-refile-cache-check-set set) set)))))
10563 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10564 "Produce a table with refile targets."
10565 (let ((case-fold-search nil)
10566 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10567 (entries (or org-refile-targets '((nil . (:level . 1)))))
10568 targets tgs txt re files f desc descre fast-path-p level pos0)
10569 (message "Getting targets...")
10570 (with-current-buffer (or default-buffer (current-buffer))
10571 (while (setq entry (pop entries))
10572 (setq files (car entry) desc (cdr entry))
10573 (setq fast-path-p nil)
10574 (cond
10575 ((null files) (setq files (list (current-buffer))))
10576 ((eq files 'org-agenda-files)
10577 (setq files (org-agenda-files 'unrestricted)))
10578 ((and (symbolp files) (fboundp files))
10579 (setq files (funcall files)))
10580 ((and (symbolp files) (boundp files))
10581 (setq files (symbol-value files))))
10582 (if (stringp files) (setq files (list files)))
10583 (cond
10584 ((eq (car desc) :tag)
10585 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10586 ((eq (car desc) :todo)
10587 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10588 ((eq (car desc) :regexp)
10589 (setq descre (cdr desc)))
10590 ((eq (car desc) :level)
10591 (setq descre (concat "^\\*\\{" (number-to-string
10592 (if org-odd-levels-only
10593 (1- (* 2 (cdr desc)))
10594 (cdr desc)))
10595 "\\}[ \t]")))
10596 ((eq (car desc) :maxlevel)
10597 (setq fast-path-p t)
10598 (setq descre (concat "^\\*\\{1," (number-to-string
10599 (if org-odd-levels-only
10600 (1- (* 2 (cdr desc)))
10601 (cdr desc)))
10602 "\\}[ \t]")))
10603 (t (error "Bad refiling target description %s" desc)))
10604 (while (setq f (pop files))
10605 (with-current-buffer
10606 (if (bufferp f) f (org-get-agenda-file-buffer f))
10608 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10609 (progn
10610 (if (bufferp f) (setq f (buffer-file-name
10611 (buffer-base-buffer f))))
10612 (setq f (and f (expand-file-name f)))
10613 (if (eq org-refile-use-outline-path 'file)
10614 (push (list (file-name-nondirectory f) f nil nil) tgs))
10615 (save-excursion
10616 (save-restriction
10617 (widen)
10618 (goto-char (point-min))
10619 (while (re-search-forward descre nil t)
10620 (goto-char (setq pos0 (point-at-bol)))
10621 (catch 'next
10622 (when org-refile-target-verify-function
10623 (save-match-data
10624 (or (funcall org-refile-target-verify-function)
10625 (throw 'next t))))
10626 (when (and (looking-at org-complex-heading-regexp)
10627 (not (member (match-string 4) excluded-entries))
10628 (match-string 4))
10629 (setq level (org-reduced-level
10630 (- (match-end 1) (match-beginning 1)))
10631 txt (org-link-display-format (match-string 4))
10632 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10633 re (format org-complex-heading-regexp-format
10634 (regexp-quote (match-string 4))))
10635 (when org-refile-use-outline-path
10636 (setq txt (mapconcat
10637 'org-protect-slash
10638 (append
10639 (if (eq org-refile-use-outline-path
10640 'file)
10641 (list (file-name-nondirectory
10642 (buffer-file-name
10643 (buffer-base-buffer))))
10644 (if (eq org-refile-use-outline-path
10645 'full-file-path)
10646 (list (buffer-file-name
10647 (buffer-base-buffer)))))
10648 (org-get-outline-path fast-path-p
10649 level txt)
10650 (list txt))
10651 "/")))
10652 (push (list txt f re (org-refile-marker (point)))
10653 tgs)))
10654 (when (= (point) pos0)
10655 ;; verification function has not moved point
10656 (goto-char (point-at-eol))))))))
10657 (when org-refile-use-cache
10658 (org-refile-cache-put tgs (buffer-file-name) descre))
10659 (setq targets (append tgs targets))
10660 ))))
10661 (message "Getting targets...done")
10662 (nreverse targets)))
10664 (defun org-protect-slash (s)
10665 (while (string-match "/" s)
10666 (setq s (replace-match "\\" t t s)))
10669 (defvar org-olpa (make-vector 20 nil))
10671 (defun org-get-outline-path (&optional fastp level heading)
10672 "Return the outline path to the current entry, as a list.
10674 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10675 routine which makes outline path derivations for an entire file,
10676 avoiding backtracing. Refile target collection makes use of that."
10677 (if fastp
10678 (progn
10679 (if (> level 19)
10680 (error "Outline path failure, more than 19 levels"))
10681 (loop for i from level upto 19 do
10682 (aset org-olpa i nil))
10683 (prog1
10684 (delq nil (append org-olpa nil))
10685 (aset org-olpa level heading)))
10686 (let (rtn case-fold-search)
10687 (save-excursion
10688 (save-restriction
10689 (widen)
10690 (while (org-up-heading-safe)
10691 (when (looking-at org-complex-heading-regexp)
10692 (push (org-match-string-no-properties 4) rtn)))
10693 rtn)))))
10695 (defun org-format-outline-path (path &optional width prefix)
10696 "Format the outline path PATH for display.
10697 Width is the maximum number of characters that is available.
10698 Prefix is a prefix to be included in the returned string,
10699 such as the file name."
10700 (setq width (or width 79))
10701 (if prefix (setq width (- width (length prefix))))
10702 (if (not path)
10703 (or prefix "")
10704 (let* ((nsteps (length path))
10705 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10706 (maxwidth (if (<= total-width width)
10707 10000 ;; everything fits
10708 ;; we need to shorten the level headings
10709 (/ (- width nsteps) nsteps)))
10710 (org-odd-levels-only nil)
10711 (n 0)
10712 (total (1+ (length prefix))))
10713 (setq maxwidth (max maxwidth 10))
10714 (concat prefix
10715 (mapconcat
10716 (lambda (h)
10717 (setq n (1+ n))
10718 (if (and (= n nsteps) (< maxwidth 10000))
10719 (setq maxwidth (- total-width total)))
10720 (if (< (length h) maxwidth)
10721 (progn (setq total (+ total (length h) 1)) h)
10722 (setq h (substring h 0 (- maxwidth 2))
10723 total (+ total maxwidth 1))
10724 (if (string-match "[ \t]+\\'" h)
10725 (setq h (substring h 0 (match-beginning 0))))
10726 (setq h (concat h "..")))
10727 (org-add-props h nil 'face
10728 (nth (% (1- n) org-n-level-faces)
10729 org-level-faces))
10731 path "/")))))
10733 (defun org-display-outline-path (&optional file current)
10734 "Display the current outline path in the echo area."
10735 (interactive "P")
10736 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10737 (case-fold-search nil)
10738 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10739 (if current (setq path (append path
10740 (save-excursion
10741 (org-back-to-heading t)
10742 (if (looking-at org-complex-heading-regexp)
10743 (list (match-string 4)))))))
10744 (message "%s"
10745 (org-format-outline-path
10746 path
10747 (1- (frame-width))
10748 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10750 (defvar org-refile-history nil
10751 "History for refiling operations.")
10753 (defvar org-after-refile-insert-hook nil
10754 "Hook run after `org-refile' has inserted its stuff at the new location.
10755 Note that this is still *before* the stuff will be removed from
10756 the *old* location.")
10758 (defvar org-capture-last-stored-marker)
10759 (defun org-refile (&optional goto default-buffer rfloc)
10760 "Move the entry or entries at point to another heading.
10761 The list of target headings is compiled using the information in
10762 `org-refile-targets', which see.
10764 At the target location, the entry is filed as a subitem of the target
10765 heading. Depending on `org-reverse-note-order', the new subitem will
10766 either be the first or the last subitem.
10768 If there is an active region, all entries in that region will be moved.
10769 However, the region must fulfill the requirement that the first heading
10770 is the first one sets the top-level of the moved text - at most siblings
10771 below it are allowed.
10773 With prefix arg GOTO, the command will only visit the target location
10774 and not actually move anything.
10776 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10777 go to the location where the last refiling operation has put the subtree.
10778 With a prefix argument of `2', refile to the running clock.
10780 RFLOC can be a refile location obtained in a different way.
10782 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10784 If you are using target caching (see `org-refile-use-cache'),
10785 you have to clear the target cache in order to find new targets.
10786 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10787 prefix argument (`C-u C-u C-u C-c C-w')."
10789 (interactive "P")
10790 (if (member goto '(0 (64)))
10791 (org-refile-cache-clear)
10792 (let* ((cbuf (current-buffer))
10793 (regionp (org-region-active-p))
10794 (region-start (and regionp (region-beginning)))
10795 (region-end (and regionp (region-end)))
10796 (region-length (and regionp (- region-end region-start)))
10797 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10798 pos it nbuf file re level reversed)
10799 (setq last-command nil)
10800 (when regionp
10801 (goto-char region-start)
10802 (or (bolp) (goto-char (point-at-bol)))
10803 (setq region-start (point))
10804 (unless (or (org-kill-is-subtree-p
10805 (buffer-substring region-start region-end))
10806 (prog1 org-refile-active-region-within-subtree
10807 (org-toggle-heading)))
10808 (error "The region is not a (sequence of) subtree(s)")))
10809 (if (equal goto '(16))
10810 (org-refile-goto-last-stored)
10811 (when (or
10812 (and (equal goto 2)
10813 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10814 (prog1
10815 (setq it (list (or org-clock-heading "running clock")
10816 (buffer-file-name
10817 (marker-buffer org-clock-hd-marker))
10819 (marker-position org-clock-hd-marker)))
10820 (setq goto nil)))
10821 (setq it (or rfloc
10822 (let (heading-text)
10823 (save-excursion
10824 (unless goto
10825 (org-back-to-heading t)
10826 (setq heading-text
10827 (nth 4 (org-heading-components))))
10828 (org-refile-get-location
10829 (cond (goto "Goto")
10830 (regionp "Refile region to")
10831 (t (concat "Refile subtree \""
10832 heading-text "\" to")))
10833 default-buffer
10834 (and (not (equal '(4) goto))
10835 org-refile-allow-creating-parent-nodes)
10836 goto))))))
10837 (setq file (nth 1 it)
10838 re (nth 2 it)
10839 pos (nth 3 it))
10840 (if (and (not goto)
10842 (equal (buffer-file-name) file)
10843 (if regionp
10844 (and (>= pos region-start)
10845 (<= pos region-end))
10846 (and (>= pos (point))
10847 (< pos (save-excursion
10848 (org-end-of-subtree t t))))))
10849 (error "Cannot refile to position inside the tree or region"))
10851 (setq nbuf (or (find-buffer-visiting file)
10852 (find-file-noselect file)))
10853 (if goto
10854 (progn
10855 (org-pop-to-buffer-same-window nbuf)
10856 (goto-char pos)
10857 (org-show-context 'org-goto))
10858 (if regionp
10859 (progn
10860 (org-kill-new (buffer-substring region-start region-end))
10861 (org-save-markers-in-region region-start region-end))
10862 (org-copy-subtree 1 nil t))
10863 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10864 (find-file-noselect file)))
10865 (setq reversed (org-notes-order-reversed-p))
10866 (save-excursion
10867 (save-restriction
10868 (widen)
10869 (if pos
10870 (progn
10871 (goto-char pos)
10872 (looking-at org-outline-regexp)
10873 (setq level (org-get-valid-level (funcall outline-level) 1))
10874 (goto-char
10875 (if reversed
10876 (or (outline-next-heading) (point-max))
10877 (or (save-excursion (org-get-next-sibling))
10878 (org-end-of-subtree t t)
10879 (point-max)))))
10880 (setq level 1)
10881 (if (not reversed)
10882 (goto-char (point-max))
10883 (goto-char (point-min))
10884 (or (outline-next-heading) (goto-char (point-max)))))
10885 (if (not (bolp)) (newline))
10886 (org-paste-subtree level)
10887 (when org-log-refile
10888 (org-add-log-setup 'refile nil nil 'findpos
10889 org-log-refile)
10890 (unless (eq org-log-refile 'note)
10891 (save-excursion (org-add-log-note))))
10892 (and org-auto-align-tags
10893 (let ((org-loop-over-headlines-in-active-region nil))
10894 (org-set-tags nil t)))
10895 (with-demoted-errors
10896 (bookmark-set "org-refile-last-stored"))
10897 ;; If we are refiling for capture, make sure that the
10898 ;; last-capture pointers point here
10899 (when (org-bound-and-true-p org-refile-for-capture)
10900 (with-demoted-errors
10901 (bookmark-set "org-capture-last-stored-marker"))
10902 (move-marker org-capture-last-stored-marker (point)))
10903 (if (fboundp 'deactivate-mark) (deactivate-mark))
10904 (run-hooks 'org-after-refile-insert-hook))))
10905 (if regionp
10906 (delete-region (point) (+ (point) region-length))
10907 (org-cut-subtree))
10908 (when (featurep 'org-inlinetask)
10909 (org-inlinetask-remove-END-maybe))
10910 (setq org-markers-to-move nil)
10911 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10913 (defun org-refile-goto-last-stored ()
10914 "Go to the location where the last refile was stored."
10915 (interactive)
10916 (bookmark-jump "org-refile-last-stored")
10917 (message "This is the location of the last refile"))
10919 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10920 no-exclude)
10921 "Prompt the user for a refile location, using PROMPT.
10922 PROMPT should not be suffixed with a colon and a space, because
10923 this function appends the default value from
10924 `org-refile-history' automatically, if that is not empty.
10925 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10926 this is used for the GOTO interface."
10927 (let ((org-refile-targets org-refile-targets)
10928 (org-refile-use-outline-path org-refile-use-outline-path)
10929 excluded-entries)
10930 (when (and (derived-mode-p 'org-mode)
10931 (not org-refile-use-cache)
10932 (not no-exclude))
10933 (org-map-tree
10934 (lambda()
10935 (setq excluded-entries
10936 (append excluded-entries (list (org-get-heading t t)))))))
10937 (setq org-refile-target-table
10938 (org-refile-get-targets default-buffer excluded-entries)))
10939 (unless org-refile-target-table
10940 (error "No refile targets"))
10941 (let* ((prompt (concat prompt
10942 (and (car org-refile-history)
10943 (concat " (default " (car org-refile-history) ")"))
10944 ": "))
10945 (cbuf (current-buffer))
10946 (partial-completion-mode nil)
10947 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10948 (cfunc (if (and org-refile-use-outline-path
10949 org-outline-path-complete-in-steps)
10950 'org-olpath-completing-read
10951 'org-icompleting-read))
10952 (extra (if org-refile-use-outline-path "/" ""))
10953 (filename (and cfn (expand-file-name cfn)))
10954 (tbl (mapcar
10955 (lambda (x)
10956 (if (and (not (member org-refile-use-outline-path
10957 '(file full-file-path)))
10958 (not (equal filename (nth 1 x))))
10959 (cons (concat (car x) extra " ("
10960 (file-name-nondirectory (nth 1 x)) ")")
10961 (cdr x))
10962 (cons (concat (car x) extra) (cdr x))))
10963 org-refile-target-table))
10964 (completion-ignore-case t)
10965 pa answ parent-target child parent old-hist)
10966 (setq old-hist org-refile-history)
10967 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10968 nil 'org-refile-history (car org-refile-history)))
10969 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10970 (org-refile-check-position pa)
10971 (if pa
10972 (progn
10973 (when (or (not org-refile-history)
10974 (not (eq old-hist org-refile-history))
10975 (not (equal (car pa) (car org-refile-history))))
10976 (setq org-refile-history
10977 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10978 org-refile-history
10979 (cdr org-refile-history))))
10980 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10981 (pop org-refile-history)))
10983 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10984 (progn
10985 (setq parent (match-string 1 answ)
10986 child (match-string 2 answ))
10987 (setq parent-target (or (assoc parent tbl)
10988 (assoc (concat parent "/") tbl)))
10989 (when (and parent-target
10990 (or (eq new-nodes t)
10991 (and (eq new-nodes 'confirm)
10992 (y-or-n-p (format "Create new node \"%s\"? "
10993 child)))))
10994 (org-refile-new-child parent-target child)))
10995 (error "Invalid target location")))))
10997 (declare-function org-string-nw-p "org-macs" (s))
10998 (defun org-refile-check-position (refile-pointer)
10999 "Check if the refile pointer matches the headline to which it points."
11000 (let* ((file (nth 1 refile-pointer))
11001 (re (nth 2 refile-pointer))
11002 (pos (nth 3 refile-pointer))
11003 buffer)
11004 (if (and (not (markerp pos)) (not file))
11005 (error "Please save the buffer to a file before refiling")
11006 (when (org-string-nw-p re)
11007 (setq buffer (if (markerp pos)
11008 (marker-buffer pos)
11009 (or (find-buffer-visiting file)
11010 (find-file-noselect file))))
11011 (with-current-buffer buffer
11012 (save-excursion
11013 (save-restriction
11014 (widen)
11015 (goto-char pos)
11016 (beginning-of-line 1)
11017 (unless (org-looking-at-p re)
11018 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11020 (defun org-refile-new-child (parent-target child)
11021 "Use refile target PARENT-TARGET to add new CHILD below it."
11022 (unless parent-target
11023 (error "Cannot find parent for new node"))
11024 (let ((file (nth 1 parent-target))
11025 (pos (nth 3 parent-target))
11026 level)
11027 (with-current-buffer (or (find-buffer-visiting file)
11028 (find-file-noselect file))
11029 (save-excursion
11030 (save-restriction
11031 (widen)
11032 (if pos
11033 (goto-char pos)
11034 (goto-char (point-max))
11035 (if (not (bolp)) (newline)))
11036 (when (looking-at org-outline-regexp)
11037 (setq level (funcall outline-level))
11038 (org-end-of-subtree t t))
11039 (org-back-over-empty-lines)
11040 (insert "\n" (make-string
11041 (if pos (org-get-valid-level level 1) 1) ?*)
11042 " " child "\n")
11043 (beginning-of-line 0)
11044 (list (concat (car parent-target) "/" child) file "" (point)))))))
11046 (defun org-olpath-completing-read (prompt collection &rest args)
11047 "Read an outline path like a file name."
11048 (let ((thetable collection)
11049 (org-completion-use-ido nil) ; does not work with ido.
11050 (org-completion-use-iswitchb nil)) ; or iswitchb
11051 (apply
11052 'org-icompleting-read prompt
11053 (lambda (string predicate &optional flag)
11054 (let (rtn r f (l (length string)))
11055 (cond
11056 ((eq flag nil)
11057 ;; try completion
11058 (try-completion string thetable))
11059 ((eq flag t)
11060 ;; all-completions
11061 (setq rtn (all-completions string thetable predicate))
11062 (mapcar
11063 (lambda (x)
11064 (setq r (substring x l))
11065 (if (string-match " ([^)]*)$" x)
11066 (setq f (match-string 0 x))
11067 (setq f ""))
11068 (if (string-match "/" r)
11069 (concat string (substring r 0 (match-end 0)) f)
11071 rtn))
11072 ((eq flag 'lambda)
11073 ;; exact match?
11074 (assoc string thetable)))))
11075 args)))
11077 ;;;; Dynamic blocks
11079 (defun org-find-dblock (name)
11080 "Find the first dynamic block with name NAME in the buffer.
11081 If not found, stay at current position and return nil."
11082 (let ((case-fold-search t) pos)
11083 (save-excursion
11084 (goto-char (point-min))
11085 (setq pos (and (re-search-forward
11086 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11087 (match-beginning 0))))
11088 (if pos (goto-char pos))
11089 pos))
11091 (defconst org-dblock-start-re
11092 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11093 "Matches the start line of a dynamic block, with parameters.")
11095 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11096 "Matches the end of a dynamic block.")
11098 (defun org-create-dblock (plist)
11099 "Create a dynamic block section, with parameters taken from PLIST.
11100 PLIST must contain a :name entry which is used as name of the block."
11101 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11102 (end-of-line 1)
11103 (newline))
11104 (let ((col (current-column))
11105 (name (plist-get plist :name)))
11106 (insert "#+BEGIN: " name)
11107 (while plist
11108 (if (eq (car plist) :name)
11109 (setq plist (cddr plist))
11110 (insert " " (prin1-to-string (pop plist)))))
11111 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11112 (beginning-of-line -2)))
11114 (defun org-prepare-dblock ()
11115 "Prepare dynamic block for refresh.
11116 This empties the block, puts the cursor at the insert position and returns
11117 the property list including an extra property :name with the block name."
11118 (unless (looking-at org-dblock-start-re)
11119 (error "Not at a dynamic block"))
11120 (let* ((begdel (1+ (match-end 0)))
11121 (name (org-no-properties (match-string 1)))
11122 (params (append (list :name name)
11123 (read (concat "(" (match-string 3) ")")))))
11124 (save-excursion
11125 (beginning-of-line 1)
11126 (skip-chars-forward " \t")
11127 (setq params (plist-put params :indentation-column (current-column))))
11128 (unless (re-search-forward org-dblock-end-re nil t)
11129 (error "Dynamic block not terminated"))
11130 (setq params
11131 (append params
11132 (list :content (buffer-substring
11133 begdel (match-beginning 0)))))
11134 (delete-region begdel (match-beginning 0))
11135 (goto-char begdel)
11136 (open-line 1)
11137 params))
11139 (defun org-map-dblocks (&optional command)
11140 "Apply COMMAND to all dynamic blocks in the current buffer.
11141 If COMMAND is not given, use `org-update-dblock'."
11142 (let ((cmd (or command 'org-update-dblock)))
11143 (save-excursion
11144 (goto-char (point-min))
11145 (while (re-search-forward org-dblock-start-re nil t)
11146 (goto-char (match-beginning 0))
11147 (save-excursion
11148 (condition-case nil
11149 (funcall cmd)
11150 (error (message "Error during update of dynamic block"))))
11151 (unless (re-search-forward org-dblock-end-re nil t)
11152 (error "Dynamic block not terminated"))))))
11154 (defun org-dblock-update (&optional arg)
11155 "User command for updating dynamic blocks.
11156 Update the dynamic block at point. With prefix ARG, update all dynamic
11157 blocks in the buffer."
11158 (interactive "P")
11159 (if arg
11160 (org-update-all-dblocks)
11161 (or (looking-at org-dblock-start-re)
11162 (org-beginning-of-dblock))
11163 (org-update-dblock)))
11165 (defun org-update-dblock ()
11166 "Update the dynamic block at point.
11167 This means to empty the block, parse for parameters and then call
11168 the correct writing function."
11169 (interactive)
11170 (save-window-excursion
11171 (let* ((pos (point))
11172 (line (org-current-line))
11173 (params (org-prepare-dblock))
11174 (name (plist-get params :name))
11175 (indent (plist-get params :indentation-column))
11176 (cmd (intern (concat "org-dblock-write:" name))))
11177 (message "Updating dynamic block `%s' at line %d..." name line)
11178 (funcall cmd params)
11179 (message "Updating dynamic block `%s' at line %d...done" name line)
11180 (goto-char pos)
11181 (when (and indent (> indent 0))
11182 (setq indent (make-string indent ?\ ))
11183 (save-excursion
11184 (org-beginning-of-dblock)
11185 (forward-line 1)
11186 (while (not (looking-at org-dblock-end-re))
11187 (insert indent)
11188 (beginning-of-line 2))
11189 (when (looking-at org-dblock-end-re)
11190 (and (looking-at "[ \t]+")
11191 (replace-match ""))
11192 (insert indent)))))))
11194 (defun org-beginning-of-dblock ()
11195 "Find the beginning of the dynamic block at point.
11196 Error if there is no such block at point."
11197 (let ((pos (point))
11198 beg)
11199 (end-of-line 1)
11200 (if (and (re-search-backward org-dblock-start-re nil t)
11201 (setq beg (match-beginning 0))
11202 (re-search-forward org-dblock-end-re nil t)
11203 (> (match-end 0) pos))
11204 (goto-char beg)
11205 (goto-char pos)
11206 (error "Not in a dynamic block"))))
11208 (defun org-update-all-dblocks ()
11209 "Update all dynamic blocks in the buffer.
11210 This function can be used in a hook."
11211 (interactive)
11212 (when (derived-mode-p 'org-mode)
11213 (org-map-dblocks 'org-update-dblock)))
11216 ;;;; Completion
11218 (defconst org-additional-option-like-keywords
11219 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11220 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11221 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11222 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11223 "BEGIN:" "END:"
11224 "ORGTBL" "TBLFM:" "TBLNAME:"
11225 "BEGIN_EXAMPLE" "END_EXAMPLE"
11226 "BEGIN_VERBATIM" "END_VERBATIM"
11227 "BEGIN_QUOTE" "END_QUOTE"
11228 "BEGIN_VERSE" "END_VERSE"
11229 "BEGIN_CENTER" "END_CENTER"
11230 "BEGIN_SRC" "END_SRC"
11231 "BEGIN_RESULT" "END_RESULT"
11232 "BEGIN_lstlisting" "END_lstlisting"
11233 "NAME:" "RESULTS:"
11234 "HEADER:" "HEADERS:"
11235 "COLUMNS:" "PROPERTY:"
11236 "CAPTION:" "LABEL:"
11237 "SETUPFILE:"
11238 "INCLUDE:" "INDEX:"
11239 "BIND:"
11240 "MACRO:"))
11242 (defconst org-options-keywords
11243 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11244 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11245 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11246 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11247 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11248 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11249 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11251 (defconst org-additional-option-like-keywords-for-flyspell
11252 (delete-dups
11253 (split-string
11254 (mapconcat (lambda(k)
11255 (replace-regexp-in-string
11256 "_\\|:" " "
11257 (concat k " " (downcase k) " " (upcase k))))
11258 (append org-options-keywords org-additional-option-like-keywords)
11259 " ")
11260 " +" t)))
11262 (defcustom org-structure-template-alist
11264 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11265 "<src lang=\"?\">\n\n</src>")
11266 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11267 "<example>\n?\n</example>")
11268 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11269 "<quote>\n?\n</quote>")
11270 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11271 "<verse>\n?\n</verse>")
11272 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11273 "<center>\n?\n</center>")
11274 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11275 "<literal style=\"latex\">\n?\n</literal>")
11276 ("L" "#+LaTeX: "
11277 "<literal style=\"latex\">?</literal>")
11278 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11279 "<literal style=\"html\">\n?\n</literal>")
11280 ("H" "#+HTML: "
11281 "<literal style=\"html\">?</literal>")
11282 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11283 ("A" "#+ASCII: ")
11284 ("i" "#+INDEX: ?"
11285 "#+INDEX: ?")
11286 ("I" "#+INCLUDE: %file ?"
11287 "<include file=%file markup=\"?\">")
11289 "Structure completion elements.
11290 This is a list of abbreviation keys and values. The value gets inserted
11291 if you type `<' followed by the key and then press the completion key,
11292 usually `M-TAB'. %file will be replaced by a file name after prompting
11293 for the file using completion. The cursor will be placed at the position
11294 of the `?` in the template.
11295 There are two templates for each key, the first uses the original Org syntax,
11296 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11297 the default when the /org-mtags.el/ module has been loaded. See also the
11298 variable `org-mtags-prefer-muse-templates'."
11299 :group 'org-completion
11300 :type '(repeat
11301 (string :tag "Key")
11302 (string :tag "Template")
11303 (string :tag "Muse Template")))
11305 (defun org-try-structure-completion ()
11306 "Try to complete a structure template before point.
11307 This looks for strings like \"<e\" on an otherwise empty line and
11308 expands them."
11309 (let ((l (buffer-substring (point-at-bol) (point)))
11311 (when (and (looking-at "[ \t]*$")
11312 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11313 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11314 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11315 (match-beginning 1)) a)
11316 t)))
11318 (defun org-complete-expand-structure-template (start cell)
11319 "Expand a structure template."
11320 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11321 (rpl (nth (if musep 2 1) cell))
11322 (ind ""))
11323 (delete-region start (point))
11324 (when (string-match "\\`#\\+" rpl)
11325 (cond
11326 ((bolp))
11327 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11328 (setq ind (buffer-substring (point-at-bol) (point))))
11329 (t (newline))))
11330 (setq start (point))
11331 (if (string-match "%file" rpl)
11332 (setq rpl (replace-match
11333 (concat
11334 "\""
11335 (save-match-data
11336 (abbreviate-file-name (read-file-name "Include file: ")))
11337 "\"")
11338 t t rpl)))
11339 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11340 (concat "\n" ind)))
11341 (insert rpl)
11342 (if (re-search-backward "\\?" start t) (delete-char 1))))
11344 ;;;; TODO, DEADLINE, Comments
11346 (defun org-toggle-comment ()
11347 "Change the COMMENT state of an entry."
11348 (interactive)
11349 (save-excursion
11350 (org-back-to-heading)
11351 (let (case-fold-search)
11352 (cond
11353 ((looking-at (format org-heading-keyword-regexp-format
11354 org-comment-string))
11355 (goto-char (match-end 1))
11356 (looking-at (concat " +" org-comment-string))
11357 (replace-match "" t t)
11358 (when (eolp) (insert " ")))
11359 ((looking-at org-outline-regexp)
11360 (goto-char (match-end 0))
11361 (insert org-comment-string " "))))))
11363 (defvar org-last-todo-state-is-todo nil
11364 "This is non-nil when the last TODO state change led to a TODO state.
11365 If the last change removed the TODO tag or switched to DONE, then
11366 this is nil.")
11368 (defvar org-setting-tags nil) ; dynamically skipped
11370 (defvar org-todo-setup-filter-hook nil
11371 "Hook for functions that pre-filter todo specs.
11372 Each function takes a todo spec and returns either nil or the spec
11373 transformed into canonical form." )
11375 (defvar org-todo-get-default-hook nil
11376 "Hook for functions that get a default item for todo.
11377 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11378 nil or a string to be used for the todo mark." )
11380 (defvar org-agenda-headline-snapshot-before-repeat)
11382 (defun org-current-effective-time ()
11383 "Return current time adjusted for `org-extend-today-until' variable."
11384 (let* ((ct (org-current-time))
11385 (dct (decode-time ct))
11386 (ct1
11387 (if (and org-use-effective-time
11388 (< (nth 2 dct) org-extend-today-until))
11389 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11390 ct)))
11391 ct1))
11393 (defun org-todo-yesterday (&optional arg)
11394 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11395 (interactive "P")
11396 (if (eq major-mode 'org-agenda-mode)
11397 (apply 'org-agenda-todo-yesterday arg)
11398 (let* ((hour (third (decode-time
11399 (org-current-time))))
11400 (org-extend-today-until (1+ hour)))
11401 (org-todo arg))))
11403 (defun org-todo (&optional arg)
11404 "Change the TODO state of an item.
11405 The state of an item is given by a keyword at the start of the heading,
11406 like
11407 *** TODO Write paper
11408 *** DONE Call mom
11410 The different keywords are specified in the variable `org-todo-keywords'.
11411 By default the available states are \"TODO\" and \"DONE\".
11412 So for this example: when the item starts with TODO, it is changed to DONE.
11413 When it starts with DONE, the DONE is removed. And when neither TODO nor
11414 DONE are present, add TODO at the beginning of the heading.
11416 With \\[universal-argument] prefix arg, use completion to determine the new \
11417 state.
11418 With numeric prefix arg, switch to that state.
11419 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11420 keywords (nextset).
11421 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11422 With a numeric prefix arg of 0, inhibit note taking for the change.
11424 For calling through lisp, arg is also interpreted in the following way:
11425 'none -> empty state
11426 \"\"(empty string) -> switch to empty state
11427 'done -> switch to DONE
11428 'nextset -> switch to the next set of keywords
11429 'previousset -> switch to the previous set of keywords
11430 \"WAITING\" -> switch to the specified keyword, but only if it
11431 really is a member of `org-todo-keywords'."
11432 (interactive "P")
11433 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11434 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11435 'region-start-level 'region))
11436 org-loop-over-headlines-in-active-region)
11437 (org-map-entries
11438 `(org-todo ,arg)
11439 org-loop-over-headlines-in-active-region
11440 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11441 (if (equal arg '(16)) (setq arg 'nextset))
11442 (let ((org-blocker-hook org-blocker-hook)
11443 (case-fold-search nil))
11444 (when (equal arg '(64))
11445 (setq arg nil org-blocker-hook nil))
11446 (when (and org-blocker-hook
11447 (or org-inhibit-blocking
11448 (org-entry-get nil "NOBLOCKING")))
11449 (setq org-blocker-hook nil))
11450 (save-excursion
11451 (catch 'exit
11452 (org-back-to-heading t)
11453 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11454 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11455 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11456 (let* ((match-data (match-data))
11457 (startpos (point-at-bol))
11458 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11459 (org-log-done org-log-done)
11460 (org-log-repeat org-log-repeat)
11461 (org-todo-log-states org-todo-log-states)
11462 (org-inhibit-logging
11463 (if (equal arg 0)
11464 (progn (setq arg nil) 'note) org-inhibit-logging))
11465 (this (match-string 1))
11466 (hl-pos (match-beginning 0))
11467 (head (org-get-todo-sequence-head this))
11468 (ass (assoc head org-todo-kwd-alist))
11469 (interpret (nth 1 ass))
11470 (done-word (nth 3 ass))
11471 (final-done-word (nth 4 ass))
11472 (org-last-state (or this ""))
11473 (completion-ignore-case t)
11474 (member (member this org-todo-keywords-1))
11475 (tail (cdr member))
11476 (org-state (cond
11477 ((and org-todo-key-trigger
11478 (or (and (equal arg '(4))
11479 (eq org-use-fast-todo-selection 'prefix))
11480 (and (not arg) org-use-fast-todo-selection
11481 (not (eq org-use-fast-todo-selection
11482 'prefix)))))
11483 ;; Use fast selection
11484 (org-fast-todo-selection))
11485 ((and (equal arg '(4))
11486 (or (not org-use-fast-todo-selection)
11487 (not org-todo-key-trigger)))
11488 ;; Read a state with completion
11489 (org-icompleting-read
11490 "State: " (mapcar (lambda(x) (list x))
11491 org-todo-keywords-1)
11492 nil t))
11493 ((eq arg 'right)
11494 (if this
11495 (if tail (car tail) nil)
11496 (car org-todo-keywords-1)))
11497 ((eq arg 'left)
11498 (if (equal member org-todo-keywords-1)
11500 (if this
11501 (nth (- (length org-todo-keywords-1)
11502 (length tail) 2)
11503 org-todo-keywords-1)
11504 (org-last org-todo-keywords-1))))
11505 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11506 (setq arg nil))) ; hack to fall back to cycling
11507 (arg
11508 ;; user or caller requests a specific state
11509 (cond
11510 ((equal arg "") nil)
11511 ((eq arg 'none) nil)
11512 ((eq arg 'done) (or done-word (car org-done-keywords)))
11513 ((eq arg 'nextset)
11514 (or (car (cdr (member head org-todo-heads)))
11515 (car org-todo-heads)))
11516 ((eq arg 'previousset)
11517 (let ((org-todo-heads (reverse org-todo-heads)))
11518 (or (car (cdr (member head org-todo-heads)))
11519 (car org-todo-heads))))
11520 ((car (member arg org-todo-keywords-1)))
11521 ((stringp arg)
11522 (error "State `%s' not valid in this file" arg))
11523 ((nth (1- (prefix-numeric-value arg))
11524 org-todo-keywords-1))))
11525 ((null member) (or head (car org-todo-keywords-1)))
11526 ((equal this final-done-word) nil) ;; -> make empty
11527 ((null tail) nil) ;; -> first entry
11528 ((memq interpret '(type priority))
11529 (if (eq this-command last-command)
11530 (car tail)
11531 (if (> (length tail) 0)
11532 (or done-word (car org-done-keywords))
11533 nil)))
11535 (car tail))))
11536 (org-state (or
11537 (run-hook-with-args-until-success
11538 'org-todo-get-default-hook org-state org-last-state)
11539 org-state))
11540 (next (if org-state (concat " " org-state " ") " "))
11541 (change-plist (list :type 'todo-state-change :from this :to org-state
11542 :position startpos))
11543 dolog now-done-p)
11544 (when org-blocker-hook
11545 (setq org-last-todo-state-is-todo
11546 (not (member this org-done-keywords)))
11547 (unless (save-excursion
11548 (save-match-data
11549 (org-with-wide-buffer
11550 (run-hook-with-args-until-failure
11551 'org-blocker-hook change-plist))))
11552 (if (org-called-interactively-p 'interactive)
11553 (error "TODO state change from %s to %s blocked" this org-state)
11554 ;; fail silently
11555 (message "TODO state change from %s to %s blocked" this org-state)
11556 (throw 'exit nil))))
11557 (store-match-data match-data)
11558 (replace-match next t t)
11559 (unless (pos-visible-in-window-p hl-pos)
11560 (message "TODO state changed to %s" (org-trim next)))
11561 (unless head
11562 (setq head (org-get-todo-sequence-head org-state)
11563 ass (assoc head org-todo-kwd-alist)
11564 interpret (nth 1 ass)
11565 done-word (nth 3 ass)
11566 final-done-word (nth 4 ass)))
11567 (when (memq arg '(nextset previousset))
11568 (message "Keyword-Set %d/%d: %s"
11569 (- (length org-todo-sets) -1
11570 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11571 (length org-todo-sets)
11572 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11573 (setq org-last-todo-state-is-todo
11574 (not (member org-state org-done-keywords)))
11575 (setq now-done-p (and (member org-state org-done-keywords)
11576 (not (member this org-done-keywords))))
11577 (and logging (org-local-logging logging))
11578 (when (and (or org-todo-log-states org-log-done)
11579 (not (eq org-inhibit-logging t))
11580 (not (memq arg '(nextset previousset))))
11581 ;; we need to look at recording a time and note
11582 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11583 (nth 2 (assoc this org-todo-log-states))))
11584 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11585 (setq dolog 'time))
11586 (when (and org-state
11587 (member org-state org-not-done-keywords)
11588 (not (member this org-not-done-keywords)))
11589 ;; This is now a todo state and was not one before
11590 ;; If there was a CLOSED time stamp, get rid of it.
11591 (org-add-planning-info nil nil 'closed))
11592 (when (and now-done-p org-log-done)
11593 ;; It is now done, and it was not done before
11594 (org-add-planning-info 'closed (org-current-effective-time))
11595 (if (and (not dolog) (eq 'note org-log-done))
11596 (org-add-log-setup 'done org-state this 'findpos 'note)))
11597 (when (and org-state dolog)
11598 ;; This is a non-nil state, and we need to log it
11599 (org-add-log-setup 'state org-state this 'findpos dolog)))
11600 ;; Fixup tag positioning
11601 (org-todo-trigger-tag-changes org-state)
11602 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11603 (when org-provide-todo-statistics
11604 (org-update-parent-todo-statistics))
11605 (run-hooks 'org-after-todo-state-change-hook)
11606 (if (and arg (not (member org-state org-done-keywords)))
11607 (setq head (org-get-todo-sequence-head org-state)))
11608 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11609 ;; Do we need to trigger a repeat?
11610 (when now-done-p
11611 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11612 ;; This is for the agenda, take a snapshot of the headline.
11613 (save-match-data
11614 (setq org-agenda-headline-snapshot-before-repeat
11615 (org-get-heading))))
11616 (org-auto-repeat-maybe org-state))
11617 ;; Fixup cursor location if close to the keyword
11618 (if (and (outline-on-heading-p)
11619 (not (bolp))
11620 (save-excursion (beginning-of-line 1)
11621 (looking-at org-todo-line-regexp))
11622 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11623 (progn
11624 (goto-char (or (match-end 2) (match-end 1)))
11625 (and (looking-at " ") (just-one-space))))
11626 (when org-trigger-hook
11627 (save-excursion
11628 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11630 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11631 "Block turning an entry into a TODO, using the hierarchy.
11632 This checks whether the current task should be blocked from state
11633 changes. Such blocking occurs when:
11635 1. The task has children which are not all in a completed state.
11637 2. A task has a parent with the property :ORDERED:, and there
11638 are siblings prior to the current task with incomplete
11639 status.
11641 3. The parent of the task is blocked because it has siblings that should
11642 be done first, or is child of a block grandparent TODO entry."
11644 (if (not org-enforce-todo-dependencies)
11645 t ; if locally turned off don't block
11646 (catch 'dont-block
11647 ;; If this is not a todo state change, or if this entry is already DONE,
11648 ;; do not block
11649 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11650 (member (plist-get change-plist :from)
11651 (cons 'done org-done-keywords))
11652 (member (plist-get change-plist :to)
11653 (cons 'todo org-not-done-keywords))
11654 (not (plist-get change-plist :to)))
11655 (throw 'dont-block t))
11656 ;; If this task has children, and any are undone, it's blocked
11657 (save-excursion
11658 (org-back-to-heading t)
11659 (let ((this-level (funcall outline-level)))
11660 (outline-next-heading)
11661 (let ((child-level (funcall outline-level)))
11662 (while (and (not (eobp))
11663 (> child-level this-level))
11664 ;; this todo has children, check whether they are all
11665 ;; completed
11666 (if (and (not (org-entry-is-done-p))
11667 (org-entry-is-todo-p))
11668 (throw 'dont-block nil))
11669 (outline-next-heading)
11670 (setq child-level (funcall outline-level))))))
11671 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11672 ;; any previous siblings are undone, it's blocked
11673 (save-excursion
11674 (org-back-to-heading t)
11675 (let* ((pos (point))
11676 (parent-pos (and (org-up-heading-safe) (point))))
11677 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11678 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11679 (forward-line 1)
11680 (re-search-forward org-not-done-heading-regexp pos t))
11681 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11682 ;; Search further up the hierarchy, to see if an ancestor is blocked
11683 (while t
11684 (goto-char parent-pos)
11685 (if (not (looking-at org-not-done-heading-regexp))
11686 (throw 'dont-block t)) ; do not block, parent is not a TODO
11687 (setq pos (point))
11688 (setq parent-pos (and (org-up-heading-safe) (point)))
11689 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11690 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11691 (forward-line 1)
11692 (re-search-forward org-not-done-heading-regexp pos t))
11693 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11695 (defcustom org-track-ordered-property-with-tag nil
11696 "Should the ORDERED property also be shown as a tag?
11697 The ORDERED property decides if an entry should require subtasks to be
11698 completed in sequence. Since a property is not very visible, setting
11699 this option means that toggling the ORDERED property with the command
11700 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11701 not relevant for the behavior, but it makes things more visible.
11703 Note that toggling the tag with tags commands will not change the property
11704 and therefore not influence behavior!
11706 This can be t, meaning the tag ORDERED should be used, It can also be a
11707 string to select a different tag for this task."
11708 :group 'org-todo
11709 :type '(choice
11710 (const :tag "No tracking" nil)
11711 (const :tag "Track with ORDERED tag" t)
11712 (string :tag "Use other tag")))
11714 (defun org-toggle-ordered-property ()
11715 "Toggle the ORDERED property of the current entry.
11716 For better visibility, you can track the value of this property with a tag.
11717 See variable `org-track-ordered-property-with-tag'."
11718 (interactive)
11719 (let* ((t1 org-track-ordered-property-with-tag)
11720 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11721 (save-excursion
11722 (org-back-to-heading)
11723 (if (org-entry-get nil "ORDERED")
11724 (progn
11725 (org-delete-property "ORDERED")
11726 (and tag (org-toggle-tag tag 'off))
11727 (message "Subtasks can be completed in arbitrary order"))
11728 (org-entry-put nil "ORDERED" "t")
11729 (and tag (org-toggle-tag tag 'on))
11730 (message "Subtasks must be completed in sequence")))))
11732 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11733 (defun org-block-todo-from-checkboxes (change-plist)
11734 "Block turning an entry into a TODO, using checkboxes.
11735 This checks whether the current task should be blocked from state
11736 changes because there are unchecked boxes in this entry."
11737 (if (not org-enforce-todo-checkbox-dependencies)
11738 t ; if locally turned off don't block
11739 (catch 'dont-block
11740 ;; If this is not a todo state change, or if this entry is already DONE,
11741 ;; do not block
11742 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11743 (member (plist-get change-plist :from)
11744 (cons 'done org-done-keywords))
11745 (member (plist-get change-plist :to)
11746 (cons 'todo org-not-done-keywords))
11747 (not (plist-get change-plist :to)))
11748 (throw 'dont-block t))
11749 ;; If this task has checkboxes that are not checked, it's blocked
11750 (save-excursion
11751 (org-back-to-heading t)
11752 (let ((beg (point)) end)
11753 (outline-next-heading)
11754 (setq end (point))
11755 (goto-char beg)
11756 (if (org-list-search-forward
11757 (concat (org-item-beginning-re)
11758 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11759 "\\[[- ]\\]")
11760 end t)
11761 (progn
11762 (if (boundp 'org-blocked-by-checkboxes)
11763 (setq org-blocked-by-checkboxes t))
11764 (throw 'dont-block nil)))))
11765 t))) ; do not block
11767 (defun org-entry-blocked-p ()
11768 "Is the current entry blocked?"
11769 (if (org-entry-get nil "NOBLOCKING")
11770 nil ;; Never block this entry
11771 (not
11772 (run-hook-with-args-until-failure
11773 'org-blocker-hook
11774 (list :type 'todo-state-change
11775 :position (point)
11776 :from 'todo
11777 :to 'done)))))
11779 (defun org-update-statistics-cookies (all)
11780 "Update the statistics cookie, either from TODO or from checkboxes.
11781 This should be called with the cursor in a line with a statistics cookie."
11782 (interactive "P")
11783 (if all
11784 (progn
11785 (org-update-checkbox-count 'all)
11786 (org-map-entries 'org-update-parent-todo-statistics))
11787 (if (not (org-at-heading-p))
11788 (org-update-checkbox-count)
11789 (let ((pos (point-marker))
11790 end l1 l2)
11791 (ignore-errors (org-back-to-heading t))
11792 (if (not (org-at-heading-p))
11793 (org-update-checkbox-count)
11794 (setq l1 (org-outline-level))
11795 (setq end (save-excursion
11796 (outline-next-heading)
11797 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11798 (point)))
11799 (if (and (save-excursion
11800 (re-search-forward
11801 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11802 (not (save-excursion (re-search-forward
11803 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11804 (org-update-checkbox-count)
11805 (if (and l2 (> l2 l1))
11806 (progn
11807 (goto-char end)
11808 (org-update-parent-todo-statistics))
11809 (goto-char pos)
11810 (beginning-of-line 1)
11811 (while (re-search-forward
11812 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11813 (point-at-eol) t)
11814 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11815 (goto-char pos)
11816 (move-marker pos nil)))))
11818 (defvar org-entry-property-inherited-from) ;; defined below
11819 (defun org-update-parent-todo-statistics ()
11820 "Update any statistics cookie in the parent of the current headline.
11821 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11822 the entire subtree and this will travel up the hierarchy and update
11823 statistics everywhere."
11824 (let* ((prop (save-excursion (org-up-heading-safe)
11825 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11826 (recursive (or (not org-hierarchical-todo-statistics)
11827 (and prop (string-match "\\<recursive\\>" prop))))
11828 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11830 (first t)
11831 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11832 level ltoggle l1 new ndel
11833 (cnt-all 0) (cnt-done 0) is-percent kwd
11834 checkbox-beg ov ovs ove cookie-present)
11835 (catch 'exit
11836 (save-excursion
11837 (beginning-of-line 1)
11838 (setq ltoggle (funcall outline-level))
11839 ;; Three situations are to consider:
11841 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11842 ;; to the top-level ancestor on the headline;
11844 ;; 2. If parent has "recursive" property, repeat up to the
11845 ;; headline setting that property, taking inheritance into
11846 ;; account;
11848 ;; 3. Else, move up to direct parent and proceed only once.
11849 (while (and (setq level (org-up-heading-safe))
11850 (or recursive first)
11851 (>= (point) lim))
11852 (setq first nil cookie-present nil)
11853 (unless (and level
11854 (not (string-match
11855 "\\<checkbox\\>"
11856 (downcase (or (org-entry-get nil "COOKIE_DATA")
11857 "")))))
11858 (throw 'exit nil))
11859 (while (re-search-forward box-re (point-at-eol) t)
11860 (setq cnt-all 0 cnt-done 0 cookie-present t)
11861 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11862 (save-match-data
11863 (unless (outline-next-heading) (throw 'exit nil))
11864 (while (and (looking-at org-complex-heading-regexp)
11865 (> (setq l1 (length (match-string 1))) level))
11866 (setq kwd (and (or recursive (= l1 ltoggle))
11867 (match-string 2)))
11868 (if (or (eq org-provide-todo-statistics 'all-headlines)
11869 (and (listp org-provide-todo-statistics)
11870 (or (member kwd org-provide-todo-statistics)
11871 (member kwd org-done-keywords))))
11872 (setq cnt-all (1+ cnt-all))
11873 (if (eq org-provide-todo-statistics t)
11874 (and kwd (setq cnt-all (1+ cnt-all)))))
11875 (and (member kwd org-done-keywords)
11876 (setq cnt-done (1+ cnt-done)))
11877 (outline-next-heading)))
11878 (setq new
11879 (if is-percent
11880 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11881 (format "[%d/%d]" cnt-done cnt-all))
11882 ndel (- (match-end 0) checkbox-beg))
11883 ;; handle overlays when updating cookie from column view
11884 (when (setq ov (car (overlays-at checkbox-beg)))
11885 (setq ovs (overlay-start ov) ove (overlay-end ov))
11886 (delete-overlay ov))
11887 (goto-char checkbox-beg)
11888 (insert new)
11889 (delete-region (point) (+ (point) ndel))
11890 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11891 (when ov (move-overlay ov ovs ove)))
11892 (when cookie-present
11893 (run-hook-with-args 'org-after-todo-statistics-hook
11894 cnt-done (- cnt-all cnt-done))))))
11895 (run-hooks 'org-todo-statistics-hook)))
11897 (defvar org-after-todo-statistics-hook nil
11898 "Hook that is called after a TODO statistics cookie has been updated.
11899 Each function is called with two arguments: the number of not-done entries
11900 and the number of done entries.
11902 For example, the following function, when added to this hook, will switch
11903 an entry to DONE when all children are done, and back to TODO when new
11904 entries are set to a TODO status. Note that this hook is only called
11905 when there is a statistics cookie in the headline!
11907 (defun org-summary-todo (n-done n-not-done)
11908 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11909 (let (org-log-done org-log-states) ; turn off logging
11910 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11913 (defvar org-todo-statistics-hook nil
11914 "Hook that is run whenever Org thinks TODO statistics should be updated.
11915 This hook runs even if there is no statistics cookie present, in which case
11916 `org-after-todo-statistics-hook' would not run.")
11918 (defun org-todo-trigger-tag-changes (state)
11919 "Apply the changes defined in `org-todo-state-tags-triggers'."
11920 (let ((l org-todo-state-tags-triggers)
11921 changes)
11922 (when (or (not state) (equal state ""))
11923 (setq changes (append changes (cdr (assoc "" l)))))
11924 (when (and (stringp state) (> (length state) 0))
11925 (setq changes (append changes (cdr (assoc state l)))))
11926 (when (member state org-not-done-keywords)
11927 (setq changes (append changes (cdr (assoc 'todo l)))))
11928 (when (member state org-done-keywords)
11929 (setq changes (append changes (cdr (assoc 'done l)))))
11930 (dolist (c changes)
11931 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11933 (defun org-local-logging (value)
11934 "Get logging settings from a property VALUE."
11935 (let* (words w a)
11936 ;; directly set the variables, they are already local.
11937 (setq org-log-done nil
11938 org-log-repeat nil
11939 org-todo-log-states nil)
11940 (setq words (org-split-string value))
11941 (while (setq w (pop words))
11942 (cond
11943 ((setq a (assoc w org-startup-options))
11944 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11945 (set (nth 1 a) (nth 2 a))))
11946 ((setq a (org-extract-log-state-settings w))
11947 (and (member (car a) org-todo-keywords-1)
11948 (push a org-todo-log-states)))))))
11950 (defun org-get-todo-sequence-head (kwd)
11951 "Return the head of the TODO sequence to which KWD belongs.
11952 If KWD is not set, check if there is a text property remembering the
11953 right sequence."
11954 (let (p)
11955 (cond
11956 ((not kwd)
11957 (or (get-text-property (point-at-bol) 'org-todo-head)
11958 (progn
11959 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11960 nil (point-at-eol)))
11961 (get-text-property p 'org-todo-head))))
11962 ((not (member kwd org-todo-keywords-1))
11963 (car org-todo-keywords-1))
11964 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11966 (defun org-fast-todo-selection ()
11967 "Fast TODO keyword selection with single keys.
11968 Returns the new TODO keyword, or nil if no state change should occur."
11969 (let* ((fulltable org-todo-key-alist)
11970 (done-keywords org-done-keywords) ;; needed for the faces.
11971 (maxlen (apply 'max (mapcar
11972 (lambda (x)
11973 (if (stringp (car x)) (string-width (car x)) 0))
11974 fulltable)))
11975 (expert nil)
11976 (fwidth (+ maxlen 3 1 3))
11977 (ncol (/ (- (window-width) 4) fwidth))
11978 tg cnt e c tbl
11979 groups ingroup)
11980 (save-excursion
11981 (save-window-excursion
11982 (if expert
11983 (set-buffer (get-buffer-create " *Org todo*"))
11984 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11985 (erase-buffer)
11986 (org-set-local 'org-done-keywords done-keywords)
11987 (setq tbl fulltable cnt 0)
11988 (while (setq e (pop tbl))
11989 (cond
11990 ((equal e '(:startgroup))
11991 (push '() groups) (setq ingroup t)
11992 (when (not (= cnt 0))
11993 (setq cnt 0)
11994 (insert "\n"))
11995 (insert "{ "))
11996 ((equal e '(:endgroup))
11997 (setq ingroup nil cnt 0)
11998 (insert "}\n"))
11999 ((equal e '(:newline))
12000 (when (not (= cnt 0))
12001 (setq cnt 0)
12002 (insert "\n")
12003 (setq e (car tbl))
12004 (while (equal (car tbl) '(:newline))
12005 (insert "\n")
12006 (setq tbl (cdr tbl)))))
12008 (setq tg (car e) c (cdr e))
12009 (if ingroup (push tg (car groups)))
12010 (setq tg (org-add-props tg nil 'face
12011 (org-get-todo-face tg)))
12012 (if (and (= cnt 0) (not ingroup)) (insert " "))
12013 (insert "[" c "] " tg (make-string
12014 (- fwidth 4 (length tg)) ?\ ))
12015 (when (= (setq cnt (1+ cnt)) ncol)
12016 (insert "\n")
12017 (if ingroup (insert " "))
12018 (setq cnt 0)))))
12019 (insert "\n")
12020 (goto-char (point-min))
12021 (if (not expert) (org-fit-window-to-buffer))
12022 (message "[a-z..]:Set [SPC]:clear")
12023 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12024 (cond
12025 ((or (= c ?\C-g)
12026 (and (= c ?q) (not (rassoc c fulltable))))
12027 (setq quit-flag t))
12028 ((= c ?\ ) nil)
12029 ((setq e (rassoc c fulltable) tg (car e))
12031 (t (setq quit-flag t)))))))
12033 (defun org-entry-is-todo-p ()
12034 (member (org-get-todo-state) org-not-done-keywords))
12036 (defun org-entry-is-done-p ()
12037 (member (org-get-todo-state) org-done-keywords))
12039 (defun org-get-todo-state ()
12040 (save-excursion
12041 (org-back-to-heading t)
12042 (and (looking-at org-todo-line-regexp)
12043 (match-end 2)
12044 (match-string 2))))
12046 (defun org-at-date-range-p (&optional inactive-ok)
12047 "Is the cursor inside a date range?"
12048 (interactive)
12049 (save-excursion
12050 (catch 'exit
12051 (let ((pos (point)))
12052 (skip-chars-backward "^[<\r\n")
12053 (skip-chars-backward "<[")
12054 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12055 (>= (match-end 0) pos)
12056 (throw 'exit t))
12057 (skip-chars-backward "^<[\r\n")
12058 (skip-chars-backward "<[")
12059 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12060 (>= (match-end 0) pos)
12061 (throw 'exit t)))
12062 nil)))
12064 (defun org-get-repeat (&optional tagline)
12065 "Check if there is a deadline/schedule with repeater in this entry."
12066 (save-match-data
12067 (save-excursion
12068 (org-back-to-heading t)
12069 (and (re-search-forward (if tagline
12070 (concat tagline "\\s-*" org-repeat-re)
12071 org-repeat-re)
12072 (org-entry-end-position) t)
12073 (match-string-no-properties 1)))))
12075 (defvar org-last-changed-timestamp)
12076 (defvar org-last-inserted-timestamp)
12077 (defvar org-log-post-message)
12078 (defvar org-log-note-purpose)
12079 (defvar org-log-note-how)
12080 (defvar org-log-note-extra)
12081 (defun org-auto-repeat-maybe (done-word)
12082 "Check if the current headline contains a repeated deadline/schedule.
12083 If yes, set TODO state back to what it was and change the base date
12084 of repeating deadline/scheduled time stamps to new date.
12085 This function is run automatically after each state change to a DONE state."
12086 ;; last-state is dynamically scoped into this function
12087 (let* ((repeat (org-get-repeat))
12088 (aa (assoc org-last-state org-todo-kwd-alist))
12089 (interpret (nth 1 aa))
12090 (head (nth 2 aa))
12091 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12092 (msg "Entry repeats: ")
12093 (org-log-done nil)
12094 (org-todo-log-states nil)
12095 re type n what ts time to-state)
12096 (when repeat
12097 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12098 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12099 org-todo-repeat-to-state))
12100 (unless (and to-state (member to-state org-todo-keywords-1))
12101 (setq to-state (if (eq interpret 'type) org-last-state head)))
12102 (org-todo to-state)
12103 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12104 (org-entry-put nil "LAST_REPEAT" (format-time-string
12105 (org-time-stamp-format t t))))
12106 (when org-log-repeat
12107 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12108 (memq 'org-add-log-note post-command-hook))
12109 ;; OK, we are already setup for some record
12110 (if (eq org-log-repeat 'note)
12111 ;; make sure we take a note, not only a time stamp
12112 (setq org-log-note-how 'note))
12113 ;; Set up for taking a record
12114 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12115 org-last-state
12116 'findpos org-log-repeat)))
12117 (org-back-to-heading t)
12118 (org-add-planning-info nil nil 'closed)
12119 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12120 org-deadline-time-regexp "\\)\\|\\("
12121 org-ts-regexp "\\)"))
12122 (while (re-search-forward
12123 re (save-excursion (outline-next-heading) (point)) t)
12124 (setq type (if (match-end 1) org-scheduled-string
12125 (if (match-end 3) org-deadline-string "Plain:"))
12126 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12127 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12128 (setq n (string-to-number (match-string 2 ts))
12129 what (match-string 3 ts))
12130 (if (equal what "w") (setq n (* n 7) what "d"))
12131 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12132 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12133 ;; Preparation, see if we need to modify the start date for the change
12134 (when (match-end 1)
12135 (setq time (save-match-data (org-time-string-to-time ts)))
12136 (cond
12137 ((equal (match-string 1 ts) ".")
12138 ;; Shift starting date to today
12139 (org-timestamp-change
12140 (- (org-today) (time-to-days time))
12141 'day))
12142 ((equal (match-string 1 ts) "+")
12143 (let ((nshiftmax 10) (nshift 0))
12144 (while (or (= nshift 0)
12145 (<= (time-to-days time)
12146 (time-to-days (current-time))))
12147 (when (= (incf nshift) nshiftmax)
12148 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12149 (error "Abort")))
12150 (org-timestamp-change n (cdr (assoc what whata)))
12151 (org-at-timestamp-p t)
12152 (setq ts (match-string 1))
12153 (setq time (save-match-data (org-time-string-to-time ts)))))
12154 (org-timestamp-change (- n) (cdr (assoc what whata)))
12155 ;; rematch, so that we have everything in place for the real shift
12156 (org-at-timestamp-p t)
12157 (setq ts (match-string 1))
12158 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12159 (org-timestamp-change n (cdr (assoc what whata)))
12160 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12161 (setq org-log-post-message msg)
12162 (message "%s" msg))))
12164 (defun org-show-todo-tree (arg)
12165 "Make a compact tree which shows all headlines marked with TODO.
12166 The tree will show the lines where the regexp matches, and all higher
12167 headlines above the match.
12168 With a \\[universal-argument] prefix, prompt for a regexp to match.
12169 With a numeric prefix N, construct a sparse tree for the Nth element
12170 of `org-todo-keywords-1'."
12171 (interactive "P")
12172 (let ((case-fold-search nil)
12173 (kwd-re
12174 (cond ((null arg) org-not-done-regexp)
12175 ((equal arg '(4))
12176 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12177 (mapcar 'list org-todo-keywords-1))))
12178 (concat "\\("
12179 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12180 "\\)\\>")))
12181 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12182 (regexp-quote (nth (1- (prefix-numeric-value arg))
12183 org-todo-keywords-1)))
12184 (t (error "Invalid prefix argument: %s" arg)))))
12185 (message "%d TODO entries found"
12186 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12188 (defun org-deadline (&optional remove time)
12189 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12190 With argument REMOVE, remove any deadline from the item.
12191 With argument TIME, set the deadline at the corresponding date. TIME
12192 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12193 (interactive "P")
12194 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12195 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12196 'region-start-level 'region))
12197 org-loop-over-headlines-in-active-region)
12198 (org-map-entries
12199 `(org-deadline ',remove ,time)
12200 org-loop-over-headlines-in-active-region
12201 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12202 (let* ((old-date (org-entry-get nil "DEADLINE"))
12203 (repeater (and old-date
12204 (string-match
12205 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12206 old-date)
12207 (match-string 1 old-date))))
12208 (if remove
12209 (progn
12210 (when (and old-date org-log-redeadline)
12211 (org-add-log-setup 'deldeadline nil old-date 'findpos
12212 org-log-redeadline))
12213 (org-remove-timestamp-with-keyword org-deadline-string)
12214 (message "Item no longer has a deadline."))
12215 (org-add-planning-info 'deadline time 'closed)
12216 (when (and old-date org-log-redeadline
12217 (not (equal old-date
12218 (substring org-last-inserted-timestamp 1 -1))))
12219 (org-add-log-setup 'redeadline nil old-date 'findpos
12220 org-log-redeadline))
12221 (when repeater
12222 (save-excursion
12223 (org-back-to-heading t)
12224 (when (re-search-forward (concat org-deadline-string " "
12225 org-last-inserted-timestamp)
12226 (save-excursion
12227 (outline-next-heading) (point)) t)
12228 (goto-char (1- (match-end 0)))
12229 (insert " " repeater)
12230 (setq org-last-inserted-timestamp
12231 (concat (substring org-last-inserted-timestamp 0 -1)
12232 " " repeater
12233 (substring org-last-inserted-timestamp -1))))))
12234 (message "Deadline on %s" org-last-inserted-timestamp)))))
12236 (defun org-schedule (&optional remove time)
12237 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12238 With argument REMOVE, remove any scheduling date from the item.
12239 With argument TIME, scheduled at the corresponding date. TIME can
12240 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12241 (interactive "P")
12242 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12243 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12244 'region-start-level 'region))
12245 org-loop-over-headlines-in-active-region)
12246 (org-map-entries
12247 `(org-schedule ',remove ,time)
12248 org-loop-over-headlines-in-active-region
12249 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12250 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12251 (repeater (and old-date
12252 (string-match
12253 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12254 old-date)
12255 (match-string 1 old-date))))
12256 (if remove
12257 (progn
12258 (when (and old-date org-log-reschedule)
12259 (org-add-log-setup 'delschedule nil old-date 'findpos
12260 org-log-reschedule))
12261 (org-remove-timestamp-with-keyword org-scheduled-string)
12262 (message "Item is no longer scheduled."))
12263 (org-add-planning-info 'scheduled time 'closed)
12264 (when (and old-date org-log-reschedule
12265 (not (equal old-date
12266 (substring org-last-inserted-timestamp 1 -1))))
12267 (org-add-log-setup 'reschedule nil old-date 'findpos
12268 org-log-reschedule))
12269 (when repeater
12270 (save-excursion
12271 (org-back-to-heading t)
12272 (when (re-search-forward (concat org-scheduled-string " "
12273 org-last-inserted-timestamp)
12274 (save-excursion
12275 (outline-next-heading) (point)) t)
12276 (goto-char (1- (match-end 0)))
12277 (insert " " repeater)
12278 (setq org-last-inserted-timestamp
12279 (concat (substring org-last-inserted-timestamp 0 -1)
12280 " " repeater
12281 (substring org-last-inserted-timestamp -1))))))
12282 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12284 (defun org-get-scheduled-time (pom &optional inherit)
12285 "Get the scheduled time as a time tuple, of a format suitable
12286 for calling org-schedule with, or if there is no scheduling,
12287 returns nil."
12288 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12289 (when time
12290 (apply 'encode-time (org-parse-time-string time)))))
12292 (defun org-get-deadline-time (pom &optional inherit)
12293 "Get the deadline as a time tuple, of a format suitable for
12294 calling org-deadline with, or if there is no scheduling, returns
12295 nil."
12296 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12297 (when time
12298 (apply 'encode-time (org-parse-time-string time)))))
12300 (defun org-remove-timestamp-with-keyword (keyword)
12301 "Remove all time stamps with KEYWORD in the current entry."
12302 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12303 beg)
12304 (save-excursion
12305 (org-back-to-heading t)
12306 (setq beg (point))
12307 (outline-next-heading)
12308 (while (re-search-backward re beg t)
12309 (replace-match "")
12310 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12311 (equal (char-before) ?\ ))
12312 (backward-delete-char 1)
12313 (if (string-match "^[ \t]*$" (buffer-substring
12314 (point-at-bol) (point-at-eol)))
12315 (delete-region (point-at-bol)
12316 (min (point-max) (1+ (point-at-eol))))))))))
12318 (defun org-add-planning-info (what &optional time &rest remove)
12319 "Insert new timestamp with keyword in the line directly after the headline.
12320 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12321 If non is given, the user is prompted for a date.
12322 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12323 be removed."
12324 (interactive)
12325 (let (org-time-was-given org-end-time-was-given ts
12326 end default-time default-input)
12328 (catch 'exit
12329 (when (and (memq what '(scheduled deadline))
12330 (or (not time)
12331 (and (stringp time)
12332 (string-match "^[-+]+[0-9]" time))))
12333 ;; Try to get a default date/time from existing timestamp
12334 (save-excursion
12335 (org-back-to-heading t)
12336 (setq end (save-excursion (outline-next-heading) (point)))
12337 (when (re-search-forward (if (eq what 'scheduled)
12338 org-scheduled-time-regexp
12339 org-deadline-time-regexp)
12340 end t)
12341 (setq ts (match-string 1)
12342 default-time
12343 (apply 'encode-time (org-parse-time-string ts))
12344 default-input (and ts (org-get-compact-tod ts))))))
12345 (when what
12346 (setq time
12347 (if (stringp time)
12348 ;; This is a string (relative or absolute), set proper date
12349 (apply 'encode-time
12350 (org-read-date-analyze
12351 time default-time (decode-time default-time)))
12352 ;; If necessary, get the time from the user
12353 (or time (org-read-date nil 'to-time nil nil
12354 default-time default-input)))))
12356 (when (and org-insert-labeled-timestamps-at-point
12357 (member what '(scheduled deadline)))
12358 (insert
12359 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12360 (org-insert-time-stamp time org-time-was-given
12361 nil nil nil (list org-end-time-was-given))
12362 (setq what nil))
12363 (save-excursion
12364 (save-restriction
12365 (let (col list elt ts buffer-invisibility-spec)
12366 (org-back-to-heading t)
12367 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12368 (goto-char (match-end 1))
12369 (setq col (current-column))
12370 (goto-char (match-end 0))
12371 (if (eobp) (insert "\n") (forward-char 1))
12372 (when (and (not what)
12373 (not (looking-at
12374 (concat "[ \t]*"
12375 org-keyword-time-not-clock-regexp))))
12376 ;; Nothing to add, nothing to remove...... :-)
12377 (throw 'exit nil))
12378 (if (and (not (looking-at org-outline-regexp))
12379 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12380 "[^\r\n]*"))
12381 (not (equal (match-string 1) org-clock-string)))
12382 (narrow-to-region (match-beginning 0) (match-end 0))
12383 (insert-before-markers "\n")
12384 (backward-char 1)
12385 (narrow-to-region (point) (point))
12386 (and org-adapt-indentation (org-indent-to-column col)))
12387 ;; Check if we have to remove something.
12388 (setq list (cons what remove))
12389 (while list
12390 (setq elt (pop list))
12391 (when (or (and (eq elt 'scheduled)
12392 (re-search-forward org-scheduled-time-regexp nil t))
12393 (and (eq elt 'deadline)
12394 (re-search-forward org-deadline-time-regexp nil t))
12395 (and (eq elt 'closed)
12396 (re-search-forward org-closed-time-regexp nil t)))
12397 (replace-match "")
12398 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12399 (and (looking-at "[ \t]+") (replace-match ""))
12400 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12401 (when what
12402 (insert
12403 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12404 (cond ((eq what 'scheduled) org-scheduled-string)
12405 ((eq what 'deadline) org-deadline-string)
12406 ((eq what 'closed) org-closed-string))
12407 " ")
12408 (setq ts (org-insert-time-stamp
12409 time
12410 (or org-time-was-given
12411 (and (eq what 'closed) org-log-done-with-time))
12412 (eq what 'closed)
12413 nil nil (list org-end-time-was-given)))
12414 (insert
12415 (if (not (or (bolp) (eq (char-before) ?\ )
12416 (memq (char-after) '(32 10))
12417 (eobp))) " " ""))
12418 (end-of-line 1))
12419 (goto-char (point-min))
12420 (widen)
12421 (if (and (looking-at "[ \t]*\n")
12422 (equal (char-before) ?\n))
12423 (delete-region (1- (point)) (point-at-eol)))
12424 ts))))))
12426 (defvar org-log-note-marker (make-marker))
12427 (defvar org-log-note-purpose nil)
12428 (defvar org-log-note-state nil)
12429 (defvar org-log-note-previous-state nil)
12430 (defvar org-log-note-how nil)
12431 (defvar org-log-note-extra nil)
12432 (defvar org-log-note-window-configuration nil)
12433 (defvar org-log-note-return-to (make-marker))
12434 (defvar org-log-note-effective-time nil
12435 "Remembered current time so that dynamically scoped
12436 `org-extend-today-until' affects tha timestamps in state change
12437 log")
12439 (defvar org-log-post-message nil
12440 "Message to be displayed after a log note has been stored.
12441 The auto-repeater uses this.")
12443 (defun org-add-note ()
12444 "Add a note to the current entry.
12445 This is done in the same way as adding a state change note."
12446 (interactive)
12447 (org-add-log-setup 'note nil nil 'findpos nil))
12449 (defvar org-property-end-re)
12450 (defun org-add-log-setup (&optional purpose state prev-state
12451 findpos how extra)
12452 "Set up the post command hook to take a note.
12453 If this is about to TODO state change, the new state is expected in STATE.
12454 When FINDPOS is non-nil, find the correct position for the note in
12455 the current entry. If not, assume that it can be inserted at point.
12456 HOW is an indicator what kind of note should be created.
12457 EXTRA is additional text that will be inserted into the notes buffer."
12458 (let* ((org-log-into-drawer (org-log-into-drawer))
12459 (drawer (cond ((stringp org-log-into-drawer)
12460 org-log-into-drawer)
12461 (org-log-into-drawer "LOGBOOK"))))
12462 (save-restriction
12463 (save-excursion
12464 (when findpos
12465 (org-back-to-heading t)
12466 (narrow-to-region (point) (save-excursion
12467 (outline-next-heading) (point)))
12468 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12469 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12470 "[^\r\n]*\\)?"))
12471 (goto-char (match-end 0))
12472 (cond
12473 (drawer
12474 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12475 nil t)
12476 (progn
12477 (goto-char (match-end 0))
12478 (or org-log-states-order-reversed
12479 (and (re-search-forward org-property-end-re nil t)
12480 (goto-char (1- (match-beginning 0))))))
12481 (insert "\n:" drawer ":\n:END:")
12482 (beginning-of-line 0)
12483 (org-indent-line)
12484 (beginning-of-line 2)
12485 (org-indent-line)
12486 (end-of-line 0)))
12487 ((and org-log-state-notes-insert-after-drawers
12488 (save-excursion
12489 (forward-line) (looking-at org-drawer-regexp)))
12490 (forward-line)
12491 (while (looking-at org-drawer-regexp)
12492 (goto-char (match-end 0))
12493 (re-search-forward org-property-end-re (point-max) t)
12494 (forward-line))
12495 (forward-line -1)))
12496 (unless org-log-states-order-reversed
12497 (and (= (char-after) ?\n) (forward-char 1))
12498 (org-skip-over-state-notes)
12499 (skip-chars-backward " \t\n\r")))
12500 (move-marker org-log-note-marker (point))
12501 (setq org-log-note-purpose purpose
12502 org-log-note-state state
12503 org-log-note-previous-state prev-state
12504 org-log-note-how how
12505 org-log-note-extra extra
12506 org-log-note-effective-time (org-current-effective-time))
12507 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12509 (defun org-skip-over-state-notes ()
12510 "Skip past the list of State notes in an entry."
12511 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12512 (when (ignore-errors (goto-char (org-in-item-p)))
12513 (let* ((struct (org-list-struct))
12514 (prevs (org-list-prevs-alist struct)))
12515 (while (looking-at "[ \t]*- State")
12516 (goto-char (or (org-list-get-next-item (point) struct prevs)
12517 (org-list-get-item-end (point) struct)))))))
12519 (defun org-add-log-note (&optional purpose)
12520 "Pop up a window for taking a note, and add this note later at point."
12521 (remove-hook 'post-command-hook 'org-add-log-note)
12522 (setq org-log-note-window-configuration (current-window-configuration))
12523 (delete-other-windows)
12524 (move-marker org-log-note-return-to (point))
12525 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12526 (goto-char org-log-note-marker)
12527 (org-switch-to-buffer-other-window "*Org Note*")
12528 (erase-buffer)
12529 (if (memq org-log-note-how '(time state))
12530 (let (current-prefix-arg) (org-store-log-note))
12531 (let ((org-inhibit-startup t)) (org-mode))
12532 (insert (format "# Insert note for %s.
12533 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12534 (cond
12535 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12536 ((eq org-log-note-purpose 'done) "closed todo item")
12537 ((eq org-log-note-purpose 'state)
12538 (format "state change from \"%s\" to \"%s\""
12539 (or org-log-note-previous-state "")
12540 (or org-log-note-state "")))
12541 ((eq org-log-note-purpose 'reschedule)
12542 "rescheduling")
12543 ((eq org-log-note-purpose 'delschedule)
12544 "no longer scheduled")
12545 ((eq org-log-note-purpose 'redeadline)
12546 "changing deadline")
12547 ((eq org-log-note-purpose 'deldeadline)
12548 "removing deadline")
12549 ((eq org-log-note-purpose 'refile)
12550 "refiling")
12551 ((eq org-log-note-purpose 'note)
12552 "this entry")
12553 (t (error "This should not happen")))))
12554 (if org-log-note-extra (insert org-log-note-extra))
12555 (org-set-local 'org-finish-function 'org-store-log-note)
12556 (run-hooks 'org-log-buffer-setup-hook)))
12558 (defvar org-note-abort nil) ; dynamically scoped
12559 (defun org-store-log-note ()
12560 "Finish taking a log note, and insert it to where it belongs."
12561 (let ((txt (buffer-string))
12562 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12563 lines ind bul)
12564 (kill-buffer (current-buffer))
12565 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12566 (setq txt (replace-match "" t t txt)))
12567 (if (string-match "\\s-+\\'" txt)
12568 (setq txt (replace-match "" t t txt)))
12569 (setq lines (org-split-string txt "\n"))
12570 (when (and note (string-match "\\S-" note))
12571 (setq note
12572 (org-replace-escapes
12573 note
12574 (list (cons "%u" (user-login-name))
12575 (cons "%U" user-full-name)
12576 (cons "%t" (format-time-string
12577 (org-time-stamp-format 'long 'inactive)
12578 org-log-note-effective-time))
12579 (cons "%T" (format-time-string
12580 (org-time-stamp-format 'long nil)
12581 org-log-note-effective-time))
12582 (cons "%d" (format-time-string
12583 (org-time-stamp-format nil 'inactive)
12584 org-log-note-effective-time))
12585 (cons "%D" (format-time-string
12586 (org-time-stamp-format nil nil)
12587 org-log-note-effective-time))
12588 (cons "%s" (if org-log-note-state
12589 (concat "\"" org-log-note-state "\"")
12590 ""))
12591 (cons "%S" (if org-log-note-previous-state
12592 (concat "\"" org-log-note-previous-state "\"")
12593 "\"\"")))))
12594 (if lines (setq note (concat note " \\\\")))
12595 (push note lines))
12596 (when (or current-prefix-arg org-note-abort)
12597 (when org-log-into-drawer
12598 (org-remove-empty-drawer-at
12599 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12600 org-log-note-marker))
12601 (setq lines nil))
12602 (when lines
12603 (with-current-buffer (marker-buffer org-log-note-marker)
12604 (save-excursion
12605 (goto-char org-log-note-marker)
12606 (move-marker org-log-note-marker nil)
12607 (end-of-line 1)
12608 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12609 (setq ind (save-excursion
12610 (if (ignore-errors (goto-char (org-in-item-p)))
12611 (let ((struct (org-list-struct)))
12612 (org-list-get-ind
12613 (org-list-get-top-point struct) struct))
12614 (skip-chars-backward " \r\t\n")
12615 (cond
12616 ((and (org-at-heading-p)
12617 org-adapt-indentation)
12618 (1+ (org-current-level)))
12619 ((org-at-heading-p) 0)
12620 (t (org-get-indentation))))))
12621 (setq bul (org-list-bullet-string "-"))
12622 (org-indent-line-to ind)
12623 (insert bul (pop lines))
12624 (let ((ind-body (+ (length bul) ind)))
12625 (while lines
12626 (insert "\n")
12627 (org-indent-line-to ind-body)
12628 (insert (pop lines))))
12629 (message "Note stored")
12630 (org-back-to-heading t)
12631 (org-cycle-hide-drawers 'children)))))
12632 (set-window-configuration org-log-note-window-configuration)
12633 (with-current-buffer (marker-buffer org-log-note-return-to)
12634 (goto-char org-log-note-return-to))
12635 (move-marker org-log-note-return-to nil)
12636 (and org-log-post-message (message "%s" org-log-post-message)))
12638 (defun org-remove-empty-drawer-at (drawer pos)
12639 "Remove an empty drawer DRAWER at position POS.
12640 POS may also be a marker."
12641 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12642 (save-excursion
12643 (save-restriction
12644 (widen)
12645 (goto-char pos)
12646 (if (org-in-regexp
12647 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12648 (replace-match ""))))))
12650 (defvar org-ts-type nil)
12651 (defun org-sparse-tree (&optional arg type)
12652 "Create a sparse tree, prompt for the details.
12653 This command can create sparse trees. You first need to select the type
12654 of match used to create the tree:
12656 t Show all TODO entries.
12657 T Show entries with a specific TODO keyword.
12658 m Show entries selected by a tags/property match.
12659 p Enter a property name and its value (both with completion on existing
12660 names/values) and show entries with that property.
12661 r Show entries matching a regular expression (`/' can be used as well).
12662 b Show deadlines and scheduled items before a date.
12663 a Show deadlines and scheduled items after a date.
12664 d Show deadlines due within `org-deadline-warning-days'.
12665 D Show deadlines and scheduled items between a date range."
12666 (interactive "P")
12667 (let (ans kwd value ts-type)
12668 (setq type (or type org-sparse-tree-default-date-type))
12669 (setq org-ts-type type)
12670 (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date [D]ates range\n [c]ycle through date types: %s"
12671 (cond ((eq type 'all) "all timestamps")
12672 ((eq type 'scheduled) "only scheduled")
12673 ((eq type 'deadline) "only deadline")
12674 ((eq type 'active) "only active timestamps")
12675 ((eq type 'inactive) "only inactive timestamps")
12676 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12677 (t "scheduled/deadline")))
12678 (setq ans (read-char-exclusive))
12679 (cond
12680 ((equal ans ?c)
12681 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12682 ((equal ans ?d)
12683 (call-interactively 'org-check-deadlines))
12684 ((equal ans ?b)
12685 (call-interactively 'org-check-before-date))
12686 ((equal ans ?a)
12687 (call-interactively 'org-check-after-date))
12688 ((equal ans ?D)
12689 (call-interactively 'org-check-dates-range))
12690 ((equal ans ?t)
12691 (call-interactively 'org-show-todo-tree))
12692 ((equal ans ?T)
12693 (org-show-todo-tree '(4)))
12694 ((member ans '(?T ?m))
12695 (call-interactively 'org-match-sparse-tree))
12696 ((member ans '(?p ?P))
12697 (setq kwd (org-icompleting-read "Property: "
12698 (mapcar 'list (org-buffer-property-keys))))
12699 (setq value (org-icompleting-read "Value: "
12700 (mapcar 'list (org-property-values kwd))))
12701 (unless (string-match "\\`{.*}\\'" value)
12702 (setq value (concat "\"" value "\"")))
12703 (org-match-sparse-tree arg (concat kwd "=" value)))
12704 ((member ans '(?r ?R ?/))
12705 (call-interactively 'org-occur))
12706 (t (error "No such sparse tree command \"%c\"" ans)))))
12708 (defvar org-occur-highlights nil
12709 "List of overlays used for occur matches.")
12710 (make-variable-buffer-local 'org-occur-highlights)
12711 (defvar org-occur-parameters nil
12712 "Parameters of the active org-occur calls.
12713 This is a list, each call to org-occur pushes as cons cell,
12714 containing the regular expression and the callback, onto the list.
12715 The list can contain several entries if `org-occur' has been called
12716 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12717 will only contain one set of parameters. When the highlights are
12718 removed (for example with `C-c C-c', or with the next edit (depending
12719 on `org-remove-highlights-with-change'), this variable is emptied
12720 as well.")
12721 (make-variable-buffer-local 'org-occur-parameters)
12723 (defun org-occur (regexp &optional keep-previous callback)
12724 "Make a compact tree which shows all matches of REGEXP.
12725 The tree will show the lines where the regexp matches, and all higher
12726 headlines above the match. It will also show the heading after the match,
12727 to make sure editing the matching entry is easy.
12728 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12729 call to `org-occur' will be kept, to allow stacking of calls to this
12730 command.
12731 If CALLBACK is non-nil, it is a function which is called to confirm
12732 that the match should indeed be shown."
12733 (interactive "sRegexp: \nP")
12734 (when (equal regexp "")
12735 (error "Regexp cannot be empty"))
12736 (unless keep-previous
12737 (org-remove-occur-highlights nil nil t))
12738 (push (cons regexp callback) org-occur-parameters)
12739 (let ((cnt 0))
12740 (save-excursion
12741 (goto-char (point-min))
12742 (if (or (not keep-previous) ; do not want to keep
12743 (not org-occur-highlights)) ; no previous matches
12744 ;; hide everything
12745 (org-overview))
12746 (while (re-search-forward regexp nil t)
12747 (when (or (not callback)
12748 (save-match-data (funcall callback)))
12749 (setq cnt (1+ cnt))
12750 (when org-highlight-sparse-tree-matches
12751 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12752 (org-show-context 'occur-tree))))
12753 (when org-remove-highlights-with-change
12754 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12755 nil 'local))
12756 (unless org-sparse-tree-open-archived-trees
12757 (org-hide-archived-subtrees (point-min) (point-max)))
12758 (run-hooks 'org-occur-hook)
12759 (if (org-called-interactively-p 'interactive)
12760 (message "%d match(es) for regexp %s" cnt regexp))
12761 cnt))
12763 (defun org-occur-next-match (&optional n reset)
12764 "Function for `next-error-function' to find sparse tree matches.
12765 N is the number of matches to move, when negative move backwards.
12766 RESET is entirely ignored - this function always goes back to the
12767 starting point when no match is found."
12768 (let* ((limit (if (< n 0) (point-min) (point-max)))
12769 (search-func (if (< n 0)
12770 'previous-single-char-property-change
12771 'next-single-char-property-change))
12772 (n (abs n))
12773 (pos (point))
12775 (catch 'exit
12776 (while (setq p1 (funcall search-func (point) 'org-type))
12777 (when (equal p1 limit)
12778 (goto-char pos)
12779 (error "No more matches"))
12780 (when (equal (get-char-property p1 'org-type) 'org-occur)
12781 (setq n (1- n))
12782 (when (= n 0)
12783 (goto-char p1)
12784 (throw 'exit (point))))
12785 (goto-char p1))
12786 (goto-char p1)
12787 (error "No more matches"))))
12789 (defun org-show-context (&optional key)
12790 "Make sure point and context are visible.
12791 How much context is shown depends upon the variables
12792 `org-show-hierarchy-above', `org-show-following-heading',
12793 `org-show-entry-below' and `org-show-siblings'."
12794 (let ((heading-p (org-at-heading-p t))
12795 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12796 (following-p (org-get-alist-option org-show-following-heading key))
12797 (entry-p (org-get-alist-option org-show-entry-below key))
12798 (siblings-p (org-get-alist-option org-show-siblings key)))
12799 (catch 'exit
12800 ;; Show heading or entry text
12801 (if (and heading-p (not entry-p))
12802 (org-flag-heading nil) ; only show the heading
12803 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12804 (org-show-hidden-entry))) ; show entire entry
12805 (when following-p
12806 ;; Show next sibling, or heading below text
12807 (save-excursion
12808 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12809 (org-flag-heading nil))))
12810 (when siblings-p (org-show-siblings))
12811 (when hierarchy-p
12812 ;; show all higher headings, possibly with siblings
12813 (save-excursion
12814 (while (and (condition-case nil
12815 (progn (org-up-heading-all 1) t)
12816 (error nil))
12817 (not (bobp)))
12818 (org-flag-heading nil)
12819 (when siblings-p (org-show-siblings))))))))
12821 (defvar org-reveal-start-hook nil
12822 "Hook run before revealing a location.")
12824 (defun org-reveal (&optional siblings)
12825 "Show current entry, hierarchy above it, and the following headline.
12826 This can be used to show a consistent set of context around locations
12827 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12828 not t for the search context.
12830 With optional argument SIBLINGS, on each level of the hierarchy all
12831 siblings are shown. This repairs the tree structure to what it would
12832 look like when opened with hierarchical calls to `org-cycle'.
12833 With double optional argument \\[universal-argument] \\[universal-argument], \
12834 go to the parent and show the
12835 entire tree."
12836 (interactive "P")
12837 (run-hooks 'org-reveal-start-hook)
12838 (let ((org-show-hierarchy-above t)
12839 (org-show-following-heading t)
12840 (org-show-siblings (if siblings t org-show-siblings)))
12841 (org-show-context nil))
12842 (when (equal siblings '(16))
12843 (save-excursion
12844 (when (org-up-heading-safe)
12845 (org-show-subtree)
12846 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12848 (defun org-highlight-new-match (beg end)
12849 "Highlight from BEG to END and mark the highlight is an occur headline."
12850 (let ((ov (make-overlay beg end)))
12851 (overlay-put ov 'face 'secondary-selection)
12852 (overlay-put ov 'org-type 'org-occur)
12853 (push ov org-occur-highlights)))
12855 (defun org-remove-occur-highlights (&optional beg end noremove)
12856 "Remove the occur highlights from the buffer.
12857 BEG and END are ignored. If NOREMOVE is nil, remove this function
12858 from the `before-change-functions' in the current buffer."
12859 (interactive)
12860 (unless org-inhibit-highlight-removal
12861 (mapc 'delete-overlay org-occur-highlights)
12862 (setq org-occur-highlights nil)
12863 (setq org-occur-parameters nil)
12864 (unless noremove
12865 (remove-hook 'before-change-functions
12866 'org-remove-occur-highlights 'local))))
12868 ;;;; Priorities
12870 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12871 "Regular expression matching the priority indicator.")
12873 (defvar org-remove-priority-next-time nil)
12875 (defun org-priority-up ()
12876 "Increase the priority of the current item."
12877 (interactive)
12878 (org-priority 'up))
12880 (defun org-priority-down ()
12881 "Decrease the priority of the current item."
12882 (interactive)
12883 (org-priority 'down))
12885 (defun org-priority (&optional action show)
12886 "Change the priority of an item.
12887 ACTION can be `set', `up', `down', or a character."
12888 (interactive "P")
12889 (if (equal action '(4))
12890 (org-show-priority)
12891 (unless org-enable-priority-commands
12892 (error "Priority commands are disabled"))
12893 (setq action (or action 'set))
12894 (let (current new news have remove)
12895 (save-excursion
12896 (org-back-to-heading t)
12897 (if (looking-at org-priority-regexp)
12898 (setq current (string-to-char (match-string 2))
12899 have t))
12900 (cond
12901 ((eq action 'remove)
12902 (setq remove t new ?\ ))
12903 ((or (eq action 'set)
12904 (if (featurep 'xemacs) (characterp action) (integerp action)))
12905 (if (not (eq action 'set))
12906 (setq new action)
12907 (message "Priority %c-%c, SPC to remove: "
12908 org-highest-priority org-lowest-priority)
12909 (save-match-data
12910 (setq new (read-char-exclusive))))
12911 (if (and (= (upcase org-highest-priority) org-highest-priority)
12912 (= (upcase org-lowest-priority) org-lowest-priority))
12913 (setq new (upcase new)))
12914 (cond ((equal new ?\ ) (setq remove t))
12915 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12916 (error "Priority must be between `%c' and `%c'"
12917 org-highest-priority org-lowest-priority))))
12918 ((eq action 'up)
12919 (setq new (if have
12920 (1- current) ; normal cycling
12921 ;; last priority was empty
12922 (if (eq last-command this-command)
12923 org-lowest-priority ; wrap around empty to lowest
12924 ;; default
12925 (if org-priority-start-cycle-with-default
12926 org-default-priority
12927 (1- org-default-priority))))))
12928 ((eq action 'down)
12929 (setq new (if have
12930 (1+ current) ; normal cycling
12931 ;; last priority was empty
12932 (if (eq last-command this-command)
12933 org-highest-priority ; wrap around empty to highest
12934 ;; default
12935 (if org-priority-start-cycle-with-default
12936 org-default-priority
12937 (1+ org-default-priority))))))
12938 (t (error "Invalid action")))
12939 (if (or (< (upcase new) org-highest-priority)
12940 (> (upcase new) org-lowest-priority))
12941 (if (and (memq action '(up down))
12942 (not have) (not (eq last-command this-command)))
12943 ;; `new' is from default priority
12944 (error
12945 "The default can not be set, see `org-default-priority' why")
12946 ;; normal cycling: `new' is beyond highest/lowest priority
12947 ;; and is wrapped around to the empty priority
12948 (setq remove t)))
12949 (setq news (format "%c" new))
12950 (if have
12951 (if remove
12952 (replace-match "" t t nil 1)
12953 (replace-match news t t nil 2))
12954 (if remove
12955 (error "No priority cookie found in line")
12956 (let ((case-fold-search nil))
12957 (looking-at org-todo-line-regexp))
12958 (if (match-end 2)
12959 (progn
12960 (goto-char (match-end 2))
12961 (insert " [#" news "]"))
12962 (goto-char (match-beginning 3))
12963 (insert "[#" news "] "))))
12964 (org-preserve-lc (org-set-tags nil 'align)))
12965 (if remove
12966 (message "Priority removed")
12967 (message "Priority of current item set to %s" news)))))
12969 (defun org-show-priority ()
12970 "Show the priority of the current item.
12971 This priority is composed of the main priority given with the [#A] cookies,
12972 and by additional input from the age of a schedules or deadline entry."
12973 (interactive)
12974 (let ((pri (if (eq major-mode 'org-agenda-mode)
12975 (org-get-at-bol 'priority)
12976 (save-excursion
12977 (save-match-data
12978 (beginning-of-line)
12979 (and (looking-at org-heading-regexp)
12980 (org-get-priority (match-string 0))))))))
12981 (message "Priority is %d" (if pri pri -1000))))
12983 (defun org-get-priority (s)
12984 "Find priority cookie and return priority."
12985 (if (functionp org-get-priority-function)
12986 (funcall org-get-priority-function)
12987 (save-match-data
12988 (if (not (string-match org-priority-regexp s))
12989 (* 1000 (- org-lowest-priority org-default-priority))
12990 (* 1000 (- org-lowest-priority
12991 (string-to-char (match-string 2 s))))))))
12993 ;;;; Tags
12995 (defvar org-agenda-archives-mode)
12996 (defvar org-map-continue-from nil
12997 "Position from where mapping should continue.
12998 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13000 (defvar org-scanner-tags nil
13001 "The current tag list while the tags scanner is running.")
13002 (defvar org-trust-scanner-tags nil
13003 "Should `org-get-tags-at' use the tags for the scanner.
13004 This is for internal dynamical scoping only.
13005 When this is non-nil, the function `org-get-tags-at' will return the value
13006 of `org-scanner-tags' instead of building the list by itself. This
13007 can lead to large speed-ups when the tags scanner is used in a file with
13008 many entries, and when the list of tags is retrieved, for example to
13009 obtain a list of properties. Building the tags list for each entry in such
13010 a file becomes an N^2 operation - but with this variable set, it scales
13011 as N.")
13013 (defun org-scan-tags (action matcher todo-only &optional start-level)
13014 "Scan headline tags with inheritance and produce output ACTION.
13016 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13017 or `agenda' to produce an entry list for an agenda view. It can also be
13018 a Lisp form or a function that should be called at each matched headline, in
13019 this case the return value is a list of all return values from these calls.
13021 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13022 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13023 only lines with a not-done TODO keyword are included in the output.
13024 This should be the same variable that was scoped into
13025 and set by `org-make-tags-matcher' when it constructed MATCHER.
13027 START-LEVEL can be a string with asterisks, reducing the scope to
13028 headlines matching this string."
13029 (require 'org-agenda)
13030 (let* ((re (concat "^"
13031 (if start-level
13032 ;; Get the correct level to match
13033 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13034 org-outline-regexp)
13035 " *\\(\\<\\("
13036 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13037 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13038 (props (list 'face 'default
13039 'done-face 'org-agenda-done
13040 'undone-face 'default
13041 'mouse-face 'highlight
13042 'org-not-done-regexp org-not-done-regexp
13043 'org-todo-regexp org-todo-regexp
13044 'org-complex-heading-regexp org-complex-heading-regexp
13045 'help-echo
13046 (format "mouse-2 or RET jump to org file %s"
13047 (abbreviate-file-name
13048 (or (buffer-file-name (buffer-base-buffer))
13049 (buffer-name (buffer-base-buffer)))))))
13050 (case-fold-search nil)
13051 (org-map-continue-from nil)
13052 lspos tags tags-list
13053 (tags-alist (list (cons 0 org-file-tags)))
13054 (llast 0) rtn rtn1 level category i txt
13055 todo marker entry priority)
13056 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13057 (setq action (list 'lambda nil action)))
13058 (save-excursion
13059 (goto-char (point-min))
13060 (when (eq action 'sparse-tree)
13061 (org-overview)
13062 (org-remove-occur-highlights))
13063 (while (re-search-forward re nil t)
13064 (setq org-map-continue-from nil)
13065 (catch :skip
13066 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13067 tags (if (match-end 4) (org-match-string-no-properties 4)))
13068 (goto-char (setq lspos (match-beginning 0)))
13069 (setq level (org-reduced-level (funcall outline-level))
13070 category (org-get-category))
13071 (setq i llast llast level)
13072 ;; remove tag lists from same and sublevels
13073 (while (>= i level)
13074 (when (setq entry (assoc i tags-alist))
13075 (setq tags-alist (delete entry tags-alist)))
13076 (setq i (1- i)))
13077 ;; add the next tags
13078 (when tags
13079 (setq tags (org-split-string tags ":")
13080 tags-alist
13081 (cons (cons level tags) tags-alist)))
13082 ;; compile tags for current headline
13083 (setq tags-list
13084 (if org-use-tag-inheritance
13085 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13086 tags)
13087 org-scanner-tags tags-list)
13088 (when org-use-tag-inheritance
13089 (setcdr (car tags-alist)
13090 (mapcar (lambda (x)
13091 (setq x (copy-sequence x))
13092 (org-add-prop-inherited x))
13093 (cdar tags-alist))))
13094 (when (and tags org-use-tag-inheritance
13095 (or (not (eq t org-use-tag-inheritance))
13096 org-tags-exclude-from-inheritance))
13097 ;; selective inheritance, remove uninherited ones
13098 (setcdr (car tags-alist)
13099 (org-remove-uninherited-tags (cdar tags-alist))))
13100 (when (and
13102 ;; eval matcher only when the todo condition is OK
13103 (and (or (not todo-only) (member todo org-not-done-keywords))
13104 (let ((case-fold-search t) (org-trust-scanner-tags t))
13105 (eval matcher)))
13107 ;; Call the skipper, but return t if it does not skip,
13108 ;; so that the `and' form continues evaluating
13109 (progn
13110 (unless (eq action 'sparse-tree) (org-agenda-skip))
13113 ;; Check if timestamps are deselecting this entry
13114 (or (not todo-only)
13115 (and (member todo org-not-done-keywords)
13116 (or (not org-agenda-tags-todo-honor-ignore-options)
13117 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13119 ;; Extra check for the archive tag
13120 ;; FIXME: Does the skipper already do this????
13122 (not (member org-archive-tag tags-list))
13123 ;; we have an archive tag, should we use this anyway?
13124 (or (not org-agenda-skip-archived-trees)
13125 (and (eq action 'agenda) org-agenda-archives-mode))))
13127 ;; select this headline
13129 (cond
13130 ((eq action 'sparse-tree)
13131 (and org-highlight-sparse-tree-matches
13132 (org-get-heading) (match-end 0)
13133 (org-highlight-new-match
13134 (match-beginning 1) (match-end 1)))
13135 (org-show-context 'tags-tree))
13136 ((eq action 'agenda)
13137 (setq txt (org-agenda-format-item
13139 (concat
13140 (if (eq org-tags-match-list-sublevels 'indented)
13141 (make-string (1- level) ?.) "")
13142 (org-get-heading))
13143 category
13144 tags-list)
13145 priority (org-get-priority txt))
13146 (goto-char lspos)
13147 (setq marker (org-agenda-new-marker))
13148 (org-add-props txt props
13149 'org-marker marker 'org-hd-marker marker 'org-category category
13150 'todo-state todo
13151 'priority priority 'type "tagsmatch")
13152 (push txt rtn))
13153 ((functionp action)
13154 (setq org-map-continue-from nil)
13155 (save-excursion
13156 (setq rtn1 (funcall action))
13157 (push rtn1 rtn)))
13158 (t (error "Invalid action")))
13160 ;; if we are to skip sublevels, jump to end of subtree
13161 (unless org-tags-match-list-sublevels
13162 (org-end-of-subtree t)
13163 (backward-char 1))))
13164 ;; Get the correct position from where to continue
13165 (if org-map-continue-from
13166 (goto-char org-map-continue-from)
13167 (and (= (point) lspos) (end-of-line 1)))))
13168 (when (and (eq action 'sparse-tree)
13169 (not org-sparse-tree-open-archived-trees))
13170 (org-hide-archived-subtrees (point-min) (point-max)))
13171 (nreverse rtn)))
13173 (defun org-remove-uninherited-tags (tags)
13174 "Remove all tags that are not inherited from the list TAGS."
13175 (cond
13176 ((eq org-use-tag-inheritance t)
13177 (if org-tags-exclude-from-inheritance
13178 (org-delete-all org-tags-exclude-from-inheritance tags)
13179 tags))
13180 ((not org-use-tag-inheritance) nil)
13181 ((stringp org-use-tag-inheritance)
13182 (delq nil (mapcar
13183 (lambda (x)
13184 (if (and (string-match org-use-tag-inheritance x)
13185 (not (member x org-tags-exclude-from-inheritance)))
13186 x nil))
13187 tags)))
13188 ((listp org-use-tag-inheritance)
13189 (delq nil (mapcar
13190 (lambda (x)
13191 (if (member x org-use-tag-inheritance) x nil))
13192 tags)))))
13194 (defun org-match-sparse-tree (&optional todo-only match)
13195 "Create a sparse tree according to tags string MATCH.
13196 MATCH can contain positive and negative selection of tags, like
13197 \"+WORK+URGENT-WITHBOSS\".
13198 If optional argument TODO-ONLY is non-nil, only select lines that are
13199 also TODO lines."
13200 (interactive "P")
13201 (org-agenda-prepare-buffers (list (current-buffer)))
13202 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13204 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13206 (defvar org-cached-props nil)
13207 (defun org-cached-entry-get (pom property)
13208 (if (or (eq t org-use-property-inheritance)
13209 (and (stringp org-use-property-inheritance)
13210 (string-match org-use-property-inheritance property))
13211 (and (listp org-use-property-inheritance)
13212 (member property org-use-property-inheritance)))
13213 ;; Caching is not possible, check it directly
13214 (org-entry-get pom property 'inherit)
13215 ;; Get all properties, so that we can do complicated checks easily
13216 (cdr (assoc property (or org-cached-props
13217 (setq org-cached-props
13218 (org-entry-properties pom)))))))
13220 (defun org-global-tags-completion-table (&optional files)
13221 "Return the list of all tags in all agenda buffer/files.
13222 Optional FILES argument is a list of files which can be used
13223 instead of the agenda files."
13224 (save-excursion
13225 (org-uniquify
13226 (delq nil
13227 (apply 'append
13228 (mapcar
13229 (lambda (file)
13230 (set-buffer (find-file-noselect file))
13231 (append (org-get-buffer-tags)
13232 (mapcar (lambda (x) (if (stringp (car-safe x))
13233 (list (car-safe x)) nil))
13234 org-tag-alist)))
13235 (if (and files (car files))
13236 files
13237 (org-agenda-files))))))))
13239 (defun org-make-tags-matcher (match)
13240 "Create the TAGS/TODO matcher form for the selection string MATCH.
13242 The variable `todo-only' is scoped dynamically into this function.
13243 It will be set to t if the matcher restricts matching to TODO entries,
13244 otherwise will not be touched.
13246 Returns a cons of the selection string MATCH and the constructed
13247 lisp form implementing the matcher. The matcher is to be evaluated
13248 at an Org entry, with point on the headline, and returns t if the
13249 entry matches the selection string MATCH. The returned lisp form
13250 references two variables with information about the entry, which
13251 must be bound around the form's evaluation: todo, the TODO keyword
13252 at the entry (or nil of none); and tags-list, the list of all tags
13253 at the entry including inherited ones. Additionally, the category
13254 of the entry (if any) must be specified as the text property
13255 'org-category on the headline.
13257 See also `org-scan-tags'.
13259 (declare (special todo-only))
13260 (unless (boundp 'todo-only)
13261 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13262 (unless match
13263 ;; Get a new match request, with completion
13264 (let ((org-last-tags-completion-table
13265 (org-global-tags-completion-table)))
13266 (setq match (org-completing-read-no-i
13267 "Match: " 'org-tags-completion-function nil nil nil
13268 'org-tags-history))))
13270 ;; Parse the string and create a lisp form
13271 (let ((match0 match)
13272 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13273 minus tag mm
13274 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13275 orterms term orlist re-p str-p level-p level-op time-p
13276 prop-p pn pv po gv rest)
13277 (if (string-match "/+" match)
13278 ;; match contains also a todo-matching request
13279 (progn
13280 (setq tagsmatch (substring match 0 (match-beginning 0))
13281 todomatch (substring match (match-end 0)))
13282 (if (string-match "^!" todomatch)
13283 (setq todo-only t todomatch (substring todomatch 1)))
13284 (if (string-match "^\\s-*$" todomatch)
13285 (setq todomatch nil)))
13286 ;; only matching tags
13287 (setq tagsmatch match todomatch nil))
13289 ;; Make the tags matcher
13290 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13291 (setq tagsmatcher t)
13292 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13293 (while (setq term (pop orterms))
13294 (while (and (equal (substring term -1) "\\") orterms)
13295 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13296 (while (string-match re term)
13297 (setq rest (substring term (match-end 0))
13298 minus (and (match-end 1)
13299 (equal (match-string 1 term) "-"))
13300 tag (save-match-data (replace-regexp-in-string
13301 "\\\\-" "-"
13302 (match-string 2 term)))
13303 re-p (equal (string-to-char tag) ?{)
13304 level-p (match-end 4)
13305 prop-p (match-end 5)
13306 mm (cond
13307 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13308 (level-p
13309 (setq level-op (org-op-to-function (match-string 3 term)))
13310 `(,level-op level ,(string-to-number
13311 (match-string 4 term))))
13312 (prop-p
13313 (setq pn (match-string 5 term)
13314 po (match-string 6 term)
13315 pv (match-string 7 term)
13316 re-p (equal (string-to-char pv) ?{)
13317 str-p (equal (string-to-char pv) ?\")
13318 time-p (save-match-data
13319 (string-match "^\"[[<].*[]>]\"$" pv))
13320 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13321 (if time-p (setq pv (org-matcher-time pv)))
13322 (setq po (org-op-to-function po (if time-p 'time str-p)))
13323 (cond
13324 ((equal pn "CATEGORY")
13325 (setq gv '(get-text-property (point) 'org-category)))
13326 ((equal pn "TODO")
13327 (setq gv 'todo))
13329 (setq gv `(org-cached-entry-get nil ,pn))))
13330 (if re-p
13331 (if (eq po 'org<>)
13332 `(not (string-match ,pv (or ,gv "")))
13333 `(string-match ,pv (or ,gv "")))
13334 (if str-p
13335 `(,po (or ,gv "") ,pv)
13336 `(,po (string-to-number (or ,gv ""))
13337 ,(string-to-number pv) ))))
13338 (t `(member ,tag tags-list)))
13339 mm (if minus (list 'not mm) mm)
13340 term rest)
13341 (push mm tagsmatcher))
13342 (push (if (> (length tagsmatcher) 1)
13343 (cons 'and tagsmatcher)
13344 (car tagsmatcher))
13345 orlist)
13346 (setq tagsmatcher nil))
13347 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13348 (setq tagsmatcher
13349 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13350 ;; Make the todo matcher
13351 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13352 (setq todomatcher t)
13353 (setq orterms (org-split-string todomatch "|") orlist nil)
13354 (while (setq term (pop orterms))
13355 (while (string-match re term)
13356 (setq minus (and (match-end 1)
13357 (equal (match-string 1 term) "-"))
13358 kwd (match-string 2 term)
13359 re-p (equal (string-to-char kwd) ?{)
13360 term (substring term (match-end 0))
13361 mm (if re-p
13362 `(string-match ,(substring kwd 1 -1) todo)
13363 (list 'equal 'todo kwd))
13364 mm (if minus (list 'not mm) mm))
13365 (push mm todomatcher))
13366 (push (if (> (length todomatcher) 1)
13367 (cons 'and todomatcher)
13368 (car todomatcher))
13369 orlist)
13370 (setq todomatcher nil))
13371 (setq todomatcher (if (> (length orlist) 1)
13372 (cons 'or orlist) (car orlist))))
13374 ;; Return the string and lisp forms of the matcher
13375 (setq matcher (if todomatcher
13376 (list 'and tagsmatcher todomatcher)
13377 tagsmatcher))
13378 (when todo-only
13379 (setq matcher (list 'and '(member todo org-not-done-keywords)
13380 matcher)))
13381 (cons match0 matcher)))
13383 (defun org-op-to-function (op &optional stringp)
13384 "Turn an operator into the appropriate function."
13385 (setq op
13386 (cond
13387 ((equal op "<" ) '(< string< org-time<))
13388 ((equal op ">" ) '(> org-string> org-time>))
13389 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13390 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13391 ((member op '("=" "==")) '(= string= org-time=))
13392 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13393 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13395 (defun org<> (a b) (not (= a b)))
13396 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13397 (defun org-string>= (a b) (not (string< a b)))
13398 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13399 (defun org-string<> (a b) (not (string= a b)))
13400 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13401 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13402 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13403 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13404 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13405 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13406 (defun org-2ft (s)
13407 "Convert S to a floating point time.
13408 If S is already a number, just return it. If it is a string, parse
13409 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13410 (cond
13411 ((numberp s) s)
13412 ((stringp s)
13413 (condition-case nil
13414 (float-time (apply 'encode-time (org-parse-time-string s)))
13415 (error 0.)))
13416 (t 0.)))
13418 (defun org-time-today ()
13419 "Time in seconds today at 0:00.
13420 Returns the float number of seconds since the beginning of the
13421 epoch to the beginning of today (00:00)."
13422 (float-time (apply 'encode-time
13423 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13425 (defun org-matcher-time (s)
13426 "Interpret a time comparison value."
13427 (save-match-data
13428 (cond
13429 ((string= s "<now>") (float-time))
13430 ((string= s "<today>") (org-time-today))
13431 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13432 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13433 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13434 (+ (org-time-today)
13435 (* (string-to-number (match-string 1 s))
13436 (cdr (assoc (match-string 2 s)
13437 '(("d" . 86400.0) ("w" . 604800.0)
13438 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13439 (t (org-2ft s)))))
13441 (defun org-match-any-p (re list)
13442 "Does re match any element of list?"
13443 (setq list (mapcar (lambda (x) (string-match re x)) list))
13444 (delq nil list))
13446 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13447 (defvar org-tags-overlay (make-overlay 1 1))
13448 (org-detach-overlay org-tags-overlay)
13450 (defun org-get-local-tags-at (&optional pos)
13451 "Get a list of tags defined in the current headline."
13452 (org-get-tags-at pos 'local))
13454 (defun org-get-local-tags ()
13455 "Get a list of tags defined in the current headline."
13456 (org-get-tags-at nil 'local))
13458 (defun org-get-tags-at (&optional pos local)
13459 "Get a list of all headline tags applicable at POS.
13460 POS defaults to point. If tags are inherited, the list contains
13461 the targets in the same sequence as the headlines appear, i.e.
13462 the tags of the current headline come last.
13463 When LOCAL is non-nil, only return tags from the current headline,
13464 ignore inherited ones."
13465 (interactive)
13466 (if (and org-trust-scanner-tags
13467 (or (not pos) (equal pos (point)))
13468 (not local))
13469 org-scanner-tags
13470 (let (tags ltags lastpos parent)
13471 (save-excursion
13472 (save-restriction
13473 (widen)
13474 (goto-char (or pos (point)))
13475 (save-match-data
13476 (catch 'done
13477 (condition-case nil
13478 (progn
13479 (org-back-to-heading t)
13480 (while (not (equal lastpos (point)))
13481 (setq lastpos (point))
13482 (when (looking-at
13483 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13484 (setq ltags (org-split-string
13485 (org-match-string-no-properties 1) ":"))
13486 (when parent
13487 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13488 (setq tags (append
13489 (if parent
13490 (org-remove-uninherited-tags ltags)
13491 ltags)
13492 tags)))
13493 (or org-use-tag-inheritance (throw 'done t))
13494 (if local (throw 'done t))
13495 (or (org-up-heading-safe) (error nil))
13496 (setq parent t)))
13497 (error nil)))))
13498 (if local
13499 tags
13500 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13502 (defun org-add-prop-inherited (s)
13503 (add-text-properties 0 (length s) '(inherited t) s)
13506 (defun org-toggle-tag (tag &optional onoff)
13507 "Toggle the tag TAG for the current line.
13508 If ONOFF is `on' or `off', don't toggle but set to this state."
13509 (let (res current)
13510 (save-excursion
13511 (org-back-to-heading t)
13512 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13513 (point-at-eol) t)
13514 (progn
13515 (setq current (match-string 1))
13516 (replace-match ""))
13517 (setq current ""))
13518 (setq current (nreverse (org-split-string current ":")))
13519 (cond
13520 ((eq onoff 'on)
13521 (setq res t)
13522 (or (member tag current) (push tag current)))
13523 ((eq onoff 'off)
13524 (or (not (member tag current)) (setq current (delete tag current))))
13525 (t (if (member tag current)
13526 (setq current (delete tag current))
13527 (setq res t)
13528 (push tag current))))
13529 (end-of-line 1)
13530 (if current
13531 (progn
13532 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13533 (org-set-tags nil t))
13534 (delete-horizontal-space))
13535 (run-hooks 'org-after-tags-change-hook))
13536 res))
13538 (defun org-align-tags-here (to-col)
13539 ;; Assumes that this is a headline
13540 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13541 (beginning-of-line 1)
13542 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13543 (< pos (match-beginning 2)))
13544 (progn
13545 (setq tags-l (- (match-end 2) (match-beginning 2)))
13546 (goto-char (match-beginning 1))
13547 (insert " ")
13548 (delete-region (point) (1+ (match-beginning 2)))
13549 (setq ncol (max (current-column)
13550 (1+ col)
13551 (if (> to-col 0)
13552 to-col
13553 (- (abs to-col) tags-l))))
13554 (setq p (point))
13555 (insert (make-string (- ncol (current-column)) ?\ ))
13556 (setq ncol (current-column))
13557 (when indent-tabs-mode (tabify p (point-at-eol)))
13558 (org-move-to-column (min ncol col) t))
13559 (goto-char pos))))
13561 (defun org-set-tags-command (&optional arg just-align)
13562 "Call the set-tags command for the current entry."
13563 (interactive "P")
13564 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13565 (org-set-tags arg just-align)
13566 (save-excursion
13567 (org-back-to-heading t)
13568 (org-set-tags arg just-align))))
13570 (defun org-set-tags-to (data)
13571 "Set the tags of the current entry to DATA, replacing the current tags.
13572 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13573 If DATA is nil or the empty string, any tags will be removed."
13574 (interactive "sTags: ")
13575 (setq data
13576 (cond
13577 ((eq data nil) "")
13578 ((equal data "") "")
13579 ((stringp data)
13580 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13581 ":"))
13582 ((listp data)
13583 (concat ":" (mapconcat 'identity data ":") ":"))))
13584 (when data
13585 (save-excursion
13586 (org-back-to-heading t)
13587 (when (looking-at org-complex-heading-regexp)
13588 (if (match-end 5)
13589 (progn
13590 (goto-char (match-beginning 5))
13591 (insert data)
13592 (delete-region (point) (point-at-eol))
13593 (org-set-tags nil 'align))
13594 (goto-char (point-at-eol))
13595 (insert " " data)
13596 (org-set-tags nil 'align)))
13597 (beginning-of-line 1)
13598 (if (looking-at ".*?\\([ \t]+\\)$")
13599 (delete-region (match-beginning 1) (match-end 1))))))
13601 (defun org-align-all-tags ()
13602 "Align the tags i all headings."
13603 (interactive)
13604 (save-excursion
13605 (or (ignore-errors (org-back-to-heading t))
13606 (outline-next-heading))
13607 (if (org-at-heading-p)
13608 (org-set-tags t)
13609 (message "No headings"))))
13611 (defvar org-indent-indentation-per-level)
13612 (defun org-set-tags (&optional arg just-align)
13613 "Set the tags for the current headline.
13614 With prefix ARG, realign all tags in headings in the current buffer."
13615 (interactive "P")
13616 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13617 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13618 'region-start-level 'region))
13619 org-loop-over-headlines-in-active-region)
13620 (org-map-entries
13621 ;; We don't use ARG and JUST-ALIGN here these args are not
13622 ;; useful when looping over headlines
13623 `(org-set-tags)
13624 org-loop-over-headlines-in-active-region
13625 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13626 (let* ((re org-outline-regexp-bol)
13627 (current (unless arg (org-get-tags-string)))
13628 (col (current-column))
13629 (org-setting-tags t)
13630 table current-tags inherited-tags ; computed below when needed
13631 tags p0 c0 c1 rpl di tc level)
13632 (if arg
13633 (save-excursion
13634 (goto-char (point-min))
13635 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13636 (while (re-search-forward re nil t)
13637 (org-set-tags nil t)
13638 (end-of-line 1)))
13639 (message "All tags realigned to column %d" org-tags-column))
13640 (if just-align
13641 (setq tags current)
13642 ;; Get a new set of tags from the user
13643 (save-excursion
13644 (setq table (append org-tag-persistent-alist
13645 (or org-tag-alist (org-get-buffer-tags))
13646 (and
13647 org-complete-tags-always-offer-all-agenda-tags
13648 (org-global-tags-completion-table
13649 (org-agenda-files))))
13650 org-last-tags-completion-table table
13651 current-tags (org-split-string current ":")
13652 inherited-tags (nreverse
13653 (nthcdr (length current-tags)
13654 (nreverse (org-get-tags-at))))
13655 tags
13656 (if (or (eq t org-use-fast-tag-selection)
13657 (and org-use-fast-tag-selection
13658 (delq nil (mapcar 'cdr table))))
13659 (org-fast-tag-selection
13660 current-tags inherited-tags table
13661 (if org-fast-tag-selection-include-todo
13662 org-todo-key-alist))
13663 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13664 (org-trim
13665 (org-icompleting-read "Tags: "
13666 'org-tags-completion-function
13667 nil nil current 'org-tags-history))))))
13668 (while (string-match "[-+&]+" tags)
13669 ;; No boolean logic, just a list
13670 (setq tags (replace-match ":" t t tags))))
13672 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13674 (if org-tags-sort-function
13675 (setq tags (mapconcat 'identity
13676 (sort (org-split-string
13677 tags (org-re "[^[:alnum:]_@#%]+"))
13678 org-tags-sort-function) ":")))
13680 (if (string-match "\\`[\t ]*\\'" tags)
13681 (setq tags "")
13682 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13683 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13685 ;; Insert new tags at the correct column
13686 (beginning-of-line 1)
13687 (setq level (or (and (looking-at org-outline-regexp)
13688 (- (match-end 0) (point) 1))
13690 (cond
13691 ((and (equal current "") (equal tags "")))
13692 ((re-search-forward
13693 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13694 (point-at-eol) t)
13695 (if (equal tags "")
13696 (setq rpl "")
13697 (goto-char (match-beginning 0))
13698 (setq c0 (current-column)
13699 ;; compute offset for the case of org-indent-mode active
13700 di (if org-indent-mode
13701 (* (1- org-indent-indentation-per-level) (1- level))
13703 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13704 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13705 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13706 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13707 (replace-match rpl t t)
13708 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13709 tags)
13710 (t (error "Tags alignment failed")))
13711 (org-move-to-column col)
13712 (unless just-align
13713 (run-hooks 'org-after-tags-change-hook))))))
13715 (defun org-change-tag-in-region (beg end tag off)
13716 "Add or remove TAG for each entry in the region.
13717 This works in the agenda, and also in an org-mode buffer."
13718 (interactive
13719 (list (region-beginning) (region-end)
13720 (let ((org-last-tags-completion-table
13721 (if (derived-mode-p 'org-mode)
13722 (org-get-buffer-tags)
13723 (org-global-tags-completion-table))))
13724 (org-icompleting-read
13725 "Tag: " 'org-tags-completion-function nil nil nil
13726 'org-tags-history))
13727 (progn
13728 (message "[s]et or [r]emove? ")
13729 (equal (read-char-exclusive) ?r))))
13730 (if (fboundp 'deactivate-mark) (deactivate-mark))
13731 (let ((agendap (equal major-mode 'org-agenda-mode))
13732 l1 l2 m buf pos newhead (cnt 0))
13733 (goto-char end)
13734 (setq l2 (1- (org-current-line)))
13735 (goto-char beg)
13736 (setq l1 (org-current-line))
13737 (loop for l from l1 to l2 do
13738 (org-goto-line l)
13739 (setq m (get-text-property (point) 'org-hd-marker))
13740 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13741 (and agendap m))
13742 (setq buf (if agendap (marker-buffer m) (current-buffer))
13743 pos (if agendap m (point)))
13744 (with-current-buffer buf
13745 (save-excursion
13746 (save-restriction
13747 (goto-char pos)
13748 (setq cnt (1+ cnt))
13749 (org-toggle-tag tag (if off 'off 'on))
13750 (setq newhead (org-get-heading)))))
13751 (and agendap (org-agenda-change-all-lines newhead m))))
13752 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13754 (defun org-tags-completion-function (string predicate &optional flag)
13755 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13756 (confirm (lambda (x) (stringp (car x)))))
13757 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13758 (setq s1 (match-string 1 string)
13759 s2 (match-string 2 string))
13760 (setq s1 "" s2 string))
13761 (cond
13762 ((eq flag nil)
13763 ;; try completion
13764 (setq rtn (try-completion s2 ctable confirm))
13765 (if (stringp rtn)
13766 (setq rtn
13767 (concat s1 s2 (substring rtn (length s2))
13768 (if (and org-add-colon-after-tag-completion
13769 (assoc rtn ctable))
13770 ":" ""))))
13771 rtn)
13772 ((eq flag t)
13773 ;; all-completions
13774 (all-completions s2 ctable confirm)
13776 ((eq flag 'lambda)
13777 ;; exact match?
13778 (assoc s2 ctable)))
13781 (defun org-fast-tag-insert (kwd tags face &optional end)
13782 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13783 (insert (format "%-12s" (concat kwd ":"))
13784 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13785 (or end "")))
13787 (defun org-fast-tag-show-exit (flag)
13788 (save-excursion
13789 (org-goto-line 3)
13790 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13791 (replace-match ""))
13792 (when flag
13793 (end-of-line 1)
13794 (org-move-to-column (- (window-width) 19) t)
13795 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13797 (defun org-set-current-tags-overlay (current prefix)
13798 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13799 (if (featurep 'xemacs)
13800 (org-overlay-display org-tags-overlay (concat prefix s)
13801 'secondary-selection)
13802 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13803 (org-overlay-display org-tags-overlay (concat prefix s)))))
13805 (defvar org-last-tag-selection-key nil)
13806 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13807 "Fast tag selection with single keys.
13808 CURRENT is the current list of tags in the headline, INHERITED is the
13809 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13810 possibly with grouping information. TODO-TABLE is a similar table with
13811 TODO keywords, should these have keys assigned to them.
13812 If the keys are nil, a-z are automatically assigned.
13813 Returns the new tags string, or nil to not change the current settings."
13814 (let* ((fulltable (append table todo-table))
13815 (maxlen (apply 'max (mapcar
13816 (lambda (x)
13817 (if (stringp (car x)) (string-width (car x)) 0))
13818 fulltable)))
13819 (buf (current-buffer))
13820 (expert (eq org-fast-tag-selection-single-key 'expert))
13821 (buffer-tags nil)
13822 (fwidth (+ maxlen 3 1 3))
13823 (ncol (/ (- (window-width) 4) fwidth))
13824 (i-face 'org-done)
13825 (c-face 'org-todo)
13826 tg cnt e c char c1 c2 ntable tbl rtn
13827 ov-start ov-end ov-prefix
13828 (exit-after-next org-fast-tag-selection-single-key)
13829 (done-keywords org-done-keywords)
13830 groups ingroup)
13831 (save-excursion
13832 (beginning-of-line 1)
13833 (if (looking-at
13834 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13835 (setq ov-start (match-beginning 1)
13836 ov-end (match-end 1)
13837 ov-prefix "")
13838 (setq ov-start (1- (point-at-eol))
13839 ov-end (1+ ov-start))
13840 (skip-chars-forward "^\n\r")
13841 (setq ov-prefix
13842 (concat
13843 (buffer-substring (1- (point)) (point))
13844 (if (> (current-column) org-tags-column)
13846 (make-string (- org-tags-column (current-column)) ?\ ))))))
13847 (move-overlay org-tags-overlay ov-start ov-end)
13848 (save-window-excursion
13849 (if expert
13850 (set-buffer (get-buffer-create " *Org tags*"))
13851 (delete-other-windows)
13852 (split-window-vertically)
13853 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13854 (erase-buffer)
13855 (org-set-local 'org-done-keywords done-keywords)
13856 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13857 (org-fast-tag-insert "Current" current c-face "\n\n")
13858 (org-fast-tag-show-exit exit-after-next)
13859 (org-set-current-tags-overlay current ov-prefix)
13860 (setq tbl fulltable char ?a cnt 0)
13861 (while (setq e (pop tbl))
13862 (cond
13863 ((equal (car e) :startgroup)
13864 (push '() groups) (setq ingroup t)
13865 (when (not (= cnt 0))
13866 (setq cnt 0)
13867 (insert "\n"))
13868 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13869 ((equal (car e) :endgroup)
13870 (setq ingroup nil cnt 0)
13871 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13872 ((equal e '(:newline))
13873 (when (not (= cnt 0))
13874 (setq cnt 0)
13875 (insert "\n")
13876 (setq e (car tbl))
13877 (while (equal (car tbl) '(:newline))
13878 (insert "\n")
13879 (setq tbl (cdr tbl)))))
13881 (setq tg (copy-sequence (car e)) c2 nil)
13882 (if (cdr e)
13883 (setq c (cdr e))
13884 ;; automatically assign a character.
13885 (setq c1 (string-to-char
13886 (downcase (substring
13887 tg (if (= (string-to-char tg) ?@) 1 0)))))
13888 (if (or (rassoc c1 ntable) (rassoc c1 table))
13889 (while (or (rassoc char ntable) (rassoc char table))
13890 (setq char (1+ char)))
13891 (setq c2 c1))
13892 (setq c (or c2 char)))
13893 (if ingroup (push tg (car groups)))
13894 (setq tg (org-add-props tg nil 'face
13895 (cond
13896 ((not (assoc tg table))
13897 (org-get-todo-face tg))
13898 ((member tg current) c-face)
13899 ((member tg inherited) i-face))))
13900 (if (and (= cnt 0) (not ingroup)) (insert " "))
13901 (insert "[" c "] " tg (make-string
13902 (- fwidth 4 (length tg)) ?\ ))
13903 (push (cons tg c) ntable)
13904 (when (= (setq cnt (1+ cnt)) ncol)
13905 (insert "\n")
13906 (if ingroup (insert " "))
13907 (setq cnt 0)))))
13908 (setq ntable (nreverse ntable))
13909 (insert "\n")
13910 (goto-char (point-min))
13911 (if (not expert) (org-fit-window-to-buffer))
13912 (setq rtn
13913 (catch 'exit
13914 (while t
13915 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13916 (if (not groups) "no " "")
13917 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13918 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13919 (setq org-last-tag-selection-key c)
13920 (cond
13921 ((= c ?\r) (throw 'exit t))
13922 ((= c ?!)
13923 (setq groups (not groups))
13924 (goto-char (point-min))
13925 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13926 ((= c ?\C-c)
13927 (if (not expert)
13928 (org-fast-tag-show-exit
13929 (setq exit-after-next (not exit-after-next)))
13930 (setq expert nil)
13931 (delete-other-windows)
13932 (set-window-buffer (split-window-vertically) " *Org tags*")
13933 (org-switch-to-buffer-other-window " *Org tags*")
13934 (org-fit-window-to-buffer)))
13935 ((or (= c ?\C-g)
13936 (and (= c ?q) (not (rassoc c ntable))))
13937 (org-detach-overlay org-tags-overlay)
13938 (setq quit-flag t))
13939 ((= c ?\ )
13940 (setq current nil)
13941 (if exit-after-next (setq exit-after-next 'now)))
13942 ((= c ?\t)
13943 (condition-case nil
13944 (setq tg (org-icompleting-read
13945 "Tag: "
13946 (or buffer-tags
13947 (with-current-buffer buf
13948 (org-get-buffer-tags)))))
13949 (quit (setq tg "")))
13950 (when (string-match "\\S-" tg)
13951 (add-to-list 'buffer-tags (list tg))
13952 (if (member tg current)
13953 (setq current (delete tg current))
13954 (push tg current)))
13955 (if exit-after-next (setq exit-after-next 'now)))
13956 ((setq e (rassoc c todo-table) tg (car e))
13957 (with-current-buffer buf
13958 (save-excursion (org-todo tg)))
13959 (if exit-after-next (setq exit-after-next 'now)))
13960 ((setq e (rassoc c ntable) tg (car e))
13961 (if (member tg current)
13962 (setq current (delete tg current))
13963 (loop for g in groups do
13964 (if (member tg g)
13965 (mapc (lambda (x)
13966 (setq current (delete x current)))
13967 g)))
13968 (push tg current))
13969 (if exit-after-next (setq exit-after-next 'now))))
13971 ;; Create a sorted list
13972 (setq current
13973 (sort current
13974 (lambda (a b)
13975 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13976 (if (eq exit-after-next 'now) (throw 'exit t))
13977 (goto-char (point-min))
13978 (beginning-of-line 2)
13979 (delete-region (point) (point-at-eol))
13980 (org-fast-tag-insert "Current" current c-face)
13981 (org-set-current-tags-overlay current ov-prefix)
13982 (while (re-search-forward
13983 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13984 (setq tg (match-string 1))
13985 (add-text-properties
13986 (match-beginning 1) (match-end 1)
13987 (list 'face
13988 (cond
13989 ((member tg current) c-face)
13990 ((member tg inherited) i-face)
13991 (t (get-text-property (match-beginning 1) 'face))))))
13992 (goto-char (point-min)))))
13993 (org-detach-overlay org-tags-overlay)
13994 (if rtn
13995 (mapconcat 'identity current ":")
13996 nil))))
13998 (defun org-get-tags-string ()
13999 "Get the TAGS string in the current headline."
14000 (unless (org-at-heading-p t)
14001 (error "Not on a heading"))
14002 (save-excursion
14003 (beginning-of-line 1)
14004 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14005 (org-match-string-no-properties 1)
14006 "")))
14008 (defun org-get-tags ()
14009 "Get the list of tags specified in the current headline."
14010 (org-split-string (org-get-tags-string) ":"))
14012 (defun org-get-buffer-tags ()
14013 "Get a table of all tags used in the buffer, for completion."
14014 (let (tags)
14015 (save-excursion
14016 (goto-char (point-min))
14017 (while (re-search-forward
14018 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14019 (when (equal (char-after (point-at-bol 0)) ?*)
14020 (mapc (lambda (x) (add-to-list 'tags x))
14021 (org-split-string (org-match-string-no-properties 1) ":")))))
14022 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14023 (mapcar 'list tags)))
14025 ;;;; The mapping API
14027 (defun org-map-entries (func &optional match scope &rest skip)
14028 "Call FUNC at each headline selected by MATCH in SCOPE.
14030 FUNC is a function or a lisp form. The function will be called without
14031 arguments, with the cursor positioned at the beginning of the headline.
14032 The return values of all calls to the function will be collected and
14033 returned as a list.
14035 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14036 does not need to preserve point. After evaluation, the cursor will be
14037 moved to the end of the line (presumably of the headline of the
14038 processed entry) and search continues from there. Under some
14039 circumstances, this may not produce the wanted results. For example,
14040 if you have removed (e.g. archived) the current (sub)tree it could
14041 mean that the next entry will be skipped entirely. In such cases, you
14042 can specify the position from where search should continue by making
14043 FUNC set the variable `org-map-continue-from' to the desired buffer
14044 position.
14046 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14047 Only headlines that are matched by this query will be considered during
14048 the iteration. When MATCH is nil or t, all headlines will be
14049 visited by the iteration.
14051 SCOPE determines the scope of this command. It can be any of:
14053 nil The current buffer, respecting the restriction if any
14054 tree The subtree started with the entry at point
14055 region The entries within the active region, if any
14056 region-start-level
14057 The entries within the active region, but only those at
14058 the same level than the first one.
14059 file The current buffer, without restriction
14060 file-with-archives
14061 The current buffer, and any archives associated with it
14062 agenda All agenda files
14063 agenda-with-archives
14064 All agenda files with any archive files associated with them
14065 \(file1 file2 ...)
14066 If this is a list, all files in the list will be scanned
14068 The remaining args are treated as settings for the skipping facilities of
14069 the scanner. The following items can be given here:
14071 archive skip trees with the archive tag.
14072 comment skip trees with the COMMENT keyword
14073 function or Emacs Lisp form:
14074 will be used as value for `org-agenda-skip-function', so whenever
14075 the function returns t, FUNC will not be called for that
14076 entry and search will continue from the point where the
14077 function leaves it.
14079 If your function needs to retrieve the tags including inherited tags
14080 at the *current* entry, you can use the value of the variable
14081 `org-scanner-tags' which will be much faster than getting the value
14082 with `org-get-tags-at'. If your function gets properties with
14083 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14084 to t around the call to `org-entry-properties' to get the same speedup.
14085 Note that if your function moves around to retrieve tags and properties at
14086 a *different* entry, you cannot use these techniques."
14087 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14088 (not (org-region-active-p)))
14089 (let* ((org-agenda-archives-mode nil) ; just to make sure
14090 (org-agenda-skip-archived-trees (memq 'archive skip))
14091 (org-agenda-skip-comment-trees (memq 'comment skip))
14092 (org-agenda-skip-function
14093 (car (org-delete-all '(comment archive) skip)))
14094 (org-tags-match-list-sublevels t)
14095 (start-level (eq scope 'region-start-level))
14096 matcher file res
14097 org-todo-keywords-for-agenda
14098 org-done-keywords-for-agenda
14099 org-todo-keyword-alist-for-agenda
14100 org-drawers-for-agenda
14101 org-tag-alist-for-agenda
14102 todo-only)
14104 (cond
14105 ((eq match t) (setq matcher t))
14106 ((eq match nil) (setq matcher t))
14107 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14109 (save-excursion
14110 (save-restriction
14111 (cond ((eq scope 'tree)
14112 (org-back-to-heading t)
14113 (org-narrow-to-subtree)
14114 (setq scope nil))
14115 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14116 (org-region-active-p))
14117 ;; If needed, set start-level to a string like "2"
14118 (when start-level
14119 (save-excursion
14120 (goto-char (region-beginning))
14121 (unless (org-at-heading-p) (outline-next-heading))
14122 (setq start-level (org-current-level))))
14123 (narrow-to-region (region-beginning)
14124 (save-excursion
14125 (goto-char (region-end))
14126 (unless (and (bolp) (org-at-heading-p))
14127 (outline-next-heading))
14128 (point)))
14129 (setq scope nil)))
14131 (if (not scope)
14132 (progn
14133 (org-agenda-prepare-buffers
14134 (list (buffer-file-name (current-buffer))))
14135 (setq res (org-scan-tags func matcher todo-only start-level)))
14136 ;; Get the right scope
14137 (cond
14138 ((and scope (listp scope) (symbolp (car scope)))
14139 (setq scope (eval scope)))
14140 ((eq scope 'agenda)
14141 (setq scope (org-agenda-files t)))
14142 ((eq scope 'agenda-with-archives)
14143 (setq scope (org-agenda-files t))
14144 (setq scope (org-add-archive-files scope)))
14145 ((eq scope 'file)
14146 (setq scope (list (buffer-file-name))))
14147 ((eq scope 'file-with-archives)
14148 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14149 (org-agenda-prepare-buffers scope)
14150 (while (setq file (pop scope))
14151 (with-current-buffer (org-find-base-buffer-visiting file)
14152 (save-excursion
14153 (save-restriction
14154 (widen)
14155 (goto-char (point-min))
14156 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14157 res)))
14159 ;;;; Properties
14161 ;;; Setting and retrieving properties
14163 (defconst org-special-properties
14164 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14165 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14166 "The special properties valid in Org-mode.
14168 These are properties that are not defined in the property drawer,
14169 but in some other way.")
14171 (defconst org-default-properties
14172 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14173 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14174 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14175 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14176 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14177 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14178 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14179 "Some properties that are used by Org-mode for various purposes.
14180 Being in this list makes sure that they are offered for completion.")
14182 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14183 "Regular expression matching the first line of a property drawer.")
14185 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14186 "Regular expression matching the last line of a property drawer.")
14188 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14189 "Regular expression matching the first line of a property drawer.")
14191 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14192 "Regular expression matching the first line of a property drawer.")
14194 (defconst org-property-drawer-re
14195 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14196 org-property-end-re "\\)\n?")
14197 "Matches an entire property drawer.")
14199 (defconst org-clock-drawer-re
14200 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14201 org-property-end-re "\\)\n?")
14202 "Matches an entire clock drawer.")
14204 (defsubst org-re-property (property)
14205 "Return a regexp matching a PROPERTY line.
14206 Match group 1 will be set to the value."
14207 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14209 (defsubst org-re-property-keyword (property)
14210 "Return a regexp matching a PROPERTY line, possibly with no
14211 value for the property."
14212 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14214 (defun org-property-action ()
14215 "Do an action on properties."
14216 (interactive)
14217 (let (c)
14218 (org-at-property-p)
14219 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14220 (setq c (read-char-exclusive))
14221 (cond
14222 ((equal c ?s)
14223 (call-interactively 'org-set-property))
14224 ((equal c ?d)
14225 (call-interactively 'org-delete-property))
14226 ((equal c ?D)
14227 (call-interactively 'org-delete-property-globally))
14228 ((equal c ?c)
14229 (call-interactively 'org-compute-property-at-point))
14230 (t (error "No such property action %c" c)))))
14232 (defun org-inc-effort ()
14233 "Increment the value of the effort property in the current entry."
14234 (interactive)
14235 (org-set-effort nil t))
14237 (defun org-set-effort (&optional value increment)
14238 "Set the effort property of the current entry.
14239 With numerical prefix arg, use the nth allowed value, 0 stands for the
14240 10th allowed value.
14242 When INCREMENT is non-nil, set the property to the next allowed value."
14243 (interactive "P")
14244 (if (equal value 0) (setq value 10))
14245 (let* ((completion-ignore-case t)
14246 (prop org-effort-property)
14247 (cur (org-entry-get nil prop))
14248 (allowed (org-property-get-allowed-values nil prop 'table))
14249 (existing (mapcar 'list (org-property-values prop)))
14251 (val (cond
14252 ((stringp value) value)
14253 ((and allowed (integerp value))
14254 (or (car (nth (1- value) allowed))
14255 (car (org-last allowed))))
14256 ((and allowed increment)
14257 (or (caadr (member (list cur) allowed))
14258 (error "Allowed effort values are not set")))
14259 (allowed
14260 (message "Select 1-9,0, [RET%s]: %s"
14261 (if cur (concat "=" cur) "")
14262 (mapconcat 'car allowed " "))
14263 (setq rpl (read-char-exclusive))
14264 (if (equal rpl ?\r)
14266 (setq rpl (- rpl ?0))
14267 (if (equal rpl 0) (setq rpl 10))
14268 (if (and (> rpl 0) (<= rpl (length allowed)))
14269 (car (nth (1- rpl) allowed))
14270 (org-completing-read "Effort: " allowed nil))))
14272 (let (org-completion-use-ido org-completion-use-iswitchb)
14273 (org-completing-read
14274 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14275 (concat "[" cur "]") "")
14276 ": ")
14277 existing nil nil "" nil cur))))))
14278 (unless (equal (org-entry-get nil prop) val)
14279 (org-entry-put nil prop val))
14280 (message "%s is now %s" prop val)))
14282 (defun org-at-property-p ()
14283 "Is cursor inside a property drawer?"
14284 (save-excursion
14285 (beginning-of-line 1)
14286 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14287 (save-match-data ;; Used by calling procedures
14288 (let ((p (point))
14289 (range (unless (org-before-first-heading-p)
14290 (org-get-property-block))))
14291 (and range (<= (car range) p) (< p (cdr range))))))))
14293 (defun org-get-property-block (&optional beg end force)
14294 "Return the (beg . end) range of the body of the property drawer.
14295 BEG and END are the beginning and end of the current subtree, or of
14296 the part before the first headline. If they are not given, they will
14297 be found. If the drawer does not exist and FORCE is non-nil, create
14298 the drawer."
14299 (catch 'exit
14300 (save-excursion
14301 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14302 (progn (org-back-to-heading t) (point))))
14303 (end (or end (and (not (outline-next-heading)) (point-max))
14304 (point))))
14305 (goto-char beg)
14306 (if (re-search-forward org-property-start-re end t)
14307 (setq beg (1+ (match-end 0)))
14308 (if force
14309 (save-excursion
14310 (org-insert-property-drawer)
14311 (setq end (progn (outline-next-heading) (point))))
14312 (throw 'exit nil))
14313 (goto-char beg)
14314 (if (re-search-forward org-property-start-re end t)
14315 (setq beg (1+ (match-end 0)))))
14316 (if (re-search-forward org-property-end-re end t)
14317 (setq end (match-beginning 0))
14318 (or force (throw 'exit nil))
14319 (goto-char beg)
14320 (setq end beg)
14321 (org-indent-line)
14322 (insert ":END:\n"))
14323 (cons beg end)))))
14325 (defun org-entry-properties (&optional pom which specific)
14326 "Get all properties of the entry at point-or-marker POM.
14327 This includes the TODO keyword, the tags, time strings for deadline,
14328 scheduled, and clocking, and any additional properties defined in the
14329 entry. The return value is an alist, keys may occur multiple times
14330 if the property key was used several times.
14331 POM may also be nil, in which case the current entry is used.
14332 If WHICH is nil or `all', get all properties. If WHICH is
14333 `special' or `standard', only get that subclass. If WHICH
14334 is a string only get exactly this property. SPECIFIC can be a string, the
14335 specific property we are interested in. Specifying it can speed
14336 things up because then unnecessary parsing is avoided."
14337 (setq which (or which 'all))
14338 (org-with-point-at pom
14339 (let ((clockstr (substring org-clock-string 0 -1))
14340 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14341 (case-fold-search nil)
14342 beg end range props sum-props key key1 value string clocksum clocksumt)
14343 (save-excursion
14344 (when (condition-case nil
14345 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14346 (error nil))
14347 (setq beg (point))
14348 (setq sum-props (get-text-property (point) 'org-summaries))
14349 (setq clocksum (get-text-property (point) :org-clock-minutes)
14350 clocksumt (get-text-property (point) :org-clock-minutes-today))
14351 (outline-next-heading)
14352 (setq end (point))
14353 (when (memq which '(all special))
14354 ;; Get the special properties, like TODO and tags
14355 (goto-char beg)
14356 (when (and (or (not specific) (string= specific "TODO"))
14357 (looking-at org-todo-line-regexp) (match-end 2))
14358 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14359 (when (and (or (not specific) (string= specific "PRIORITY"))
14360 (looking-at org-priority-regexp))
14361 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14362 (when (or (not specific) (string= specific "FILE"))
14363 (push (cons "FILE" buffer-file-name) props))
14364 (when (and (or (not specific) (string= specific "TAGS"))
14365 (setq value (org-get-tags-string))
14366 (string-match "\\S-" value))
14367 (push (cons "TAGS" value) props))
14368 (when (and (or (not specific) (string= specific "ALLTAGS"))
14369 (setq value (org-get-tags-at)))
14370 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14371 ":"))
14372 props))
14373 (when (or (not specific) (string= specific "BLOCKED"))
14374 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14375 (when (or (not specific)
14376 (member specific
14377 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14378 "TIMESTAMP" "TIMESTAMP_IA")))
14379 (catch 'match
14380 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14381 (setq key (if (match-end 1)
14382 (substring (org-match-string-no-properties 1)
14383 0 -1))
14384 string (if (equal key clockstr)
14385 (org-trim
14386 (buffer-substring-no-properties
14387 (match-beginning 3) (goto-char
14388 (point-at-eol))))
14389 (substring (org-match-string-no-properties 3)
14390 1 -1)))
14391 ;; Get the correct property name from the key. This is
14392 ;; necessary if the user has configured time keywords.
14393 (setq key1 (concat key ":"))
14394 (cond
14395 ((not key)
14396 (setq key
14397 (if (= (char-after (match-beginning 3)) ?\[)
14398 "TIMESTAMP_IA" "TIMESTAMP")))
14399 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14400 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14401 ((equal key1 org-closed-string) (setq key "CLOSED"))
14402 ((equal key1 org-clock-string) (setq key "CLOCK")))
14403 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14404 (progn
14405 (push (cons key string) props)
14406 ;; no need to search further if match is found
14407 (throw 'match t))
14408 (when (or (equal key "CLOCK") (not (assoc key props)))
14409 (push (cons key string) props)))))))
14411 (when (memq which '(all standard))
14412 ;; Get the standard properties, like :PROP: ...
14413 (setq range (org-get-property-block beg end))
14414 (when range
14415 (goto-char (car range))
14416 (while (re-search-forward
14417 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14418 (cdr range) t)
14419 (setq key (org-match-string-no-properties 1)
14420 value (org-trim (or (org-match-string-no-properties 2) "")))
14421 (unless (member key excluded)
14422 (push (cons key (or value "")) props)))))
14423 (if clocksum
14424 (push (cons "CLOCKSUM"
14425 (org-columns-number-to-string (/ (float clocksum) 60.)
14426 'add_times))
14427 props))
14428 (if clocksumt
14429 (push (cons "CLOCKSUM_T"
14430 (org-columns-number-to-string (/ (float clocksumt) 60.)
14431 'add_times))
14432 props))
14433 (unless (assoc "CATEGORY" props)
14434 (push (cons "CATEGORY" (org-get-category)) props))
14435 (append sum-props (nreverse props)))))))
14437 (defun org-entry-get (pom property &optional inherit literal-nil)
14438 "Get value of PROPERTY for entry or content at point-or-marker POM.
14439 If INHERIT is non-nil and the entry does not have the property,
14440 then also check higher levels of the hierarchy.
14441 If INHERIT is the symbol `selective', use inheritance only if the setting
14442 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14443 If the property is present but empty, the return value is the empty string.
14444 If the property is not present at all, nil is returned.
14446 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14447 do not interpret it as the list atom nil. This is used for inheritance
14448 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14449 (org-with-point-at pom
14450 (if (and inherit (if (eq inherit 'selective)
14451 (org-property-inherit-p property)
14453 (org-entry-get-with-inheritance property literal-nil)
14454 (if (member property org-special-properties)
14455 ;; We need a special property. Use `org-entry-properties' to
14456 ;; retrieve it, but specify the wanted property
14457 (cdr (assoc property (org-entry-properties nil 'special property)))
14458 (let* ((range (org-get-property-block))
14459 (props (list (or (assoc property org-file-properties)
14460 (assoc property org-global-properties)
14461 (assoc property org-global-properties-fixed))))
14462 (ap (lambda (key)
14463 (when (re-search-forward
14464 (org-re-property key) (cdr range) t)
14465 (setq props
14466 (org-update-property-plist
14468 (if (match-end 1)
14469 (org-match-string-no-properties 1) "")
14470 props)))))
14471 val)
14472 (when (and range (goto-char (car range)))
14473 (funcall ap property)
14474 (goto-char (car range))
14475 (while (funcall ap (concat property "+")))
14476 (setq val (cdr (assoc property props)))
14477 (when val (if literal-nil val (org-not-nil val)))))))))
14479 (defun org-property-or-variable-value (var &optional inherit)
14480 "Check if there is a property fixing the value of VAR.
14481 If yes, return this value. If not, return the current value of the variable."
14482 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14483 (if (and prop (stringp prop) (string-match "\\S-" prop))
14484 (read prop)
14485 (symbol-value var))))
14487 (defun org-entry-delete (pom property)
14488 "Delete the property PROPERTY from entry at point-or-marker POM."
14489 (org-with-point-at pom
14490 (if (member property org-special-properties)
14491 nil ; cannot delete these properties.
14492 (let ((range (org-get-property-block)))
14493 (if (and range
14494 (goto-char (car range))
14495 (re-search-forward
14496 (org-re-property property)
14497 (cdr range) t))
14498 (progn
14499 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14501 nil)))))
14503 ;; Multi-values properties are properties that contain multiple values
14504 ;; These values are assumed to be single words, separated by whitespace.
14505 (defun org-entry-add-to-multivalued-property (pom property value)
14506 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14507 (let* ((old (org-entry-get pom property))
14508 (values (and old (org-split-string old "[ \t]"))))
14509 (setq value (org-entry-protect-space value))
14510 (unless (member value values)
14511 (setq values (cons value values))
14512 (org-entry-put pom property
14513 (mapconcat 'identity values " ")))))
14515 (defun org-entry-remove-from-multivalued-property (pom property value)
14516 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14517 (let* ((old (org-entry-get pom property))
14518 (values (and old (org-split-string old "[ \t]"))))
14519 (setq value (org-entry-protect-space value))
14520 (when (member value values)
14521 (setq values (delete value values))
14522 (org-entry-put pom property
14523 (mapconcat 'identity values " ")))))
14525 (defun org-entry-member-in-multivalued-property (pom property value)
14526 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14527 (let* ((old (org-entry-get pom property))
14528 (values (and old (org-split-string old "[ \t]"))))
14529 (setq value (org-entry-protect-space value))
14530 (member value values)))
14532 (defun org-entry-get-multivalued-property (pom property)
14533 "Return a list of values in a multivalued property."
14534 (let* ((value (org-entry-get pom property))
14535 (values (and value (org-split-string value "[ \t]"))))
14536 (mapcar 'org-entry-restore-space values)))
14538 (defun org-entry-put-multivalued-property (pom property &rest values)
14539 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14540 VALUES should be a list of strings. Spaces will be protected."
14541 (org-entry-put pom property
14542 (mapconcat 'org-entry-protect-space values " "))
14543 (let* ((value (org-entry-get pom property))
14544 (values (and value (org-split-string value "[ \t]"))))
14545 (mapcar 'org-entry-restore-space values)))
14547 (defun org-entry-protect-space (s)
14548 "Protect spaces and newline in string S."
14549 (while (string-match " " s)
14550 (setq s (replace-match "%20" t t s)))
14551 (while (string-match "\n" s)
14552 (setq s (replace-match "%0A" t t s)))
14555 (defun org-entry-restore-space (s)
14556 "Restore spaces and newline in string S."
14557 (while (string-match "%20" s)
14558 (setq s (replace-match " " t t s)))
14559 (while (string-match "%0A" s)
14560 (setq s (replace-match "\n" t t s)))
14563 (defvar org-entry-property-inherited-from (make-marker)
14564 "Marker pointing to the entry from where a property was inherited.
14565 Each call to `org-entry-get-with-inheritance' will set this marker to the
14566 location of the entry where the inheritance search matched. If there was
14567 no match, the marker will point nowhere.
14568 Note that also `org-entry-get' calls this function, if the INHERIT flag
14569 is set.")
14571 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14572 "Get PROPERTY of entry or content at point, search higher levels if needed.
14573 The search will stop at the first ancestor which has the property defined.
14574 If the value found is \"nil\", return nil to show that the property
14575 should be considered as undefined (this is the meaning of nil here).
14576 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14577 (move-marker org-entry-property-inherited-from nil)
14578 (let (tmp)
14579 (save-excursion
14580 (save-restriction
14581 (widen)
14582 (catch 'ex
14583 (while t
14584 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14585 (or (ignore-errors (org-back-to-heading t))
14586 (goto-char (point-min)))
14587 (move-marker org-entry-property-inherited-from (point))
14588 (throw 'ex tmp))
14589 (or (ignore-errors (org-up-heading-safe))
14590 (throw 'ex nil))))))
14591 (setq tmp (or tmp
14592 (cdr (assoc property org-file-properties))
14593 (cdr (assoc property org-global-properties))
14594 (cdr (assoc property org-global-properties-fixed))))
14595 (if literal-nil tmp (org-not-nil tmp))))
14597 (defvar org-property-changed-functions nil
14598 "Hook called when the value of a property has changed.
14599 Each hook function should accept two arguments, the name of the property
14600 and the new value.")
14602 (defun org-entry-put (pom property value)
14603 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14604 (org-with-point-at pom
14605 (org-back-to-heading t)
14606 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14607 range)
14608 (cond
14609 ((equal property "TODO")
14610 (when (and (stringp value) (string-match "\\S-" value)
14611 (not (member value org-todo-keywords-1)))
14612 (error "\"%s\" is not a valid TODO state" value))
14613 (if (or (not value)
14614 (not (string-match "\\S-" value)))
14615 (setq value 'none))
14616 (org-todo value)
14617 (org-set-tags nil 'align))
14618 ((equal property "PRIORITY")
14619 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14620 (string-to-char value) ?\ ))
14621 (org-set-tags nil 'align))
14622 ((equal property "SCHEDULED")
14623 (if (re-search-forward org-scheduled-time-regexp end t)
14624 (cond
14625 ((eq value 'earlier) (org-timestamp-change -1 'day))
14626 ((eq value 'later) (org-timestamp-change 1 'day))
14627 (t (call-interactively 'org-schedule)))
14628 (call-interactively 'org-schedule)))
14629 ((equal property "DEADLINE")
14630 (if (re-search-forward org-deadline-time-regexp end t)
14631 (cond
14632 ((eq value 'earlier) (org-timestamp-change -1 'day))
14633 ((eq value 'later) (org-timestamp-change 1 'day))
14634 (t (call-interactively 'org-deadline)))
14635 (call-interactively 'org-deadline)))
14636 ((member property org-special-properties)
14637 (error "The %s property can not yet be set with `org-entry-put'"
14638 property))
14639 (t ; a non-special property
14640 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14641 (setq range (org-get-property-block beg end 'force))
14642 (goto-char (car range))
14643 (if (re-search-forward
14644 (org-re-property-keyword property) (cdr range) t)
14645 (progn
14646 (delete-region (match-beginning 0) (match-end 0))
14647 (goto-char (match-beginning 0)))
14648 (goto-char (cdr range))
14649 (insert "\n")
14650 (backward-char 1)
14651 (org-indent-line))
14652 (insert ":" property ":")
14653 (and value (insert " " value))
14654 (org-indent-line)))))
14655 (run-hook-with-args 'org-property-changed-functions property value)))
14657 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14658 "Get all property keys in the current buffer.
14659 With INCLUDE-SPECIALS, also list the special properties that reflect things
14660 like tags and TODO state.
14661 With INCLUDE-DEFAULTS, also include properties that has special meaning
14662 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14663 and others.
14664 With INCLUDE-COLUMNS, also include property names given in COLUMN
14665 formats in the current buffer."
14666 (let (rtn range cfmt s p)
14667 (save-excursion
14668 (save-restriction
14669 (widen)
14670 (goto-char (point-min))
14671 (while (re-search-forward org-property-start-re nil t)
14672 (setq range (org-get-property-block))
14673 (goto-char (car range))
14674 (while (re-search-forward
14675 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14676 (cdr range) t)
14677 (add-to-list 'rtn (org-match-string-no-properties 1)))
14678 (outline-next-heading))))
14680 (when include-specials
14681 (setq rtn (append org-special-properties rtn)))
14683 (when include-defaults
14684 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14685 (add-to-list 'rtn org-effort-property))
14687 (when include-columns
14688 (save-excursion
14689 (save-restriction
14690 (widen)
14691 (goto-char (point-min))
14692 (while (re-search-forward
14693 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14694 nil t)
14695 (setq cfmt (match-string 2) s 0)
14696 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14697 cfmt s)
14698 (setq s (match-end 0)
14699 p (match-string 1 cfmt))
14700 (unless (or (equal p "ITEM")
14701 (member p org-special-properties))
14702 (add-to-list 'rtn (match-string 1 cfmt))))))))
14704 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14706 (defun org-property-values (key)
14707 "Return a list of all values of property KEY in the current buffer."
14708 (save-excursion
14709 (save-restriction
14710 (widen)
14711 (goto-char (point-min))
14712 (let ((re (org-re-property key))
14713 values)
14714 (while (re-search-forward re nil t)
14715 (add-to-list 'values (org-trim (match-string 1))))
14716 (delete "" values)))))
14718 (defun org-insert-property-drawer ()
14719 "Insert a property drawer into the current entry."
14720 (org-back-to-heading t)
14721 (looking-at org-outline-regexp)
14722 (let ((indent (if org-adapt-indentation
14723 (- (match-end 0) (match-beginning 0))
14725 (beg (point))
14726 (re (concat "^[ \t]*" org-keyword-time-regexp))
14727 end hiddenp)
14728 (outline-next-heading)
14729 (setq end (point))
14730 (goto-char beg)
14731 (while (re-search-forward re end t))
14732 (setq hiddenp (outline-invisible-p))
14733 (end-of-line 1)
14734 (and (equal (char-after) ?\n) (forward-char 1))
14735 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14736 (if (member (match-string 1) '("CLOCK:" ":END:"))
14737 ;; just skip this line
14738 (beginning-of-line 2)
14739 ;; Drawer start, find the end
14740 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14741 (beginning-of-line 1)))
14742 (org-skip-over-state-notes)
14743 (skip-chars-backward " \t\n\r")
14744 (if (eq (char-before) ?*) (forward-char 1))
14745 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14746 (beginning-of-line 0)
14747 (org-indent-to-column indent)
14748 (beginning-of-line 2)
14749 (org-indent-to-column indent)
14750 (beginning-of-line 0)
14751 (if hiddenp
14752 (save-excursion
14753 (org-back-to-heading t)
14754 (hide-entry))
14755 (org-flag-drawer t))))
14757 (defun org-insert-drawer (&optional arg drawer)
14758 "Insert a drawer at point.
14760 Optional argument DRAWER, when non-nil, is a string representing
14761 drawer's name. Otherwise, the user is prompted for a name.
14763 If a region is active, insert the drawer around that region
14764 instead.
14766 Point is left between drawer's boundaries."
14767 (interactive "P")
14768 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14769 "LOGBOOK"))
14770 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14771 ;; internally by Org. They are meant to be inserted
14772 ;; automatically.
14773 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14774 ;; Remove system drawers from list. Note: For some reason,
14775 ;; `org-completing-read' ignores the predicate while
14776 ;; `completing-read' handles it fine.
14777 (drawer (if arg "PROPERTIES"
14778 (or drawer
14779 (completing-read
14780 "Drawer: " org-drawers
14781 (lambda (d) (not (member d system-drawers))))))))
14782 (cond
14783 ;; With C-u, fall back on `org-insert-property-drawer'
14784 (arg (org-insert-property-drawer))
14785 ;; With an active region, insert a drawer at point.
14786 ((not (org-region-active-p))
14787 (progn
14788 (unless (bolp) (insert "\n"))
14789 (insert (format ":%s:\n\n:END:\n" drawer))
14790 (forward-line -2)))
14791 ;; Otherwise, insert the drawer at point
14793 (let ((rbeg (region-beginning))
14794 (rend (copy-marker (region-end))))
14795 (unwind-protect
14796 (progn
14797 (goto-char rbeg)
14798 (beginning-of-line)
14799 (when (save-excursion
14800 (re-search-forward org-outline-regexp-bol rend t))
14801 (error "Drawers cannot contain headlines"))
14802 ;; Position point at the beginning of the first
14803 ;; non-blank line in region. Insert drawer's opening
14804 ;; there, then indent it.
14805 (org-skip-whitespace)
14806 (beginning-of-line)
14807 (insert ":" drawer ":\n")
14808 (forward-line -1)
14809 (indent-for-tab-command)
14810 ;; Move point to the beginning of the first blank line
14811 ;; after the last non-blank line in region. Insert
14812 ;; drawer's closing, then indent it.
14813 (goto-char rend)
14814 (skip-chars-backward " \r\t\n")
14815 (insert "\n:END:")
14816 (deactivate-mark t)
14817 (indent-for-tab-command)
14818 (unless (eolp) (insert "\n")))
14819 ;; Clear marker, whatever the outcome of insertion is.
14820 (set-marker rend nil)))))))
14822 (defvar org-property-set-functions-alist nil
14823 "Property set function alist.
14824 Each entry should have the following format:
14826 (PROPERTY . READ-FUNCTION)
14828 The read function will be called with the same argument as
14829 `org-completing-read'.")
14831 (defun org-set-property-function (property)
14832 "Get the function that should be used to set PROPERTY.
14833 This is computed according to `org-property-set-functions-alist'."
14834 (or (cdr (assoc property org-property-set-functions-alist))
14835 'org-completing-read))
14837 (defun org-read-property-value (property)
14838 "Read PROPERTY value from user."
14839 (let* ((completion-ignore-case t)
14840 (allowed (org-property-get-allowed-values nil property 'table))
14841 (cur (org-entry-get nil property))
14842 (prompt (concat property " value"
14843 (if (and cur (string-match "\\S-" cur))
14844 (concat " [" cur "]") "") ": "))
14845 (set-function (org-set-property-function property))
14846 (val (if allowed
14847 (funcall set-function prompt allowed nil
14848 (not (get-text-property 0 'org-unrestricted
14849 (caar allowed))))
14850 (let (org-completion-use-ido org-completion-use-iswitchb)
14851 (funcall set-function prompt
14852 (mapcar 'list (org-property-values property))
14853 nil nil "" nil cur)))))
14854 (if (equal val "")
14856 val)))
14858 (defvar org-last-set-property nil)
14859 (defun org-read-property-name ()
14860 "Read a property name."
14861 (let* ((completion-ignore-case t)
14862 (keys (org-buffer-property-keys nil t t))
14863 (default-prop (or (save-excursion
14864 (save-match-data
14865 (beginning-of-line)
14866 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14867 (null (string= (match-string 1) "END"))
14868 (match-string 1))))
14869 org-last-set-property))
14870 (property (org-icompleting-read
14871 (concat "Property"
14872 (if default-prop (concat " [" default-prop "]") "")
14873 ": ")
14874 (mapcar 'list keys)
14875 nil nil nil nil
14876 default-prop
14878 (if (member property keys)
14879 property
14880 (or (cdr (assoc (downcase property)
14881 (mapcar (lambda (x) (cons (downcase x) x))
14882 keys)))
14883 property))))
14885 (defun org-set-property (property value)
14886 "In the current entry, set PROPERTY to VALUE.
14887 When called interactively, this will prompt for a property name, offering
14888 completion on existing and default properties. And then it will prompt
14889 for a value, offering completion either on allowed values (via an inherited
14890 xxx_ALL property) or on existing values in other instances of this property
14891 in the current file."
14892 (interactive (list nil nil))
14893 (let* ((property (or property (org-read-property-name)))
14894 (value (or value (org-read-property-value property)))
14895 (fn (cdr (assoc property org-properties-postprocess-alist))))
14896 (setq org-last-set-property property)
14897 ;; Possibly postprocess the inserted value:
14898 (when fn (setq value (funcall fn value)))
14899 (unless (equal (org-entry-get nil property) value)
14900 (org-entry-put nil property value))))
14902 (defun org-delete-property (property)
14903 "In the current entry, delete PROPERTY."
14904 (interactive
14905 (let* ((completion-ignore-case t)
14906 (prop (org-icompleting-read "Property: "
14907 (org-entry-properties nil 'standard))))
14908 (list prop)))
14909 (message "Property %s %s" property
14910 (if (org-entry-delete nil property)
14911 "deleted"
14912 "was not present in the entry")))
14914 (defun org-delete-property-globally (property)
14915 "Remove PROPERTY globally, from all entries."
14916 (interactive
14917 (let* ((completion-ignore-case t)
14918 (prop (org-icompleting-read
14919 "Globally remove property: "
14920 (mapcar 'list (org-buffer-property-keys)))))
14921 (list prop)))
14922 (save-excursion
14923 (save-restriction
14924 (widen)
14925 (goto-char (point-min))
14926 (let ((cnt 0))
14927 (while (re-search-forward
14928 (org-re-property property)
14929 nil t)
14930 (setq cnt (1+ cnt))
14931 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14932 (message "Property \"%s\" removed from %d entries" property cnt)))))
14934 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14936 (defun org-compute-property-at-point ()
14937 "Compute the property at point.
14938 This looks for an enclosing column format, extracts the operator and
14939 then applies it to the property in the column format's scope."
14940 (interactive)
14941 (unless (org-at-property-p)
14942 (error "Not at a property"))
14943 (let ((prop (org-match-string-no-properties 2)))
14944 (org-columns-get-format-and-top-level)
14945 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14946 (error "No operator defined for property %s" prop))
14947 (org-columns-compute prop)))
14949 (defvar org-property-allowed-value-functions nil
14950 "Hook for functions supplying allowed values for a specific property.
14951 The functions must take a single argument, the name of the property, and
14952 return a flat list of allowed values. If \":ETC\" is one of
14953 the values, this means that these values are intended as defaults for
14954 completion, but that other values should be allowed too.
14955 The functions must return nil if they are not responsible for this
14956 property.")
14958 (defun org-property-get-allowed-values (pom property &optional table)
14959 "Get allowed values for the property PROPERTY.
14960 When TABLE is non-nil, return an alist that can directly be used for
14961 completion."
14962 (let (vals)
14963 (cond
14964 ((equal property "TODO")
14965 (setq vals (org-with-point-at pom
14966 (append org-todo-keywords-1 '("")))))
14967 ((equal property "PRIORITY")
14968 (let ((n org-lowest-priority))
14969 (while (>= n org-highest-priority)
14970 (push (char-to-string n) vals)
14971 (setq n (1- n)))))
14972 ((member property org-special-properties))
14973 ((setq vals (run-hook-with-args-until-success
14974 'org-property-allowed-value-functions property)))
14976 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14977 (when (and vals (string-match "\\S-" vals))
14978 (setq vals (car (read-from-string (concat "(" vals ")"))))
14979 (setq vals (mapcar (lambda (x)
14980 (cond ((stringp x) x)
14981 ((numberp x) (number-to-string x))
14982 ((symbolp x) (symbol-name x))
14983 (t "???")))
14984 vals)))))
14985 (when (member ":ETC" vals)
14986 (setq vals (remove ":ETC" vals))
14987 (org-add-props (car vals) '(org-unrestricted t)))
14988 (if table (mapcar 'list vals) vals)))
14990 (defun org-property-previous-allowed-value (&optional previous)
14991 "Switch to the next allowed value for this property."
14992 (interactive)
14993 (org-property-next-allowed-value t))
14995 (defun org-property-next-allowed-value (&optional previous)
14996 "Switch to the next allowed value for this property."
14997 (interactive)
14998 (unless (org-at-property-p)
14999 (error "Not at a property"))
15000 (let* ((key (match-string 2))
15001 (value (match-string 3))
15002 (allowed (or (org-property-get-allowed-values (point) key)
15003 (and (member value '("[ ]" "[-]" "[X]"))
15004 '("[ ]" "[X]"))))
15005 nval)
15006 (unless allowed
15007 (error "Allowed values for this property have not been defined"))
15008 (if previous (setq allowed (reverse allowed)))
15009 (if (member value allowed)
15010 (setq nval (car (cdr (member value allowed)))))
15011 (setq nval (or nval (car allowed)))
15012 (if (equal nval value)
15013 (error "Only one allowed value for this property"))
15014 (org-at-property-p)
15015 (replace-match (concat " :" key ": " nval) t t)
15016 (org-indent-line)
15017 (beginning-of-line 1)
15018 (skip-chars-forward " \t")
15019 (run-hook-with-args 'org-property-changed-functions key nval)))
15021 (defun org-find-olp (path &optional this-buffer)
15022 "Return a marker pointing to the entry at outline path OLP.
15023 If anything goes wrong, throw an error.
15024 You can wrap this call to catch the error like this:
15026 (condition-case msg
15027 (org-mobile-locate-entry (match-string 4))
15028 (error (nth 1 msg)))
15030 The return value will then be either a string with the error message,
15031 or a marker if everything is OK.
15033 If THIS-BUFFER is set, the outline path does not contain a file,
15034 only headings."
15035 (let* ((file (if this-buffer buffer-file-name (pop path)))
15036 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15037 (level 1)
15038 (lmin 1)
15039 (lmax 1)
15040 limit re end found pos heading cnt flevel)
15041 (unless buffer (error "File not found :%s" file))
15042 (with-current-buffer buffer
15043 (save-excursion
15044 (save-restriction
15045 (widen)
15046 (setq limit (point-max))
15047 (goto-char (point-min))
15048 (while (setq heading (pop path))
15049 (setq re (format org-complex-heading-regexp-format
15050 (regexp-quote heading)))
15051 (setq cnt 0 pos (point))
15052 (while (re-search-forward re end t)
15053 (setq level (- (match-end 1) (match-beginning 1)))
15054 (if (and (>= level lmin) (<= level lmax))
15055 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15056 (when (= cnt 0) (error "Heading not found on level %d: %s"
15057 lmax heading))
15058 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15059 lmax heading))
15060 (goto-char found)
15061 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15062 (setq end (save-excursion (org-end-of-subtree t t))))
15063 (when (org-at-heading-p)
15064 (point-marker)))))))
15066 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15067 "Find node HEADING in BUFFER.
15068 Return a marker to the heading if it was found, or nil if not.
15069 If POS-ONLY is set, return just the position instead of a marker.
15071 The heading text must match exact, but it may have a TODO keyword,
15072 a priority cookie and tags in the standard locations."
15073 (with-current-buffer (or buffer (current-buffer))
15074 (save-excursion
15075 (save-restriction
15076 (widen)
15077 (goto-char (point-min))
15078 (let (case-fold-search)
15079 (if (re-search-forward
15080 (format org-complex-heading-regexp-format
15081 (regexp-quote heading)) nil t)
15082 (if pos-only
15083 (match-beginning 0)
15084 (move-marker (make-marker) (match-beginning 0)))))))))
15086 (defun org-find-exact-heading-in-directory (heading &optional dir)
15087 "Find Org node headline HEADING in all .org files in directory DIR.
15088 When the target headline is found, return a marker to this location."
15089 (let ((files (directory-files (or dir default-directory)
15090 nil "\\`[^.#].*\\.org\\'"))
15091 file visiting m buffer)
15092 (catch 'found
15093 (while (setq file (pop files))
15094 (message "trying %s" file)
15095 (setq visiting (org-find-base-buffer-visiting file))
15096 (setq buffer (or visiting (find-file-noselect file)))
15097 (setq m (org-find-exact-headline-in-buffer
15098 heading buffer))
15099 (when (and (not m) (not visiting)) (kill-buffer buffer))
15100 (and m (throw 'found m))))))
15102 (defun org-find-entry-with-id (ident)
15103 "Locate the entry that contains the ID property with exact value IDENT.
15104 IDENT can be a string, a symbol or a number, this function will search for
15105 the string representation of it.
15106 Return the position where this entry starts, or nil if there is no such entry."
15107 (interactive "sID: ")
15108 (let ((id (cond
15109 ((stringp ident) ident)
15110 ((symbol-name ident) (symbol-name ident))
15111 ((numberp ident) (number-to-string ident))
15112 (t (error "IDENT %s must be a string, symbol or number" ident))))
15113 (case-fold-search nil))
15114 (save-excursion
15115 (save-restriction
15116 (widen)
15117 (goto-char (point-min))
15118 (when (re-search-forward
15119 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15120 nil t)
15121 (org-back-to-heading t)
15122 (point))))))
15124 ;;;; Timestamps
15126 (defvar org-last-changed-timestamp nil)
15127 (defvar org-last-inserted-timestamp nil
15128 "The last time stamp inserted with `org-insert-time-stamp'.")
15129 (defvar org-time-was-given) ; dynamically scoped parameter
15130 (defvar org-end-time-was-given) ; dynamically scoped parameter
15131 (defvar org-ts-what) ; dynamically scoped parameter
15133 (defun org-time-stamp (arg &optional inactive)
15134 "Prompt for a date/time and insert a time stamp.
15135 If the user specifies a time like HH:MM or if this command is
15136 called with at least one prefix argument, the time stamp contains
15137 the date and the time. Otherwise, only the date is be included.
15139 All parts of a date not specified by the user is filled in from
15140 the current date/time. So if you just press return without
15141 typing anything, the time stamp will represent the current
15142 date/time.
15144 If there is already a timestamp at the cursor, it will be
15145 modified.
15147 With two universal prefix arguments, insert an active timestamp
15148 with the current time without prompting the user."
15149 (interactive "P")
15150 (let* ((ts nil)
15151 (default-time
15152 ;; Default time is either today, or, when entering a range,
15153 ;; the range start.
15154 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15155 (save-excursion
15156 (re-search-backward
15157 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15158 (- (point) 20) t)))
15159 (apply 'encode-time (org-parse-time-string (match-string 1)))
15160 (current-time)))
15161 (default-input (and ts (org-get-compact-tod ts)))
15162 (repeater (save-excursion
15163 (save-match-data
15164 (beginning-of-line)
15165 (when (re-search-forward
15166 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15167 (save-excursion (progn (end-of-line) (point))) t)
15168 (match-string 0)))))
15169 org-time-was-given org-end-time-was-given time)
15170 (cond
15171 ((and (org-at-timestamp-p t)
15172 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15173 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15174 (insert "--")
15175 (setq time (let ((this-command this-command))
15176 (org-read-date arg 'totime nil nil
15177 default-time default-input inactive)))
15178 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15179 ((org-at-timestamp-p t)
15180 (setq time (let ((this-command this-command))
15181 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15182 (when (org-at-timestamp-p t) ; just to get the match data
15183 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15184 (replace-match "")
15185 (setq org-last-changed-timestamp
15186 (org-insert-time-stamp
15187 time (or org-time-was-given arg)
15188 inactive nil nil (list org-end-time-was-given)))
15189 (when repeater (goto-char (1- (point))) (insert " " repeater)
15190 (setq org-last-changed-timestamp
15191 (concat (substring org-last-inserted-timestamp 0 -1)
15192 " " repeater ">"))))
15193 (message "Timestamp updated"))
15194 ((equal arg '(16))
15195 (org-insert-time-stamp (current-time) t))
15197 (setq time (let ((this-command this-command))
15198 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15199 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15200 nil nil (list org-end-time-was-given))))))
15202 ;; FIXME: can we use this for something else, like computing time differences?
15203 (defun org-get-compact-tod (s)
15204 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15205 (let* ((t1 (match-string 1 s))
15206 (h1 (string-to-number (match-string 2 s)))
15207 (m1 (string-to-number (match-string 3 s)))
15208 (t2 (and (match-end 4) (match-string 5 s)))
15209 (h2 (and t2 (string-to-number (match-string 6 s))))
15210 (m2 (and t2 (string-to-number (match-string 7 s))))
15211 dh dm)
15212 (if (not t2)
15214 (setq dh (- h2 h1) dm (- m2 m1))
15215 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15216 (concat t1 "+" (number-to-string dh)
15217 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15219 (defun org-time-stamp-inactive (&optional arg)
15220 "Insert an inactive time stamp.
15221 An inactive time stamp is enclosed in square brackets instead of angle
15222 brackets. It is inactive in the sense that it does not trigger agenda entries,
15223 does not link to the calendar and cannot be changed with the S-cursor keys.
15224 So these are more for recording a certain time/date."
15225 (interactive "P")
15226 (org-time-stamp arg 'inactive))
15228 (defvar org-date-ovl (make-overlay 1 1))
15229 (overlay-put org-date-ovl 'face 'org-date-selected)
15230 (org-detach-overlay org-date-ovl)
15232 (defvar org-ans1) ; dynamically scoped parameter
15233 (defvar org-ans2) ; dynamically scoped parameter
15235 (defvar org-plain-time-of-day-regexp) ; defined below
15237 (defvar org-overriding-default-time nil) ; dynamically scoped
15238 (defvar org-read-date-overlay nil)
15239 (defvar org-dcst nil) ; dynamically scoped
15240 (defvar org-read-date-history nil)
15241 (defvar org-read-date-final-answer nil)
15242 (defvar org-read-date-analyze-futurep nil)
15243 (defvar org-read-date-analyze-forced-year nil)
15244 (defvar org-read-date-inactive)
15246 (defun org-read-date (&optional org-with-time to-time from-string prompt
15247 default-time default-input inactive)
15248 "Read a date, possibly a time, and make things smooth for the user.
15249 The prompt will suggest to enter an ISO date, but you can also enter anything
15250 which will at least partially be understood by `parse-time-string'.
15251 Unrecognized parts of the date will default to the current day, month, year,
15252 hour and minute. If this command is called to replace a timestamp at point,
15253 or to enter the second timestamp of a range, the default time is taken
15254 from the existing stamp. Furthermore, the command prefers the future,
15255 so if you are giving a date where the year is not given, and the day-month
15256 combination is already past in the current year, it will assume you
15257 mean next year. For details, see the manual. A few examples:
15259 3-2-5 --> 2003-02-05
15260 feb 15 --> currentyear-02-15
15261 2/15 --> currentyear-02-15
15262 sep 12 9 --> 2009-09-12
15263 12:45 --> today 12:45
15264 22 sept 0:34 --> currentyear-09-22 0:34
15265 12 --> currentyear-currentmonth-12
15266 Fri --> nearest Friday (today or later)
15267 etc.
15269 Furthermore you can specify a relative date by giving, as the *first* thing
15270 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15271 change in days weeks, months, years.
15272 With a single plus or minus, the date is relative to today. With a double
15273 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15274 +4d --> four days from today
15275 +4 --> same as above
15276 +2w --> two weeks from today
15277 ++5 --> five days from default date
15279 The function understands only English month and weekday abbreviations.
15281 While prompting, a calendar is popped up - you can also select the
15282 date with the mouse (button 1). The calendar shows a period of three
15283 months. To scroll it to other months, use the keys `>' and `<'.
15284 If you don't like the calendar, turn it off with
15285 \(setq org-read-date-popup-calendar nil)
15287 With optional argument TO-TIME, the date will immediately be converted
15288 to an internal time.
15289 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15290 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15291 still enter a time, and this function will inform the calling routine
15292 about this change. The calling routine may then choose to change the
15293 format used to insert the time stamp into the buffer to include the time.
15294 With optional argument FROM-STRING, read from this string instead from
15295 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15296 the time/date that is used for everything that is not specified by the
15297 user."
15298 (require 'parse-time)
15299 (let* ((org-time-stamp-rounding-minutes
15300 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15301 (org-dcst org-display-custom-times)
15302 (ct (org-current-time))
15303 (org-def (or org-overriding-default-time default-time ct))
15304 (org-defdecode (decode-time org-def))
15305 (dummy (progn
15306 (when (< (nth 2 org-defdecode) org-extend-today-until)
15307 (setcar (nthcdr 2 org-defdecode) -1)
15308 (setcar (nthcdr 1 org-defdecode) 59)
15309 (setq org-def (apply 'encode-time org-defdecode)
15310 org-defdecode (decode-time org-def)))))
15311 (calendar-frame-setup nil)
15312 (calendar-setup nil)
15313 (calendar-move-hook nil)
15314 (calendar-view-diary-initially-flag nil)
15315 (calendar-view-holidays-initially-flag nil)
15316 (timestr (format-time-string
15317 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15318 (prompt (concat (if prompt (concat prompt " ") "")
15319 (format "Date+time [%s]: " timestr)))
15320 ans (org-ans0 "") org-ans1 org-ans2 final)
15322 (cond
15323 (from-string (setq ans from-string))
15324 (org-read-date-popup-calendar
15325 (save-excursion
15326 (save-window-excursion
15327 (calendar)
15328 (org-eval-in-calendar '(setq cursor-type nil) t)
15329 (unwind-protect
15330 (progn
15331 (calendar-forward-day (- (time-to-days org-def)
15332 (calendar-absolute-from-gregorian
15333 (calendar-current-date))))
15334 (org-eval-in-calendar nil t)
15335 (let* ((old-map (current-local-map))
15336 (map (copy-keymap calendar-mode-map))
15337 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15338 (org-defkey map (kbd "RET") 'org-calendar-select)
15339 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15340 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15341 (org-defkey minibuffer-local-map [(meta shift left)]
15342 (lambda () (interactive)
15343 (org-eval-in-calendar '(calendar-backward-month 1))))
15344 (org-defkey minibuffer-local-map [(meta shift right)]
15345 (lambda () (interactive)
15346 (org-eval-in-calendar '(calendar-forward-month 1))))
15347 (org-defkey minibuffer-local-map [(meta shift up)]
15348 (lambda () (interactive)
15349 (org-eval-in-calendar '(calendar-backward-year 1))))
15350 (org-defkey minibuffer-local-map [(meta shift down)]
15351 (lambda () (interactive)
15352 (org-eval-in-calendar '(calendar-forward-year 1))))
15353 (org-defkey minibuffer-local-map [?\e (shift left)]
15354 (lambda () (interactive)
15355 (org-eval-in-calendar '(calendar-backward-month 1))))
15356 (org-defkey minibuffer-local-map [?\e (shift right)]
15357 (lambda () (interactive)
15358 (org-eval-in-calendar '(calendar-forward-month 1))))
15359 (org-defkey minibuffer-local-map [?\e (shift up)]
15360 (lambda () (interactive)
15361 (org-eval-in-calendar '(calendar-backward-year 1))))
15362 (org-defkey minibuffer-local-map [?\e (shift down)]
15363 (lambda () (interactive)
15364 (org-eval-in-calendar '(calendar-forward-year 1))))
15365 (org-defkey minibuffer-local-map [(shift up)]
15366 (lambda () (interactive)
15367 (org-eval-in-calendar '(calendar-backward-week 1))))
15368 (org-defkey minibuffer-local-map [(shift down)]
15369 (lambda () (interactive)
15370 (org-eval-in-calendar '(calendar-forward-week 1))))
15371 (org-defkey minibuffer-local-map [(shift left)]
15372 (lambda () (interactive)
15373 (org-eval-in-calendar '(calendar-backward-day 1))))
15374 (org-defkey minibuffer-local-map [(shift right)]
15375 (lambda () (interactive)
15376 (org-eval-in-calendar '(calendar-forward-day 1))))
15377 (org-defkey minibuffer-local-map ">"
15378 (lambda () (interactive)
15379 (org-eval-in-calendar '(scroll-calendar-left 1))))
15380 (org-defkey minibuffer-local-map "<"
15381 (lambda () (interactive)
15382 (org-eval-in-calendar '(scroll-calendar-right 1))))
15383 (org-defkey minibuffer-local-map "\C-v"
15384 (lambda () (interactive)
15385 (org-eval-in-calendar
15386 '(calendar-scroll-left-three-months 1))))
15387 (org-defkey minibuffer-local-map "\M-v"
15388 (lambda () (interactive)
15389 (org-eval-in-calendar
15390 '(calendar-scroll-right-three-months 1))))
15391 (run-hooks 'org-read-date-minibuffer-setup-hook)
15392 (unwind-protect
15393 (progn
15394 (use-local-map map)
15395 (setq org-read-date-inactive inactive)
15396 (add-hook 'post-command-hook 'org-read-date-display)
15397 (setq org-ans0 (read-string prompt default-input
15398 'org-read-date-history nil))
15399 ;; org-ans0: from prompt
15400 ;; org-ans1: from mouse click
15401 ;; org-ans2: from calendar motion
15402 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15403 (remove-hook 'post-command-hook 'org-read-date-display)
15404 (use-local-map old-map)
15405 (when org-read-date-overlay
15406 (delete-overlay org-read-date-overlay)
15407 (setq org-read-date-overlay nil)))))
15408 (bury-buffer "*Calendar*")))))
15410 (t ; Naked prompt only
15411 (unwind-protect
15412 (setq ans (read-string prompt default-input
15413 'org-read-date-history timestr))
15414 (when org-read-date-overlay
15415 (delete-overlay org-read-date-overlay)
15416 (setq org-read-date-overlay nil)))))
15418 (setq final (org-read-date-analyze ans org-def org-defdecode))
15420 (when org-read-date-analyze-forced-year
15421 (message "Year was forced into %s"
15422 (if org-read-date-force-compatible-dates
15423 "compatible range (1970-2037)"
15424 "range representable on this machine"))
15425 (ding))
15427 ;; One round trip to get rid of 34th of August and stuff like that....
15428 (setq final (decode-time (apply 'encode-time final)))
15430 (setq org-read-date-final-answer ans)
15432 (if to-time
15433 (apply 'encode-time final)
15434 (if (and (boundp 'org-time-was-given) org-time-was-given)
15435 (format "%04d-%02d-%02d %02d:%02d"
15436 (nth 5 final) (nth 4 final) (nth 3 final)
15437 (nth 2 final) (nth 1 final))
15438 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15440 (defvar org-def)
15441 (defvar org-defdecode)
15442 (defvar org-with-time)
15443 (defun org-read-date-display ()
15444 "Display the current date prompt interpretation in the minibuffer."
15445 (when org-read-date-display-live
15446 (when org-read-date-overlay
15447 (delete-overlay org-read-date-overlay))
15448 (when (minibufferp (current-buffer))
15449 (save-excursion
15450 (end-of-line 1)
15451 (while (not (equal (buffer-substring
15452 (max (point-min) (- (point) 4)) (point))
15453 " "))
15454 (insert " ")))
15455 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15456 " " (or org-ans1 org-ans2)))
15457 (org-end-time-was-given nil)
15458 (f (org-read-date-analyze ans org-def org-defdecode))
15459 (fmts (if org-dcst
15460 org-time-stamp-custom-formats
15461 org-time-stamp-formats))
15462 (fmt (if (or org-with-time
15463 (and (boundp 'org-time-was-given) org-time-was-given))
15464 (cdr fmts)
15465 (car fmts)))
15466 (txt (format-time-string fmt (apply 'encode-time f)))
15467 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15468 (txt (concat "=> " txt)))
15469 (when (and org-end-time-was-given
15470 (string-match org-plain-time-of-day-regexp txt))
15471 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15472 org-end-time-was-given
15473 (substring txt (match-end 0)))))
15474 (when org-read-date-analyze-futurep
15475 (setq txt (concat txt " (=>F)")))
15476 (setq org-read-date-overlay
15477 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15478 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15480 (defun org-read-date-analyze (ans org-def org-defdecode)
15481 "Analyze the combined answer of the date prompt."
15482 ;; FIXME: cleanup and comment
15483 (let ((nowdecode (decode-time (current-time)))
15484 delta deltan deltaw deltadef year month day
15485 hour minute second wday pm h2 m2 tl wday1
15486 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15487 (setq org-read-date-analyze-futurep nil
15488 org-read-date-analyze-forced-year nil)
15489 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15490 (setq ans "+0"))
15492 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15493 (setq ans (replace-match "" t t ans)
15494 deltan (car delta)
15495 deltaw (nth 1 delta)
15496 deltadef (nth 2 delta)))
15498 ;; Check if there is an iso week date in there. If yes, store the
15499 ;; info and postpone interpreting it until the rest of the parsing
15500 ;; is done.
15501 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15502 (setq iso-year (if (match-end 1)
15503 (org-small-year-to-year
15504 (string-to-number (match-string 1 ans))))
15505 iso-weekday (if (match-end 3)
15506 (string-to-number (match-string 3 ans)))
15507 iso-week (string-to-number (match-string 2 ans)))
15508 (setq ans (replace-match "" t t ans)))
15510 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15511 (when (string-match
15512 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15513 (setq year (if (match-end 2)
15514 (string-to-number (match-string 2 ans))
15515 (progn (setq kill-year t)
15516 (string-to-number (format-time-string "%Y"))))
15517 month (string-to-number (match-string 3 ans))
15518 day (string-to-number (match-string 4 ans)))
15519 (if (< year 100) (setq year (+ 2000 year)))
15520 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15521 t nil ans)))
15523 ;; Help matching dotted european dates
15524 (when (string-match
15525 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15526 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15527 (setq kill-year t)
15528 (string-to-number (format-time-string "%Y")))
15529 day (string-to-number (match-string 1 ans))
15530 month (string-to-number (match-string 2 ans))
15531 ans (replace-match (format "%04d-%02d-%02d" year month day)
15532 t nil ans)))
15534 ;; Help matching american dates, like 5/30 or 5/30/7
15535 (when (string-match
15536 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15537 (setq year (if (match-end 4)
15538 (string-to-number (match-string 4 ans))
15539 (progn (setq kill-year t)
15540 (string-to-number (format-time-string "%Y"))))
15541 month (string-to-number (match-string 1 ans))
15542 day (string-to-number (match-string 2 ans)))
15543 (if (< year 100) (setq year (+ 2000 year)))
15544 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15545 t nil ans)))
15546 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15547 ;; If there is a time with am/pm, and *no* time without it, we convert
15548 ;; so that matching will be successful.
15549 (loop for i from 1 to 2 do ; twice, for end time as well
15550 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15551 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15552 (setq hour (string-to-number (match-string 1 ans))
15553 minute (if (match-end 3)
15554 (string-to-number (match-string 3 ans))
15556 pm (equal ?p
15557 (string-to-char (downcase (match-string 4 ans)))))
15558 (if (and (= hour 12) (not pm))
15559 (setq hour 0)
15560 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15561 (setq ans (replace-match (format "%02d:%02d" hour minute)
15562 t t ans))))
15564 ;; Check if a time range is given as a duration
15565 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15566 (setq hour (string-to-number (match-string 1 ans))
15567 h2 (+ hour (string-to-number (match-string 3 ans)))
15568 minute (string-to-number (match-string 2 ans))
15569 m2 (+ minute (if (match-end 5) (string-to-number
15570 (match-string 5 ans))0)))
15571 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15572 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15573 t t ans)))
15575 ;; Check if there is a time range
15576 (when (boundp 'org-end-time-was-given)
15577 (setq org-time-was-given nil)
15578 (when (and (string-match org-plain-time-of-day-regexp ans)
15579 (match-end 8))
15580 (setq org-end-time-was-given (match-string 8 ans))
15581 (setq ans (concat (substring ans 0 (match-beginning 7))
15582 (substring ans (match-end 7))))))
15584 (setq tl (parse-time-string ans)
15585 day (or (nth 3 tl) (nth 3 org-defdecode))
15586 month (or (nth 4 tl)
15587 (if (and org-read-date-prefer-future
15588 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15589 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15590 (nth 4 org-defdecode)))
15591 year (or (and (not kill-year) (nth 5 tl))
15592 (if (and org-read-date-prefer-future
15593 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15594 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15595 (nth 5 org-defdecode)))
15596 hour (or (nth 2 tl) (nth 2 org-defdecode))
15597 minute (or (nth 1 tl) (nth 1 org-defdecode))
15598 second (or (nth 0 tl) 0)
15599 wday (nth 6 tl))
15601 (when (and (eq org-read-date-prefer-future 'time)
15602 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15603 (equal day (nth 3 nowdecode))
15604 (equal month (nth 4 nowdecode))
15605 (equal year (nth 5 nowdecode))
15606 (nth 2 tl)
15607 (or (< (nth 2 tl) (nth 2 nowdecode))
15608 (and (= (nth 2 tl) (nth 2 nowdecode))
15609 (nth 1 tl)
15610 (< (nth 1 tl) (nth 1 nowdecode)))))
15611 (setq day (1+ day)
15612 futurep t))
15614 ;; Special date definitions below
15615 (cond
15616 (iso-week
15617 ;; There was an iso week
15618 (require 'cal-iso)
15619 (setq futurep nil)
15620 (setq year (or iso-year year)
15621 day (or iso-weekday wday 1)
15622 wday nil ; to make sure that the trigger below does not match
15623 iso-date (calendar-gregorian-from-absolute
15624 (calendar-absolute-from-iso
15625 (list iso-week day year))))
15626 ; FIXME: Should we also push ISO weeks into the future?
15627 ; (when (and org-read-date-prefer-future
15628 ; (not iso-year)
15629 ; (< (calendar-absolute-from-gregorian iso-date)
15630 ; (time-to-days (current-time))))
15631 ; (setq year (1+ year)
15632 ; iso-date (calendar-gregorian-from-absolute
15633 ; (calendar-absolute-from-iso
15634 ; (list iso-week day year)))))
15635 (setq month (car iso-date)
15636 year (nth 2 iso-date)
15637 day (nth 1 iso-date)))
15638 (deltan
15639 (setq futurep nil)
15640 (unless deltadef
15641 (let ((now (decode-time (current-time))))
15642 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15643 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15644 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15645 ((equal deltaw "m") (setq month (+ month deltan)))
15646 ((equal deltaw "y") (setq year (+ year deltan)))))
15647 ((and wday (not (nth 3 tl)))
15648 ;; Weekday was given, but no day, so pick that day in the week
15649 ;; on or after the derived date.
15650 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15651 (unless (equal wday wday1)
15652 (setq day (+ day (% (- wday wday1 -7) 7))))))
15653 (if (and (boundp 'org-time-was-given)
15654 (nth 2 tl))
15655 (setq org-time-was-given t))
15656 (if (< year 100) (setq year (+ 2000 year)))
15657 ;; Check of the date is representable
15658 (if org-read-date-force-compatible-dates
15659 (progn
15660 (if (< year 1970)
15661 (setq year 1970 org-read-date-analyze-forced-year t))
15662 (if (> year 2037)
15663 (setq year 2037 org-read-date-analyze-forced-year t)))
15664 (condition-case nil
15665 (ignore (encode-time second minute hour day month year))
15666 (error
15667 (setq year (nth 5 org-defdecode))
15668 (setq org-read-date-analyze-forced-year t))))
15669 (setq org-read-date-analyze-futurep futurep)
15670 (list second minute hour day month year)))
15672 (defvar parse-time-weekdays)
15673 (defun org-read-date-get-relative (s today default)
15674 "Check string S for special relative date string.
15675 TODAY and DEFAULT are internal times, for today and for a default.
15676 Return shift list (N what def-flag)
15677 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15678 N is the number of WHATs to shift.
15679 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15680 the DEFAULT date rather than TODAY."
15681 (require 'parse-time)
15682 (when (and
15683 (string-match
15684 (concat
15685 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15686 "\\([0-9]+\\)?"
15687 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15688 "\\([ \t]\\|$\\)") s)
15689 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15690 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15691 (string-to-char (substring (match-string 1 s) -1))
15692 ?+))
15693 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15694 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15695 (what (if (match-end 3) (match-string 3 s) "d"))
15696 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15697 (date (if rel default today))
15698 (wday (nth 6 (decode-time date)))
15699 delta)
15700 (if wday1
15701 (progn
15702 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15703 (if (= dir ?-) (setq delta (- delta 7)))
15704 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15705 (list delta "d" rel))
15706 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15708 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15709 "Turn a user-specified date into the internal representation.
15710 The internal representation needed by the calendar is (month day year).
15711 This is a wrapper to handle the brain-dead convention in calendar that
15712 user function argument order change dependent on argument order."
15713 (if (boundp 'calendar-date-style)
15714 (cond
15715 ((eq calendar-date-style 'american)
15716 (list arg1 arg2 arg3))
15717 ((eq calendar-date-style 'european)
15718 (list arg2 arg1 arg3))
15719 ((eq calendar-date-style 'iso)
15720 (list arg2 arg3 arg1)))
15721 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15722 (if (org-bound-and-true-p european-calendar-style)
15723 (list arg2 arg1 arg3)
15724 (list arg1 arg2 arg3)))))
15726 (defun org-eval-in-calendar (form &optional keepdate)
15727 "Eval FORM in the calendar window and return to current window.
15728 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15729 otherwise stick to the current value of `org-ans2'."
15730 (let ((sf (selected-frame))
15731 (sw (selected-window)))
15732 (select-window (get-buffer-window "*Calendar*" t))
15733 (eval form)
15734 (when (and (not keepdate) (calendar-cursor-to-date))
15735 (let* ((date (calendar-cursor-to-date))
15736 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15737 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15738 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15739 (select-window sw)
15740 (org-select-frame-set-input-focus sf)))
15742 (defun org-calendar-select ()
15743 "Return to `org-read-date' with the date currently selected.
15744 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15745 (interactive)
15746 (when (calendar-cursor-to-date)
15747 (let* ((date (calendar-cursor-to-date))
15748 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15749 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15750 (if (active-minibuffer-window) (exit-minibuffer))))
15752 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15753 "Insert a date stamp for the date given by the internal TIME.
15754 WITH-HM means use the stamp format that includes the time of the day.
15755 INACTIVE means use square brackets instead of angular ones, so that the
15756 stamp will not contribute to the agenda.
15757 PRE and POST are optional strings to be inserted before and after the
15758 stamp.
15759 The command returns the inserted time stamp."
15760 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15761 stamp)
15762 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15763 (insert-before-markers (or pre ""))
15764 (when (listp extra)
15765 (setq extra (car extra))
15766 (if (and (stringp extra)
15767 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15768 (setq extra (format "-%02d:%02d"
15769 (string-to-number (match-string 1 extra))
15770 (string-to-number (match-string 2 extra))))
15771 (setq extra nil)))
15772 (when extra
15773 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15774 (insert-before-markers (setq stamp (format-time-string fmt time)))
15775 (insert-before-markers (or post ""))
15776 (setq org-last-inserted-timestamp stamp)))
15778 (defun org-toggle-time-stamp-overlays ()
15779 "Toggle the use of custom time stamp formats."
15780 (interactive)
15781 (setq org-display-custom-times (not org-display-custom-times))
15782 (unless org-display-custom-times
15783 (let ((p (point-min)) (bmp (buffer-modified-p)))
15784 (while (setq p (next-single-property-change p 'display))
15785 (if (and (get-text-property p 'display)
15786 (eq (get-text-property p 'face) 'org-date))
15787 (remove-text-properties
15788 p (setq p (next-single-property-change p 'display))
15789 '(display t))))
15790 (set-buffer-modified-p bmp)))
15791 (if (featurep 'xemacs)
15792 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15793 (org-restart-font-lock)
15794 (setq org-table-may-need-update t)
15795 (if org-display-custom-times
15796 (message "Time stamps are overlaid with custom format")
15797 (message "Time stamp overlays removed")))
15799 (defun org-display-custom-time (beg end)
15800 "Overlay modified time stamp format over timestamp between BEG and END."
15801 (let* ((ts (buffer-substring beg end))
15802 t1 w1 with-hm tf time str w2 (off 0))
15803 (save-match-data
15804 (setq t1 (org-parse-time-string ts t))
15805 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15806 (setq off (- (match-end 0) (match-beginning 0)))))
15807 (setq end (- end off))
15808 (setq w1 (- end beg)
15809 with-hm (and (nth 1 t1) (nth 2 t1))
15810 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15811 time (org-fix-decoded-time t1)
15812 str (org-add-props
15813 (format-time-string
15814 (substring tf 1 -1) (apply 'encode-time time))
15815 nil 'mouse-face 'highlight)
15816 w2 (length str))
15817 (if (not (= w2 w1))
15818 (add-text-properties (1+ beg) (+ 2 beg)
15819 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15820 (if (featurep 'xemacs)
15821 (progn
15822 (put-text-property beg end 'invisible t)
15823 (put-text-property beg end 'end-glyph (make-glyph str)))
15824 (put-text-property beg end 'display str))))
15826 (defun org-translate-time (string)
15827 "Translate all timestamps in STRING to custom format.
15828 But do this only if the variable `org-display-custom-times' is set."
15829 (when org-display-custom-times
15830 (save-match-data
15831 (let* ((start 0)
15832 (re org-ts-regexp-both)
15833 t1 with-hm inactive tf time str beg end)
15834 (while (setq start (string-match re string start))
15835 (setq beg (match-beginning 0)
15836 end (match-end 0)
15837 t1 (save-match-data
15838 (org-parse-time-string (substring string beg end) t))
15839 with-hm (and (nth 1 t1) (nth 2 t1))
15840 inactive (equal (substring string beg (1+ beg)) "[")
15841 tf (funcall (if with-hm 'cdr 'car)
15842 org-time-stamp-custom-formats)
15843 time (org-fix-decoded-time t1)
15844 str (format-time-string
15845 (concat
15846 (if inactive "[" "<") (substring tf 1 -1)
15847 (if inactive "]" ">"))
15848 (apply 'encode-time time))
15849 string (replace-match str t t string)
15850 start (+ start (length str)))))))
15851 string)
15853 (defun org-fix-decoded-time (time)
15854 "Set 0 instead of nil for the first 6 elements of time.
15855 Don't touch the rest."
15856 (let ((n 0))
15857 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15859 (defun org-days-to-time (timestamp-string)
15860 "Difference between TIMESTAMP-STRING and now in days."
15861 (- (time-to-days (org-time-string-to-time timestamp-string))
15862 (time-to-days (current-time))))
15864 (defun org-deadline-close (timestamp-string &optional ndays)
15865 "Is the time in TIMESTAMP-STRING close to the current date?"
15866 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15867 (and (< (org-days-to-time timestamp-string) ndays)
15868 (not (org-entry-is-done-p))))
15870 (defun org-get-wdays (ts)
15871 "Get the deadline lead time appropriate for timestring TS."
15872 (cond
15873 ((<= org-deadline-warning-days 0)
15874 ;; 0 or negative, enforce this value no matter what
15875 (- org-deadline-warning-days))
15876 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15877 ;; lead time is specified.
15878 (floor (* (string-to-number (match-string 1 ts))
15879 (cdr (assoc (match-string 2 ts)
15880 '(("d" . 1) ("w" . 7)
15881 ("m" . 30.4) ("y" . 365.25)))))))
15882 ;; go for the default.
15883 (t org-deadline-warning-days)))
15885 (defun org-calendar-select-mouse (ev)
15886 "Return to `org-read-date' with the date currently selected.
15887 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15888 (interactive "e")
15889 (mouse-set-point ev)
15890 (when (calendar-cursor-to-date)
15891 (let* ((date (calendar-cursor-to-date))
15892 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15893 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15894 (if (active-minibuffer-window) (exit-minibuffer))))
15896 (defun org-check-deadlines (ndays)
15897 "Check if there are any deadlines due or past due.
15898 A deadline is considered due if it happens within `org-deadline-warning-days'
15899 days from today's date. If the deadline appears in an entry marked DONE,
15900 it is not shown. The prefix arg NDAYS can be used to test that many
15901 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15902 (interactive "P")
15903 (let* ((org-warn-days
15904 (cond
15905 ((equal ndays '(4)) 100000)
15906 (ndays (prefix-numeric-value ndays))
15907 (t (abs org-deadline-warning-days))))
15908 (case-fold-search nil)
15909 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15910 (callback
15911 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15913 (message "%d deadlines past-due or due within %d days"
15914 (org-occur regexp nil callback)
15915 org-warn-days)))
15917 (defsubst org-re-timestamp (type)
15918 "Return a regexp for timestamp TYPE.
15919 Allowed values for TYPE are:
15921 all: all timestamps
15922 active: only active timestamps (<...>)
15923 inactive: only inactive timestamps ([...])
15924 scheduled: only scheduled timestamps
15925 deadline: only deadline timestamps
15927 When TYPE is nil, fall back on returning a regexp that matches
15928 both scheduled and deadline timestamps."
15929 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
15930 ((eq type 'active) org-ts-regexp)
15931 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
15932 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
15933 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15934 ((eq type 'scheduled-or-deadline)
15935 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
15937 (defun org-check-before-date (date)
15938 "Check if there are deadlines or scheduled entries before DATE."
15939 (interactive (list (org-read-date)))
15940 (let ((case-fold-search nil)
15941 (regexp (org-re-timestamp org-ts-type))
15942 (callback
15943 (lambda () (time-less-p
15944 (org-time-string-to-time (match-string 1))
15945 (org-time-string-to-time date)))))
15946 (message "%d entries before %s"
15947 (org-occur regexp nil callback) date)))
15949 (defun org-check-after-date (date)
15950 "Check if there are deadlines or scheduled entries after DATE."
15951 (interactive (list (org-read-date)))
15952 (let ((case-fold-search nil)
15953 (regexp (org-re-timestamp org-ts-type))
15954 (callback
15955 (lambda () (not
15956 (time-less-p
15957 (org-time-string-to-time (match-string 1))
15958 (org-time-string-to-time date))))))
15959 (message "%d entries after %s"
15960 (org-occur regexp nil callback) date)))
15962 (defun org-check-dates-range (start-date end-date)
15963 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
15964 (interactive (list (org-read-date nil nil nil "Range starts")
15965 (org-read-date nil nil nil "Range end")))
15966 (let ((case-fold-search nil)
15967 (regexp (org-re-timestamp org-ts-type))
15968 (callback
15969 (lambda ()
15970 (let ((match (match-string 1)))
15971 (and
15972 (not (time-less-p
15973 (org-time-string-to-time match)
15974 (org-time-string-to-time start-date)))
15975 (time-less-p
15976 (org-time-string-to-time match)
15977 (org-time-string-to-time end-date)))))))
15978 (message "%d entries between %s and %s"
15979 (org-occur regexp nil callback) start-date end-date)))
15981 (defun org-evaluate-time-range (&optional to-buffer)
15982 "Evaluate a time range by computing the difference between start and end.
15983 Normally the result is just printed in the echo area, but with prefix arg
15984 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15985 If the time range is actually in a table, the result is inserted into the
15986 next column.
15987 For time difference computation, a year is assumed to be exactly 365
15988 days in order to avoid rounding problems."
15989 (interactive "P")
15991 (org-clock-update-time-maybe)
15992 (save-excursion
15993 (unless (org-at-date-range-p t)
15994 (goto-char (point-at-bol))
15995 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15996 (if (not (org-at-date-range-p t))
15997 (error "Not at a time-stamp range, and none found in current line")))
15998 (let* ((ts1 (match-string 1))
15999 (ts2 (match-string 2))
16000 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16001 (match-end (match-end 0))
16002 (time1 (org-time-string-to-time ts1))
16003 (time2 (org-time-string-to-time ts2))
16004 (t1 (org-float-time time1))
16005 (t2 (org-float-time time2))
16006 (diff (abs (- t2 t1)))
16007 (negative (< (- t2 t1) 0))
16008 ;; (ys (floor (* 365 24 60 60)))
16009 (ds (* 24 60 60))
16010 (hs (* 60 60))
16011 (fy "%dy %dd %02d:%02d")
16012 (fy1 "%dy %dd")
16013 (fd "%dd %02d:%02d")
16014 (fd1 "%dd")
16015 (fh "%02d:%02d")
16016 y d h m align)
16017 (if havetime
16018 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16020 d (floor (/ diff ds)) diff (mod diff ds)
16021 h (floor (/ diff hs)) diff (mod diff hs)
16022 m (floor (/ diff 60)))
16023 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16025 d (floor (+ (/ diff ds) 0.5))
16026 h 0 m 0))
16027 (if (not to-buffer)
16028 (message "%s" (org-make-tdiff-string y d h m))
16029 (if (org-at-table-p)
16030 (progn
16031 (goto-char match-end)
16032 (setq align t)
16033 (and (looking-at " *|") (goto-char (match-end 0))))
16034 (goto-char match-end))
16035 (if (looking-at
16036 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16037 (replace-match ""))
16038 (if negative (insert " -"))
16039 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16040 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16041 (insert " " (format fh h m))))
16042 (if align (org-table-align))
16043 (message "Time difference inserted")))))
16045 (defun org-make-tdiff-string (y d h m)
16046 (let ((fmt "")
16047 (l nil))
16048 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16049 l (push y l)))
16050 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16051 l (push d l)))
16052 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16053 l (push h l)))
16054 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16055 l (push m l)))
16056 (apply 'format fmt (nreverse l))))
16058 (defun org-time-string-to-time (s &optional buffer pos)
16059 "Convert a timestamp string into internal time."
16060 (condition-case errdata
16061 (apply 'encode-time (org-parse-time-string s))
16062 (error (error "Bad timestamp `%s'%s\nError was: %s"
16063 s (if (not (and buffer pos))
16065 (format " at %d in buffer `%s'" pos buffer))
16066 (cdr errdata)))))
16068 (defun org-time-string-to-seconds (s)
16069 "Convert a timestamp string to a number of seconds."
16070 (org-float-time (org-time-string-to-time s)))
16072 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16073 "Convert a time stamp to an absolute day number.
16074 If there is a specifier for a cyclic time stamp, get the closest date to
16075 DAYNR.
16076 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16077 The variable date is bound by the calendar when this is called."
16078 (cond
16079 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16080 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16081 daynr
16082 (+ daynr 1000)))
16083 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16084 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16085 (time-to-days (current-time))) (match-string 0 s)
16086 prefer show-all))
16087 (t (time-to-days
16088 (condition-case errdata
16089 (apply 'encode-time (org-parse-time-string s))
16090 (error (error "Bad timestamp `%s'%s\nError was: %s"
16091 s (if (not (and buffer pos))
16093 (format " at %d in buffer `%s'" pos buffer))
16094 (cdr errdata))))))))
16096 (defun org-days-to-iso-week (days)
16097 "Return the iso week number."
16098 (require 'cal-iso)
16099 (car (calendar-iso-from-absolute days)))
16101 (defun org-small-year-to-year (year)
16102 "Convert 2-digit years into 4-digit years.
16103 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16104 The year 2000 cannot be abbreviated. Any year larger than 99
16105 is returned unchanged."
16106 (if (< year 38)
16107 (setq year (+ 2000 year))
16108 (if (< year 100)
16109 (setq year (+ 1900 year))))
16110 year)
16112 (defun org-time-from-absolute (d)
16113 "Return the time corresponding to date D.
16114 D may be an absolute day number, or a calendar-type list (month day year)."
16115 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16116 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16118 (defun org-calendar-holiday ()
16119 "List of holidays, for Diary display in Org-mode."
16120 (require 'holidays)
16121 (let ((hl (funcall
16122 (if (fboundp 'calendar-check-holidays)
16123 'calendar-check-holidays 'check-calendar-holidays) date)))
16124 (if hl (mapconcat 'identity hl "; "))))
16126 (defun org-diary-sexp-entry (sexp entry date)
16127 "Process a SEXP diary ENTRY for DATE."
16128 (require 'diary-lib)
16129 (let ((result (if calendar-debug-sexp
16130 (let ((stack-trace-on-error t))
16131 (eval (car (read-from-string sexp))))
16132 (condition-case nil
16133 (eval (car (read-from-string sexp)))
16134 (error
16135 (beep)
16136 (message "Bad sexp at line %d in %s: %s"
16137 (org-current-line)
16138 (buffer-file-name) sexp)
16139 (sleep-for 2))))))
16140 (cond ((stringp result) (split-string result "; "))
16141 ((and (consp result)
16142 (not (consp (cdr result)))
16143 (stringp (cdr result))) (cdr result))
16144 ((and (consp result)
16145 (stringp (car result))) result)
16146 (result entry))))
16148 (defun org-diary-to-ical-string (frombuf)
16149 "Get iCalendar entries from diary entries in buffer FROMBUF.
16150 This uses the icalendar.el library."
16151 (let* ((tmpdir (if (featurep 'xemacs)
16152 (temp-directory)
16153 temporary-file-directory))
16154 (tmpfile (make-temp-name
16155 (expand-file-name "orgics" tmpdir)))
16156 buf rtn b e)
16157 (with-current-buffer frombuf
16158 (icalendar-export-region (point-min) (point-max) tmpfile)
16159 (setq buf (find-buffer-visiting tmpfile))
16160 (set-buffer buf)
16161 (goto-char (point-min))
16162 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16163 (setq b (match-beginning 0)))
16164 (goto-char (point-max))
16165 (if (re-search-backward "^END:VEVENT" nil t)
16166 (setq e (match-end 0)))
16167 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16168 (kill-buffer buf)
16169 (delete-file tmpfile)
16170 rtn))
16172 (defun org-closest-date (start current change prefer show-all)
16173 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16174 When PREFER is `past', return a date that is either CURRENT or past.
16175 When PREFER is `future', return a date that is either CURRENT or future.
16176 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16177 ;; Make the proper lists from the dates
16178 (catch 'exit
16179 (let ((a1 '(("h" . hour)
16180 ("d" . day)
16181 ("w" . week)
16182 ("m" . month)
16183 ("y" . year)))
16184 (shour (nth 2 (org-parse-time-string start)))
16185 dn dw sday cday n1 n2 n0
16186 d m y y1 y2 date1 date2 nmonths nm ny m2)
16188 (setq start (org-date-to-gregorian start)
16189 current (org-date-to-gregorian
16190 (if show-all
16191 current
16192 (time-to-days (current-time))))
16193 sday (calendar-absolute-from-gregorian start)
16194 cday (calendar-absolute-from-gregorian current))
16196 (if (<= cday sday) (throw 'exit sday))
16198 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16199 (setq dn (string-to-number (match-string 1 change))
16200 dw (cdr (assoc (match-string 2 change) a1)))
16201 (error "Invalid change specifier: %s" change))
16202 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16203 (cond
16204 ((eq dw 'hour)
16205 (let ((missing-hours
16206 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16207 dn)))
16208 (setq n1 (if (zerop missing-hours) cday
16209 (- cday (1+ (floor (/ missing-hours 24)))))
16210 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16211 ((eq dw 'day)
16212 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16213 n2 (+ n1 dn)))
16214 ((eq dw 'year)
16215 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16216 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16217 (setq date1 (list m d y1)
16218 n1 (calendar-absolute-from-gregorian date1)
16219 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16220 n2 (calendar-absolute-from-gregorian date2)))
16221 ((eq dw 'month)
16222 ;; approx number of month between the two dates
16223 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16224 ;; How often does dn fit in there?
16225 (setq d (nth 1 start) m (car start) y (nth 2 start)
16226 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16227 m (+ m nm)
16228 ny (floor (/ m 12))
16229 y (+ y ny)
16230 m (- m (* ny 12)))
16231 (while (> m 12) (setq m (- m 12) y (1+ y)))
16232 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16233 (setq m2 (+ m dn) y2 y)
16234 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16235 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16236 (while (<= n2 cday)
16237 (setq n1 n2 m m2 y y2)
16238 (setq m2 (+ m dn) y2 y)
16239 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16240 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16241 ;; Make sure n1 is the earlier date
16242 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16243 (if show-all
16244 (cond
16245 ((eq prefer 'past) (if (= cday n2) n2 n1))
16246 ((eq prefer 'future) (if (= cday n1) n1 n2))
16247 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16248 (cond
16249 ((eq prefer 'past) (if (= cday n2) n2 n1))
16250 ((eq prefer 'future) (if (= cday n1) n1 n2))
16251 (t (if (= cday n1) n1 n2)))))))
16253 (defun org-date-to-gregorian (date)
16254 "Turn any specification of DATE into a Gregorian date for the calendar."
16255 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16256 ((and (listp date) (= (length date) 3)) date)
16257 ((stringp date)
16258 (setq date (org-parse-time-string date))
16259 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16260 ((listp date)
16261 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16263 (defun org-parse-time-string (s &optional nodefault)
16264 "Parse the standard Org-mode time string.
16265 This should be a lot faster than the normal `parse-time-string'.
16266 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16267 hour and minute fields will be nil if not given."
16268 (if (string-match org-ts-regexp0 s)
16269 (list 0
16270 (if (or (match-beginning 8) (not nodefault))
16271 (string-to-number (or (match-string 8 s) "0")))
16272 (if (or (match-beginning 7) (not nodefault))
16273 (string-to-number (or (match-string 7 s) "0")))
16274 (string-to-number (match-string 4 s))
16275 (string-to-number (match-string 3 s))
16276 (string-to-number (match-string 2 s))
16277 nil nil nil)
16278 (error "Not a standard Org-mode time string: %s" s)))
16280 (defun org-timestamp-up (&optional arg)
16281 "Increase the date item at the cursor by one.
16282 If the cursor is on the year, change the year. If it is on the month,
16283 the day or the time, change that.
16284 With prefix ARG, change by that many units."
16285 (interactive "p")
16286 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16288 (defun org-timestamp-down (&optional arg)
16289 "Decrease the date item at the cursor by one.
16290 If the cursor is on the year, change the year. If it is on the month,
16291 the day or the time, change that.
16292 With prefix ARG, change by that many units."
16293 (interactive "p")
16294 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16296 (defun org-timestamp-up-day (&optional arg)
16297 "Increase the date in the time stamp by one day.
16298 With prefix ARG, change that many days."
16299 (interactive "p")
16300 (if (and (not (org-at-timestamp-p t))
16301 (org-at-heading-p))
16302 (org-todo 'up)
16303 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16305 (defun org-timestamp-down-day (&optional arg)
16306 "Decrease the date in the time stamp by one day.
16307 With prefix ARG, change that many days."
16308 (interactive "p")
16309 (if (and (not (org-at-timestamp-p t))
16310 (org-at-heading-p))
16311 (org-todo 'down)
16312 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16314 (defun org-at-timestamp-p (&optional inactive-ok)
16315 "Determine if the cursor is in or at a timestamp."
16316 (interactive)
16317 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16318 (pos (point))
16319 (ans (or (looking-at tsr)
16320 (save-excursion
16321 (skip-chars-backward "^[<\n\r\t")
16322 (if (> (point) (point-min)) (backward-char 1))
16323 (and (looking-at tsr)
16324 (> (- (match-end 0) pos) -1))))))
16325 (and ans
16326 (boundp 'org-ts-what)
16327 (setq org-ts-what
16328 (cond
16329 ((= pos (match-beginning 0)) 'bracket)
16330 ;; Point is considered to be "on the bracket" whether
16331 ;; it's really on it or right after it.
16332 ((= pos (1- (match-end 0))) 'bracket)
16333 ((= pos (match-end 0)) 'after)
16334 ((org-pos-in-match-range pos 2) 'year)
16335 ((org-pos-in-match-range pos 3) 'month)
16336 ((org-pos-in-match-range pos 7) 'hour)
16337 ((org-pos-in-match-range pos 8) 'minute)
16338 ((or (org-pos-in-match-range pos 4)
16339 (org-pos-in-match-range pos 5)) 'day)
16340 ((and (> pos (or (match-end 8) (match-end 5)))
16341 (< pos (match-end 0)))
16342 (- pos (or (match-end 8) (match-end 5))))
16343 (t 'day))))
16344 ans))
16346 (defun org-toggle-timestamp-type ()
16347 "Toggle the type (<active> or [inactive]) of a time stamp."
16348 (interactive)
16349 (when (org-at-timestamp-p t)
16350 (let ((beg (match-beginning 0)) (end (match-end 0))
16351 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16352 (save-excursion
16353 (goto-char beg)
16354 (while (re-search-forward "[][<>]" end t)
16355 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16356 t t)))
16357 (message "Timestamp is now %sactive"
16358 (if (equal (char-after beg) ?<) "" "in")))))
16360 (defvar org-clock-history) ; defined in org-clock.el
16361 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16362 (defun org-timestamp-change (n &optional what updown)
16363 "Change the date in the time stamp at point.
16364 The date will be changed by N times WHAT. WHAT can be `day', `month',
16365 `year', `minute', `second'. If WHAT is not given, the cursor position
16366 in the timestamp determines what will be changed."
16367 (let ((origin (point)) origin-cat
16368 with-hm inactive
16369 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16370 org-ts-what
16371 extra rem
16372 ts time time0 fixnext clrgx)
16373 (if (not (org-at-timestamp-p t))
16374 (error "Not at a timestamp"))
16375 (if (and (not what) (eq org-ts-what 'bracket))
16376 (org-toggle-timestamp-type)
16377 ;; Point isn't on brackets. Remember the part of the time-stamp
16378 ;; the point was in. Indeed, size of time-stamps may change,
16379 ;; but point must be kept in the same category nonetheless.
16380 (setq origin-cat org-ts-what)
16381 (if (and (not what) (not (eq org-ts-what 'day))
16382 org-display-custom-times
16383 (get-text-property (point) 'display)
16384 (not (get-text-property (1- (point)) 'display)))
16385 (setq org-ts-what 'day))
16386 (setq org-ts-what (or what org-ts-what)
16387 inactive (= (char-after (match-beginning 0)) ?\[)
16388 ts (match-string 0))
16389 (replace-match "")
16390 (if (string-match
16391 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16393 (setq extra (match-string 1 ts)))
16394 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16395 (setq with-hm t))
16396 (setq time0 (org-parse-time-string ts))
16397 (when (and updown
16398 (eq org-ts-what 'minute)
16399 (not current-prefix-arg))
16400 ;; This looks like s-up and s-down. Change by one rounding step.
16401 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16402 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16403 (setcar (cdr time0) (+ (nth 1 time0)
16404 (if (> n 0) (- rem) (- dm rem))))))
16405 (setq time
16406 (encode-time (or (car time0) 0)
16407 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16408 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16409 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16410 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16411 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16412 (nthcdr 6 time0)))
16413 (when (and (member org-ts-what '(hour minute))
16414 extra
16415 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16416 (setq extra (org-modify-ts-extra
16417 extra
16418 (if (eq org-ts-what 'hour) 2 5)
16419 n dm)))
16420 (when (integerp org-ts-what)
16421 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16422 (if (eq what 'calendar)
16423 (let ((cal-date (org-get-date-from-calendar)))
16424 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16425 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16426 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16427 (setcar time0 (or (car time0) 0))
16428 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16429 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16430 (setq time (apply 'encode-time time0))))
16431 ;; Insert the new time-stamp, and ensure point stays in the same
16432 ;; category as before (i.e. not after the last position in that
16433 ;; category).
16434 (let ((pos (point)))
16435 ;; Stay before inserted string. `save-excursion' is of no use.
16436 (setq org-last-changed-timestamp
16437 (org-insert-time-stamp time with-hm inactive nil nil extra))
16438 (goto-char pos))
16439 (save-match-data
16440 (looking-at org-ts-regexp3)
16441 (goto-char (cond
16442 ;; `day' category ends before `hour' if any, or at
16443 ;; the end of the day name.
16444 ((eq origin-cat 'day)
16445 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16446 ((eq origin-cat 'hour) (min (match-end 7) origin))
16447 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16448 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16449 ;; `year' and `month' have both fixed size: point
16450 ;; couldn't have moved into another part.
16451 (t origin))))
16452 ;; Update clock if on a CLOCK line.
16453 (org-clock-update-time-maybe)
16454 ;; Maybe adjust the closest clock in `org-clock-history'
16455 (when org-clock-adjust-closest
16456 (if (not (and (org-at-clock-log-p)
16457 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16458 org-clock-history))))))
16459 (message "No clock to adjust")
16460 (cond ((save-excursion ; fix previous clock?
16461 (re-search-backward org-ts-regexp0 nil t)
16462 (org-looking-back (concat org-clock-string " \\[")))
16463 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16464 ((save-excursion ; fix next clock?
16465 (re-search-backward org-ts-regexp0 nil t)
16466 (looking-at (concat org-ts-regexp0 "\\] =>")))
16467 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16468 (save-window-excursion
16469 ;; Find closest clock to point, adjust the previous/next one in history
16470 (let* ((p (save-excursion (org-back-to-heading t)))
16471 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16472 (clfixnth
16473 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16474 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16475 (if (not clfixpos)
16476 (message "No clock to adjust")
16477 (save-excursion
16478 (org-goto-marker-or-bmk clfixpos)
16479 (org-show-subtree)
16480 (when (re-search-forward clrgx nil t)
16481 (goto-char (match-beginning 1))
16482 (let (org-clock-adjust-closest)
16483 (org-timestamp-change n org-ts-what updown))
16484 (message "Clock adjusted in %s for heading: %s"
16485 (file-name-nondirectory (buffer-file-name))
16486 (org-get-heading t t)))))))))
16487 ;; Try to recenter the calendar window, if any.
16488 (if (and org-calendar-follow-timestamp-change
16489 (get-buffer-window "*Calendar*" t)
16490 (memq org-ts-what '(day month year)))
16491 (org-recenter-calendar (time-to-days time))))))
16493 (defun org-modify-ts-extra (s pos n dm)
16494 "Change the different parts of the lead-time and repeat fields in timestamp."
16495 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16496 ng h m new rem)
16497 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16498 (cond
16499 ((or (org-pos-in-match-range pos 2)
16500 (org-pos-in-match-range pos 3))
16501 (setq m (string-to-number (match-string 3 s))
16502 h (string-to-number (match-string 2 s)))
16503 (if (org-pos-in-match-range pos 2)
16504 (setq h (+ h n))
16505 (setq n (* dm (org-no-warnings (signum n))))
16506 (when (not (= 0 (setq rem (% m dm))))
16507 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16508 (setq m (+ m n)))
16509 (if (< m 0) (setq m (+ m 60) h (1- h)))
16510 (if (> m 59) (setq m (- m 60) h (1+ h)))
16511 (setq h (min 24 (max 0 h)))
16512 (setq ng 1 new (format "-%02d:%02d" h m)))
16513 ((org-pos-in-match-range pos 6)
16514 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16515 ((org-pos-in-match-range pos 5)
16516 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16518 ((org-pos-in-match-range pos 9)
16519 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16520 ((org-pos-in-match-range pos 8)
16521 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16523 (when ng
16524 (setq s (concat
16525 (substring s 0 (match-beginning ng))
16527 (substring s (match-end ng))))))
16530 (defun org-recenter-calendar (date)
16531 "If the calendar is visible, recenter it to DATE."
16532 (let ((cwin (get-buffer-window "*Calendar*" t)))
16533 (when cwin
16534 (let ((calendar-move-hook nil))
16535 (with-selected-window cwin
16536 (calendar-goto-date (if (listp date) date
16537 (calendar-gregorian-from-absolute date))))))))
16539 (defun org-goto-calendar (&optional arg)
16540 "Go to the Emacs calendar at the current date.
16541 If there is a time stamp in the current line, go to that date.
16542 A prefix ARG can be used to force the current date."
16543 (interactive "P")
16544 (let ((tsr org-ts-regexp) diff
16545 (calendar-move-hook nil)
16546 (calendar-view-holidays-initially-flag nil)
16547 (calendar-view-diary-initially-flag nil))
16548 (if (or (org-at-timestamp-p)
16549 (save-excursion
16550 (beginning-of-line 1)
16551 (looking-at (concat ".*" tsr))))
16552 (let ((d1 (time-to-days (current-time)))
16553 (d2 (time-to-days
16554 (org-time-string-to-time (match-string 1)))))
16555 (setq diff (- d2 d1))))
16556 (calendar)
16557 (calendar-goto-today)
16558 (if (and diff (not arg)) (calendar-forward-day diff))))
16560 (defun org-get-date-from-calendar ()
16561 "Return a list (month day year) of date at point in calendar."
16562 (with-current-buffer "*Calendar*"
16563 (save-match-data
16564 (calendar-cursor-to-date))))
16566 (defun org-date-from-calendar ()
16567 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16568 If there is already a time stamp at the cursor position, update it."
16569 (interactive)
16570 (if (org-at-timestamp-p t)
16571 (org-timestamp-change 0 'calendar)
16572 (let ((cal-date (org-get-date-from-calendar)))
16573 (org-insert-time-stamp
16574 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16576 (defun org-minutes-to-hh:mm-string (m)
16577 "Compute H:MM from a number of minutes."
16578 (let ((h (/ m 60)))
16579 (setq m (- m (* 60 h)))
16580 (format org-time-clocksum-format h m)))
16582 (defun org-hh:mm-string-to-minutes (s)
16583 "Convert a string H:MM to a number of minutes.
16584 If the string is just a number, interpret it as minutes.
16585 In fact, the first hh:mm or number in the string will be taken,
16586 there can be extra stuff in the string.
16587 If no number is found, the return value is 0."
16588 (cond
16589 ((integerp s) s)
16590 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16591 (+ (* (string-to-number (match-string 1 s)) 60)
16592 (string-to-number (match-string 2 s))))
16593 ((string-match "\\([0-9]+\\)" s)
16594 (string-to-number (match-string 1 s)))
16595 (t 0)))
16597 (defcustom org-effort-durations
16598 `(("h" . 60)
16599 ("d" . ,(* 60 8))
16600 ("w" . ,(* 60 8 5))
16601 ("m" . ,(* 60 8 5 4))
16602 ("y" . ,(* 60 8 5 40)))
16603 "Conversion factor to minutes for an effort modifier.
16605 Each entry has the form (MODIFIER . MINUTES).
16607 In an effort string, a number followed by MODIFIER is multiplied
16608 by the specified number of MINUTES to obtain an effort in
16609 minutes.
16611 For example, if the value of this variable is ((\"hours\" . 60)), then an
16612 effort string \"2hours\" is equivalent to 120 minutes."
16613 :group 'org-agenda
16614 :version "24.1"
16615 :type '(alist :key-type (string :tag "Modifier")
16616 :value-type (number :tag "Minutes")))
16618 (defun org-duration-string-to-minutes (s &optional output-to-string)
16619 "Convert a duration string S to minutes.
16621 A bare number is interpreted as minutes, modifiers can be set by
16622 customizing `org-effort-durations' (which see).
16624 Entries containing a colon are interpreted as H:MM by
16625 `org-hh:mm-string-to-minutes'."
16626 (let ((result 0)
16627 (re (concat "\\([0-9.]+\\) *\\("
16628 (regexp-opt (mapcar 'car org-effort-durations))
16629 "\\)")))
16630 (while (string-match re s)
16631 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16632 (string-to-number (match-string 1 s))))
16633 (setq s (replace-match "" nil t s)))
16634 (setq result (floor result))
16635 (incf result (org-hh:mm-string-to-minutes s))
16636 (if output-to-string (number-to-string result) result)))
16638 ;;;; Files
16640 (defun org-save-all-org-buffers ()
16641 "Save all Org-mode buffers without user confirmation."
16642 (interactive)
16643 (message "Saving all Org-mode buffers...")
16644 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16645 (when (featurep 'org-id) (org-id-locations-save))
16646 (message "Saving all Org-mode buffers... done"))
16648 (defun org-revert-all-org-buffers ()
16649 "Revert all Org-mode buffers.
16650 Prompt for confirmation when there are unsaved changes.
16651 Be sure you know what you are doing before letting this function
16652 overwrite your changes.
16654 This function is useful in a setup where one tracks org files
16655 with a version control system, to revert on one machine after pulling
16656 changes from another. I believe the procedure must be like this:
16658 1. M-x org-save-all-org-buffers
16659 2. Pull changes from the other machine, resolve conflicts
16660 3. M-x org-revert-all-org-buffers"
16661 (interactive)
16662 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16663 (error "Abort"))
16664 (save-excursion
16665 (save-window-excursion
16666 (mapc
16667 (lambda (b)
16668 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16669 (with-current-buffer b buffer-file-name))
16670 (org-pop-to-buffer-same-window b)
16671 (revert-buffer t 'no-confirm)))
16672 (buffer-list))
16673 (when (and (featurep 'org-id) org-id-track-globally)
16674 (org-id-locations-load)))))
16676 ;;;; Agenda files
16678 ;;;###autoload
16679 (defun org-switchb (&optional arg)
16680 "Switch between Org buffers.
16681 With one prefix argument, restrict available buffers to files.
16682 With two prefix arguments, restrict available buffers to agenda files.
16684 Defaults to `iswitchb' for buffer name completion.
16685 Set `org-completion-use-ido' to make it use ido instead."
16686 (interactive "P")
16687 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16688 ((equal arg '(16)) (org-buffer-list 'agenda))
16689 (t (org-buffer-list))))
16690 (org-completion-use-iswitchb org-completion-use-iswitchb)
16691 (org-completion-use-ido org-completion-use-ido))
16692 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16693 (setq org-completion-use-iswitchb t))
16694 (org-pop-to-buffer-same-window
16695 (org-icompleting-read "Org buffer: "
16696 (mapcar 'list (mapcar 'buffer-name blist))
16697 nil t))))
16699 ;;; Define some older names previously used for this functionality
16700 ;;;###autoload
16701 (defalias 'org-ido-switchb 'org-switchb)
16702 ;;;###autoload
16703 (defalias 'org-iswitchb 'org-switchb)
16705 (defun org-buffer-list (&optional predicate exclude-tmp)
16706 "Return a list of Org buffers.
16707 PREDICATE can be `export', `files' or `agenda'.
16709 export restrict the list to Export buffers.
16710 files restrict the list to buffers visiting Org files.
16711 agenda restrict the list to buffers visiting agenda files.
16713 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16714 (let* ((bfn nil)
16715 (agenda-files (and (eq predicate 'agenda)
16716 (mapcar 'file-truename (org-agenda-files t))))
16717 (filter
16718 (cond
16719 ((eq predicate 'files)
16720 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16721 ((eq predicate 'export)
16722 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16723 ((eq predicate 'agenda)
16724 (lambda (b)
16725 (with-current-buffer b
16726 (and (derived-mode-p 'org-mode)
16727 (setq bfn (buffer-file-name b))
16728 (member (file-truename bfn) agenda-files)))))
16729 (t (lambda (b) (with-current-buffer b
16730 (or (derived-mode-p 'org-mode)
16731 (string-match "\*Org .*Export"
16732 (buffer-name b)))))))))
16733 (delq nil
16734 (mapcar
16735 (lambda(b)
16736 (if (and (funcall filter b)
16737 (or (not exclude-tmp)
16738 (not (string-match "tmp" (buffer-name b)))))
16740 nil))
16741 (buffer-list)))))
16743 (defun org-agenda-files (&optional unrestricted archives)
16744 "Get the list of agenda files.
16745 Optional UNRESTRICTED means return the full list even if a restriction
16746 is currently in place.
16747 When ARCHIVES is t, include all archive files that are really being
16748 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16749 `org-agenda-archives-mode' is t."
16750 (let ((files
16751 (cond
16752 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16753 ((stringp org-agenda-files) (org-read-agenda-file-list))
16754 ((listp org-agenda-files) org-agenda-files)
16755 (t (error "Invalid value of `org-agenda-files'")))))
16756 (setq files (apply 'append
16757 (mapcar (lambda (f)
16758 (if (file-directory-p f)
16759 (directory-files
16760 f t org-agenda-file-regexp)
16761 (list f)))
16762 files)))
16763 (when org-agenda-skip-unavailable-files
16764 (setq files (delq nil
16765 (mapcar (function
16766 (lambda (file)
16767 (and (file-readable-p file) file)))
16768 files))))
16769 (when (or (eq archives t)
16770 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16771 (setq files (org-add-archive-files files)))
16772 files))
16774 (defun org-agenda-file-p (&optional file)
16775 "Return non-nil, if FILE is an agenda file.
16776 If FILE is omitted, use the file associated with the current
16777 buffer."
16778 (member (or file (buffer-file-name))
16779 (org-agenda-files t)))
16781 (defun org-edit-agenda-file-list ()
16782 "Edit the list of agenda files.
16783 Depending on setup, this either uses customize to edit the variable
16784 `org-agenda-files', or it visits the file that is holding the list. In the
16785 latter case, the buffer is set up in a way that saving it automatically kills
16786 the buffer and restores the previous window configuration."
16787 (interactive)
16788 (if (stringp org-agenda-files)
16789 (let ((cw (current-window-configuration)))
16790 (find-file org-agenda-files)
16791 (org-set-local 'org-window-configuration cw)
16792 (org-add-hook 'after-save-hook
16793 (lambda ()
16794 (set-window-configuration
16795 (prog1 org-window-configuration
16796 (kill-buffer (current-buffer))))
16797 (org-install-agenda-files-menu)
16798 (message "New agenda file list installed"))
16799 nil 'local)
16800 (message "%s" (substitute-command-keys
16801 "Edit list and finish with \\[save-buffer]")))
16802 (customize-variable 'org-agenda-files)))
16804 (defun org-store-new-agenda-file-list (list)
16805 "Set new value for the agenda file list and save it correctly."
16806 (if (stringp org-agenda-files)
16807 (let ((fe (org-read-agenda-file-list t)) b u)
16808 (while (setq b (find-buffer-visiting org-agenda-files))
16809 (kill-buffer b))
16810 (with-temp-file org-agenda-files
16811 (insert
16812 (mapconcat
16813 (lambda (f) ;; Keep un-expanded entries.
16814 (if (setq u (assoc f fe))
16815 (cdr u)
16817 list "\n")
16818 "\n")))
16819 (let ((org-mode-hook nil) (org-inhibit-startup t)
16820 (org-insert-mode-line-in-empty-file nil))
16821 (setq org-agenda-files list)
16822 (customize-save-variable 'org-agenda-files org-agenda-files))))
16824 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16825 "Read the list of agenda files from a file.
16826 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16827 filenames, used by `org-store-new-agenda-file-list' to write back
16828 un-expanded file names."
16829 (when (file-directory-p org-agenda-files)
16830 (error "`org-agenda-files' cannot be a single directory"))
16831 (when (stringp org-agenda-files)
16832 (with-temp-buffer
16833 (insert-file-contents org-agenda-files)
16834 (mapcar
16835 (lambda (f)
16836 (let ((e (expand-file-name (substitute-in-file-name f)
16837 org-directory)))
16838 (if pair-with-expansion
16839 (cons e f)
16840 e)))
16841 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16843 ;;;###autoload
16844 (defun org-cycle-agenda-files ()
16845 "Cycle through the files in `org-agenda-files'.
16846 If the current buffer visits an agenda file, find the next one in the list.
16847 If the current buffer does not, find the first agenda file."
16848 (interactive)
16849 (let* ((fs (org-agenda-files t))
16850 (files (append fs (list (car fs))))
16851 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16852 file)
16853 (unless files (error "No agenda files"))
16854 (catch 'exit
16855 (while (setq file (pop files))
16856 (if (equal (file-truename file) tcf)
16857 (when (car files)
16858 (find-file (car files))
16859 (throw 'exit t))))
16860 (find-file (car fs)))
16861 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16863 (defun org-agenda-file-to-front (&optional to-end)
16864 "Move/add the current file to the top of the agenda file list.
16865 If the file is not present in the list, it is added to the front. If it is
16866 present, it is moved there. With optional argument TO-END, add/move to the
16867 end of the list."
16868 (interactive "P")
16869 (let ((org-agenda-skip-unavailable-files nil)
16870 (file-alist (mapcar (lambda (x)
16871 (cons (file-truename x) x))
16872 (org-agenda-files t)))
16873 (ctf (file-truename
16874 (or buffer-file-name
16875 (error "Please save the current buffer to a file"))))
16876 x had)
16877 (setq x (assoc ctf file-alist) had x)
16879 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16880 (if to-end
16881 (setq file-alist (append (delq x file-alist) (list x)))
16882 (setq file-alist (cons x (delq x file-alist))))
16883 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16884 (org-install-agenda-files-menu)
16885 (message "File %s to %s of agenda file list"
16886 (if had "moved" "added") (if to-end "end" "front"))))
16888 (defun org-remove-file (&optional file)
16889 "Remove current file from the list of files in variable `org-agenda-files'.
16890 These are the files which are being checked for agenda entries.
16891 Optional argument FILE means use this file instead of the current."
16892 (interactive)
16893 (let* ((org-agenda-skip-unavailable-files nil)
16894 (file (or file buffer-file-name
16895 (error "Current buffer does not visit a file")))
16896 (true-file (file-truename file))
16897 (afile (abbreviate-file-name file))
16898 (files (delq nil (mapcar
16899 (lambda (x)
16900 (if (equal true-file
16901 (file-truename x))
16902 nil x))
16903 (org-agenda-files t)))))
16904 (if (not (= (length files) (length (org-agenda-files t))))
16905 (progn
16906 (org-store-new-agenda-file-list files)
16907 (org-install-agenda-files-menu)
16908 (message "Removed file: %s" afile))
16909 (message "File was not in list: %s (not removed)" afile))))
16911 (defun org-file-menu-entry (file)
16912 (vector file (list 'find-file file) t))
16914 (defun org-check-agenda-file (file)
16915 "Make sure FILE exists. If not, ask user what to do."
16916 (when (not (file-exists-p file))
16917 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
16918 (abbreviate-file-name file))
16919 (let ((r (downcase (read-char-exclusive))))
16920 (cond
16921 ((equal r ?r)
16922 (org-remove-file file)
16923 (throw 'nextfile t))
16924 (t (error "Abort"))))))
16926 (defun org-get-agenda-file-buffer (file)
16927 "Get a buffer visiting FILE. If the buffer needs to be created, add
16928 it to the list of buffers which might be released later."
16929 (let ((buf (org-find-base-buffer-visiting file)))
16930 (if buf
16931 buf ; just return it
16932 ;; Make a new buffer and remember it
16933 (setq buf (find-file-noselect file))
16934 (if buf (push buf org-agenda-new-buffers))
16935 buf)))
16937 (defun org-release-buffers (blist)
16938 "Release all buffers in list, asking the user for confirmation when needed.
16939 When a buffer is unmodified, it is just killed. When modified, it is saved
16940 \(if the user agrees) and then killed."
16941 (let (buf file)
16942 (while (setq buf (pop blist))
16943 (setq file (buffer-file-name buf))
16944 (when (and (buffer-modified-p buf)
16945 file
16946 (y-or-n-p (format "Save file %s? " file)))
16947 (with-current-buffer buf (save-buffer)))
16948 (kill-buffer buf))))
16950 (defun org-agenda-prepare-buffers (files)
16951 "Create buffers for all agenda files, protect archived trees and comments."
16952 (interactive)
16953 (let ((pa '(:org-archived t))
16954 (pc '(:org-comment t))
16955 (pall '(:org-archived t :org-comment t))
16956 (inhibit-read-only t)
16957 (rea (concat ":" org-archive-tag ":"))
16958 bmp file re)
16959 (save-excursion
16960 (save-restriction
16961 (while (setq file (pop files))
16962 (catch 'nextfile
16963 (if (bufferp file)
16964 (set-buffer file)
16965 (org-check-agenda-file file)
16966 (set-buffer (org-get-agenda-file-buffer file)))
16967 (widen)
16968 (setq bmp (buffer-modified-p))
16969 (org-refresh-category-properties)
16970 (setq org-todo-keywords-for-agenda
16971 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16972 (setq org-done-keywords-for-agenda
16973 (append org-done-keywords-for-agenda org-done-keywords))
16974 (setq org-todo-keyword-alist-for-agenda
16975 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16976 (setq org-drawers-for-agenda
16977 (append org-drawers-for-agenda org-drawers))
16978 (setq org-tag-alist-for-agenda
16979 (append org-tag-alist-for-agenda org-tag-alist))
16981 (save-excursion
16982 (remove-text-properties (point-min) (point-max) pall)
16983 (when org-agenda-skip-archived-trees
16984 (goto-char (point-min))
16985 (while (re-search-forward rea nil t)
16986 (if (org-at-heading-p t)
16987 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16988 (goto-char (point-min))
16989 (setq re (format org-heading-keyword-regexp-format
16990 org-comment-string))
16991 (while (re-search-forward re nil t)
16992 (add-text-properties
16993 (match-beginning 0) (org-end-of-subtree t) pc)))
16994 (set-buffer-modified-p bmp)))))
16995 (setq org-todo-keywords-for-agenda
16996 (org-uniquify org-todo-keywords-for-agenda))
16997 (setq org-todo-keyword-alist-for-agenda
16998 (org-uniquify org-todo-keyword-alist-for-agenda)
16999 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17001 ;;;; Embedded LaTeX
17003 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17004 "Keymap for the minor `org-cdlatex-mode'.")
17006 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17007 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17008 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17009 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17010 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17012 (defvar org-cdlatex-texmathp-advice-is-done nil
17013 "Flag remembering if we have applied the advice to texmathp already.")
17015 (define-minor-mode org-cdlatex-mode
17016 "Toggle the minor `org-cdlatex-mode'.
17017 This mode supports entering LaTeX environment and math in LaTeX fragments
17018 in Org-mode.
17019 \\{org-cdlatex-mode-map}"
17020 nil " OCDL" nil
17021 (when org-cdlatex-mode
17022 (require 'cdlatex)
17023 (run-hooks 'cdlatex-mode-hook)
17024 (cdlatex-compute-tables))
17025 (unless org-cdlatex-texmathp-advice-is-done
17026 (setq org-cdlatex-texmathp-advice-is-done t)
17027 (defadvice texmathp (around org-math-always-on activate)
17028 "Always return t in org-mode buffers.
17029 This is because we want to insert math symbols without dollars even outside
17030 the LaTeX math segments. If Orgmode thinks that point is actually inside
17031 an embedded LaTeX fragment, let texmathp do its job.
17032 \\[org-cdlatex-mode-map]"
17033 (interactive)
17034 (let (p)
17035 (cond
17036 ((not (derived-mode-p 'org-mode)) ad-do-it)
17037 ((eq this-command 'cdlatex-math-symbol)
17038 (setq ad-return-value t
17039 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17041 (let ((p (org-inside-LaTeX-fragment-p)))
17042 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17043 (setq ad-return-value t
17044 texmathp-why '("Org-mode embedded math" . 0))
17045 (if p ad-do-it)))))))))
17047 (defun turn-on-org-cdlatex ()
17048 "Unconditionally turn on `org-cdlatex-mode'."
17049 (org-cdlatex-mode 1))
17051 (defun org-inside-LaTeX-fragment-p ()
17052 "Test if point is inside a LaTeX fragment.
17053 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17054 sequence appearing also before point.
17055 Even though the matchers for math are configurable, this function assumes
17056 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17057 delimiters are skipped when they have been removed by customization.
17058 The return value is nil, or a cons cell with the delimiter and the
17059 position of this delimiter.
17061 This function does a reasonably good job, but can locally be fooled by
17062 for example currency specifications. For example it will assume being in
17063 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17064 fragments that are properly closed, but during editing, we have to live
17065 with the uncertainty caused by missing closing delimiters. This function
17066 looks only before point, not after."
17067 (catch 'exit
17068 (let ((pos (point))
17069 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17070 (lim (progn
17071 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17072 (point)))
17073 dd-on str (start 0) m re)
17074 (goto-char pos)
17075 (when dodollar
17076 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17077 re (nth 1 (assoc "$" org-latex-regexps)))
17078 (while (string-match re str start)
17079 (cond
17080 ((= (match-end 0) (length str))
17081 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17082 ((= (match-end 0) (- (length str) 5))
17083 (throw 'exit nil))
17084 (t (setq start (match-end 0))))))
17085 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17086 (goto-char pos)
17087 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17088 (and (match-beginning 2) (throw 'exit nil))
17089 ;; count $$
17090 (while (re-search-backward "\\$\\$" lim t)
17091 (setq dd-on (not dd-on)))
17092 (goto-char pos)
17093 (if dd-on (cons "$$" m))))))
17095 (defun org-inside-latex-macro-p ()
17096 "Is point inside a LaTeX macro or its arguments?"
17097 (save-match-data
17098 (org-in-regexp
17099 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17101 (defun org-try-cdlatex-tab ()
17102 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17103 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17104 - inside a LaTeX fragment, or
17105 - after the first word in a line, where an abbreviation expansion could
17106 insert a LaTeX environment."
17107 (when org-cdlatex-mode
17108 (cond
17109 ;; Before any word on the line: No expansion possible.
17110 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17111 ;; Just after first word on the line: Expand it. Make sure it
17112 ;; cannot happen on headlines, though.
17113 ((save-excursion
17114 (skip-chars-backward "a-zA-Z0-9*")
17115 (skip-chars-backward " \t")
17116 (and (bolp) (not (org-at-heading-p))))
17117 (cdlatex-tab) t)
17118 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17120 (defun org-cdlatex-underscore-caret (&optional arg)
17121 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17122 Revert to the normal definition outside of these fragments."
17123 (interactive "P")
17124 (if (org-inside-LaTeX-fragment-p)
17125 (call-interactively 'cdlatex-sub-superscript)
17126 (let (org-cdlatex-mode)
17127 (call-interactively (key-binding (vector last-input-event))))))
17129 (defun org-cdlatex-math-modify (&optional arg)
17130 "Execute `cdlatex-math-modify' in LaTeX fragments.
17131 Revert to the normal definition outside of these fragments."
17132 (interactive "P")
17133 (if (org-inside-LaTeX-fragment-p)
17134 (call-interactively 'cdlatex-math-modify)
17135 (let (org-cdlatex-mode)
17136 (call-interactively (key-binding (vector last-input-event))))))
17138 (defvar org-latex-fragment-image-overlays nil
17139 "List of overlays carrying the images of latex fragments.")
17140 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17142 (defun org-remove-latex-fragment-image-overlays ()
17143 "Remove all overlays with LaTeX fragment images in current buffer."
17144 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17145 (setq org-latex-fragment-image-overlays nil))
17147 (defun org-preview-latex-fragment (&optional subtree)
17148 "Preview the LaTeX fragment at point, or all locally or globally.
17149 If the cursor is in a LaTeX fragment, create the image and overlay
17150 it over the source code. If there is no fragment at point, display
17151 all fragments in the current text, from one headline to the next. With
17152 prefix SUBTREE, display all fragments in the current subtree. With a
17153 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17154 the cursor is before the first headline,
17155 display all fragments in the buffer.
17156 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17157 (interactive "P")
17158 (unless buffer-file-name
17159 (error "Can't preview LaTeX fragment in a non-file buffer"))
17160 (org-remove-latex-fragment-image-overlays)
17161 (save-excursion
17162 (save-restriction
17163 (let (beg end at msg)
17164 (cond
17165 ((or (equal subtree '(16))
17166 (not (save-excursion
17167 (re-search-backward org-outline-regexp-bol nil t))))
17168 (setq beg (point-min) end (point-max)
17169 msg "Creating images for buffer...%s"))
17170 ((equal subtree '(4))
17171 (org-back-to-heading)
17172 (setq beg (point) end (org-end-of-subtree t)
17173 msg "Creating images for subtree...%s"))
17175 (if (setq at (org-inside-LaTeX-fragment-p))
17176 (goto-char (max (point-min) (- (cdr at) 2)))
17177 (org-back-to-heading))
17178 (setq beg (point) end (progn (outline-next-heading) (point))
17179 msg (if at "Creating image...%s"
17180 "Creating images for entry...%s"))))
17181 (message msg "")
17182 (narrow-to-region beg end)
17183 (goto-char beg)
17184 (org-format-latex
17185 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17186 (file-name-nondirectory
17187 buffer-file-name)))
17188 default-directory 'overlays msg at 'forbuffer
17189 org-latex-create-formula-image-program)
17190 (message msg "done. Use `C-c C-c' to remove images.")))))
17192 (defvar org-latex-regexps
17193 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17194 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17195 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17196 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17197 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17198 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17199 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17200 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17201 "Regular expressions for matching embedded LaTeX.")
17203 (defvar org-export-have-math nil) ;; dynamic scoping
17204 (defun org-format-latex (prefix &optional dir overlays msg at
17205 forbuffer processing-type)
17206 "Replace LaTeX fragments with links to an image, and produce images.
17207 Some of the options can be changed using the variable
17208 `org-format-latex-options'."
17209 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17210 (let* ((prefixnodir (file-name-nondirectory prefix))
17211 (absprefix (expand-file-name prefix dir))
17212 (todir (file-name-directory absprefix))
17213 (opt org-format-latex-options)
17214 (matchers (plist-get opt :matchers))
17215 (re-list org-latex-regexps)
17216 (org-format-latex-header-extra
17217 (plist-get (org-infile-export-plist) :latex-header-extra))
17218 (cnt 0) txt hash link beg end re e checkdir
17219 executables-checked string
17220 m n block-type block linkfile movefile ov)
17221 ;; Check the different regular expressions
17222 (while (setq e (pop re-list))
17223 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17224 block (if block-type "\n\n" ""))
17225 (when (member m matchers)
17226 (goto-char (point-min))
17227 (while (re-search-forward re nil t)
17228 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17229 (not (get-text-property (match-beginning n)
17230 'org-protected))
17231 (or (not overlays)
17232 (not (eq (get-char-property (match-beginning n)
17233 'org-overlay-type)
17234 'org-latex-overlay))))
17235 (setq org-export-have-math t)
17236 (cond
17237 ((eq processing-type 'verbatim)
17238 ;; Leave the text verbatim, just protect it
17239 (add-text-properties (match-beginning n) (match-end n)
17240 '(org-protected t)))
17241 ((eq processing-type 'mathjax)
17242 ;; Prepare for MathJax processing
17243 (setq string (match-string n))
17244 (if (member m '("$" "$1"))
17245 (save-excursion
17246 (delete-region (match-beginning n) (match-end n))
17247 (goto-char (match-beginning n))
17248 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17249 "\\)")
17250 '(org-protected t))))
17251 (add-text-properties (match-beginning n) (match-end n)
17252 '(org-protected t))))
17253 ((or (eq processing-type 'dvipng)
17254 (eq processing-type 'imagemagick))
17255 ;; Process to an image
17256 (setq txt (match-string n)
17257 beg (match-beginning n) end (match-end n)
17258 cnt (1+ cnt))
17259 (let (print-length print-level) ; make sure full list is printed
17260 (setq hash (sha1 (prin1-to-string
17261 (list org-format-latex-header
17262 org-format-latex-header-extra
17263 org-export-latex-default-packages-alist
17264 org-export-latex-packages-alist
17265 org-format-latex-options
17266 forbuffer txt)))
17267 linkfile (format "%s_%s.png" prefix hash)
17268 movefile (format "%s_%s.png" absprefix hash)))
17269 (setq link (concat block "[[file:" linkfile "]]" block))
17270 (if msg (message msg cnt))
17271 (goto-char beg)
17272 (unless checkdir ; make sure the directory exists
17273 (setq checkdir t)
17274 (or (file-directory-p todir) (make-directory todir t)))
17275 (cond
17276 ((eq processing-type 'dvipng)
17277 (unless executables-checked
17278 (org-check-external-command
17279 "latex" "needed to convert LaTeX fragments to images")
17280 (org-check-external-command
17281 "dvipng" "needed to convert LaTeX fragments to images")
17282 (setq executables-checked t))
17283 (unless (file-exists-p movefile)
17284 (org-create-formula-image-with-dvipng
17285 txt movefile opt forbuffer)))
17286 ((eq processing-type 'imagemagick)
17287 (unless executables-checked
17288 (org-check-external-command
17289 "convert" "you need to install imagemagick")
17290 (setq executables-checked t))
17291 (unless (file-exists-p movefile)
17292 (org-create-formula-image-with-imagemagick
17293 txt movefile opt forbuffer))))
17294 (if overlays
17295 (progn
17296 (mapc (lambda (o)
17297 (if (eq (overlay-get o 'org-overlay-type)
17298 'org-latex-overlay)
17299 (delete-overlay o)))
17300 (overlays-in beg end))
17301 (setq ov (make-overlay beg end))
17302 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17303 (if (featurep 'xemacs)
17304 (progn
17305 (overlay-put ov 'invisible t)
17306 (overlay-put
17307 ov 'end-glyph
17308 (make-glyph (vector 'png :file movefile))))
17309 (overlay-put
17310 ov 'display
17311 (list 'image :type 'png :file movefile :ascent 'center)))
17312 (push ov org-latex-fragment-image-overlays)
17313 (goto-char end))
17314 (delete-region beg end)
17315 (insert (org-add-props link
17316 (list 'org-latex-src
17317 (replace-regexp-in-string
17318 "\"" "" txt)
17319 'org-latex-src-embed-type
17320 (if block-type 'paragraph 'character))))))
17321 ((eq processing-type 'mathml)
17322 ;; Process to MathML
17323 (unless executables-checked
17324 (unless (save-match-data (org-format-latex-mathml-available-p))
17325 (error "LaTeX to MathML converter not configured"))
17326 (setq executables-checked t))
17327 (setq txt (match-string n)
17328 beg (match-beginning n) end (match-end n)
17329 cnt (1+ cnt))
17330 (if msg (message msg cnt))
17331 (goto-char beg)
17332 (delete-region beg end)
17333 (insert (org-format-latex-as-mathml
17334 txt block-type prefix dir)))
17336 (error "Unknown conversion type %s for latex fragments"
17337 processing-type)))))))))
17339 (defun org-create-math-formula (latex-frag &optional mathml-file)
17340 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17341 Use `org-latex-to-mathml-convert-command'. If the conversion is
17342 sucessful, return the portion between \"<math...> </math>\"
17343 elements otherwise return nil. When MATHML-FILE is specified,
17344 write the results in to that file. When invoked as an
17345 interactive command, prompt for LATEX-FRAG, with initial value
17346 set to the current active region and echo the results for user
17347 inspection."
17348 (interactive (list (let ((frag (when (org-region-active-p)
17349 (buffer-substring-no-properties
17350 (region-beginning) (region-end)))))
17351 (read-string "LaTeX Fragment: " frag nil frag))))
17352 (unless latex-frag (error "Invalid latex-frag"))
17353 (let* ((tmp-in-file (file-relative-name
17354 (make-temp-name (expand-file-name "ltxmathml-in"))))
17355 (ignore (write-region latex-frag nil tmp-in-file))
17356 (tmp-out-file (file-relative-name
17357 (make-temp-name (expand-file-name "ltxmathml-out"))))
17358 (cmd (format-spec
17359 org-latex-to-mathml-convert-command
17360 `((?j . ,(shell-quote-argument
17361 (expand-file-name org-latex-to-mathml-jar-file)))
17362 (?I . ,(shell-quote-argument tmp-in-file))
17363 (?o . ,(shell-quote-argument tmp-out-file)))))
17364 mathml shell-command-output)
17365 (when (org-called-interactively-p 'any)
17366 (unless (org-format-latex-mathml-available-p)
17367 (error "LaTeX to MathML converter not configured")))
17368 (message "Running %s" cmd)
17369 (setq shell-command-output (shell-command-to-string cmd))
17370 (setq mathml
17371 (when (file-readable-p tmp-out-file)
17372 (with-current-buffer (find-file-noselect tmp-out-file t)
17373 (goto-char (point-min))
17374 (when (re-search-forward
17375 (concat
17376 (regexp-quote
17377 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17378 "\\(.\\|\n\\)*"
17379 (regexp-quote "</math>")) nil t)
17380 (prog1 (match-string 0) (kill-buffer))))))
17381 (cond
17382 (mathml
17383 (setq mathml
17384 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17385 (when mathml-file
17386 (write-region mathml nil mathml-file))
17387 (when (org-called-interactively-p 'any)
17388 (message mathml)))
17389 ((message "LaTeX to MathML conversion failed")
17390 (message shell-command-output)))
17391 (delete-file tmp-in-file)
17392 (when (file-exists-p tmp-out-file)
17393 (delete-file tmp-out-file))
17394 mathml))
17396 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17397 prefix &optional dir)
17398 "Use `org-create-math-formula' but check local cache first."
17399 (let* ((absprefix (expand-file-name prefix dir))
17400 (print-length nil) (print-level nil)
17401 (formula-id (concat
17402 "formula-"
17403 (sha1
17404 (prin1-to-string
17405 (list latex-frag
17406 org-latex-to-mathml-convert-command)))))
17407 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17408 (formula-cache-dir (file-name-directory formula-cache)))
17410 (unless (file-directory-p formula-cache-dir)
17411 (make-directory formula-cache-dir t))
17413 (unless (file-exists-p formula-cache)
17414 (org-create-math-formula latex-frag formula-cache))
17416 (if (file-exists-p formula-cache)
17417 ;; Successful conversion. Return the link to MathML file.
17418 (org-add-props
17419 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17420 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17421 'org-latex-src-embed-type (if latex-frag-type
17422 'paragraph 'character)))
17423 ;; Failed conversion. Return the LaTeX fragment verbatim
17424 (add-text-properties
17425 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17426 latex-frag)))
17428 ;; This function borrows from Ganesh Swami's latex2png.el
17429 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17430 "This calls dvipng."
17431 (require 'org-latex)
17432 (let* ((tmpdir (if (featurep 'xemacs)
17433 (temp-directory)
17434 temporary-file-directory))
17435 (texfilebase (make-temp-name
17436 (expand-file-name "orgtex" tmpdir)))
17437 (texfile (concat texfilebase ".tex"))
17438 (dvifile (concat texfilebase ".dvi"))
17439 (pngfile (concat texfilebase ".png"))
17440 (fnh (if (featurep 'xemacs)
17441 (font-height (face-font 'default))
17442 (face-attribute 'default :height nil)))
17443 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17444 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17445 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17446 "Black"))
17447 (bg (or (plist-get options (if buffer :background :html-background))
17448 "Transparent")))
17449 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17450 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17451 (with-temp-file texfile
17452 (insert (org-splice-latex-header
17453 org-format-latex-header
17454 org-export-latex-default-packages-alist
17455 org-export-latex-packages-alist t
17456 org-format-latex-header-extra))
17457 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17458 (require 'org-latex)
17459 (org-export-latex-fix-inputenc))
17460 (let ((dir default-directory))
17461 (condition-case nil
17462 (progn
17463 (cd tmpdir)
17464 (call-process "latex" nil nil nil texfile))
17465 (error nil))
17466 (cd dir))
17467 (if (not (file-exists-p dvifile))
17468 (progn (message "Failed to create dvi file from %s" texfile) nil)
17469 (condition-case nil
17470 (if (featurep 'xemacs)
17471 (call-process "dvipng" nil nil nil
17472 "-fg" fg "-bg" bg
17473 "-T" "tight"
17474 "-o" pngfile
17475 dvifile)
17476 (call-process "dvipng" nil nil nil
17477 "-fg" fg "-bg" bg
17478 "-D" dpi
17479 ;;"-x" scale "-y" scale
17480 "-T" "tight"
17481 "-o" pngfile
17482 dvifile))
17483 (error nil))
17484 (if (not (file-exists-p pngfile))
17485 (if org-format-latex-signal-error
17486 (error "Failed to create png file from %s" texfile)
17487 (message "Failed to create png file from %s" texfile)
17488 nil)
17489 ;; Use the requested file name and clean up
17490 (copy-file pngfile tofile 'replace)
17491 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17492 (if (file-exists-p (concat texfilebase e))
17493 (delete-file (concat texfilebase e))))
17494 pngfile))))
17496 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17497 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17498 "This calls convert, which is included into imagemagick."
17499 (require 'org-latex)
17500 (let* ((tmpdir (if (featurep 'xemacs)
17501 (temp-directory)
17502 temporary-file-directory))
17503 (texfilebase (make-temp-name
17504 (expand-file-name "orgtex" tmpdir)))
17505 (texfile (concat texfilebase ".tex"))
17506 (pdffile (concat texfilebase ".pdf"))
17507 (pngfile (concat texfilebase ".png"))
17508 (fnh (if (featurep 'xemacs)
17509 (font-height (face-font 'default))
17510 (face-attribute 'default :height nil)))
17511 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17512 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17513 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17514 "black"))
17515 (bg (or (plist-get options (if buffer :background :html-background))
17516 "white")))
17517 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17518 (setq fg (org-latex-color-format fg)))
17519 (if (eq bg 'default) (setq bg (org-latex-color :background))
17520 (setq bg (org-latex-color-format
17521 (if (string= bg "Transparent")(setq bg "white")))))
17522 (with-temp-file texfile
17523 (insert (org-splice-latex-header
17524 org-format-latex-header
17525 org-export-latex-default-packages-alist
17526 org-export-latex-packages-alist t
17527 org-format-latex-header-extra))
17528 (insert "\n\\begin{document}\n"
17529 "\\definecolor{fg}{rgb}{" fg "}\n"
17530 "\\definecolor{bg}{rgb}{" bg "}\n"
17531 "\n\\pagecolor{bg}\n"
17532 "\n{\\color{fg}\n"
17533 string
17534 "\n}\n"
17535 "\n\\end{document}\n" )
17536 (require 'org-latex)
17537 (org-export-latex-fix-inputenc))
17538 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17539 (condition-case nil
17540 (progn
17541 (cd tmpdir)
17542 (setq cmds org-latex-to-pdf-process)
17543 (while cmds
17544 (setq latex-frags-cmds (pop cmds))
17545 (if (listp latex-frags-cmds)
17546 (setq cmds nil)
17547 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17548 (while latex-frags-cmds
17549 (setq cmd (pop latex-frags-cmds))
17550 (while (string-match "%b" cmd)
17551 (setq cmd (replace-match
17552 (save-match-data
17553 (shell-quote-argument texfile))
17554 t t cmd)))
17555 (while (string-match "%f" cmd)
17556 (setq cmd (replace-match
17557 (save-match-data
17558 (shell-quote-argument (file-name-nondirectory texfile)))
17559 t t cmd)))
17560 (while (string-match "%o" cmd)
17561 (setq cmd (replace-match
17562 (save-match-data
17563 (shell-quote-argument (file-name-directory texfile)))
17564 t t cmd)))
17565 (setq cmd (split-string cmd))
17566 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17567 (error nil))
17568 (cd dir))
17569 (if (not (file-exists-p pdffile))
17570 (progn (message "Failed to create pdf file from %s" texfile) nil)
17571 (condition-case nil
17572 (if (featurep 'xemacs)
17573 (call-process "convert" nil nil nil
17574 "-density" "96"
17575 "-trim"
17576 "-antialias"
17577 pdffile
17578 "-quality" "100"
17579 ;; "-sharpen" "0x1.0"
17580 pngfile)
17581 (call-process "convert" nil nil nil
17582 "-density" dpi
17583 "-trim"
17584 "-antialias"
17585 pdffile
17586 "-quality" "100"
17587 ; "-sharpen" "0x1.0"
17588 pngfile))
17589 (error nil))
17590 (if (not (file-exists-p pngfile))
17591 (if org-format-latex-signal-error
17592 (error "Failed to create png file from %s" texfile)
17593 (message "Failed to create png file from %s" texfile)
17594 nil)
17595 ;; Use the requested file name and clean up
17596 (copy-file pngfile tofile 'replace)
17597 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17598 (if (file-exists-p (concat texfilebase e))
17599 (delete-file (concat texfilebase e))))
17600 pngfile))))
17602 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17603 "Fill a LaTeX header template TPL.
17604 In the template, the following place holders will be recognized:
17606 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17607 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17608 [PACKAGES] \\usepackage statements for PKG
17609 [NO-PACKAGES] do not include PKG
17610 [EXTRA] the string EXTRA
17611 [NO-EXTRA] do not include EXTRA
17613 For backward compatibility, if both the positive and the negative place
17614 holder is missing, the positive one (without the \"NO-\") will be
17615 assumed to be present at the end of the template.
17616 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17617 EXTRA is a string.
17618 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17619 (let (rpl (end ""))
17620 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17621 (setq rpl (if (or (match-end 1) (not def-pkg))
17622 "" (org-latex-packages-to-string def-pkg snippets-p t))
17623 tpl (replace-match rpl t t tpl))
17624 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17626 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17627 (setq rpl (if (or (match-end 1) (not pkg))
17628 "" (org-latex-packages-to-string pkg snippets-p t))
17629 tpl (replace-match rpl t t tpl))
17630 (if pkg (setq end
17631 (concat end "\n"
17632 (org-latex-packages-to-string pkg snippets-p)))))
17634 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17635 (setq rpl (if (or (match-end 1) (not extra))
17636 "" (concat extra "\n"))
17637 tpl (replace-match rpl t t tpl))
17638 (if (and extra (string-match "\\S-" extra))
17639 (setq end (concat end "\n" extra))))
17641 (if (string-match "\\S-" end)
17642 (concat tpl "\n" end)
17643 tpl)))
17645 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17646 "Turn an alist of packages into a string with the \\usepackage macros."
17647 (setq pkg (mapconcat (lambda(p)
17648 (cond
17649 ((stringp p) p)
17650 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17651 (format "%% Package %s omitted" (cadr p)))
17652 ((equal "" (car p))
17653 (format "\\usepackage{%s}" (cadr p)))
17655 (format "\\usepackage[%s]{%s}"
17656 (car p) (cadr p)))))
17658 "\n"))
17659 (if newline (concat pkg "\n") pkg))
17661 (defun org-dvipng-color (attr)
17662 "Return a RGB color specification for dvipng."
17663 (apply 'format "rgb %s %s %s"
17664 (mapcar 'org-normalize-color
17665 (if (featurep 'xemacs)
17666 (color-rgb-components
17667 (face-property 'default
17668 (cond ((eq attr :foreground) 'foreground)
17669 ((eq attr :background) 'background))))
17670 (color-values (face-attribute 'default attr nil))))))
17672 (defun org-latex-color (attr)
17673 "Return a RGB color for the LaTeX color package."
17674 (apply 'format "%s,%s,%s"
17675 (mapcar 'org-normalize-color
17676 (if (featurep 'xemacs)
17677 (color-rgb-components
17678 (face-property 'default
17679 (cond ((eq attr :foreground) 'foreground)
17680 ((eq attr :background) 'background))))
17681 (color-values (face-attribute 'default attr nil))))))
17683 (defun org-latex-color-format (color-name)
17684 "Convert COLOR-NAME to a RGB color value."
17685 (apply 'format "%s,%s,%s"
17686 (mapcar 'org-normalize-color
17687 (color-values color-name))))
17689 (defun org-normalize-color (value)
17690 "Return string to be used as color value for an RGB component."
17691 (format "%g" (/ value 65535.0)))
17693 ;; Image display
17696 (defvar org-inline-image-overlays nil)
17697 (make-variable-buffer-local 'org-inline-image-overlays)
17699 (defun org-toggle-inline-images (&optional include-linked)
17700 "Toggle the display of inline images.
17701 INCLUDE-LINKED is passed to `org-display-inline-images'."
17702 (interactive "P")
17703 (if org-inline-image-overlays
17704 (progn
17705 (org-remove-inline-images)
17706 (message "Inline image display turned off"))
17707 (org-display-inline-images include-linked)
17708 (if org-inline-image-overlays
17709 (message "%d images displayed inline"
17710 (length org-inline-image-overlays))
17711 (message "No images to display inline"))))
17713 (defun org-redisplay-inline-images ()
17714 "Refresh the display of inline images."
17715 (interactive)
17716 (if (not org-inline-image-overlays)
17717 (org-toggle-inline-images)
17718 (org-toggle-inline-images)
17719 (org-toggle-inline-images)))
17721 (defun org-display-inline-images (&optional include-linked refresh beg end)
17722 "Display inline images.
17723 Normally only links without a description part are inlined, because this
17724 is how it will work for export. When INCLUDE-LINKED is set, also links
17725 with a description part will be inlined. This can be nice for a quick
17726 look at those images, but it does not reflect what exported files will look
17727 like.
17728 When REFRESH is set, refresh existing images between BEG and END.
17729 This will create new image displays only if necessary.
17730 BEG and END default to the buffer boundaries."
17731 (interactive "P")
17732 (unless refresh
17733 (org-remove-inline-images)
17734 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17735 (save-excursion
17736 (save-restriction
17737 (widen)
17738 (setq beg (or beg (point-min)) end (or end (point-max)))
17739 (goto-char beg)
17740 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17741 (substring (org-image-file-name-regexp) 0 -2)
17742 "\\)\\]" (if include-linked "" "\\]")))
17743 old file ov img)
17744 (while (re-search-forward re end t)
17745 (setq old (get-char-property-and-overlay (match-beginning 1)
17746 'org-image-overlay))
17747 (setq file (expand-file-name
17748 (concat (or (match-string 3) "") (match-string 4))))
17749 (when (file-exists-p file)
17750 (if (and (car-safe old) refresh)
17751 (image-refresh (overlay-get (cdr old) 'display))
17752 (setq img (save-match-data (create-image file)))
17753 (when img
17754 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17755 (overlay-put ov 'display img)
17756 (overlay-put ov 'face 'default)
17757 (overlay-put ov 'org-image-overlay t)
17758 (overlay-put ov 'modification-hooks
17759 (list 'org-display-inline-remove-overlay))
17760 (push ov org-inline-image-overlays)))))))))
17762 (define-obsolete-function-alias
17763 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
17765 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
17766 "Remove inline-display overlay if a corresponding region is modified."
17767 (let ((inhibit-modification-hooks t))
17768 (when (and ov after)
17769 (delete ov org-inline-image-overlays)
17770 (delete-overlay ov))))
17772 (defun org-remove-inline-images ()
17773 "Remove inline display of images."
17774 (interactive)
17775 (mapc 'delete-overlay org-inline-image-overlays)
17776 (setq org-inline-image-overlays nil))
17778 ;;;; Key bindings
17780 ;; Outline functions from `outline-mode-prefix-map'
17781 ;; that can be remapped in Org:
17782 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17783 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17784 (define-key org-mode-map [remap outline-forward-same-level]
17785 'org-forward-heading-same-level)
17786 (define-key org-mode-map [remap outline-backward-same-level]
17787 'org-backward-heading-same-level)
17788 (define-key org-mode-map [remap show-branches]
17789 'org-kill-note-or-show-branches)
17790 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17791 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17792 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17794 ;; Outline functions from `outline-mode-prefix-map' that can not
17795 ;; be remapped in Org:
17797 ;; - the column "key binding" shows whether the Outline function is still
17798 ;; available in Org mode on the same key that it has been bound to in
17799 ;; Outline mode:
17800 ;; - "overridden": key used for a different functionality in Org mode
17801 ;; - else: key still bound to the same Outline function in Org mode
17803 ;; | Outline function | key binding | Org replacement |
17804 ;; |------------------------------------+-------------+-----------------------|
17805 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17806 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17807 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17808 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
17809 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17810 ;; | `show-entry' | overridden | no replacement |
17811 ;; | `show-children' | `C-c C-i' | visibility cycling |
17812 ;; | `show-branches' | `C-c C-k' | still same function |
17813 ;; | `show-subtree' | overridden | visibility cycling |
17814 ;; | `show-all' | overridden | no replacement |
17815 ;; | `hide-subtree' | overridden | visibility cycling |
17816 ;; | `hide-body' | overridden | no replacement |
17817 ;; | `hide-entry' | overridden | visibility cycling |
17818 ;; | `hide-leaves' | overridden | no replacement |
17819 ;; | `hide-sublevels' | overridden | no replacement |
17820 ;; | `hide-other' | overridden | no replacement |
17822 ;; Make `C-c C-x' a prefix key
17823 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17825 ;; TAB key with modifiers
17826 (org-defkey org-mode-map "\C-i" 'org-cycle)
17827 (org-defkey org-mode-map [(tab)] 'org-cycle)
17828 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17829 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17830 ;; The following line is necessary under Suse GNU/Linux
17831 (unless (featurep 'xemacs)
17832 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17833 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17834 (define-key org-mode-map [backtab] 'org-shifttab)
17836 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17837 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17838 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17840 ;; Cursor keys with modifiers
17841 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17842 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17843 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17844 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17846 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17847 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17848 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17849 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17851 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17852 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17853 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17854 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17856 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17857 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17858 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17859 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17861 ;; Babel keys
17862 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17863 (mapc (lambda (pair)
17864 (define-key org-babel-map (car pair) (cdr pair)))
17865 org-babel-key-bindings)
17867 ;;; Extra keys for tty access.
17868 ;; We only set them when really needed because otherwise the
17869 ;; menus don't show the simple keys
17871 (when (or org-use-extra-keys
17872 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17873 (not window-system))
17874 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17875 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17876 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17877 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17878 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17879 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17880 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17881 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17882 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17883 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17884 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17885 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17886 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17887 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17888 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17889 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17890 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17891 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17892 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17893 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17894 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17895 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17896 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17897 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17898 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17899 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17900 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17901 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17903 ;; All the other keys
17905 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17906 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17907 (if (boundp 'narrow-map)
17908 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17909 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17910 (if (boundp 'narrow-map)
17911 (org-defkey narrow-map "b" 'org-narrow-to-block)
17912 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17913 (if (boundp 'narrow-map)
17914 (org-defkey narrow-map "e" 'org-narrow-to-element)
17915 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
17916 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
17917 (org-defkey org-mode-map "\M-}" 'org-forward-element)
17918 (org-defkey org-mode-map "\M-{" 'org-backward-element)
17919 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
17920 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
17921 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
17922 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
17923 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17924 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17925 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17926 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
17927 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17928 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17929 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17930 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17931 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17932 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17933 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17934 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17935 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17936 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17937 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17938 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17939 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17940 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17941 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17942 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17943 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17944 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17945 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17946 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17947 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17948 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
17949 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17950 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17951 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17952 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17953 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17954 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17955 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17956 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17957 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17958 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17959 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17960 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17961 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17962 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17963 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17964 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17965 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17966 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17967 (org-defkey org-mode-map "\C-c^" 'org-sort)
17968 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17969 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17970 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17971 (org-defkey org-mode-map "\C-m" 'org-return)
17972 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17973 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17974 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17975 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17976 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17977 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17978 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17979 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17980 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17981 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17982 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17983 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17984 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17985 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17986 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17987 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17988 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17989 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17990 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17991 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17992 (org-defkey org-mode-map "\M-h" 'org-mark-element)
17993 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17994 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17996 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17997 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17998 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18000 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18001 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18002 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18003 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18004 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18005 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18006 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18007 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18008 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18009 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18010 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18011 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18012 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18013 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18014 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18015 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18016 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18017 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18018 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18019 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18020 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18021 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18023 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18024 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18025 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18026 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18027 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18029 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18031 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18033 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18034 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18036 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18039 (when (featurep 'xemacs)
18040 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18043 (defconst org-speed-commands-default
18045 ("Outline Navigation")
18046 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18047 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18048 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18049 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18050 ("u" . (org-speed-move-safe 'outline-up-heading))
18051 ("j" . org-goto)
18052 ("g" . (org-refile t))
18053 ("Outline Visibility")
18054 ("c" . org-cycle)
18055 ("C" . org-shifttab)
18056 (" " . org-display-outline-path)
18057 (":" . org-columns)
18058 ("Outline Structure Editing")
18059 ("U" . org-shiftmetaup)
18060 ("D" . org-shiftmetadown)
18061 ("r" . org-metaright)
18062 ("l" . org-metaleft)
18063 ("R" . org-shiftmetaright)
18064 ("L" . org-shiftmetaleft)
18065 ("i" . (progn (forward-char 1) (call-interactively
18066 'org-insert-heading-respect-content)))
18067 ("^" . org-sort)
18068 ("w" . org-refile)
18069 ("a" . org-archive-subtree-default-with-confirmation)
18070 ("." . org-mark-subtree)
18071 ("#" . org-toggle-comment)
18072 ("Clock Commands")
18073 ("I" . org-clock-in)
18074 ("O" . org-clock-out)
18075 ("Meta Data Editing")
18076 ("t" . org-todo)
18077 ("," . (org-priority))
18078 ("0" . (org-priority ?\ ))
18079 ("1" . (org-priority ?A))
18080 ("2" . (org-priority ?B))
18081 ("3" . (org-priority ?C))
18082 (";" . org-set-tags-command)
18083 ("e" . org-set-effort)
18084 ("E" . org-inc-effort)
18085 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18086 (org-entry-put (point) "APPT_WARNTIME" m)))
18087 ("Agenda Views etc")
18088 ("v" . org-agenda)
18089 ("/" . org-sparse-tree)
18090 ("Misc")
18091 ("o" . org-open-at-point)
18092 ("?" . org-speed-command-help)
18093 ("<" . (org-agenda-set-restriction-lock 'subtree))
18094 (">" . (org-agenda-remove-restriction-lock))
18096 "The default speed commands.")
18098 (defun org-print-speed-command (e)
18099 (if (> (length (car e)) 1)
18100 (progn
18101 (princ "\n")
18102 (princ (car e))
18103 (princ "\n")
18104 (princ (make-string (length (car e)) ?-))
18105 (princ "\n"))
18106 (princ (car e))
18107 (princ " ")
18108 (if (symbolp (cdr e))
18109 (princ (symbol-name (cdr e)))
18110 (prin1 (cdr e)))
18111 (princ "\n")))
18113 (defun org-speed-command-help ()
18114 "Show the available speed commands."
18115 (interactive)
18116 (if (not org-use-speed-commands)
18117 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18118 (with-output-to-temp-buffer "*Help*"
18119 (princ "User-defined Speed commands\n===========================\n")
18120 (mapc 'org-print-speed-command org-speed-commands-user)
18121 (princ "\n")
18122 (princ "Built-in Speed commands\n=======================\n")
18123 (mapc 'org-print-speed-command org-speed-commands-default))
18124 (with-current-buffer "*Help*"
18125 (setq truncate-lines t))))
18127 (defun org-speed-move-safe (cmd)
18128 "Execute CMD, but make sure that the cursor always ends up in a headline.
18129 If not, return to the original position and throw an error."
18130 (interactive)
18131 (let ((pos (point)))
18132 (call-interactively cmd)
18133 (unless (and (bolp) (org-at-heading-p))
18134 (goto-char pos)
18135 (error "Boundary reached while executing %s" cmd))))
18137 (defvar org-self-insert-command-undo-counter 0)
18139 (defvar org-table-auto-blank-field) ; defined in org-table.el
18140 (defvar org-speed-command nil)
18142 (define-obsolete-function-alias
18143 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18145 (defun org-speed-command-activate (keys)
18146 "Hook for activating single-letter speed commands.
18147 `org-speed-commands-default' specifies a minimal command set.
18148 Use `org-speed-commands-user' for further customization."
18149 (when (or (and (bolp) (looking-at org-outline-regexp))
18150 (and (functionp org-use-speed-commands)
18151 (funcall org-use-speed-commands)))
18152 (cdr (assoc keys (append org-speed-commands-user
18153 org-speed-commands-default)))))
18155 (define-obsolete-function-alias
18156 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18158 (defun org-babel-speed-command-activate (keys)
18159 "Hook for activating single-letter code block commands."
18160 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18161 (cdr (assoc keys org-babel-key-bindings))))
18163 (defcustom org-speed-command-hook
18164 '(org-speed-command-default-hook org-babel-speed-command-hook)
18165 "Hook for activating speed commands at strategic locations.
18166 Hook functions are called in sequence until a valid handler is
18167 found.
18169 Each hook takes a single argument, a user-pressed command key
18170 which is also a `self-insert-command' from the global map.
18172 Within the hook, examine the cursor position and the command key
18173 and return nil or a valid handler as appropriate. Handler could
18174 be one of an interactive command, a function, or a form.
18176 Set `org-use-speed-commands' to non-nil value to enable this
18177 hook. The default setting is `org-speed-command-activate'."
18178 :group 'org-structure
18179 :version "24.1"
18180 :type 'hook)
18182 (defun org-self-insert-command (N)
18183 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18184 If the cursor is in a table looking at whitespace, the whitespace is
18185 overwritten, and the table is not marked as requiring realignment."
18186 (interactive "p")
18187 (org-check-before-invisible-edit 'insert)
18188 (cond
18189 ((and org-use-speed-commands
18190 (setq org-speed-command
18191 (run-hook-with-args-until-success
18192 'org-speed-command-hook (this-command-keys))))
18193 (cond
18194 ((commandp org-speed-command)
18195 (setq this-command org-speed-command)
18196 (call-interactively org-speed-command))
18197 ((functionp org-speed-command)
18198 (funcall org-speed-command))
18199 ((and org-speed-command (listp org-speed-command))
18200 (eval org-speed-command))
18201 (t (let (org-use-speed-commands)
18202 (call-interactively 'org-self-insert-command)))))
18203 ((and
18204 (org-table-p)
18205 (progn
18206 ;; check if we blank the field, and if that triggers align
18207 (and (featurep 'org-table) org-table-auto-blank-field
18208 (member last-command
18209 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18210 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18211 ;; got extra space, this field does not determine column width
18212 (let (org-table-may-need-update) (org-table-blank-field))
18213 ;; no extra space, this field may determine column width
18214 (org-table-blank-field)))
18216 (eq N 1)
18217 (looking-at "[^|\n]* |"))
18218 (let (org-table-may-need-update)
18219 (goto-char (1- (match-end 0)))
18220 (backward-delete-char 1)
18221 (goto-char (match-beginning 0))
18222 (self-insert-command N)))
18224 (setq org-table-may-need-update t)
18225 (self-insert-command N)
18226 (org-fix-tags-on-the-fly)
18227 (if org-self-insert-cluster-for-undo
18228 (if (not (eq last-command 'org-self-insert-command))
18229 (setq org-self-insert-command-undo-counter 1)
18230 (if (>= org-self-insert-command-undo-counter 20)
18231 (setq org-self-insert-command-undo-counter 1)
18232 (and (> org-self-insert-command-undo-counter 0)
18233 buffer-undo-list (listp buffer-undo-list)
18234 (not (cadr buffer-undo-list)) ; remove nil entry
18235 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18236 (setq org-self-insert-command-undo-counter
18237 (1+ org-self-insert-command-undo-counter))))))))
18239 (defun org-check-before-invisible-edit (kind)
18240 "Check is editing if kind KIND would be dangerous with invisible text around.
18241 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18242 ;; First, try to get out of here as quickly as possible, to reduce overhead
18243 (if (and org-catch-invisible-edits
18244 (or (not (boundp 'visible-mode)) (not visible-mode))
18245 (or (get-char-property (point) 'invisible)
18246 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18247 ;; OK, we need to take a closer look
18248 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18249 (invisible-before-point (if (bobp) nil (get-char-property
18250 (1- (point)) 'invisible)))
18251 (border-and-ok-direction
18253 ;; Check if we are acting predictably before invisible text
18254 (and invisible-at-point (not invisible-before-point)
18255 (memq kind '(insert delete-backward)))
18256 ;; Check if we are acting predictably after invisible text
18257 ;; This works not well, and I have turned it off. It seems
18258 ;; better to always show and stop after invisible text.
18259 ;; (and (not invisible-at-point) invisible-before-point
18260 ;; (memq kind '(insert delete)))
18262 (when (or (memq invisible-at-point '(outline org-hide-block t))
18263 (memq invisible-before-point '(outline org-hide-block t)))
18264 (if (eq org-catch-invisible-edits 'error)
18265 (error "Editing in invisible areas is prohibited - make visible first"))
18266 (if (and org-custom-properties-overlays
18267 (y-or-n-p "Display invisible properties in this buffer? "))
18268 (org-toggle-custom-properties-visibility)
18269 ;; Make the area visible
18270 (save-excursion
18271 (if invisible-before-point
18272 (goto-char (previous-single-char-property-change
18273 (point) 'invisible)))
18274 (org-cycle))
18275 (cond
18276 ((eq org-catch-invisible-edits 'show)
18277 ;; That's it, we do the edit after showing
18278 (message
18279 "Unfolding invisible region around point before editing")
18280 (sit-for 1))
18281 ((and (eq org-catch-invisible-edits 'smart)
18282 border-and-ok-direction)
18283 (message "Unfolding invisible region around point before editing"))
18285 ;; Don't do the edit, make the user repeat it in full visibility
18286 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18288 (defun org-fix-tags-on-the-fly ()
18289 (when (and (equal (char-after (point-at-bol)) ?*)
18290 (org-at-heading-p))
18291 (org-align-tags-here org-tags-column)))
18293 (defun org-delete-backward-char (N)
18294 "Like `delete-backward-char', insert whitespace at field end in tables.
18295 When deleting backwards, in tables this function will insert whitespace in
18296 front of the next \"|\" separator, to keep the table aligned. The table will
18297 still be marked for re-alignment if the field did fill the entire column,
18298 because, in this case the deletion might narrow the column."
18299 (interactive "p")
18300 (org-check-before-invisible-edit 'delete-backward)
18301 (if (and (org-table-p)
18302 (eq N 1)
18303 (string-match "|" (buffer-substring (point-at-bol) (point)))
18304 (looking-at ".*?|"))
18305 (let ((pos (point))
18306 (noalign (looking-at "[^|\n\r]* |"))
18307 (c org-table-may-need-update))
18308 (backward-delete-char N)
18309 (if (not overwrite-mode)
18310 (progn
18311 (skip-chars-forward "^|")
18312 (insert " ")
18313 (goto-char (1- pos))))
18314 ;; noalign: if there were two spaces at the end, this field
18315 ;; does not determine the width of the column.
18316 (if noalign (setq org-table-may-need-update c)))
18317 (backward-delete-char N)
18318 (org-fix-tags-on-the-fly)))
18320 (defun org-delete-char (N)
18321 "Like `delete-char', but insert whitespace at field end in tables.
18322 When deleting characters, in tables this function will insert whitespace in
18323 front of the next \"|\" separator, to keep the table aligned. The table will
18324 still be marked for re-alignment if the field did fill the entire column,
18325 because, in this case the deletion might narrow the column."
18326 (interactive "p")
18327 (org-check-before-invisible-edit 'delete)
18328 (if (and (org-table-p)
18329 (not (bolp))
18330 (not (= (char-after) ?|))
18331 (eq N 1))
18332 (if (looking-at ".*?|")
18333 (let ((pos (point))
18334 (noalign (looking-at "[^|\n\r]* |"))
18335 (c org-table-may-need-update))
18336 (replace-match (concat
18337 (substring (match-string 0) 1 -1)
18338 " |"))
18339 (goto-char pos)
18340 ;; noalign: if there were two spaces at the end, this field
18341 ;; does not determine the width of the column.
18342 (if noalign (setq org-table-may-need-update c)))
18343 (delete-char N))
18344 (delete-char N)
18345 (org-fix-tags-on-the-fly)))
18347 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18348 (put 'org-self-insert-command 'delete-selection t)
18349 (put 'orgtbl-self-insert-command 'delete-selection t)
18350 (put 'org-delete-char 'delete-selection 'supersede)
18351 (put 'org-delete-backward-char 'delete-selection 'supersede)
18352 (put 'org-yank 'delete-selection 'yank)
18354 ;; Make `flyspell-mode' delay after some commands
18355 (put 'org-self-insert-command 'flyspell-delayed t)
18356 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18357 (put 'org-delete-char 'flyspell-delayed t)
18358 (put 'org-delete-backward-char 'flyspell-delayed t)
18360 ;; Make pabbrev-mode expand after org-mode commands
18361 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18362 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18364 ;; How to do this: Measure non-white length of current string
18365 ;; If equal to column width, we should realign.
18367 (defun org-remap (map &rest commands)
18368 "In MAP, remap the functions given in COMMANDS.
18369 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18370 (let (new old)
18371 (while commands
18372 (setq old (pop commands) new (pop commands))
18373 (if (fboundp 'command-remapping)
18374 (org-defkey map (vector 'remap old) new)
18375 (substitute-key-definition old new map global-map)))))
18377 (when (eq org-enable-table-editor 'optimized)
18378 ;; If the user wants maximum table support, we need to hijack
18379 ;; some standard editing functions
18380 (org-remap org-mode-map
18381 'self-insert-command 'org-self-insert-command
18382 'delete-char 'org-delete-char
18383 'delete-backward-char 'org-delete-backward-char)
18384 (org-defkey org-mode-map "|" 'org-force-self-insert))
18386 (defvar org-ctrl-c-ctrl-c-hook nil
18387 "Hook for functions attaching themselves to `C-c C-c'.
18389 This can be used to add additional functionality to the C-c C-c
18390 key which executes context-dependent commands. This hook is run
18391 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18392 run after the last test.
18394 Each function will be called with no arguments. The function
18395 must check if the context is appropriate for it to act. If yes,
18396 it should do its thing and then return a non-nil value. If the
18397 context is wrong, just do nothing and return nil.")
18399 (defvar org-ctrl-c-ctrl-c-final-hook nil
18400 "Hook for functions attaching themselves to `C-c C-c'.
18402 This can be used to add additional functionality to the C-c C-c
18403 key which executes context-dependent commands. This hook is run
18404 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18405 before the first test.
18407 Each function will be called with no arguments. The function
18408 must check if the context is appropriate for it to act. If yes,
18409 it should do its thing and then return a non-nil value. If the
18410 context is wrong, just do nothing and return nil.")
18412 (defvar org-tab-first-hook nil
18413 "Hook for functions to attach themselves to TAB.
18414 See `org-ctrl-c-ctrl-c-hook' for more information.
18415 This hook runs as the first action when TAB is pressed, even before
18416 `org-cycle' messes around with the `outline-regexp' to cater for
18417 inline tasks and plain list item folding.
18418 If any function in this hook returns t, any other actions that
18419 would have been caused by TAB (such as table field motion or visibility
18420 cycling) will not occur.")
18422 (defvar org-tab-after-check-for-table-hook nil
18423 "Hook for functions to attach themselves to TAB.
18424 See `org-ctrl-c-ctrl-c-hook' for more information.
18425 This hook runs after it has been established that the cursor is not in a
18426 table, but before checking if the cursor is in a headline or if global cycling
18427 should be done.
18428 If any function in this hook returns t, not other actions like visibility
18429 cycling will be done.")
18431 (defvar org-tab-after-check-for-cycling-hook nil
18432 "Hook for functions to attach themselves to TAB.
18433 See `org-ctrl-c-ctrl-c-hook' for more information.
18434 This hook runs after it has been established that not table field motion and
18435 not visibility should be done because of current context. This is probably
18436 the place where a package like yasnippets can hook in.")
18438 (defvar org-tab-before-tab-emulation-hook nil
18439 "Hook for functions to attach themselves to TAB.
18440 See `org-ctrl-c-ctrl-c-hook' for more information.
18441 This hook runs after every other options for TAB have been exhausted, but
18442 before indentation and \t insertion takes place.")
18444 (defvar org-metaleft-hook nil
18445 "Hook for functions attaching themselves to `M-left'.
18446 See `org-ctrl-c-ctrl-c-hook' for more information.")
18447 (defvar org-metaright-hook nil
18448 "Hook for functions attaching themselves to `M-right'.
18449 See `org-ctrl-c-ctrl-c-hook' for more information.")
18450 (defvar org-metaup-hook nil
18451 "Hook for functions attaching themselves to `M-up'.
18452 See `org-ctrl-c-ctrl-c-hook' for more information.")
18453 (defvar org-metadown-hook nil
18454 "Hook for functions attaching themselves to `M-down'.
18455 See `org-ctrl-c-ctrl-c-hook' for more information.")
18456 (defvar org-shiftmetaleft-hook nil
18457 "Hook for functions attaching themselves to `M-S-left'.
18458 See `org-ctrl-c-ctrl-c-hook' for more information.")
18459 (defvar org-shiftmetaright-hook nil
18460 "Hook for functions attaching themselves to `M-S-right'.
18461 See `org-ctrl-c-ctrl-c-hook' for more information.")
18462 (defvar org-shiftmetaup-hook nil
18463 "Hook for functions attaching themselves to `M-S-up'.
18464 See `org-ctrl-c-ctrl-c-hook' for more information.")
18465 (defvar org-shiftmetadown-hook nil
18466 "Hook for functions attaching themselves to `M-S-down'.
18467 See `org-ctrl-c-ctrl-c-hook' for more information.")
18468 (defvar org-metareturn-hook nil
18469 "Hook for functions attaching themselves to `M-RET'.
18470 See `org-ctrl-c-ctrl-c-hook' for more information.")
18471 (defvar org-shiftup-hook nil
18472 "Hook for functions attaching themselves to `S-up'.
18473 See `org-ctrl-c-ctrl-c-hook' for more information.")
18474 (defvar org-shiftup-final-hook nil
18475 "Hook for functions attaching themselves to `S-up'.
18476 This one runs after all other options except shift-select have been excluded.
18477 See `org-ctrl-c-ctrl-c-hook' for more information.")
18478 (defvar org-shiftdown-hook nil
18479 "Hook for functions attaching themselves to `S-down'.
18480 See `org-ctrl-c-ctrl-c-hook' for more information.")
18481 (defvar org-shiftdown-final-hook nil
18482 "Hook for functions attaching themselves to `S-down'.
18483 This one runs after all other options except shift-select have been excluded.
18484 See `org-ctrl-c-ctrl-c-hook' for more information.")
18485 (defvar org-shiftleft-hook nil
18486 "Hook for functions attaching themselves to `S-left'.
18487 See `org-ctrl-c-ctrl-c-hook' for more information.")
18488 (defvar org-shiftleft-final-hook nil
18489 "Hook for functions attaching themselves to `S-left'.
18490 This one runs after all other options except shift-select have been excluded.
18491 See `org-ctrl-c-ctrl-c-hook' for more information.")
18492 (defvar org-shiftright-hook nil
18493 "Hook for functions attaching themselves to `S-right'.
18494 See `org-ctrl-c-ctrl-c-hook' for more information.")
18495 (defvar org-shiftright-final-hook nil
18496 "Hook for functions attaching themselves to `S-right'.
18497 This one runs after all other options except shift-select have been excluded.
18498 See `org-ctrl-c-ctrl-c-hook' for more information.")
18500 (defun org-modifier-cursor-error ()
18501 "Throw an error, a modified cursor command was applied in wrong context."
18502 (error "This command is active in special context like tables, headlines or items"))
18504 (defun org-shiftselect-error ()
18505 "Throw an error because Shift-Cursor command was applied in wrong context."
18506 (if (and (boundp 'shift-select-mode) shift-select-mode)
18507 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18508 (error "This command works only in special context like headlines or timestamps")))
18510 (defun org-call-for-shift-select (cmd)
18511 (let ((this-command-keys-shift-translated t))
18512 (call-interactively cmd)))
18514 (defun org-shifttab (&optional arg)
18515 "Global visibility cycling or move to previous table field.
18516 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18517 on context.
18518 See the individual commands for more information."
18519 (interactive "P")
18520 (cond
18521 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18522 ((integerp arg)
18523 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18524 (message "Content view to level: %d" arg)
18525 (org-content (prefix-numeric-value arg2))
18526 (setq org-cycle-global-status 'overview)))
18527 (t (call-interactively 'org-global-cycle))))
18529 (defun org-shiftmetaleft ()
18530 "Promote subtree or delete table column.
18531 Calls `org-promote-subtree', `org-outdent-item-tree', or
18532 `org-table-delete-column', depending on context. See the
18533 individual commands for more information."
18534 (interactive)
18535 (cond
18536 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18537 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18538 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18539 ((if (not (org-region-active-p)) (org-at-item-p)
18540 (save-excursion (goto-char (region-beginning))
18541 (org-at-item-p)))
18542 (call-interactively 'org-outdent-item-tree))
18543 (t (org-modifier-cursor-error))))
18545 (defun org-shiftmetaright ()
18546 "Demote subtree or insert table column.
18547 Calls `org-demote-subtree', `org-indent-item-tree', or
18548 `org-table-insert-column', depending on context. See the
18549 individual commands for more information."
18550 (interactive)
18551 (cond
18552 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18553 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18554 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18555 ((if (not (org-region-active-p)) (org-at-item-p)
18556 (save-excursion (goto-char (region-beginning))
18557 (org-at-item-p)))
18558 (call-interactively 'org-indent-item-tree))
18559 (t (org-modifier-cursor-error))))
18561 (defun org-shiftmetaup (&optional arg)
18562 "Move subtree up or kill table row.
18563 Calls `org-move-subtree-up' or `org-table-kill-row' or
18564 `org-move-item-up' or `org-timestamp-up', depending on context.
18565 See the individual commands for more information."
18566 (interactive "P")
18567 (cond
18568 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18569 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18570 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18571 ((org-at-item-p) (call-interactively 'org-move-item-up))
18572 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18573 (call-interactively 'org-timestamp-up)))
18574 (t (org-modifier-cursor-error))))
18576 (defun org-shiftmetadown (&optional arg)
18577 "Move subtree down or insert table row.
18578 Calls `org-move-subtree-down' or `org-table-insert-row' or
18579 `org-move-item-down' or `org-timestamp-up', depending on context.
18580 See the individual commands for more information."
18581 (interactive "P")
18582 (cond
18583 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18584 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18585 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18586 ((org-at-item-p) (call-interactively 'org-move-item-down))
18587 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18588 (call-interactively 'org-timestamp-down)))
18589 (t (org-modifier-cursor-error))))
18591 (defsubst org-hidden-tree-error ()
18592 (error
18593 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18595 (defun org-metaleft (&optional arg)
18596 "Promote heading or move table column to left.
18597 Calls `org-do-promote' or `org-table-move-column', depending on context.
18598 With no specific context, calls the Emacs default `backward-word'.
18599 See the individual commands for more information."
18600 (interactive "P")
18601 (cond
18602 ((run-hook-with-args-until-success 'org-metaleft-hook))
18603 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18604 ((org-with-limited-levels
18605 (or (org-at-heading-p)
18606 (and (org-region-active-p)
18607 (save-excursion
18608 (goto-char (region-beginning))
18609 (org-at-heading-p)))))
18610 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18611 (call-interactively 'org-do-promote))
18612 ;; At an inline task.
18613 ((org-at-heading-p)
18614 (call-interactively 'org-inlinetask-promote))
18615 ((or (org-at-item-p)
18616 (and (org-region-active-p)
18617 (save-excursion
18618 (goto-char (region-beginning))
18619 (org-at-item-p))))
18620 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18621 (call-interactively 'org-outdent-item))
18622 (t (call-interactively 'backward-word))))
18624 (defun org-metaright (&optional arg)
18625 "Demote a subtree, a list item or move table column to right.
18626 In front of a drawer or a block keyword, indent it correctly.
18627 With no specific context, calls the Emacs default `forward-word'.
18628 See the individual commands for more information."
18629 (interactive "P")
18630 (cond
18631 ((run-hook-with-args-until-success 'org-metaright-hook))
18632 ((org-at-table-p) (call-interactively 'org-table-move-column))
18633 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18634 ((org-at-block-p) (call-interactively 'org-indent-block))
18635 ((org-with-limited-levels
18636 (or (org-at-heading-p)
18637 (and (org-region-active-p)
18638 (save-excursion
18639 (goto-char (region-beginning))
18640 (org-at-heading-p)))))
18641 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18642 (call-interactively 'org-do-demote))
18643 ;; At an inline task.
18644 ((org-at-heading-p)
18645 (call-interactively 'org-inlinetask-demote))
18646 ((or (org-at-item-p)
18647 (and (org-region-active-p)
18648 (save-excursion
18649 (goto-char (region-beginning))
18650 (org-at-item-p))))
18651 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18652 (call-interactively 'org-indent-item))
18653 (t (call-interactively 'forward-word))))
18655 (defun org-check-for-hidden (what)
18656 "Check if there are hidden headlines/items in the current visual line.
18657 WHAT can be either `headlines' or `items'. If the current line is
18658 an outline or item heading and it has a folded subtree below it,
18659 this function returns t, nil otherwise."
18660 (let ((re (cond
18661 ((eq what 'headlines) org-outline-regexp-bol)
18662 ((eq what 'items) (org-item-beginning-re))
18663 (t (error "This should not happen"))))
18664 beg end)
18665 (save-excursion
18666 (catch 'exit
18667 (unless (org-region-active-p)
18668 (setq beg (point-at-bol))
18669 (beginning-of-line 2)
18670 (while (and (not (eobp)) ;; this is like `next-line'
18671 (get-char-property (1- (point)) 'invisible))
18672 (beginning-of-line 2))
18673 (setq end (point))
18674 (goto-char beg)
18675 (goto-char (point-at-eol))
18676 (setq end (max end (point)))
18677 (while (re-search-forward re end t)
18678 (if (get-char-property (match-beginning 0) 'invisible)
18679 (throw 'exit t))))
18680 nil))))
18682 (autoload 'org-element-at-point "org-element")
18683 (autoload 'org-element-type "org-element")
18685 (declare-function org-element-at-point "org-element" (&optional keep-trail))
18686 (declare-function org-element-type "org-element" (element))
18687 (declare-function org-element-contents "org-element" (element))
18688 (declare-function org-element-property "org-element" (property element))
18689 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
18690 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
18691 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
18692 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
18693 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
18695 (defun org-metaup (&optional arg)
18696 "Move subtree up or move table row up.
18697 Calls `org-move-subtree-up' or `org-table-move-row' or
18698 `org-move-item-up', depending on context. See the individual commands
18699 for more information."
18700 (interactive "P")
18701 (cond
18702 ((run-hook-with-args-until-success 'org-metaup-hook))
18703 ((org-region-active-p)
18704 (let* ((a (min (region-beginning) (region-end)))
18705 (b (1- (max (region-beginning) (region-end))))
18706 (c (save-excursion (goto-char a)
18707 (move-beginning-of-line 0)))
18708 (d (save-excursion (goto-char a)
18709 (move-end-of-line 0) (point))))
18710 (transpose-regions a b c d)
18711 (goto-char c)))
18712 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18713 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18714 ((org-at-item-p) (call-interactively 'org-move-item-up))
18715 (t (org-drag-element-backward))))
18717 (defun org-metadown (&optional arg)
18718 "Move subtree down or move table row down.
18719 Calls `org-move-subtree-down' or `org-table-move-row' or
18720 `org-move-item-down', depending on context. See the individual
18721 commands for more information."
18722 (interactive "P")
18723 (cond
18724 ((run-hook-with-args-until-success 'org-metadown-hook))
18725 ((org-region-active-p)
18726 (let* ((a (min (region-beginning) (region-end)))
18727 (b (max (region-beginning) (region-end)))
18728 (c (save-excursion (goto-char b)
18729 (move-beginning-of-line 1)))
18730 (d (save-excursion (goto-char b)
18731 (move-end-of-line 1) (1+ (point)))))
18732 (transpose-regions a b c d)
18733 (goto-char d)))
18734 ((org-at-table-p) (call-interactively 'org-table-move-row))
18735 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18736 ((org-at-item-p) (call-interactively 'org-move-item-down))
18737 (t (org-drag-element-forward))))
18739 (defun org-shiftup (&optional arg)
18740 "Increase item in timestamp or increase priority of current headline.
18741 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18742 depending on context. See the individual commands for more information."
18743 (interactive "P")
18744 (cond
18745 ((run-hook-with-args-until-success 'org-shiftup-hook))
18746 ((and org-support-shift-select (org-region-active-p))
18747 (org-call-for-shift-select 'previous-line))
18748 ((org-at-timestamp-p t)
18749 (call-interactively (if org-edit-timestamp-down-means-later
18750 'org-timestamp-down 'org-timestamp-up)))
18751 ((and (not (eq org-support-shift-select 'always))
18752 org-enable-priority-commands
18753 (org-at-heading-p))
18754 (call-interactively 'org-priority-up))
18755 ((and (not org-support-shift-select) (org-at-item-p))
18756 (call-interactively 'org-previous-item))
18757 ((org-clocktable-try-shift 'up arg))
18758 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18759 (org-support-shift-select
18760 (org-call-for-shift-select 'previous-line))
18761 (t (org-shiftselect-error))))
18763 (defun org-shiftdown (&optional arg)
18764 "Decrease item in timestamp or decrease priority of current headline.
18765 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18766 depending on context. See the individual commands for more information."
18767 (interactive "P")
18768 (cond
18769 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18770 ((and org-support-shift-select (org-region-active-p))
18771 (org-call-for-shift-select 'next-line))
18772 ((org-at-timestamp-p t)
18773 (call-interactively (if org-edit-timestamp-down-means-later
18774 'org-timestamp-up 'org-timestamp-down)))
18775 ((and (not (eq org-support-shift-select 'always))
18776 org-enable-priority-commands
18777 (org-at-heading-p))
18778 (call-interactively 'org-priority-down))
18779 ((and (not org-support-shift-select) (org-at-item-p))
18780 (call-interactively 'org-next-item))
18781 ((org-clocktable-try-shift 'down arg))
18782 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18783 (org-support-shift-select
18784 (org-call-for-shift-select 'next-line))
18785 (t (org-shiftselect-error))))
18787 (defun org-shiftright (&optional arg)
18788 "Cycle the thing at point or in the current line, depending on context.
18789 Depending on context, this does one of the following:
18791 - switch a timestamp at point one day into the future
18792 - on a headline, switch to the next TODO keyword.
18793 - on an item, switch entire list to the next bullet type
18794 - on a property line, switch to the next allowed value
18795 - on a clocktable definition line, move time block into the future"
18796 (interactive "P")
18797 (cond
18798 ((run-hook-with-args-until-success 'org-shiftright-hook))
18799 ((and org-support-shift-select (org-region-active-p))
18800 (org-call-for-shift-select 'forward-char))
18801 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18802 ((and (not (eq org-support-shift-select 'always))
18803 (org-at-heading-p))
18804 (let ((org-inhibit-logging
18805 (not org-treat-S-cursor-todo-selection-as-state-change))
18806 (org-inhibit-blocking
18807 (not org-treat-S-cursor-todo-selection-as-state-change)))
18808 (org-call-with-arg 'org-todo 'right)))
18809 ((or (and org-support-shift-select
18810 (not (eq org-support-shift-select 'always))
18811 (org-at-item-bullet-p))
18812 (and (not org-support-shift-select) (org-at-item-p)))
18813 (org-call-with-arg 'org-cycle-list-bullet nil))
18814 ((and (not (eq org-support-shift-select 'always))
18815 (org-at-property-p))
18816 (call-interactively 'org-property-next-allowed-value))
18817 ((org-clocktable-try-shift 'right arg))
18818 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18819 (org-support-shift-select
18820 (org-call-for-shift-select 'forward-char))
18821 (t (org-shiftselect-error))))
18823 (defun org-shiftleft (&optional arg)
18824 "Cycle the thing at point or in the current line, depending on context.
18825 Depending on context, this does one of the following:
18827 - switch a timestamp at point one day into the past
18828 - on a headline, switch to the previous TODO keyword.
18829 - on an item, switch entire list to the previous bullet type
18830 - on a property line, switch to the previous allowed value
18831 - on a clocktable definition line, move time block into the past"
18832 (interactive "P")
18833 (cond
18834 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18835 ((and org-support-shift-select (org-region-active-p))
18836 (org-call-for-shift-select 'backward-char))
18837 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18838 ((and (not (eq org-support-shift-select 'always))
18839 (org-at-heading-p))
18840 (let ((org-inhibit-logging
18841 (not org-treat-S-cursor-todo-selection-as-state-change))
18842 (org-inhibit-blocking
18843 (not org-treat-S-cursor-todo-selection-as-state-change)))
18844 (org-call-with-arg 'org-todo 'left)))
18845 ((or (and org-support-shift-select
18846 (not (eq org-support-shift-select 'always))
18847 (org-at-item-bullet-p))
18848 (and (not org-support-shift-select) (org-at-item-p)))
18849 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18850 ((and (not (eq org-support-shift-select 'always))
18851 (org-at-property-p))
18852 (call-interactively 'org-property-previous-allowed-value))
18853 ((org-clocktable-try-shift 'left arg))
18854 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18855 (org-support-shift-select
18856 (org-call-for-shift-select 'backward-char))
18857 (t (org-shiftselect-error))))
18859 (defun org-shiftcontrolright ()
18860 "Switch to next TODO set."
18861 (interactive)
18862 (cond
18863 ((and org-support-shift-select (org-region-active-p))
18864 (org-call-for-shift-select 'forward-word))
18865 ((and (not (eq org-support-shift-select 'always))
18866 (org-at-heading-p))
18867 (org-call-with-arg 'org-todo 'nextset))
18868 (org-support-shift-select
18869 (org-call-for-shift-select 'forward-word))
18870 (t (org-shiftselect-error))))
18872 (defun org-shiftcontrolleft ()
18873 "Switch to previous TODO set."
18874 (interactive)
18875 (cond
18876 ((and org-support-shift-select (org-region-active-p))
18877 (org-call-for-shift-select 'backward-word))
18878 ((and (not (eq org-support-shift-select 'always))
18879 (org-at-heading-p))
18880 (org-call-with-arg 'org-todo 'previousset))
18881 (org-support-shift-select
18882 (org-call-for-shift-select 'backward-word))
18883 (t (org-shiftselect-error))))
18885 (defun org-shiftcontrolup ()
18886 "Change timestamps synchronously up in CLOCK log lines."
18887 (interactive)
18888 (cond ((and (not org-support-shift-select)
18889 (org-at-clock-log-p)
18890 (org-at-timestamp-p t))
18891 (org-clock-timestamps-up))
18892 (t (org-shiftselect-error))))
18894 (defun org-shiftcontroldown ()
18895 "Change timestamps synchronously down in CLOCK log lines."
18896 (interactive)
18897 (cond ((and (not org-support-shift-select)
18898 (org-at-clock-log-p)
18899 (org-at-timestamp-p t))
18900 (org-clock-timestamps-down))
18901 (t (org-shiftselect-error))))
18903 (defun org-ctrl-c-ret ()
18904 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18905 (interactive)
18906 (cond
18907 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18908 (t (call-interactively 'org-insert-heading))))
18910 (defun org-find-visible ()
18911 (let ((s (point)))
18912 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18913 (get-char-property s 'invisible)))
18915 (defun org-find-invisible ()
18916 (let ((s (point)))
18917 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18918 (not (get-char-property s 'invisible))))
18921 (defun org-copy-visible (beg end)
18922 "Copy the visible parts of the region."
18923 (interactive "r")
18924 (let (snippets s)
18925 (save-excursion
18926 (save-restriction
18927 (narrow-to-region beg end)
18928 (setq s (goto-char (point-min)))
18929 (while (not (= (point) (point-max)))
18930 (goto-char (org-find-invisible))
18931 (push (buffer-substring s (point)) snippets)
18932 (setq s (goto-char (org-find-visible))))))
18933 (kill-new (apply 'concat (nreverse snippets)))))
18935 (defun org-copy-special ()
18936 "Copy region in table or copy current subtree.
18937 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18938 See the individual commands for more information."
18939 (interactive)
18940 (call-interactively
18941 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18943 (defun org-cut-special ()
18944 "Cut region in table or cut current subtree.
18945 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18946 See the individual commands for more information."
18947 (interactive)
18948 (call-interactively
18949 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18951 (defun org-paste-special (arg)
18952 "Paste rectangular region into table, or past subtree relative to level.
18953 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18954 See the individual commands for more information."
18955 (interactive "P")
18956 (if (org-at-table-p)
18957 (org-table-paste-rectangle)
18958 (org-paste-subtree arg)))
18960 (defsubst org-in-fixed-width-region-p ()
18961 "Is point in a fixed-width region?"
18962 (eq 'fixed-width (org-element-type (org-element-at-point))))
18964 (defun org-edit-special (&optional arg)
18965 "Call a special editor for the stuff at point.
18966 When at a table, call the formula editor with `org-table-edit-formulas'.
18967 When in a source code block, call `org-edit-src-code'.
18968 When in an #+include line, visit the included file.
18969 On a link, call `ffap' to visit the link at point.
18970 Otherwise, return a user error."
18971 (interactive)
18972 ;; possibly prep session before editing source
18973 (when (and (org-in-src-block-p) arg)
18974 (let* ((info (org-babel-get-src-block-info))
18975 (lang (nth 0 info))
18976 (params (nth 2 info))
18977 (session (cdr (assoc :session params))))
18978 (when (and info session) ;; we are in a source-code block with a session
18979 (funcall
18980 (intern (concat "org-babel-prep-session:" lang)) session params))))
18981 (cond ;; proceed with `org-edit-special'
18982 ((save-excursion
18983 (beginning-of-line 1)
18984 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18985 (find-file (org-trim (match-string 1))))
18986 ((or (org-at-table-p)
18987 (save-excursion
18988 (beginning-of-line 1)
18989 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
18990 (call-interactively 'org-table-edit-formulas))
18991 ((or (org-in-src-block-p) (org-at-table.el-p)) (org-edit-src-code))
18992 ((org-in-fixed-width-region-p) (org-edit-fixed-width-region))
18993 ((org-at-regexp-p org-any-link-re) (call-interactively 'ffap))
18994 (t (user-error "No special environment to edit here"))))
18996 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18997 (defun org-ctrl-c-ctrl-c (&optional arg)
18998 "Set tags in headline, or update according to changed information at point.
19000 This command does many different things, depending on context:
19002 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19003 this is what we do.
19005 - If the cursor is on a statistics cookie, update it.
19007 - If the cursor is in a headline, prompt for tags and insert them
19008 into the current line, aligned to `org-tags-column'. When called
19009 with prefix arg, realign all tags in the current buffer.
19011 - If the cursor is in one of the special #+KEYWORD lines, this
19012 triggers scanning the buffer for these lines and updating the
19013 information.
19015 - If the cursor is inside a table, realign the table. This command
19016 works even if the automatic table editor has been turned off.
19018 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19019 the entire table.
19021 - If the cursor is at a footnote reference or definition, jump to
19022 the corresponding definition or references, respectively.
19024 - If the cursor is a the beginning of a dynamic block, update it.
19026 - If the current buffer is a capture buffer, close note and file it.
19028 - If the cursor is on a <<<target>>>, update radio targets and
19029 corresponding links in this buffer.
19031 - If the cursor is on a numbered item in a plain list, renumber the
19032 ordered list.
19034 - If the cursor is on a checkbox, toggle it.
19036 - If the cursor is on a code block, evaluate it. The variable
19037 `org-confirm-babel-evaluate' can be used to control prompting
19038 before code block evaluation, by default every code block
19039 evaluation requires confirmation. Code block evaluation can be
19040 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19041 (interactive "P")
19042 (let ((org-enable-table-editor t))
19043 (cond
19044 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19045 org-occur-highlights
19046 org-latex-fragment-image-overlays)
19047 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19048 (org-remove-occur-highlights)
19049 (org-remove-latex-fragment-image-overlays)
19050 (message "Temporary highlights/overlays removed from current buffer"))
19051 ((and (local-variable-p 'org-finish-function (current-buffer))
19052 (fboundp org-finish-function))
19053 (funcall org-finish-function))
19054 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19055 ((org-in-regexp org-ts-regexp-both)
19056 (org-timestamp-change 0 'day))
19057 ((or (looking-at org-property-start-re)
19058 (org-at-property-p))
19059 (call-interactively 'org-property-action))
19060 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19061 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19062 (or (org-at-heading-p) (org-at-item-p)))
19063 (call-interactively 'org-update-statistics-cookies))
19064 ((org-at-heading-p) (call-interactively 'org-set-tags))
19065 ((org-at-table.el-p)
19066 (message "Use C-c ' to edit table.el tables"))
19067 ((org-at-table-p)
19068 (org-table-maybe-eval-formula)
19069 (if arg
19070 (call-interactively 'org-table-recalculate)
19071 (org-table-maybe-recalculate-line))
19072 (call-interactively 'org-table-align)
19073 (orgtbl-send-table 'maybe))
19074 ((or (org-footnote-at-reference-p)
19075 (org-footnote-at-definition-p))
19076 (call-interactively 'org-footnote-action))
19077 ((org-at-item-checkbox-p)
19078 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19079 ;; list only if at top item.
19080 (let* ((cbox (match-string 1))
19081 (struct (org-list-struct))
19082 (old-struct (copy-tree struct))
19083 (parents (org-list-parents-alist struct))
19084 (orderedp (org-entry-get nil "ORDERED"))
19085 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19086 block-item)
19087 ;; Use a light version of `org-toggle-checkbox' to avoid
19088 ;; computing list structure twice.
19089 (let ((new-box (cond
19090 ((equal arg '(16)) "[-]")
19091 ((equal arg '(4)) nil)
19092 ((equal "[X]" cbox) "[ ]")
19093 (t "[X]"))))
19094 (if (and firstp arg)
19095 ;; If at first item of sub-list, remove check-box from
19096 ;; every item at the same level.
19097 (mapc
19098 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19099 (org-list-get-all-items
19100 (point-at-bol) struct (org-list-prevs-alist struct)))
19101 (org-list-set-checkbox (point-at-bol) struct new-box)))
19102 ;; Replicate `org-list-write-struct', while grabbing a return
19103 ;; value from `org-list-struct-fix-box'.
19104 (org-list-struct-fix-ind struct parents 2)
19105 (org-list-struct-fix-item-end struct)
19106 (let ((prevs (org-list-prevs-alist struct)))
19107 (org-list-struct-fix-bul struct prevs)
19108 (org-list-struct-fix-ind struct parents)
19109 (setq block-item
19110 (org-list-struct-fix-box struct parents prevs orderedp)))
19111 (org-list-struct-apply-struct struct old-struct)
19112 (org-update-checkbox-count-maybe)
19113 (when block-item
19114 (message
19115 "Checkboxes were removed due to unchecked box at line %d"
19116 (org-current-line block-item)))
19117 (when firstp (org-list-send-list 'maybe))))
19118 ((org-at-item-p)
19119 ;; Cursor at an item: repair list. Do checkbox related actions
19120 ;; only if function was called with an argument. Send list only
19121 ;; if at top item.
19122 (let* ((struct (org-list-struct))
19123 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19124 old-struct)
19125 (when arg
19126 (setq old-struct (copy-tree struct))
19127 (if firstp
19128 ;; If at first item of sub-list, add check-box to every
19129 ;; item at the same level.
19130 (mapc
19131 (lambda (pos)
19132 (unless (org-list-get-checkbox pos struct)
19133 (org-list-set-checkbox pos struct "[ ]")))
19134 (org-list-get-all-items
19135 (point-at-bol) struct (org-list-prevs-alist struct)))
19136 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19137 (org-list-write-struct
19138 struct (org-list-parents-alist struct) old-struct)
19139 (when arg (org-update-checkbox-count-maybe))
19140 (when firstp (org-list-send-list 'maybe))))
19141 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19142 ;; Dynamic block
19143 (beginning-of-line 1)
19144 (save-excursion (org-update-dblock)))
19145 ((save-excursion
19146 (let ((case-fold-search t))
19147 (beginning-of-line 1)
19148 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19149 (cond
19150 ((or (equal (match-string 1) "TBLFM")
19151 (equal (match-string 1) "tblfm"))
19152 ;; Recalculate the table before this line
19153 (save-excursion
19154 (beginning-of-line 1)
19155 (skip-chars-backward " \r\n\t")
19156 (if (org-at-table-p)
19157 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19159 (let ((org-inhibit-startup-visibility-stuff t)
19160 (org-startup-align-all-tables nil))
19161 (when (boundp 'org-table-coordinate-overlays)
19162 (mapc 'delete-overlay org-table-coordinate-overlays)
19163 (setq org-table-coordinate-overlays nil))
19164 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19165 (message "Local setup has been refreshed"))))
19166 ((org-clock-update-time-maybe))
19168 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19169 (error "C-c C-c can do nothing useful at this location"))))))
19171 (defun org-mode-restart ()
19172 "Restart Org-mode, to scan again for special lines.
19173 Also updates the keyword regular expressions."
19174 (interactive)
19175 (org-mode)
19176 (message "Org-mode restarted"))
19178 (defun org-kill-note-or-show-branches ()
19179 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19180 (interactive)
19181 (if (not org-finish-function)
19182 (progn
19183 (hide-subtree)
19184 (call-interactively 'show-branches))
19185 (let ((org-note-abort t))
19186 (funcall org-finish-function))))
19188 (defun org-return (&optional indent)
19189 "Goto next table row or insert a newline.
19190 Calls `org-table-next-row' or `newline', depending on context.
19191 See the individual commands for more information."
19192 (interactive)
19193 (let (org-ts-what)
19194 (cond
19195 ((or (bobp) (org-in-src-block-p))
19196 (if indent (newline-and-indent) (newline)))
19197 ((org-at-table-p)
19198 (org-table-justify-field-maybe)
19199 (call-interactively 'org-table-next-row))
19200 ;; when `newline-and-indent' is called within a list, make sure
19201 ;; text moved stays inside the item.
19202 ((and (org-in-item-p) indent)
19203 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19204 (progn
19205 (save-match-data (newline))
19206 (org-indent-line-to (length (match-string 0))))
19207 (let ((ind (org-get-indentation)))
19208 (newline)
19209 (if (org-looking-back org-list-end-re)
19210 (org-indent-line)
19211 (org-indent-line-to ind)))))
19212 ((and org-return-follows-link
19213 (org-at-timestamp-p t)
19214 (not (eq org-ts-what 'after)))
19215 (org-follow-timestamp-link))
19216 ((and org-return-follows-link
19217 (let ((tprop (get-text-property (point) 'face)))
19218 (or (eq tprop 'org-link)
19219 (and (listp tprop) (memq 'org-link tprop)))))
19220 (call-interactively 'org-open-at-point))
19221 ((and (org-at-heading-p)
19222 (looking-at
19223 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19224 (org-show-entry)
19225 (end-of-line 1)
19226 (newline))
19227 (t (if indent (newline-and-indent) (newline))))))
19229 (defun org-return-indent ()
19230 "Goto next table row or insert a newline and indent.
19231 Calls `org-table-next-row' or `newline-and-indent', depending on
19232 context. See the individual commands for more information."
19233 (interactive)
19234 (org-return t))
19236 (defun org-ctrl-c-star ()
19237 "Compute table, or change heading status of lines.
19238 Calls `org-table-recalculate' or `org-toggle-heading',
19239 depending on context."
19240 (interactive)
19241 (cond
19242 ((org-at-table-p)
19243 (call-interactively 'org-table-recalculate))
19245 ;; Convert all lines in region to list items
19246 (call-interactively 'org-toggle-heading))))
19248 (defun org-ctrl-c-minus ()
19249 "Insert separator line in table or modify bullet status of line.
19250 Also turns a plain line or a region of lines into list items.
19251 Calls `org-table-insert-hline', `org-toggle-item', or
19252 `org-cycle-list-bullet', depending on context."
19253 (interactive)
19254 (cond
19255 ((org-at-table-p)
19256 (call-interactively 'org-table-insert-hline))
19257 ((org-region-active-p)
19258 (call-interactively 'org-toggle-item))
19259 ((org-in-item-p)
19260 (call-interactively 'org-cycle-list-bullet))
19262 (call-interactively 'org-toggle-item))))
19264 (defun org-toggle-item (arg)
19265 "Convert headings or normal lines to items, items to normal lines.
19266 If there is no active region, only the current line is considered.
19268 If the first non blank line in the region is an headline, convert
19269 all headlines to items, shifting text accordingly.
19271 If it is an item, convert all items to normal lines.
19273 If it is normal text, change region into an item. With a prefix
19274 argument ARG, change each line in region into an item."
19275 (interactive "P")
19276 (let ((shift-text
19277 (function
19278 ;; Shift text in current section to IND, from point to END.
19279 ;; The function leaves point to END line.
19280 (lambda (ind end)
19281 (let ((min-i 1000) (end (copy-marker end)))
19282 ;; First determine the minimum indentation (MIN-I) of
19283 ;; the text.
19284 (save-excursion
19285 (catch 'exit
19286 (while (< (point) end)
19287 (let ((i (org-get-indentation)))
19288 (cond
19289 ;; Skip blank lines and inline tasks.
19290 ((looking-at "^[ \t]*$"))
19291 ((looking-at org-outline-regexp-bol))
19292 ;; We can't find less than 0 indentation.
19293 ((zerop i) (throw 'exit (setq min-i 0)))
19294 ((< i min-i) (setq min-i i))))
19295 (forward-line))))
19296 ;; Then indent each line so that a line indented to
19297 ;; MIN-I becomes indented to IND. Ignore blank lines
19298 ;; and inline tasks in the process.
19299 (let ((delta (- ind min-i)))
19300 (while (< (point) end)
19301 (unless (or (looking-at "^[ \t]*$")
19302 (looking-at org-outline-regexp-bol))
19303 (org-indent-line-to (+ (org-get-indentation) delta)))
19304 (forward-line)))))))
19305 (skip-blanks
19306 (function
19307 ;; Return beginning of first non-blank line, starting from
19308 ;; line at POS.
19309 (lambda (pos)
19310 (save-excursion
19311 (goto-char pos)
19312 (skip-chars-forward " \r\t\n")
19313 (point-at-bol)))))
19314 beg end)
19315 ;; Determine boundaries of changes.
19316 (if (org-region-active-p)
19317 (setq beg (funcall skip-blanks (region-beginning))
19318 end (copy-marker (region-end)))
19319 (setq beg (funcall skip-blanks (point-at-bol))
19320 end (copy-marker (point-at-eol))))
19321 ;; Depending on the starting line, choose an action on the text
19322 ;; between BEG and END.
19323 (org-with-limited-levels
19324 (save-excursion
19325 (goto-char beg)
19326 (cond
19327 ;; Case 1. Start at an item: de-itemize. Note that it only
19328 ;; happens when a region is active: `org-ctrl-c-minus'
19329 ;; would call `org-cycle-list-bullet' otherwise.
19330 ((org-at-item-p)
19331 (while (< (point) end)
19332 (when (org-at-item-p)
19333 (skip-chars-forward " \t")
19334 (delete-region (point) (match-end 0)))
19335 (forward-line)))
19336 ;; Case 2. Start at an heading: convert to items.
19337 ((org-at-heading-p)
19338 (let* ((bul (org-list-bullet-string "-"))
19339 (bul-len (length bul))
19340 ;; Indentation of the first heading. It should be
19341 ;; relative to the indentation of its parent, if any.
19342 (start-ind (save-excursion
19343 (cond
19344 ((not org-adapt-indentation) 0)
19345 ((not (outline-previous-heading)) 0)
19346 (t (length (match-string 0))))))
19347 ;; Level of first heading. Further headings will be
19348 ;; compared to it to determine hierarchy in the list.
19349 (ref-level (org-reduced-level (org-outline-level))))
19350 (while (< (point) end)
19351 (let* ((level (org-reduced-level (org-outline-level)))
19352 (delta (max 0 (- level ref-level))))
19353 ;; If current headline is less indented than the first
19354 ;; one, set it as reference, in order to preserve
19355 ;; subtrees.
19356 (when (< level ref-level) (setq ref-level level))
19357 (replace-match bul t t)
19358 (org-indent-line-to (+ start-ind (* delta bul-len)))
19359 ;; Ensure all text down to END (or SECTION-END) belongs
19360 ;; to the newly created item.
19361 (let ((section-end (save-excursion
19362 (or (outline-next-heading) (point)))))
19363 (forward-line)
19364 (funcall shift-text
19365 (+ start-ind (* (1+ delta) bul-len))
19366 (min end section-end)))))))
19367 ;; Case 3. Normal line with ARG: turn each non-item line into
19368 ;; an item.
19369 (arg
19370 (while (< (point) end)
19371 (unless (or (org-at-heading-p) (org-at-item-p))
19372 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19373 (replace-match
19374 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19375 (forward-line)))
19376 ;; Case 4. Normal line without ARG: make the first line of
19377 ;; region an item, and shift indentation of others
19378 ;; lines to set them as item's body.
19379 (t (let* ((bul (org-list-bullet-string "-"))
19380 (bul-len (length bul))
19381 (ref-ind (org-get-indentation)))
19382 (skip-chars-forward " \t")
19383 (insert bul)
19384 (forward-line)
19385 (while (< (point) end)
19386 ;; Ensure that lines less indented than first one
19387 ;; still get included in item body.
19388 (funcall shift-text
19389 (+ ref-ind bul-len)
19390 (min end (save-excursion (or (outline-next-heading)
19391 (point)))))
19392 (forward-line)))))))))
19394 (defun org-toggle-heading (&optional nstars)
19395 "Convert headings to normal text, or items or text to headings.
19396 If there is no active region, only the current line is considered.
19398 With a \\[universal-argument] prefix, convert the whole list at
19399 point into heading.
19401 In a region:
19403 - If the first non blank line is an headline, remove the stars
19404 from all headlines in the region.
19406 - If it is a normal line turn each and every normal line (i.e. not an
19407 heading or an item) in the region into a heading.
19409 - If it is a plain list item, turn all plain list items into headings.
19411 When converting a line into a heading, the number of stars is chosen
19412 such that the lines become children of the current entry. However,
19413 when a prefix argument is given, its value determines the number of
19414 stars to add."
19415 (interactive "P")
19416 (let ((skip-blanks
19417 (function
19418 ;; Return beginning of first non-blank line, starting from
19419 ;; line at POS.
19420 (lambda (pos)
19421 (save-excursion
19422 (goto-char pos)
19423 (while (org-at-comment-p) (forward-line))
19424 (skip-chars-forward " \r\t\n")
19425 (point-at-bol)))))
19426 beg end toggled)
19427 ;; Determine boundaries of changes. If a universal prefix has
19428 ;; been given, put the list in a region. If region ends at a bol,
19429 ;; do not consider the last line to be in the region.
19431 (when (and current-prefix-arg (org-at-item-p))
19432 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19433 (org-mark-element))
19435 (if (org-region-active-p)
19436 (setq beg (funcall skip-blanks (region-beginning))
19437 end (copy-marker (save-excursion
19438 (goto-char (region-end))
19439 (if (bolp) (point) (point-at-eol)))))
19440 (setq beg (funcall skip-blanks (point-at-bol))
19441 end (copy-marker (point-at-eol))))
19442 ;; Ensure inline tasks don't count as headings.
19443 (org-with-limited-levels
19444 (save-excursion
19445 (goto-char beg)
19446 (cond
19447 ;; Case 1. Started at an heading: de-star headings.
19448 ((org-at-heading-p)
19449 (while (< (point) end)
19450 (when (org-at-heading-p t)
19451 (looking-at org-outline-regexp) (replace-match "")
19452 (setq toggled t))
19453 (forward-line)))
19454 ;; Case 2. Started at an item: change items into headlines.
19455 ;; One star will be added by `org-list-to-subtree'.
19456 ((org-at-item-p)
19457 (let* ((stars (make-string
19458 (if nstars
19459 ;; subtract the star that will be added again by
19460 ;; `org-list-to-subtree'
19461 (1- (prefix-numeric-value current-prefix-arg))
19462 (or (org-current-level) 0))
19463 ?*))
19464 (add-stars
19465 (cond (nstars "") ; stars from prefix only
19466 ((equal stars "") "") ; before first heading
19467 (org-odd-levels-only "*") ; inside heading, odd
19468 (t "")))) ; inside heading, oddeven
19469 (while (< (point) end)
19470 (when (org-at-item-p)
19471 ;; Pay attention to cases when region ends before list.
19472 (let* ((struct (org-list-struct))
19473 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19474 (save-restriction
19475 (narrow-to-region (point) list-end)
19476 (insert
19477 (org-list-to-subtree
19478 (org-list-parse-list t)
19479 '(:istart (concat stars add-stars (funcall get-stars depth))
19480 :icount (concat stars add-stars (funcall get-stars depth)))))))
19481 (setq toggled t))
19482 (forward-line))))
19483 ;; Case 3. Started at normal text: make every line an heading,
19484 ;; skipping headlines and items.
19485 (t (let* ((stars (make-string
19486 (if nstars
19487 (prefix-numeric-value current-prefix-arg)
19488 (or (org-current-level) 0))
19489 ?*))
19490 (add-stars
19491 (cond (nstars "") ; stars from prefix only
19492 ((equal stars "") "*") ; before first heading
19493 (org-odd-levels-only "**") ; inside heading, odd
19494 (t "*"))) ; inside heading, oddeven
19495 (rpl (concat stars add-stars " ")))
19496 (while (< (point) end)
19497 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19498 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19499 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19500 (forward-line)))))))
19501 (unless toggled (message "Cannot toggle heading from here"))))
19503 (defun org-meta-return (&optional arg)
19504 "Insert a new heading or wrap a region in a table.
19505 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19506 See the individual commands for more information."
19507 (interactive "P")
19508 (cond
19509 ((run-hook-with-args-until-success 'org-metareturn-hook))
19510 ((or (org-at-drawer-p) (org-at-property-p))
19511 (newline-and-indent))
19512 ((org-at-table-p)
19513 (call-interactively 'org-table-wrap-region))
19514 (t (call-interactively 'org-insert-heading))))
19516 ;;; Menu entries
19518 (defsubst org-in-subtree-not-table-p ()
19519 "Are we in a subtree and not in a table?"
19520 (and (not (org-before-first-heading-p))
19521 (not (org-at-table-p))))
19523 ;; Define the Org-mode menus
19524 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19525 '("Tbl"
19526 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19527 ["Next Field" org-cycle (org-at-table-p)]
19528 ["Previous Field" org-shifttab (org-at-table-p)]
19529 ["Next Row" org-return (org-at-table-p)]
19530 "--"
19531 ["Blank Field" org-table-blank-field (org-at-table-p)]
19532 ["Edit Field" org-table-edit-field (org-at-table-p)]
19533 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19534 "--"
19535 ("Column"
19536 ["Move Column Left" org-metaleft (org-at-table-p)]
19537 ["Move Column Right" org-metaright (org-at-table-p)]
19538 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19539 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19540 ("Row"
19541 ["Move Row Up" org-metaup (org-at-table-p)]
19542 ["Move Row Down" org-metadown (org-at-table-p)]
19543 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19544 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19545 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19546 "--"
19547 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19548 ("Rectangle"
19549 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19550 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19551 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19552 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19553 "--"
19554 ("Calculate"
19555 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19556 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19557 ["Edit Formulas" org-edit-special (org-at-table-p)]
19558 "--"
19559 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19560 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19561 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19562 "--"
19563 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19564 "--"
19565 ["Sum Column/Rectangle" org-table-sum
19566 (or (org-at-table-p) (org-region-active-p))]
19567 ["Which Column?" org-table-current-column (org-at-table-p)])
19568 ["Debug Formulas"
19569 org-table-toggle-formula-debugger
19570 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19571 ["Show Col/Row Numbers"
19572 org-table-toggle-coordinate-overlays
19573 :style toggle
19574 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19575 "--"
19576 ["Create" org-table-create (and (not (org-at-table-p))
19577 org-enable-table-editor)]
19578 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19579 ["Import from File" org-table-import (not (org-at-table-p))]
19580 ["Export to File" org-table-export (org-at-table-p)]
19581 "--"
19582 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19584 (easy-menu-define org-org-menu org-mode-map "Org menu"
19585 '("Org"
19586 ("Show/Hide"
19587 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19588 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19589 ["Sparse Tree..." org-sparse-tree t]
19590 ["Reveal Context" org-reveal t]
19591 ["Show All" show-all t]
19592 "--"
19593 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19594 "--"
19595 ["New Heading" org-insert-heading t]
19596 ("Navigate Headings"
19597 ["Up" outline-up-heading t]
19598 ["Next" outline-next-visible-heading t]
19599 ["Previous" outline-previous-visible-heading t]
19600 ["Next Same Level" outline-forward-same-level t]
19601 ["Previous Same Level" outline-backward-same-level t]
19602 "--"
19603 ["Jump" org-goto t])
19604 ("Edit Structure"
19605 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
19606 "--"
19607 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
19608 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
19609 "--"
19610 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
19611 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
19612 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19613 "--"
19614 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19615 "--"
19616 ["Copy visible text" org-copy-visible t]
19617 "--"
19618 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
19619 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
19620 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
19621 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
19622 "--"
19623 ["Sort Region/Children" org-sort t]
19624 "--"
19625 ["Convert to odd levels" org-convert-to-odd-levels t]
19626 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19627 ("Editing"
19628 ["Emphasis..." org-emphasize t]
19629 ["Edit Source Example" org-edit-special t]
19630 "--"
19631 ["Footnote new/jump" org-footnote-action t]
19632 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19633 ("Archive"
19634 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
19635 "--"
19636 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
19637 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
19638 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
19640 "--"
19641 ("Hyperlinks"
19642 ["Store Link (Global)" org-store-link t]
19643 ["Find existing link to here" org-occur-link-in-agenda-files t]
19644 ["Insert Link" org-insert-link t]
19645 ["Follow Link" org-open-at-point t]
19646 "--"
19647 ["Next link" org-next-link t]
19648 ["Previous link" org-previous-link t]
19649 "--"
19650 ["Descriptive Links"
19651 org-toggle-link-display
19652 :style radio
19653 :selected org-descriptive-links
19655 ["Literal Links"
19656 org-toggle-link-display
19657 :style radio
19658 :selected (not org-descriptive-links)])
19659 "--"
19660 ("TODO Lists"
19661 ["TODO/DONE/-" org-todo t]
19662 ("Select keyword"
19663 ["Next keyword" org-shiftright (org-at-heading-p)]
19664 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19665 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19666 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19667 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19668 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19669 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19670 "--"
19671 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19672 :selected org-enforce-todo-dependencies :style toggle :active t]
19673 "Settings for tree at point"
19674 ["Do Children sequentially" org-toggle-ordered-property :style radio
19675 :selected (org-entry-get nil "ORDERED")
19676 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19677 ["Do Children parallel" org-toggle-ordered-property :style radio
19678 :selected (not (org-entry-get nil "ORDERED"))
19679 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19680 "--"
19681 ["Set Priority" org-priority t]
19682 ["Priority Up" org-shiftup t]
19683 ["Priority Down" org-shiftdown t]
19684 "--"
19685 ["Get news from all feeds" org-feed-update-all t]
19686 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19687 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19688 ("TAGS and Properties"
19689 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
19690 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19691 "--"
19692 ["Set property" org-set-property (not (org-before-first-heading-p))]
19693 ["Column view of properties" org-columns t]
19694 ["Insert Column View DBlock" org-insert-columns-dblock t])
19695 ("Dates and Scheduling"
19696 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
19697 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
19698 ("Change Date"
19699 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
19700 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
19701 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
19702 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
19703 ["Compute Time Range" org-evaluate-time-range t]
19704 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
19705 ["Deadline" org-deadline (not (org-before-first-heading-p))]
19706 "--"
19707 ["Custom time format" org-toggle-time-stamp-overlays
19708 :style radio :selected org-display-custom-times]
19709 "--"
19710 ["Goto Calendar" org-goto-calendar t]
19711 ["Date from Calendar" org-date-from-calendar t]
19712 "--"
19713 ["Start/Restart Timer" org-timer-start t]
19714 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19715 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19716 ["Insert Timer String" org-timer t]
19717 ["Insert Timer Item" org-timer-item t])
19718 ("Logging work"
19719 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19720 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19721 ["Clock out" org-clock-out t]
19722 ["Clock cancel" org-clock-cancel t]
19723 "--"
19724 ["Mark as default task" org-clock-mark-default-task t]
19725 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19726 ["Goto running clock" org-clock-goto t]
19727 "--"
19728 ["Display times" org-clock-display t]
19729 ["Create clock table" org-clock-report t]
19730 "--"
19731 ["Record DONE time"
19732 (progn (setq org-log-done (not org-log-done))
19733 (message "Switching to %s will %s record a timestamp"
19734 (car org-done-keywords)
19735 (if org-log-done "automatically" "not")))
19736 :style toggle :selected org-log-done])
19737 "--"
19738 ["Agenda Command..." org-agenda t]
19739 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19740 ("File List for Agenda")
19741 ("Special views current file"
19742 ["TODO Tree" org-show-todo-tree t]
19743 ["Check Deadlines" org-check-deadlines t]
19744 ["Timeline" org-timeline t]
19745 ["Tags/Property tree" org-match-sparse-tree t])
19746 "--"
19747 ["Export/Publish..." org-export t]
19748 ("LaTeX"
19749 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19750 :selected org-cdlatex-mode]
19751 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19752 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19753 ["Modify math symbol" org-cdlatex-math-modify
19754 (org-inside-LaTeX-fragment-p)]
19755 ["Insert citation" org-reftex-citation t]
19756 "--"
19757 ["Template for BEAMER" (progn (require 'org-beamer)
19758 (org-insert-beamer-options-template)) t])
19759 "--"
19760 ("MobileOrg"
19761 ["Push Files and Views" org-mobile-push t]
19762 ["Get Captured and Flagged" org-mobile-pull t]
19763 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19764 "--"
19765 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19766 "--"
19767 ("Documentation"
19768 ["Show Version" org-version t]
19769 ["Info Documentation" org-info t])
19770 ("Customize"
19771 ["Browse Org Group" org-customize t]
19772 "--"
19773 ["Expand This Menu" org-create-customize-menu
19774 (fboundp 'customize-menu-create)])
19775 ["Send bug report" org-submit-bug-report t]
19776 "--"
19777 ("Refresh/Reload"
19778 ["Refresh setup current buffer" org-mode-restart t]
19779 ["Reload Org (after update)" org-reload t]
19780 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19783 (defun org-info (&optional node)
19784 "Read documentation for Org-mode in the info system.
19785 With optional NODE, go directly to that node."
19786 (interactive)
19787 (info (format "(org)%s" (or node ""))))
19789 ;;;###autoload
19790 (defun org-submit-bug-report ()
19791 "Submit a bug report on Org-mode via mail.
19793 Don't hesitate to report any problems or inaccurate documentation.
19795 If you don't have setup sending mail from (X)Emacs, please copy the
19796 output buffer into your mail program, as it gives us important
19797 information about your Org-mode version and configuration."
19798 (interactive)
19799 (require 'reporter)
19800 (org-load-modules-maybe)
19801 (org-require-autoloaded-modules)
19802 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19803 (reporter-submit-bug-report
19804 "emacs-orgmode@gnu.org"
19805 (org-version nil 'full)
19806 (let (list)
19807 (save-window-excursion
19808 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19809 (delete-other-windows)
19810 (erase-buffer)
19811 (insert "You are about to submit a bug report to the Org-mode mailing list.
19813 We would like to add your full Org-mode and Outline configuration to the
19814 bug report. This greatly simplifies the work of the maintainer and
19815 other experts on the mailing list.
19817 HOWEVER, some variables you have customized may contain private
19818 information. The names of customers, colleagues, or friends, might
19819 appear in the form of file names, tags, todo states, or search strings.
19820 If you answer yes to the prompt, you might want to check and remove
19821 such private information before sending the email.")
19822 (add-text-properties (point-min) (point-max) '(face org-warning))
19823 (when (yes-or-no-p "Include your Org-mode configuration ")
19824 (mapatoms
19825 (lambda (v)
19826 (and (boundp v)
19827 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19828 (or (and (symbol-value v)
19829 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19830 (and
19831 (get v 'custom-type) (get v 'standard-value)
19832 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19833 (push v list)))))
19834 (kill-buffer (get-buffer "*Warn about privacy*"))
19835 list))
19836 nil nil
19837 "Remember to cover the basics, that is, what you expected to happen and
19838 what in fact did happen. You don't know how to make a good report? See
19840 http://orgmode.org/manual/Feedback.html#Feedback
19842 Your bug report will be posted to the Org-mode mailing list.
19843 ------------------------------------------------------------------------")
19844 (save-excursion
19845 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19846 (replace-match "\\1Bug: \\3 [\\2]")))))
19849 (defun org-install-agenda-files-menu ()
19850 (let ((bl (buffer-list)))
19851 (save-excursion
19852 (while bl
19853 (set-buffer (pop bl))
19854 (if (derived-mode-p 'org-mode) (setq bl nil)))
19855 (when (derived-mode-p 'org-mode)
19856 (easy-menu-change
19857 '("Org") "File List for Agenda"
19858 (append
19859 (list
19860 ["Edit File List" (org-edit-agenda-file-list) t]
19861 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19862 ["Remove Current File from List" org-remove-file t]
19863 ["Cycle through agenda files" org-cycle-agenda-files t]
19864 ["Occur in all agenda files" org-occur-in-agenda-files t]
19865 "--")
19866 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19868 ;;;; Documentation
19870 (defun org-require-autoloaded-modules ()
19871 (interactive)
19872 (mapc 'require
19873 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19874 org-docbook org-exp org-html org-icalendar
19875 org-id org-latex
19876 org-publish org-remember org-table
19877 org-timer org-xoxo)))
19879 ;;;###autoload
19880 (defun org-reload (&optional uncompiled)
19881 "Reload all org lisp files.
19882 With prefix arg UNCOMPILED, load the uncompiled versions."
19883 (interactive "P")
19884 (require 'find-func)
19885 (let* ((file-re "^org\\(-.*\\)?\\.el")
19886 (dir-org (file-name-directory (org-find-library-dir "org")))
19887 (dir-org-contrib (ignore-errors
19888 (file-name-directory
19889 (org-find-library-dir "org-contribdir"))))
19890 (babel-files
19891 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19892 (append (list nil "comint" "eval" "exp" "keys"
19893 "lob" "ref" "table" "tangle")
19894 (delq nil
19895 (mapcar
19896 (lambda (lang)
19897 (when (cdr lang) (symbol-name (car lang))))
19898 org-babel-load-languages)))))
19899 (files
19900 (append babel-files
19901 (and dir-org-contrib
19902 (directory-files dir-org-contrib t file-re))
19903 (directory-files dir-org t file-re)))
19904 (remove-re (concat (if (featurep 'xemacs)
19905 "org-colview" "org-colview-xemacs")
19906 "\\'")))
19907 (setq files (mapcar 'file-name-sans-extension files))
19908 (setq files (mapcar
19909 (lambda (x) (if (string-match remove-re x) nil x))
19910 files))
19911 (setq files (delq nil files))
19912 (mapc
19913 (lambda (f)
19914 (when (featurep (intern (file-name-nondirectory f)))
19915 (if (and (not uncompiled)
19916 (file-exists-p (concat f ".elc")))
19917 (load (concat f ".elc") nil nil 'nosuffix)
19918 (load (concat f ".el") nil nil 'nosuffix))))
19919 files)
19920 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
19921 (org-version nil 'full 'message))
19923 ;;;###autoload
19924 (defun org-customize ()
19925 "Call the customize function with org as argument."
19926 (interactive)
19927 (org-load-modules-maybe)
19928 (org-require-autoloaded-modules)
19929 (customize-browse 'org))
19931 (defun org-create-customize-menu ()
19932 "Create a full customization menu for Org-mode, insert it into the menu."
19933 (interactive)
19934 (org-load-modules-maybe)
19935 (org-require-autoloaded-modules)
19936 (if (fboundp 'customize-menu-create)
19937 (progn
19938 (easy-menu-change
19939 '("Org") "Customize"
19940 `(["Browse Org group" org-customize t]
19941 "--"
19942 ,(customize-menu-create 'org)
19943 ["Set" Custom-set t]
19944 ["Save" Custom-save t]
19945 ["Reset to Current" Custom-reset-current t]
19946 ["Reset to Saved" Custom-reset-saved t]
19947 ["Reset to Standard Settings" Custom-reset-standard t]))
19948 (message "\"Org\"-menu now contains full customization menu"))
19949 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19951 ;;;; Miscellaneous stuff
19953 ;;; Generally useful functions
19955 (defun org-get-at-bol (property)
19956 "Get text property PROPERTY at beginning of line."
19957 (get-text-property (point-at-bol) property))
19959 (defun org-find-text-property-in-string (prop s)
19960 "Return the first non-nil value of property PROP in string S."
19961 (or (get-text-property 0 prop s)
19962 (get-text-property (or (next-single-property-change 0 prop s) 0)
19963 prop s)))
19965 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19966 "Display the given MESSAGE as a warning."
19967 (if (fboundp 'display-warning)
19968 (display-warning 'org message
19969 (if (featurep 'xemacs) 'warning :warning))
19970 (let ((buf (get-buffer-create "*Org warnings*")))
19971 (with-current-buffer buf
19972 (goto-char (point-max))
19973 (insert "Warning (Org): " message)
19974 (unless (bolp)
19975 (newline)))
19976 (display-buffer buf)
19977 (sit-for 0))))
19979 (defun org-eval (form)
19980 "Eval FORM and return result."
19981 (condition-case error
19982 (eval form)
19983 (error (format "%%![Error: %s]" error))))
19985 (defun org-in-clocktable-p ()
19986 "Check if the cursor is in a clocktable."
19987 (let ((pos (point)) start)
19988 (save-excursion
19989 (end-of-line 1)
19990 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
19991 (setq start (match-beginning 0))
19992 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
19993 (>= (match-end 0) pos)
19994 start))))
19996 (defun org-in-commented-line ()
19997 "Is point in a line starting with `#'?"
19998 (equal (char-after (point-at-bol)) ?#))
20000 (defun org-in-indented-comment-line ()
20001 "Is point in a line starting with `#' after some white space?"
20002 (save-excursion
20003 (save-match-data
20004 (goto-char (point-at-bol))
20005 (looking-at "[ \t]*#"))))
20007 (defun org-in-verbatim-emphasis ()
20008 (save-match-data
20009 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20011 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20012 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20013 (if (and marker (marker-buffer marker)
20014 (buffer-live-p (marker-buffer marker)))
20015 (progn
20016 (org-pop-to-buffer-same-window (marker-buffer marker))
20017 (if (or (> marker (point-max)) (< marker (point-min)))
20018 (widen))
20019 (goto-char marker)
20020 (org-show-context 'org-goto))
20021 (if bookmark
20022 (bookmark-jump bookmark)
20023 (error "Cannot find location"))))
20025 (defun org-quote-csv-field (s)
20026 "Quote field for inclusion in CSV material."
20027 (if (string-match "[\",]" s)
20028 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20031 (defun org-force-self-insert (N)
20032 "Needed to enforce self-insert under remapping."
20033 (interactive "p")
20034 (self-insert-command N))
20036 (defun org-string-width (s)
20037 "Compute width of string, ignoring invisible characters.
20038 This ignores character with invisibility property `org-link', and also
20039 characters with property `org-cwidth', because these will become invisible
20040 upon the next fontification round."
20041 (let (b l)
20042 (when (or (eq t buffer-invisibility-spec)
20043 (assq 'org-link buffer-invisibility-spec))
20044 (while (setq b (text-property-any 0 (length s)
20045 'invisible 'org-link s))
20046 (setq s (concat (substring s 0 b)
20047 (substring s (or (next-single-property-change
20048 b 'invisible s) (length s)))))))
20049 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20050 (setq s (concat (substring s 0 b)
20051 (substring s (or (next-single-property-change
20052 b 'org-cwidth s) (length s))))))
20053 (setq l (string-width s) b -1)
20054 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20055 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20058 (defun org-shorten-string (s maxlength)
20059 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20060 If the string is shorter or has length MAXLENGTH, just return the
20061 original string. If it is longer, the functions finds a space in the
20062 string, breaks this string off at that locations and adds three dots
20063 as ellipsis. Including the ellipsis, the string will not be longer
20064 than MAXLENGTH. If finding a good breaking point in the string does
20065 not work, the string is just chopped off in the middle of a word
20066 if necessary."
20067 (if (<= (length s) maxlength)
20069 (let* ((n (max (- maxlength 4) 1))
20070 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20071 (if (string-match re s)
20072 (concat (match-string 1 s) "...")
20073 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20075 (defun org-get-indentation (&optional line)
20076 "Get the indentation of the current line, interpreting tabs.
20077 When LINE is given, assume it represents a line and compute its indentation."
20078 (if line
20079 (if (string-match "^ *" (org-remove-tabs line))
20080 (match-end 0))
20081 (save-excursion
20082 (beginning-of-line 1)
20083 (skip-chars-forward " \t")
20084 (current-column))))
20086 (defun org-get-string-indentation (s)
20087 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20088 (let ((n -1) (i 0) (w tab-width) c)
20089 (catch 'exit
20090 (while (< (setq n (1+ n)) (length s))
20091 (setq c (aref s n))
20092 (cond ((= c ?\ ) (setq i (1+ i)))
20093 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20094 (t (throw 'exit t)))))
20097 (defun org-remove-tabs (s &optional width)
20098 "Replace tabulators in S with spaces.
20099 Assumes that s is a single line, starting in column 0."
20100 (setq width (or width tab-width))
20101 (while (string-match "\t" s)
20102 (setq s (replace-match
20103 (make-string
20104 (- (* width (/ (+ (match-beginning 0) width) width))
20105 (match-beginning 0)) ?\ )
20106 t t s)))
20109 (defun org-fix-indentation (line ind)
20110 "Fix indentation in LINE.
20111 IND is a cons cell with target and minimum indentation.
20112 If the current indentation in LINE is smaller than the minimum,
20113 leave it alone. If it is larger than ind, set it to the target."
20114 (let* ((l (org-remove-tabs line))
20115 (i (org-get-indentation l))
20116 (i1 (car ind)) (i2 (cdr ind)))
20117 (if (>= i i2) (setq l (substring line i2)))
20118 (if (> i1 0)
20119 (concat (make-string i1 ?\ ) l)
20120 l)))
20122 (defun org-remove-indentation (code &optional n)
20123 "Remove the maximum common indentation from the lines in CODE.
20124 N may optionally be the number of spaces to remove."
20125 (with-temp-buffer
20126 (insert code)
20127 (org-do-remove-indentation n)
20128 (buffer-string)))
20130 (defun org-do-remove-indentation (&optional n)
20131 "Remove the maximum common indentation from the buffer."
20132 (untabify (point-min) (point-max))
20133 (let ((min 10000) re)
20134 (if n
20135 (setq min n)
20136 (goto-char (point-min))
20137 (while (re-search-forward "^ *[^ \n]" nil t)
20138 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20139 (unless (or (= min 0) (= min 10000))
20140 (setq re (format "^ \\{%d\\}" min))
20141 (goto-char (point-min))
20142 (while (re-search-forward re nil t)
20143 (replace-match "")
20144 (end-of-line 1))
20145 min)))
20147 (defun org-fill-template (template alist)
20148 "Find each %key of ALIST in TEMPLATE and replace it."
20149 (let ((case-fold-search nil)
20150 entry key value)
20151 (setq alist (sort (copy-sequence alist)
20152 (lambda (a b) (< (length (car a)) (length (car b))))))
20153 (while (setq entry (pop alist))
20154 (setq template
20155 (replace-regexp-in-string
20156 (concat "%" (regexp-quote (car entry)))
20157 (or (cdr entry) "") template t t)))
20158 template))
20160 (defun org-base-buffer (buffer)
20161 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20162 (if (not buffer)
20163 buffer
20164 (or (buffer-base-buffer buffer)
20165 buffer)))
20167 (defun org-trim (s)
20168 "Remove whitespace at beginning and end of string."
20169 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20170 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20173 (defun org-wrap (string &optional width lines)
20174 "Wrap string to either a number of lines, or a width in characters.
20175 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20176 that costs. If there is a word longer than WIDTH, the text is actually
20177 wrapped to the length of that word.
20178 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20179 many lines, whatever width that takes.
20180 The return value is a list of lines, without newlines at the end."
20181 (let* ((words (org-split-string string "[ \t\n]+"))
20182 (maxword (apply 'max (mapcar 'org-string-width words)))
20183 w ll)
20184 (cond (width
20185 (org-do-wrap words (max maxword width)))
20186 (lines
20187 (setq w maxword)
20188 (setq ll (org-do-wrap words maxword))
20189 (if (<= (length ll) lines)
20191 (setq ll words)
20192 (while (> (length ll) lines)
20193 (setq w (1+ w))
20194 (setq ll (org-do-wrap words w)))
20195 ll))
20196 (t (error "Cannot wrap this")))))
20198 (defun org-do-wrap (words width)
20199 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20200 (let (lines line)
20201 (while words
20202 (setq line (pop words))
20203 (while (and words (< (+ (length line) (length (car words))) width))
20204 (setq line (concat line " " (pop words))))
20205 (setq lines (push line lines)))
20206 (nreverse lines)))
20208 (defun org-split-string (string &optional separators)
20209 "Splits STRING into substrings at SEPARATORS.
20210 No empty strings are returned if there are matches at the beginning
20211 and end of string."
20212 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20213 (start 0)
20214 notfirst
20215 (list nil))
20216 (while (and (string-match rexp string
20217 (if (and notfirst
20218 (= start (match-beginning 0))
20219 (< start (length string)))
20220 (1+ start) start))
20221 (< (match-beginning 0) (length string)))
20222 (setq notfirst t)
20223 (or (eq (match-beginning 0) 0)
20224 (and (eq (match-beginning 0) (match-end 0))
20225 (eq (match-beginning 0) start))
20226 (setq list
20227 (cons (substring string start (match-beginning 0))
20228 list)))
20229 (setq start (match-end 0)))
20230 (or (eq start (length string))
20231 (setq list
20232 (cons (substring string start)
20233 list)))
20234 (nreverse list)))
20236 (defun org-quote-vert (s)
20237 "Replace \"|\" with \"\\vert\"."
20238 (while (string-match "|" s)
20239 (setq s (replace-match "\\vert" t t s)))
20242 (defun org-uuidgen-p (s)
20243 "Is S an ID created by UUIDGEN?"
20244 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20246 (defun org-in-src-block-p (&optional inside)
20247 "Whether point is in a code source block.
20248 When INSIDE is non-nil, don't consider we are within a src block
20249 when point is at #+BEGIN_SRC or #+END_SRC."
20250 (let (ov)
20251 (or (when (setq ov (overlays-at (point)))
20252 (memq 'org-block-background
20253 (overlay-properties
20254 (car ov))))
20255 (and (not inside)
20256 (save-match-data
20257 (save-excursion
20258 (move-beginning-of-line 1)
20259 (looking-at ".*#\\+\\(BEGIN\\|END\\)_SRC")))))))
20261 (defun org-context ()
20262 "Return a list of contexts of the current cursor position.
20263 If several contexts apply, all are returned.
20264 Each context entry is a list with a symbol naming the context, and
20265 two positions indicating start and end of the context. Possible
20266 contexts are:
20268 :headline anywhere in a headline
20269 :headline-stars on the leading stars in a headline
20270 :todo-keyword on a TODO keyword (including DONE) in a headline
20271 :tags on the TAGS in a headline
20272 :priority on the priority cookie in a headline
20273 :item on the first line of a plain list item
20274 :item-bullet on the bullet/number of a plain list item
20275 :checkbox on the checkbox in a plain list item
20276 :table in an org-mode table
20277 :table-special on a special filed in a table
20278 :table-table in a table.el table
20279 :clocktable in a clocktable
20280 :src-block in a source block
20281 :link on a hyperlink
20282 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20283 :target on a <<target>>
20284 :radio-target on a <<<radio-target>>>
20285 :latex-fragment on a LaTeX fragment
20286 :latex-preview on a LaTeX fragment with overlaid preview image
20288 This function expects the position to be visible because it uses font-lock
20289 faces as a help to recognize the following contexts: :table-special, :link,
20290 and :keyword."
20291 (let* ((f (get-text-property (point) 'face))
20292 (faces (if (listp f) f (list f)))
20293 (case-fold-search t)
20294 (p (point)) clist o)
20295 ;; First the large context
20296 (cond
20297 ((org-at-heading-p t)
20298 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20299 (when (progn
20300 (beginning-of-line 1)
20301 (looking-at org-todo-line-tags-regexp))
20302 (push (org-point-in-group p 1 :headline-stars) clist)
20303 (push (org-point-in-group p 2 :todo-keyword) clist)
20304 (push (org-point-in-group p 4 :tags) clist))
20305 (goto-char p)
20306 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20307 (if (looking-at "\\[#[A-Z0-9]\\]")
20308 (push (org-point-in-group p 0 :priority) clist)))
20310 ((org-at-item-p)
20311 (push (org-point-in-group p 2 :item-bullet) clist)
20312 (push (list :item (point-at-bol)
20313 (save-excursion (org-end-of-item) (point)))
20314 clist)
20315 (and (org-at-item-checkbox-p)
20316 (push (org-point-in-group p 0 :checkbox) clist)))
20318 ((org-at-table-p)
20319 (push (list :table (org-table-begin) (org-table-end)) clist)
20320 (if (memq 'org-formula faces)
20321 (push (list :table-special
20322 (previous-single-property-change p 'face)
20323 (next-single-property-change p 'face)) clist)))
20324 ((org-at-table-p 'any)
20325 (push (list :table-table) clist)))
20326 (goto-char p)
20328 (let ((case-fold-search t))
20329 ;; New the "medium" contexts: clocktables, source blocks
20330 (cond ((org-in-clocktable-p)
20331 (push (list :clocktable
20332 (and (or (looking-at "#\\+BEGIN: clocktable")
20333 (search-backward "#+BEGIN: clocktable" nil t))
20334 (match-beginning 0))
20335 (and (re-search-forward "#\\+END:?" nil t)
20336 (match-end 0))) clist))
20337 ((org-in-src-block-p)
20338 (push (list :src-block
20339 (and (or (looking-at "#\\+BEGIN_SRC")
20340 (search-backward "#+BEGIN_SRC" nil t))
20341 (match-beginning 0))
20342 (and (search-forward "#+END_SRC" nil t)
20343 (match-beginning 0))) clist))))
20344 (goto-char p)
20346 ;; Now the small context
20347 (cond
20348 ((org-at-timestamp-p)
20349 (push (org-point-in-group p 0 :timestamp) clist))
20350 ((memq 'org-link faces)
20351 (push (list :link
20352 (previous-single-property-change p 'face)
20353 (next-single-property-change p 'face)) clist))
20354 ((memq 'org-special-keyword faces)
20355 (push (list :keyword
20356 (previous-single-property-change p 'face)
20357 (next-single-property-change p 'face)) clist))
20358 ((org-at-target-p)
20359 (push (org-point-in-group p 0 :target) clist)
20360 (goto-char (1- (match-beginning 0)))
20361 (if (looking-at org-radio-target-regexp)
20362 (push (org-point-in-group p 0 :radio-target) clist))
20363 (goto-char p))
20364 ((setq o (car (delq nil
20365 (mapcar
20366 (lambda (x)
20367 (if (memq x org-latex-fragment-image-overlays) x))
20368 (overlays-at (point))))))
20369 (push (list :latex-fragment
20370 (overlay-start o) (overlay-end o)) clist)
20371 (push (list :latex-preview
20372 (overlay-start o) (overlay-end o)) clist))
20373 ((org-inside-LaTeX-fragment-p)
20374 ;; FIXME: positions wrong.
20375 (push (list :latex-fragment (point) (point)) clist)))
20377 (setq clist (nreverse (delq nil clist)))
20378 clist))
20380 ;; FIXME: Compare with at-regexp-p Do we need both?
20381 (defun org-in-regexp (re &optional nlines visually)
20382 "Check if point is inside a match of regexp.
20383 Normally only the current line is checked, but you can include NLINES extra
20384 lines both before and after point into the search.
20385 If VISUALLY is set, require that the cursor is not after the match but
20386 really on, so that the block visually is on the match."
20387 (catch 'exit
20388 (let ((pos (point))
20389 (eol (point-at-eol (+ 1 (or nlines 0))))
20390 (inc (if visually 1 0)))
20391 (save-excursion
20392 (beginning-of-line (- 1 (or nlines 0)))
20393 (while (re-search-forward re eol t)
20394 (if (and (<= (match-beginning 0) pos)
20395 (>= (+ inc (match-end 0)) pos))
20396 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20398 (defun org-at-regexp-p (regexp)
20399 "Is point inside a match of REGEXP in the current line?"
20400 (catch 'exit
20401 (save-excursion
20402 (let ((pos (point)) (end (point-at-eol)))
20403 (beginning-of-line 1)
20404 (while (re-search-forward regexp end t)
20405 (if (and (<= (match-beginning 0) pos)
20406 (>= (match-end 0) pos))
20407 (throw 'exit t)))
20408 nil))))
20410 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20411 "Non-nil when point is between matches of START-RE and END-RE.
20413 Also return a non-nil value when point is on one of the matches.
20415 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20416 buffer positions. Default values are the positions of headlines
20417 surrounding the point.
20419 The functions returns a cons cell whose car (resp. cdr) is the
20420 position before START-RE (resp. after END-RE)."
20421 (save-match-data
20422 (let ((pos (point))
20423 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20424 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20425 beg end)
20426 (save-excursion
20427 ;; Point is on a block when on START-RE or if START-RE can be
20428 ;; found before it...
20429 (and (or (org-at-regexp-p start-re)
20430 (re-search-backward start-re limit-up t))
20431 (setq beg (match-beginning 0))
20432 ;; ... and END-RE after it...
20433 (goto-char (match-end 0))
20434 (re-search-forward end-re limit-down t)
20435 (> (setq end (match-end 0)) pos)
20436 ;; ... without another START-RE in-between.
20437 (goto-char (match-beginning 0))
20438 (not (re-search-backward start-re (1+ beg) t))
20439 ;; Return value.
20440 (cons beg end))))))
20442 (defun org-in-block-p (names)
20443 "Non-nil when point belongs to a block whose name belongs to NAMES.
20445 NAMES is a list of strings containing names of blocks.
20447 Return first block name matched, or nil. Beware that in case of
20448 nested blocks, the returned name may not belong to the closest
20449 block from point."
20450 (save-match-data
20451 (catch 'exit
20452 (let ((case-fold-search t)
20453 (lim-up (save-excursion (outline-previous-heading)))
20454 (lim-down (save-excursion (outline-next-heading))))
20455 (mapc (lambda (name)
20456 (let ((n (regexp-quote name)))
20457 (when (org-between-regexps-p
20458 (concat "^[ \t]*#\\+begin_" n)
20459 (concat "^[ \t]*#\\+end_" n)
20460 lim-up lim-down)
20461 (throw 'exit n))))
20462 names))
20463 nil)))
20465 (defun org-occur-in-agenda-files (regexp &optional nlines)
20466 "Call `multi-occur' with buffers for all agenda files."
20467 (interactive "sOrg-files matching: \np")
20468 (let* ((files (org-agenda-files))
20469 (tnames (mapcar 'file-truename files))
20470 (extra org-agenda-text-search-extra-files)
20472 (when (eq (car extra) 'agenda-archives)
20473 (setq extra (cdr extra))
20474 (setq files (org-add-archive-files files)))
20475 (while (setq f (pop extra))
20476 (unless (member (file-truename f) tnames)
20477 (add-to-list 'files f 'append)
20478 (add-to-list 'tnames (file-truename f) 'append)))
20479 (multi-occur
20480 (mapcar (lambda (x)
20481 (with-current-buffer
20482 (or (get-file-buffer x) (find-file-noselect x))
20483 (widen)
20484 (current-buffer)))
20485 files)
20486 regexp)))
20488 (if (boundp 'occur-mode-find-occurrence-hook)
20489 ;; Emacs 23
20490 (add-hook 'occur-mode-find-occurrence-hook
20491 (lambda ()
20492 (when (derived-mode-p 'org-mode)
20493 (org-reveal))))
20494 ;; Emacs 22
20495 (defadvice occur-mode-goto-occurrence
20496 (after org-occur-reveal activate)
20497 (and (derived-mode-p 'org-mode) (org-reveal)))
20498 (defadvice occur-mode-goto-occurrence-other-window
20499 (after org-occur-reveal activate)
20500 (and (derived-mode-p 'org-mode) (org-reveal)))
20501 (defadvice occur-mode-display-occurrence
20502 (after org-occur-reveal activate)
20503 (when (derived-mode-p 'org-mode)
20504 (let ((pos (occur-mode-find-occurrence)))
20505 (with-current-buffer (marker-buffer pos)
20506 (save-excursion
20507 (goto-char pos)
20508 (org-reveal)))))))
20510 (defun org-occur-link-in-agenda-files ()
20511 "Create a link and search for it in the agendas.
20512 The link is not stored in `org-stored-links', it is just created
20513 for the search purpose."
20514 (interactive)
20515 (let ((link (condition-case nil
20516 (org-store-link nil)
20517 (error "Unable to create a link to here"))))
20518 (org-occur-in-agenda-files (regexp-quote link))))
20520 (defun org-uniquify (list)
20521 "Remove duplicate elements from LIST."
20522 (let (res)
20523 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20524 res))
20526 (defun org-delete-all (elts list)
20527 "Remove all elements in ELTS from LIST."
20528 (while elts
20529 (setq list (delete (pop elts) list)))
20530 list)
20532 (defun org-count (cl-item cl-seq)
20533 "Count the number of occurrences of ITEM in SEQ.
20534 Taken from `count' in cl-seq.el with all keyword arguments removed."
20535 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20536 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20537 (while (< cl-start cl-end)
20538 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20539 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20540 (setq cl-start (1+ cl-start)))
20541 cl-count))
20543 (defun org-remove-if (predicate seq)
20544 "Remove everything from SEQ that fulfills PREDICATE."
20545 (let (res e)
20546 (while seq
20547 (setq e (pop seq))
20548 (if (not (funcall predicate e)) (push e res)))
20549 (nreverse res)))
20551 (defun org-remove-if-not (predicate seq)
20552 "Remove everything from SEQ that does not fulfill PREDICATE."
20553 (let (res e)
20554 (while seq
20555 (setq e (pop seq))
20556 (if (funcall predicate e) (push e res)))
20557 (nreverse res)))
20559 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20560 "Reduce two-argument FUNCTION across SEQ.
20561 Taken from `reduce' in cl-seq.el with all keyword arguments but
20562 \":initial-value\" removed."
20563 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20564 (cadr (memq :initial-value cl-keys)))
20565 (cl-seq (pop cl-seq))
20566 (t (funcall cl-func)))))
20567 (while cl-seq
20568 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20569 cl-accum))
20571 (defun org-back-over-empty-lines ()
20572 "Move backwards over whitespace, to the beginning of the first empty line.
20573 Returns the number of empty lines passed."
20574 (let ((pos (point)))
20575 (if (cdr (assoc 'heading org-blank-before-new-entry))
20576 (skip-chars-backward " \t\n\r")
20577 (unless (eobp)
20578 (forward-line -1)))
20579 (beginning-of-line 2)
20580 (goto-char (min (point) pos))
20581 (count-lines (point) pos)))
20583 (defun org-skip-whitespace ()
20584 (skip-chars-forward " \t\n\r"))
20586 (defun org-point-in-group (point group &optional context)
20587 "Check if POINT is in match-group GROUP.
20588 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20589 match. If the match group does not exist or point is not inside it,
20590 return nil."
20591 (and (match-beginning group)
20592 (>= point (match-beginning group))
20593 (<= point (match-end group))
20594 (if context
20595 (list context (match-beginning group) (match-end group))
20596 t)))
20598 (defun org-switch-to-buffer-other-window (&rest args)
20599 "Switch to buffer in a second window on the current frame.
20600 In particular, do not allow pop-up frames.
20601 Returns the newly created buffer."
20602 (org-no-popups
20603 (apply 'switch-to-buffer-other-window args)))
20605 (defun org-combine-plists (&rest plists)
20606 "Create a single property list from all plists in PLISTS.
20607 The process starts by copying the first list, and then setting properties
20608 from the other lists. Settings in the last list are the most significant
20609 ones and overrule settings in the other lists."
20610 (let ((rtn (copy-sequence (pop plists)))
20611 p v ls)
20612 (while plists
20613 (setq ls (pop plists))
20614 (while ls
20615 (setq p (pop ls) v (pop ls))
20616 (setq rtn (plist-put rtn p v))))
20617 rtn))
20619 (defun org-replace-escapes (string table)
20620 "Replace %-escapes in STRING with values in TABLE.
20621 TABLE is an association list with keys like \"%a\" and string values.
20622 The sequences in STRING may contain normal field width and padding information,
20623 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20624 so values can contain further %-escapes if they are define later in TABLE."
20625 (let ((tbl (copy-alist table))
20626 (case-fold-search nil)
20627 (pchg 0)
20628 e re rpl)
20629 (while (setq e (pop tbl))
20630 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20631 (when (and (cdr e) (string-match re (cdr e)))
20632 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20633 (safe "SREF"))
20634 (add-text-properties 0 3 (list 'sref sref) safe)
20635 (setcdr e (replace-match safe t t (cdr e)))))
20636 (while (string-match re string)
20637 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20638 (cdr e)))
20639 (setq string (replace-match rpl t t string))))
20640 (while (setq pchg (next-property-change pchg string))
20641 (let ((sref (get-text-property pchg 'sref string)))
20642 (when (and sref (string-match "SREF" string pchg))
20643 (setq string (replace-match sref t t string)))))
20644 string))
20646 (defun org-sublist (list start end)
20647 "Return a section of LIST, from START to END.
20648 Counting starts at 1."
20649 (let (rtn (c start))
20650 (setq list (nthcdr (1- start) list))
20651 (while (and list (<= c end))
20652 (push (pop list) rtn)
20653 (setq c (1+ c)))
20654 (nreverse rtn)))
20656 (defun org-find-base-buffer-visiting (file)
20657 "Like `find-buffer-visiting' but always return the base buffer and
20658 not an indirect buffer."
20659 (let ((buf (or (get-file-buffer file)
20660 (find-buffer-visiting file))))
20661 (if buf
20662 (or (buffer-base-buffer buf) buf)
20663 nil)))
20665 (defun org-image-file-name-regexp (&optional extensions)
20666 "Return regexp matching the file names of images.
20667 If EXTENSIONS is given, only match these."
20668 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20669 (image-file-name-regexp)
20670 (let ((image-file-name-extensions
20671 (or extensions
20672 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20673 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20674 (concat "\\."
20675 (regexp-opt (nconc (mapcar 'upcase
20676 image-file-name-extensions)
20677 image-file-name-extensions)
20679 "\\'"))))
20681 (defun org-file-image-p (file &optional extensions)
20682 "Return non-nil if FILE is an image."
20683 (save-match-data
20684 (string-match (org-image-file-name-regexp extensions) file)))
20686 (defun org-get-cursor-date ()
20687 "Return the date at cursor in as a time.
20688 This works in the calendar and in the agenda, anywhere else it just
20689 returns the current time."
20690 (let (date day defd)
20691 (cond
20692 ((eq major-mode 'calendar-mode)
20693 (setq date (calendar-cursor-to-date)
20694 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20695 ((eq major-mode 'org-agenda-mode)
20696 (setq day (get-text-property (point) 'day))
20697 (if day
20698 (setq date (calendar-gregorian-from-absolute day)
20699 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20700 (nth 2 date))))))
20701 (or defd (current-time))))
20703 (defun org-mark-subtree (&optional up)
20704 "Mark the current subtree.
20705 This puts point at the start of the current subtree, and mark at
20706 the end. If a numeric prefix UP is given, move up into the
20707 hierarchy of headlines by UP levels before marking the subtree."
20708 (interactive "P")
20709 (org-with-limited-levels
20710 (cond ((org-at-heading-p) (beginning-of-line))
20711 ((org-before-first-heading-p) (error "Not in a subtree"))
20712 (t (outline-previous-visible-heading 1))))
20713 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
20714 (if (org-called-interactively-p 'any)
20715 (call-interactively 'org-mark-element)
20716 (org-mark-element)))
20718 ;;; Indentation
20720 (defun org-indent-line ()
20721 "Indent line depending on context."
20722 (interactive)
20723 (let* ((pos (point))
20724 (itemp (org-at-item-p))
20725 (case-fold-search t)
20726 (org-drawer-regexp (or org-drawer-regexp "\000"))
20727 (inline-task-p (and (featurep 'org-inlinetask)
20728 (org-inlinetask-in-task-p)))
20729 (inline-re (and inline-task-p
20730 (org-inlinetask-outline-regexp)))
20731 column)
20732 (if (and orgstruct-is-++ (eq pos (point)))
20733 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
20734 (indent-according-to-mode))
20735 (beginning-of-line 1)
20736 (cond
20737 ;; Headings
20738 ((looking-at org-outline-regexp) (setq column 0))
20739 ;; Included files
20740 ((looking-at "#\\+include:") (setq column 0))
20741 ;; Footnote definition
20742 ((looking-at org-footnote-definition-re) (setq column 0))
20743 ;; Literal examples
20744 ((looking-at "[ \t]*:\\( \\|$\\)")
20745 (setq column (org-get-indentation))) ; do nothing
20746 ;; Lists
20747 ((ignore-errors (goto-char (org-in-item-p)))
20748 (setq column (if itemp
20749 (org-get-indentation)
20750 (org-list-item-body-column (point))))
20751 (goto-char pos))
20752 ;; Drawers
20753 ((and (looking-at "[ \t]*:END:")
20754 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20755 (save-excursion
20756 (goto-char (1- (match-beginning 1)))
20757 (setq column (current-column))))
20758 ;; Special blocks
20759 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20760 (save-excursion
20761 (re-search-backward
20762 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20763 (setq column (org-get-indentation (match-string 0))))
20764 ((and (not (looking-at "[ \t]*#\\+begin_"))
20765 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20766 (save-excursion
20767 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20768 (setq column
20769 (cond ((equal (downcase (match-string 1)) "src")
20770 ;; src blocks: let `org-edit-src-exit' handle them
20771 (org-get-indentation))
20772 ((equal (downcase (match-string 1)) "example")
20773 (max (org-get-indentation)
20774 (org-get-indentation (match-string 0))))
20776 (org-get-indentation (match-string 0))))))
20777 ;; This line has nothing special, look at the previous relevant
20778 ;; line to compute indentation
20780 (beginning-of-line 0)
20781 (while (and (not (bobp))
20782 (not (looking-at org-drawer-regexp))
20783 ;; When point started in an inline task, do not move
20784 ;; above task starting line.
20785 (not (and inline-task-p (looking-at inline-re)))
20786 ;; Skip drawers, blocks, empty lines, verbatim,
20787 ;; comments, tables, footnotes definitions, lists,
20788 ;; inline tasks.
20789 (or (and (looking-at "[ \t]*:END:")
20790 (re-search-backward org-drawer-regexp nil t))
20791 (and (looking-at "[ \t]*#\\+end_")
20792 (re-search-backward "[ \t]*#\\+begin_"nil t))
20793 (looking-at "[ \t]*[\n:#|]")
20794 (looking-at org-footnote-definition-re)
20795 (and (ignore-errors (goto-char (org-in-item-p)))
20796 (goto-char
20797 (org-list-get-top-point (org-list-struct))))
20798 (and (not inline-task-p)
20799 (featurep 'org-inlinetask)
20800 (org-inlinetask-in-task-p)
20801 (or (org-inlinetask-goto-beginning) t))))
20802 (beginning-of-line 0))
20803 (cond
20804 ;; There was an heading above.
20805 ((looking-at "\\*+[ \t]+")
20806 (if (not org-adapt-indentation)
20807 (setq column 0)
20808 (goto-char (match-end 0))
20809 (setq column (current-column))))
20810 ;; A drawer had started and is unfinished
20811 ((looking-at org-drawer-regexp)
20812 (goto-char (1- (match-beginning 1)))
20813 (setq column (current-column)))
20814 ;; Else, nothing noticeable found: get indentation and go on.
20815 (t (setq column (org-get-indentation))))))
20816 ;; Now apply indentation and move cursor accordingly
20817 (goto-char pos)
20818 (if (<= (current-column) (current-indentation))
20819 (org-indent-line-to column)
20820 (save-excursion (org-indent-line-to column)))
20821 ;; Special polishing for properties, see `org-property-format'
20822 (setq column (current-column))
20823 (beginning-of-line 1)
20824 (if (looking-at
20825 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20826 (replace-match (concat (match-string 1)
20827 (format org-property-format
20828 (match-string 2) (match-string 3)))
20829 t t))
20830 (org-move-to-column column))))
20832 (defun org-indent-drawer ()
20833 "Indent the drawer at point."
20834 (interactive)
20835 (let ((p (point))
20836 (e (and (save-excursion (re-search-forward ":END:" nil t))
20837 (match-end 0)))
20838 (folded
20839 (save-excursion
20840 (end-of-line)
20841 (when (overlays-at (point))
20842 (member 'invisible (overlay-properties
20843 (car (overlays-at (point)))))))))
20844 (when folded (org-cycle))
20845 (indent-for-tab-command)
20846 (while (and (move-beginning-of-line 2) (< (point) e))
20847 (indent-for-tab-command))
20848 (goto-char p)
20849 (when folded (org-cycle)))
20850 (message "Drawer at point indented"))
20852 (defun org-indent-block ()
20853 "Indent the block at point."
20854 (interactive)
20855 (let ((p (point))
20856 (case-fold-search t)
20857 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20858 (match-end 0)))
20859 (folded
20860 (save-excursion
20861 (end-of-line)
20862 (when (overlays-at (point))
20863 (member 'invisible (overlay-properties
20864 (car (overlays-at (point)))))))))
20865 (when folded (org-cycle))
20866 (indent-for-tab-command)
20867 (while (and (move-beginning-of-line 2) (< (point) e))
20868 (indent-for-tab-command))
20869 (goto-char p)
20870 (when folded (org-cycle)))
20871 (message "Block at point indented"))
20873 (defun org-indent-region (start end)
20874 "Indent region."
20875 (interactive "r")
20876 (save-excursion
20877 (let ((line-end (org-current-line end)))
20878 (goto-char start)
20879 (while (< (org-current-line) line-end)
20880 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
20881 (t (call-interactively 'org-indent-line)))
20882 (move-beginning-of-line 2)))))
20885 ;;; Filling
20887 ;; We use our own fill-paragraph and auto-fill functions.
20889 ;; `org-fill-paragraph' relies on adaptive filling and context
20890 ;; checking. Appropriate `fill-prefix' is computed with
20891 ;; `org-adaptive-fill-function'.
20893 ;; `org-auto-fill-function' takes care of auto-filling. It calls
20894 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
20895 ;; `org-adaptive-fill-function' value. Internally,
20896 ;; `org-comment-line-break-function' breaks the line.
20898 ;; `org-setup-filling' installs filling and auto-filling related
20899 ;; variables during `org-mode' initialization.
20901 (defun org-setup-filling ()
20902 (interactive)
20903 ;; Prevent auto-fill from inserting unwanted new items.
20904 (when (boundp 'fill-nobreak-predicate)
20905 (org-set-local
20906 'fill-nobreak-predicate
20907 (org-uniquify
20908 (append fill-nobreak-predicate
20909 '(org-fill-paragraph-separate-nobreak-p
20910 org-fill-line-break-nobreak-p)))))
20911 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20912 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
20913 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20914 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
20916 (defvar org-element-paragraph-separate) ; org-element.el
20917 (defun org-fill-paragraph-separate-nobreak-p ()
20918 "Non-nil when a line break at point would insert a new item."
20919 (looking-at (substring org-element-paragraph-separate 1)))
20921 (defun org-fill-line-break-nobreak-p ()
20922 "Non-nil when a line break at point would create an Org line break."
20923 (save-excursion
20924 (skip-chars-backward "[ \t]")
20925 (skip-chars-backward "\\\\")
20926 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
20928 (declare-function message-in-body-p "message" ())
20929 (defvar org-element--affiliated-re) ; From org-element.el
20930 (defun org-adaptive-fill-function ()
20931 "Compute a fill prefix for the current line.
20932 Return fill prefix, as a string, or nil if current line isn't
20933 meant to be filled."
20934 (org-with-wide-buffer
20935 (unless (and (derived-mode-p 'message-mode) (not (message-in-body-p)))
20936 ;; FIXME: This is really the job of orgstruct++-mode
20937 (let* ((p (line-beginning-position))
20938 (element (save-excursion (beginning-of-line)
20939 (org-element-at-point)))
20940 (type (org-element-type element))
20941 (post-affiliated
20942 (save-excursion
20943 (goto-char (org-element-property :begin element))
20944 (while (looking-at org-element--affiliated-re) (forward-line))
20945 (point))))
20946 (unless (< p post-affiliated)
20947 (case type
20948 (comment (looking-at "[ \t]*# ?") (match-string 0))
20949 (footnote-definition "")
20950 ((item plain-list)
20951 (make-string (org-list-item-body-column post-affiliated) ? ))
20952 (paragraph
20953 ;; Fill prefix is usually the same as the current line,
20954 ;; except if the paragraph is at the beginning of an item.
20955 (let ((parent (org-element-property :parent element)))
20956 (cond ((eq (org-element-type parent) 'item)
20957 (make-string (org-list-item-body-column
20958 (org-element-property :begin parent))
20959 ? ))
20960 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
20961 (match-string 0))
20962 (t ""))))
20963 (comment-block
20964 ;; Only fill contents if P is within block boundaries.
20965 (let* ((cbeg (save-excursion (goto-char post-affiliated)
20966 (forward-line)
20967 (point)))
20968 (cend (save-excursion
20969 (goto-char (org-element-property :end element))
20970 (skip-chars-backward " \r\t\n")
20971 (line-beginning-position))))
20972 (when (and (>= p cbeg) (< p cend))
20973 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
20974 (match-string 0)
20975 ""))))))))))
20977 (declare-function message-goto-body "message" ())
20978 (defvar message-cite-prefix-regexp) ; From message.el
20979 (defvar org-element-all-objects) ; From org-element.el
20980 (defun org-fill-paragraph (&optional justify)
20981 "Fill element at point, when applicable.
20983 This function only applies to comment blocks, comments, example
20984 blocks and paragraphs. Also, as a special case, re-align table
20985 when point is at one.
20987 If JUSTIFY is non-nil (interactively, with prefix argument),
20988 justify as well. If `sentence-end-double-space' is non-nil, then
20989 period followed by one space does not end a sentence, so don't
20990 break a line there. The variable `fill-column' controls the
20991 width for filling.
20993 For convenience, when point is at a plain list, an item or
20994 a footnote definition, try to fill the first paragraph within."
20995 (interactive)
20996 (if (and (derived-mode-p 'message-mode)
20997 (or (not (message-in-body-p))
20998 (save-excursion (move-beginning-of-line 1)
20999 (looking-at message-cite-prefix-regexp))))
21000 ;; First ensure filling is correct in message-mode.
21001 (let ((fill-paragraph-function
21002 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21003 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21004 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21005 (paragraph-separate
21006 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21007 (fill-paragraph nil))
21008 (save-excursion
21009 ;; Move to end of line in order to get the first paragraph
21010 ;; within a plain list or a footnote definition.
21011 (end-of-line)
21012 (let ((element (org-element-at-point)))
21013 ;; First check if point is in a blank line at the beginning of
21014 ;; the buffer. In that case, ignore filling.
21015 (if (< (point) (org-element-property :begin element)) t
21016 (case (org-element-type element)
21017 ;; Use major mode filling function is src blocks.
21018 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21019 ;; Align Org tables, leave table.el tables as-is.
21020 (table-row (org-table-align) t)
21021 (table
21022 (when (eq (org-element-property :type element) 'org)
21023 (org-table-align))
21025 (paragraph
21026 ;; Paragraphs may contain `line-break' type objects.
21027 (let ((beg (max (point-min)
21028 (org-element-property :contents-begin element)))
21029 (end (min (point-max)
21030 (org-element-property :contents-end element))))
21031 ;; Do nothing if point is at an affiliated keyword.
21032 (if (< (point) beg) t
21033 (when (derived-mode-p 'message-mode)
21034 ;; In `message-mode', do not fill following
21035 ;; citation in current paragraph nor text before
21036 ;; message body.
21037 (let ((body-start (save-excursion (message-goto-body))))
21038 (when body-start (setq beg (max body-start beg))))
21039 (when (save-excursion
21040 (re-search-forward
21041 (concat "^" message-cite-prefix-regexp) end t))
21042 (setq end (match-beginning 0))))
21043 ;; Fill paragraph, taking line breaks into
21044 ;; consideration. For that, slice the paragraph
21045 ;; using line breaks as separators, and fill the
21046 ;; parts in reverse order to avoid messing with
21047 ;; markers.
21048 (save-excursion
21049 (goto-char end)
21050 (mapc
21051 (lambda (pos)
21052 (fill-region-as-paragraph pos (point) justify)
21053 (goto-char pos))
21054 ;; Find the list of ending positions for line
21055 ;; breaks in the current paragraph. Add paragraph
21056 ;; beginning to include first slice.
21057 (nreverse
21058 (cons
21060 (org-element-map
21061 (org-element--parse-objects
21062 beg end nil org-element-all-objects)
21063 'line-break
21064 (lambda (lb) (org-element-property :end lb)))))))
21065 t)))
21066 ;; Contents of `comment-block' type elements should be
21067 ;; filled as plain text, but only if point is within block
21068 ;; markers.
21069 (comment-block
21070 (let* ((case-fold-search t)
21071 (beg (save-excursion
21072 (goto-char (org-element-property :begin element))
21073 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21074 (forward-line)
21075 (point)))
21076 (end (save-excursion
21077 (goto-char (org-element-property :end element))
21078 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21079 (line-beginning-position))))
21080 (when (and (>= (point) beg) (< (point) end))
21081 (fill-region-as-paragraph
21082 (save-excursion
21083 (end-of-line)
21084 (re-search-backward "^[ \t]*$" beg 'move)
21085 (line-beginning-position))
21086 (save-excursion
21087 (beginning-of-line)
21088 (re-search-forward "^[ \t]*$" end 'move)
21089 (line-beginning-position))
21090 justify)))
21092 ;; Fill comments.
21093 (comment (fill-comment-paragraph justify))
21094 ;; Ignore every other element.
21095 (otherwise t)))))))
21097 (defun org-auto-fill-function ()
21098 "Auto-fill function."
21099 ;; Check if auto-filling is meaningful.
21100 (let ((fc (current-fill-column)))
21101 (when (and fc (> (current-column) fc))
21102 (let* ((fill-prefix (org-adaptive-fill-function))
21103 ;; Enforce empty fill prefix, if required. Otherwise, it
21104 ;; will be computed again.
21105 (adaptive-fill-mode (not (equal fill-prefix ""))))
21106 (when fill-prefix (do-auto-fill))))))
21108 (defun org-comment-line-break-function (&optional soft)
21109 "Break line at point and indent, continuing comment if within one.
21110 The inserted newline is marked hard if variable
21111 `use-hard-newlines' is true, unless optional argument SOFT is
21112 non-nil."
21113 (if soft (insert-and-inherit ?\n) (newline 1))
21114 (save-excursion (forward-char -1) (delete-horizontal-space))
21115 (delete-horizontal-space)
21116 (indent-to-left-margin)
21117 (insert-before-markers-and-inherit fill-prefix))
21120 ;;; Comments
21122 ;; Org comments syntax is quite complex. It requires the entire line
21123 ;; to be just a comment. Also, even with the right syntax at the
21124 ;; beginning of line, some some elements (i.e. verse-block or
21125 ;; example-block) don't accept comments. Usual Emacs comment commands
21126 ;; cannot cope with those requirements. Therefore, Org replaces them.
21128 ;; Org still relies on `comment-dwim', but cannot trust
21129 ;; `comment-only-p'. So, `comment-region-function' and
21130 ;; `uncomment-region-function' both point
21131 ;; to`org-comment-or-uncomment-region'. Eventually,
21132 ;; `org-insert-comment' takes care of insertion of comments at the
21133 ;; beginning of line.
21135 ;; `org-setup-comments-handling' install comments related variables
21136 ;; during `org-mode' initialization.
21138 (defun org-setup-comments-handling ()
21139 (interactive)
21140 (org-set-local 'comment-use-syntax nil)
21141 (org-set-local 'comment-start "# ")
21142 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21143 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21144 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21145 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21147 (defun org-insert-comment ()
21148 "Insert an empty comment above current line.
21149 If the line is empty, insert comment at its beginning."
21150 (beginning-of-line)
21151 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21152 (org-indent-line)
21153 (insert "# "))
21155 (defvar comment-empty-lines) ; From newcomment.el.
21156 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21157 "Comment or uncomment each non-blank line in the region.
21158 Uncomment each non-blank line between BEG and END if it only
21159 contains commented lines. Otherwise, comment them."
21160 (save-restriction
21161 ;; Restrict region
21162 (narrow-to-region (save-excursion (goto-char beg)
21163 (skip-chars-forward " \r\t\n" end)
21164 (line-beginning-position))
21165 (save-excursion (goto-char end)
21166 (skip-chars-backward " \r\t\n" beg)
21167 (line-end-position)))
21168 (let ((uncommentp
21169 ;; UNCOMMENTP is non-nil when every non blank line between
21170 ;; BEG and END is a comment.
21171 (save-excursion
21172 (goto-char (point-min))
21173 (while (and (not (eobp))
21174 (let ((element (org-element-at-point)))
21175 (and (eq (org-element-type element) 'comment)
21176 (goto-char (min (point-max)
21177 (org-element-property
21178 :end element)))))))
21179 (eobp))))
21180 (if uncommentp
21181 ;; Only blank lines and comments in region: uncomment it.
21182 (save-excursion
21183 (goto-char (point-min))
21184 (while (not (eobp))
21185 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21186 (replace-match "" nil nil nil 1))
21187 (forward-line)))
21188 ;; Comment each line in region.
21189 (let ((min-indent (point-max)))
21190 ;; First find the minimum indentation across all lines.
21191 (save-excursion
21192 (goto-char (point-min))
21193 (while (and (not (eobp)) (not (zerop min-indent)))
21194 (unless (looking-at "[ \t]*$")
21195 (setq min-indent (min min-indent (current-indentation))))
21196 (forward-line)))
21197 ;; Then loop over all lines.
21198 (save-excursion
21199 (goto-char (point-min))
21200 (while (not (eobp))
21201 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21202 (org-move-to-column min-indent t)
21203 (insert comment-start))
21204 (forward-line))))))))
21207 ;;; Other stuff.
21209 (defun org-toggle-fixed-width-section (arg)
21210 "Toggle the fixed-width export.
21211 If there is no active region, the QUOTE keyword at the current headline is
21212 inserted or removed. When present, it causes the text between this headline
21213 and the next to be exported as fixed-width text, and unmodified.
21214 If there is an active region, this command adds or removes a colon as the
21215 first character of this line. If the first character of a line is a colon,
21216 this line is also exported in fixed-width font."
21217 (interactive "P")
21218 (let* ((cc 0)
21219 (regionp (org-region-active-p))
21220 (beg (if regionp (region-beginning) (point)))
21221 (end (if regionp (region-end)))
21222 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21223 (case-fold-search nil)
21224 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21225 off)
21226 (if regionp
21227 (save-excursion
21228 (goto-char beg)
21229 (setq cc (current-column))
21230 (beginning-of-line 1)
21231 (setq off (looking-at re))
21232 (while (> nlines 0)
21233 (setq nlines (1- nlines))
21234 (beginning-of-line 1)
21235 (cond
21236 (arg
21237 (org-move-to-column cc t)
21238 (insert ": \n")
21239 (forward-line -1))
21240 ((and off (looking-at re))
21241 (replace-match "" t t nil 1))
21242 ((not off) (org-move-to-column cc t) (insert ": ")))
21243 (forward-line 1)))
21244 (save-excursion
21245 (org-back-to-heading)
21246 (cond
21247 ((looking-at (format org-heading-keyword-regexp-format
21248 org-quote-string))
21249 (goto-char (match-end 1))
21250 (looking-at (concat " +" org-quote-string))
21251 (replace-match "" t t)
21252 (when (eolp) (insert " ")))
21253 ((looking-at org-outline-regexp)
21254 (goto-char (match-end 0))
21255 (insert org-quote-string " ")))))))
21257 (defun org-reftex-citation ()
21258 "Use reftex-citation to insert a citation into the buffer.
21259 This looks for a line like
21261 #+BIBLIOGRAPHY: foo plain option:-d
21263 and derives from it that foo.bib is the bibliography file relevant
21264 for this document. It then installs the necessary environment for RefTeX
21265 to work in this buffer and calls `reftex-citation' to insert a citation
21266 into the buffer.
21268 Export of such citations to both LaTeX and HTML is handled by the contributed
21269 package org-exp-bibtex by Taru Karttunen."
21270 (interactive)
21271 (let ((reftex-docstruct-symbol 'rds)
21272 (reftex-cite-format "\\cite{%l}")
21273 rds bib)
21274 (save-excursion
21275 (save-restriction
21276 (widen)
21277 (let ((case-fold-search t)
21278 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21279 (if (not (save-excursion
21280 (or (re-search-forward re nil t)
21281 (re-search-backward re nil t))))
21282 (error "No bibliography defined in file")
21283 (setq bib (concat (match-string 1) ".bib")
21284 rds (list (list 'bib bib)))))))
21285 (call-interactively 'reftex-citation)))
21287 ;;;; Functions extending outline functionality
21289 (defun org-beginning-of-line (&optional arg)
21290 "Go to the beginning of the current line. If that is invisible, continue
21291 to a visible line beginning. This makes the function of C-a more intuitive.
21292 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21293 first attempt, and only move to after the tags when the cursor is already
21294 beyond the end of the headline."
21295 (interactive "P")
21296 (let ((pos (point))
21297 (special (if (consp org-special-ctrl-a/e)
21298 (car org-special-ctrl-a/e)
21299 org-special-ctrl-a/e))
21300 refpos)
21301 (if (org-bound-and-true-p visual-line-mode)
21302 (beginning-of-visual-line 1)
21303 (beginning-of-line 1))
21304 (if (and arg (fboundp 'move-beginning-of-line))
21305 (call-interactively 'move-beginning-of-line)
21306 (if (bobp)
21308 (backward-char 1)
21309 (if (org-truely-invisible-p)
21310 (while (and (not (bobp)) (org-truely-invisible-p))
21311 (backward-char 1)
21312 (beginning-of-line 1))
21313 (forward-char 1))))
21314 (when special
21315 (cond
21316 ((and (looking-at org-complex-heading-regexp)
21317 (= (char-after (match-end 1)) ?\ ))
21318 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21319 (point-at-eol)))
21320 (goto-char
21321 (if (eq special t)
21322 (cond ((> pos refpos) refpos)
21323 ((= pos (point)) refpos)
21324 (t (point)))
21325 (cond ((> pos (point)) (point))
21326 ((not (eq last-command this-command)) (point))
21327 (t refpos)))))
21328 ((org-at-item-p)
21329 ;; Being at an item and not looking at an the item means point
21330 ;; was previously moved to beginning of a visual line, which
21331 ;; doesn't contain the item. Therefore, do nothing special,
21332 ;; just stay here.
21333 (when (looking-at org-list-full-item-re)
21334 ;; Set special position at first white space character after
21335 ;; bullet, and check-box, if any.
21336 (let ((after-bullet
21337 (let ((box (match-end 3)))
21338 (if (not box) (match-end 1)
21339 (let ((after (char-after box)))
21340 (if (and after (= after ? )) (1+ box) box))))))
21341 ;; Special case: Move point to special position when
21342 ;; currently after it or at beginning of line.
21343 (if (eq special t)
21344 (when (or (> pos after-bullet) (= (point) pos))
21345 (goto-char after-bullet))
21346 ;; Reversed case: Move point to special position when
21347 ;; point was already at beginning of line and command is
21348 ;; repeated.
21349 (when (and (= (point) pos) (eq last-command this-command))
21350 (goto-char after-bullet))))))))
21351 (org-no-warnings
21352 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21354 (defun org-end-of-line (&optional arg)
21355 "Go to the end of the line.
21356 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
21357 tags on the first attempt, and only move to after the tags when
21358 the cursor is already beyond the end of the headline."
21359 (interactive "P")
21360 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
21361 org-special-ctrl-a/e))
21362 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
21363 'end-of-visual-line)
21364 ((fboundp 'move-end-of-line) 'move-end-of-line)
21365 (t 'end-of-line))))
21366 (if (or (not special) arg) (call-interactively move-fun)
21367 (let* ((element (save-excursion (beginning-of-line)
21368 (org-element-at-point)))
21369 (type (org-element-type element)))
21370 (cond
21371 ((memq type '(headline inlinetask))
21372 (let ((pos (point)))
21373 (beginning-of-line 1)
21374 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21375 (if (eq special t)
21376 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
21377 (goto-char (match-beginning 1))
21378 (goto-char (match-end 0)))
21379 (if (or (< pos (match-end 0))
21380 (not (eq this-command last-command)))
21381 (goto-char (match-end 0))
21382 (goto-char (match-beginning 1))))
21383 (call-interactively move-fun))))
21384 ((org-element-property :hiddenp element)
21385 ;; If element is hidden, `move-end-of-line' would put point
21386 ;; after it. Use `end-of-line' to stay on current line.
21387 (call-interactively 'end-of-line))
21388 (t (call-interactively move-fun)))))
21389 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21391 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21392 (define-key org-mode-map "\C-e" 'org-end-of-line)
21394 (defun org-backward-sentence (&optional arg)
21395 "Go to beginning of sentence, or beginning of table field.
21396 This will call `backward-sentence' or `org-table-beginning-of-field',
21397 depending on context."
21398 (interactive "P")
21399 (cond
21400 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21401 (t (call-interactively 'backward-sentence))))
21403 (defun org-forward-sentence (&optional arg)
21404 "Go to end of sentence, or end of table field.
21405 This will call `forward-sentence' or `org-table-end-of-field',
21406 depending on context."
21407 (interactive "P")
21408 (cond
21409 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21410 (t (call-interactively 'forward-sentence))))
21412 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21413 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21415 (defun org-kill-line (&optional arg)
21416 "Kill line, to tags or end of line."
21417 (interactive "P")
21418 (cond
21419 ((or (not org-special-ctrl-k)
21420 (bolp)
21421 (not (org-at-heading-p)))
21422 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21423 org-ctrl-k-protect-subtree)
21424 (if (or (eq org-ctrl-k-protect-subtree 'error)
21425 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21426 (error "C-k aborted - would kill hidden subtree")))
21427 (call-interactively
21428 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
21429 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21430 (kill-region (point) (match-beginning 1))
21431 (org-set-tags nil t))
21432 (t (kill-region (point) (point-at-eol)))))
21434 (define-key org-mode-map "\C-k" 'org-kill-line)
21436 (defun org-yank (&optional arg)
21437 "Yank. If the kill is a subtree, treat it specially.
21438 This command will look at the current kill and check if is a single
21439 subtree, or a series of subtrees[1]. If it passes the test, and if the
21440 cursor is at the beginning of a line or after the stars of a currently
21441 empty headline, then the yank is handled specially. How exactly depends
21442 on the value of the following variables, both set by default.
21444 org-yank-folded-subtrees
21445 When set, the subtree(s) will be folded after insertion, but only
21446 if doing so would now swallow text after the yanked text.
21448 org-yank-adjusted-subtrees
21449 When set, the subtree will be promoted or demoted in order to
21450 fit into the local outline tree structure, which means that the level
21451 will be adjusted so that it becomes the smaller one of the two
21452 *visible* surrounding headings.
21454 Any prefix to this command will cause `yank' to be called directly with
21455 no special treatment. In particular, a simple \\[universal-argument] prefix \
21456 will just
21457 plainly yank the text as it is.
21459 \[1] The test checks if the first non-white line is a heading
21460 and if there are no other headings with fewer stars."
21461 (interactive "P")
21462 (org-yank-generic 'yank arg))
21464 (defun org-yank-generic (command arg)
21465 "Perform some yank-like command.
21467 This function implements the behavior described in the `org-yank'
21468 documentation. However, it has been generalized to work for any
21469 interactive command with similar behavior."
21471 ;; pretend to be command COMMAND
21472 (setq this-command command)
21474 (if arg
21475 (call-interactively command)
21477 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21478 (and (org-kill-is-subtree-p)
21479 (or (bolp)
21480 (and (looking-at "[ \t]*$")
21481 (string-match
21482 "\\`\\*+\\'"
21483 (buffer-substring (point-at-bol) (point)))))))
21484 swallowp)
21485 (cond
21486 ((and subtreep org-yank-folded-subtrees)
21487 (let ((beg (point))
21488 end)
21489 (if (and subtreep org-yank-adjusted-subtrees)
21490 (org-paste-subtree nil nil 'for-yank)
21491 (call-interactively command))
21493 (setq end (point))
21494 (goto-char beg)
21495 (when (and (bolp) subtreep
21496 (not (setq swallowp
21497 (org-yank-folding-would-swallow-text beg end))))
21498 (org-with-limited-levels
21499 (or (looking-at org-outline-regexp)
21500 (re-search-forward org-outline-regexp-bol end t))
21501 (while (and (< (point) end) (looking-at org-outline-regexp))
21502 (hide-subtree)
21503 (org-cycle-show-empty-lines 'folded)
21504 (condition-case nil
21505 (outline-forward-same-level 1)
21506 (error (goto-char end))))))
21507 (when swallowp
21508 (message
21509 "Inserted text not folded because that would swallow text"))
21511 (goto-char end)
21512 (skip-chars-forward " \t\n\r")
21513 (beginning-of-line 1)
21514 (push-mark beg 'nomsg)))
21515 ((and subtreep org-yank-adjusted-subtrees)
21516 (let ((beg (point-at-bol)))
21517 (org-paste-subtree nil nil 'for-yank)
21518 (push-mark beg 'nomsg)))
21520 (call-interactively command))))))
21522 (defun org-yank-folding-would-swallow-text (beg end)
21523 "Would hide-subtree at BEG swallow any text after END?"
21524 (let (level)
21525 (org-with-limited-levels
21526 (save-excursion
21527 (goto-char beg)
21528 (when (or (looking-at org-outline-regexp)
21529 (re-search-forward org-outline-regexp-bol end t))
21530 (setq level (org-outline-level)))
21531 (goto-char end)
21532 (skip-chars-forward " \t\r\n\v\f")
21533 (if (or (eobp)
21534 (and (bolp) (looking-at org-outline-regexp)
21535 (<= (org-outline-level) level)))
21536 nil ; Nothing would be swallowed
21537 t))))) ; something would swallow
21539 (define-key org-mode-map "\C-y" 'org-yank)
21541 (defun org-truely-invisible-p ()
21542 "Check if point is at a character currently not visible.
21543 This version does not only check the character property, but also
21544 `visible-mode'."
21545 ;; Early versions of noutline don't have `outline-invisible-p'.
21546 (if (org-bound-and-true-p visible-mode)
21548 (outline-invisible-p)))
21550 (defun org-invisible-p2 ()
21551 "Check if point is at a character currently not visible."
21552 (save-excursion
21553 (if (and (eolp) (not (bobp))) (backward-char 1))
21554 ;; Early versions of noutline don't have `outline-invisible-p'.
21555 (outline-invisible-p)))
21557 (defun org-back-to-heading (&optional invisible-ok)
21558 "Call `outline-back-to-heading', but provide a better error message."
21559 (condition-case nil
21560 (outline-back-to-heading invisible-ok)
21561 (error (error "Before first headline at position %d in buffer %s"
21562 (point) (current-buffer)))))
21564 (defun org-before-first-heading-p ()
21565 "Before first heading?"
21566 (save-excursion
21567 (end-of-line)
21568 (null (re-search-backward org-outline-regexp-bol nil t))))
21570 (defun org-at-heading-p (&optional ignored)
21571 (outline-on-heading-p t))
21572 ;; Compatibility alias with Org versions < 7.8.03
21573 (defalias 'org-on-heading-p 'org-at-heading-p)
21575 (defun org-at-comment-p nil
21576 "Is cursor in a line starting with a # character?"
21577 (save-excursion
21578 (beginning-of-line)
21579 (looking-at "^#")))
21581 (defun org-at-drawer-p nil
21582 "Is cursor at a drawer keyword?"
21583 (save-excursion
21584 (move-beginning-of-line 1)
21585 (looking-at org-drawer-regexp)))
21587 (defun org-at-block-p nil
21588 "Is cursor at a block keyword?"
21589 (save-excursion
21590 (move-beginning-of-line 1)
21591 (looking-at org-block-regexp)))
21593 (defun org-point-at-end-of-empty-headline ()
21594 "If point is at the end of an empty headline, return t, else nil.
21595 If the heading only contains a TODO keyword, it is still still considered
21596 empty."
21597 (and (looking-at "[ \t]*$")
21598 (when org-todo-line-regexp
21599 (save-excursion
21600 (beginning-of-line 1)
21601 (let ((case-fold-search nil))
21602 (looking-at org-todo-line-regexp)
21603 (string= (match-string 3) ""))))))
21605 (defun org-at-heading-or-item-p ()
21606 (or (org-at-heading-p) (org-at-item-p)))
21608 (defun org-at-target-p ()
21609 (or (org-in-regexp org-radio-target-regexp)
21610 (org-in-regexp org-target-regexp)))
21611 ;; Compatibility alias with Org versions < 7.8.03
21612 (defalias 'org-on-target-p 'org-at-target-p)
21614 (defun org-up-heading-all (arg)
21615 "Move to the heading line of which the present line is a subheading.
21616 This function considers both visible and invisible heading lines.
21617 With argument, move up ARG levels."
21618 (if (fboundp 'outline-up-heading-all)
21619 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21620 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21622 (defun org-up-heading-safe ()
21623 "Move to the heading line of which the present line is a subheading.
21624 This version will not throw an error. It will return the level of the
21625 headline found, or nil if no higher level is found.
21627 Also, this function will be a lot faster than `outline-up-heading',
21628 because it relies on stars being the outline starters. This can really
21629 make a significant difference in outlines with very many siblings."
21630 (let (start-level re)
21631 (org-back-to-heading t)
21632 (setq start-level (funcall outline-level))
21633 (if (equal start-level 1)
21635 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21636 (if (re-search-backward re nil t)
21637 (funcall outline-level)))))
21639 (defun org-first-sibling-p ()
21640 "Is this heading the first child of its parents?"
21641 (interactive)
21642 (let ((re org-outline-regexp-bol)
21643 level l)
21644 (unless (org-at-heading-p t)
21645 (error "Not at a heading"))
21646 (setq level (funcall outline-level))
21647 (save-excursion
21648 (if (not (re-search-backward re nil t))
21650 (setq l (funcall outline-level))
21651 (< l level)))))
21653 (defun org-goto-sibling (&optional previous)
21654 "Goto the next sibling, even if it is invisible.
21655 When PREVIOUS is set, go to the previous sibling instead. Returns t
21656 when a sibling was found. When none is found, return nil and don't
21657 move point."
21658 (let ((fun (if previous 're-search-backward 're-search-forward))
21659 (pos (point))
21660 (re org-outline-regexp-bol)
21661 level l)
21662 (when (condition-case nil (org-back-to-heading t) (error nil))
21663 (setq level (funcall outline-level))
21664 (catch 'exit
21665 (or previous (forward-char 1))
21666 (while (funcall fun re nil t)
21667 (setq l (funcall outline-level))
21668 (when (< l level) (goto-char pos) (throw 'exit nil))
21669 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21670 (goto-char pos)
21671 nil))))
21673 (defun org-show-siblings ()
21674 "Show all siblings of the current headline."
21675 (save-excursion
21676 (while (org-goto-sibling) (org-flag-heading nil)))
21677 (save-excursion
21678 (while (org-goto-sibling 'previous)
21679 (org-flag-heading nil))))
21681 (defun org-goto-first-child ()
21682 "Goto the first child, even if it is invisible.
21683 Return t when a child was found. Otherwise don't move point and
21684 return nil."
21685 (let (level (pos (point)) (re org-outline-regexp-bol))
21686 (when (condition-case nil (org-back-to-heading t) (error nil))
21687 (setq level (outline-level))
21688 (forward-char 1)
21689 (if (and (re-search-forward re nil t) (> (outline-level) level))
21690 (progn (goto-char (match-beginning 0)) t)
21691 (goto-char pos) nil))))
21693 (defun org-show-hidden-entry ()
21694 "Show an entry where even the heading is hidden."
21695 (save-excursion
21696 (org-show-entry)))
21698 (defun org-flag-heading (flag &optional entry)
21699 "Flag the current heading. FLAG non-nil means make invisible.
21700 When ENTRY is non-nil, show the entire entry."
21701 (save-excursion
21702 (org-back-to-heading t)
21703 ;; Check if we should show the entire entry
21704 (if entry
21705 (progn
21706 (org-show-entry)
21707 (save-excursion
21708 (and (outline-next-heading)
21709 (org-flag-heading nil))))
21710 (outline-flag-region (max (point-min) (1- (point)))
21711 (save-excursion (outline-end-of-heading) (point))
21712 flag))))
21714 (defun org-get-next-sibling ()
21715 "Move to next heading of the same level, and return point.
21716 If there is no such heading, return nil.
21717 This is like outline-next-sibling, but invisible headings are ok."
21718 (let ((level (funcall outline-level)))
21719 (outline-next-heading)
21720 (while (and (not (eobp)) (> (funcall outline-level) level))
21721 (outline-next-heading))
21722 (if (or (eobp) (< (funcall outline-level) level))
21724 (point))))
21726 (defun org-get-last-sibling ()
21727 "Move to previous heading of the same level, and return point.
21728 If there is no such heading, return nil."
21729 (let ((opoint (point))
21730 (level (funcall outline-level)))
21731 (outline-previous-heading)
21732 (when (and (/= (point) opoint) (outline-on-heading-p t))
21733 (while (and (> (funcall outline-level) level)
21734 (not (bobp)))
21735 (outline-previous-heading))
21736 (if (< (funcall outline-level) level)
21738 (point)))))
21740 (defun org-end-of-subtree (&optional invisible-ok to-heading)
21741 "Goto to the end of a subtree."
21742 ;; This contains an exact copy of the original function, but it uses
21743 ;; `org-back-to-heading', to make it work also in invisible
21744 ;; trees. And is uses an invisible-ok argument.
21745 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21746 ;; Furthermore, when used inside Org, finding the end of a large subtree
21747 ;; with many children and grandchildren etc, this can be much faster
21748 ;; than the outline version.
21749 (org-back-to-heading invisible-ok)
21750 (let ((first t)
21751 (level (funcall outline-level)))
21752 (if (and (derived-mode-p 'org-mode) (< level 1000))
21753 ;; A true heading (not a plain list item), in Org-mode
21754 ;; This means we can easily find the end by looking
21755 ;; only for the right number of stars. Using a regexp to do
21756 ;; this is so much faster than using a Lisp loop.
21757 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21758 (forward-char 1)
21759 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21760 ;; something else, do it the slow way
21761 (while (and (not (eobp))
21762 (or first (> (funcall outline-level) level)))
21763 (setq first nil)
21764 (outline-next-heading)))
21765 (unless to-heading
21766 (if (memq (preceding-char) '(?\n ?\^M))
21767 (progn
21768 ;; Go to end of line before heading
21769 (forward-char -1)
21770 (if (memq (preceding-char) '(?\n ?\^M))
21771 ;; leave blank line before heading
21772 (forward-char -1))))))
21773 (point))
21775 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21776 "Use Org version in org-mode, for dramatic speed-up."
21777 (if (derived-mode-p 'org-mode)
21778 (progn
21779 (org-end-of-subtree nil t)
21780 (unless (eobp) (backward-char 1)))
21781 ad-do-it))
21783 (defun org-end-of-meta-data-and-drawers ()
21784 "Jump to the first text after meta data and drawers in the current entry.
21785 This will move over empty lines, lines with planning time stamps,
21786 clocking lines, and drawers."
21787 (org-back-to-heading t)
21788 (let ((end (save-excursion (outline-next-heading) (point)))
21789 (re (concat "\\(" org-drawer-regexp "\\)"
21790 "\\|" "[ \t]*" org-keyword-time-regexp)))
21791 (forward-line 1)
21792 (while (re-search-forward re end t)
21793 (if (not (match-end 1))
21794 ;; empty or planning line
21795 (forward-line 1)
21796 ;; a drawer, find the end
21797 (re-search-forward "^[ \t]*:END:" end 'move)
21798 (forward-line 1)))
21799 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21800 (point)))
21802 (defun org-forward-heading-same-level (arg &optional invisible-ok)
21803 "Move forward to the arg'th subheading at same level as this one.
21804 Stop at the first and last subheadings of a superior heading.
21805 Normally this only looks at visible headings, but when INVISIBLE-OK is
21806 non-nil it will also look at invisible ones."
21807 (interactive "p")
21808 (org-back-to-heading invisible-ok)
21809 (org-at-heading-p)
21810 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21811 (re (format "^\\*\\{1,%d\\} " level))
21813 (forward-char 1)
21814 (while (> arg 0)
21815 (while (and (re-search-forward re nil 'move)
21816 (setq l (- (match-end 0) (match-beginning 0) 1))
21817 (= l level)
21818 (not invisible-ok)
21819 (progn (backward-char 1) (outline-invisible-p)))
21820 (if (< l level) (setq arg 1)))
21821 (setq arg (1- arg)))
21822 (beginning-of-line 1)))
21824 (defun org-backward-heading-same-level (arg &optional invisible-ok)
21825 "Move backward to the arg'th subheading at same level as this one.
21826 Stop at the first and last subheadings of a superior heading."
21827 (interactive "p")
21828 (org-back-to-heading)
21829 (org-at-heading-p)
21830 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21831 (re (format "^\\*\\{1,%d\\} " level))
21833 (while (> arg 0)
21834 (while (and (re-search-backward re nil 'move)
21835 (setq l (- (match-end 0) (match-beginning 0) 1))
21836 (= l level)
21837 (not invisible-ok)
21838 (outline-invisible-p))
21839 (if (< l level) (setq arg 1)))
21840 (setq arg (1- arg)))))
21842 (defun org-forward-element ()
21843 "Move forward by one element.
21844 Move to the next element at the same level, when possible."
21845 (interactive)
21846 (cond ((eobp) (error "Cannot move further down"))
21847 ((org-with-limited-levels (org-at-heading-p))
21848 (let ((origin (point)))
21849 (org-forward-heading-same-level 1)
21850 (unless (org-with-limited-levels (org-at-heading-p))
21851 (goto-char origin)
21852 (error "Cannot move further down"))))
21854 (let* ((elem (org-element-at-point))
21855 (end (org-element-property :end elem))
21856 (parent (org-element-property :parent elem)))
21857 (if (and parent (= (org-element-property :contents-end parent) end))
21858 (goto-char (org-element-property :end parent))
21859 (goto-char end))))))
21861 (defun org-backward-element ()
21862 "Move backward by one element.
21863 Move to the previous element at the same level, when possible."
21864 (interactive)
21865 (cond ((bobp) (error "Cannot move further up"))
21866 ((org-with-limited-levels (org-at-heading-p))
21867 ;; At an headline, move to the previous one, if any, or stay
21868 ;; here.
21869 (let ((origin (point)))
21870 (org-backward-heading-same-level 1)
21871 (unless (org-with-limited-levels (org-at-heading-p))
21872 (goto-char origin)
21873 (error "Cannot move further up"))))
21875 (let* ((trail (org-element-at-point 'keep-trail))
21876 (elem (car trail))
21877 (prev-elem (nth 1 trail))
21878 (beg (org-element-property :begin elem)))
21879 (cond
21880 ;; Move to beginning of current element if point isn't
21881 ;; there already.
21882 ((/= (point) beg) (goto-char beg))
21883 (prev-elem (goto-char (org-element-property :begin prev-elem)))
21884 ((org-before-first-heading-p) (goto-char (point-min)))
21885 (t (org-back-to-heading)))))))
21887 (defun org-up-element ()
21888 "Move to upper element."
21889 (interactive)
21890 (if (org-with-limited-levels (org-at-heading-p))
21891 (unless (org-up-heading-safe) (error "No surrounding element"))
21892 (let* ((elem (org-element-at-point))
21893 (parent (org-element-property :parent elem)))
21894 (if parent (goto-char (org-element-property :begin parent))
21895 (if (org-with-limited-levels (org-before-first-heading-p))
21896 (error "No surrounding element")
21897 (org-with-limited-levels (org-back-to-heading)))))))
21899 (defvar org-element-greater-elements)
21900 (defun org-down-element ()
21901 "Move to inner element."
21902 (interactive)
21903 (let ((element (org-element-at-point)))
21904 (cond
21905 ((memq (org-element-type element) '(plain-list table))
21906 (goto-char (org-element-property :contents-begin element))
21907 (forward-char))
21908 ((memq (org-element-type element) org-element-greater-elements)
21909 ;; If contents are hidden, first disclose them.
21910 (when (org-element-property :hiddenp element) (org-cycle))
21911 (goto-char (or (org-element-property :contents-begin element)
21912 (error "No content for this element"))))
21913 (t (error "No inner element")))))
21915 (defun org-drag-element-backward ()
21916 "Move backward element at point."
21917 (interactive)
21918 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
21919 (let* ((trail (org-element-at-point 'keep-trail))
21920 (elem (car trail))
21921 (prev-elem (nth 1 trail)))
21922 ;; Error out if no previous element or previous element is
21923 ;; a parent of the current one.
21924 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
21925 (error "Cannot drag element backward")
21926 (let ((pos (point)))
21927 (org-element-swap-A-B prev-elem elem)
21928 (goto-char (+ (org-element-property :begin prev-elem)
21929 (- pos (org-element-property :begin elem)))))))))
21931 (defun org-drag-element-forward ()
21932 "Move forward element at point."
21933 (interactive)
21934 (let* ((pos (point))
21935 (elem (org-element-at-point)))
21936 (when (= (point-max) (org-element-property :end elem))
21937 (error "Cannot drag element forward"))
21938 (goto-char (org-element-property :end elem))
21939 (let ((next-elem (org-element-at-point)))
21940 (when (or (org-element-nested-p elem next-elem)
21941 (and (eq (org-element-type next-elem) 'headline)
21942 (not (eq (org-element-type elem) 'headline))))
21943 (goto-char pos)
21944 (error "Cannot drag element forward"))
21945 ;; Compute new position of point: it's shifted by NEXT-ELEM
21946 ;; body's length (without final blanks) and by the length of
21947 ;; blanks between ELEM and NEXT-ELEM.
21948 (let ((size-next (- (save-excursion
21949 (goto-char (org-element-property :end next-elem))
21950 (skip-chars-backward " \r\t\n")
21951 (forward-line)
21952 ;; Small correction if buffer doesn't end
21953 ;; with a newline character.
21954 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
21955 (org-element-property :begin next-elem)))
21956 (size-blank (- (org-element-property :end elem)
21957 (save-excursion
21958 (goto-char (org-element-property :end elem))
21959 (skip-chars-backward " \r\t\n")
21960 (forward-line)
21961 (point)))))
21962 (org-element-swap-A-B elem next-elem)
21963 (goto-char (+ pos size-next size-blank))))))
21965 (defun org-mark-element ()
21966 "Put point at beginning of this element, mark at end.
21968 Interactively, if this command is repeated or (in Transient Mark
21969 mode) if the mark is active, it marks the next element after the
21970 ones already marked."
21971 (interactive)
21972 (let (deactivate-mark)
21973 (if (and (org-called-interactively-p 'any)
21974 (or (and (eq last-command this-command) (mark t))
21975 (and transient-mark-mode mark-active)))
21976 (set-mark
21977 (save-excursion
21978 (goto-char (mark))
21979 (goto-char (org-element-property :end (org-element-at-point)))))
21980 (let ((element (org-element-at-point)))
21981 (end-of-line)
21982 (push-mark (org-element-property :end element) t t)
21983 (goto-char (org-element-property :begin element))))))
21985 (defun org-narrow-to-element ()
21986 "Narrow buffer to current element."
21987 (interactive)
21988 (let ((elem (org-element-at-point)))
21989 (cond
21990 ((eq (car elem) 'headline)
21991 (narrow-to-region
21992 (org-element-property :begin elem)
21993 (org-element-property :end elem)))
21994 ((memq (car elem) org-element-greater-elements)
21995 (narrow-to-region
21996 (org-element-property :contents-begin elem)
21997 (org-element-property :contents-end elem)))
21999 (narrow-to-region
22000 (org-element-property :begin elem)
22001 (org-element-property :end elem))))))
22003 (defun org-transpose-element ()
22004 "Transpose current and previous elements, keeping blank lines between.
22005 Point is moved after both elements."
22006 (interactive)
22007 (org-skip-whitespace)
22008 (let ((end (org-element-property :end (org-element-at-point))))
22009 (org-drag-element-backward)
22010 (goto-char end)))
22012 (defun org-unindent-buffer ()
22013 "Un-indent the visible part of the buffer.
22014 Relative indentation (between items, inside blocks, etc.) isn't
22015 modified."
22016 (interactive)
22017 (unless (eq major-mode 'org-mode)
22018 (error "Cannot un-indent a buffer not in Org mode"))
22019 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22020 unindent-tree ; For byte-compiler.
22021 (unindent-tree
22022 (function
22023 (lambda (contents)
22024 (mapc
22025 (lambda (element)
22026 (if (memq (org-element-type element) '(headline section))
22027 (funcall unindent-tree (org-element-contents element))
22028 (save-excursion
22029 (save-restriction
22030 (narrow-to-region
22031 (org-element-property :begin element)
22032 (org-element-property :end element))
22033 (org-do-remove-indentation)))))
22034 (reverse contents))))))
22035 (funcall unindent-tree (org-element-contents parse-tree))))
22037 (defun org-show-subtree ()
22038 "Show everything after this heading at deeper levels."
22039 (interactive)
22040 (outline-flag-region
22041 (point)
22042 (save-excursion
22043 (org-end-of-subtree t t))
22044 nil))
22046 (defun org-show-entry ()
22047 "Show the body directly following this heading.
22048 Show the heading too, if it is currently invisible."
22049 (interactive)
22050 (save-excursion
22051 (condition-case nil
22052 (progn
22053 (org-back-to-heading t)
22054 (outline-flag-region
22055 (max (point-min) (1- (point)))
22056 (save-excursion
22057 (if (re-search-forward
22058 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22059 (match-beginning 1)
22060 (point-max)))
22061 nil)
22062 (org-cycle-hide-drawers 'children))
22063 (error nil))))
22065 (defun org-make-options-regexp (kwds &optional extra)
22066 "Make a regular expression for keyword lines."
22067 (concat
22068 "^#\\+\\("
22069 (mapconcat 'regexp-quote kwds "\\|")
22070 (if extra (concat "\\|" extra))
22071 "\\):[ \t]*\\(.*\\)"))
22073 ;; Make isearch reveal the necessary context
22074 (defun org-isearch-end ()
22075 "Reveal context after isearch exits."
22076 (when isearch-success ; only if search was successful
22077 (if (featurep 'xemacs)
22078 ;; Under XEmacs, the hook is run in the correct place,
22079 ;; we directly show the context.
22080 (org-show-context 'isearch)
22081 ;; In Emacs the hook runs *before* restoring the overlays.
22082 ;; So we have to use a one-time post-command-hook to do this.
22083 ;; (Emacs 22 has a special variable, see function `org-mode')
22084 (unless (and (boundp 'isearch-mode-end-hook-quit)
22085 isearch-mode-end-hook-quit)
22086 ;; Only when the isearch was not quitted.
22087 (org-add-hook 'post-command-hook 'org-isearch-post-command
22088 'append 'local)))))
22090 (defun org-isearch-post-command ()
22091 "Remove self from hook, and show context."
22092 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22093 (org-show-context 'isearch))
22096 ;;;; Integration with and fixes for other packages
22098 ;;; Imenu support
22100 (defvar org-imenu-markers nil
22101 "All markers currently used by Imenu.")
22102 (make-variable-buffer-local 'org-imenu-markers)
22104 (defun org-imenu-new-marker (&optional pos)
22105 "Return a new marker for use by Imenu, and remember the marker."
22106 (let ((m (make-marker)))
22107 (move-marker m (or pos (point)))
22108 (push m org-imenu-markers)
22111 (defun org-imenu-get-tree ()
22112 "Produce the index for Imenu."
22113 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22114 (setq org-imenu-markers nil)
22115 (let* ((n org-imenu-depth)
22116 (re (concat "^" (org-get-limited-outline-regexp)))
22117 (subs (make-vector (1+ n) nil))
22118 (last-level 0)
22119 m level head)
22120 (save-excursion
22121 (save-restriction
22122 (widen)
22123 (goto-char (point-max))
22124 (while (re-search-backward re nil t)
22125 (setq level (org-reduced-level (funcall outline-level)))
22126 (when (and (<= level n)
22127 (looking-at org-complex-heading-regexp))
22128 (setq head (org-link-display-format
22129 (org-match-string-no-properties 4))
22130 m (org-imenu-new-marker))
22131 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22132 (if (>= level last-level)
22133 (push (cons head m) (aref subs level))
22134 (push (cons head (aref subs (1+ level))) (aref subs level))
22135 (loop for i from (1+ level) to n do (aset subs i nil)))
22136 (setq last-level level)))))
22137 (aref subs 1)))
22139 (eval-after-load "imenu"
22140 '(progn
22141 (add-hook 'imenu-after-jump-hook
22142 (lambda ()
22143 (if (derived-mode-p 'org-mode)
22144 (org-show-context 'org-goto))))))
22146 (defun org-link-display-format (link)
22147 "Replace a link with either the description, or the link target
22148 if no description is present"
22149 (save-match-data
22150 (if (string-match org-bracket-link-analytic-regexp link)
22151 (replace-match (if (match-end 5)
22152 (match-string 5 link)
22153 (concat (match-string 1 link)
22154 (match-string 3 link)))
22155 nil t link)
22156 link)))
22158 (defun org-toggle-link-display ()
22159 "Toggle the literal or descriptive display of links."
22160 (interactive)
22161 (if org-descriptive-links
22162 (progn (org-remove-from-invisibility-spec '(org-link))
22163 (org-restart-font-lock)
22164 (setq org-descriptive-links nil))
22165 (progn (add-to-invisibility-spec '(org-link))
22166 (org-restart-font-lock)
22167 (setq org-descriptive-links t))))
22169 ;; Speedbar support
22171 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22172 "Overlay marking the agenda restriction line in speedbar.")
22173 (overlay-put org-speedbar-restriction-lock-overlay
22174 'face 'org-agenda-restriction-lock)
22175 (overlay-put org-speedbar-restriction-lock-overlay
22176 'help-echo "Agendas are currently limited to this item.")
22177 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22179 (defun org-speedbar-set-agenda-restriction ()
22180 "Restrict future agenda commands to the location at point in speedbar.
22181 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22182 (interactive)
22183 (require 'org-agenda)
22184 (let (p m tp np dir txt)
22185 (cond
22186 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22187 'org-imenu t))
22188 (setq m (get-text-property p 'org-imenu-marker))
22189 (with-current-buffer (marker-buffer m)
22190 (goto-char m)
22191 (org-agenda-set-restriction-lock 'subtree)))
22192 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22193 'speedbar-function 'speedbar-find-file))
22194 (setq tp (previous-single-property-change
22195 (1+ p) 'speedbar-function)
22196 np (next-single-property-change
22197 tp 'speedbar-function)
22198 dir (speedbar-line-directory)
22199 txt (buffer-substring-no-properties (or tp (point-min))
22200 (or np (point-max))))
22201 (with-current-buffer (find-file-noselect
22202 (let ((default-directory dir))
22203 (expand-file-name txt)))
22204 (unless (derived-mode-p 'org-mode)
22205 (error "Cannot restrict to non-Org-mode file"))
22206 (org-agenda-set-restriction-lock 'file)))
22207 (t (error "Don't know how to restrict Org-mode's agenda")))
22208 (move-overlay org-speedbar-restriction-lock-overlay
22209 (point-at-bol) (point-at-eol))
22210 (setq current-prefix-arg nil)
22211 (org-agenda-maybe-redo)))
22213 (eval-after-load "speedbar"
22214 '(progn
22215 (speedbar-add-supported-extension ".org")
22216 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22217 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22218 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22219 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22220 (add-hook 'speedbar-visiting-tag-hook
22221 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22223 ;;; Fixes and Hacks for problems with other packages
22225 ;; Make flyspell not check words in links, to not mess up our keymap
22226 (defun org-mode-flyspell-verify ()
22227 "Don't let flyspell put overlays at active buttons, or on
22228 {todo,all-time,additional-option-like}-keywords."
22229 (let ((pos (max (1- (point)) (point-min)))
22230 (word (thing-at-point 'word)))
22231 (and (not (get-text-property pos 'keymap))
22232 (not (get-text-property pos 'org-no-flyspell))
22233 (not (member word org-todo-keywords-1))
22234 (not (member word org-all-time-keywords))
22235 (not (member word org-options-keywords))
22236 (not (member word (mapcar 'car org-startup-options)))
22237 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22239 (defun org-remove-flyspell-overlays-in (beg end)
22240 "Remove flyspell overlays in region."
22241 (and (org-bound-and-true-p flyspell-mode)
22242 (fboundp 'flyspell-delete-region-overlays)
22243 (flyspell-delete-region-overlays beg end))
22244 (add-text-properties beg end '(org-no-flyspell t)))
22246 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22247 (eval-after-load "bookmark"
22248 '(if (boundp 'bookmark-after-jump-hook)
22249 ;; We can use the hook
22250 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22251 ;; Hook not available, use advice
22252 (defadvice bookmark-jump (after org-make-visible activate)
22253 "Make the position visible."
22254 (org-bookmark-jump-unhide))))
22256 ;; Make sure saveplace shows the location if it was hidden
22257 (eval-after-load "saveplace"
22258 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22259 "Make the position visible."
22260 (org-bookmark-jump-unhide)))
22262 ;; Make sure ecb shows the location if it was hidden
22263 (eval-after-load "ecb"
22264 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22265 "Make hierarchy visible when jumping into location from ECB tree buffer."
22266 (if (derived-mode-p 'org-mode)
22267 (org-show-context))))
22269 (defun org-bookmark-jump-unhide ()
22270 "Unhide the current position, to show the bookmark location."
22271 (and (derived-mode-p 'org-mode)
22272 (or (outline-invisible-p)
22273 (save-excursion (goto-char (max (point-min) (1- (point))))
22274 (outline-invisible-p)))
22275 (org-show-context 'bookmark-jump)))
22277 ;; Make session.el ignore our circular variable
22278 (eval-after-load "session"
22279 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22281 ;;;; Experimental code
22283 (defun org-closed-in-range ()
22284 "Sparse tree of items closed in a certain time range.
22285 Still experimental, may disappear in the future."
22286 (interactive)
22287 ;; Get the time interval from the user.
22288 (let* ((time1 (org-float-time
22289 (org-read-date nil 'to-time nil "Starting date: ")))
22290 (time2 (org-float-time
22291 (org-read-date nil 'to-time nil "End date:")))
22292 ;; callback function
22293 (callback (lambda ()
22294 (let ((time
22295 (org-float-time
22296 (apply 'encode-time
22297 (org-parse-time-string
22298 (match-string 1))))))
22299 ;; check if time in interval
22300 (and (>= time time1) (<= time time2))))))
22301 ;; make tree, check each match with the callback
22302 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22304 ;;;; Finish up
22306 (provide 'org)
22308 (run-hooks 'org-load-hook)
22310 ;;; org.el ends here