org.el (org-set-tags-command): Fix bug.
[org-mode.git] / lisp / org.el
blob7939804ae060f000144c167070930d287ca7c309
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2013 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 (load "org-loaddefs.el" t t)
83 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
84 ;; some places -- e.g. see the macro org-with-limited-levels.
86 ;; In Org buffers, the value of `outline-regexp' is that of
87 ;; `org-outline-regexp'. The only function still directly relying on
88 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
89 ;; job when `orgstruct-mode' is active.
90 (defvar org-outline-regexp "\\*+ "
91 "Regexp to match Org headlines.")
93 (defvar org-outline-regexp-bol "^\\*+ "
94 "Regexp to match Org headlines.
95 This is similar to `org-outline-regexp' but additionally makes
96 sure that we are at the beginning of the line.")
98 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
99 "Matches an headline, putting stars and text into groups.
100 Stars are put in group 1 and the trimmed body in group 2.")
102 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
103 (when (fboundp 'defvaralias)
104 (unless (boundp 'calendar-view-holidays-initially-flag)
105 (defvaralias 'calendar-view-holidays-initially-flag
106 'view-calendar-holidays-initially))
107 (unless (boundp 'calendar-view-diary-initially-flag)
108 (defvaralias 'calendar-view-diary-initially-flag
109 'view-diary-entries-initially))
110 (unless (boundp 'diary-fancy-buffer)
111 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
113 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
114 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
115 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
116 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
117 (declare-function org-at-clock-log-p "org-clock" ())
118 (declare-function org-clock-timestamps-up "org-clock" ())
119 (declare-function org-clock-timestamps-down "org-clock" ())
120 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
122 (declare-function orgtbl-mode "org-table" (&optional arg))
123 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
124 (declare-function org-beamer-mode "org-beamer" ())
125 (declare-function org-table-edit-field "org-table" (arg))
126 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
127 (declare-function org-id-get-create "org-id" (&optional force))
128 (declare-function org-id-find-id-file "org-id" (id))
129 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
130 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
131 (declare-function org-table-align "org-table" ())
132 (declare-function org-table-paste-rectangle "org-table" ())
133 (declare-function org-table-maybe-eval-formula "org-table" ())
134 (declare-function org-table-maybe-recalculate-line "org-table" ())
136 ;; load languages based on value of `org-babel-load-languages'
137 (defvar org-babel-load-languages)
139 ;;;###autoload
140 (defun org-babel-do-load-languages (sym value)
141 "Load the languages defined in `org-babel-load-languages'."
142 (set-default sym value)
143 (mapc (lambda (pair)
144 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
145 (if active
146 (progn
147 (require (intern (concat "ob-" lang))))
148 (progn
149 (funcall 'fmakunbound
150 (intern (concat "org-babel-execute:" lang)))
151 (funcall 'fmakunbound
152 (intern (concat "org-babel-expand-body:" lang)))))))
153 org-babel-load-languages))
155 (defcustom org-babel-load-languages '((emacs-lisp . t))
156 "Languages which can be evaluated in Org-mode buffers.
157 This list can be used to load support for any of the languages
158 below, note that each language will depend on a different set of
159 system executables and/or Emacs modes. When a language is
160 \"loaded\", then code blocks in that language can be evaluated
161 with `org-babel-execute-src-block' bound by default to C-c
162 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
163 be set to remove code block evaluation from the C-c C-c
164 keybinding. By default only Emacs Lisp (which has no
165 requirements) is loaded."
166 :group 'org-babel
167 :set 'org-babel-do-load-languages
168 :version "24.1"
169 :type '(alist :tag "Babel Languages"
170 :key-type
171 (choice
172 (const :tag "Awk" awk)
173 (const :tag "C" C)
174 (const :tag "R" R)
175 (const :tag "Asymptote" asymptote)
176 (const :tag "Calc" calc)
177 (const :tag "Clojure" clojure)
178 (const :tag "CSS" css)
179 (const :tag "Ditaa" ditaa)
180 (const :tag "Dot" dot)
181 (const :tag "Emacs Lisp" emacs-lisp)
182 (const :tag "Fortran" fortran)
183 (const :tag "Gnuplot" gnuplot)
184 (const :tag "Haskell" haskell)
185 (const :tag "IO" io)
186 (const :tag "Java" java)
187 (const :tag "Javascript" js)
188 (const :tag "LaTeX" latex)
189 (const :tag "Ledger" ledger)
190 (const :tag "Lilypond" lilypond)
191 (const :tag "Lisp" lisp)
192 (const :tag "Maxima" maxima)
193 (const :tag "Matlab" matlab)
194 (const :tag "Mscgen" mscgen)
195 (const :tag "Ocaml" ocaml)
196 (const :tag "Octave" octave)
197 (const :tag "Org" org)
198 (const :tag "Perl" perl)
199 (const :tag "Pico Lisp" picolisp)
200 (const :tag "PlantUML" plantuml)
201 (const :tag "Python" python)
202 (const :tag "Ruby" ruby)
203 (const :tag "Sass" sass)
204 (const :tag "Scala" scala)
205 (const :tag "Scheme" scheme)
206 (const :tag "Screen" screen)
207 (const :tag "Shell Script" sh)
208 (const :tag "Shen" shen)
209 (const :tag "Sql" sql)
210 (const :tag "Sqlite" sqlite))
211 :value-type (boolean :tag "Activate" :value t)))
213 ;;;; Customization variables
214 (defcustom org-clone-delete-id nil
215 "Remove ID property of clones of a subtree.
216 When non-nil, clones of a subtree don't inherit the ID property.
217 Otherwise they inherit the ID property with a new unique
218 identifier."
219 :type 'boolean
220 :version "24.1"
221 :group 'org-id)
223 ;;; Version
224 (require 'org-compat)
225 (org-check-version)
227 ;;;###autoload
228 (defun org-version (&optional here full message)
229 "Show the org-mode version in the echo area.
230 With prefix argument HERE, insert it at point.
231 When FULL is non-nil, use a verbose version string.
232 When MESSAGE is non-nil, display a message with the version."
233 (interactive "P")
234 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
235 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs.el")))
236 (org-trash (or
237 (and (fboundp 'org-release) (fboundp 'org-git-version))
238 (load (concat org-dir "org-version.el")
239 'noerror 'nomessage 'nosuffix)))
240 (org-version (org-release))
241 (git-version (org-git-version))
242 (version (format "Org-mode version %s (%s @ %s)"
243 org-version
244 git-version
245 (if org-install-dir
246 (if (string= org-dir org-install-dir)
247 org-install-dir
248 (concat "mixed installation! " org-install-dir " and " org-dir))
249 "org-loaddefs.el can not be found!")))
250 (_version (if full version org-version)))
251 (if (org-called-interactively-p 'interactive)
252 (if here
253 (insert version)
254 (message version))
255 (if message (message _version))
256 _version)))
258 (defconst org-version (org-version))
260 ;;; Compatibility constants
262 ;;; The custom variables
264 (defgroup org nil
265 "Outline-based notes management and organizer."
266 :tag "Org"
267 :group 'outlines
268 :group 'calendar)
270 (defcustom org-mode-hook nil
271 "Mode hook for Org-mode, run after the mode was turned on."
272 :group 'org
273 :type 'hook)
275 (defcustom org-load-hook nil
276 "Hook that is run after org.el has been loaded."
277 :group 'org
278 :type 'hook)
280 (defcustom org-log-buffer-setup-hook nil
281 "Hook that is run after an Org log buffer is created."
282 :group 'org
283 :version "24.1"
284 :type 'hook)
286 (defvar org-modules) ; defined below
287 (defvar org-modules-loaded nil
288 "Have the modules been loaded already?")
290 (defun org-load-modules-maybe (&optional force)
291 "Load all extensions listed in `org-modules'."
292 (when (or force (not org-modules-loaded))
293 (mapc (lambda (ext)
294 (condition-case nil (require ext)
295 (error (message "Problems while trying to load feature `%s'" ext))))
296 org-modules)
297 (setq org-modules-loaded t)))
299 (defun org-set-modules (var value)
300 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
301 (set var value)
302 (when (featurep 'org)
303 (org-load-modules-maybe 'force)))
305 (when (org-bound-and-true-p org-modules)
306 (let ((a (member 'org-infojs org-modules)))
307 (and a (setcar a 'org-jsinfo))))
309 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
310 "Modules that should always be loaded together with org.el.
311 If a description starts with <C>, the file is not part of Emacs
312 and loading it will require that you have downloaded and properly installed
313 the org-mode distribution.
315 You can also use this system to load external packages (i.e. neither Org
316 core modules, nor modules from the CONTRIB directory). Just add symbols
317 to the end of the list. If the package is called org-xyz.el, then you need
318 to add the symbol `xyz', and the package must have a call to
320 (provide 'org-xyz)"
321 :group 'org
322 :set 'org-set-modules
323 :type
324 '(set :greedy t
325 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
326 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
327 (const :tag " crypt: Encryption of subtrees" org-crypt)
328 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
329 (const :tag " docview: Links to doc-view buffers" org-docview)
330 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
331 (const :tag " id: Global IDs for identifying entries" org-id)
332 (const :tag " info: Links to Info nodes" org-info)
333 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
334 (const :tag " habit: Track your consistency with habits" org-habit)
335 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
336 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
337 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
338 (const :tag " mew Links to Mew folders/messages" org-mew)
339 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
340 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
341 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
342 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
343 (const :tag " vm: Links to VM folders/messages" org-vm)
344 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
345 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
346 (const :tag " mouse: Additional mouse support" org-mouse)
347 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
349 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
350 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
351 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
352 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
353 (const :tag "C collector: Collect properties into tables" org-collector)
354 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
355 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
356 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
357 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
358 (const :tag "C eval: Include command output as text" org-eval)
359 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
360 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
361 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
362 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
363 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
365 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
367 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
368 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
369 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
370 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
371 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
372 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
373 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
374 (const :tag "C mtags: Support for muse-like tags" org-mtags)
375 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
376 (const :tag "C registry: A registry for Org-mode links" org-registry)
377 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
378 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
379 (const :tag "C secretary: Team management with org-mode" org-secretary)
380 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
381 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
382 (const :tag "C track: Keep up with Org-mode development" org-track)
383 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
384 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
385 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
387 (defcustom org-support-shift-select nil
388 "Non-nil means make shift-cursor commands select text when possible.
390 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
391 start selecting a region, or enlarge regions started in this way.
392 In Org-mode, in special contexts, these same keys are used for
393 other purposes, important enough to compete with shift selection.
394 Org tries to balance these needs by supporting `shift-select-mode'
395 outside these special contexts, under control of this variable.
397 The default of this variable is nil, to avoid confusing behavior. Shifted
398 cursor keys will then execute Org commands in the following contexts:
399 - on a headline, changing TODO state (left/right) and priority (up/down)
400 - on a time stamp, changing the time
401 - in a plain list item, changing the bullet type
402 - in a property definition line, switching between allowed values
403 - in the BEGIN line of a clock table (changing the time block).
404 Outside these contexts, the commands will throw an error.
406 When this variable is t and the cursor is not in a special
407 context, Org-mode will support shift-selection for making and
408 enlarging regions. To make this more effective, the bullet
409 cycling will no longer happen anywhere in an item line, but only
410 if the cursor is exactly on the bullet.
412 If you set this variable to the symbol `always', then the keys
413 will not be special in headlines, property lines, and item lines,
414 to make shift selection work there as well. If this is what you
415 want, you can use the following alternative commands: `C-c C-t'
416 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
417 can be used to switch TODO sets, `C-c -' to cycle item bullet
418 types, and properties can be edited by hand or in column view.
420 However, when the cursor is on a timestamp, shift-cursor commands
421 will still edit the time stamp - this is just too good to give up.
423 XEmacs user should have this variable set to nil, because
424 `shift-select-mode' is in Emacs 23 or later only."
425 :group 'org
426 :type '(choice
427 (const :tag "Never" nil)
428 (const :tag "When outside special context" t)
429 (const :tag "Everywhere except timestamps" always)))
431 (defcustom org-loop-over-headlines-in-active-region nil
432 "Shall some commands act upon headlines in the active region?
434 When set to `t', some commands will be performed in all headlines
435 within the active region.
437 When set to `start-level', some commands will be performed in all
438 headlines within the active region, provided that these headlines
439 are of the same level than the first one.
441 When set to a string, those commands will be performed on the
442 matching headlines within the active region. Such string must be
443 a tags/property/todo match as it is used in the agenda tags view.
445 The list of commands is: `org-schedule', `org-deadline',
446 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
447 `org-archive-to-archive-sibling'. The archiving commands skip
448 already archived entries."
449 :type '(choice (const :tag "Don't loop" nil)
450 (const :tag "All headlines in active region" t)
451 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
452 (string :tag "Tags/Property/Todo matcher"))
453 :version "24.1"
454 :group 'org-todo
455 :group 'org-archive)
457 (defgroup org-startup nil
458 "Options concerning startup of Org-mode."
459 :tag "Org Startup"
460 :group 'org)
462 (defcustom org-startup-folded t
463 "Non-nil means entering Org-mode will switch to OVERVIEW.
464 This can also be configured on a per-file basis by adding one of
465 the following lines anywhere in the buffer:
467 #+STARTUP: fold (or `overview', this is equivalent)
468 #+STARTUP: nofold (or `showall', this is equivalent)
469 #+STARTUP: content
470 #+STARTUP: showeverything
472 By default, this option is ignored when Org opens agenda files
473 for the first time. If you want the agenda to honor the startup
474 option, set `org-agenda-inhibit-startup' to nil."
475 :group 'org-startup
476 :type '(choice
477 (const :tag "nofold: show all" nil)
478 (const :tag "fold: overview" t)
479 (const :tag "content: all headlines" content)
480 (const :tag "show everything, even drawers" showeverything)))
482 (defcustom org-startup-truncated t
483 "Non-nil means entering Org-mode will set `truncate-lines'.
484 This is useful since some lines containing links can be very long and
485 uninteresting. Also tables look terrible when wrapped."
486 :group 'org-startup
487 :type 'boolean)
489 (defcustom org-startup-indented nil
490 "Non-nil means turn on `org-indent-mode' on startup.
491 This can also be configured on a per-file basis by adding one of
492 the following lines anywhere in the buffer:
494 #+STARTUP: indent
495 #+STARTUP: noindent"
496 :group 'org-structure
497 :type '(choice
498 (const :tag "Not" nil)
499 (const :tag "Globally (slow on startup in large files)" t)))
501 (defcustom org-use-sub-superscripts t
502 "Non-nil means interpret \"_\" and \"^\" for export.
503 When this option is turned on, you can use TeX-like syntax for sub- and
504 superscripts. Several characters after \"_\" or \"^\" will be
505 considered as a single item - so grouping with {} is normally not
506 needed. For example, the following things will be parsed as single
507 sub- or superscripts.
509 10^24 or 10^tau several digits will be considered 1 item.
510 10^-12 or 10^-tau a leading sign with digits or a word
511 x^2-y^3 will be read as x^2 - y^3, because items are
512 terminated by almost any nonword/nondigit char.
513 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
515 Still, ambiguity is possible - so when in doubt use {} to enclose the
516 sub/superscript. If you set this variable to the symbol `{}',
517 the braces are *required* in order to trigger interpretations as
518 sub/superscript. This can be helpful in documents that need \"_\"
519 frequently in plain text.
521 Not all export backends support this, but HTML does.
523 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
524 :group 'org-startup
525 :group 'org-export-translation
526 :version "24.1"
527 :type '(choice
528 (const :tag "Always interpret" t)
529 (const :tag "Only with braces" {})
530 (const :tag "Never interpret" nil)))
532 (if (fboundp 'defvaralias)
533 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
536 (defcustom org-startup-with-beamer-mode nil
537 "Non-nil means turn on `org-beamer-mode' on startup.
538 This can also be configured on a per-file basis by adding one of
539 the following lines anywhere in the buffer:
541 #+STARTUP: beamer"
542 :group 'org-startup
543 :version "24.1"
544 :type 'boolean)
546 (defcustom org-startup-align-all-tables nil
547 "Non-nil means align all tables when visiting a file.
548 This is useful when the column width in tables is forced with <N> cookies
549 in table fields. Such tables will look correct only after the first re-align.
550 This can also be configured on a per-file basis by adding one of
551 the following lines anywhere in the buffer:
552 #+STARTUP: align
553 #+STARTUP: noalign"
554 :group 'org-startup
555 :type 'boolean)
557 (defcustom org-startup-with-inline-images nil
558 "Non-nil means show inline images when loading a new Org file.
559 This can also be configured on a per-file basis by adding one of
560 the following lines anywhere in the buffer:
561 #+STARTUP: inlineimages
562 #+STARTUP: noinlineimages"
563 :group 'org-startup
564 :version "24.1"
565 :type 'boolean)
567 (defcustom org-insert-mode-line-in-empty-file nil
568 "Non-nil means insert the first line setting Org-mode in empty files.
569 When the function `org-mode' is called interactively in an empty file, this
570 normally means that the file name does not automatically trigger Org-mode.
571 To ensure that the file will always be in Org-mode in the future, a
572 line enforcing Org-mode will be inserted into the buffer, if this option
573 has been set."
574 :group 'org-startup
575 :type 'boolean)
577 (defcustom org-replace-disputed-keys nil
578 "Non-nil means use alternative key bindings for some keys.
579 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
580 These keys are also used by other packages like shift-selection-mode'
581 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
582 If you want to use Org-mode together with one of these other modes,
583 or more generally if you would like to move some Org-mode commands to
584 other keys, set this variable and configure the keys with the variable
585 `org-disputed-keys'.
587 This option is only relevant at load-time of Org-mode, and must be set
588 *before* org.el is loaded. Changing it requires a restart of Emacs to
589 become effective."
590 :group 'org-startup
591 :type 'boolean)
593 (defcustom org-use-extra-keys nil
594 "Non-nil means use extra key sequence definitions for certain commands.
595 This happens automatically if you run XEmacs or if `window-system'
596 is nil. This variable lets you do the same manually. You must
597 set it before loading org.
599 Example: on Carbon Emacs 22 running graphically, with an external
600 keyboard on a Powerbook, the default way of setting M-left might
601 not work for either Alt or ESC. Setting this variable will make
602 it work for ESC."
603 :group 'org-startup
604 :type 'boolean)
606 (if (fboundp 'defvaralias)
607 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
609 (defcustom org-disputed-keys
610 '(([(shift up)] . [(meta p)])
611 ([(shift down)] . [(meta n)])
612 ([(shift left)] . [(meta -)])
613 ([(shift right)] . [(meta +)])
614 ([(control shift right)] . [(meta shift +)])
615 ([(control shift left)] . [(meta shift -)]))
616 "Keys for which Org-mode and other modes compete.
617 This is an alist, cars are the default keys, second element specifies
618 the alternative to use when `org-replace-disputed-keys' is t.
620 Keys can be specified in any syntax supported by `define-key'.
621 The value of this option takes effect only at Org-mode's startup,
622 therefore you'll have to restart Emacs to apply it after changing."
623 :group 'org-startup
624 :type 'alist)
626 (defun org-key (key)
627 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
628 Or return the original if not disputed.
629 Also apply the translations defined in `org-xemacs-key-equivalents'."
630 (when org-replace-disputed-keys
631 (let* ((nkey (key-description key))
632 (x (org-find-if (lambda (x)
633 (equal (key-description (car x)) nkey))
634 org-disputed-keys)))
635 (setq key (if x (cdr x) key))))
636 (when (featurep 'xemacs)
637 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
638 key)
640 (defun org-find-if (predicate seq)
641 (catch 'exit
642 (while seq
643 (if (funcall predicate (car seq))
644 (throw 'exit (car seq))
645 (pop seq)))))
647 (defun org-defkey (keymap key def)
648 "Define a key, possibly translated, as returned by `org-key'."
649 (define-key keymap (org-key key) def))
651 (defcustom org-ellipsis nil
652 "The ellipsis to use in the Org-mode outline.
653 When nil, just use the standard three dots. When a string, use that instead,
654 When a face, use the standard 3 dots, but with the specified face.
655 The change affects only Org-mode (which will then use its own display table).
656 Changing this requires executing `M-x org-mode' in a buffer to become
657 effective."
658 :group 'org-startup
659 :type '(choice (const :tag "Default" nil)
660 (face :tag "Face" :value org-warning)
661 (string :tag "String" :value "...#")))
663 (defvar org-display-table nil
664 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
666 (defgroup org-keywords nil
667 "Keywords in Org-mode."
668 :tag "Org Keywords"
669 :group 'org)
671 (defcustom org-deadline-string "DEADLINE:"
672 "String to mark deadline entries.
673 A deadline is this string, followed by a time stamp. Should be a word,
674 terminated by a colon. You can insert a schedule keyword and
675 a timestamp with \\[org-deadline].
676 Changes become only effective after restarting Emacs."
677 :group 'org-keywords
678 :type 'string)
680 (defcustom org-scheduled-string "SCHEDULED:"
681 "String to mark scheduled TODO entries.
682 A schedule is this string, followed by a time stamp. Should be a word,
683 terminated by a colon. You can insert a schedule keyword and
684 a timestamp with \\[org-schedule].
685 Changes become only effective after restarting Emacs."
686 :group 'org-keywords
687 :type 'string)
689 (defcustom org-closed-string "CLOSED:"
690 "String used as the prefix for timestamps logging closing a TODO entry."
691 :group 'org-keywords
692 :type 'string)
694 (defcustom org-clock-string "CLOCK:"
695 "String used as prefix for timestamps clocking work hours on an item."
696 :group 'org-keywords
697 :type 'string)
699 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
700 org-scheduled-string "\\|"
701 org-deadline-string "\\|"
702 org-closed-string "\\|"
703 org-clock-string "\\)")
704 "Matches a line with planning or clock info.")
706 (defcustom org-comment-string "COMMENT"
707 "Entries starting with this keyword will never be exported.
708 An entry can be toggled between COMMENT and normal with
709 \\[org-toggle-comment].
710 Changes become only effective after restarting Emacs."
711 :group 'org-keywords
712 :type 'string)
714 (defcustom org-quote-string "QUOTE"
715 "Entries starting with this keyword will be exported in fixed-width font.
716 Quoting applies only to the text in the entry following the headline, and does
717 not extend beyond the next headline, even if that is lower level.
718 An entry can be toggled between QUOTE and normal with
719 \\[org-toggle-fixed-width-section]."
720 :group 'org-keywords
721 :type 'string)
723 (defconst org-repeat-re
724 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
725 "Regular expression for specifying repeated events.
726 After a match, group 1 contains the repeat expression.")
728 (defgroup org-structure nil
729 "Options concerning the general structure of Org-mode files."
730 :tag "Org Structure"
731 :group 'org)
733 (defgroup org-reveal-location nil
734 "Options about how to make context of a location visible."
735 :tag "Org Reveal Location"
736 :group 'org-structure)
738 (defconst org-context-choice
739 '(choice
740 (const :tag "Always" t)
741 (const :tag "Never" nil)
742 (repeat :greedy t :tag "Individual contexts"
743 (cons
744 (choice :tag "Context"
745 (const agenda)
746 (const org-goto)
747 (const occur-tree)
748 (const tags-tree)
749 (const link-search)
750 (const mark-goto)
751 (const bookmark-jump)
752 (const isearch)
753 (const default))
754 (boolean))))
755 "Contexts for the reveal options.")
757 (defcustom org-show-hierarchy-above '((default . t))
758 "Non-nil means show full hierarchy when revealing a location.
759 Org-mode often shows locations in an org-mode file which might have
760 been invisible before. When this is set, the hierarchy of headings
761 above the exposed location is shown.
762 Turning this off for example for sparse trees makes them very compact.
763 Instead of t, this can also be an alist specifying this option for different
764 contexts. Valid contexts are
765 agenda when exposing an entry from the agenda
766 org-goto when using the command `org-goto' on key C-c C-j
767 occur-tree when using the command `org-occur' on key C-c /
768 tags-tree when constructing a sparse tree based on tags matches
769 link-search when exposing search matches associated with a link
770 mark-goto when exposing the jump goal of a mark
771 bookmark-jump when exposing a bookmark location
772 isearch when exiting from an incremental search
773 default default for all contexts not set explicitly"
774 :group 'org-reveal-location
775 :type org-context-choice)
777 (defcustom org-show-following-heading '((default . nil))
778 "Non-nil means show following heading when revealing a location.
779 Org-mode often shows locations in an org-mode file which might have
780 been invisible before. When this is set, the heading following the
781 match is shown.
782 Turning this off for example for sparse trees makes them very compact,
783 but makes it harder to edit the location of the match. In such a case,
784 use the command \\[org-reveal] to show more context.
785 Instead of t, this can also be an alist specifying this option for different
786 contexts. See `org-show-hierarchy-above' for valid contexts."
787 :group 'org-reveal-location
788 :type org-context-choice)
790 (defcustom org-show-siblings '((default . nil) (isearch t))
791 "Non-nil means show all sibling heading when revealing a location.
792 Org-mode often shows locations in an org-mode file which might have
793 been invisible before. When this is set, the sibling of the current entry
794 heading are all made visible. If `org-show-hierarchy-above' is t,
795 the same happens on each level of the hierarchy above the current entry.
797 By default this is on for the isearch context, off for all other contexts.
798 Turning this off for example for sparse trees makes them very compact,
799 but makes it harder to edit the location of the match. In such a case,
800 use the command \\[org-reveal] to show more context.
801 Instead of t, this can also be an alist specifying this option for different
802 contexts. See `org-show-hierarchy-above' for valid contexts."
803 :group 'org-reveal-location
804 :type org-context-choice)
806 (defcustom org-show-entry-below '((default . nil))
807 "Non-nil means show the entry below a headline when revealing a location.
808 Org-mode often shows locations in an org-mode file which might have
809 been invisible before. When this is set, the text below the headline that is
810 exposed is also shown.
812 By default this is off for all contexts.
813 Instead of t, this can also be an alist specifying this option for different
814 contexts. See `org-show-hierarchy-above' for valid contexts."
815 :group 'org-reveal-location
816 :type org-context-choice)
818 (defcustom org-indirect-buffer-display 'other-window
819 "How should indirect tree buffers be displayed?
820 This applies to indirect buffers created with the commands
821 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
822 Valid values are:
823 current-window Display in the current window
824 other-window Just display in another window.
825 dedicated-frame Create one new frame, and re-use it each time.
826 new-frame Make a new frame each time. Note that in this case
827 previously-made indirect buffers are kept, and you need to
828 kill these buffers yourself."
829 :group 'org-structure
830 :group 'org-agenda-windows
831 :type '(choice
832 (const :tag "In current window" current-window)
833 (const :tag "In current frame, other window" other-window)
834 (const :tag "Each time a new frame" new-frame)
835 (const :tag "One dedicated frame" dedicated-frame)))
837 (defcustom org-use-speed-commands nil
838 "Non-nil means activate single letter commands at beginning of a headline.
839 This may also be a function to test for appropriate locations where speed
840 commands should be active."
841 :group 'org-structure
842 :type '(choice
843 (const :tag "Never" nil)
844 (const :tag "At beginning of headline stars" t)
845 (function)))
847 (defcustom org-speed-commands-user nil
848 "Alist of additional speed commands.
849 This list will be checked before `org-speed-commands-default'
850 when the variable `org-use-speed-commands' is non-nil
851 and when the cursor is at the beginning of a headline.
852 The car if each entry is a string with a single letter, which must
853 be assigned to `self-insert-command' in the global map.
854 The cdr is either a command to be called interactively, a function
855 to be called, or a form to be evaluated.
856 An entry that is just a list with a single string will be interpreted
857 as a descriptive headline that will be added when listing the speed
858 commands in the Help buffer using the `?' speed command."
859 :group 'org-structure
860 :type '(repeat :value ("k" . ignore)
861 (choice :value ("k" . ignore)
862 (list :tag "Descriptive Headline" (string :tag "Headline"))
863 (cons :tag "Letter and Command"
864 (string :tag "Command letter")
865 (choice
866 (function)
867 (sexp))))))
869 (defgroup org-cycle nil
870 "Options concerning visibility cycling in Org-mode."
871 :tag "Org Cycle"
872 :group 'org-structure)
874 (defcustom org-cycle-skip-children-state-if-no-children t
875 "Non-nil means skip CHILDREN state in entries that don't have any."
876 :group 'org-cycle
877 :type 'boolean)
879 (defcustom org-cycle-max-level nil
880 "Maximum level which should still be subject to visibility cycling.
881 Levels higher than this will, for cycling, be treated as text, not a headline.
882 When `org-odd-levels-only' is set, a value of N in this variable actually
883 means 2N-1 stars as the limiting headline.
884 When nil, cycle all levels.
885 Note that the limiting level of cycling is also influenced by
886 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
887 `org-inlinetask-min-level' is, cycling will be limited to levels one less
888 than its value."
889 :group 'org-cycle
890 :type '(choice
891 (const :tag "No limit" nil)
892 (integer :tag "Maximum level")))
894 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
895 "Names of drawers. Drawers are not opened by cycling on the headline above.
896 Drawers only open with a TAB on the drawer line itself. A drawer looks like
897 this:
898 :DRAWERNAME:
899 .....
900 :END:
901 The drawer \"PROPERTIES\" is special for capturing properties through
902 the property API.
904 Drawers can be defined on the per-file basis with a line like:
906 #+DRAWERS: HIDDEN STATE PROPERTIES"
907 :group 'org-structure
908 :group 'org-cycle
909 :type '(repeat (string :tag "Drawer Name")))
911 (defcustom org-hide-block-startup nil
912 "Non-nil means entering Org-mode will fold all blocks.
913 This can also be set in on a per-file basis with
915 #+STARTUP: hideblocks
916 #+STARTUP: showblocks"
917 :group 'org-startup
918 :group 'org-cycle
919 :type 'boolean)
921 (defcustom org-cycle-global-at-bob nil
922 "Cycle globally if cursor is at beginning of buffer and not at a headline.
923 This makes it possible to do global cycling without having to use S-TAB or
924 \\[universal-argument] TAB. For this special case to work, the first line
925 of the buffer must not be a headline -- it may be empty or some other text.
926 When used in this way, `org-cycle-hook' is disabled temporarily to make
927 sure the cursor stays at the beginning of the buffer. When this option is
928 nil, don't do anything special at the beginning of the buffer."
929 :group 'org-cycle
930 :type 'boolean)
932 (defcustom org-cycle-level-after-item/entry-creation t
933 "Non-nil means cycle entry level or item indentation in new empty entries.
935 When the cursor is at the end of an empty headline, i.e., with only stars
936 and maybe a TODO keyword, TAB will then switch the entry to become a child,
937 and then all possible ancestor states, before returning to the original state.
938 This makes data entry extremely fast: M-RET to create a new headline,
939 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
941 When the cursor is at the end of an empty plain list item, one TAB will
942 make it a subitem, two or more tabs will back up to make this an item
943 higher up in the item hierarchy."
944 :group 'org-cycle
945 :type 'boolean)
947 (defcustom org-cycle-emulate-tab t
948 "Where should `org-cycle' emulate TAB.
949 nil Never
950 white Only in completely white lines
951 whitestart Only at the beginning of lines, before the first non-white char
952 t Everywhere except in headlines
953 exc-hl-bol Everywhere except at the start of a headline
954 If TAB is used in a place where it does not emulate TAB, the current subtree
955 visibility is cycled."
956 :group 'org-cycle
957 :type '(choice (const :tag "Never" nil)
958 (const :tag "Only in completely white lines" white)
959 (const :tag "Before first char in a line" whitestart)
960 (const :tag "Everywhere except in headlines" t)
961 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
964 (defcustom org-cycle-separator-lines 2
965 "Number of empty lines needed to keep an empty line between collapsed trees.
966 If you leave an empty line between the end of a subtree and the following
967 headline, this empty line is hidden when the subtree is folded.
968 Org-mode will leave (exactly) one empty line visible if the number of
969 empty lines is equal or larger to the number given in this variable.
970 So the default 2 means at least 2 empty lines after the end of a subtree
971 are needed to produce free space between a collapsed subtree and the
972 following headline.
974 If the number is negative, and the number of empty lines is at least -N,
975 all empty lines are shown.
977 Special case: when 0, never leave empty lines in collapsed view."
978 :group 'org-cycle
979 :type 'integer)
980 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
982 (defcustom org-pre-cycle-hook nil
983 "Hook that is run before visibility cycling is happening.
984 The function(s) in this hook must accept a single argument which indicates
985 the new state that will be set right after running this hook. The
986 argument is a symbol. Before a global state change, it can have the values
987 `overview', `content', or `all'. Before a local state change, it can have
988 the values `folded', `children', or `subtree'."
989 :group 'org-cycle
990 :type 'hook)
992 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
993 org-cycle-hide-drawers
994 org-cycle-show-empty-lines
995 org-optimize-window-after-visibility-change)
996 "Hook that is run after `org-cycle' has changed the buffer visibility.
997 The function(s) in this hook must accept a single argument which indicates
998 the new state that was set by the most recent `org-cycle' command. The
999 argument is a symbol. After a global state change, it can have the values
1000 `overview', `contents', or `all'. After a local state change, it can have
1001 the values `folded', `children', or `subtree'."
1002 :group 'org-cycle
1003 :type 'hook)
1005 (defgroup org-edit-structure nil
1006 "Options concerning structure editing in Org-mode."
1007 :tag "Org Edit Structure"
1008 :group 'org-structure)
1010 (defcustom org-odd-levels-only nil
1011 "Non-nil means skip even levels and only use odd levels for the outline.
1012 This has the effect that two stars are being added/taken away in
1013 promotion/demotion commands. It also influences how levels are
1014 handled by the exporters.
1015 Changing it requires restart of `font-lock-mode' to become effective
1016 for fontification also in regions already fontified.
1017 You may also set this on a per-file basis by adding one of the following
1018 lines to the buffer:
1020 #+STARTUP: odd
1021 #+STARTUP: oddeven"
1022 :group 'org-edit-structure
1023 :group 'org-appearance
1024 :type 'boolean)
1026 (defcustom org-adapt-indentation t
1027 "Non-nil means adapt indentation to outline node level.
1029 When this variable is set, Org assumes that you write outlines by
1030 indenting text in each node to align with the headline (after the stars).
1031 The following issues are influenced by this variable:
1033 - When this is set and the *entire* text in an entry is indented, the
1034 indentation is increased by one space in a demotion command, and
1035 decreased by one in a promotion command. If any line in the entry
1036 body starts with text at column 0, indentation is not changed at all.
1038 - Property drawers and planning information is inserted indented when
1039 this variable s set. When nil, they will not be indented.
1041 - TAB indents a line relative to context. The lines below a headline
1042 will be indented when this variable is set.
1044 Note that this is all about true indentation, by adding and removing
1045 space characters. See also `org-indent.el' which does level-dependent
1046 indentation in a virtual way, i.e. at display time in Emacs."
1047 :group 'org-edit-structure
1048 :type 'boolean)
1050 (defcustom org-special-ctrl-a/e nil
1051 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1053 When t, `C-a' will bring back the cursor to the beginning of the
1054 headline text, i.e. after the stars and after a possible TODO
1055 keyword. In an item, this will be the position after bullet and
1056 check-box, if any. When the cursor is already at that position,
1057 another `C-a' will bring it to the beginning of the line.
1059 `C-e' will jump to the end of the headline, ignoring the presence
1060 of tags in the headline. A second `C-e' will then jump to the
1061 true end of the line, after any tags. This also means that, when
1062 this variable is non-nil, `C-e' also will never jump beyond the
1063 end of the heading of a folded section, i.e. not after the
1064 ellipses.
1066 When set to the symbol `reversed', the first `C-a' or `C-e' works
1067 normally, going to the true line boundary first. Only a directly
1068 following, identical keypress will bring the cursor to the
1069 special positions.
1071 This may also be a cons cell where the behavior for `C-a' and
1072 `C-e' is set separately."
1073 :group 'org-edit-structure
1074 :type '(choice
1075 (const :tag "off" nil)
1076 (const :tag "on: after stars/bullet and before tags first" t)
1077 (const :tag "reversed: true line boundary first" reversed)
1078 (cons :tag "Set C-a and C-e separately"
1079 (choice :tag "Special C-a"
1080 (const :tag "off" nil)
1081 (const :tag "on: after stars/bullet first" t)
1082 (const :tag "reversed: before stars/bullet first" reversed))
1083 (choice :tag "Special C-e"
1084 (const :tag "off" nil)
1085 (const :tag "on: before tags first" t)
1086 (const :tag "reversed: after tags first" reversed)))))
1087 (if (fboundp 'defvaralias)
1088 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1090 (defcustom org-special-ctrl-k nil
1091 "Non-nil means `C-k' will behave specially in headlines.
1092 When nil, `C-k' will call the default `kill-line' command.
1093 When t, the following will happen while the cursor is in the headline:
1095 - When the cursor is at the beginning of a headline, kill the entire
1096 line and possible the folded subtree below the line.
1097 - When in the middle of the headline text, kill the headline up to the tags.
1098 - When after the headline text, kill the tags."
1099 :group 'org-edit-structure
1100 :type 'boolean)
1102 (defcustom org-ctrl-k-protect-subtree nil
1103 "Non-nil means, do not delete a hidden subtree with C-k.
1104 When set to the symbol `error', simply throw an error when C-k is
1105 used to kill (part-of) a headline that has hidden text behind it.
1106 Any other non-nil value will result in a query to the user, if it is
1107 OK to kill that hidden subtree. When nil, kill without remorse."
1108 :group 'org-edit-structure
1109 :version "24.1"
1110 :type '(choice
1111 (const :tag "Do not protect hidden subtrees" nil)
1112 (const :tag "Protect hidden subtrees with a security query" t)
1113 (const :tag "Never kill a hidden subtree with C-k" error)))
1115 (defcustom org-catch-invisible-edits nil
1116 "Check if in invisible region before inserting or deleting a character.
1117 Valid values are:
1119 nil Do not check, so just do invisible edits.
1120 error Throw an error and do nothing.
1121 show Make point visible, and do the requested edit.
1122 show-and-error Make point visible, then throw an error and abort the edit.
1123 smart Make point visible, and do insertion/deletion if it is
1124 adjacent to visible text and the change feels predictable.
1125 Never delete a previously invisible character or add in the
1126 middle or right after an invisible region. Basically, this
1127 allows insertion and backward-delete right before ellipses.
1128 FIXME: maybe in this case we should not even show?"
1129 :group 'org-edit-structure
1130 :version "24.1"
1131 :type '(choice
1132 (const :tag "Do not check" nil)
1133 (const :tag "Throw error when trying to edit" error)
1134 (const :tag "Unhide, but do not do the edit" show-and-error)
1135 (const :tag "Show invisible part and do the edit" show)
1136 (const :tag "Be smart and do the right thing" smart)))
1138 (defcustom org-yank-folded-subtrees t
1139 "Non-nil means when yanking subtrees, fold them.
1140 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1141 it starts with a heading and all other headings in it are either children
1142 or siblings, then fold all the subtrees. However, do this only if no
1143 text after the yank would be swallowed into a folded tree by this action."
1144 :group 'org-edit-structure
1145 :type 'boolean)
1147 (defcustom org-yank-adjusted-subtrees nil
1148 "Non-nil means when yanking subtrees, adjust the level.
1149 With this setting, `org-paste-subtree' is used to insert the subtree, see
1150 this function for details."
1151 :group 'org-edit-structure
1152 :type 'boolean)
1154 (defcustom org-M-RET-may-split-line '((default . t))
1155 "Non-nil means M-RET will split the line at the cursor position.
1156 When nil, it will go to the end of the line before making a
1157 new line.
1158 You may also set this option in a different way for different
1159 contexts. Valid contexts are:
1161 headline when creating a new headline
1162 item when creating a new item
1163 table in a table field
1164 default the value to be used for all contexts not explicitly
1165 customized"
1166 :group 'org-structure
1167 :group 'org-table
1168 :type '(choice
1169 (const :tag "Always" t)
1170 (const :tag "Never" nil)
1171 (repeat :greedy t :tag "Individual contexts"
1172 (cons
1173 (choice :tag "Context"
1174 (const headline)
1175 (const item)
1176 (const table)
1177 (const default))
1178 (boolean)))))
1181 (defcustom org-insert-heading-respect-content nil
1182 "Non-nil means insert new headings after the current subtree.
1183 When nil, the new heading is created directly after the current line.
1184 The commands \\[org-insert-heading-respect-content] and
1185 \\[org-insert-todo-heading-respect-content] turn this variable on
1186 for the duration of the command."
1187 :group 'org-structure
1188 :type 'boolean)
1190 (defcustom org-blank-before-new-entry '((heading . auto)
1191 (plain-list-item . auto))
1192 "Should `org-insert-heading' leave a blank line before new heading/item?
1193 The value is an alist, with `heading' and `plain-list-item' as CAR,
1194 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1195 which case Org will look at the surrounding headings/items and try to
1196 make an intelligent decision whether to insert a blank line or not.
1198 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1199 set, the setting here is ignored and no empty line is inserted, to avoid
1200 breaking the list structure."
1201 :group 'org-edit-structure
1202 :type '(list
1203 (cons (const heading)
1204 (choice (const :tag "Never" nil)
1205 (const :tag "Always" t)
1206 (const :tag "Auto" auto)))
1207 (cons (const plain-list-item)
1208 (choice (const :tag "Never" nil)
1209 (const :tag "Always" t)
1210 (const :tag "Auto" auto)))))
1212 (defcustom org-insert-heading-hook nil
1213 "Hook being run after inserting a new heading."
1214 :group 'org-edit-structure
1215 :type 'hook)
1217 (defcustom org-enable-fixed-width-editor t
1218 "Non-nil means lines starting with \":\" are treated as fixed-width.
1219 This currently only means they are never auto-wrapped.
1220 When nil, such lines will be treated like ordinary lines.
1221 See also the QUOTE keyword."
1222 :group 'org-edit-structure
1223 :type 'boolean)
1225 (defcustom org-goto-auto-isearch t
1226 "Non-nil means typing characters in `org-goto' starts incremental search.
1227 When nil, you can use these keybindings to navigate the buffer:
1229 q Quit the org-goto interface
1230 n Go to the next visible heading
1231 p Go to the previous visible heading
1232 f Go one heading forward on same level
1233 b Go one heading backward on same level
1234 u Go one heading up"
1235 :group 'org-edit-structure
1236 :type 'boolean)
1238 (defgroup org-sparse-trees nil
1239 "Options concerning sparse trees in Org-mode."
1240 :tag "Org Sparse Trees"
1241 :group 'org-structure)
1243 (defcustom org-highlight-sparse-tree-matches t
1244 "Non-nil means highlight all matches that define a sparse tree.
1245 The highlights will automatically disappear the next time the buffer is
1246 changed by an edit command."
1247 :group 'org-sparse-trees
1248 :type 'boolean)
1250 (defcustom org-remove-highlights-with-change t
1251 "Non-nil means any change to the buffer will remove temporary highlights.
1252 Such highlights are created by `org-occur' and `org-clock-display'.
1253 When nil, `C-c C-c needs to be used to get rid of the highlights.
1254 The highlights created by `org-preview-latex-fragment' always need
1255 `C-c C-c' to be removed."
1256 :group 'org-sparse-trees
1257 :group 'org-time
1258 :type 'boolean)
1261 (defcustom org-occur-hook '(org-first-headline-recenter)
1262 "Hook that is run after `org-occur' has constructed a sparse tree.
1263 This can be used to recenter the window to show as much of the structure
1264 as possible."
1265 :group 'org-sparse-trees
1266 :type 'hook)
1268 (defgroup org-imenu-and-speedbar nil
1269 "Options concerning imenu and speedbar in Org-mode."
1270 :tag "Org Imenu and Speedbar"
1271 :group 'org-structure)
1273 (defcustom org-imenu-depth 2
1274 "The maximum level for Imenu access to Org-mode headlines.
1275 This also applied for speedbar access."
1276 :group 'org-imenu-and-speedbar
1277 :type 'integer)
1279 (defgroup org-table nil
1280 "Options concerning tables in Org-mode."
1281 :tag "Org Table"
1282 :group 'org)
1284 (defcustom org-enable-table-editor 'optimized
1285 "Non-nil means lines starting with \"|\" are handled by the table editor.
1286 When nil, such lines will be treated like ordinary lines.
1288 When equal to the symbol `optimized', the table editor will be optimized to
1289 do the following:
1290 - Automatic overwrite mode in front of whitespace in table fields.
1291 This makes the structure of the table stay in tact as long as the edited
1292 field does not exceed the column width.
1293 - Minimize the number of realigns. Normally, the table is aligned each time
1294 TAB or RET are pressed to move to another field. With optimization this
1295 happens only if changes to a field might have changed the column width.
1296 Optimization requires replacing the functions `self-insert-command',
1297 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1298 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1299 very good at guessing when a re-align will be necessary, but you can always
1300 force one with \\[org-ctrl-c-ctrl-c].
1302 If you would like to use the optimized version in Org-mode, but the
1303 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1305 This variable can be used to turn on and off the table editor during a session,
1306 but in order to toggle optimization, a restart is required.
1308 See also the variable `org-table-auto-blank-field'."
1309 :group 'org-table
1310 :type '(choice
1311 (const :tag "off" nil)
1312 (const :tag "on" t)
1313 (const :tag "on, optimized" optimized)))
1315 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1316 (version<= emacs-version "24.1"))
1317 "Non-nil means cluster self-insert commands for undo when possible.
1318 If this is set, then, like in the Emacs command loop, 20 consecutive
1319 characters will be undone together.
1320 This is configurable, because there is some impact on typing performance."
1321 :group 'org-table
1322 :type 'boolean)
1324 (defcustom org-table-tab-recognizes-table.el t
1325 "Non-nil means TAB will automatically notice a table.el table.
1326 When it sees such a table, it moves point into it and - if necessary -
1327 calls `table-recognize-table'."
1328 :group 'org-table-editing
1329 :type 'boolean)
1331 (defgroup org-link nil
1332 "Options concerning links in Org-mode."
1333 :tag "Org Link"
1334 :group 'org)
1336 (defvar org-link-abbrev-alist-local nil
1337 "Buffer-local version of `org-link-abbrev-alist', which see.
1338 The value of this is taken from the #+LINK lines.")
1339 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1341 (defcustom org-link-abbrev-alist nil
1342 "Alist of link abbreviations.
1343 The car of each element is a string, to be replaced at the start of a link.
1344 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1345 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1347 [[linkkey:tag][description]]
1349 The 'linkkey' must be a word word, starting with a letter, followed
1350 by letters, numbers, '-' or '_'.
1352 If REPLACE is a string, the tag will simply be appended to create the link.
1353 If the string contains \"%s\", the tag will be inserted there. If the string
1354 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1355 at that point (see the function `url-hexify-string'). If the string contains
1356 the specifier \"%(my-function)\", then the custom function `my-function' will
1357 be invoked: this function takes the tag as its only argument and must return
1358 a string.
1360 REPLACE may also be a function that will be called with the tag as the
1361 only argument to create the link, which should be returned as a string.
1363 See the manual for examples."
1364 :group 'org-link
1365 :type '(repeat
1366 (cons
1367 (string :tag "Protocol")
1368 (choice
1369 (string :tag "Format")
1370 (function)))))
1372 (defcustom org-descriptive-links t
1373 "Non-nil means Org will display descriptive links.
1374 E.g. [[http://orgmode.org][Org website]] will be displayed as
1375 \"Org Website\", hiding the link itself and just displaying its
1376 description. When set to `nil', Org will display the full links
1377 literally.
1379 You can interactively set the value of this variable by calling
1380 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1381 :group 'org-link
1382 :type 'boolean)
1384 (defcustom org-link-file-path-type 'adaptive
1385 "How the path name in file links should be stored.
1386 Valid values are:
1388 relative Relative to the current directory, i.e. the directory of the file
1389 into which the link is being inserted.
1390 absolute Absolute path, if possible with ~ for home directory.
1391 noabbrev Absolute path, no abbreviation of home directory.
1392 adaptive Use relative path for files in the current directory and sub-
1393 directories of it. For other files, use an absolute path."
1394 :group 'org-link
1395 :type '(choice
1396 (const relative)
1397 (const absolute)
1398 (const noabbrev)
1399 (const adaptive)))
1401 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1402 "Types of links that should be activated in Org-mode files.
1403 This is a list of symbols, each leading to the activation of a certain link
1404 type. In principle, it does not hurt to turn on most link types - there may
1405 be a small gain when turning off unused link types. The types are:
1407 bracket The recommended [[link][description]] or [[link]] links with hiding.
1408 angle Links in angular brackets that may contain whitespace like
1409 <bbdb:Carsten Dominik>.
1410 plain Plain links in normal text, no whitespace, like http://google.com.
1411 radio Text that is matched by a radio target, see manual for details.
1412 tag Tag settings in a headline (link to tag search).
1413 date Time stamps (link to calendar).
1414 footnote Footnote labels.
1416 Changing this variable requires a restart of Emacs to become effective."
1417 :group 'org-link
1418 :type '(set :greedy t
1419 (const :tag "Double bracket links" bracket)
1420 (const :tag "Angular bracket links" angle)
1421 (const :tag "Plain text links" plain)
1422 (const :tag "Radio target matches" radio)
1423 (const :tag "Tags" tag)
1424 (const :tag "Timestamps" date)
1425 (const :tag "Footnotes" footnote)))
1427 (defcustom org-make-link-description-function nil
1428 "Function to use for generating link descriptions from links.
1429 When nil, the link location will be used. This function must take
1430 two parameters: the first one is the link, the second one is the
1431 description generated by `org-insert-link'. The function should
1432 return the description to use."
1433 :group 'org-link
1434 :type 'function)
1436 (defgroup org-link-store nil
1437 "Options concerning storing links in Org-mode."
1438 :tag "Org Store Link"
1439 :group 'org-link)
1441 (defcustom org-url-hexify-p t
1442 "When non-nil, hexify URL when creating a link."
1443 :type 'boolean
1444 :version "24.3"
1445 :group 'org-link-store)
1447 (defcustom org-email-link-description-format "Email %c: %.30s"
1448 "Format of the description part of a link to an email or usenet message.
1449 The following %-escapes will be replaced by corresponding information:
1451 %F full \"From\" field
1452 %f name, taken from \"From\" field, address if no name
1453 %T full \"To\" field
1454 %t first name in \"To\" field, address if no name
1455 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1456 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1457 %s subject
1458 %d date
1459 %m message-id.
1461 You may use normal field width specification between the % and the letter.
1462 This is for example useful to limit the length of the subject.
1464 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1465 :group 'org-link-store
1466 :type 'string)
1468 (defcustom org-from-is-user-regexp
1469 (let (r1 r2)
1470 (when (and user-mail-address (not (string= user-mail-address "")))
1471 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1472 (when (and user-full-name (not (string= user-full-name "")))
1473 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1474 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1475 "Regexp matched against the \"From:\" header of an email or usenet message.
1476 It should match if the message is from the user him/herself."
1477 :group 'org-link-store
1478 :type 'regexp)
1480 (defcustom org-context-in-file-links t
1481 "Non-nil means file links from `org-store-link' contain context.
1482 A search string will be added to the file name with :: as separator and
1483 used to find the context when the link is activated by the command
1484 `org-open-at-point'. When this option is t, the entire active region
1485 will be placed in the search string of the file link. If set to a
1486 positive integer, only the first n lines of context will be stored.
1488 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1489 negates this setting for the duration of the command."
1490 :group 'org-link-store
1491 :type '(choice boolean integer))
1493 (defcustom org-keep-stored-link-after-insertion nil
1494 "Non-nil means keep link in list for entire session.
1496 The command `org-store-link' adds a link pointing to the current
1497 location to an internal list. These links accumulate during a session.
1498 The command `org-insert-link' can be used to insert links into any
1499 Org-mode file (offering completion for all stored links). When this
1500 option is nil, every link which has been inserted once using \\[org-insert-link]
1501 will be removed from the list, to make completing the unused links
1502 more efficient."
1503 :group 'org-link-store
1504 :type 'boolean)
1506 (defgroup org-link-follow nil
1507 "Options concerning following links in Org-mode."
1508 :tag "Org Follow Link"
1509 :group 'org-link)
1511 (defcustom org-link-translation-function nil
1512 "Function to translate links with different syntax to Org syntax.
1513 This can be used to translate links created for example by the Planner
1514 or emacs-wiki packages to Org syntax.
1515 The function must accept two parameters, a TYPE containing the link
1516 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1517 which is everything after the link protocol. It should return a cons
1518 with possibly modified values of type and path.
1519 Org contains a function for this, so if you set this variable to
1520 `org-translate-link-from-planner', you should be able follow many
1521 links created by planner."
1522 :group 'org-link-follow
1523 :type 'function)
1525 (defcustom org-follow-link-hook nil
1526 "Hook that is run after a link has been followed."
1527 :group 'org-link-follow
1528 :type 'hook)
1530 (defcustom org-tab-follows-link nil
1531 "Non-nil means on links TAB will follow the link.
1532 Needs to be set before org.el is loaded.
1533 This really should not be used, it does not make sense, and the
1534 implementation is bad."
1535 :group 'org-link-follow
1536 :type 'boolean)
1538 (defcustom org-return-follows-link nil
1539 "Non-nil means on links RET will follow the link."
1540 :group 'org-link-follow
1541 :type 'boolean)
1543 (defcustom org-mouse-1-follows-link
1544 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1545 "Non-nil means mouse-1 on a link will follow the link.
1546 A longer mouse click will still set point. Does not work on XEmacs.
1547 Needs to be set before org.el is loaded."
1548 :group 'org-link-follow
1549 :type 'boolean)
1551 (defcustom org-mark-ring-length 4
1552 "Number of different positions to be recorded in the ring.
1553 Changing this requires a restart of Emacs to work correctly."
1554 :group 'org-link-follow
1555 :type 'integer)
1557 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1558 "Non-nil means internal links in Org files must exactly match a headline.
1559 When nil, the link search tries to match a phrase with all words
1560 in the search text."
1561 :group 'org-link-follow
1562 :version "24.1"
1563 :type '(choice
1564 (const :tag "Use fuzzy text search" nil)
1565 (const :tag "Match only exact headline" t)
1566 (const :tag "Match exact headline or query to create it"
1567 query-to-create)))
1569 (defcustom org-link-frame-setup
1570 '((vm . vm-visit-folder-other-frame)
1571 (vm-imap . vm-visit-imap-folder-other-frame)
1572 (gnus . org-gnus-no-new-news)
1573 (file . find-file-other-window)
1574 (wl . wl-other-frame))
1575 "Setup the frame configuration for following links.
1576 When following a link with Emacs, it may often be useful to display
1577 this link in another window or frame. This variable can be used to
1578 set this up for the different types of links.
1579 For VM, use any of
1580 `vm-visit-folder'
1581 `vm-visit-folder-other-window'
1582 `vm-visit-folder-other-frame'
1583 For Gnus, use any of
1584 `gnus'
1585 `gnus-other-frame'
1586 `org-gnus-no-new-news'
1587 For FILE, use any of
1588 `find-file'
1589 `find-file-other-window'
1590 `find-file-other-frame'
1591 For Wanderlust use any of
1592 `wl'
1593 `wl-other-frame'
1594 For the calendar, use the variable `calendar-setup'.
1595 For BBDB, it is currently only possible to display the matches in
1596 another window."
1597 :group 'org-link-follow
1598 :type '(list
1599 (cons (const vm)
1600 (choice
1601 (const vm-visit-folder)
1602 (const vm-visit-folder-other-window)
1603 (const vm-visit-folder-other-frame)))
1604 (cons (const gnus)
1605 (choice
1606 (const gnus)
1607 (const gnus-other-frame)
1608 (const org-gnus-no-new-news)))
1609 (cons (const file)
1610 (choice
1611 (const find-file)
1612 (const find-file-other-window)
1613 (const find-file-other-frame)))
1614 (cons (const wl)
1615 (choice
1616 (const wl)
1617 (const wl-other-frame)))))
1619 (defcustom org-display-internal-link-with-indirect-buffer nil
1620 "Non-nil means use indirect buffer to display infile links.
1621 Activating internal links (from one location in a file to another location
1622 in the same file) normally just jumps to the location. When the link is
1623 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1624 is displayed in
1625 another window. When this option is set, the other window actually displays
1626 an indirect buffer clone of the current buffer, to avoid any visibility
1627 changes to the current buffer."
1628 :group 'org-link-follow
1629 :type 'boolean)
1631 (defcustom org-open-non-existing-files nil
1632 "Non-nil means `org-open-file' will open non-existing files.
1633 When nil, an error will be generated.
1634 This variable applies only to external applications because they
1635 might choke on non-existing files. If the link is to a file that
1636 will be opened in Emacs, the variable is ignored."
1637 :group 'org-link-follow
1638 :type 'boolean)
1640 (defcustom org-open-directory-means-index-dot-org nil
1641 "Non-nil means a link to a directory really means to index.org.
1642 When nil, following a directory link will run dired or open a finder/explorer
1643 window on that directory."
1644 :group 'org-link-follow
1645 :type 'boolean)
1647 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1648 "Function and arguments to call for following mailto links.
1649 This is a list with the first element being a Lisp function, and the
1650 remaining elements being arguments to the function. In string arguments,
1651 %a will be replaced by the address, and %s will be replaced by the subject
1652 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1653 :group 'org-link-follow
1654 :type '(choice
1655 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1656 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1657 (const :tag "message-mail" (message-mail "%a" "%s"))
1658 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1660 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1661 "Non-nil means ask for confirmation before executing shell links.
1662 Shell links can be dangerous: just think about a link
1664 [[shell:rm -rf ~/*][Google Search]]
1666 This link would show up in your Org-mode document as \"Google Search\",
1667 but really it would remove your entire home directory.
1668 Therefore we advise against setting this variable to nil.
1669 Just change it to `y-or-n-p' if you want to confirm with a
1670 single keystroke rather than having to type \"yes\"."
1671 :group 'org-link-follow
1672 :type '(choice
1673 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1674 (const :tag "with y-or-n (faster)" y-or-n-p)
1675 (const :tag "no confirmation (dangerous)" nil)))
1676 (put 'org-confirm-shell-link-function
1677 'safe-local-variable
1678 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1680 (defcustom org-confirm-shell-link-not-regexp ""
1681 "A regexp to skip confirmation for shell links."
1682 :group 'org-link-follow
1683 :version "24.1"
1684 :type 'regexp)
1686 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1687 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1688 Elisp links can be dangerous: just think about a link
1690 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1692 This link would show up in your Org-mode document as \"Google Search\",
1693 but really it would remove your entire home directory.
1694 Therefore we advise against setting this variable to nil.
1695 Just change it to `y-or-n-p' if you want to confirm with a
1696 single keystroke rather than having to type \"yes\"."
1697 :group 'org-link-follow
1698 :type '(choice
1699 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1700 (const :tag "with y-or-n (faster)" y-or-n-p)
1701 (const :tag "no confirmation (dangerous)" nil)))
1702 (put 'org-confirm-shell-link-function
1703 'safe-local-variable
1704 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1706 (defcustom org-confirm-elisp-link-not-regexp ""
1707 "A regexp to skip confirmation for Elisp links."
1708 :group 'org-link-follow
1709 :version "24.1"
1710 :type 'regexp)
1712 (defconst org-file-apps-defaults-gnu
1713 '((remote . emacs)
1714 (system . mailcap)
1715 (t . mailcap))
1716 "Default file applications on a UNIX or GNU/Linux system.
1717 See `org-file-apps'.")
1719 (defconst org-file-apps-defaults-macosx
1720 '((remote . emacs)
1721 (t . "open %s")
1722 (system . "open %s")
1723 ("ps.gz" . "gv %s")
1724 ("eps.gz" . "gv %s")
1725 ("dvi" . "xdvi %s")
1726 ("fig" . "xfig %s"))
1727 "Default file applications on a MacOS X system.
1728 The system \"open\" is known as a default, but we use X11 applications
1729 for some files for which the OS does not have a good default.
1730 See `org-file-apps'.")
1732 (defconst org-file-apps-defaults-windowsnt
1733 (list
1734 '(remote . emacs)
1735 (cons t
1736 (list (if (featurep 'xemacs)
1737 'mswindows-shell-execute
1738 'w32-shell-execute)
1739 "open" 'file))
1740 (cons 'system
1741 (list (if (featurep 'xemacs)
1742 'mswindows-shell-execute
1743 'w32-shell-execute)
1744 "open" 'file)))
1745 "Default file applications on a Windows NT system.
1746 The system \"open\" is used for most files.
1747 See `org-file-apps'.")
1749 (defcustom org-file-apps
1751 (auto-mode . emacs)
1752 ("\\.mm\\'" . default)
1753 ("\\.x?html?\\'" . default)
1754 ("\\.pdf\\'" . default)
1756 "External applications for opening `file:path' items in a document.
1757 Org-mode uses system defaults for different file types, but
1758 you can use this variable to set the application for a given file
1759 extension. The entries in this list are cons cells where the car identifies
1760 files and the cdr the corresponding command. Possible values for the
1761 file identifier are
1762 \"string\" A string as a file identifier can be interpreted in different
1763 ways, depending on its contents:
1765 - Alphanumeric characters only:
1766 Match links with this file extension.
1767 Example: (\"pdf\" . \"evince %s\")
1768 to open PDFs with evince.
1770 - Regular expression: Match links where the
1771 filename matches the regexp. If you want to
1772 use groups here, use shy groups.
1774 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1775 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1776 to open *.html and *.xhtml with firefox.
1778 - Regular expression which contains (non-shy) groups:
1779 Match links where the whole link, including \"::\", and
1780 anything after that, matches the regexp.
1781 In a custom command string, %1, %2, etc. are replaced with
1782 the parts of the link that were matched by the groups.
1783 For backwards compatibility, if a command string is given
1784 that does not use any of the group matches, this case is
1785 handled identically to the second one (i.e. match against
1786 file name only).
1787 In a custom lisp form, you can access the group matches with
1788 (match-string n link).
1790 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1791 to open [[file:document.pdf::5]] with evince at page 5.
1793 `directory' Matches a directory
1794 `remote' Matches a remote file, accessible through tramp or efs.
1795 Remote files most likely should be visited through Emacs
1796 because external applications cannot handle such paths.
1797 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1798 so all files Emacs knows how to handle. Using this with
1799 command `emacs' will open most files in Emacs. Beware that this
1800 will also open html files inside Emacs, unless you add
1801 (\"html\" . default) to the list as well.
1802 t Default for files not matched by any of the other options.
1803 `system' The system command to open files, like `open' on Windows
1804 and Mac OS X, and mailcap under GNU/Linux. This is the command
1805 that will be selected if you call `C-c C-o' with a double
1806 \\[universal-argument] \\[universal-argument] prefix.
1808 Possible values for the command are:
1809 `emacs' The file will be visited by the current Emacs process.
1810 `default' Use the default application for this file type, which is the
1811 association for t in the list, most likely in the system-specific
1812 part.
1813 This can be used to overrule an unwanted setting in the
1814 system-specific variable.
1815 `system' Use the system command for opening files, like \"open\".
1816 This command is specified by the entry whose car is `system'.
1817 Most likely, the system-specific version of this variable
1818 does define this command, but you can overrule/replace it
1819 here.
1820 string A command to be executed by a shell; %s will be replaced
1821 by the path to the file.
1822 sexp A Lisp form which will be evaluated. The file path will
1823 be available in the Lisp variable `file'.
1824 For more examples, see the system specific constants
1825 `org-file-apps-defaults-macosx'
1826 `org-file-apps-defaults-windowsnt'
1827 `org-file-apps-defaults-gnu'."
1828 :group 'org-link-follow
1829 :type '(repeat
1830 (cons (choice :value ""
1831 (string :tag "Extension")
1832 (const :tag "System command to open files" system)
1833 (const :tag "Default for unrecognized files" t)
1834 (const :tag "Remote file" remote)
1835 (const :tag "Links to a directory" directory)
1836 (const :tag "Any files that have Emacs modes"
1837 auto-mode))
1838 (choice :value ""
1839 (const :tag "Visit with Emacs" emacs)
1840 (const :tag "Use default" default)
1841 (const :tag "Use the system command" system)
1842 (string :tag "Command")
1843 (sexp :tag "Lisp form")))))
1845 (defcustom org-doi-server-url "http://dx.doi.org/"
1846 "The URL of the DOI server."
1847 :type 'string
1848 :version "24.3"
1849 :group 'org-link-follow)
1851 (defgroup org-refile nil
1852 "Options concerning refiling entries in Org-mode."
1853 :tag "Org Refile"
1854 :group 'org)
1856 (defcustom org-directory "~/org"
1857 "Directory with org files.
1858 This is just a default location to look for Org files. There is no need
1859 at all to put your files into this directory. It is only used in the
1860 following situations:
1862 1. When a capture template specifies a target file that is not an
1863 absolute path. The path will then be interpreted relative to
1864 `org-directory'
1865 2. When a capture note is filed away in an interactive way (when exiting the
1866 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1867 with `org-directory' as the default path."
1868 :group 'org-refile
1869 :group 'org-remember
1870 :group 'org-capture
1871 :type 'directory)
1873 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1874 "Default target for storing notes.
1875 Used as a fall back file for org-remember.el and org-capture.el, for
1876 templates that do not specify a target file."
1877 :group 'org-refile
1878 :group 'org-remember
1879 :group 'org-capture
1880 :type '(choice
1881 (const :tag "Default from remember-data-file" nil)
1882 file))
1884 (defcustom org-goto-interface 'outline
1885 "The default interface to be used for `org-goto'.
1886 Allowed values are:
1887 outline The interface shows an outline of the relevant file
1888 and the correct heading is found by moving through
1889 the outline or by searching with incremental search.
1890 outline-path-completion Headlines in the current buffer are offered via
1891 completion. This is the interface also used by
1892 the refile command."
1893 :group 'org-refile
1894 :type '(choice
1895 (const :tag "Outline" outline)
1896 (const :tag "Outline-path-completion" outline-path-completion)))
1898 (defcustom org-goto-max-level 5
1899 "Maximum target level when running `org-goto' with refile interface."
1900 :group 'org-refile
1901 :type 'integer)
1903 (defcustom org-reverse-note-order nil
1904 "Non-nil means store new notes at the beginning of a file or entry.
1905 When nil, new notes will be filed to the end of a file or entry.
1906 This can also be a list with cons cells of regular expressions that
1907 are matched against file names, and values."
1908 :group 'org-remember
1909 :group 'org-capture
1910 :group 'org-refile
1911 :type '(choice
1912 (const :tag "Reverse always" t)
1913 (const :tag "Reverse never" nil)
1914 (repeat :tag "By file name regexp"
1915 (cons regexp boolean))))
1917 (defcustom org-log-refile nil
1918 "Information to record when a task is refiled.
1920 Possible values are:
1922 nil Don't add anything
1923 time Add a time stamp to the task
1924 note Prompt for a note and add it with template `org-log-note-headings'
1926 This option can also be set with on a per-file-basis with
1928 #+STARTUP: nologrefile
1929 #+STARTUP: logrefile
1930 #+STARTUP: lognoterefile
1932 You can have local logging settings for a subtree by setting the LOGGING
1933 property to one or more of these keywords.
1935 When bulk-refiling from the agenda, the value `note' is forbidden and
1936 will temporarily be changed to `time'."
1937 :group 'org-refile
1938 :group 'org-progress
1939 :version "24.1"
1940 :type '(choice
1941 (const :tag "No logging" nil)
1942 (const :tag "Record timestamp" time)
1943 (const :tag "Record timestamp with note." note)))
1945 (defcustom org-refile-targets nil
1946 "Targets for refiling entries with \\[org-refile].
1947 This is a list of cons cells. Each cell contains:
1948 - a specification of the files to be considered, either a list of files,
1949 or a symbol whose function or variable value will be used to retrieve
1950 a file name or a list of file names. If you use `org-agenda-files' for
1951 that, all agenda files will be scanned for targets. Nil means consider
1952 headings in the current buffer.
1953 - A specification of how to find candidate refile targets. This may be
1954 any of:
1955 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1956 This tag has to be present in all target headlines, inheritance will
1957 not be considered.
1958 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1959 todo keyword.
1960 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1961 headlines that are refiling targets.
1962 - a cons cell (:level . N). Any headline of level N is considered a target.
1963 Note that, when `org-odd-levels-only' is set, level corresponds to
1964 order in hierarchy, not to the number of stars.
1965 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1966 Note that, when `org-odd-levels-only' is set, level corresponds to
1967 order in hierarchy, not to the number of stars.
1969 Each element of this list generates a set of possible targets.
1970 The union of these sets is presented (with completion) to
1971 the user by `org-refile'.
1973 You can set the variable `org-refile-target-verify-function' to a function
1974 to verify each headline found by the simple criteria above.
1976 When this variable is nil, all top-level headlines in the current buffer
1977 are used, equivalent to the value `((nil . (:level . 1))'."
1978 :group 'org-refile
1979 :type '(repeat
1980 (cons
1981 (choice :value org-agenda-files
1982 (const :tag "All agenda files" org-agenda-files)
1983 (const :tag "Current buffer" nil)
1984 (function) (variable) (file))
1985 (choice :tag "Identify target headline by"
1986 (cons :tag "Specific tag" (const :value :tag) (string))
1987 (cons :tag "TODO keyword" (const :value :todo) (string))
1988 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1989 (cons :tag "Level number" (const :value :level) (integer))
1990 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1992 (defcustom org-refile-target-verify-function nil
1993 "Function to verify if the headline at point should be a refile target.
1994 The function will be called without arguments, with point at the
1995 beginning of the headline. It should return t and leave point
1996 where it is if the headline is a valid target for refiling.
1998 If the target should not be selected, the function must return nil.
1999 In addition to this, it may move point to a place from where the search
2000 should be continued. For example, the function may decide that the entire
2001 subtree of the current entry should be excluded and move point to the end
2002 of the subtree."
2003 :group 'org-refile
2004 :type 'function)
2006 (defcustom org-refile-use-cache nil
2007 "Non-nil means cache refile targets to speed up the process.
2008 The cache for a particular file will be updated automatically when
2009 the buffer has been killed, or when any of the marker used for flagging
2010 refile targets no longer points at a live buffer.
2011 If you have added new entries to a buffer that might themselves be targets,
2012 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2013 find that easier, `C-u C-u C-u C-c C-w'."
2014 :group 'org-refile
2015 :version "24.1"
2016 :type 'boolean)
2018 (defcustom org-refile-use-outline-path nil
2019 "Non-nil means provide refile targets as paths.
2020 So a level 3 headline will be available as level1/level2/level3.
2022 When the value is `file', also include the file name (without directory)
2023 into the path. In this case, you can also stop the completion after
2024 the file name, to get entries inserted as top level in the file.
2026 When `full-file-path', include the full file path."
2027 :group 'org-refile
2028 :type '(choice
2029 (const :tag "Not" nil)
2030 (const :tag "Yes" t)
2031 (const :tag "Start with file name" file)
2032 (const :tag "Start with full file path" full-file-path)))
2034 (defcustom org-outline-path-complete-in-steps t
2035 "Non-nil means complete the outline path in hierarchical steps.
2036 When Org-mode uses the refile interface to select an outline path
2037 \(see variable `org-refile-use-outline-path'), the completion of
2038 the path can be done is a single go, or if can be done in steps down
2039 the headline hierarchy. Going in steps is probably the best if you
2040 do not use a special completion package like `ido' or `icicles'.
2041 However, when using these packages, going in one step can be very
2042 fast, while still showing the whole path to the entry."
2043 :group 'org-refile
2044 :type 'boolean)
2046 (defcustom org-refile-allow-creating-parent-nodes nil
2047 "Non-nil means allow to create new nodes as refile targets.
2048 New nodes are then created by adding \"/new node name\" to the completion
2049 of an existing node. When the value of this variable is `confirm',
2050 new node creation must be confirmed by the user (recommended)
2051 When nil, the completion must match an existing entry.
2053 Note that, if the new heading is not seen by the criteria
2054 listed in `org-refile-targets', multiple instances of the same
2055 heading would be created by trying again to file under the new
2056 heading."
2057 :group 'org-refile
2058 :type '(choice
2059 (const :tag "Never" nil)
2060 (const :tag "Always" t)
2061 (const :tag "Prompt for confirmation" confirm)))
2063 (defcustom org-refile-active-region-within-subtree nil
2064 "Non-nil means also refile active region within a subtree.
2066 By default `org-refile' doesn't allow refiling regions if they
2067 don't contain a set of subtrees, but it might be convenient to
2068 do so sometimes: in that case, the first line of the region is
2069 converted to a headline before refiling."
2070 :group 'org-refile
2071 :version "24.1"
2072 :type 'boolean)
2074 (defgroup org-todo nil
2075 "Options concerning TODO items in Org-mode."
2076 :tag "Org TODO"
2077 :group 'org)
2079 (defgroup org-progress nil
2080 "Options concerning Progress logging in Org-mode."
2081 :tag "Org Progress"
2082 :group 'org-time)
2084 (defvar org-todo-interpretation-widgets
2085 '((:tag "Sequence (cycling hits every state)" sequence)
2086 (:tag "Type (cycling directly to DONE)" type))
2087 "The available interpretation symbols for customizing `org-todo-keywords'.
2088 Interested libraries should add to this list.")
2090 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2091 "List of TODO entry keyword sequences and their interpretation.
2092 \\<org-mode-map>This is a list of sequences.
2094 Each sequence starts with a symbol, either `sequence' or `type',
2095 indicating if the keywords should be interpreted as a sequence of
2096 action steps, or as different types of TODO items. The first
2097 keywords are states requiring action - these states will select a headline
2098 for inclusion into the global TODO list Org-mode produces. If one of
2099 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2100 signify that no further action is necessary. If \"|\" is not found,
2101 the last keyword is treated as the only DONE state of the sequence.
2103 The command \\[org-todo] cycles an entry through these states, and one
2104 additional state where no keyword is present. For details about this
2105 cycling, see the manual.
2107 TODO keywords and interpretation can also be set on a per-file basis with
2108 the special #+SEQ_TODO and #+TYP_TODO lines.
2110 Each keyword can optionally specify a character for fast state selection
2111 \(in combination with the variable `org-use-fast-todo-selection')
2112 and specifiers for state change logging, using the same syntax that
2113 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2114 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2115 indicates to record a time stamp each time this state is selected.
2117 Each keyword may also specify if a timestamp or a note should be
2118 recorded when entering or leaving the state, by adding additional
2119 characters in the parenthesis after the keyword. This looks like this:
2120 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2121 record only the time of the state change. With X and Y being either
2122 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2123 Y when leaving the state if and only if the *target* state does not
2124 define X. You may omit any of the fast-selection key or X or /Y,
2125 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2127 For backward compatibility, this variable may also be just a list
2128 of keywords. In this case the interpretation (sequence or type) will be
2129 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2130 :group 'org-todo
2131 :group 'org-keywords
2132 :type '(choice
2133 (repeat :tag "Old syntax, just keywords"
2134 (string :tag "Keyword"))
2135 (repeat :tag "New syntax"
2136 (cons
2137 (choice
2138 :tag "Interpretation"
2139 ;;Quick and dirty way to see
2140 ;;`org-todo-interpretations'. This takes the
2141 ;;place of item arguments
2142 :convert-widget
2143 (lambda (widget)
2144 (widget-put widget
2145 :args (mapcar
2146 #'(lambda (x)
2147 (widget-convert
2148 (cons 'const x)))
2149 org-todo-interpretation-widgets))
2150 widget))
2151 (repeat
2152 (string :tag "Keyword"))))))
2154 (defvar org-todo-keywords-1 nil
2155 "All TODO and DONE keywords active in a buffer.")
2156 (make-variable-buffer-local 'org-todo-keywords-1)
2157 (defvar org-todo-keywords-for-agenda nil)
2158 (defvar org-done-keywords-for-agenda nil)
2159 (defvar org-drawers-for-agenda nil)
2160 (defvar org-todo-keyword-alist-for-agenda nil)
2161 (defvar org-tag-alist-for-agenda nil)
2162 (defvar org-agenda-contributing-files nil)
2163 (defvar org-not-done-keywords nil)
2164 (make-variable-buffer-local 'org-not-done-keywords)
2165 (defvar org-done-keywords nil)
2166 (make-variable-buffer-local 'org-done-keywords)
2167 (defvar org-todo-heads nil)
2168 (make-variable-buffer-local 'org-todo-heads)
2169 (defvar org-todo-sets nil)
2170 (make-variable-buffer-local 'org-todo-sets)
2171 (defvar org-todo-log-states nil)
2172 (make-variable-buffer-local 'org-todo-log-states)
2173 (defvar org-todo-kwd-alist nil)
2174 (make-variable-buffer-local 'org-todo-kwd-alist)
2175 (defvar org-todo-key-alist nil)
2176 (make-variable-buffer-local 'org-todo-key-alist)
2177 (defvar org-todo-key-trigger nil)
2178 (make-variable-buffer-local 'org-todo-key-trigger)
2180 (defcustom org-todo-interpretation 'sequence
2181 "Controls how TODO keywords are interpreted.
2182 This variable is in principle obsolete and is only used for
2183 backward compatibility, if the interpretation of todo keywords is
2184 not given already in `org-todo-keywords'. See that variable for
2185 more information."
2186 :group 'org-todo
2187 :group 'org-keywords
2188 :type '(choice (const sequence)
2189 (const type)))
2191 (defcustom org-use-fast-todo-selection t
2192 "Non-nil means use the fast todo selection scheme with C-c C-t.
2193 This variable describes if and under what circumstances the cycling
2194 mechanism for TODO keywords will be replaced by a single-key, direct
2195 selection scheme.
2197 When nil, fast selection is never used.
2199 When the symbol `prefix', it will be used when `org-todo' is called
2200 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2201 `C-u t' in an agenda buffer.
2203 When t, fast selection is used by default. In this case, the prefix
2204 argument forces cycling instead.
2206 In all cases, the special interface is only used if access keys have
2207 actually been assigned by the user, i.e. if keywords in the configuration
2208 are followed by a letter in parenthesis, like TODO(t)."
2209 :group 'org-todo
2210 :type '(choice
2211 (const :tag "Never" nil)
2212 (const :tag "By default" t)
2213 (const :tag "Only with C-u C-c C-t" prefix)))
2215 (defcustom org-provide-todo-statistics t
2216 "Non-nil means update todo statistics after insert and toggle.
2217 ALL-HEADLINES means update todo statistics by including headlines
2218 with no TODO keyword as well, counting them as not done.
2219 A list of TODO keywords means the same, but skip keywords that are
2220 not in this list.
2222 When this is set, todo statistics is updated in the parent of the
2223 current entry each time a todo state is changed."
2224 :group 'org-todo
2225 :type '(choice
2226 (const :tag "Yes, only for TODO entries" t)
2227 (const :tag "Yes, including all entries" 'all-headlines)
2228 (repeat :tag "Yes, for TODOs in this list"
2229 (string :tag "TODO keyword"))
2230 (other :tag "No TODO statistics" nil)))
2232 (defcustom org-hierarchical-todo-statistics t
2233 "Non-nil means TODO statistics covers just direct children.
2234 When nil, all entries in the subtree are considered.
2235 This has only an effect if `org-provide-todo-statistics' is set.
2236 To set this to nil for only a single subtree, use a COOKIE_DATA
2237 property and include the word \"recursive\" into the value."
2238 :group 'org-todo
2239 :type 'boolean)
2241 (defcustom org-after-todo-state-change-hook nil
2242 "Hook which is run after the state of a TODO item was changed.
2243 The new state (a string with a TODO keyword, or nil) is available in the
2244 Lisp variable `org-state'."
2245 :group 'org-todo
2246 :type 'hook)
2248 (defvar org-blocker-hook nil
2249 "Hook for functions that are allowed to block a state change.
2251 Functions in this hook should not modify the buffer.
2252 Each function gets as its single argument a property list,
2253 see `org-trigger-hook' for more information about this list.
2255 If any of the functions in this hook returns nil, the state change
2256 is blocked.")
2258 (defvar org-trigger-hook nil
2259 "Hook for functions that are triggered by a state change.
2261 Each function gets as its single argument a property list with at
2262 least the following elements:
2264 (:type type-of-change :position pos-at-entry-start
2265 :from old-state :to new-state)
2267 Depending on the type, more properties may be present.
2269 This mechanism is currently implemented for:
2271 TODO state changes
2272 ------------------
2273 :type todo-state-change
2274 :from previous state (keyword as a string), or nil, or a symbol
2275 'todo' or 'done', to indicate the general type of state.
2276 :to new state, like in :from")
2278 (defcustom org-enforce-todo-dependencies nil
2279 "Non-nil means undone TODO entries will block switching the parent to DONE.
2280 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2281 be blocked if any prior sibling is not yet done.
2282 Finally, if the parent is blocked because of ordered siblings of its own,
2283 the child will also be blocked."
2284 :set (lambda (var val)
2285 (set var val)
2286 (if val
2287 (add-hook 'org-blocker-hook
2288 'org-block-todo-from-children-or-siblings-or-parent)
2289 (remove-hook 'org-blocker-hook
2290 'org-block-todo-from-children-or-siblings-or-parent)))
2291 :group 'org-todo
2292 :type 'boolean)
2294 (defcustom org-enforce-todo-checkbox-dependencies nil
2295 "Non-nil means unchecked boxes will block switching the parent to DONE.
2296 When this is nil, checkboxes have no influence on switching TODO states.
2297 When non-nil, you first need to check off all check boxes before the TODO
2298 entry can be switched to DONE.
2299 This variable needs to be set before org.el is loaded, and you need to
2300 restart Emacs after a change to make the change effective. The only way
2301 to change is while Emacs is running is through the customize interface."
2302 :set (lambda (var val)
2303 (set var val)
2304 (if val
2305 (add-hook 'org-blocker-hook
2306 'org-block-todo-from-checkboxes)
2307 (remove-hook 'org-blocker-hook
2308 'org-block-todo-from-checkboxes)))
2309 :group 'org-todo
2310 :type 'boolean)
2312 (defcustom org-treat-insert-todo-heading-as-state-change nil
2313 "Non-nil means inserting a TODO heading is treated as state change.
2314 So when the command \\[org-insert-todo-heading] is used, state change
2315 logging will apply if appropriate. When nil, the new TODO item will
2316 be inserted directly, and no logging will take place."
2317 :group 'org-todo
2318 :type 'boolean)
2320 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2321 "Non-nil means switching TODO states with S-cursor counts as state change.
2322 This is the default behavior. However, setting this to nil allows a
2323 convenient way to select a TODO state and bypass any logging associated
2324 with that."
2325 :group 'org-todo
2326 :type 'boolean)
2328 (defcustom org-todo-state-tags-triggers nil
2329 "Tag changes that should be triggered by TODO state changes.
2330 This is a list. Each entry is
2332 (state-change (tag . flag) .......)
2334 State-change can be a string with a state, and empty string to indicate the
2335 state that has no TODO keyword, or it can be one of the symbols `todo'
2336 or `done', meaning any not-done or done state, respectively."
2337 :group 'org-todo
2338 :group 'org-tags
2339 :type '(repeat
2340 (cons (choice :tag "When changing to"
2341 (const :tag "Not-done state" todo)
2342 (const :tag "Done state" done)
2343 (string :tag "State"))
2344 (repeat
2345 (cons :tag "Tag action"
2346 (string :tag "Tag")
2347 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2349 (defcustom org-log-done nil
2350 "Information to record when a task moves to the DONE state.
2352 Possible values are:
2354 nil Don't add anything, just change the keyword
2355 time Add a time stamp to the task
2356 note Prompt for a note and add it with template `org-log-note-headings'
2358 This option can also be set with on a per-file-basis with
2360 #+STARTUP: nologdone
2361 #+STARTUP: logdone
2362 #+STARTUP: lognotedone
2364 You can have local logging settings for a subtree by setting the LOGGING
2365 property to one or more of these keywords."
2366 :group 'org-todo
2367 :group 'org-progress
2368 :type '(choice
2369 (const :tag "No logging" nil)
2370 (const :tag "Record CLOSED timestamp" time)
2371 (const :tag "Record CLOSED timestamp with note." note)))
2373 ;; Normalize old uses of org-log-done.
2374 (cond
2375 ((eq org-log-done t) (setq org-log-done 'time))
2376 ((and (listp org-log-done) (memq 'done org-log-done))
2377 (setq org-log-done 'note)))
2379 (defcustom org-log-reschedule nil
2380 "Information to record when the scheduling date of a tasks is modified.
2382 Possible values are:
2384 nil Don't add anything, just change the date
2385 time Add a time stamp to the task
2386 note Prompt for a note and add it with template `org-log-note-headings'
2388 This option can also be set with on a per-file-basis with
2390 #+STARTUP: nologreschedule
2391 #+STARTUP: logreschedule
2392 #+STARTUP: lognotereschedule"
2393 :group 'org-todo
2394 :group 'org-progress
2395 :type '(choice
2396 (const :tag "No logging" nil)
2397 (const :tag "Record timestamp" time)
2398 (const :tag "Record timestamp with note." note)))
2400 (defcustom org-log-redeadline nil
2401 "Information to record when the deadline date of a tasks is modified.
2403 Possible values are:
2405 nil Don't add anything, just change the date
2406 time Add a time stamp to the task
2407 note Prompt for a note and add it with template `org-log-note-headings'
2409 This option can also be set with on a per-file-basis with
2411 #+STARTUP: nologredeadline
2412 #+STARTUP: logredeadline
2413 #+STARTUP: lognoteredeadline
2415 You can have local logging settings for a subtree by setting the LOGGING
2416 property to one or more of these keywords."
2417 :group 'org-todo
2418 :group 'org-progress
2419 :type '(choice
2420 (const :tag "No logging" nil)
2421 (const :tag "Record timestamp" time)
2422 (const :tag "Record timestamp with note." note)))
2424 (defcustom org-log-note-clock-out nil
2425 "Non-nil means record a note when clocking out of an item.
2426 This can also be configured on a per-file basis by adding one of
2427 the following lines anywhere in the buffer:
2429 #+STARTUP: lognoteclock-out
2430 #+STARTUP: nolognoteclock-out"
2431 :group 'org-todo
2432 :group 'org-progress
2433 :type 'boolean)
2435 (defcustom org-log-done-with-time t
2436 "Non-nil means the CLOSED time stamp will contain date and time.
2437 When nil, only the date will be recorded."
2438 :group 'org-progress
2439 :type 'boolean)
2441 (defcustom org-log-note-headings
2442 '((done . "CLOSING NOTE %t")
2443 (state . "State %-12s from %-12S %t")
2444 (note . "Note taken on %t")
2445 (reschedule . "Rescheduled from %S on %t")
2446 (delschedule . "Not scheduled, was %S on %t")
2447 (redeadline . "New deadline from %S on %t")
2448 (deldeadline . "Removed deadline, was %S on %t")
2449 (refile . "Refiled on %t")
2450 (clock-out . ""))
2451 "Headings for notes added to entries.
2452 The value is an alist, with the car being a symbol indicating the note
2453 context, and the cdr is the heading to be used. The heading may also be the
2454 empty string.
2455 %t in the heading will be replaced by a time stamp.
2456 %T will be an active time stamp instead the default inactive one
2457 %d will be replaced by a short-format time stamp.
2458 %D will be replaced by an active short-format time stamp.
2459 %s will be replaced by the new TODO state, in double quotes.
2460 %S will be replaced by the old TODO state, in double quotes.
2461 %u will be replaced by the user name.
2462 %U will be replaced by the full user name.
2464 In fact, it is not a good idea to change the `state' entry, because
2465 agenda log mode depends on the format of these entries."
2466 :group 'org-todo
2467 :group 'org-progress
2468 :type '(list :greedy t
2469 (cons (const :tag "Heading when closing an item" done) string)
2470 (cons (const :tag
2471 "Heading when changing todo state (todo sequence only)"
2472 state) string)
2473 (cons (const :tag "Heading when just taking a note" note) string)
2474 (cons (const :tag "Heading when clocking out" clock-out) string)
2475 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2476 (cons (const :tag "Heading when rescheduling" reschedule) string)
2477 (cons (const :tag "Heading when changing deadline" redeadline) string)
2478 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2479 (cons (const :tag "Heading when refiling" refile) string)))
2481 (unless (assq 'note org-log-note-headings)
2482 (push '(note . "%t") org-log-note-headings))
2484 (defcustom org-log-into-drawer nil
2485 "Non-nil means insert state change notes and time stamps into a drawer.
2486 When nil, state changes notes will be inserted after the headline and
2487 any scheduling and clock lines, but not inside a drawer.
2489 The value of this variable should be the name of the drawer to use.
2490 LOGBOOK is proposed as the default drawer for this purpose, you can
2491 also set this to a string to define the drawer of your choice.
2493 A value of t is also allowed, representing \"LOGBOOK\".
2495 If this variable is set, `org-log-state-notes-insert-after-drawers'
2496 will be ignored.
2498 You can set the property LOG_INTO_DRAWER to overrule this setting for
2499 a subtree."
2500 :group 'org-todo
2501 :group 'org-progress
2502 :type '(choice
2503 (const :tag "Not into a drawer" nil)
2504 (const :tag "LOGBOOK" t)
2505 (string :tag "Other")))
2507 (if (fboundp 'defvaralias)
2508 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2510 (defun org-log-into-drawer ()
2511 "Return the value of `org-log-into-drawer', but let properties overrule.
2512 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2513 used instead of the default value."
2514 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2515 (cond
2516 ((not p) org-log-into-drawer)
2517 ((equal p "nil") nil)
2518 ((equal p "t") "LOGBOOK")
2519 (t p))))
2521 (defcustom org-log-state-notes-insert-after-drawers nil
2522 "Non-nil means insert state change notes after any drawers in entry.
2523 Only the drawers that *immediately* follow the headline and the
2524 deadline/scheduled line are skipped.
2525 When nil, insert notes right after the heading and perhaps the line
2526 with deadline/scheduling if present.
2528 This variable will have no effect if `org-log-into-drawer' is
2529 set."
2530 :group 'org-todo
2531 :group 'org-progress
2532 :type 'boolean)
2534 (defcustom org-log-states-order-reversed t
2535 "Non-nil means the latest state note will be directly after heading.
2536 When nil, the state change notes will be ordered according to time."
2537 :group 'org-todo
2538 :group 'org-progress
2539 :type 'boolean)
2541 (defcustom org-todo-repeat-to-state nil
2542 "The TODO state to which a repeater should return the repeating task.
2543 By default this is the first task in a TODO sequence, or the previous state
2544 in a TODO_TYP set. But you can specify another task here.
2545 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2546 :group 'org-todo
2547 :version "24.1"
2548 :type '(choice (const :tag "Head of sequence" nil)
2549 (string :tag "Specific state")))
2551 (defcustom org-log-repeat 'time
2552 "Non-nil means record moving through the DONE state when triggering repeat.
2553 An auto-repeating task is immediately switched back to TODO when
2554 marked DONE. If you are not logging state changes (by adding \"@\"
2555 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2556 record a closing note, there will be no record of the task moving
2557 through DONE. This variable forces taking a note anyway.
2559 nil Don't force a record
2560 time Record a time stamp
2561 note Prompt for a note and add it with template `org-log-note-headings'
2563 This option can also be set with on a per-file-basis with
2565 #+STARTUP: nologrepeat
2566 #+STARTUP: logrepeat
2567 #+STARTUP: lognoterepeat
2569 You can have local logging settings for a subtree by setting the LOGGING
2570 property to one or more of these keywords."
2571 :group 'org-todo
2572 :group 'org-progress
2573 :type '(choice
2574 (const :tag "Don't force a record" nil)
2575 (const :tag "Force recording the DONE state" time)
2576 (const :tag "Force recording a note with the DONE state" note)))
2579 (defgroup org-priorities nil
2580 "Priorities in Org-mode."
2581 :tag "Org Priorities"
2582 :group 'org-todo)
2584 (defcustom org-enable-priority-commands t
2585 "Non-nil means priority commands are active.
2586 When nil, these commands will be disabled, so that you never accidentally
2587 set a priority."
2588 :group 'org-priorities
2589 :type 'boolean)
2591 (defcustom org-highest-priority ?A
2592 "The highest priority of TODO items. A character like ?A, ?B etc.
2593 Must have a smaller ASCII number than `org-lowest-priority'."
2594 :group 'org-priorities
2595 :type 'character)
2597 (defcustom org-lowest-priority ?C
2598 "The lowest priority of TODO items. A character like ?A, ?B etc.
2599 Must have a larger ASCII number than `org-highest-priority'."
2600 :group 'org-priorities
2601 :type 'character)
2603 (defcustom org-default-priority ?B
2604 "The default priority of TODO items.
2605 This is the priority an item gets if no explicit priority is given.
2606 When starting to cycle on an empty priority the first step in the cycle
2607 depends on `org-priority-start-cycle-with-default'. The resulting first
2608 step priority must not exceed the range from `org-highest-priority' to
2609 `org-lowest-priority' which means that `org-default-priority' has to be
2610 in this range exclusive or inclusive the range boundaries. Else the
2611 first step refuses to set the default and the second will fall back
2612 to (depending on the command used) the highest or lowest priority."
2613 :group 'org-priorities
2614 :type 'character)
2616 (defcustom org-priority-start-cycle-with-default t
2617 "Non-nil means start with default priority when starting to cycle.
2618 When this is nil, the first step in the cycle will be (depending on the
2619 command used) one higher or lower than the default priority.
2620 See also `org-default-priority'."
2621 :group 'org-priorities
2622 :type 'boolean)
2624 (defcustom org-get-priority-function nil
2625 "Function to extract the priority from a string.
2626 The string is normally the headline. If this is nil Org computes the
2627 priority from the priority cookie like [#A] in the headline. It returns
2628 an integer, increasing by 1000 for each priority level.
2629 The user can set a different function here, which should take a string
2630 as an argument and return the numeric priority."
2631 :group 'org-priorities
2632 :version "24.1"
2633 :type 'function)
2635 (defgroup org-time nil
2636 "Options concerning time stamps and deadlines in Org-mode."
2637 :tag "Org Time"
2638 :group 'org)
2640 (defcustom org-insert-labeled-timestamps-at-point nil
2641 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2642 When nil, these labeled time stamps are forces into the second line of an
2643 entry, just after the headline. When scheduling from the global TODO list,
2644 the time stamp will always be forced into the second line."
2645 :group 'org-time
2646 :type 'boolean)
2648 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2649 "Formats for `format-time-string' which are used for time stamps.
2650 It is not recommended to change this constant.")
2652 (defcustom org-time-stamp-rounding-minutes '(0 5)
2653 "Number of minutes to round time stamps to.
2654 These are two values, the first applies when first creating a time stamp.
2655 The second applies when changing it with the commands `S-up' and `S-down'.
2656 When changing the time stamp, this means that it will change in steps
2657 of N minutes, as given by the second value.
2659 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2660 numbers should be factors of 60, so for example 5, 10, 15.
2662 When this is larger than 1, you can still force an exact time stamp by using
2663 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2664 and by using a prefix arg to `S-up/down' to specify the exact number
2665 of minutes to shift."
2666 :group 'org-time
2667 :get #'(lambda (var) ; Make sure both elements are there
2668 (if (integerp (default-value var))
2669 (list (default-value var) 5)
2670 (default-value var)))
2671 :type '(list
2672 (integer :tag "when inserting times")
2673 (integer :tag "when modifying times")))
2675 ;; Normalize old customizations of this variable.
2676 (when (integerp org-time-stamp-rounding-minutes)
2677 (setq org-time-stamp-rounding-minutes
2678 (list org-time-stamp-rounding-minutes
2679 org-time-stamp-rounding-minutes)))
2681 (defcustom org-display-custom-times nil
2682 "Non-nil means overlay custom formats over all time stamps.
2683 The formats are defined through the variable `org-time-stamp-custom-formats'.
2684 To turn this on on a per-file basis, insert anywhere in the file:
2685 #+STARTUP: customtime"
2686 :group 'org-time
2687 :set 'set-default
2688 :type 'sexp)
2689 (make-variable-buffer-local 'org-display-custom-times)
2691 (defcustom org-time-stamp-custom-formats
2692 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2693 "Custom formats for time stamps. See `format-time-string' for the syntax.
2694 These are overlaid over the default ISO format if the variable
2695 `org-display-custom-times' is set. Time like %H:%M should be at the
2696 end of the second format. The custom formats are also honored by export
2697 commands, if custom time display is turned on at the time of export."
2698 :group 'org-time
2699 :type 'sexp)
2701 (defun org-time-stamp-format (&optional long inactive)
2702 "Get the right format for a time string."
2703 (let ((f (if long (cdr org-time-stamp-formats)
2704 (car org-time-stamp-formats))))
2705 (if inactive
2706 (concat "[" (substring f 1 -1) "]")
2707 f)))
2709 (defcustom org-time-clocksum-format "%d:%02d"
2710 "The format string used when creating CLOCKSUM lines.
2711 This is also used when org-mode generates a time duration."
2712 :group 'org-time
2713 :type 'string)
2715 (defcustom org-time-clocksum-use-fractional nil
2716 "If non-nil, \\[org-clock-display] uses fractional times.
2717 org-mode generates a time duration."
2718 :group 'org-time
2719 :type 'boolean)
2721 (defcustom org-time-clocksum-fractional-format "%.2f"
2722 "The format string used when creating CLOCKSUM lines, or when
2723 org-mode generates a time duration."
2724 :group 'org-time
2725 :type 'string)
2727 (defcustom org-deadline-warning-days 14
2728 "No. of days before expiration during which a deadline becomes active.
2729 This variable governs the display in sparse trees and in the agenda.
2730 When 0 or negative, it means use this number (the absolute value of it)
2731 even if a deadline has a different individual lead time specified.
2733 Custom commands can set this variable in the options section."
2734 :group 'org-time
2735 :group 'org-agenda-daily/weekly
2736 :type 'integer)
2738 (defcustom org-read-date-prefer-future t
2739 "Non-nil means assume future for incomplete date input from user.
2740 This affects the following situations:
2741 1. The user gives a month but not a year.
2742 For example, if it is April and you enter \"feb 2\", this will be read
2743 as Feb 2, *next* year. \"May 5\", however, will be this year.
2744 2. The user gives a day, but no month.
2745 For example, if today is the 15th, and you enter \"3\", Org-mode will
2746 read this as the third of *next* month. However, if you enter \"17\",
2747 it will be considered as *this* month.
2749 If you set this variable to the symbol `time', then also the following
2750 will work:
2752 3. If the user gives a time.
2753 If the time is before now, it will be interpreted as tomorrow.
2755 Currently none of this works for ISO week specifications.
2757 When this option is nil, the current day, month and year will always be
2758 used as defaults.
2760 See also `org-agenda-jump-prefer-future'."
2761 :group 'org-time
2762 :type '(choice
2763 (const :tag "Never" nil)
2764 (const :tag "Check month and day" t)
2765 (const :tag "Check month, day, and time" time)))
2767 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2768 "Should the agenda jump command prefer the future for incomplete dates?
2769 The default is to do the same as configured in `org-read-date-prefer-future'.
2770 But you can also set a deviating value here.
2771 This may t or nil, or the symbol `org-read-date-prefer-future'."
2772 :group 'org-agenda
2773 :group 'org-time
2774 :version "24.1"
2775 :type '(choice
2776 (const :tag "Use org-read-date-prefer-future"
2777 org-read-date-prefer-future)
2778 (const :tag "Never" nil)
2779 (const :tag "Always" t)))
2781 (defcustom org-read-date-force-compatible-dates t
2782 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2784 Depending on the system Emacs is running on, certain dates cannot
2785 be represented with the type used internally to represent time.
2786 Dates between 1970-1-1 and 2038-1-1 can always be represented
2787 correctly. Some systems allow for earlier dates, some for later,
2788 some for both. One way to find out it to insert any date into an
2789 Org buffer, putting the cursor on the year and hitting S-up and
2790 S-down to test the range.
2792 When this variable is set to t, the date/time prompt will not let
2793 you specify dates outside the 1970-2037 range, so it is certain that
2794 these dates will work in whatever version of Emacs you are
2795 running, and also that you can move a file from one Emacs implementation
2796 to another. WHenever Org is forcing the year for you, it will display
2797 a message and beep.
2799 When this variable is nil, Org will check if the date is
2800 representable in the specific Emacs implementation you are using.
2801 If not, it will force a year, usually the current year, and beep
2802 to remind you. Currently this setting is not recommended because
2803 the likelihood that you will open your Org files in an Emacs that
2804 has limited date range is not negligible.
2806 A workaround for this problem is to use diary sexp dates for time
2807 stamps outside of this range."
2808 :group 'org-time
2809 :version "24.1"
2810 :type 'boolean)
2812 (defcustom org-read-date-display-live t
2813 "Non-nil means display current interpretation of date prompt live.
2814 This display will be in an overlay, in the minibuffer."
2815 :group 'org-time
2816 :type 'boolean)
2818 (defcustom org-read-date-popup-calendar t
2819 "Non-nil means pop up a calendar when prompting for a date.
2820 In the calendar, the date can be selected with mouse-1. However, the
2821 minibuffer will also be active, and you can simply enter the date as well.
2822 When nil, only the minibuffer will be available."
2823 :group 'org-time
2824 :type 'boolean)
2825 (if (fboundp 'defvaralias)
2826 (defvaralias 'org-popup-calendar-for-date-prompt
2827 'org-read-date-popup-calendar))
2829 (defcustom org-read-date-minibuffer-setup-hook nil
2830 "Hook to be used to set up keys for the date/time interface.
2831 Add key definitions to `minibuffer-local-map', which will be a temporary
2832 copy."
2833 :group 'org-time
2834 :type 'hook)
2836 (defcustom org-extend-today-until 0
2837 "The hour when your day really ends. Must be an integer.
2838 This has influence for the following applications:
2839 - When switching the agenda to \"today\". It it is still earlier than
2840 the time given here, the day recognized as TODAY is actually yesterday.
2841 - When a date is read from the user and it is still before the time given
2842 here, the current date and time will be assumed to be yesterday, 23:59.
2843 Also, timestamps inserted in capture templates follow this rule.
2845 IMPORTANT: This is a feature whose implementation is and likely will
2846 remain incomplete. Really, it is only here because past midnight seems to
2847 be the favorite working time of John Wiegley :-)"
2848 :group 'org-time
2849 :type 'integer)
2851 (defcustom org-use-effective-time nil
2852 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2853 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2854 \"effective time\" of any timestamps between midnight and 8am will be
2855 23:59 of the previous day."
2856 :group 'org-time
2857 :version "24.1"
2858 :type 'boolean)
2860 (defcustom org-edit-timestamp-down-means-later nil
2861 "Non-nil means S-down will increase the time in a time stamp.
2862 When nil, S-up will increase."
2863 :group 'org-time
2864 :type 'boolean)
2866 (defcustom org-calendar-follow-timestamp-change t
2867 "Non-nil means make the calendar window follow timestamp changes.
2868 When a timestamp is modified and the calendar window is visible, it will be
2869 moved to the new date."
2870 :group 'org-time
2871 :type 'boolean)
2873 (defgroup org-tags nil
2874 "Options concerning tags in Org-mode."
2875 :tag "Org Tags"
2876 :group 'org)
2878 (defcustom org-tag-alist nil
2879 "List of tags allowed in Org-mode files.
2880 When this list is nil, Org-mode will base TAG input on what is already in the
2881 buffer.
2882 The value of this variable is an alist, the car of each entry must be a
2883 keyword as a string, the cdr may be a character that is used to select
2884 that tag through the fast-tag-selection interface.
2885 See the manual for details."
2886 :group 'org-tags
2887 :type '(repeat
2888 (choice
2889 (cons (string :tag "Tag name")
2890 (character :tag "Access char"))
2891 (list :tag "Start radio group"
2892 (const :startgroup)
2893 (option (string :tag "Group description")))
2894 (list :tag "End radio group"
2895 (const :endgroup)
2896 (option (string :tag "Group description")))
2897 (const :tag "New line" (:newline)))))
2899 (defcustom org-tag-persistent-alist nil
2900 "List of tags that will always appear in all Org-mode files.
2901 This is in addition to any in buffer settings or customizations
2902 of `org-tag-alist'.
2903 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2904 The value of this variable is an alist, the car of each entry must be a
2905 keyword as a string, the cdr may be a character that is used to select
2906 that tag through the fast-tag-selection interface.
2907 See the manual for details.
2908 To disable these tags on a per-file basis, insert anywhere in the file:
2909 #+STARTUP: noptag"
2910 :group 'org-tags
2911 :type '(repeat
2912 (choice
2913 (cons (string :tag "Tag name")
2914 (character :tag "Access char"))
2915 (const :tag "Start radio group" (:startgroup))
2916 (const :tag "End radio group" (:endgroup))
2917 (const :tag "New line" (:newline)))))
2919 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2920 "If non-nil, always offer completion for all tags of all agenda files.
2921 Instead of customizing this variable directly, you might want to
2922 set it locally for capture buffers, because there no list of
2923 tags in that file can be created dynamically (there are none).
2925 (add-hook 'org-capture-mode-hook
2926 (lambda ()
2927 (set (make-local-variable
2928 'org-complete-tags-always-offer-all-agenda-tags)
2929 t)))"
2930 :group 'org-tags
2931 :version "24.1"
2932 :type 'boolean)
2934 (defvar org-file-tags nil
2935 "List of tags that can be inherited by all entries in the file.
2936 The tags will be inherited if the variable `org-use-tag-inheritance'
2937 says they should be.
2938 This variable is populated from #+FILETAGS lines.")
2940 (defcustom org-use-fast-tag-selection 'auto
2941 "Non-nil means use fast tag selection scheme.
2942 This is a special interface to select and deselect tags with single keys.
2943 When nil, fast selection is never used.
2944 When the symbol `auto', fast selection is used if and only if selection
2945 characters for tags have been configured, either through the variable
2946 `org-tag-alist' or through a #+TAGS line in the buffer.
2947 When t, fast selection is always used and selection keys are assigned
2948 automatically if necessary."
2949 :group 'org-tags
2950 :type '(choice
2951 (const :tag "Always" t)
2952 (const :tag "Never" nil)
2953 (const :tag "When selection characters are configured" 'auto)))
2955 (defcustom org-fast-tag-selection-single-key nil
2956 "Non-nil means fast tag selection exits after first change.
2957 When nil, you have to press RET to exit it.
2958 During fast tag selection, you can toggle this flag with `C-c'.
2959 This variable can also have the value `expert'. In this case, the window
2960 displaying the tags menu is not even shown, until you press C-c again."
2961 :group 'org-tags
2962 :type '(choice
2963 (const :tag "No" nil)
2964 (const :tag "Yes" t)
2965 (const :tag "Expert" expert)))
2967 (defvar org-fast-tag-selection-include-todo nil
2968 "Non-nil means fast tags selection interface will also offer TODO states.
2969 This is an undocumented feature, you should not rely on it.")
2971 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2972 "The column to which tags should be indented in a headline.
2973 If this number is positive, it specifies the column. If it is negative,
2974 it means that the tags should be flushright to that column. For example,
2975 -80 works well for a normal 80 character screen.
2976 When 0, place tags directly after headline text, with only one space in
2977 between."
2978 :group 'org-tags
2979 :type 'integer)
2981 (defcustom org-auto-align-tags t
2982 "Non-nil keeps tags aligned when modifying headlines.
2983 Some operations (i.e. demoting) change the length of a headline and
2984 therefore shift the tags around. With this option turned on, after
2985 each such operation the tags are again aligned to `org-tags-column'."
2986 :group 'org-tags
2987 :type 'boolean)
2989 (defcustom org-use-tag-inheritance t
2990 "Non-nil means tags in levels apply also for sublevels.
2991 When nil, only the tags directly given in a specific line apply there.
2992 This may also be a list of tags that should be inherited, or a regexp that
2993 matches tags that should be inherited. Additional control is possible
2994 with the variable `org-tags-exclude-from-inheritance' which gives an
2995 explicit list of tags to be excluded from inheritance, even if the value of
2996 `org-use-tag-inheritance' would select it for inheritance.
2998 If this option is t, a match early-on in a tree can lead to a large
2999 number of matches in the subtree when constructing the agenda or creating
3000 a sparse tree. If you only want to see the first match in a tree during
3001 a search, check out the variable `org-tags-match-list-sublevels'."
3002 :group 'org-tags
3003 :type '(choice
3004 (const :tag "Not" nil)
3005 (const :tag "Always" t)
3006 (repeat :tag "Specific tags" (string :tag "Tag"))
3007 (regexp :tag "Tags matched by regexp")))
3009 (defcustom org-tags-exclude-from-inheritance nil
3010 "List of tags that should never be inherited.
3011 This is a way to exclude a few tags from inheritance. For way to do
3012 the opposite, to actively allow inheritance for selected tags,
3013 see the variable `org-use-tag-inheritance'."
3014 :group 'org-tags
3015 :type '(repeat (string :tag "Tag")))
3017 (defun org-tag-inherit-p (tag)
3018 "Check if TAG is one that should be inherited."
3019 (cond
3020 ((member tag org-tags-exclude-from-inheritance) nil)
3021 ((eq org-use-tag-inheritance t) t)
3022 ((not org-use-tag-inheritance) nil)
3023 ((stringp org-use-tag-inheritance)
3024 (string-match org-use-tag-inheritance tag))
3025 ((listp org-use-tag-inheritance)
3026 (member tag org-use-tag-inheritance))
3027 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3029 (defcustom org-tags-match-list-sublevels t
3030 "Non-nil means list also sublevels of headlines matching a search.
3031 This variable applies to tags/property searches, and also to stuck
3032 projects because this search is based on a tags match as well.
3034 When set to the symbol `indented', sublevels are indented with
3035 leading dots.
3037 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3038 the sublevels of a headline matching a tag search often also match
3039 the same search. Listing all of them can create very long lists.
3040 Setting this variable to nil causes subtrees of a match to be skipped.
3042 This variable is semi-obsolete and probably should always be true. It
3043 is better to limit inheritance to certain tags using the variables
3044 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3045 :group 'org-tags
3046 :type '(choice
3047 (const :tag "No, don't list them" nil)
3048 (const :tag "Yes, do list them" t)
3049 (const :tag "List them, indented with leading dots" indented)))
3051 (defcustom org-tags-sort-function nil
3052 "When set, tags are sorted using this function as a comparator."
3053 :group 'org-tags
3054 :type '(choice
3055 (const :tag "No sorting" nil)
3056 (const :tag "Alphabetical" string<)
3057 (const :tag "Reverse alphabetical" string>)
3058 (function :tag "Custom function" nil)))
3060 (defvar org-tags-history nil
3061 "History of minibuffer reads for tags.")
3062 (defvar org-last-tags-completion-table nil
3063 "The last used completion table for tags.")
3064 (defvar org-after-tags-change-hook nil
3065 "Hook that is run after the tags in a line have changed.")
3067 (defgroup org-properties nil
3068 "Options concerning properties in Org-mode."
3069 :tag "Org Properties"
3070 :group 'org)
3072 (defcustom org-property-format "%-10s %s"
3073 "How property key/value pairs should be formatted by `indent-line'.
3074 When `indent-line' hits a property definition, it will format the line
3075 according to this format, mainly to make sure that the values are
3076 lined-up with respect to each other."
3077 :group 'org-properties
3078 :type 'string)
3080 (defcustom org-properties-postprocess-alist nil
3081 "Alist of properties and functions to adjust inserted values.
3082 Elements of this alist must be of the form
3084 ([string] [function])
3086 where [string] must be a property name and [function] must be a
3087 lambda expression: this lambda expression must take one argument,
3088 the value to adjust, and return the new value as a string.
3090 For example, this element will allow the property \"Remaining\"
3091 to be updated wrt the relation between the \"Effort\" property
3092 and the clock summary:
3094 ((\"Remaining\" (lambda(value)
3095 (let ((clocksum (org-clock-sum-current-item))
3096 (effort (org-duration-string-to-minutes
3097 (org-entry-get (point) \"Effort\"))))
3098 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3099 :group 'org-properties
3100 :version "24.1"
3101 :type '(alist :key-type (string :tag "Property")
3102 :value-type (function :tag "Function")))
3104 (defcustom org-use-property-inheritance nil
3105 "Non-nil means properties apply also for sublevels.
3107 This setting is chiefly used during property searches. Turning it on can
3108 cause significant overhead when doing a search, which is why it is not
3109 on by default.
3111 When nil, only the properties directly given in the current entry count.
3112 When t, every property is inherited. The value may also be a list of
3113 properties that should have inheritance, or a regular expression matching
3114 properties that should be inherited.
3116 However, note that some special properties use inheritance under special
3117 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3118 and the properties ending in \"_ALL\" when they are used as descriptor
3119 for valid values of a property.
3121 Note for programmers:
3122 When querying an entry with `org-entry-get', you can control if inheritance
3123 should be used. By default, `org-entry-get' looks only at the local
3124 properties. You can request inheritance by setting the inherit argument
3125 to t (to force inheritance) or to `selective' (to respect the setting
3126 in this variable)."
3127 :group 'org-properties
3128 :type '(choice
3129 (const :tag "Not" nil)
3130 (const :tag "Always" t)
3131 (repeat :tag "Specific properties" (string :tag "Property"))
3132 (regexp :tag "Properties matched by regexp")))
3134 (defun org-property-inherit-p (property)
3135 "Check if PROPERTY is one that should be inherited."
3136 (cond
3137 ((eq org-use-property-inheritance t) t)
3138 ((not org-use-property-inheritance) nil)
3139 ((stringp org-use-property-inheritance)
3140 (string-match org-use-property-inheritance property))
3141 ((listp org-use-property-inheritance)
3142 (member property org-use-property-inheritance))
3143 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3145 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3146 "The default column format, if no other format has been defined.
3147 This variable can be set on the per-file basis by inserting a line
3149 #+COLUMNS: %25ITEM ....."
3150 :group 'org-properties
3151 :type 'string)
3153 (defcustom org-columns-ellipses ".."
3154 "The ellipses to be used when a field in column view is truncated.
3155 When this is the empty string, as many characters as possible are shown,
3156 but then there will be no visual indication that the field has been truncated.
3157 When this is a string of length N, the last N characters of a truncated
3158 field are replaced by this string. If the column is narrower than the
3159 ellipses string, only part of the ellipses string will be shown."
3160 :group 'org-properties
3161 :type 'string)
3163 (defcustom org-columns-modify-value-for-display-function nil
3164 "Function that modifies values for display in column view.
3165 For example, it can be used to cut out a certain part from a time stamp.
3166 The function must take 2 arguments:
3168 column-title The title of the column (*not* the property name)
3169 value The value that should be modified.
3171 The function should return the value that should be displayed,
3172 or nil if the normal value should be used."
3173 :group 'org-properties
3174 :type 'function)
3176 (defcustom org-effort-property "Effort"
3177 "The property that is being used to keep track of effort estimates.
3178 Effort estimates given in this property need to have the format H:MM."
3179 :group 'org-properties
3180 :group 'org-progress
3181 :type '(string :tag "Property"))
3183 (defconst org-global-properties-fixed
3184 '(("VISIBILITY_ALL" . "folded children content all")
3185 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3186 "List of property/value pairs that can be inherited by any entry.
3188 These are fixed values, for the preset properties. The user variable
3189 that can be used to add to this list is `org-global-properties'.
3191 The entries in this list are cons cells where the car is a property
3192 name and cdr is a string with the value. If the value represents
3193 multiple items like an \"_ALL\" property, separate the items by
3194 spaces.")
3196 (defcustom org-global-properties nil
3197 "List of property/value pairs that can be inherited by any entry.
3199 This list will be combined with the constant `org-global-properties-fixed'.
3201 The entries in this list are cons cells where the car is a property
3202 name and cdr is a string with the value.
3204 You can set buffer-local values for the same purpose in the variable
3205 `org-file-properties' this by adding lines like
3207 #+PROPERTY: NAME VALUE"
3208 :group 'org-properties
3209 :type '(repeat
3210 (cons (string :tag "Property")
3211 (string :tag "Value"))))
3213 (defvar org-file-properties nil
3214 "List of property/value pairs that can be inherited by any entry.
3215 Valid for the current buffer.
3216 This variable is populated from #+PROPERTY lines.")
3217 (make-variable-buffer-local 'org-file-properties)
3219 (defgroup org-agenda nil
3220 "Options concerning agenda views in Org-mode."
3221 :tag "Org Agenda"
3222 :group 'org)
3224 (defvar org-category nil
3225 "Variable used by org files to set a category for agenda display.
3226 Such files should use a file variable to set it, for example
3228 # -*- mode: org; org-category: \"ELisp\"
3230 or contain a special line
3232 #+CATEGORY: ELisp
3234 If the file does not specify a category, then file's base name
3235 is used instead.")
3236 (make-variable-buffer-local 'org-category)
3237 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3239 (defcustom org-agenda-files nil
3240 "The files to be used for agenda display.
3241 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3242 \\[org-remove-file]. You can also use customize to edit the list.
3244 If an entry is a directory, all files in that directory that are matched by
3245 `org-agenda-file-regexp' will be part of the file list.
3247 If the value of the variable is not a list but a single file name, then
3248 the list of agenda files is actually stored and maintained in that file, one
3249 agenda file per line. In this file paths can be given relative to
3250 `org-directory'. Tilde expansion and environment variable substitution
3251 are also made."
3252 :group 'org-agenda
3253 :type '(choice
3254 (repeat :tag "List of files and directories" file)
3255 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3257 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3258 "Regular expression to match files for `org-agenda-files'.
3259 If any element in the list in that variable contains a directory instead
3260 of a normal file, all files in that directory that are matched by this
3261 regular expression will be included."
3262 :group 'org-agenda
3263 :type 'regexp)
3265 (defcustom org-agenda-text-search-extra-files nil
3266 "List of extra files to be searched by text search commands.
3267 These files will be search in addition to the agenda files by the
3268 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3269 Note that these files will only be searched for text search commands,
3270 not for the other agenda views like todo lists, tag searches or the weekly
3271 agenda. This variable is intended to list notes and possibly archive files
3272 that should also be searched by these two commands.
3273 In fact, if the first element in the list is the symbol `agenda-archives',
3274 than all archive files of all agenda files will be added to the search
3275 scope."
3276 :group 'org-agenda
3277 :type '(set :greedy t
3278 (const :tag "Agenda Archives" agenda-archives)
3279 (repeat :inline t (file))))
3281 (if (fboundp 'defvaralias)
3282 (defvaralias 'org-agenda-multi-occur-extra-files
3283 'org-agenda-text-search-extra-files))
3285 (defcustom org-agenda-skip-unavailable-files nil
3286 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3287 A nil value means to remove them, after a query, from the list."
3288 :group 'org-agenda
3289 :type 'boolean)
3291 (defcustom org-calendar-to-agenda-key [?c]
3292 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3293 The command `org-calendar-goto-agenda' will be bound to this key. The
3294 default is the character `c' because then `c' can be used to switch back and
3295 forth between agenda and calendar."
3296 :group 'org-agenda
3297 :type 'sexp)
3299 (defcustom org-calendar-insert-diary-entry-key [?i]
3300 "The key to be installed in `calendar-mode-map' for adding diary entries.
3301 This option is irrelevant until `org-agenda-diary-file' has been configured
3302 to point to an Org-mode file. When that is the case, the command
3303 `org-agenda-diary-entry' will be bound to the key given here, by default
3304 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3305 if you want to continue doing this, you need to change this to a different
3306 key."
3307 :group 'org-agenda
3308 :type 'sexp)
3310 (defcustom org-agenda-diary-file 'diary-file
3311 "File to which to add new entries with the `i' key in agenda and calendar.
3312 When this is the symbol `diary-file', the functionality in the Emacs
3313 calendar will be used to add entries to the `diary-file'. But when this
3314 points to a file, `org-agenda-diary-entry' will be used instead."
3315 :group 'org-agenda
3316 :type '(choice
3317 (const :tag "The standard Emacs diary file" diary-file)
3318 (file :tag "Special Org file diary entries")))
3320 (eval-after-load "calendar"
3321 '(progn
3322 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3323 'org-calendar-goto-agenda)
3324 (add-hook 'calendar-mode-hook
3325 (lambda ()
3326 (unless (eq org-agenda-diary-file 'diary-file)
3327 (define-key calendar-mode-map
3328 org-calendar-insert-diary-entry-key
3329 'org-agenda-diary-entry))))))
3331 (defgroup org-latex nil
3332 "Options for embedding LaTeX code into Org-mode."
3333 :tag "Org LaTeX"
3334 :group 'org)
3336 (defcustom org-format-latex-options
3337 '(:foreground default :background default :scale 1.0
3338 :html-foreground "Black" :html-background "Transparent"
3339 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3340 "Options for creating images from LaTeX fragments.
3341 This is a property list with the following properties:
3342 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3343 `default' means use the foreground of the default face.
3344 :background the background color, or \"Transparent\".
3345 `default' means use the background of the default face.
3346 :scale a scaling factor for the size of the images, to get more pixels
3347 :html-foreground, :html-background, :html-scale
3348 the same numbers for HTML export.
3349 :matchers a list indicating which matchers should be used to
3350 find LaTeX fragments. Valid members of this list are:
3351 \"begin\" find environments
3352 \"$1\" find single characters surrounded by $.$
3353 \"$\" find math expressions surrounded by $...$
3354 \"$$\" find math expressions surrounded by $$....$$
3355 \"\\(\" find math expressions surrounded by \\(...\\)
3356 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3357 :group 'org-latex
3358 :type 'plist)
3360 (defcustom org-format-latex-signal-error t
3361 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3362 When nil, just push out a message."
3363 :group 'org-latex
3364 :version "24.1"
3365 :type 'boolean)
3367 (defcustom org-latex-to-mathml-jar-file nil
3368 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3369 Use this to specify additional executable file say a jar file.
3371 When using MathToWeb as the converter, specify the full-path to
3372 your mathtoweb.jar file."
3373 :group 'org-latex
3374 :version "24.1"
3375 :type '(choice
3376 (const :tag "None" nil)
3377 (file :tag "JAR file" :must-match t)))
3379 (defcustom org-latex-to-mathml-convert-command nil
3380 "Command to convert LaTeX fragments to MathML.
3381 Replace format-specifiers in the command as noted below and use
3382 `shell-command' to convert LaTeX to MathML.
3383 %j: Executable file in fully expanded form as specified by
3384 `org-latex-to-mathml-jar-file'.
3385 %I: Input LaTeX file in fully expanded form
3386 %o: Output MathML file
3387 This command is used by `org-create-math-formula'.
3389 When using MathToWeb as the converter, set this to
3390 \"java -jar %j -unicode -force -df %o %I\"."
3391 :group 'org-latex
3392 :version "24.1"
3393 :type '(choice
3394 (const :tag "None" nil)
3395 (string :tag "\nShell command")))
3397 (defcustom org-latex-create-formula-image-program 'dvipng
3398 "Program to convert LaTeX fragments with.
3400 dvipng Process the LaTeX fragments to dvi file, then convert
3401 dvi files to png files using dvipng.
3402 This will also include processing of non-math environments.
3403 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3404 to convert pdf files to png files"
3405 :group 'org-latex
3406 :version "24.1"
3407 :type '(choice
3408 (const :tag "dvipng" dvipng)
3409 (const :tag "imagemagick" imagemagick)))
3411 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3412 "Path to store latex preview images. A relative path here creates many
3413 directories relative to the processed org files paths. An absolute path
3414 puts all preview images at the same place."
3415 :group 'org-latex
3416 :version "24.3"
3417 :type 'string)
3419 (defun org-format-latex-mathml-available-p ()
3420 "Return t if `org-latex-to-mathml-convert-command' is usable."
3421 (save-match-data
3422 (when (and (boundp 'org-latex-to-mathml-convert-command)
3423 org-latex-to-mathml-convert-command)
3424 (let ((executable (car (split-string
3425 org-latex-to-mathml-convert-command))))
3426 (when (executable-find executable)
3427 (if (string-match
3428 "%j" org-latex-to-mathml-convert-command)
3429 (file-readable-p org-latex-to-mathml-jar-file)
3430 t))))))
3432 (defcustom org-format-latex-header "\\documentclass{article}
3433 \\usepackage[usenames]{color}
3434 \\usepackage{amsmath}
3435 \\usepackage[mathscr]{eucal}
3436 \\pagestyle{empty} % do not remove
3437 \[PACKAGES]
3438 \[DEFAULT-PACKAGES]
3439 % The settings below are copied from fullpage.sty
3440 \\setlength{\\textwidth}{\\paperwidth}
3441 \\addtolength{\\textwidth}{-3cm}
3442 \\setlength{\\oddsidemargin}{1.5cm}
3443 \\addtolength{\\oddsidemargin}{-2.54cm}
3444 \\setlength{\\evensidemargin}{\\oddsidemargin}
3445 \\setlength{\\textheight}{\\paperheight}
3446 \\addtolength{\\textheight}{-\\headheight}
3447 \\addtolength{\\textheight}{-\\headsep}
3448 \\addtolength{\\textheight}{-\\footskip}
3449 \\addtolength{\\textheight}{-3cm}
3450 \\setlength{\\topmargin}{1.5cm}
3451 \\addtolength{\\topmargin}{-2.54cm}"
3452 "The document header used for processing LaTeX fragments.
3453 It is imperative that this header make sure that no page number
3454 appears on the page. The package defined in the variables
3455 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3456 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3457 will be appended."
3458 :group 'org-latex
3459 :type 'string)
3461 (defvar org-format-latex-header-extra nil)
3463 (defun org-set-packages-alist (var val)
3464 "Set the packages alist and make sure it has 3 elements per entry."
3465 (set var (mapcar (lambda (x)
3466 (if (and (consp x) (= (length x) 2))
3467 (list (car x) (nth 1 x) t)
3469 val)))
3471 (defun org-get-packages-alist (var)
3473 "Get the packages alist and make sure it has 3 elements per entry."
3474 (mapcar (lambda (x)
3475 (if (and (consp x) (= (length x) 2))
3476 (list (car x) (nth 1 x) t)
3478 (default-value var)))
3480 ;; The following variables are defined here because is it also used
3481 ;; when formatting latex fragments. Originally it was part of the
3482 ;; LaTeX exporter, which is why the name includes "export".
3483 (defcustom org-export-latex-default-packages-alist
3484 '(("AUTO" "inputenc" t)
3485 ("T1" "fontenc" t)
3486 ("" "fixltx2e" nil)
3487 ("" "graphicx" t)
3488 ("" "longtable" nil)
3489 ("" "float" nil)
3490 ("" "wrapfig" nil)
3491 ("" "soul" t)
3492 ("" "textcomp" t)
3493 ("" "marvosym" t)
3494 ("" "wasysym" t)
3495 ("" "latexsym" t)
3496 ("" "amssymb" t)
3497 ("" "hyperref" nil)
3498 "\\tolerance=1000"
3500 "Alist of default packages to be inserted in the header.
3501 Change this only if one of the packages here causes an incompatibility
3502 with another package you are using.
3503 The packages in this list are needed by one part or another of Org-mode
3504 to function properly.
3506 - inputenc, fontenc: for basic font and character selection
3507 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3508 for interpreting the entities in `org-entities'. You can skip some of these
3509 packages if you don't use any of the symbols in it.
3510 - graphicx: for including images
3511 - float, wrapfig: for figure placement
3512 - longtable: for long tables
3513 - hyperref: for cross references
3515 Therefore you should not modify this variable unless you know what you
3516 are doing. The one reason to change it anyway is that you might be loading
3517 some other package that conflicts with one of the default packages.
3518 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3519 If SNIPPET-FLAG is t, the package also needs to be included when
3520 compiling LaTeX snippets into images for inclusion into HTML."
3521 :group 'org-export-latex
3522 :set 'org-set-packages-alist
3523 :get 'org-get-packages-alist
3524 :version "24.1"
3525 :type '(repeat
3526 (choice
3527 (list :tag "options/package pair"
3528 (string :tag "options")
3529 (string :tag "package")
3530 (boolean :tag "Snippet"))
3531 (string :tag "A line of LaTeX"))))
3533 (defcustom org-export-latex-packages-alist nil
3534 "Alist of packages to be inserted in every LaTeX header.
3535 These will be inserted after `org-export-latex-default-packages-alist'.
3536 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3537 SNIPPET-FLAG, when t, indicates that this package is also needed when
3538 turning LaTeX snippets into images for inclusion into HTML.
3539 Make sure that you only list packages here which:
3540 - you want in every file
3541 - do not conflict with the default packages in
3542 `org-export-latex-default-packages-alist'
3543 - do not conflict with the setup in `org-format-latex-header'."
3544 :group 'org-export-latex
3545 :set 'org-set-packages-alist
3546 :get 'org-get-packages-alist
3547 :type '(repeat
3548 (choice
3549 (list :tag "options/package pair"
3550 (string :tag "options")
3551 (string :tag "package")
3552 (boolean :tag "Snippet"))
3553 (string :tag "A line of LaTeX"))))
3556 (defgroup org-appearance nil
3557 "Settings for Org-mode appearance."
3558 :tag "Org Appearance"
3559 :group 'org)
3561 (defcustom org-level-color-stars-only nil
3562 "Non-nil means fontify only the stars in each headline.
3563 When nil, the entire headline is fontified.
3564 Changing it requires restart of `font-lock-mode' to become effective
3565 also in regions already fontified."
3566 :group 'org-appearance
3567 :type 'boolean)
3569 (defcustom org-hide-leading-stars nil
3570 "Non-nil means hide the first N-1 stars in a headline.
3571 This works by using the face `org-hide' for these stars. This
3572 face is white for a light background, and black for a dark
3573 background. You may have to customize the face `org-hide' to
3574 make this work.
3575 Changing it requires restart of `font-lock-mode' to become effective
3576 also in regions already fontified.
3577 You may also set this on a per-file basis by adding one of the following
3578 lines to the buffer:
3580 #+STARTUP: hidestars
3581 #+STARTUP: showstars"
3582 :group 'org-appearance
3583 :type 'boolean)
3585 (defcustom org-hidden-keywords nil
3586 "List of symbols corresponding to keywords to be hidden the org buffer.
3587 For example, a value '(title) for this list will make the document's title
3588 appear in the buffer without the initial #+TITLE: keyword."
3589 :group 'org-appearance
3590 :version "24.1"
3591 :type '(set (const :tag "#+AUTHOR" author)
3592 (const :tag "#+DATE" date)
3593 (const :tag "#+EMAIL" email)
3594 (const :tag "#+TITLE" title)))
3596 (defcustom org-custom-properties nil
3597 "List of properties (as strings) with a special meaning.
3598 The default use of these custom properties is to let the user
3599 hide them with `org-toggle-custom-properties-visibility'."
3600 :group 'org-properties
3601 :group 'org-appearance
3602 :version "24.3"
3603 :type '(repeat (string :tag "Property Name")))
3605 (defcustom org-fontify-done-headline nil
3606 "Non-nil means change the face of a headline if it is marked DONE.
3607 Normally, only the TODO/DONE keyword indicates the state of a headline.
3608 When this is non-nil, the headline after the keyword is set to the
3609 `org-headline-done' as an additional indication."
3610 :group 'org-appearance
3611 :type 'boolean)
3613 (defcustom org-fontify-emphasized-text t
3614 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3615 Changing this variable requires a restart of Emacs to take effect."
3616 :group 'org-appearance
3617 :type 'boolean)
3619 (defcustom org-fontify-whole-heading-line nil
3620 "Non-nil means fontify the whole line for headings.
3621 This is useful when setting a background color for the
3622 org-level-* faces."
3623 :group 'org-appearance
3624 :type 'boolean)
3626 (defcustom org-highlight-latex-fragments-and-specials nil
3627 "Non-nil means fontify what is treated specially by the exporters."
3628 :group 'org-appearance
3629 :type 'boolean)
3631 (defcustom org-hide-emphasis-markers nil
3632 "Non-nil mean font-lock should hide the emphasis marker characters."
3633 :group 'org-appearance
3634 :type 'boolean)
3636 (defcustom org-pretty-entities nil
3637 "Non-nil means show entities as UTF8 characters.
3638 When nil, the \\name form remains in the buffer."
3639 :group 'org-appearance
3640 :version "24.1"
3641 :type 'boolean)
3643 (defcustom org-pretty-entities-include-sub-superscripts t
3644 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3645 :group 'org-appearance
3646 :version "24.1"
3647 :type 'boolean)
3649 (defvar org-emph-re nil
3650 "Regular expression for matching emphasis.
3651 After a match, the match groups contain these elements:
3652 0 The match of the full regular expression, including the characters
3653 before and after the proper match
3654 1 The character before the proper match, or empty at beginning of line
3655 2 The proper match, including the leading and trailing markers
3656 3 The leading marker like * or /, indicating the type of highlighting
3657 4 The text between the emphasis markers, not including the markers
3658 5 The character after the match, empty at the end of a line")
3659 (defvar org-verbatim-re nil
3660 "Regular expression for matching verbatim text.")
3661 (defvar org-emphasis-regexp-components) ; defined just below
3662 (defvar org-emphasis-alist) ; defined just below
3663 (defun org-set-emph-re (var val)
3664 "Set variable and compute the emphasis regular expression."
3665 (set var val)
3666 (when (and (boundp 'org-emphasis-alist)
3667 (boundp 'org-emphasis-regexp-components)
3668 org-emphasis-alist org-emphasis-regexp-components)
3669 (let* ((e org-emphasis-regexp-components)
3670 (pre (car e))
3671 (post (nth 1 e))
3672 (border (nth 2 e))
3673 (body (nth 3 e))
3674 (nl (nth 4 e))
3675 (body1 (concat body "*?"))
3676 (markers (mapconcat 'car org-emphasis-alist ""))
3677 (vmarkers (mapconcat
3678 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3679 org-emphasis-alist "")))
3680 ;; make sure special characters appear at the right position in the class
3681 (if (string-match "\\^" markers)
3682 (setq markers (concat (replace-match "" t t markers) "^")))
3683 (if (string-match "-" markers)
3684 (setq markers (concat (replace-match "" t t markers) "-")))
3685 (if (string-match "\\^" vmarkers)
3686 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3687 (if (string-match "-" vmarkers)
3688 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3689 (if (> nl 0)
3690 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3691 (int-to-string nl) "\\}")))
3692 ;; Make the regexp
3693 (setq org-emph-re
3694 (concat "\\([" pre "]\\|^\\)"
3695 "\\("
3696 "\\([" markers "]\\)"
3697 "\\("
3698 "[^" border "]\\|"
3699 "[^" border "]"
3700 body1
3701 "[^" border "]"
3702 "\\)"
3703 "\\3\\)"
3704 "\\([" post "]\\|$\\)"))
3705 (setq org-verbatim-re
3706 (concat "\\([" pre "]\\|^\\)"
3707 "\\("
3708 "\\([" vmarkers "]\\)"
3709 "\\("
3710 "[^" border "]\\|"
3711 "[^" border "]"
3712 body1
3713 "[^" border "]"
3714 "\\)"
3715 "\\3\\)"
3716 "\\([" post "]\\|$\\)")))))
3718 (defcustom org-emphasis-regexp-components
3719 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3720 "Components used to build the regular expression for emphasis.
3721 This is a list with five entries. Terminology: In an emphasis string
3722 like \" *strong word* \", we call the initial space PREMATCH, the final
3723 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3724 and \"trong wor\" is the body. The different components in this variable
3725 specify what is allowed/forbidden in each part:
3727 pre Chars allowed as prematch. Beginning of line will be allowed too.
3728 post Chars allowed as postmatch. End of line will be allowed too.
3729 border The chars *forbidden* as border characters.
3730 body-regexp A regexp like \".\" to match a body character. Don't use
3731 non-shy groups here, and don't allow newline here.
3732 newline The maximum number of newlines allowed in an emphasis exp.
3734 Use customize to modify this, or restart Emacs after changing it."
3735 :group 'org-appearance
3736 :set 'org-set-emph-re
3737 :type '(list
3738 (sexp :tag "Allowed chars in pre ")
3739 (sexp :tag "Allowed chars in post ")
3740 (sexp :tag "Forbidden chars in border ")
3741 (sexp :tag "Regexp for body ")
3742 (integer :tag "number of newlines allowed")
3743 (option (boolean :tag "Please ignore this button"))))
3745 (defcustom org-emphasis-alist
3746 `(("*" bold "<b>" "</b>")
3747 ("/" italic "<i>" "</i>")
3748 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3749 ("=" org-code "<code>" "</code>" verbatim)
3750 ("~" org-verbatim "<code>" "</code>" verbatim)
3751 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3752 "<del>" "</del>")
3754 "Special syntax for emphasized text.
3755 Text starting and ending with a special character will be emphasized, for
3756 example *bold*, _underlined_ and /italic/. This variable sets the marker
3757 characters, the face to be used by font-lock for highlighting in Org-mode
3758 Emacs buffers, and the HTML tags to be used for this.
3759 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3760 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3761 Use customize to modify this, or restart Emacs after changing it."
3762 :group 'org-appearance
3763 :set 'org-set-emph-re
3764 :type '(repeat
3765 (list
3766 (string :tag "Marker character")
3767 (choice
3768 (face :tag "Font-lock-face")
3769 (plist :tag "Face property list"))
3770 (string :tag "HTML start tag")
3771 (string :tag "HTML end tag")
3772 (option (const verbatim)))))
3774 (defvar org-protecting-blocks
3775 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3776 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3777 This is needed for font-lock setup.")
3779 ;;; Miscellaneous options
3781 (defgroup org-completion nil
3782 "Completion in Org-mode."
3783 :tag "Org Completion"
3784 :group 'org)
3786 (defcustom org-completion-use-ido nil
3787 "Non-nil means use ido completion wherever possible.
3788 Note that `ido-mode' must be active for this variable to be relevant.
3789 If you decide to turn this variable on, you might well want to turn off
3790 `org-outline-path-complete-in-steps'.
3791 See also `org-completion-use-iswitchb'."
3792 :group 'org-completion
3793 :type 'boolean)
3795 (defcustom org-completion-use-iswitchb nil
3796 "Non-nil means use iswitchb completion wherever possible.
3797 Note that `iswitchb-mode' must be active for this variable to be relevant.
3798 If you decide to turn this variable on, you might well want to turn off
3799 `org-outline-path-complete-in-steps'.
3800 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3801 :group 'org-completion
3802 :type 'boolean)
3804 (defcustom org-completion-fallback-command 'hippie-expand
3805 "The expansion command called by \\[pcomplete] in normal context.
3806 Normal means, no org-mode-specific context."
3807 :group 'org-completion
3808 :type 'function)
3810 ;;; Functions and variables from their packages
3811 ;; Declared here to avoid compiler warnings
3813 ;; XEmacs only
3814 (defvar outline-mode-menu-heading)
3815 (defvar outline-mode-menu-show)
3816 (defvar outline-mode-menu-hide)
3817 (defvar zmacs-regions) ; XEmacs regions
3819 ;; Emacs only
3820 (defvar mark-active)
3822 ;; Various packages
3823 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3824 (declare-function calendar-forward-day "cal-move" (arg))
3825 (declare-function calendar-goto-date "cal-move" (date))
3826 (declare-function calendar-goto-today "cal-move" ())
3827 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3828 (defvar calc-embedded-close-formula)
3829 (defvar calc-embedded-open-formula)
3830 (declare-function cdlatex-tab "ext:cdlatex" ())
3831 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3832 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3833 (defvar font-lock-unfontify-region-function)
3834 (declare-function iswitchb-read-buffer "iswitchb"
3835 (prompt &optional default require-match start matches-set))
3836 (defvar iswitchb-temp-buflist)
3837 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3838 (defvar org-agenda-tags-todo-honor-ignore-options)
3839 (declare-function org-agenda-skip "org-agenda" ())
3840 (declare-function
3841 org-agenda-format-item "org-agenda"
3842 (extra txt &optional category tags dotime noprefix remove-re habitp))
3843 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3844 (declare-function org-agenda-change-all-lines "org-agenda"
3845 (newhead hdmarker &optional fixface just-this))
3846 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3847 (declare-function org-agenda-maybe-redo "org-agenda" ())
3848 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3849 (beg end))
3850 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3851 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3852 "org-agenda" (&optional end))
3853 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3854 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3855 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3856 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3857 (declare-function org-indent-mode "org-indent" (&optional arg))
3858 (declare-function parse-time-string "parse-time" (string))
3859 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3860 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3861 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3862 (defvar remember-data-file)
3863 (defvar texmathp-why)
3864 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3865 (declare-function table--at-cell-p "table" (position &optional object at-column))
3867 (defvar w3m-current-url)
3868 (defvar w3m-current-title)
3870 (defvar org-latex-regexps)
3872 ;;; Autoload and prepare some org modules
3874 ;; Some table stuff that needs to be defined here, because it is used
3875 ;; by the functions setting up org-mode or checking for table context.
3877 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3878 "Detect an org-type or table-type table.")
3879 (defconst org-table-line-regexp "^[ \t]*|"
3880 "Detect an org-type table line.")
3881 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3882 "Detect an org-type table line.")
3883 (defconst org-table-hline-regexp "^[ \t]*|-"
3884 "Detect an org-type table hline.")
3885 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3886 "Detect a table-type table hline.")
3887 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3888 "Detect the first line outside a table when searching from within it.
3889 This works for both table types.")
3891 ;; Autoload the functions in org-table.el that are needed by functions here.
3893 (eval-and-compile
3894 (org-autoload "org-table"
3895 '(org-table-begin org-table-blank-field org-table-end)))
3897 ;;;###autoload
3898 (defun turn-on-orgtbl ()
3899 "Unconditionally turn on `orgtbl-mode'."
3900 (require 'org-table)
3901 (orgtbl-mode 1))
3903 (defun org-at-table-p (&optional table-type)
3904 "Return t if the cursor is inside an org-type table.
3905 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3906 (if org-enable-table-editor
3907 (save-excursion
3908 (beginning-of-line 1)
3909 (looking-at (if table-type org-table-any-line-regexp
3910 org-table-line-regexp)))
3911 nil))
3912 (defsubst org-table-p () (org-at-table-p))
3914 (defun org-at-table.el-p ()
3915 "Return t if and only if we are at a table.el table."
3916 (and (org-at-table-p 'any)
3917 (save-excursion
3918 (goto-char (org-table-begin 'any))
3919 (looking-at org-table1-hline-regexp))))
3920 (defun org-table-recognize-table.el ()
3921 "If there is a table.el table nearby, recognize it and move into it."
3922 (if org-table-tab-recognizes-table.el
3923 (if (org-at-table.el-p)
3924 (progn
3925 (beginning-of-line 1)
3926 (if (looking-at org-table-dataline-regexp)
3928 (if (looking-at org-table1-hline-regexp)
3929 (progn
3930 (beginning-of-line 2)
3931 (if (looking-at org-table-any-border-regexp)
3932 (beginning-of-line -1)))))
3933 (if (re-search-forward "|" (org-table-end t) t)
3934 (progn
3935 (require 'table)
3936 (if (table--at-cell-p (point))
3938 (message "recognizing table.el table...")
3939 (table-recognize-table)
3940 (message "recognizing table.el table...done")))
3941 (error "This should not happen"))
3943 nil)
3944 nil))
3946 (defun org-at-table-hline-p ()
3947 "Return t if the cursor is inside a hline in a table."
3948 (if org-enable-table-editor
3949 (save-excursion
3950 (beginning-of-line 1)
3951 (looking-at org-table-hline-regexp))
3952 nil))
3954 (defvar org-table-clean-did-remove-column nil)
3956 (defun org-table-map-tables (function &optional quietly)
3957 "Apply FUNCTION to the start of all tables in the buffer."
3958 (save-excursion
3959 (save-restriction
3960 (widen)
3961 (goto-char (point-min))
3962 (while (re-search-forward org-table-any-line-regexp nil t)
3963 (unless quietly
3964 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3965 (beginning-of-line 1)
3966 (when (and (looking-at org-table-line-regexp)
3967 ;; Exclude tables in src/example/verbatim/clocktable blocks
3968 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
3969 (save-excursion (funcall function))
3970 (or (looking-at org-table-line-regexp)
3971 (forward-char 1)))
3972 (re-search-forward org-table-any-border-regexp nil 1))))
3973 (unless quietly (message "Mapping tables: done")))
3975 ;; Declare and autoload functions from org-exp.el & Co
3977 (declare-function org-default-export-plist "org-exp")
3978 (declare-function org-infile-export-plist "org-exp")
3979 (declare-function org-get-current-options "org-exp")
3981 ;; Declare and autoload functions from org-agenda.el
3983 (eval-and-compile
3984 (org-autoload "org-agenda"
3985 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3987 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
3988 (declare-function org-clock-update-mode-line "org-clock" ())
3989 (declare-function org-resolve-clocks "org-clock"
3990 (&optional also-non-dangling-p prompt last-valid))
3991 (defvar org-clock-start-time)
3992 (defvar org-clock-marker (make-marker)
3993 "Marker recording the last clock-in.")
3994 (defvar org-clock-hd-marker (make-marker)
3995 "Marker recording the last clock-in, but the headline position.")
3996 (defvar org-clock-heading ""
3997 "The heading of the current clock entry.")
3998 (defun org-clock-is-active ()
3999 "Return non-nil if clock is currently running.
4000 The return value is actually the clock marker."
4001 (marker-buffer org-clock-marker))
4003 (eval-and-compile
4004 (org-autoload "org-clock" '(org-clock-remove-overlays
4005 org-clock-update-time-maybe
4006 org-clocktable-shift)))
4008 (defun org-check-running-clock ()
4009 "Check if the current buffer contains the running clock.
4010 If yes, offer to stop it and to save the buffer with the changes."
4011 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4012 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4013 (buffer-name))))
4014 (org-clock-out)
4015 (when (y-or-n-p "Save changed buffer?")
4016 (save-buffer))))
4018 (defun org-clocktable-try-shift (dir n)
4019 "Check if this line starts a clock table, if yes, shift the time block."
4020 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4021 (org-clocktable-shift dir n)))
4023 ;;;###autoload
4024 (defun org-clock-persistence-insinuate ()
4025 "Set up hooks for clock persistence."
4026 (require 'org-clock)
4027 (add-hook 'org-mode-hook 'org-clock-load)
4028 (add-hook 'kill-emacs-hook 'org-clock-save))
4030 ;; Define the variable already here, to make sure we have it.
4031 (defvar org-indent-mode nil
4032 "Non-nil if Org-Indent mode is enabled.
4033 Use the command `org-indent-mode' to change this variable.")
4035 ;; Autoload archiving code
4036 ;; The stuff that is needed for cycling and tags has to be defined here.
4038 (defgroup org-archive nil
4039 "Options concerning archiving in Org-mode."
4040 :tag "Org Archive"
4041 :group 'org-structure)
4043 (defcustom org-archive-location "%s_archive::"
4044 "The location where subtrees should be archived.
4046 The value of this variable is a string, consisting of two parts,
4047 separated by a double-colon. The first part is a filename and
4048 the second part is a headline.
4050 When the filename is omitted, archiving happens in the same file.
4051 %s in the filename will be replaced by the current file
4052 name (without the directory part). Archiving to a different file
4053 is useful to keep archived entries from contributing to the
4054 Org-mode Agenda.
4056 The archived entries will be filed as subtrees of the specified
4057 headline. When the headline is omitted, the subtrees are simply
4058 filed away at the end of the file, as top-level entries. Also in
4059 the heading you can use %s to represent the file name, this can be
4060 useful when using the same archive for a number of different files.
4062 Here are a few examples:
4063 \"%s_archive::\"
4064 If the current file is Projects.org, archive in file
4065 Projects.org_archive, as top-level trees. This is the default.
4067 \"::* Archived Tasks\"
4068 Archive in the current file, under the top-level headline
4069 \"* Archived Tasks\".
4071 \"~/org/archive.org::\"
4072 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4074 \"~/org/archive.org::* From %s\"
4075 Archive in file ~/org/archive.org (absolute path), under headlines
4076 \"From FILENAME\" where file name is the current file name.
4078 \"~/org/datetree.org::datetree/* Finished Tasks\"
4079 The \"datetree/\" string is special, signifying to archive
4080 items to the datetree. Items are placed in either the CLOSED
4081 date of the item, or the current date if there is no CLOSED date.
4082 The heading will be a subentry to the current date. There doesn't
4083 need to be a heading, but there always needs to be a slash after
4084 datetree. For example, to store archived items directly in the
4085 datetree, use \"~/org/datetree.org::datetree/\".
4087 \"basement::** Finished Tasks\"
4088 Archive in file ./basement (relative path), as level 3 trees
4089 below the level 2 heading \"** Finished Tasks\".
4091 You may set this option on a per-file basis by adding to the buffer a
4092 line like
4094 #+ARCHIVE: basement::** Finished Tasks
4096 You may also define it locally for a subtree by setting an ARCHIVE property
4097 in the entry. If such a property is found in an entry, or anywhere up
4098 the hierarchy, it will be used."
4099 :group 'org-archive
4100 :type 'string)
4102 (defcustom org-archive-tag "ARCHIVE"
4103 "The tag that marks a subtree as archived.
4104 An archived subtree does not open during visibility cycling, and does
4105 not contribute to the agenda listings.
4106 After changing this, font-lock must be restarted in the relevant buffers to
4107 get the proper fontification."
4108 :group 'org-archive
4109 :group 'org-keywords
4110 :type 'string)
4112 (defcustom org-agenda-skip-archived-trees t
4113 "Non-nil means the agenda will skip any items located in archived trees.
4114 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4115 variable is no longer recommended, you should leave it at the value t.
4116 Instead, use the key `v' to cycle the archives-mode in the agenda."
4117 :group 'org-archive
4118 :group 'org-agenda-skip
4119 :type 'boolean)
4121 (defcustom org-columns-skip-archived-trees t
4122 "Non-nil means ignore archived trees when creating column view."
4123 :group 'org-archive
4124 :group 'org-properties
4125 :type 'boolean)
4127 (defcustom org-cycle-open-archived-trees nil
4128 "Non-nil means `org-cycle' will open archived trees.
4129 An archived tree is a tree marked with the tag ARCHIVE.
4130 When nil, archived trees will stay folded. You can still open them with
4131 normal outline commands like `show-all', but not with the cycling commands."
4132 :group 'org-archive
4133 :group 'org-cycle
4134 :type 'boolean)
4136 (defcustom org-sparse-tree-open-archived-trees nil
4137 "Non-nil means sparse tree construction shows matches in archived trees.
4138 When nil, matches in these trees are highlighted, but the trees are kept in
4139 collapsed state."
4140 :group 'org-archive
4141 :group 'org-sparse-trees
4142 :type 'boolean)
4144 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4145 "The default date type when building a sparse tree.
4146 When this is nil, a date is a scheduled or a deadline timestamp.
4147 Otherwise, these types are allowed:
4149 all: all timestamps
4150 active: only active timestamps (<...>)
4151 inactive: only inactive timestamps (<...)
4152 scheduled: only scheduled timestamps
4153 deadline: only deadline timestamps"
4154 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4155 (const :tag "All timestamps" all)
4156 (const :tag "Only active timestamps" active)
4157 (const :tag "Only inactive timestamps" inactive)
4158 (const :tag "Only scheduled timestamps" scheduled)
4159 (const :tag "Only deadline timestamps" deadline))
4160 :version "24.3"
4161 :group 'org-sparse-trees)
4163 (defun org-cycle-hide-archived-subtrees (state)
4164 "Re-hide all archived subtrees after a visibility state change."
4165 (when (and (not org-cycle-open-archived-trees)
4166 (not (memq state '(overview folded))))
4167 (save-excursion
4168 (let* ((globalp (memq state '(contents all)))
4169 (beg (if globalp (point-min) (point)))
4170 (end (if globalp (point-max) (org-end-of-subtree t))))
4171 (org-hide-archived-subtrees beg end)
4172 (goto-char beg)
4173 (if (looking-at (concat ".*:" org-archive-tag ":"))
4174 (message "%s" (substitute-command-keys
4175 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4177 (defun org-force-cycle-archived ()
4178 "Cycle subtree even if it is archived."
4179 (interactive)
4180 (setq this-command 'org-cycle)
4181 (let ((org-cycle-open-archived-trees t))
4182 (call-interactively 'org-cycle)))
4184 (defun org-hide-archived-subtrees (beg end)
4185 "Re-hide all archived subtrees after a visibility state change."
4186 (save-excursion
4187 (let* ((re (concat ":" org-archive-tag ":")))
4188 (goto-char beg)
4189 (while (re-search-forward re end t)
4190 (when (org-at-heading-p)
4191 (org-flag-subtree t)
4192 (org-end-of-subtree t))))))
4194 (declare-function outline-end-of-heading "outline" ())
4195 (declare-function outline-flag-region "outline" (from to flag))
4196 (defun org-flag-subtree (flag)
4197 (save-excursion
4198 (org-back-to-heading t)
4199 (outline-end-of-heading)
4200 (outline-flag-region (point)
4201 (progn (org-end-of-subtree t) (point))
4202 flag)))
4204 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4206 (eval-and-compile
4207 (org-autoload "org-archive"
4208 '(org-add-archive-files)))
4210 ;; Autoload Column View Code
4212 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4213 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4214 (declare-function org-columns-compute "org-colview" (property))
4216 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4217 '(org-columns-number-to-string
4218 org-columns-get-format-and-top-level
4219 org-columns-compute
4220 org-columns-remove-overlays))
4222 ;; Autoload ID code
4224 (declare-function org-id-store-link "org-id")
4225 (declare-function org-id-locations-load "org-id")
4226 (declare-function org-id-locations-save "org-id")
4227 (defvar org-id-track-globally)
4228 (org-autoload "org-id"
4229 '(org-id-new
4230 org-id-copy
4231 org-id-get-with-outline-path-completion
4232 org-id-get-with-outline-drilling))
4234 ;;; Variables for pre-computed regular expressions, all buffer local
4236 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4237 "Matches first line of a hidden block.")
4238 (make-variable-buffer-local 'org-drawer-regexp)
4239 (defvar org-todo-regexp nil
4240 "Matches any of the TODO state keywords.")
4241 (make-variable-buffer-local 'org-todo-regexp)
4242 (defvar org-not-done-regexp nil
4243 "Matches any of the TODO state keywords except the last one.")
4244 (make-variable-buffer-local 'org-not-done-regexp)
4245 (defvar org-not-done-heading-regexp nil
4246 "Matches a TODO headline that is not done.")
4247 (make-variable-buffer-local 'org-not-done-regexp)
4248 (defvar org-todo-line-regexp nil
4249 "Matches a headline and puts TODO state into group 2 if present.")
4250 (make-variable-buffer-local 'org-todo-line-regexp)
4251 (defvar org-complex-heading-regexp nil
4252 "Matches a headline and puts everything into groups:
4253 group 1: the stars
4254 group 2: The todo keyword, maybe
4255 group 3: Priority cookie
4256 group 4: True headline
4257 group 5: Tags")
4258 (make-variable-buffer-local 'org-complex-heading-regexp)
4259 (defvar org-complex-heading-regexp-format nil
4260 "Printf format to make regexp to match an exact headline.
4261 This regexp will match the headline of any node which has the
4262 exact headline text that is put into the format, but may have any
4263 TODO state, priority and tags.")
4264 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4265 (defvar org-todo-line-tags-regexp nil
4266 "Matches a headline and puts TODO state into group 2 if present.
4267 Also put tags into group 4 if tags are present.")
4268 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4269 (defvar org-ds-keyword-length 12
4270 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4271 (make-variable-buffer-local 'org-ds-keyword-length)
4272 (defvar org-deadline-regexp nil
4273 "Matches the DEADLINE keyword.")
4274 (make-variable-buffer-local 'org-deadline-regexp)
4275 (defvar org-deadline-time-regexp nil
4276 "Matches the DEADLINE keyword together with a time stamp.")
4277 (make-variable-buffer-local 'org-deadline-time-regexp)
4278 (defvar org-deadline-line-regexp nil
4279 "Matches the DEADLINE keyword and the rest of the line.")
4280 (make-variable-buffer-local 'org-deadline-line-regexp)
4281 (defvar org-scheduled-regexp nil
4282 "Matches the SCHEDULED keyword.")
4283 (make-variable-buffer-local 'org-scheduled-regexp)
4284 (defvar org-scheduled-time-regexp nil
4285 "Matches the SCHEDULED keyword together with a time stamp.")
4286 (make-variable-buffer-local 'org-scheduled-time-regexp)
4287 (defvar org-closed-time-regexp nil
4288 "Matches the CLOSED keyword together with a time stamp.")
4289 (make-variable-buffer-local 'org-closed-time-regexp)
4291 (defvar org-keyword-time-regexp nil
4292 "Matches any of the 4 keywords, together with the time stamp.")
4293 (make-variable-buffer-local 'org-keyword-time-regexp)
4294 (defvar org-keyword-time-not-clock-regexp nil
4295 "Matches any of the 3 keywords, together with the time stamp.")
4296 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4297 (defvar org-maybe-keyword-time-regexp nil
4298 "Matches a timestamp, possibly preceded by a keyword.")
4299 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4300 (defvar org-all-time-keywords nil
4301 "List of time keywords.")
4302 (make-variable-buffer-local 'org-all-time-keywords)
4304 (defconst org-plain-time-of-day-regexp
4305 (concat
4306 "\\(\\<[012]?[0-9]"
4307 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4308 "\\(--?"
4309 "\\(\\<[012]?[0-9]"
4310 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4311 "\\)?")
4312 "Regular expression to match a plain time or time range.
4313 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4314 groups carry important information:
4315 0 the full match
4316 1 the first time, range or not
4317 8 the second time, if it is a range.")
4319 (defconst org-plain-time-extension-regexp
4320 (concat
4321 "\\(\\<[012]?[0-9]"
4322 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4323 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4324 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4325 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4326 groups carry important information:
4327 0 the full match
4328 7 hours of duration
4329 9 minutes of duration")
4331 (defconst org-stamp-time-of-day-regexp
4332 (concat
4333 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4334 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4335 "\\(--?"
4336 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4337 "Regular expression to match a timestamp time or time range.
4338 After a match, the following groups carry important information:
4339 0 the full match
4340 1 date plus weekday, for back referencing to make sure both times are on the same day
4341 2 the first time, range or not
4342 4 the second time, if it is a range.")
4344 (defconst org-startup-options
4345 '(("fold" org-startup-folded t)
4346 ("overview" org-startup-folded t)
4347 ("nofold" org-startup-folded nil)
4348 ("showall" org-startup-folded nil)
4349 ("showeverything" org-startup-folded showeverything)
4350 ("content" org-startup-folded content)
4351 ("indent" org-startup-indented t)
4352 ("noindent" org-startup-indented nil)
4353 ("hidestars" org-hide-leading-stars t)
4354 ("showstars" org-hide-leading-stars nil)
4355 ("odd" org-odd-levels-only t)
4356 ("oddeven" org-odd-levels-only nil)
4357 ("align" org-startup-align-all-tables t)
4358 ("noalign" org-startup-align-all-tables nil)
4359 ("inlineimages" org-startup-with-inline-images t)
4360 ("noinlineimages" org-startup-with-inline-images nil)
4361 ("customtime" org-display-custom-times t)
4362 ("logdone" org-log-done time)
4363 ("lognotedone" org-log-done note)
4364 ("nologdone" org-log-done nil)
4365 ("lognoteclock-out" org-log-note-clock-out t)
4366 ("nolognoteclock-out" org-log-note-clock-out nil)
4367 ("logrepeat" org-log-repeat state)
4368 ("lognoterepeat" org-log-repeat note)
4369 ("nologrepeat" org-log-repeat nil)
4370 ("logreschedule" org-log-reschedule time)
4371 ("lognotereschedule" org-log-reschedule note)
4372 ("nologreschedule" org-log-reschedule nil)
4373 ("logredeadline" org-log-redeadline time)
4374 ("lognoteredeadline" org-log-redeadline note)
4375 ("nologredeadline" org-log-redeadline nil)
4376 ("logrefile" org-log-refile time)
4377 ("lognoterefile" org-log-refile note)
4378 ("nologrefile" org-log-refile nil)
4379 ("fninline" org-footnote-define-inline t)
4380 ("nofninline" org-footnote-define-inline nil)
4381 ("fnlocal" org-footnote-section nil)
4382 ("fnauto" org-footnote-auto-label t)
4383 ("fnprompt" org-footnote-auto-label nil)
4384 ("fnconfirm" org-footnote-auto-label confirm)
4385 ("fnplain" org-footnote-auto-label plain)
4386 ("fnadjust" org-footnote-auto-adjust t)
4387 ("nofnadjust" org-footnote-auto-adjust nil)
4388 ("constcgs" constants-unit-system cgs)
4389 ("constSI" constants-unit-system SI)
4390 ("noptag" org-tag-persistent-alist nil)
4391 ("hideblocks" org-hide-block-startup t)
4392 ("nohideblocks" org-hide-block-startup nil)
4393 ("beamer" org-startup-with-beamer-mode t)
4394 ("entitiespretty" org-pretty-entities t)
4395 ("entitiesplain" org-pretty-entities nil))
4396 "Variable associated with STARTUP options for org-mode.
4397 Each element is a list of three items: the startup options (as written
4398 in the #+STARTUP line), the corresponding variable, and the value to set
4399 this variable to if the option is found. An optional forth element PUSH
4400 means to push this value onto the list in the variable.")
4402 (defun org-update-property-plist (key val props)
4403 "Update PROPS with KEY and VAL."
4404 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4405 (key (if appending (substring key 0 (- (length key) 1)) key))
4406 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4407 (previous (cdr (assoc key props))))
4408 (if appending
4409 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4410 (cons (cons key val) remainder))))
4412 (defconst org-block-regexp
4413 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4414 "Regular expression for hiding blocks.")
4415 (defconst org-heading-keyword-regexp-format
4416 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4417 "Printf format for a regexp matching an headline with some keyword.
4418 This regexp will match the headline of any node which has the
4419 exact keyword that is put into the format. The keyword isn't in
4420 any group by default, but the stars and the body are.")
4421 (defconst org-heading-keyword-maybe-regexp-format
4422 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4423 "Printf format for a regexp matching an headline, possibly with some keyword.
4424 This regexp can match any headline with the specified keyword, or
4425 without a keyword. The keyword isn't in any group by default,
4426 but the stars and the body are.")
4428 (defun org-set-regexps-and-options ()
4429 "Precompute regular expressions for current buffer."
4430 (when (derived-mode-p 'org-mode)
4431 (org-set-local 'org-todo-kwd-alist nil)
4432 (org-set-local 'org-todo-key-alist nil)
4433 (org-set-local 'org-todo-key-trigger nil)
4434 (org-set-local 'org-todo-keywords-1 nil)
4435 (org-set-local 'org-done-keywords nil)
4436 (org-set-local 'org-todo-heads nil)
4437 (org-set-local 'org-todo-sets nil)
4438 (org-set-local 'org-todo-log-states nil)
4439 (org-set-local 'org-file-properties nil)
4440 (org-set-local 'org-file-tags nil)
4441 (let ((re (org-make-options-regexp
4442 '("CATEGORY" "TODO" "COLUMNS"
4443 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4444 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4445 "OPTIONS")
4446 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4447 (splitre "[ \t]+")
4448 (scripts org-use-sub-superscripts)
4449 kwds kws0 kwsa key log value cat arch tags const links hw dws
4450 tail sep kws1 prio props ftags drawers beamer-p
4451 ext-setup-or-nil setup-contents (start 0))
4452 (save-excursion
4453 (save-restriction
4454 (widen)
4455 (goto-char (point-min))
4456 (while (or (and ext-setup-or-nil
4457 (string-match re ext-setup-or-nil start)
4458 (setq start (match-end 0)))
4459 (and (setq ext-setup-or-nil nil start 0)
4460 (re-search-forward re nil t)))
4461 (setq key (upcase (match-string 1 ext-setup-or-nil))
4462 value (org-match-string-no-properties 2 ext-setup-or-nil))
4463 (if (stringp value) (setq value (org-trim value)))
4464 (cond
4465 ((equal key "CATEGORY")
4466 (setq cat value))
4467 ((member key '("SEQ_TODO" "TODO"))
4468 (push (cons 'sequence (org-split-string value splitre)) kwds))
4469 ((equal key "TYP_TODO")
4470 (push (cons 'type (org-split-string value splitre)) kwds))
4471 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4472 ;; general TODO-like setup
4473 (push (cons (intern (downcase (match-string 1 key)))
4474 (org-split-string value splitre)) kwds))
4475 ((equal key "TAGS")
4476 (setq tags (append tags (if tags '("\\n") nil)
4477 (org-split-string value splitre))))
4478 ((equal key "COLUMNS")
4479 (org-set-local 'org-columns-default-format value))
4480 ((equal key "LINK")
4481 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4482 (push (cons (match-string 1 value)
4483 (org-trim (match-string 2 value)))
4484 links)))
4485 ((equal key "PRIORITIES")
4486 (setq prio (org-split-string value " +")))
4487 ((equal key "PROPERTY")
4488 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4489 (setq props (org-update-property-plist (match-string 1 value)
4490 (match-string 2 value)
4491 props))))
4492 ((equal key "FILETAGS")
4493 (when (string-match "\\S-" value)
4494 (setq ftags
4495 (append
4496 ftags
4497 (apply 'append
4498 (mapcar (lambda (x) (org-split-string x ":"))
4499 (org-split-string value)))))))
4500 ((equal key "DRAWERS")
4501 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4502 ((equal key "CONSTANTS")
4503 (setq const (append const (org-split-string value splitre))))
4504 ((equal key "STARTUP")
4505 (let ((opts (org-split-string value splitre))
4506 l var val)
4507 (while (setq l (pop opts))
4508 (when (setq l (assoc l org-startup-options))
4509 (setq var (nth 1 l) val (nth 2 l))
4510 (if (not (nth 3 l))
4511 (set (make-local-variable var) val)
4512 (if (not (listp (symbol-value var)))
4513 (set (make-local-variable var) nil))
4514 (set (make-local-variable var) (symbol-value var))
4515 (add-to-list var val))))))
4516 ((equal key "ARCHIVE")
4517 (setq arch value)
4518 (remove-text-properties 0 (length arch)
4519 '(face t fontified t) arch))
4520 ((equal key "LATEX_CLASS")
4521 (setq beamer-p (equal value "beamer")))
4522 ((equal key "OPTIONS")
4523 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4524 (setq scripts (read (match-string 2 value)))))
4525 ((equal key "SETUPFILE")
4526 (setq setup-contents (org-file-contents
4527 (expand-file-name
4528 (org-remove-double-quotes value))
4529 'noerror))
4530 (if (not ext-setup-or-nil)
4531 (setq ext-setup-or-nil setup-contents start 0)
4532 (setq ext-setup-or-nil
4533 (concat (substring ext-setup-or-nil 0 start)
4534 "\n" setup-contents "\n"
4535 (substring ext-setup-or-nil start)))))))
4536 ;; search for property blocks
4537 (goto-char (point-min))
4538 (while (re-search-forward org-block-regexp nil t)
4539 (when (equal "PROPERTY" (upcase (match-string 1)))
4540 (setq value (replace-regexp-in-string
4541 "[\n\r]" " " (match-string 4)))
4542 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4543 (setq props (org-update-property-plist (match-string 1 value)
4544 (match-string 2 value)
4545 props)))))))
4546 (org-set-local 'org-use-sub-superscripts scripts)
4547 (when cat
4548 (org-set-local 'org-category (intern cat))
4549 (push (cons "CATEGORY" cat) props))
4550 (when prio
4551 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4552 (setq prio (mapcar 'string-to-char prio))
4553 (org-set-local 'org-highest-priority (nth 0 prio))
4554 (org-set-local 'org-lowest-priority (nth 1 prio))
4555 (org-set-local 'org-default-priority (nth 2 prio)))
4556 (and props (org-set-local 'org-file-properties (nreverse props)))
4557 (and ftags (org-set-local 'org-file-tags
4558 (mapcar 'org-add-prop-inherited ftags)))
4559 (and drawers (org-set-local 'org-drawers drawers))
4560 (and arch (org-set-local 'org-archive-location arch))
4561 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4562 ;; Process the TODO keywords
4563 (unless kwds
4564 ;; Use the global values as if they had been given locally.
4565 (setq kwds (default-value 'org-todo-keywords))
4566 (if (stringp (car kwds))
4567 (setq kwds (list (cons org-todo-interpretation
4568 (default-value 'org-todo-keywords)))))
4569 (setq kwds (reverse kwds)))
4570 (setq kwds (nreverse kwds))
4571 (let (inter kws kw)
4572 (while (setq kws (pop kwds))
4573 (let ((kws (or
4574 (run-hook-with-args-until-success
4575 'org-todo-setup-filter-hook kws)
4576 kws)))
4577 (setq inter (pop kws) sep (member "|" kws)
4578 kws0 (delete "|" (copy-sequence kws))
4579 kwsa nil
4580 kws1 (mapcar
4581 (lambda (x)
4582 ;; 1 2
4583 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4584 (progn
4585 (setq kw (match-string 1 x)
4586 key (and (match-end 2) (match-string 2 x))
4587 log (org-extract-log-state-settings x))
4588 (push (cons kw (and key (string-to-char key))) kwsa)
4589 (and log (push log org-todo-log-states))
4591 (error "Invalid TODO keyword %s" x)))
4592 kws0)
4593 kwsa (if kwsa (append '((:startgroup))
4594 (nreverse kwsa)
4595 '((:endgroup))))
4596 hw (car kws1)
4597 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4598 tail (list inter hw (car dws) (org-last dws))))
4599 (add-to-list 'org-todo-heads hw 'append)
4600 (push kws1 org-todo-sets)
4601 (setq org-done-keywords (append org-done-keywords dws nil))
4602 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4603 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4604 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4605 (setq org-todo-sets (nreverse org-todo-sets)
4606 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4607 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4608 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4609 ;; Process the constants
4610 (when const
4611 (let (e cst)
4612 (while (setq e (pop const))
4613 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4614 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4615 (setq org-table-formula-constants-local cst)))
4617 ;; Process the tags.
4618 (when tags
4619 (let (e tgs)
4620 (while (setq e (pop tags))
4621 (cond
4622 ((equal e "{") (push '(:startgroup) tgs))
4623 ((equal e "}") (push '(:endgroup) tgs))
4624 ((equal e "\\n") (push '(:newline) tgs))
4625 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4626 (push (cons (match-string 1 e)
4627 (string-to-char (match-string 2 e)))
4628 tgs))
4629 (t (push (list e) tgs))))
4630 (org-set-local 'org-tag-alist nil)
4631 (while (setq e (pop tgs))
4632 (or (and (stringp (car e))
4633 (assoc (car e) org-tag-alist))
4634 (push e org-tag-alist)))))
4636 ;; Compute the regular expressions and other local variables.
4637 ;; Using `org-outline-regexp-bol' would complicate them much,
4638 ;; because of the fixed white space at the end of that string.
4639 (if (not org-done-keywords)
4640 (setq org-done-keywords (and org-todo-keywords-1
4641 (list (org-last org-todo-keywords-1)))))
4642 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4643 (length org-scheduled-string)
4644 (length org-clock-string)
4645 (length org-closed-string)))
4646 org-drawer-regexp
4647 (concat "^[ \t]*:\\("
4648 (mapconcat 'regexp-quote org-drawers "\\|")
4649 "\\):[ \t]*$")
4650 org-not-done-keywords
4651 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4652 org-todo-regexp
4653 (concat "\\("
4654 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4655 "\\)")
4656 org-not-done-regexp
4657 (concat "\\("
4658 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4659 "\\)")
4660 org-not-done-heading-regexp
4661 (format org-heading-keyword-regexp-format org-not-done-regexp)
4662 org-todo-line-regexp
4663 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4664 org-complex-heading-regexp
4665 (concat "^\\(\\*+\\)"
4666 "\\(?: +" org-todo-regexp "\\)?"
4667 "\\(?: +\\(\\[#.\\]\\)\\)?"
4668 "\\(?: +\\(.*?\\)\\)??"
4669 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4670 "[ \t]*$")
4671 org-complex-heading-regexp-format
4672 (concat "^\\(\\*+\\)"
4673 "\\(?: +" org-todo-regexp "\\)?"
4674 "\\(?: +\\(\\[#.\\]\\)\\)?"
4675 "\\(?: +"
4676 ;; Stats cookies can be stuck to body.
4677 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4678 "\\(%s\\)"
4679 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4680 "\\)"
4681 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4682 "[ \t]*$")
4683 org-todo-line-tags-regexp
4684 (concat "^\\(\\*+\\)"
4685 "\\(?: +" org-todo-regexp "\\)?"
4686 "\\(?: +\\(.*?\\)\\)??"
4687 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4688 "[ \t]*$")
4689 org-deadline-regexp (concat "\\<" org-deadline-string)
4690 org-deadline-time-regexp
4691 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4692 org-deadline-line-regexp
4693 (concat "\\<\\(" org-deadline-string "\\).*")
4694 org-scheduled-regexp
4695 (concat "\\<" org-scheduled-string)
4696 org-scheduled-time-regexp
4697 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4698 org-closed-time-regexp
4699 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4700 org-keyword-time-regexp
4701 (concat "\\<\\(" org-scheduled-string
4702 "\\|" org-deadline-string
4703 "\\|" org-closed-string
4704 "\\|" org-clock-string "\\)"
4705 " *[[<]\\([^]>]+\\)[]>]")
4706 org-keyword-time-not-clock-regexp
4707 (concat "\\<\\(" org-scheduled-string
4708 "\\|" org-deadline-string
4709 "\\|" org-closed-string
4710 "\\)"
4711 " *[[<]\\([^]>]+\\)[]>]")
4712 org-maybe-keyword-time-regexp
4713 (concat "\\(\\<\\(" org-scheduled-string
4714 "\\|" org-deadline-string
4715 "\\|" org-closed-string
4716 "\\|" org-clock-string "\\)\\)?"
4717 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4718 org-all-time-keywords
4719 (mapcar (lambda (w) (substring w 0 -1))
4720 (list org-scheduled-string org-deadline-string
4721 org-clock-string org-closed-string))
4723 (org-compute-latex-and-specials-regexp)
4724 (org-set-font-lock-defaults))))
4726 (defun org-file-contents (file &optional noerror)
4727 "Return the contents of FILE, as a string."
4728 (if (or (not file)
4729 (not (file-readable-p file)))
4730 (if noerror
4731 (progn
4732 (message "Cannot read file \"%s\"" file)
4733 (ding) (sit-for 2)
4735 (error "Cannot read file \"%s\"" file))
4736 (with-temp-buffer
4737 (insert-file-contents file)
4738 (buffer-string))))
4740 (defun org-extract-log-state-settings (x)
4741 "Extract the log state setting from a TODO keyword string.
4742 This will extract info from a string like \"WAIT(w@/!)\"."
4743 (let (kw key log1 log2)
4744 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4745 (setq kw (match-string 1 x)
4746 key (and (match-end 2) (match-string 2 x))
4747 log1 (and (match-end 3) (match-string 3 x))
4748 log2 (and (match-end 4) (match-string 4 x)))
4749 (and (or log1 log2)
4750 (list kw
4751 (and log1 (if (equal log1 "!") 'time 'note))
4752 (and log2 (if (equal log2 "!") 'time 'note)))))))
4754 (defun org-remove-keyword-keys (list)
4755 "Remove a pair of parenthesis at the end of each string in LIST."
4756 (mapcar (lambda (x)
4757 (if (string-match "(.*)$" x)
4758 (substring x 0 (match-beginning 0))
4760 list))
4762 (defun org-assign-fast-keys (alist)
4763 "Assign fast keys to a keyword-key alist.
4764 Respect keys that are already there."
4765 (let (new e (alt ?0))
4766 (while (setq e (pop alist))
4767 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4768 (cdr e)) ;; Key already assigned.
4769 (push e new)
4770 (let ((clist (string-to-list (downcase (car e))))
4771 (used (append new alist)))
4772 (when (= (car clist) ?@)
4773 (pop clist))
4774 (while (and clist (rassoc (car clist) used))
4775 (pop clist))
4776 (unless clist
4777 (while (rassoc alt used)
4778 (incf alt)))
4779 (push (cons (car e) (or (car clist) alt)) new))))
4780 (nreverse new)))
4782 ;;; Some variables used in various places
4784 (defvar org-window-configuration nil
4785 "Used in various places to store a window configuration.")
4786 (defvar org-selected-window nil
4787 "Used in various places to store a window configuration.")
4788 (defvar org-finish-function nil
4789 "Function to be called when `C-c C-c' is used.
4790 This is for getting out of special buffers like capture.")
4793 ;; FIXME: Occasionally check by commenting these, to make sure
4794 ;; no other functions uses these, forgetting to let-bind them.
4795 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4796 (defvar org-last-state)
4797 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4799 ;; Defined somewhere in this file, but used before definition.
4800 (defvar org-entities) ;; defined in org-entities.el
4801 (defvar org-struct-menu)
4802 (defvar org-org-menu)
4803 (defvar org-tbl-menu)
4805 ;;;; Define the Org-mode
4807 ;; We use a before-change function to check if a table might need
4808 ;; an update.
4809 (defvar org-table-may-need-update t
4810 "Indicates that a table might need an update.
4811 This variable is set by `org-before-change-function'.
4812 `org-table-align' sets it back to nil.")
4813 (defun org-before-change-function (beg end)
4814 "Every change indicates that a table might need an update."
4815 (setq org-table-may-need-update t))
4816 (defvar org-mode-map)
4817 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4818 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4819 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4820 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4821 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4822 (defvar org-table-buffer-is-an nil)
4824 (defvar bidi-paragraph-direction)
4825 (defvar buffer-face-mode-face)
4827 (require 'outline)
4828 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4829 (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"))
4830 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4832 ;; Other stuff we need.
4833 (require 'time-date)
4834 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4835 (require 'easymenu)
4836 (require 'overlay)
4838 (require 'org-macs)
4839 (require 'org-entities)
4840 ;; (require 'org-compat) moved higher up in the file before it is first used
4841 (require 'org-faces)
4842 (require 'org-list)
4843 (require 'org-pcomplete)
4844 (require 'org-src)
4845 (require 'org-footnote)
4847 ;; babel
4848 (require 'ob)
4849 (require 'ob-table)
4850 (require 'ob-lob)
4851 (require 'ob-ref)
4852 (require 'ob-tangle)
4853 (require 'ob-comint)
4854 (require 'ob-keys)
4856 ;;;###autoload
4857 (define-derived-mode org-mode outline-mode "Org"
4858 "Outline-based notes management and organizer, alias
4859 \"Carsten's outline-mode for keeping track of everything.\"
4861 Org-mode develops organizational tasks around a NOTES file which
4862 contains information about projects as plain text. Org-mode is
4863 implemented on top of outline-mode, which is ideal to keep the content
4864 of large files well structured. It supports ToDo items, deadlines and
4865 time stamps, which magically appear in the diary listing of the Emacs
4866 calendar. Tables are easily created with a built-in table editor.
4867 Plain text URL-like links connect to websites, emails (VM), Usenet
4868 messages (Gnus), BBDB entries, and any files related to the project.
4869 For printing and sharing of notes, an Org-mode file (or a part of it)
4870 can be exported as a structured ASCII or HTML file.
4872 The following commands are available:
4874 \\{org-mode-map}"
4876 ;; Get rid of Outline menus, they are not needed
4877 ;; Need to do this here because define-derived-mode sets up
4878 ;; the keymap so late. Still, it is a waste to call this each time
4879 ;; we switch another buffer into org-mode.
4880 (if (featurep 'xemacs)
4881 (when (boundp 'outline-mode-menu-heading)
4882 ;; Assume this is Greg's port, it uses easymenu
4883 (easy-menu-remove outline-mode-menu-heading)
4884 (easy-menu-remove outline-mode-menu-show)
4885 (easy-menu-remove outline-mode-menu-hide))
4886 (define-key org-mode-map [menu-bar headings] 'undefined)
4887 (define-key org-mode-map [menu-bar hide] 'undefined)
4888 (define-key org-mode-map [menu-bar show] 'undefined))
4890 (org-load-modules-maybe)
4891 (easy-menu-add org-org-menu)
4892 (easy-menu-add org-tbl-menu)
4893 (org-install-agenda-files-menu)
4894 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4895 (add-to-invisibility-spec '(org-cwidth))
4896 (add-to-invisibility-spec '(org-hide-block . t))
4897 (when (featurep 'xemacs)
4898 (org-set-local 'line-move-ignore-invisible t))
4899 (org-set-local 'outline-regexp org-outline-regexp)
4900 (org-set-local 'outline-level 'org-outline-level)
4901 (setq bidi-paragraph-direction 'left-to-right)
4902 (when (and org-ellipsis
4903 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4904 (fboundp 'make-glyph-code))
4905 (unless org-display-table
4906 (setq org-display-table (make-display-table)))
4907 (set-display-table-slot
4908 org-display-table 4
4909 (vconcat (mapcar
4910 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4911 org-ellipsis)))
4912 (if (stringp org-ellipsis) org-ellipsis "..."))))
4913 (setq buffer-display-table org-display-table))
4914 (org-set-regexps-and-options)
4915 (when (and org-tag-faces (not org-tags-special-faces-re))
4916 ;; tag faces set outside customize.... force initialization.
4917 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4918 ;; Calc embedded
4919 (org-set-local 'calc-embedded-open-mode "# ")
4920 (modify-syntax-entry ?@ "w")
4921 (if org-startup-truncated (setq truncate-lines t))
4922 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
4923 (org-set-local 'font-lock-unfontify-region-function
4924 'org-unfontify-region)
4925 ;; Activate before-change-function
4926 (org-set-local 'org-table-may-need-update t)
4927 (org-add-hook 'before-change-functions 'org-before-change-function nil
4928 'local)
4929 ;; Check for running clock before killing a buffer
4930 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4931 ;; Indentation.
4932 (org-set-local 'indent-line-function 'org-indent-line)
4933 (org-set-local 'indent-region-function 'org-indent-region)
4934 ;; Initialize radio targets.
4935 (org-update-radio-target-regexp)
4936 ;; Filling and auto-filling.
4937 (org-setup-filling)
4938 ;; Comments.
4939 (org-setup-comments-handling)
4940 ;; Beginning/end of defun
4941 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
4942 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
4943 ;; Next error for sparse trees
4944 (org-set-local 'next-error-function 'org-occur-next-match)
4945 ;; Make sure dependence stuff works reliably, even for users who set it
4946 ;; too late :-(
4947 (if org-enforce-todo-dependencies
4948 (add-hook 'org-blocker-hook
4949 'org-block-todo-from-children-or-siblings-or-parent)
4950 (remove-hook 'org-blocker-hook
4951 'org-block-todo-from-children-or-siblings-or-parent))
4952 (if org-enforce-todo-checkbox-dependencies
4953 (add-hook 'org-blocker-hook
4954 'org-block-todo-from-checkboxes)
4955 (remove-hook 'org-blocker-hook
4956 'org-block-todo-from-checkboxes))
4958 ;; Align options lines
4959 (org-set-local
4960 'align-mode-rules-list
4961 '((org-in-buffer-settings
4962 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4963 (modes . '(org-mode)))))
4965 ;; Imenu
4966 (org-set-local 'imenu-create-index-function
4967 'org-imenu-get-tree)
4969 ;; Make isearch reveal context
4970 (if (or (featurep 'xemacs)
4971 (not (boundp 'outline-isearch-open-invisible-function)))
4972 ;; Emacs 21 and XEmacs make use of the hook
4973 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4974 ;; Emacs 22 deals with this through a special variable
4975 (org-set-local 'outline-isearch-open-invisible-function
4976 (lambda (&rest ignore) (org-show-context 'isearch))))
4978 ;; Setup the pcomplete hooks
4979 (set (make-local-variable 'pcomplete-command-completion-function)
4980 'org-pcomplete-initial)
4981 (set (make-local-variable 'pcomplete-command-name-function)
4982 'org-command-at-point)
4983 (set (make-local-variable 'pcomplete-default-completion-function)
4984 'ignore)
4985 (set (make-local-variable 'pcomplete-parse-arguments-function)
4986 'org-parse-arguments)
4987 (set (make-local-variable 'pcomplete-termination-string) "")
4988 (when (>= emacs-major-version 23)
4989 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
4991 ;; If empty file that did not turn on org-mode automatically, make it to.
4992 (if (and org-insert-mode-line-in-empty-file
4993 (org-called-interactively-p 'any)
4994 (= (point-min) (point-max)))
4995 (insert "# -*- mode: org -*-\n\n"))
4996 (unless org-inhibit-startup
4997 (and org-startup-with-beamer-mode (org-beamer-mode))
4998 (when org-startup-align-all-tables
4999 (let ((bmp (buffer-modified-p)))
5000 (org-table-map-tables 'org-table-align 'quietly)
5001 (set-buffer-modified-p bmp)))
5002 (when org-startup-with-inline-images
5003 (org-display-inline-images))
5004 (unless org-inhibit-startup-visibility-stuff
5005 (org-set-startup-visibility)))
5006 ;; Try to set org-hide correctly
5007 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5009 (when (fboundp 'abbrev-table-put)
5010 (abbrev-table-put org-mode-abbrev-table
5011 :parents (list text-mode-abbrev-table)))
5013 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5016 (defun org-find-invisible-foreground ()
5017 (let ((candidates (remove
5018 "unspecified-bg"
5019 (nconc
5020 (list (face-background 'default)
5021 (face-background 'org-default))
5022 (mapcar
5023 (lambda (alist)
5024 (when (boundp alist)
5025 (cdr (assoc 'background-color (symbol-value alist)))))
5026 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5027 (list (face-foreground 'org-hide))))))
5028 (car (remove nil candidates))))
5030 (defun org-current-time ()
5031 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5032 (if (> (car org-time-stamp-rounding-minutes) 1)
5033 (let ((r (car org-time-stamp-rounding-minutes))
5034 (time (decode-time)))
5035 (apply 'encode-time
5036 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5037 (nthcdr 2 time))))
5038 (current-time)))
5040 (defun org-today ()
5041 "Return today date, considering `org-extend-today-until'."
5042 (time-to-days
5043 (time-subtract (current-time)
5044 (list 0 (* 3600 org-extend-today-until) 0))))
5046 ;;;; Font-Lock stuff, including the activators
5048 (defvar org-mouse-map (make-sparse-keymap))
5049 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5050 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5051 (when org-mouse-1-follows-link
5052 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5053 (when org-tab-follows-link
5054 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5055 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5057 (require 'font-lock)
5059 (defconst org-non-link-chars "]\t\n\r<>")
5060 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5061 "shell" "elisp" "doi" "message"))
5062 (defvar org-link-types-re nil
5063 "Matches a link that has a url-like prefix like \"http:\"")
5064 (defvar org-link-re-with-space nil
5065 "Matches a link with spaces, optional angular brackets around it.")
5066 (defvar org-link-re-with-space2 nil
5067 "Matches a link with spaces, optional angular brackets around it.")
5068 (defvar org-link-re-with-space3 nil
5069 "Matches a link with spaces, only for internal part in bracket links.")
5070 (defvar org-angle-link-re nil
5071 "Matches link with angular brackets, spaces are allowed.")
5072 (defvar org-plain-link-re nil
5073 "Matches plain link, without spaces.")
5074 (defvar org-bracket-link-regexp nil
5075 "Matches a link in double brackets.")
5076 (defvar org-bracket-link-analytic-regexp nil
5077 "Regular expression used to analyze links.
5078 Here is what the match groups contain after a match:
5079 1: http:
5080 2: http
5081 3: path
5082 4: [desc]
5083 5: desc")
5084 (defvar org-bracket-link-analytic-regexp++ nil
5085 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5086 (defvar org-any-link-re nil
5087 "Regular expression matching any link.")
5089 (defcustom org-match-sexp-depth 3
5090 "Number of stacked braces for sub/superscript matching.
5091 This has to be set before loading org.el to be effective."
5092 :group 'org-export-translation ; ??????????????????????????/
5093 :type 'integer)
5095 (defun org-create-multibrace-regexp (left right n)
5096 "Create a regular expression which will match a balanced sexp.
5097 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5098 as single character strings.
5099 The regexp returned will match the entire expression including the
5100 delimiters. It will also define a single group which contains the
5101 match except for the outermost delimiters. The maximum depth of
5102 stacked delimiters is N. Escaping delimiters is not possible."
5103 (let* ((nothing (concat "[^" left right "]*?"))
5104 (or "\\|")
5105 (re nothing)
5106 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5107 (while (> n 1)
5108 (setq n (1- n)
5109 re (concat re or next)
5110 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5111 (concat left "\\(" re "\\)" right)))
5113 (defvar org-match-substring-regexp
5114 (concat
5115 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5116 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5117 "\\|"
5118 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5119 "\\|"
5120 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5121 "The regular expression matching a sub- or superscript.")
5123 (defvar org-match-substring-with-braces-regexp
5124 (concat
5125 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5126 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5127 "\\)")
5128 "The regular expression matching a sub- or superscript, forcing braces.")
5130 (defun org-make-link-regexps ()
5131 "Update the link regular expressions.
5132 This should be called after the variable `org-link-types' has changed."
5133 (setq org-link-types-re
5134 (concat
5135 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5136 org-link-re-with-space
5137 (concat
5138 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5139 "\\([^" org-non-link-chars " ]"
5140 "[^" org-non-link-chars "]*"
5141 "[^" org-non-link-chars " ]\\)>?")
5142 org-link-re-with-space2
5143 (concat
5144 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5145 "\\([^" org-non-link-chars " ]"
5146 "[^\t\n\r]*"
5147 "[^" org-non-link-chars " ]\\)>?")
5148 org-link-re-with-space3
5149 (concat
5150 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5151 "\\([^" org-non-link-chars " ]"
5152 "[^\t\n\r]*\\)")
5153 org-angle-link-re
5154 (concat
5155 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5156 "\\([^" org-non-link-chars " ]"
5157 "[^" org-non-link-chars "]*"
5158 "\\)>")
5159 org-plain-link-re
5160 (concat
5161 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5162 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5163 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5164 org-bracket-link-regexp
5165 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5166 org-bracket-link-analytic-regexp
5167 (concat
5168 "\\[\\["
5169 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5170 "\\([^]]+\\)"
5171 "\\]"
5172 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5173 "\\]")
5174 org-bracket-link-analytic-regexp++
5175 (concat
5176 "\\[\\["
5177 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5178 "\\([^]]+\\)"
5179 "\\]"
5180 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5181 "\\]")
5182 org-any-link-re
5183 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5184 org-angle-link-re "\\)\\|\\("
5185 org-plain-link-re "\\)")))
5187 (org-make-link-regexps)
5189 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5190 "Regular expression for fast time stamp matching.")
5191 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5192 "Regular expression for fast time stamp matching.")
5193 (defconst org-ts-regexp0
5194 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5195 "Regular expression matching time strings for analysis.
5196 This one does not require the space after the date, so it can be used
5197 on a string that terminates immediately after the date.")
5198 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5199 "Regular expression matching time strings for analysis.")
5200 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5201 "Regular expression matching time stamps, with groups.")
5202 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5203 "Regular expression matching time stamps (also [..]), with groups.")
5204 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5205 "Regular expression matching a time stamp range.")
5206 (defconst org-tr-regexp-both
5207 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5208 "Regular expression matching a time stamp range.")
5209 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5210 org-ts-regexp "\\)?")
5211 "Regular expression matching a time stamp or time stamp range.")
5212 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5213 org-ts-regexp-both "\\)?")
5214 "Regular expression matching a time stamp or time stamp range.
5215 The time stamps may be either active or inactive.")
5217 (defvar org-emph-face nil)
5219 (defun org-do-emphasis-faces (limit)
5220 "Run through the buffer and add overlays to emphasized strings."
5221 (let (rtn a)
5222 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5223 (if (not (= (char-after (match-beginning 3))
5224 (char-after (match-beginning 4))))
5225 (progn
5226 (setq rtn t)
5227 (setq a (assoc (match-string 3) org-emphasis-alist))
5228 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5229 'face
5230 (nth 1 a))
5231 (and (nth 4 a)
5232 (org-remove-flyspell-overlays-in
5233 (match-beginning 0) (match-end 0)))
5234 (add-text-properties (match-beginning 2) (match-end 2)
5235 '(font-lock-multiline t org-emphasis t))
5236 (when org-hide-emphasis-markers
5237 (add-text-properties (match-end 4) (match-beginning 5)
5238 '(invisible org-link))
5239 (add-text-properties (match-beginning 3) (match-end 3)
5240 '(invisible org-link)))))
5241 (backward-char 1))
5242 rtn))
5244 (defun org-emphasize (&optional char)
5245 "Insert or change an emphasis, i.e. a font like bold or italic.
5246 If there is an active region, change that region to a new emphasis.
5247 If there is no region, just insert the marker characters and position
5248 the cursor between them.
5249 CHAR should be either the marker character, or the first character of the
5250 HTML tag associated with that emphasis. If CHAR is a space, the means
5251 to remove the emphasis of the selected region.
5252 If char is not given (for example in an interactive call) it
5253 will be prompted for."
5254 (interactive)
5255 (let ((eal org-emphasis-alist) e det
5256 (erc org-emphasis-regexp-components)
5257 (prompt "")
5258 (string "") beg end move tag c s)
5259 (if (org-region-active-p)
5260 (setq beg (region-beginning) end (region-end)
5261 string (buffer-substring beg end))
5262 (setq move t))
5264 (while (setq e (pop eal))
5265 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5266 c (aref tag 0))
5267 (push (cons c (string-to-char (car e))) det)
5268 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5269 (substring tag 1)))))
5270 (setq det (nreverse det))
5271 (unless char
5272 (message "%s" (concat "Emphasis marker or tag:" prompt))
5273 (setq char (read-char-exclusive)))
5274 (setq char (or (cdr (assoc char det)) char))
5275 (if (equal char ?\ )
5276 (setq s "" move nil)
5277 (unless (assoc (char-to-string char) org-emphasis-alist)
5278 (error "No such emphasis marker: \"%c\"" char))
5279 (setq s (char-to-string char)))
5280 (while (and (> (length string) 1)
5281 (equal (substring string 0 1) (substring string -1))
5282 (assoc (substring string 0 1) org-emphasis-alist))
5283 (setq string (substring string 1 -1)))
5284 (setq string (concat s string s))
5285 (if beg (delete-region beg end))
5286 (unless (or (bolp)
5287 (string-match (concat "[" (nth 0 erc) "\n]")
5288 (char-to-string (char-before (point)))))
5289 (insert " "))
5290 (unless (or (eobp)
5291 (string-match (concat "[" (nth 1 erc) "\n]")
5292 (char-to-string (char-after (point)))))
5293 (insert " ") (backward-char 1))
5294 (insert string)
5295 (and move (backward-char 1))))
5297 (defconst org-nonsticky-props
5298 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5300 (defsubst org-rear-nonsticky-at (pos)
5301 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5303 (defun org-activate-plain-links (limit)
5304 "Run through the buffer and add overlays to links."
5305 (catch 'exit
5306 (let (f)
5307 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5308 (not (org-in-src-block-p)))
5309 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5310 (setq f (get-text-property (match-beginning 0) 'face))
5311 (unless (or (org-in-src-block-p)
5312 (eq f 'org-tag)
5313 (and (listp f) (memq 'org-tag f)))
5314 (add-text-properties (match-beginning 0) (match-end 0)
5315 (list 'mouse-face 'highlight
5316 'face 'org-link
5317 'keymap org-mouse-map))
5318 (org-rear-nonsticky-at (match-end 0)))
5319 t))))
5321 (defun org-activate-code (limit)
5322 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5323 (progn
5324 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5325 (remove-text-properties (match-beginning 0) (match-end 0)
5326 '(display t invisible t intangible t))
5327 t)))
5329 (defcustom org-src-fontify-natively nil
5330 "When non-nil, fontify code in code blocks."
5331 :type 'boolean
5332 :version "24.1"
5333 :group 'org-appearance
5334 :group 'org-babel)
5336 (defcustom org-allow-promoting-top-level-subtree nil
5337 "When non-nil, allow promoting a top level subtree.
5338 The leading star of the top level headline will be replaced
5339 by a #."
5340 :type 'boolean
5341 :version "24.1"
5342 :group 'org-appearance)
5344 (defun org-fontify-meta-lines-and-blocks (limit)
5345 (condition-case nil
5346 (org-fontify-meta-lines-and-blocks-1 limit)
5347 (error (message "org-mode fontification error"))))
5349 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5350 "Fontify #+ lines and blocks, in the correct ways."
5351 (let ((case-fold-search t))
5352 (if (re-search-forward
5353 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5354 limit t)
5355 (let ((beg (match-beginning 0))
5356 (block-start (match-end 0))
5357 (block-end nil)
5358 (lang (match-string 7))
5359 (beg1 (line-beginning-position 2))
5360 (dc1 (downcase (match-string 2)))
5361 (dc3 (downcase (match-string 3)))
5362 end end1 quoting block-type ovl)
5363 (cond
5364 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5365 ;; a single line of backend-specific content
5366 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5367 (remove-text-properties (match-beginning 0) (match-end 0)
5368 '(display t invisible t intangible t))
5369 (add-text-properties (match-beginning 1) (match-end 3)
5370 '(font-lock-fontified t face org-meta-line))
5371 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5372 '(font-lock-fontified t face org-block))
5373 ; for backend-specific code
5375 ((and (match-end 4) (equal dc3 "+begin"))
5376 ;; Truly a block
5377 (setq block-type (downcase (match-string 5))
5378 quoting (member block-type org-protecting-blocks))
5379 (when (re-search-forward
5380 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5381 nil t) ;; on purpose, we look further than LIMIT
5382 (setq end (min (point-max) (match-end 0))
5383 end1 (min (point-max) (1- (match-beginning 0))))
5384 (setq block-end (match-beginning 0))
5385 (when quoting
5386 (remove-text-properties beg end
5387 '(display t invisible t intangible t)))
5388 (add-text-properties
5389 beg end
5390 '(font-lock-fontified t font-lock-multiline t))
5391 (add-text-properties beg beg1 '(face org-meta-line))
5392 (add-text-properties end1 (min (point-max) (1+ end))
5393 '(face org-meta-line)) ; for end_src
5394 (cond
5395 ((and lang (not (string= lang "")) org-src-fontify-natively)
5396 (org-src-font-lock-fontify-block lang block-start block-end)
5397 ;; remove old background overlays
5398 (mapc (lambda (ov)
5399 (if (eq (overlay-get ov 'face) 'org-block-background)
5400 (delete-overlay ov)))
5401 (overlays-at (/ (+ beg1 block-end) 2)))
5402 ;; add a background overlay
5403 (setq ovl (make-overlay beg1 block-end))
5404 (overlay-put ovl 'face 'org-block-background)
5405 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5406 (quoting
5407 (add-text-properties beg1 (min (point-max) (1+ end1))
5408 '(face org-block))) ; end of source block
5409 ((not org-fontify-quote-and-verse-blocks))
5410 ((string= block-type "quote")
5411 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5412 ((string= block-type "verse")
5413 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5414 (add-text-properties beg beg1 '(face org-block-begin-line))
5415 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5416 '(face org-block-end-line))
5418 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5419 (add-text-properties
5420 beg (match-end 3)
5421 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5422 '(font-lock-fontified t invisible t)
5423 '(font-lock-fontified t face org-document-info-keyword)))
5424 (add-text-properties
5425 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5426 (if (string-equal dc1 "+title:")
5427 '(font-lock-fontified t face org-document-title)
5428 '(font-lock-fontified t face org-document-info))))
5429 ((or (equal dc1 "+results")
5430 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5431 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5432 "+call:" "+header:" "+headers:" "+name:"))
5433 (and (match-end 4) (equal dc3 "+attr")))
5434 (add-text-properties
5435 beg (match-end 0)
5436 '(font-lock-fontified t face org-meta-line))
5438 ((member dc3 '(" " ""))
5439 (add-text-properties
5440 beg (match-end 0)
5441 '(font-lock-fontified t face font-lock-comment-face)))
5442 ((not (member (char-after beg) '(?\ ?\t)))
5443 ;; just any other in-buffer setting, but not indented
5444 (add-text-properties
5445 beg (match-end 0)
5446 '(font-lock-fontified t face org-meta-line))
5448 (t nil))))))
5450 (defun org-activate-angle-links (limit)
5451 "Run through the buffer and add overlays to links."
5452 (if (and (re-search-forward org-angle-link-re limit t)
5453 (not (org-in-src-block-p)))
5454 (progn
5455 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5456 (add-text-properties (match-beginning 0) (match-end 0)
5457 (list 'mouse-face 'highlight
5458 'keymap org-mouse-map))
5459 (org-rear-nonsticky-at (match-end 0))
5460 t)))
5462 (defun org-activate-footnote-links (limit)
5463 "Run through the buffer and add overlays to footnotes."
5464 (let ((fn (org-footnote-next-reference-or-definition limit)))
5465 (when fn
5466 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5467 (org-remove-flyspell-overlays-in beg end)
5468 (add-text-properties beg end
5469 (list 'mouse-face 'highlight
5470 'keymap org-mouse-map
5471 'help-echo
5472 (if (= (point-at-bol) beg)
5473 "Footnote definition"
5474 "Footnote reference")
5475 'font-lock-fontified t
5476 'font-lock-multiline t
5477 'face 'org-footnote))))))
5479 (defun org-activate-bracket-links (limit)
5480 "Run through the buffer and add overlays to bracketed links."
5481 (if (and (re-search-forward org-bracket-link-regexp limit t)
5482 (not (org-in-src-block-p)))
5483 (let* ((help (concat "LINK: "
5484 (org-match-string-no-properties 1)))
5485 ;; FIXME: above we should remove the escapes.
5486 ;; but that requires another match, protecting match data,
5487 ;; a lot of overhead for font-lock.
5488 (ip (org-maybe-intangible
5489 (list 'invisible 'org-link
5490 'keymap org-mouse-map 'mouse-face 'highlight
5491 'font-lock-multiline t 'help-echo help)))
5492 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5493 'font-lock-multiline t 'help-echo help)))
5494 ;; We need to remove the invisible property here. Table narrowing
5495 ;; may have made some of this invisible.
5496 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5497 (remove-text-properties (match-beginning 0) (match-end 0)
5498 '(invisible nil))
5499 (if (match-end 3)
5500 (progn
5501 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5502 (org-rear-nonsticky-at (match-beginning 3))
5503 (add-text-properties (match-beginning 3) (match-end 3) vp)
5504 (org-rear-nonsticky-at (match-end 3))
5505 (add-text-properties (match-end 3) (match-end 0) ip)
5506 (org-rear-nonsticky-at (match-end 0)))
5507 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5508 (org-rear-nonsticky-at (match-beginning 1))
5509 (add-text-properties (match-beginning 1) (match-end 1) vp)
5510 (org-rear-nonsticky-at (match-end 1))
5511 (add-text-properties (match-end 1) (match-end 0) ip)
5512 (org-rear-nonsticky-at (match-end 0)))
5513 t)))
5515 (defun org-activate-dates (limit)
5516 "Run through the buffer and add overlays to dates."
5517 (if (re-search-forward org-tsr-regexp-both limit t)
5518 (progn
5519 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5520 (add-text-properties (match-beginning 0) (match-end 0)
5521 (list 'mouse-face 'highlight
5522 'keymap org-mouse-map))
5523 (org-rear-nonsticky-at (match-end 0))
5524 (when org-display-custom-times
5525 (if (match-end 3)
5526 (org-display-custom-time (match-beginning 3) (match-end 3)))
5527 (org-display-custom-time (match-beginning 1) (match-end 1)))
5528 t)))
5530 (defvar org-target-link-regexp nil
5531 "Regular expression matching radio targets in plain text.")
5532 (make-variable-buffer-local 'org-target-link-regexp)
5533 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5534 "Regular expression matching a link target.")
5535 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5536 "Regular expression matching a radio target.")
5537 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5538 "Regular expression matching any target.")
5540 (defun org-activate-target-links (limit)
5541 "Run through the buffer and add overlays to target matches."
5542 (when org-target-link-regexp
5543 (let ((case-fold-search t))
5544 (if (re-search-forward org-target-link-regexp limit t)
5545 (progn
5546 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5547 (add-text-properties (match-beginning 0) (match-end 0)
5548 (list 'mouse-face 'highlight
5549 'keymap org-mouse-map
5550 'help-echo "Radio target link"
5551 'org-linked-text t))
5552 (org-rear-nonsticky-at (match-end 0))
5553 t)))))
5555 (defun org-update-radio-target-regexp ()
5556 "Find all radio targets in this file and update the regular expression."
5557 (interactive)
5558 (when (memq 'radio org-activate-links)
5559 (setq org-target-link-regexp
5560 (org-make-target-link-regexp (org-all-targets 'radio)))
5561 (org-restart-font-lock)))
5563 (defun org-hide-wide-columns (limit)
5564 (let (s e)
5565 (setq s (text-property-any (point) (or limit (point-max))
5566 'org-cwidth t))
5567 (when s
5568 (setq e (next-single-property-change s 'org-cwidth))
5569 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5570 (goto-char e)
5571 t)))
5573 (defvar org-latex-and-specials-regexp nil
5574 "Regular expression for highlighting export special stuff.")
5575 (defvar org-match-substring-regexp)
5576 (defvar org-match-substring-with-braces-regexp)
5578 ;; This should be with the exporter code, but we also use if for font-locking
5579 (defconst org-export-html-special-string-regexps
5580 '(("\\\\-" . "&shy;")
5581 ("---\\([^-]\\)" . "&mdash;\\1")
5582 ("--\\([^-]\\)" . "&ndash;\\1")
5583 ("\\.\\.\\." . "&hellip;"))
5584 "Regular expressions for special string conversion.")
5587 (defun org-compute-latex-and-specials-regexp ()
5588 "Compute regular expression for stuff treated specially by exporters."
5589 (if (not org-highlight-latex-fragments-and-specials)
5590 (org-set-local 'org-latex-and-specials-regexp nil)
5591 (require 'org-exp)
5592 (let*
5593 ((matchers (plist-get org-format-latex-options :matchers))
5594 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5595 org-latex-regexps)))
5596 (org-export-allow-BIND nil)
5597 (options (org-combine-plists (org-default-export-plist)
5598 (org-infile-export-plist)))
5599 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5600 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5601 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5602 (org-export-html-expand (plist-get options :expand-quoted-html))
5603 (org-export-with-special-strings (plist-get options :special-strings))
5604 (re-sub
5605 (cond
5606 ((equal org-export-with-sub-superscripts '{})
5607 (list org-match-substring-with-braces-regexp))
5608 (org-export-with-sub-superscripts
5609 (list org-match-substring-regexp))))
5610 (re-latex
5611 (if org-export-with-LaTeX-fragments
5612 (mapcar (lambda (x) (nth 1 x)) latexs)))
5613 (re-macros
5614 (if org-export-with-TeX-macros
5615 (list (concat "\\\\"
5616 (regexp-opt
5617 (append
5619 (delq nil
5620 (mapcar 'car-safe
5621 (append org-entities-user
5622 org-entities)))
5623 (if (boundp 'org-latex-entities)
5624 (mapcar (lambda (x)
5625 (or (car-safe x) x))
5626 org-latex-entities)
5627 nil))
5628 'words))) ; FIXME
5630 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5631 (re-special (if org-export-with-special-strings
5632 (mapcar (lambda (x) (car x))
5633 org-export-html-special-string-regexps)))
5634 (re-rest
5635 (delq nil
5636 (list
5637 (if org-export-html-expand "@<[^>\n]+>")
5638 ))))
5639 (org-set-local
5640 'org-latex-and-specials-regexp
5641 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5642 re-rest) "\\|")))))
5644 (defun org-do-latex-and-special-faces (limit)
5645 "Run through the buffer and add overlays to links."
5646 (when org-latex-and-specials-regexp
5647 (let (rtn d)
5648 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5649 limit t))
5650 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5651 'face))
5652 '(org-code org-verbatim underline)))
5653 (progn
5654 (setq rtn t
5655 d (cond ((member (char-after (1+ (match-beginning 0)))
5656 '(?_ ?^)) 1)
5657 (t 0)))
5658 (font-lock-prepend-text-property
5659 (+ d (match-beginning 0)) (match-end 0)
5660 'face 'org-latex-and-export-specials)
5661 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5662 '(font-lock-multiline t)))))
5663 rtn)))
5665 (defun org-restart-font-lock ()
5666 "Restart `font-lock-mode', to force refontification."
5667 (when (and (boundp 'font-lock-mode) font-lock-mode)
5668 (font-lock-mode -1)
5669 (font-lock-mode 1)))
5671 (defun org-all-targets (&optional radio)
5672 "Return a list of all targets in this file.
5673 With optional argument RADIO, only find radio targets."
5674 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5675 rtn)
5676 (save-excursion
5677 (goto-char (point-min))
5678 (while (re-search-forward re nil t)
5679 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5680 rtn)))
5682 (defun org-make-target-link-regexp (targets)
5683 "Make regular expression matching all strings in TARGETS.
5684 The regular expression finds the targets also if there is a line break
5685 between words."
5686 (and targets
5687 (concat
5688 "\\<\\("
5689 (mapconcat
5690 (lambda (x)
5691 (setq x (regexp-quote x))
5692 (while (string-match " +" x)
5693 (setq x (replace-match "\\s-+" t t x)))
5695 targets
5696 "\\|")
5697 "\\)\\>")))
5699 (defun org-activate-tags (limit)
5700 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5701 (progn
5702 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5703 (add-text-properties (match-beginning 1) (match-end 1)
5704 (list 'mouse-face 'highlight
5705 'keymap org-mouse-map))
5706 (org-rear-nonsticky-at (match-end 1))
5707 t)))
5709 (defun org-outline-level ()
5710 "Compute the outline level of the heading at point.
5711 This function assumes that the cursor is at the beginning of a line matched
5712 by `outline-regexp'. Otherwise it returns garbage.
5713 If this is called at a normal headline, the level is the number of stars.
5714 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5715 (save-excursion
5716 (looking-at org-outline-regexp)
5717 (1- (- (match-end 0) (match-beginning 0)))))
5719 (defvar org-font-lock-keywords nil)
5721 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5722 "Regular expression matching a property line.")
5724 (defvar org-font-lock-hook nil
5725 "Functions to be called for special font lock stuff.")
5727 (defvar org-font-lock-set-keywords-hook nil
5728 "Functions that can manipulate `org-font-lock-extra-keywords'.
5729 This is called after `org-font-lock-extra-keywords' is defined, but before
5730 it is installed to be used by font lock. This can be useful if something
5731 needs to be inserted at a specific position in the font-lock sequence.")
5733 (defun org-font-lock-hook (limit)
5734 "Run `org-font-lock-hook' within LIMIT."
5735 (run-hook-with-args 'org-font-lock-hook limit))
5737 (defun org-set-font-lock-defaults ()
5738 "Set font lock defaults for the current buffer."
5739 (let* ((em org-fontify-emphasized-text)
5740 (lk org-activate-links)
5741 (org-font-lock-extra-keywords
5742 (list
5743 ;; Call the hook
5744 '(org-font-lock-hook)
5745 ;; Headlines
5746 `(,(if org-fontify-whole-heading-line
5747 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5748 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5749 (1 (org-get-level-face 1))
5750 (2 (org-get-level-face 2))
5751 (3 (org-get-level-face 3)))
5752 ;; Table lines
5753 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5754 (1 'org-table t))
5755 ;; Table internals
5756 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5757 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5758 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5759 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5760 ;; Drawers
5761 (list org-drawer-regexp '(0 'org-special-keyword t))
5762 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5763 ;; Properties
5764 (list org-property-re
5765 '(1 'org-special-keyword t)
5766 '(3 'org-property-value t))
5767 ;; Links
5768 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5769 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5770 (if (memq 'plain lk) '(org-activate-plain-links))
5771 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5772 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5773 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5774 (if (memq 'footnote lk) '(org-activate-footnote-links))
5775 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5776 '(org-hide-wide-columns (0 nil append))
5777 ;; TODO keyword
5778 (list (format org-heading-keyword-regexp-format
5779 org-todo-regexp)
5780 '(2 (org-get-todo-face 2) t))
5781 ;; DONE
5782 (if org-fontify-done-headline
5783 (list (format org-heading-keyword-regexp-format
5784 (concat
5785 "\\(?:"
5786 (mapconcat 'regexp-quote org-done-keywords "\\|")
5787 "\\)"))
5788 '(2 'org-headline-done t))
5789 nil)
5790 ;; Priorities
5791 '(org-font-lock-add-priority-faces)
5792 ;; Tags
5793 '(org-font-lock-add-tag-faces)
5794 ;; Special keywords
5795 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5796 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5797 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5798 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5799 ;; Emphasis
5800 (if em
5801 (if (featurep 'xemacs)
5802 '(org-do-emphasis-faces (0 nil append))
5803 '(org-do-emphasis-faces)))
5804 ;; Checkboxes
5805 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5806 1 'org-checkbox prepend)
5807 (if (cdr (assq 'checkbox org-list-automatic-rules))
5808 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5809 (0 (org-get-checkbox-statistics-face) t)))
5810 ;; Description list items
5811 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5812 1 'org-list-dt prepend)
5813 ;; ARCHIVEd headings
5814 (list (concat
5815 org-outline-regexp-bol
5816 "\\(.*:" org-archive-tag ":.*\\)")
5817 '(1 'org-archived prepend))
5818 ;; Specials
5819 '(org-do-latex-and-special-faces)
5820 '(org-fontify-entities)
5821 '(org-raise-scripts)
5822 ;; Code
5823 '(org-activate-code (1 'org-code t))
5824 ;; COMMENT
5825 (list (format org-heading-keyword-regexp-format
5826 (concat "\\("
5827 org-comment-string "\\|" org-quote-string
5828 "\\)"))
5829 '(2 'org-special-keyword t))
5830 ;; Blocks and meta lines
5831 '(org-fontify-meta-lines-and-blocks)
5833 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5834 (run-hooks 'org-font-lock-set-keywords-hook)
5835 ;; Now set the full font-lock-keywords
5836 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5837 (org-set-local 'font-lock-defaults
5838 '(org-font-lock-keywords t nil nil backward-paragraph))
5839 (kill-local-variable 'font-lock-keywords) nil))
5841 (defun org-toggle-pretty-entities ()
5842 "Toggle the composition display of entities as UTF8 characters."
5843 (interactive)
5844 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5845 (org-restart-font-lock)
5846 (if org-pretty-entities
5847 (message "Entities are displayed as UTF8 characters")
5848 (save-restriction
5849 (widen)
5850 (org-decompose-region (point-min) (point-max))
5851 (message "Entities are displayed plain"))))
5853 (defvar org-custom-properties-overlays nil
5854 "List of overlays used for custom properties.")
5855 (make-variable-buffer-local 'org-custom-properties-overlays)
5857 (defun org-toggle-custom-properties-visibility ()
5858 "Display or hide properties in `org-custom-properties'."
5859 (interactive)
5860 (if org-custom-properties-overlays
5861 (progn (mapc 'delete-overlay org-custom-properties-overlays)
5862 (setq org-custom-properties-overlays nil))
5863 (unless (not org-custom-properties)
5864 (save-excursion
5865 (save-restriction
5866 (widen)
5867 (goto-char (point-min))
5868 (while (re-search-forward org-property-re nil t)
5869 (mapc (lambda(p)
5870 (when (equal p (substring (match-string 1) 1 -1))
5871 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
5872 (overlay-put o 'invisible t)
5873 (overlay-put o 'org-custom-property t)
5874 (push o org-custom-properties-overlays))))
5875 org-custom-properties)))))))
5877 (defun org-fontify-entities (limit)
5878 "Find an entity to fontify."
5879 (let (ee)
5880 (when org-pretty-entities
5881 (catch 'match
5882 (while (re-search-forward
5883 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
5884 limit t)
5885 (if (and (not (org-in-indented-comment-line))
5886 (setq ee (org-entity-get (match-string 1)))
5887 (= (length (nth 6 ee)) 1))
5888 (let*
5889 ((end (if (equal (match-string 2) "{}")
5890 (match-end 2)
5891 (match-end 1))))
5892 (add-text-properties
5893 (match-beginning 0) end
5894 (list 'font-lock-fontified t))
5895 (compose-region (match-beginning 0) end
5896 (nth 6 ee) nil)
5897 (backward-char 1)
5898 (throw 'match t))))
5899 nil))))
5901 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5902 "Fontify string S like in Org-mode."
5903 (with-temp-buffer
5904 (insert s)
5905 (let ((org-odd-levels-only odd-levels))
5906 (org-mode)
5907 (font-lock-fontify-buffer)
5908 (buffer-string))))
5910 (defvar org-m nil)
5911 (defvar org-l nil)
5912 (defvar org-f nil)
5913 (defun org-get-level-face (n)
5914 "Get the right face for match N in font-lock matching of headlines."
5915 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5916 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5917 (if org-cycle-level-faces
5918 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5919 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5920 (cond
5921 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5922 ((eq n 2) org-f)
5923 (t (if org-level-color-stars-only nil org-f))))
5926 (defun org-get-todo-face (kwd)
5927 "Get the right face for a TODO keyword KWD.
5928 If KWD is a number, get the corresponding match group."
5929 (if (numberp kwd) (setq kwd (match-string kwd)))
5930 (or (org-face-from-face-or-color
5931 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5932 (and (member kwd org-done-keywords) 'org-done)
5933 'org-todo))
5935 (defun org-face-from-face-or-color (context inherit face-or-color)
5936 "Create a face list that inherits INHERIT, but sets the foreground color.
5937 When FACE-OR-COLOR is not a string, just return it."
5938 (if (stringp face-or-color)
5939 (list :inherit inherit
5940 (cdr (assoc context org-faces-easy-properties))
5941 face-or-color)
5942 face-or-color))
5944 (defun org-font-lock-add-tag-faces (limit)
5945 "Add the special tag faces."
5946 (when (and org-tag-faces org-tags-special-faces-re)
5947 (while (re-search-forward org-tags-special-faces-re limit t)
5948 (add-text-properties (match-beginning 1) (match-end 1)
5949 (list 'face (org-get-tag-face 1)
5950 'font-lock-fontified t))
5951 (backward-char 1))))
5953 (defun org-font-lock-add-priority-faces (limit)
5954 "Add the special priority faces."
5955 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5956 (when (save-match-data (org-at-heading-p))
5957 (add-text-properties
5958 (match-beginning 0) (match-end 0)
5959 (list 'face (or (org-face-from-face-or-color
5960 'priority 'org-special-keyword
5961 (cdr (assoc (char-after (match-beginning 1))
5962 org-priority-faces)))
5963 'org-special-keyword)
5964 'font-lock-fontified t)))))
5966 (defun org-get-tag-face (kwd)
5967 "Get the right face for a TODO keyword KWD.
5968 If KWD is a number, get the corresponding match group."
5969 (if (numberp kwd) (setq kwd (match-string kwd)))
5970 (or (org-face-from-face-or-color
5971 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5972 'org-tag))
5974 (defun org-unfontify-region (beg end &optional maybe_loudly)
5975 "Remove fontification and activation overlays from links."
5976 (font-lock-default-unfontify-region beg end)
5977 (let* ((buffer-undo-list t)
5978 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5979 (inhibit-modification-hooks t)
5980 deactivate-mark buffer-file-name buffer-file-truename)
5981 (org-decompose-region beg end)
5982 (remove-text-properties beg end
5983 '(mouse-face t keymap t org-linked-text t
5984 invisible t intangible t
5985 org-no-flyspell t org-emphasis t))
5986 (org-remove-font-lock-display-properties beg end)))
5988 (defconst org-script-display '(((raise -0.3) (height 0.7))
5989 ((raise 0.3) (height 0.7))
5990 ((raise -0.5))
5991 ((raise 0.5)))
5992 "Display properties for showing superscripts and subscripts.")
5994 (defun org-remove-font-lock-display-properties (beg end)
5995 "Remove specific display properties that have been added by font lock.
5996 The will remove the raise properties that are used to show superscripts
5997 and subscripts."
5998 (let (next prop)
5999 (while (< beg end)
6000 (setq next (next-single-property-change beg 'display nil end)
6001 prop (get-text-property beg 'display))
6002 (if (member prop org-script-display)
6003 (put-text-property beg next 'display nil))
6004 (setq beg next))))
6006 (defun org-raise-scripts (limit)
6007 "Add raise properties to sub/superscripts."
6008 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6009 (if (re-search-forward
6010 (if (eq org-use-sub-superscripts t)
6011 org-match-substring-regexp
6012 org-match-substring-with-braces-regexp)
6013 limit t)
6014 (let* ((pos (point)) table-p comment-p
6015 (mpos (match-beginning 3))
6016 (emph-p (get-text-property mpos 'org-emphasis))
6017 (link-p (get-text-property mpos 'mouse-face))
6018 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6019 (goto-char (point-at-bol))
6020 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6021 comment-p (org-looking-at-p "[ \t]*#"))
6022 (goto-char pos)
6023 ;; FIXME: Should we go back one character here, for a_b^c
6024 ;; (goto-char (1- pos)) ;????????????????????
6025 (if (or comment-p emph-p link-p keyw-p)
6027 (put-text-property (match-beginning 3) (match-end 0)
6028 'display
6029 (if (equal (char-after (match-beginning 2)) ?^)
6030 (nth (if table-p 3 1) org-script-display)
6031 (nth (if table-p 2 0) org-script-display)))
6032 (add-text-properties (match-beginning 2) (match-end 2)
6033 (list 'invisible t
6034 'org-dwidth t 'org-dwidth-n 1))
6035 (if (and (eq (char-after (match-beginning 3)) ?{)
6036 (eq (char-before (match-end 3)) ?}))
6037 (progn
6038 (add-text-properties
6039 (match-beginning 3) (1+ (match-beginning 3))
6040 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6041 (add-text-properties
6042 (1- (match-end 3)) (match-end 3)
6043 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6044 t)))))
6046 ;;;; Visibility cycling, including org-goto and indirect buffer
6048 ;;; Cycling
6050 (defvar org-cycle-global-status nil)
6051 (make-variable-buffer-local 'org-cycle-global-status)
6052 (defvar org-cycle-subtree-status nil)
6053 (make-variable-buffer-local 'org-cycle-subtree-status)
6055 (defvar org-inlinetask-min-level)
6057 ;;;###autoload
6058 (defun org-cycle (&optional arg)
6059 "TAB-action and visibility cycling for Org-mode.
6061 This is the command invoked in Org-mode by the TAB key. Its main purpose
6062 is outline visibility cycling, but it also invokes other actions
6063 in special contexts.
6065 - When this function is called with a prefix argument, rotate the entire
6066 buffer through 3 states (global cycling)
6067 1. OVERVIEW: Show only top-level headlines.
6068 2. CONTENTS: Show all headlines of all levels, but no body text.
6069 3. SHOW ALL: Show everything.
6070 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6071 determined by the variable `org-startup-folded', and by any VISIBILITY
6072 properties in the buffer.
6073 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6074 including any drawers.
6076 - When inside a table, re-align the table and move to the next field.
6078 - When point is at the beginning of a headline, rotate the subtree started
6079 by this line through 3 different states (local cycling)
6080 1. FOLDED: Only the main headline is shown.
6081 2. CHILDREN: The main headline and the direct children are shown.
6082 From this state, you can move to one of the children
6083 and zoom in further.
6084 3. SUBTREE: Show the entire subtree, including body text.
6085 If there is no subtree, switch directly from CHILDREN to FOLDED.
6087 - When point is at the beginning of an empty headline and the variable
6088 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6089 of the headline by demoting and promoting it to likely levels. This
6090 speeds up creation document structure by pressing TAB once or several
6091 times right after creating a new headline.
6093 - When there is a numeric prefix, go up to a heading with level ARG, do
6094 a `show-subtree' and return to the previous cursor position. If ARG
6095 is negative, go up that many levels.
6097 - When point is not at the beginning of a headline, execute the global
6098 binding for TAB, which is re-indenting the line. See the option
6099 `org-cycle-emulate-tab' for details.
6101 - Special case: if point is at the beginning of the buffer and there is
6102 no headline in line 1, this function will act as if called with prefix arg
6103 (C-u TAB, same as S-TAB) also when called without prefix arg.
6104 But only if also the variable `org-cycle-global-at-bob' is t."
6105 (interactive "P")
6106 (org-load-modules-maybe)
6107 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6108 (and org-cycle-level-after-item/entry-creation
6109 (or (org-cycle-level)
6110 (org-cycle-item-indentation))))
6111 (let* ((limit-level
6112 (or org-cycle-max-level
6113 (and (boundp 'org-inlinetask-min-level)
6114 org-inlinetask-min-level
6115 (1- org-inlinetask-min-level))))
6116 (nstars (and limit-level
6117 (if org-odd-levels-only
6118 (and limit-level (1- (* limit-level 2)))
6119 limit-level)))
6120 (org-outline-regexp
6121 (if (not (derived-mode-p 'org-mode))
6122 outline-regexp
6123 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6124 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6125 (not (looking-at org-outline-regexp))))
6126 (org-cycle-hook
6127 (if bob-special
6128 (delq 'org-optimize-window-after-visibility-change
6129 (copy-sequence org-cycle-hook))
6130 org-cycle-hook))
6131 (pos (point)))
6133 (if (or bob-special (equal arg '(4)))
6134 ;; special case: use global cycling
6135 (setq arg t))
6137 (cond
6139 ((equal arg '(16))
6140 (setq last-command 'dummy)
6141 (org-set-startup-visibility)
6142 (message "Startup visibility, plus VISIBILITY properties"))
6144 ((equal arg '(64))
6145 (show-all)
6146 (message "Entire buffer visible, including drawers"))
6148 ;; Table: enter it or move to the next field.
6149 ((org-at-table-p 'any)
6150 (if (org-at-table.el-p)
6151 (message "Use C-c ' to edit table.el tables")
6152 (if arg (org-table-edit-field t)
6153 (org-table-justify-field-maybe)
6154 (call-interactively 'org-table-next-field))))
6156 ((run-hook-with-args-until-success
6157 'org-tab-after-check-for-table-hook))
6159 ;; Global cycling: delegate to `org-cycle-internal-global'.
6160 ((eq arg t) (org-cycle-internal-global))
6162 ;; Drawers: delegate to `org-flag-drawer'.
6163 ((and org-drawers org-drawer-regexp
6164 (save-excursion
6165 (beginning-of-line 1)
6166 (looking-at org-drawer-regexp)))
6167 (org-flag-drawer ; toggle block visibility
6168 (not (get-char-property (match-end 0) 'invisible))))
6170 ;; Show-subtree, ARG levels up from here.
6171 ((integerp arg)
6172 (save-excursion
6173 (org-back-to-heading)
6174 (outline-up-heading (if (< arg 0) (- arg)
6175 (- (funcall outline-level) arg)))
6176 (org-show-subtree)))
6178 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6179 ((and (featurep 'org-inlinetask)
6180 (org-inlinetask-at-task-p)
6181 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6182 (org-inlinetask-toggle-visibility))
6184 ((org-try-cdlatex-tab))
6186 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6187 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6188 (save-excursion (beginning-of-line 1)
6189 (looking-at org-outline-regexp)))
6190 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6191 (org-cycle-internal-local))
6193 ;; From there: TAB emulation and template completion.
6194 (buffer-read-only (org-back-to-heading))
6196 ((run-hook-with-args-until-success
6197 'org-tab-after-check-for-cycling-hook))
6199 ((org-try-structure-completion))
6201 ((run-hook-with-args-until-success
6202 'org-tab-before-tab-emulation-hook))
6204 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6205 (or (not (bolp))
6206 (not (looking-at org-outline-regexp))))
6207 (call-interactively (global-key-binding "\t")))
6209 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6210 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6211 (or (and (eq org-cycle-emulate-tab 'white)
6212 (= (match-end 0) (point-at-eol)))
6213 (and (eq org-cycle-emulate-tab 'whitestart)
6214 (>= (match-end 0) pos))))
6216 (eq org-cycle-emulate-tab t))
6217 (call-interactively (global-key-binding "\t")))
6219 (t (save-excursion
6220 (org-back-to-heading)
6221 (org-cycle)))))))
6223 (defun org-cycle-internal-global ()
6224 "Do the global cycling action."
6225 ;; Hack to avoid display of messages for .org attachments in Gnus
6226 (let ((ga (string-match "\\*fontification" (buffer-name))))
6227 (cond
6228 ((and (eq last-command this-command)
6229 (eq org-cycle-global-status 'overview))
6230 ;; We just created the overview - now do table of contents
6231 ;; This can be slow in very large buffers, so indicate action
6232 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6233 (unless ga (message "CONTENTS..."))
6234 (org-content)
6235 (unless ga (message "CONTENTS...done"))
6236 (setq org-cycle-global-status 'contents)
6237 (run-hook-with-args 'org-cycle-hook 'contents))
6239 ((and (eq last-command this-command)
6240 (eq org-cycle-global-status 'contents))
6241 ;; We just showed the table of contents - now show everything
6242 (run-hook-with-args 'org-pre-cycle-hook 'all)
6243 (show-all)
6244 (unless ga (message "SHOW ALL"))
6245 (setq org-cycle-global-status 'all)
6246 (run-hook-with-args 'org-cycle-hook 'all))
6249 ;; Default action: go to overview
6250 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6251 (org-overview)
6252 (unless ga (message "OVERVIEW"))
6253 (setq org-cycle-global-status 'overview)
6254 (run-hook-with-args 'org-cycle-hook 'overview)))))
6256 (defun org-cycle-internal-local ()
6257 "Do the local cycling action."
6258 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6259 ;; First, determine end of headline (EOH), end of subtree or item
6260 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6261 (save-excursion
6262 (if (org-at-item-p)
6263 (progn
6264 (beginning-of-line)
6265 (setq struct (org-list-struct))
6266 (setq eoh (point-at-eol))
6267 (setq eos (org-list-get-item-end-before-blank (point) struct))
6268 (setq has-children (org-list-has-child-p (point) struct)))
6269 (org-back-to-heading)
6270 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6271 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6272 (setq has-children
6273 (or (save-excursion
6274 (let ((level (funcall outline-level)))
6275 (outline-next-heading)
6276 (and (org-at-heading-p t)
6277 (> (funcall outline-level) level))))
6278 (save-excursion
6279 (org-list-search-forward (org-item-beginning-re) eos t)))))
6280 ;; Determine end invisible part of buffer (EOL)
6281 (beginning-of-line 2)
6282 ;; XEmacs doesn't have `next-single-char-property-change'
6283 (if (featurep 'xemacs)
6284 (while (and (not (eobp)) ;; this is like `next-line'
6285 (get-char-property (1- (point)) 'invisible))
6286 (beginning-of-line 2))
6287 (while (and (not (eobp)) ;; this is like `next-line'
6288 (get-char-property (1- (point)) 'invisible))
6289 (goto-char (next-single-char-property-change (point) 'invisible))
6290 (and (eolp) (beginning-of-line 2))))
6291 (setq eol (point)))
6292 ;; Find out what to do next and set `this-command'
6293 (cond
6294 ((= eos eoh)
6295 ;; Nothing is hidden behind this heading
6296 (unless (org-before-first-heading-p)
6297 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6298 (message "EMPTY ENTRY")
6299 (setq org-cycle-subtree-status nil)
6300 (save-excursion
6301 (goto-char eos)
6302 (outline-next-heading)
6303 (if (outline-invisible-p) (org-flag-heading nil))))
6304 ((and (or (>= eol eos)
6305 (not (string-match "\\S-" (buffer-substring eol eos))))
6306 (or has-children
6307 (not (setq children-skipped
6308 org-cycle-skip-children-state-if-no-children))))
6309 ;; Entire subtree is hidden in one line: children view
6310 (unless (org-before-first-heading-p)
6311 (run-hook-with-args 'org-pre-cycle-hook 'children))
6312 (if (org-at-item-p)
6313 (org-list-set-item-visibility (point-at-bol) struct 'children)
6314 (org-show-entry)
6315 (org-with-limited-levels (show-children))
6316 ;; FIXME: This slows down the func way too much.
6317 ;; How keep drawers hidden in subtree anyway?
6318 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6319 ;; (org-cycle-hide-drawers 'subtree))
6321 ;; Fold every list in subtree to top-level items.
6322 (when (eq org-cycle-include-plain-lists 'integrate)
6323 (save-excursion
6324 (org-back-to-heading)
6325 (while (org-list-search-forward (org-item-beginning-re) eos t)
6326 (beginning-of-line 1)
6327 (let* ((struct (org-list-struct))
6328 (prevs (org-list-prevs-alist struct))
6329 (end (org-list-get-bottom-point struct)))
6330 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6331 (org-list-get-all-items (point) struct prevs))
6332 (goto-char end))))))
6333 (message "CHILDREN")
6334 (save-excursion
6335 (goto-char eos)
6336 (outline-next-heading)
6337 (if (outline-invisible-p) (org-flag-heading nil)))
6338 (setq org-cycle-subtree-status 'children)
6339 (unless (org-before-first-heading-p)
6340 (run-hook-with-args 'org-cycle-hook 'children)))
6341 ((or children-skipped
6342 (and (eq last-command this-command)
6343 (eq org-cycle-subtree-status 'children)))
6344 ;; We just showed the children, or no children are there,
6345 ;; now show everything.
6346 (unless (org-before-first-heading-p)
6347 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6348 (outline-flag-region eoh eos nil)
6349 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6350 (setq org-cycle-subtree-status 'subtree)
6351 (unless (org-before-first-heading-p)
6352 (run-hook-with-args 'org-cycle-hook 'subtree)))
6354 ;; Default action: hide the subtree.
6355 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6356 (outline-flag-region eoh eos t)
6357 (message "FOLDED")
6358 (setq org-cycle-subtree-status 'folded)
6359 (unless (org-before-first-heading-p)
6360 (run-hook-with-args 'org-cycle-hook 'folded))))))
6362 ;;;###autoload
6363 (defun org-global-cycle (&optional arg)
6364 "Cycle the global visibility. For details see `org-cycle'.
6365 With \\[universal-argument] prefix arg, switch to startup visibility.
6366 With a numeric prefix, show all headlines up to that level."
6367 (interactive "P")
6368 (let ((org-cycle-include-plain-lists
6369 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6370 (cond
6371 ((integerp arg)
6372 (show-all)
6373 (hide-sublevels arg)
6374 (setq org-cycle-global-status 'contents))
6375 ((equal arg '(4))
6376 (org-set-startup-visibility)
6377 (message "Startup visibility, plus VISIBILITY properties."))
6379 (org-cycle '(4))))))
6381 (defun org-set-startup-visibility ()
6382 "Set the visibility required by startup options and properties."
6383 (cond
6384 ((eq org-startup-folded t)
6385 (org-cycle '(4)))
6386 ((eq org-startup-folded 'content)
6387 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6388 (org-cycle '(4)) (org-cycle '(4)))))
6389 (unless (eq org-startup-folded 'showeverything)
6390 (if org-hide-block-startup (org-hide-block-all))
6391 (org-set-visibility-according-to-property 'no-cleanup)
6392 (org-cycle-hide-archived-subtrees 'all)
6393 (org-cycle-hide-drawers 'all)
6394 (org-cycle-show-empty-lines t)))
6396 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6397 "Switch subtree visibilities according to :VISIBILITY: property."
6398 (interactive)
6399 (let (org-show-entry-below state)
6400 (save-excursion
6401 (goto-char (point-min))
6402 (while (re-search-forward
6403 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6404 nil t)
6405 (setq state (match-string 1))
6406 (save-excursion
6407 (org-back-to-heading t)
6408 (hide-subtree)
6409 (org-reveal)
6410 (cond
6411 ((equal state '("fold" "folded"))
6412 (hide-subtree))
6413 ((equal state "children")
6414 (org-show-hidden-entry)
6415 (show-children))
6416 ((equal state "content")
6417 (save-excursion
6418 (save-restriction
6419 (org-narrow-to-subtree)
6420 (org-content))))
6421 ((member state '("all" "showall"))
6422 (show-subtree)))))
6423 (unless no-cleanup
6424 (org-cycle-hide-archived-subtrees 'all)
6425 (org-cycle-hide-drawers 'all)
6426 (org-cycle-show-empty-lines 'all)))))
6428 ;; This function uses outline-regexp instead of the more fundamental
6429 ;; org-outline-regexp so that org-cycle-global works outside of Org
6430 ;; buffers, where outline-regexp is needed.
6431 (defun org-overview ()
6432 "Switch to overview mode, showing only top-level headlines.
6433 Really, this shows all headlines with level equal or greater than the level
6434 of the first headline in the buffer. This is important, because if the
6435 first headline is not level one, then (hide-sublevels 1) gives confusing
6436 results."
6437 (interactive)
6438 (let ((level (save-excursion
6439 (goto-char (point-min))
6440 (if (re-search-forward (concat "^" outline-regexp) nil t)
6441 (progn
6442 (goto-char (match-beginning 0))
6443 (funcall outline-level))))))
6444 (and level (hide-sublevels level))))
6446 (defun org-content (&optional arg)
6447 "Show all headlines in the buffer, like a table of contents.
6448 With numerical argument N, show content up to level N."
6449 (interactive "P")
6450 (save-excursion
6451 ;; Visit all headings and show their offspring
6452 (and (integerp arg) (org-overview))
6453 (goto-char (point-max))
6454 (catch 'exit
6455 (while (and (progn (condition-case nil
6456 (outline-previous-visible-heading 1)
6457 (error (goto-char (point-min))))
6459 (looking-at org-outline-regexp))
6460 (if (integerp arg)
6461 (show-children (1- arg))
6462 (show-branches))
6463 (if (bobp) (throw 'exit nil))))))
6466 (defun org-optimize-window-after-visibility-change (state)
6467 "Adjust the window after a change in outline visibility.
6468 This function is the default value of the hook `org-cycle-hook'."
6469 (when (get-buffer-window (current-buffer))
6470 (cond
6471 ((eq state 'content) nil)
6472 ((eq state 'all) nil)
6473 ((eq state 'folded) nil)
6474 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6475 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6477 (defun org-remove-empty-overlays-at (pos)
6478 "Remove outline overlays that do not contain non-white stuff."
6479 (mapc
6480 (lambda (o)
6481 (and (eq 'outline (overlay-get o 'invisible))
6482 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6483 (overlay-end o))))
6484 (delete-overlay o)))
6485 (overlays-at pos)))
6487 (defun org-clean-visibility-after-subtree-move ()
6488 "Fix visibility issues after moving a subtree."
6489 ;; First, find a reasonable region to look at:
6490 ;; Start two siblings above, end three below
6491 (let* ((beg (save-excursion
6492 (and (org-get-last-sibling)
6493 (org-get-last-sibling))
6494 (point)))
6495 (end (save-excursion
6496 (and (org-get-next-sibling)
6497 (org-get-next-sibling)
6498 (org-get-next-sibling))
6499 (if (org-at-heading-p)
6500 (point-at-eol)
6501 (point))))
6502 (level (looking-at "\\*+"))
6503 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6504 (save-excursion
6505 (save-restriction
6506 (narrow-to-region beg end)
6507 (when re
6508 ;; Properly fold already folded siblings
6509 (goto-char (point-min))
6510 (while (re-search-forward re nil t)
6511 (if (and (not (outline-invisible-p))
6512 (save-excursion
6513 (goto-char (point-at-eol)) (outline-invisible-p)))
6514 (hide-entry))))
6515 (org-cycle-show-empty-lines 'overview)
6516 (org-cycle-hide-drawers 'overview)))))
6518 (defun org-cycle-show-empty-lines (state)
6519 "Show empty lines above all visible headlines.
6520 The region to be covered depends on STATE when called through
6521 `org-cycle-hook'. Lisp program can use t for STATE to get the
6522 entire buffer covered. Note that an empty line is only shown if there
6523 are at least `org-cycle-separator-lines' empty lines before the headline."
6524 (when (not (= org-cycle-separator-lines 0))
6525 (save-excursion
6526 (let* ((n (abs org-cycle-separator-lines))
6527 (re (cond
6528 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6529 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6530 (t (let ((ns (number-to-string (- n 2))))
6531 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6532 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6533 beg end b e)
6534 (cond
6535 ((memq state '(overview contents t))
6536 (setq beg (point-min) end (point-max)))
6537 ((memq state '(children folded))
6538 (setq beg (point) end (progn (org-end-of-subtree t t)
6539 (beginning-of-line 2)
6540 (point)))))
6541 (when beg
6542 (goto-char beg)
6543 (while (re-search-forward re end t)
6544 (unless (get-char-property (match-end 1) 'invisible)
6545 (setq e (match-end 1))
6546 (if (< org-cycle-separator-lines 0)
6547 (setq b (save-excursion
6548 (goto-char (match-beginning 0))
6549 (org-back-over-empty-lines)
6550 (if (save-excursion
6551 (goto-char (max (point-min) (1- (point))))
6552 (org-at-heading-p))
6553 (1- (point))
6554 (point))))
6555 (setq b (match-beginning 1)))
6556 (outline-flag-region b e nil)))))))
6557 ;; Never hide empty lines at the end of the file.
6558 (save-excursion
6559 (goto-char (point-max))
6560 (outline-previous-heading)
6561 (outline-end-of-heading)
6562 (if (and (looking-at "[ \t\n]+")
6563 (= (match-end 0) (point-max)))
6564 (outline-flag-region (point) (match-end 0) nil))))
6566 (defun org-show-empty-lines-in-parent ()
6567 "Move to the parent and re-show empty lines before visible headlines."
6568 (save-excursion
6569 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6570 (org-cycle-show-empty-lines context))))
6572 (defun org-files-list ()
6573 "Return `org-agenda-files' list, plus all open org-mode files.
6574 This is useful for operations that need to scan all of a user's
6575 open and agenda-wise Org files."
6576 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6577 (dolist (buf (buffer-list))
6578 (with-current-buffer buf
6579 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6580 (let ((file (expand-file-name (buffer-file-name))))
6581 (unless (member file files)
6582 (push file files))))))
6583 files))
6585 (defsubst org-entry-beginning-position ()
6586 "Return the beginning position of the current entry."
6587 (save-excursion (outline-back-to-heading t) (point)))
6589 (defsubst org-entry-end-position ()
6590 "Return the end position of the current entry."
6591 (save-excursion (outline-next-heading) (point)))
6593 (defun org-cycle-hide-drawers (state)
6594 "Re-hide all drawers after a visibility state change."
6595 (when (and (derived-mode-p 'org-mode)
6596 (not (memq state '(overview folded contents))))
6597 (save-excursion
6598 (let* ((globalp (memq state '(contents all)))
6599 (beg (if globalp (point-min) (point)))
6600 (end (if globalp (point-max)
6601 (if (eq state 'children)
6602 (save-excursion (outline-next-heading) (point))
6603 (org-end-of-subtree t)))))
6604 (goto-char beg)
6605 (while (re-search-forward org-drawer-regexp end t)
6606 (org-flag-drawer t))))))
6608 (defun org-flag-drawer (flag)
6609 "When FLAG is non-nil, hide the drawer we are within.
6610 Otherwise make it visible."
6611 (save-excursion
6612 (beginning-of-line 1)
6613 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6614 (let ((b (match-end 0)))
6615 (if (re-search-forward
6616 "^[ \t]*:END:"
6617 (save-excursion (outline-next-heading) (point)) t)
6618 (outline-flag-region b (point-at-eol) flag)
6619 (error ":END: line missing at position %s" b))))))
6621 (defun org-subtree-end-visible-p ()
6622 "Is the end of the current subtree visible?"
6623 (pos-visible-in-window-p
6624 (save-excursion (org-end-of-subtree t) (point))))
6626 (defun org-first-headline-recenter (&optional N)
6627 "Move cursor to the first headline and recenter the headline.
6628 Optional argument N means put the headline into the Nth line of the window."
6629 (goto-char (point-min))
6630 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6631 (beginning-of-line)
6632 (recenter (prefix-numeric-value N))))
6634 ;;; Saving and restoring visibility
6636 (defun org-outline-overlay-data (&optional use-markers)
6637 "Return a list of the locations of all outline overlays.
6638 These are overlays with the `invisible' property value `outline'.
6639 The return value is a list of cons cells, with start and stop
6640 positions for each overlay.
6641 If USE-MARKERS is set, return the positions as markers."
6642 (let (beg end)
6643 (save-excursion
6644 (save-restriction
6645 (widen)
6646 (delq nil
6647 (mapcar (lambda (o)
6648 (when (eq (overlay-get o 'invisible) 'outline)
6649 (setq beg (overlay-start o)
6650 end (overlay-end o))
6651 (and beg end (> end beg)
6652 (if use-markers
6653 (cons (move-marker (make-marker) beg)
6654 (move-marker (make-marker) end))
6655 (cons beg end)))))
6656 (overlays-in (point-min) (point-max))))))))
6658 (defun org-set-outline-overlay-data (data)
6659 "Create visibility overlays for all positions in DATA.
6660 DATA should have been made by `org-outline-overlay-data'."
6661 (let (o)
6662 (save-excursion
6663 (save-restriction
6664 (widen)
6665 (show-all)
6666 (mapc (lambda (c)
6667 (outline-flag-region (car c) (cdr c) t))
6668 data)))))
6670 ;;; Folding of blocks
6672 (defvar org-hide-block-overlays nil
6673 "Overlays hiding blocks.")
6674 (make-variable-buffer-local 'org-hide-block-overlays)
6676 (defun org-block-map (function &optional start end)
6677 "Call FUNCTION at the head of all source blocks in the current buffer.
6678 Optional arguments START and END can be used to limit the range."
6679 (let ((start (or start (point-min)))
6680 (end (or end (point-max))))
6681 (save-excursion
6682 (goto-char start)
6683 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6684 (save-excursion
6685 (save-match-data
6686 (goto-char (match-beginning 0))
6687 (funcall function)))))))
6689 (defun org-hide-block-toggle-all ()
6690 "Toggle the visibility of all blocks in the current buffer."
6691 (org-block-map #'org-hide-block-toggle))
6693 (defun org-hide-block-all ()
6694 "Fold all blocks in the current buffer."
6695 (interactive)
6696 (org-show-block-all)
6697 (org-block-map #'org-hide-block-toggle-maybe))
6699 (defun org-show-block-all ()
6700 "Unfold all blocks in the current buffer."
6701 (interactive)
6702 (mapc 'delete-overlay org-hide-block-overlays)
6703 (setq org-hide-block-overlays nil))
6705 (defun org-hide-block-toggle-maybe ()
6706 "Toggle visibility of block at point."
6707 (interactive)
6708 (let ((case-fold-search t))
6709 (if (save-excursion
6710 (beginning-of-line 1)
6711 (looking-at org-block-regexp))
6712 (progn (org-hide-block-toggle)
6713 t) ;; to signal that we took action
6714 nil))) ;; to signal that we did not
6716 (defun org-hide-block-toggle (&optional force)
6717 "Toggle the visibility of the current block."
6718 (interactive)
6719 (save-excursion
6720 (beginning-of-line)
6721 (if (re-search-forward org-block-regexp nil t)
6722 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6723 (end (match-end 0)) ;; end of entire body
6725 (if (memq t (mapcar (lambda (overlay)
6726 (eq (overlay-get overlay 'invisible)
6727 'org-hide-block))
6728 (overlays-at start)))
6729 (if (or (not force) (eq force 'off))
6730 (mapc (lambda (ov)
6731 (when (member ov org-hide-block-overlays)
6732 (setq org-hide-block-overlays
6733 (delq ov org-hide-block-overlays)))
6734 (when (eq (overlay-get ov 'invisible)
6735 'org-hide-block)
6736 (delete-overlay ov)))
6737 (overlays-at start)))
6738 (setq ov (make-overlay start end))
6739 (overlay-put ov 'invisible 'org-hide-block)
6740 ;; make the block accessible to isearch
6741 (overlay-put
6742 ov 'isearch-open-invisible
6743 (lambda (ov)
6744 (when (member ov org-hide-block-overlays)
6745 (setq org-hide-block-overlays
6746 (delq ov org-hide-block-overlays)))
6747 (when (eq (overlay-get ov 'invisible)
6748 'org-hide-block)
6749 (delete-overlay ov))))
6750 (push ov org-hide-block-overlays)))
6751 (error "Not looking at a source block"))))
6753 ;; org-tab-after-check-for-cycling-hook
6754 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6755 ;; Remove overlays when changing major mode
6756 (add-hook 'org-mode-hook
6757 (lambda () (org-add-hook 'change-major-mode-hook
6758 'org-show-block-all 'append 'local)))
6760 ;;; Org-goto
6762 (defvar org-goto-window-configuration nil)
6763 (defvar org-goto-marker nil)
6764 (defvar org-goto-map)
6765 (defun org-goto-map ()
6766 "Set the keymap `org-goto'."
6767 (setq org-goto-map
6768 (let ((map (make-sparse-keymap)))
6769 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
6770 mouse-drag-region universal-argument org-occur))
6771 cmd)
6772 (while (setq cmd (pop cmds))
6773 (substitute-key-definition cmd cmd map global-map)))
6774 (suppress-keymap map)
6775 (org-defkey map "\C-m" 'org-goto-ret)
6776 (org-defkey map [(return)] 'org-goto-ret)
6777 (org-defkey map [(left)] 'org-goto-left)
6778 (org-defkey map [(right)] 'org-goto-right)
6779 (org-defkey map [(control ?g)] 'org-goto-quit)
6780 (org-defkey map "\C-i" 'org-cycle)
6781 (org-defkey map [(tab)] 'org-cycle)
6782 (org-defkey map [(down)] 'outline-next-visible-heading)
6783 (org-defkey map [(up)] 'outline-previous-visible-heading)
6784 (if org-goto-auto-isearch
6785 (if (fboundp 'define-key-after)
6786 (define-key-after map [t] 'org-goto-local-auto-isearch)
6787 nil)
6788 (org-defkey map "q" 'org-goto-quit)
6789 (org-defkey map "n" 'outline-next-visible-heading)
6790 (org-defkey map "p" 'outline-previous-visible-heading)
6791 (org-defkey map "f" 'outline-forward-same-level)
6792 (org-defkey map "b" 'outline-backward-same-level)
6793 (org-defkey map "u" 'outline-up-heading))
6794 (org-defkey map "/" 'org-occur)
6795 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6796 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6797 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6798 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6799 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6800 map)))
6802 (defconst org-goto-help
6803 "Browse buffer copy, to find location or copy text.%s
6804 RET=jump to location C-g=quit and return to previous location
6805 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6807 (defvar org-goto-start-pos) ; dynamically scoped parameter
6809 ;; FIXME: Docstring does not mention both interfaces
6810 (defun org-goto (&optional alternative-interface)
6811 "Look up a different location in the current file, keeping current visibility.
6813 When you want look-up or go to a different location in a
6814 document, the fastest way is often to fold the entire buffer and
6815 then dive into the tree. This method has the disadvantage, that
6816 the previous location will be folded, which may not be what you
6817 want.
6819 This command works around this by showing a copy of the current
6820 buffer in an indirect buffer, in overview mode. You can dive
6821 into the tree in that copy, use org-occur and incremental search
6822 to find a location. When pressing RET or `Q', the command
6823 returns to the original buffer in which the visibility is still
6824 unchanged. After RET it will also jump to the location selected
6825 in the indirect buffer and expose the headline hierarchy above.
6827 With a prefix argument, use the alternative interface: e.g. if
6828 `org-goto-interface' is 'outline use 'outline-path-completion."
6829 (interactive "P")
6830 (org-goto-map)
6831 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6832 (org-refile-use-outline-path t)
6833 (org-refile-target-verify-function nil)
6834 (interface
6835 (if (not alternative-interface)
6836 org-goto-interface
6837 (if (eq org-goto-interface 'outline)
6838 'outline-path-completion
6839 'outline)))
6840 (org-goto-start-pos (point))
6841 (selected-point
6842 (if (eq interface 'outline)
6843 (car (org-get-location (current-buffer) org-goto-help))
6844 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6845 (org-refile-check-position pa)
6846 (nth 3 pa)))))
6847 (if selected-point
6848 (progn
6849 (org-mark-ring-push org-goto-start-pos)
6850 (goto-char selected-point)
6851 (if (or (outline-invisible-p) (org-invisible-p2))
6852 (org-show-context 'org-goto)))
6853 (message "Quit"))))
6855 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6856 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6857 (defvar org-goto-local-auto-isearch-map) ; defined below
6859 (defun org-get-location (buf help)
6860 "Let the user select a location in the Org-mode buffer BUF.
6861 This function uses a recursive edit. It returns the selected position
6862 or nil."
6863 (org-no-popups
6864 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6865 (isearch-hide-immediately nil)
6866 (isearch-search-fun-function
6867 (lambda () 'org-goto-local-search-headings))
6868 (org-goto-selected-point org-goto-exit-command))
6869 (save-excursion
6870 (save-window-excursion
6871 (delete-other-windows)
6872 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6873 (org-pop-to-buffer-same-window
6874 (condition-case nil
6875 (make-indirect-buffer (current-buffer) "*org-goto*")
6876 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6877 (with-output-to-temp-buffer "*Org Help*"
6878 (princ (format help (if org-goto-auto-isearch
6879 " Just type for auto-isearch."
6880 " n/p/f/b/u to navigate, q to quit."))))
6881 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
6882 (setq buffer-read-only nil)
6883 (let ((org-startup-truncated t)
6884 (org-startup-folded nil)
6885 (org-startup-align-all-tables nil))
6886 (org-mode)
6887 (org-overview))
6888 (setq buffer-read-only t)
6889 (if (and (boundp 'org-goto-start-pos)
6890 (integer-or-marker-p org-goto-start-pos))
6891 (let ((org-show-hierarchy-above t)
6892 (org-show-siblings t)
6893 (org-show-following-heading t))
6894 (goto-char org-goto-start-pos)
6895 (and (outline-invisible-p) (org-show-context)))
6896 (goto-char (point-min)))
6897 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6898 (message "Select location and press RET")
6899 (use-local-map org-goto-map)
6900 (recursive-edit)))
6901 (kill-buffer "*org-goto*")
6902 (cons org-goto-selected-point org-goto-exit-command))))
6904 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6905 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6906 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6907 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6909 (defun org-goto-local-search-headings (string bound noerror)
6910 "Search and make sure that any matches are in headlines."
6911 (catch 'return
6912 (while (if isearch-forward
6913 (search-forward string bound noerror)
6914 (search-backward string bound noerror))
6915 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6916 (and (member :headline context)
6917 (not (member :tags context))))
6918 (throw 'return (point))))))
6920 (defun org-goto-local-auto-isearch ()
6921 "Start isearch."
6922 (interactive)
6923 (goto-char (point-min))
6924 (let ((keys (this-command-keys)))
6925 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6926 (isearch-mode t)
6927 (isearch-process-search-char (string-to-char keys)))))
6929 (defun org-goto-ret (&optional arg)
6930 "Finish `org-goto' by going to the new location."
6931 (interactive "P")
6932 (setq org-goto-selected-point (point)
6933 org-goto-exit-command 'return)
6934 (throw 'exit nil))
6936 (defun org-goto-left ()
6937 "Finish `org-goto' by going to the new location."
6938 (interactive)
6939 (if (org-at-heading-p)
6940 (progn
6941 (beginning-of-line 1)
6942 (setq org-goto-selected-point (point)
6943 org-goto-exit-command 'left)
6944 (throw 'exit nil))
6945 (error "Not on a heading")))
6947 (defun org-goto-right ()
6948 "Finish `org-goto' by going to the new location."
6949 (interactive)
6950 (if (org-at-heading-p)
6951 (progn
6952 (setq org-goto-selected-point (point)
6953 org-goto-exit-command 'right)
6954 (throw 'exit nil))
6955 (error "Not on a heading")))
6957 (defun org-goto-quit ()
6958 "Finish `org-goto' without cursor motion."
6959 (interactive)
6960 (setq org-goto-selected-point nil)
6961 (setq org-goto-exit-command 'quit)
6962 (throw 'exit nil))
6964 ;;; Indirect buffer display of subtrees
6966 (defvar org-indirect-dedicated-frame nil
6967 "This is the frame being used for indirect tree display.")
6968 (defvar org-last-indirect-buffer nil)
6970 (defun org-tree-to-indirect-buffer (&optional arg)
6971 "Create indirect buffer and narrow it to current subtree.
6972 With a numerical prefix ARG, go up to this level and then take that tree.
6973 If ARG is negative, go up that many levels.
6975 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6976 indirect buffer previously made with this command, to avoid proliferation of
6977 indirect buffers. However, when you call the command with a \
6978 \\[universal-argument] prefix, or
6979 when `org-indirect-buffer-display' is `new-frame', the last buffer
6980 is kept so that you can work with several indirect buffers at the same time.
6981 If `org-indirect-buffer-display' is `dedicated-frame', the \
6982 \\[universal-argument] prefix also
6983 requests that a new frame be made for the new buffer, so that the dedicated
6984 frame is not changed."
6985 (interactive "P")
6986 (let ((cbuf (current-buffer))
6987 (cwin (selected-window))
6988 (pos (point))
6989 beg end level heading ibuf)
6990 (save-excursion
6991 (org-back-to-heading t)
6992 (when (numberp arg)
6993 (setq level (org-outline-level))
6994 (if (< arg 0) (setq arg (+ level arg)))
6995 (while (> (setq level (org-outline-level)) arg)
6996 (org-up-heading-safe)))
6997 (setq beg (point)
6998 heading (org-get-heading))
6999 (org-end-of-subtree t t)
7000 (if (org-at-heading-p) (backward-char 1))
7001 (setq end (point)))
7002 (if (and (buffer-live-p org-last-indirect-buffer)
7003 (not (eq org-indirect-buffer-display 'new-frame))
7004 (not arg))
7005 (kill-buffer org-last-indirect-buffer))
7006 (setq ibuf (org-get-indirect-buffer cbuf)
7007 org-last-indirect-buffer ibuf)
7008 (cond
7009 ((or (eq org-indirect-buffer-display 'new-frame)
7010 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7011 (select-frame (make-frame))
7012 (delete-other-windows)
7013 (org-pop-to-buffer-same-window ibuf)
7014 (org-set-frame-title heading))
7015 ((eq org-indirect-buffer-display 'dedicated-frame)
7016 (raise-frame
7017 (select-frame (or (and org-indirect-dedicated-frame
7018 (frame-live-p org-indirect-dedicated-frame)
7019 org-indirect-dedicated-frame)
7020 (setq org-indirect-dedicated-frame (make-frame)))))
7021 (delete-other-windows)
7022 (org-pop-to-buffer-same-window ibuf)
7023 (org-set-frame-title (concat "Indirect: " heading)))
7024 ((eq org-indirect-buffer-display 'current-window)
7025 (org-pop-to-buffer-same-window ibuf))
7026 ((eq org-indirect-buffer-display 'other-window)
7027 (pop-to-buffer ibuf))
7028 (t (error "Invalid value")))
7029 (if (featurep 'xemacs)
7030 (save-excursion (org-mode) (turn-on-font-lock)))
7031 (narrow-to-region beg end)
7032 (show-all)
7033 (goto-char pos)
7034 (run-hook-with-args 'org-cycle-hook 'all)
7035 (and (window-live-p cwin) (select-window cwin))))
7037 (defun org-get-indirect-buffer (&optional buffer)
7038 (setq buffer (or buffer (current-buffer)))
7039 (let ((n 1) (base (buffer-name buffer)) bname)
7040 (while (buffer-live-p
7041 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7042 (setq n (1+ n)))
7043 (condition-case nil
7044 (make-indirect-buffer buffer bname 'clone)
7045 (error (make-indirect-buffer buffer bname)))))
7047 (defun org-set-frame-title (title)
7048 "Set the title of the current frame to the string TITLE."
7049 ;; FIXME: how to name a single frame in XEmacs???
7050 (unless (featurep 'xemacs)
7051 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7053 ;;;; Structure editing
7055 ;;; Inserting headlines
7057 (defun org-previous-line-empty-p ()
7058 (save-excursion
7059 (and (not (bobp))
7060 (or (beginning-of-line 0) t)
7061 (save-match-data
7062 (looking-at "[ \t]*$")))))
7064 (defun org-insert-heading (&optional force-heading invisible-ok)
7065 "Insert a new heading or item with same depth at point.
7066 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7067 If point is at the beginning of a headline, insert a sibling before the
7068 current headline. If point is not at the beginning, split the line,
7069 create the new headline with the text in the current line after point
7070 \(but see also the variable `org-M-RET-may-split-line').
7072 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7073 This is important for non-interactive uses of the command."
7074 (interactive "P")
7075 (if (or (= (buffer-size) 0)
7076 (and (not (save-excursion
7077 (and (ignore-errors (org-back-to-heading invisible-ok))
7078 (org-at-heading-p))))
7079 (or force-heading (not (org-in-item-p)))))
7080 (progn
7081 (insert "\n* ")
7082 (run-hooks 'org-insert-heading-hook))
7083 (when (or force-heading (not (org-insert-item)))
7084 (let* ((empty-line-p nil)
7085 (level nil)
7086 (on-heading (org-at-heading-p))
7087 (head (save-excursion
7088 (condition-case nil
7089 (progn
7090 (org-back-to-heading invisible-ok)
7091 (when (and (not on-heading)
7092 (featurep 'org-inlinetask)
7093 (integerp org-inlinetask-min-level)
7094 (>= (length (match-string 0))
7095 org-inlinetask-min-level))
7096 ;; Find a heading level before the inline task
7097 (while (and (setq level (org-up-heading-safe))
7098 (>= level org-inlinetask-min-level)))
7099 (if (org-at-heading-p)
7100 (org-back-to-heading invisible-ok)
7101 (error "This should not happen")))
7102 (setq empty-line-p (org-previous-line-empty-p))
7103 (match-string 0))
7104 (error "*"))))
7105 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7106 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7107 pos hide-previous previous-pos)
7108 (cond
7109 ((and (org-at-heading-p) (bolp)
7110 (or (bobp)
7111 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7112 ;; insert before the current line
7113 (open-line (if blank 2 1)))
7114 ((and (bolp)
7115 (not org-insert-heading-respect-content)
7116 (or (bobp)
7117 (save-excursion
7118 (backward-char 1) (not (outline-invisible-p)))))
7119 ;; insert right here
7120 nil)
7122 ;; somewhere in the line
7123 (save-excursion
7124 (setq previous-pos (point-at-bol))
7125 (end-of-line)
7126 (setq hide-previous (outline-invisible-p)))
7127 (and org-insert-heading-respect-content (org-show-subtree))
7128 (let ((split
7129 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7130 (save-excursion
7131 (let ((p (point)))
7132 (goto-char (point-at-bol))
7133 (and (looking-at org-complex-heading-regexp)
7134 (match-beginning 4)
7135 (> p (match-beginning 4)))))))
7136 tags pos)
7137 (cond
7138 (org-insert-heading-respect-content
7139 (org-end-of-subtree nil t)
7140 (when (featurep 'org-inlinetask)
7141 (while (and (not (eobp))
7142 (looking-at "\\(\\*+\\)[ \t]+")
7143 (>= (length (match-string 1))
7144 org-inlinetask-min-level))
7145 (org-end-of-subtree nil t)))
7146 (or (bolp) (newline))
7147 (or (org-previous-line-empty-p)
7148 (and blank (newline)))
7149 (open-line 1))
7150 ((org-at-heading-p)
7151 (when hide-previous
7152 (show-children)
7153 (org-show-entry))
7154 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7155 (setq tags (and (match-end 2) (match-string 2)))
7156 (and (match-end 1)
7157 (delete-region (match-beginning 1) (match-end 1)))
7158 (setq pos (point-at-bol))
7159 (or split (end-of-line 1))
7160 (delete-horizontal-space)
7161 (if (string-match "\\`\\*+\\'"
7162 (buffer-substring (point-at-bol) (point)))
7163 (insert " "))
7164 (newline (if blank 2 1))
7165 (when tags
7166 (save-excursion
7167 (goto-char pos)
7168 (end-of-line 1)
7169 (insert " " tags)
7170 (org-set-tags nil 'align))))
7172 (or split (end-of-line 1))
7173 (newline (if blank 2 1)))))))
7174 (insert head) (just-one-space)
7175 (setq pos (point))
7176 (end-of-line 1)
7177 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7178 (when (and org-insert-heading-respect-content hide-previous)
7179 (save-excursion
7180 (goto-char previous-pos)
7181 (hide-subtree)))
7182 (run-hooks 'org-insert-heading-hook)))))
7184 (defun org-get-heading (&optional no-tags no-todo)
7185 "Return the heading of the current entry, without the stars.
7186 When NO-TAGS is non-nil, don't include tags.
7187 When NO-TODO is non-nil, don't include TODO keywords."
7188 (save-excursion
7189 (org-back-to-heading t)
7190 (cond
7191 ((and no-tags no-todo)
7192 (looking-at org-complex-heading-regexp)
7193 (match-string 4))
7194 (no-tags
7195 (looking-at (concat org-outline-regexp
7196 "\\(.*?\\)"
7197 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7198 (match-string 1))
7199 (no-todo
7200 (looking-at org-todo-line-regexp)
7201 (match-string 3))
7202 (t (looking-at org-heading-regexp)
7203 (match-string 2)))))
7205 (defun org-heading-components ()
7206 "Return the components of the current heading.
7207 This is a list with the following elements:
7208 - the level as an integer
7209 - the reduced level, different if `org-odd-levels-only' is set.
7210 - the TODO keyword, or nil
7211 - the priority character, like ?A, or nil if no priority is given
7212 - the headline text itself, or the tags string if no headline text
7213 - the tags string, or nil."
7214 (save-excursion
7215 (org-back-to-heading t)
7216 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7217 (list (length (match-string 1))
7218 (org-reduced-level (length (match-string 1)))
7219 (org-match-string-no-properties 2)
7220 (and (match-end 3) (aref (match-string 3) 2))
7221 (org-match-string-no-properties 4)
7222 (org-match-string-no-properties 5)))))
7224 (defun org-get-entry ()
7225 "Get the entry text, after heading, entire subtree."
7226 (save-excursion
7227 (org-back-to-heading t)
7228 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7230 (defun org-insert-heading-after-current ()
7231 "Insert a new heading with same level as current, after current subtree."
7232 (interactive)
7233 (org-back-to-heading)
7234 (org-insert-heading)
7235 (org-move-subtree-down)
7236 (end-of-line 1))
7238 (defun org-insert-heading-respect-content (invisible-ok)
7239 "Insert heading with `org-insert-heading-respect-content' set to t."
7240 (interactive "P")
7241 (let ((org-insert-heading-respect-content t))
7242 (org-insert-heading t invisible-ok)))
7244 (defun org-insert-todo-heading-respect-content (&optional force-state)
7245 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7246 (interactive "P")
7247 (let ((org-insert-heading-respect-content t))
7248 (org-insert-todo-heading force-state t)))
7250 (defun org-insert-todo-heading (arg &optional force-heading)
7251 "Insert a new heading with the same level and TODO state as current heading.
7252 If the heading has no TODO state, or if the state is DONE, use the first
7253 state (TODO by default). Also with prefix arg, force first state."
7254 (interactive "P")
7255 (when (or force-heading (not (org-insert-item 'checkbox)))
7256 (org-insert-heading force-heading)
7257 (save-excursion
7258 (org-back-to-heading)
7259 (outline-previous-heading)
7260 (looking-at org-todo-line-regexp))
7261 (let*
7262 ((new-mark-x
7263 (if (or arg
7264 (not (match-beginning 2))
7265 (member (match-string 2) org-done-keywords))
7266 (car org-todo-keywords-1)
7267 (match-string 2)))
7268 (new-mark
7270 (run-hook-with-args-until-success
7271 'org-todo-get-default-hook new-mark-x nil)
7272 new-mark-x)))
7273 (beginning-of-line 1)
7274 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7275 (if org-treat-insert-todo-heading-as-state-change
7276 (org-todo new-mark)
7277 (insert new-mark " "))))
7278 (when org-provide-todo-statistics
7279 (org-update-parent-todo-statistics))))
7281 (defun org-insert-subheading (arg)
7282 "Insert a new subheading and demote it.
7283 Works for outline headings and for plain lists alike."
7284 (interactive "P")
7285 (org-insert-heading arg)
7286 (cond
7287 ((org-at-heading-p) (org-do-demote))
7288 ((org-at-item-p) (org-indent-item))))
7290 (defun org-insert-todo-subheading (arg)
7291 "Insert a new subheading with TODO keyword or checkbox and demote it.
7292 Works for outline headings and for plain lists alike."
7293 (interactive "P")
7294 (org-insert-todo-heading arg)
7295 (cond
7296 ((org-at-heading-p) (org-do-demote))
7297 ((org-at-item-p) (org-indent-item))))
7299 ;;; Promotion and Demotion
7301 (defvar org-after-demote-entry-hook nil
7302 "Hook run after an entry has been demoted.
7303 The cursor will be at the beginning of the entry.
7304 When a subtree is being demoted, the hook will be called for each node.")
7306 (defvar org-after-promote-entry-hook nil
7307 "Hook run after an entry has been promoted.
7308 The cursor will be at the beginning of the entry.
7309 When a subtree is being promoted, the hook will be called for each node.")
7311 (defun org-promote-subtree ()
7312 "Promote the entire subtree.
7313 See also `org-promote'."
7314 (interactive)
7315 (save-excursion
7316 (org-with-limited-levels (org-map-tree 'org-promote)))
7317 (org-fix-position-after-promote))
7319 (defun org-demote-subtree ()
7320 "Demote the entire subtree. See `org-demote'.
7321 See also `org-promote'."
7322 (interactive)
7323 (save-excursion
7324 (org-with-limited-levels (org-map-tree 'org-demote)))
7325 (org-fix-position-after-promote))
7328 (defun org-do-promote ()
7329 "Promote the current heading higher up the tree.
7330 If the region is active in `transient-mark-mode', promote all headings
7331 in the region."
7332 (interactive)
7333 (save-excursion
7334 (if (org-region-active-p)
7335 (org-map-region 'org-promote (region-beginning) (region-end))
7336 (org-promote)))
7337 (org-fix-position-after-promote))
7339 (defun org-do-demote ()
7340 "Demote the current heading lower down the tree.
7341 If the region is active in `transient-mark-mode', demote all headings
7342 in the region."
7343 (interactive)
7344 (save-excursion
7345 (if (org-region-active-p)
7346 (org-map-region 'org-demote (region-beginning) (region-end))
7347 (org-demote)))
7348 (org-fix-position-after-promote))
7350 (defun org-fix-position-after-promote ()
7351 "Make sure that after pro/demotion cursor position is right."
7352 (let ((pos (point)))
7353 (when (save-excursion
7354 (beginning-of-line 1)
7355 (looking-at org-todo-line-regexp)
7356 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7357 (cond ((eobp) (insert " "))
7358 ((eolp) (insert " "))
7359 ((equal (char-after) ?\ ) (forward-char 1))))))
7361 (defun org-current-level ()
7362 "Return the level of the current entry, or nil if before the first headline.
7363 The level is the number of stars at the beginning of the headline."
7364 (save-excursion
7365 (org-with-limited-levels
7366 (if (ignore-errors (org-back-to-heading t))
7367 (funcall outline-level)))))
7369 (defun org-get-previous-line-level ()
7370 "Return the outline depth of the last headline before the current line.
7371 Returns 0 for the first headline in the buffer, and nil if before the
7372 first headline."
7373 (let ((current-level (org-current-level))
7374 (prev-level (when (> (line-number-at-pos) 1)
7375 (save-excursion
7376 (beginning-of-line 0)
7377 (org-current-level)))))
7378 (cond ((null current-level) nil) ; Before first headline
7379 ((null prev-level) 0) ; At first headline
7380 (prev-level))))
7382 (defun org-reduced-level (l)
7383 "Compute the effective level of a heading.
7384 This takes into account the setting of `org-odd-levels-only'."
7385 (cond
7386 ((zerop l) 0)
7387 (org-odd-levels-only (1+ (floor (/ l 2))))
7388 (t l)))
7390 (defun org-level-increment ()
7391 "Return the number of stars that will be added or removed at a
7392 time to headlines when structure editing, based on the value of
7393 `org-odd-levels-only'."
7394 (if org-odd-levels-only 2 1))
7396 (defun org-get-valid-level (level &optional change)
7397 "Rectify a level change under the influence of `org-odd-levels-only'
7398 LEVEL is a current level, CHANGE is by how much the level should be
7399 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7400 even level numbers will become the next higher odd number."
7401 (if org-odd-levels-only
7402 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7403 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7404 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7405 (max 1 (+ level (or change 0)))))
7407 (if (boundp 'define-obsolete-function-alias)
7408 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7409 (define-obsolete-function-alias 'org-get-legal-level
7410 'org-get-valid-level)
7411 (define-obsolete-function-alias 'org-get-legal-level
7412 'org-get-valid-level "23.1")))
7414 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7415 ;; ̀org-with-limited-levels'
7416 (defun org-promote ()
7417 "Promote the current heading higher up the tree.
7418 If the region is active in `transient-mark-mode', promote 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 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7425 (diff (abs (- level (length up-head) -1))))
7426 (cond ((and (= level 1) org-called-with-limited-levels
7427 org-allow-promoting-top-level-subtree)
7428 (replace-match "# " nil t))
7429 ((= level 1)
7430 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7431 (t (replace-match up-head nil t)))
7432 ;; Fixup tag positioning
7433 (unless (= level 1)
7434 (and org-auto-align-tags (org-set-tags nil t))
7435 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7436 (run-hooks 'org-after-promote-entry-hook)))
7438 (defun org-demote ()
7439 "Demote the current heading lower down the tree.
7440 If the region is active in `transient-mark-mode', demote all headings
7441 in the region."
7442 (org-back-to-heading t)
7443 (let* ((level (save-match-data (funcall outline-level)))
7444 (after-change-functions (remove 'flyspell-after-change-function
7445 after-change-functions))
7446 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7447 (diff (abs (- level (length down-head) -1))))
7448 (replace-match down-head nil t)
7449 ;; Fixup tag positioning
7450 (and org-auto-align-tags (org-set-tags nil t))
7451 (if org-adapt-indentation (org-fixup-indentation diff))
7452 (run-hooks 'org-after-demote-entry-hook)))
7454 (defun org-cycle-level ()
7455 "Cycle the level of an empty headline through possible states.
7456 This goes first to child, then to parent, level, then up the hierarchy.
7457 After top level, it switches back to sibling level."
7458 (interactive)
7459 (let ((org-adapt-indentation nil))
7460 (when (org-point-at-end-of-empty-headline)
7461 (setq this-command 'org-cycle-level) ; Only needed for caching
7462 (let ((cur-level (org-current-level))
7463 (prev-level (org-get-previous-line-level)))
7464 (cond
7465 ;; If first headline in file, promote to top-level.
7466 ((= prev-level 0)
7467 (loop repeat (/ (- cur-level 1) (org-level-increment))
7468 do (org-do-promote)))
7469 ;; If same level as prev, demote one.
7470 ((= prev-level cur-level)
7471 (org-do-demote))
7472 ;; If parent is top-level, promote to top level if not already.
7473 ((= prev-level 1)
7474 (loop repeat (/ (- cur-level 1) (org-level-increment))
7475 do (org-do-promote)))
7476 ;; If top-level, return to prev-level.
7477 ((= cur-level 1)
7478 (loop repeat (/ (- prev-level 1) (org-level-increment))
7479 do (org-do-demote)))
7480 ;; If less than prev-level, promote one.
7481 ((< cur-level prev-level)
7482 (org-do-promote))
7483 ;; If deeper than prev-level, promote until higher than
7484 ;; prev-level.
7485 ((> cur-level prev-level)
7486 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7487 do (org-do-promote))))
7488 t))))
7490 (defun org-map-tree (fun)
7491 "Call FUN for every heading underneath the current one."
7492 (org-back-to-heading)
7493 (let ((level (funcall outline-level)))
7494 (save-excursion
7495 (funcall fun)
7496 (while (and (progn
7497 (outline-next-heading)
7498 (> (funcall outline-level) level))
7499 (not (eobp)))
7500 (funcall fun)))))
7502 (defun org-map-region (fun beg end)
7503 "Call FUN for every heading between BEG and END."
7504 (let ((org-ignore-region t))
7505 (save-excursion
7506 (setq end (copy-marker end))
7507 (goto-char beg)
7508 (if (and (re-search-forward org-outline-regexp-bol nil t)
7509 (< (point) end))
7510 (funcall fun))
7511 (while (and (progn
7512 (outline-next-heading)
7513 (< (point) end))
7514 (not (eobp)))
7515 (funcall fun)))))
7517 (defvar org-property-end-re) ; silence byte-compiler
7518 (defun org-fixup-indentation (diff)
7519 "Change the indentation in the current entry by DIFF.
7520 However, if any line in the current entry has no indentation, or if it
7521 would end up with no indentation after the change, nothing at all is done."
7522 (save-excursion
7523 (let ((end (save-excursion (outline-next-heading)
7524 (point-marker)))
7525 (prohibit (if (> diff 0)
7526 "^\\S-"
7527 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7528 col)
7529 (unless (save-excursion (end-of-line 1)
7530 (re-search-forward prohibit end t))
7531 (while (and (< (point) end)
7532 (re-search-forward "^[ \t]+" end t))
7533 (goto-char (match-end 0))
7534 (setq col (current-column))
7535 (if (< diff 0) (replace-match ""))
7536 (org-indent-to-column (+ diff col))))
7537 (move-marker end nil))))
7539 (defun org-convert-to-odd-levels ()
7540 "Convert an org-mode file with all levels allowed to one with odd levels.
7541 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7542 level 5 etc."
7543 (interactive)
7544 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7545 (let ((outline-level 'org-outline-level)
7546 (org-odd-levels-only nil) n)
7547 (save-excursion
7548 (goto-char (point-min))
7549 (while (re-search-forward "^\\*\\*+ " nil t)
7550 (setq n (- (length (match-string 0)) 2))
7551 (while (>= (setq n (1- n)) 0)
7552 (org-demote))
7553 (end-of-line 1))))))
7555 (defun org-convert-to-oddeven-levels ()
7556 "Convert an org-mode file with only odd levels to one with odd/even levels.
7557 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7558 file contains a section with an even level, conversion would
7559 destroy the structure of the file. An error is signaled in this
7560 case."
7561 (interactive)
7562 (goto-char (point-min))
7563 ;; First check if there are no even levels
7564 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7565 (org-show-context t)
7566 (error "Not all levels are odd in this file. Conversion not possible"))
7567 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7568 (let ((outline-regexp org-outline-regexp)
7569 (outline-level 'org-outline-level)
7570 (org-odd-levels-only nil) n)
7571 (save-excursion
7572 (goto-char (point-min))
7573 (while (re-search-forward "^\\*\\*+ " nil t)
7574 (setq n (/ (1- (length (match-string 0))) 2))
7575 (while (>= (setq n (1- n)) 0)
7576 (org-promote))
7577 (end-of-line 1))))))
7579 (defun org-tr-level (n)
7580 "Make N odd if required."
7581 (if org-odd-levels-only (1+ (/ n 2)) n))
7583 ;;; Vertical tree motion, cutting and pasting of subtrees
7585 (defun org-move-subtree-up (&optional arg)
7586 "Move the current subtree up past ARG headlines of the same level."
7587 (interactive "p")
7588 (org-move-subtree-down (- (prefix-numeric-value arg))))
7590 (defun org-move-subtree-down (&optional arg)
7591 "Move the current subtree down past ARG headlines of the same level."
7592 (interactive "p")
7593 (setq arg (prefix-numeric-value arg))
7594 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7595 'org-get-last-sibling))
7596 (ins-point (make-marker))
7597 (cnt (abs arg))
7598 (col (current-column))
7599 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7600 ;; Select the tree
7601 (org-back-to-heading)
7602 (setq beg0 (point))
7603 (save-excursion
7604 (setq ne-beg (org-back-over-empty-lines))
7605 (setq beg (point)))
7606 (save-match-data
7607 (save-excursion (outline-end-of-heading)
7608 (setq folded (outline-invisible-p)))
7609 (outline-end-of-subtree))
7610 (outline-next-heading)
7611 (setq ne-end (org-back-over-empty-lines))
7612 (setq end (point))
7613 (goto-char beg0)
7614 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7615 ;; include less whitespace
7616 (save-excursion
7617 (goto-char beg)
7618 (forward-line (- ne-beg ne-end))
7619 (setq beg (point))))
7620 ;; Find insertion point, with error handling
7621 (while (> cnt 0)
7622 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7623 (progn (goto-char beg0)
7624 (error "Cannot move past superior level or buffer limit")))
7625 (setq cnt (1- cnt)))
7626 (if (> arg 0)
7627 ;; Moving forward - still need to move over subtree
7628 (progn (org-end-of-subtree t t)
7629 (save-excursion
7630 (org-back-over-empty-lines)
7631 (or (bolp) (newline)))))
7632 (setq ne-ins (org-back-over-empty-lines))
7633 (move-marker ins-point (point))
7634 (setq txt (buffer-substring beg end))
7635 (org-save-markers-in-region beg end)
7636 (delete-region beg end)
7637 (org-remove-empty-overlays-at beg)
7638 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7639 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7640 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7641 (let ((bbb (point)))
7642 (insert-before-markers txt)
7643 (org-reinstall-markers-in-region bbb)
7644 (move-marker ins-point bbb))
7645 (or (bolp) (insert "\n"))
7646 (setq ins-end (point))
7647 (goto-char ins-point)
7648 (org-skip-whitespace)
7649 (when (and (< arg 0)
7650 (org-first-sibling-p)
7651 (> ne-ins ne-beg))
7652 ;; Move whitespace back to beginning
7653 (save-excursion
7654 (goto-char ins-end)
7655 (let ((kill-whole-line t))
7656 (kill-line (- ne-ins ne-beg)) (point)))
7657 (insert (make-string (- ne-ins ne-beg) ?\n)))
7658 (move-marker ins-point nil)
7659 (if folded
7660 (hide-subtree)
7661 (org-show-entry)
7662 (show-children)
7663 (org-cycle-hide-drawers 'children))
7664 (org-clean-visibility-after-subtree-move)
7665 ;; move back to the initial column we were at
7666 (move-to-column col)))
7668 (defvar org-subtree-clip ""
7669 "Clipboard for cut and paste of subtrees.
7670 This is actually only a copy of the kill, because we use the normal kill
7671 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7673 (defvar org-subtree-clip-folded nil
7674 "Was the last copied subtree folded?
7675 This is used to fold the tree back after pasting.")
7677 (defun org-cut-subtree (&optional n)
7678 "Cut the current subtree into the clipboard.
7679 With prefix arg N, cut this many sequential subtrees.
7680 This is a short-hand for marking the subtree and then cutting it."
7681 (interactive "p")
7682 (org-copy-subtree n 'cut))
7684 (defun org-copy-subtree (&optional n cut force-store-markers)
7685 "Cut the current subtree into the clipboard.
7686 With prefix arg N, cut this many sequential subtrees.
7687 This is a short-hand for marking the subtree and then copying it.
7688 If CUT is non-nil, actually cut the subtree.
7689 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7690 of some markers in the region, even if CUT is non-nil. This is
7691 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7692 (interactive "p")
7693 (let (beg end folded (beg0 (point)))
7694 (if (org-called-interactively-p 'any)
7695 (org-back-to-heading nil) ; take what looks like a subtree
7696 (org-back-to-heading t)) ; take what is really there
7697 (setq beg (point))
7698 (skip-chars-forward " \t\r\n")
7699 (save-match-data
7700 (save-excursion (outline-end-of-heading)
7701 (setq folded (outline-invisible-p)))
7702 (condition-case nil
7703 (org-forward-heading-same-level (1- n) t)
7704 (error nil))
7705 (org-end-of-subtree t t))
7706 (setq end (point))
7707 (goto-char beg0)
7708 (when (> end beg)
7709 (setq org-subtree-clip-folded folded)
7710 (when (or cut force-store-markers)
7711 (org-save-markers-in-region beg end))
7712 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7713 (setq org-subtree-clip (current-kill 0))
7714 (message "%s: Subtree(s) with %d characters"
7715 (if cut "Cut" "Copied")
7716 (length org-subtree-clip)))))
7718 (defun org-paste-subtree (&optional level tree for-yank)
7719 "Paste the clipboard as a subtree, with modification of headline level.
7720 The entire subtree is promoted or demoted in order to match a new headline
7721 level.
7723 If the cursor is at the beginning of a headline, the same level as
7724 that headline is used to paste the tree
7726 If not, the new level is derived from the *visible* headings
7727 before and after the insertion point, and taken to be the inferior headline
7728 level of the two. So if the previous visible heading is level 3 and the
7729 next is level 4 (or vice versa), level 4 will be used for insertion.
7730 This makes sure that the subtree remains an independent subtree and does
7731 not swallow low level entries.
7733 You can also force a different level, either by using a numeric prefix
7734 argument, or by inserting the heading marker by hand. For example, if the
7735 cursor is after \"*****\", then the tree will be shifted to level 5.
7737 If optional TREE is given, use this text instead of the kill ring.
7739 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7740 move back over whitespace before inserting, and move point to the end of
7741 the inserted text when done."
7742 (interactive "P")
7743 (setq tree (or tree (and kill-ring (current-kill 0))))
7744 (unless (org-kill-is-subtree-p tree)
7745 (error "%s"
7746 (substitute-command-keys
7747 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7748 (org-with-limited-levels
7749 (let* ((visp (not (outline-invisible-p)))
7750 (txt tree)
7751 (^re_ "\\(\\*+\\)[ \t]*")
7752 (old-level (if (string-match org-outline-regexp-bol txt)
7753 (- (match-end 0) (match-beginning 0) 1)
7754 -1))
7755 (force-level (cond (level (prefix-numeric-value level))
7756 ((and (looking-at "[ \t]*$")
7757 (string-match
7758 "^\\*+$" (buffer-substring
7759 (point-at-bol) (point))))
7760 (- (match-end 1) (match-beginning 1)))
7761 ((and (bolp)
7762 (looking-at org-outline-regexp))
7763 (- (match-end 0) (point) 1))))
7764 (previous-level (save-excursion
7765 (condition-case nil
7766 (progn
7767 (outline-previous-visible-heading 1)
7768 (if (looking-at ^re_)
7769 (- (match-end 0) (match-beginning 0) 1)
7771 (error 1))))
7772 (next-level (save-excursion
7773 (condition-case nil
7774 (progn
7775 (or (looking-at org-outline-regexp)
7776 (outline-next-visible-heading 1))
7777 (if (looking-at ^re_)
7778 (- (match-end 0) (match-beginning 0) 1)
7780 (error 1))))
7781 (new-level (or force-level (max previous-level next-level)))
7782 (shift (if (or (= old-level -1)
7783 (= new-level -1)
7784 (= old-level new-level))
7786 (- new-level old-level)))
7787 (delta (if (> shift 0) -1 1))
7788 (func (if (> shift 0) 'org-demote 'org-promote))
7789 (org-odd-levels-only nil)
7790 beg end newend)
7791 ;; Remove the forced level indicator
7792 (if force-level
7793 (delete-region (point-at-bol) (point)))
7794 ;; Paste
7795 (beginning-of-line (if (bolp) 1 2))
7796 (setq beg (point))
7797 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7798 (insert-before-markers txt)
7799 (unless (string-match "\n\\'" txt) (insert "\n"))
7800 (setq newend (point))
7801 (org-reinstall-markers-in-region beg)
7802 (setq end (point))
7803 (goto-char beg)
7804 (skip-chars-forward " \t\n\r")
7805 (setq beg (point))
7806 (if (and (outline-invisible-p) visp)
7807 (save-excursion (outline-show-heading)))
7808 ;; Shift if necessary
7809 (unless (= shift 0)
7810 (save-restriction
7811 (narrow-to-region beg end)
7812 (while (not (= shift 0))
7813 (org-map-region func (point-min) (point-max))
7814 (setq shift (+ delta shift)))
7815 (goto-char (point-min))
7816 (setq newend (point-max))))
7817 (when (or (org-called-interactively-p 'interactive) for-yank)
7818 (message "Clipboard pasted as level %d subtree" new-level))
7819 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7820 kill-ring
7821 (eq org-subtree-clip (current-kill 0))
7822 org-subtree-clip-folded)
7823 ;; The tree was folded before it was killed/copied
7824 (hide-subtree))
7825 (and for-yank (goto-char newend)))))
7827 (defun org-kill-is-subtree-p (&optional txt)
7828 "Check if the current kill is an outline subtree, or a set of trees.
7829 Returns nil if kill does not start with a headline, or if the first
7830 headline level is not the largest headline level in the tree.
7831 So this will actually accept several entries of equal levels as well,
7832 which is OK for `org-paste-subtree'.
7833 If optional TXT is given, check this string instead of the current kill."
7834 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7835 (re (org-get-limited-outline-regexp))
7836 (^re (concat "^" re))
7837 (start-level (and kill
7838 (string-match
7839 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7840 kill)
7841 (- (match-end 2) (match-beginning 2) 1)))
7842 (start (1+ (or (match-beginning 2) -1))))
7843 (if (not start-level)
7844 (progn
7845 nil) ;; does not even start with a heading
7846 (catch 'exit
7847 (while (setq start (string-match ^re kill (1+ start)))
7848 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7849 (throw 'exit nil)))
7850 t))))
7852 (defvar org-markers-to-move nil
7853 "Markers that should be moved with a cut-and-paste operation.
7854 Those markers are stored together with their positions relative to
7855 the start of the region.")
7857 (defun org-save-markers-in-region (beg end)
7858 "Check markers in region.
7859 If these markers are between BEG and END, record their position relative
7860 to BEG, so that after moving the block of text, we can put the markers back
7861 into place.
7862 This function gets called just before an entry or tree gets cut from the
7863 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7864 called immediately, to move the markers with the entries."
7865 (setq org-markers-to-move nil)
7866 (when (featurep 'org-clock)
7867 (org-clock-save-markers-for-cut-and-paste beg end))
7868 (when (featurep 'org-agenda)
7869 (org-agenda-save-markers-for-cut-and-paste beg end)))
7871 (defun org-check-and-save-marker (marker beg end)
7872 "Check if MARKER is between BEG and END.
7873 If yes, remember the marker and the distance to BEG."
7874 (when (and (marker-buffer marker)
7875 (equal (marker-buffer marker) (current-buffer)))
7876 (if (and (>= marker beg) (< marker end))
7877 (push (cons marker (- marker beg)) org-markers-to-move))))
7879 (defun org-reinstall-markers-in-region (beg)
7880 "Move all remembered markers to their position relative to BEG."
7881 (mapc (lambda (x)
7882 (move-marker (car x) (+ beg (cdr x))))
7883 org-markers-to-move)
7884 (setq org-markers-to-move nil))
7886 (defun org-narrow-to-subtree ()
7887 "Narrow buffer to the current subtree."
7888 (interactive)
7889 (save-excursion
7890 (save-match-data
7891 (org-with-limited-levels
7892 (narrow-to-region
7893 (progn (org-back-to-heading t) (point))
7894 (progn (org-end-of-subtree t t)
7895 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7896 (point)))))))
7898 (defun org-narrow-to-block ()
7899 "Narrow buffer to the current block."
7900 (interactive)
7901 (let* ((case-fold-search t)
7902 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7903 "^[ \t]*#\\+end_.*")))
7904 (if blockp
7905 (narrow-to-region (car blockp) (cdr blockp))
7906 (error "Not in a block"))))
7908 (eval-when-compile
7909 (defvar org-property-drawer-re))
7911 (defvar org-property-start-re) ;; defined below
7912 (defun org-clone-subtree-with-time-shift (n &optional shift)
7913 "Clone the task (subtree) at point N times.
7914 The clones will be inserted as siblings.
7916 In interactive use, the user will be prompted for the number of
7917 clones to be produced, and for a time SHIFT, which may be a
7918 repeater as used in time stamps, for example `+3d'.
7920 When a valid repeater is given and the entry contains any time
7921 stamps, the clones will become a sequence in time, with time
7922 stamps in the subtree shifted for each clone produced. If SHIFT
7923 is nil or the empty string, time stamps will be left alone. The
7924 ID property of the original subtree is removed.
7926 If the original subtree did contain time stamps with a repeater,
7927 the following will happen:
7928 - the repeater will be removed in each clone
7929 - an additional clone will be produced, with the current, unshifted
7930 date(s) in the entry.
7931 - the original entry will be placed *after* all the clones, with
7932 repeater intact.
7933 - the start days in the repeater in the original entry will be shifted
7934 to past the last clone.
7935 In this way you can spell out a number of instances of a repeating task,
7936 and still retain the repeater to cover future instances of the task."
7937 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7938 (let (beg end template task idprop
7939 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7940 (drawer-re org-drawer-regexp))
7941 (if (not (and (integerp n) (> n 0)))
7942 (error "Invalid number of replications %s" n))
7943 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7944 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
7945 shift)))
7946 (error "Invalid shift specification %s" shift))
7947 (when doshift
7948 (setq shift-n (string-to-number (match-string 1 shift))
7949 shift-what (cdr (assoc (match-string 2 shift)
7950 '(("d" . day) ("w" . week)
7951 ("m" . month) ("y" . year))))))
7952 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7953 (setq nmin 1 nmax n)
7954 (org-back-to-heading t)
7955 (setq beg (point))
7956 (setq idprop (org-entry-get nil "ID"))
7957 (org-end-of-subtree t t)
7958 (or (bolp) (insert "\n"))
7959 (setq end (point))
7960 (setq template (buffer-substring beg end))
7961 (when (and doshift
7962 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
7963 (delete-region beg end)
7964 (setq end beg)
7965 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7966 (goto-char end)
7967 (loop for n from nmin to nmax do
7968 ;; prepare clone
7969 (with-temp-buffer
7970 (insert template)
7971 (org-mode)
7972 (goto-char (point-min))
7973 (org-show-subtree)
7974 (and idprop (if org-clone-delete-id
7975 (org-entry-delete nil "ID")
7976 (org-id-get-create t)))
7977 (unless (= n 0)
7978 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
7979 (kill-whole-line))
7980 (goto-char (point-min))
7981 (while (re-search-forward drawer-re nil t)
7982 (mapc (lambda (d)
7983 (org-remove-empty-drawer-at d (point))) org-drawers)))
7984 (goto-char (point-min))
7985 (when doshift
7986 (while (re-search-forward org-ts-regexp-both nil t)
7987 (org-timestamp-change (* n shift-n) shift-what))
7988 (unless (= n n-no-remove)
7989 (goto-char (point-min))
7990 (while (re-search-forward org-ts-regexp nil t)
7991 (save-excursion
7992 (goto-char (match-beginning 0))
7993 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
7994 (delete-region (match-beginning 1) (match-end 1)))))))
7995 (setq task (buffer-string)))
7996 (insert task))
7997 (goto-char beg)))
7999 ;;; Outline Sorting
8001 (defun org-sort (with-case)
8002 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8003 Optional argument WITH-CASE means sort case-sensitively."
8004 (interactive "P")
8005 (cond
8006 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8007 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8009 (org-call-with-arg 'org-sort-entries with-case))))
8011 (defun org-sort-remove-invisible (s)
8012 (remove-text-properties 0 (length s) org-rm-props s)
8013 (while (string-match org-bracket-link-regexp s)
8014 (setq s (replace-match (if (match-end 2)
8015 (match-string 3 s)
8016 (match-string 1 s)) t t s)))
8019 (defvar org-priority-regexp) ; defined later in the file
8021 (defvar org-after-sorting-entries-or-items-hook nil
8022 "Hook that is run after a bunch of entries or items have been sorted.
8023 When children are sorted, the cursor is in the parent line when this
8024 hook gets called. When a region or a plain list is sorted, the cursor
8025 will be in the first entry of the sorted region/list.")
8027 (defun org-sort-entries
8028 (&optional with-case sorting-type getkey-func compare-func property)
8029 "Sort entries on a certain level of an outline tree.
8030 If there is an active region, the entries in the region are sorted.
8031 Else, if the cursor is before the first entry, sort the top-level items.
8032 Else, the children of the entry at point are sorted.
8034 Sorting can be alphabetically, numerically, by date/time as given by
8035 a time stamp, by a property or by priority.
8037 The command prompts for the sorting type unless it has been given to the
8038 function through the SORTING-TYPE argument, which needs to be a character,
8039 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8040 precise meaning of each character:
8042 n Numerically, by converting the beginning of the entry/item to a number.
8043 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8044 o By order of TODO keywords.
8045 t By date/time, either the first active time stamp in the entry, or, if
8046 none exist, by the first inactive one.
8047 s By the scheduled date/time.
8048 d By deadline date/time.
8049 c By creation time, which is assumed to be the first inactive time stamp
8050 at the beginning of a line.
8051 p By priority according to the cookie.
8052 r By the value of a property.
8054 Capital letters will reverse the sort order.
8056 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8057 called with point at the beginning of the record. It must return either
8058 a string or a number that should serve as the sorting key for that record.
8060 Comparing entries ignores case by default. However, with an optional argument
8061 WITH-CASE, the sorting considers case as well."
8062 (interactive "P")
8063 (let ((case-func (if with-case 'identity 'downcase))
8064 (cmstr
8065 ;; The clock marker is lost when using `sort-subr', let's
8066 ;; store the clocking string.
8067 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8068 (save-excursion
8069 (goto-char org-clock-marker)
8070 (looking-back "^.*") (match-string-no-properties 0))))
8071 start beg end stars re re2
8072 txt what tmp)
8073 ;; Find beginning and end of region to sort
8074 (cond
8075 ((org-region-active-p)
8076 ;; we will sort the region
8077 (setq end (region-end)
8078 what "region")
8079 (goto-char (region-beginning))
8080 (if (not (org-at-heading-p)) (outline-next-heading))
8081 (setq start (point)))
8082 ((or (org-at-heading-p)
8083 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8084 ;; we will sort the children of the current headline
8085 (org-back-to-heading)
8086 (setq start (point)
8087 end (progn (org-end-of-subtree t t)
8088 (or (bolp) (insert "\n"))
8089 (org-back-over-empty-lines)
8090 (point))
8091 what "children")
8092 (goto-char start)
8093 (show-subtree)
8094 (outline-next-heading))
8096 ;; we will sort the top-level entries in this file
8097 (goto-char (point-min))
8098 (or (org-at-heading-p) (outline-next-heading))
8099 (setq start (point))
8100 (goto-char (point-max))
8101 (beginning-of-line 1)
8102 (when (looking-at ".*?\\S-")
8103 ;; File ends in a non-white line
8104 (end-of-line 1)
8105 (insert "\n"))
8106 (setq end (point-max))
8107 (setq what "top-level")
8108 (goto-char start)
8109 (show-all)))
8111 (setq beg (point))
8112 (if (>= beg end) (error "Nothing to sort"))
8114 (looking-at "\\(\\*+\\)")
8115 (setq stars (match-string 1)
8116 re (concat "^" (regexp-quote stars) " +")
8117 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8118 txt (buffer-substring beg end))
8119 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8120 (if (and (not (equal stars "*")) (string-match re2 txt))
8121 (error "Region to sort contains a level above the first entry"))
8123 (unless sorting-type
8124 (message
8125 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8126 [t]ime [s]cheduled [d]eadline [c]reated
8127 A/N/P/R/O/F/T/S/D/C means reversed:"
8128 what)
8129 (setq sorting-type (read-char-exclusive))
8131 (and (= (downcase sorting-type) ?f)
8132 (setq getkey-func
8133 (org-icompleting-read "Sort using function: "
8134 obarray 'fboundp t nil nil))
8135 (setq getkey-func (intern getkey-func)))
8137 (and (= (downcase sorting-type) ?r)
8138 (setq property
8139 (org-icompleting-read "Property: "
8140 (mapcar 'list (org-buffer-property-keys t))
8141 nil t))))
8143 (message "Sorting entries...")
8145 (save-restriction
8146 (narrow-to-region start end)
8147 (let ((dcst (downcase sorting-type))
8148 (case-fold-search nil)
8149 (now (current-time)))
8150 (sort-subr
8151 (/= dcst sorting-type)
8152 ;; This function moves to the beginning character of the "record" to
8153 ;; be sorted.
8154 (lambda nil
8155 (if (re-search-forward re nil t)
8156 (goto-char (match-beginning 0))
8157 (goto-char (point-max))))
8158 ;; This function moves to the last character of the "record" being
8159 ;; sorted.
8160 (lambda nil
8161 (save-match-data
8162 (condition-case nil
8163 (outline-forward-same-level 1)
8164 (error
8165 (goto-char (point-max))))))
8166 ;; This function returns the value that gets sorted against.
8167 (lambda nil
8168 (cond
8169 ((= dcst ?n)
8170 (if (looking-at org-complex-heading-regexp)
8171 (string-to-number (match-string 4))
8172 nil))
8173 ((= dcst ?a)
8174 (if (looking-at org-complex-heading-regexp)
8175 (funcall case-func (match-string 4))
8176 nil))
8177 ((= dcst ?t)
8178 (let ((end (save-excursion (outline-next-heading) (point))))
8179 (if (or (re-search-forward org-ts-regexp end t)
8180 (re-search-forward org-ts-regexp-both end t))
8181 (org-time-string-to-seconds (match-string 0))
8182 (org-float-time now))))
8183 ((= dcst ?c)
8184 (let ((end (save-excursion (outline-next-heading) (point))))
8185 (if (re-search-forward
8186 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8187 end t)
8188 (org-time-string-to-seconds (match-string 0))
8189 (org-float-time now))))
8190 ((= dcst ?s)
8191 (let ((end (save-excursion (outline-next-heading) (point))))
8192 (if (re-search-forward org-scheduled-time-regexp end t)
8193 (org-time-string-to-seconds (match-string 1))
8194 (org-float-time now))))
8195 ((= dcst ?d)
8196 (let ((end (save-excursion (outline-next-heading) (point))))
8197 (if (re-search-forward org-deadline-time-regexp end t)
8198 (org-time-string-to-seconds (match-string 1))
8199 (org-float-time now))))
8200 ((= dcst ?p)
8201 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8202 (string-to-char (match-string 2))
8203 org-default-priority))
8204 ((= dcst ?r)
8205 (or (org-entry-get nil property) ""))
8206 ((= dcst ?o)
8207 (if (looking-at org-complex-heading-regexp)
8208 (- 9999 (length (member (match-string 2)
8209 org-todo-keywords-1)))))
8210 ((= dcst ?f)
8211 (if getkey-func
8212 (progn
8213 (setq tmp (funcall getkey-func))
8214 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8215 tmp)
8216 (error "Invalid key function `%s'" getkey-func)))
8217 (t (error "Invalid sorting type `%c'" sorting-type))))
8219 (cond
8220 ((= dcst ?a) 'string<)
8221 ((= dcst ?f) compare-func)
8222 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8223 (run-hooks 'org-after-sorting-entries-or-items-hook)
8224 ;; Reset the clock marker if needed
8225 (when cmstr
8226 (save-excursion
8227 (goto-char start)
8228 (search-forward cmstr nil t)
8229 (move-marker org-clock-marker (point))))
8230 (message "Sorting entries...done")))
8232 (defun org-do-sort (table what &optional with-case sorting-type)
8233 "Sort TABLE of WHAT according to SORTING-TYPE.
8234 The user will be prompted for the SORTING-TYPE if the call to this
8235 function does not specify it. WHAT is only for the prompt, to indicate
8236 what is being sorted. The sorting key will be extracted from
8237 the car of the elements of the table.
8238 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8239 (unless sorting-type
8240 (message
8241 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8242 what)
8243 (setq sorting-type (read-char-exclusive)))
8244 (let ((dcst (downcase sorting-type))
8245 extractfun comparefun)
8246 ;; Define the appropriate functions
8247 (cond
8248 ((= dcst ?n)
8249 (setq extractfun 'string-to-number
8250 comparefun (if (= dcst sorting-type) '< '>)))
8251 ((= dcst ?a)
8252 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8253 (lambda(x) (downcase (org-sort-remove-invisible x))))
8254 comparefun (if (= dcst sorting-type)
8255 'string<
8256 (lambda (a b) (and (not (string< a b))
8257 (not (string= a b)))))))
8258 ((= dcst ?t)
8259 (setq extractfun
8260 (lambda (x)
8261 (if (or (string-match org-ts-regexp x)
8262 (string-match org-ts-regexp-both x))
8263 (org-float-time
8264 (org-time-string-to-time (match-string 0 x)))
8266 comparefun (if (= dcst sorting-type) '< '>)))
8267 (t (error "Invalid sorting type `%c'" sorting-type)))
8269 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8270 table)
8271 (lambda (a b) (funcall comparefun (car a) (car b))))))
8274 ;;; The orgstruct minor mode
8276 ;; Define a minor mode which can be used in other modes in order to
8277 ;; integrate the org-mode structure editing commands.
8279 ;; This is really a hack, because the org-mode structure commands use
8280 ;; keys which normally belong to the major mode. Here is how it
8281 ;; works: The minor mode defines all the keys necessary to operate the
8282 ;; structure commands, but wraps the commands into a function which
8283 ;; tests if the cursor is currently at a headline or a plain list
8284 ;; item. If that is the case, the structure command is used,
8285 ;; temporarily setting many Org-mode variables like regular
8286 ;; expressions for filling etc. However, when any of those keys is
8287 ;; used at a different location, function uses `key-binding' to look
8288 ;; up if the key has an associated command in another currently active
8289 ;; keymap (minor modes, major mode, global), and executes that
8290 ;; command. There might be problems if any of the keys is otherwise
8291 ;; used as a prefix key.
8293 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8294 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8295 ;; addresses this by checking explicitly for both bindings.
8297 (defvar orgstruct-mode-map (make-sparse-keymap)
8298 "Keymap for the minor `orgstruct-mode'.")
8300 (defvar org-local-vars nil
8301 "List of local variables, for use by `orgstruct-mode'.")
8303 ;;;###autoload
8304 (define-minor-mode orgstruct-mode
8305 "Toggle the minor mode `orgstruct-mode'.
8306 This mode is for using Org-mode structure commands in other
8307 modes. The following keys behave as if Org-mode were active, if
8308 the cursor is on a headline, or on a plain list item (both as
8309 defined by Org-mode).
8311 M-up Move entry/item up
8312 M-down Move entry/item down
8313 M-left Promote
8314 M-right Demote
8315 M-S-up Move entry/item up
8316 M-S-down Move entry/item down
8317 M-S-left Promote subtree
8318 M-S-right Demote subtree
8319 M-q Fill paragraph and items like in Org-mode
8320 C-c ^ Sort entries
8321 C-c - Cycle list bullet
8322 TAB Cycle item visibility
8323 M-RET Insert new heading/item
8324 S-M-RET Insert new TODO heading / Checkbox item
8325 C-c C-c Set tags / toggle checkbox"
8326 nil " OrgStruct" nil
8327 (org-load-modules-maybe)
8328 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8330 ;;;###autoload
8331 (defun turn-on-orgstruct ()
8332 "Unconditionally turn on `orgstruct-mode'."
8333 (orgstruct-mode 1))
8335 (defvar org-fb-vars nil)
8336 (make-variable-buffer-local 'org-fb-vars)
8337 (defun orgstruct++-mode (&optional arg)
8338 "Toggle `orgstruct-mode', the enhanced version of it.
8339 In addition to setting orgstruct-mode, this also exports all
8340 indentation and autofilling variables from org-mode into the
8341 buffer. It will also recognize item context in multiline items."
8342 (interactive "P")
8343 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8344 (if (< arg 1)
8345 (progn (orgstruct-mode -1)
8346 (mapc (lambda(v)
8347 (org-set-local (car v)
8348 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8349 org-fb-vars))
8350 (orgstruct-mode 1)
8351 (setq org-fb-vars nil)
8352 (let (var val)
8353 (mapc
8354 (lambda (x)
8355 (when (string-match
8356 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8357 (symbol-name (car x)))
8358 (setq var (car x) val (nth 1 x))
8359 (push (list var `(quote ,(eval var))) org-fb-vars)
8360 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8361 org-local-vars)
8362 (org-set-local 'orgstruct-is-++ t))))
8364 (defvar orgstruct-is-++ nil
8365 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8366 (make-variable-buffer-local 'orgstruct-is-++)
8368 ;;;###autoload
8369 (defun turn-on-orgstruct++ ()
8370 "Unconditionally turn on `orgstruct++-mode'."
8371 (orgstruct++-mode 1))
8373 (defun orgstruct-error ()
8374 "Error when there is no default binding for a structure key."
8375 (interactive)
8376 (error "This key has no function outside structure elements"))
8378 (defun orgstruct-setup ()
8379 "Setup orgstruct keymaps."
8380 (let ((nfunc 0)
8381 (bindings
8382 (list
8383 '([(meta up)] org-metaup)
8384 '([(meta down)] org-metadown)
8385 '([(meta left)] org-metaleft)
8386 '([(meta right)] org-metaright)
8387 '([(meta shift up)] org-shiftmetaup)
8388 '([(meta shift down)] org-shiftmetadown)
8389 '([(meta shift left)] org-shiftmetaleft)
8390 '([(meta shift right)] org-shiftmetaright)
8391 '([?\e (up)] org-metaup)
8392 '([?\e (down)] org-metadown)
8393 '([?\e (left)] org-metaleft)
8394 '([?\e (right)] org-metaright)
8395 '([?\e (shift up)] org-shiftmetaup)
8396 '([?\e (shift down)] org-shiftmetadown)
8397 '([?\e (shift left)] org-shiftmetaleft)
8398 '([?\e (shift right)] org-shiftmetaright)
8399 '([(shift up)] org-shiftup)
8400 '([(shift down)] org-shiftdown)
8401 '([(shift left)] org-shiftleft)
8402 '([(shift right)] org-shiftright)
8403 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8404 '("\M-q" fill-paragraph)
8405 '("\C-c^" org-sort)
8406 '("\C-c-" org-cycle-list-bullet)))
8407 elt key fun cmd)
8408 (while (setq elt (pop bindings))
8409 (setq nfunc (1+ nfunc))
8410 (setq key (org-key (car elt))
8411 fun (nth 1 elt)
8412 cmd (orgstruct-make-binding fun nfunc key))
8413 (org-defkey orgstruct-mode-map key cmd))
8415 ;; Prevent an error for users who forgot to make autoloads
8416 (require 'org-element)
8418 ;; Special treatment needed for TAB and RET
8419 (org-defkey orgstruct-mode-map [(tab)]
8420 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8421 (org-defkey orgstruct-mode-map "\C-i"
8422 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8424 (org-defkey orgstruct-mode-map "\M-\C-m"
8425 (orgstruct-make-binding 'org-insert-heading 105
8426 "\M-\C-m" [(meta return)]))
8427 (org-defkey orgstruct-mode-map [(meta return)]
8428 (orgstruct-make-binding 'org-insert-heading 106
8429 [(meta return)] "\M-\C-m"))
8431 (org-defkey orgstruct-mode-map [(shift meta return)]
8432 (orgstruct-make-binding 'org-insert-todo-heading 107
8433 [(meta return)] "\M-\C-m"))
8435 (org-defkey orgstruct-mode-map "\e\C-m"
8436 (orgstruct-make-binding 'org-insert-heading 108
8437 "\e\C-m" [?\e (return)]))
8438 (org-defkey orgstruct-mode-map [?\e (return)]
8439 (orgstruct-make-binding 'org-insert-heading 109
8440 [?\e (return)] "\e\C-m"))
8441 (org-defkey orgstruct-mode-map [?\e (shift return)]
8442 (orgstruct-make-binding 'org-insert-todo-heading 110
8443 [?\e (return)] "\e\C-m"))
8445 (unless org-local-vars
8446 (setq org-local-vars (org-get-local-variables)))
8450 (defun orgstruct-make-binding (fun n &rest keys)
8451 "Create a function for binding in the structure minor mode.
8452 FUN is the command to call inside a table. N is used to create a unique
8453 command name. KEYS are keys that should be checked in for a command
8454 to execute outside of tables."
8455 (eval
8456 (list 'defun
8457 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8458 '(arg)
8459 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8460 "Outside of structure, run the binding of `"
8461 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8462 "'.")
8463 '(interactive "p")
8464 (list 'if
8465 `(org-context-p 'headline 'item
8466 (and orgstruct-is-++
8467 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8468 'item-body))
8469 (list 'org-run-like-in-org-mode (list 'quote fun))
8470 (list 'let '(orgstruct-mode)
8471 (list 'call-interactively
8472 (append '(or)
8473 (mapcar (lambda (k)
8474 (list 'key-binding k))
8475 keys)
8476 '('orgstruct-error))))))))
8478 (defun org-contextualize-keys (alist contexts)
8479 "Return valid elements in ALIST depending on CONTEXTS.
8481 `org-agenda-custom-commands' or `org-capture-templates' are the
8482 values used for ALIST, and `org-agenda-custom-commands-contexts'
8483 or `org-capture-templates-contexts' are the associated contexts
8484 definitions."
8485 (let ((contexts
8486 ;; normalize contexts
8487 (mapcar
8488 (lambda(c) (cond ((listp (cadr c))
8489 (list (car c) (car c) (cadr c)))
8490 ((string= "" (cadr c))
8491 (list (car c) (car c) (caddr c)))
8492 (t c))) contexts))
8493 (a alist) c r s)
8494 ;; loop over all commands or templates
8495 (while (setq c (pop a))
8496 (let (vrules repl)
8497 (cond
8498 ((not (assoc (car c) contexts))
8499 (push c r))
8500 ((and (assoc (car c) contexts)
8501 (setq vrules (org-contextualize-validate-key
8502 (car c) contexts)))
8503 (mapc (lambda (vr)
8504 (when (not (equal (car vr) (cadr vr)))
8505 (setq repl vr))) vrules)
8506 (if (not repl) (push c r)
8507 (push (cadr repl) s)
8508 (push
8509 (cons (car c)
8510 (cdr (or (assoc (cadr repl) alist)
8511 (error "Undefined key `%s' as contextual replacement for `%s'"
8512 (cadr repl) (car c)))))
8513 r))))))
8514 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8515 (delq
8517 (delete-dups
8518 (mapcar (lambda (x)
8519 (let ((tpl (car x)))
8520 (when (not (delq
8522 (mapcar (lambda(y)
8523 (equal y tpl)) s))) x)))
8524 (reverse r))))))
8526 (defun org-contextualize-validate-key (key contexts)
8527 "Check CONTEXTS for agenda or capture KEY."
8528 (let (r rr res)
8529 (while (setq r (pop contexts))
8530 (mapc
8531 (lambda (rr)
8532 (when
8533 (and (equal key (car r))
8534 (if (functionp rr) (funcall rr)
8535 (or (and (eq (car rr) 'in-file)
8536 (buffer-file-name)
8537 (string-match (cdr rr) (buffer-file-name)))
8538 (and (eq (car rr) 'in-mode)
8539 (string-match (cdr rr) (symbol-name major-mode)))
8540 (when (and (eq (car rr) 'not-in-file)
8541 (buffer-file-name))
8542 (not (string-match (cdr rr) (buffer-file-name))))
8543 (when (eq (car rr) 'not-in-mode)
8544 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8545 (push r res)))
8546 (car (last r))))
8547 (delete-dups (delq nil res))))
8549 (defun org-context-p (&rest contexts)
8550 "Check if local context is any of CONTEXTS.
8551 Possible values in the list of contexts are `table', `headline', and `item'."
8552 (let ((pos (point)))
8553 (goto-char (point-at-bol))
8554 (prog1 (or (and (memq 'table contexts)
8555 (looking-at "[ \t]*|"))
8556 (and (memq 'headline contexts)
8557 (looking-at org-outline-regexp))
8558 (and (memq 'item contexts)
8559 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8560 (and (memq 'item-body contexts)
8561 (org-in-item-p)))
8562 (goto-char pos))))
8564 (defun org-get-local-variables ()
8565 "Return a list of all local variables in an Org mode buffer."
8566 (let (varlist)
8567 (with-current-buffer (get-buffer-create "*Org tmp*")
8568 (erase-buffer)
8569 (org-mode)
8570 (setq varlist (buffer-local-variables)))
8571 (kill-buffer "*Org tmp*")
8572 (delq nil
8573 (mapcar
8574 (lambda (x)
8575 (setq x
8576 (if (symbolp x)
8577 (list x)
8578 (list (car x) (list 'quote (cdr x)))))
8579 (if (string-match
8580 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8581 (symbol-name (car x)))
8582 x nil))
8583 varlist))))
8585 (defun org-clone-local-variables (from-buffer &optional regexp)
8586 "Clone local variables from FROM-BUFFER.
8587 Optional argument REGEXP selects variables to clone."
8588 (mapc
8589 (lambda (pair)
8590 (and (symbolp (car pair))
8591 (or (null regexp)
8592 (string-match regexp (symbol-name (car pair))))
8593 (set (make-local-variable (car pair))
8594 (cdr pair))))
8595 (buffer-local-variables from-buffer)))
8597 ;;;###autoload
8598 (defun org-run-like-in-org-mode (cmd)
8599 "Run a command, pretending that the current buffer is in Org-mode.
8600 This will temporarily bind local variables that are typically bound in
8601 Org-mode to the values they have in Org-mode, and then interactively
8602 call CMD."
8603 (org-load-modules-maybe)
8604 (unless org-local-vars
8605 (setq org-local-vars (org-get-local-variables)))
8606 (eval (list 'let org-local-vars
8607 (list 'call-interactively (list 'quote cmd)))))
8609 ;;;; Archiving
8611 (defun org-get-category (&optional pos force-refresh)
8612 "Get the category applying to position POS."
8613 (save-match-data
8614 (if force-refresh (org-refresh-category-properties))
8615 (let ((pos (or pos (point))))
8616 (or (get-text-property pos 'org-category)
8617 (progn (org-refresh-category-properties)
8618 (get-text-property pos 'org-category))))))
8620 (defun org-refresh-category-properties ()
8621 "Refresh category text properties in the buffer."
8622 (let ((case-fold-search t)
8623 (inhibit-read-only t)
8624 (def-cat (cond
8625 ((null org-category)
8626 (if buffer-file-name
8627 (file-name-sans-extension
8628 (file-name-nondirectory buffer-file-name))
8629 "???"))
8630 ((symbolp org-category) (symbol-name org-category))
8631 (t org-category)))
8632 beg end cat pos optionp)
8633 (org-unmodified
8634 (save-excursion
8635 (save-restriction
8636 (widen)
8637 (goto-char (point-min))
8638 (put-text-property (point) (point-max) 'org-category def-cat)
8639 (while (re-search-forward
8640 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8641 (setq pos (match-end 0)
8642 optionp (equal (char-after (match-beginning 0)) ?#)
8643 cat (org-trim (match-string 2)))
8644 (if optionp
8645 (setq beg (point-at-bol) end (point-max))
8646 (org-back-to-heading t)
8647 (setq beg (point) end (org-end-of-subtree t t)))
8648 (put-text-property beg end 'org-category cat)
8649 (put-text-property beg end 'org-category-position beg)
8650 (goto-char pos)))))))
8652 (defun org-refresh-properties (dprop tprop)
8653 "Refresh buffer text properties.
8654 DPROP is the drawer property and TPROP is the corresponding text
8655 property to set."
8656 (let ((case-fold-search t)
8657 (inhibit-read-only t) p)
8658 (org-unmodified
8659 (save-excursion
8660 (save-restriction
8661 (widen)
8662 (goto-char (point-min))
8663 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
8664 (setq p (org-match-string-no-properties 1))
8665 (save-excursion
8666 (org-back-to-heading t)
8667 (put-text-property
8668 (point-at-bol) (point-at-eol) tprop p))))))))
8671 ;;;; Link Stuff
8673 ;;; Link abbreviations
8675 (defun org-link-expand-abbrev (link)
8676 "Apply replacements as defined in `org-link-abbrev-alist'."
8677 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8678 (let* ((key (match-string 1 link))
8679 (as (or (assoc key org-link-abbrev-alist-local)
8680 (assoc key org-link-abbrev-alist)))
8681 (tag (and (match-end 2) (match-string 3 link)))
8682 rpl)
8683 (if (not as)
8684 link
8685 (setq rpl (cdr as))
8686 (cond
8687 ((symbolp rpl) (funcall rpl tag))
8688 ((string-match "%(\\([^)]+\\))" rpl)
8689 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8690 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8691 ((string-match "%h" rpl)
8692 (replace-match (url-hexify-string (or tag "")) t t rpl))
8693 (t (concat rpl tag)))))
8694 link))
8696 ;;; Storing and inserting links
8698 (defvar org-insert-link-history nil
8699 "Minibuffer history for links inserted with `org-insert-link'.")
8701 (defvar org-stored-links nil
8702 "Contains the links stored with `org-store-link'.")
8704 (defvar org-store-link-plist nil
8705 "Plist with info about the most recently link created with `org-store-link'.")
8707 (defvar org-link-protocols nil
8708 "Link protocols added to Org-mode using `org-add-link-type'.")
8710 (defvar org-store-link-functions nil
8711 "List of functions that are called to create and store a link.
8712 Each function will be called in turn until one returns a non-nil
8713 value. Each function should check if it is responsible for creating
8714 this link (for example by looking at the major mode).
8715 If not, it must exit and return nil.
8716 If yes, it should return a non-nil value after a calling
8717 `org-store-link-props' with a list of properties and values.
8718 Special properties are:
8720 :type The link prefix, like \"http\". This must be given.
8721 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8722 This is obligatory as well.
8723 :description Optional default description for the second pair
8724 of brackets in an Org-mode link. The user can still change
8725 this when inserting this link into an Org-mode buffer.
8727 In addition to these, any additional properties can be specified
8728 and then used in capture templates.")
8730 (defun org-add-link-type (type &optional follow export)
8731 "Add TYPE to the list of `org-link-types'.
8732 Re-compute all regular expressions depending on `org-link-types'
8734 FOLLOW and EXPORT are two functions.
8736 FOLLOW should take the link path as the single argument and do whatever
8737 is necessary to follow the link, for example find a file or display
8738 a mail message.
8740 EXPORT should format the link path for export to one of the export formats.
8741 It should be a function accepting three arguments:
8743 path the path of the link, the text after the prefix (like \"http:\")
8744 desc the description of the link, if any, or a description added by
8745 org-export-normalize-links if there is none
8746 format the export format, a symbol like `html' or `latex' or `ascii'..
8748 The function may use the FORMAT information to return different values
8749 depending on the format. The return value will be put literally into
8750 the exported file. If the return value is nil, this means Org should
8751 do what it normally does with links which do not have EXPORT defined.
8753 Org-mode has a built-in default for exporting links. If you are happy with
8754 this default, there is no need to define an export function for the link
8755 type. For a simple example of an export function, see `org-bbdb.el'."
8756 (add-to-list 'org-link-types type t)
8757 (org-make-link-regexps)
8758 (if (assoc type org-link-protocols)
8759 (setcdr (assoc type org-link-protocols) (list follow export))
8760 (push (list type follow export) org-link-protocols)))
8762 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8763 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
8765 ;;;###autoload
8766 (defun org-store-link (arg)
8767 "\\<org-mode-map>Store an org-link to the current location.
8768 This link is added to `org-stored-links' and can later be inserted
8769 into an org-buffer with \\[org-insert-link].
8771 For some link types, a prefix arg is interpreted:
8772 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8773 For file links, arg negates `org-context-in-file-links'."
8774 (interactive "P")
8775 (org-load-modules-maybe)
8776 (setq org-store-link-plist nil) ; reset
8777 (org-with-limited-levels
8778 (let (link cpltxt desc description search txt custom-id agenda-link)
8779 (cond
8781 ((run-hook-with-args-until-success 'org-store-link-functions)
8782 (setq link (plist-get org-store-link-plist :link)
8783 desc (or (plist-get org-store-link-plist :description) link)))
8785 ((org-src-edit-buffer-p)
8786 (let (label gc)
8787 (while (or (not label)
8788 (save-excursion
8789 (save-restriction
8790 (widen)
8791 (goto-char (point-min))
8792 (re-search-forward
8793 (regexp-quote (format org-coderef-label-format label))
8794 nil t))))
8795 (when label (message "Label exists already") (sit-for 2))
8796 (setq label (read-string "Code line label: " label)))
8797 (end-of-line 1)
8798 (setq link (format org-coderef-label-format label))
8799 (setq gc (- 79 (length link)))
8800 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8801 (insert link)
8802 (setq link (concat "(" label ")") desc nil)))
8804 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8805 ;; We are in the agenda, link to referenced location
8806 (let ((m (or (get-text-property (point) 'org-hd-marker)
8807 (get-text-property (point) 'org-marker))))
8808 (when m
8809 (org-with-point-at m
8810 (setq agenda-link
8811 (if (org-called-interactively-p 'any)
8812 (call-interactively 'org-store-link)
8813 (org-store-link nil)))))))
8815 ((eq major-mode 'calendar-mode)
8816 (let ((cd (calendar-cursor-to-date)))
8817 (setq link
8818 (format-time-string
8819 (car org-time-stamp-formats)
8820 (apply 'encode-time
8821 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8822 nil nil nil))))
8823 (org-store-link-props :type "calendar" :date cd)))
8825 ((eq major-mode 'help-mode)
8826 (setq link (concat "help:" (save-excursion
8827 (goto-char (point-min))
8828 (looking-at "^[^ ]+")
8829 (match-string 0))))
8830 (org-store-link-props :type "help"))
8832 ((eq major-mode 'w3-mode)
8833 (setq cpltxt (if (and (buffer-name)
8834 (not (string-match "Untitled" (buffer-name))))
8835 (buffer-name)
8836 (url-view-url t))
8837 link (url-view-url t))
8838 (org-store-link-props :type "w3" :url (url-view-url t)))
8840 ((eq major-mode 'w3m-mode)
8841 (setq cpltxt (or w3m-current-title w3m-current-url)
8842 link w3m-current-url)
8843 (org-store-link-props :type "w3m" :url (url-view-url t)))
8845 ((setq search (run-hook-with-args-until-success
8846 'org-create-file-search-functions))
8847 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8848 "::" search))
8849 (setq cpltxt (or description link)))
8851 ((eq major-mode 'image-mode)
8852 (setq cpltxt (concat "file:"
8853 (abbreviate-file-name buffer-file-name))
8854 link cpltxt)
8855 (org-store-link-props :type "image" :file buffer-file-name))
8857 ((eq major-mode 'dired-mode)
8858 ;; link to the file in the current line
8859 (let ((file (dired-get-filename nil t)))
8860 (setq file (if file
8861 (abbreviate-file-name
8862 (expand-file-name (dired-get-filename nil t)))
8863 ;; otherwise, no file so use current directory.
8864 default-directory))
8865 (setq cpltxt (concat "file:" file)
8866 link cpltxt)))
8868 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8869 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8870 (cond
8871 ((org-in-regexp "<<\\(.*?\\)>>")
8872 (setq cpltxt
8873 (concat "file:"
8874 (abbreviate-file-name
8875 (buffer-file-name (buffer-base-buffer)))
8876 "::" (match-string 1))
8877 link cpltxt))
8878 ((and (featurep 'org-id)
8879 (or (eq org-id-link-to-org-use-id t)
8880 (and (org-called-interactively-p 'any)
8881 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
8882 (and (eq org-id-link-to-org-use-id
8883 'create-if-interactive-and-no-custom-id)
8884 (not custom-id))))
8885 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
8886 ;; We can make a link using the ID.
8887 (setq link (condition-case nil
8888 (prog1 (org-id-store-link)
8889 (setq desc (plist-get org-store-link-plist :description)))
8890 (error
8891 ;; probably before first headline, link to file only
8892 (concat "file:"
8893 (abbreviate-file-name
8894 (buffer-file-name (buffer-base-buffer))))))))
8896 ;; Just link to current headline
8897 (setq cpltxt (concat "file:"
8898 (abbreviate-file-name
8899 (buffer-file-name (buffer-base-buffer)))))
8900 ;; Add a context search string
8901 (when (org-xor org-context-in-file-links arg)
8902 (setq txt (cond
8903 ((org-at-heading-p) nil)
8904 ((org-region-active-p)
8905 (buffer-substring (region-beginning) (region-end)))))
8906 (when (or (null txt) (string-match "\\S-" txt))
8907 (setq cpltxt
8908 (concat cpltxt "::"
8909 (condition-case nil
8910 (org-make-org-heading-search-string txt)
8911 (error "")))
8912 desc (or (nth 4 (ignore-errors
8913 (org-heading-components))) "NONE"))))
8914 (if (string-match "::\\'" cpltxt)
8915 (setq cpltxt (substring cpltxt 0 -2)))
8916 (setq link cpltxt))))
8918 ((buffer-file-name (buffer-base-buffer))
8919 ;; Just link to this file here.
8920 (setq cpltxt (concat "file:"
8921 (abbreviate-file-name
8922 (buffer-file-name (buffer-base-buffer)))))
8923 ;; Add a context string
8924 (when (org-xor org-context-in-file-links arg)
8925 (setq txt (if (org-region-active-p)
8926 (buffer-substring (region-beginning) (region-end))
8927 (buffer-substring (point-at-bol) (point-at-eol))))
8928 ;; Only use search option if there is some text.
8929 (when (string-match "\\S-" txt)
8930 (setq cpltxt
8931 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8932 desc "NONE")))
8933 (setq link cpltxt))
8935 ((org-called-interactively-p 'interactive)
8936 (error "Cannot link to a buffer which is not visiting a file"))
8938 (t (setq link nil)))
8940 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8941 (setq link (or link cpltxt)
8942 desc (or desc cpltxt))
8943 (if (equal desc "NONE") (setq desc nil))
8945 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8946 (progn
8947 (setq org-stored-links
8948 (cons (list link desc) org-stored-links))
8949 (message "Stored: %s" (or desc link))
8950 (when custom-id
8951 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8952 "::#" custom-id))
8953 (setq org-stored-links
8954 (cons (list link desc) org-stored-links))))
8955 (or agenda-link (and link (org-make-link-string link desc)))))))
8957 (defun org-store-link-props (&rest plist)
8958 "Store link properties, extract names and addresses."
8959 (let (x adr)
8960 (when (setq x (plist-get plist :from))
8961 (setq adr (mail-extract-address-components x))
8962 (setq plist (plist-put plist :fromname (car adr)))
8963 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8964 (when (setq x (plist-get plist :to))
8965 (setq adr (mail-extract-address-components x))
8966 (setq plist (plist-put plist :toname (car adr)))
8967 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8968 (let ((from (plist-get plist :from))
8969 (to (plist-get plist :to)))
8970 (when (and from to org-from-is-user-regexp)
8971 (setq plist
8972 (plist-put plist :fromto
8973 (if (string-match org-from-is-user-regexp from)
8974 (concat "to %t")
8975 (concat "from %f"))))))
8976 (setq org-store-link-plist plist))
8978 (defun org-add-link-props (&rest plist)
8979 "Add these properties to the link property list."
8980 (let (key value)
8981 (while plist
8982 (setq key (pop plist) value (pop plist))
8983 (setq org-store-link-plist
8984 (plist-put org-store-link-plist key value)))))
8986 (defun org-email-link-description (&optional fmt)
8987 "Return the description part of an email link.
8988 This takes information from `org-store-link-plist' and formats it
8989 according to FMT (default from `org-email-link-description-format')."
8990 (setq fmt (or fmt org-email-link-description-format))
8991 (let* ((p org-store-link-plist)
8992 (to (plist-get p :toaddress))
8993 (from (plist-get p :fromaddress))
8994 (table
8995 (list
8996 (cons "%c" (plist-get p :fromto))
8997 (cons "%F" (plist-get p :from))
8998 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8999 (cons "%T" (plist-get p :to))
9000 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9001 (cons "%s" (plist-get p :subject))
9002 (cons "%d" (plist-get p :date))
9003 (cons "%m" (plist-get p :message-id)))))
9004 (when (string-match "%c" fmt)
9005 ;; Check if the user wrote this message
9006 (if (and org-from-is-user-regexp from to
9007 (save-match-data (string-match org-from-is-user-regexp from)))
9008 (setq fmt (replace-match "to %t" t t fmt))
9009 (setq fmt (replace-match "from %f" t t fmt))))
9010 (org-replace-escapes fmt table)))
9012 (defun org-make-org-heading-search-string (&optional string heading)
9013 "Make search string for STRING or current headline."
9014 (interactive)
9015 (let ((s (or string (org-get-heading)))
9016 (lines org-context-in-file-links))
9017 (unless (and string (not heading))
9018 ;; We are using a headline, clean up garbage in there.
9019 (if (string-match org-todo-regexp s)
9020 (setq s (replace-match "" t t s)))
9021 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
9022 (setq s (replace-match "" t t s)))
9023 (setq s (org-trim s))
9024 (if (string-match (concat "^\\(" org-quote-string "\\|"
9025 org-comment-string "\\)") s)
9026 (setq s (replace-match "" t t s)))
9027 (while (string-match org-ts-regexp s)
9028 (setq s (replace-match "" t t s))))
9029 (or string (setq s (concat "*" s))) ; Add * for headlines
9030 (when (and string (integerp lines) (> lines 0))
9031 (let ((slines (org-split-string s "\n")))
9032 (when (< lines (length slines))
9033 (setq s (mapconcat
9034 'identity
9035 (reverse (nthcdr (- (length slines) lines)
9036 (reverse slines))) "\n")))))
9037 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9039 (defun org-make-link-string (link &optional description)
9040 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9041 (unless (string-match "\\S-" link)
9042 (error "Empty link"))
9043 (when (and description
9044 (stringp description)
9045 (not (string-match "\\S-" description)))
9046 (setq description nil))
9047 (when (stringp description)
9048 ;; Remove brackets from the description, they are fatal.
9049 (while (string-match "\\[" description)
9050 (setq description (replace-match "{" t t description)))
9051 (while (string-match "\\]" description)
9052 (setq description (replace-match "}" t t description))))
9053 (when (equal link description)
9054 ;; No description needed, it is identical
9055 (setq description nil))
9056 (when (and (not description)
9057 (not (string-match (org-image-file-name-regexp) link))
9058 (not (equal link (org-link-escape link))))
9059 (setq description (org-extract-attributes link)))
9060 (setq link
9061 (cond ((string-match (org-image-file-name-regexp) link) link)
9062 ((string-match org-link-types-re link)
9063 (concat (match-string 1 link)
9064 (org-link-escape (substring link (match-end 1)))))
9065 (t (org-link-escape link))))
9066 (concat "[[" link "]"
9067 (if description (concat "[" description "]") "")
9068 "]"))
9070 (defconst org-link-escape-chars
9071 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9072 "List of characters that should be escaped in link.
9073 This is the list that is used for internal purposes.")
9075 (defconst org-link-escape-chars-browser
9076 '(?\ )
9077 "List of escapes for characters that are problematic in links.
9078 This is the list that is used before handing over to the browser.")
9080 (defun org-link-escape (text &optional table merge)
9081 "Return percent escaped representation of TEXT.
9082 TEXT is a string with the text to escape.
9083 Optional argument TABLE is a list with characters that should be
9084 escaped. When nil, `org-link-escape-chars' is used.
9085 If optional argument MERGE is set, merge TABLE into
9086 `org-link-escape-chars'."
9087 (cond
9088 ((and table merge)
9089 (mapc (lambda (defchr)
9090 (unless (member defchr table)
9091 (setq table (cons defchr table)))) org-link-escape-chars))
9092 ((null table)
9093 (setq table org-link-escape-chars)))
9094 (mapconcat
9095 (lambda (char)
9096 (if (or (member char table)
9097 (and (or (< char 32) (= char 37) (> char 126))
9098 org-url-hexify-p))
9099 (mapconcat (lambda (sequence-element)
9100 (format "%%%.2X" sequence-element))
9101 (or (encode-coding-char char 'utf-8)
9102 (error "Unable to percent escape character: %s"
9103 (char-to-string char))) "")
9104 (char-to-string char))) text ""))
9106 (defun org-link-unescape (str)
9107 "Unhex hexified Unicode strings as returned from the JavaScript function
9108 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9109 (unless (and (null str) (string= "" str))
9110 (let ((pos 0) (case-fold-search t) unhexed)
9111 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9112 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9113 (setq str (replace-match unhexed t t str))
9114 (setq pos (+ pos (length unhexed))))))
9115 str)
9117 (defun org-link-unescape-compound (hex)
9118 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9119 Note: this function also decodes single byte encodings like
9120 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9121 (save-match-data
9122 (let* ((bytes (cdr (split-string hex "%")))
9123 (ret "")
9124 (eat 0)
9125 (sum 0))
9126 (while bytes
9127 (let* ((val (string-to-number (pop bytes) 16))
9128 (shift-xor
9129 (if (= 0 eat)
9130 (cond
9131 ((>= val 252) (cons 6 252))
9132 ((>= val 248) (cons 5 248))
9133 ((>= val 240) (cons 4 240))
9134 ((>= val 224) (cons 3 224))
9135 ((>= val 192) (cons 2 192))
9136 (t (cons 0 0)))
9137 (cons 6 128))))
9138 (if (>= val 192) (setq eat (car shift-xor)))
9139 (setq val (logxor val (cdr shift-xor)))
9140 (setq sum (+ (lsh sum (car shift-xor)) val))
9141 (if (> eat 0) (setq eat (- eat 1)))
9142 (cond
9143 ((= 0 eat) ;multi byte
9144 (setq ret (concat ret (org-char-to-string sum)))
9145 (setq sum 0))
9146 ((not bytes) ; single byte(s)
9147 (setq ret (org-link-unescape-single-byte-sequence hex))))
9148 )) ;; end (while bytes
9149 ret )))
9151 (defun org-link-unescape-single-byte-sequence (hex)
9152 "Unhexify hex-encoded single byte character sequences."
9153 (mapconcat (lambda (byte)
9154 (char-to-string (string-to-number byte 16)))
9155 (cdr (split-string hex "%")) ""))
9157 (defun org-xor (a b)
9158 "Exclusive or."
9159 (if a (not b) b))
9161 (defun org-fixup-message-id-for-http (s)
9162 "Replace special characters in a message id, so it can be used in an http query."
9163 (when (string-match "%" s)
9164 (setq s (mapconcat (lambda (c)
9165 (if (eq c ?%)
9166 "%25"
9167 (char-to-string c)))
9168 s "")))
9169 (while (string-match "<" s)
9170 (setq s (replace-match "%3C" t t s)))
9171 (while (string-match ">" s)
9172 (setq s (replace-match "%3E" t t s)))
9173 (while (string-match "@" s)
9174 (setq s (replace-match "%40" t t s)))
9177 (defun org-link-prettify (link)
9178 "Return a human-readable representation of LINK.
9179 The car of LINK must be a raw link the cdr of LINK must be either
9180 a link description or nil."
9181 (let ((desc (or (cadr link) "<no description>")))
9182 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9183 "<" (car link) ">")))
9185 ;;;###autoload
9186 (defun org-insert-link-global ()
9187 "Insert a link like Org-mode does.
9188 This command can be called in any mode to insert a link in Org-mode syntax."
9189 (interactive)
9190 (org-load-modules-maybe)
9191 (org-run-like-in-org-mode 'org-insert-link))
9193 (defun org-insert-all-links (&optional keep)
9194 "Insert all links in `org-stored-links'."
9195 (interactive "P")
9196 (let ((links (copy-sequence org-stored-links)) l)
9197 (while (setq l (if keep (pop links) (pop org-stored-links)))
9198 (insert "- ")
9199 (org-insert-link nil (car l) (cadr l))
9200 (insert "\n"))))
9202 (defun org-link-fontify-links-to-this-file ()
9203 "Fontify links to the current file in `org-stored-links'."
9204 (let ((f (buffer-file-name)) a b)
9205 (setq a (mapcar (lambda(l)
9206 (let ((ll (car l)))
9207 (when (and (string-match "^file:\\(.+\\)::" ll)
9208 (equal f (expand-file-name (match-string 1 ll))))
9209 ll)))
9210 org-stored-links))
9211 (when (featurep 'org-id)
9212 (setq b (mapcar (lambda(l)
9213 (let ((ll (car l)))
9214 (when (and (string-match "^id:\\(.+\\)$" ll)
9215 (equal f (expand-file-name
9216 (or (org-id-find-id-file
9217 (match-string 1 ll)) ""))))
9218 ll)))
9219 org-stored-links)))
9220 (mapcar (lambda(l)
9221 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9222 (delq nil (append a b)))))
9224 (defvar org-link-links-in-this-file nil)
9225 (defun org-insert-link (&optional complete-file link-location default-description)
9226 "Insert a link. At the prompt, enter the link.
9228 Completion can be used to insert any of the link protocol prefixes like
9229 http or ftp in use.
9231 The history can be used to select a link previously stored with
9232 `org-store-link'. When the empty string is entered (i.e. if you just
9233 press RET at the prompt), the link defaults to the most recently
9234 stored link. As SPC triggers completion in the minibuffer, you need to
9235 use M-SPC or C-q SPC to force the insertion of a space character.
9237 You will also be prompted for a description, and if one is given, it will
9238 be displayed in the buffer instead of the link.
9240 If there is already a link at point, this command will allow you to edit link
9241 and description parts.
9243 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9244 be selected using completion. The path to the file will be relative to the
9245 current directory if the file is in the current directory or a subdirectory.
9246 Otherwise, the link will be the absolute path as completed in the minibuffer
9247 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9248 option `org-link-file-path-type'.
9250 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9251 the current directory or below.
9253 With three \\[universal-argument] prefixes, negate the meaning of
9254 `org-keep-stored-link-after-insertion'.
9256 If `org-make-link-description-function' is non-nil, this function will be
9257 called with the link target, and the result will be the default
9258 link description.
9260 If the LINK-LOCATION parameter is non-nil, this value will be
9261 used as the link location instead of reading one interactively.
9263 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9264 be used as the default description."
9265 (interactive "P")
9266 (let* ((wcf (current-window-configuration))
9267 (region (if (org-region-active-p)
9268 (buffer-substring (region-beginning) (region-end))))
9269 (remove (and region (list (region-beginning) (region-end))))
9270 (desc region)
9271 tmphist ; byte-compile incorrectly complains about this
9272 (link link-location)
9273 (abbrevs org-link-abbrev-alist-local)
9274 entry file all-prefixes auto-desc)
9275 (cond
9276 (link-location) ; specified by arg, just use it.
9277 ((org-in-regexp org-bracket-link-regexp 1)
9278 ;; We do have a link at point, and we are going to edit it.
9279 (setq remove (list (match-beginning 0) (match-end 0)))
9280 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9281 (setq link (read-string "Link: "
9282 (org-link-unescape
9283 (org-match-string-no-properties 1)))))
9284 ((or (org-in-regexp org-angle-link-re)
9285 (org-in-regexp org-plain-link-re))
9286 ;; Convert to bracket link
9287 (setq remove (list (match-beginning 0) (match-end 0))
9288 link (read-string "Link: "
9289 (org-remove-angle-brackets (match-string 0)))))
9290 ((member complete-file '((4) (16)))
9291 ;; Completing read for file names.
9292 (setq link (org-file-complete-link complete-file)))
9294 ;; Read link, with completion for stored links.
9295 (org-link-fontify-links-to-this-file)
9296 (org-switch-to-buffer-other-window "*Org Links*")
9297 (with-current-buffer "*Org Links*"
9298 (erase-buffer)
9299 (insert "Insert a link.
9300 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9301 (when org-stored-links
9302 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9303 (insert (mapconcat 'org-link-prettify
9304 (reverse org-stored-links) "\n")))
9305 (goto-char (point-min)))
9306 (let ((cw (selected-window)))
9307 (select-window (get-buffer-window "*Org Links*" 'visible))
9308 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9309 (unless (pos-visible-in-window-p (point-max))
9310 (org-fit-window-to-buffer))
9311 (and (window-live-p cw) (select-window cw)))
9312 ;; Fake a link history, containing the stored links.
9313 (setq tmphist (append (mapcar 'car org-stored-links)
9314 org-insert-link-history))
9315 (setq all-prefixes (append (mapcar 'car abbrevs)
9316 (mapcar 'car org-link-abbrev-alist)
9317 org-link-types))
9318 (unwind-protect
9319 (progn
9320 (setq link
9321 (let ((org-completion-use-ido nil)
9322 (org-completion-use-iswitchb nil))
9323 (org-completing-read
9324 "Link: "
9325 (append
9326 (mapcar (lambda (x) (list (concat x ":")))
9327 all-prefixes)
9328 (mapcar 'car org-stored-links)
9329 (mapcar 'cadr org-stored-links))
9330 nil nil nil
9331 'tmphist
9332 (caar org-stored-links))))
9333 (if (not (string-match "\\S-" link))
9334 (error "No link selected"))
9335 (mapc (lambda(l)
9336 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9337 org-stored-links)
9338 (if (or (member link all-prefixes)
9339 (and (equal ":" (substring link -1))
9340 (member (substring link 0 -1) all-prefixes)
9341 (setq link (substring link 0 -1))))
9342 (setq link (org-link-try-special-completion link))))
9343 (set-window-configuration wcf)
9344 (kill-buffer "*Org Links*"))
9345 (setq entry (assoc link org-stored-links))
9346 (or entry (push link org-insert-link-history))
9347 (setq desc (or desc (nth 1 entry)))))
9349 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9350 (not org-keep-stored-link-after-insertion))
9351 (setq org-stored-links (delq (assoc link org-stored-links)
9352 org-stored-links)))
9354 (if (string-match org-plain-link-re link)
9355 ;; URL-like link, normalize the use of angular brackets.
9356 (setq link (org-remove-angle-brackets link)))
9358 ;; Check if we are linking to the current file with a search
9359 ;; option If yes, simplify the link by using only the search
9360 ;; option.
9361 (when (and buffer-file-name
9362 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9363 (let* ((path (match-string 1 link))
9364 (case-fold-search nil)
9365 (search (match-string 2 link)))
9366 (save-match-data
9367 (if (equal (file-truename buffer-file-name) (file-truename path))
9368 ;; We are linking to this same file, with a search option
9369 (setq link search)))))
9371 ;; Check if we can/should use a relative path. If yes, simplify the link
9372 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9373 (let* ((type (match-string 1 link))
9374 (path (match-string 2 link))
9375 (origpath path)
9376 (case-fold-search nil))
9377 (cond
9378 ((or (eq org-link-file-path-type 'absolute)
9379 (equal complete-file '(16)))
9380 (setq path (abbreviate-file-name (expand-file-name path))))
9381 ((eq org-link-file-path-type 'noabbrev)
9382 (setq path (expand-file-name path)))
9383 ((eq org-link-file-path-type 'relative)
9384 (setq path (file-relative-name path)))
9386 (save-match-data
9387 (if (string-match (concat "^" (regexp-quote
9388 (expand-file-name
9389 (file-name-as-directory
9390 default-directory))))
9391 (expand-file-name path))
9392 ;; We are linking a file with relative path name.
9393 (setq path (substring (expand-file-name path)
9394 (match-end 0)))
9395 (setq path (abbreviate-file-name (expand-file-name path)))))))
9396 (setq link (concat type path))
9397 (if (equal desc origpath)
9398 (setq desc path))))
9400 (if org-make-link-description-function
9401 (setq desc
9402 (or (condition-case nil
9403 (funcall org-make-link-description-function link desc)
9404 (error (progn (message "Can't get link description from `%s'"
9405 (symbol-name org-make-link-description-function))
9406 (sit-for 2) nil)))
9407 (read-string "Description: " default-description)))
9408 (if default-description (setq desc default-description)
9409 (setq desc (or (and auto-desc desc)
9410 (read-string "Description: " desc)))))
9412 (unless (string-match "\\S-" desc) (setq desc nil))
9413 (if remove (apply 'delete-region remove))
9414 (insert (org-make-link-string link desc))))
9416 (defun org-link-try-special-completion (type)
9417 "If there is completion support for link type TYPE, offer it."
9418 (let ((fun (intern (concat "org-" type "-complete-link"))))
9419 (if (functionp fun)
9420 (funcall fun)
9421 (read-string "Link (no completion support): " (concat type ":")))))
9423 (defun org-file-complete-link (&optional arg)
9424 "Create a file link using completion."
9425 (let (file link)
9426 (setq file (read-file-name "File: "))
9427 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9428 (pwd1 (file-name-as-directory (abbreviate-file-name
9429 (expand-file-name ".")))))
9430 (cond
9431 ((equal arg '(16))
9432 (setq link (concat
9433 "file:"
9434 (abbreviate-file-name (expand-file-name file)))))
9435 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9436 (setq link (concat "file:" (match-string 1 file))))
9437 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9438 (expand-file-name file))
9439 (setq link (concat
9440 "file:" (match-string 1 (expand-file-name file)))))
9441 (t (setq link (concat "file:" file)))))
9442 link))
9444 (defun org-completing-read (&rest args)
9445 "Completing-read with SPACE being a normal character."
9446 (let ((enable-recursive-minibuffers t)
9447 (minibuffer-local-completion-map
9448 (copy-keymap minibuffer-local-completion-map)))
9449 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9450 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9451 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9452 (apply 'org-icompleting-read args)))
9454 (defun org-completing-read-no-i (&rest args)
9455 (let (org-completion-use-ido org-completion-use-iswitchb)
9456 (apply 'org-completing-read args)))
9458 (defun org-iswitchb-completing-read (prompt choices &rest args)
9459 "Use iswitch as a completing-read replacement to choose from choices.
9460 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9461 from."
9462 (let* ((iswitchb-use-virtual-buffers nil)
9463 (iswitchb-make-buflist-hook
9464 (lambda ()
9465 (setq iswitchb-temp-buflist choices))))
9466 (iswitchb-read-buffer prompt)))
9468 (defun org-icompleting-read (&rest args)
9469 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9470 (org-without-partial-completion
9471 (if (and org-completion-use-ido
9472 (fboundp 'ido-completing-read)
9473 (boundp 'ido-mode) ido-mode
9474 (listp (second args)))
9475 (let ((ido-enter-matching-directory nil))
9476 (apply 'ido-completing-read (concat (car args))
9477 (if (consp (car (nth 1 args)))
9478 (mapcar 'car (nth 1 args))
9479 (nth 1 args))
9480 (cddr args)))
9481 (if (and org-completion-use-iswitchb
9482 (boundp 'iswitchb-mode) iswitchb-mode
9483 (listp (second args)))
9484 (apply 'org-iswitchb-completing-read (concat (car args))
9485 (if (consp (car (nth 1 args)))
9486 (mapcar 'car (nth 1 args))
9487 (nth 1 args))
9488 (cddr args))
9489 (apply 'completing-read args)))))
9491 (defun org-extract-attributes (s)
9492 "Extract the attributes cookie from a string and set as text property."
9493 (let (a attr (start 0) key value)
9494 (save-match-data
9495 (when (string-match "{{\\([^}]+\\)}}$" s)
9496 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9497 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9498 (setq key (match-string 1 a) value (match-string 2 a)
9499 start (match-end 0)
9500 attr (plist-put attr (intern key) value))))
9501 (org-add-props s nil 'org-attr attr))
9504 (defun org-extract-attributes-from-string (tag)
9505 (let (key value attr)
9506 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9507 (setq key (match-string 1 tag) value (match-string 2 tag)
9508 tag (replace-match "" t t tag)
9509 attr (plist-put attr (intern key) value)))
9510 (cons tag attr)))
9512 (defun org-attributes-to-string (plist)
9513 "Format a property list into an HTML attribute list."
9514 (let ((s "") key value)
9515 (while plist
9516 (setq key (pop plist) value (pop plist))
9517 (and value
9518 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9521 ;;; Opening/following a link
9523 (defvar org-link-search-failed nil)
9525 (defvar org-open-link-functions nil
9526 "Hook for functions finding a plain text link.
9527 These functions must take a single argument, the link content.
9528 They will be called for links that look like [[link text][description]]
9529 when LINK TEXT does not have a protocol like \"http:\" and does not look
9530 like a filename (e.g. \"./blue.png\").
9532 These functions will be called *before* Org attempts to resolve the
9533 link by doing text searches in the current buffer - so if you want a
9534 link \"[[target]]\" to still find \"<<target>>\", your function should
9535 handle this as a special case.
9537 When the function does handle the link, it must return a non-nil value.
9538 If it decides that it is not responsible for this link, it must return
9539 nil to indicate that that Org-mode can continue with other options
9540 like exact and fuzzy text search.")
9542 (defun org-next-link ()
9543 "Move forward to the next link.
9544 If the link is in hidden text, expose it."
9545 (interactive)
9546 (when (and org-link-search-failed (eq this-command last-command))
9547 (goto-char (point-min))
9548 (message "Link search wrapped back to beginning of buffer"))
9549 (setq org-link-search-failed nil)
9550 (let* ((pos (point))
9551 (ct (org-context))
9552 (a (assoc :link ct)))
9553 (if a (goto-char (nth 2 a)))
9554 (if (re-search-forward org-any-link-re nil t)
9555 (progn
9556 (goto-char (match-beginning 0))
9557 (if (outline-invisible-p) (org-show-context)))
9558 (goto-char pos)
9559 (setq org-link-search-failed t)
9560 (error "No further link found"))))
9562 (defun org-previous-link ()
9563 "Move backward to the previous link.
9564 If the link is in hidden text, expose it."
9565 (interactive)
9566 (when (and org-link-search-failed (eq this-command last-command))
9567 (goto-char (point-max))
9568 (message "Link search wrapped back to end of buffer"))
9569 (setq org-link-search-failed nil)
9570 (let* ((pos (point))
9571 (ct (org-context))
9572 (a (assoc :link ct)))
9573 (if a (goto-char (nth 1 a)))
9574 (if (re-search-backward org-any-link-re nil t)
9575 (progn
9576 (goto-char (match-beginning 0))
9577 (if (outline-invisible-p) (org-show-context)))
9578 (goto-char pos)
9579 (setq org-link-search-failed t)
9580 (error "No further link found"))))
9582 (defun org-translate-link (s)
9583 "Translate a link string if a translation function has been defined."
9584 (if (and org-link-translation-function
9585 (fboundp org-link-translation-function)
9586 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9587 (progn
9588 (setq s (funcall org-link-translation-function
9589 (match-string 1 s) (match-string 2 s)))
9590 (concat (car s) ":" (cdr s)))
9593 (defun org-translate-link-from-planner (type path)
9594 "Translate a link from Emacs Planner syntax so that Org can follow it.
9595 This is still an experimental function, your mileage may vary."
9596 (cond
9597 ((member type '("http" "https" "news" "ftp"))
9598 ;; standard Internet links are the same.
9599 nil)
9600 ((and (equal type "irc") (string-match "^//" path))
9601 ;; Planner has two / at the beginning of an irc link, we have 1.
9602 ;; We should have zero, actually....
9603 (setq path (substring path 1)))
9604 ((and (equal type "lisp") (string-match "^/" path))
9605 ;; Planner has a slash, we do not.
9606 (setq type "elisp" path (substring path 1)))
9607 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9608 ;; A typical message link. Planner has the id after the final slash,
9609 ;; we separate it with a hash mark
9610 (setq path (concat (match-string 1 path) "#"
9611 (org-remove-angle-brackets (match-string 2 path)))))
9613 (cons type path))
9615 (defun org-find-file-at-mouse (ev)
9616 "Open file link or URL at mouse."
9617 (interactive "e")
9618 (mouse-set-point ev)
9619 (org-open-at-point 'in-emacs))
9621 (defun org-open-at-mouse (ev)
9622 "Open file link or URL at mouse.
9623 See the docstring of `org-open-file' for details."
9624 (interactive "e")
9625 (mouse-set-point ev)
9626 (if (eq major-mode 'org-agenda-mode)
9627 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9628 (org-open-at-point))
9630 (defvar org-window-config-before-follow-link nil
9631 "The window configuration before following a link.
9632 This is saved in case the need arises to restore it.")
9634 (defvar org-open-link-marker (make-marker)
9635 "Marker pointing to the location where `org-open-at-point; was called.")
9637 ;;;###autoload
9638 (defun org-open-at-point-global ()
9639 "Follow a link like Org-mode does.
9640 This command can be called in any mode to follow a link that has
9641 Org-mode syntax."
9642 (interactive)
9643 (org-run-like-in-org-mode 'org-open-at-point))
9645 ;;;###autoload
9646 (defun org-open-link-from-string (s &optional arg reference-buffer)
9647 "Open a link in the string S, as if it was in Org-mode."
9648 (interactive "sLink: \nP")
9649 (let ((reference-buffer (or reference-buffer (current-buffer))))
9650 (with-temp-buffer
9651 (let ((org-inhibit-startup (not reference-buffer)))
9652 (org-mode)
9653 (insert s)
9654 (goto-char (point-min))
9655 (when reference-buffer
9656 (setq org-link-abbrev-alist-local
9657 (with-current-buffer reference-buffer
9658 org-link-abbrev-alist-local)))
9659 (org-open-at-point arg reference-buffer)))))
9661 (defvar org-open-at-point-functions nil
9662 "Hook that is run when following a link at point.
9664 Functions in this hook must return t if they identify and follow
9665 a link at point. If they don't find anything interesting at point,
9666 they must return nil.")
9668 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9669 (defun org-open-at-point (&optional arg reference-buffer)
9670 "Open link at or after point.
9671 If there is no link at point, this function will search forward up to
9672 the end of the current line.
9673 Normally, files will be opened by an appropriate application. If the
9674 optional prefix argument ARG is non-nil, Emacs will visit the file.
9675 With a double prefix argument, try to open outside of Emacs, in the
9676 application the system uses for this file type."
9677 (interactive "P")
9678 ;; if in a code block, then open the block's results
9679 (unless (call-interactively #'org-babel-open-src-block-result)
9680 (org-load-modules-maybe)
9681 (move-marker org-open-link-marker (point))
9682 (setq org-window-config-before-follow-link (current-window-configuration))
9683 (org-remove-occur-highlights nil nil t)
9684 (cond
9685 ((and (org-at-heading-p)
9686 (not (org-at-timestamp-p t))
9687 (not (org-in-regexp
9688 (concat org-plain-link-re "\\|"
9689 org-bracket-link-regexp "\\|"
9690 org-angle-link-re "\\|"
9691 "[ \t]:[^ \t\n]+:[ \t]*$")))
9692 (not (get-text-property (point) 'org-linked-text)))
9693 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
9694 (lk0 (car lkall))
9695 (lk (if (stringp lk0) (list lk0) lk0))
9696 (lkend (cdr lkall)))
9697 (mapcar (lambda(l)
9698 (search-forward l nil lkend)
9699 (goto-char (match-beginning 0))
9700 (org-open-at-point))
9701 lk))
9702 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9703 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9704 ((and (org-at-timestamp-p t)
9705 (not (org-in-regexp org-bracket-link-regexp)))
9706 (org-follow-timestamp-link))
9707 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9708 (not (org-in-regexp org-any-link-re)))
9709 (org-footnote-action))
9711 (let (type path link line search (pos (point)))
9712 (catch 'match
9713 (save-excursion
9714 (skip-chars-forward "^]\n\r")
9715 (when (org-in-regexp org-bracket-link-regexp 1)
9716 (setq link (org-extract-attributes
9717 (org-link-unescape (org-match-string-no-properties 1))))
9718 (while (string-match " *\n *" link)
9719 (setq link (replace-match " " t t link)))
9720 (setq link (org-link-expand-abbrev link))
9721 (cond
9722 ((or (file-name-absolute-p link)
9723 (string-match "^\\.\\.?/" link))
9724 (setq type "file" path link))
9725 ((string-match org-link-re-with-space3 link)
9726 (setq type (match-string 1 link) path (match-string 2 link)))
9727 ((string-match "^help:+\\(.+\\)" link)
9728 (setq type "help" path (match-string 1 link)))
9729 (t (setq type "thisfile" path link)))
9730 (throw 'match t)))
9732 (when (get-text-property (point) 'org-linked-text)
9733 (setq type "thisfile"
9734 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9735 (1+ (point)) (point))
9736 path (buffer-substring
9737 (or (previous-single-property-change pos 'org-linked-text)
9738 (point-min))
9739 (or (next-single-property-change pos 'org-linked-text)
9740 (point-max))))
9741 (throw 'match t))
9743 (save-excursion
9744 (let ((plinkpos (org-in-regexp org-plain-link-re)))
9745 (when (or (org-in-regexp org-angle-link-re)
9746 (and plinkpos (goto-char (car plinkpos))
9747 (save-match-data (not (looking-back "\\[\\[")))))
9748 (setq type (match-string 1)
9749 path (org-link-unescape (match-string 2)))
9750 (throw 'match t))))
9751 (save-excursion
9752 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9753 (setq type "tags"
9754 path (match-string 1))
9755 (while (string-match ":" path)
9756 (setq path (replace-match "+" t t path)))
9757 (throw 'match t)))
9758 (when (org-in-regexp "<\\([^><\n]+\\)>")
9759 (setq type "tree-match"
9760 path (match-string 1))
9761 (throw 'match t)))
9762 (unless path
9763 (user-error "No link found"))
9765 ;; switch back to reference buffer
9766 ;; needed when if called in a temporary buffer through
9767 ;; org-open-link-from-string
9768 (with-current-buffer (or reference-buffer (current-buffer))
9770 ;; Remove any trailing spaces in path
9771 (if (string-match " +\\'" path)
9772 (setq path (replace-match "" t t path)))
9773 (if (and org-link-translation-function
9774 (fboundp org-link-translation-function))
9775 ;; Check if we need to translate the link
9776 (let ((tmp (funcall org-link-translation-function type path)))
9777 (setq type (car tmp) path (cdr tmp))))
9779 (cond
9781 ((assoc type org-link-protocols)
9782 (funcall (nth 1 (assoc type org-link-protocols)) path))
9784 ((equal type "help")
9785 (let ((f-or-v (intern path)))
9786 (cond ((fboundp f-or-v)
9787 (describe-function f-or-v))
9788 ((boundp f-or-v)
9789 (describe-variable f-or-v))
9790 (t (error "Not a known function or variable")))))
9792 ((equal type "mailto")
9793 (let ((cmd (car org-link-mailto-program))
9794 (args (cdr org-link-mailto-program)) args1
9795 (address path) (subject "") a)
9796 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9797 (setq address (match-string 1 path)
9798 subject (org-link-escape (match-string 2 path))))
9799 (while args
9800 (cond
9801 ((not (stringp (car args))) (push (pop args) args1))
9802 (t (setq a (pop args))
9803 (if (string-match "%a" a)
9804 (setq a (replace-match address t t a)))
9805 (if (string-match "%s" a)
9806 (setq a (replace-match subject t t a)))
9807 (push a args1))))
9808 (apply cmd (nreverse args1))))
9810 ((member type '("http" "https" "ftp" "news"))
9811 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9812 (org-link-escape
9813 path org-link-escape-chars-browser)
9814 path))))
9816 ((string= type "doi")
9817 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9818 (org-link-escape
9819 path org-link-escape-chars-browser)
9820 path))))
9822 ((member type '("message"))
9823 (browse-url (concat type ":" path)))
9825 ((string= type "tags")
9826 (org-tags-view arg path))
9828 ((string= type "tree-match")
9829 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9831 ((string= type "file")
9832 (if (string-match "::\\([0-9]+\\)\\'" path)
9833 (setq line (string-to-number (match-string 1 path))
9834 path (substring path 0 (match-beginning 0)))
9835 (if (string-match "::\\(.+\\)\\'" path)
9836 (setq search (match-string 1 path)
9837 path (substring path 0 (match-beginning 0)))))
9838 (if (string-match "[*?{]" (file-name-nondirectory path))
9839 (dired path)
9840 (org-open-file path arg line search)))
9842 ((string= type "shell")
9843 (let ((buf (generate-new-buffer "*Org Shell Output"))
9844 (cmd path))
9845 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9846 (string-match org-confirm-shell-link-not-regexp cmd))
9847 (not org-confirm-shell-link-function)
9848 (funcall org-confirm-shell-link-function
9849 (format "Execute \"%s\" in shell? "
9850 (org-add-props cmd nil
9851 'face 'org-warning))))
9852 (progn
9853 (message "Executing %s" cmd)
9854 (shell-command cmd buf)
9855 (if (featurep 'midnight)
9856 (setq clean-buffer-list-kill-buffer-names
9857 (cons buf clean-buffer-list-kill-buffer-names))))
9858 (error "Abort"))))
9860 ((string= type "elisp")
9861 (let ((cmd path))
9862 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9863 (string-match org-confirm-elisp-link-not-regexp cmd))
9864 (not org-confirm-elisp-link-function)
9865 (funcall org-confirm-elisp-link-function
9866 (format "Execute \"%s\" as elisp? "
9867 (org-add-props cmd nil
9868 'face 'org-warning))))
9869 (message "%s => %s" cmd
9870 (if (equal (string-to-char cmd) ?\()
9871 (eval (read cmd))
9872 (call-interactively (read cmd))))
9873 (error "Abort"))))
9875 ((and (string= type "thisfile")
9876 (run-hook-with-args-until-success
9877 'org-open-link-functions path)))
9879 ((string= type "thisfile")
9880 (if arg
9881 (switch-to-buffer-other-window
9882 (org-get-buffer-for-internal-link (current-buffer)))
9883 (org-mark-ring-push))
9884 (let ((cmd `(org-link-search
9885 ,path
9886 ,(cond ((equal arg '(4)) ''occur)
9887 ((equal arg '(16)) ''org-occur))
9888 ,pos)))
9889 (condition-case nil (let ((org-link-search-inhibit-query t))
9890 (eval cmd))
9891 (error (progn (widen) (eval cmd))))))
9893 (t (browse-url-at-point)))))))
9894 (move-marker org-open-link-marker nil)
9895 (run-hook-with-args 'org-follow-link-hook)))
9897 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
9898 "Offer links in the current entry and return the selected link.
9899 If there is only one link, return it.
9900 If NTH is an integer, return the NTH link found.
9901 If ZERO is a string, check also this string for a link, and if
9902 there is one, return it."
9903 (with-current-buffer buffer
9904 (save-excursion
9905 (save-restriction
9906 (widen)
9907 (goto-char marker)
9908 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9909 "\\(" org-angle-link-re "\\)\\|"
9910 "\\(" org-plain-link-re "\\)"))
9911 (cnt ?0)
9912 (in-emacs (if (integerp nth) nil nth))
9913 have-zero end links link c)
9914 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9915 (push (match-string 0 zero) links)
9916 (setq cnt (1- cnt) have-zero t))
9917 (save-excursion
9918 (org-back-to-heading t)
9919 (setq end (save-excursion (outline-next-heading) (point)))
9920 (while (re-search-forward re end t)
9921 (push (match-string 0) links))
9922 (setq links (org-uniquify (reverse links))))
9923 (cond
9924 ((null links)
9925 (message "No links"))
9926 ((equal (length links) 1)
9927 (setq link (car links)))
9928 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9929 (setq link (nth (if have-zero nth (1- nth)) links)))
9930 (t ; we have to select a link
9931 (save-excursion
9932 (save-window-excursion
9933 (delete-other-windows)
9934 (with-output-to-temp-buffer "*Select Link*"
9935 (mapc (lambda (l)
9936 (if (not (string-match org-bracket-link-regexp l))
9937 (princ (format "[%c] %s\n" (incf cnt)
9938 (org-remove-angle-brackets l)))
9939 (if (match-end 3)
9940 (princ (format "[%c] %s (%s)\n" (incf cnt)
9941 (match-string 3 l) (match-string 1 l)))
9942 (princ (format "[%c] %s\n" (incf cnt)
9943 (match-string 1 l))))))
9944 links))
9945 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9946 (message "Select link to open, RET to open all:")
9947 (setq c (read-char-exclusive))
9948 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9949 (when (equal c ?q) (error "Abort"))
9950 (if (equal c ?\C-m)
9951 (setq link links)
9952 (setq nth (- c ?0))
9953 (if have-zero (setq nth (1+ nth)))
9954 (unless (and (integerp nth) (>= (length links) nth))
9955 (error "Invalid link selection"))
9956 (setq link (nth (1- nth) links)))))
9957 (cons link end))))))
9959 ;; Add special file links that specify the way of opening
9961 (org-add-link-type "file+sys" 'org-open-file-with-system)
9962 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9963 (defun org-open-file-with-system (path)
9964 "Open file at PATH using the system way of opening it."
9965 (org-open-file path 'system))
9966 (defun org-open-file-with-emacs (path)
9967 "Open file at PATH in Emacs."
9968 (org-open-file path 'emacs))
9969 (defun org-remove-file-link-modifiers ()
9970 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9971 (goto-char (point-min))
9972 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9973 (org-if-unprotected
9974 (replace-match "file:" t t))))
9975 (eval-after-load "org-exp"
9976 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9977 'org-remove-file-link-modifiers))
9979 ;;; File search
9981 (defvar org-create-file-search-functions nil
9982 "List of functions to construct the right search string for a file link.
9983 These functions are called in turn with point at the location to
9984 which the link should point.
9986 A function in the hook should first test if it would like to
9987 handle this file type, for example by checking the `major-mode'
9988 or the file extension. If it decides not to handle this file, it
9989 should just return nil to give other functions a chance. If it
9990 does handle the file, it must return the search string to be used
9991 when following the link. The search string will be part of the
9992 file link, given after a double colon, and `org-open-at-point'
9993 will automatically search for it. If special measures must be
9994 taken to make the search successful, another function should be
9995 added to the companion hook `org-execute-file-search-functions',
9996 which see.
9998 A function in this hook may also use `setq' to set the variable
9999 `description' to provide a suggestion for the descriptive text to
10000 be used for this link when it gets inserted into an Org-mode
10001 buffer with \\[org-insert-link].")
10003 (defvar org-execute-file-search-functions nil
10004 "List of functions to execute a file search triggered by a link.
10006 Functions added to this hook must accept a single argument, the
10007 search string that was part of the file link, the part after the
10008 double colon. The function must first check if it would like to
10009 handle this search, for example by checking the `major-mode' or
10010 the file extension. If it decides not to handle this search, it
10011 should just return nil to give other functions a chance. If it
10012 does handle the search, it must return a non-nil value to keep
10013 other functions from trying.
10015 Each function can access the current prefix argument through the
10016 variable `current-prefix-argument'. Note that a single prefix is
10017 used to force opening a link in Emacs, so it may be good to only
10018 use a numeric or double prefix to guide the search function.
10020 In case this is needed, a function in this hook can also restore
10021 the window configuration before `org-open-at-point' was called using:
10023 (set-window-configuration org-window-config-before-follow-link)")
10025 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10026 (defun org-link-search (s &optional type avoid-pos stealth)
10027 "Search for a link search option.
10028 If S is surrounded by forward slashes, it is interpreted as a
10029 regular expression. In org-mode files, this will create an `org-occur'
10030 sparse tree. In ordinary files, `occur' will be used to list matches.
10031 If the current buffer is in `dired-mode', grep will be used to search
10032 in all files. If AVOID-POS is given, ignore matches near that position.
10034 When optional argument STEALTH is non-nil, do not modify
10035 visibility around point, thus ignoring
10036 `org-show-hierarchy-above', `org-show-following-heading' and
10037 `org-show-siblings' variables."
10038 (let ((case-fold-search t)
10039 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10040 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10041 (append '(("") (" ") ("\t") ("\n"))
10042 org-emphasis-alist)
10043 "\\|") "\\)"))
10044 (pos (point))
10045 (pre nil) (post nil)
10046 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10047 (cond
10048 ;; First check if there are any special search functions
10049 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10050 ;; Now try the builtin stuff
10051 ((and (equal (string-to-char s0) ?#)
10052 (> (length s0) 1)
10053 (save-excursion
10054 (goto-char (point-min))
10055 (and
10056 (re-search-forward
10057 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10058 (setq type 'dedicated
10059 pos (match-beginning 0))))
10060 ;; There is an exact target for this
10061 (goto-char pos)
10062 (org-back-to-heading t)))
10063 ((save-excursion
10064 (goto-char (point-min))
10065 (and
10066 (re-search-forward
10067 (concat "<<" (regexp-quote s0) ">>") nil t)
10068 (setq type 'dedicated
10069 pos (match-beginning 0))))
10070 ;; There is an exact target for this
10071 (goto-char pos))
10072 ((save-excursion
10073 (goto-char (point-min))
10074 (and
10075 (re-search-forward
10076 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10077 (setq type 'dedicated pos (match-beginning 0))))
10078 ;; Found an invisible target.
10079 (goto-char pos))
10080 ((save-excursion
10081 (goto-char (point-min))
10082 (and
10083 (re-search-forward
10084 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10085 (setq type 'dedicated pos (match-beginning 0))))
10086 ;; Found an element with a matching #+name affiliated keyword.
10087 (goto-char pos))
10088 ((and (string-match "^(\\(.*\\))$" s0)
10089 (save-excursion
10090 (goto-char (point-min))
10091 (and
10092 (re-search-forward
10093 (concat "[^[]" (regexp-quote
10094 (format org-coderef-label-format
10095 (match-string 1 s0))))
10096 nil t)
10097 (setq type 'dedicated
10098 pos (1+ (match-beginning 0))))))
10099 ;; There is a coderef target for this
10100 (goto-char pos))
10101 ((string-match "^/\\(.*\\)/$" s)
10102 ;; A regular expression
10103 (cond
10104 ((derived-mode-p 'org-mode)
10105 (org-occur (match-string 1 s)))
10106 ;;((eq major-mode 'dired-mode)
10107 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10108 (t (org-do-occur (match-string 1 s)))))
10109 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10110 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10111 (goto-char (point-min))
10112 (cond
10113 ((let (case-fold-search)
10114 (re-search-forward (format org-complex-heading-regexp-format
10115 (regexp-quote s))
10116 nil t))
10117 ;; OK, found a match
10118 (setq type 'dedicated)
10119 (goto-char (match-beginning 0)))
10120 ((and (not org-link-search-inhibit-query)
10121 (eq org-link-search-must-match-exact-headline 'query-to-create)
10122 (y-or-n-p "No match - create this as a new heading? "))
10123 (goto-char (point-max))
10124 (or (bolp) (newline))
10125 (insert "* " s "\n")
10126 (beginning-of-line 0))
10128 (goto-char pos)
10129 (error "No match"))))
10131 ;; A normal search string
10132 (when (equal (string-to-char s) ?*)
10133 ;; Anchor on headlines, post may include tags.
10134 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10135 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10136 s (substring s 1)))
10137 (remove-text-properties
10138 0 (length s)
10139 '(face nil mouse-face nil keymap nil fontified nil) s)
10140 ;; Make a series of regular expressions to find a match
10141 (setq words (org-split-string s "[ \n\r\t]+")
10143 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10144 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10145 "\\)" markers)
10146 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10147 re2a (concat "[ \t\r\n]" re2a_)
10148 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10149 re4 (concat "[^a-zA-Z_]" re4_)
10151 re1 (concat pre re2 post)
10152 re3 (concat pre (if pre re4_ re4) post)
10153 re5 (concat pre ".*" re4)
10154 re2 (concat pre re2)
10155 re2a (concat pre (if pre re2a_ re2a))
10156 re4 (concat pre (if pre re4_ re4))
10157 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10158 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10159 re5 "\\)"
10161 (cond
10162 ((eq type 'org-occur) (org-occur reall))
10163 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10164 (t (goto-char (point-min))
10165 (setq type 'fuzzy)
10166 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10167 (org-search-not-self 1 re1 nil t)
10168 (org-search-not-self 1 re2 nil t)
10169 (org-search-not-self 1 re2a nil t)
10170 (org-search-not-self 1 re3 nil t)
10171 (org-search-not-self 1 re4 nil t)
10172 (org-search-not-self 1 re5 nil t)
10174 (goto-char (match-beginning 1))
10175 (goto-char pos)
10176 (error "No match"))))))
10177 (and (derived-mode-p 'org-mode)
10178 (not stealth)
10179 (org-show-context 'link-search))
10180 type))
10182 (defun org-search-not-self (group &rest args)
10183 "Execute `re-search-forward', but only accept matches that do not
10184 enclose the position of `org-open-link-marker'."
10185 (let ((m org-open-link-marker))
10186 (catch 'exit
10187 (while (apply 're-search-forward args)
10188 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10189 (goto-char (match-end group))
10190 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10191 (> (match-beginning 0) (marker-position m))
10192 (< (match-end 0) (marker-position m)))
10193 (save-match-data
10194 (or (not (org-in-regexp
10195 org-bracket-link-analytic-regexp 1))
10196 (not (match-end 4)) ; no description
10197 (and (<= (match-beginning 4) (point))
10198 (>= (match-end 4) (point))))))
10199 (throw 'exit (point))))))))
10201 (defun org-get-buffer-for-internal-link (buffer)
10202 "Return a buffer to be used for displaying the link target of internal links."
10203 (cond
10204 ((not org-display-internal-link-with-indirect-buffer)
10205 buffer)
10206 ((string-match "(Clone)$" (buffer-name buffer))
10207 (message "Buffer is already a clone, not making another one")
10208 ;; we also do not modify visibility in this case
10209 buffer)
10210 (t ; make a new indirect buffer for displaying the link
10211 (let* ((bn (buffer-name buffer))
10212 (ibn (concat bn "(Clone)"))
10213 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10214 (with-current-buffer ib (org-overview))
10215 ib))))
10217 (defun org-do-occur (regexp &optional cleanup)
10218 "Call the Emacs command `occur'.
10219 If CLEANUP is non-nil, remove the printout of the regular expression
10220 in the *Occur* buffer. This is useful if the regex is long and not useful
10221 to read."
10222 (occur regexp)
10223 (when cleanup
10224 (let ((cwin (selected-window)) win beg end)
10225 (when (setq win (get-buffer-window "*Occur*"))
10226 (select-window win))
10227 (goto-char (point-min))
10228 (when (re-search-forward "match[a-z]+" nil t)
10229 (setq beg (match-end 0))
10230 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10231 (setq end (1- (match-beginning 0)))))
10232 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10233 (goto-char (point-min))
10234 (select-window cwin))))
10236 ;;; The mark ring for links jumps
10238 (defvar org-mark-ring nil
10239 "Mark ring for positions before jumps in Org-mode.")
10240 (defvar org-mark-ring-last-goto nil
10241 "Last position in the mark ring used to go back.")
10242 ;; Fill and close the ring
10243 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10244 (loop for i from 1 to org-mark-ring-length do
10245 (push (make-marker) org-mark-ring))
10246 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10247 org-mark-ring)
10249 (defun org-mark-ring-push (&optional pos buffer)
10250 "Put the current position or POS into the mark ring and rotate it."
10251 (interactive)
10252 (setq pos (or pos (point)))
10253 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10254 (move-marker (car org-mark-ring)
10255 (or pos (point))
10256 (or buffer (current-buffer)))
10257 (message "%s"
10258 (substitute-command-keys
10259 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10261 (defun org-mark-ring-goto (&optional n)
10262 "Jump to the previous position in the mark ring.
10263 With prefix arg N, jump back that many stored positions. When
10264 called several times in succession, walk through the entire ring.
10265 Org-mode commands jumping to a different position in the current file,
10266 or to another Org-mode file, automatically push the old position
10267 onto the ring."
10268 (interactive "p")
10269 (let (p m)
10270 (if (eq last-command this-command)
10271 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10272 (setq p org-mark-ring))
10273 (setq org-mark-ring-last-goto p)
10274 (setq m (car p))
10275 (org-pop-to-buffer-same-window (marker-buffer m))
10276 (goto-char m)
10277 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10279 (defun org-remove-angle-brackets (s)
10280 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10281 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10283 (defun org-add-angle-brackets (s)
10284 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10285 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10287 (defun org-remove-double-quotes (s)
10288 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10289 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10292 ;;; Following specific links
10294 (defun org-follow-timestamp-link ()
10295 "Open an agenda view for the time-stamp date/range at point."
10296 (cond
10297 ((org-at-date-range-p t)
10298 (let ((org-agenda-start-on-weekday)
10299 (t1 (match-string 1))
10300 (t2 (match-string 2)) tt1 tt2)
10301 (setq tt1 (time-to-days (org-time-string-to-time t1))
10302 tt2 (time-to-days (org-time-string-to-time t2)))
10303 (let ((org-agenda-buffer-tmp-name
10304 (format "*Org Agenda(a:%s)"
10305 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10306 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10307 ((org-at-timestamp-p t)
10308 (let ((org-agenda-buffer-tmp-name
10309 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10310 (org-agenda-list nil (time-to-days (org-time-string-to-time
10311 (substring (match-string 1) 0 10)))
10312 1)))
10313 (t (error "This should not happen"))))
10316 ;;; Following file links
10317 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10318 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10319 (declare-function mailcap-mime-info
10320 "mailcap" (string &optional request no-decode))
10321 (defvar org-wait nil)
10322 (defun org-open-file (path &optional in-emacs line search)
10323 "Open the file at PATH.
10324 First, this expands any special file name abbreviations. Then the
10325 configuration variable `org-file-apps' is checked if it contains an
10326 entry for this file type, and if yes, the corresponding command is launched.
10328 If no application is found, Emacs simply visits the file.
10330 With optional prefix argument IN-EMACS, Emacs will visit the file.
10331 With a double \\[universal-argument] \\[universal-argument] \
10332 prefix arg, Org tries to avoid opening in Emacs
10333 and to use an external application to visit the file.
10335 Optional LINE specifies a line to go to, optional SEARCH a string
10336 to search for. If LINE or SEARCH is given, the file will be
10337 opened in Emacs, unless an entry from org-file-apps that makes
10338 use of groups in a regexp matches.
10340 If you want to change the way frames are used when following a
10341 link, please customize `org-link-frame-setup'.
10343 If the file does not exist, an error is thrown."
10344 (let* ((file (if (equal path "")
10345 buffer-file-name
10346 (substitute-in-file-name (expand-file-name path))))
10347 (file-apps (append org-file-apps (org-default-apps)))
10348 (apps (org-remove-if
10349 'org-file-apps-entry-match-against-dlink-p file-apps))
10350 (apps-dlink (org-remove-if-not
10351 'org-file-apps-entry-match-against-dlink-p file-apps))
10352 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10353 (dirp (if remp nil (file-directory-p file)))
10354 (file (if (and dirp org-open-directory-means-index-dot-org)
10355 (concat (file-name-as-directory file) "index.org")
10356 file))
10357 (a-m-a-p (assq 'auto-mode apps))
10358 (dfile (downcase file))
10359 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10360 (link (cond ((and (eq line nil)
10361 (eq search nil))
10362 file)
10363 (line
10364 (concat file "::" (number-to-string line)))
10365 (search
10366 (concat file "::" search))))
10367 (dlink (downcase link))
10368 (old-buffer (current-buffer))
10369 (old-pos (point))
10370 (old-mode major-mode)
10371 ext cmd link-match-data)
10372 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10373 (setq ext (match-string 1 dfile))
10374 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10375 (setq ext (match-string 1 dfile))))
10376 (cond
10377 ((member in-emacs '((16) system))
10378 (setq cmd (cdr (assoc 'system apps))))
10379 (in-emacs (setq cmd 'emacs))
10381 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10382 (and dirp (cdr (assoc 'directory apps)))
10383 ; first, try matching against apps-dlink
10384 ; if we get a match here, store the match data for later
10385 (let ((match (assoc-default dlink apps-dlink
10386 'string-match)))
10387 (if match
10388 (progn (setq link-match-data (match-data))
10389 match)
10390 (progn (setq in-emacs (or in-emacs line search))
10391 nil))) ; if we have no match in apps-dlink,
10392 ; always open the file in emacs if line or search
10393 ; is given (for backwards compatibility)
10394 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10395 'string-match)
10396 (cdr (assoc ext apps))
10397 (cdr (assoc t apps))))))
10398 (when (eq cmd 'system)
10399 (setq cmd (cdr (assoc 'system apps))))
10400 (when (eq cmd 'default)
10401 (setq cmd (cdr (assoc t apps))))
10402 (when (eq cmd 'mailcap)
10403 (require 'mailcap)
10404 (mailcap-parse-mailcaps)
10405 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10406 (command (mailcap-mime-info mime-type)))
10407 (if (stringp command)
10408 (setq cmd command)
10409 (setq cmd 'emacs))))
10410 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10411 (not (file-exists-p file))
10412 (not org-open-non-existing-files))
10413 (error "No such file: %s" file))
10414 (cond
10415 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10416 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10417 (while (string-match "['\"]%s['\"]" cmd)
10418 (setq cmd (replace-match "%s" t t cmd)))
10419 (while (string-match "%s" cmd)
10420 (setq cmd (replace-match
10421 (save-match-data
10422 (shell-quote-argument
10423 (convert-standard-filename file)))
10424 t t cmd)))
10426 ;; Replace "%1", "%2" etc. in command with group matches from regex
10427 (save-match-data
10428 (let ((match-index 1)
10429 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10430 (set-match-data link-match-data)
10431 (while (<= match-index number-of-groups)
10432 (let ((regex (concat "%" (number-to-string match-index)))
10433 (replace-with (match-string match-index dlink)))
10434 (while (string-match regex cmd)
10435 (setq cmd (replace-match replace-with t t cmd))))
10436 (setq match-index (+ match-index 1)))))
10438 (save-window-excursion
10439 (start-process-shell-command cmd nil cmd)
10440 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10442 ((or (stringp cmd)
10443 (eq cmd 'emacs))
10444 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10445 (widen)
10446 (if line (org-goto-line line)
10447 (if search (org-link-search search))))
10448 ((consp cmd)
10449 (let ((file (convert-standard-filename file)))
10450 (save-match-data
10451 (set-match-data link-match-data)
10452 (eval cmd))))
10453 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10454 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10455 (or (not (equal old-buffer (current-buffer)))
10456 (not (equal old-pos (point))))
10457 (org-mark-ring-push old-pos old-buffer))))
10459 (defun org-file-apps-entry-match-against-dlink-p (entry)
10460 "This function returns non-nil if `entry' uses a regular
10461 expression which should be matched against the whole link by
10462 org-open-file.
10464 It assumes that is the case when the entry uses a regular
10465 expression which has at least one grouping construct and the
10466 action is either a lisp form or a command string containing
10467 '%1', i.e. using at least one subexpression match as a
10468 parameter."
10469 (let ((selector (car entry))
10470 (action (cdr entry)))
10471 (if (stringp selector)
10472 (and (> (regexp-opt-depth selector) 0)
10473 (or (and (stringp action)
10474 (string-match "%[0-9]" action))
10475 (consp action)))
10476 nil)))
10478 (defun org-default-apps ()
10479 "Return the default applications for this operating system."
10480 (cond
10481 ((eq system-type 'darwin)
10482 org-file-apps-defaults-macosx)
10483 ((eq system-type 'windows-nt)
10484 org-file-apps-defaults-windowsnt)
10485 (t org-file-apps-defaults-gnu)))
10487 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10488 "Convert extensions to regular expressions in the cars of LIST.
10489 Also, weed out any non-string entries, because the return value is used
10490 only for regexp matching.
10491 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10492 point to the symbol `emacs', indicating that the file should
10493 be opened in Emacs."
10494 (append
10495 (delq nil
10496 (mapcar (lambda (x)
10497 (if (not (stringp (car x)))
10499 (if (string-match "\\W" (car x))
10501 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10502 list))
10503 (if add-auto-mode
10504 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10506 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10507 (defun org-file-remote-p (file)
10508 "Test whether FILE specifies a location on a remote system.
10509 Return non-nil if the location is indeed remote.
10511 For example, the filename \"/user@host:/foo\" specifies a location
10512 on the system \"/user@host:\"."
10513 (cond ((fboundp 'file-remote-p)
10514 (file-remote-p file))
10515 ((fboundp 'tramp-handle-file-remote-p)
10516 (tramp-handle-file-remote-p file))
10517 ((and (boundp 'ange-ftp-name-format)
10518 (string-match (car ange-ftp-name-format) file))
10519 t)))
10522 ;;;; Refiling
10524 (defun org-get-org-file ()
10525 "Read a filename, with default directory `org-directory'."
10526 (let ((default (or org-default-notes-file remember-data-file)))
10527 (read-file-name (format "File name [%s]: " default)
10528 (file-name-as-directory org-directory)
10529 default)))
10531 (defun org-notes-order-reversed-p ()
10532 "Check if the current file should receive notes in reversed order."
10533 (cond
10534 ((not org-reverse-note-order) nil)
10535 ((eq t org-reverse-note-order) t)
10536 ((not (listp org-reverse-note-order)) nil)
10537 (t (catch 'exit
10538 (let ((all org-reverse-note-order)
10539 entry)
10540 (while (setq entry (pop all))
10541 (if (string-match (car entry) buffer-file-name)
10542 (throw 'exit (cdr entry))))
10543 nil)))))
10545 (defvar org-refile-target-table nil
10546 "The list of refile targets, created by `org-refile'.")
10548 (defvar org-agenda-new-buffers nil
10549 "Buffers created to visit agenda files.")
10551 (defvar org-refile-cache nil
10552 "Cache for refile targets.")
10554 (defvar org-refile-markers nil
10555 "All the markers used for caching refile locations.")
10557 (defun org-refile-marker (pos)
10558 "Get a new refile marker, but only if caching is in use."
10559 (if (not org-refile-use-cache)
10561 (let ((m (make-marker)))
10562 (move-marker m pos)
10563 (push m org-refile-markers)
10564 m)))
10566 (defun org-refile-cache-clear ()
10567 "Clear the refile cache and disable all the markers."
10568 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10569 (setq org-refile-markers nil)
10570 (setq org-refile-cache nil)
10571 (message "Refile cache has been cleared"))
10573 (defun org-refile-cache-check-set (set)
10574 "Check if all the markers in the cache still have live buffers."
10575 (let (marker)
10576 (catch 'exit
10577 (while (and set (setq marker (nth 3 (pop set))))
10578 ;; if org-refile-use-outline-path is 'file, marker may be nil
10579 (when (and marker (null (marker-buffer marker)))
10580 (message "not found") (sit-for 3)
10581 (throw 'exit nil)))
10582 t)))
10584 (defun org-refile-cache-put (set &rest identifiers)
10585 "Push the refile targets SET into the cache, under IDENTIFIERS."
10586 (let* ((key (sha1 (prin1-to-string identifiers)))
10587 (entry (assoc key org-refile-cache)))
10588 (if entry
10589 (setcdr entry set)
10590 (push (cons key set) org-refile-cache))))
10592 (defun org-refile-cache-get (&rest identifiers)
10593 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10594 (cond
10595 ((not org-refile-cache) nil)
10596 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10598 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10599 org-refile-cache))))
10600 (and set (org-refile-cache-check-set set) set)))))
10602 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10603 "Produce a table with refile targets."
10604 (let ((case-fold-search nil)
10605 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10606 (entries (or org-refile-targets '((nil . (:level . 1)))))
10607 targets tgs txt re files f desc descre fast-path-p level pos0)
10608 (message "Getting targets...")
10609 (with-current-buffer (or default-buffer (current-buffer))
10610 (while (setq entry (pop entries))
10611 (setq files (car entry) desc (cdr entry))
10612 (setq fast-path-p nil)
10613 (cond
10614 ((null files) (setq files (list (current-buffer))))
10615 ((eq files 'org-agenda-files)
10616 (setq files (org-agenda-files 'unrestricted)))
10617 ((and (symbolp files) (fboundp files))
10618 (setq files (funcall files)))
10619 ((and (symbolp files) (boundp files))
10620 (setq files (symbol-value files))))
10621 (if (stringp files) (setq files (list files)))
10622 (cond
10623 ((eq (car desc) :tag)
10624 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10625 ((eq (car desc) :todo)
10626 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10627 ((eq (car desc) :regexp)
10628 (setq descre (cdr desc)))
10629 ((eq (car desc) :level)
10630 (setq descre (concat "^\\*\\{" (number-to-string
10631 (if org-odd-levels-only
10632 (1- (* 2 (cdr desc)))
10633 (cdr desc)))
10634 "\\}[ \t]")))
10635 ((eq (car desc) :maxlevel)
10636 (setq fast-path-p t)
10637 (setq descre (concat "^\\*\\{1," (number-to-string
10638 (if org-odd-levels-only
10639 (1- (* 2 (cdr desc)))
10640 (cdr desc)))
10641 "\\}[ \t]")))
10642 (t (error "Bad refiling target description %s" desc)))
10643 (while (setq f (pop files))
10644 (with-current-buffer
10645 (if (bufferp f) f (org-get-agenda-file-buffer f))
10647 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10648 (progn
10649 (if (bufferp f) (setq f (buffer-file-name
10650 (buffer-base-buffer f))))
10651 (setq f (and f (expand-file-name f)))
10652 (if (eq org-refile-use-outline-path 'file)
10653 (push (list (file-name-nondirectory f) f nil nil) tgs))
10654 (save-excursion
10655 (save-restriction
10656 (widen)
10657 (goto-char (point-min))
10658 (while (re-search-forward descre nil t)
10659 (goto-char (setq pos0 (point-at-bol)))
10660 (catch 'next
10661 (when org-refile-target-verify-function
10662 (save-match-data
10663 (or (funcall org-refile-target-verify-function)
10664 (throw 'next t))))
10665 (when (and (looking-at org-complex-heading-regexp)
10666 (not (member (match-string 4) excluded-entries))
10667 (match-string 4))
10668 (setq level (org-reduced-level
10669 (- (match-end 1) (match-beginning 1)))
10670 txt (org-link-display-format (match-string 4))
10671 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10672 re (format org-complex-heading-regexp-format
10673 (regexp-quote (match-string 4))))
10674 (when org-refile-use-outline-path
10675 (setq txt (mapconcat
10676 'org-protect-slash
10677 (append
10678 (if (eq org-refile-use-outline-path
10679 'file)
10680 (list (file-name-nondirectory
10681 (buffer-file-name
10682 (buffer-base-buffer))))
10683 (if (eq org-refile-use-outline-path
10684 'full-file-path)
10685 (list (buffer-file-name
10686 (buffer-base-buffer)))))
10687 (org-get-outline-path fast-path-p
10688 level txt)
10689 (list txt))
10690 "/")))
10691 (push (list txt f re (org-refile-marker (point)))
10692 tgs)))
10693 (when (= (point) pos0)
10694 ;; verification function has not moved point
10695 (goto-char (point-at-eol))))))))
10696 (when org-refile-use-cache
10697 (org-refile-cache-put tgs (buffer-file-name) descre))
10698 (setq targets (append tgs targets))
10699 ))))
10700 (message "Getting targets...done")
10701 (nreverse targets)))
10703 (defun org-protect-slash (s)
10704 (while (string-match "/" s)
10705 (setq s (replace-match "\\" t t s)))
10708 (defvar org-olpa (make-vector 20 nil))
10710 (defun org-get-outline-path (&optional fastp level heading)
10711 "Return the outline path to the current entry, as a list.
10713 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10714 routine which makes outline path derivations for an entire file,
10715 avoiding backtracing. Refile target collection makes use of that."
10716 (if fastp
10717 (progn
10718 (if (> level 19)
10719 (error "Outline path failure, more than 19 levels"))
10720 (loop for i from level upto 19 do
10721 (aset org-olpa i nil))
10722 (prog1
10723 (delq nil (append org-olpa nil))
10724 (aset org-olpa level heading)))
10725 (let (rtn case-fold-search)
10726 (save-excursion
10727 (save-restriction
10728 (widen)
10729 (while (org-up-heading-safe)
10730 (when (looking-at org-complex-heading-regexp)
10731 (push (org-match-string-no-properties 4) rtn)))
10732 rtn)))))
10734 (defun org-format-outline-path (path &optional width prefix)
10735 "Format the outline path PATH for display.
10736 Width is the maximum number of characters that is available.
10737 Prefix is a prefix to be included in the returned string,
10738 such as the file name."
10739 (setq width (or width 79))
10740 (if prefix (setq width (- width (length prefix))))
10741 (if (not path)
10742 (or prefix "")
10743 (let* ((nsteps (length path))
10744 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10745 (maxwidth (if (<= total-width width)
10746 10000 ;; everything fits
10747 ;; we need to shorten the level headings
10748 (/ (- width nsteps) nsteps)))
10749 (org-odd-levels-only nil)
10750 (n 0)
10751 (total (1+ (length prefix))))
10752 (setq maxwidth (max maxwidth 10))
10753 (concat prefix
10754 (mapconcat
10755 (lambda (h)
10756 (setq n (1+ n))
10757 (if (and (= n nsteps) (< maxwidth 10000))
10758 (setq maxwidth (- total-width total)))
10759 (if (< (length h) maxwidth)
10760 (progn (setq total (+ total (length h) 1)) h)
10761 (setq h (substring h 0 (- maxwidth 2))
10762 total (+ total maxwidth 1))
10763 (if (string-match "[ \t]+\\'" h)
10764 (setq h (substring h 0 (match-beginning 0))))
10765 (setq h (concat h "..")))
10766 (org-add-props h nil 'face
10767 (nth (% (1- n) org-n-level-faces)
10768 org-level-faces))
10770 path "/")))))
10772 (defun org-display-outline-path (&optional file current)
10773 "Display the current outline path in the echo area."
10774 (interactive "P")
10775 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10776 (case-fold-search nil)
10777 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10778 (if current (setq path (append path
10779 (save-excursion
10780 (org-back-to-heading t)
10781 (if (looking-at org-complex-heading-regexp)
10782 (list (match-string 4)))))))
10783 (message "%s"
10784 (org-format-outline-path
10785 path
10786 (1- (frame-width))
10787 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10789 (defvar org-refile-history nil
10790 "History for refiling operations.")
10792 (defvar org-after-refile-insert-hook nil
10793 "Hook run after `org-refile' has inserted its stuff at the new location.
10794 Note that this is still *before* the stuff will be removed from
10795 the *old* location.")
10797 (defvar org-capture-last-stored-marker)
10798 (defun org-refile (&optional goto default-buffer rfloc)
10799 "Move the entry or entries at point to another heading.
10800 The list of target headings is compiled using the information in
10801 `org-refile-targets', which see.
10803 At the target location, the entry is filed as a subitem of the target
10804 heading. Depending on `org-reverse-note-order', the new subitem will
10805 either be the first or the last subitem.
10807 If there is an active region, all entries in that region will be moved.
10808 However, the region must fulfill the requirement that the first heading
10809 is the first one sets the top-level of the moved text - at most siblings
10810 below it are allowed.
10812 With prefix arg GOTO, the command will only visit the target location
10813 and not actually move anything.
10815 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10816 go to the location where the last refiling operation has put the subtree.
10817 With a prefix argument of `2', refile to the running clock.
10819 RFLOC can be a refile location obtained in a different way.
10821 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10823 If you are using target caching (see `org-refile-use-cache'),
10824 you have to clear the target cache in order to find new targets.
10825 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10826 prefix argument (`C-u C-u C-u C-c C-w')."
10828 (interactive "P")
10829 (if (member goto '(0 (64)))
10830 (org-refile-cache-clear)
10831 (let* ((cbuf (current-buffer))
10832 (regionp (org-region-active-p))
10833 (region-start (and regionp (region-beginning)))
10834 (region-end (and regionp (region-end)))
10835 (region-length (and regionp (- region-end region-start)))
10836 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10837 pos it nbuf file re level reversed)
10838 (setq last-command nil)
10839 (when regionp
10840 (goto-char region-start)
10841 (or (bolp) (goto-char (point-at-bol)))
10842 (setq region-start (point))
10843 (unless (or (org-kill-is-subtree-p
10844 (buffer-substring region-start region-end))
10845 (prog1 org-refile-active-region-within-subtree
10846 (org-toggle-heading)))
10847 (error "The region is not a (sequence of) subtree(s)")))
10848 (if (equal goto '(16))
10849 (org-refile-goto-last-stored)
10850 (when (or
10851 (and (equal goto 2)
10852 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10853 (prog1
10854 (setq it (list (or org-clock-heading "running clock")
10855 (buffer-file-name
10856 (marker-buffer org-clock-hd-marker))
10858 (marker-position org-clock-hd-marker)))
10859 (setq goto nil)))
10860 (setq it (or rfloc
10861 (let (heading-text)
10862 (save-excursion
10863 (unless goto
10864 (org-back-to-heading t)
10865 (setq heading-text
10866 (nth 4 (org-heading-components))))
10867 (org-refile-get-location
10868 (cond (goto "Goto")
10869 (regionp "Refile region to")
10870 (t (concat "Refile subtree \""
10871 heading-text "\" to")))
10872 default-buffer
10873 (and (not (equal '(4) goto))
10874 org-refile-allow-creating-parent-nodes)
10875 goto))))))
10876 (setq file (nth 1 it)
10877 re (nth 2 it)
10878 pos (nth 3 it))
10879 (if (and (not goto)
10881 (equal (buffer-file-name) file)
10882 (if regionp
10883 (and (>= pos region-start)
10884 (<= pos region-end))
10885 (and (>= pos (point))
10886 (< pos (save-excursion
10887 (org-end-of-subtree t t))))))
10888 (error "Cannot refile to position inside the tree or region"))
10890 (setq nbuf (or (find-buffer-visiting file)
10891 (find-file-noselect file)))
10892 (if goto
10893 (progn
10894 (org-pop-to-buffer-same-window nbuf)
10895 (goto-char pos)
10896 (org-show-context 'org-goto))
10897 (if regionp
10898 (progn
10899 (org-kill-new (buffer-substring region-start region-end))
10900 (org-save-markers-in-region region-start region-end))
10901 (org-copy-subtree 1 nil t))
10902 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10903 (find-file-noselect file)))
10904 (setq reversed (org-notes-order-reversed-p))
10905 (save-excursion
10906 (save-restriction
10907 (widen)
10908 (if pos
10909 (progn
10910 (goto-char pos)
10911 (looking-at org-outline-regexp)
10912 (setq level (org-get-valid-level (funcall outline-level) 1))
10913 (goto-char
10914 (if reversed
10915 (or (outline-next-heading) (point-max))
10916 (or (save-excursion (org-get-next-sibling))
10917 (org-end-of-subtree t t)
10918 (point-max)))))
10919 (setq level 1)
10920 (if (not reversed)
10921 (goto-char (point-max))
10922 (goto-char (point-min))
10923 (or (outline-next-heading) (goto-char (point-max)))))
10924 (if (not (bolp)) (newline))
10925 (org-paste-subtree level)
10926 (when org-log-refile
10927 (org-add-log-setup 'refile nil nil 'findpos
10928 org-log-refile)
10929 (unless (eq org-log-refile 'note)
10930 (save-excursion (org-add-log-note))))
10931 (and org-auto-align-tags
10932 (let ((org-loop-over-headlines-in-active-region nil))
10933 (org-set-tags nil t)))
10934 (with-demoted-errors
10935 (bookmark-set "org-refile-last-stored"))
10936 ;; If we are refiling for capture, make sure that the
10937 ;; last-capture pointers point here
10938 (when (org-bound-and-true-p org-refile-for-capture)
10939 (with-demoted-errors
10940 (bookmark-set "org-capture-last-stored-marker"))
10941 (move-marker org-capture-last-stored-marker (point)))
10942 (if (fboundp 'deactivate-mark) (deactivate-mark))
10943 (run-hooks 'org-after-refile-insert-hook))))
10944 (if regionp
10945 (delete-region (point) (+ (point) region-length))
10946 (org-cut-subtree))
10947 (when (featurep 'org-inlinetask)
10948 (org-inlinetask-remove-END-maybe))
10949 (setq org-markers-to-move nil)
10950 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10952 (defun org-refile-goto-last-stored ()
10953 "Go to the location where the last refile was stored."
10954 (interactive)
10955 (bookmark-jump "org-refile-last-stored")
10956 (message "This is the location of the last refile"))
10958 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10959 no-exclude)
10960 "Prompt the user for a refile location, using PROMPT.
10961 PROMPT should not be suffixed with a colon and a space, because
10962 this function appends the default value from
10963 `org-refile-history' automatically, if that is not empty.
10964 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10965 this is used for the GOTO interface."
10966 (let ((org-refile-targets org-refile-targets)
10967 (org-refile-use-outline-path org-refile-use-outline-path)
10968 excluded-entries)
10969 (when (and (derived-mode-p 'org-mode)
10970 (not org-refile-use-cache)
10971 (not no-exclude))
10972 (org-map-tree
10973 (lambda()
10974 (setq excluded-entries
10975 (append excluded-entries (list (org-get-heading t t)))))))
10976 (setq org-refile-target-table
10977 (org-refile-get-targets default-buffer excluded-entries)))
10978 (unless org-refile-target-table
10979 (error "No refile targets"))
10980 (let* ((prompt (concat prompt
10981 (and (car org-refile-history)
10982 (concat " (default " (car org-refile-history) ")"))
10983 ": "))
10984 (cbuf (current-buffer))
10985 (partial-completion-mode nil)
10986 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10987 (cfunc (if (and org-refile-use-outline-path
10988 org-outline-path-complete-in-steps)
10989 'org-olpath-completing-read
10990 'org-icompleting-read))
10991 (extra (if org-refile-use-outline-path "/" ""))
10992 (filename (and cfn (expand-file-name cfn)))
10993 (tbl (mapcar
10994 (lambda (x)
10995 (if (and (not (member org-refile-use-outline-path
10996 '(file full-file-path)))
10997 (not (equal filename (nth 1 x))))
10998 (cons (concat (car x) extra " ("
10999 (file-name-nondirectory (nth 1 x)) ")")
11000 (cdr x))
11001 (cons (concat (car x) extra) (cdr x))))
11002 org-refile-target-table))
11003 (completion-ignore-case t)
11004 pa answ parent-target child parent old-hist)
11005 (setq old-hist org-refile-history)
11006 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11007 nil 'org-refile-history (car org-refile-history)))
11008 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11009 (org-refile-check-position pa)
11010 (if pa
11011 (progn
11012 (when (or (not org-refile-history)
11013 (not (eq old-hist org-refile-history))
11014 (not (equal (car pa) (car org-refile-history))))
11015 (setq org-refile-history
11016 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11017 org-refile-history
11018 (cdr org-refile-history))))
11019 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11020 (pop org-refile-history)))
11022 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11023 (progn
11024 (setq parent (match-string 1 answ)
11025 child (match-string 2 answ))
11026 (setq parent-target (or (assoc parent tbl)
11027 (assoc (concat parent "/") tbl)))
11028 (when (and parent-target
11029 (or (eq new-nodes t)
11030 (and (eq new-nodes 'confirm)
11031 (y-or-n-p (format "Create new node \"%s\"? "
11032 child)))))
11033 (org-refile-new-child parent-target child)))
11034 (error "Invalid target location")))))
11036 (declare-function org-string-nw-p "org-macs" (s))
11037 (defun org-refile-check-position (refile-pointer)
11038 "Check if the refile pointer matches the headline to which it points."
11039 (let* ((file (nth 1 refile-pointer))
11040 (re (nth 2 refile-pointer))
11041 (pos (nth 3 refile-pointer))
11042 buffer)
11043 (if (and (not (markerp pos)) (not file))
11044 (error "Please save the buffer to a file before refiling")
11045 (when (org-string-nw-p re)
11046 (setq buffer (if (markerp pos)
11047 (marker-buffer pos)
11048 (or (find-buffer-visiting file)
11049 (find-file-noselect file))))
11050 (with-current-buffer buffer
11051 (save-excursion
11052 (save-restriction
11053 (widen)
11054 (goto-char pos)
11055 (beginning-of-line 1)
11056 (unless (org-looking-at-p re)
11057 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11059 (defun org-refile-new-child (parent-target child)
11060 "Use refile target PARENT-TARGET to add new CHILD below it."
11061 (unless parent-target
11062 (error "Cannot find parent for new node"))
11063 (let ((file (nth 1 parent-target))
11064 (pos (nth 3 parent-target))
11065 level)
11066 (with-current-buffer (or (find-buffer-visiting file)
11067 (find-file-noselect file))
11068 (save-excursion
11069 (save-restriction
11070 (widen)
11071 (if pos
11072 (goto-char pos)
11073 (goto-char (point-max))
11074 (if (not (bolp)) (newline)))
11075 (when (looking-at org-outline-regexp)
11076 (setq level (funcall outline-level))
11077 (org-end-of-subtree t t))
11078 (org-back-over-empty-lines)
11079 (insert "\n" (make-string
11080 (if pos (org-get-valid-level level 1) 1) ?*)
11081 " " child "\n")
11082 (beginning-of-line 0)
11083 (list (concat (car parent-target) "/" child) file "" (point)))))))
11085 (defun org-olpath-completing-read (prompt collection &rest args)
11086 "Read an outline path like a file name."
11087 (let ((thetable collection)
11088 (org-completion-use-ido nil) ; does not work with ido.
11089 (org-completion-use-iswitchb nil)) ; or iswitchb
11090 (apply
11091 'org-icompleting-read prompt
11092 (lambda (string predicate &optional flag)
11093 (let (rtn r f (l (length string)))
11094 (cond
11095 ((eq flag nil)
11096 ;; try completion
11097 (try-completion string thetable))
11098 ((eq flag t)
11099 ;; all-completions
11100 (setq rtn (all-completions string thetable predicate))
11101 (mapcar
11102 (lambda (x)
11103 (setq r (substring x l))
11104 (if (string-match " ([^)]*)$" x)
11105 (setq f (match-string 0 x))
11106 (setq f ""))
11107 (if (string-match "/" r)
11108 (concat string (substring r 0 (match-end 0)) f)
11110 rtn))
11111 ((eq flag 'lambda)
11112 ;; exact match?
11113 (assoc string thetable)))))
11114 args)))
11116 ;;;; Dynamic blocks
11118 (defun org-find-dblock (name)
11119 "Find the first dynamic block with name NAME in the buffer.
11120 If not found, stay at current position and return nil."
11121 (let ((case-fold-search t) pos)
11122 (save-excursion
11123 (goto-char (point-min))
11124 (setq pos (and (re-search-forward
11125 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11126 (match-beginning 0))))
11127 (if pos (goto-char pos))
11128 pos))
11130 (defconst org-dblock-start-re
11131 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11132 "Matches the start line of a dynamic block, with parameters.")
11134 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11135 "Matches the end of a dynamic block.")
11137 (defun org-create-dblock (plist)
11138 "Create a dynamic block section, with parameters taken from PLIST.
11139 PLIST must contain a :name entry which is used as name of the block."
11140 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11141 (end-of-line 1)
11142 (newline))
11143 (let ((col (current-column))
11144 (name (plist-get plist :name)))
11145 (insert "#+BEGIN: " name)
11146 (while plist
11147 (if (eq (car plist) :name)
11148 (setq plist (cddr plist))
11149 (insert " " (prin1-to-string (pop plist)))))
11150 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11151 (beginning-of-line -2)))
11153 (defun org-prepare-dblock ()
11154 "Prepare dynamic block for refresh.
11155 This empties the block, puts the cursor at the insert position and returns
11156 the property list including an extra property :name with the block name."
11157 (unless (looking-at org-dblock-start-re)
11158 (error "Not at a dynamic block"))
11159 (let* ((begdel (1+ (match-end 0)))
11160 (name (org-no-properties (match-string 1)))
11161 (params (append (list :name name)
11162 (read (concat "(" (match-string 3) ")")))))
11163 (save-excursion
11164 (beginning-of-line 1)
11165 (skip-chars-forward " \t")
11166 (setq params (plist-put params :indentation-column (current-column))))
11167 (unless (re-search-forward org-dblock-end-re nil t)
11168 (error "Dynamic block not terminated"))
11169 (setq params
11170 (append params
11171 (list :content (buffer-substring
11172 begdel (match-beginning 0)))))
11173 (delete-region begdel (match-beginning 0))
11174 (goto-char begdel)
11175 (open-line 1)
11176 params))
11178 (defun org-map-dblocks (&optional command)
11179 "Apply COMMAND to all dynamic blocks in the current buffer.
11180 If COMMAND is not given, use `org-update-dblock'."
11181 (let ((cmd (or command 'org-update-dblock)))
11182 (save-excursion
11183 (goto-char (point-min))
11184 (while (re-search-forward org-dblock-start-re nil t)
11185 (goto-char (match-beginning 0))
11186 (save-excursion
11187 (condition-case nil
11188 (funcall cmd)
11189 (error (message "Error during update of dynamic block"))))
11190 (unless (re-search-forward org-dblock-end-re nil t)
11191 (error "Dynamic block not terminated"))))))
11193 (defun org-dblock-update (&optional arg)
11194 "User command for updating dynamic blocks.
11195 Update the dynamic block at point. With prefix ARG, update all dynamic
11196 blocks in the buffer."
11197 (interactive "P")
11198 (if arg
11199 (org-update-all-dblocks)
11200 (or (looking-at org-dblock-start-re)
11201 (org-beginning-of-dblock))
11202 (org-update-dblock)))
11204 (defun org-update-dblock ()
11205 "Update the dynamic block at point.
11206 This means to empty the block, parse for parameters and then call
11207 the correct writing function."
11208 (interactive)
11209 (save-window-excursion
11210 (let* ((pos (point))
11211 (line (org-current-line))
11212 (params (org-prepare-dblock))
11213 (name (plist-get params :name))
11214 (indent (plist-get params :indentation-column))
11215 (cmd (intern (concat "org-dblock-write:" name))))
11216 (message "Updating dynamic block `%s' at line %d..." name line)
11217 (funcall cmd params)
11218 (message "Updating dynamic block `%s' at line %d...done" name line)
11219 (goto-char pos)
11220 (when (and indent (> indent 0))
11221 (setq indent (make-string indent ?\ ))
11222 (save-excursion
11223 (org-beginning-of-dblock)
11224 (forward-line 1)
11225 (while (not (looking-at org-dblock-end-re))
11226 (insert indent)
11227 (beginning-of-line 2))
11228 (when (looking-at org-dblock-end-re)
11229 (and (looking-at "[ \t]+")
11230 (replace-match ""))
11231 (insert indent)))))))
11233 (defun org-beginning-of-dblock ()
11234 "Find the beginning of the dynamic block at point.
11235 Error if there is no such block at point."
11236 (let ((pos (point))
11237 beg)
11238 (end-of-line 1)
11239 (if (and (re-search-backward org-dblock-start-re nil t)
11240 (setq beg (match-beginning 0))
11241 (re-search-forward org-dblock-end-re nil t)
11242 (> (match-end 0) pos))
11243 (goto-char beg)
11244 (goto-char pos)
11245 (error "Not in a dynamic block"))))
11247 (defun org-update-all-dblocks ()
11248 "Update all dynamic blocks in the buffer.
11249 This function can be used in a hook."
11250 (interactive)
11251 (when (derived-mode-p 'org-mode)
11252 (org-map-dblocks 'org-update-dblock)))
11255 ;;;; Completion
11257 (defconst org-additional-option-like-keywords
11258 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11259 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11260 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11261 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11262 "BEGIN:" "END:"
11263 "ORGTBL" "TBLFM:" "TBLNAME:"
11264 "BEGIN_EXAMPLE" "END_EXAMPLE"
11265 "BEGIN_VERBATIM" "END_VERBATIM"
11266 "BEGIN_QUOTE" "END_QUOTE"
11267 "BEGIN_VERSE" "END_VERSE"
11268 "BEGIN_CENTER" "END_CENTER"
11269 "BEGIN_SRC" "END_SRC"
11270 "BEGIN_RESULT" "END_RESULT"
11271 "BEGIN_lstlisting" "END_lstlisting"
11272 "NAME:" "RESULTS:"
11273 "HEADER:" "HEADERS:"
11274 "COLUMNS:" "PROPERTY:"
11275 "CAPTION:" "LABEL:"
11276 "SETUPFILE:"
11277 "INCLUDE:" "INDEX:"
11278 "BIND:"
11279 "MACRO:"))
11281 (defconst org-options-keywords
11282 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11283 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11284 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11285 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11286 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11287 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11288 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11290 (defconst org-additional-option-like-keywords-for-flyspell
11291 (delete-dups
11292 (split-string
11293 (mapconcat (lambda(k)
11294 (replace-regexp-in-string
11295 "_\\|:" " "
11296 (concat k " " (downcase k) " " (upcase k))))
11297 (append org-options-keywords org-additional-option-like-keywords)
11298 " ")
11299 " +" t)))
11301 (defcustom org-structure-template-alist
11302 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11303 "<src lang=\"?\">\n\n</src>")
11304 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11305 "<example>\n?\n</example>")
11306 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11307 "<quote>\n?\n</quote>")
11308 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11309 "<verse>\n?\n</verse>")
11310 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11311 "<verbatim>\n?\n</verbatim>")
11312 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11313 "<center>\n?\n</center>")
11314 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11315 "<literal style=\"latex\">\n?\n</literal>")
11316 ("L" "#+LaTeX: "
11317 "<literal style=\"latex\">?</literal>")
11318 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11319 "<literal style=\"html\">\n?\n</literal>")
11320 ("H" "#+HTML: "
11321 "<literal style=\"html\">?</literal>")
11322 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11323 ("A" "#+ASCII: ")
11324 ("i" "#+INDEX: ?"
11325 "#+INDEX: ?")
11326 ("I" "#+INCLUDE: %file ?"
11327 "<include file=%file markup=\"?\">"))
11328 "Structure completion elements.
11329 This is a list of abbreviation keys and values. The value gets inserted
11330 if you type `<' followed by the key and then press the completion key,
11331 usually `M-TAB'. %file will be replaced by a file name after prompting
11332 for the file using completion. The cursor will be placed at the position
11333 of the `?` in the template.
11334 There are two templates for each key, the first uses the original Org syntax,
11335 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11336 the default when the /org-mtags.el/ module has been loaded. See also the
11337 variable `org-mtags-prefer-muse-templates'."
11338 :group 'org-completion
11339 :type '(repeat
11340 (string :tag "Key")
11341 (string :tag "Template")
11342 (string :tag "Muse Template")))
11344 (defun org-try-structure-completion ()
11345 "Try to complete a structure template before point.
11346 This looks for strings like \"<e\" on an otherwise empty line and
11347 expands them."
11348 (let ((l (buffer-substring (point-at-bol) (point)))
11350 (when (and (looking-at "[ \t]*$")
11351 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11352 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11353 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11354 (match-beginning 1)) a)
11355 t)))
11357 (defun org-complete-expand-structure-template (start cell)
11358 "Expand a structure template."
11359 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11360 (rpl (nth (if musep 2 1) cell))
11361 (ind ""))
11362 (delete-region start (point))
11363 (when (string-match "\\`#\\+" rpl)
11364 (cond
11365 ((bolp))
11366 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11367 (setq ind (buffer-substring (point-at-bol) (point))))
11368 (t (newline))))
11369 (setq start (point))
11370 (if (string-match "%file" rpl)
11371 (setq rpl (replace-match
11372 (concat
11373 "\""
11374 (save-match-data
11375 (abbreviate-file-name (read-file-name "Include file: ")))
11376 "\"")
11377 t t rpl)))
11378 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11379 (concat "\n" ind)))
11380 (insert rpl)
11381 (if (re-search-backward "\\?" start t) (delete-char 1))))
11383 ;;;; TODO, DEADLINE, Comments
11385 (defun org-toggle-comment ()
11386 "Change the COMMENT state of an entry."
11387 (interactive)
11388 (save-excursion
11389 (org-back-to-heading)
11390 (let (case-fold-search)
11391 (cond
11392 ((looking-at (format org-heading-keyword-regexp-format
11393 org-comment-string))
11394 (goto-char (match-end 1))
11395 (looking-at (concat " +" org-comment-string))
11396 (replace-match "" t t)
11397 (when (eolp) (insert " ")))
11398 ((looking-at org-outline-regexp)
11399 (goto-char (match-end 0))
11400 (insert org-comment-string " "))))))
11402 (defvar org-last-todo-state-is-todo nil
11403 "This is non-nil when the last TODO state change led to a TODO state.
11404 If the last change removed the TODO tag or switched to DONE, then
11405 this is nil.")
11407 (defvar org-setting-tags nil) ; dynamically skipped
11409 (defvar org-todo-setup-filter-hook nil
11410 "Hook for functions that pre-filter todo specs.
11411 Each function takes a todo spec and returns either nil or the spec
11412 transformed into canonical form." )
11414 (defvar org-todo-get-default-hook nil
11415 "Hook for functions that get a default item for todo.
11416 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11417 nil or a string to be used for the todo mark." )
11419 (defvar org-agenda-headline-snapshot-before-repeat)
11421 (defun org-current-effective-time ()
11422 "Return current time adjusted for `org-extend-today-until' variable."
11423 (let* ((ct (org-current-time))
11424 (dct (decode-time ct))
11425 (ct1
11426 (if (and org-use-effective-time
11427 (< (nth 2 dct) org-extend-today-until))
11428 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11429 ct)))
11430 ct1))
11432 (defun org-todo-yesterday (&optional arg)
11433 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11434 (interactive "P")
11435 (if (eq major-mode 'org-agenda-mode)
11436 (apply 'org-agenda-todo-yesterday arg)
11437 (let* ((hour (third (decode-time
11438 (org-current-time))))
11439 (org-extend-today-until (1+ hour)))
11440 (org-todo arg))))
11442 (defun org-todo (&optional arg)
11443 "Change the TODO state of an item.
11444 The state of an item is given by a keyword at the start of the heading,
11445 like
11446 *** TODO Write paper
11447 *** DONE Call mom
11449 The different keywords are specified in the variable `org-todo-keywords'.
11450 By default the available states are \"TODO\" and \"DONE\".
11451 So for this example: when the item starts with TODO, it is changed to DONE.
11452 When it starts with DONE, the DONE is removed. And when neither TODO nor
11453 DONE are present, add TODO at the beginning of the heading.
11455 With \\[universal-argument] prefix arg, use completion to determine the new \
11456 state.
11457 With numeric prefix arg, switch to that state.
11458 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11459 keywords (nextset).
11460 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11461 With a numeric prefix arg of 0, inhibit note taking for the change.
11463 For calling through lisp, arg is also interpreted in the following way:
11464 'none -> empty state
11465 \"\"(empty string) -> switch to empty state
11466 'done -> switch to DONE
11467 'nextset -> switch to the next set of keywords
11468 'previousset -> switch to the previous set of keywords
11469 \"WAITING\" -> switch to the specified keyword, but only if it
11470 really is a member of `org-todo-keywords'."
11471 (interactive "P")
11472 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11473 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11474 'region-start-level 'region))
11475 org-loop-over-headlines-in-active-region)
11476 (org-map-entries
11477 `(org-todo ,arg)
11478 org-loop-over-headlines-in-active-region
11479 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11480 (if (equal arg '(16)) (setq arg 'nextset))
11481 (let ((org-blocker-hook org-blocker-hook)
11482 commentp
11483 case-fold-search)
11484 (when (equal arg '(64))
11485 (setq arg nil org-blocker-hook nil))
11486 (when (and org-blocker-hook
11487 (or org-inhibit-blocking
11488 (org-entry-get nil "NOBLOCKING")))
11489 (setq org-blocker-hook nil))
11490 (save-excursion
11491 (catch 'exit
11492 (org-back-to-heading t)
11493 (when (looking-at (concat "^\\*+ " org-comment-string))
11494 (org-toggle-comment)
11495 (setq commentp t))
11496 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11497 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11498 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11499 (let* ((match-data (match-data))
11500 (startpos (point-at-bol))
11501 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11502 (org-log-done org-log-done)
11503 (org-log-repeat org-log-repeat)
11504 (org-todo-log-states org-todo-log-states)
11505 (org-inhibit-logging
11506 (if (equal arg 0)
11507 (progn (setq arg nil) 'note) org-inhibit-logging))
11508 (this (match-string 1))
11509 (hl-pos (match-beginning 0))
11510 (head (org-get-todo-sequence-head this))
11511 (ass (assoc head org-todo-kwd-alist))
11512 (interpret (nth 1 ass))
11513 (done-word (nth 3 ass))
11514 (final-done-word (nth 4 ass))
11515 (org-last-state (or this ""))
11516 (completion-ignore-case t)
11517 (member (member this org-todo-keywords-1))
11518 (tail (cdr member))
11519 (org-state (cond
11520 ((and org-todo-key-trigger
11521 (or (and (equal arg '(4))
11522 (eq org-use-fast-todo-selection 'prefix))
11523 (and (not arg) org-use-fast-todo-selection
11524 (not (eq org-use-fast-todo-selection
11525 'prefix)))))
11526 ;; Use fast selection
11527 (org-fast-todo-selection))
11528 ((and (equal arg '(4))
11529 (or (not org-use-fast-todo-selection)
11530 (not org-todo-key-trigger)))
11531 ;; Read a state with completion
11532 (org-icompleting-read
11533 "State: " (mapcar (lambda(x) (list x))
11534 org-todo-keywords-1)
11535 nil t))
11536 ((eq arg 'right)
11537 (if this
11538 (if tail (car tail) nil)
11539 (car org-todo-keywords-1)))
11540 ((eq arg 'left)
11541 (if (equal member org-todo-keywords-1)
11543 (if this
11544 (nth (- (length org-todo-keywords-1)
11545 (length tail) 2)
11546 org-todo-keywords-1)
11547 (org-last org-todo-keywords-1))))
11548 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11549 (setq arg nil))) ; hack to fall back to cycling
11550 (arg
11551 ;; user or caller requests a specific state
11552 (cond
11553 ((equal arg "") nil)
11554 ((eq arg 'none) nil)
11555 ((eq arg 'done) (or done-word (car org-done-keywords)))
11556 ((eq arg 'nextset)
11557 (or (car (cdr (member head org-todo-heads)))
11558 (car org-todo-heads)))
11559 ((eq arg 'previousset)
11560 (let ((org-todo-heads (reverse org-todo-heads)))
11561 (or (car (cdr (member head org-todo-heads)))
11562 (car org-todo-heads))))
11563 ((car (member arg org-todo-keywords-1)))
11564 ((stringp arg)
11565 (error "State `%s' not valid in this file" arg))
11566 ((nth (1- (prefix-numeric-value arg))
11567 org-todo-keywords-1))))
11568 ((null member) (or head (car org-todo-keywords-1)))
11569 ((equal this final-done-word) nil) ;; -> make empty
11570 ((null tail) nil) ;; -> first entry
11571 ((memq interpret '(type priority))
11572 (if (eq this-command last-command)
11573 (car tail)
11574 (if (> (length tail) 0)
11575 (or done-word (car org-done-keywords))
11576 nil)))
11578 (car tail))))
11579 (org-state (or
11580 (run-hook-with-args-until-success
11581 'org-todo-get-default-hook org-state org-last-state)
11582 org-state))
11583 (next (if org-state (concat " " org-state " ") " "))
11584 (change-plist (list :type 'todo-state-change :from this :to org-state
11585 :position startpos))
11586 dolog now-done-p)
11587 (when org-blocker-hook
11588 (setq org-last-todo-state-is-todo
11589 (not (member this org-done-keywords)))
11590 (unless (save-excursion
11591 (save-match-data
11592 (org-with-wide-buffer
11593 (run-hook-with-args-until-failure
11594 'org-blocker-hook change-plist))))
11595 (if (org-called-interactively-p 'interactive)
11596 (error "TODO state change from %s to %s blocked" this org-state)
11597 ;; fail silently
11598 (message "TODO state change from %s to %s blocked" this org-state)
11599 (throw 'exit nil))))
11600 (store-match-data match-data)
11601 (replace-match next t t)
11602 (unless (pos-visible-in-window-p hl-pos)
11603 (message "TODO state changed to %s" (org-trim next)))
11604 (unless head
11605 (setq head (org-get-todo-sequence-head org-state)
11606 ass (assoc head org-todo-kwd-alist)
11607 interpret (nth 1 ass)
11608 done-word (nth 3 ass)
11609 final-done-word (nth 4 ass)))
11610 (when (memq arg '(nextset previousset))
11611 (message "Keyword-Set %d/%d: %s"
11612 (- (length org-todo-sets) -1
11613 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11614 (length org-todo-sets)
11615 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11616 (setq org-last-todo-state-is-todo
11617 (not (member org-state org-done-keywords)))
11618 (setq now-done-p (and (member org-state org-done-keywords)
11619 (not (member this org-done-keywords))))
11620 (and logging (org-local-logging logging))
11621 (when (and (or org-todo-log-states org-log-done)
11622 (not (eq org-inhibit-logging t))
11623 (not (memq arg '(nextset previousset))))
11624 ;; we need to look at recording a time and note
11625 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11626 (nth 2 (assoc this org-todo-log-states))))
11627 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11628 (setq dolog 'time))
11629 (when (and org-state
11630 (member org-state org-not-done-keywords)
11631 (not (member this org-not-done-keywords)))
11632 ;; This is now a todo state and was not one before
11633 ;; If there was a CLOSED time stamp, get rid of it.
11634 (org-add-planning-info nil nil 'closed))
11635 (when (and now-done-p org-log-done)
11636 ;; It is now done, and it was not done before
11637 (org-add-planning-info 'closed (org-current-effective-time))
11638 (if (and (not dolog) (eq 'note org-log-done))
11639 (org-add-log-setup 'done org-state this 'findpos 'note)))
11640 (when (and org-state dolog)
11641 ;; This is a non-nil state, and we need to log it
11642 (org-add-log-setup 'state org-state this 'findpos dolog)))
11643 ;; Fixup tag positioning
11644 (org-todo-trigger-tag-changes org-state)
11645 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11646 (when org-provide-todo-statistics
11647 (org-update-parent-todo-statistics))
11648 (run-hooks 'org-after-todo-state-change-hook)
11649 (if (and arg (not (member org-state org-done-keywords)))
11650 (setq head (org-get-todo-sequence-head org-state)))
11651 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11652 ;; Do we need to trigger a repeat?
11653 (when now-done-p
11654 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11655 ;; This is for the agenda, take a snapshot of the headline.
11656 (save-match-data
11657 (setq org-agenda-headline-snapshot-before-repeat
11658 (org-get-heading))))
11659 (org-auto-repeat-maybe org-state))
11660 ;; Fixup cursor location if close to the keyword
11661 (if (and (outline-on-heading-p)
11662 (not (bolp))
11663 (save-excursion (beginning-of-line 1)
11664 (looking-at org-todo-line-regexp))
11665 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11666 (progn
11667 (goto-char (or (match-end 2) (match-end 1)))
11668 (and (looking-at " ") (just-one-space))))
11669 (when org-trigger-hook
11670 (save-excursion
11671 (run-hook-with-args 'org-trigger-hook change-plist)))
11672 (when commentp (org-toggle-comment))))))))
11674 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11675 "Block turning an entry into a TODO, using the hierarchy.
11676 This checks whether the current task should be blocked from state
11677 changes. Such blocking occurs when:
11679 1. The task has children which are not all in a completed state.
11681 2. A task has a parent with the property :ORDERED:, and there
11682 are siblings prior to the current task with incomplete
11683 status.
11685 3. The parent of the task is blocked because it has siblings that should
11686 be done first, or is child of a block grandparent TODO entry."
11688 (if (not org-enforce-todo-dependencies)
11689 t ; if locally turned off don't block
11690 (catch 'dont-block
11691 ;; If this is not a todo state change, or if this entry is already DONE,
11692 ;; do not block
11693 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11694 (member (plist-get change-plist :from)
11695 (cons 'done org-done-keywords))
11696 (member (plist-get change-plist :to)
11697 (cons 'todo org-not-done-keywords))
11698 (not (plist-get change-plist :to)))
11699 (throw 'dont-block t))
11700 ;; If this task has children, and any are undone, it's blocked
11701 (save-excursion
11702 (org-back-to-heading t)
11703 (let ((this-level (funcall outline-level)))
11704 (outline-next-heading)
11705 (let ((child-level (funcall outline-level)))
11706 (while (and (not (eobp))
11707 (> child-level this-level))
11708 ;; this todo has children, check whether they are all
11709 ;; completed
11710 (if (and (not (org-entry-is-done-p))
11711 (org-entry-is-todo-p))
11712 (throw 'dont-block nil))
11713 (outline-next-heading)
11714 (setq child-level (funcall outline-level))))))
11715 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11716 ;; any previous siblings are undone, it's blocked
11717 (save-excursion
11718 (org-back-to-heading t)
11719 (let* ((pos (point))
11720 (parent-pos (and (org-up-heading-safe) (point))))
11721 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11722 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11723 (forward-line 1)
11724 (re-search-forward org-not-done-heading-regexp pos t))
11725 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11726 ;; Search further up the hierarchy, to see if an ancestor is blocked
11727 (while t
11728 (goto-char parent-pos)
11729 (if (not (looking-at org-not-done-heading-regexp))
11730 (throw 'dont-block t)) ; do not block, parent is not a TODO
11731 (setq pos (point))
11732 (setq parent-pos (and (org-up-heading-safe) (point)))
11733 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11734 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11735 (forward-line 1)
11736 (re-search-forward org-not-done-heading-regexp pos t))
11737 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11739 (defcustom org-track-ordered-property-with-tag nil
11740 "Should the ORDERED property also be shown as a tag?
11741 The ORDERED property decides if an entry should require subtasks to be
11742 completed in sequence. Since a property is not very visible, setting
11743 this option means that toggling the ORDERED property with the command
11744 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11745 not relevant for the behavior, but it makes things more visible.
11747 Note that toggling the tag with tags commands will not change the property
11748 and therefore not influence behavior!
11750 This can be t, meaning the tag ORDERED should be used, It can also be a
11751 string to select a different tag for this task."
11752 :group 'org-todo
11753 :type '(choice
11754 (const :tag "No tracking" nil)
11755 (const :tag "Track with ORDERED tag" t)
11756 (string :tag "Use other tag")))
11758 (defun org-toggle-ordered-property ()
11759 "Toggle the ORDERED property of the current entry.
11760 For better visibility, you can track the value of this property with a tag.
11761 See variable `org-track-ordered-property-with-tag'."
11762 (interactive)
11763 (let* ((t1 org-track-ordered-property-with-tag)
11764 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11765 (save-excursion
11766 (org-back-to-heading)
11767 (if (org-entry-get nil "ORDERED")
11768 (progn
11769 (org-delete-property "ORDERED")
11770 (and tag (org-toggle-tag tag 'off))
11771 (message "Subtasks can be completed in arbitrary order"))
11772 (org-entry-put nil "ORDERED" "t")
11773 (and tag (org-toggle-tag tag 'on))
11774 (message "Subtasks must be completed in sequence")))))
11776 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11777 (defun org-block-todo-from-checkboxes (change-plist)
11778 "Block turning an entry into a TODO, using checkboxes.
11779 This checks whether the current task should be blocked from state
11780 changes because there are unchecked boxes in this entry."
11781 (if (not org-enforce-todo-checkbox-dependencies)
11782 t ; if locally turned off don't block
11783 (catch 'dont-block
11784 ;; If this is not a todo state change, or if this entry is already DONE,
11785 ;; do not block
11786 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11787 (member (plist-get change-plist :from)
11788 (cons 'done org-done-keywords))
11789 (member (plist-get change-plist :to)
11790 (cons 'todo org-not-done-keywords))
11791 (not (plist-get change-plist :to)))
11792 (throw 'dont-block t))
11793 ;; If this task has checkboxes that are not checked, it's blocked
11794 (save-excursion
11795 (org-back-to-heading t)
11796 (let ((beg (point)) end)
11797 (outline-next-heading)
11798 (setq end (point))
11799 (goto-char beg)
11800 (if (org-list-search-forward
11801 (concat (org-item-beginning-re)
11802 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11803 "\\[[- ]\\]")
11804 end t)
11805 (progn
11806 (if (boundp 'org-blocked-by-checkboxes)
11807 (setq org-blocked-by-checkboxes t))
11808 (throw 'dont-block nil)))))
11809 t))) ; do not block
11811 (defun org-entry-blocked-p ()
11812 "Is the current entry blocked?"
11813 (org-with-buffer-modified-unmodified
11814 (if (org-entry-get nil "NOBLOCKING")
11815 nil ;; Never block this entry
11816 (not
11817 (run-hook-with-args-until-failure
11818 'org-blocker-hook
11819 (list :type 'todo-state-change
11820 :position (point)
11821 :from 'todo
11822 :to 'done))))))
11824 (defun org-update-statistics-cookies (all)
11825 "Update the statistics cookie, either from TODO or from checkboxes.
11826 This should be called with the cursor in a line with a statistics cookie."
11827 (interactive "P")
11828 (if all
11829 (progn
11830 (org-update-checkbox-count 'all)
11831 (org-map-entries 'org-update-parent-todo-statistics))
11832 (if (not (org-at-heading-p))
11833 (org-update-checkbox-count)
11834 (let ((pos (point-marker))
11835 end l1 l2)
11836 (ignore-errors (org-back-to-heading t))
11837 (if (not (org-at-heading-p))
11838 (org-update-checkbox-count)
11839 (setq l1 (org-outline-level))
11840 (setq end (save-excursion
11841 (outline-next-heading)
11842 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11843 (point)))
11844 (if (and (save-excursion
11845 (re-search-forward
11846 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11847 (not (save-excursion (re-search-forward
11848 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11849 (org-update-checkbox-count)
11850 (if (and l2 (> l2 l1))
11851 (progn
11852 (goto-char end)
11853 (org-update-parent-todo-statistics))
11854 (goto-char pos)
11855 (beginning-of-line 1)
11856 (while (re-search-forward
11857 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11858 (point-at-eol) t)
11859 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11860 (goto-char pos)
11861 (move-marker pos nil)))))
11863 (defvar org-entry-property-inherited-from) ;; defined below
11864 (defun org-update-parent-todo-statistics ()
11865 "Update any statistics cookie in the parent of the current headline.
11866 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11867 the entire subtree and this will travel up the hierarchy and update
11868 statistics everywhere."
11869 (let* ((prop (save-excursion (org-up-heading-safe)
11870 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11871 (recursive (or (not org-hierarchical-todo-statistics)
11872 (and prop (string-match "\\<recursive\\>" prop))))
11873 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11875 (first t)
11876 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11877 level ltoggle l1 new ndel
11878 (cnt-all 0) (cnt-done 0) is-percent kwd
11879 checkbox-beg ov ovs ove cookie-present)
11880 (catch 'exit
11881 (save-excursion
11882 (beginning-of-line 1)
11883 (setq ltoggle (funcall outline-level))
11884 ;; Three situations are to consider:
11886 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11887 ;; to the top-level ancestor on the headline;
11889 ;; 2. If parent has "recursive" property, repeat up to the
11890 ;; headline setting that property, taking inheritance into
11891 ;; account;
11893 ;; 3. Else, move up to direct parent and proceed only once.
11894 (while (and (setq level (org-up-heading-safe))
11895 (or recursive first)
11896 (>= (point) lim))
11897 (setq first nil cookie-present nil)
11898 (unless (and level
11899 (not (string-match
11900 "\\<checkbox\\>"
11901 (downcase (or (org-entry-get nil "COOKIE_DATA")
11902 "")))))
11903 (throw 'exit nil))
11904 (while (re-search-forward box-re (point-at-eol) t)
11905 (setq cnt-all 0 cnt-done 0 cookie-present t)
11906 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11907 (save-match-data
11908 (unless (outline-next-heading) (throw 'exit nil))
11909 (while (and (looking-at org-complex-heading-regexp)
11910 (> (setq l1 (length (match-string 1))) level))
11911 (setq kwd (and (or recursive (= l1 ltoggle))
11912 (match-string 2)))
11913 (if (or (eq org-provide-todo-statistics 'all-headlines)
11914 (and (listp org-provide-todo-statistics)
11915 (or (member kwd org-provide-todo-statistics)
11916 (member kwd org-done-keywords))))
11917 (setq cnt-all (1+ cnt-all))
11918 (if (eq org-provide-todo-statistics t)
11919 (and kwd (setq cnt-all (1+ cnt-all)))))
11920 (and (member kwd org-done-keywords)
11921 (setq cnt-done (1+ cnt-done)))
11922 (outline-next-heading)))
11923 (setq new
11924 (if is-percent
11925 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11926 (format "[%d/%d]" cnt-done cnt-all))
11927 ndel (- (match-end 0) checkbox-beg))
11928 ;; handle overlays when updating cookie from column view
11929 (when (setq ov (car (overlays-at checkbox-beg)))
11930 (setq ovs (overlay-start ov) ove (overlay-end ov))
11931 (delete-overlay ov))
11932 (goto-char checkbox-beg)
11933 (insert new)
11934 (delete-region (point) (+ (point) ndel))
11935 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11936 (when ov (move-overlay ov ovs ove)))
11937 (when cookie-present
11938 (run-hook-with-args 'org-after-todo-statistics-hook
11939 cnt-done (- cnt-all cnt-done))))))
11940 (run-hooks 'org-todo-statistics-hook)))
11942 (defvar org-after-todo-statistics-hook nil
11943 "Hook that is called after a TODO statistics cookie has been updated.
11944 Each function is called with two arguments: the number of not-done entries
11945 and the number of done entries.
11947 For example, the following function, when added to this hook, will switch
11948 an entry to DONE when all children are done, and back to TODO when new
11949 entries are set to a TODO status. Note that this hook is only called
11950 when there is a statistics cookie in the headline!
11952 (defun org-summary-todo (n-done n-not-done)
11953 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11954 (let (org-log-done org-log-states) ; turn off logging
11955 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11958 (defvar org-todo-statistics-hook nil
11959 "Hook that is run whenever Org thinks TODO statistics should be updated.
11960 This hook runs even if there is no statistics cookie present, in which case
11961 `org-after-todo-statistics-hook' would not run.")
11963 (defun org-todo-trigger-tag-changes (state)
11964 "Apply the changes defined in `org-todo-state-tags-triggers'."
11965 (let ((l org-todo-state-tags-triggers)
11966 changes)
11967 (when (or (not state) (equal state ""))
11968 (setq changes (append changes (cdr (assoc "" l)))))
11969 (when (and (stringp state) (> (length state) 0))
11970 (setq changes (append changes (cdr (assoc state l)))))
11971 (when (member state org-not-done-keywords)
11972 (setq changes (append changes (cdr (assoc 'todo l)))))
11973 (when (member state org-done-keywords)
11974 (setq changes (append changes (cdr (assoc 'done l)))))
11975 (dolist (c changes)
11976 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11978 (defun org-local-logging (value)
11979 "Get logging settings from a property VALUE."
11980 (let* (words w a)
11981 ;; directly set the variables, they are already local.
11982 (setq org-log-done nil
11983 org-log-repeat nil
11984 org-todo-log-states nil)
11985 (setq words (org-split-string value))
11986 (while (setq w (pop words))
11987 (cond
11988 ((setq a (assoc w org-startup-options))
11989 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11990 (set (nth 1 a) (nth 2 a))))
11991 ((setq a (org-extract-log-state-settings w))
11992 (and (member (car a) org-todo-keywords-1)
11993 (push a org-todo-log-states)))))))
11995 (defun org-get-todo-sequence-head (kwd)
11996 "Return the head of the TODO sequence to which KWD belongs.
11997 If KWD is not set, check if there is a text property remembering the
11998 right sequence."
11999 (let (p)
12000 (cond
12001 ((not kwd)
12002 (or (get-text-property (point-at-bol) 'org-todo-head)
12003 (progn
12004 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12005 nil (point-at-eol)))
12006 (get-text-property p 'org-todo-head))))
12007 ((not (member kwd org-todo-keywords-1))
12008 (car org-todo-keywords-1))
12009 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12011 (defun org-fast-todo-selection ()
12012 "Fast TODO keyword selection with single keys.
12013 Returns the new TODO keyword, or nil if no state change should occur."
12014 (let* ((fulltable org-todo-key-alist)
12015 (done-keywords org-done-keywords) ;; needed for the faces.
12016 (maxlen (apply 'max (mapcar
12017 (lambda (x)
12018 (if (stringp (car x)) (string-width (car x)) 0))
12019 fulltable)))
12020 (expert nil)
12021 (fwidth (+ maxlen 3 1 3))
12022 (ncol (/ (- (window-width) 4) fwidth))
12023 tg cnt e c tbl
12024 groups ingroup)
12025 (save-excursion
12026 (save-window-excursion
12027 (if expert
12028 (set-buffer (get-buffer-create " *Org todo*"))
12029 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12030 (erase-buffer)
12031 (org-set-local 'org-done-keywords done-keywords)
12032 (setq tbl fulltable cnt 0)
12033 (while (setq e (pop tbl))
12034 (cond
12035 ((equal e '(:startgroup))
12036 (push '() groups) (setq ingroup t)
12037 (when (not (= cnt 0))
12038 (setq cnt 0)
12039 (insert "\n"))
12040 (insert "{ "))
12041 ((equal e '(:endgroup))
12042 (setq ingroup nil cnt 0)
12043 (insert "}\n"))
12044 ((equal e '(:newline))
12045 (when (not (= cnt 0))
12046 (setq cnt 0)
12047 (insert "\n")
12048 (setq e (car tbl))
12049 (while (equal (car tbl) '(:newline))
12050 (insert "\n")
12051 (setq tbl (cdr tbl)))))
12053 (setq tg (car e) c (cdr e))
12054 (if ingroup (push tg (car groups)))
12055 (setq tg (org-add-props tg nil 'face
12056 (org-get-todo-face tg)))
12057 (if (and (= cnt 0) (not ingroup)) (insert " "))
12058 (insert "[" c "] " tg (make-string
12059 (- fwidth 4 (length tg)) ?\ ))
12060 (when (= (setq cnt (1+ cnt)) ncol)
12061 (insert "\n")
12062 (if ingroup (insert " "))
12063 (setq cnt 0)))))
12064 (insert "\n")
12065 (goto-char (point-min))
12066 (if (not expert) (org-fit-window-to-buffer))
12067 (message "[a-z..]:Set [SPC]:clear")
12068 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12069 (cond
12070 ((or (= c ?\C-g)
12071 (and (= c ?q) (not (rassoc c fulltable))))
12072 (setq quit-flag t))
12073 ((= c ?\ ) nil)
12074 ((setq e (rassoc c fulltable) tg (car e))
12076 (t (setq quit-flag t)))))))
12078 (defun org-entry-is-todo-p ()
12079 (member (org-get-todo-state) org-not-done-keywords))
12081 (defun org-entry-is-done-p ()
12082 (member (org-get-todo-state) org-done-keywords))
12084 (defun org-get-todo-state ()
12085 (save-excursion
12086 (org-back-to-heading t)
12087 (and (looking-at org-todo-line-regexp)
12088 (match-end 2)
12089 (match-string 2))))
12091 (defun org-at-date-range-p (&optional inactive-ok)
12092 "Is the cursor inside a date range?"
12093 (interactive)
12094 (save-excursion
12095 (catch 'exit
12096 (let ((pos (point)))
12097 (skip-chars-backward "^[<\r\n")
12098 (skip-chars-backward "<[")
12099 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12100 (>= (match-end 0) pos)
12101 (throw 'exit t))
12102 (skip-chars-backward "^<[\r\n")
12103 (skip-chars-backward "<[")
12104 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12105 (>= (match-end 0) pos)
12106 (throw 'exit t)))
12107 nil)))
12109 (defun org-get-repeat (&optional tagline)
12110 "Check if there is a deadline/schedule with repeater in this entry."
12111 (save-match-data
12112 (save-excursion
12113 (org-back-to-heading t)
12114 (and (re-search-forward (if tagline
12115 (concat tagline "\\s-*" org-repeat-re)
12116 org-repeat-re)
12117 (org-entry-end-position) t)
12118 (match-string-no-properties 1)))))
12120 (defvar org-last-changed-timestamp)
12121 (defvar org-last-inserted-timestamp)
12122 (defvar org-log-post-message)
12123 (defvar org-log-note-purpose)
12124 (defvar org-log-note-how)
12125 (defvar org-log-note-extra)
12126 (defun org-auto-repeat-maybe (done-word)
12127 "Check if the current headline contains a repeated deadline/schedule.
12128 If yes, set TODO state back to what it was and change the base date
12129 of repeating deadline/scheduled time stamps to new date.
12130 This function is run automatically after each state change to a DONE state."
12131 ;; last-state is dynamically scoped into this function
12132 (let* ((repeat (org-get-repeat))
12133 (aa (assoc org-last-state org-todo-kwd-alist))
12134 (interpret (nth 1 aa))
12135 (head (nth 2 aa))
12136 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12137 (msg "Entry repeats: ")
12138 (org-log-done nil)
12139 (org-todo-log-states nil)
12140 re type n what ts time to-state)
12141 (when repeat
12142 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12143 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12144 org-todo-repeat-to-state))
12145 (unless (and to-state (member to-state org-todo-keywords-1))
12146 (setq to-state (if (eq interpret 'type) org-last-state head)))
12147 (org-todo to-state)
12148 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12149 (org-entry-put nil "LAST_REPEAT" (format-time-string
12150 (org-time-stamp-format t t))))
12151 (when org-log-repeat
12152 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12153 (memq 'org-add-log-note post-command-hook))
12154 ;; OK, we are already setup for some record
12155 (if (eq org-log-repeat 'note)
12156 ;; make sure we take a note, not only a time stamp
12157 (setq org-log-note-how 'note))
12158 ;; Set up for taking a record
12159 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12160 org-last-state
12161 'findpos org-log-repeat)))
12162 (org-back-to-heading t)
12163 (org-add-planning-info nil nil 'closed)
12164 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12165 org-deadline-time-regexp "\\)\\|\\("
12166 org-ts-regexp "\\)"))
12167 (while (re-search-forward
12168 re (save-excursion (outline-next-heading) (point)) t)
12169 (setq type (if (match-end 1) org-scheduled-string
12170 (if (match-end 3) org-deadline-string "Plain:"))
12171 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12172 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12173 (setq n (string-to-number (match-string 2 ts))
12174 what (match-string 3 ts))
12175 (if (equal what "w") (setq n (* n 7) what "d"))
12176 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12177 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12178 ;; Preparation, see if we need to modify the start date for the change
12179 (when (match-end 1)
12180 (setq time (save-match-data (org-time-string-to-time ts)))
12181 (cond
12182 ((equal (match-string 1 ts) ".")
12183 ;; Shift starting date to today
12184 (org-timestamp-change
12185 (- (org-today) (time-to-days time))
12186 'day))
12187 ((equal (match-string 1 ts) "+")
12188 (let ((nshiftmax 10) (nshift 0))
12189 (while (or (= nshift 0)
12190 (<= (time-to-days time)
12191 (time-to-days (current-time))))
12192 (when (= (incf nshift) nshiftmax)
12193 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12194 (error "Abort")))
12195 (org-timestamp-change n (cdr (assoc what whata)))
12196 (org-at-timestamp-p t)
12197 (setq ts (match-string 1))
12198 (setq time (save-match-data (org-time-string-to-time ts)))))
12199 (org-timestamp-change (- n) (cdr (assoc what whata)))
12200 ;; rematch, so that we have everything in place for the real shift
12201 (org-at-timestamp-p t)
12202 (setq ts (match-string 1))
12203 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12204 (org-timestamp-change n (cdr (assoc what whata)))
12205 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12206 (setq org-log-post-message msg)
12207 (message "%s" msg))))
12209 (defun org-show-todo-tree (arg)
12210 "Make a compact tree which shows all headlines marked with TODO.
12211 The tree will show the lines where the regexp matches, and all higher
12212 headlines above the match.
12213 With a \\[universal-argument] prefix, prompt for a regexp to match.
12214 With a numeric prefix N, construct a sparse tree for the Nth element
12215 of `org-todo-keywords-1'."
12216 (interactive "P")
12217 (let ((case-fold-search nil)
12218 (kwd-re
12219 (cond ((null arg) org-not-done-regexp)
12220 ((equal arg '(4))
12221 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12222 (mapcar 'list org-todo-keywords-1))))
12223 (concat "\\("
12224 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12225 "\\)\\>")))
12226 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12227 (regexp-quote (nth (1- (prefix-numeric-value arg))
12228 org-todo-keywords-1)))
12229 (t (error "Invalid prefix argument: %s" arg)))))
12230 (message "%d TODO entries found"
12231 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12233 (defun org-deadline (&optional remove time)
12234 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12235 With argument REMOVE, remove any deadline from the item.
12236 With argument TIME, set the deadline at the corresponding date. TIME
12237 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12238 (interactive "P")
12239 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12240 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12241 'region-start-level 'region))
12242 org-loop-over-headlines-in-active-region)
12243 (org-map-entries
12244 `(org-deadline ',remove ,time)
12245 org-loop-over-headlines-in-active-region
12246 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12247 (let* ((old-date (org-entry-get nil "DEADLINE"))
12248 (repeater (and old-date
12249 (string-match
12250 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12251 old-date)
12252 (match-string 1 old-date))))
12253 (if remove
12254 (progn
12255 (when (and old-date org-log-redeadline)
12256 (org-add-log-setup 'deldeadline nil old-date 'findpos
12257 org-log-redeadline))
12258 (org-remove-timestamp-with-keyword org-deadline-string)
12259 (message "Item no longer has a deadline."))
12260 (org-add-planning-info 'deadline time 'closed)
12261 (when (and old-date org-log-redeadline
12262 (not (equal old-date
12263 (substring org-last-inserted-timestamp 1 -1))))
12264 (org-add-log-setup 'redeadline nil old-date 'findpos
12265 org-log-redeadline))
12266 (when repeater
12267 (save-excursion
12268 (org-back-to-heading t)
12269 (when (re-search-forward (concat org-deadline-string " "
12270 org-last-inserted-timestamp)
12271 (save-excursion
12272 (outline-next-heading) (point)) t)
12273 (goto-char (1- (match-end 0)))
12274 (insert " " repeater)
12275 (setq org-last-inserted-timestamp
12276 (concat (substring org-last-inserted-timestamp 0 -1)
12277 " " repeater
12278 (substring org-last-inserted-timestamp -1))))))
12279 (message "Deadline on %s" org-last-inserted-timestamp)))))
12281 (defun org-schedule (&optional remove time)
12282 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12283 With argument REMOVE, remove any scheduling date from the item.
12284 With argument TIME, scheduled at the corresponding date. TIME can
12285 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12286 (interactive "P")
12287 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12288 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12289 'region-start-level 'region))
12290 org-loop-over-headlines-in-active-region)
12291 (org-map-entries
12292 `(org-schedule ',remove ,time)
12293 org-loop-over-headlines-in-active-region
12294 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12295 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12296 (repeater (and old-date
12297 (string-match
12298 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12299 old-date)
12300 (match-string 1 old-date))))
12301 (if remove
12302 (progn
12303 (when (and old-date org-log-reschedule)
12304 (org-add-log-setup 'delschedule nil old-date 'findpos
12305 org-log-reschedule))
12306 (org-remove-timestamp-with-keyword org-scheduled-string)
12307 (message "Item is no longer scheduled."))
12308 (org-add-planning-info 'scheduled time 'closed)
12309 (when (and old-date org-log-reschedule
12310 (not (equal old-date
12311 (substring org-last-inserted-timestamp 1 -1))))
12312 (org-add-log-setup 'reschedule nil old-date 'findpos
12313 org-log-reschedule))
12314 (when repeater
12315 (save-excursion
12316 (org-back-to-heading t)
12317 (when (re-search-forward (concat org-scheduled-string " "
12318 org-last-inserted-timestamp)
12319 (save-excursion
12320 (outline-next-heading) (point)) t)
12321 (goto-char (1- (match-end 0)))
12322 (insert " " repeater)
12323 (setq org-last-inserted-timestamp
12324 (concat (substring org-last-inserted-timestamp 0 -1)
12325 " " repeater
12326 (substring org-last-inserted-timestamp -1))))))
12327 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12329 (defun org-get-scheduled-time (pom &optional inherit)
12330 "Get the scheduled time as a time tuple, of a format suitable
12331 for calling org-schedule with, or if there is no scheduling,
12332 returns nil."
12333 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12334 (when time
12335 (apply 'encode-time (org-parse-time-string time)))))
12337 (defun org-get-deadline-time (pom &optional inherit)
12338 "Get the deadline as a time tuple, of a format suitable for
12339 calling org-deadline with, or if there is no scheduling, returns
12340 nil."
12341 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12342 (when time
12343 (apply 'encode-time (org-parse-time-string time)))))
12345 (defun org-remove-timestamp-with-keyword (keyword)
12346 "Remove all time stamps with KEYWORD in the current entry."
12347 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12348 beg)
12349 (save-excursion
12350 (org-back-to-heading t)
12351 (setq beg (point))
12352 (outline-next-heading)
12353 (while (re-search-backward re beg t)
12354 (replace-match "")
12355 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12356 (equal (char-before) ?\ ))
12357 (backward-delete-char 1)
12358 (if (string-match "^[ \t]*$" (buffer-substring
12359 (point-at-bol) (point-at-eol)))
12360 (delete-region (point-at-bol)
12361 (min (point-max) (1+ (point-at-eol))))))))))
12363 (defun org-add-planning-info (what &optional time &rest remove)
12364 "Insert new timestamp with keyword in the line directly after the headline.
12365 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12366 If non is given, the user is prompted for a date.
12367 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12368 be removed."
12369 (interactive)
12370 (let (org-time-was-given org-end-time-was-given ts
12371 end default-time default-input)
12373 (catch 'exit
12374 (when (and (memq what '(scheduled deadline))
12375 (or (not time)
12376 (and (stringp time)
12377 (string-match "^[-+]+[0-9]" time))))
12378 ;; Try to get a default date/time from existing timestamp
12379 (save-excursion
12380 (org-back-to-heading t)
12381 (setq end (save-excursion (outline-next-heading) (point)))
12382 (when (re-search-forward (if (eq what 'scheduled)
12383 org-scheduled-time-regexp
12384 org-deadline-time-regexp)
12385 end t)
12386 (setq ts (match-string 1)
12387 default-time
12388 (apply 'encode-time (org-parse-time-string ts))
12389 default-input (and ts (org-get-compact-tod ts))))))
12390 (when what
12391 (setq time
12392 (if (stringp time)
12393 ;; This is a string (relative or absolute), set proper date
12394 (apply 'encode-time
12395 (org-read-date-analyze
12396 time default-time (decode-time default-time)))
12397 ;; If necessary, get the time from the user
12398 (or time (org-read-date nil 'to-time nil nil
12399 default-time default-input)))))
12401 (when (and org-insert-labeled-timestamps-at-point
12402 (member what '(scheduled deadline)))
12403 (insert
12404 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12405 (org-insert-time-stamp time org-time-was-given
12406 nil nil nil (list org-end-time-was-given))
12407 (setq what nil))
12408 (save-excursion
12409 (save-restriction
12410 (let (col list elt ts buffer-invisibility-spec)
12411 (org-back-to-heading t)
12412 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12413 (goto-char (match-end 1))
12414 (setq col (current-column))
12415 (goto-char (match-end 0))
12416 (if (eobp) (insert "\n") (forward-char 1))
12417 (when (and (not what)
12418 (not (looking-at
12419 (concat "[ \t]*"
12420 org-keyword-time-not-clock-regexp))))
12421 ;; Nothing to add, nothing to remove...... :-)
12422 (throw 'exit nil))
12423 (if (and (not (looking-at org-outline-regexp))
12424 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12425 "[^\r\n]*"))
12426 (not (equal (match-string 1) org-clock-string)))
12427 (narrow-to-region (match-beginning 0) (match-end 0))
12428 (insert-before-markers "\n")
12429 (backward-char 1)
12430 (narrow-to-region (point) (point))
12431 (and org-adapt-indentation (org-indent-to-column col)))
12432 ;; Check if we have to remove something.
12433 (setq list (cons what remove))
12434 (while list
12435 (setq elt (pop list))
12436 (when (or (and (eq elt 'scheduled)
12437 (re-search-forward org-scheduled-time-regexp nil t))
12438 (and (eq elt 'deadline)
12439 (re-search-forward org-deadline-time-regexp nil t))
12440 (and (eq elt 'closed)
12441 (re-search-forward org-closed-time-regexp nil t)))
12442 (replace-match "")
12443 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12444 (and (looking-at "[ \t]+") (replace-match ""))
12445 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12446 (when what
12447 (insert
12448 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12449 (cond ((eq what 'scheduled) org-scheduled-string)
12450 ((eq what 'deadline) org-deadline-string)
12451 ((eq what 'closed) org-closed-string))
12452 " ")
12453 (setq ts (org-insert-time-stamp
12454 time
12455 (or org-time-was-given
12456 (and (eq what 'closed) org-log-done-with-time))
12457 (eq what 'closed)
12458 nil nil (list org-end-time-was-given)))
12459 (insert
12460 (if (not (or (bolp) (eq (char-before) ?\ )
12461 (memq (char-after) '(32 10))
12462 (eobp))) " " ""))
12463 (end-of-line 1))
12464 (goto-char (point-min))
12465 (widen)
12466 (if (and (looking-at "[ \t]*\n")
12467 (equal (char-before) ?\n))
12468 (delete-region (1- (point)) (point-at-eol)))
12469 ts))))))
12471 (defvar org-log-note-marker (make-marker))
12472 (defvar org-log-note-purpose nil)
12473 (defvar org-log-note-state nil)
12474 (defvar org-log-note-previous-state nil)
12475 (defvar org-log-note-how nil)
12476 (defvar org-log-note-extra nil)
12477 (defvar org-log-note-window-configuration nil)
12478 (defvar org-log-note-return-to (make-marker))
12479 (defvar org-log-note-effective-time nil
12480 "Remembered current time so that dynamically scoped
12481 `org-extend-today-until' affects tha timestamps in state change
12482 log")
12484 (defvar org-log-post-message nil
12485 "Message to be displayed after a log note has been stored.
12486 The auto-repeater uses this.")
12488 (defun org-add-note ()
12489 "Add a note to the current entry.
12490 This is done in the same way as adding a state change note."
12491 (interactive)
12492 (org-add-log-setup 'note nil nil 'findpos nil))
12494 (defvar org-property-end-re)
12495 (defun org-add-log-setup (&optional purpose state prev-state
12496 findpos how extra)
12497 "Set up the post command hook to take a note.
12498 If this is about to TODO state change, the new state is expected in STATE.
12499 When FINDPOS is non-nil, find the correct position for the note in
12500 the current entry. If not, assume that it can be inserted at point.
12501 HOW is an indicator what kind of note should be created.
12502 EXTRA is additional text that will be inserted into the notes buffer."
12503 (let* ((org-log-into-drawer (org-log-into-drawer))
12504 (drawer (cond ((stringp org-log-into-drawer)
12505 org-log-into-drawer)
12506 (org-log-into-drawer "LOGBOOK"))))
12507 (save-restriction
12508 (save-excursion
12509 (when findpos
12510 (org-back-to-heading t)
12511 (narrow-to-region (point) (save-excursion
12512 (outline-next-heading) (point)))
12513 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12514 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12515 "[^\r\n]*\\)?"))
12516 (goto-char (match-end 0))
12517 (cond
12518 (drawer
12519 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12520 nil t)
12521 (progn
12522 (goto-char (match-end 0))
12523 (or org-log-states-order-reversed
12524 (and (re-search-forward org-property-end-re nil t)
12525 (goto-char (1- (match-beginning 0))))))
12526 (insert "\n:" drawer ":\n:END:")
12527 (beginning-of-line 0)
12528 (org-indent-line)
12529 (beginning-of-line 2)
12530 (org-indent-line)
12531 (end-of-line 0)))
12532 ((and org-log-state-notes-insert-after-drawers
12533 (save-excursion
12534 (forward-line) (looking-at org-drawer-regexp)))
12535 (forward-line)
12536 (while (looking-at org-drawer-regexp)
12537 (goto-char (match-end 0))
12538 (re-search-forward org-property-end-re (point-max) t)
12539 (forward-line))
12540 (forward-line -1)))
12541 (unless org-log-states-order-reversed
12542 (and (= (char-after) ?\n) (forward-char 1))
12543 (org-skip-over-state-notes)
12544 (skip-chars-backward " \t\n\r")))
12545 (move-marker org-log-note-marker (point))
12546 (setq org-log-note-purpose purpose
12547 org-log-note-state state
12548 org-log-note-previous-state prev-state
12549 org-log-note-how how
12550 org-log-note-extra extra
12551 org-log-note-effective-time (org-current-effective-time))
12552 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12554 (defun org-skip-over-state-notes ()
12555 "Skip past the list of State notes in an entry."
12556 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12557 (when (ignore-errors (goto-char (org-in-item-p)))
12558 (let* ((struct (org-list-struct))
12559 (prevs (org-list-prevs-alist struct)))
12560 (while (looking-at "[ \t]*- State")
12561 (goto-char (or (org-list-get-next-item (point) struct prevs)
12562 (org-list-get-item-end (point) struct)))))))
12564 (defun org-add-log-note (&optional purpose)
12565 "Pop up a window for taking a note, and add this note later at point."
12566 (remove-hook 'post-command-hook 'org-add-log-note)
12567 (setq org-log-note-window-configuration (current-window-configuration))
12568 (delete-other-windows)
12569 (move-marker org-log-note-return-to (point))
12570 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12571 (goto-char org-log-note-marker)
12572 (org-switch-to-buffer-other-window "*Org Note*")
12573 (erase-buffer)
12574 (if (memq org-log-note-how '(time state))
12575 (let (current-prefix-arg) (org-store-log-note))
12576 (let ((org-inhibit-startup t)) (org-mode))
12577 (insert (format "# Insert note for %s.
12578 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12579 (cond
12580 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12581 ((eq org-log-note-purpose 'done) "closed todo item")
12582 ((eq org-log-note-purpose 'state)
12583 (format "state change from \"%s\" to \"%s\""
12584 (or org-log-note-previous-state "")
12585 (or org-log-note-state "")))
12586 ((eq org-log-note-purpose 'reschedule)
12587 "rescheduling")
12588 ((eq org-log-note-purpose 'delschedule)
12589 "no longer scheduled")
12590 ((eq org-log-note-purpose 'redeadline)
12591 "changing deadline")
12592 ((eq org-log-note-purpose 'deldeadline)
12593 "removing deadline")
12594 ((eq org-log-note-purpose 'refile)
12595 "refiling")
12596 ((eq org-log-note-purpose 'note)
12597 "this entry")
12598 (t (error "This should not happen")))))
12599 (if org-log-note-extra (insert org-log-note-extra))
12600 (org-set-local 'org-finish-function 'org-store-log-note)
12601 (run-hooks 'org-log-buffer-setup-hook)))
12603 (defvar org-note-abort nil) ; dynamically scoped
12604 (defun org-store-log-note ()
12605 "Finish taking a log note, and insert it to where it belongs."
12606 (let ((txt (buffer-string))
12607 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12608 lines ind bul)
12609 (kill-buffer (current-buffer))
12610 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12611 (setq txt (replace-match "" t t txt)))
12612 (if (string-match "\\s-+\\'" txt)
12613 (setq txt (replace-match "" t t txt)))
12614 (setq lines (org-split-string txt "\n"))
12615 (when (and note (string-match "\\S-" note))
12616 (setq note
12617 (org-replace-escapes
12618 note
12619 (list (cons "%u" (user-login-name))
12620 (cons "%U" user-full-name)
12621 (cons "%t" (format-time-string
12622 (org-time-stamp-format 'long 'inactive)
12623 org-log-note-effective-time))
12624 (cons "%T" (format-time-string
12625 (org-time-stamp-format 'long nil)
12626 org-log-note-effective-time))
12627 (cons "%d" (format-time-string
12628 (org-time-stamp-format nil 'inactive)
12629 org-log-note-effective-time))
12630 (cons "%D" (format-time-string
12631 (org-time-stamp-format nil nil)
12632 org-log-note-effective-time))
12633 (cons "%s" (if org-log-note-state
12634 (concat "\"" org-log-note-state "\"")
12635 ""))
12636 (cons "%S" (if org-log-note-previous-state
12637 (concat "\"" org-log-note-previous-state "\"")
12638 "\"\"")))))
12639 (if lines (setq note (concat note " \\\\")))
12640 (push note lines))
12641 (when (or current-prefix-arg org-note-abort)
12642 (when org-log-into-drawer
12643 (org-remove-empty-drawer-at
12644 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12645 org-log-note-marker))
12646 (setq lines nil))
12647 (when lines
12648 (with-current-buffer (marker-buffer org-log-note-marker)
12649 (save-excursion
12650 (goto-char org-log-note-marker)
12651 (move-marker org-log-note-marker nil)
12652 (end-of-line 1)
12653 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12654 (setq ind (save-excursion
12655 (if (ignore-errors (goto-char (org-in-item-p)))
12656 (let ((struct (org-list-struct)))
12657 (org-list-get-ind
12658 (org-list-get-top-point struct) struct))
12659 (skip-chars-backward " \r\t\n")
12660 (cond
12661 ((and (org-at-heading-p)
12662 org-adapt-indentation)
12663 (1+ (org-current-level)))
12664 ((org-at-heading-p) 0)
12665 (t (org-get-indentation))))))
12666 (setq bul (org-list-bullet-string "-"))
12667 (org-indent-line-to ind)
12668 (insert bul (pop lines))
12669 (let ((ind-body (+ (length bul) ind)))
12670 (while lines
12671 (insert "\n")
12672 (org-indent-line-to ind-body)
12673 (insert (pop lines))))
12674 (message "Note stored")
12675 (org-back-to-heading t)
12676 (org-cycle-hide-drawers 'children)))))
12677 (set-window-configuration org-log-note-window-configuration)
12678 (with-current-buffer (marker-buffer org-log-note-return-to)
12679 (goto-char org-log-note-return-to))
12680 (move-marker org-log-note-return-to nil)
12681 (and org-log-post-message (message "%s" org-log-post-message)))
12683 (defun org-remove-empty-drawer-at (drawer pos)
12684 "Remove an empty drawer DRAWER at position POS.
12685 POS may also be a marker."
12686 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12687 (save-excursion
12688 (save-restriction
12689 (widen)
12690 (goto-char pos)
12691 (if (org-in-regexp
12692 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12693 (replace-match ""))))))
12695 (defvar org-ts-type nil)
12696 (defun org-sparse-tree (&optional arg type)
12697 "Create a sparse tree, prompt for the details.
12698 This command can create sparse trees. You first need to select the type
12699 of match used to create the tree:
12701 t Show all TODO entries.
12702 T Show entries with a specific TODO keyword.
12703 m Show entries selected by a tags/property match.
12704 p Enter a property name and its value (both with completion on existing
12705 names/values) and show entries with that property.
12706 r Show entries matching a regular expression (`/' can be used as well).
12707 b Show deadlines and scheduled items before a date.
12708 a Show deadlines and scheduled items after a date.
12709 d Show deadlines due within `org-deadline-warning-days'.
12710 D Show deadlines and scheduled items between a date range."
12711 (interactive "P")
12712 (let (ans kwd value ts-type)
12713 (setq type (or type org-sparse-tree-default-date-type))
12714 (setq org-ts-type type)
12715 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date [D]ates range\n [c]ycle through date types: %s"
12716 (cond ((eq type 'all) "all timestamps")
12717 ((eq type 'scheduled) "only scheduled")
12718 ((eq type 'deadline) "only deadline")
12719 ((eq type 'active) "only active timestamps")
12720 ((eq type 'inactive) "only inactive timestamps")
12721 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12722 (t "scheduled/deadline")))
12723 (setq ans (read-char-exclusive))
12724 (cond
12725 ((equal ans ?c)
12726 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12727 ((equal ans ?d)
12728 (call-interactively 'org-check-deadlines))
12729 ((equal ans ?b)
12730 (call-interactively 'org-check-before-date))
12731 ((equal ans ?a)
12732 (call-interactively 'org-check-after-date))
12733 ((equal ans ?D)
12734 (call-interactively 'org-check-dates-range))
12735 ((equal ans ?t)
12736 (call-interactively 'org-show-todo-tree))
12737 ((equal ans ?T)
12738 (org-show-todo-tree '(4)))
12739 ((member ans '(?T ?m))
12740 (call-interactively 'org-match-sparse-tree))
12741 ((member ans '(?p ?P))
12742 (setq kwd (org-icompleting-read "Property: "
12743 (mapcar 'list (org-buffer-property-keys))))
12744 (setq value (org-icompleting-read "Value: "
12745 (mapcar 'list (org-property-values kwd))))
12746 (unless (string-match "\\`{.*}\\'" value)
12747 (setq value (concat "\"" value "\"")))
12748 (org-match-sparse-tree arg (concat kwd "=" value)))
12749 ((member ans '(?r ?R ?/))
12750 (call-interactively 'org-occur))
12751 (t (error "No such sparse tree command \"%c\"" ans)))))
12753 (defvar org-occur-highlights nil
12754 "List of overlays used for occur matches.")
12755 (make-variable-buffer-local 'org-occur-highlights)
12756 (defvar org-occur-parameters nil
12757 "Parameters of the active org-occur calls.
12758 This is a list, each call to org-occur pushes as cons cell,
12759 containing the regular expression and the callback, onto the list.
12760 The list can contain several entries if `org-occur' has been called
12761 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12762 will only contain one set of parameters. When the highlights are
12763 removed (for example with `C-c C-c', or with the next edit (depending
12764 on `org-remove-highlights-with-change'), this variable is emptied
12765 as well.")
12766 (make-variable-buffer-local 'org-occur-parameters)
12768 (defun org-occur (regexp &optional keep-previous callback)
12769 "Make a compact tree which shows all matches of REGEXP.
12770 The tree will show the lines where the regexp matches, and all higher
12771 headlines above the match. It will also show the heading after the match,
12772 to make sure editing the matching entry is easy.
12773 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12774 call to `org-occur' will be kept, to allow stacking of calls to this
12775 command.
12776 If CALLBACK is non-nil, it is a function which is called to confirm
12777 that the match should indeed be shown."
12778 (interactive "sRegexp: \nP")
12779 (when (equal regexp "")
12780 (error "Regexp cannot be empty"))
12781 (unless keep-previous
12782 (org-remove-occur-highlights nil nil t))
12783 (push (cons regexp callback) org-occur-parameters)
12784 (let ((cnt 0))
12785 (save-excursion
12786 (goto-char (point-min))
12787 (if (or (not keep-previous) ; do not want to keep
12788 (not org-occur-highlights)) ; no previous matches
12789 ;; hide everything
12790 (org-overview))
12791 (while (re-search-forward regexp nil t)
12792 (when (or (not callback)
12793 (save-match-data (funcall callback)))
12794 (setq cnt (1+ cnt))
12795 (when org-highlight-sparse-tree-matches
12796 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12797 (org-show-context 'occur-tree))))
12798 (when org-remove-highlights-with-change
12799 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12800 nil 'local))
12801 (unless org-sparse-tree-open-archived-trees
12802 (org-hide-archived-subtrees (point-min) (point-max)))
12803 (run-hooks 'org-occur-hook)
12804 (if (org-called-interactively-p 'interactive)
12805 (message "%d match(es) for regexp %s" cnt regexp))
12806 cnt))
12808 (defun org-occur-next-match (&optional n reset)
12809 "Function for `next-error-function' to find sparse tree matches.
12810 N is the number of matches to move, when negative move backwards.
12811 RESET is entirely ignored - this function always goes back to the
12812 starting point when no match is found."
12813 (let* ((limit (if (< n 0) (point-min) (point-max)))
12814 (search-func (if (< n 0)
12815 'previous-single-char-property-change
12816 'next-single-char-property-change))
12817 (n (abs n))
12818 (pos (point))
12820 (catch 'exit
12821 (while (setq p1 (funcall search-func (point) 'org-type))
12822 (when (equal p1 limit)
12823 (goto-char pos)
12824 (error "No more matches"))
12825 (when (equal (get-char-property p1 'org-type) 'org-occur)
12826 (setq n (1- n))
12827 (when (= n 0)
12828 (goto-char p1)
12829 (throw 'exit (point))))
12830 (goto-char p1))
12831 (goto-char p1)
12832 (error "No more matches"))))
12834 (defun org-show-context (&optional key)
12835 "Make sure point and context are visible.
12836 How much context is shown depends upon the variables
12837 `org-show-hierarchy-above', `org-show-following-heading',
12838 `org-show-entry-below' and `org-show-siblings'."
12839 (let ((heading-p (org-at-heading-p t))
12840 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12841 (following-p (org-get-alist-option org-show-following-heading key))
12842 (entry-p (org-get-alist-option org-show-entry-below key))
12843 (siblings-p (org-get-alist-option org-show-siblings key)))
12844 (catch 'exit
12845 ;; Show heading or entry text
12846 (if (and heading-p (not entry-p))
12847 (org-flag-heading nil) ; only show the heading
12848 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12849 (org-show-hidden-entry))) ; show entire entry
12850 (when following-p
12851 ;; Show next sibling, or heading below text
12852 (save-excursion
12853 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12854 (org-flag-heading nil))))
12855 (when siblings-p (org-show-siblings))
12856 (when hierarchy-p
12857 ;; show all higher headings, possibly with siblings
12858 (save-excursion
12859 (while (and (condition-case nil
12860 (progn (org-up-heading-all 1) t)
12861 (error nil))
12862 (not (bobp)))
12863 (org-flag-heading nil)
12864 (when siblings-p (org-show-siblings))))))))
12866 (defvar org-reveal-start-hook nil
12867 "Hook run before revealing a location.")
12869 (defun org-reveal (&optional siblings)
12870 "Show current entry, hierarchy above it, and the following headline.
12871 This can be used to show a consistent set of context around locations
12872 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12873 not t for the search context.
12875 With optional argument SIBLINGS, on each level of the hierarchy all
12876 siblings are shown. This repairs the tree structure to what it would
12877 look like when opened with hierarchical calls to `org-cycle'.
12878 With double optional argument \\[universal-argument] \\[universal-argument], \
12879 go to the parent and show the
12880 entire tree."
12881 (interactive "P")
12882 (run-hooks 'org-reveal-start-hook)
12883 (let ((org-show-hierarchy-above t)
12884 (org-show-following-heading t)
12885 (org-show-siblings (if siblings t org-show-siblings)))
12886 (org-show-context nil))
12887 (when (equal siblings '(16))
12888 (save-excursion
12889 (when (org-up-heading-safe)
12890 (org-show-subtree)
12891 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12893 (defun org-highlight-new-match (beg end)
12894 "Highlight from BEG to END and mark the highlight is an occur headline."
12895 (let ((ov (make-overlay beg end)))
12896 (overlay-put ov 'face 'secondary-selection)
12897 (overlay-put ov 'org-type 'org-occur)
12898 (push ov org-occur-highlights)))
12900 (defun org-remove-occur-highlights (&optional beg end noremove)
12901 "Remove the occur highlights from the buffer.
12902 BEG and END are ignored. If NOREMOVE is nil, remove this function
12903 from the `before-change-functions' in the current buffer."
12904 (interactive)
12905 (unless org-inhibit-highlight-removal
12906 (mapc 'delete-overlay org-occur-highlights)
12907 (setq org-occur-highlights nil)
12908 (setq org-occur-parameters nil)
12909 (unless noremove
12910 (remove-hook 'before-change-functions
12911 'org-remove-occur-highlights 'local))))
12913 ;;;; Priorities
12915 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12916 "Regular expression matching the priority indicator.")
12918 (defvar org-remove-priority-next-time nil)
12920 (defun org-priority-up ()
12921 "Increase the priority of the current item."
12922 (interactive)
12923 (org-priority 'up))
12925 (defun org-priority-down ()
12926 "Decrease the priority of the current item."
12927 (interactive)
12928 (org-priority 'down))
12930 (defun org-priority (&optional action show)
12931 "Change the priority of an item.
12932 ACTION can be `set', `up', `down', or a character."
12933 (interactive "P")
12934 (if (equal action '(4))
12935 (org-show-priority)
12936 (unless org-enable-priority-commands
12937 (error "Priority commands are disabled"))
12938 (setq action (or action 'set))
12939 (let (current new news have remove)
12940 (save-excursion
12941 (org-back-to-heading t)
12942 (if (looking-at org-priority-regexp)
12943 (setq current (string-to-char (match-string 2))
12944 have t))
12945 (cond
12946 ((eq action 'remove)
12947 (setq remove t new ?\ ))
12948 ((or (eq action 'set)
12949 (if (featurep 'xemacs) (characterp action) (integerp action)))
12950 (if (not (eq action 'set))
12951 (setq new action)
12952 (message "Priority %c-%c, SPC to remove: "
12953 org-highest-priority org-lowest-priority)
12954 (save-match-data
12955 (setq new (read-char-exclusive))))
12956 (if (and (= (upcase org-highest-priority) org-highest-priority)
12957 (= (upcase org-lowest-priority) org-lowest-priority))
12958 (setq new (upcase new)))
12959 (cond ((equal new ?\ ) (setq remove t))
12960 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12961 (error "Priority must be between `%c' and `%c'"
12962 org-highest-priority org-lowest-priority))))
12963 ((eq action 'up)
12964 (setq new (if have
12965 (1- current) ; normal cycling
12966 ;; last priority was empty
12967 (if (eq last-command this-command)
12968 org-lowest-priority ; wrap around empty to lowest
12969 ;; default
12970 (if org-priority-start-cycle-with-default
12971 org-default-priority
12972 (1- org-default-priority))))))
12973 ((eq action 'down)
12974 (setq new (if have
12975 (1+ current) ; normal cycling
12976 ;; last priority was empty
12977 (if (eq last-command this-command)
12978 org-highest-priority ; wrap around empty to highest
12979 ;; default
12980 (if org-priority-start-cycle-with-default
12981 org-default-priority
12982 (1+ org-default-priority))))))
12983 (t (error "Invalid action")))
12984 (if (or (< (upcase new) org-highest-priority)
12985 (> (upcase new) org-lowest-priority))
12986 (if (and (memq action '(up down))
12987 (not have) (not (eq last-command this-command)))
12988 ;; `new' is from default priority
12989 (error
12990 "The default can not be set, see `org-default-priority' why")
12991 ;; normal cycling: `new' is beyond highest/lowest priority
12992 ;; and is wrapped around to the empty priority
12993 (setq remove t)))
12994 (setq news (format "%c" new))
12995 (if have
12996 (if remove
12997 (replace-match "" t t nil 1)
12998 (replace-match news t t nil 2))
12999 (if remove
13000 (error "No priority cookie found in line")
13001 (let ((case-fold-search nil))
13002 (looking-at org-todo-line-regexp))
13003 (if (match-end 2)
13004 (progn
13005 (goto-char (match-end 2))
13006 (insert " [#" news "]"))
13007 (goto-char (match-beginning 3))
13008 (insert "[#" news "] "))))
13009 (org-preserve-lc (org-set-tags nil 'align)))
13010 (if remove
13011 (message "Priority removed")
13012 (message "Priority of current item set to %s" news)))))
13014 (defun org-show-priority ()
13015 "Show the priority of the current item.
13016 This priority is composed of the main priority given with the [#A] cookies,
13017 and by additional input from the age of a schedules or deadline entry."
13018 (interactive)
13019 (let ((pri (if (eq major-mode 'org-agenda-mode)
13020 (org-get-at-bol 'priority)
13021 (save-excursion
13022 (save-match-data
13023 (beginning-of-line)
13024 (and (looking-at org-heading-regexp)
13025 (org-get-priority (match-string 0))))))))
13026 (message "Priority is %d" (if pri pri -1000))))
13028 (defun org-get-priority (s)
13029 "Find priority cookie and return priority."
13030 (save-match-data
13031 (if (functionp org-get-priority-function)
13032 (funcall org-get-priority-function)
13033 (if (not (string-match org-priority-regexp s))
13034 (* 1000 (- org-lowest-priority org-default-priority))
13035 (* 1000 (- org-lowest-priority
13036 (string-to-char (match-string 2 s))))))))
13038 ;;;; Tags
13040 (defvar org-agenda-archives-mode)
13041 (defvar org-map-continue-from nil
13042 "Position from where mapping should continue.
13043 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13045 (defvar org-scanner-tags nil
13046 "The current tag list while the tags scanner is running.")
13047 (defvar org-trust-scanner-tags nil
13048 "Should `org-get-tags-at' use the tags for the scanner.
13049 This is for internal dynamical scoping only.
13050 When this is non-nil, the function `org-get-tags-at' will return the value
13051 of `org-scanner-tags' instead of building the list by itself. This
13052 can lead to large speed-ups when the tags scanner is used in a file with
13053 many entries, and when the list of tags is retrieved, for example to
13054 obtain a list of properties. Building the tags list for each entry in such
13055 a file becomes an N^2 operation - but with this variable set, it scales
13056 as N.")
13058 (defun org-scan-tags (action matcher todo-only &optional start-level)
13059 "Scan headline tags with inheritance and produce output ACTION.
13061 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13062 or `agenda' to produce an entry list for an agenda view. It can also be
13063 a Lisp form or a function that should be called at each matched headline, in
13064 this case the return value is a list of all return values from these calls.
13066 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13067 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13068 only lines with a not-done TODO keyword are included in the output.
13069 This should be the same variable that was scoped into
13070 and set by `org-make-tags-matcher' when it constructed MATCHER.
13072 START-LEVEL can be a string with asterisks, reducing the scope to
13073 headlines matching this string."
13074 (require 'org-agenda)
13075 (let* ((re (concat "^"
13076 (if start-level
13077 ;; Get the correct level to match
13078 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13079 org-outline-regexp)
13080 " *\\(\\<\\("
13081 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13082 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13083 (props (list 'face 'default
13084 'done-face 'org-agenda-done
13085 'undone-face 'default
13086 'mouse-face 'highlight
13087 'org-not-done-regexp org-not-done-regexp
13088 'org-todo-regexp org-todo-regexp
13089 'org-complex-heading-regexp org-complex-heading-regexp
13090 'help-echo
13091 (format "mouse-2 or RET jump to org file %s"
13092 (abbreviate-file-name
13093 (or (buffer-file-name (buffer-base-buffer))
13094 (buffer-name (buffer-base-buffer)))))))
13095 (case-fold-search nil)
13096 (org-map-continue-from nil)
13097 lspos tags tags-list
13098 (tags-alist (list (cons 0 org-file-tags)))
13099 (llast 0) rtn rtn1 level category i txt
13100 todo marker entry priority)
13101 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13102 (setq action (list 'lambda nil action)))
13103 (save-excursion
13104 (goto-char (point-min))
13105 (when (eq action 'sparse-tree)
13106 (org-overview)
13107 (org-remove-occur-highlights))
13108 (while (re-search-forward re nil t)
13109 (setq org-map-continue-from nil)
13110 (catch :skip
13111 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13112 tags (if (match-end 4) (org-match-string-no-properties 4)))
13113 (goto-char (setq lspos (match-beginning 0)))
13114 (setq level (org-reduced-level (funcall outline-level))
13115 category (org-get-category))
13116 (setq i llast llast level)
13117 ;; remove tag lists from same and sublevels
13118 (while (>= i level)
13119 (when (setq entry (assoc i tags-alist))
13120 (setq tags-alist (delete entry tags-alist)))
13121 (setq i (1- i)))
13122 ;; add the next tags
13123 (when tags
13124 (setq tags (org-split-string tags ":")
13125 tags-alist
13126 (cons (cons level tags) tags-alist)))
13127 ;; compile tags for current headline
13128 (setq tags-list
13129 (if org-use-tag-inheritance
13130 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13131 tags)
13132 org-scanner-tags tags-list)
13133 (when org-use-tag-inheritance
13134 (setcdr (car tags-alist)
13135 (mapcar (lambda (x)
13136 (setq x (copy-sequence x))
13137 (org-add-prop-inherited x))
13138 (cdar tags-alist))))
13139 (when (and tags org-use-tag-inheritance
13140 (or (not (eq t org-use-tag-inheritance))
13141 org-tags-exclude-from-inheritance))
13142 ;; selective inheritance, remove uninherited ones
13143 (setcdr (car tags-alist)
13144 (org-remove-uninherited-tags (cdar tags-alist))))
13145 (when (and
13147 ;; eval matcher only when the todo condition is OK
13148 (and (or (not todo-only) (member todo org-not-done-keywords))
13149 (let ((case-fold-search t) (org-trust-scanner-tags t))
13150 (eval matcher)))
13152 ;; Call the skipper, but return t if it does not skip,
13153 ;; so that the `and' form continues evaluating
13154 (progn
13155 (unless (eq action 'sparse-tree) (org-agenda-skip))
13158 ;; Check if timestamps are deselecting this entry
13159 (or (not todo-only)
13160 (and (member todo org-not-done-keywords)
13161 (or (not org-agenda-tags-todo-honor-ignore-options)
13162 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13164 ;; select this headline
13165 (cond
13166 ((eq action 'sparse-tree)
13167 (and org-highlight-sparse-tree-matches
13168 (org-get-heading) (match-end 0)
13169 (org-highlight-new-match
13170 (match-beginning 1) (match-end 1)))
13171 (org-show-context 'tags-tree))
13172 ((eq action 'agenda)
13173 (setq txt (org-agenda-format-item
13175 (concat
13176 (if (eq org-tags-match-list-sublevels 'indented)
13177 (make-string (1- level) ?.) "")
13178 (org-get-heading))
13179 category
13180 tags-list)
13181 priority (org-get-priority txt))
13182 (goto-char lspos)
13183 (setq marker (org-agenda-new-marker))
13184 (org-add-props txt props
13185 'org-marker marker 'org-hd-marker marker 'org-category category
13186 'todo-state todo
13187 'priority priority 'type "tagsmatch")
13188 (push txt rtn))
13189 ((functionp action)
13190 (setq org-map-continue-from nil)
13191 (save-excursion
13192 (setq rtn1 (funcall action))
13193 (push rtn1 rtn)))
13194 (t (error "Invalid action")))
13196 ;; if we are to skip sublevels, jump to end of subtree
13197 (unless org-tags-match-list-sublevels
13198 (org-end-of-subtree t)
13199 (backward-char 1))))
13200 ;; Get the correct position from where to continue
13201 (if org-map-continue-from
13202 (goto-char org-map-continue-from)
13203 (and (= (point) lspos) (end-of-line 1)))))
13204 (when (and (eq action 'sparse-tree)
13205 (not org-sparse-tree-open-archived-trees))
13206 (org-hide-archived-subtrees (point-min) (point-max)))
13207 (nreverse rtn)))
13209 (defun org-remove-uninherited-tags (tags)
13210 "Remove all tags that are not inherited from the list TAGS."
13211 (cond
13212 ((eq org-use-tag-inheritance t)
13213 (if org-tags-exclude-from-inheritance
13214 (org-delete-all org-tags-exclude-from-inheritance tags)
13215 tags))
13216 ((not org-use-tag-inheritance) nil)
13217 ((stringp org-use-tag-inheritance)
13218 (delq nil (mapcar
13219 (lambda (x)
13220 (if (and (string-match org-use-tag-inheritance x)
13221 (not (member x org-tags-exclude-from-inheritance)))
13222 x nil))
13223 tags)))
13224 ((listp org-use-tag-inheritance)
13225 (delq nil (mapcar
13226 (lambda (x)
13227 (if (member x org-use-tag-inheritance) x nil))
13228 tags)))))
13230 (defun org-match-sparse-tree (&optional todo-only match)
13231 "Create a sparse tree according to tags string MATCH.
13232 MATCH can contain positive and negative selection of tags, like
13233 \"+WORK+URGENT-WITHBOSS\".
13234 If optional argument TODO-ONLY is non-nil, only select lines that are
13235 also TODO lines."
13236 (interactive "P")
13237 (org-agenda-prepare-buffers (list (current-buffer)))
13238 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13240 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13242 (defvar org-cached-props nil)
13243 (defun org-cached-entry-get (pom property)
13244 (if (or (eq t org-use-property-inheritance)
13245 (and (stringp org-use-property-inheritance)
13246 (string-match org-use-property-inheritance property))
13247 (and (listp org-use-property-inheritance)
13248 (member property org-use-property-inheritance)))
13249 ;; Caching is not possible, check it directly
13250 (org-entry-get pom property 'inherit)
13251 ;; Get all properties, so that we can do complicated checks easily
13252 (cdr (assoc property (or org-cached-props
13253 (setq org-cached-props
13254 (org-entry-properties pom)))))))
13256 (defun org-global-tags-completion-table (&optional files)
13257 "Return the list of all tags in all agenda buffer/files.
13258 Optional FILES argument is a list of files which can be used
13259 instead of the agenda files."
13260 (save-excursion
13261 (org-uniquify
13262 (delq nil
13263 (apply 'append
13264 (mapcar
13265 (lambda (file)
13266 (set-buffer (find-file-noselect file))
13267 (append (org-get-buffer-tags)
13268 (mapcar (lambda (x) (if (stringp (car-safe x))
13269 (list (car-safe x)) nil))
13270 org-tag-alist)))
13271 (if (and files (car files))
13272 files
13273 (org-agenda-files))))))))
13275 (defun org-make-tags-matcher (match)
13276 "Create the TAGS/TODO matcher form for the selection string MATCH.
13278 The variable `todo-only' is scoped dynamically into this function.
13279 It will be set to t if the matcher restricts matching to TODO entries,
13280 otherwise will not be touched.
13282 Returns a cons of the selection string MATCH and the constructed
13283 lisp form implementing the matcher. The matcher is to be evaluated
13284 at an Org entry, with point on the headline, and returns t if the
13285 entry matches the selection string MATCH. The returned lisp form
13286 references two variables with information about the entry, which
13287 must be bound around the form's evaluation: todo, the TODO keyword
13288 at the entry (or nil of none); and tags-list, the list of all tags
13289 at the entry including inherited ones. Additionally, the category
13290 of the entry (if any) must be specified as the text property
13291 'org-category on the headline.
13293 See also `org-scan-tags'.
13295 (declare (special todo-only))
13296 (unless (boundp 'todo-only)
13297 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13298 (unless match
13299 ;; Get a new match request, with completion
13300 (let ((org-last-tags-completion-table
13301 (org-global-tags-completion-table)))
13302 (setq match (org-completing-read-no-i
13303 "Match: " 'org-tags-completion-function nil nil nil
13304 'org-tags-history))))
13306 ;; Parse the string and create a lisp form
13307 (let ((match0 match)
13308 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13309 minus tag mm
13310 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13311 orterms term orlist re-p str-p level-p level-op time-p
13312 prop-p pn pv po gv rest)
13313 (if (string-match "/+" match)
13314 ;; match contains also a todo-matching request
13315 (progn
13316 (setq tagsmatch (substring match 0 (match-beginning 0))
13317 todomatch (substring match (match-end 0)))
13318 (if (string-match "^!" todomatch)
13319 (setq todo-only t todomatch (substring todomatch 1)))
13320 (if (string-match "^\\s-*$" todomatch)
13321 (setq todomatch nil)))
13322 ;; only matching tags
13323 (setq tagsmatch match todomatch nil))
13325 ;; Make the tags matcher
13326 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13327 (setq tagsmatcher t)
13328 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13329 (while (setq term (pop orterms))
13330 (while (and (equal (substring term -1) "\\") orterms)
13331 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13332 (while (string-match re term)
13333 (setq rest (substring term (match-end 0))
13334 minus (and (match-end 1)
13335 (equal (match-string 1 term) "-"))
13336 tag (save-match-data (replace-regexp-in-string
13337 "\\\\-" "-"
13338 (match-string 2 term)))
13339 re-p (equal (string-to-char tag) ?{)
13340 level-p (match-end 4)
13341 prop-p (match-end 5)
13342 mm (cond
13343 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13344 (level-p
13345 (setq level-op (org-op-to-function (match-string 3 term)))
13346 `(,level-op level ,(string-to-number
13347 (match-string 4 term))))
13348 (prop-p
13349 (setq pn (match-string 5 term)
13350 po (match-string 6 term)
13351 pv (match-string 7 term)
13352 re-p (equal (string-to-char pv) ?{)
13353 str-p (equal (string-to-char pv) ?\")
13354 time-p (save-match-data
13355 (string-match "^\"[[<].*[]>]\"$" pv))
13356 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13357 (if time-p (setq pv (org-matcher-time pv)))
13358 (setq po (org-op-to-function po (if time-p 'time str-p)))
13359 (cond
13360 ((equal pn "CATEGORY")
13361 (setq gv '(get-text-property (point) 'org-category)))
13362 ((equal pn "TODO")
13363 (setq gv 'todo))
13365 (setq gv `(org-cached-entry-get nil ,pn))))
13366 (if re-p
13367 (if (eq po 'org<>)
13368 `(not (string-match ,pv (or ,gv "")))
13369 `(string-match ,pv (or ,gv "")))
13370 (if str-p
13371 `(,po (or ,gv "") ,pv)
13372 `(,po (string-to-number (or ,gv ""))
13373 ,(string-to-number pv) ))))
13374 (t `(member ,tag tags-list)))
13375 mm (if minus (list 'not mm) mm)
13376 term rest)
13377 (push mm tagsmatcher))
13378 (push (if (> (length tagsmatcher) 1)
13379 (cons 'and tagsmatcher)
13380 (car tagsmatcher))
13381 orlist)
13382 (setq tagsmatcher nil))
13383 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13384 (setq tagsmatcher
13385 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13386 ;; Make the todo matcher
13387 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13388 (setq todomatcher t)
13389 (setq orterms (org-split-string todomatch "|") orlist nil)
13390 (while (setq term (pop orterms))
13391 (while (string-match re term)
13392 (setq minus (and (match-end 1)
13393 (equal (match-string 1 term) "-"))
13394 kwd (match-string 2 term)
13395 re-p (equal (string-to-char kwd) ?{)
13396 term (substring term (match-end 0))
13397 mm (if re-p
13398 `(string-match ,(substring kwd 1 -1) todo)
13399 (list 'equal 'todo kwd))
13400 mm (if minus (list 'not mm) mm))
13401 (push mm todomatcher))
13402 (push (if (> (length todomatcher) 1)
13403 (cons 'and todomatcher)
13404 (car todomatcher))
13405 orlist)
13406 (setq todomatcher nil))
13407 (setq todomatcher (if (> (length orlist) 1)
13408 (cons 'or orlist) (car orlist))))
13410 ;; Return the string and lisp forms of the matcher
13411 (setq matcher (if todomatcher
13412 (list 'and tagsmatcher todomatcher)
13413 tagsmatcher))
13414 (when todo-only
13415 (setq matcher (list 'and '(member todo org-not-done-keywords)
13416 matcher)))
13417 (cons match0 matcher)))
13419 (defun org-op-to-function (op &optional stringp)
13420 "Turn an operator into the appropriate function."
13421 (setq op
13422 (cond
13423 ((equal op "<" ) '(< string< org-time<))
13424 ((equal op ">" ) '(> org-string> org-time>))
13425 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13426 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13427 ((member op '("=" "==")) '(= string= org-time=))
13428 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13429 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13431 (defun org<> (a b) (not (= a b)))
13432 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13433 (defun org-string>= (a b) (not (string< a b)))
13434 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13435 (defun org-string<> (a b) (not (string= a b)))
13436 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13437 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13438 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13439 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13440 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13441 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13442 (defun org-2ft (s)
13443 "Convert S to a floating point time.
13444 If S is already a number, just return it. If it is a string, parse
13445 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13446 (cond
13447 ((numberp s) s)
13448 ((stringp s)
13449 (condition-case nil
13450 (float-time (apply 'encode-time (org-parse-time-string s)))
13451 (error 0.)))
13452 (t 0.)))
13454 (defun org-time-today ()
13455 "Time in seconds today at 0:00.
13456 Returns the float number of seconds since the beginning of the
13457 epoch to the beginning of today (00:00)."
13458 (float-time (apply 'encode-time
13459 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13461 (defun org-matcher-time (s)
13462 "Interpret a time comparison value."
13463 (save-match-data
13464 (cond
13465 ((string= s "<now>") (float-time))
13466 ((string= s "<today>") (org-time-today))
13467 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13468 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13469 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13470 (+ (org-time-today)
13471 (* (string-to-number (match-string 1 s))
13472 (cdr (assoc (match-string 2 s)
13473 '(("d" . 86400.0) ("w" . 604800.0)
13474 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13475 (t (org-2ft s)))))
13477 (defun org-match-any-p (re list)
13478 "Does re match any element of list?"
13479 (setq list (mapcar (lambda (x) (string-match re x)) list))
13480 (delq nil list))
13482 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13483 (defvar org-tags-overlay (make-overlay 1 1))
13484 (org-detach-overlay org-tags-overlay)
13486 (defun org-get-local-tags-at (&optional pos)
13487 "Get a list of tags defined in the current headline."
13488 (org-get-tags-at pos 'local))
13490 (defun org-get-local-tags ()
13491 "Get a list of tags defined in the current headline."
13492 (org-get-tags-at nil 'local))
13494 (defun org-get-tags-at (&optional pos local)
13495 "Get a list of all headline tags applicable at POS.
13496 POS defaults to point. If tags are inherited, the list contains
13497 the targets in the same sequence as the headlines appear, i.e.
13498 the tags of the current headline come last.
13499 When LOCAL is non-nil, only return tags from the current headline,
13500 ignore inherited ones."
13501 (interactive)
13502 (if (and org-trust-scanner-tags
13503 (or (not pos) (equal pos (point)))
13504 (not local))
13505 org-scanner-tags
13506 (let (tags ltags lastpos parent)
13507 (save-excursion
13508 (save-restriction
13509 (widen)
13510 (goto-char (or pos (point)))
13511 (save-match-data
13512 (catch 'done
13513 (condition-case nil
13514 (progn
13515 (org-back-to-heading t)
13516 (while (not (equal lastpos (point)))
13517 (setq lastpos (point))
13518 (when (looking-at
13519 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13520 (setq ltags (org-split-string
13521 (org-match-string-no-properties 1) ":"))
13522 (when parent
13523 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13524 (setq tags (append
13525 (if parent
13526 (org-remove-uninherited-tags ltags)
13527 ltags)
13528 tags)))
13529 (or org-use-tag-inheritance (throw 'done t))
13530 (if local (throw 'done t))
13531 (or (org-up-heading-safe) (error nil))
13532 (setq parent t)))
13533 (error nil)))))
13534 (if local
13535 tags
13536 (reverse (delete-dups
13537 (reverse (append
13538 (org-remove-uninherited-tags
13539 org-file-tags) tags)))))))))
13541 (defun org-add-prop-inherited (s)
13542 (add-text-properties 0 (length s) '(inherited t) s)
13545 (defun org-toggle-tag (tag &optional onoff)
13546 "Toggle the tag TAG for the current line.
13547 If ONOFF is `on' or `off', don't toggle but set to this state."
13548 (let (res current)
13549 (save-excursion
13550 (org-back-to-heading t)
13551 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13552 (point-at-eol) t)
13553 (progn
13554 (setq current (match-string 1))
13555 (replace-match ""))
13556 (setq current ""))
13557 (setq current (nreverse (org-split-string current ":")))
13558 (cond
13559 ((eq onoff 'on)
13560 (setq res t)
13561 (or (member tag current) (push tag current)))
13562 ((eq onoff 'off)
13563 (or (not (member tag current)) (setq current (delete tag current))))
13564 (t (if (member tag current)
13565 (setq current (delete tag current))
13566 (setq res t)
13567 (push tag current))))
13568 (end-of-line 1)
13569 (if current
13570 (progn
13571 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13572 (org-set-tags nil t))
13573 (delete-horizontal-space))
13574 (run-hooks 'org-after-tags-change-hook))
13575 res))
13577 (defun org-align-tags-here (to-col)
13578 ;; Assumes that this is a headline
13579 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13580 (beginning-of-line 1)
13581 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13582 (< pos (match-beginning 2)))
13583 (progn
13584 (setq tags-l (- (match-end 2) (match-beginning 2)))
13585 (goto-char (match-beginning 1))
13586 (insert " ")
13587 (delete-region (point) (1+ (match-beginning 2)))
13588 (setq ncol (max (current-column)
13589 (1+ col)
13590 (if (> to-col 0)
13591 to-col
13592 (- (abs to-col) tags-l))))
13593 (setq p (point))
13594 (insert (make-string (- ncol (current-column)) ?\ ))
13595 (setq ncol (current-column))
13596 (when indent-tabs-mode (tabify p (point-at-eol)))
13597 (org-move-to-column (min ncol col) t))
13598 (goto-char pos))))
13600 (defun org-set-tags-command (&optional arg just-align)
13601 "Call the set-tags command for the current entry."
13602 (interactive "P")
13603 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13604 (org-set-tags arg just-align)
13605 (save-excursion
13606 (unless (and (org-region-active-p)
13607 org-loop-over-headlines-in-active-region)
13608 (org-back-to-heading t))
13609 (org-set-tags arg just-align))))
13611 (defun org-set-tags-to (data)
13612 "Set the tags of the current entry to DATA, replacing the current tags.
13613 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13614 If DATA is nil or the empty string, any tags will be removed."
13615 (interactive "sTags: ")
13616 (setq data
13617 (cond
13618 ((eq data nil) "")
13619 ((equal data "") "")
13620 ((stringp data)
13621 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13622 ":"))
13623 ((listp data)
13624 (concat ":" (mapconcat 'identity data ":") ":"))))
13625 (when data
13626 (save-excursion
13627 (org-back-to-heading t)
13628 (when (looking-at org-complex-heading-regexp)
13629 (if (match-end 5)
13630 (progn
13631 (goto-char (match-beginning 5))
13632 (insert data)
13633 (delete-region (point) (point-at-eol))
13634 (org-set-tags nil 'align))
13635 (goto-char (point-at-eol))
13636 (insert " " data)
13637 (org-set-tags nil 'align)))
13638 (beginning-of-line 1)
13639 (if (looking-at ".*?\\([ \t]+\\)$")
13640 (delete-region (match-beginning 1) (match-end 1))))))
13642 (defun org-align-all-tags ()
13643 "Align the tags i all headings."
13644 (interactive)
13645 (save-excursion
13646 (or (ignore-errors (org-back-to-heading t))
13647 (outline-next-heading))
13648 (if (org-at-heading-p)
13649 (org-set-tags t)
13650 (message "No headings"))))
13652 (defvar org-indent-indentation-per-level)
13653 (defun org-set-tags (&optional arg just-align)
13654 "Set the tags for the current headline.
13655 With prefix ARG, realign all tags in headings in the current buffer."
13656 (interactive "P")
13657 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13658 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13659 'region-start-level 'region))
13660 org-loop-over-headlines-in-active-region)
13661 (org-map-entries
13662 ;; We don't use ARG and JUST-ALIGN here these args are not
13663 ;; useful when looping over headlines
13664 `(org-set-tags)
13665 org-loop-over-headlines-in-active-region
13666 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13667 (let* ((re org-outline-regexp-bol)
13668 (current (unless arg (org-get-tags-string)))
13669 (col (current-column))
13670 (org-setting-tags t)
13671 table current-tags inherited-tags ; computed below when needed
13672 tags p0 c0 c1 rpl di tc level)
13673 (if arg
13674 (save-excursion
13675 (goto-char (point-min))
13676 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13677 (while (re-search-forward re nil t)
13678 (org-set-tags nil t)
13679 (end-of-line 1)))
13680 (message "All tags realigned to column %d" org-tags-column))
13681 (if just-align
13682 (setq tags current)
13683 ;; Get a new set of tags from the user
13684 (save-excursion
13685 (setq table (append org-tag-persistent-alist
13686 (or org-tag-alist (org-get-buffer-tags))
13687 (and
13688 org-complete-tags-always-offer-all-agenda-tags
13689 (org-global-tags-completion-table
13690 (org-agenda-files))))
13691 org-last-tags-completion-table table
13692 current-tags (org-split-string current ":")
13693 inherited-tags (nreverse
13694 (nthcdr (length current-tags)
13695 (nreverse (org-get-tags-at))))
13696 tags
13697 (if (or (eq t org-use-fast-tag-selection)
13698 (and org-use-fast-tag-selection
13699 (delq nil (mapcar 'cdr table))))
13700 (org-fast-tag-selection
13701 current-tags inherited-tags table
13702 (if org-fast-tag-selection-include-todo
13703 org-todo-key-alist))
13704 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13705 (org-trim
13706 (org-icompleting-read "Tags: "
13707 'org-tags-completion-function
13708 nil nil current 'org-tags-history))))))
13709 (while (string-match "[-+&]+" tags)
13710 ;; No boolean logic, just a list
13711 (setq tags (replace-match ":" t t tags))))
13713 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13715 (if org-tags-sort-function
13716 (setq tags (mapconcat 'identity
13717 (sort (org-split-string
13718 tags (org-re "[^[:alnum:]_@#%]+"))
13719 org-tags-sort-function) ":")))
13721 (if (string-match "\\`[\t ]*\\'" tags)
13722 (setq tags "")
13723 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13724 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13726 ;; Insert new tags at the correct column
13727 (beginning-of-line 1)
13728 (setq level (or (and (looking-at org-outline-regexp)
13729 (- (match-end 0) (point) 1))
13731 (cond
13732 ((and (equal current "") (equal tags "")))
13733 ((re-search-forward
13734 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13735 (point-at-eol) t)
13736 (if (equal tags "")
13737 (setq rpl "")
13738 (goto-char (match-beginning 0))
13739 (setq c0 (current-column)
13740 ;; compute offset for the case of org-indent-mode active
13741 di (if org-indent-mode
13742 (* (1- org-indent-indentation-per-level) (1- level))
13744 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13745 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13746 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13747 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13748 (replace-match rpl t t)
13749 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13750 tags)
13751 (t (error "Tags alignment failed")))
13752 (org-move-to-column col)
13753 (unless just-align
13754 (run-hooks 'org-after-tags-change-hook))))))
13756 (defun org-change-tag-in-region (beg end tag off)
13757 "Add or remove TAG for each entry in the region.
13758 This works in the agenda, and also in an org-mode buffer."
13759 (interactive
13760 (list (region-beginning) (region-end)
13761 (let ((org-last-tags-completion-table
13762 (if (derived-mode-p 'org-mode)
13763 (org-get-buffer-tags)
13764 (org-global-tags-completion-table))))
13765 (org-icompleting-read
13766 "Tag: " 'org-tags-completion-function nil nil nil
13767 'org-tags-history))
13768 (progn
13769 (message "[s]et or [r]emove? ")
13770 (equal (read-char-exclusive) ?r))))
13771 (if (fboundp 'deactivate-mark) (deactivate-mark))
13772 (let ((agendap (equal major-mode 'org-agenda-mode))
13773 l1 l2 m buf pos newhead (cnt 0))
13774 (goto-char end)
13775 (setq l2 (1- (org-current-line)))
13776 (goto-char beg)
13777 (setq l1 (org-current-line))
13778 (loop for l from l1 to l2 do
13779 (org-goto-line l)
13780 (setq m (get-text-property (point) 'org-hd-marker))
13781 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13782 (and agendap m))
13783 (setq buf (if agendap (marker-buffer m) (current-buffer))
13784 pos (if agendap m (point)))
13785 (with-current-buffer buf
13786 (save-excursion
13787 (save-restriction
13788 (goto-char pos)
13789 (setq cnt (1+ cnt))
13790 (org-toggle-tag tag (if off 'off 'on))
13791 (setq newhead (org-get-heading)))))
13792 (and agendap (org-agenda-change-all-lines newhead m))))
13793 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13795 (defun org-tags-completion-function (string predicate &optional flag)
13796 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13797 (confirm (lambda (x) (stringp (car x)))))
13798 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13799 (setq s1 (match-string 1 string)
13800 s2 (match-string 2 string))
13801 (setq s1 "" s2 string))
13802 (cond
13803 ((eq flag nil)
13804 ;; try completion
13805 (setq rtn (try-completion s2 ctable confirm))
13806 (if (stringp rtn)
13807 (setq rtn
13808 (concat s1 s2 (substring rtn (length s2))
13809 (if (and org-add-colon-after-tag-completion
13810 (assoc rtn ctable))
13811 ":" ""))))
13812 rtn)
13813 ((eq flag t)
13814 ;; all-completions
13815 (all-completions s2 ctable confirm)
13817 ((eq flag 'lambda)
13818 ;; exact match?
13819 (assoc s2 ctable)))
13822 (defun org-fast-tag-insert (kwd tags face &optional end)
13823 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13824 (insert (format "%-12s" (concat kwd ":"))
13825 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13826 (or end "")))
13828 (defun org-fast-tag-show-exit (flag)
13829 (save-excursion
13830 (org-goto-line 3)
13831 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13832 (replace-match ""))
13833 (when flag
13834 (end-of-line 1)
13835 (org-move-to-column (- (window-width) 19) t)
13836 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13838 (defun org-set-current-tags-overlay (current prefix)
13839 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13840 (if (featurep 'xemacs)
13841 (org-overlay-display org-tags-overlay (concat prefix s)
13842 'secondary-selection)
13843 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13844 (org-overlay-display org-tags-overlay (concat prefix s)))))
13846 (defvar org-last-tag-selection-key nil)
13847 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13848 "Fast tag selection with single keys.
13849 CURRENT is the current list of tags in the headline, INHERITED is the
13850 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13851 possibly with grouping information. TODO-TABLE is a similar table with
13852 TODO keywords, should these have keys assigned to them.
13853 If the keys are nil, a-z are automatically assigned.
13854 Returns the new tags string, or nil to not change the current settings."
13855 (let* ((fulltable (append table todo-table))
13856 (maxlen (apply 'max (mapcar
13857 (lambda (x)
13858 (if (stringp (car x)) (string-width (car x)) 0))
13859 fulltable)))
13860 (buf (current-buffer))
13861 (expert (eq org-fast-tag-selection-single-key 'expert))
13862 (buffer-tags nil)
13863 (fwidth (+ maxlen 3 1 3))
13864 (ncol (/ (- (window-width) 4) fwidth))
13865 (i-face 'org-done)
13866 (c-face 'org-todo)
13867 tg cnt e c char c1 c2 ntable tbl rtn
13868 ov-start ov-end ov-prefix
13869 (exit-after-next org-fast-tag-selection-single-key)
13870 (done-keywords org-done-keywords)
13871 groups ingroup)
13872 (save-excursion
13873 (beginning-of-line 1)
13874 (if (looking-at
13875 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13876 (setq ov-start (match-beginning 1)
13877 ov-end (match-end 1)
13878 ov-prefix "")
13879 (setq ov-start (1- (point-at-eol))
13880 ov-end (1+ ov-start))
13881 (skip-chars-forward "^\n\r")
13882 (setq ov-prefix
13883 (concat
13884 (buffer-substring (1- (point)) (point))
13885 (if (> (current-column) org-tags-column)
13887 (make-string (- org-tags-column (current-column)) ?\ ))))))
13888 (move-overlay org-tags-overlay ov-start ov-end)
13889 (save-window-excursion
13890 (if expert
13891 (set-buffer (get-buffer-create " *Org tags*"))
13892 (delete-other-windows)
13893 (split-window-vertically)
13894 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13895 (erase-buffer)
13896 (org-set-local 'org-done-keywords done-keywords)
13897 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13898 (org-fast-tag-insert "Current" current c-face "\n\n")
13899 (org-fast-tag-show-exit exit-after-next)
13900 (org-set-current-tags-overlay current ov-prefix)
13901 (setq tbl fulltable char ?a cnt 0)
13902 (while (setq e (pop tbl))
13903 (cond
13904 ((equal (car e) :startgroup)
13905 (push '() groups) (setq ingroup t)
13906 (when (not (= cnt 0))
13907 (setq cnt 0)
13908 (insert "\n"))
13909 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13910 ((equal (car e) :endgroup)
13911 (setq ingroup nil cnt 0)
13912 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13913 ((equal e '(:newline))
13914 (when (not (= cnt 0))
13915 (setq cnt 0)
13916 (insert "\n")
13917 (setq e (car tbl))
13918 (while (equal (car tbl) '(:newline))
13919 (insert "\n")
13920 (setq tbl (cdr tbl)))))
13922 (setq tg (copy-sequence (car e)) c2 nil)
13923 (if (cdr e)
13924 (setq c (cdr e))
13925 ;; automatically assign a character.
13926 (setq c1 (string-to-char
13927 (downcase (substring
13928 tg (if (= (string-to-char tg) ?@) 1 0)))))
13929 (if (or (rassoc c1 ntable) (rassoc c1 table))
13930 (while (or (rassoc char ntable) (rassoc char table))
13931 (setq char (1+ char)))
13932 (setq c2 c1))
13933 (setq c (or c2 char)))
13934 (if ingroup (push tg (car groups)))
13935 (setq tg (org-add-props tg nil 'face
13936 (cond
13937 ((not (assoc tg table))
13938 (org-get-todo-face tg))
13939 ((member tg current) c-face)
13940 ((member tg inherited) i-face))))
13941 (if (and (= cnt 0) (not ingroup)) (insert " "))
13942 (insert "[" c "] " tg (make-string
13943 (- fwidth 4 (length tg)) ?\ ))
13944 (push (cons tg c) ntable)
13945 (when (= (setq cnt (1+ cnt)) ncol)
13946 (insert "\n")
13947 (if ingroup (insert " "))
13948 (setq cnt 0)))))
13949 (setq ntable (nreverse ntable))
13950 (insert "\n")
13951 (goto-char (point-min))
13952 (if (not expert) (org-fit-window-to-buffer))
13953 (setq rtn
13954 (catch 'exit
13955 (while t
13956 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13957 (if (not groups) "no " "")
13958 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13959 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13960 (setq org-last-tag-selection-key c)
13961 (cond
13962 ((= c ?\r) (throw 'exit t))
13963 ((= c ?!)
13964 (setq groups (not groups))
13965 (goto-char (point-min))
13966 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13967 ((= c ?\C-c)
13968 (if (not expert)
13969 (org-fast-tag-show-exit
13970 (setq exit-after-next (not exit-after-next)))
13971 (setq expert nil)
13972 (delete-other-windows)
13973 (set-window-buffer (split-window-vertically) " *Org tags*")
13974 (org-switch-to-buffer-other-window " *Org tags*")
13975 (org-fit-window-to-buffer)))
13976 ((or (= c ?\C-g)
13977 (and (= c ?q) (not (rassoc c ntable))))
13978 (org-detach-overlay org-tags-overlay)
13979 (setq quit-flag t))
13980 ((= c ?\ )
13981 (setq current nil)
13982 (if exit-after-next (setq exit-after-next 'now)))
13983 ((= c ?\t)
13984 (condition-case nil
13985 (setq tg (org-icompleting-read
13986 "Tag: "
13987 (or buffer-tags
13988 (with-current-buffer buf
13989 (org-get-buffer-tags)))))
13990 (quit (setq tg "")))
13991 (when (string-match "\\S-" tg)
13992 (add-to-list 'buffer-tags (list tg))
13993 (if (member tg current)
13994 (setq current (delete tg current))
13995 (push tg current)))
13996 (if exit-after-next (setq exit-after-next 'now)))
13997 ((setq e (rassoc c todo-table) tg (car e))
13998 (with-current-buffer buf
13999 (save-excursion (org-todo tg)))
14000 (if exit-after-next (setq exit-after-next 'now)))
14001 ((setq e (rassoc c ntable) tg (car e))
14002 (if (member tg current)
14003 (setq current (delete tg current))
14004 (loop for g in groups do
14005 (if (member tg g)
14006 (mapc (lambda (x)
14007 (setq current (delete x current)))
14008 g)))
14009 (push tg current))
14010 (if exit-after-next (setq exit-after-next 'now))))
14012 ;; Create a sorted list
14013 (setq current
14014 (sort current
14015 (lambda (a b)
14016 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14017 (if (eq exit-after-next 'now) (throw 'exit t))
14018 (goto-char (point-min))
14019 (beginning-of-line 2)
14020 (delete-region (point) (point-at-eol))
14021 (org-fast-tag-insert "Current" current c-face)
14022 (org-set-current-tags-overlay current ov-prefix)
14023 (while (re-search-forward
14024 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14025 (setq tg (match-string 1))
14026 (add-text-properties
14027 (match-beginning 1) (match-end 1)
14028 (list 'face
14029 (cond
14030 ((member tg current) c-face)
14031 ((member tg inherited) i-face)
14032 (t (get-text-property (match-beginning 1) 'face))))))
14033 (goto-char (point-min)))))
14034 (org-detach-overlay org-tags-overlay)
14035 (if rtn
14036 (mapconcat 'identity current ":")
14037 nil))))
14039 (defun org-get-tags-string ()
14040 "Get the TAGS string in the current headline."
14041 (unless (org-at-heading-p t)
14042 (error "Not on a heading"))
14043 (save-excursion
14044 (beginning-of-line 1)
14045 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14046 (org-match-string-no-properties 1)
14047 "")))
14049 (defun org-get-tags ()
14050 "Get the list of tags specified in the current headline."
14051 (org-split-string (org-get-tags-string) ":"))
14053 (defun org-get-buffer-tags ()
14054 "Get a table of all tags used in the buffer, for completion."
14055 (let (tags)
14056 (save-excursion
14057 (goto-char (point-min))
14058 (while (re-search-forward
14059 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14060 (when (equal (char-after (point-at-bol 0)) ?*)
14061 (mapc (lambda (x) (add-to-list 'tags x))
14062 (org-split-string (org-match-string-no-properties 1) ":")))))
14063 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14064 (mapcar 'list tags)))
14066 ;;;; The mapping API
14068 (defun org-map-entries (func &optional match scope &rest skip)
14069 "Call FUNC at each headline selected by MATCH in SCOPE.
14071 FUNC is a function or a lisp form. The function will be called without
14072 arguments, with the cursor positioned at the beginning of the headline.
14073 The return values of all calls to the function will be collected and
14074 returned as a list.
14076 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14077 does not need to preserve point. After evaluation, the cursor will be
14078 moved to the end of the line (presumably of the headline of the
14079 processed entry) and search continues from there. Under some
14080 circumstances, this may not produce the wanted results. For example,
14081 if you have removed (e.g. archived) the current (sub)tree it could
14082 mean that the next entry will be skipped entirely. In such cases, you
14083 can specify the position from where search should continue by making
14084 FUNC set the variable `org-map-continue-from' to the desired buffer
14085 position.
14087 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14088 Only headlines that are matched by this query will be considered during
14089 the iteration. When MATCH is nil or t, all headlines will be
14090 visited by the iteration.
14092 SCOPE determines the scope of this command. It can be any of:
14094 nil The current buffer, respecting the restriction if any
14095 tree The subtree started with the entry at point
14096 region The entries within the active region, if any
14097 region-start-level
14098 The entries within the active region, but only those at
14099 the same level than the first one.
14100 file The current buffer, without restriction
14101 file-with-archives
14102 The current buffer, and any archives associated with it
14103 agenda All agenda files
14104 agenda-with-archives
14105 All agenda files with any archive files associated with them
14106 \(file1 file2 ...)
14107 If this is a list, all files in the list will be scanned
14109 The remaining args are treated as settings for the skipping facilities of
14110 the scanner. The following items can be given here:
14112 archive skip trees with the archive tag.
14113 comment skip trees with the COMMENT keyword
14114 function or Emacs Lisp form:
14115 will be used as value for `org-agenda-skip-function', so whenever
14116 the function returns t, FUNC will not be called for that
14117 entry and search will continue from the point where the
14118 function leaves it.
14120 If your function needs to retrieve the tags including inherited tags
14121 at the *current* entry, you can use the value of the variable
14122 `org-scanner-tags' which will be much faster than getting the value
14123 with `org-get-tags-at'. If your function gets properties with
14124 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14125 to t around the call to `org-entry-properties' to get the same speedup.
14126 Note that if your function moves around to retrieve tags and properties at
14127 a *different* entry, you cannot use these techniques."
14128 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14129 (not (org-region-active-p)))
14130 (let* ((org-agenda-archives-mode nil) ; just to make sure
14131 (org-agenda-skip-archived-trees (memq 'archive skip))
14132 (org-agenda-skip-comment-trees (memq 'comment skip))
14133 (org-agenda-skip-function
14134 (car (org-delete-all '(comment archive) skip)))
14135 (org-tags-match-list-sublevels t)
14136 (start-level (eq scope 'region-start-level))
14137 matcher file res
14138 org-todo-keywords-for-agenda
14139 org-done-keywords-for-agenda
14140 org-todo-keyword-alist-for-agenda
14141 org-drawers-for-agenda
14142 org-tag-alist-for-agenda
14143 todo-only)
14145 (cond
14146 ((eq match t) (setq matcher t))
14147 ((eq match nil) (setq matcher t))
14148 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14150 (save-excursion
14151 (save-restriction
14152 (cond ((eq scope 'tree)
14153 (org-back-to-heading t)
14154 (org-narrow-to-subtree)
14155 (setq scope nil))
14156 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14157 (org-region-active-p))
14158 ;; If needed, set start-level to a string like "2"
14159 (when start-level
14160 (save-excursion
14161 (goto-char (region-beginning))
14162 (unless (org-at-heading-p) (outline-next-heading))
14163 (setq start-level (org-current-level))))
14164 (narrow-to-region (region-beginning)
14165 (save-excursion
14166 (goto-char (region-end))
14167 (unless (and (bolp) (org-at-heading-p))
14168 (outline-next-heading))
14169 (point)))
14170 (setq scope nil)))
14172 (if (not scope)
14173 (progn
14174 (org-agenda-prepare-buffers
14175 (list (buffer-file-name (current-buffer))))
14176 (setq res (org-scan-tags func matcher todo-only start-level)))
14177 ;; Get the right scope
14178 (cond
14179 ((and scope (listp scope) (symbolp (car scope)))
14180 (setq scope (eval scope)))
14181 ((eq scope 'agenda)
14182 (setq scope (org-agenda-files t)))
14183 ((eq scope 'agenda-with-archives)
14184 (setq scope (org-agenda-files t))
14185 (setq scope (org-add-archive-files scope)))
14186 ((eq scope 'file)
14187 (setq scope (list (buffer-file-name))))
14188 ((eq scope 'file-with-archives)
14189 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14190 (org-agenda-prepare-buffers scope)
14191 (while (setq file (pop scope))
14192 (with-current-buffer (org-find-base-buffer-visiting file)
14193 (save-excursion
14194 (save-restriction
14195 (widen)
14196 (goto-char (point-min))
14197 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14198 res)))
14200 ;;;; Properties
14202 ;;; Setting and retrieving properties
14204 (defconst org-special-properties
14205 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14206 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14207 "The special properties valid in Org-mode.
14209 These are properties that are not defined in the property drawer,
14210 but in some other way.")
14212 (defconst org-default-properties
14213 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14214 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14215 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14216 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14217 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14218 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14219 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14220 "Some properties that are used by Org-mode for various purposes.
14221 Being in this list makes sure that they are offered for completion.")
14223 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14224 "Regular expression matching the first line of a property drawer.")
14226 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14227 "Regular expression matching the last line of a property drawer.")
14229 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14230 "Regular expression matching the first line of a property drawer.")
14232 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14233 "Regular expression matching the first line of a property drawer.")
14235 (defconst org-property-drawer-re
14236 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14237 org-property-end-re "\\)\n?")
14238 "Matches an entire property drawer.")
14240 (defconst org-clock-drawer-re
14241 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14242 org-property-end-re "\\)\n?")
14243 "Matches an entire clock drawer.")
14245 (defsubst org-re-property (property)
14246 "Return a regexp matching a PROPERTY line.
14247 Match group 1 will be set to the value."
14248 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14250 (defsubst org-re-property-keyword (property)
14251 "Return a regexp matching a PROPERTY line, possibly with no
14252 value for the property."
14253 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14255 (defun org-property-action ()
14256 "Do an action on properties."
14257 (interactive)
14258 (let (c)
14259 (org-at-property-p)
14260 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14261 (setq c (read-char-exclusive))
14262 (cond
14263 ((equal c ?s)
14264 (call-interactively 'org-set-property))
14265 ((equal c ?d)
14266 (call-interactively 'org-delete-property))
14267 ((equal c ?D)
14268 (call-interactively 'org-delete-property-globally))
14269 ((equal c ?c)
14270 (call-interactively 'org-compute-property-at-point))
14271 (t (error "No such property action %c" c)))))
14273 (defun org-inc-effort ()
14274 "Increment the value of the effort property in the current entry."
14275 (interactive)
14276 (org-set-effort nil t))
14278 (defun org-set-effort (&optional value increment)
14279 "Set the effort property of the current entry.
14280 With numerical prefix arg, use the nth allowed value, 0 stands for the
14281 10th allowed value.
14283 When INCREMENT is non-nil, set the property to the next allowed value."
14284 (interactive "P")
14285 (if (equal value 0) (setq value 10))
14286 (let* ((completion-ignore-case t)
14287 (prop org-effort-property)
14288 (cur (org-entry-get nil prop))
14289 (allowed (org-property-get-allowed-values nil prop 'table))
14290 (existing (mapcar 'list (org-property-values prop)))
14292 (val (cond
14293 ((stringp value) value)
14294 ((and allowed (integerp value))
14295 (or (car (nth (1- value) allowed))
14296 (car (org-last allowed))))
14297 ((and allowed increment)
14298 (or (caadr (member (list cur) allowed))
14299 (error "Allowed effort values are not set")))
14300 (allowed
14301 (message "Select 1-9,0, [RET%s]: %s"
14302 (if cur (concat "=" cur) "")
14303 (mapconcat 'car allowed " "))
14304 (setq rpl (read-char-exclusive))
14305 (if (equal rpl ?\r)
14307 (setq rpl (- rpl ?0))
14308 (if (equal rpl 0) (setq rpl 10))
14309 (if (and (> rpl 0) (<= rpl (length allowed)))
14310 (car (nth (1- rpl) allowed))
14311 (org-completing-read "Effort: " allowed nil))))
14313 (let (org-completion-use-ido org-completion-use-iswitchb)
14314 (org-completing-read
14315 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14316 (concat "[" cur "]") "")
14317 ": ")
14318 existing nil nil "" nil cur))))))
14319 (unless (equal (org-entry-get nil prop) val)
14320 (org-entry-put nil prop val))
14321 (save-excursion
14322 (org-back-to-heading t)
14323 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14324 (message "%s is now %s" prop val)))
14326 (defun org-at-property-p ()
14327 "Is cursor inside a property drawer?"
14328 (save-excursion
14329 (beginning-of-line 1)
14330 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14331 (save-match-data ;; Used by calling procedures
14332 (let ((p (point))
14333 (range (unless (org-before-first-heading-p)
14334 (org-get-property-block))))
14335 (and range (<= (car range) p) (< p (cdr range))))))))
14337 (defun org-get-property-block (&optional beg end force)
14338 "Return the (beg . end) range of the body of the property drawer.
14339 BEG and END are the beginning and end of the current subtree, or of
14340 the part before the first headline. If they are not given, they will
14341 be found. If the drawer does not exist and FORCE is non-nil, create
14342 the drawer."
14343 (catch 'exit
14344 (save-excursion
14345 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14346 (progn (org-back-to-heading t) (point))))
14347 (end (or end (and (not (outline-next-heading)) (point-max))
14348 (point))))
14349 (goto-char beg)
14350 (if (re-search-forward org-property-start-re end t)
14351 (setq beg (1+ (match-end 0)))
14352 (if force
14353 (save-excursion
14354 (org-insert-property-drawer)
14355 (setq end (progn (outline-next-heading) (point))))
14356 (throw 'exit nil))
14357 (goto-char beg)
14358 (if (re-search-forward org-property-start-re end t)
14359 (setq beg (1+ (match-end 0)))))
14360 (if (re-search-forward org-property-end-re end t)
14361 (setq end (match-beginning 0))
14362 (or force (throw 'exit nil))
14363 (goto-char beg)
14364 (setq end beg)
14365 (org-indent-line)
14366 (insert ":END:\n"))
14367 (cons beg end)))))
14369 (defun org-entry-properties (&optional pom which specific)
14370 "Get all properties of the entry at point-or-marker POM.
14371 This includes the TODO keyword, the tags, time strings for deadline,
14372 scheduled, and clocking, and any additional properties defined in the
14373 entry. The return value is an alist, keys may occur multiple times
14374 if the property key was used several times.
14375 POM may also be nil, in which case the current entry is used.
14376 If WHICH is nil or `all', get all properties. If WHICH is
14377 `special' or `standard', only get that subclass. If WHICH
14378 is a string only get exactly this property. SPECIFIC can be a string, the
14379 specific property we are interested in. Specifying it can speed
14380 things up because then unnecessary parsing is avoided."
14381 (setq which (or which 'all))
14382 (org-with-point-at pom
14383 (let ((clockstr (substring org-clock-string 0 -1))
14384 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14385 (case-fold-search nil)
14386 beg end range props sum-props key key1 value string clocksum clocksumt)
14387 (save-excursion
14388 (when (condition-case nil
14389 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14390 (error nil))
14391 (setq beg (point))
14392 (setq sum-props (get-text-property (point) 'org-summaries))
14393 (setq clocksum (get-text-property (point) :org-clock-minutes)
14394 clocksumt (get-text-property (point) :org-clock-minutes-today))
14395 (outline-next-heading)
14396 (setq end (point))
14397 (when (memq which '(all special))
14398 ;; Get the special properties, like TODO and tags
14399 (goto-char beg)
14400 (when (and (or (not specific) (string= specific "TODO"))
14401 (looking-at org-todo-line-regexp) (match-end 2))
14402 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14403 (when (and (or (not specific) (string= specific "PRIORITY"))
14404 (looking-at org-priority-regexp))
14405 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14406 (when (or (not specific) (string= specific "FILE"))
14407 (push (cons "FILE" buffer-file-name) props))
14408 (when (and (or (not specific) (string= specific "TAGS"))
14409 (setq value (org-get-tags-string))
14410 (string-match "\\S-" value))
14411 (push (cons "TAGS" value) props))
14412 (when (and (or (not specific) (string= specific "ALLTAGS"))
14413 (setq value (org-get-tags-at)))
14414 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14415 ":"))
14416 props))
14417 (when (or (not specific) (string= specific "BLOCKED"))
14418 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14419 (when (or (not specific)
14420 (member specific
14421 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14422 "TIMESTAMP" "TIMESTAMP_IA")))
14423 (catch 'match
14424 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14425 (setq key (if (match-end 1)
14426 (substring (org-match-string-no-properties 1)
14427 0 -1))
14428 string (if (equal key clockstr)
14429 (org-trim
14430 (buffer-substring-no-properties
14431 (match-beginning 3) (goto-char
14432 (point-at-eol))))
14433 (substring (org-match-string-no-properties 3)
14434 1 -1)))
14435 ;; Get the correct property name from the key. This is
14436 ;; necessary if the user has configured time keywords.
14437 (setq key1 (concat key ":"))
14438 (cond
14439 ((not key)
14440 (setq key
14441 (if (= (char-after (match-beginning 3)) ?\[)
14442 "TIMESTAMP_IA" "TIMESTAMP")))
14443 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14444 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14445 ((equal key1 org-closed-string) (setq key "CLOSED"))
14446 ((equal key1 org-clock-string) (setq key "CLOCK")))
14447 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14448 (progn
14449 (push (cons key string) props)
14450 ;; no need to search further if match is found
14451 (throw 'match t))
14452 (when (or (equal key "CLOCK") (not (assoc key props)))
14453 (push (cons key string) props)))))))
14455 (when (memq which '(all standard))
14456 ;; Get the standard properties, like :PROP: ...
14457 (setq range (org-get-property-block beg end))
14458 (when range
14459 (goto-char (car range))
14460 (while (re-search-forward
14461 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14462 (cdr range) t)
14463 (setq key (org-match-string-no-properties 1)
14464 value (org-trim (or (org-match-string-no-properties 2) "")))
14465 (unless (member key excluded)
14466 (push (cons key (or value "")) props)))))
14467 (if clocksum
14468 (push (cons "CLOCKSUM"
14469 (org-columns-number-to-string (/ (float clocksum) 60.)
14470 'add_times))
14471 props))
14472 (if clocksumt
14473 (push (cons "CLOCKSUM_T"
14474 (org-columns-number-to-string (/ (float clocksumt) 60.)
14475 'add_times))
14476 props))
14477 (unless (assoc "CATEGORY" props)
14478 (push (cons "CATEGORY" (org-get-category)) props))
14479 (append sum-props (nreverse props)))))))
14481 (defun org-entry-get (pom property &optional inherit literal-nil)
14482 "Get value of PROPERTY for entry or content at point-or-marker POM.
14483 If INHERIT is non-nil and the entry does not have the property,
14484 then also check higher levels of the hierarchy.
14485 If INHERIT is the symbol `selective', use inheritance only if the setting
14486 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14487 If the property is present but empty, the return value is the empty string.
14488 If the property is not present at all, nil is returned.
14490 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14491 do not interpret it as the list atom nil. This is used for inheritance
14492 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14493 (org-with-point-at pom
14494 (if (and inherit (if (eq inherit 'selective)
14495 (org-property-inherit-p property)
14497 (org-entry-get-with-inheritance property literal-nil)
14498 (if (member property org-special-properties)
14499 ;; We need a special property. Use `org-entry-properties' to
14500 ;; retrieve it, but specify the wanted property
14501 (cdr (assoc property (org-entry-properties nil 'special property)))
14502 (let ((range (org-get-property-block)))
14503 (when (and range (not (eq (car range) (cdr range))))
14504 (let* ((props (list (or (assoc property org-file-properties)
14505 (assoc property org-global-properties)
14506 (assoc property org-global-properties-fixed))))
14507 (ap (lambda (key)
14508 (when (re-search-forward
14509 (org-re-property key) (cdr range) t)
14510 (setq props
14511 (org-update-property-plist
14513 (if (match-end 1)
14514 (org-match-string-no-properties 1) "")
14515 props)))))
14516 val)
14517 (goto-char (car range))
14518 (funcall ap property)
14519 (goto-char (car range))
14520 (while (funcall ap (concat property "+")))
14521 (setq val (cdr (assoc property props)))
14522 (when val (if literal-nil val (org-not-nil val))))))))))
14524 (defun org-property-or-variable-value (var &optional inherit)
14525 "Check if there is a property fixing the value of VAR.
14526 If yes, return this value. If not, return the current value of the variable."
14527 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14528 (if (and prop (stringp prop) (string-match "\\S-" prop))
14529 (read prop)
14530 (symbol-value var))))
14532 (defun org-entry-delete (pom property)
14533 "Delete the property PROPERTY from entry at point-or-marker POM."
14534 (org-with-point-at pom
14535 (if (member property org-special-properties)
14536 nil ; cannot delete these properties.
14537 (let ((range (org-get-property-block)))
14538 (if (and range
14539 (goto-char (car range))
14540 (re-search-forward
14541 (org-re-property property)
14542 (cdr range) t))
14543 (progn
14544 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14546 nil)))))
14548 ;; Multi-values properties are properties that contain multiple values
14549 ;; These values are assumed to be single words, separated by whitespace.
14550 (defun org-entry-add-to-multivalued-property (pom property value)
14551 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14552 (let* ((old (org-entry-get pom property))
14553 (values (and old (org-split-string old "[ \t]"))))
14554 (setq value (org-entry-protect-space value))
14555 (unless (member value values)
14556 (setq values (cons value values))
14557 (org-entry-put pom property
14558 (mapconcat 'identity values " ")))))
14560 (defun org-entry-remove-from-multivalued-property (pom property value)
14561 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14562 (let* ((old (org-entry-get pom property))
14563 (values (and old (org-split-string old "[ \t]"))))
14564 (setq value (org-entry-protect-space value))
14565 (when (member value values)
14566 (setq values (delete value values))
14567 (org-entry-put pom property
14568 (mapconcat 'identity values " ")))))
14570 (defun org-entry-member-in-multivalued-property (pom property value)
14571 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14572 (let* ((old (org-entry-get pom property))
14573 (values (and old (org-split-string old "[ \t]"))))
14574 (setq value (org-entry-protect-space value))
14575 (member value values)))
14577 (defun org-entry-get-multivalued-property (pom property)
14578 "Return a list of values in a multivalued property."
14579 (let* ((value (org-entry-get pom property))
14580 (values (and value (org-split-string value "[ \t]"))))
14581 (mapcar 'org-entry-restore-space values)))
14583 (defun org-entry-put-multivalued-property (pom property &rest values)
14584 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14585 VALUES should be a list of strings. Spaces will be protected."
14586 (org-entry-put pom property
14587 (mapconcat 'org-entry-protect-space values " "))
14588 (let* ((value (org-entry-get pom property))
14589 (values (and value (org-split-string value "[ \t]"))))
14590 (mapcar 'org-entry-restore-space values)))
14592 (defun org-entry-protect-space (s)
14593 "Protect spaces and newline in string S."
14594 (while (string-match " " s)
14595 (setq s (replace-match "%20" t t s)))
14596 (while (string-match "\n" s)
14597 (setq s (replace-match "%0A" t t s)))
14600 (defun org-entry-restore-space (s)
14601 "Restore spaces and newline in string S."
14602 (while (string-match "%20" s)
14603 (setq s (replace-match " " t t s)))
14604 (while (string-match "%0A" s)
14605 (setq s (replace-match "\n" t t s)))
14608 (defvar org-entry-property-inherited-from (make-marker)
14609 "Marker pointing to the entry from where a property was inherited.
14610 Each call to `org-entry-get-with-inheritance' will set this marker to the
14611 location of the entry where the inheritance search matched. If there was
14612 no match, the marker will point nowhere.
14613 Note that also `org-entry-get' calls this function, if the INHERIT flag
14614 is set.")
14616 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14617 "Get PROPERTY of entry or content at point, search higher levels if needed.
14618 The search will stop at the first ancestor which has the property defined.
14619 If the value found is \"nil\", return nil to show that the property
14620 should be considered as undefined (this is the meaning of nil here).
14621 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14622 (move-marker org-entry-property-inherited-from nil)
14623 (let (tmp)
14624 (save-excursion
14625 (save-restriction
14626 (widen)
14627 (catch 'ex
14628 (while t
14629 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14630 (or (ignore-errors (org-back-to-heading t))
14631 (goto-char (point-min)))
14632 (move-marker org-entry-property-inherited-from (point))
14633 (throw 'ex tmp))
14634 (or (ignore-errors (org-up-heading-safe))
14635 (throw 'ex nil))))))
14636 (setq tmp (or tmp
14637 (cdr (assoc property org-file-properties))
14638 (cdr (assoc property org-global-properties))
14639 (cdr (assoc property org-global-properties-fixed))))
14640 (if literal-nil tmp (org-not-nil tmp))))
14642 (defvar org-property-changed-functions nil
14643 "Hook called when the value of a property has changed.
14644 Each hook function should accept two arguments, the name of the property
14645 and the new value.")
14647 (defun org-entry-put (pom property value)
14648 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14649 (org-with-point-at pom
14650 (org-back-to-heading t)
14651 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14652 range)
14653 (cond
14654 ((equal property "TODO")
14655 (when (and (stringp value) (string-match "\\S-" value)
14656 (not (member value org-todo-keywords-1)))
14657 (error "\"%s\" is not a valid TODO state" value))
14658 (if (or (not value)
14659 (not (string-match "\\S-" value)))
14660 (setq value 'none))
14661 (org-todo value)
14662 (org-set-tags nil 'align))
14663 ((equal property "PRIORITY")
14664 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14665 (string-to-char value) ?\ ))
14666 (org-set-tags nil 'align))
14667 ((equal property "SCHEDULED")
14668 (if (re-search-forward org-scheduled-time-regexp end t)
14669 (cond
14670 ((eq value 'earlier) (org-timestamp-change -1 'day))
14671 ((eq value 'later) (org-timestamp-change 1 'day))
14672 (t (call-interactively 'org-schedule)))
14673 (call-interactively 'org-schedule)))
14674 ((equal property "DEADLINE")
14675 (if (re-search-forward org-deadline-time-regexp end t)
14676 (cond
14677 ((eq value 'earlier) (org-timestamp-change -1 'day))
14678 ((eq value 'later) (org-timestamp-change 1 'day))
14679 (t (call-interactively 'org-deadline)))
14680 (call-interactively 'org-deadline)))
14681 ((member property org-special-properties)
14682 (error "The %s property can not yet be set with `org-entry-put'"
14683 property))
14684 (t ; a non-special property
14685 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14686 (setq range (org-get-property-block beg end 'force))
14687 (goto-char (car range))
14688 (if (re-search-forward
14689 (org-re-property-keyword property) (cdr range) t)
14690 (progn
14691 (delete-region (match-beginning 0) (match-end 0))
14692 (goto-char (match-beginning 0)))
14693 (goto-char (cdr range))
14694 (insert "\n")
14695 (backward-char 1)
14696 (org-indent-line))
14697 (insert ":" property ":")
14698 (and value (insert " " value))
14699 (org-indent-line)))))
14700 (run-hook-with-args 'org-property-changed-functions property value)))
14702 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14703 "Get all property keys in the current buffer.
14704 With INCLUDE-SPECIALS, also list the special properties that reflect things
14705 like tags and TODO state.
14706 With INCLUDE-DEFAULTS, also include properties that has special meaning
14707 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14708 and others.
14709 With INCLUDE-COLUMNS, also include property names given in COLUMN
14710 formats in the current buffer."
14711 (let (rtn range cfmt s p)
14712 (save-excursion
14713 (save-restriction
14714 (widen)
14715 (goto-char (point-min))
14716 (while (re-search-forward org-property-start-re nil t)
14717 (setq range (org-get-property-block))
14718 (goto-char (car range))
14719 (while (re-search-forward
14720 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14721 (cdr range) t)
14722 (add-to-list 'rtn (org-match-string-no-properties 1)))
14723 (outline-next-heading))))
14725 (when include-specials
14726 (setq rtn (append org-special-properties rtn)))
14728 (when include-defaults
14729 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14730 (add-to-list 'rtn org-effort-property))
14732 (when include-columns
14733 (save-excursion
14734 (save-restriction
14735 (widen)
14736 (goto-char (point-min))
14737 (while (re-search-forward
14738 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14739 nil t)
14740 (setq cfmt (match-string 2) s 0)
14741 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14742 cfmt s)
14743 (setq s (match-end 0)
14744 p (match-string 1 cfmt))
14745 (unless (or (equal p "ITEM")
14746 (member p org-special-properties))
14747 (add-to-list 'rtn (match-string 1 cfmt))))))))
14749 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14751 (defun org-property-values (key)
14752 "Return a list of all values of property KEY in the current buffer."
14753 (save-excursion
14754 (save-restriction
14755 (widen)
14756 (goto-char (point-min))
14757 (let ((re (org-re-property key))
14758 values)
14759 (while (re-search-forward re nil t)
14760 (add-to-list 'values (org-trim (match-string 1))))
14761 (delete "" values)))))
14763 (defun org-insert-property-drawer ()
14764 "Insert a property drawer into the current entry."
14765 (org-back-to-heading t)
14766 (looking-at org-outline-regexp)
14767 (let ((indent (if org-adapt-indentation
14768 (- (match-end 0) (match-beginning 0))
14770 (beg (point))
14771 (re (concat "^[ \t]*" org-keyword-time-regexp))
14772 end hiddenp)
14773 (outline-next-heading)
14774 (setq end (point))
14775 (goto-char beg)
14776 (while (re-search-forward re end t))
14777 (setq hiddenp (outline-invisible-p))
14778 (end-of-line 1)
14779 (and (equal (char-after) ?\n) (forward-char 1))
14780 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14781 (if (member (match-string 1) '("CLOCK:" ":END:"))
14782 ;; just skip this line
14783 (beginning-of-line 2)
14784 ;; Drawer start, find the end
14785 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14786 (beginning-of-line 1)))
14787 (org-skip-over-state-notes)
14788 (skip-chars-backward " \t\n\r")
14789 (if (eq (char-before) ?*) (forward-char 1))
14790 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14791 (beginning-of-line 0)
14792 (org-indent-to-column indent)
14793 (beginning-of-line 2)
14794 (org-indent-to-column indent)
14795 (beginning-of-line 0)
14796 (if hiddenp
14797 (save-excursion
14798 (org-back-to-heading t)
14799 (hide-entry))
14800 (org-flag-drawer t))))
14802 (defun org-insert-drawer (&optional arg drawer)
14803 "Insert a drawer at point.
14805 Optional argument DRAWER, when non-nil, is a string representing
14806 drawer's name. Otherwise, the user is prompted for a name.
14808 If a region is active, insert the drawer around that region
14809 instead.
14811 Point is left between drawer's boundaries."
14812 (interactive "P")
14813 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14814 "LOGBOOK"))
14815 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14816 ;; internally by Org. They are meant to be inserted
14817 ;; automatically.
14818 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14819 ;; Remove system drawers from list. Note: For some reason,
14820 ;; `org-completing-read' ignores the predicate while
14821 ;; `completing-read' handles it fine.
14822 (drawer (if arg "PROPERTIES"
14823 (or drawer
14824 (completing-read
14825 "Drawer: " org-drawers
14826 (lambda (d) (not (member d system-drawers))))))))
14827 (cond
14828 ;; With C-u, fall back on `org-insert-property-drawer'
14829 (arg (org-insert-property-drawer))
14830 ;; With an active region, insert a drawer at point.
14831 ((not (org-region-active-p))
14832 (progn
14833 (unless (bolp) (insert "\n"))
14834 (insert (format ":%s:\n\n:END:\n" drawer))
14835 (forward-line -2)))
14836 ;; Otherwise, insert the drawer at point
14838 (let ((rbeg (region-beginning))
14839 (rend (copy-marker (region-end))))
14840 (unwind-protect
14841 (progn
14842 (goto-char rbeg)
14843 (beginning-of-line)
14844 (when (save-excursion
14845 (re-search-forward org-outline-regexp-bol rend t))
14846 (error "Drawers cannot contain headlines"))
14847 ;; Position point at the beginning of the first
14848 ;; non-blank line in region. Insert drawer's opening
14849 ;; there, then indent it.
14850 (org-skip-whitespace)
14851 (beginning-of-line)
14852 (insert ":" drawer ":\n")
14853 (forward-line -1)
14854 (indent-for-tab-command)
14855 ;; Move point to the beginning of the first blank line
14856 ;; after the last non-blank line in region. Insert
14857 ;; drawer's closing, then indent it.
14858 (goto-char rend)
14859 (skip-chars-backward " \r\t\n")
14860 (insert "\n:END:")
14861 (deactivate-mark t)
14862 (indent-for-tab-command)
14863 (unless (eolp) (insert "\n")))
14864 ;; Clear marker, whatever the outcome of insertion is.
14865 (set-marker rend nil)))))))
14867 (defvar org-property-set-functions-alist nil
14868 "Property set function alist.
14869 Each entry should have the following format:
14871 (PROPERTY . READ-FUNCTION)
14873 The read function will be called with the same argument as
14874 `org-completing-read'.")
14876 (defun org-set-property-function (property)
14877 "Get the function that should be used to set PROPERTY.
14878 This is computed according to `org-property-set-functions-alist'."
14879 (or (cdr (assoc property org-property-set-functions-alist))
14880 'org-completing-read))
14882 (defun org-read-property-value (property)
14883 "Read PROPERTY value from user."
14884 (let* ((completion-ignore-case t)
14885 (allowed (org-property-get-allowed-values nil property 'table))
14886 (cur (org-entry-get nil property))
14887 (prompt (concat property " value"
14888 (if (and cur (string-match "\\S-" cur))
14889 (concat " [" cur "]") "") ": "))
14890 (set-function (org-set-property-function property))
14891 (val (if allowed
14892 (funcall set-function prompt allowed nil
14893 (not (get-text-property 0 'org-unrestricted
14894 (caar allowed))))
14895 (let (org-completion-use-ido org-completion-use-iswitchb)
14896 (funcall set-function prompt
14897 (mapcar 'list (org-property-values property))
14898 nil nil "" nil cur)))))
14899 (if (equal val "")
14901 val)))
14903 (defvar org-last-set-property nil)
14904 (defun org-read-property-name ()
14905 "Read a property name."
14906 (let* ((completion-ignore-case t)
14907 (keys (org-buffer-property-keys nil t t))
14908 (default-prop (or (save-excursion
14909 (save-match-data
14910 (beginning-of-line)
14911 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14912 (null (string= (match-string 1) "END"))
14913 (match-string 1))))
14914 org-last-set-property))
14915 (property (org-icompleting-read
14916 (concat "Property"
14917 (if default-prop (concat " [" default-prop "]") "")
14918 ": ")
14919 (mapcar 'list keys)
14920 nil nil nil nil
14921 default-prop
14923 (if (member property keys)
14924 property
14925 (or (cdr (assoc (downcase property)
14926 (mapcar (lambda (x) (cons (downcase x) x))
14927 keys)))
14928 property))))
14930 (defun org-set-property (property value)
14931 "In the current entry, set PROPERTY to VALUE.
14932 When called interactively, this will prompt for a property name, offering
14933 completion on existing and default properties. And then it will prompt
14934 for a value, offering completion either on allowed values (via an inherited
14935 xxx_ALL property) or on existing values in other instances of this property
14936 in the current file."
14937 (interactive (list nil nil))
14938 (let* ((property (or property (org-read-property-name)))
14939 (value (or value (org-read-property-value property)))
14940 (fn (cdr (assoc property org-properties-postprocess-alist))))
14941 (setq org-last-set-property property)
14942 ;; Possibly postprocess the inserted value:
14943 (when fn (setq value (funcall fn value)))
14944 (unless (equal (org-entry-get nil property) value)
14945 (org-entry-put nil property value))))
14947 (defun org-delete-property (property)
14948 "In the current entry, delete PROPERTY."
14949 (interactive
14950 (let* ((completion-ignore-case t)
14951 (prop (org-icompleting-read "Property: "
14952 (org-entry-properties nil 'standard))))
14953 (list prop)))
14954 (message "Property %s %s" property
14955 (if (org-entry-delete nil property)
14956 "deleted"
14957 "was not present in the entry")))
14959 (defun org-delete-property-globally (property)
14960 "Remove PROPERTY globally, from all entries."
14961 (interactive
14962 (let* ((completion-ignore-case t)
14963 (prop (org-icompleting-read
14964 "Globally remove property: "
14965 (mapcar 'list (org-buffer-property-keys)))))
14966 (list prop)))
14967 (save-excursion
14968 (save-restriction
14969 (widen)
14970 (goto-char (point-min))
14971 (let ((cnt 0))
14972 (while (re-search-forward
14973 (org-re-property property)
14974 nil t)
14975 (setq cnt (1+ cnt))
14976 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14977 (message "Property \"%s\" removed from %d entries" property cnt)))))
14979 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14981 (defun org-compute-property-at-point ()
14982 "Compute the property at point.
14983 This looks for an enclosing column format, extracts the operator and
14984 then applies it to the property in the column format's scope."
14985 (interactive)
14986 (unless (org-at-property-p)
14987 (error "Not at a property"))
14988 (let ((prop (org-match-string-no-properties 2)))
14989 (org-columns-get-format-and-top-level)
14990 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14991 (error "No operator defined for property %s" prop))
14992 (org-columns-compute prop)))
14994 (defvar org-property-allowed-value-functions nil
14995 "Hook for functions supplying allowed values for a specific property.
14996 The functions must take a single argument, the name of the property, and
14997 return a flat list of allowed values. If \":ETC\" is one of
14998 the values, this means that these values are intended as defaults for
14999 completion, but that other values should be allowed too.
15000 The functions must return nil if they are not responsible for this
15001 property.")
15003 (defun org-property-get-allowed-values (pom property &optional table)
15004 "Get allowed values for the property PROPERTY.
15005 When TABLE is non-nil, return an alist that can directly be used for
15006 completion."
15007 (let (vals)
15008 (cond
15009 ((equal property "TODO")
15010 (setq vals (org-with-point-at pom
15011 (append org-todo-keywords-1 '("")))))
15012 ((equal property "PRIORITY")
15013 (let ((n org-lowest-priority))
15014 (while (>= n org-highest-priority)
15015 (push (char-to-string n) vals)
15016 (setq n (1- n)))))
15017 ((member property org-special-properties))
15018 ((setq vals (run-hook-with-args-until-success
15019 'org-property-allowed-value-functions property)))
15021 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15022 (when (and vals (string-match "\\S-" vals))
15023 (setq vals (car (read-from-string (concat "(" vals ")"))))
15024 (setq vals (mapcar (lambda (x)
15025 (cond ((stringp x) x)
15026 ((numberp x) (number-to-string x))
15027 ((symbolp x) (symbol-name x))
15028 (t "???")))
15029 vals)))))
15030 (when (member ":ETC" vals)
15031 (setq vals (remove ":ETC" vals))
15032 (org-add-props (car vals) '(org-unrestricted t)))
15033 (if table (mapcar 'list vals) vals)))
15035 (defun org-property-previous-allowed-value (&optional previous)
15036 "Switch to the next allowed value for this property."
15037 (interactive)
15038 (org-property-next-allowed-value t))
15040 (defun org-property-next-allowed-value (&optional previous)
15041 "Switch to the next allowed value for this property."
15042 (interactive)
15043 (unless (org-at-property-p)
15044 (error "Not at a property"))
15045 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15046 (key (match-string 2))
15047 (value (match-string 3))
15048 (allowed (or (org-property-get-allowed-values (point) key)
15049 (and (member value '("[ ]" "[-]" "[X]"))
15050 '("[ ]" "[X]"))))
15051 nval)
15052 (unless allowed
15053 (error "Allowed values for this property have not been defined"))
15054 (if previous (setq allowed (reverse allowed)))
15055 (if (member value allowed)
15056 (setq nval (car (cdr (member value allowed)))))
15057 (setq nval (or nval (car allowed)))
15058 (if (equal nval value)
15059 (error "Only one allowed value for this property"))
15060 (org-at-property-p)
15061 (replace-match (concat " :" key ": " nval) t t)
15062 (org-indent-line)
15063 (beginning-of-line 1)
15064 (skip-chars-forward " \t")
15065 (when (equal prop org-effort-property)
15066 (save-excursion
15067 (org-back-to-heading t)
15068 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval)))
15069 (run-hook-with-args 'org-property-changed-functions key nval)))
15071 (defun org-find-olp (path &optional this-buffer)
15072 "Return a marker pointing to the entry at outline path OLP.
15073 If anything goes wrong, throw an error.
15074 You can wrap this call to catch the error like this:
15076 (condition-case msg
15077 (org-mobile-locate-entry (match-string 4))
15078 (error (nth 1 msg)))
15080 The return value will then be either a string with the error message,
15081 or a marker if everything is OK.
15083 If THIS-BUFFER is set, the outline path does not contain a file,
15084 only headings."
15085 (let* ((file (if this-buffer buffer-file-name (pop path)))
15086 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15087 (level 1)
15088 (lmin 1)
15089 (lmax 1)
15090 limit re end found pos heading cnt flevel)
15091 (unless buffer (error "File not found :%s" file))
15092 (with-current-buffer buffer
15093 (save-excursion
15094 (save-restriction
15095 (widen)
15096 (setq limit (point-max))
15097 (goto-char (point-min))
15098 (while (setq heading (pop path))
15099 (setq re (format org-complex-heading-regexp-format
15100 (regexp-quote heading)))
15101 (setq cnt 0 pos (point))
15102 (while (re-search-forward re end t)
15103 (setq level (- (match-end 1) (match-beginning 1)))
15104 (if (and (>= level lmin) (<= level lmax))
15105 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15106 (when (= cnt 0) (error "Heading not found on level %d: %s"
15107 lmax heading))
15108 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15109 lmax heading))
15110 (goto-char found)
15111 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15112 (setq end (save-excursion (org-end-of-subtree t t))))
15113 (when (org-at-heading-p)
15114 (point-marker)))))))
15116 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15117 "Find node HEADING in BUFFER.
15118 Return a marker to the heading if it was found, or nil if not.
15119 If POS-ONLY is set, return just the position instead of a marker.
15121 The heading text must match exact, but it may have a TODO keyword,
15122 a priority cookie and tags in the standard locations."
15123 (with-current-buffer (or buffer (current-buffer))
15124 (save-excursion
15125 (save-restriction
15126 (widen)
15127 (goto-char (point-min))
15128 (let (case-fold-search)
15129 (if (re-search-forward
15130 (format org-complex-heading-regexp-format
15131 (regexp-quote heading)) nil t)
15132 (if pos-only
15133 (match-beginning 0)
15134 (move-marker (make-marker) (match-beginning 0)))))))))
15136 (defun org-find-exact-heading-in-directory (heading &optional dir)
15137 "Find Org node headline HEADING in all .org files in directory DIR.
15138 When the target headline is found, return a marker to this location."
15139 (let ((files (directory-files (or dir default-directory)
15140 nil "\\`[^.#].*\\.org\\'"))
15141 file visiting m buffer)
15142 (catch 'found
15143 (while (setq file (pop files))
15144 (message "trying %s" file)
15145 (setq visiting (org-find-base-buffer-visiting file))
15146 (setq buffer (or visiting (find-file-noselect file)))
15147 (setq m (org-find-exact-headline-in-buffer
15148 heading buffer))
15149 (when (and (not m) (not visiting)) (kill-buffer buffer))
15150 (and m (throw 'found m))))))
15152 (defun org-find-entry-with-id (ident)
15153 "Locate the entry that contains the ID property with exact value IDENT.
15154 IDENT can be a string, a symbol or a number, this function will search for
15155 the string representation of it.
15156 Return the position where this entry starts, or nil if there is no such entry."
15157 (interactive "sID: ")
15158 (let ((id (cond
15159 ((stringp ident) ident)
15160 ((symbol-name ident) (symbol-name ident))
15161 ((numberp ident) (number-to-string ident))
15162 (t (error "IDENT %s must be a string, symbol or number" ident))))
15163 (case-fold-search nil))
15164 (save-excursion
15165 (save-restriction
15166 (widen)
15167 (goto-char (point-min))
15168 (when (re-search-forward
15169 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15170 nil t)
15171 (org-back-to-heading t)
15172 (point))))))
15174 ;;;; Timestamps
15176 (defvar org-last-changed-timestamp nil)
15177 (defvar org-last-inserted-timestamp nil
15178 "The last time stamp inserted with `org-insert-time-stamp'.")
15179 (defvar org-time-was-given) ; dynamically scoped parameter
15180 (defvar org-end-time-was-given) ; dynamically scoped parameter
15181 (defvar org-ts-what) ; dynamically scoped parameter
15183 (defun org-time-stamp (arg &optional inactive)
15184 "Prompt for a date/time and insert a time stamp.
15185 If the user specifies a time like HH:MM or if this command is
15186 called with at least one prefix argument, the time stamp contains
15187 the date and the time. Otherwise, only the date is be included.
15189 All parts of a date not specified by the user is filled in from
15190 the current date/time. So if you just press return without
15191 typing anything, the time stamp will represent the current
15192 date/time.
15194 If there is already a timestamp at the cursor, it will be
15195 modified.
15197 With two universal prefix arguments, insert an active timestamp
15198 with the current time without prompting the user."
15199 (interactive "P")
15200 (let* ((ts nil)
15201 (default-time
15202 ;; Default time is either today, or, when entering a range,
15203 ;; the range start.
15204 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15205 (save-excursion
15206 (re-search-backward
15207 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15208 (- (point) 20) t)))
15209 (apply 'encode-time (org-parse-time-string (match-string 1)))
15210 (current-time)))
15211 (default-input (and ts (org-get-compact-tod ts)))
15212 (repeater (save-excursion
15213 (save-match-data
15214 (beginning-of-line)
15215 (when (re-search-forward
15216 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15217 (save-excursion (progn (end-of-line) (point))) t)
15218 (match-string 0)))))
15219 org-time-was-given org-end-time-was-given time)
15220 (cond
15221 ((and (org-at-timestamp-p t)
15222 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15223 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15224 (insert "--")
15225 (setq time (let ((this-command this-command))
15226 (org-read-date arg 'totime nil nil
15227 default-time default-input inactive)))
15228 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15229 ((org-at-timestamp-p t)
15230 (setq time (let ((this-command this-command))
15231 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15232 (when (org-at-timestamp-p t) ; just to get the match data
15233 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15234 (replace-match "")
15235 (setq org-last-changed-timestamp
15236 (org-insert-time-stamp
15237 time (or org-time-was-given arg)
15238 inactive nil nil (list org-end-time-was-given)))
15239 (when repeater (goto-char (1- (point))) (insert " " repeater)
15240 (setq org-last-changed-timestamp
15241 (concat (substring org-last-inserted-timestamp 0 -1)
15242 " " repeater ">"))))
15243 (message "Timestamp updated"))
15244 ((equal arg '(16))
15245 (org-insert-time-stamp (current-time) t))
15247 (setq time (let ((this-command this-command))
15248 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15249 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15250 nil nil (list org-end-time-was-given))))))
15252 ;; FIXME: can we use this for something else, like computing time differences?
15253 (defun org-get-compact-tod (s)
15254 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15255 (let* ((t1 (match-string 1 s))
15256 (h1 (string-to-number (match-string 2 s)))
15257 (m1 (string-to-number (match-string 3 s)))
15258 (t2 (and (match-end 4) (match-string 5 s)))
15259 (h2 (and t2 (string-to-number (match-string 6 s))))
15260 (m2 (and t2 (string-to-number (match-string 7 s))))
15261 dh dm)
15262 (if (not t2)
15264 (setq dh (- h2 h1) dm (- m2 m1))
15265 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15266 (concat t1 "+" (number-to-string dh)
15267 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15269 (defun org-time-stamp-inactive (&optional arg)
15270 "Insert an inactive time stamp.
15271 An inactive time stamp is enclosed in square brackets instead of angle
15272 brackets. It is inactive in the sense that it does not trigger agenda entries,
15273 does not link to the calendar and cannot be changed with the S-cursor keys.
15274 So these are more for recording a certain time/date."
15275 (interactive "P")
15276 (org-time-stamp arg 'inactive))
15278 (defvar org-date-ovl (make-overlay 1 1))
15279 (overlay-put org-date-ovl 'face 'org-date-selected)
15280 (org-detach-overlay org-date-ovl)
15282 (defvar org-ans1) ; dynamically scoped parameter
15283 (defvar org-ans2) ; dynamically scoped parameter
15285 (defvar org-plain-time-of-day-regexp) ; defined below
15287 (defvar org-overriding-default-time nil) ; dynamically scoped
15288 (defvar org-read-date-overlay nil)
15289 (defvar org-dcst nil) ; dynamically scoped
15290 (defvar org-read-date-history nil)
15291 (defvar org-read-date-final-answer nil)
15292 (defvar org-read-date-analyze-futurep nil)
15293 (defvar org-read-date-analyze-forced-year nil)
15294 (defvar org-read-date-inactive)
15296 (defun org-read-date (&optional org-with-time to-time from-string prompt
15297 default-time default-input inactive)
15298 "Read a date, possibly a time, and make things smooth for the user.
15299 The prompt will suggest to enter an ISO date, but you can also enter anything
15300 which will at least partially be understood by `parse-time-string'.
15301 Unrecognized parts of the date will default to the current day, month, year,
15302 hour and minute. If this command is called to replace a timestamp at point,
15303 or to enter the second timestamp of a range, the default time is taken
15304 from the existing stamp. Furthermore, the command prefers the future,
15305 so if you are giving a date where the year is not given, and the day-month
15306 combination is already past in the current year, it will assume you
15307 mean next year. For details, see the manual. A few examples:
15309 3-2-5 --> 2003-02-05
15310 feb 15 --> currentyear-02-15
15311 2/15 --> currentyear-02-15
15312 sep 12 9 --> 2009-09-12
15313 12:45 --> today 12:45
15314 22 sept 0:34 --> currentyear-09-22 0:34
15315 12 --> currentyear-currentmonth-12
15316 Fri --> nearest Friday (today or later)
15317 etc.
15319 Furthermore you can specify a relative date by giving, as the *first* thing
15320 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15321 change in days weeks, months, years.
15322 With a single plus or minus, the date is relative to today. With a double
15323 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15324 +4d --> four days from today
15325 +4 --> same as above
15326 +2w --> two weeks from today
15327 ++5 --> five days from default date
15329 The function understands only English month and weekday abbreviations.
15331 While prompting, a calendar is popped up - you can also select the
15332 date with the mouse (button 1). The calendar shows a period of three
15333 months. To scroll it to other months, use the keys `>' and `<'.
15334 If you don't like the calendar, turn it off with
15335 \(setq org-read-date-popup-calendar nil)
15337 With optional argument TO-TIME, the date will immediately be converted
15338 to an internal time.
15339 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15340 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15341 still enter a time, and this function will inform the calling routine
15342 about this change. The calling routine may then choose to change the
15343 format used to insert the time stamp into the buffer to include the time.
15344 With optional argument FROM-STRING, read from this string instead from
15345 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15346 the time/date that is used for everything that is not specified by the
15347 user."
15348 (require 'parse-time)
15349 (let* ((org-time-stamp-rounding-minutes
15350 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15351 (org-dcst org-display-custom-times)
15352 (ct (org-current-time))
15353 (org-def (or org-overriding-default-time default-time ct))
15354 (org-defdecode (decode-time org-def))
15355 (dummy (progn
15356 (when (< (nth 2 org-defdecode) org-extend-today-until)
15357 (setcar (nthcdr 2 org-defdecode) -1)
15358 (setcar (nthcdr 1 org-defdecode) 59)
15359 (setq org-def (apply 'encode-time org-defdecode)
15360 org-defdecode (decode-time org-def)))))
15361 (mouse-autoselect-window nil) ; Don't let the mouse jump
15362 (calendar-frame-setup nil)
15363 (calendar-setup nil)
15364 (calendar-move-hook nil)
15365 (calendar-view-diary-initially-flag nil)
15366 (calendar-view-holidays-initially-flag nil)
15367 (timestr (format-time-string
15368 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15369 (prompt (concat (if prompt (concat prompt " ") "")
15370 (format "Date+time [%s]: " timestr)))
15371 ans (org-ans0 "") org-ans1 org-ans2 final)
15373 (cond
15374 (from-string (setq ans from-string))
15375 (org-read-date-popup-calendar
15376 (save-excursion
15377 (save-window-excursion
15378 (calendar)
15379 (org-eval-in-calendar '(setq cursor-type nil) t)
15380 (unwind-protect
15381 (progn
15382 (calendar-forward-day (- (time-to-days org-def)
15383 (calendar-absolute-from-gregorian
15384 (calendar-current-date))))
15385 (org-eval-in-calendar nil t)
15386 (let* ((old-map (current-local-map))
15387 (map (copy-keymap calendar-mode-map))
15388 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15389 (org-defkey map (kbd "RET") 'org-calendar-select)
15390 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15391 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15392 (org-defkey minibuffer-local-map [(meta shift left)]
15393 (lambda () (interactive)
15394 (org-eval-in-calendar '(calendar-backward-month 1))))
15395 (org-defkey minibuffer-local-map [(meta shift right)]
15396 (lambda () (interactive)
15397 (org-eval-in-calendar '(calendar-forward-month 1))))
15398 (org-defkey minibuffer-local-map [(meta shift up)]
15399 (lambda () (interactive)
15400 (org-eval-in-calendar '(calendar-backward-year 1))))
15401 (org-defkey minibuffer-local-map [(meta shift down)]
15402 (lambda () (interactive)
15403 (org-eval-in-calendar '(calendar-forward-year 1))))
15404 (org-defkey minibuffer-local-map [?\e (shift left)]
15405 (lambda () (interactive)
15406 (org-eval-in-calendar '(calendar-backward-month 1))))
15407 (org-defkey minibuffer-local-map [?\e (shift right)]
15408 (lambda () (interactive)
15409 (org-eval-in-calendar '(calendar-forward-month 1))))
15410 (org-defkey minibuffer-local-map [?\e (shift up)]
15411 (lambda () (interactive)
15412 (org-eval-in-calendar '(calendar-backward-year 1))))
15413 (org-defkey minibuffer-local-map [?\e (shift down)]
15414 (lambda () (interactive)
15415 (org-eval-in-calendar '(calendar-forward-year 1))))
15416 (org-defkey minibuffer-local-map [(shift up)]
15417 (lambda () (interactive)
15418 (org-eval-in-calendar '(calendar-backward-week 1))))
15419 (org-defkey minibuffer-local-map [(shift down)]
15420 (lambda () (interactive)
15421 (org-eval-in-calendar '(calendar-forward-week 1))))
15422 (org-defkey minibuffer-local-map [(shift left)]
15423 (lambda () (interactive)
15424 (org-eval-in-calendar '(calendar-backward-day 1))))
15425 (org-defkey minibuffer-local-map [(shift right)]
15426 (lambda () (interactive)
15427 (org-eval-in-calendar '(calendar-forward-day 1))))
15428 (org-defkey minibuffer-local-map ">"
15429 (lambda () (interactive)
15430 (org-eval-in-calendar '(scroll-calendar-left 1))))
15431 (org-defkey minibuffer-local-map "<"
15432 (lambda () (interactive)
15433 (org-eval-in-calendar '(scroll-calendar-right 1))))
15434 (org-defkey minibuffer-local-map "\C-v"
15435 (lambda () (interactive)
15436 (org-eval-in-calendar
15437 '(calendar-scroll-left-three-months 1))))
15438 (org-defkey minibuffer-local-map "\M-v"
15439 (lambda () (interactive)
15440 (org-eval-in-calendar
15441 '(calendar-scroll-right-three-months 1))))
15442 (run-hooks 'org-read-date-minibuffer-setup-hook)
15443 (unwind-protect
15444 (progn
15445 (use-local-map map)
15446 (setq org-read-date-inactive inactive)
15447 (add-hook 'post-command-hook 'org-read-date-display)
15448 (setq org-ans0 (read-string prompt default-input
15449 'org-read-date-history nil))
15450 ;; org-ans0: from prompt
15451 ;; org-ans1: from mouse click
15452 ;; org-ans2: from calendar motion
15453 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15454 (remove-hook 'post-command-hook 'org-read-date-display)
15455 (use-local-map old-map)
15456 (when org-read-date-overlay
15457 (delete-overlay org-read-date-overlay)
15458 (setq org-read-date-overlay nil)))))
15459 (bury-buffer "*Calendar*")))))
15461 (t ; Naked prompt only
15462 (unwind-protect
15463 (setq ans (read-string prompt default-input
15464 'org-read-date-history timestr))
15465 (when org-read-date-overlay
15466 (delete-overlay org-read-date-overlay)
15467 (setq org-read-date-overlay nil)))))
15469 (setq final (org-read-date-analyze ans org-def org-defdecode))
15471 (when org-read-date-analyze-forced-year
15472 (message "Year was forced into %s"
15473 (if org-read-date-force-compatible-dates
15474 "compatible range (1970-2037)"
15475 "range representable on this machine"))
15476 (ding))
15478 ;; One round trip to get rid of 34th of August and stuff like that....
15479 (setq final (decode-time (apply 'encode-time final)))
15481 (setq org-read-date-final-answer ans)
15483 (if to-time
15484 (apply 'encode-time final)
15485 (if (and (boundp 'org-time-was-given) org-time-was-given)
15486 (format "%04d-%02d-%02d %02d:%02d"
15487 (nth 5 final) (nth 4 final) (nth 3 final)
15488 (nth 2 final) (nth 1 final))
15489 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15491 (defvar org-def)
15492 (defvar org-defdecode)
15493 (defvar org-with-time)
15494 (defun org-read-date-display ()
15495 "Display the current date prompt interpretation in the minibuffer."
15496 (when org-read-date-display-live
15497 (when org-read-date-overlay
15498 (delete-overlay org-read-date-overlay))
15499 (when (minibufferp (current-buffer))
15500 (save-excursion
15501 (end-of-line 1)
15502 (while (not (equal (buffer-substring
15503 (max (point-min) (- (point) 4)) (point))
15504 " "))
15505 (insert " ")))
15506 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15507 " " (or org-ans1 org-ans2)))
15508 (org-end-time-was-given nil)
15509 (f (org-read-date-analyze ans org-def org-defdecode))
15510 (fmts (if org-dcst
15511 org-time-stamp-custom-formats
15512 org-time-stamp-formats))
15513 (fmt (if (or org-with-time
15514 (and (boundp 'org-time-was-given) org-time-was-given))
15515 (cdr fmts)
15516 (car fmts)))
15517 (txt (format-time-string fmt (apply 'encode-time f)))
15518 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15519 (txt (concat "=> " txt)))
15520 (when (and org-end-time-was-given
15521 (string-match org-plain-time-of-day-regexp txt))
15522 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15523 org-end-time-was-given
15524 (substring txt (match-end 0)))))
15525 (when org-read-date-analyze-futurep
15526 (setq txt (concat txt " (=>F)")))
15527 (setq org-read-date-overlay
15528 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15529 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15531 (defun org-read-date-analyze (ans org-def org-defdecode)
15532 "Analyze the combined answer of the date prompt."
15533 ;; FIXME: cleanup and comment
15534 (let ((nowdecode (decode-time (current-time)))
15535 delta deltan deltaw deltadef year month day
15536 hour minute second wday pm h2 m2 tl wday1
15537 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15538 (setq org-read-date-analyze-futurep nil
15539 org-read-date-analyze-forced-year nil)
15540 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15541 (setq ans "+0"))
15543 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15544 (setq ans (replace-match "" t t ans)
15545 deltan (car delta)
15546 deltaw (nth 1 delta)
15547 deltadef (nth 2 delta)))
15549 ;; Check if there is an iso week date in there. If yes, store the
15550 ;; info and postpone interpreting it until the rest of the parsing
15551 ;; is done.
15552 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15553 (setq iso-year (if (match-end 1)
15554 (org-small-year-to-year
15555 (string-to-number (match-string 1 ans))))
15556 iso-weekday (if (match-end 3)
15557 (string-to-number (match-string 3 ans)))
15558 iso-week (string-to-number (match-string 2 ans)))
15559 (setq ans (replace-match "" t t ans)))
15561 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15562 (when (string-match
15563 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15564 (setq year (if (match-end 2)
15565 (string-to-number (match-string 2 ans))
15566 (progn (setq kill-year t)
15567 (string-to-number (format-time-string "%Y"))))
15568 month (string-to-number (match-string 3 ans))
15569 day (string-to-number (match-string 4 ans)))
15570 (if (< year 100) (setq year (+ 2000 year)))
15571 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15572 t nil ans)))
15574 ;; Help matching dotted european dates
15575 (when (string-match
15576 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15577 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15578 (setq kill-year t)
15579 (string-to-number (format-time-string "%Y")))
15580 day (string-to-number (match-string 1 ans))
15581 month (string-to-number (match-string 2 ans))
15582 ans (replace-match (format "%04d-%02d-%02d" year month day)
15583 t nil ans)))
15585 ;; Help matching american dates, like 5/30 or 5/30/7
15586 (when (string-match
15587 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15588 (setq year (if (match-end 4)
15589 (string-to-number (match-string 4 ans))
15590 (progn (setq kill-year t)
15591 (string-to-number (format-time-string "%Y"))))
15592 month (string-to-number (match-string 1 ans))
15593 day (string-to-number (match-string 2 ans)))
15594 (if (< year 100) (setq year (+ 2000 year)))
15595 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15596 t nil ans)))
15597 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15598 ;; If there is a time with am/pm, and *no* time without it, we convert
15599 ;; so that matching will be successful.
15600 (loop for i from 1 to 2 do ; twice, for end time as well
15601 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15602 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15603 (setq hour (string-to-number (match-string 1 ans))
15604 minute (if (match-end 3)
15605 (string-to-number (match-string 3 ans))
15607 pm (equal ?p
15608 (string-to-char (downcase (match-string 4 ans)))))
15609 (if (and (= hour 12) (not pm))
15610 (setq hour 0)
15611 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15612 (setq ans (replace-match (format "%02d:%02d" hour minute)
15613 t t ans))))
15615 ;; Check if a time range is given as a duration
15616 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15617 (setq hour (string-to-number (match-string 1 ans))
15618 h2 (+ hour (string-to-number (match-string 3 ans)))
15619 minute (string-to-number (match-string 2 ans))
15620 m2 (+ minute (if (match-end 5) (string-to-number
15621 (match-string 5 ans))0)))
15622 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15623 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15624 t t ans)))
15626 ;; Check if there is a time range
15627 (when (boundp 'org-end-time-was-given)
15628 (setq org-time-was-given nil)
15629 (when (and (string-match org-plain-time-of-day-regexp ans)
15630 (match-end 8))
15631 (setq org-end-time-was-given (match-string 8 ans))
15632 (setq ans (concat (substring ans 0 (match-beginning 7))
15633 (substring ans (match-end 7))))))
15635 (setq tl (parse-time-string ans)
15636 day (or (nth 3 tl) (nth 3 org-defdecode))
15637 month (or (nth 4 tl)
15638 (if (and org-read-date-prefer-future
15639 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15640 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15641 (nth 4 org-defdecode)))
15642 year (or (and (not kill-year) (nth 5 tl))
15643 (if (and org-read-date-prefer-future
15644 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15645 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15646 (nth 5 org-defdecode)))
15647 hour (or (nth 2 tl) (nth 2 org-defdecode))
15648 minute (or (nth 1 tl) (nth 1 org-defdecode))
15649 second (or (nth 0 tl) 0)
15650 wday (nth 6 tl))
15652 (when (and (eq org-read-date-prefer-future 'time)
15653 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15654 (equal day (nth 3 nowdecode))
15655 (equal month (nth 4 nowdecode))
15656 (equal year (nth 5 nowdecode))
15657 (nth 2 tl)
15658 (or (< (nth 2 tl) (nth 2 nowdecode))
15659 (and (= (nth 2 tl) (nth 2 nowdecode))
15660 (nth 1 tl)
15661 (< (nth 1 tl) (nth 1 nowdecode)))))
15662 (setq day (1+ day)
15663 futurep t))
15665 ;; Special date definitions below
15666 (cond
15667 (iso-week
15668 ;; There was an iso week
15669 (require 'cal-iso)
15670 (setq futurep nil)
15671 (setq year (or iso-year year)
15672 day (or iso-weekday wday 1)
15673 wday nil ; to make sure that the trigger below does not match
15674 iso-date (calendar-gregorian-from-absolute
15675 (calendar-absolute-from-iso
15676 (list iso-week day year))))
15677 ; FIXME: Should we also push ISO weeks into the future?
15678 ; (when (and org-read-date-prefer-future
15679 ; (not iso-year)
15680 ; (< (calendar-absolute-from-gregorian iso-date)
15681 ; (time-to-days (current-time))))
15682 ; (setq year (1+ year)
15683 ; iso-date (calendar-gregorian-from-absolute
15684 ; (calendar-absolute-from-iso
15685 ; (list iso-week day year)))))
15686 (setq month (car iso-date)
15687 year (nth 2 iso-date)
15688 day (nth 1 iso-date)))
15689 (deltan
15690 (setq futurep nil)
15691 (unless deltadef
15692 (let ((now (decode-time (current-time))))
15693 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15694 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15695 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15696 ((equal deltaw "m") (setq month (+ month deltan)))
15697 ((equal deltaw "y") (setq year (+ year deltan)))))
15698 ((and wday (not (nth 3 tl)))
15699 ;; Weekday was given, but no day, so pick that day in the week
15700 ;; on or after the derived date.
15701 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15702 (unless (equal wday wday1)
15703 (setq day (+ day (% (- wday wday1 -7) 7))))))
15704 (if (and (boundp 'org-time-was-given)
15705 (nth 2 tl))
15706 (setq org-time-was-given t))
15707 (if (< year 100) (setq year (+ 2000 year)))
15708 ;; Check of the date is representable
15709 (if org-read-date-force-compatible-dates
15710 (progn
15711 (if (< year 1970)
15712 (setq year 1970 org-read-date-analyze-forced-year t))
15713 (if (> year 2037)
15714 (setq year 2037 org-read-date-analyze-forced-year t)))
15715 (condition-case nil
15716 (ignore (encode-time second minute hour day month year))
15717 (error
15718 (setq year (nth 5 org-defdecode))
15719 (setq org-read-date-analyze-forced-year t))))
15720 (setq org-read-date-analyze-futurep futurep)
15721 (list second minute hour day month year)))
15723 (defvar parse-time-weekdays)
15724 (defun org-read-date-get-relative (s today default)
15725 "Check string S for special relative date string.
15726 TODAY and DEFAULT are internal times, for today and for a default.
15727 Return shift list (N what def-flag)
15728 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15729 N is the number of WHATs to shift.
15730 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15731 the DEFAULT date rather than TODAY."
15732 (require 'parse-time)
15733 (when (and
15734 (string-match
15735 (concat
15736 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15737 "\\([0-9]+\\)?"
15738 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15739 "\\([ \t]\\|$\\)") s)
15740 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15741 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15742 (string-to-char (substring (match-string 1 s) -1))
15743 ?+))
15744 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15745 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15746 (what (if (match-end 3) (match-string 3 s) "d"))
15747 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15748 (date (if rel default today))
15749 (wday (nth 6 (decode-time date)))
15750 delta)
15751 (if wday1
15752 (progn
15753 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15754 (if (= dir ?-) (setq delta (- delta 7)))
15755 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15756 (list delta "d" rel))
15757 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15759 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15760 "Turn a user-specified date into the internal representation.
15761 The internal representation needed by the calendar is (month day year).
15762 This is a wrapper to handle the brain-dead convention in calendar that
15763 user function argument order change dependent on argument order."
15764 (if (boundp 'calendar-date-style)
15765 (cond
15766 ((eq calendar-date-style 'american)
15767 (list arg1 arg2 arg3))
15768 ((eq calendar-date-style 'european)
15769 (list arg2 arg1 arg3))
15770 ((eq calendar-date-style 'iso)
15771 (list arg2 arg3 arg1)))
15772 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15773 (if (org-bound-and-true-p european-calendar-style)
15774 (list arg2 arg1 arg3)
15775 (list arg1 arg2 arg3)))))
15777 (defun org-eval-in-calendar (form &optional keepdate)
15778 "Eval FORM in the calendar window and return to current window.
15779 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15780 otherwise stick to the current value of `org-ans2'."
15781 (let ((sf (selected-frame))
15782 (sw (selected-window)))
15783 (select-window (get-buffer-window "*Calendar*" t))
15784 (eval form)
15785 (when (and (not keepdate) (calendar-cursor-to-date))
15786 (let* ((date (calendar-cursor-to-date))
15787 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15788 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15789 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15790 (select-window sw)
15791 (org-select-frame-set-input-focus sf)))
15793 (defun org-calendar-select ()
15794 "Return to `org-read-date' with the date currently selected.
15795 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15796 (interactive)
15797 (when (calendar-cursor-to-date)
15798 (let* ((date (calendar-cursor-to-date))
15799 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15800 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15801 (if (active-minibuffer-window) (exit-minibuffer))))
15803 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15804 "Insert a date stamp for the date given by the internal TIME.
15805 WITH-HM means use the stamp format that includes the time of the day.
15806 INACTIVE means use square brackets instead of angular ones, so that the
15807 stamp will not contribute to the agenda.
15808 PRE and POST are optional strings to be inserted before and after the
15809 stamp.
15810 The command returns the inserted time stamp."
15811 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15812 stamp)
15813 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15814 (insert-before-markers (or pre ""))
15815 (when (listp extra)
15816 (setq extra (car extra))
15817 (if (and (stringp extra)
15818 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15819 (setq extra (format "-%02d:%02d"
15820 (string-to-number (match-string 1 extra))
15821 (string-to-number (match-string 2 extra))))
15822 (setq extra nil)))
15823 (when extra
15824 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15825 (insert-before-markers (setq stamp (format-time-string fmt time)))
15826 (insert-before-markers (or post ""))
15827 (setq org-last-inserted-timestamp stamp)))
15829 (defun org-toggle-time-stamp-overlays ()
15830 "Toggle the use of custom time stamp formats."
15831 (interactive)
15832 (setq org-display-custom-times (not org-display-custom-times))
15833 (unless org-display-custom-times
15834 (let ((p (point-min)) (bmp (buffer-modified-p)))
15835 (while (setq p (next-single-property-change p 'display))
15836 (if (and (get-text-property p 'display)
15837 (eq (get-text-property p 'face) 'org-date))
15838 (remove-text-properties
15839 p (setq p (next-single-property-change p 'display))
15840 '(display t))))
15841 (set-buffer-modified-p bmp)))
15842 (if (featurep 'xemacs)
15843 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15844 (org-restart-font-lock)
15845 (setq org-table-may-need-update t)
15846 (if org-display-custom-times
15847 (message "Time stamps are overlaid with custom format")
15848 (message "Time stamp overlays removed")))
15850 (defun org-display-custom-time (beg end)
15851 "Overlay modified time stamp format over timestamp between BEG and END."
15852 (let* ((ts (buffer-substring beg end))
15853 t1 w1 with-hm tf time str w2 (off 0))
15854 (save-match-data
15855 (setq t1 (org-parse-time-string ts t))
15856 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15857 (setq off (- (match-end 0) (match-beginning 0)))))
15858 (setq end (- end off))
15859 (setq w1 (- end beg)
15860 with-hm (and (nth 1 t1) (nth 2 t1))
15861 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15862 time (org-fix-decoded-time t1)
15863 str (org-add-props
15864 (format-time-string
15865 (substring tf 1 -1) (apply 'encode-time time))
15866 nil 'mouse-face 'highlight)
15867 w2 (length str))
15868 (if (not (= w2 w1))
15869 (add-text-properties (1+ beg) (+ 2 beg)
15870 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15871 (if (featurep 'xemacs)
15872 (progn
15873 (put-text-property beg end 'invisible t)
15874 (put-text-property beg end 'end-glyph (make-glyph str)))
15875 (put-text-property beg end 'display str))))
15877 (defun org-translate-time (string)
15878 "Translate all timestamps in STRING to custom format.
15879 But do this only if the variable `org-display-custom-times' is set."
15880 (when org-display-custom-times
15881 (save-match-data
15882 (let* ((start 0)
15883 (re org-ts-regexp-both)
15884 t1 with-hm inactive tf time str beg end)
15885 (while (setq start (string-match re string start))
15886 (setq beg (match-beginning 0)
15887 end (match-end 0)
15888 t1 (save-match-data
15889 (org-parse-time-string (substring string beg end) t))
15890 with-hm (and (nth 1 t1) (nth 2 t1))
15891 inactive (equal (substring string beg (1+ beg)) "[")
15892 tf (funcall (if with-hm 'cdr 'car)
15893 org-time-stamp-custom-formats)
15894 time (org-fix-decoded-time t1)
15895 str (format-time-string
15896 (concat
15897 (if inactive "[" "<") (substring tf 1 -1)
15898 (if inactive "]" ">"))
15899 (apply 'encode-time time))
15900 string (replace-match str t t string)
15901 start (+ start (length str)))))))
15902 string)
15904 (defun org-fix-decoded-time (time)
15905 "Set 0 instead of nil for the first 6 elements of time.
15906 Don't touch the rest."
15907 (let ((n 0))
15908 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15910 (defun org-days-to-time (timestamp-string)
15911 "Difference between TIMESTAMP-STRING and now in days."
15912 (- (time-to-days (org-time-string-to-time timestamp-string))
15913 (time-to-days (current-time))))
15915 (defun org-deadline-close (timestamp-string &optional ndays)
15916 "Is the time in TIMESTAMP-STRING close to the current date?"
15917 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15918 (and (< (org-days-to-time timestamp-string) ndays)
15919 (not (org-entry-is-done-p))))
15921 (defun org-get-wdays (ts)
15922 "Get the deadline lead time appropriate for timestring TS."
15923 (cond
15924 ((<= org-deadline-warning-days 0)
15925 ;; 0 or negative, enforce this value no matter what
15926 (- org-deadline-warning-days))
15927 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15928 ;; lead time is specified.
15929 (floor (* (string-to-number (match-string 1 ts))
15930 (cdr (assoc (match-string 2 ts)
15931 '(("d" . 1) ("w" . 7)
15932 ("m" . 30.4) ("y" . 365.25)
15933 ("h" . 0.041667)))))))
15934 ;; go for the default.
15935 (t org-deadline-warning-days)))
15937 (defun org-calendar-select-mouse (ev)
15938 "Return to `org-read-date' with the date currently selected.
15939 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15940 (interactive "e")
15941 (mouse-set-point ev)
15942 (when (calendar-cursor-to-date)
15943 (let* ((date (calendar-cursor-to-date))
15944 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15945 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15946 (if (active-minibuffer-window) (exit-minibuffer))))
15948 (defun org-check-deadlines (ndays)
15949 "Check if there are any deadlines due or past due.
15950 A deadline is considered due if it happens within `org-deadline-warning-days'
15951 days from today's date. If the deadline appears in an entry marked DONE,
15952 it is not shown. The prefix arg NDAYS can be used to test that many
15953 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15954 (interactive "P")
15955 (let* ((org-warn-days
15956 (cond
15957 ((equal ndays '(4)) 100000)
15958 (ndays (prefix-numeric-value ndays))
15959 (t (abs org-deadline-warning-days))))
15960 (case-fold-search nil)
15961 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15962 (callback
15963 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15965 (message "%d deadlines past-due or due within %d days"
15966 (org-occur regexp nil callback)
15967 org-warn-days)))
15969 (defsubst org-re-timestamp (type)
15970 "Return a regexp for timestamp TYPE.
15971 Allowed values for TYPE are:
15973 all: all timestamps
15974 active: only active timestamps (<...>)
15975 inactive: only inactive timestamps ([...])
15976 scheduled: only scheduled timestamps
15977 deadline: only deadline timestamps
15979 When TYPE is nil, fall back on returning a regexp that matches
15980 both scheduled and deadline timestamps."
15981 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
15982 ((eq type 'active) org-ts-regexp)
15983 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
15984 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
15985 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15986 ((eq type 'scheduled-or-deadline)
15987 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
15989 (defun org-check-before-date (date)
15990 "Check if there are deadlines or scheduled entries before DATE."
15991 (interactive (list (org-read-date)))
15992 (let ((case-fold-search nil)
15993 (regexp (org-re-timestamp org-ts-type))
15994 (callback
15995 (lambda () (time-less-p
15996 (org-time-string-to-time (match-string 1))
15997 (org-time-string-to-time date)))))
15998 (message "%d entries before %s"
15999 (org-occur regexp nil callback) date)))
16001 (defun org-check-after-date (date)
16002 "Check if there are deadlines or scheduled entries after DATE."
16003 (interactive (list (org-read-date)))
16004 (let ((case-fold-search nil)
16005 (regexp (org-re-timestamp org-ts-type))
16006 (callback
16007 (lambda () (not
16008 (time-less-p
16009 (org-time-string-to-time (match-string 1))
16010 (org-time-string-to-time date))))))
16011 (message "%d entries after %s"
16012 (org-occur regexp nil callback) date)))
16014 (defun org-check-dates-range (start-date end-date)
16015 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16016 (interactive (list (org-read-date nil nil nil "Range starts")
16017 (org-read-date nil nil nil "Range end")))
16018 (let ((case-fold-search nil)
16019 (regexp (org-re-timestamp org-ts-type))
16020 (callback
16021 (lambda ()
16022 (let ((match (match-string 1)))
16023 (and
16024 (not (time-less-p
16025 (org-time-string-to-time match)
16026 (org-time-string-to-time start-date)))
16027 (time-less-p
16028 (org-time-string-to-time match)
16029 (org-time-string-to-time end-date)))))))
16030 (message "%d entries between %s and %s"
16031 (org-occur regexp nil callback) start-date end-date)))
16033 (defun org-evaluate-time-range (&optional to-buffer)
16034 "Evaluate a time range by computing the difference between start and end.
16035 Normally the result is just printed in the echo area, but with prefix arg
16036 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16037 If the time range is actually in a table, the result is inserted into the
16038 next column.
16039 For time difference computation, a year is assumed to be exactly 365
16040 days in order to avoid rounding problems."
16041 (interactive "P")
16043 (org-clock-update-time-maybe)
16044 (save-excursion
16045 (unless (org-at-date-range-p t)
16046 (goto-char (point-at-bol))
16047 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16048 (if (not (org-at-date-range-p t))
16049 (error "Not at a time-stamp range, and none found in current line")))
16050 (let* ((ts1 (match-string 1))
16051 (ts2 (match-string 2))
16052 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16053 (match-end (match-end 0))
16054 (time1 (org-time-string-to-time ts1))
16055 (time2 (org-time-string-to-time ts2))
16056 (t1 (org-float-time time1))
16057 (t2 (org-float-time time2))
16058 (diff (abs (- t2 t1)))
16059 (negative (< (- t2 t1) 0))
16060 ;; (ys (floor (* 365 24 60 60)))
16061 (ds (* 24 60 60))
16062 (hs (* 60 60))
16063 (fy "%dy %dd %02d:%02d")
16064 (fy1 "%dy %dd")
16065 (fd "%dd %02d:%02d")
16066 (fd1 "%dd")
16067 (fh "%02d:%02d")
16068 y d h m align)
16069 (if havetime
16070 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16072 d (floor (/ diff ds)) diff (mod diff ds)
16073 h (floor (/ diff hs)) diff (mod diff hs)
16074 m (floor (/ diff 60)))
16075 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16077 d (floor (+ (/ diff ds) 0.5))
16078 h 0 m 0))
16079 (if (not to-buffer)
16080 (message "%s" (org-make-tdiff-string y d h m))
16081 (if (org-at-table-p)
16082 (progn
16083 (goto-char match-end)
16084 (setq align t)
16085 (and (looking-at " *|") (goto-char (match-end 0))))
16086 (goto-char match-end))
16087 (if (looking-at
16088 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16089 (replace-match ""))
16090 (if negative (insert " -"))
16091 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16092 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16093 (insert " " (format fh h m))))
16094 (if align (org-table-align))
16095 (message "Time difference inserted")))))
16097 (defun org-make-tdiff-string (y d h m)
16098 (let ((fmt "")
16099 (l nil))
16100 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16101 l (push y l)))
16102 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16103 l (push d l)))
16104 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16105 l (push h l)))
16106 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16107 l (push m l)))
16108 (apply 'format fmt (nreverse l))))
16110 (defun org-time-string-to-time (s &optional buffer pos)
16111 "Convert a timestamp string into internal time."
16112 (condition-case errdata
16113 (apply 'encode-time (org-parse-time-string s))
16114 (error (error "Bad timestamp `%s'%s\nError was: %s"
16115 s (if (not (and buffer pos))
16117 (format " at %d in buffer `%s'" pos buffer))
16118 (cdr errdata)))))
16120 (defun org-time-string-to-seconds (s)
16121 "Convert a timestamp string to a number of seconds."
16122 (org-float-time (org-time-string-to-time s)))
16124 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16125 "Convert a time stamp to an absolute day number.
16126 If there is a specifier for a cyclic time stamp, get the closest date to
16127 DAYNR.
16128 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16129 The variable date is bound by the calendar when this is called."
16130 (cond
16131 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16132 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16133 daynr
16134 (+ daynr 1000)))
16135 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16136 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16137 (time-to-days (current-time))) (match-string 0 s)
16138 prefer show-all))
16139 (t (time-to-days
16140 (condition-case errdata
16141 (apply 'encode-time (org-parse-time-string s))
16142 (error (error "Bad timestamp `%s'%s\nError was: %s"
16143 s (if (not (and buffer pos))
16145 (format " at %d in buffer `%s'" pos buffer))
16146 (cdr errdata))))))))
16148 (defun org-days-to-iso-week (days)
16149 "Return the iso week number."
16150 (require 'cal-iso)
16151 (car (calendar-iso-from-absolute days)))
16153 (defun org-small-year-to-year (year)
16154 "Convert 2-digit years into 4-digit years.
16155 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16156 The year 2000 cannot be abbreviated. Any year larger than 99
16157 is returned unchanged."
16158 (if (< year 38)
16159 (setq year (+ 2000 year))
16160 (if (< year 100)
16161 (setq year (+ 1900 year))))
16162 year)
16164 (defun org-time-from-absolute (d)
16165 "Return the time corresponding to date D.
16166 D may be an absolute day number, or a calendar-type list (month day year)."
16167 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16168 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16170 (defun org-calendar-holiday ()
16171 "List of holidays, for Diary display in Org-mode."
16172 (require 'holidays)
16173 (let ((hl (funcall
16174 (if (fboundp 'calendar-check-holidays)
16175 'calendar-check-holidays 'check-calendar-holidays) date)))
16176 (if hl (mapconcat 'identity hl "; "))))
16178 (defun org-diary-sexp-entry (sexp entry date)
16179 "Process a SEXP diary ENTRY for DATE."
16180 (require 'diary-lib)
16181 (let ((result (if calendar-debug-sexp
16182 (let ((stack-trace-on-error t))
16183 (eval (car (read-from-string sexp))))
16184 (condition-case nil
16185 (eval (car (read-from-string sexp)))
16186 (error
16187 (beep)
16188 (message "Bad sexp at line %d in %s: %s"
16189 (org-current-line)
16190 (buffer-file-name) sexp)
16191 (sleep-for 2))))))
16192 (cond ((stringp result) (split-string result "; "))
16193 ((and (consp result)
16194 (not (consp (cdr result)))
16195 (stringp (cdr result))) (cdr result))
16196 ((and (consp result)
16197 (stringp (car result))) result)
16198 (result entry))))
16200 (defun org-diary-to-ical-string (frombuf)
16201 "Get iCalendar entries from diary entries in buffer FROMBUF.
16202 This uses the icalendar.el library."
16203 (let* ((tmpdir (if (featurep 'xemacs)
16204 (temp-directory)
16205 temporary-file-directory))
16206 (tmpfile (make-temp-name
16207 (expand-file-name "orgics" tmpdir)))
16208 buf rtn b e)
16209 (with-current-buffer frombuf
16210 (icalendar-export-region (point-min) (point-max) tmpfile)
16211 (setq buf (find-buffer-visiting tmpfile))
16212 (set-buffer buf)
16213 (goto-char (point-min))
16214 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16215 (setq b (match-beginning 0)))
16216 (goto-char (point-max))
16217 (if (re-search-backward "^END:VEVENT" nil t)
16218 (setq e (match-end 0)))
16219 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16220 (kill-buffer buf)
16221 (delete-file tmpfile)
16222 rtn))
16224 (defun org-closest-date (start current change prefer show-all)
16225 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16226 When PREFER is `past', return a date that is either CURRENT or past.
16227 When PREFER is `future', return a date that is either CURRENT or future.
16228 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16229 ;; Make the proper lists from the dates
16230 (catch 'exit
16231 (let ((a1 '(("h" . hour)
16232 ("d" . day)
16233 ("w" . week)
16234 ("m" . month)
16235 ("y" . year)))
16236 (shour (nth 2 (org-parse-time-string start)))
16237 dn dw sday cday n1 n2 n0
16238 d m y y1 y2 date1 date2 nmonths nm ny m2)
16240 (setq start (org-date-to-gregorian start)
16241 current (org-date-to-gregorian
16242 (if show-all
16243 current
16244 (time-to-days (current-time))))
16245 sday (calendar-absolute-from-gregorian start)
16246 cday (calendar-absolute-from-gregorian current))
16248 (if (<= cday sday) (throw 'exit sday))
16250 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16251 (setq dn (string-to-number (match-string 1 change))
16252 dw (cdr (assoc (match-string 2 change) a1)))
16253 (error "Invalid change specifier: %s" change))
16254 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16255 (cond
16256 ((eq dw 'hour)
16257 (let ((missing-hours
16258 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16259 dn)))
16260 (setq n1 (if (zerop missing-hours) cday
16261 (- cday (1+ (floor (/ missing-hours 24)))))
16262 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16263 ((eq dw 'day)
16264 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16265 n2 (+ n1 dn)))
16266 ((eq dw 'year)
16267 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16268 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16269 (setq date1 (list m d y1)
16270 n1 (calendar-absolute-from-gregorian date1)
16271 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16272 n2 (calendar-absolute-from-gregorian date2)))
16273 ((eq dw 'month)
16274 ;; approx number of month between the two dates
16275 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16276 ;; How often does dn fit in there?
16277 (setq d (nth 1 start) m (car start) y (nth 2 start)
16278 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16279 m (+ m nm)
16280 ny (floor (/ m 12))
16281 y (+ y ny)
16282 m (- m (* ny 12)))
16283 (while (> m 12) (setq m (- m 12) y (1+ y)))
16284 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16285 (setq m2 (+ m dn) y2 y)
16286 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16287 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16288 (while (<= n2 cday)
16289 (setq n1 n2 m m2 y y2)
16290 (setq m2 (+ m dn) y2 y)
16291 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16292 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16293 ;; Make sure n1 is the earlier date
16294 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16295 (if show-all
16296 (cond
16297 ((eq prefer 'past) (if (= cday n2) n2 n1))
16298 ((eq prefer 'future) (if (= cday n1) n1 n2))
16299 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16300 (cond
16301 ((eq prefer 'past) (if (= cday n2) n2 n1))
16302 ((eq prefer 'future) (if (= cday n1) n1 n2))
16303 (t (if (= cday n1) n1 n2)))))))
16305 (defun org-date-to-gregorian (date)
16306 "Turn any specification of DATE into a Gregorian date for the calendar."
16307 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16308 ((and (listp date) (= (length date) 3)) date)
16309 ((stringp date)
16310 (setq date (org-parse-time-string date))
16311 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16312 ((listp date)
16313 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16315 (defun org-parse-time-string (s &optional nodefault)
16316 "Parse the standard Org-mode time string.
16317 This should be a lot faster than the normal `parse-time-string'.
16318 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16319 hour and minute fields will be nil if not given."
16320 (if (string-match org-ts-regexp0 s)
16321 (list 0
16322 (if (or (match-beginning 8) (not nodefault))
16323 (string-to-number (or (match-string 8 s) "0")))
16324 (if (or (match-beginning 7) (not nodefault))
16325 (string-to-number (or (match-string 7 s) "0")))
16326 (string-to-number (match-string 4 s))
16327 (string-to-number (match-string 3 s))
16328 (string-to-number (match-string 2 s))
16329 nil nil nil)
16330 (error "Not a standard Org-mode time string: %s" s)))
16332 (defun org-timestamp-up (&optional arg)
16333 "Increase the date item at the cursor by one.
16334 If the cursor is on the year, change the year. If it is on the month,
16335 the day or the time, change that.
16336 With prefix ARG, change by that many units."
16337 (interactive "p")
16338 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16340 (defun org-timestamp-down (&optional arg)
16341 "Decrease the date item at the cursor by one.
16342 If the cursor is on the year, change the year. If it is on the month,
16343 the day or the time, change that.
16344 With prefix ARG, change by that many units."
16345 (interactive "p")
16346 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16348 (defun org-timestamp-up-day (&optional arg)
16349 "Increase the date in the time stamp by one day.
16350 With prefix ARG, change that many days."
16351 (interactive "p")
16352 (if (and (not (org-at-timestamp-p t))
16353 (org-at-heading-p))
16354 (org-todo 'up)
16355 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16357 (defun org-timestamp-down-day (&optional arg)
16358 "Decrease the date in the time stamp by one day.
16359 With prefix ARG, change that many days."
16360 (interactive "p")
16361 (if (and (not (org-at-timestamp-p t))
16362 (org-at-heading-p))
16363 (org-todo 'down)
16364 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16366 (defun org-at-timestamp-p (&optional inactive-ok)
16367 "Determine if the cursor is in or at a timestamp."
16368 (interactive)
16369 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16370 (pos (point))
16371 (ans (or (looking-at tsr)
16372 (save-excursion
16373 (skip-chars-backward "^[<\n\r\t")
16374 (if (> (point) (point-min)) (backward-char 1))
16375 (and (looking-at tsr)
16376 (> (- (match-end 0) pos) -1))))))
16377 (and ans
16378 (boundp 'org-ts-what)
16379 (setq org-ts-what
16380 (cond
16381 ((= pos (match-beginning 0)) 'bracket)
16382 ;; Point is considered to be "on the bracket" whether
16383 ;; it's really on it or right after it.
16384 ((= pos (1- (match-end 0))) 'bracket)
16385 ((= pos (match-end 0)) 'after)
16386 ((org-pos-in-match-range pos 2) 'year)
16387 ((org-pos-in-match-range pos 3) 'month)
16388 ((org-pos-in-match-range pos 7) 'hour)
16389 ((org-pos-in-match-range pos 8) 'minute)
16390 ((or (org-pos-in-match-range pos 4)
16391 (org-pos-in-match-range pos 5)) 'day)
16392 ((and (> pos (or (match-end 8) (match-end 5)))
16393 (< pos (match-end 0)))
16394 (- pos (or (match-end 8) (match-end 5))))
16395 (t 'day))))
16396 ans))
16398 (defun org-toggle-timestamp-type ()
16399 "Toggle the type (<active> or [inactive]) of a time stamp."
16400 (interactive)
16401 (when (org-at-timestamp-p t)
16402 (let ((beg (match-beginning 0)) (end (match-end 0))
16403 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16404 (save-excursion
16405 (goto-char beg)
16406 (while (re-search-forward "[][<>]" end t)
16407 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16408 t t)))
16409 (message "Timestamp is now %sactive"
16410 (if (equal (char-after beg) ?<) "" "in")))))
16412 (defvar org-clock-history) ; defined in org-clock.el
16413 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16414 (defun org-timestamp-change (n &optional what updown)
16415 "Change the date in the time stamp at point.
16416 The date will be changed by N times WHAT. WHAT can be `day', `month',
16417 `year', `minute', `second'. If WHAT is not given, the cursor position
16418 in the timestamp determines what will be changed."
16419 (let ((origin (point)) origin-cat
16420 with-hm inactive
16421 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16422 org-ts-what
16423 extra rem
16424 ts time time0 fixnext clrgx)
16425 (if (not (org-at-timestamp-p t))
16426 (error "Not at a timestamp"))
16427 (if (and (not what) (eq org-ts-what 'bracket))
16428 (org-toggle-timestamp-type)
16429 ;; Point isn't on brackets. Remember the part of the time-stamp
16430 ;; the point was in. Indeed, size of time-stamps may change,
16431 ;; but point must be kept in the same category nonetheless.
16432 (setq origin-cat org-ts-what)
16433 (if (and (not what) (not (eq org-ts-what 'day))
16434 org-display-custom-times
16435 (get-text-property (point) 'display)
16436 (not (get-text-property (1- (point)) 'display)))
16437 (setq org-ts-what 'day))
16438 (setq org-ts-what (or what org-ts-what)
16439 inactive (= (char-after (match-beginning 0)) ?\[)
16440 ts (match-string 0))
16441 (replace-match "")
16442 (if (string-match
16443 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16445 (setq extra (match-string 1 ts)))
16446 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16447 (setq with-hm t))
16448 (setq time0 (org-parse-time-string ts))
16449 (when (and updown
16450 (eq org-ts-what 'minute)
16451 (not current-prefix-arg))
16452 ;; This looks like s-up and s-down. Change by one rounding step.
16453 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16454 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16455 (setcar (cdr time0) (+ (nth 1 time0)
16456 (if (> n 0) (- rem) (- dm rem))))))
16457 (setq time
16458 (encode-time (or (car time0) 0)
16459 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16460 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16461 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16462 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16463 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16464 (nthcdr 6 time0)))
16465 (when (and (member org-ts-what '(hour minute))
16466 extra
16467 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16468 (setq extra (org-modify-ts-extra
16469 extra
16470 (if (eq org-ts-what 'hour) 2 5)
16471 n dm)))
16472 (when (integerp org-ts-what)
16473 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16474 (if (eq what 'calendar)
16475 (let ((cal-date (org-get-date-from-calendar)))
16476 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16477 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16478 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16479 (setcar time0 (or (car time0) 0))
16480 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16481 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16482 (setq time (apply 'encode-time time0))))
16483 ;; Insert the new time-stamp, and ensure point stays in the same
16484 ;; category as before (i.e. not after the last position in that
16485 ;; category).
16486 (let ((pos (point)))
16487 ;; Stay before inserted string. `save-excursion' is of no use.
16488 (setq org-last-changed-timestamp
16489 (org-insert-time-stamp time with-hm inactive nil nil extra))
16490 (goto-char pos))
16491 (save-match-data
16492 (looking-at org-ts-regexp3)
16493 (goto-char (cond
16494 ;; `day' category ends before `hour' if any, or at
16495 ;; the end of the day name.
16496 ((eq origin-cat 'day)
16497 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16498 ((eq origin-cat 'hour) (min (match-end 7) origin))
16499 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16500 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16501 ;; `year' and `month' have both fixed size: point
16502 ;; couldn't have moved into another part.
16503 (t origin))))
16504 ;; Update clock if on a CLOCK line.
16505 (org-clock-update-time-maybe)
16506 ;; Maybe adjust the closest clock in `org-clock-history'
16507 (when org-clock-adjust-closest
16508 (if (not (and (org-at-clock-log-p)
16509 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16510 org-clock-history))))))
16511 (message "No clock to adjust")
16512 (cond ((save-excursion ; fix previous clock?
16513 (re-search-backward org-ts-regexp0 nil t)
16514 (org-looking-back (concat org-clock-string " \\[")))
16515 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16516 ((save-excursion ; fix next clock?
16517 (re-search-backward org-ts-regexp0 nil t)
16518 (looking-at (concat org-ts-regexp0 "\\] =>")))
16519 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16520 (save-window-excursion
16521 ;; Find closest clock to point, adjust the previous/next one in history
16522 (let* ((p (save-excursion (org-back-to-heading t)))
16523 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16524 (clfixnth
16525 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16526 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16527 (if (not clfixpos)
16528 (message "No clock to adjust")
16529 (save-excursion
16530 (org-goto-marker-or-bmk clfixpos)
16531 (org-show-subtree)
16532 (when (re-search-forward clrgx nil t)
16533 (goto-char (match-beginning 1))
16534 (let (org-clock-adjust-closest)
16535 (org-timestamp-change n org-ts-what updown))
16536 (message "Clock adjusted in %s for heading: %s"
16537 (file-name-nondirectory (buffer-file-name))
16538 (org-get-heading t t)))))))))
16539 ;; Try to recenter the calendar window, if any.
16540 (if (and org-calendar-follow-timestamp-change
16541 (get-buffer-window "*Calendar*" t)
16542 (memq org-ts-what '(day month year)))
16543 (org-recenter-calendar (time-to-days time))))))
16545 (defun org-modify-ts-extra (s pos n dm)
16546 "Change the different parts of the lead-time and repeat fields in timestamp."
16547 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16548 ng h m new rem)
16549 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16550 (cond
16551 ((or (org-pos-in-match-range pos 2)
16552 (org-pos-in-match-range pos 3))
16553 (setq m (string-to-number (match-string 3 s))
16554 h (string-to-number (match-string 2 s)))
16555 (if (org-pos-in-match-range pos 2)
16556 (setq h (+ h n))
16557 (setq n (* dm (org-no-warnings (signum n))))
16558 (when (not (= 0 (setq rem (% m dm))))
16559 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16560 (setq m (+ m n)))
16561 (if (< m 0) (setq m (+ m 60) h (1- h)))
16562 (if (> m 59) (setq m (- m 60) h (1+ h)))
16563 (setq h (min 24 (max 0 h)))
16564 (setq ng 1 new (format "-%02d:%02d" h m)))
16565 ((org-pos-in-match-range pos 6)
16566 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16567 ((org-pos-in-match-range pos 5)
16568 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16570 ((org-pos-in-match-range pos 9)
16571 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16572 ((org-pos-in-match-range pos 8)
16573 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16575 (when ng
16576 (setq s (concat
16577 (substring s 0 (match-beginning ng))
16579 (substring s (match-end ng))))))
16582 (defun org-recenter-calendar (date)
16583 "If the calendar is visible, recenter it to DATE."
16584 (let ((cwin (get-buffer-window "*Calendar*" t)))
16585 (when cwin
16586 (let ((calendar-move-hook nil))
16587 (with-selected-window cwin
16588 (calendar-goto-date (if (listp date) date
16589 (calendar-gregorian-from-absolute date))))))))
16591 (defun org-goto-calendar (&optional arg)
16592 "Go to the Emacs calendar at the current date.
16593 If there is a time stamp in the current line, go to that date.
16594 A prefix ARG can be used to force the current date."
16595 (interactive "P")
16596 (let ((tsr org-ts-regexp) diff
16597 (calendar-move-hook nil)
16598 (calendar-view-holidays-initially-flag nil)
16599 (calendar-view-diary-initially-flag nil))
16600 (if (or (org-at-timestamp-p)
16601 (save-excursion
16602 (beginning-of-line 1)
16603 (looking-at (concat ".*" tsr))))
16604 (let ((d1 (time-to-days (current-time)))
16605 (d2 (time-to-days
16606 (org-time-string-to-time (match-string 1)))))
16607 (setq diff (- d2 d1))))
16608 (calendar)
16609 (calendar-goto-today)
16610 (if (and diff (not arg)) (calendar-forward-day diff))))
16612 (defun org-get-date-from-calendar ()
16613 "Return a list (month day year) of date at point in calendar."
16614 (with-current-buffer "*Calendar*"
16615 (save-match-data
16616 (calendar-cursor-to-date))))
16618 (defun org-date-from-calendar ()
16619 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16620 If there is already a time stamp at the cursor position, update it."
16621 (interactive)
16622 (if (org-at-timestamp-p t)
16623 (org-timestamp-change 0 'calendar)
16624 (let ((cal-date (org-get-date-from-calendar)))
16625 (org-insert-time-stamp
16626 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16628 (defun org-minutes-to-hh:mm-string (m)
16629 "Compute H:MM from a number of minutes."
16630 (let ((h (/ m 60)))
16631 (setq m (- m (* 60 h)))
16632 (format org-time-clocksum-format h m)))
16634 (defun org-hh:mm-string-to-minutes (s)
16635 "Convert a string H:MM to a number of minutes.
16636 If the string is just a number, interpret it as minutes.
16637 In fact, the first hh:mm or number in the string will be taken,
16638 there can be extra stuff in the string.
16639 If no number is found, the return value is 0."
16640 (cond
16641 ((integerp s) s)
16642 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16643 (+ (* (string-to-number (match-string 1 s)) 60)
16644 (string-to-number (match-string 2 s))))
16645 ((string-match "\\([0-9]+\\)" s)
16646 (string-to-number (match-string 1 s)))
16647 (t 0)))
16649 (defcustom org-effort-durations
16650 `(("h" . 60)
16651 ("d" . ,(* 60 8))
16652 ("w" . ,(* 60 8 5))
16653 ("m" . ,(* 60 8 5 4))
16654 ("y" . ,(* 60 8 5 40)))
16655 "Conversion factor to minutes for an effort modifier.
16657 Each entry has the form (MODIFIER . MINUTES).
16659 In an effort string, a number followed by MODIFIER is multiplied
16660 by the specified number of MINUTES to obtain an effort in
16661 minutes.
16663 For example, if the value of this variable is ((\"hours\" . 60)), then an
16664 effort string \"2hours\" is equivalent to 120 minutes."
16665 :group 'org-agenda
16666 :version "24.1"
16667 :type '(alist :key-type (string :tag "Modifier")
16668 :value-type (number :tag "Minutes")))
16670 (defcustom org-agenda-inhibit-startup t
16671 "Inhibit startup when preparing agenda buffers.
16672 When this variable is `t' (the default), the initialization of
16673 the Org agenda buffers is inhibited: e.g. the visibility state
16674 is not set, the tables are not re-aligned, etc."
16675 :type 'boolean
16676 :version "24.3"
16677 :group 'org-agenda)
16679 (defun org-duration-string-to-minutes (s &optional output-to-string)
16680 "Convert a duration string S to minutes.
16682 A bare number is interpreted as minutes, modifiers can be set by
16683 customizing `org-effort-durations' (which see).
16685 Entries containing a colon are interpreted as H:MM by
16686 `org-hh:mm-string-to-minutes'."
16687 (let ((result 0)
16688 (re (concat "\\([0-9.]+\\) *\\("
16689 (regexp-opt (mapcar 'car org-effort-durations))
16690 "\\)")))
16691 (while (string-match re s)
16692 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16693 (string-to-number (match-string 1 s))))
16694 (setq s (replace-match "" nil t s)))
16695 (setq result (floor result))
16696 (incf result (org-hh:mm-string-to-minutes s))
16697 (if output-to-string (number-to-string result) result)))
16699 ;;;; Files
16701 (defun org-save-all-org-buffers ()
16702 "Save all Org-mode buffers without user confirmation."
16703 (interactive)
16704 (message "Saving all Org-mode buffers...")
16705 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16706 (when (featurep 'org-id) (org-id-locations-save))
16707 (message "Saving all Org-mode buffers... done"))
16709 (defun org-revert-all-org-buffers ()
16710 "Revert all Org-mode buffers.
16711 Prompt for confirmation when there are unsaved changes.
16712 Be sure you know what you are doing before letting this function
16713 overwrite your changes.
16715 This function is useful in a setup where one tracks org files
16716 with a version control system, to revert on one machine after pulling
16717 changes from another. I believe the procedure must be like this:
16719 1. M-x org-save-all-org-buffers
16720 2. Pull changes from the other machine, resolve conflicts
16721 3. M-x org-revert-all-org-buffers"
16722 (interactive)
16723 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16724 (error "Abort"))
16725 (save-excursion
16726 (save-window-excursion
16727 (mapc
16728 (lambda (b)
16729 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16730 (with-current-buffer b buffer-file-name))
16731 (org-pop-to-buffer-same-window b)
16732 (revert-buffer t 'no-confirm)))
16733 (buffer-list))
16734 (when (and (featurep 'org-id) org-id-track-globally)
16735 (org-id-locations-load)))))
16737 ;;;; Agenda files
16739 ;;;###autoload
16740 (defun org-switchb (&optional arg)
16741 "Switch between Org buffers.
16742 With one prefix argument, restrict available buffers to files.
16743 With two prefix arguments, restrict available buffers to agenda files.
16745 Defaults to `iswitchb' for buffer name completion.
16746 Set `org-completion-use-ido' to make it use ido instead."
16747 (interactive "P")
16748 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16749 ((equal arg '(16)) (org-buffer-list 'agenda))
16750 (t (org-buffer-list))))
16751 (org-completion-use-iswitchb org-completion-use-iswitchb)
16752 (org-completion-use-ido org-completion-use-ido))
16753 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16754 (setq org-completion-use-iswitchb t))
16755 (org-pop-to-buffer-same-window
16756 (org-icompleting-read "Org buffer: "
16757 (mapcar 'list (mapcar 'buffer-name blist))
16758 nil t))))
16760 ;;; Define some older names previously used for this functionality
16761 ;;;###autoload
16762 (defalias 'org-ido-switchb 'org-switchb)
16763 ;;;###autoload
16764 (defalias 'org-iswitchb 'org-switchb)
16766 (defun org-buffer-list (&optional predicate exclude-tmp)
16767 "Return a list of Org buffers.
16768 PREDICATE can be `export', `files' or `agenda'.
16770 export restrict the list to Export buffers.
16771 files restrict the list to buffers visiting Org files.
16772 agenda restrict the list to buffers visiting agenda files.
16774 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16775 (let* ((bfn nil)
16776 (agenda-files (and (eq predicate 'agenda)
16777 (mapcar 'file-truename (org-agenda-files t))))
16778 (filter
16779 (cond
16780 ((eq predicate 'files)
16781 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16782 ((eq predicate 'export)
16783 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16784 ((eq predicate 'agenda)
16785 (lambda (b)
16786 (with-current-buffer b
16787 (and (derived-mode-p 'org-mode)
16788 (setq bfn (buffer-file-name b))
16789 (member (file-truename bfn) agenda-files)))))
16790 (t (lambda (b) (with-current-buffer b
16791 (or (derived-mode-p 'org-mode)
16792 (string-match "\*Org .*Export"
16793 (buffer-name b)))))))))
16794 (delq nil
16795 (mapcar
16796 (lambda(b)
16797 (if (and (funcall filter b)
16798 (or (not exclude-tmp)
16799 (not (string-match "tmp" (buffer-name b)))))
16801 nil))
16802 (buffer-list)))))
16804 (defun org-agenda-files (&optional unrestricted archives)
16805 "Get the list of agenda files.
16806 Optional UNRESTRICTED means return the full list even if a restriction
16807 is currently in place.
16808 When ARCHIVES is t, include all archive files that are really being
16809 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16810 `org-agenda-archives-mode' is t."
16811 (let ((files
16812 (cond
16813 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16814 ((stringp org-agenda-files) (org-read-agenda-file-list))
16815 ((listp org-agenda-files) org-agenda-files)
16816 (t (error "Invalid value of `org-agenda-files'")))))
16817 (setq files (apply 'append
16818 (mapcar (lambda (f)
16819 (if (file-directory-p f)
16820 (directory-files
16821 f t org-agenda-file-regexp)
16822 (list f)))
16823 files)))
16824 (when org-agenda-skip-unavailable-files
16825 (setq files (delq nil
16826 (mapcar (function
16827 (lambda (file)
16828 (and (file-readable-p file) file)))
16829 files))))
16830 (when (or (eq archives t)
16831 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16832 (setq files (org-add-archive-files files)))
16833 files))
16835 (defun org-agenda-file-p (&optional file)
16836 "Return non-nil, if FILE is an agenda file.
16837 If FILE is omitted, use the file associated with the current
16838 buffer."
16839 (member (or file (buffer-file-name))
16840 (org-agenda-files t)))
16842 (defun org-edit-agenda-file-list ()
16843 "Edit the list of agenda files.
16844 Depending on setup, this either uses customize to edit the variable
16845 `org-agenda-files', or it visits the file that is holding the list. In the
16846 latter case, the buffer is set up in a way that saving it automatically kills
16847 the buffer and restores the previous window configuration."
16848 (interactive)
16849 (if (stringp org-agenda-files)
16850 (let ((cw (current-window-configuration)))
16851 (find-file org-agenda-files)
16852 (org-set-local 'org-window-configuration cw)
16853 (org-add-hook 'after-save-hook
16854 (lambda ()
16855 (set-window-configuration
16856 (prog1 org-window-configuration
16857 (kill-buffer (current-buffer))))
16858 (org-install-agenda-files-menu)
16859 (message "New agenda file list installed"))
16860 nil 'local)
16861 (message "%s" (substitute-command-keys
16862 "Edit list and finish with \\[save-buffer]")))
16863 (customize-variable 'org-agenda-files)))
16865 (defun org-store-new-agenda-file-list (list)
16866 "Set new value for the agenda file list and save it correctly."
16867 (if (stringp org-agenda-files)
16868 (let ((fe (org-read-agenda-file-list t)) b u)
16869 (while (setq b (find-buffer-visiting org-agenda-files))
16870 (kill-buffer b))
16871 (with-temp-file org-agenda-files
16872 (insert
16873 (mapconcat
16874 (lambda (f) ;; Keep un-expanded entries.
16875 (if (setq u (assoc f fe))
16876 (cdr u)
16878 list "\n")
16879 "\n")))
16880 (let ((org-mode-hook nil) (org-inhibit-startup t)
16881 (org-insert-mode-line-in-empty-file nil))
16882 (setq org-agenda-files list)
16883 (customize-save-variable 'org-agenda-files org-agenda-files))))
16885 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16886 "Read the list of agenda files from a file.
16887 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16888 filenames, used by `org-store-new-agenda-file-list' to write back
16889 un-expanded file names."
16890 (when (file-directory-p org-agenda-files)
16891 (error "`org-agenda-files' cannot be a single directory"))
16892 (when (stringp org-agenda-files)
16893 (with-temp-buffer
16894 (insert-file-contents org-agenda-files)
16895 (mapcar
16896 (lambda (f)
16897 (let ((e (expand-file-name (substitute-in-file-name f)
16898 org-directory)))
16899 (if pair-with-expansion
16900 (cons e f)
16901 e)))
16902 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16904 ;;;###autoload
16905 (defun org-cycle-agenda-files ()
16906 "Cycle through the files in `org-agenda-files'.
16907 If the current buffer visits an agenda file, find the next one in the list.
16908 If the current buffer does not, find the first agenda file."
16909 (interactive)
16910 (let* ((fs (org-agenda-files t))
16911 (files (append fs (list (car fs))))
16912 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16913 file)
16914 (unless files (error "No agenda files"))
16915 (catch 'exit
16916 (while (setq file (pop files))
16917 (if (equal (file-truename file) tcf)
16918 (when (car files)
16919 (find-file (car files))
16920 (throw 'exit t))))
16921 (find-file (car fs)))
16922 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16924 (defun org-agenda-file-to-front (&optional to-end)
16925 "Move/add the current file to the top of the agenda file list.
16926 If the file is not present in the list, it is added to the front. If it is
16927 present, it is moved there. With optional argument TO-END, add/move to the
16928 end of the list."
16929 (interactive "P")
16930 (let ((org-agenda-skip-unavailable-files nil)
16931 (file-alist (mapcar (lambda (x)
16932 (cons (file-truename x) x))
16933 (org-agenda-files t)))
16934 (ctf (file-truename
16935 (or buffer-file-name
16936 (error "Please save the current buffer to a file"))))
16937 x had)
16938 (setq x (assoc ctf file-alist) had x)
16940 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16941 (if to-end
16942 (setq file-alist (append (delq x file-alist) (list x)))
16943 (setq file-alist (cons x (delq x file-alist))))
16944 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16945 (org-install-agenda-files-menu)
16946 (message "File %s to %s of agenda file list"
16947 (if had "moved" "added") (if to-end "end" "front"))))
16949 (defun org-remove-file (&optional file)
16950 "Remove current file from the list of files in variable `org-agenda-files'.
16951 These are the files which are being checked for agenda entries.
16952 Optional argument FILE means use this file instead of the current."
16953 (interactive)
16954 (let* ((org-agenda-skip-unavailable-files nil)
16955 (file (or file buffer-file-name
16956 (error "Current buffer does not visit a file")))
16957 (true-file (file-truename file))
16958 (afile (abbreviate-file-name file))
16959 (files (delq nil (mapcar
16960 (lambda (x)
16961 (if (equal true-file
16962 (file-truename x))
16963 nil x))
16964 (org-agenda-files t)))))
16965 (if (not (= (length files) (length (org-agenda-files t))))
16966 (progn
16967 (org-store-new-agenda-file-list files)
16968 (org-install-agenda-files-menu)
16969 (message "Removed file: %s" afile))
16970 (message "File was not in list: %s (not removed)" afile))))
16972 (defun org-file-menu-entry (file)
16973 (vector file (list 'find-file file) t))
16975 (defun org-check-agenda-file (file)
16976 "Make sure FILE exists. If not, ask user what to do."
16977 (when (not (file-exists-p file))
16978 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
16979 (abbreviate-file-name file))
16980 (let ((r (downcase (read-char-exclusive))))
16981 (cond
16982 ((equal r ?r)
16983 (org-remove-file file)
16984 (throw 'nextfile t))
16985 (t (error "Abort"))))))
16987 (defun org-get-agenda-file-buffer (file)
16988 "Get a buffer visiting FILE. If the buffer needs to be created, add
16989 it to the list of buffers which might be released later."
16990 (let ((buf (org-find-base-buffer-visiting file)))
16991 (if buf
16992 buf ; just return it
16993 ;; Make a new buffer and remember it
16994 (setq buf (find-file-noselect file))
16995 (if buf (push buf org-agenda-new-buffers))
16996 buf)))
16998 (defun org-release-buffers (blist)
16999 "Release all buffers in list, asking the user for confirmation when needed.
17000 When a buffer is unmodified, it is just killed. When modified, it is saved
17001 \(if the user agrees) and then killed."
17002 (let (buf file)
17003 (while (setq buf (pop blist))
17004 (setq file (buffer-file-name buf))
17005 (when (and (buffer-modified-p buf)
17006 file
17007 (y-or-n-p (format "Save file %s? " file)))
17008 (with-current-buffer buf (save-buffer)))
17009 (kill-buffer buf))))
17011 (defun org-agenda-prepare-buffers (files)
17012 "Create buffers for all agenda files, protect archived trees and comments."
17013 (interactive)
17014 (let ((pa '(:org-archived t))
17015 (pc '(:org-comment t))
17016 (pall '(:org-archived t :org-comment t))
17017 (inhibit-read-only t)
17018 (org-inhibit-startup org-agenda-inhibit-startup)
17019 (rea (concat ":" org-archive-tag ":"))
17020 bmp file re)
17021 (save-excursion
17022 (save-restriction
17023 (while (setq file (pop files))
17024 (catch 'nextfile
17025 (if (bufferp file)
17026 (set-buffer file)
17027 (org-check-agenda-file file)
17028 (set-buffer (org-get-agenda-file-buffer file)))
17029 (widen)
17030 (setq bmp (buffer-modified-p))
17031 (org-refresh-category-properties)
17032 (org-refresh-properties org-effort-property 'org-effort)
17033 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17034 (setq org-todo-keywords-for-agenda
17035 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17036 (setq org-done-keywords-for-agenda
17037 (append org-done-keywords-for-agenda org-done-keywords))
17038 (setq org-todo-keyword-alist-for-agenda
17039 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17040 (setq org-drawers-for-agenda
17041 (append org-drawers-for-agenda org-drawers))
17042 (setq org-tag-alist-for-agenda
17043 (append org-tag-alist-for-agenda org-tag-alist))
17045 (save-excursion
17046 (remove-text-properties (point-min) (point-max) pall)
17047 (when org-agenda-skip-archived-trees
17048 (goto-char (point-min))
17049 (while (re-search-forward rea nil t)
17050 (if (org-at-heading-p t)
17051 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17052 (goto-char (point-min))
17053 (setq re (format org-heading-keyword-regexp-format
17054 org-comment-string))
17055 (while (re-search-forward re nil t)
17056 (add-text-properties
17057 (match-beginning 0) (org-end-of-subtree t) pc)))
17058 (set-buffer-modified-p bmp)))))
17059 (setq org-todo-keywords-for-agenda
17060 (org-uniquify org-todo-keywords-for-agenda))
17061 (setq org-todo-keyword-alist-for-agenda
17062 (org-uniquify org-todo-keyword-alist-for-agenda)
17063 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17065 ;;;; Embedded LaTeX
17067 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17068 "Keymap for the minor `org-cdlatex-mode'.")
17070 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17071 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17072 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17073 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17074 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17076 (defvar org-cdlatex-texmathp-advice-is-done nil
17077 "Flag remembering if we have applied the advice to texmathp already.")
17079 (define-minor-mode org-cdlatex-mode
17080 "Toggle the minor `org-cdlatex-mode'.
17081 This mode supports entering LaTeX environment and math in LaTeX fragments
17082 in Org-mode.
17083 \\{org-cdlatex-mode-map}"
17084 nil " OCDL" nil
17085 (when org-cdlatex-mode
17086 (require 'cdlatex)
17087 (run-hooks 'cdlatex-mode-hook)
17088 (cdlatex-compute-tables))
17089 (unless org-cdlatex-texmathp-advice-is-done
17090 (setq org-cdlatex-texmathp-advice-is-done t)
17091 (defadvice texmathp (around org-math-always-on activate)
17092 "Always return t in org-mode buffers.
17093 This is because we want to insert math symbols without dollars even outside
17094 the LaTeX math segments. If Orgmode thinks that point is actually inside
17095 an embedded LaTeX fragment, let texmathp do its job.
17096 \\[org-cdlatex-mode-map]"
17097 (interactive)
17098 (let (p)
17099 (cond
17100 ((not (derived-mode-p 'org-mode)) ad-do-it)
17101 ((eq this-command 'cdlatex-math-symbol)
17102 (setq ad-return-value t
17103 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17105 (let ((p (org-inside-LaTeX-fragment-p)))
17106 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17107 (setq ad-return-value t
17108 texmathp-why '("Org-mode embedded math" . 0))
17109 (if p ad-do-it)))))))))
17111 (defun turn-on-org-cdlatex ()
17112 "Unconditionally turn on `org-cdlatex-mode'."
17113 (org-cdlatex-mode 1))
17115 (defun org-inside-LaTeX-fragment-p ()
17116 "Test if point is inside a LaTeX fragment.
17117 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17118 sequence appearing also before point.
17119 Even though the matchers for math are configurable, this function assumes
17120 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17121 delimiters are skipped when they have been removed by customization.
17122 The return value is nil, or a cons cell with the delimiter and the
17123 position of this delimiter.
17125 This function does a reasonably good job, but can locally be fooled by
17126 for example currency specifications. For example it will assume being in
17127 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17128 fragments that are properly closed, but during editing, we have to live
17129 with the uncertainty caused by missing closing delimiters. This function
17130 looks only before point, not after."
17131 (catch 'exit
17132 (let ((pos (point))
17133 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17134 (lim (progn
17135 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17136 (point)))
17137 dd-on str (start 0) m re)
17138 (goto-char pos)
17139 (when dodollar
17140 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17141 re (nth 1 (assoc "$" org-latex-regexps)))
17142 (while (string-match re str start)
17143 (cond
17144 ((= (match-end 0) (length str))
17145 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17146 ((= (match-end 0) (- (length str) 5))
17147 (throw 'exit nil))
17148 (t (setq start (match-end 0))))))
17149 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17150 (goto-char pos)
17151 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17152 (and (match-beginning 2) (throw 'exit nil))
17153 ;; count $$
17154 (while (re-search-backward "\\$\\$" lim t)
17155 (setq dd-on (not dd-on)))
17156 (goto-char pos)
17157 (if dd-on (cons "$$" m))))))
17159 (defun org-inside-latex-macro-p ()
17160 "Is point inside a LaTeX macro or its arguments?"
17161 (save-match-data
17162 (org-in-regexp
17163 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17165 (defun org-try-cdlatex-tab ()
17166 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17167 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17168 - inside a LaTeX fragment, or
17169 - after the first word in a line, where an abbreviation expansion could
17170 insert a LaTeX environment."
17171 (when org-cdlatex-mode
17172 (cond
17173 ;; Before any word on the line: No expansion possible.
17174 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17175 ;; Just after first word on the line: Expand it. Make sure it
17176 ;; cannot happen on headlines, though.
17177 ((save-excursion
17178 (skip-chars-backward "a-zA-Z0-9*")
17179 (skip-chars-backward " \t")
17180 (and (bolp) (not (org-at-heading-p))))
17181 (cdlatex-tab) t)
17182 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17184 (defun org-cdlatex-underscore-caret (&optional arg)
17185 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17186 Revert to the normal definition outside of these fragments."
17187 (interactive "P")
17188 (if (org-inside-LaTeX-fragment-p)
17189 (call-interactively 'cdlatex-sub-superscript)
17190 (let (org-cdlatex-mode)
17191 (call-interactively (key-binding (vector last-input-event))))))
17193 (defun org-cdlatex-math-modify (&optional arg)
17194 "Execute `cdlatex-math-modify' in LaTeX fragments.
17195 Revert to the normal definition outside of these fragments."
17196 (interactive "P")
17197 (if (org-inside-LaTeX-fragment-p)
17198 (call-interactively 'cdlatex-math-modify)
17199 (let (org-cdlatex-mode)
17200 (call-interactively (key-binding (vector last-input-event))))))
17202 (defvar org-latex-fragment-image-overlays nil
17203 "List of overlays carrying the images of latex fragments.")
17204 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17206 (defun org-remove-latex-fragment-image-overlays ()
17207 "Remove all overlays with LaTeX fragment images in current buffer."
17208 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17209 (setq org-latex-fragment-image-overlays nil))
17211 (defun org-preview-latex-fragment (&optional subtree)
17212 "Preview the LaTeX fragment at point, or all locally or globally.
17213 If the cursor is in a LaTeX fragment, create the image and overlay
17214 it over the source code. If there is no fragment at point, display
17215 all fragments in the current text, from one headline to the next. With
17216 prefix SUBTREE, display all fragments in the current subtree. With a
17217 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17218 the cursor is before the first headline,
17219 display all fragments in the buffer.
17220 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17221 (interactive "P")
17222 (unless buffer-file-name
17223 (error "Can't preview LaTeX fragment in a non-file buffer"))
17224 (org-remove-latex-fragment-image-overlays)
17225 (save-excursion
17226 (save-restriction
17227 (let (beg end at msg)
17228 (cond
17229 ((or (equal subtree '(16))
17230 (not (save-excursion
17231 (re-search-backward org-outline-regexp-bol nil t))))
17232 (setq beg (point-min) end (point-max)
17233 msg "Creating images for buffer...%s"))
17234 ((equal subtree '(4))
17235 (org-back-to-heading)
17236 (setq beg (point) end (org-end-of-subtree t)
17237 msg "Creating images for subtree...%s"))
17239 (if (setq at (org-inside-LaTeX-fragment-p))
17240 (goto-char (max (point-min) (- (cdr at) 2)))
17241 (org-back-to-heading))
17242 (setq beg (point) end (progn (outline-next-heading) (point))
17243 msg (if at "Creating image...%s"
17244 "Creating images for entry...%s"))))
17245 (message msg "")
17246 (narrow-to-region beg end)
17247 (goto-char beg)
17248 (org-format-latex
17249 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17250 (file-name-nondirectory
17251 buffer-file-name)))
17252 default-directory 'overlays msg at 'forbuffer
17253 org-latex-create-formula-image-program)
17254 (message msg "done. Use `C-c C-c' to remove images.")))))
17256 (defvar org-latex-regexps
17257 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17258 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17259 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17260 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17261 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17262 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17263 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17264 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17265 "Regular expressions for matching embedded LaTeX.")
17267 (defvar org-export-have-math nil) ;; dynamic scoping
17268 (defun org-format-latex (prefix &optional dir overlays msg at
17269 forbuffer processing-type)
17270 "Replace LaTeX fragments with links to an image, and produce images.
17271 Some of the options can be changed using the variable
17272 `org-format-latex-options'."
17273 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17274 (let* ((prefixnodir (file-name-nondirectory prefix))
17275 (absprefix (expand-file-name prefix dir))
17276 (todir (file-name-directory absprefix))
17277 (opt org-format-latex-options)
17278 (matchers (plist-get opt :matchers))
17279 (re-list org-latex-regexps)
17280 (org-format-latex-header-extra
17281 (plist-get (org-infile-export-plist) :latex-header-extra))
17282 (cnt 0) txt hash link beg end re e checkdir
17283 executables-checked string
17284 m n block-type block linkfile movefile ov)
17285 ;; Check the different regular expressions
17286 (while (setq e (pop re-list))
17287 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17288 block (if block-type "\n\n" ""))
17289 (when (member m matchers)
17290 (goto-char (point-min))
17291 (while (re-search-forward re nil t)
17292 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17293 (not (get-text-property (match-beginning n)
17294 'org-protected))
17295 (or (not overlays)
17296 (not (eq (get-char-property (match-beginning n)
17297 'org-overlay-type)
17298 'org-latex-overlay))))
17299 (setq org-export-have-math t)
17300 (cond
17301 ((eq processing-type 'verbatim)
17302 ;; Leave the text verbatim, just protect it
17303 (add-text-properties (match-beginning n) (match-end n)
17304 '(org-protected t)))
17305 ((eq processing-type 'mathjax)
17306 ;; Prepare for MathJax processing
17307 (setq string (match-string n))
17308 (if (member m '("$" "$1"))
17309 (save-excursion
17310 (delete-region (match-beginning n) (match-end n))
17311 (goto-char (match-beginning n))
17312 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17313 "\\)")
17314 '(org-protected t))))
17315 (add-text-properties (match-beginning n) (match-end n)
17316 '(org-protected t))))
17317 ((or (eq processing-type 'dvipng)
17318 (eq processing-type 'imagemagick))
17319 ;; Process to an image
17320 (setq txt (match-string n)
17321 beg (match-beginning n) end (match-end n)
17322 cnt (1+ cnt))
17323 (let (print-length print-level) ; make sure full list is printed
17324 (setq hash (sha1 (prin1-to-string
17325 (list org-format-latex-header
17326 org-format-latex-header-extra
17327 org-export-latex-default-packages-alist
17328 org-export-latex-packages-alist
17329 org-format-latex-options
17330 forbuffer txt)))
17331 linkfile (format "%s_%s.png" prefix hash)
17332 movefile (format "%s_%s.png" absprefix hash)))
17333 (setq link (concat block "[[file:" linkfile "]]" block))
17334 (if msg (message msg cnt))
17335 (goto-char beg)
17336 (unless checkdir ; make sure the directory exists
17337 (setq checkdir t)
17338 (or (file-directory-p todir) (make-directory todir t)))
17339 (cond
17340 ((eq processing-type 'dvipng)
17341 (unless executables-checked
17342 (org-check-external-command
17343 "latex" "needed to convert LaTeX fragments to images")
17344 (org-check-external-command
17345 "dvipng" "needed to convert LaTeX fragments to images")
17346 (setq executables-checked t))
17347 (unless (file-exists-p movefile)
17348 (org-create-formula-image-with-dvipng
17349 txt movefile opt forbuffer)))
17350 ((eq processing-type 'imagemagick)
17351 (unless executables-checked
17352 (org-check-external-command
17353 "convert" "you need to install imagemagick")
17354 (setq executables-checked t))
17355 (unless (file-exists-p movefile)
17356 (org-create-formula-image-with-imagemagick
17357 txt movefile opt forbuffer))))
17358 (if overlays
17359 (progn
17360 (mapc (lambda (o)
17361 (if (eq (overlay-get o 'org-overlay-type)
17362 'org-latex-overlay)
17363 (delete-overlay o)))
17364 (overlays-in beg end))
17365 (setq ov (make-overlay beg end))
17366 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17367 (if (featurep 'xemacs)
17368 (progn
17369 (overlay-put ov 'invisible t)
17370 (overlay-put
17371 ov 'end-glyph
17372 (make-glyph (vector 'png :file movefile))))
17373 (overlay-put
17374 ov 'display
17375 (list 'image :type 'png :file movefile :ascent 'center)))
17376 (push ov org-latex-fragment-image-overlays)
17377 (goto-char end))
17378 (delete-region beg end)
17379 (insert (org-add-props link
17380 (list 'org-latex-src
17381 (replace-regexp-in-string
17382 "\"" "" txt)
17383 'org-latex-src-embed-type
17384 (if block-type 'paragraph 'character))))))
17385 ((eq processing-type 'mathml)
17386 ;; Process to MathML
17387 (unless executables-checked
17388 (unless (save-match-data (org-format-latex-mathml-available-p))
17389 (error "LaTeX to MathML converter not configured"))
17390 (setq executables-checked t))
17391 (setq txt (match-string n)
17392 beg (match-beginning n) end (match-end n)
17393 cnt (1+ cnt))
17394 (if msg (message msg cnt))
17395 (goto-char beg)
17396 (delete-region beg end)
17397 (insert (org-format-latex-as-mathml
17398 txt block-type prefix dir)))
17400 (error "Unknown conversion type %s for latex fragments"
17401 processing-type)))))))))
17403 (defun org-create-math-formula (latex-frag &optional mathml-file)
17404 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17405 Use `org-latex-to-mathml-convert-command'. If the conversion is
17406 sucessful, return the portion between \"<math...> </math>\"
17407 elements otherwise return nil. When MATHML-FILE is specified,
17408 write the results in to that file. When invoked as an
17409 interactive command, prompt for LATEX-FRAG, with initial value
17410 set to the current active region and echo the results for user
17411 inspection."
17412 (interactive (list (let ((frag (when (org-region-active-p)
17413 (buffer-substring-no-properties
17414 (region-beginning) (region-end)))))
17415 (read-string "LaTeX Fragment: " frag nil frag))))
17416 (unless latex-frag (error "Invalid latex-frag"))
17417 (let* ((tmp-in-file (file-relative-name
17418 (make-temp-name (expand-file-name "ltxmathml-in"))))
17419 (ignore (write-region latex-frag nil tmp-in-file))
17420 (tmp-out-file (file-relative-name
17421 (make-temp-name (expand-file-name "ltxmathml-out"))))
17422 (cmd (format-spec
17423 org-latex-to-mathml-convert-command
17424 `((?j . ,(shell-quote-argument
17425 (expand-file-name org-latex-to-mathml-jar-file)))
17426 (?I . ,(shell-quote-argument tmp-in-file))
17427 (?o . ,(shell-quote-argument tmp-out-file)))))
17428 mathml shell-command-output)
17429 (when (org-called-interactively-p 'any)
17430 (unless (org-format-latex-mathml-available-p)
17431 (error "LaTeX to MathML converter not configured")))
17432 (message "Running %s" cmd)
17433 (setq shell-command-output (shell-command-to-string cmd))
17434 (setq mathml
17435 (when (file-readable-p tmp-out-file)
17436 (with-current-buffer (find-file-noselect tmp-out-file t)
17437 (goto-char (point-min))
17438 (when (re-search-forward
17439 (concat
17440 (regexp-quote
17441 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17442 "\\(.\\|\n\\)*"
17443 (regexp-quote "</math>")) nil t)
17444 (prog1 (match-string 0) (kill-buffer))))))
17445 (cond
17446 (mathml
17447 (setq mathml
17448 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17449 (when mathml-file
17450 (write-region mathml nil mathml-file))
17451 (when (org-called-interactively-p 'any)
17452 (message mathml)))
17453 ((message "LaTeX to MathML conversion failed")
17454 (message shell-command-output)))
17455 (delete-file tmp-in-file)
17456 (when (file-exists-p tmp-out-file)
17457 (delete-file tmp-out-file))
17458 mathml))
17460 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17461 prefix &optional dir)
17462 "Use `org-create-math-formula' but check local cache first."
17463 (let* ((absprefix (expand-file-name prefix dir))
17464 (print-length nil) (print-level nil)
17465 (formula-id (concat
17466 "formula-"
17467 (sha1
17468 (prin1-to-string
17469 (list latex-frag
17470 org-latex-to-mathml-convert-command)))))
17471 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17472 (formula-cache-dir (file-name-directory formula-cache)))
17474 (unless (file-directory-p formula-cache-dir)
17475 (make-directory formula-cache-dir t))
17477 (unless (file-exists-p formula-cache)
17478 (org-create-math-formula latex-frag formula-cache))
17480 (if (file-exists-p formula-cache)
17481 ;; Successful conversion. Return the link to MathML file.
17482 (org-add-props
17483 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17484 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17485 'org-latex-src-embed-type (if latex-frag-type
17486 'paragraph 'character)))
17487 ;; Failed conversion. Return the LaTeX fragment verbatim
17488 (add-text-properties
17489 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17490 latex-frag)))
17492 ;; This function borrows from Ganesh Swami's latex2png.el
17493 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17494 "This calls dvipng."
17495 (require 'org-latex)
17496 (let* ((tmpdir (if (featurep 'xemacs)
17497 (temp-directory)
17498 temporary-file-directory))
17499 (texfilebase (make-temp-name
17500 (expand-file-name "orgtex" tmpdir)))
17501 (texfile (concat texfilebase ".tex"))
17502 (dvifile (concat texfilebase ".dvi"))
17503 (pngfile (concat texfilebase ".png"))
17504 (fnh (if (featurep 'xemacs)
17505 (font-height (face-font 'default))
17506 (face-attribute 'default :height nil)))
17507 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17508 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17509 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17510 "Black"))
17511 (bg (or (plist-get options (if buffer :background :html-background))
17512 "Transparent")))
17513 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17514 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17515 (with-temp-file texfile
17516 (insert (org-splice-latex-header
17517 org-format-latex-header
17518 org-export-latex-default-packages-alist
17519 org-export-latex-packages-alist t
17520 org-format-latex-header-extra))
17521 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17522 (require 'org-latex)
17523 (org-export-latex-fix-inputenc))
17524 (let ((dir default-directory))
17525 (condition-case nil
17526 (progn
17527 (cd tmpdir)
17528 (call-process "latex" nil nil nil texfile))
17529 (error nil))
17530 (cd dir))
17531 (if (not (file-exists-p dvifile))
17532 (progn (message "Failed to create dvi file from %s" texfile) nil)
17533 (condition-case nil
17534 (if (featurep 'xemacs)
17535 (call-process "dvipng" nil nil nil
17536 "-fg" fg "-bg" bg
17537 "-T" "tight"
17538 "-o" pngfile
17539 dvifile)
17540 (call-process "dvipng" nil nil nil
17541 "-fg" fg "-bg" bg
17542 "-D" dpi
17543 ;;"-x" scale "-y" scale
17544 "-T" "tight"
17545 "-o" pngfile
17546 dvifile))
17547 (error nil))
17548 (if (not (file-exists-p pngfile))
17549 (if org-format-latex-signal-error
17550 (error "Failed to create png file from %s" texfile)
17551 (message "Failed to create png file from %s" texfile)
17552 nil)
17553 ;; Use the requested file name and clean up
17554 (copy-file pngfile tofile 'replace)
17555 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17556 (if (file-exists-p (concat texfilebase e))
17557 (delete-file (concat texfilebase e))))
17558 pngfile))))
17560 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17561 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17562 "This calls convert, which is included into imagemagick."
17563 (require 'org-latex)
17564 (let* ((tmpdir (if (featurep 'xemacs)
17565 (temp-directory)
17566 temporary-file-directory))
17567 (texfilebase (make-temp-name
17568 (expand-file-name "orgtex" tmpdir)))
17569 (texfile (concat texfilebase ".tex"))
17570 (pdffile (concat texfilebase ".pdf"))
17571 (pngfile (concat texfilebase ".png"))
17572 (fnh (if (featurep 'xemacs)
17573 (font-height (face-font 'default))
17574 (face-attribute 'default :height nil)))
17575 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17576 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17577 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17578 "black"))
17579 (bg (or (plist-get options (if buffer :background :html-background))
17580 "white")))
17581 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17582 (setq fg (org-latex-color-format fg)))
17583 (if (eq bg 'default) (setq bg (org-latex-color :background))
17584 (setq bg (org-latex-color-format
17585 (if (string= bg "Transparent")(setq bg "white")))))
17586 (with-temp-file texfile
17587 (insert (org-splice-latex-header
17588 org-format-latex-header
17589 org-export-latex-default-packages-alist
17590 org-export-latex-packages-alist t
17591 org-format-latex-header-extra))
17592 (insert "\n\\begin{document}\n"
17593 "\\definecolor{fg}{rgb}{" fg "}\n"
17594 "\\definecolor{bg}{rgb}{" bg "}\n"
17595 "\n\\pagecolor{bg}\n"
17596 "\n{\\color{fg}\n"
17597 string
17598 "\n}\n"
17599 "\n\\end{document}\n" )
17600 (require 'org-latex)
17601 (org-export-latex-fix-inputenc))
17602 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17603 (condition-case nil
17604 (progn
17605 (cd tmpdir)
17606 (setq cmds org-latex-to-pdf-process)
17607 (while cmds
17608 (setq latex-frags-cmds (pop cmds))
17609 (if (listp latex-frags-cmds)
17610 (setq cmds nil)
17611 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17612 (while latex-frags-cmds
17613 (setq cmd (pop latex-frags-cmds))
17614 (while (string-match "%b" cmd)
17615 (setq cmd (replace-match
17616 (save-match-data
17617 (shell-quote-argument texfile))
17618 t t cmd)))
17619 (while (string-match "%f" cmd)
17620 (setq cmd (replace-match
17621 (save-match-data
17622 (shell-quote-argument (file-name-nondirectory texfile)))
17623 t t cmd)))
17624 (while (string-match "%o" cmd)
17625 (setq cmd (replace-match
17626 (save-match-data
17627 (shell-quote-argument (file-name-directory texfile)))
17628 t t cmd)))
17629 (setq cmd (split-string cmd))
17630 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17631 (error nil))
17632 (cd dir))
17633 (if (not (file-exists-p pdffile))
17634 (progn (message "Failed to create pdf file from %s" texfile) nil)
17635 (condition-case nil
17636 (if (featurep 'xemacs)
17637 (call-process "convert" nil nil nil
17638 "-density" "96"
17639 "-trim"
17640 "-antialias"
17641 pdffile
17642 "-quality" "100"
17643 ;; "-sharpen" "0x1.0"
17644 pngfile)
17645 (call-process "convert" nil nil nil
17646 "-density" dpi
17647 "-trim"
17648 "-antialias"
17649 pdffile
17650 "-quality" "100"
17651 ; "-sharpen" "0x1.0"
17652 pngfile))
17653 (error nil))
17654 (if (not (file-exists-p pngfile))
17655 (if org-format-latex-signal-error
17656 (error "Failed to create png file from %s" texfile)
17657 (message "Failed to create png file from %s" texfile)
17658 nil)
17659 ;; Use the requested file name and clean up
17660 (copy-file pngfile tofile 'replace)
17661 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17662 (if (file-exists-p (concat texfilebase e))
17663 (delete-file (concat texfilebase e))))
17664 pngfile))))
17666 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17667 "Fill a LaTeX header template TPL.
17668 In the template, the following place holders will be recognized:
17670 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17671 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17672 [PACKAGES] \\usepackage statements for PKG
17673 [NO-PACKAGES] do not include PKG
17674 [EXTRA] the string EXTRA
17675 [NO-EXTRA] do not include EXTRA
17677 For backward compatibility, if both the positive and the negative place
17678 holder is missing, the positive one (without the \"NO-\") will be
17679 assumed to be present at the end of the template.
17680 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17681 EXTRA is a string.
17682 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17683 (let (rpl (end ""))
17684 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17685 (setq rpl (if (or (match-end 1) (not def-pkg))
17686 "" (org-latex-packages-to-string def-pkg snippets-p t))
17687 tpl (replace-match rpl t t tpl))
17688 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17690 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17691 (setq rpl (if (or (match-end 1) (not pkg))
17692 "" (org-latex-packages-to-string pkg snippets-p t))
17693 tpl (replace-match rpl t t tpl))
17694 (if pkg (setq end
17695 (concat end "\n"
17696 (org-latex-packages-to-string pkg snippets-p)))))
17698 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17699 (setq rpl (if (or (match-end 1) (not extra))
17700 "" (concat extra "\n"))
17701 tpl (replace-match rpl t t tpl))
17702 (if (and extra (string-match "\\S-" extra))
17703 (setq end (concat end "\n" extra))))
17705 (if (string-match "\\S-" end)
17706 (concat tpl "\n" end)
17707 tpl)))
17709 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17710 "Turn an alist of packages into a string with the \\usepackage macros."
17711 (setq pkg (mapconcat (lambda(p)
17712 (cond
17713 ((stringp p) p)
17714 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17715 (format "%% Package %s omitted" (cadr p)))
17716 ((equal "" (car p))
17717 (format "\\usepackage{%s}" (cadr p)))
17719 (format "\\usepackage[%s]{%s}"
17720 (car p) (cadr p)))))
17722 "\n"))
17723 (if newline (concat pkg "\n") pkg))
17725 (defun org-dvipng-color (attr)
17726 "Return a RGB color specification for dvipng."
17727 (apply 'format "rgb %s %s %s"
17728 (mapcar 'org-normalize-color
17729 (if (featurep 'xemacs)
17730 (color-rgb-components
17731 (face-property 'default
17732 (cond ((eq attr :foreground) 'foreground)
17733 ((eq attr :background) 'background))))
17734 (color-values (face-attribute 'default attr nil))))))
17736 (defun org-latex-color (attr)
17737 "Return a RGB color for the LaTeX color package."
17738 (apply 'format "%s,%s,%s"
17739 (mapcar 'org-normalize-color
17740 (if (featurep 'xemacs)
17741 (color-rgb-components
17742 (face-property 'default
17743 (cond ((eq attr :foreground) 'foreground)
17744 ((eq attr :background) 'background))))
17745 (color-values (face-attribute 'default attr nil))))))
17747 (defun org-latex-color-format (color-name)
17748 "Convert COLOR-NAME to a RGB color value."
17749 (apply 'format "%s,%s,%s"
17750 (mapcar 'org-normalize-color
17751 (color-values color-name))))
17753 (defun org-normalize-color (value)
17754 "Return string to be used as color value for an RGB component."
17755 (format "%g" (/ value 65535.0)))
17757 ;; Image display
17760 (defvar org-inline-image-overlays nil)
17761 (make-variable-buffer-local 'org-inline-image-overlays)
17763 (defun org-toggle-inline-images (&optional include-linked)
17764 "Toggle the display of inline images.
17765 INCLUDE-LINKED is passed to `org-display-inline-images'."
17766 (interactive "P")
17767 (if org-inline-image-overlays
17768 (progn
17769 (org-remove-inline-images)
17770 (message "Inline image display turned off"))
17771 (org-display-inline-images include-linked)
17772 (if org-inline-image-overlays
17773 (message "%d images displayed inline"
17774 (length org-inline-image-overlays))
17775 (message "No images to display inline"))))
17777 (defun org-redisplay-inline-images ()
17778 "Refresh the display of inline images."
17779 (interactive)
17780 (if (not org-inline-image-overlays)
17781 (org-toggle-inline-images)
17782 (org-toggle-inline-images)
17783 (org-toggle-inline-images)))
17785 (defun org-display-inline-images (&optional include-linked refresh beg end)
17786 "Display inline images.
17787 Normally only links without a description part are inlined, because this
17788 is how it will work for export. When INCLUDE-LINKED is set, also links
17789 with a description part will be inlined. This can be nice for a quick
17790 look at those images, but it does not reflect what exported files will look
17791 like.
17792 When REFRESH is set, refresh existing images between BEG and END.
17793 This will create new image displays only if necessary.
17794 BEG and END default to the buffer boundaries."
17795 (interactive "P")
17796 (unless refresh
17797 (org-remove-inline-images)
17798 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17799 (save-excursion
17800 (save-restriction
17801 (widen)
17802 (setq beg (or beg (point-min)) end (or end (point-max)))
17803 (goto-char beg)
17804 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17805 (substring (org-image-file-name-regexp) 0 -2)
17806 "\\)\\]" (if include-linked "" "\\]")))
17807 old file ov img)
17808 (while (re-search-forward re end t)
17809 (setq old (get-char-property-and-overlay (match-beginning 1)
17810 'org-image-overlay))
17811 (setq file (expand-file-name
17812 (concat (or (match-string 3) "") (match-string 4))))
17813 (when (file-exists-p file)
17814 (if (and (car-safe old) refresh)
17815 (image-refresh (overlay-get (cdr old) 'display))
17816 (setq img (save-match-data (create-image file)))
17817 (when img
17818 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17819 (overlay-put ov 'display img)
17820 (overlay-put ov 'face 'default)
17821 (overlay-put ov 'org-image-overlay t)
17822 (overlay-put ov 'modification-hooks
17823 (list 'org-display-inline-remove-overlay))
17824 (push ov org-inline-image-overlays)))))))))
17826 (define-obsolete-function-alias
17827 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
17829 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
17830 "Remove inline-display overlay if a corresponding region is modified."
17831 (let ((inhibit-modification-hooks t))
17832 (when (and ov after)
17833 (delete ov org-inline-image-overlays)
17834 (delete-overlay ov))))
17836 (defun org-remove-inline-images ()
17837 "Remove inline display of images."
17838 (interactive)
17839 (mapc 'delete-overlay org-inline-image-overlays)
17840 (setq org-inline-image-overlays nil))
17842 ;;;; Key bindings
17844 ;; Outline functions from `outline-mode-prefix-map'
17845 ;; that can be remapped in Org:
17846 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17847 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17848 (define-key org-mode-map [remap outline-forward-same-level]
17849 'org-forward-heading-same-level)
17850 (define-key org-mode-map [remap outline-backward-same-level]
17851 'org-backward-heading-same-level)
17852 (define-key org-mode-map [remap show-branches]
17853 'org-kill-note-or-show-branches)
17854 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17855 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17856 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17858 ;; Outline functions from `outline-mode-prefix-map' that can not
17859 ;; be remapped in Org:
17861 ;; - the column "key binding" shows whether the Outline function is still
17862 ;; available in Org mode on the same key that it has been bound to in
17863 ;; Outline mode:
17864 ;; - "overridden": key used for a different functionality in Org mode
17865 ;; - else: key still bound to the same Outline function in Org mode
17867 ;; | Outline function | key binding | Org replacement |
17868 ;; |------------------------------------+-------------+-----------------------|
17869 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17870 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17871 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17872 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
17873 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17874 ;; | `show-entry' | overridden | no replacement |
17875 ;; | `show-children' | `C-c C-i' | visibility cycling |
17876 ;; | `show-branches' | `C-c C-k' | still same function |
17877 ;; | `show-subtree' | overridden | visibility cycling |
17878 ;; | `show-all' | overridden | no replacement |
17879 ;; | `hide-subtree' | overridden | visibility cycling |
17880 ;; | `hide-body' | overridden | no replacement |
17881 ;; | `hide-entry' | overridden | visibility cycling |
17882 ;; | `hide-leaves' | overridden | no replacement |
17883 ;; | `hide-sublevels' | overridden | no replacement |
17884 ;; | `hide-other' | overridden | no replacement |
17886 ;; Make `C-c C-x' a prefix key
17887 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17889 ;; TAB key with modifiers
17890 (org-defkey org-mode-map "\C-i" 'org-cycle)
17891 (org-defkey org-mode-map [(tab)] 'org-cycle)
17892 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17893 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17894 ;; The following line is necessary under Suse GNU/Linux
17895 (unless (featurep 'xemacs)
17896 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17897 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17898 (define-key org-mode-map [backtab] 'org-shifttab)
17900 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17901 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17902 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17904 ;; Cursor keys with modifiers
17905 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17906 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17907 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17908 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17910 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17911 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17912 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17913 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17915 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17916 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17917 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17918 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17920 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17921 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17922 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17923 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17925 ;; Babel keys
17926 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17927 (mapc (lambda (pair)
17928 (define-key org-babel-map (car pair) (cdr pair)))
17929 org-babel-key-bindings)
17931 ;;; Extra keys for tty access.
17932 ;; We only set them when really needed because otherwise the
17933 ;; menus don't show the simple keys
17935 (when (or org-use-extra-keys
17936 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17937 (not window-system))
17938 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17939 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17940 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17941 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17942 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17943 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17944 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17945 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17946 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17947 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17948 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17949 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17950 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17951 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17952 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17953 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17954 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17955 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17956 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17957 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17958 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17959 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17960 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17961 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17962 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17963 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17964 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17965 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17967 ;; All the other keys
17969 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17970 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17971 (if (boundp 'narrow-map)
17972 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17973 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17974 (if (boundp 'narrow-map)
17975 (org-defkey narrow-map "b" 'org-narrow-to-block)
17976 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17977 (if (boundp 'narrow-map)
17978 (org-defkey narrow-map "e" 'org-narrow-to-element)
17979 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
17980 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
17981 (org-defkey org-mode-map "\M-}" 'org-forward-element)
17982 (org-defkey org-mode-map "\M-{" 'org-backward-element)
17983 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
17984 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
17985 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
17986 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
17987 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17988 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17989 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17990 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
17991 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17992 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17993 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17994 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17995 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17996 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17997 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17998 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17999 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18000 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18001 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18002 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18003 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18004 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18005 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18006 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18007 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18008 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18009 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18010 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18011 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18012 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18013 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18014 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18015 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18016 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18017 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18018 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18019 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18020 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18021 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18022 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18023 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18024 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18025 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18026 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18027 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18028 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18029 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18030 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18031 (org-defkey org-mode-map "\C-c^" 'org-sort)
18032 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18033 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18034 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18035 (org-defkey org-mode-map "\C-m" 'org-return)
18036 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18037 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18038 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18039 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18040 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18041 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18042 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18043 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18044 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18045 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18046 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18047 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18048 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18049 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18050 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18051 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18052 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18053 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18054 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18055 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18056 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18057 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18058 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18060 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18061 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18062 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18064 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18065 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18066 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18067 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18068 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18069 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18070 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18071 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18072 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18073 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18074 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18075 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18076 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18077 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18078 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18079 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18080 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18081 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18082 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18083 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18084 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18085 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18087 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18088 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18089 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18090 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18091 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18093 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18095 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18097 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18098 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18100 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18103 (when (featurep 'xemacs)
18104 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18107 (defconst org-speed-commands-default
18109 ("Outline Navigation")
18110 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18111 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18112 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18113 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18114 ("u" . (org-speed-move-safe 'outline-up-heading))
18115 ("j" . org-goto)
18116 ("g" . (org-refile t))
18117 ("Outline Visibility")
18118 ("c" . org-cycle)
18119 ("C" . org-shifttab)
18120 (" " . org-display-outline-path)
18121 ("=" . org-columns)
18122 ("Outline Structure Editing")
18123 ("U" . org-shiftmetaup)
18124 ("D" . org-shiftmetadown)
18125 ("r" . org-metaright)
18126 ("l" . org-metaleft)
18127 ("R" . org-shiftmetaright)
18128 ("L" . org-shiftmetaleft)
18129 ("i" . (progn (forward-char 1) (call-interactively
18130 'org-insert-heading-respect-content)))
18131 ("^" . org-sort)
18132 ("w" . org-refile)
18133 ("a" . org-archive-subtree-default-with-confirmation)
18134 ("." . org-mark-subtree)
18135 ("#" . org-toggle-comment)
18136 ("Clock Commands")
18137 ("I" . org-clock-in)
18138 ("O" . org-clock-out)
18139 ("Meta Data Editing")
18140 ("t" . org-todo)
18141 ("," . (org-priority))
18142 ("0" . (org-priority ?\ ))
18143 ("1" . (org-priority ?A))
18144 ("2" . (org-priority ?B))
18145 ("3" . (org-priority ?C))
18146 (":" . org-set-tags-command)
18147 ("e" . org-set-effort)
18148 ("E" . org-inc-effort)
18149 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18150 (org-entry-put (point) "APPT_WARNTIME" m)))
18151 ("Agenda Views etc")
18152 ("v" . org-agenda)
18153 ("/" . org-sparse-tree)
18154 ("Misc")
18155 ("o" . org-open-at-point)
18156 ("?" . org-speed-command-help)
18157 ("<" . (org-agenda-set-restriction-lock 'subtree))
18158 (">" . (org-agenda-remove-restriction-lock))
18160 "The default speed commands.")
18162 (defun org-print-speed-command (e)
18163 (if (> (length (car e)) 1)
18164 (progn
18165 (princ "\n")
18166 (princ (car e))
18167 (princ "\n")
18168 (princ (make-string (length (car e)) ?-))
18169 (princ "\n"))
18170 (princ (car e))
18171 (princ " ")
18172 (if (symbolp (cdr e))
18173 (princ (symbol-name (cdr e)))
18174 (prin1 (cdr e)))
18175 (princ "\n")))
18177 (defun org-speed-command-help ()
18178 "Show the available speed commands."
18179 (interactive)
18180 (if (not org-use-speed-commands)
18181 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18182 (with-output-to-temp-buffer "*Help*"
18183 (princ "User-defined Speed commands\n===========================\n")
18184 (mapc 'org-print-speed-command org-speed-commands-user)
18185 (princ "\n")
18186 (princ "Built-in Speed commands\n=======================\n")
18187 (mapc 'org-print-speed-command org-speed-commands-default))
18188 (with-current-buffer "*Help*"
18189 (setq truncate-lines t))))
18191 (defun org-speed-move-safe (cmd)
18192 "Execute CMD, but make sure that the cursor always ends up in a headline.
18193 If not, return to the original position and throw an error."
18194 (interactive)
18195 (let ((pos (point)))
18196 (call-interactively cmd)
18197 (unless (and (bolp) (org-at-heading-p))
18198 (goto-char pos)
18199 (error "Boundary reached while executing %s" cmd))))
18201 (defvar org-self-insert-command-undo-counter 0)
18203 (defvar org-table-auto-blank-field) ; defined in org-table.el
18204 (defvar org-speed-command nil)
18206 (define-obsolete-function-alias
18207 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18209 (defun org-speed-command-activate (keys)
18210 "Hook for activating single-letter speed commands.
18211 `org-speed-commands-default' specifies a minimal command set.
18212 Use `org-speed-commands-user' for further customization."
18213 (when (or (and (bolp) (looking-at org-outline-regexp))
18214 (and (functionp org-use-speed-commands)
18215 (funcall org-use-speed-commands)))
18216 (cdr (assoc keys (append org-speed-commands-user
18217 org-speed-commands-default)))))
18219 (define-obsolete-function-alias
18220 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18222 (defun org-babel-speed-command-activate (keys)
18223 "Hook for activating single-letter code block commands."
18224 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18225 (cdr (assoc keys org-babel-key-bindings))))
18227 (defcustom org-speed-command-hook
18228 '(org-speed-command-default-hook org-babel-speed-command-hook)
18229 "Hook for activating speed commands at strategic locations.
18230 Hook functions are called in sequence until a valid handler is
18231 found.
18233 Each hook takes a single argument, a user-pressed command key
18234 which is also a `self-insert-command' from the global map.
18236 Within the hook, examine the cursor position and the command key
18237 and return nil or a valid handler as appropriate. Handler could
18238 be one of an interactive command, a function, or a form.
18240 Set `org-use-speed-commands' to non-nil value to enable this
18241 hook. The default setting is `org-speed-command-activate'."
18242 :group 'org-structure
18243 :version "24.1"
18244 :type 'hook)
18246 (defun org-self-insert-command (N)
18247 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18248 If the cursor is in a table looking at whitespace, the whitespace is
18249 overwritten, and the table is not marked as requiring realignment."
18250 (interactive "p")
18251 (org-check-before-invisible-edit 'insert)
18252 (cond
18253 ((and org-use-speed-commands
18254 (setq org-speed-command
18255 (run-hook-with-args-until-success
18256 'org-speed-command-hook (this-command-keys))))
18257 (cond
18258 ((commandp org-speed-command)
18259 (setq this-command org-speed-command)
18260 (call-interactively org-speed-command))
18261 ((functionp org-speed-command)
18262 (funcall org-speed-command))
18263 ((and org-speed-command (listp org-speed-command))
18264 (eval org-speed-command))
18265 (t (let (org-use-speed-commands)
18266 (call-interactively 'org-self-insert-command)))))
18267 ((and
18268 (org-table-p)
18269 (progn
18270 ;; check if we blank the field, and if that triggers align
18271 (and (featurep 'org-table) org-table-auto-blank-field
18272 (member last-command
18273 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18274 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18275 ;; got extra space, this field does not determine column width
18276 (let (org-table-may-need-update) (org-table-blank-field))
18277 ;; no extra space, this field may determine column width
18278 (org-table-blank-field)))
18280 (eq N 1)
18281 (looking-at "[^|\n]* |"))
18282 (let (org-table-may-need-update)
18283 (goto-char (1- (match-end 0)))
18284 (backward-delete-char 1)
18285 (goto-char (match-beginning 0))
18286 (self-insert-command N)))
18288 (setq org-table-may-need-update t)
18289 (self-insert-command N)
18290 (org-fix-tags-on-the-fly)
18291 (if org-self-insert-cluster-for-undo
18292 (if (not (eq last-command 'org-self-insert-command))
18293 (setq org-self-insert-command-undo-counter 1)
18294 (if (>= org-self-insert-command-undo-counter 20)
18295 (setq org-self-insert-command-undo-counter 1)
18296 (and (> org-self-insert-command-undo-counter 0)
18297 buffer-undo-list (listp buffer-undo-list)
18298 (not (cadr buffer-undo-list)) ; remove nil entry
18299 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18300 (setq org-self-insert-command-undo-counter
18301 (1+ org-self-insert-command-undo-counter))))))))
18303 (defun org-check-before-invisible-edit (kind)
18304 "Check is editing if kind KIND would be dangerous with invisible text around.
18305 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18306 ;; First, try to get out of here as quickly as possible, to reduce overhead
18307 (if (and org-catch-invisible-edits
18308 (or (not (boundp 'visible-mode)) (not visible-mode))
18309 (or (get-char-property (point) 'invisible)
18310 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18311 ;; OK, we need to take a closer look
18312 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18313 (invisible-before-point (if (bobp) nil (get-char-property
18314 (1- (point)) 'invisible)))
18315 (border-and-ok-direction
18317 ;; Check if we are acting predictably before invisible text
18318 (and invisible-at-point (not invisible-before-point)
18319 (memq kind '(insert delete-backward)))
18320 ;; Check if we are acting predictably after invisible text
18321 ;; This works not well, and I have turned it off. It seems
18322 ;; better to always show and stop after invisible text.
18323 ;; (and (not invisible-at-point) invisible-before-point
18324 ;; (memq kind '(insert delete)))
18326 (when (or (memq invisible-at-point '(outline org-hide-block t))
18327 (memq invisible-before-point '(outline org-hide-block t)))
18328 (if (eq org-catch-invisible-edits 'error)
18329 (error "Editing in invisible areas is prohibited - make visible first"))
18330 (if (and org-custom-properties-overlays
18331 (y-or-n-p "Display invisible properties in this buffer? "))
18332 (org-toggle-custom-properties-visibility)
18333 ;; Make the area visible
18334 (save-excursion
18335 (if invisible-before-point
18336 (goto-char (previous-single-char-property-change
18337 (point) 'invisible)))
18338 (org-cycle))
18339 (cond
18340 ((eq org-catch-invisible-edits 'show)
18341 ;; That's it, we do the edit after showing
18342 (message
18343 "Unfolding invisible region around point before editing")
18344 (sit-for 1))
18345 ((and (eq org-catch-invisible-edits 'smart)
18346 border-and-ok-direction)
18347 (message "Unfolding invisible region around point before editing"))
18349 ;; Don't do the edit, make the user repeat it in full visibility
18350 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18352 (defun org-fix-tags-on-the-fly ()
18353 (when (and (equal (char-after (point-at-bol)) ?*)
18354 (org-at-heading-p))
18355 (org-align-tags-here org-tags-column)))
18357 (defun org-delete-backward-char (N)
18358 "Like `delete-backward-char', insert whitespace at field end in tables.
18359 When deleting backwards, in tables this function will insert whitespace in
18360 front of the next \"|\" separator, to keep the table aligned. The table will
18361 still be marked for re-alignment if the field did fill the entire column,
18362 because, in this case the deletion might narrow the column."
18363 (interactive "p")
18364 (save-match-data
18365 (org-check-before-invisible-edit 'delete-backward)
18366 (if (and (org-table-p)
18367 (eq N 1)
18368 (string-match "|" (buffer-substring (point-at-bol) (point)))
18369 (looking-at ".*?|"))
18370 (let ((pos (point))
18371 (noalign (looking-at "[^|\n\r]* |"))
18372 (c org-table-may-need-update))
18373 (backward-delete-char N)
18374 (if (not overwrite-mode)
18375 (progn
18376 (skip-chars-forward "^|")
18377 (insert " ")
18378 (goto-char (1- pos))))
18379 ;; noalign: if there were two spaces at the end, this field
18380 ;; does not determine the width of the column.
18381 (if noalign (setq org-table-may-need-update c)))
18382 (backward-delete-char N)
18383 (org-fix-tags-on-the-fly))))
18385 (defun org-delete-char (N)
18386 "Like `delete-char', but insert whitespace at field end in tables.
18387 When deleting characters, in tables this function will insert whitespace in
18388 front of the next \"|\" separator, to keep the table aligned. The table will
18389 still be marked for re-alignment if the field did fill the entire column,
18390 because, in this case the deletion might narrow the column."
18391 (interactive "p")
18392 (save-match-data
18393 (org-check-before-invisible-edit 'delete)
18394 (if (and (org-table-p)
18395 (not (bolp))
18396 (not (= (char-after) ?|))
18397 (eq N 1))
18398 (if (looking-at ".*?|")
18399 (let ((pos (point))
18400 (noalign (looking-at "[^|\n\r]* |"))
18401 (c org-table-may-need-update))
18402 (replace-match (concat
18403 (substring (match-string 0) 1 -1)
18404 " |"))
18405 (goto-char pos)
18406 ;; noalign: if there were two spaces at the end, this field
18407 ;; does not determine the width of the column.
18408 (if noalign (setq org-table-may-need-update c)))
18409 (delete-char N))
18410 (delete-char N)
18411 (org-fix-tags-on-the-fly))))
18413 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18414 (put 'org-self-insert-command 'delete-selection t)
18415 (put 'orgtbl-self-insert-command 'delete-selection t)
18416 (put 'org-delete-char 'delete-selection 'supersede)
18417 (put 'org-delete-backward-char 'delete-selection 'supersede)
18418 (put 'org-yank 'delete-selection 'yank)
18420 ;; Make `flyspell-mode' delay after some commands
18421 (put 'org-self-insert-command 'flyspell-delayed t)
18422 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18423 (put 'org-delete-char 'flyspell-delayed t)
18424 (put 'org-delete-backward-char 'flyspell-delayed t)
18426 ;; Make pabbrev-mode expand after org-mode commands
18427 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18428 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18430 ;; How to do this: Measure non-white length of current string
18431 ;; If equal to column width, we should realign.
18433 (defun org-remap (map &rest commands)
18434 "In MAP, remap the functions given in COMMANDS.
18435 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18436 (let (new old)
18437 (while commands
18438 (setq old (pop commands) new (pop commands))
18439 (if (fboundp 'command-remapping)
18440 (org-defkey map (vector 'remap old) new)
18441 (substitute-key-definition old new map global-map)))))
18443 (when (eq org-enable-table-editor 'optimized)
18444 ;; If the user wants maximum table support, we need to hijack
18445 ;; some standard editing functions
18446 (org-remap org-mode-map
18447 'self-insert-command 'org-self-insert-command
18448 'delete-char 'org-delete-char
18449 'delete-backward-char 'org-delete-backward-char)
18450 (org-defkey org-mode-map "|" 'org-force-self-insert))
18452 (defvar org-ctrl-c-ctrl-c-hook nil
18453 "Hook for functions attaching themselves to `C-c C-c'.
18455 This can be used to add additional functionality to the C-c C-c
18456 key which executes context-dependent commands. This hook is run
18457 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18458 run after the last test.
18460 Each function will be called with no arguments. The function
18461 must check if the context is appropriate for it to act. If yes,
18462 it should do its thing and then return a non-nil value. If the
18463 context is wrong, just do nothing and return nil.")
18465 (defvar org-ctrl-c-ctrl-c-final-hook nil
18466 "Hook for functions attaching themselves to `C-c C-c'.
18468 This can be used to add additional functionality to the C-c C-c
18469 key which executes context-dependent commands. This hook is run
18470 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18471 before the first test.
18473 Each function will be called with no arguments. The function
18474 must check if the context is appropriate for it to act. If yes,
18475 it should do its thing and then return a non-nil value. If the
18476 context is wrong, just do nothing and return nil.")
18478 (defvar org-tab-first-hook nil
18479 "Hook for functions to attach themselves to TAB.
18480 See `org-ctrl-c-ctrl-c-hook' for more information.
18481 This hook runs as the first action when TAB is pressed, even before
18482 `org-cycle' messes around with the `outline-regexp' to cater for
18483 inline tasks and plain list item folding.
18484 If any function in this hook returns t, any other actions that
18485 would have been caused by TAB (such as table field motion or visibility
18486 cycling) will not occur.")
18488 (defvar org-tab-after-check-for-table-hook nil
18489 "Hook for functions to attach themselves to TAB.
18490 See `org-ctrl-c-ctrl-c-hook' for more information.
18491 This hook runs after it has been established that the cursor is not in a
18492 table, but before checking if the cursor is in a headline or if global cycling
18493 should be done.
18494 If any function in this hook returns t, not other actions like visibility
18495 cycling will be done.")
18497 (defvar org-tab-after-check-for-cycling-hook nil
18498 "Hook for functions to attach themselves to TAB.
18499 See `org-ctrl-c-ctrl-c-hook' for more information.
18500 This hook runs after it has been established that not table field motion and
18501 not visibility should be done because of current context. This is probably
18502 the place where a package like yasnippets can hook in.")
18504 (defvar org-tab-before-tab-emulation-hook nil
18505 "Hook for functions to attach themselves to TAB.
18506 See `org-ctrl-c-ctrl-c-hook' for more information.
18507 This hook runs after every other options for TAB have been exhausted, but
18508 before indentation and \t insertion takes place.")
18510 (defvar org-metaleft-hook nil
18511 "Hook for functions attaching themselves to `M-left'.
18512 See `org-ctrl-c-ctrl-c-hook' for more information.")
18513 (defvar org-metaright-hook nil
18514 "Hook for functions attaching themselves to `M-right'.
18515 See `org-ctrl-c-ctrl-c-hook' for more information.")
18516 (defvar org-metaup-hook nil
18517 "Hook for functions attaching themselves to `M-up'.
18518 See `org-ctrl-c-ctrl-c-hook' for more information.")
18519 (defvar org-metadown-hook nil
18520 "Hook for functions attaching themselves to `M-down'.
18521 See `org-ctrl-c-ctrl-c-hook' for more information.")
18522 (defvar org-shiftmetaleft-hook nil
18523 "Hook for functions attaching themselves to `M-S-left'.
18524 See `org-ctrl-c-ctrl-c-hook' for more information.")
18525 (defvar org-shiftmetaright-hook nil
18526 "Hook for functions attaching themselves to `M-S-right'.
18527 See `org-ctrl-c-ctrl-c-hook' for more information.")
18528 (defvar org-shiftmetaup-hook nil
18529 "Hook for functions attaching themselves to `M-S-up'.
18530 See `org-ctrl-c-ctrl-c-hook' for more information.")
18531 (defvar org-shiftmetadown-hook nil
18532 "Hook for functions attaching themselves to `M-S-down'.
18533 See `org-ctrl-c-ctrl-c-hook' for more information.")
18534 (defvar org-metareturn-hook nil
18535 "Hook for functions attaching themselves to `M-RET'.
18536 See `org-ctrl-c-ctrl-c-hook' for more information.")
18537 (defvar org-shiftup-hook nil
18538 "Hook for functions attaching themselves to `S-up'.
18539 See `org-ctrl-c-ctrl-c-hook' for more information.")
18540 (defvar org-shiftup-final-hook nil
18541 "Hook for functions attaching themselves to `S-up'.
18542 This one runs after all other options except shift-select have been excluded.
18543 See `org-ctrl-c-ctrl-c-hook' for more information.")
18544 (defvar org-shiftdown-hook nil
18545 "Hook for functions attaching themselves to `S-down'.
18546 See `org-ctrl-c-ctrl-c-hook' for more information.")
18547 (defvar org-shiftdown-final-hook nil
18548 "Hook for functions attaching themselves to `S-down'.
18549 This one runs after all other options except shift-select have been excluded.
18550 See `org-ctrl-c-ctrl-c-hook' for more information.")
18551 (defvar org-shiftleft-hook nil
18552 "Hook for functions attaching themselves to `S-left'.
18553 See `org-ctrl-c-ctrl-c-hook' for more information.")
18554 (defvar org-shiftleft-final-hook nil
18555 "Hook for functions attaching themselves to `S-left'.
18556 This one runs after all other options except shift-select have been excluded.
18557 See `org-ctrl-c-ctrl-c-hook' for more information.")
18558 (defvar org-shiftright-hook nil
18559 "Hook for functions attaching themselves to `S-right'.
18560 See `org-ctrl-c-ctrl-c-hook' for more information.")
18561 (defvar org-shiftright-final-hook nil
18562 "Hook for functions attaching themselves to `S-right'.
18563 This one runs after all other options except shift-select have been excluded.
18564 See `org-ctrl-c-ctrl-c-hook' for more information.")
18566 (defun org-modifier-cursor-error ()
18567 "Throw an error, a modified cursor command was applied in wrong context."
18568 (error "This command is active in special context like tables, headlines or items"))
18570 (defun org-shiftselect-error ()
18571 "Throw an error because Shift-Cursor command was applied in wrong context."
18572 (if (and (boundp 'shift-select-mode) shift-select-mode)
18573 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18574 (error "This command works only in special context like headlines or timestamps")))
18576 (defun org-call-for-shift-select (cmd)
18577 (let ((this-command-keys-shift-translated t))
18578 (call-interactively cmd)))
18580 (defun org-shifttab (&optional arg)
18581 "Global visibility cycling or move to previous table field.
18582 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18583 on context.
18584 See the individual commands for more information."
18585 (interactive "P")
18586 (cond
18587 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18588 ((integerp arg)
18589 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18590 (message "Content view to level: %d" arg)
18591 (org-content (prefix-numeric-value arg2))
18592 (setq org-cycle-global-status 'overview)))
18593 (t (call-interactively 'org-global-cycle))))
18595 (defun org-shiftmetaleft ()
18596 "Promote subtree or delete table column.
18597 Calls `org-promote-subtree', `org-outdent-item-tree', or
18598 `org-table-delete-column', depending on context. See the
18599 individual commands for more information."
18600 (interactive)
18601 (cond
18602 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18603 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18604 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18605 ((if (not (org-region-active-p)) (org-at-item-p)
18606 (save-excursion (goto-char (region-beginning))
18607 (org-at-item-p)))
18608 (call-interactively 'org-outdent-item-tree))
18609 (t (org-modifier-cursor-error))))
18611 (defun org-shiftmetaright ()
18612 "Demote subtree or insert table column.
18613 Calls `org-demote-subtree', `org-indent-item-tree', or
18614 `org-table-insert-column', depending on context. See the
18615 individual commands for more information."
18616 (interactive)
18617 (cond
18618 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18619 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18620 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18621 ((if (not (org-region-active-p)) (org-at-item-p)
18622 (save-excursion (goto-char (region-beginning))
18623 (org-at-item-p)))
18624 (call-interactively 'org-indent-item-tree))
18625 (t (org-modifier-cursor-error))))
18627 (defun org-shiftmetaup (&optional arg)
18628 "Move subtree up or kill table row.
18629 Calls `org-move-subtree-up' or `org-table-kill-row' or
18630 `org-move-item-up' or `org-timestamp-up', depending on context.
18631 See the individual commands for more information."
18632 (interactive "P")
18633 (cond
18634 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18635 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18636 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18637 ((org-at-item-p) (call-interactively 'org-move-item-up))
18638 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18639 (call-interactively 'org-timestamp-up)))
18640 (t (org-modifier-cursor-error))))
18642 (defun org-shiftmetadown (&optional arg)
18643 "Move subtree down or insert table row.
18644 Calls `org-move-subtree-down' or `org-table-insert-row' or
18645 `org-move-item-down' or `org-timestamp-up', depending on context.
18646 See the individual commands for more information."
18647 (interactive "P")
18648 (cond
18649 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18650 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18651 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18652 ((org-at-item-p) (call-interactively 'org-move-item-down))
18653 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18654 (call-interactively 'org-timestamp-down)))
18655 (t (org-modifier-cursor-error))))
18657 (defsubst org-hidden-tree-error ()
18658 (error
18659 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18661 (defun org-metaleft (&optional arg)
18662 "Promote heading or move table column to left.
18663 Calls `org-do-promote' or `org-table-move-column', depending on context.
18664 With no specific context, calls the Emacs default `backward-word'.
18665 See the individual commands for more information."
18666 (interactive "P")
18667 (cond
18668 ((run-hook-with-args-until-success 'org-metaleft-hook))
18669 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18670 ((org-with-limited-levels
18671 (or (org-at-heading-p)
18672 (and (org-region-active-p)
18673 (save-excursion
18674 (goto-char (region-beginning))
18675 (org-at-heading-p)))))
18676 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18677 (call-interactively 'org-do-promote))
18678 ;; At an inline task.
18679 ((org-at-heading-p)
18680 (call-interactively 'org-inlinetask-promote))
18681 ((or (org-at-item-p)
18682 (and (org-region-active-p)
18683 (save-excursion
18684 (goto-char (region-beginning))
18685 (org-at-item-p))))
18686 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18687 (call-interactively 'org-outdent-item))
18688 (t (call-interactively 'backward-word))))
18690 (defun org-metaright (&optional arg)
18691 "Demote a subtree, a list item or move table column to right.
18692 In front of a drawer or a block keyword, indent it correctly.
18693 With no specific context, calls the Emacs default `forward-word'.
18694 See the individual commands for more information."
18695 (interactive "P")
18696 (cond
18697 ((run-hook-with-args-until-success 'org-metaright-hook))
18698 ((org-at-table-p) (call-interactively 'org-table-move-column))
18699 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18700 ((org-at-block-p) (call-interactively 'org-indent-block))
18701 ((org-with-limited-levels
18702 (or (org-at-heading-p)
18703 (and (org-region-active-p)
18704 (save-excursion
18705 (goto-char (region-beginning))
18706 (org-at-heading-p)))))
18707 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18708 (call-interactively 'org-do-demote))
18709 ;; At an inline task.
18710 ((org-at-heading-p)
18711 (call-interactively 'org-inlinetask-demote))
18712 ((or (org-at-item-p)
18713 (and (org-region-active-p)
18714 (save-excursion
18715 (goto-char (region-beginning))
18716 (org-at-item-p))))
18717 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18718 (call-interactively 'org-indent-item))
18719 (t (call-interactively 'forward-word))))
18721 (defun org-check-for-hidden (what)
18722 "Check if there are hidden headlines/items in the current visual line.
18723 WHAT can be either `headlines' or `items'. If the current line is
18724 an outline or item heading and it has a folded subtree below it,
18725 this function returns t, nil otherwise."
18726 (let ((re (cond
18727 ((eq what 'headlines) org-outline-regexp-bol)
18728 ((eq what 'items) (org-item-beginning-re))
18729 (t (error "This should not happen"))))
18730 beg end)
18731 (save-excursion
18732 (catch 'exit
18733 (unless (org-region-active-p)
18734 (setq beg (point-at-bol))
18735 (beginning-of-line 2)
18736 (while (and (not (eobp)) ;; this is like `next-line'
18737 (get-char-property (1- (point)) 'invisible))
18738 (beginning-of-line 2))
18739 (setq end (point))
18740 (goto-char beg)
18741 (goto-char (point-at-eol))
18742 (setq end (max end (point)))
18743 (while (re-search-forward re end t)
18744 (if (get-char-property (match-beginning 0) 'invisible)
18745 (throw 'exit t))))
18746 nil))))
18748 (autoload 'org-element-at-point "org-element")
18749 (autoload 'org-element-type "org-element")
18751 (declare-function org-element-at-point "org-element" (&optional keep-trail))
18752 (declare-function org-element-type "org-element" (element))
18753 (declare-function org-element-contents "org-element" (element))
18754 (declare-function org-element-property "org-element" (property element))
18755 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
18756 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
18757 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
18758 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
18759 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
18761 (defun org-metaup (&optional arg)
18762 "Move subtree up or move table row up.
18763 Calls `org-move-subtree-up' or `org-table-move-row' or
18764 `org-move-item-up', depending on context. See the individual commands
18765 for more information."
18766 (interactive "P")
18767 (cond
18768 ((run-hook-with-args-until-success 'org-metaup-hook))
18769 ((org-region-active-p)
18770 (let* ((a (min (region-beginning) (region-end)))
18771 (b (1- (max (region-beginning) (region-end))))
18772 (c (save-excursion (goto-char a)
18773 (move-beginning-of-line 0)))
18774 (d (save-excursion (goto-char a)
18775 (move-end-of-line 0) (point))))
18776 (transpose-regions a b c d)
18777 (goto-char c)))
18778 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18779 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18780 ((org-at-item-p) (call-interactively 'org-move-item-up))
18781 (t (org-drag-element-backward))))
18783 (defun org-metadown (&optional arg)
18784 "Move subtree down or move table row down.
18785 Calls `org-move-subtree-down' or `org-table-move-row' or
18786 `org-move-item-down', depending on context. See the individual
18787 commands for more information."
18788 (interactive "P")
18789 (cond
18790 ((run-hook-with-args-until-success 'org-metadown-hook))
18791 ((org-region-active-p)
18792 (let* ((a (min (region-beginning) (region-end)))
18793 (b (max (region-beginning) (region-end)))
18794 (c (save-excursion (goto-char b)
18795 (move-beginning-of-line 1)))
18796 (d (save-excursion (goto-char b)
18797 (move-end-of-line 1) (1+ (point)))))
18798 (transpose-regions a b c d)
18799 (goto-char d)))
18800 ((org-at-table-p) (call-interactively 'org-table-move-row))
18801 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18802 ((org-at-item-p) (call-interactively 'org-move-item-down))
18803 (t (org-drag-element-forward))))
18805 (defun org-shiftup (&optional arg)
18806 "Increase item in timestamp or increase priority of current headline.
18807 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18808 depending on context. See the individual commands for more information."
18809 (interactive "P")
18810 (cond
18811 ((run-hook-with-args-until-success 'org-shiftup-hook))
18812 ((and org-support-shift-select (org-region-active-p))
18813 (org-call-for-shift-select 'previous-line))
18814 ((org-at-timestamp-p t)
18815 (call-interactively (if org-edit-timestamp-down-means-later
18816 'org-timestamp-down 'org-timestamp-up)))
18817 ((and (not (eq org-support-shift-select 'always))
18818 org-enable-priority-commands
18819 (org-at-heading-p))
18820 (call-interactively 'org-priority-up))
18821 ((and (not org-support-shift-select) (org-at-item-p))
18822 (call-interactively 'org-previous-item))
18823 ((org-clocktable-try-shift 'up arg))
18824 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18825 (org-support-shift-select
18826 (org-call-for-shift-select 'previous-line))
18827 (t (org-shiftselect-error))))
18829 (defun org-shiftdown (&optional arg)
18830 "Decrease item in timestamp or decrease priority of current headline.
18831 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18832 depending on context. See the individual commands for more information."
18833 (interactive "P")
18834 (cond
18835 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18836 ((and org-support-shift-select (org-region-active-p))
18837 (org-call-for-shift-select 'next-line))
18838 ((org-at-timestamp-p t)
18839 (call-interactively (if org-edit-timestamp-down-means-later
18840 'org-timestamp-up 'org-timestamp-down)))
18841 ((and (not (eq org-support-shift-select 'always))
18842 org-enable-priority-commands
18843 (org-at-heading-p))
18844 (call-interactively 'org-priority-down))
18845 ((and (not org-support-shift-select) (org-at-item-p))
18846 (call-interactively 'org-next-item))
18847 ((org-clocktable-try-shift 'down arg))
18848 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18849 (org-support-shift-select
18850 (org-call-for-shift-select 'next-line))
18851 (t (org-shiftselect-error))))
18853 (defun org-shiftright (&optional arg)
18854 "Cycle the thing at point or in the current line, depending on context.
18855 Depending on context, this does one of the following:
18857 - switch a timestamp at point one day into the future
18858 - on a headline, switch to the next TODO keyword.
18859 - on an item, switch entire list to the next bullet type
18860 - on a property line, switch to the next allowed value
18861 - on a clocktable definition line, move time block into the future"
18862 (interactive "P")
18863 (cond
18864 ((run-hook-with-args-until-success 'org-shiftright-hook))
18865 ((and org-support-shift-select (org-region-active-p))
18866 (org-call-for-shift-select 'forward-char))
18867 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18868 ((and (not (eq org-support-shift-select 'always))
18869 (org-at-heading-p))
18870 (let ((org-inhibit-logging
18871 (not org-treat-S-cursor-todo-selection-as-state-change))
18872 (org-inhibit-blocking
18873 (not org-treat-S-cursor-todo-selection-as-state-change)))
18874 (org-call-with-arg 'org-todo 'right)))
18875 ((or (and org-support-shift-select
18876 (not (eq org-support-shift-select 'always))
18877 (org-at-item-bullet-p))
18878 (and (not org-support-shift-select) (org-at-item-p)))
18879 (org-call-with-arg 'org-cycle-list-bullet nil))
18880 ((and (not (eq org-support-shift-select 'always))
18881 (org-at-property-p))
18882 (call-interactively 'org-property-next-allowed-value))
18883 ((org-clocktable-try-shift 'right arg))
18884 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18885 (org-support-shift-select
18886 (org-call-for-shift-select 'forward-char))
18887 (t (org-shiftselect-error))))
18889 (defun org-shiftleft (&optional arg)
18890 "Cycle the thing at point or in the current line, depending on context.
18891 Depending on context, this does one of the following:
18893 - switch a timestamp at point one day into the past
18894 - on a headline, switch to the previous TODO keyword.
18895 - on an item, switch entire list to the previous bullet type
18896 - on a property line, switch to the previous allowed value
18897 - on a clocktable definition line, move time block into the past"
18898 (interactive "P")
18899 (cond
18900 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18901 ((and org-support-shift-select (org-region-active-p))
18902 (org-call-for-shift-select 'backward-char))
18903 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18904 ((and (not (eq org-support-shift-select 'always))
18905 (org-at-heading-p))
18906 (let ((org-inhibit-logging
18907 (not org-treat-S-cursor-todo-selection-as-state-change))
18908 (org-inhibit-blocking
18909 (not org-treat-S-cursor-todo-selection-as-state-change)))
18910 (org-call-with-arg 'org-todo 'left)))
18911 ((or (and org-support-shift-select
18912 (not (eq org-support-shift-select 'always))
18913 (org-at-item-bullet-p))
18914 (and (not org-support-shift-select) (org-at-item-p)))
18915 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18916 ((and (not (eq org-support-shift-select 'always))
18917 (org-at-property-p))
18918 (call-interactively 'org-property-previous-allowed-value))
18919 ((org-clocktable-try-shift 'left arg))
18920 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18921 (org-support-shift-select
18922 (org-call-for-shift-select 'backward-char))
18923 (t (org-shiftselect-error))))
18925 (defun org-shiftcontrolright ()
18926 "Switch to next TODO set."
18927 (interactive)
18928 (cond
18929 ((and org-support-shift-select (org-region-active-p))
18930 (org-call-for-shift-select 'forward-word))
18931 ((and (not (eq org-support-shift-select 'always))
18932 (org-at-heading-p))
18933 (org-call-with-arg 'org-todo 'nextset))
18934 (org-support-shift-select
18935 (org-call-for-shift-select 'forward-word))
18936 (t (org-shiftselect-error))))
18938 (defun org-shiftcontrolleft ()
18939 "Switch to previous TODO set."
18940 (interactive)
18941 (cond
18942 ((and org-support-shift-select (org-region-active-p))
18943 (org-call-for-shift-select 'backward-word))
18944 ((and (not (eq org-support-shift-select 'always))
18945 (org-at-heading-p))
18946 (org-call-with-arg 'org-todo 'previousset))
18947 (org-support-shift-select
18948 (org-call-for-shift-select 'backward-word))
18949 (t (org-shiftselect-error))))
18951 (defun org-shiftcontrolup ()
18952 "Change timestamps synchronously up in CLOCK log lines."
18953 (interactive)
18954 (cond ((and (not org-support-shift-select)
18955 (org-at-clock-log-p)
18956 (org-at-timestamp-p t))
18957 (org-clock-timestamps-up))
18958 (t (org-shiftselect-error))))
18960 (defun org-shiftcontroldown ()
18961 "Change timestamps synchronously down in CLOCK log lines."
18962 (interactive)
18963 (cond ((and (not org-support-shift-select)
18964 (org-at-clock-log-p)
18965 (org-at-timestamp-p t))
18966 (org-clock-timestamps-down))
18967 (t (org-shiftselect-error))))
18969 (defun org-ctrl-c-ret ()
18970 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18971 (interactive)
18972 (cond
18973 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18974 (t (call-interactively 'org-insert-heading))))
18976 (defun org-find-visible ()
18977 (let ((s (point)))
18978 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18979 (get-char-property s 'invisible)))
18981 (defun org-find-invisible ()
18982 (let ((s (point)))
18983 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18984 (not (get-char-property s 'invisible))))
18987 (defun org-copy-visible (beg end)
18988 "Copy the visible parts of the region."
18989 (interactive "r")
18990 (let (snippets s)
18991 (save-excursion
18992 (save-restriction
18993 (narrow-to-region beg end)
18994 (setq s (goto-char (point-min)))
18995 (while (not (= (point) (point-max)))
18996 (goto-char (org-find-invisible))
18997 (push (buffer-substring s (point)) snippets)
18998 (setq s (goto-char (org-find-visible))))))
18999 (kill-new (apply 'concat (nreverse snippets)))))
19001 (defun org-copy-special ()
19002 "Copy region in table or copy current subtree.
19003 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19004 See the individual commands for more information."
19005 (interactive)
19006 (call-interactively
19007 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19009 (defun org-cut-special ()
19010 "Cut region in table or cut current subtree.
19011 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19012 See the individual commands for more information."
19013 (interactive)
19014 (call-interactively
19015 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19017 (defun org-paste-special (arg)
19018 "Paste rectangular region into table, or past subtree relative to level.
19019 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19020 See the individual commands for more information."
19021 (interactive "P")
19022 (if (org-at-table-p)
19023 (org-table-paste-rectangle)
19024 (org-paste-subtree arg)))
19026 (defsubst org-in-fixed-width-region-p ()
19027 "Is point in a fixed-width region?"
19028 (save-match-data
19029 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19031 (defun org-edit-special (&optional arg)
19032 "Call a special editor for the stuff at point.
19033 When at a table, call the formula editor with `org-table-edit-formulas'.
19034 When in a source code block, call `org-edit-src-code'.
19035 When in a fixed-width region, call `org-edit-fixed-width-region'.
19036 When in an #+include line, visit the included file.
19037 On a link, call `ffap' to visit the link at point.
19038 Otherwise, return a user error."
19039 (interactive)
19040 ;; possibly prep session before editing source
19041 (when (and (org-in-src-block-p) arg)
19042 (let* ((info (org-babel-get-src-block-info))
19043 (lang (nth 0 info))
19044 (params (nth 2 info))
19045 (session (cdr (assoc :session params))))
19046 (when (and info session) ;; we are in a source-code block with a session
19047 (funcall
19048 (intern (concat "org-babel-prep-session:" lang)) session params))))
19049 (cond ;; proceed with `org-edit-special'
19050 ((save-excursion
19051 (beginning-of-line 1)
19052 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19053 (find-file (org-trim (match-string 1))))
19054 ((org-at-table.el-p) (org-edit-src-code))
19055 ((or (org-at-table-p)
19056 (save-excursion
19057 (beginning-of-line 1)
19058 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19059 (call-interactively 'org-table-edit-formulas))
19060 ((org-in-block-p '("src" "example" "latex" "html")) (org-edit-src-code))
19061 ((org-in-fixed-width-region-p) (org-edit-fixed-width-region))
19062 ((org-at-regexp-p org-any-link-re) (call-interactively 'ffap))
19063 (t (user-error "No special environment to edit here"))))
19065 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19066 (defun org-ctrl-c-ctrl-c (&optional arg)
19067 "Set tags in headline, or update according to changed information at point.
19069 This command does many different things, depending on context:
19071 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19072 this is what we do.
19074 - If the cursor is on a statistics cookie, update it.
19076 - If the cursor is in a headline, prompt for tags and insert them
19077 into the current line, aligned to `org-tags-column'. When called
19078 with prefix arg, realign all tags in the current buffer.
19080 - If the cursor is in one of the special #+KEYWORD lines, this
19081 triggers scanning the buffer for these lines and updating the
19082 information.
19084 - If the cursor is inside a table, realign the table. This command
19085 works even if the automatic table editor has been turned off.
19087 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19088 the entire table.
19090 - If the cursor is at a footnote reference or definition, jump to
19091 the corresponding definition or references, respectively.
19093 - If the cursor is a the beginning of a dynamic block, update it.
19095 - If the current buffer is a capture buffer, close note and file it.
19097 - If the cursor is on a <<<target>>>, update radio targets and
19098 corresponding links in this buffer.
19100 - If the cursor is on a numbered item in a plain list, renumber the
19101 ordered list.
19103 - If the cursor is on a checkbox, toggle it.
19105 - If the cursor is on a code block, evaluate it. The variable
19106 `org-confirm-babel-evaluate' can be used to control prompting
19107 before code block evaluation, by default every code block
19108 evaluation requires confirmation. Code block evaluation can be
19109 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19110 (interactive "P")
19111 (let ((org-enable-table-editor t))
19112 (cond
19113 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19114 org-occur-highlights
19115 org-latex-fragment-image-overlays)
19116 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19117 (org-remove-occur-highlights)
19118 (org-remove-latex-fragment-image-overlays)
19119 (message "Temporary highlights/overlays removed from current buffer"))
19120 ((and (local-variable-p 'org-finish-function (current-buffer))
19121 (fboundp org-finish-function))
19122 (funcall org-finish-function))
19123 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19124 ((org-in-regexp org-ts-regexp-both)
19125 (org-timestamp-change 0 'day))
19126 ((or (looking-at org-property-start-re)
19127 (org-at-property-p))
19128 (call-interactively 'org-property-action))
19129 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19130 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19131 (or (org-at-heading-p) (org-at-item-p)))
19132 (call-interactively 'org-update-statistics-cookies))
19133 ((org-at-heading-p) (call-interactively 'org-set-tags))
19134 ((org-at-table.el-p)
19135 (message "Use C-c ' to edit table.el tables"))
19136 ((org-at-table-p)
19137 (org-table-maybe-eval-formula)
19138 (if arg
19139 (call-interactively 'org-table-recalculate)
19140 (org-table-maybe-recalculate-line))
19141 (call-interactively 'org-table-align)
19142 (orgtbl-send-table 'maybe))
19143 ((or (org-footnote-at-reference-p)
19144 (org-footnote-at-definition-p))
19145 (call-interactively 'org-footnote-action))
19146 ((org-at-item-checkbox-p)
19147 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19148 ;; list only if at top item.
19149 (let* ((cbox (match-string 1))
19150 (struct (org-list-struct))
19151 (old-struct (copy-tree struct))
19152 (parents (org-list-parents-alist struct))
19153 (orderedp (org-entry-get nil "ORDERED"))
19154 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19155 block-item)
19156 ;; Use a light version of `org-toggle-checkbox' to avoid
19157 ;; computing list structure twice.
19158 (let ((new-box (cond
19159 ((equal arg '(16)) "[-]")
19160 ((equal arg '(4)) nil)
19161 ((equal "[X]" cbox) "[ ]")
19162 (t "[X]"))))
19163 (if (and firstp arg)
19164 ;; If at first item of sub-list, remove check-box from
19165 ;; every item at the same level.
19166 (mapc
19167 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19168 (org-list-get-all-items
19169 (point-at-bol) struct (org-list-prevs-alist struct)))
19170 (org-list-set-checkbox (point-at-bol) struct new-box)))
19171 ;; Replicate `org-list-write-struct', while grabbing a return
19172 ;; value from `org-list-struct-fix-box'.
19173 (org-list-struct-fix-ind struct parents 2)
19174 (org-list-struct-fix-item-end struct)
19175 (let ((prevs (org-list-prevs-alist struct)))
19176 (org-list-struct-fix-bul struct prevs)
19177 (org-list-struct-fix-ind struct parents)
19178 (setq block-item
19179 (org-list-struct-fix-box struct parents prevs orderedp)))
19180 (if (equal struct old-struct)
19181 (user-error "Cannot toggle this checkbox (unchecked subitems?)")
19182 (org-list-struct-apply-struct struct old-struct)
19183 (org-update-checkbox-count-maybe))
19184 (when block-item
19185 (message
19186 "Checkboxes were removed due to unchecked box at line %d"
19187 (org-current-line block-item)))
19188 (when firstp (org-list-send-list 'maybe))))
19189 ((org-at-item-p)
19190 ;; Cursor at an item: repair list. Do checkbox related actions
19191 ;; only if function was called with an argument. Send list only
19192 ;; if at top item.
19193 (let* ((struct (org-list-struct))
19194 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19195 old-struct)
19196 (when arg
19197 (setq old-struct (copy-tree struct))
19198 (if firstp
19199 ;; If at first item of sub-list, add check-box to every
19200 ;; item at the same level.
19201 (mapc
19202 (lambda (pos)
19203 (unless (org-list-get-checkbox pos struct)
19204 (org-list-set-checkbox pos struct "[ ]")))
19205 (org-list-get-all-items
19206 (point-at-bol) struct (org-list-prevs-alist struct)))
19207 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19208 (org-list-write-struct
19209 struct (org-list-parents-alist struct) old-struct)
19210 (when arg (org-update-checkbox-count-maybe))
19211 (when firstp (org-list-send-list 'maybe))))
19212 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19213 ;; Dynamic block
19214 (beginning-of-line 1)
19215 (save-excursion (org-update-dblock)))
19216 ((save-excursion
19217 (let ((case-fold-search t))
19218 (beginning-of-line 1)
19219 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19220 (cond
19221 ((or (equal (match-string 1) "TBLFM")
19222 (equal (match-string 1) "tblfm"))
19223 ;; Recalculate the table before this line
19224 (save-excursion
19225 (beginning-of-line 1)
19226 (skip-chars-backward " \r\n\t")
19227 (if (org-at-table-p)
19228 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19230 (let ((org-inhibit-startup-visibility-stuff t)
19231 (org-startup-align-all-tables nil))
19232 (when (boundp 'org-table-coordinate-overlays)
19233 (mapc 'delete-overlay org-table-coordinate-overlays)
19234 (setq org-table-coordinate-overlays nil))
19235 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19236 (message "Local setup has been refreshed"))))
19237 ((org-clock-update-time-maybe))
19239 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19240 (error "C-c C-c can do nothing useful at this location"))))))
19242 (defun org-mode-restart ()
19243 "Restart Org-mode, to scan again for special lines.
19244 Also updates the keyword regular expressions."
19245 (interactive)
19246 (org-mode)
19247 (message "Org-mode restarted"))
19249 (defun org-kill-note-or-show-branches ()
19250 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19251 (interactive)
19252 (if (not org-finish-function)
19253 (progn
19254 (hide-subtree)
19255 (call-interactively 'show-branches))
19256 (let ((org-note-abort t))
19257 (funcall org-finish-function))))
19259 (defun org-return (&optional indent)
19260 "Goto next table row or insert a newline.
19261 Calls `org-table-next-row' or `newline', depending on context.
19262 See the individual commands for more information."
19263 (interactive)
19264 (let (org-ts-what)
19265 (cond
19266 ((or (bobp) (org-in-src-block-p))
19267 (if indent (newline-and-indent) (newline)))
19268 ((org-at-table-p)
19269 (org-table-justify-field-maybe)
19270 (call-interactively 'org-table-next-row))
19271 ;; when `newline-and-indent' is called within a list, make sure
19272 ;; text moved stays inside the item.
19273 ((and (org-in-item-p) indent)
19274 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19275 (progn
19276 (save-match-data (newline))
19277 (org-indent-line-to (length (match-string 0))))
19278 (let ((ind (org-get-indentation)))
19279 (newline)
19280 (if (org-looking-back org-list-end-re)
19281 (org-indent-line)
19282 (org-indent-line-to ind)))))
19283 ((and org-return-follows-link
19284 (org-at-timestamp-p t)
19285 (not (eq org-ts-what 'after)))
19286 (org-follow-timestamp-link))
19287 ((and org-return-follows-link
19288 (let ((tprop (get-text-property (point) 'face)))
19289 (or (eq tprop 'org-link)
19290 (and (listp tprop) (memq 'org-link tprop)))))
19291 (call-interactively 'org-open-at-point))
19292 ((and (org-at-heading-p)
19293 (looking-at
19294 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19295 (org-show-entry)
19296 (end-of-line 1)
19297 (newline))
19298 (t (if indent (newline-and-indent) (newline))))))
19300 (defun org-return-indent ()
19301 "Goto next table row or insert a newline and indent.
19302 Calls `org-table-next-row' or `newline-and-indent', depending on
19303 context. See the individual commands for more information."
19304 (interactive)
19305 (org-return t))
19307 (defun org-ctrl-c-star ()
19308 "Compute table, or change heading status of lines.
19309 Calls `org-table-recalculate' or `org-toggle-heading',
19310 depending on context."
19311 (interactive)
19312 (cond
19313 ((org-at-table-p)
19314 (call-interactively 'org-table-recalculate))
19316 ;; Convert all lines in region to list items
19317 (call-interactively 'org-toggle-heading))))
19319 (defun org-ctrl-c-minus ()
19320 "Insert separator line in table or modify bullet status of line.
19321 Also turns a plain line or a region of lines into list items.
19322 Calls `org-table-insert-hline', `org-toggle-item', or
19323 `org-cycle-list-bullet', depending on context."
19324 (interactive)
19325 (cond
19326 ((org-at-table-p)
19327 (call-interactively 'org-table-insert-hline))
19328 ((org-region-active-p)
19329 (call-interactively 'org-toggle-item))
19330 ((org-in-item-p)
19331 (call-interactively 'org-cycle-list-bullet))
19333 (call-interactively 'org-toggle-item))))
19335 (defun org-toggle-item (arg)
19336 "Convert headings or normal lines to items, items to normal lines.
19337 If there is no active region, only the current line is considered.
19339 If the first non blank line in the region is an headline, convert
19340 all headlines to items, shifting text accordingly.
19342 If it is an item, convert all items to normal lines.
19344 If it is normal text, change region into an item. With a prefix
19345 argument ARG, change each line in region into an item."
19346 (interactive "P")
19347 (let ((shift-text
19348 (function
19349 ;; Shift text in current section to IND, from point to END.
19350 ;; The function leaves point to END line.
19351 (lambda (ind end)
19352 (let ((min-i 1000) (end (copy-marker end)))
19353 ;; First determine the minimum indentation (MIN-I) of
19354 ;; the text.
19355 (save-excursion
19356 (catch 'exit
19357 (while (< (point) end)
19358 (let ((i (org-get-indentation)))
19359 (cond
19360 ;; Skip blank lines and inline tasks.
19361 ((looking-at "^[ \t]*$"))
19362 ((looking-at org-outline-regexp-bol))
19363 ;; We can't find less than 0 indentation.
19364 ((zerop i) (throw 'exit (setq min-i 0)))
19365 ((< i min-i) (setq min-i i))))
19366 (forward-line))))
19367 ;; Then indent each line so that a line indented to
19368 ;; MIN-I becomes indented to IND. Ignore blank lines
19369 ;; and inline tasks in the process.
19370 (let ((delta (- ind min-i)))
19371 (while (< (point) end)
19372 (unless (or (looking-at "^[ \t]*$")
19373 (looking-at org-outline-regexp-bol))
19374 (org-indent-line-to (+ (org-get-indentation) delta)))
19375 (forward-line)))))))
19376 (skip-blanks
19377 (function
19378 ;; Return beginning of first non-blank line, starting from
19379 ;; line at POS.
19380 (lambda (pos)
19381 (save-excursion
19382 (goto-char pos)
19383 (skip-chars-forward " \r\t\n")
19384 (point-at-bol)))))
19385 beg end)
19386 ;; Determine boundaries of changes.
19387 (if (org-region-active-p)
19388 (setq beg (funcall skip-blanks (region-beginning))
19389 end (copy-marker (region-end)))
19390 (setq beg (funcall skip-blanks (point-at-bol))
19391 end (copy-marker (point-at-eol))))
19392 ;; Depending on the starting line, choose an action on the text
19393 ;; between BEG and END.
19394 (org-with-limited-levels
19395 (save-excursion
19396 (goto-char beg)
19397 (cond
19398 ;; Case 1. Start at an item: de-itemize. Note that it only
19399 ;; happens when a region is active: `org-ctrl-c-minus'
19400 ;; would call `org-cycle-list-bullet' otherwise.
19401 ((org-at-item-p)
19402 (while (< (point) end)
19403 (when (org-at-item-p)
19404 (skip-chars-forward " \t")
19405 (delete-region (point) (match-end 0)))
19406 (forward-line)))
19407 ;; Case 2. Start at an heading: convert to items.
19408 ((org-at-heading-p)
19409 (let* ((bul (org-list-bullet-string "-"))
19410 (bul-len (length bul))
19411 ;; Indentation of the first heading. It should be
19412 ;; relative to the indentation of its parent, if any.
19413 (start-ind (save-excursion
19414 (cond
19415 ((not org-adapt-indentation) 0)
19416 ((not (outline-previous-heading)) 0)
19417 (t (length (match-string 0))))))
19418 ;; Level of first heading. Further headings will be
19419 ;; compared to it to determine hierarchy in the list.
19420 (ref-level (org-reduced-level (org-outline-level))))
19421 (while (< (point) end)
19422 (let* ((level (org-reduced-level (org-outline-level)))
19423 (delta (max 0 (- level ref-level))))
19424 ;; If current headline is less indented than the first
19425 ;; one, set it as reference, in order to preserve
19426 ;; subtrees.
19427 (when (< level ref-level) (setq ref-level level))
19428 (replace-match bul t t)
19429 (org-indent-line-to (+ start-ind (* delta bul-len)))
19430 ;; Ensure all text down to END (or SECTION-END) belongs
19431 ;; to the newly created item.
19432 (let ((section-end (save-excursion
19433 (or (outline-next-heading) (point)))))
19434 (forward-line)
19435 (funcall shift-text
19436 (+ start-ind (* (1+ delta) bul-len))
19437 (min end section-end)))))))
19438 ;; Case 3. Normal line with ARG: turn each non-item line into
19439 ;; an item.
19440 (arg
19441 (while (< (point) end)
19442 (unless (or (org-at-heading-p) (org-at-item-p))
19443 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19444 (replace-match
19445 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19446 (forward-line)))
19447 ;; Case 4. Normal line without ARG: make the first line of
19448 ;; region an item, and shift indentation of others
19449 ;; lines to set them as item's body.
19450 (t (let* ((bul (org-list-bullet-string "-"))
19451 (bul-len (length bul))
19452 (ref-ind (org-get-indentation)))
19453 (skip-chars-forward " \t")
19454 (insert bul)
19455 (forward-line)
19456 (while (< (point) end)
19457 ;; Ensure that lines less indented than first one
19458 ;; still get included in item body.
19459 (funcall shift-text
19460 (+ ref-ind bul-len)
19461 (min end (save-excursion (or (outline-next-heading)
19462 (point)))))
19463 (forward-line)))))))))
19465 (defun org-toggle-heading (&optional nstars)
19466 "Convert headings to normal text, or items or text to headings.
19467 If there is no active region, only the current line is considered.
19469 With a \\[universal-argument] prefix, convert the whole list at
19470 point into heading.
19472 In a region:
19474 - If the first non blank line is an headline, remove the stars
19475 from all headlines in the region.
19477 - If it is a normal line turn each and every normal line (i.e. not an
19478 heading or an item) in the region into a heading.
19480 - If it is a plain list item, turn all plain list items into headings.
19482 When converting a line into a heading, the number of stars is chosen
19483 such that the lines become children of the current entry. However,
19484 when a prefix argument is given, its value determines the number of
19485 stars to add."
19486 (interactive "P")
19487 (let ((skip-blanks
19488 (function
19489 ;; Return beginning of first non-blank line, starting from
19490 ;; line at POS.
19491 (lambda (pos)
19492 (save-excursion
19493 (goto-char pos)
19494 (while (org-at-comment-p) (forward-line))
19495 (skip-chars-forward " \r\t\n")
19496 (point-at-bol)))))
19497 beg end toggled)
19498 ;; Determine boundaries of changes. If a universal prefix has
19499 ;; been given, put the list in a region. If region ends at a bol,
19500 ;; do not consider the last line to be in the region.
19502 (when (and current-prefix-arg (org-at-item-p))
19503 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19504 (org-mark-element))
19506 (if (org-region-active-p)
19507 (setq beg (funcall skip-blanks (region-beginning))
19508 end (copy-marker (save-excursion
19509 (goto-char (region-end))
19510 (if (bolp) (point) (point-at-eol)))))
19511 (setq beg (funcall skip-blanks (point-at-bol))
19512 end (copy-marker (point-at-eol))))
19513 ;; Ensure inline tasks don't count as headings.
19514 (org-with-limited-levels
19515 (save-excursion
19516 (goto-char beg)
19517 (cond
19518 ;; Case 1. Started at an heading: de-star headings.
19519 ((org-at-heading-p)
19520 (while (< (point) end)
19521 (when (org-at-heading-p t)
19522 (looking-at org-outline-regexp) (replace-match "")
19523 (setq toggled t))
19524 (forward-line)))
19525 ;; Case 2. Started at an item: change items into headlines.
19526 ;; One star will be added by `org-list-to-subtree'.
19527 ((org-at-item-p)
19528 (let* ((stars (make-string
19529 (if nstars
19530 ;; subtract the star that will be added again by
19531 ;; `org-list-to-subtree'
19532 (1- (prefix-numeric-value current-prefix-arg))
19533 (or (org-current-level) 0))
19534 ?*))
19535 (add-stars
19536 (cond (nstars "") ; stars from prefix only
19537 ((equal stars "") "") ; before first heading
19538 (org-odd-levels-only "*") ; inside heading, odd
19539 (t "")))) ; inside heading, oddeven
19540 (while (< (point) end)
19541 (when (org-at-item-p)
19542 ;; Pay attention to cases when region ends before list.
19543 (let* ((struct (org-list-struct))
19544 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19545 (save-restriction
19546 (narrow-to-region (point) list-end)
19547 (insert
19548 (org-list-to-subtree
19549 (org-list-parse-list t)
19550 '(:istart (concat stars add-stars (funcall get-stars depth))
19551 :icount (concat stars add-stars (funcall get-stars depth)))))))
19552 (setq toggled t))
19553 (forward-line))))
19554 ;; Case 3. Started at normal text: make every line an heading,
19555 ;; skipping headlines and items.
19556 (t (let* ((stars (make-string
19557 (if nstars
19558 (prefix-numeric-value current-prefix-arg)
19559 (or (org-current-level) 0))
19560 ?*))
19561 (add-stars
19562 (cond (nstars "") ; stars from prefix only
19563 ((equal stars "") "*") ; before first heading
19564 (org-odd-levels-only "**") ; inside heading, odd
19565 (t "*"))) ; inside heading, oddeven
19566 (rpl (concat stars add-stars " ")))
19567 (while (< (point) end)
19568 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19569 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19570 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19571 (forward-line)))))))
19572 (unless toggled (message "Cannot toggle heading from here"))))
19574 (defun org-meta-return (&optional arg)
19575 "Insert a new heading or wrap a region in a table.
19576 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19577 See the individual commands for more information."
19578 (interactive "P")
19579 (cond
19580 ((run-hook-with-args-until-success 'org-metareturn-hook))
19581 ((or (org-at-drawer-p) (org-at-property-p))
19582 (newline-and-indent))
19583 ((org-at-table-p)
19584 (call-interactively 'org-table-wrap-region))
19585 (t (call-interactively 'org-insert-heading))))
19587 ;;; Menu entries
19589 (defsubst org-in-subtree-not-table-p ()
19590 "Are we in a subtree and not in a table?"
19591 (and (not (org-before-first-heading-p))
19592 (not (org-at-table-p))))
19594 ;; Define the Org-mode menus
19595 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19596 '("Tbl"
19597 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19598 ["Next Field" org-cycle (org-at-table-p)]
19599 ["Previous Field" org-shifttab (org-at-table-p)]
19600 ["Next Row" org-return (org-at-table-p)]
19601 "--"
19602 ["Blank Field" org-table-blank-field (org-at-table-p)]
19603 ["Edit Field" org-table-edit-field (org-at-table-p)]
19604 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19605 "--"
19606 ("Column"
19607 ["Move Column Left" org-metaleft (org-at-table-p)]
19608 ["Move Column Right" org-metaright (org-at-table-p)]
19609 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19610 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19611 ("Row"
19612 ["Move Row Up" org-metaup (org-at-table-p)]
19613 ["Move Row Down" org-metadown (org-at-table-p)]
19614 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19615 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19616 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19617 "--"
19618 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19619 ("Rectangle"
19620 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19621 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19622 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19623 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19624 "--"
19625 ("Calculate"
19626 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19627 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19628 ["Edit Formulas" org-edit-special (org-at-table-p)]
19629 "--"
19630 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19631 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19632 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19633 "--"
19634 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19635 "--"
19636 ["Sum Column/Rectangle" org-table-sum
19637 (or (org-at-table-p) (org-region-active-p))]
19638 ["Which Column?" org-table-current-column (org-at-table-p)])
19639 ["Debug Formulas"
19640 org-table-toggle-formula-debugger
19641 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19642 ["Show Col/Row Numbers"
19643 org-table-toggle-coordinate-overlays
19644 :style toggle
19645 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19646 "--"
19647 ["Create" org-table-create (and (not (org-at-table-p))
19648 org-enable-table-editor)]
19649 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19650 ["Import from File" org-table-import (not (org-at-table-p))]
19651 ["Export to File" org-table-export (org-at-table-p)]
19652 "--"
19653 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19655 (easy-menu-define org-org-menu org-mode-map "Org menu"
19656 '("Org"
19657 ("Show/Hide"
19658 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19659 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19660 ["Sparse Tree..." org-sparse-tree t]
19661 ["Reveal Context" org-reveal t]
19662 ["Show All" show-all t]
19663 "--"
19664 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19665 "--"
19666 ["New Heading" org-insert-heading t]
19667 ("Navigate Headings"
19668 ["Up" outline-up-heading t]
19669 ["Next" outline-next-visible-heading t]
19670 ["Previous" outline-previous-visible-heading t]
19671 ["Next Same Level" outline-forward-same-level t]
19672 ["Previous Same Level" outline-backward-same-level t]
19673 "--"
19674 ["Jump" org-goto t])
19675 ("Edit Structure"
19676 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
19677 "--"
19678 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
19679 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
19680 "--"
19681 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
19682 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
19683 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19684 "--"
19685 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19686 "--"
19687 ["Copy visible text" org-copy-visible t]
19688 "--"
19689 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
19690 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
19691 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
19692 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
19693 "--"
19694 ["Sort Region/Children" org-sort t]
19695 "--"
19696 ["Convert to odd levels" org-convert-to-odd-levels t]
19697 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19698 ("Editing"
19699 ["Emphasis..." org-emphasize t]
19700 ["Edit Source Example" org-edit-special t]
19701 "--"
19702 ["Footnote new/jump" org-footnote-action t]
19703 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19704 ("Archive"
19705 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
19706 "--"
19707 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
19708 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
19709 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
19711 "--"
19712 ("Hyperlinks"
19713 ["Store Link (Global)" org-store-link t]
19714 ["Find existing link to here" org-occur-link-in-agenda-files t]
19715 ["Insert Link" org-insert-link t]
19716 ["Follow Link" org-open-at-point t]
19717 "--"
19718 ["Next link" org-next-link t]
19719 ["Previous link" org-previous-link t]
19720 "--"
19721 ["Descriptive Links"
19722 org-toggle-link-display
19723 :style radio
19724 :selected org-descriptive-links
19726 ["Literal Links"
19727 org-toggle-link-display
19728 :style radio
19729 :selected (not org-descriptive-links)])
19730 "--"
19731 ("TODO Lists"
19732 ["TODO/DONE/-" org-todo t]
19733 ("Select keyword"
19734 ["Next keyword" org-shiftright (org-at-heading-p)]
19735 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19736 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19737 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19738 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19739 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19740 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19741 "--"
19742 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19743 :selected org-enforce-todo-dependencies :style toggle :active t]
19744 "Settings for tree at point"
19745 ["Do Children sequentially" org-toggle-ordered-property :style radio
19746 :selected (org-entry-get nil "ORDERED")
19747 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19748 ["Do Children parallel" org-toggle-ordered-property :style radio
19749 :selected (not (org-entry-get nil "ORDERED"))
19750 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19751 "--"
19752 ["Set Priority" org-priority t]
19753 ["Priority Up" org-shiftup t]
19754 ["Priority Down" org-shiftdown t]
19755 "--"
19756 ["Get news from all feeds" org-feed-update-all t]
19757 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19758 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19759 ("TAGS and Properties"
19760 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
19761 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19762 "--"
19763 ["Set property" org-set-property (not (org-before-first-heading-p))]
19764 ["Column view of properties" org-columns t]
19765 ["Insert Column View DBlock" org-insert-columns-dblock t])
19766 ("Dates and Scheduling"
19767 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
19768 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
19769 ("Change Date"
19770 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
19771 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
19772 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
19773 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
19774 ["Compute Time Range" org-evaluate-time-range t]
19775 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
19776 ["Deadline" org-deadline (not (org-before-first-heading-p))]
19777 "--"
19778 ["Custom time format" org-toggle-time-stamp-overlays
19779 :style radio :selected org-display-custom-times]
19780 "--"
19781 ["Goto Calendar" org-goto-calendar t]
19782 ["Date from Calendar" org-date-from-calendar t]
19783 "--"
19784 ["Start/Restart Timer" org-timer-start t]
19785 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19786 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19787 ["Insert Timer String" org-timer t]
19788 ["Insert Timer Item" org-timer-item t])
19789 ("Logging work"
19790 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19791 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19792 ["Clock out" org-clock-out t]
19793 ["Clock cancel" org-clock-cancel t]
19794 "--"
19795 ["Mark as default task" org-clock-mark-default-task t]
19796 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19797 ["Goto running clock" org-clock-goto t]
19798 "--"
19799 ["Display times" org-clock-display t]
19800 ["Create clock table" org-clock-report t]
19801 "--"
19802 ["Record DONE time"
19803 (progn (setq org-log-done (not org-log-done))
19804 (message "Switching to %s will %s record a timestamp"
19805 (car org-done-keywords)
19806 (if org-log-done "automatically" "not")))
19807 :style toggle :selected org-log-done])
19808 "--"
19809 ["Agenda Command..." org-agenda t]
19810 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19811 ("File List for Agenda")
19812 ("Special views current file"
19813 ["TODO Tree" org-show-todo-tree t]
19814 ["Check Deadlines" org-check-deadlines t]
19815 ["Timeline" org-timeline t]
19816 ["Tags/Property tree" org-match-sparse-tree t])
19817 "--"
19818 ["Export/Publish..." org-export t]
19819 ("LaTeX"
19820 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19821 :selected org-cdlatex-mode]
19822 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19823 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19824 ["Modify math symbol" org-cdlatex-math-modify
19825 (org-inside-LaTeX-fragment-p)]
19826 ["Insert citation" org-reftex-citation t]
19827 "--"
19828 ["Template for BEAMER" (progn (require 'org-beamer)
19829 (org-insert-beamer-options-template)) t])
19830 "--"
19831 ("MobileOrg"
19832 ["Push Files and Views" org-mobile-push t]
19833 ["Get Captured and Flagged" org-mobile-pull t]
19834 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19835 "--"
19836 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19837 "--"
19838 ("Documentation"
19839 ["Show Version" org-version t]
19840 ["Info Documentation" org-info t])
19841 ("Customize"
19842 ["Browse Org Group" org-customize t]
19843 "--"
19844 ["Expand This Menu" org-create-customize-menu
19845 (fboundp 'customize-menu-create)])
19846 ["Send bug report" org-submit-bug-report t]
19847 "--"
19848 ("Refresh/Reload"
19849 ["Refresh setup current buffer" org-mode-restart t]
19850 ["Reload Org (after update)" org-reload t]
19851 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
19854 (defun org-info (&optional node)
19855 "Read documentation for Org-mode in the info system.
19856 With optional NODE, go directly to that node."
19857 (interactive)
19858 (info (format "(org)%s" (or node ""))))
19860 ;;;###autoload
19861 (defun org-submit-bug-report ()
19862 "Submit a bug report on Org-mode via mail.
19864 Don't hesitate to report any problems or inaccurate documentation.
19866 If you don't have setup sending mail from (X)Emacs, please copy the
19867 output buffer into your mail program, as it gives us important
19868 information about your Org-mode version and configuration."
19869 (interactive)
19870 (require 'reporter)
19871 (org-load-modules-maybe)
19872 (org-require-autoloaded-modules)
19873 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19874 (reporter-submit-bug-report
19875 "emacs-orgmode@gnu.org"
19876 (org-version nil 'full)
19877 (let (list)
19878 (save-window-excursion
19879 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19880 (delete-other-windows)
19881 (erase-buffer)
19882 (insert "You are about to submit a bug report to the Org-mode mailing list.
19884 We would like to add your full Org-mode and Outline configuration to the
19885 bug report. This greatly simplifies the work of the maintainer and
19886 other experts on the mailing list.
19888 HOWEVER, some variables you have customized may contain private
19889 information. The names of customers, colleagues, or friends, might
19890 appear in the form of file names, tags, todo states, or search strings.
19891 If you answer yes to the prompt, you might want to check and remove
19892 such private information before sending the email.")
19893 (add-text-properties (point-min) (point-max) '(face org-warning))
19894 (when (yes-or-no-p "Include your Org-mode configuration ")
19895 (mapatoms
19896 (lambda (v)
19897 (and (boundp v)
19898 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19899 (or (and (symbol-value v)
19900 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19901 (and
19902 (get v 'custom-type) (get v 'standard-value)
19903 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19904 (push v list)))))
19905 (kill-buffer (get-buffer "*Warn about privacy*"))
19906 list))
19907 nil nil
19908 "Remember to cover the basics, that is, what you expected to happen and
19909 what in fact did happen. You don't know how to make a good report? See
19911 http://orgmode.org/manual/Feedback.html#Feedback
19913 Your bug report will be posted to the Org-mode mailing list.
19914 ------------------------------------------------------------------------")
19915 (save-excursion
19916 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19917 (replace-match "\\1Bug: \\3 [\\2]")))))
19920 (defun org-install-agenda-files-menu ()
19921 (let ((bl (buffer-list)))
19922 (save-excursion
19923 (while bl
19924 (set-buffer (pop bl))
19925 (if (derived-mode-p 'org-mode) (setq bl nil)))
19926 (when (derived-mode-p 'org-mode)
19927 (easy-menu-change
19928 '("Org") "File List for Agenda"
19929 (append
19930 (list
19931 ["Edit File List" (org-edit-agenda-file-list) t]
19932 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19933 ["Remove Current File from List" org-remove-file t]
19934 ["Cycle through agenda files" org-cycle-agenda-files t]
19935 ["Occur in all agenda files" org-occur-in-agenda-files t]
19936 "--")
19937 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19939 ;;;; Documentation
19941 (defun org-require-autoloaded-modules ()
19942 (interactive)
19943 (mapc 'require
19944 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19945 org-docbook org-exp org-html org-icalendar
19946 org-id org-latex
19947 org-publish org-remember org-table
19948 org-timer org-xoxo)))
19950 ;;;###autoload
19951 (defun org-reload (&optional uncompiled)
19952 "Reload all org lisp files.
19953 With prefix arg UNCOMPILED, load the uncompiled versions."
19954 (interactive "P")
19955 (require 'find-func)
19956 (let* ((file-re "^org\\(-.*\\)?\\.el")
19957 (dir-org (file-name-directory (org-find-library-dir "org")))
19958 (dir-org-contrib (ignore-errors
19959 (file-name-directory
19960 (org-find-library-dir "org-contribdir"))))
19961 (babel-files
19962 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19963 (append (list nil "comint" "eval" "exp" "keys"
19964 "lob" "ref" "table" "tangle")
19965 (delq nil
19966 (mapcar
19967 (lambda (lang)
19968 (when (cdr lang) (symbol-name (car lang))))
19969 org-babel-load-languages)))))
19970 (files
19971 (append babel-files
19972 (and dir-org-contrib
19973 (directory-files dir-org-contrib t file-re))
19974 (directory-files dir-org t file-re)))
19975 (remove-re (concat (if (featurep 'xemacs)
19976 "org-colview" "org-colview-xemacs")
19977 "\\'")))
19978 (setq files (mapcar 'file-name-sans-extension files))
19979 (setq files (mapcar
19980 (lambda (x) (if (string-match remove-re x) nil x))
19981 files))
19982 (setq files (delq nil files))
19983 (mapc
19984 (lambda (f)
19985 (when (featurep (intern (file-name-nondirectory f)))
19986 (if (and (not uncompiled)
19987 (file-exists-p (concat f ".elc")))
19988 (load (concat f ".elc") nil nil 'nosuffix)
19989 (load (concat f ".el") nil nil 'nosuffix))))
19990 files)
19991 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
19992 (org-version nil 'full 'message))
19994 ;;;###autoload
19995 (defun org-customize ()
19996 "Call the customize function with org as argument."
19997 (interactive)
19998 (org-load-modules-maybe)
19999 (org-require-autoloaded-modules)
20000 (customize-browse 'org))
20002 (defun org-create-customize-menu ()
20003 "Create a full customization menu for Org-mode, insert it into the menu."
20004 (interactive)
20005 (org-load-modules-maybe)
20006 (org-require-autoloaded-modules)
20007 (if (fboundp 'customize-menu-create)
20008 (progn
20009 (easy-menu-change
20010 '("Org") "Customize"
20011 `(["Browse Org group" org-customize t]
20012 "--"
20013 ,(customize-menu-create 'org)
20014 ["Set" Custom-set t]
20015 ["Save" Custom-save t]
20016 ["Reset to Current" Custom-reset-current t]
20017 ["Reset to Saved" Custom-reset-saved t]
20018 ["Reset to Standard Settings" Custom-reset-standard t]))
20019 (message "\"Org\"-menu now contains full customization menu"))
20020 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20022 ;;;; Miscellaneous stuff
20024 ;;; Generally useful functions
20026 (defun org-get-at-bol (property)
20027 "Get text property PROPERTY at beginning of line."
20028 (get-text-property (point-at-bol) property))
20030 (defun org-find-text-property-in-string (prop s)
20031 "Return the first non-nil value of property PROP in string S."
20032 (or (get-text-property 0 prop s)
20033 (get-text-property (or (next-single-property-change 0 prop s) 0)
20034 prop s)))
20036 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20037 "Display the given MESSAGE as a warning."
20038 (if (fboundp 'display-warning)
20039 (display-warning 'org message
20040 (if (featurep 'xemacs) 'warning :warning))
20041 (let ((buf (get-buffer-create "*Org warnings*")))
20042 (with-current-buffer buf
20043 (goto-char (point-max))
20044 (insert "Warning (Org): " message)
20045 (unless (bolp)
20046 (newline)))
20047 (display-buffer buf)
20048 (sit-for 0))))
20050 (defun org-eval (form)
20051 "Eval FORM and return result."
20052 (condition-case error
20053 (eval form)
20054 (error (format "%%![Error: %s]" error))))
20056 (defun org-in-clocktable-p ()
20057 "Check if the cursor is in a clocktable."
20058 (let ((pos (point)) start)
20059 (save-excursion
20060 (end-of-line 1)
20061 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20062 (setq start (match-beginning 0))
20063 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20064 (>= (match-end 0) pos)
20065 start))))
20067 (defun org-in-commented-line ()
20068 "Is point in a line starting with `#'?"
20069 (equal (char-after (point-at-bol)) ?#))
20071 (defun org-in-indented-comment-line ()
20072 "Is point in a line starting with `#' after some white space?"
20073 (save-excursion
20074 (save-match-data
20075 (goto-char (point-at-bol))
20076 (looking-at "[ \t]*#"))))
20078 (defun org-in-verbatim-emphasis ()
20079 (save-match-data
20080 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20082 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20083 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20084 (if (and marker (marker-buffer marker)
20085 (buffer-live-p (marker-buffer marker)))
20086 (progn
20087 (org-pop-to-buffer-same-window (marker-buffer marker))
20088 (if (or (> marker (point-max)) (< marker (point-min)))
20089 (widen))
20090 (goto-char marker)
20091 (org-show-context 'org-goto))
20092 (if bookmark
20093 (bookmark-jump bookmark)
20094 (error "Cannot find location"))))
20096 (defun org-quote-csv-field (s)
20097 "Quote field for inclusion in CSV material."
20098 (if (string-match "[\",]" s)
20099 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20102 (defun org-force-self-insert (N)
20103 "Needed to enforce self-insert under remapping."
20104 (interactive "p")
20105 (self-insert-command N))
20107 (defun org-string-width (s)
20108 "Compute width of string, ignoring invisible characters.
20109 This ignores character with invisibility property `org-link', and also
20110 characters with property `org-cwidth', because these will become invisible
20111 upon the next fontification round."
20112 (let (b l)
20113 (when (or (eq t buffer-invisibility-spec)
20114 (assq 'org-link buffer-invisibility-spec))
20115 (while (setq b (text-property-any 0 (length s)
20116 'invisible 'org-link s))
20117 (setq s (concat (substring s 0 b)
20118 (substring s (or (next-single-property-change
20119 b 'invisible s) (length s)))))))
20120 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20121 (setq s (concat (substring s 0 b)
20122 (substring s (or (next-single-property-change
20123 b 'org-cwidth s) (length s))))))
20124 (setq l (string-width s) b -1)
20125 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20126 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20129 (defun org-shorten-string (s maxlength)
20130 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20131 If the string is shorter or has length MAXLENGTH, just return the
20132 original string. If it is longer, the functions finds a space in the
20133 string, breaks this string off at that locations and adds three dots
20134 as ellipsis. Including the ellipsis, the string will not be longer
20135 than MAXLENGTH. If finding a good breaking point in the string does
20136 not work, the string is just chopped off in the middle of a word
20137 if necessary."
20138 (if (<= (length s) maxlength)
20140 (let* ((n (max (- maxlength 4) 1))
20141 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20142 (if (string-match re s)
20143 (concat (match-string 1 s) "...")
20144 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20146 (defun org-get-indentation (&optional line)
20147 "Get the indentation of the current line, interpreting tabs.
20148 When LINE is given, assume it represents a line and compute its indentation."
20149 (if line
20150 (if (string-match "^ *" (org-remove-tabs line))
20151 (match-end 0))
20152 (save-excursion
20153 (beginning-of-line 1)
20154 (skip-chars-forward " \t")
20155 (current-column))))
20157 (defun org-get-string-indentation (s)
20158 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20159 (let ((n -1) (i 0) (w tab-width) c)
20160 (catch 'exit
20161 (while (< (setq n (1+ n)) (length s))
20162 (setq c (aref s n))
20163 (cond ((= c ?\ ) (setq i (1+ i)))
20164 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20165 (t (throw 'exit t)))))
20168 (defun org-remove-tabs (s &optional width)
20169 "Replace tabulators in S with spaces.
20170 Assumes that s is a single line, starting in column 0."
20171 (setq width (or width tab-width))
20172 (while (string-match "\t" s)
20173 (setq s (replace-match
20174 (make-string
20175 (- (* width (/ (+ (match-beginning 0) width) width))
20176 (match-beginning 0)) ?\ )
20177 t t s)))
20180 (defun org-fix-indentation (line ind)
20181 "Fix indentation in LINE.
20182 IND is a cons cell with target and minimum indentation.
20183 If the current indentation in LINE is smaller than the minimum,
20184 leave it alone. If it is larger than ind, set it to the target."
20185 (let* ((l (org-remove-tabs line))
20186 (i (org-get-indentation l))
20187 (i1 (car ind)) (i2 (cdr ind)))
20188 (if (>= i i2) (setq l (substring line i2)))
20189 (if (> i1 0)
20190 (concat (make-string i1 ?\ ) l)
20191 l)))
20193 (defun org-remove-indentation (code &optional n)
20194 "Remove the maximum common indentation from the lines in CODE.
20195 N may optionally be the number of spaces to remove."
20196 (with-temp-buffer
20197 (insert code)
20198 (org-do-remove-indentation n)
20199 (buffer-string)))
20201 (defun org-do-remove-indentation (&optional n)
20202 "Remove the maximum common indentation from the buffer."
20203 (untabify (point-min) (point-max))
20204 (let ((min 10000) re)
20205 (if n
20206 (setq min n)
20207 (goto-char (point-min))
20208 (while (re-search-forward "^ *[^ \n]" nil t)
20209 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20210 (unless (or (= min 0) (= min 10000))
20211 (setq re (format "^ \\{%d\\}" min))
20212 (goto-char (point-min))
20213 (while (re-search-forward re nil t)
20214 (replace-match "")
20215 (end-of-line 1))
20216 min)))
20218 (defun org-fill-template (template alist)
20219 "Find each %key of ALIST in TEMPLATE and replace it."
20220 (let ((case-fold-search nil)
20221 entry key value)
20222 (setq alist (sort (copy-sequence alist)
20223 (lambda (a b) (< (length (car a)) (length (car b))))))
20224 (while (setq entry (pop alist))
20225 (setq template
20226 (replace-regexp-in-string
20227 (concat "%" (regexp-quote (car entry)))
20228 (or (cdr entry) "") template t t)))
20229 template))
20231 (defun org-base-buffer (buffer)
20232 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20233 (if (not buffer)
20234 buffer
20235 (or (buffer-base-buffer buffer)
20236 buffer)))
20238 (defun org-trim (s)
20239 "Remove whitespace at beginning and end of string."
20240 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20241 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20244 (defun org-wrap (string &optional width lines)
20245 "Wrap string to either a number of lines, or a width in characters.
20246 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20247 that costs. If there is a word longer than WIDTH, the text is actually
20248 wrapped to the length of that word.
20249 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20250 many lines, whatever width that takes.
20251 The return value is a list of lines, without newlines at the end."
20252 (let* ((words (org-split-string string "[ \t\n]+"))
20253 (maxword (apply 'max (mapcar 'org-string-width words)))
20254 w ll)
20255 (cond (width
20256 (org-do-wrap words (max maxword width)))
20257 (lines
20258 (setq w maxword)
20259 (setq ll (org-do-wrap words maxword))
20260 (if (<= (length ll) lines)
20262 (setq ll words)
20263 (while (> (length ll) lines)
20264 (setq w (1+ w))
20265 (setq ll (org-do-wrap words w)))
20266 ll))
20267 (t (error "Cannot wrap this")))))
20269 (defun org-do-wrap (words width)
20270 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20271 (let (lines line)
20272 (while words
20273 (setq line (pop words))
20274 (while (and words (< (+ (length line) (length (car words))) width))
20275 (setq line (concat line " " (pop words))))
20276 (setq lines (push line lines)))
20277 (nreverse lines)))
20279 (defun org-split-string (string &optional separators)
20280 "Splits STRING into substrings at SEPARATORS.
20281 No empty strings are returned if there are matches at the beginning
20282 and end of string."
20283 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20284 (start 0)
20285 notfirst
20286 (list nil))
20287 (while (and (string-match rexp string
20288 (if (and notfirst
20289 (= start (match-beginning 0))
20290 (< start (length string)))
20291 (1+ start) start))
20292 (< (match-beginning 0) (length string)))
20293 (setq notfirst t)
20294 (or (eq (match-beginning 0) 0)
20295 (and (eq (match-beginning 0) (match-end 0))
20296 (eq (match-beginning 0) start))
20297 (setq list
20298 (cons (substring string start (match-beginning 0))
20299 list)))
20300 (setq start (match-end 0)))
20301 (or (eq start (length string))
20302 (setq list
20303 (cons (substring string start)
20304 list)))
20305 (nreverse list)))
20307 (defun org-quote-vert (s)
20308 "Replace \"|\" with \"\\vert\"."
20309 (while (string-match "|" s)
20310 (setq s (replace-match "\\vert" t t s)))
20313 (defun org-uuidgen-p (s)
20314 "Is S an ID created by UUIDGEN?"
20315 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20317 (defun org-in-src-block-p (&optional inside)
20318 "Whether point is in a code source block.
20319 When INSIDE is non-nil, don't consider we are within a src block
20320 when point is at #+BEGIN_SRC or #+END_SRC."
20321 (let ((case-fold-search t) ov)
20322 (or (and (setq ov (overlays-at (point)))
20323 (memq 'org-block-background
20324 (overlay-properties (car ov))))
20325 (and (not inside)
20326 (save-match-data
20327 (save-excursion
20328 (beginning-of-line)
20329 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20331 (defun org-context ()
20332 "Return a list of contexts of the current cursor position.
20333 If several contexts apply, all are returned.
20334 Each context entry is a list with a symbol naming the context, and
20335 two positions indicating start and end of the context. Possible
20336 contexts are:
20338 :headline anywhere in a headline
20339 :headline-stars on the leading stars in a headline
20340 :todo-keyword on a TODO keyword (including DONE) in a headline
20341 :tags on the TAGS in a headline
20342 :priority on the priority cookie in a headline
20343 :item on the first line of a plain list item
20344 :item-bullet on the bullet/number of a plain list item
20345 :checkbox on the checkbox in a plain list item
20346 :table in an org-mode table
20347 :table-special on a special filed in a table
20348 :table-table in a table.el table
20349 :clocktable in a clocktable
20350 :src-block in a source block
20351 :link on a hyperlink
20352 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20353 :target on a <<target>>
20354 :radio-target on a <<<radio-target>>>
20355 :latex-fragment on a LaTeX fragment
20356 :latex-preview on a LaTeX fragment with overlaid preview image
20358 This function expects the position to be visible because it uses font-lock
20359 faces as a help to recognize the following contexts: :table-special, :link,
20360 and :keyword."
20361 (let* ((f (get-text-property (point) 'face))
20362 (faces (if (listp f) f (list f)))
20363 (case-fold-search t)
20364 (p (point)) clist o)
20365 ;; First the large context
20366 (cond
20367 ((org-at-heading-p t)
20368 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20369 (when (progn
20370 (beginning-of-line 1)
20371 (looking-at org-todo-line-tags-regexp))
20372 (push (org-point-in-group p 1 :headline-stars) clist)
20373 (push (org-point-in-group p 2 :todo-keyword) clist)
20374 (push (org-point-in-group p 4 :tags) clist))
20375 (goto-char p)
20376 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20377 (if (looking-at "\\[#[A-Z0-9]\\]")
20378 (push (org-point-in-group p 0 :priority) clist)))
20380 ((org-at-item-p)
20381 (push (org-point-in-group p 2 :item-bullet) clist)
20382 (push (list :item (point-at-bol)
20383 (save-excursion (org-end-of-item) (point)))
20384 clist)
20385 (and (org-at-item-checkbox-p)
20386 (push (org-point-in-group p 0 :checkbox) clist)))
20388 ((org-at-table-p)
20389 (push (list :table (org-table-begin) (org-table-end)) clist)
20390 (if (memq 'org-formula faces)
20391 (push (list :table-special
20392 (previous-single-property-change p 'face)
20393 (next-single-property-change p 'face)) clist)))
20394 ((org-at-table-p 'any)
20395 (push (list :table-table) clist)))
20396 (goto-char p)
20398 (let ((case-fold-search t))
20399 ;; New the "medium" contexts: clocktables, source blocks
20400 (cond ((org-in-clocktable-p)
20401 (push (list :clocktable
20402 (and (or (looking-at "#\\+BEGIN: clocktable")
20403 (search-backward "#+BEGIN: clocktable" nil t))
20404 (match-beginning 0))
20405 (and (re-search-forward "#\\+END:?" nil t)
20406 (match-end 0))) clist))
20407 ((org-in-src-block-p)
20408 (push (list :src-block
20409 (and (or (looking-at "#\\+BEGIN_SRC")
20410 (search-backward "#+BEGIN_SRC" nil t))
20411 (match-beginning 0))
20412 (and (search-forward "#+END_SRC" nil t)
20413 (match-beginning 0))) clist))))
20414 (goto-char p)
20416 ;; Now the small context
20417 (cond
20418 ((org-at-timestamp-p)
20419 (push (org-point-in-group p 0 :timestamp) clist))
20420 ((memq 'org-link faces)
20421 (push (list :link
20422 (previous-single-property-change p 'face)
20423 (next-single-property-change p 'face)) clist))
20424 ((memq 'org-special-keyword faces)
20425 (push (list :keyword
20426 (previous-single-property-change p 'face)
20427 (next-single-property-change p 'face)) clist))
20428 ((org-at-target-p)
20429 (push (org-point-in-group p 0 :target) clist)
20430 (goto-char (1- (match-beginning 0)))
20431 (if (looking-at org-radio-target-regexp)
20432 (push (org-point-in-group p 0 :radio-target) clist))
20433 (goto-char p))
20434 ((setq o (car (delq nil
20435 (mapcar
20436 (lambda (x)
20437 (if (memq x org-latex-fragment-image-overlays) x))
20438 (overlays-at (point))))))
20439 (push (list :latex-fragment
20440 (overlay-start o) (overlay-end o)) clist)
20441 (push (list :latex-preview
20442 (overlay-start o) (overlay-end o)) clist))
20443 ((org-inside-LaTeX-fragment-p)
20444 ;; FIXME: positions wrong.
20445 (push (list :latex-fragment (point) (point)) clist)))
20447 (setq clist (nreverse (delq nil clist)))
20448 clist))
20450 ;; FIXME: Compare with at-regexp-p Do we need both?
20451 (defun org-in-regexp (re &optional nlines visually)
20452 "Check if point is inside a match of regexp.
20453 Normally only the current line is checked, but you can include NLINES extra
20454 lines both before and after point into the search.
20455 If VISUALLY is set, require that the cursor is not after the match but
20456 really on, so that the block visually is on the match."
20457 (catch 'exit
20458 (let ((pos (point))
20459 (eol (point-at-eol (+ 1 (or nlines 0))))
20460 (inc (if visually 1 0)))
20461 (save-excursion
20462 (beginning-of-line (- 1 (or nlines 0)))
20463 (while (re-search-forward re eol t)
20464 (if (and (<= (match-beginning 0) pos)
20465 (>= (+ inc (match-end 0)) pos))
20466 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20468 (defun org-at-regexp-p (regexp)
20469 "Is point inside a match of REGEXP in the current line?"
20470 (catch 'exit
20471 (save-excursion
20472 (let ((pos (point)) (end (point-at-eol)))
20473 (beginning-of-line 1)
20474 (while (re-search-forward regexp end t)
20475 (if (and (<= (match-beginning 0) pos)
20476 (>= (match-end 0) pos))
20477 (throw 'exit t)))
20478 nil))))
20480 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20481 "Non-nil when point is between matches of START-RE and END-RE.
20483 Also return a non-nil value when point is on one of the matches.
20485 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20486 buffer positions. Default values are the positions of headlines
20487 surrounding the point.
20489 The functions returns a cons cell whose car (resp. cdr) is the
20490 position before START-RE (resp. after END-RE)."
20491 (save-match-data
20492 (let ((pos (point))
20493 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20494 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20495 beg end)
20496 (save-excursion
20497 ;; Point is on a block when on START-RE or if START-RE can be
20498 ;; found before it...
20499 (and (or (org-at-regexp-p start-re)
20500 (re-search-backward start-re limit-up t))
20501 (setq beg (match-beginning 0))
20502 ;; ... and END-RE after it...
20503 (goto-char (match-end 0))
20504 (re-search-forward end-re limit-down t)
20505 (> (setq end (match-end 0)) pos)
20506 ;; ... without another START-RE in-between.
20507 (goto-char (match-beginning 0))
20508 (not (re-search-backward start-re (1+ beg) t))
20509 ;; Return value.
20510 (cons beg end))))))
20512 (defun org-in-block-p (names)
20513 "Non-nil when point belongs to a block whose name belongs to NAMES.
20515 NAMES is a list of strings containing names of blocks.
20517 Return first block name matched, or nil. Beware that in case of
20518 nested blocks, the returned name may not belong to the closest
20519 block from point."
20520 (save-match-data
20521 (catch 'exit
20522 (let ((case-fold-search t)
20523 (lim-up (save-excursion (outline-previous-heading)))
20524 (lim-down (save-excursion (outline-next-heading))))
20525 (mapc (lambda (name)
20526 (let ((n (regexp-quote name)))
20527 (when (org-between-regexps-p
20528 (concat "^[ \t]*#\\+begin_" n)
20529 (concat "^[ \t]*#\\+end_" n)
20530 lim-up lim-down)
20531 (throw 'exit n))))
20532 names))
20533 nil)))
20535 (defun org-occur-in-agenda-files (regexp &optional nlines)
20536 "Call `multi-occur' with buffers for all agenda files."
20537 (interactive "sOrg-files matching: \np")
20538 (let* ((files (org-agenda-files))
20539 (tnames (mapcar 'file-truename files))
20540 (extra org-agenda-text-search-extra-files)
20542 (when (eq (car extra) 'agenda-archives)
20543 (setq extra (cdr extra))
20544 (setq files (org-add-archive-files files)))
20545 (while (setq f (pop extra))
20546 (unless (member (file-truename f) tnames)
20547 (add-to-list 'files f 'append)
20548 (add-to-list 'tnames (file-truename f) 'append)))
20549 (multi-occur
20550 (mapcar (lambda (x)
20551 (with-current-buffer
20552 (or (get-file-buffer x) (find-file-noselect x))
20553 (widen)
20554 (current-buffer)))
20555 files)
20556 regexp)))
20558 (if (boundp 'occur-mode-find-occurrence-hook)
20559 ;; Emacs 23
20560 (add-hook 'occur-mode-find-occurrence-hook
20561 (lambda ()
20562 (when (derived-mode-p 'org-mode)
20563 (org-reveal))))
20564 ;; Emacs 22
20565 (defadvice occur-mode-goto-occurrence
20566 (after org-occur-reveal activate)
20567 (and (derived-mode-p 'org-mode) (org-reveal)))
20568 (defadvice occur-mode-goto-occurrence-other-window
20569 (after org-occur-reveal activate)
20570 (and (derived-mode-p 'org-mode) (org-reveal)))
20571 (defadvice occur-mode-display-occurrence
20572 (after org-occur-reveal activate)
20573 (when (derived-mode-p 'org-mode)
20574 (let ((pos (occur-mode-find-occurrence)))
20575 (with-current-buffer (marker-buffer pos)
20576 (save-excursion
20577 (goto-char pos)
20578 (org-reveal)))))))
20580 (defun org-occur-link-in-agenda-files ()
20581 "Create a link and search for it in the agendas.
20582 The link is not stored in `org-stored-links', it is just created
20583 for the search purpose."
20584 (interactive)
20585 (let ((link (condition-case nil
20586 (org-store-link nil)
20587 (error "Unable to create a link to here"))))
20588 (org-occur-in-agenda-files (regexp-quote link))))
20590 (defun org-uniquify (list)
20591 "Remove duplicate elements from LIST."
20592 (let (res)
20593 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20594 res))
20596 (defun org-delete-all (elts list)
20597 "Remove all elements in ELTS from LIST."
20598 (while elts
20599 (setq list (delete (pop elts) list)))
20600 list)
20602 (defun org-count (cl-item cl-seq)
20603 "Count the number of occurrences of ITEM in SEQ.
20604 Taken from `count' in cl-seq.el with all keyword arguments removed."
20605 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20606 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20607 (while (< cl-start cl-end)
20608 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20609 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20610 (setq cl-start (1+ cl-start)))
20611 cl-count))
20613 (defun org-remove-if (predicate seq)
20614 "Remove everything from SEQ that fulfills PREDICATE."
20615 (let (res e)
20616 (while seq
20617 (setq e (pop seq))
20618 (if (not (funcall predicate e)) (push e res)))
20619 (nreverse res)))
20621 (defun org-remove-if-not (predicate seq)
20622 "Remove everything from SEQ that does not fulfill PREDICATE."
20623 (let (res e)
20624 (while seq
20625 (setq e (pop seq))
20626 (if (funcall predicate e) (push e res)))
20627 (nreverse res)))
20629 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20630 "Reduce two-argument FUNCTION across SEQ.
20631 Taken from `reduce' in cl-seq.el with all keyword arguments but
20632 \":initial-value\" removed."
20633 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20634 (cadr (memq :initial-value cl-keys)))
20635 (cl-seq (pop cl-seq))
20636 (t (funcall cl-func)))))
20637 (while cl-seq
20638 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20639 cl-accum))
20641 (defun org-back-over-empty-lines ()
20642 "Move backwards over whitespace, to the beginning of the first empty line.
20643 Returns the number of empty lines passed."
20644 (let ((pos (point)))
20645 (if (cdr (assoc 'heading org-blank-before-new-entry))
20646 (skip-chars-backward " \t\n\r")
20647 (unless (eobp)
20648 (forward-line -1)))
20649 (beginning-of-line 2)
20650 (goto-char (min (point) pos))
20651 (count-lines (point) pos)))
20653 (defun org-skip-whitespace ()
20654 (skip-chars-forward " \t\n\r"))
20656 (defun org-point-in-group (point group &optional context)
20657 "Check if POINT is in match-group GROUP.
20658 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20659 match. If the match group does not exist or point is not inside it,
20660 return nil."
20661 (and (match-beginning group)
20662 (>= point (match-beginning group))
20663 (<= point (match-end group))
20664 (if context
20665 (list context (match-beginning group) (match-end group))
20666 t)))
20668 (defun org-switch-to-buffer-other-window (&rest args)
20669 "Switch to buffer in a second window on the current frame.
20670 In particular, do not allow pop-up frames.
20671 Returns the newly created buffer."
20672 (org-no-popups
20673 (apply 'switch-to-buffer-other-window args)))
20675 (defun org-combine-plists (&rest plists)
20676 "Create a single property list from all plists in PLISTS.
20677 The process starts by copying the first list, and then setting properties
20678 from the other lists. Settings in the last list are the most significant
20679 ones and overrule settings in the other lists."
20680 (let ((rtn (copy-sequence (pop plists)))
20681 p v ls)
20682 (while plists
20683 (setq ls (pop plists))
20684 (while ls
20685 (setq p (pop ls) v (pop ls))
20686 (setq rtn (plist-put rtn p v))))
20687 rtn))
20689 (defun org-replace-escapes (string table)
20690 "Replace %-escapes in STRING with values in TABLE.
20691 TABLE is an association list with keys like \"%a\" and string values.
20692 The sequences in STRING may contain normal field width and padding information,
20693 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20694 so values can contain further %-escapes if they are define later in TABLE."
20695 (let ((tbl (copy-alist table))
20696 (case-fold-search nil)
20697 (pchg 0)
20698 e re rpl)
20699 (while (setq e (pop tbl))
20700 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20701 (when (and (cdr e) (string-match re (cdr e)))
20702 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20703 (safe "SREF"))
20704 (add-text-properties 0 3 (list 'sref sref) safe)
20705 (setcdr e (replace-match safe t t (cdr e)))))
20706 (while (string-match re string)
20707 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20708 (cdr e)))
20709 (setq string (replace-match rpl t t string))))
20710 (while (setq pchg (next-property-change pchg string))
20711 (let ((sref (get-text-property pchg 'sref string)))
20712 (when (and sref (string-match "SREF" string pchg))
20713 (setq string (replace-match sref t t string)))))
20714 string))
20716 (defun org-sublist (list start end)
20717 "Return a section of LIST, from START to END.
20718 Counting starts at 1."
20719 (let (rtn (c start))
20720 (setq list (nthcdr (1- start) list))
20721 (while (and list (<= c end))
20722 (push (pop list) rtn)
20723 (setq c (1+ c)))
20724 (nreverse rtn)))
20726 (defun org-find-base-buffer-visiting (file)
20727 "Like `find-buffer-visiting' but always return the base buffer and
20728 not an indirect buffer."
20729 (let ((buf (or (get-file-buffer file)
20730 (find-buffer-visiting file))))
20731 (if buf
20732 (or (buffer-base-buffer buf) buf)
20733 nil)))
20735 (defun org-image-file-name-regexp (&optional extensions)
20736 "Return regexp matching the file names of images.
20737 If EXTENSIONS is given, only match these."
20738 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20739 (image-file-name-regexp)
20740 (let ((image-file-name-extensions
20741 (or extensions
20742 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20743 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20744 (concat "\\."
20745 (regexp-opt (nconc (mapcar 'upcase
20746 image-file-name-extensions)
20747 image-file-name-extensions)
20749 "\\'"))))
20751 (defun org-file-image-p (file &optional extensions)
20752 "Return non-nil if FILE is an image."
20753 (save-match-data
20754 (string-match (org-image-file-name-regexp extensions) file)))
20756 (defun org-get-cursor-date ()
20757 "Return the date at cursor in as a time.
20758 This works in the calendar and in the agenda, anywhere else it just
20759 returns the current time."
20760 (let (date day defd)
20761 (cond
20762 ((eq major-mode 'calendar-mode)
20763 (setq date (calendar-cursor-to-date)
20764 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20765 ((eq major-mode 'org-agenda-mode)
20766 (setq day (get-text-property (point) 'day))
20767 (if day
20768 (setq date (calendar-gregorian-from-absolute day)
20769 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20770 (nth 2 date))))))
20771 (or defd (current-time))))
20773 (defun org-mark-subtree (&optional up)
20774 "Mark the current subtree.
20775 This puts point at the start of the current subtree, and mark at
20776 the end. If a numeric prefix UP is given, move up into the
20777 hierarchy of headlines by UP levels before marking the subtree."
20778 (interactive "P")
20779 (org-with-limited-levels
20780 (cond ((org-at-heading-p) (beginning-of-line))
20781 ((org-before-first-heading-p) (error "Not in a subtree"))
20782 (t (outline-previous-visible-heading 1))))
20783 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
20784 (if (org-called-interactively-p 'any)
20785 (call-interactively 'org-mark-element)
20786 (org-mark-element)))
20788 ;;; Indentation
20790 (defun org-indent-line ()
20791 "Indent line depending on context."
20792 (interactive)
20793 (let* ((pos (point))
20794 (itemp (org-at-item-p))
20795 (case-fold-search t)
20796 (org-drawer-regexp (or org-drawer-regexp "\000"))
20797 (inline-task-p (and (featurep 'org-inlinetask)
20798 (org-inlinetask-in-task-p)))
20799 (inline-re (and inline-task-p
20800 (org-inlinetask-outline-regexp)))
20801 column)
20802 (if (and orgstruct-is-++ (eq pos (point)))
20803 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
20804 (indent-according-to-mode))
20805 (beginning-of-line 1)
20806 (cond
20807 ;; Headings
20808 ((looking-at org-outline-regexp) (setq column 0))
20809 ;; Included files
20810 ((looking-at "#\\+include:") (setq column 0))
20811 ;; Footnote definition
20812 ((looking-at org-footnote-definition-re) (setq column 0))
20813 ;; Literal examples
20814 ((looking-at "[ \t]*:\\( \\|$\\)")
20815 (setq column (org-get-indentation))) ; do nothing
20816 ;; Lists
20817 ((ignore-errors (goto-char (org-in-item-p)))
20818 (setq column (if itemp
20819 (org-get-indentation)
20820 (org-list-item-body-column (point))))
20821 (goto-char pos))
20822 ;; Drawers
20823 ((and (looking-at "[ \t]*:END:")
20824 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20825 (save-excursion
20826 (goto-char (1- (match-beginning 1)))
20827 (setq column (current-column))))
20828 ;; Special blocks
20829 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20830 (save-excursion
20831 (re-search-backward
20832 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20833 (setq column (org-get-indentation (match-string 0))))
20834 ((and (not (looking-at "[ \t]*#\\+begin_"))
20835 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20836 (save-excursion
20837 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20838 (setq column
20839 (cond ((equal (downcase (match-string 1)) "src")
20840 ;; src blocks: let `org-edit-src-exit' handle them
20841 (org-get-indentation))
20842 ((equal (downcase (match-string 1)) "example")
20843 (max (org-get-indentation)
20844 (org-get-indentation (match-string 0))))
20846 (org-get-indentation (match-string 0))))))
20847 ;; This line has nothing special, look at the previous relevant
20848 ;; line to compute indentation
20850 (beginning-of-line 0)
20851 (while (and (not (bobp))
20852 (not (looking-at org-table-line-regexp))
20853 (not (looking-at org-drawer-regexp))
20854 ;; When point started in an inline task, do not move
20855 ;; above task starting line.
20856 (not (and inline-task-p (looking-at inline-re)))
20857 ;; Skip drawers, blocks, empty lines, verbatim,
20858 ;; comments, tables, footnotes definitions, lists,
20859 ;; inline tasks.
20860 (or (and (looking-at "[ \t]*:END:")
20861 (re-search-backward org-drawer-regexp nil t))
20862 (and (looking-at "[ \t]*#\\+end_")
20863 (re-search-backward "[ \t]*#\\+begin_"nil t))
20864 (looking-at "[ \t]*[\n:#|]")
20865 (looking-at org-footnote-definition-re)
20866 (and (ignore-errors (goto-char (org-in-item-p)))
20867 (goto-char
20868 (org-list-get-top-point (org-list-struct))))
20869 (and (not inline-task-p)
20870 (featurep 'org-inlinetask)
20871 (org-inlinetask-in-task-p)
20872 (or (org-inlinetask-goto-beginning) t))))
20873 (beginning-of-line 0))
20874 (cond
20875 ;; There was an heading above.
20876 ((looking-at "\\*+[ \t]+")
20877 (if (not org-adapt-indentation)
20878 (setq column 0)
20879 (goto-char (match-end 0))
20880 (setq column (current-column))))
20881 ;; A drawer had started and is unfinished
20882 ((looking-at org-drawer-regexp)
20883 (goto-char (1- (match-beginning 1)))
20884 (setq column (current-column)))
20885 ;; Else, nothing noticeable found: get indentation and go on.
20886 (t (setq column (org-get-indentation))))))
20887 ;; Now apply indentation and move cursor accordingly
20888 (goto-char pos)
20889 (if (<= (current-column) (current-indentation))
20890 (org-indent-line-to column)
20891 (save-excursion (org-indent-line-to column)))
20892 ;; Special polishing for properties, see `org-property-format'
20893 (setq column (current-column))
20894 (beginning-of-line 1)
20895 (if (looking-at
20896 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20897 (replace-match (concat (match-string 1)
20898 (format org-property-format
20899 (match-string 2) (match-string 3)))
20900 t t))
20901 (org-move-to-column column))))
20903 (defun org-indent-drawer ()
20904 "Indent the drawer at point."
20905 (interactive)
20906 (let ((p (point))
20907 (e (and (save-excursion (re-search-forward ":END:" nil t))
20908 (match-end 0)))
20909 (folded
20910 (save-excursion
20911 (end-of-line)
20912 (when (overlays-at (point))
20913 (member 'invisible (overlay-properties
20914 (car (overlays-at (point)))))))))
20915 (when folded (org-cycle))
20916 (indent-for-tab-command)
20917 (while (and (move-beginning-of-line 2) (< (point) e))
20918 (indent-for-tab-command))
20919 (goto-char p)
20920 (when folded (org-cycle)))
20921 (message "Drawer at point indented"))
20923 (defun org-indent-block ()
20924 "Indent the block at point."
20925 (interactive)
20926 (let ((p (point))
20927 (case-fold-search t)
20928 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20929 (match-end 0)))
20930 (folded
20931 (save-excursion
20932 (end-of-line)
20933 (when (overlays-at (point))
20934 (member 'invisible (overlay-properties
20935 (car (overlays-at (point)))))))))
20936 (when folded (org-cycle))
20937 (indent-for-tab-command)
20938 (while (and (move-beginning-of-line 2) (< (point) e))
20939 (indent-for-tab-command))
20940 (goto-char p)
20941 (when folded (org-cycle)))
20942 (message "Block at point indented"))
20944 (defun org-indent-region (start end)
20945 "Indent region."
20946 (interactive "r")
20947 (save-excursion
20948 (let ((line-end (org-current-line end)))
20949 (goto-char start)
20950 (while (< (org-current-line) line-end)
20951 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
20952 (t (call-interactively 'org-indent-line)))
20953 (move-beginning-of-line 2)))))
20956 ;;; Filling
20958 ;; We use our own fill-paragraph and auto-fill functions.
20960 ;; `org-fill-paragraph' relies on adaptive filling and context
20961 ;; checking. Appropriate `fill-prefix' is computed with
20962 ;; `org-adaptive-fill-function'.
20964 ;; `org-auto-fill-function' takes care of auto-filling. It calls
20965 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
20966 ;; `org-adaptive-fill-function' value. Internally,
20967 ;; `org-comment-line-break-function' breaks the line.
20969 ;; `org-setup-filling' installs filling and auto-filling related
20970 ;; variables during `org-mode' initialization.
20972 (defun org-setup-filling ()
20973 (interactive)
20974 ;; Prevent auto-fill from inserting unwanted new items.
20975 (when (boundp 'fill-nobreak-predicate)
20976 (org-set-local
20977 'fill-nobreak-predicate
20978 (org-uniquify
20979 (append fill-nobreak-predicate
20980 '(org-fill-paragraph-separate-nobreak-p
20981 org-fill-line-break-nobreak-p
20982 org-fill-paragraph-with-timestamp-nobreak-p)))))
20983 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20984 (org-set-local 'auto-fill-inhibit-regexp nil)
20985 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
20986 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20987 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
20989 (defvar org-element-paragraph-separate) ; org-element.el
20990 (defun org-fill-paragraph-separate-nobreak-p ()
20991 "Non-nil when a line break at point would insert a new item."
20992 (looking-at (substring org-element-paragraph-separate 1)))
20994 (defun org-fill-line-break-nobreak-p ()
20995 "Non-nil when a line break at point would create an Org line break."
20996 (save-excursion
20997 (skip-chars-backward "[ \t]")
20998 (skip-chars-backward "\\\\")
20999 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21001 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21002 "Non-nil when a line break at point would insert a new item."
21003 (and (org-at-timestamp-p t)
21004 (not (looking-at org-ts-regexp-both))))
21006 (declare-function message-in-body-p "message" ())
21007 (defvar org-element--affiliated-re) ; From org-element.el
21008 (defvar orgtbl-line-start-regexp) ; From org-table.el
21009 (defun org-adaptive-fill-function ()
21010 "Compute a fill prefix for the current line.
21011 Return fill prefix, as a string, or nil if current line isn't
21012 meant to be filled."
21013 (let (prefix)
21014 (catch 'exit
21015 (when (derived-mode-p 'message-mode)
21016 (save-excursion
21017 (beginning-of-line)
21018 (cond ((or (not (message-in-body-p))
21019 (looking-at orgtbl-line-start-regexp))
21020 (throw 'exit nil))
21021 ((looking-at message-cite-prefix-regexp)
21022 (throw 'exit (match-string-no-properties 0)))
21023 ((looking-at org-outline-regexp)
21024 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21025 (org-with-wide-buffer
21026 (let* ((p (line-beginning-position))
21027 (element (save-excursion (beginning-of-line) (org-element-at-point)))
21028 (type (org-element-type element))
21029 (post-affiliated
21030 (save-excursion
21031 (goto-char (org-element-property :begin element))
21032 (while (looking-at org-element--affiliated-re) (forward-line))
21033 (point))))
21034 (unless (< p post-affiliated)
21035 (case type
21036 (comment (looking-at "[ \t]*# ?") (match-string 0))
21037 (footnote-definition "")
21038 ((item plain-list)
21039 (make-string (org-list-item-body-column post-affiliated) ? ))
21040 (paragraph
21041 ;; Fill prefix is usually the same as the current line,
21042 ;; except if the paragraph is at the beginning of an item.
21043 (let ((parent (org-element-property :parent element)))
21044 (cond ((eq (org-element-type parent) 'item)
21045 (make-string (org-list-item-body-column
21046 (org-element-property :begin parent))
21047 ? ))
21048 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21049 (match-string 0))
21050 (t ""))))
21051 (comment-block
21052 ;; Only fill contents if P is within block boundaries.
21053 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21054 (forward-line)
21055 (point)))
21056 (cend (save-excursion
21057 (goto-char (org-element-property :end element))
21058 (skip-chars-backward " \r\t\n")
21059 (line-beginning-position))))
21060 (when (and (>= p cbeg) (< p cend))
21061 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21062 (match-string 0)
21063 "")))))))))))
21065 (declare-function message-goto-body "message" ())
21066 (defvar message-cite-prefix-regexp) ; From message.el
21067 (defvar org-element-all-objects) ; From org-element.el
21068 (defun org-fill-paragraph (&optional justify)
21069 "Fill element at point, when applicable.
21071 This function only applies to comment blocks, comments, example
21072 blocks and paragraphs. Also, as a special case, re-align table
21073 when point is at one.
21075 If JUSTIFY is non-nil (interactively, with prefix argument),
21076 justify as well. If `sentence-end-double-space' is non-nil, then
21077 period followed by one space does not end a sentence, so don't
21078 break a line there. The variable `fill-column' controls the
21079 width for filling.
21081 For convenience, when point is at a plain list, an item or
21082 a footnote definition, try to fill the first paragraph within."
21083 (interactive)
21084 (if (and (derived-mode-p 'message-mode)
21085 (or (not (message-in-body-p))
21086 (save-excursion (move-beginning-of-line 1)
21087 (looking-at message-cite-prefix-regexp))))
21088 ;; First ensure filling is correct in message-mode.
21089 (let ((fill-paragraph-function
21090 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21091 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21092 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21093 (paragraph-separate
21094 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21095 (fill-paragraph nil))
21096 (save-excursion
21097 ;; Move to end of line in order to get the first paragraph
21098 ;; within a plain list or a footnote definition.
21099 (end-of-line)
21100 (let ((element (org-element-at-point)))
21101 ;; First check if point is in a blank line at the beginning of
21102 ;; the buffer. In that case, ignore filling.
21103 (if (< (point) (org-element-property :begin element)) t
21104 (case (org-element-type element)
21105 ;; Use major mode filling function is src blocks.
21106 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21107 ;; Align Org tables, leave table.el tables as-is.
21108 (table-row (org-table-align) t)
21109 (table
21110 (when (eq (org-element-property :type element) 'org)
21111 (org-table-align))
21113 (paragraph
21114 ;; Paragraphs may contain `line-break' type objects.
21115 (let ((beg (max (point-min)
21116 (org-element-property :contents-begin element)))
21117 (end (min (point-max)
21118 (org-element-property :contents-end element))))
21119 ;; Do nothing if point is at an affiliated keyword.
21120 (if (< (point) beg) t
21121 (when (derived-mode-p 'message-mode)
21122 ;; In `message-mode', do not fill following
21123 ;; citation in current paragraph nor text before
21124 ;; message body.
21125 (let ((body-start (save-excursion (message-goto-body))))
21126 (when body-start (setq beg (max body-start beg))))
21127 (when (save-excursion
21128 (re-search-forward
21129 (concat "^" message-cite-prefix-regexp) end t))
21130 (setq end (match-beginning 0))))
21131 ;; Fill paragraph, taking line breaks into
21132 ;; consideration. For that, slice the paragraph
21133 ;; using line breaks as separators, and fill the
21134 ;; parts in reverse order to avoid messing with
21135 ;; markers.
21136 (save-excursion
21137 (goto-char end)
21138 (mapc
21139 (lambda (pos)
21140 (fill-region-as-paragraph pos (point) justify)
21141 (goto-char pos))
21142 ;; Find the list of ending positions for line
21143 ;; breaks in the current paragraph. Add paragraph
21144 ;; beginning to include first slice.
21145 (nreverse
21146 (cons
21148 (org-element-map
21149 (org-element--parse-objects
21150 beg end nil org-element-all-objects)
21151 'line-break
21152 (lambda (lb) (org-element-property :end lb)))))))
21153 t)))
21154 ;; Contents of `comment-block' type elements should be
21155 ;; filled as plain text, but only if point is within block
21156 ;; markers.
21157 (comment-block
21158 (let* ((case-fold-search t)
21159 (beg (save-excursion
21160 (goto-char (org-element-property :begin element))
21161 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21162 (forward-line)
21163 (point)))
21164 (end (save-excursion
21165 (goto-char (org-element-property :end element))
21166 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21167 (line-beginning-position))))
21168 (when (and (>= (point) beg) (< (point) end))
21169 (fill-region-as-paragraph
21170 (save-excursion
21171 (end-of-line)
21172 (re-search-backward "^[ \t]*$" beg 'move)
21173 (line-beginning-position))
21174 (save-excursion
21175 (beginning-of-line)
21176 (re-search-forward "^[ \t]*$" end 'move)
21177 (line-beginning-position))
21178 justify)))
21180 ;; Fill comments.
21181 (comment (fill-comment-paragraph justify))
21182 ;; Ignore every other element.
21183 (otherwise t)))))))
21185 (defun org-auto-fill-function ()
21186 "Auto-fill function."
21187 ;; Check if auto-filling is meaningful.
21188 (let ((fc (current-fill-column)))
21189 (when (and fc (> (current-column) fc))
21190 (let* ((fill-prefix (org-adaptive-fill-function))
21191 ;; Enforce empty fill prefix, if required. Otherwise, it
21192 ;; will be computed again.
21193 (adaptive-fill-mode (not (equal fill-prefix ""))))
21194 (when fill-prefix (do-auto-fill))))))
21196 (defun org-comment-line-break-function (&optional soft)
21197 "Break line at point and indent, continuing comment if within one.
21198 The inserted newline is marked hard if variable
21199 `use-hard-newlines' is true, unless optional argument SOFT is
21200 non-nil."
21201 (if soft (insert-and-inherit ?\n) (newline 1))
21202 (save-excursion (forward-char -1) (delete-horizontal-space))
21203 (delete-horizontal-space)
21204 (indent-to-left-margin)
21205 (insert-before-markers-and-inherit fill-prefix))
21208 ;;; Comments
21210 ;; Org comments syntax is quite complex. It requires the entire line
21211 ;; to be just a comment. Also, even with the right syntax at the
21212 ;; beginning of line, some some elements (i.e. verse-block or
21213 ;; example-block) don't accept comments. Usual Emacs comment commands
21214 ;; cannot cope with those requirements. Therefore, Org replaces them.
21216 ;; Org still relies on `comment-dwim', but cannot trust
21217 ;; `comment-only-p'. So, `comment-region-function' and
21218 ;; `uncomment-region-function' both point
21219 ;; to`org-comment-or-uncomment-region'. Eventually,
21220 ;; `org-insert-comment' takes care of insertion of comments at the
21221 ;; beginning of line.
21223 ;; `org-setup-comments-handling' install comments related variables
21224 ;; during `org-mode' initialization.
21226 (defun org-setup-comments-handling ()
21227 (interactive)
21228 (org-set-local 'comment-use-syntax nil)
21229 (org-set-local 'comment-start "# ")
21230 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21231 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21232 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21233 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21235 (defun org-insert-comment ()
21236 "Insert an empty comment above current line.
21237 If the line is empty, insert comment at its beginning."
21238 (beginning-of-line)
21239 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21240 (org-indent-line)
21241 (insert "# "))
21243 (defvar comment-empty-lines) ; From newcomment.el.
21244 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21245 "Comment or uncomment each non-blank line in the region.
21246 Uncomment each non-blank line between BEG and END if it only
21247 contains commented lines. Otherwise, comment them."
21248 (save-restriction
21249 ;; Restrict region
21250 (narrow-to-region (save-excursion (goto-char beg)
21251 (skip-chars-forward " \r\t\n" end)
21252 (line-beginning-position))
21253 (save-excursion (goto-char end)
21254 (skip-chars-backward " \r\t\n" beg)
21255 (line-end-position)))
21256 (let ((uncommentp
21257 ;; UNCOMMENTP is non-nil when every non blank line between
21258 ;; BEG and END is a comment.
21259 (save-excursion
21260 (goto-char (point-min))
21261 (while (and (not (eobp))
21262 (let ((element (org-element-at-point)))
21263 (and (eq (org-element-type element) 'comment)
21264 (goto-char (min (point-max)
21265 (org-element-property
21266 :end element)))))))
21267 (eobp))))
21268 (if uncommentp
21269 ;; Only blank lines and comments in region: uncomment it.
21270 (save-excursion
21271 (goto-char (point-min))
21272 (while (not (eobp))
21273 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21274 (replace-match "" nil nil nil 1))
21275 (forward-line)))
21276 ;; Comment each line in region.
21277 (let ((min-indent (point-max)))
21278 ;; First find the minimum indentation across all lines.
21279 (save-excursion
21280 (goto-char (point-min))
21281 (while (and (not (eobp)) (not (zerop min-indent)))
21282 (unless (looking-at "[ \t]*$")
21283 (setq min-indent (min min-indent (current-indentation))))
21284 (forward-line)))
21285 ;; Then loop over all lines.
21286 (save-excursion
21287 (goto-char (point-min))
21288 (while (not (eobp))
21289 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21290 (org-move-to-column min-indent t)
21291 (insert comment-start))
21292 (forward-line))))))))
21295 ;;; Other stuff.
21297 (defun org-toggle-fixed-width-section (arg)
21298 "Toggle the fixed-width export.
21299 If there is no active region, the QUOTE keyword at the current headline is
21300 inserted or removed. When present, it causes the text between this headline
21301 and the next to be exported as fixed-width text, and unmodified.
21302 If there is an active region, this command adds or removes a colon as the
21303 first character of this line. If the first character of a line is a colon,
21304 this line is also exported in fixed-width font."
21305 (interactive "P")
21306 (let* ((cc 0)
21307 (regionp (org-region-active-p))
21308 (beg (if regionp (region-beginning) (point)))
21309 (end (if regionp (region-end)))
21310 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21311 (case-fold-search nil)
21312 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21313 off)
21314 (if regionp
21315 (save-excursion
21316 (goto-char beg)
21317 (setq cc (current-column))
21318 (beginning-of-line 1)
21319 (setq off (looking-at re))
21320 (while (> nlines 0)
21321 (setq nlines (1- nlines))
21322 (beginning-of-line 1)
21323 (cond
21324 (arg
21325 (org-move-to-column cc t)
21326 (insert ": \n")
21327 (forward-line -1))
21328 ((and off (looking-at re))
21329 (replace-match "" t t nil 1))
21330 ((not off) (org-move-to-column cc t) (insert ": ")))
21331 (forward-line 1)))
21332 (save-excursion
21333 (org-back-to-heading)
21334 (cond
21335 ((looking-at (format org-heading-keyword-regexp-format
21336 org-quote-string))
21337 (goto-char (match-end 1))
21338 (looking-at (concat " +" org-quote-string))
21339 (replace-match "" t t)
21340 (when (eolp) (insert " ")))
21341 ((looking-at org-outline-regexp)
21342 (goto-char (match-end 0))
21343 (insert org-quote-string " ")))))))
21345 (defun org-reftex-citation ()
21346 "Use reftex-citation to insert a citation into the buffer.
21347 This looks for a line like
21349 #+BIBLIOGRAPHY: foo plain option:-d
21351 and derives from it that foo.bib is the bibliography file relevant
21352 for this document. It then installs the necessary environment for RefTeX
21353 to work in this buffer and calls `reftex-citation' to insert a citation
21354 into the buffer.
21356 Export of such citations to both LaTeX and HTML is handled by the contributed
21357 package org-exp-bibtex by Taru Karttunen."
21358 (interactive)
21359 (let ((reftex-docstruct-symbol 'rds)
21360 (reftex-cite-format "\\cite{%l}")
21361 rds bib)
21362 (save-excursion
21363 (save-restriction
21364 (widen)
21365 (let ((case-fold-search t)
21366 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21367 (if (not (save-excursion
21368 (or (re-search-forward re nil t)
21369 (re-search-backward re nil t))))
21370 (error "No bibliography defined in file")
21371 (setq bib (concat (match-string 1) ".bib")
21372 rds (list (list 'bib bib)))))))
21373 (call-interactively 'reftex-citation)))
21375 ;;;; Functions extending outline functionality
21377 (defun org-beginning-of-line (&optional arg)
21378 "Go to the beginning of the current line. If that is invisible, continue
21379 to a visible line beginning. This makes the function of C-a more intuitive.
21380 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21381 first attempt, and only move to after the tags when the cursor is already
21382 beyond the end of the headline."
21383 (interactive "P")
21384 (let ((pos (point))
21385 (special (if (consp org-special-ctrl-a/e)
21386 (car org-special-ctrl-a/e)
21387 org-special-ctrl-a/e))
21388 refpos)
21389 (if (org-bound-and-true-p visual-line-mode)
21390 (beginning-of-visual-line 1)
21391 (beginning-of-line 1))
21392 (if (and arg (fboundp 'move-beginning-of-line))
21393 (call-interactively 'move-beginning-of-line)
21394 (if (bobp)
21396 (backward-char 1)
21397 (if (org-truely-invisible-p)
21398 (while (and (not (bobp)) (org-truely-invisible-p))
21399 (backward-char 1)
21400 (beginning-of-line 1))
21401 (forward-char 1))))
21402 (when special
21403 (cond
21404 ((and (looking-at org-complex-heading-regexp)
21405 (= (char-after (match-end 1)) ?\ ))
21406 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21407 (point-at-eol)))
21408 (goto-char
21409 (if (eq special t)
21410 (cond ((> pos refpos) refpos)
21411 ((= pos (point)) refpos)
21412 (t (point)))
21413 (cond ((> pos (point)) (point))
21414 ((not (eq last-command this-command)) (point))
21415 (t refpos)))))
21416 ((org-at-item-p)
21417 ;; Being at an item and not looking at an the item means point
21418 ;; was previously moved to beginning of a visual line, which
21419 ;; doesn't contain the item. Therefore, do nothing special,
21420 ;; just stay here.
21421 (when (looking-at org-list-full-item-re)
21422 ;; Set special position at first white space character after
21423 ;; bullet, and check-box, if any.
21424 (let ((after-bullet
21425 (let ((box (match-end 3)))
21426 (if (not box) (match-end 1)
21427 (let ((after (char-after box)))
21428 (if (and after (= after ? )) (1+ box) box))))))
21429 ;; Special case: Move point to special position when
21430 ;; currently after it or at beginning of line.
21431 (if (eq special t)
21432 (when (or (> pos after-bullet) (= (point) pos))
21433 (goto-char after-bullet))
21434 ;; Reversed case: Move point to special position when
21435 ;; point was already at beginning of line and command is
21436 ;; repeated.
21437 (when (and (= (point) pos) (eq last-command this-command))
21438 (goto-char after-bullet))))))))
21439 (org-no-warnings
21440 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21442 (defun org-end-of-line (&optional arg)
21443 "Go to the end of the line.
21444 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
21445 tags on the first attempt, and only move to after the tags when
21446 the cursor is already beyond the end of the headline."
21447 (interactive "P")
21448 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
21449 org-special-ctrl-a/e))
21450 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
21451 'end-of-visual-line)
21452 ((fboundp 'move-end-of-line) 'move-end-of-line)
21453 (t 'end-of-line))))
21454 (if (or (not special) arg) (call-interactively move-fun)
21455 (let* ((element (save-excursion (beginning-of-line)
21456 (org-element-at-point)))
21457 (type (org-element-type element)))
21458 (cond
21459 ((memq type '(headline inlinetask))
21460 (let ((pos (point)))
21461 (beginning-of-line 1)
21462 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21463 (if (eq special t)
21464 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
21465 (goto-char (match-beginning 1))
21466 (goto-char (match-end 0)))
21467 (if (or (< pos (match-end 0))
21468 (not (eq this-command last-command)))
21469 (goto-char (match-end 0))
21470 (goto-char (match-beginning 1))))
21471 (call-interactively move-fun))))
21472 ((org-element-property :hiddenp element)
21473 ;; If element is hidden, `move-end-of-line' would put point
21474 ;; after it. Use `end-of-line' to stay on current line.
21475 (call-interactively 'end-of-line))
21476 (t (call-interactively move-fun)))))
21477 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21479 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21480 (define-key org-mode-map "\C-e" 'org-end-of-line)
21482 (defun org-backward-sentence (&optional arg)
21483 "Go to beginning of sentence, or beginning of table field.
21484 This will call `backward-sentence' or `org-table-beginning-of-field',
21485 depending on context."
21486 (interactive "P")
21487 (cond
21488 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21489 (t (call-interactively 'backward-sentence))))
21491 (defun org-forward-sentence (&optional arg)
21492 "Go to end of sentence, or end of table field.
21493 This will call `forward-sentence' or `org-table-end-of-field',
21494 depending on context."
21495 (interactive "P")
21496 (cond
21497 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21498 (t (call-interactively 'forward-sentence))))
21500 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21501 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21503 (defun org-kill-line (&optional arg)
21504 "Kill line, to tags or end of line."
21505 (interactive "P")
21506 (cond
21507 ((or (not org-special-ctrl-k)
21508 (bolp)
21509 (not (org-at-heading-p)))
21510 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21511 org-ctrl-k-protect-subtree)
21512 (if (or (eq org-ctrl-k-protect-subtree 'error)
21513 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21514 (error "C-k aborted - would kill hidden subtree")))
21515 (call-interactively
21516 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
21517 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21518 (kill-region (point) (match-beginning 1))
21519 (org-set-tags nil t))
21520 (t (kill-region (point) (point-at-eol)))))
21522 (define-key org-mode-map "\C-k" 'org-kill-line)
21524 (defun org-yank (&optional arg)
21525 "Yank. If the kill is a subtree, treat it specially.
21526 This command will look at the current kill and check if is a single
21527 subtree, or a series of subtrees[1]. If it passes the test, and if the
21528 cursor is at the beginning of a line or after the stars of a currently
21529 empty headline, then the yank is handled specially. How exactly depends
21530 on the value of the following variables, both set by default.
21532 org-yank-folded-subtrees
21533 When set, the subtree(s) will be folded after insertion, but only
21534 if doing so would now swallow text after the yanked text.
21536 org-yank-adjusted-subtrees
21537 When set, the subtree will be promoted or demoted in order to
21538 fit into the local outline tree structure, which means that the level
21539 will be adjusted so that it becomes the smaller one of the two
21540 *visible* surrounding headings.
21542 Any prefix to this command will cause `yank' to be called directly with
21543 no special treatment. In particular, a simple \\[universal-argument] prefix \
21544 will just
21545 plainly yank the text as it is.
21547 \[1] The test checks if the first non-white line is a heading
21548 and if there are no other headings with fewer stars."
21549 (interactive "P")
21550 (org-yank-generic 'yank arg))
21552 (defun org-yank-generic (command arg)
21553 "Perform some yank-like command.
21555 This function implements the behavior described in the `org-yank'
21556 documentation. However, it has been generalized to work for any
21557 interactive command with similar behavior."
21559 ;; pretend to be command COMMAND
21560 (setq this-command command)
21562 (if arg
21563 (call-interactively command)
21565 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21566 (and (org-kill-is-subtree-p)
21567 (or (bolp)
21568 (and (looking-at "[ \t]*$")
21569 (string-match
21570 "\\`\\*+\\'"
21571 (buffer-substring (point-at-bol) (point)))))))
21572 swallowp)
21573 (cond
21574 ((and subtreep org-yank-folded-subtrees)
21575 (let ((beg (point))
21576 end)
21577 (if (and subtreep org-yank-adjusted-subtrees)
21578 (org-paste-subtree nil nil 'for-yank)
21579 (call-interactively command))
21581 (setq end (point))
21582 (goto-char beg)
21583 (when (and (bolp) subtreep
21584 (not (setq swallowp
21585 (org-yank-folding-would-swallow-text beg end))))
21586 (org-with-limited-levels
21587 (or (looking-at org-outline-regexp)
21588 (re-search-forward org-outline-regexp-bol end t))
21589 (while (and (< (point) end) (looking-at org-outline-regexp))
21590 (hide-subtree)
21591 (org-cycle-show-empty-lines 'folded)
21592 (condition-case nil
21593 (outline-forward-same-level 1)
21594 (error (goto-char end))))))
21595 (when swallowp
21596 (message
21597 "Inserted text not folded because that would swallow text"))
21599 (goto-char end)
21600 (skip-chars-forward " \t\n\r")
21601 (beginning-of-line 1)
21602 (push-mark beg 'nomsg)))
21603 ((and subtreep org-yank-adjusted-subtrees)
21604 (let ((beg (point-at-bol)))
21605 (org-paste-subtree nil nil 'for-yank)
21606 (push-mark beg 'nomsg)))
21608 (call-interactively command))))))
21610 (defun org-yank-folding-would-swallow-text (beg end)
21611 "Would hide-subtree at BEG swallow any text after END?"
21612 (let (level)
21613 (org-with-limited-levels
21614 (save-excursion
21615 (goto-char beg)
21616 (when (or (looking-at org-outline-regexp)
21617 (re-search-forward org-outline-regexp-bol end t))
21618 (setq level (org-outline-level)))
21619 (goto-char end)
21620 (skip-chars-forward " \t\r\n\v\f")
21621 (if (or (eobp)
21622 (and (bolp) (looking-at org-outline-regexp)
21623 (<= (org-outline-level) level)))
21624 nil ; Nothing would be swallowed
21625 t))))) ; something would swallow
21627 (define-key org-mode-map "\C-y" 'org-yank)
21629 (defun org-truely-invisible-p ()
21630 "Check if point is at a character currently not visible.
21631 This version does not only check the character property, but also
21632 `visible-mode'."
21633 ;; Early versions of noutline don't have `outline-invisible-p'.
21634 (if (org-bound-and-true-p visible-mode)
21636 (outline-invisible-p)))
21638 (defun org-invisible-p2 ()
21639 "Check if point is at a character currently not visible."
21640 (save-excursion
21641 (if (and (eolp) (not (bobp))) (backward-char 1))
21642 ;; Early versions of noutline don't have `outline-invisible-p'.
21643 (outline-invisible-p)))
21645 (defun org-back-to-heading (&optional invisible-ok)
21646 "Call `outline-back-to-heading', but provide a better error message."
21647 (condition-case nil
21648 (outline-back-to-heading invisible-ok)
21649 (error (error "Before first headline at position %d in buffer %s"
21650 (point) (current-buffer)))))
21652 (defun org-before-first-heading-p ()
21653 "Before first heading?"
21654 (save-excursion
21655 (end-of-line)
21656 (null (re-search-backward org-outline-regexp-bol nil t))))
21658 (defun org-at-heading-p (&optional ignored)
21659 (outline-on-heading-p t))
21660 ;; Compatibility alias with Org versions < 7.8.03
21661 (defalias 'org-on-heading-p 'org-at-heading-p)
21663 (defun org-at-comment-p nil
21664 "Is cursor in a line starting with a # character?"
21665 (save-excursion
21666 (beginning-of-line)
21667 (looking-at "^#")))
21669 (defun org-at-drawer-p nil
21670 "Is cursor at a drawer keyword?"
21671 (save-excursion
21672 (move-beginning-of-line 1)
21673 (looking-at org-drawer-regexp)))
21675 (defun org-at-block-p nil
21676 "Is cursor at a block keyword?"
21677 (save-excursion
21678 (move-beginning-of-line 1)
21679 (looking-at org-block-regexp)))
21681 (defun org-point-at-end-of-empty-headline ()
21682 "If point is at the end of an empty headline, return t, else nil.
21683 If the heading only contains a TODO keyword, it is still still considered
21684 empty."
21685 (and (looking-at "[ \t]*$")
21686 (when org-todo-line-regexp
21687 (save-excursion
21688 (beginning-of-line 1)
21689 (let ((case-fold-search nil))
21690 (looking-at org-todo-line-regexp)
21691 (string= (match-string 3) ""))))))
21693 (defun org-at-heading-or-item-p ()
21694 (or (org-at-heading-p) (org-at-item-p)))
21696 (defun org-at-target-p ()
21697 (or (org-in-regexp org-radio-target-regexp)
21698 (org-in-regexp org-target-regexp)))
21699 ;; Compatibility alias with Org versions < 7.8.03
21700 (defalias 'org-on-target-p 'org-at-target-p)
21702 (defun org-up-heading-all (arg)
21703 "Move to the heading line of which the present line is a subheading.
21704 This function considers both visible and invisible heading lines.
21705 With argument, move up ARG levels."
21706 (if (fboundp 'outline-up-heading-all)
21707 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21708 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21710 (defun org-up-heading-safe ()
21711 "Move to the heading line of which the present line is a subheading.
21712 This version will not throw an error. It will return the level of the
21713 headline found, or nil if no higher level is found.
21715 Also, this function will be a lot faster than `outline-up-heading',
21716 because it relies on stars being the outline starters. This can really
21717 make a significant difference in outlines with very many siblings."
21718 (let (start-level re)
21719 (org-back-to-heading t)
21720 (setq start-level (funcall outline-level))
21721 (if (equal start-level 1)
21723 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21724 (if (re-search-backward re nil t)
21725 (funcall outline-level)))))
21727 (defun org-first-sibling-p ()
21728 "Is this heading the first child of its parents?"
21729 (interactive)
21730 (let ((re org-outline-regexp-bol)
21731 level l)
21732 (unless (org-at-heading-p t)
21733 (error "Not at a heading"))
21734 (setq level (funcall outline-level))
21735 (save-excursion
21736 (if (not (re-search-backward re nil t))
21738 (setq l (funcall outline-level))
21739 (< l level)))))
21741 (defun org-goto-sibling (&optional previous)
21742 "Goto the next sibling, even if it is invisible.
21743 When PREVIOUS is set, go to the previous sibling instead. Returns t
21744 when a sibling was found. When none is found, return nil and don't
21745 move point."
21746 (let ((fun (if previous 're-search-backward 're-search-forward))
21747 (pos (point))
21748 (re org-outline-regexp-bol)
21749 level l)
21750 (when (condition-case nil (org-back-to-heading t) (error nil))
21751 (setq level (funcall outline-level))
21752 (catch 'exit
21753 (or previous (forward-char 1))
21754 (while (funcall fun re nil t)
21755 (setq l (funcall outline-level))
21756 (when (< l level) (goto-char pos) (throw 'exit nil))
21757 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21758 (goto-char pos)
21759 nil))))
21761 (defun org-show-siblings ()
21762 "Show all siblings of the current headline."
21763 (save-excursion
21764 (while (org-goto-sibling) (org-flag-heading nil)))
21765 (save-excursion
21766 (while (org-goto-sibling 'previous)
21767 (org-flag-heading nil))))
21769 (defun org-goto-first-child ()
21770 "Goto the first child, even if it is invisible.
21771 Return t when a child was found. Otherwise don't move point and
21772 return nil."
21773 (let (level (pos (point)) (re org-outline-regexp-bol))
21774 (when (condition-case nil (org-back-to-heading t) (error nil))
21775 (setq level (outline-level))
21776 (forward-char 1)
21777 (if (and (re-search-forward re nil t) (> (outline-level) level))
21778 (progn (goto-char (match-beginning 0)) t)
21779 (goto-char pos) nil))))
21781 (defun org-show-hidden-entry ()
21782 "Show an entry where even the heading is hidden."
21783 (save-excursion
21784 (org-show-entry)))
21786 (defun org-flag-heading (flag &optional entry)
21787 "Flag the current heading. FLAG non-nil means make invisible.
21788 When ENTRY is non-nil, show the entire entry."
21789 (save-excursion
21790 (org-back-to-heading t)
21791 ;; Check if we should show the entire entry
21792 (if entry
21793 (progn
21794 (org-show-entry)
21795 (save-excursion
21796 (and (outline-next-heading)
21797 (org-flag-heading nil))))
21798 (outline-flag-region (max (point-min) (1- (point)))
21799 (save-excursion (outline-end-of-heading) (point))
21800 flag))))
21802 (defun org-get-next-sibling ()
21803 "Move to next heading of the same level, and return point.
21804 If there is no such heading, return nil.
21805 This is like outline-next-sibling, but invisible headings are ok."
21806 (let ((level (funcall outline-level)))
21807 (outline-next-heading)
21808 (while (and (not (eobp)) (> (funcall outline-level) level))
21809 (outline-next-heading))
21810 (if (or (eobp) (< (funcall outline-level) level))
21812 (point))))
21814 (defun org-get-last-sibling ()
21815 "Move to previous heading of the same level, and return point.
21816 If there is no such heading, return nil."
21817 (let ((opoint (point))
21818 (level (funcall outline-level)))
21819 (outline-previous-heading)
21820 (when (and (/= (point) opoint) (outline-on-heading-p t))
21821 (while (and (> (funcall outline-level) level)
21822 (not (bobp)))
21823 (outline-previous-heading))
21824 (if (< (funcall outline-level) level)
21826 (point)))))
21828 (defun org-end-of-subtree (&optional invisible-ok to-heading)
21829 "Goto to the end of a subtree."
21830 ;; This contains an exact copy of the original function, but it uses
21831 ;; `org-back-to-heading', to make it work also in invisible
21832 ;; trees. And is uses an invisible-ok argument.
21833 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21834 ;; Furthermore, when used inside Org, finding the end of a large subtree
21835 ;; with many children and grandchildren etc, this can be much faster
21836 ;; than the outline version.
21837 (org-back-to-heading invisible-ok)
21838 (let ((first t)
21839 (level (funcall outline-level)))
21840 (if (and (derived-mode-p 'org-mode) (< level 1000))
21841 ;; A true heading (not a plain list item), in Org-mode
21842 ;; This means we can easily find the end by looking
21843 ;; only for the right number of stars. Using a regexp to do
21844 ;; this is so much faster than using a Lisp loop.
21845 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21846 (forward-char 1)
21847 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21848 ;; something else, do it the slow way
21849 (while (and (not (eobp))
21850 (or first (> (funcall outline-level) level)))
21851 (setq first nil)
21852 (outline-next-heading)))
21853 (unless to-heading
21854 (if (memq (preceding-char) '(?\n ?\^M))
21855 (progn
21856 ;; Go to end of line before heading
21857 (forward-char -1)
21858 (if (memq (preceding-char) '(?\n ?\^M))
21859 ;; leave blank line before heading
21860 (forward-char -1))))))
21861 (point))
21863 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21864 "Use Org version in org-mode, for dramatic speed-up."
21865 (if (derived-mode-p 'org-mode)
21866 (progn
21867 (org-end-of-subtree nil t)
21868 (unless (eobp) (backward-char 1)))
21869 ad-do-it))
21871 (defun org-end-of-meta-data-and-drawers ()
21872 "Jump to the first text after meta data and drawers in the current entry.
21873 This will move over empty lines, lines with planning time stamps,
21874 clocking lines, and drawers."
21875 (org-back-to-heading t)
21876 (let ((end (save-excursion (outline-next-heading) (point)))
21877 (re (concat "\\(" org-drawer-regexp "\\)"
21878 "\\|" "[ \t]*" org-keyword-time-regexp)))
21879 (forward-line 1)
21880 (while (re-search-forward re end t)
21881 (if (not (match-end 1))
21882 ;; empty or planning line
21883 (forward-line 1)
21884 ;; a drawer, find the end
21885 (re-search-forward "^[ \t]*:END:" end 'move)
21886 (forward-line 1)))
21887 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21888 (point)))
21890 (defun org-forward-heading-same-level (arg &optional invisible-ok)
21891 "Move forward to the arg'th subheading at same level as this one.
21892 Stop at the first and last subheadings of a superior heading.
21893 Normally this only looks at visible headings, but when INVISIBLE-OK is
21894 non-nil it will also look at invisible ones."
21895 (interactive "p")
21896 (org-back-to-heading invisible-ok)
21897 (org-at-heading-p)
21898 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21899 (re (format "^\\*\\{1,%d\\} " level))
21901 (forward-char 1)
21902 (while (> arg 0)
21903 (while (and (re-search-forward re nil 'move)
21904 (setq l (- (match-end 0) (match-beginning 0) 1))
21905 (= l level)
21906 (not invisible-ok)
21907 (progn (backward-char 1) (outline-invisible-p)))
21908 (if (< l level) (setq arg 1)))
21909 (setq arg (1- arg)))
21910 (beginning-of-line 1)))
21912 (defun org-backward-heading-same-level (arg &optional invisible-ok)
21913 "Move backward to the arg'th subheading at same level as this one.
21914 Stop at the first and last subheadings of a superior heading."
21915 (interactive "p")
21916 (org-back-to-heading)
21917 (org-at-heading-p)
21918 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21919 (re (format "^\\*\\{1,%d\\} " level))
21921 (while (> arg 0)
21922 (while (and (re-search-backward re nil 'move)
21923 (setq l (- (match-end 0) (match-beginning 0) 1))
21924 (= l level)
21925 (not invisible-ok)
21926 (outline-invisible-p))
21927 (if (< l level) (setq arg 1)))
21928 (setq arg (1- arg)))))
21930 (defun org-forward-element ()
21931 "Move forward by one element.
21932 Move to the next element at the same level, when possible."
21933 (interactive)
21934 (cond ((eobp) (error "Cannot move further down"))
21935 ((org-with-limited-levels (org-at-heading-p))
21936 (let ((origin (point)))
21937 (org-forward-heading-same-level 1)
21938 (unless (org-with-limited-levels (org-at-heading-p))
21939 (goto-char origin)
21940 (error "Cannot move further down"))))
21942 (let* ((elem (org-element-at-point))
21943 (end (org-element-property :end elem))
21944 (parent (org-element-property :parent elem)))
21945 (if (and parent (= (org-element-property :contents-end parent) end))
21946 (goto-char (org-element-property :end parent))
21947 (goto-char end))))))
21949 (defun org-backward-element ()
21950 "Move backward by one element.
21951 Move to the previous element at the same level, when possible."
21952 (interactive)
21953 (cond ((bobp) (error "Cannot move further up"))
21954 ((org-with-limited-levels (org-at-heading-p))
21955 ;; At an headline, move to the previous one, if any, or stay
21956 ;; here.
21957 (let ((origin (point)))
21958 (org-backward-heading-same-level 1)
21959 (unless (org-with-limited-levels (org-at-heading-p))
21960 (goto-char origin)
21961 (error "Cannot move further up"))))
21963 (let* ((trail (org-element-at-point 'keep-trail))
21964 (elem (car trail))
21965 (prev-elem (nth 1 trail))
21966 (beg (org-element-property :begin elem)))
21967 (cond
21968 ;; Move to beginning of current element if point isn't
21969 ;; there already.
21970 ((/= (point) beg) (goto-char beg))
21971 (prev-elem (goto-char (org-element-property :begin prev-elem)))
21972 ((org-before-first-heading-p) (goto-char (point-min)))
21973 (t (org-back-to-heading)))))))
21975 (defun org-up-element ()
21976 "Move to upper element."
21977 (interactive)
21978 (if (org-with-limited-levels (org-at-heading-p))
21979 (unless (org-up-heading-safe) (error "No surrounding element"))
21980 (let* ((elem (org-element-at-point))
21981 (parent (org-element-property :parent elem)))
21982 (if parent (goto-char (org-element-property :begin parent))
21983 (if (org-with-limited-levels (org-before-first-heading-p))
21984 (error "No surrounding element")
21985 (org-with-limited-levels (org-back-to-heading)))))))
21987 (defvar org-element-greater-elements)
21988 (defun org-down-element ()
21989 "Move to inner element."
21990 (interactive)
21991 (let ((element (org-element-at-point)))
21992 (cond
21993 ((memq (org-element-type element) '(plain-list table))
21994 (goto-char (org-element-property :contents-begin element))
21995 (forward-char))
21996 ((memq (org-element-type element) org-element-greater-elements)
21997 ;; If contents are hidden, first disclose them.
21998 (when (org-element-property :hiddenp element) (org-cycle))
21999 (goto-char (or (org-element-property :contents-begin element)
22000 (error "No content for this element"))))
22001 (t (error "No inner element")))))
22003 (defun org-drag-element-backward ()
22004 "Move backward element at point."
22005 (interactive)
22006 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22007 (let* ((trail (org-element-at-point 'keep-trail))
22008 (elem (car trail))
22009 (prev-elem (nth 1 trail)))
22010 ;; Error out if no previous element or previous element is
22011 ;; a parent of the current one.
22012 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22013 (error "Cannot drag element backward")
22014 (let ((pos (point)))
22015 (org-element-swap-A-B prev-elem elem)
22016 (goto-char (+ (org-element-property :begin prev-elem)
22017 (- pos (org-element-property :begin elem)))))))))
22019 (defun org-drag-element-forward ()
22020 "Move forward element at point."
22021 (interactive)
22022 (let* ((pos (point))
22023 (elem (org-element-at-point)))
22024 (when (= (point-max) (org-element-property :end elem))
22025 (error "Cannot drag element forward"))
22026 (goto-char (org-element-property :end elem))
22027 (let ((next-elem (org-element-at-point)))
22028 (when (or (org-element-nested-p elem next-elem)
22029 (and (eq (org-element-type next-elem) 'headline)
22030 (not (eq (org-element-type elem) 'headline))))
22031 (goto-char pos)
22032 (error "Cannot drag element forward"))
22033 ;; Compute new position of point: it's shifted by NEXT-ELEM
22034 ;; body's length (without final blanks) and by the length of
22035 ;; blanks between ELEM and NEXT-ELEM.
22036 (let ((size-next (- (save-excursion
22037 (goto-char (org-element-property :end next-elem))
22038 (skip-chars-backward " \r\t\n")
22039 (forward-line)
22040 ;; Small correction if buffer doesn't end
22041 ;; with a newline character.
22042 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22043 (org-element-property :begin next-elem)))
22044 (size-blank (- (org-element-property :end elem)
22045 (save-excursion
22046 (goto-char (org-element-property :end elem))
22047 (skip-chars-backward " \r\t\n")
22048 (forward-line)
22049 (point)))))
22050 (org-element-swap-A-B elem next-elem)
22051 (goto-char (+ pos size-next size-blank))))))
22053 (defun org-mark-element ()
22054 "Put point at beginning of this element, mark at end.
22056 Interactively, if this command is repeated or (in Transient Mark
22057 mode) if the mark is active, it marks the next element after the
22058 ones already marked."
22059 (interactive)
22060 (let (deactivate-mark)
22061 (if (and (org-called-interactively-p 'any)
22062 (or (and (eq last-command this-command) (mark t))
22063 (and transient-mark-mode mark-active)))
22064 (set-mark
22065 (save-excursion
22066 (goto-char (mark))
22067 (goto-char (org-element-property :end (org-element-at-point)))))
22068 (let ((element (org-element-at-point)))
22069 (end-of-line)
22070 (push-mark (org-element-property :end element) t t)
22071 (goto-char (org-element-property :begin element))))))
22073 (defun org-narrow-to-element ()
22074 "Narrow buffer to current element."
22075 (interactive)
22076 (let ((elem (org-element-at-point)))
22077 (cond
22078 ((eq (car elem) 'headline)
22079 (narrow-to-region
22080 (org-element-property :begin elem)
22081 (org-element-property :end elem)))
22082 ((memq (car elem) org-element-greater-elements)
22083 (narrow-to-region
22084 (org-element-property :contents-begin elem)
22085 (org-element-property :contents-end elem)))
22087 (narrow-to-region
22088 (org-element-property :begin elem)
22089 (org-element-property :end elem))))))
22091 (defun org-transpose-element ()
22092 "Transpose current and previous elements, keeping blank lines between.
22093 Point is moved after both elements."
22094 (interactive)
22095 (org-skip-whitespace)
22096 (let ((end (org-element-property :end (org-element-at-point))))
22097 (org-drag-element-backward)
22098 (goto-char end)))
22100 (defun org-unindent-buffer ()
22101 "Un-indent the visible part of the buffer.
22102 Relative indentation (between items, inside blocks, etc.) isn't
22103 modified."
22104 (interactive)
22105 (unless (eq major-mode 'org-mode)
22106 (error "Cannot un-indent a buffer not in Org mode"))
22107 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22108 unindent-tree ; For byte-compiler.
22109 (unindent-tree
22110 (function
22111 (lambda (contents)
22112 (mapc
22113 (lambda (element)
22114 (if (memq (org-element-type element) '(headline section))
22115 (funcall unindent-tree (org-element-contents element))
22116 (save-excursion
22117 (save-restriction
22118 (narrow-to-region
22119 (org-element-property :begin element)
22120 (org-element-property :end element))
22121 (org-do-remove-indentation)))))
22122 (reverse contents))))))
22123 (funcall unindent-tree (org-element-contents parse-tree))))
22125 (defun org-show-subtree ()
22126 "Show everything after this heading at deeper levels."
22127 (interactive)
22128 (outline-flag-region
22129 (point)
22130 (save-excursion
22131 (org-end-of-subtree t t))
22132 nil))
22134 (defun org-show-entry ()
22135 "Show the body directly following this heading.
22136 Show the heading too, if it is currently invisible."
22137 (interactive)
22138 (save-excursion
22139 (condition-case nil
22140 (progn
22141 (org-back-to-heading t)
22142 (outline-flag-region
22143 (max (point-min) (1- (point)))
22144 (save-excursion
22145 (if (re-search-forward
22146 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22147 (match-beginning 1)
22148 (point-max)))
22149 nil)
22150 (org-cycle-hide-drawers 'children))
22151 (error nil))))
22153 (defun org-make-options-regexp (kwds &optional extra)
22154 "Make a regular expression for keyword lines."
22155 (concat
22156 "^#\\+\\("
22157 (mapconcat 'regexp-quote kwds "\\|")
22158 (if extra (concat "\\|" extra))
22159 "\\):[ \t]*\\(.*\\)"))
22161 ;; Make isearch reveal the necessary context
22162 (defun org-isearch-end ()
22163 "Reveal context after isearch exits."
22164 (when isearch-success ; only if search was successful
22165 (if (featurep 'xemacs)
22166 ;; Under XEmacs, the hook is run in the correct place,
22167 ;; we directly show the context.
22168 (org-show-context 'isearch)
22169 ;; In Emacs the hook runs *before* restoring the overlays.
22170 ;; So we have to use a one-time post-command-hook to do this.
22171 ;; (Emacs 22 has a special variable, see function `org-mode')
22172 (unless (and (boundp 'isearch-mode-end-hook-quit)
22173 isearch-mode-end-hook-quit)
22174 ;; Only when the isearch was not quitted.
22175 (org-add-hook 'post-command-hook 'org-isearch-post-command
22176 'append 'local)))))
22178 (defun org-isearch-post-command ()
22179 "Remove self from hook, and show context."
22180 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22181 (org-show-context 'isearch))
22184 ;;;; Integration with and fixes for other packages
22186 ;;; Imenu support
22188 (defvar org-imenu-markers nil
22189 "All markers currently used by Imenu.")
22190 (make-variable-buffer-local 'org-imenu-markers)
22192 (defun org-imenu-new-marker (&optional pos)
22193 "Return a new marker for use by Imenu, and remember the marker."
22194 (let ((m (make-marker)))
22195 (move-marker m (or pos (point)))
22196 (push m org-imenu-markers)
22199 (defun org-imenu-get-tree ()
22200 "Produce the index for Imenu."
22201 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22202 (setq org-imenu-markers nil)
22203 (let* ((n org-imenu-depth)
22204 (re (concat "^" (org-get-limited-outline-regexp)))
22205 (subs (make-vector (1+ n) nil))
22206 (last-level 0)
22207 m level head)
22208 (save-excursion
22209 (save-restriction
22210 (widen)
22211 (goto-char (point-max))
22212 (while (re-search-backward re nil t)
22213 (setq level (org-reduced-level (funcall outline-level)))
22214 (when (and (<= level n)
22215 (looking-at org-complex-heading-regexp))
22216 (setq head (org-link-display-format
22217 (org-match-string-no-properties 4))
22218 m (org-imenu-new-marker))
22219 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22220 (if (>= level last-level)
22221 (push (cons head m) (aref subs level))
22222 (push (cons head (aref subs (1+ level))) (aref subs level))
22223 (loop for i from (1+ level) to n do (aset subs i nil)))
22224 (setq last-level level)))))
22225 (aref subs 1)))
22227 (eval-after-load "imenu"
22228 '(progn
22229 (add-hook 'imenu-after-jump-hook
22230 (lambda ()
22231 (if (derived-mode-p 'org-mode)
22232 (org-show-context 'org-goto))))))
22234 (defun org-link-display-format (link)
22235 "Replace a link with either the description, or the link target
22236 if no description is present"
22237 (save-match-data
22238 (if (string-match org-bracket-link-analytic-regexp link)
22239 (replace-match (if (match-end 5)
22240 (match-string 5 link)
22241 (concat (match-string 1 link)
22242 (match-string 3 link)))
22243 nil t link)
22244 link)))
22246 (defun org-toggle-link-display ()
22247 "Toggle the literal or descriptive display of links."
22248 (interactive)
22249 (if org-descriptive-links
22250 (progn (org-remove-from-invisibility-spec '(org-link))
22251 (org-restart-font-lock)
22252 (setq org-descriptive-links nil))
22253 (progn (add-to-invisibility-spec '(org-link))
22254 (org-restart-font-lock)
22255 (setq org-descriptive-links t))))
22257 ;; Speedbar support
22259 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22260 "Overlay marking the agenda restriction line in speedbar.")
22261 (overlay-put org-speedbar-restriction-lock-overlay
22262 'face 'org-agenda-restriction-lock)
22263 (overlay-put org-speedbar-restriction-lock-overlay
22264 'help-echo "Agendas are currently limited to this item.")
22265 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22267 (defun org-speedbar-set-agenda-restriction ()
22268 "Restrict future agenda commands to the location at point in speedbar.
22269 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22270 (interactive)
22271 (require 'org-agenda)
22272 (let (p m tp np dir txt)
22273 (cond
22274 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22275 'org-imenu t))
22276 (setq m (get-text-property p 'org-imenu-marker))
22277 (with-current-buffer (marker-buffer m)
22278 (goto-char m)
22279 (org-agenda-set-restriction-lock 'subtree)))
22280 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22281 'speedbar-function 'speedbar-find-file))
22282 (setq tp (previous-single-property-change
22283 (1+ p) 'speedbar-function)
22284 np (next-single-property-change
22285 tp 'speedbar-function)
22286 dir (speedbar-line-directory)
22287 txt (buffer-substring-no-properties (or tp (point-min))
22288 (or np (point-max))))
22289 (with-current-buffer (find-file-noselect
22290 (let ((default-directory dir))
22291 (expand-file-name txt)))
22292 (unless (derived-mode-p 'org-mode)
22293 (error "Cannot restrict to non-Org-mode file"))
22294 (org-agenda-set-restriction-lock 'file)))
22295 (t (error "Don't know how to restrict Org-mode's agenda")))
22296 (move-overlay org-speedbar-restriction-lock-overlay
22297 (point-at-bol) (point-at-eol))
22298 (setq current-prefix-arg nil)
22299 (org-agenda-maybe-redo)))
22301 (eval-after-load "speedbar"
22302 '(progn
22303 (speedbar-add-supported-extension ".org")
22304 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22305 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22306 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22307 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22308 (add-hook 'speedbar-visiting-tag-hook
22309 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22311 ;;; Fixes and Hacks for problems with other packages
22313 ;; Make flyspell not check words in links, to not mess up our keymap
22314 (defun org-mode-flyspell-verify ()
22315 "Don't let flyspell put overlays at active buttons, or on
22316 {todo,all-time,additional-option-like}-keywords."
22317 (let ((pos (max (1- (point)) (point-min)))
22318 (word (thing-at-point 'word)))
22319 (and (not (get-text-property pos 'keymap))
22320 (not (get-text-property pos 'org-no-flyspell))
22321 (not (member word org-todo-keywords-1))
22322 (not (member word org-all-time-keywords))
22323 (not (member word org-options-keywords))
22324 (not (member word (mapcar 'car org-startup-options)))
22325 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22327 (defun org-remove-flyspell-overlays-in (beg end)
22328 "Remove flyspell overlays in region."
22329 (and (org-bound-and-true-p flyspell-mode)
22330 (fboundp 'flyspell-delete-region-overlays)
22331 (flyspell-delete-region-overlays beg end))
22332 (add-text-properties beg end '(org-no-flyspell t)))
22334 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22335 (eval-after-load "bookmark"
22336 '(if (boundp 'bookmark-after-jump-hook)
22337 ;; We can use the hook
22338 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22339 ;; Hook not available, use advice
22340 (defadvice bookmark-jump (after org-make-visible activate)
22341 "Make the position visible."
22342 (org-bookmark-jump-unhide))))
22344 ;; Make sure saveplace shows the location if it was hidden
22345 (eval-after-load "saveplace"
22346 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22347 "Make the position visible."
22348 (org-bookmark-jump-unhide)))
22350 ;; Make sure ecb shows the location if it was hidden
22351 (eval-after-load "ecb"
22352 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22353 "Make hierarchy visible when jumping into location from ECB tree buffer."
22354 (if (derived-mode-p 'org-mode)
22355 (org-show-context))))
22357 (defun org-bookmark-jump-unhide ()
22358 "Unhide the current position, to show the bookmark location."
22359 (and (derived-mode-p 'org-mode)
22360 (or (outline-invisible-p)
22361 (save-excursion (goto-char (max (point-min) (1- (point))))
22362 (outline-invisible-p)))
22363 (org-show-context 'bookmark-jump)))
22365 ;; Make session.el ignore our circular variable
22366 (eval-after-load "session"
22367 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22369 ;;;; Experimental code
22371 (defun org-closed-in-range ()
22372 "Sparse tree of items closed in a certain time range.
22373 Still experimental, may disappear in the future."
22374 (interactive)
22375 ;; Get the time interval from the user.
22376 (let* ((time1 (org-float-time
22377 (org-read-date nil 'to-time nil "Starting date: ")))
22378 (time2 (org-float-time
22379 (org-read-date nil 'to-time nil "End date:")))
22380 ;; callback function
22381 (callback (lambda ()
22382 (let ((time
22383 (org-float-time
22384 (apply 'encode-time
22385 (org-parse-time-string
22386 (match-string 1))))))
22387 ;; check if time in interval
22388 (and (>= time time1) (<= time time2))))))
22389 ;; make tree, check each match with the callback
22390 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22392 ;;;; Finish up
22394 (provide 'org)
22396 (run-hooks 'org-load-hook)
22398 ;;; org.el ends here