Manage variables related to both LaTeX export and snippets
[org-mode.git] / lisp / org.el
blob9b97f3fe6616a4d2ae5658a8cc5013d00f9c6eb2
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 t)
83 (require 'org-macs)
84 (require 'org-compat)
86 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
87 ;; some places -- e.g. see the macro org-with-limited-levels.
89 ;; In Org buffers, the value of `outline-regexp' is that of
90 ;; `org-outline-regexp'. The only function still directly relying on
91 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
92 ;; job when `orgstruct-mode' is active.
93 (defvar org-outline-regexp "\\*+ "
94 "Regexp to match Org headlines.")
96 (defvar org-outline-regexp-bol "^\\*+ "
97 "Regexp to match Org headlines.
98 This is similar to `org-outline-regexp' but additionally makes
99 sure that we are at the beginning of the line.")
101 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
102 "Matches an headline, putting stars and text into groups.
103 Stars are put in group 1 and the trimmed body in group 2.")
105 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
106 (when (fboundp 'defvaralias)
107 (unless (boundp 'calendar-view-holidays-initially-flag)
108 (defvaralias 'calendar-view-holidays-initially-flag
109 'view-calendar-holidays-initially))
110 (unless (boundp 'calendar-view-diary-initially-flag)
111 (defvaralias 'calendar-view-diary-initially-flag
112 'view-diary-entries-initially))
113 (unless (boundp 'diary-fancy-buffer)
114 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
116 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
117 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
118 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
119 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
120 (declare-function org-at-clock-log-p "org-clock" ())
121 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
122 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
123 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
124 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
126 (declare-function orgtbl-mode "org-table" (&optional arg))
127 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
128 (declare-function org-beamer-mode "ox-beamer" ())
129 (declare-function org-table-edit-field "org-table" (arg))
130 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
131 (declare-function org-id-get-create "org-id" (&optional force))
132 (declare-function org-id-find-id-file "org-id" (id))
133 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
134 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
135 (declare-function org-table-align "org-table" ())
136 (declare-function org-table-paste-rectangle "org-table" ())
137 (declare-function org-table-maybe-eval-formula "org-table" ())
138 (declare-function org-table-maybe-recalculate-line "org-table" ())
140 (autoload 'org-element-at-point "org-element")
141 (autoload 'org-element-type "org-element")
143 (declare-function org-element--parse-objects "org-element"
144 (beg end acc restriction))
145 (declare-function org-element-at-point "org-element" (&optional keep-trail))
146 (declare-function org-element-contents "org-element" (element))
147 (declare-function org-element-context "org-element" (&optional element))
148 (declare-function org-element-interpret-data "org-element"
149 (data &optional parent))
150 (declare-function org-element-map "org-element"
151 (data types fun &optional info first-match no-recursion))
152 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
153 (declare-function org-element-parse-buffer "org-element"
154 (&optional granularity visible-only))
155 (declare-function org-element-property "org-element" (property element))
156 (declare-function org-element-put-property "org-element"
157 (element property value))
158 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
159 (declare-function org-element--parse-objects "org-element"
160 (beg end acc restriction))
161 (declare-function org-element-parse-buffer "org-element"
162 (&optional granularity visible-only))
163 (declare-function org-element-interpret-data "org-element"
164 (data &optional parent))
166 ;; load languages based on value of `org-babel-load-languages'
167 (defvar org-babel-load-languages)
169 ;;;###autoload
170 (defun org-babel-do-load-languages (sym value)
171 "Load the languages defined in `org-babel-load-languages'."
172 (set-default sym value)
173 (mapc (lambda (pair)
174 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
175 (if active
176 (progn
177 (require (intern (concat "ob-" lang))))
178 (progn
179 (funcall 'fmakunbound
180 (intern (concat "org-babel-execute:" lang)))
181 (funcall 'fmakunbound
182 (intern (concat "org-babel-expand-body:" lang)))))))
183 org-babel-load-languages))
185 (defcustom org-babel-load-languages '((emacs-lisp . t))
186 "Languages which can be evaluated in Org-mode buffers.
187 This list can be used to load support for any of the languages
188 below, note that each language will depend on a different set of
189 system executables and/or Emacs modes. When a language is
190 \"loaded\", then code blocks in that language can be evaluated
191 with `org-babel-execute-src-block' bound by default to C-c
192 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
193 be set to remove code block evaluation from the C-c C-c
194 keybinding. By default only Emacs Lisp (which has no
195 requirements) is loaded."
196 :group 'org-babel
197 :set 'org-babel-do-load-languages
198 :version "24.1"
199 :type '(alist :tag "Babel Languages"
200 :key-type
201 (choice
202 (const :tag "Awk" awk)
203 (const :tag "C" C)
204 (const :tag "R" R)
205 (const :tag "Asymptote" asymptote)
206 (const :tag "Calc" calc)
207 (const :tag "Clojure" clojure)
208 (const :tag "CSS" css)
209 (const :tag "Ditaa" ditaa)
210 (const :tag "Dot" dot)
211 (const :tag "Emacs Lisp" emacs-lisp)
212 (const :tag "Fortran" fortran)
213 (const :tag "Gnuplot" gnuplot)
214 (const :tag "Haskell" haskell)
215 (const :tag "IO" io)
216 (const :tag "Java" java)
217 (const :tag "Javascript" js)
218 (const :tag "LaTeX" latex)
219 (const :tag "Ledger" ledger)
220 (const :tag "Lilypond" lilypond)
221 (const :tag "Lisp" lisp)
222 (const :tag "Makefile" makefile)
223 (const :tag "Maxima" maxima)
224 (const :tag "Matlab" matlab)
225 (const :tag "Mscgen" mscgen)
226 (const :tag "Ocaml" ocaml)
227 (const :tag "Octave" octave)
228 (const :tag "Org" org)
229 (const :tag "Perl" perl)
230 (const :tag "Pico Lisp" picolisp)
231 (const :tag "PlantUML" plantuml)
232 (const :tag "Python" python)
233 (const :tag "Ruby" ruby)
234 (const :tag "Sass" sass)
235 (const :tag "Scala" scala)
236 (const :tag "Scheme" scheme)
237 (const :tag "Screen" screen)
238 (const :tag "Shell Script" sh)
239 (const :tag "Shen" shen)
240 (const :tag "Sql" sql)
241 (const :tag "Sqlite" sqlite))
242 :value-type (boolean :tag "Activate" :value t)))
244 ;;;; Customization variables
245 (defcustom org-clone-delete-id nil
246 "Remove ID property of clones of a subtree.
247 When non-nil, clones of a subtree don't inherit the ID property.
248 Otherwise they inherit the ID property with a new unique
249 identifier."
250 :type 'boolean
251 :version "24.1"
252 :group 'org-id)
254 ;;; Version
255 (org-check-version)
257 ;;;###autoload
258 (defun org-version (&optional here full message)
259 "Show the org-mode version in the echo area.
260 With prefix argument HERE, insert it at point.
261 When FULL is non-nil, use a verbose version string.
262 When MESSAGE is non-nil, display a message with the version."
263 (interactive "P")
264 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
265 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
266 (load-suffixes (list ".el"))
267 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
268 (org-trash (or
269 (and (fboundp 'org-release) (fboundp 'org-git-version))
270 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
271 (load-suffixes save-load-suffixes)
272 (org-version (org-release))
273 (git-version (org-git-version))
274 (version (format "Org-mode version %s (%s @ %s)"
275 org-version
276 git-version
277 (if org-install-dir
278 (if (string= org-dir org-install-dir)
279 org-install-dir
280 (concat "mixed installation! " org-install-dir " and " org-dir))
281 "org-loaddefs.el can not be found!")))
282 (_version (if full version org-version)))
283 (if (org-called-interactively-p 'interactive)
284 (if here
285 (insert version)
286 (message version))
287 (if message (message _version))
288 _version)))
290 (defconst org-version (org-version))
292 ;;; Compatibility constants
294 ;;; The custom variables
296 (defgroup org nil
297 "Outline-based notes management and organizer."
298 :tag "Org"
299 :group 'outlines
300 :group 'calendar)
302 (defcustom org-mode-hook nil
303 "Mode hook for Org-mode, run after the mode was turned on."
304 :group 'org
305 :type 'hook)
307 (defcustom org-load-hook nil
308 "Hook that is run after org.el has been loaded."
309 :group 'org
310 :type 'hook)
312 (defcustom org-log-buffer-setup-hook nil
313 "Hook that is run after an Org log buffer is created."
314 :group 'org
315 :version "24.1"
316 :type 'hook)
318 (defvar org-modules) ; defined below
319 (defvar org-modules-loaded nil
320 "Have the modules been loaded already?")
322 (defun org-load-modules-maybe (&optional force)
323 "Load all extensions listed in `org-modules'."
324 (when (or force (not org-modules-loaded))
325 (mapc (lambda (ext)
326 (condition-case nil (require ext)
327 (error (message "Problems while trying to load feature `%s'" ext))))
328 org-modules)
329 (setq org-modules-loaded t)))
331 (defun org-set-modules (var value)
332 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
333 (set var value)
334 (when (featurep 'org)
335 (org-load-modules-maybe 'force)))
337 (defcustom org-modules '(ox-ascii org-bbdb org-bibtex org-docview org-gnus ox-html org-info org-irc ox-latex org-mew org-mhe org-rmail org-vm org-w3m org-wl)
338 "Modules that should always be loaded together with org.el.
339 If a description starts with <C>, the file is not part of Emacs
340 and loading it will require that you have downloaded and properly
341 installed the Org mode distribution.
343 You can also use this system to load external packages (i.e. neither Org
344 core modules, nor modules from the CONTRIB directory). Just add symbols
345 to the end of the list. If the package is called org-xyz.el, then you need
346 to add the symbol `xyz', and the package must have a call to
348 \(provide 'org-xyz)"
349 :group 'org
350 :set 'org-set-modules
351 :type
352 '(set :greedy t
353 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
354 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
355 (const :tag " crypt: Encryption of subtrees" org-crypt)
356 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
357 (const :tag " docview: Links to doc-view buffers" org-docview)
358 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
359 (const :tag " id: Global IDs for identifying entries" org-id)
360 (const :tag " info: Links to Info nodes" org-info)
361 (const :tag " ascii Export buffer to ASCII format" ox-ascii)
362 (const :tag " beamer Export buffer to LaTeX Beamer presentation" ox-beamer)
363 (const :tag " html Export buffer to HTML format" ox-html)
364 (const :tag " icalendar Export buffer to iCalendar format" ox-icalendar)
365 (const :tag " latex Export buffer to LaTeX format" ox-latex)
366 (const :tag " man Export buffer to MAN format" ox-man)
367 (const :tag " md Export buffer to Markdown format" ox-md)
368 (const :tag " odt Export buffer to ODT format" ox-odt)
369 (const :tag " texinfo Export buffer to Texinfo format" ox-texinfo)
370 (const :tag " infojs: Set up Sebastian Rose's JavaScript org-info.js" ox-jsinfo)
371 (const :tag " habit: Track your consistency with habits" org-habit)
372 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
373 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
374 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
375 (const :tag " mew Links to Mew folders/messages" org-mew)
376 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
377 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
378 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
379 (const :tag " vm: Links to VM folders/messages" org-vm)
380 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
381 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
382 (const :tag " mouse: Additional mouse support" org-mouse)
384 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
385 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
386 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
387 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
388 (const :tag "C collector: Collect properties into tables" org-collector)
389 (const :tag "C confluence Export buffer to Confluence Wiki format" ox-confluence)
390 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
391 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
392 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
393 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
394 (const :tag "C eval: Include command output as text" org-eval)
395 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
396 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
397 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
398 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
399 (const :tag "C groff Export buffer to Groff format" ox-groff)
400 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
402 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
404 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
405 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" ox-koma-letter)
406 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
407 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
408 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
409 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
410 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
411 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
412 (const :tag "C mtags: Support for muse-like tags" org-mtags)
413 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
414 (const :tag "C registry: A registry for Org-mode links" org-registry)
415 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
416 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
417 (const :tag "C secretary: Team management with org-mode" org-secretary)
418 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
419 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
420 (const :tag "C track: Keep up with Org-mode development" org-track)
421 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
422 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
423 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
425 (defcustom org-support-shift-select nil
426 "Non-nil means make shift-cursor commands select text when possible.
428 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
429 start selecting a region, or enlarge regions started in this way.
430 In Org-mode, in special contexts, these same keys are used for
431 other purposes, important enough to compete with shift selection.
432 Org tries to balance these needs by supporting `shift-select-mode'
433 outside these special contexts, under control of this variable.
435 The default of this variable is nil, to avoid confusing behavior. Shifted
436 cursor keys will then execute Org commands in the following contexts:
437 - on a headline, changing TODO state (left/right) and priority (up/down)
438 - on a time stamp, changing the time
439 - in a plain list item, changing the bullet type
440 - in a property definition line, switching between allowed values
441 - in the BEGIN line of a clock table (changing the time block).
442 Outside these contexts, the commands will throw an error.
444 When this variable is t and the cursor is not in a special
445 context, Org-mode will support shift-selection for making and
446 enlarging regions. To make this more effective, the bullet
447 cycling will no longer happen anywhere in an item line, but only
448 if the cursor is exactly on the bullet.
450 If you set this variable to the symbol `always', then the keys
451 will not be special in headlines, property lines, and item lines,
452 to make shift selection work there as well. If this is what you
453 want, you can use the following alternative commands: `C-c C-t'
454 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
455 can be used to switch TODO sets, `C-c -' to cycle item bullet
456 types, and properties can be edited by hand or in column view.
458 However, when the cursor is on a timestamp, shift-cursor commands
459 will still edit the time stamp - this is just too good to give up.
461 XEmacs user should have this variable set to nil, because
462 `shift-select-mode' is in Emacs 23 or later only."
463 :group 'org
464 :type '(choice
465 (const :tag "Never" nil)
466 (const :tag "When outside special context" t)
467 (const :tag "Everywhere except timestamps" always)))
469 (defcustom org-loop-over-headlines-in-active-region nil
470 "Shall some commands act upon headlines in the active region?
472 When set to `t', some commands will be performed in all headlines
473 within the active region.
475 When set to `start-level', some commands will be performed in all
476 headlines within the active region, provided that these headlines
477 are of the same level than the first one.
479 When set to a string, those commands will be performed on the
480 matching headlines within the active region. Such string must be
481 a tags/property/todo match as it is used in the agenda tags view.
483 The list of commands is: `org-schedule', `org-deadline',
484 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
485 `org-archive-to-archive-sibling'. The archiving commands skip
486 already archived entries."
487 :type '(choice (const :tag "Don't loop" nil)
488 (const :tag "All headlines in active region" t)
489 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
490 (string :tag "Tags/Property/Todo matcher"))
491 :version "24.1"
492 :group 'org-todo
493 :group 'org-archive)
495 (defgroup org-startup nil
496 "Options concerning startup of Org-mode."
497 :tag "Org Startup"
498 :group 'org)
500 (defcustom org-startup-folded t
501 "Non-nil means entering Org-mode will switch to OVERVIEW.
502 This can also be configured on a per-file basis by adding one of
503 the following lines anywhere in the buffer:
505 #+STARTUP: fold (or `overview', this is equivalent)
506 #+STARTUP: nofold (or `showall', this is equivalent)
507 #+STARTUP: content
508 #+STARTUP: showeverything"
509 :group 'org-startup
510 :type '(choice
511 (const :tag "nofold: show all" nil)
512 (const :tag "fold: overview" t)
513 (const :tag "content: all headlines" content)
514 (const :tag "show everything, even drawers" showeverything)))
516 (defcustom org-startup-truncated t
517 "Non-nil means entering Org-mode will set `truncate-lines'.
518 This is useful since some lines containing links can be very long and
519 uninteresting. Also tables look terrible when wrapped."
520 :group 'org-startup
521 :type 'boolean)
523 (defcustom org-startup-indented nil
524 "Non-nil means turn on `org-indent-mode' on startup.
525 This can also be configured on a per-file basis by adding one of
526 the following lines anywhere in the buffer:
528 #+STARTUP: indent
529 #+STARTUP: noindent"
530 :group 'org-structure
531 :type '(choice
532 (const :tag "Not" nil)
533 (const :tag "Globally (slow on startup in large files)" t)))
535 (defcustom org-use-sub-superscripts t
536 "Non-nil means interpret \"_\" and \"^\" for display.
537 When this option is turned on, you can use TeX-like syntax for sub- and
538 superscripts. Several characters after \"_\" or \"^\" will be
539 considered as a single item - so grouping with {} is normally not
540 needed. For example, the following things will be parsed as single
541 sub- or superscripts.
543 10^24 or 10^tau several digits will be considered 1 item.
544 10^-12 or 10^-tau a leading sign with digits or a word
545 x^2-y^3 will be read as x^2 - y^3, because items are
546 terminated by almost any nonword/nondigit char.
547 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
549 Still, ambiguity is possible - so when in doubt use {} to enclose
550 the sub/superscript. If you set this variable to the symbol
551 `{}', the braces are *required* in order to trigger
552 interpretations as sub/superscript. This can be helpful in
553 documents that need \"_\" frequently in plain text."
554 :group 'org-startup
555 :version "24.1"
556 :type '(choice
557 (const :tag "Always interpret" t)
558 (const :tag "Only with braces" {})
559 (const :tag "Never interpret" nil)))
561 (defcustom org-startup-with-beamer-mode nil
562 "Non-nil means turn on `org-beamer-mode' on startup.
563 This can also be configured on a per-file basis by adding one of
564 the following lines anywhere in the buffer:
566 #+STARTUP: beamer"
567 :group 'org-startup
568 :version "24.1"
569 :type 'boolean)
571 (defcustom org-startup-align-all-tables nil
572 "Non-nil means align all tables when visiting a file.
573 This is useful when the column width in tables is forced with <N> cookies
574 in table fields. Such tables will look correct only after the first re-align.
575 This can also be configured on a per-file basis by adding one of
576 the following lines anywhere in the buffer:
577 #+STARTUP: align
578 #+STARTUP: noalign"
579 :group 'org-startup
580 :type 'boolean)
582 (defcustom org-startup-with-inline-images nil
583 "Non-nil means show inline images when loading a new Org file.
584 This can also be configured on a per-file basis by adding one of
585 the following lines anywhere in the buffer:
586 #+STARTUP: inlineimages
587 #+STARTUP: noinlineimages"
588 :group 'org-startup
589 :version "24.1"
590 :type 'boolean)
592 (defcustom org-insert-mode-line-in-empty-file nil
593 "Non-nil means insert the first line setting Org-mode in empty files.
594 When the function `org-mode' is called interactively in an empty file, this
595 normally means that the file name does not automatically trigger Org-mode.
596 To ensure that the file will always be in Org-mode in the future, a
597 line enforcing Org-mode will be inserted into the buffer, if this option
598 has been set."
599 :group 'org-startup
600 :type 'boolean)
602 (defcustom org-replace-disputed-keys nil
603 "Non-nil means use alternative key bindings for some keys.
604 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
605 These keys are also used by other packages like shift-selection-mode'
606 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
607 If you want to use Org-mode together with one of these other modes,
608 or more generally if you would like to move some Org-mode commands to
609 other keys, set this variable and configure the keys with the variable
610 `org-disputed-keys'.
612 This option is only relevant at load-time of Org-mode, and must be set
613 *before* org.el is loaded. Changing it requires a restart of Emacs to
614 become effective."
615 :group 'org-startup
616 :type 'boolean)
618 (defcustom org-use-extra-keys nil
619 "Non-nil means use extra key sequence definitions for certain commands.
620 This happens automatically if you run XEmacs or if `window-system'
621 is nil. This variable lets you do the same manually. You must
622 set it before loading org.
624 Example: on Carbon Emacs 22 running graphically, with an external
625 keyboard on a Powerbook, the default way of setting M-left might
626 not work for either Alt or ESC. Setting this variable will make
627 it work for ESC."
628 :group 'org-startup
629 :type 'boolean)
631 (if (fboundp 'defvaralias)
632 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
634 (defcustom org-disputed-keys
635 '(([(shift up)] . [(meta p)])
636 ([(shift down)] . [(meta n)])
637 ([(shift left)] . [(meta -)])
638 ([(shift right)] . [(meta +)])
639 ([(control shift right)] . [(meta shift +)])
640 ([(control shift left)] . [(meta shift -)]))
641 "Keys for which Org-mode and other modes compete.
642 This is an alist, cars are the default keys, second element specifies
643 the alternative to use when `org-replace-disputed-keys' is t.
645 Keys can be specified in any syntax supported by `define-key'.
646 The value of this option takes effect only at Org-mode's startup,
647 therefore you'll have to restart Emacs to apply it after changing."
648 :group 'org-startup
649 :type 'alist)
651 (defun org-key (key)
652 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
653 Or return the original if not disputed.
654 Also apply the translations defined in `org-xemacs-key-equivalents'."
655 (when org-replace-disputed-keys
656 (let* ((nkey (key-description key))
657 (x (org-find-if (lambda (x)
658 (equal (key-description (car x)) nkey))
659 org-disputed-keys)))
660 (setq key (if x (cdr x) key))))
661 (when (featurep 'xemacs)
662 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
663 key)
665 (defun org-find-if (predicate seq)
666 (catch 'exit
667 (while seq
668 (if (funcall predicate (car seq))
669 (throw 'exit (car seq))
670 (pop seq)))))
672 (defun org-defkey (keymap key def)
673 "Define a key, possibly translated, as returned by `org-key'."
674 (define-key keymap (org-key key) def))
676 (defcustom org-ellipsis nil
677 "The ellipsis to use in the Org-mode outline.
678 When nil, just use the standard three dots. When a string, use that instead,
679 When a face, use the standard 3 dots, but with the specified face.
680 The change affects only Org-mode (which will then use its own display table).
681 Changing this requires executing `M-x org-mode' in a buffer to become
682 effective."
683 :group 'org-startup
684 :type '(choice (const :tag "Default" nil)
685 (face :tag "Face" :value org-warning)
686 (string :tag "String" :value "...#")))
688 (defvar org-display-table nil
689 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
691 (defgroup org-keywords nil
692 "Keywords in Org-mode."
693 :tag "Org Keywords"
694 :group 'org)
696 (defcustom org-deadline-string "DEADLINE:"
697 "String to mark deadline entries.
698 A deadline is this string, followed by a time stamp. Should be a word,
699 terminated by a colon. You can insert a schedule keyword and
700 a timestamp with \\[org-deadline].
701 Changes become only effective after restarting Emacs."
702 :group 'org-keywords
703 :type 'string)
705 (defcustom org-scheduled-string "SCHEDULED:"
706 "String to mark scheduled TODO entries.
707 A schedule is this string, followed by a time stamp. Should be a word,
708 terminated by a colon. You can insert a schedule keyword and
709 a timestamp with \\[org-schedule].
710 Changes become only effective after restarting Emacs."
711 :group 'org-keywords
712 :type 'string)
714 (defcustom org-closed-string "CLOSED:"
715 "String used as the prefix for timestamps logging closing a TODO entry."
716 :group 'org-keywords
717 :type 'string)
719 (defcustom org-clock-string "CLOCK:"
720 "String used as prefix for timestamps clocking work hours on an item."
721 :group 'org-keywords
722 :type 'string)
724 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
725 org-scheduled-string "\\|"
726 org-deadline-string "\\|"
727 org-closed-string "\\|"
728 org-clock-string "\\)")
729 "Matches a line with planning or clock info.")
731 (defcustom org-comment-string "COMMENT"
732 "Entries starting with this keyword will never be exported.
733 An entry can be toggled between COMMENT and normal with
734 \\[org-toggle-comment].
735 Changes become only effective after restarting Emacs."
736 :group 'org-keywords
737 :type 'string)
739 (defcustom org-quote-string "QUOTE"
740 "Entries starting with this keyword will be exported in fixed-width font.
741 Quoting applies only to the text in the entry following the headline, and does
742 not extend beyond the next headline, even if that is lower level.
743 An entry can be toggled between QUOTE and normal with
744 \\[org-toggle-fixed-width-section]."
745 :group 'org-keywords
746 :type 'string)
748 (defconst org-repeat-re
749 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
750 "Regular expression for specifying repeated events.
751 After a match, group 1 contains the repeat expression.")
753 (defgroup org-structure nil
754 "Options concerning the general structure of Org-mode files."
755 :tag "Org Structure"
756 :group 'org)
758 (defgroup org-reveal-location nil
759 "Options about how to make context of a location visible."
760 :tag "Org Reveal Location"
761 :group 'org-structure)
763 (defconst org-context-choice
764 '(choice
765 (const :tag "Always" t)
766 (const :tag "Never" nil)
767 (repeat :greedy t :tag "Individual contexts"
768 (cons
769 (choice :tag "Context"
770 (const agenda)
771 (const org-goto)
772 (const occur-tree)
773 (const tags-tree)
774 (const link-search)
775 (const mark-goto)
776 (const bookmark-jump)
777 (const isearch)
778 (const default))
779 (boolean))))
780 "Contexts for the reveal options.")
782 (defcustom org-show-hierarchy-above '((default . t))
783 "Non-nil means show full hierarchy when revealing a location.
784 Org-mode often shows locations in an org-mode file which might have
785 been invisible before. When this is set, the hierarchy of headings
786 above the exposed location is shown.
787 Turning this off for example for sparse trees makes them very compact.
788 Instead of t, this can also be an alist specifying this option for different
789 contexts. Valid contexts are
790 agenda when exposing an entry from the agenda
791 org-goto when using the command `org-goto' on key C-c C-j
792 occur-tree when using the command `org-occur' on key C-c /
793 tags-tree when constructing a sparse tree based on tags matches
794 link-search when exposing search matches associated with a link
795 mark-goto when exposing the jump goal of a mark
796 bookmark-jump when exposing a bookmark location
797 isearch when exiting from an incremental search
798 default default for all contexts not set explicitly"
799 :group 'org-reveal-location
800 :type org-context-choice)
802 (defcustom org-show-following-heading '((default . nil))
803 "Non-nil means show following heading when revealing a location.
804 Org-mode often shows locations in an org-mode file which might have
805 been invisible before. When this is set, the heading following the
806 match is shown.
807 Turning this off for example for sparse trees makes them very compact,
808 but makes it harder to edit the location of the match. In such a case,
809 use the command \\[org-reveal] to show more context.
810 Instead of t, this can also be an alist specifying this option for different
811 contexts. See `org-show-hierarchy-above' for valid contexts."
812 :group 'org-reveal-location
813 :type org-context-choice)
815 (defcustom org-show-siblings '((default . nil) (isearch t))
816 "Non-nil means show all sibling heading when revealing a location.
817 Org-mode often shows locations in an org-mode file which might have
818 been invisible before. When this is set, the sibling of the current entry
819 heading are all made visible. If `org-show-hierarchy-above' is t,
820 the same happens on each level of the hierarchy above the current entry.
822 By default this is on for the isearch context, off for all other contexts.
823 Turning this off for example for sparse trees makes them very compact,
824 but makes it harder to edit the location of the match. In such a case,
825 use the command \\[org-reveal] to show more context.
826 Instead of t, this can also be an alist specifying this option for different
827 contexts. See `org-show-hierarchy-above' for valid contexts."
828 :group 'org-reveal-location
829 :type org-context-choice)
831 (defcustom org-show-entry-below '((default . nil))
832 "Non-nil means show the entry below a headline when revealing a location.
833 Org-mode often shows locations in an org-mode file which might have
834 been invisible before. When this is set, the text below the headline that is
835 exposed is also shown.
837 By default this is off for all contexts.
838 Instead of t, this can also be an alist specifying this option for different
839 contexts. See `org-show-hierarchy-above' for valid contexts."
840 :group 'org-reveal-location
841 :type org-context-choice)
843 (defcustom org-indirect-buffer-display 'other-window
844 "How should indirect tree buffers be displayed?
845 This applies to indirect buffers created with the commands
846 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
847 Valid values are:
848 current-window Display in the current window
849 other-window Just display in another window.
850 dedicated-frame Create one new frame, and re-use it each time.
851 new-frame Make a new frame each time. Note that in this case
852 previously-made indirect buffers are kept, and you need to
853 kill these buffers yourself."
854 :group 'org-structure
855 :group 'org-agenda-windows
856 :type '(choice
857 (const :tag "In current window" current-window)
858 (const :tag "In current frame, other window" other-window)
859 (const :tag "Each time a new frame" new-frame)
860 (const :tag "One dedicated frame" dedicated-frame)))
862 (defcustom org-use-speed-commands nil
863 "Non-nil means activate single letter commands at beginning of a headline.
864 This may also be a function to test for appropriate locations where speed
865 commands should be active."
866 :group 'org-structure
867 :type '(choice
868 (const :tag "Never" nil)
869 (const :tag "At beginning of headline stars" t)
870 (function)))
872 (defcustom org-speed-commands-user nil
873 "Alist of additional speed commands.
874 This list will be checked before `org-speed-commands-default'
875 when the variable `org-use-speed-commands' is non-nil
876 and when the cursor is at the beginning of a headline.
877 The car if each entry is a string with a single letter, which must
878 be assigned to `self-insert-command' in the global map.
879 The cdr is either a command to be called interactively, a function
880 to be called, or a form to be evaluated.
881 An entry that is just a list with a single string will be interpreted
882 as a descriptive headline that will be added when listing the speed
883 commands in the Help buffer using the `?' speed command."
884 :group 'org-structure
885 :type '(repeat :value ("k" . ignore)
886 (choice :value ("k" . ignore)
887 (list :tag "Descriptive Headline" (string :tag "Headline"))
888 (cons :tag "Letter and Command"
889 (string :tag "Command letter")
890 (choice
891 (function)
892 (sexp))))))
894 (defgroup org-cycle nil
895 "Options concerning visibility cycling in Org-mode."
896 :tag "Org Cycle"
897 :group 'org-structure)
899 (defcustom org-cycle-skip-children-state-if-no-children t
900 "Non-nil means skip CHILDREN state in entries that don't have any."
901 :group 'org-cycle
902 :type 'boolean)
904 (defcustom org-cycle-max-level nil
905 "Maximum level which should still be subject to visibility cycling.
906 Levels higher than this will, for cycling, be treated as text, not a headline.
907 When `org-odd-levels-only' is set, a value of N in this variable actually
908 means 2N-1 stars as the limiting headline.
909 When nil, cycle all levels.
910 Note that the limiting level of cycling is also influenced by
911 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
912 `org-inlinetask-min-level' is, cycling will be limited to levels one less
913 than its value."
914 :group 'org-cycle
915 :type '(choice
916 (const :tag "No limit" nil)
917 (integer :tag "Maximum level")))
919 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
920 "Names of drawers. Drawers are not opened by cycling on the headline above.
921 Drawers only open with a TAB on the drawer line itself. A drawer looks like
922 this:
923 :DRAWERNAME:
924 .....
925 :END:
926 The drawer \"PROPERTIES\" is special for capturing properties through
927 the property API.
929 Drawers can be defined on the per-file basis with a line like:
931 #+DRAWERS: HIDDEN STATE PROPERTIES"
932 :group 'org-structure
933 :group 'org-cycle
934 :type '(repeat (string :tag "Drawer Name")))
936 (defcustom org-hide-block-startup nil
937 "Non-nil means entering Org-mode will fold all blocks.
938 This can also be set in on a per-file basis with
940 #+STARTUP: hideblocks
941 #+STARTUP: showblocks"
942 :group 'org-startup
943 :group 'org-cycle
944 :type 'boolean)
946 (defcustom org-cycle-global-at-bob nil
947 "Cycle globally if cursor is at beginning of buffer and not at a headline.
948 This makes it possible to do global cycling without having to use S-TAB or
949 \\[universal-argument] TAB. For this special case to work, the first line
950 of the buffer must not be a headline -- it may be empty or some other text.
951 When used in this way, `org-cycle-hook' is disabled temporarily to make
952 sure the cursor stays at the beginning of the buffer. When this option is
953 nil, don't do anything special at the beginning of the buffer."
954 :group 'org-cycle
955 :type 'boolean)
957 (defcustom org-cycle-level-after-item/entry-creation t
958 "Non-nil means cycle entry level or item indentation in new empty entries.
960 When the cursor is at the end of an empty headline, i.e with only stars
961 and maybe a TODO keyword, TAB will then switch the entry to become a child,
962 and then all possible ancestor states, before returning to the original state.
963 This makes data entry extremely fast: M-RET to create a new headline,
964 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
966 When the cursor is at the end of an empty plain list item, one TAB will
967 make it a subitem, two or more tabs will back up to make this an item
968 higher up in the item hierarchy."
969 :group 'org-cycle
970 :type 'boolean)
972 (defcustom org-cycle-emulate-tab t
973 "Where should `org-cycle' emulate TAB.
974 nil Never
975 white Only in completely white lines
976 whitestart Only at the beginning of lines, before the first non-white char
977 t Everywhere except in headlines
978 exc-hl-bol Everywhere except at the start of a headline
979 If TAB is used in a place where it does not emulate TAB, the current subtree
980 visibility is cycled."
981 :group 'org-cycle
982 :type '(choice (const :tag "Never" nil)
983 (const :tag "Only in completely white lines" white)
984 (const :tag "Before first char in a line" whitestart)
985 (const :tag "Everywhere except in headlines" t)
986 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
989 (defcustom org-cycle-separator-lines 2
990 "Number of empty lines needed to keep an empty line between collapsed trees.
991 If you leave an empty line between the end of a subtree and the following
992 headline, this empty line is hidden when the subtree is folded.
993 Org-mode will leave (exactly) one empty line visible if the number of
994 empty lines is equal or larger to the number given in this variable.
995 So the default 2 means at least 2 empty lines after the end of a subtree
996 are needed to produce free space between a collapsed subtree and the
997 following headline.
999 If the number is negative, and the number of empty lines is at least -N,
1000 all empty lines are shown.
1002 Special case: when 0, never leave empty lines in collapsed view."
1003 :group 'org-cycle
1004 :type 'integer)
1005 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1007 (defcustom org-pre-cycle-hook nil
1008 "Hook that is run before visibility cycling is happening.
1009 The function(s) in this hook must accept a single argument which indicates
1010 the new state that will be set right after running this hook. The
1011 argument is a symbol. Before a global state change, it can have the values
1012 `overview', `content', or `all'. Before a local state change, it can have
1013 the values `folded', `children', or `subtree'."
1014 :group 'org-cycle
1015 :type 'hook)
1017 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1018 org-cycle-hide-drawers
1019 org-cycle-hide-inline-tasks
1020 org-cycle-show-empty-lines
1021 org-optimize-window-after-visibility-change)
1022 "Hook that is run after `org-cycle' has changed the buffer visibility.
1023 The function(s) in this hook must accept a single argument which indicates
1024 the new state that was set by the most recent `org-cycle' command. The
1025 argument is a symbol. After a global state change, it can have the values
1026 `overview', `contents', or `all'. After a local state change, it can have
1027 the values `folded', `children', or `subtree'."
1028 :group 'org-cycle
1029 :type 'hook)
1031 (defgroup org-edit-structure nil
1032 "Options concerning structure editing in Org-mode."
1033 :tag "Org Edit Structure"
1034 :group 'org-structure)
1036 (defcustom org-odd-levels-only nil
1037 "Non-nil means skip even levels and only use odd levels for the outline.
1038 This has the effect that two stars are being added/taken away in
1039 promotion/demotion commands. It also influences how levels are
1040 handled by the exporters.
1041 Changing it requires restart of `font-lock-mode' to become effective
1042 for fontification also in regions already fontified.
1043 You may also set this on a per-file basis by adding one of the following
1044 lines to the buffer:
1046 #+STARTUP: odd
1047 #+STARTUP: oddeven"
1048 :group 'org-edit-structure
1049 :group 'org-appearance
1050 :type 'boolean)
1052 (defcustom org-adapt-indentation t
1053 "Non-nil means adapt indentation to outline node level.
1055 When this variable is set, Org assumes that you write outlines by
1056 indenting text in each node to align with the headline (after the stars).
1057 The following issues are influenced by this variable:
1059 - When this is set and the *entire* text in an entry is indented, the
1060 indentation is increased by one space in a demotion command, and
1061 decreased by one in a promotion command. If any line in the entry
1062 body starts with text at column 0, indentation is not changed at all.
1064 - Property drawers and planning information is inserted indented when
1065 this variable s set. When nil, they will not be indented.
1067 - TAB indents a line relative to context. The lines below a headline
1068 will be indented when this variable is set.
1070 Note that this is all about true indentation, by adding and removing
1071 space characters. See also `org-indent.el' which does level-dependent
1072 indentation in a virtual way, i.e. at display time in Emacs."
1073 :group 'org-edit-structure
1074 :type 'boolean)
1076 (defcustom org-special-ctrl-a/e nil
1077 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1079 When t, `C-a' will bring back the cursor to the beginning of the
1080 headline text, i.e. after the stars and after a possible TODO
1081 keyword. In an item, this will be the position after bullet and
1082 check-box, if any. When the cursor is already at that position,
1083 another `C-a' will bring it to the beginning of the line.
1085 `C-e' will jump to the end of the headline, ignoring the presence
1086 of tags in the headline. A second `C-e' will then jump to the
1087 true end of the line, after any tags. This also means that, when
1088 this variable is non-nil, `C-e' also will never jump beyond the
1089 end of the heading of a folded section, i.e. not after the
1090 ellipses.
1092 When set to the symbol `reversed', the first `C-a' or `C-e' works
1093 normally, going to the true line boundary first. Only a directly
1094 following, identical keypress will bring the cursor to the
1095 special positions.
1097 This may also be a cons cell where the behavior for `C-a' and
1098 `C-e' is set separately."
1099 :group 'org-edit-structure
1100 :type '(choice
1101 (const :tag "off" nil)
1102 (const :tag "on: after stars/bullet and before tags first" t)
1103 (const :tag "reversed: true line boundary first" reversed)
1104 (cons :tag "Set C-a and C-e separately"
1105 (choice :tag "Special C-a"
1106 (const :tag "off" nil)
1107 (const :tag "on: after stars/bullet first" t)
1108 (const :tag "reversed: before stars/bullet first" reversed))
1109 (choice :tag "Special C-e"
1110 (const :tag "off" nil)
1111 (const :tag "on: before tags first" t)
1112 (const :tag "reversed: after tags first" reversed)))))
1113 (if (fboundp 'defvaralias)
1114 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1116 (defcustom org-special-ctrl-k nil
1117 "Non-nil means `C-k' will behave specially in headlines.
1118 When nil, `C-k' will call the default `kill-line' command.
1119 When t, the following will happen while the cursor is in the headline:
1121 - When the cursor is at the beginning of a headline, kill the entire
1122 line and possible the folded subtree below the line.
1123 - When in the middle of the headline text, kill the headline up to the tags.
1124 - When after the headline text, kill the tags."
1125 :group 'org-edit-structure
1126 :type 'boolean)
1128 (defcustom org-ctrl-k-protect-subtree nil
1129 "Non-nil means, do not delete a hidden subtree with C-k.
1130 When set to the symbol `error', simply throw an error when C-k is
1131 used to kill (part-of) a headline that has hidden text behind it.
1132 Any other non-nil value will result in a query to the user, if it is
1133 OK to kill that hidden subtree. When nil, kill without remorse."
1134 :group 'org-edit-structure
1135 :version "24.1"
1136 :type '(choice
1137 (const :tag "Do not protect hidden subtrees" nil)
1138 (const :tag "Protect hidden subtrees with a security query" t)
1139 (const :tag "Never kill a hidden subtree with C-k" error)))
1141 (defcustom org-catch-invisible-edits nil
1142 "Check if in invisible region before inserting or deleting a character.
1143 Valid values are:
1145 nil Do not check, so just do invisible edits.
1146 error Throw an error and do nothing.
1147 show Make point visible, and do the requested edit.
1148 show-and-error Make point visible, then throw an error and abort the edit.
1149 smart Make point visible, and do insertion/deletion if it is
1150 adjacent to visible text and the change feels predictable.
1151 Never delete a previously invisible character or add in the
1152 middle or right after an invisible region. Basically, this
1153 allows insertion and backward-delete right before ellipses.
1154 FIXME: maybe in this case we should not even show?"
1155 :group 'org-edit-structure
1156 :version "24.1"
1157 :type '(choice
1158 (const :tag "Do not check" nil)
1159 (const :tag "Throw error when trying to edit" error)
1160 (const :tag "Unhide, but do not do the edit" show-and-error)
1161 (const :tag "Show invisible part and do the edit" show)
1162 (const :tag "Be smart and do the right thing" smart)))
1164 (defcustom org-yank-folded-subtrees t
1165 "Non-nil means when yanking subtrees, fold them.
1166 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1167 it starts with a heading and all other headings in it are either children
1168 or siblings, then fold all the subtrees. However, do this only if no
1169 text after the yank would be swallowed into a folded tree by this action."
1170 :group 'org-edit-structure
1171 :type 'boolean)
1173 (defcustom org-yank-adjusted-subtrees nil
1174 "Non-nil means when yanking subtrees, adjust the level.
1175 With this setting, `org-paste-subtree' is used to insert the subtree, see
1176 this function for details."
1177 :group 'org-edit-structure
1178 :type 'boolean)
1180 (defcustom org-M-RET-may-split-line '((default . t))
1181 "Non-nil means M-RET will split the line at the cursor position.
1182 When nil, it will go to the end of the line before making a
1183 new line.
1184 You may also set this option in a different way for different
1185 contexts. Valid contexts are:
1187 headline when creating a new headline
1188 item when creating a new item
1189 table in a table field
1190 default the value to be used for all contexts not explicitly
1191 customized"
1192 :group 'org-structure
1193 :group 'org-table
1194 :type '(choice
1195 (const :tag "Always" t)
1196 (const :tag "Never" nil)
1197 (repeat :greedy t :tag "Individual contexts"
1198 (cons
1199 (choice :tag "Context"
1200 (const headline)
1201 (const item)
1202 (const table)
1203 (const default))
1204 (boolean)))))
1207 (defcustom org-insert-heading-respect-content nil
1208 "Non-nil means insert new headings after the current subtree.
1209 When nil, the new heading is created directly after the current line.
1210 The commands \\[org-insert-heading-respect-content] and
1211 \\[org-insert-todo-heading-respect-content] turn this variable on
1212 for the duration of the command."
1213 :group 'org-structure
1214 :type 'boolean)
1216 (defcustom org-blank-before-new-entry '((heading . auto)
1217 (plain-list-item . auto))
1218 "Should `org-insert-heading' leave a blank line before new heading/item?
1219 The value is an alist, with `heading' and `plain-list-item' as CAR,
1220 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1221 which case Org will look at the surrounding headings/items and try to
1222 make an intelligent decision whether to insert a blank line or not.
1224 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1225 set, the setting here is ignored and no empty line is inserted, to avoid
1226 breaking the list structure."
1227 :group 'org-edit-structure
1228 :type '(list
1229 (cons (const heading)
1230 (choice (const :tag "Never" nil)
1231 (const :tag "Always" t)
1232 (const :tag "Auto" auto)))
1233 (cons (const plain-list-item)
1234 (choice (const :tag "Never" nil)
1235 (const :tag "Always" t)
1236 (const :tag "Auto" auto)))))
1238 (defcustom org-insert-heading-hook nil
1239 "Hook being run after inserting a new heading."
1240 :group 'org-edit-structure
1241 :type 'hook)
1243 (defcustom org-enable-fixed-width-editor t
1244 "Non-nil means lines starting with \":\" are treated as fixed-width.
1245 This currently only means they are never auto-wrapped.
1246 When nil, such lines will be treated like ordinary lines.
1247 See also the QUOTE keyword."
1248 :group 'org-edit-structure
1249 :type 'boolean)
1251 (defcustom org-goto-auto-isearch t
1252 "Non-nil means typing characters in `org-goto' starts incremental search.
1253 When nil, you can use these keybindings to navigate the buffer:
1255 q Quit the org-goto interface
1256 n Go to the next visible heading
1257 p Go to the previous visible heading
1258 f Go one heading forward on same level
1259 b Go one heading backward on same level
1260 u Go one heading up"
1261 :group 'org-edit-structure
1262 :type 'boolean)
1264 (defgroup org-sparse-trees nil
1265 "Options concerning sparse trees in Org-mode."
1266 :tag "Org Sparse Trees"
1267 :group 'org-structure)
1269 (defcustom org-highlight-sparse-tree-matches t
1270 "Non-nil means highlight all matches that define a sparse tree.
1271 The highlights will automatically disappear the next time the buffer is
1272 changed by an edit command."
1273 :group 'org-sparse-trees
1274 :type 'boolean)
1276 (defcustom org-remove-highlights-with-change t
1277 "Non-nil means any change to the buffer will remove temporary highlights.
1278 Such highlights are created by `org-occur' and `org-clock-display'.
1279 When nil, `C-c C-c needs to be used to get rid of the highlights.
1280 The highlights created by `org-preview-latex-fragment' always need
1281 `C-c C-c' to be removed."
1282 :group 'org-sparse-trees
1283 :group 'org-time
1284 :type 'boolean)
1287 (defcustom org-occur-hook '(org-first-headline-recenter)
1288 "Hook that is run after `org-occur' has constructed a sparse tree.
1289 This can be used to recenter the window to show as much of the structure
1290 as possible."
1291 :group 'org-sparse-trees
1292 :type 'hook)
1294 (defgroup org-imenu-and-speedbar nil
1295 "Options concerning imenu and speedbar in Org-mode."
1296 :tag "Org Imenu and Speedbar"
1297 :group 'org-structure)
1299 (defcustom org-imenu-depth 2
1300 "The maximum level for Imenu access to Org-mode headlines.
1301 This also applied for speedbar access."
1302 :group 'org-imenu-and-speedbar
1303 :type 'integer)
1305 (defgroup org-table nil
1306 "Options concerning tables in Org-mode."
1307 :tag "Org Table"
1308 :group 'org)
1310 (defcustom org-enable-table-editor 'optimized
1311 "Non-nil means lines starting with \"|\" are handled by the table editor.
1312 When nil, such lines will be treated like ordinary lines.
1314 When equal to the symbol `optimized', the table editor will be optimized to
1315 do the following:
1316 - Automatic overwrite mode in front of whitespace in table fields.
1317 This makes the structure of the table stay in tact as long as the edited
1318 field does not exceed the column width.
1319 - Minimize the number of realigns. Normally, the table is aligned each time
1320 TAB or RET are pressed to move to another field. With optimization this
1321 happens only if changes to a field might have changed the column width.
1322 Optimization requires replacing the functions `self-insert-command',
1323 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1324 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1325 very good at guessing when a re-align will be necessary, but you can always
1326 force one with \\[org-ctrl-c-ctrl-c].
1328 If you would like to use the optimized version in Org-mode, but the
1329 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1331 This variable can be used to turn on and off the table editor during a session,
1332 but in order to toggle optimization, a restart is required.
1334 See also the variable `org-table-auto-blank-field'."
1335 :group 'org-table
1336 :type '(choice
1337 (const :tag "off" nil)
1338 (const :tag "on" t)
1339 (const :tag "on, optimized" optimized)))
1341 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1342 (version<= emacs-version "24.1"))
1343 "Non-nil means cluster self-insert commands for undo when possible.
1344 If this is set, then, like in the Emacs command loop, 20 consecutive
1345 characters will be undone together.
1346 This is configurable, because there is some impact on typing performance."
1347 :group 'org-table
1348 :type 'boolean)
1350 (defcustom org-table-tab-recognizes-table.el t
1351 "Non-nil means TAB will automatically notice a table.el table.
1352 When it sees such a table, it moves point into it and - if necessary -
1353 calls `table-recognize-table'."
1354 :group 'org-table-editing
1355 :type 'boolean)
1357 (defgroup org-link nil
1358 "Options concerning links in Org-mode."
1359 :tag "Org Link"
1360 :group 'org)
1362 (defvar org-link-abbrev-alist-local nil
1363 "Buffer-local version of `org-link-abbrev-alist', which see.
1364 The value of this is taken from the #+LINK lines.")
1365 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1367 (defcustom org-link-abbrev-alist nil
1368 "Alist of link abbreviations.
1369 The car of each element is a string, to be replaced at the start of a link.
1370 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1371 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1373 [[linkkey:tag][description]]
1375 The 'linkkey' must be a word word, starting with a letter, followed
1376 by letters, numbers, '-' or '_'.
1378 If REPLACE is a string, the tag will simply be appended to create the link.
1379 If the string contains \"%s\", the tag will be inserted there. If the string
1380 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1381 at that point (see the function `url-hexify-string'). If the string contains
1382 the specifier \"%(my-function)\", then the custom function `my-function' will
1383 be invoked: this function takes the tag as its only argument and must return
1384 a string.
1386 REPLACE may also be a function that will be called with the tag as the
1387 only argument to create the link, which should be returned as a string.
1389 See the manual for examples."
1390 :group 'org-link
1391 :type '(repeat
1392 (cons
1393 (string :tag "Protocol")
1394 (choice
1395 (string :tag "Format")
1396 (function)))))
1398 (defcustom org-descriptive-links t
1399 "Non-nil means Org will display descriptive links.
1400 E.g. [[http://orgmode.org][Org website]] will be displayed as
1401 \"Org Website\", hiding the link itself and just displaying its
1402 description. When set to `nil', Org will display the full links
1403 literally.
1405 You can interactively set the value of this variable by calling
1406 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1407 :group 'org-link
1408 :type 'boolean)
1410 (defcustom org-link-file-path-type 'adaptive
1411 "How the path name in file links should be stored.
1412 Valid values are:
1414 relative Relative to the current directory, i.e. the directory of the file
1415 into which the link is being inserted.
1416 absolute Absolute path, if possible with ~ for home directory.
1417 noabbrev Absolute path, no abbreviation of home directory.
1418 adaptive Use relative path for files in the current directory and sub-
1419 directories of it. For other files, use an absolute path."
1420 :group 'org-link
1421 :type '(choice
1422 (const relative)
1423 (const absolute)
1424 (const noabbrev)
1425 (const adaptive)))
1427 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1428 "Types of links that should be activated in Org-mode files.
1429 This is a list of symbols, each leading to the activation of a certain link
1430 type. In principle, it does not hurt to turn on most link types - there may
1431 be a small gain when turning off unused link types. The types are:
1433 bracket The recommended [[link][description]] or [[link]] links with hiding.
1434 angle Links in angular brackets that may contain whitespace like
1435 <bbdb:Carsten Dominik>.
1436 plain Plain links in normal text, no whitespace, like http://google.com.
1437 radio Text that is matched by a radio target, see manual for details.
1438 tag Tag settings in a headline (link to tag search).
1439 date Time stamps (link to calendar).
1440 footnote Footnote labels.
1442 Changing this variable requires a restart of Emacs to become effective."
1443 :group 'org-link
1444 :type '(set :greedy t
1445 (const :tag "Double bracket links" bracket)
1446 (const :tag "Angular bracket links" angle)
1447 (const :tag "Plain text links" plain)
1448 (const :tag "Radio target matches" radio)
1449 (const :tag "Tags" tag)
1450 (const :tag "Timestamps" date)
1451 (const :tag "Footnotes" footnote)))
1453 (defcustom org-make-link-description-function nil
1454 "Function to use for generating link descriptions from links.
1455 When nil, the link location will be used. This function must take
1456 two parameters: the first one is the link, the second one is the
1457 description generated by `org-insert-link'. The function should
1458 return the description to use."
1459 :group 'org-link
1460 :type 'function)
1462 (defgroup org-link-store nil
1463 "Options concerning storing links in Org-mode."
1464 :tag "Org Store Link"
1465 :group 'org-link)
1467 (defcustom org-url-hexify-p t
1468 "When non-nil, hexify URL when creating a link."
1469 :type 'boolean
1470 :version "24.3"
1471 :group 'org-link-store)
1473 (defcustom org-email-link-description-format "Email %c: %.30s"
1474 "Format of the description part of a link to an email or usenet message.
1475 The following %-escapes will be replaced by corresponding information:
1477 %F full \"From\" field
1478 %f name, taken from \"From\" field, address if no name
1479 %T full \"To\" field
1480 %t first name in \"To\" field, address if no name
1481 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1482 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1483 %s subject
1484 %d date
1485 %m message-id.
1487 You may use normal field width specification between the % and the letter.
1488 This is for example useful to limit the length of the subject.
1490 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1491 :group 'org-link-store
1492 :type 'string)
1494 (defcustom org-from-is-user-regexp
1495 (let (r1 r2)
1496 (when (and user-mail-address (not (string= user-mail-address "")))
1497 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1498 (when (and user-full-name (not (string= user-full-name "")))
1499 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1500 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1501 "Regexp matched against the \"From:\" header of an email or usenet message.
1502 It should match if the message is from the user him/herself."
1503 :group 'org-link-store
1504 :type 'regexp)
1506 (defcustom org-context-in-file-links t
1507 "Non-nil means file links from `org-store-link' contain context.
1508 A search string will be added to the file name with :: as separator and
1509 used to find the context when the link is activated by the command
1510 `org-open-at-point'. When this option is t, the entire active region
1511 will be placed in the search string of the file link. If set to a
1512 positive integer, only the first n lines of context will be stored.
1514 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1515 negates this setting for the duration of the command."
1516 :group 'org-link-store
1517 :type '(choice boolean integer))
1519 (defcustom org-keep-stored-link-after-insertion nil
1520 "Non-nil means keep link in list for entire session.
1522 The command `org-store-link' adds a link pointing to the current
1523 location to an internal list. These links accumulate during a session.
1524 The command `org-insert-link' can be used to insert links into any
1525 Org-mode file (offering completion for all stored links). When this
1526 option is nil, every link which has been inserted once using \\[org-insert-link]
1527 will be removed from the list, to make completing the unused links
1528 more efficient."
1529 :group 'org-link-store
1530 :type 'boolean)
1532 (defgroup org-link-follow nil
1533 "Options concerning following links in Org-mode."
1534 :tag "Org Follow Link"
1535 :group 'org-link)
1537 (defcustom org-link-translation-function nil
1538 "Function to translate links with different syntax to Org syntax.
1539 This can be used to translate links created for example by the Planner
1540 or emacs-wiki packages to Org syntax.
1541 The function must accept two parameters, a TYPE containing the link
1542 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1543 which is everything after the link protocol. It should return a cons
1544 with possibly modified values of type and path.
1545 Org contains a function for this, so if you set this variable to
1546 `org-translate-link-from-planner', you should be able follow many
1547 links created by planner."
1548 :group 'org-link-follow
1549 :type 'function)
1551 (defcustom org-follow-link-hook nil
1552 "Hook that is run after a link has been followed."
1553 :group 'org-link-follow
1554 :type 'hook)
1556 (defcustom org-tab-follows-link nil
1557 "Non-nil means on links TAB will follow the link.
1558 Needs to be set before org.el is loaded.
1559 This really should not be used, it does not make sense, and the
1560 implementation is bad."
1561 :group 'org-link-follow
1562 :type 'boolean)
1564 (defcustom org-return-follows-link nil
1565 "Non-nil means on links RET will follow the link."
1566 :group 'org-link-follow
1567 :type 'boolean)
1569 (defcustom org-mouse-1-follows-link
1570 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1571 "Non-nil means mouse-1 on a link will follow the link.
1572 A longer mouse click will still set point. Does not work on XEmacs.
1573 Needs to be set before org.el is loaded."
1574 :group 'org-link-follow
1575 :type 'boolean)
1577 (defcustom org-mark-ring-length 4
1578 "Number of different positions to be recorded in the ring.
1579 Changing this requires a restart of Emacs to work correctly."
1580 :group 'org-link-follow
1581 :type 'integer)
1583 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1584 "Non-nil means internal links in Org files must exactly match a headline.
1585 When nil, the link search tries to match a phrase with all words
1586 in the search text."
1587 :group 'org-link-follow
1588 :version "24.1"
1589 :type '(choice
1590 (const :tag "Use fuzzy text search" nil)
1591 (const :tag "Match only exact headline" t)
1592 (const :tag "Match exact headline or query to create it"
1593 query-to-create)))
1595 (defcustom org-link-frame-setup
1596 '((vm . vm-visit-folder-other-frame)
1597 (vm-imap . vm-visit-imap-folder-other-frame)
1598 (gnus . org-gnus-no-new-news)
1599 (file . find-file-other-window)
1600 (wl . wl-other-frame))
1601 "Setup the frame configuration for following links.
1602 When following a link with Emacs, it may often be useful to display
1603 this link in another window or frame. This variable can be used to
1604 set this up for the different types of links.
1605 For VM, use any of
1606 `vm-visit-folder'
1607 `vm-visit-folder-other-window'
1608 `vm-visit-folder-other-frame'
1609 For Gnus, use any of
1610 `gnus'
1611 `gnus-other-frame'
1612 `org-gnus-no-new-news'
1613 For FILE, use any of
1614 `find-file'
1615 `find-file-other-window'
1616 `find-file-other-frame'
1617 For Wanderlust use any of
1618 `wl'
1619 `wl-other-frame'
1620 For the calendar, use the variable `calendar-setup'.
1621 For BBDB, it is currently only possible to display the matches in
1622 another window."
1623 :group 'org-link-follow
1624 :type '(list
1625 (cons (const vm)
1626 (choice
1627 (const vm-visit-folder)
1628 (const vm-visit-folder-other-window)
1629 (const vm-visit-folder-other-frame)))
1630 (cons (const gnus)
1631 (choice
1632 (const gnus)
1633 (const gnus-other-frame)
1634 (const org-gnus-no-new-news)))
1635 (cons (const file)
1636 (choice
1637 (const find-file)
1638 (const find-file-other-window)
1639 (const find-file-other-frame)))
1640 (cons (const wl)
1641 (choice
1642 (const wl)
1643 (const wl-other-frame)))))
1645 (defcustom org-display-internal-link-with-indirect-buffer nil
1646 "Non-nil means use indirect buffer to display infile links.
1647 Activating internal links (from one location in a file to another location
1648 in the same file) normally just jumps to the location. When the link is
1649 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1650 is displayed in
1651 another window. When this option is set, the other window actually displays
1652 an indirect buffer clone of the current buffer, to avoid any visibility
1653 changes to the current buffer."
1654 :group 'org-link-follow
1655 :type 'boolean)
1657 (defcustom org-open-non-existing-files nil
1658 "Non-nil means `org-open-file' will open non-existing files.
1659 When nil, an error will be generated.
1660 This variable applies only to external applications because they
1661 might choke on non-existing files. If the link is to a file that
1662 will be opened in Emacs, the variable is ignored."
1663 :group 'org-link-follow
1664 :type 'boolean)
1666 (defcustom org-open-directory-means-index-dot-org nil
1667 "Non-nil means a link to a directory really means to index.org.
1668 When nil, following a directory link will run dired or open a finder/explorer
1669 window on that directory."
1670 :group 'org-link-follow
1671 :type 'boolean)
1673 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1674 "Function and arguments to call for following mailto links.
1675 This is a list with the first element being a Lisp function, and the
1676 remaining elements being arguments to the function. In string arguments,
1677 %a will be replaced by the address, and %s will be replaced by the subject
1678 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1679 :group 'org-link-follow
1680 :type '(choice
1681 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1682 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1683 (const :tag "message-mail" (message-mail "%a" "%s"))
1684 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1686 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1687 "Non-nil means ask for confirmation before executing shell links.
1688 Shell links can be dangerous: just think about a link
1690 [[shell: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-shell-link-not-regexp ""
1707 "A regexp to skip confirmation for shell links."
1708 :group 'org-link-follow
1709 :version "24.1"
1710 :type 'regexp)
1712 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1713 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1714 Elisp links can be dangerous: just think about a link
1716 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1718 This link would show up in your Org-mode document as \"Google Search\",
1719 but really it would remove your entire home directory.
1720 Therefore we advise against setting this variable to nil.
1721 Just change it to `y-or-n-p' if you want to confirm with a
1722 single keystroke rather than having to type \"yes\"."
1723 :group 'org-link-follow
1724 :type '(choice
1725 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1726 (const :tag "with y-or-n (faster)" y-or-n-p)
1727 (const :tag "no confirmation (dangerous)" nil)))
1728 (put 'org-confirm-shell-link-function
1729 'safe-local-variable
1730 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1732 (defcustom org-confirm-elisp-link-not-regexp ""
1733 "A regexp to skip confirmation for Elisp links."
1734 :group 'org-link-follow
1735 :version "24.1"
1736 :type 'regexp)
1738 (defconst org-file-apps-defaults-gnu
1739 '((remote . emacs)
1740 (system . mailcap)
1741 (t . mailcap))
1742 "Default file applications on a UNIX or GNU/Linux system.
1743 See `org-file-apps'.")
1745 (defconst org-file-apps-defaults-macosx
1746 '((remote . emacs)
1747 (t . "open %s")
1748 (system . "open %s")
1749 ("ps.gz" . "gv %s")
1750 ("eps.gz" . "gv %s")
1751 ("dvi" . "xdvi %s")
1752 ("fig" . "xfig %s"))
1753 "Default file applications on a MacOS X system.
1754 The system \"open\" is known as a default, but we use X11 applications
1755 for some files for which the OS does not have a good default.
1756 See `org-file-apps'.")
1758 (defconst org-file-apps-defaults-windowsnt
1759 (list
1760 '(remote . emacs)
1761 (cons t
1762 (list (if (featurep 'xemacs)
1763 'mswindows-shell-execute
1764 'w32-shell-execute)
1765 "open" 'file))
1766 (cons 'system
1767 (list (if (featurep 'xemacs)
1768 'mswindows-shell-execute
1769 'w32-shell-execute)
1770 "open" 'file)))
1771 "Default file applications on a Windows NT system.
1772 The system \"open\" is used for most files.
1773 See `org-file-apps'.")
1775 (defcustom org-file-apps
1777 (auto-mode . emacs)
1778 ("\\.mm\\'" . default)
1779 ("\\.x?html?\\'" . default)
1780 ("\\.pdf\\'" . default)
1782 "External applications for opening `file:path' items in a document.
1783 Org-mode uses system defaults for different file types, but
1784 you can use this variable to set the application for a given file
1785 extension. The entries in this list are cons cells where the car identifies
1786 files and the cdr the corresponding command. Possible values for the
1787 file identifier are
1788 \"string\" A string as a file identifier can be interpreted in different
1789 ways, depending on its contents:
1791 - Alphanumeric characters only:
1792 Match links with this file extension.
1793 Example: (\"pdf\" . \"evince %s\")
1794 to open PDFs with evince.
1796 - Regular expression: Match links where the
1797 filename matches the regexp. If you want to
1798 use groups here, use shy groups.
1800 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1801 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1802 to open *.html and *.xhtml with firefox.
1804 - Regular expression which contains (non-shy) groups:
1805 Match links where the whole link, including \"::\", and
1806 anything after that, matches the regexp.
1807 In a custom command string, %1, %2, etc. are replaced with
1808 the parts of the link that were matched by the groups.
1809 For backwards compatibility, if a command string is given
1810 that does not use any of the group matches, this case is
1811 handled identically to the second one (i.e. match against
1812 file name only).
1813 In a custom lisp form, you can access the group matches with
1814 (match-string n link).
1816 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1817 to open [[file:document.pdf::5]] with evince at page 5.
1819 `directory' Matches a directory
1820 `remote' Matches a remote file, accessible through tramp or efs.
1821 Remote files most likely should be visited through Emacs
1822 because external applications cannot handle such paths.
1823 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1824 so all files Emacs knows how to handle. Using this with
1825 command `emacs' will open most files in Emacs. Beware that this
1826 will also open html files inside Emacs, unless you add
1827 (\"html\" . default) to the list as well.
1828 t Default for files not matched by any of the other options.
1829 `system' The system command to open files, like `open' on Windows
1830 and Mac OS X, and mailcap under GNU/Linux. This is the command
1831 that will be selected if you call `C-c C-o' with a double
1832 \\[universal-argument] \\[universal-argument] prefix.
1834 Possible values for the command are:
1835 `emacs' The file will be visited by the current Emacs process.
1836 `default' Use the default application for this file type, which is the
1837 association for t in the list, most likely in the system-specific
1838 part.
1839 This can be used to overrule an unwanted setting in the
1840 system-specific variable.
1841 `system' Use the system command for opening files, like \"open\".
1842 This command is specified by the entry whose car is `system'.
1843 Most likely, the system-specific version of this variable
1844 does define this command, but you can overrule/replace it
1845 here.
1846 string A command to be executed by a shell; %s will be replaced
1847 by the path to the file.
1848 sexp A Lisp form which will be evaluated. The file path will
1849 be available in the Lisp variable `file'.
1850 For more examples, see the system specific constants
1851 `org-file-apps-defaults-macosx'
1852 `org-file-apps-defaults-windowsnt'
1853 `org-file-apps-defaults-gnu'."
1854 :group 'org-link-follow
1855 :type '(repeat
1856 (cons (choice :value ""
1857 (string :tag "Extension")
1858 (const :tag "System command to open files" system)
1859 (const :tag "Default for unrecognized files" t)
1860 (const :tag "Remote file" remote)
1861 (const :tag "Links to a directory" directory)
1862 (const :tag "Any files that have Emacs modes"
1863 auto-mode))
1864 (choice :value ""
1865 (const :tag "Visit with Emacs" emacs)
1866 (const :tag "Use default" default)
1867 (const :tag "Use the system command" system)
1868 (string :tag "Command")
1869 (sexp :tag "Lisp form")))))
1871 (defcustom org-doi-server-url "http://dx.doi.org/"
1872 "The URL of the DOI server."
1873 :type 'string
1874 :version "24.3"
1875 :group 'org-link-follow)
1877 (defgroup org-refile nil
1878 "Options concerning refiling entries in Org-mode."
1879 :tag "Org Refile"
1880 :group 'org)
1882 (defcustom org-directory "~/org"
1883 "Directory with org files.
1884 This is just a default location to look for Org files. There is no need
1885 at all to put your files into this directory. It is only used in the
1886 following situations:
1888 1. When a capture template specifies a target file that is not an
1889 absolute path. The path will then be interpreted relative to
1890 `org-directory'
1891 2. When a capture note is filed away in an interactive way (when exiting the
1892 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1893 with `org-directory' as the default path."
1894 :group 'org-refile
1895 :group 'org-remember
1896 :group 'org-capture
1897 :type 'directory)
1899 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1900 "Default target for storing notes.
1901 Used as a fall back file for org-remember.el and org-capture.el, for
1902 templates that do not specify a target file."
1903 :group 'org-refile
1904 :group 'org-remember
1905 :group 'org-capture
1906 :type '(choice
1907 (const :tag "Default from remember-data-file" nil)
1908 file))
1910 (defcustom org-goto-interface 'outline
1911 "The default interface to be used for `org-goto'.
1912 Allowed values are:
1913 outline The interface shows an outline of the relevant file
1914 and the correct heading is found by moving through
1915 the outline or by searching with incremental search.
1916 outline-path-completion Headlines in the current buffer are offered via
1917 completion. This is the interface also used by
1918 the refile command."
1919 :group 'org-refile
1920 :type '(choice
1921 (const :tag "Outline" outline)
1922 (const :tag "Outline-path-completion" outline-path-completion)))
1924 (defcustom org-goto-max-level 5
1925 "Maximum target level when running `org-goto' with refile interface."
1926 :group 'org-refile
1927 :type 'integer)
1929 (defcustom org-reverse-note-order nil
1930 "Non-nil means store new notes at the beginning of a file or entry.
1931 When nil, new notes will be filed to the end of a file or entry.
1932 This can also be a list with cons cells of regular expressions that
1933 are matched against file names, and values."
1934 :group 'org-remember
1935 :group 'org-capture
1936 :group 'org-refile
1937 :type '(choice
1938 (const :tag "Reverse always" t)
1939 (const :tag "Reverse never" nil)
1940 (repeat :tag "By file name regexp"
1941 (cons regexp boolean))))
1943 (defcustom org-log-refile nil
1944 "Information to record when a task is refiled.
1946 Possible values are:
1948 nil Don't add anything
1949 time Add a time stamp to the task
1950 note Prompt for a note and add it with template `org-log-note-headings'
1952 This option can also be set with on a per-file-basis with
1954 #+STARTUP: nologrefile
1955 #+STARTUP: logrefile
1956 #+STARTUP: lognoterefile
1958 You can have local logging settings for a subtree by setting the LOGGING
1959 property to one or more of these keywords.
1961 When bulk-refiling from the agenda, the value `note' is forbidden and
1962 will temporarily be changed to `time'."
1963 :group 'org-refile
1964 :group 'org-progress
1965 :version "24.1"
1966 :type '(choice
1967 (const :tag "No logging" nil)
1968 (const :tag "Record timestamp" time)
1969 (const :tag "Record timestamp with note." note)))
1971 (defcustom org-refile-targets nil
1972 "Targets for refiling entries with \\[org-refile].
1973 This is a list of cons cells. Each cell contains:
1974 - a specification of the files to be considered, either a list of files,
1975 or a symbol whose function or variable value will be used to retrieve
1976 a file name or a list of file names. If you use `org-agenda-files' for
1977 that, all agenda files will be scanned for targets. Nil means consider
1978 headings in the current buffer.
1979 - A specification of how to find candidate refile targets. This may be
1980 any of:
1981 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1982 This tag has to be present in all target headlines, inheritance will
1983 not be considered.
1984 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1985 todo keyword.
1986 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1987 headlines that are refiling targets.
1988 - a cons cell (:level . N). Any headline of level N is considered a target.
1989 Note that, when `org-odd-levels-only' is set, level corresponds to
1990 order in hierarchy, not to the number of stars.
1991 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1992 Note that, when `org-odd-levels-only' is set, level corresponds to
1993 order in hierarchy, not to the number of stars.
1995 Each element of this list generates a set of possible targets.
1996 The union of these sets is presented (with completion) to
1997 the user by `org-refile'.
1999 You can set the variable `org-refile-target-verify-function' to a function
2000 to verify each headline found by the simple criteria above.
2002 When this variable is nil, all top-level headlines in the current buffer
2003 are used, equivalent to the value `((nil . (:level . 1))'."
2004 :group 'org-refile
2005 :type '(repeat
2006 (cons
2007 (choice :value org-agenda-files
2008 (const :tag "All agenda files" org-agenda-files)
2009 (const :tag "Current buffer" nil)
2010 (function) (variable) (file))
2011 (choice :tag "Identify target headline by"
2012 (cons :tag "Specific tag" (const :value :tag) (string))
2013 (cons :tag "TODO keyword" (const :value :todo) (string))
2014 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2015 (cons :tag "Level number" (const :value :level) (integer))
2016 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2018 (defcustom org-refile-target-verify-function nil
2019 "Function to verify if the headline at point should be a refile target.
2020 The function will be called without arguments, with point at the
2021 beginning of the headline. It should return t and leave point
2022 where it is if the headline is a valid target for refiling.
2024 If the target should not be selected, the function must return nil.
2025 In addition to this, it may move point to a place from where the search
2026 should be continued. For example, the function may decide that the entire
2027 subtree of the current entry should be excluded and move point to the end
2028 of the subtree."
2029 :group 'org-refile
2030 :type 'function)
2032 (defcustom org-refile-use-cache nil
2033 "Non-nil means cache refile targets to speed up the process.
2034 The cache for a particular file will be updated automatically when
2035 the buffer has been killed, or when any of the marker used for flagging
2036 refile targets no longer points at a live buffer.
2037 If you have added new entries to a buffer that might themselves be targets,
2038 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2039 find that easier, `C-u C-u C-u C-c C-w'."
2040 :group 'org-refile
2041 :version "24.1"
2042 :type 'boolean)
2044 (defcustom org-refile-use-outline-path nil
2045 "Non-nil means provide refile targets as paths.
2046 So a level 3 headline will be available as level1/level2/level3.
2048 When the value is `file', also include the file name (without directory)
2049 into the path. In this case, you can also stop the completion after
2050 the file name, to get entries inserted as top level in the file.
2052 When `full-file-path', include the full file path."
2053 :group 'org-refile
2054 :type '(choice
2055 (const :tag "Not" nil)
2056 (const :tag "Yes" t)
2057 (const :tag "Start with file name" file)
2058 (const :tag "Start with full file path" full-file-path)))
2060 (defcustom org-outline-path-complete-in-steps t
2061 "Non-nil means complete the outline path in hierarchical steps.
2062 When Org-mode uses the refile interface to select an outline path
2063 \(see variable `org-refile-use-outline-path'), the completion of
2064 the path can be done is a single go, or if can be done in steps down
2065 the headline hierarchy. Going in steps is probably the best if you
2066 do not use a special completion package like `ido' or `icicles'.
2067 However, when using these packages, going in one step can be very
2068 fast, while still showing the whole path to the entry."
2069 :group 'org-refile
2070 :type 'boolean)
2072 (defcustom org-refile-allow-creating-parent-nodes nil
2073 "Non-nil means allow to create new nodes as refile targets.
2074 New nodes are then created by adding \"/new node name\" to the completion
2075 of an existing node. When the value of this variable is `confirm',
2076 new node creation must be confirmed by the user (recommended)
2077 When nil, the completion must match an existing entry.
2079 Note that, if the new heading is not seen by the criteria
2080 listed in `org-refile-targets', multiple instances of the same
2081 heading would be created by trying again to file under the new
2082 heading."
2083 :group 'org-refile
2084 :type '(choice
2085 (const :tag "Never" nil)
2086 (const :tag "Always" t)
2087 (const :tag "Prompt for confirmation" confirm)))
2089 (defcustom org-refile-active-region-within-subtree nil
2090 "Non-nil means also refile active region within a subtree.
2092 By default `org-refile' doesn't allow refiling regions if they
2093 don't contain a set of subtrees, but it might be convenient to
2094 do so sometimes: in that case, the first line of the region is
2095 converted to a headline before refiling."
2096 :group 'org-refile
2097 :version "24.1"
2098 :type 'boolean)
2100 (defgroup org-todo nil
2101 "Options concerning TODO items in Org-mode."
2102 :tag "Org TODO"
2103 :group 'org)
2105 (defgroup org-progress nil
2106 "Options concerning Progress logging in Org-mode."
2107 :tag "Org Progress"
2108 :group 'org-time)
2110 (defvar org-todo-interpretation-widgets
2111 '((:tag "Sequence (cycling hits every state)" sequence)
2112 (:tag "Type (cycling directly to DONE)" type))
2113 "The available interpretation symbols for customizing `org-todo-keywords'.
2114 Interested libraries should add to this list.")
2116 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2117 "List of TODO entry keyword sequences and their interpretation.
2118 \\<org-mode-map>This is a list of sequences.
2120 Each sequence starts with a symbol, either `sequence' or `type',
2121 indicating if the keywords should be interpreted as a sequence of
2122 action steps, or as different types of TODO items. The first
2123 keywords are states requiring action - these states will select a headline
2124 for inclusion into the global TODO list Org-mode produces. If one of
2125 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2126 signify that no further action is necessary. If \"|\" is not found,
2127 the last keyword is treated as the only DONE state of the sequence.
2129 The command \\[org-todo] cycles an entry through these states, and one
2130 additional state where no keyword is present. For details about this
2131 cycling, see the manual.
2133 TODO keywords and interpretation can also be set on a per-file basis with
2134 the special #+SEQ_TODO and #+TYP_TODO lines.
2136 Each keyword can optionally specify a character for fast state selection
2137 \(in combination with the variable `org-use-fast-todo-selection')
2138 and specifiers for state change logging, using the same syntax that
2139 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2140 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2141 indicates to record a time stamp each time this state is selected.
2143 Each keyword may also specify if a timestamp or a note should be
2144 recorded when entering or leaving the state, by adding additional
2145 characters in the parenthesis after the keyword. This looks like this:
2146 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2147 record only the time of the state change. With X and Y being either
2148 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2149 Y when leaving the state if and only if the *target* state does not
2150 define X. You may omit any of the fast-selection key or X or /Y,
2151 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2153 For backward compatibility, this variable may also be just a list
2154 of keywords. In this case the interpretation (sequence or type) will be
2155 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2156 :group 'org-todo
2157 :group 'org-keywords
2158 :type '(choice
2159 (repeat :tag "Old syntax, just keywords"
2160 (string :tag "Keyword"))
2161 (repeat :tag "New syntax"
2162 (cons
2163 (choice
2164 :tag "Interpretation"
2165 ;;Quick and dirty way to see
2166 ;;`org-todo-interpretations'. This takes the
2167 ;;place of item arguments
2168 :convert-widget
2169 (lambda (widget)
2170 (widget-put widget
2171 :args (mapcar
2172 #'(lambda (x)
2173 (widget-convert
2174 (cons 'const x)))
2175 org-todo-interpretation-widgets))
2176 widget))
2177 (repeat
2178 (string :tag "Keyword"))))))
2180 (defvar org-todo-keywords-1 nil
2181 "All TODO and DONE keywords active in a buffer.")
2182 (make-variable-buffer-local 'org-todo-keywords-1)
2183 (defvar org-todo-keywords-for-agenda nil)
2184 (defvar org-done-keywords-for-agenda nil)
2185 (defvar org-drawers-for-agenda nil)
2186 (defvar org-todo-keyword-alist-for-agenda nil)
2187 (defvar org-tag-alist-for-agenda nil)
2188 (defvar org-agenda-contributing-files nil)
2189 (defvar org-not-done-keywords nil)
2190 (make-variable-buffer-local 'org-not-done-keywords)
2191 (defvar org-done-keywords nil)
2192 (make-variable-buffer-local 'org-done-keywords)
2193 (defvar org-todo-heads nil)
2194 (make-variable-buffer-local 'org-todo-heads)
2195 (defvar org-todo-sets nil)
2196 (make-variable-buffer-local 'org-todo-sets)
2197 (defvar org-todo-log-states nil)
2198 (make-variable-buffer-local 'org-todo-log-states)
2199 (defvar org-todo-kwd-alist nil)
2200 (make-variable-buffer-local 'org-todo-kwd-alist)
2201 (defvar org-todo-key-alist nil)
2202 (make-variable-buffer-local 'org-todo-key-alist)
2203 (defvar org-todo-key-trigger nil)
2204 (make-variable-buffer-local 'org-todo-key-trigger)
2206 (defcustom org-todo-interpretation 'sequence
2207 "Controls how TODO keywords are interpreted.
2208 This variable is in principle obsolete and is only used for
2209 backward compatibility, if the interpretation of todo keywords is
2210 not given already in `org-todo-keywords'. See that variable for
2211 more information."
2212 :group 'org-todo
2213 :group 'org-keywords
2214 :type '(choice (const sequence)
2215 (const type)))
2217 (defcustom org-use-fast-todo-selection t
2218 "Non-nil means use the fast todo selection scheme with C-c C-t.
2219 This variable describes if and under what circumstances the cycling
2220 mechanism for TODO keywords will be replaced by a single-key, direct
2221 selection scheme.
2223 When nil, fast selection is never used.
2225 When the symbol `prefix', it will be used when `org-todo' is called
2226 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2227 `C-u t' in an agenda buffer.
2229 When t, fast selection is used by default. In this case, the prefix
2230 argument forces cycling instead.
2232 In all cases, the special interface is only used if access keys have
2233 actually been assigned by the user, i.e. if keywords in the configuration
2234 are followed by a letter in parenthesis, like TODO(t)."
2235 :group 'org-todo
2236 :type '(choice
2237 (const :tag "Never" nil)
2238 (const :tag "By default" t)
2239 (const :tag "Only with C-u C-c C-t" prefix)))
2241 (defcustom org-provide-todo-statistics t
2242 "Non-nil means update todo statistics after insert and toggle.
2243 ALL-HEADLINES means update todo statistics by including headlines
2244 with no TODO keyword as well, counting them as not done.
2245 A list of TODO keywords means the same, but skip keywords that are
2246 not in this list.
2248 When this is set, todo statistics is updated in the parent of the
2249 current entry each time a todo state is changed."
2250 :group 'org-todo
2251 :type '(choice
2252 (const :tag "Yes, only for TODO entries" t)
2253 (const :tag "Yes, including all entries" 'all-headlines)
2254 (repeat :tag "Yes, for TODOs in this list"
2255 (string :tag "TODO keyword"))
2256 (other :tag "No TODO statistics" nil)))
2258 (defcustom org-hierarchical-todo-statistics t
2259 "Non-nil means TODO statistics covers just direct children.
2260 When nil, all entries in the subtree are considered.
2261 This has only an effect if `org-provide-todo-statistics' is set.
2262 To set this to nil for only a single subtree, use a COOKIE_DATA
2263 property and include the word \"recursive\" into the value."
2264 :group 'org-todo
2265 :type 'boolean)
2267 (defcustom org-after-todo-state-change-hook nil
2268 "Hook which is run after the state of a TODO item was changed.
2269 The new state (a string with a TODO keyword, or nil) is available in the
2270 Lisp variable `org-state'."
2271 :group 'org-todo
2272 :type 'hook)
2274 (defvar org-blocker-hook nil
2275 "Hook for functions that are allowed to block a state change.
2277 Functions in this hook should not modify the buffer.
2278 Each function gets as its single argument a property list,
2279 see `org-trigger-hook' for more information about this list.
2281 If any of the functions in this hook returns nil, the state change
2282 is blocked.")
2284 (defvar org-trigger-hook nil
2285 "Hook for functions that are triggered by a state change.
2287 Each function gets as its single argument a property list with at
2288 least the following elements:
2290 (:type type-of-change :position pos-at-entry-start
2291 :from old-state :to new-state)
2293 Depending on the type, more properties may be present.
2295 This mechanism is currently implemented for:
2297 TODO state changes
2298 ------------------
2299 :type todo-state-change
2300 :from previous state (keyword as a string), or nil, or a symbol
2301 'todo' or 'done', to indicate the general type of state.
2302 :to new state, like in :from")
2304 (defcustom org-enforce-todo-dependencies nil
2305 "Non-nil means undone TODO entries will block switching the parent to DONE.
2306 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2307 be blocked if any prior sibling is not yet done.
2308 Finally, if the parent is blocked because of ordered siblings of its own,
2309 the child will also be blocked."
2310 :set (lambda (var val)
2311 (set var val)
2312 (if val
2313 (add-hook 'org-blocker-hook
2314 'org-block-todo-from-children-or-siblings-or-parent)
2315 (remove-hook 'org-blocker-hook
2316 'org-block-todo-from-children-or-siblings-or-parent)))
2317 :group 'org-todo
2318 :type 'boolean)
2320 (defcustom org-enforce-todo-checkbox-dependencies nil
2321 "Non-nil means unchecked boxes will block switching the parent to DONE.
2322 When this is nil, checkboxes have no influence on switching TODO states.
2323 When non-nil, you first need to check off all check boxes before the TODO
2324 entry can be switched to DONE.
2325 This variable needs to be set before org.el is loaded, and you need to
2326 restart Emacs after a change to make the change effective. The only way
2327 to change is while Emacs is running is through the customize interface."
2328 :set (lambda (var val)
2329 (set var val)
2330 (if val
2331 (add-hook 'org-blocker-hook
2332 'org-block-todo-from-checkboxes)
2333 (remove-hook 'org-blocker-hook
2334 'org-block-todo-from-checkboxes)))
2335 :group 'org-todo
2336 :type 'boolean)
2338 (defcustom org-treat-insert-todo-heading-as-state-change nil
2339 "Non-nil means inserting a TODO heading is treated as state change.
2340 So when the command \\[org-insert-todo-heading] is used, state change
2341 logging will apply if appropriate. When nil, the new TODO item will
2342 be inserted directly, and no logging will take place."
2343 :group 'org-todo
2344 :type 'boolean)
2346 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2347 "Non-nil means switching TODO states with S-cursor counts as state change.
2348 This is the default behavior. However, setting this to nil allows a
2349 convenient way to select a TODO state and bypass any logging associated
2350 with that."
2351 :group 'org-todo
2352 :type 'boolean)
2354 (defcustom org-todo-state-tags-triggers nil
2355 "Tag changes that should be triggered by TODO state changes.
2356 This is a list. Each entry is
2358 (state-change (tag . flag) .......)
2360 State-change can be a string with a state, and empty string to indicate the
2361 state that has no TODO keyword, or it can be one of the symbols `todo'
2362 or `done', meaning any not-done or done state, respectively."
2363 :group 'org-todo
2364 :group 'org-tags
2365 :type '(repeat
2366 (cons (choice :tag "When changing to"
2367 (const :tag "Not-done state" todo)
2368 (const :tag "Done state" done)
2369 (string :tag "State"))
2370 (repeat
2371 (cons :tag "Tag action"
2372 (string :tag "Tag")
2373 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2375 (defcustom org-log-done nil
2376 "Information to record when a task moves to the DONE state.
2378 Possible values are:
2380 nil Don't add anything, just change the keyword
2381 time Add a time stamp to the task
2382 note Prompt for a note and add it with template `org-log-note-headings'
2384 This option can also be set with on a per-file-basis with
2386 #+STARTUP: nologdone
2387 #+STARTUP: logdone
2388 #+STARTUP: lognotedone
2390 You can have local logging settings for a subtree by setting the LOGGING
2391 property to one or more of these keywords."
2392 :group 'org-todo
2393 :group 'org-progress
2394 :type '(choice
2395 (const :tag "No logging" nil)
2396 (const :tag "Record CLOSED timestamp" time)
2397 (const :tag "Record CLOSED timestamp with note." note)))
2399 ;; Normalize old uses of org-log-done.
2400 (cond
2401 ((eq org-log-done t) (setq org-log-done 'time))
2402 ((and (listp org-log-done) (memq 'done org-log-done))
2403 (setq org-log-done 'note)))
2405 (defcustom org-log-reschedule nil
2406 "Information to record when the scheduling date of a tasks is modified.
2408 Possible values are:
2410 nil Don't add anything, just change the date
2411 time Add a time stamp to the task
2412 note Prompt for a note and add it with template `org-log-note-headings'
2414 This option can also be set with on a per-file-basis with
2416 #+STARTUP: nologreschedule
2417 #+STARTUP: logreschedule
2418 #+STARTUP: lognotereschedule"
2419 :group 'org-todo
2420 :group 'org-progress
2421 :type '(choice
2422 (const :tag "No logging" nil)
2423 (const :tag "Record timestamp" time)
2424 (const :tag "Record timestamp with note." note)))
2426 (defcustom org-log-redeadline nil
2427 "Information to record when the deadline date of a tasks is modified.
2429 Possible values are:
2431 nil Don't add anything, just change the date
2432 time Add a time stamp to the task
2433 note Prompt for a note and add it with template `org-log-note-headings'
2435 This option can also be set with on a per-file-basis with
2437 #+STARTUP: nologredeadline
2438 #+STARTUP: logredeadline
2439 #+STARTUP: lognoteredeadline
2441 You can have local logging settings for a subtree by setting the LOGGING
2442 property to one or more of these keywords."
2443 :group 'org-todo
2444 :group 'org-progress
2445 :type '(choice
2446 (const :tag "No logging" nil)
2447 (const :tag "Record timestamp" time)
2448 (const :tag "Record timestamp with note." note)))
2450 (defcustom org-log-note-clock-out nil
2451 "Non-nil means record a note when clocking out of an item.
2452 This can also be configured on a per-file basis by adding one of
2453 the following lines anywhere in the buffer:
2455 #+STARTUP: lognoteclock-out
2456 #+STARTUP: nolognoteclock-out"
2457 :group 'org-todo
2458 :group 'org-progress
2459 :type 'boolean)
2461 (defcustom org-log-done-with-time t
2462 "Non-nil means the CLOSED time stamp will contain date and time.
2463 When nil, only the date will be recorded."
2464 :group 'org-progress
2465 :type 'boolean)
2467 (defcustom org-log-note-headings
2468 '((done . "CLOSING NOTE %t")
2469 (state . "State %-12s from %-12S %t")
2470 (note . "Note taken on %t")
2471 (reschedule . "Rescheduled from %S on %t")
2472 (delschedule . "Not scheduled, was %S on %t")
2473 (redeadline . "New deadline from %S on %t")
2474 (deldeadline . "Removed deadline, was %S on %t")
2475 (refile . "Refiled on %t")
2476 (clock-out . ""))
2477 "Headings for notes added to entries.
2478 The value is an alist, with the car being a symbol indicating the note
2479 context, and the cdr is the heading to be used. The heading may also be the
2480 empty string.
2481 %t in the heading will be replaced by a time stamp.
2482 %T will be an active time stamp instead the default inactive one
2483 %d will be replaced by a short-format time stamp.
2484 %D will be replaced by an active short-format time stamp.
2485 %s will be replaced by the new TODO state, in double quotes.
2486 %S will be replaced by the old TODO state, in double quotes.
2487 %u will be replaced by the user name.
2488 %U will be replaced by the full user name.
2490 In fact, it is not a good idea to change the `state' entry, because
2491 agenda log mode depends on the format of these entries."
2492 :group 'org-todo
2493 :group 'org-progress
2494 :type '(list :greedy t
2495 (cons (const :tag "Heading when closing an item" done) string)
2496 (cons (const :tag
2497 "Heading when changing todo state (todo sequence only)"
2498 state) string)
2499 (cons (const :tag "Heading when just taking a note" note) string)
2500 (cons (const :tag "Heading when clocking out" clock-out) string)
2501 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2502 (cons (const :tag "Heading when rescheduling" reschedule) string)
2503 (cons (const :tag "Heading when changing deadline" redeadline) string)
2504 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2505 (cons (const :tag "Heading when refiling" refile) string)))
2507 (unless (assq 'note org-log-note-headings)
2508 (push '(note . "%t") org-log-note-headings))
2510 (defcustom org-log-into-drawer nil
2511 "Non-nil means insert state change notes and time stamps into a drawer.
2512 When nil, state changes notes will be inserted after the headline and
2513 any scheduling and clock lines, but not inside a drawer.
2515 The value of this variable should be the name of the drawer to use.
2516 LOGBOOK is proposed as the default drawer for this purpose, you can
2517 also set this to a string to define the drawer of your choice.
2519 A value of t is also allowed, representing \"LOGBOOK\".
2521 A value of t or nil can also be set with on a per-file-basis with
2523 #+STARTUP: logdrawer
2524 #+STARTUP: nologdrawer
2526 If this variable is set, `org-log-state-notes-insert-after-drawers'
2527 will be ignored.
2529 You can set the property LOG_INTO_DRAWER to overrule this setting for
2530 a subtree."
2531 :group 'org-todo
2532 :group 'org-progress
2533 :type '(choice
2534 (const :tag "Not into a drawer" nil)
2535 (const :tag "LOGBOOK" t)
2536 (string :tag "Other")))
2538 (if (fboundp 'defvaralias)
2539 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2541 (defun org-log-into-drawer ()
2542 "Return the value of `org-log-into-drawer', but let properties overrule.
2543 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2544 used instead of the default value."
2545 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2546 (cond
2547 ((not p) org-log-into-drawer)
2548 ((equal p "nil") nil)
2549 ((equal p "t") "LOGBOOK")
2550 (t p))))
2552 (defcustom org-log-state-notes-insert-after-drawers nil
2553 "Non-nil means insert state change notes after any drawers in entry.
2554 Only the drawers that *immediately* follow the headline and the
2555 deadline/scheduled line are skipped.
2556 When nil, insert notes right after the heading and perhaps the line
2557 with deadline/scheduling if present.
2559 This variable will have no effect if `org-log-into-drawer' is
2560 set."
2561 :group 'org-todo
2562 :group 'org-progress
2563 :type 'boolean)
2565 (defcustom org-log-states-order-reversed t
2566 "Non-nil means the latest state note will be directly after heading.
2567 When nil, the state change notes will be ordered according to time.
2569 This option can also be set with on a per-file-basis with
2571 #+STARTUP: logstatesreversed
2572 #+STARTUP: nologstatesreversed"
2573 :group 'org-todo
2574 :group 'org-progress
2575 :type 'boolean)
2577 (defcustom org-todo-repeat-to-state nil
2578 "The TODO state to which a repeater should return the repeating task.
2579 By default this is the first task in a TODO sequence, or the previous state
2580 in a TODO_TYP set. But you can specify another task here.
2581 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2582 :group 'org-todo
2583 :version "24.1"
2584 :type '(choice (const :tag "Head of sequence" nil)
2585 (string :tag "Specific state")))
2587 (defcustom org-log-repeat 'time
2588 "Non-nil means record moving through the DONE state when triggering repeat.
2589 An auto-repeating task is immediately switched back to TODO when
2590 marked DONE. If you are not logging state changes (by adding \"@\"
2591 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2592 record a closing note, there will be no record of the task moving
2593 through DONE. This variable forces taking a note anyway.
2595 nil Don't force a record
2596 time Record a time stamp
2597 note Prompt for a note and add it with template `org-log-note-headings'
2599 This option can also be set with on a per-file-basis with
2601 #+STARTUP: nologrepeat
2602 #+STARTUP: logrepeat
2603 #+STARTUP: lognoterepeat
2605 You can have local logging settings for a subtree by setting the LOGGING
2606 property to one or more of these keywords."
2607 :group 'org-todo
2608 :group 'org-progress
2609 :type '(choice
2610 (const :tag "Don't force a record" nil)
2611 (const :tag "Force recording the DONE state" time)
2612 (const :tag "Force recording a note with the DONE state" note)))
2615 (defgroup org-priorities nil
2616 "Priorities in Org-mode."
2617 :tag "Org Priorities"
2618 :group 'org-todo)
2620 (defcustom org-enable-priority-commands t
2621 "Non-nil means priority commands are active.
2622 When nil, these commands will be disabled, so that you never accidentally
2623 set a priority."
2624 :group 'org-priorities
2625 :type 'boolean)
2627 (defcustom org-highest-priority ?A
2628 "The highest priority of TODO items. A character like ?A, ?B etc.
2629 Must have a smaller ASCII number than `org-lowest-priority'."
2630 :group 'org-priorities
2631 :type 'character)
2633 (defcustom org-lowest-priority ?C
2634 "The lowest priority of TODO items. A character like ?A, ?B etc.
2635 Must have a larger ASCII number than `org-highest-priority'."
2636 :group 'org-priorities
2637 :type 'character)
2639 (defcustom org-default-priority ?B
2640 "The default priority of TODO items.
2641 This is the priority an item gets if no explicit priority is given.
2642 When starting to cycle on an empty priority the first step in the cycle
2643 depends on `org-priority-start-cycle-with-default'. The resulting first
2644 step priority must not exceed the range from `org-highest-priority' to
2645 `org-lowest-priority' which means that `org-default-priority' has to be
2646 in this range exclusive or inclusive the range boundaries. Else the
2647 first step refuses to set the default and the second will fall back
2648 to (depending on the command used) the highest or lowest priority."
2649 :group 'org-priorities
2650 :type 'character)
2652 (defcustom org-priority-start-cycle-with-default t
2653 "Non-nil means start with default priority when starting to cycle.
2654 When this is nil, the first step in the cycle will be (depending on the
2655 command used) one higher or lower than the default priority.
2656 See also `org-default-priority'."
2657 :group 'org-priorities
2658 :type 'boolean)
2660 (defcustom org-get-priority-function nil
2661 "Function to extract the priority from a string.
2662 The string is normally the headline. If this is nil Org computes the
2663 priority from the priority cookie like [#A] in the headline. It returns
2664 an integer, increasing by 1000 for each priority level.
2665 The user can set a different function here, which should take a string
2666 as an argument and return the numeric priority."
2667 :group 'org-priorities
2668 :version "24.1"
2669 :type 'function)
2671 (defgroup org-time nil
2672 "Options concerning time stamps and deadlines in Org-mode."
2673 :tag "Org Time"
2674 :group 'org)
2676 (defcustom org-insert-labeled-timestamps-at-point nil
2677 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2678 When nil, these labeled time stamps are forces into the second line of an
2679 entry, just after the headline. When scheduling from the global TODO list,
2680 the time stamp will always be forced into the second line."
2681 :group 'org-time
2682 :type 'boolean)
2684 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2685 "Formats for `format-time-string' which are used for time stamps.
2686 It is not recommended to change this constant.")
2688 (defcustom org-time-stamp-rounding-minutes '(0 5)
2689 "Number of minutes to round time stamps to.
2690 These are two values, the first applies when first creating a time stamp.
2691 The second applies when changing it with the commands `S-up' and `S-down'.
2692 When changing the time stamp, this means that it will change in steps
2693 of N minutes, as given by the second value.
2695 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2696 numbers should be factors of 60, so for example 5, 10, 15.
2698 When this is larger than 1, you can still force an exact time stamp by using
2699 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2700 and by using a prefix arg to `S-up/down' to specify the exact number
2701 of minutes to shift."
2702 :group 'org-time
2703 :get #'(lambda (var) ; Make sure both elements are there
2704 (if (integerp (default-value var))
2705 (list (default-value var) 5)
2706 (default-value var)))
2707 :type '(list
2708 (integer :tag "when inserting times")
2709 (integer :tag "when modifying times")))
2711 ;; Normalize old customizations of this variable.
2712 (when (integerp org-time-stamp-rounding-minutes)
2713 (setq org-time-stamp-rounding-minutes
2714 (list org-time-stamp-rounding-minutes
2715 org-time-stamp-rounding-minutes)))
2717 (defcustom org-display-custom-times nil
2718 "Non-nil means overlay custom formats over all time stamps.
2719 The formats are defined through the variable `org-time-stamp-custom-formats'.
2720 To turn this on on a per-file basis, insert anywhere in the file:
2721 #+STARTUP: customtime"
2722 :group 'org-time
2723 :set 'set-default
2724 :type 'sexp)
2725 (make-variable-buffer-local 'org-display-custom-times)
2727 (defcustom org-time-stamp-custom-formats
2728 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2729 "Custom formats for time stamps. See `format-time-string' for the syntax.
2730 These are overlaid over the default ISO format if the variable
2731 `org-display-custom-times' is set. Time like %H:%M should be at the
2732 end of the second format. The custom formats are also honored by export
2733 commands, if custom time display is turned on at the time of export."
2734 :group 'org-time
2735 :type 'sexp)
2737 (defun org-time-stamp-format (&optional long inactive)
2738 "Get the right format for a time string."
2739 (let ((f (if long (cdr org-time-stamp-formats)
2740 (car org-time-stamp-formats))))
2741 (if inactive
2742 (concat "[" (substring f 1 -1) "]")
2743 f)))
2745 (defcustom org-time-clocksum-format
2746 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2747 "The format string used when creating CLOCKSUM lines.
2748 This is also used when Org mode generates a time duration.
2750 The value can be a single format string containing two
2751 %-sequences, which will be filled with the number of hours and
2752 minutes in that order.
2754 Alternatively, the value can be a plist associating any of the
2755 keys :years, :months, :weeks, :days, :hours or :minutes with
2756 format strings. The time duration is formatted using only the
2757 time components that are needed and concatenating the results.
2758 If a time unit in absent, it falls back to the next smallest
2759 unit.
2761 The keys :require-years, :require-months, :require-days,
2762 :require-weeks, :require-hours, :require-minutes are also
2763 meaningful. A non-nil value for these keys indicates that the
2764 corresponding time component should always be included, even if
2765 its value is 0.
2768 For example,
2770 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2771 :require-minutes t)
2773 means durations longer than a day will be expressed in days,
2774 hours and minutes, and durations less than a day will always be
2775 expressed in hours and minutes (even for durations less than an
2776 hour).
2778 The value
2780 \(:days \"%dd\" :minutes \"%dm\")
2782 means durations longer than a day will be expressed in days and
2783 minutes, and durations less than a day will be expressed entirely
2784 in minutes (even for durations longer than an hour)."
2785 :group 'org-time
2786 :group 'org-clock
2787 :version "24.3"
2788 :type '(choice (string :tag "Format string")
2789 (set :tag "Plist"
2790 (group :inline t (const :tag "Years" :years)
2791 (string :tag "Format string"))
2792 (group :inline t
2793 (const :tag "Always show years" :require-years)
2794 (const t))
2795 (group :inline t (const :tag "Months" :months)
2796 (string :tag "Format string"))
2797 (group :inline t
2798 (const :tag "Always show months" :require-months)
2799 (const t))
2800 (group :inline t (const :tag "Weeks" :weeks)
2801 (string :tag "Format string"))
2802 (group :inline t
2803 (const :tag "Always show weeks" :require-weeks)
2804 (const t))
2805 (group :inline t (const :tag "Days" :days)
2806 (string :tag "Format string"))
2807 (group :inline t
2808 (const :tag "Always show days" :require-days)
2809 (const t))
2810 (group :inline t (const :tag "Hours" :hours)
2811 (string :tag "Format string"))
2812 (group :inline t
2813 (const :tag "Always show hours" :require-hours)
2814 (const t))
2815 (group :inline t (const :tag "Minutes" :minutes)
2816 (string :tag "Format string"))
2817 (group :inline t
2818 (const :tag "Always show minutes" :require-minutes)
2819 (const t)))))
2821 (defcustom org-time-clocksum-use-fractional nil
2822 "When non-nil, \\[org-clock-display] uses fractional times.
2823 See `org-time-clocksum-format' for more on time clock formats."
2824 :group 'org-time
2825 :group 'org-clock
2826 :version "24.3"
2827 :type 'boolean)
2829 (defcustom org-time-clocksum-use-effort-durations t
2830 "When non-nil, \\[org-clock-display] uses effort durations.
2831 E.g. by default, one day is considered to be a 8 hours effort,
2832 so a task that has been clocked for 16 hours will be displayed
2833 as during 2 days in the clock display or in the clocktable.
2835 See `org-effort-durations' on how to set effort durations
2836 and `org-time-clocksum-format' for more on time clock formats."
2837 :group 'org-time
2838 :group 'org-clock
2839 :version "24.3"
2840 :type 'boolean)
2842 (defcustom org-time-clocksum-fractional-format "%.2f"
2843 "The format string used when creating CLOCKSUM lines,
2844 or when Org mode generates a time duration, if
2845 `org-time-clocksum-use-fractional' is enabled.
2847 The value can be a single format string containing one
2848 %-sequence, which will be filled with the number of hours as
2849 a float.
2851 Alternatively, the value can be a plist associating any of the
2852 keys :years, :months, :weeks, :days, :hours or :minutes with
2853 a format string. The time duration is formatted using the
2854 largest time unit which gives a non-zero integer part. If all
2855 specified formats have zero integer part, the smallest time unit
2856 is used."
2857 :group 'org-time
2858 :type '(choice (string :tag "Format string")
2859 (set (group :inline t (const :tag "Years" :years)
2860 (string :tag "Format string"))
2861 (group :inline t (const :tag "Months" :months)
2862 (string :tag "Format string"))
2863 (group :inline t (const :tag "Weeks" :weeks)
2864 (string :tag "Format string"))
2865 (group :inline t (const :tag "Days" :days)
2866 (string :tag "Format string"))
2867 (group :inline t (const :tag "Hours" :hours)
2868 (string :tag "Format string"))
2869 (group :inline t (const :tag "Minutes" :minutes)
2870 (string :tag "Format string")))))
2872 (defcustom org-deadline-warning-days 14
2873 "Number of days before expiration during which a deadline becomes active.
2874 This variable governs the display in sparse trees and in the agenda.
2875 When 0 or negative, it means use this number (the absolute value of it)
2876 even if a deadline has a different individual lead time specified.
2878 Custom commands can set this variable in the options section."
2879 :group 'org-time
2880 :group 'org-agenda-daily/weekly
2881 :type 'integer)
2883 (defcustom org-scheduled-delay-days 0
2884 "Number of days before a scheduled item becomes active.
2885 This variable governs the display in sparse trees and in the agenda.
2886 The default value (i.e. 0) means: don't delay scheduled item.
2887 When negative, it means use this number (the absolute value of it)
2888 even if a scheduled item has a different individual delay time
2889 specified.
2891 Custom commands can set this variable in the options section."
2892 :group 'org-time
2893 :group 'org-agenda-daily/weekly
2894 :version "24.3"
2895 :type 'integer)
2897 (defcustom org-read-date-prefer-future t
2898 "Non-nil means assume future for incomplete date input from user.
2899 This affects the following situations:
2900 1. The user gives a month but not a year.
2901 For example, if it is April and you enter \"feb 2\", this will be read
2902 as Feb 2, *next* year. \"May 5\", however, will be this year.
2903 2. The user gives a day, but no month.
2904 For example, if today is the 15th, and you enter \"3\", Org-mode will
2905 read this as the third of *next* month. However, if you enter \"17\",
2906 it will be considered as *this* month.
2908 If you set this variable to the symbol `time', then also the following
2909 will work:
2911 3. If the user gives a time.
2912 If the time is before now, it will be interpreted as tomorrow.
2914 Currently none of this works for ISO week specifications.
2916 When this option is nil, the current day, month and year will always be
2917 used as defaults.
2919 See also `org-agenda-jump-prefer-future'."
2920 :group 'org-time
2921 :type '(choice
2922 (const :tag "Never" nil)
2923 (const :tag "Check month and day" t)
2924 (const :tag "Check month, day, and time" time)))
2926 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2927 "Should the agenda jump command prefer the future for incomplete dates?
2928 The default is to do the same as configured in `org-read-date-prefer-future'.
2929 But you can also set a deviating value here.
2930 This may t or nil, or the symbol `org-read-date-prefer-future'."
2931 :group 'org-agenda
2932 :group 'org-time
2933 :version "24.1"
2934 :type '(choice
2935 (const :tag "Use org-read-date-prefer-future"
2936 org-read-date-prefer-future)
2937 (const :tag "Never" nil)
2938 (const :tag "Always" t)))
2940 (defcustom org-read-date-force-compatible-dates t
2941 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2943 Depending on the system Emacs is running on, certain dates cannot
2944 be represented with the type used internally to represent time.
2945 Dates between 1970-1-1 and 2038-1-1 can always be represented
2946 correctly. Some systems allow for earlier dates, some for later,
2947 some for both. One way to find out it to insert any date into an
2948 Org buffer, putting the cursor on the year and hitting S-up and
2949 S-down to test the range.
2951 When this variable is set to t, the date/time prompt will not let
2952 you specify dates outside the 1970-2037 range, so it is certain that
2953 these dates will work in whatever version of Emacs you are
2954 running, and also that you can move a file from one Emacs implementation
2955 to another. WHenever Org is forcing the year for you, it will display
2956 a message and beep.
2958 When this variable is nil, Org will check if the date is
2959 representable in the specific Emacs implementation you are using.
2960 If not, it will force a year, usually the current year, and beep
2961 to remind you. Currently this setting is not recommended because
2962 the likelihood that you will open your Org files in an Emacs that
2963 has limited date range is not negligible.
2965 A workaround for this problem is to use diary sexp dates for time
2966 stamps outside of this range."
2967 :group 'org-time
2968 :version "24.1"
2969 :type 'boolean)
2971 (defcustom org-read-date-display-live t
2972 "Non-nil means display current interpretation of date prompt live.
2973 This display will be in an overlay, in the minibuffer."
2974 :group 'org-time
2975 :type 'boolean)
2977 (defcustom org-read-date-popup-calendar t
2978 "Non-nil means pop up a calendar when prompting for a date.
2979 In the calendar, the date can be selected with mouse-1. However, the
2980 minibuffer will also be active, and you can simply enter the date as well.
2981 When nil, only the minibuffer will be available."
2982 :group 'org-time
2983 :type 'boolean)
2984 (if (fboundp 'defvaralias)
2985 (defvaralias 'org-popup-calendar-for-date-prompt
2986 'org-read-date-popup-calendar))
2988 (make-obsolete-variable
2989 'org-read-date-minibuffer-setup-hook
2990 "Set `org-read-date-minibuffer-local-map' instead." "24.3")
2991 (defcustom org-read-date-minibuffer-setup-hook nil
2992 "Hook to be used to set up keys for the date/time interface.
2993 Add key definitions to `minibuffer-local-map', which will be a
2994 temporary copy.
2996 WARNING: This option is obsolete, you should use
2997 `org-read-date-minibuffer-local-map' to set up keys."
2998 :group 'org-time
2999 :type 'hook)
3001 (defcustom org-extend-today-until 0
3002 "The hour when your day really ends. Must be an integer.
3003 This has influence for the following applications:
3004 - When switching the agenda to \"today\". It it is still earlier than
3005 the time given here, the day recognized as TODAY is actually yesterday.
3006 - When a date is read from the user and it is still before the time given
3007 here, the current date and time will be assumed to be yesterday, 23:59.
3008 Also, timestamps inserted in capture templates follow this rule.
3010 IMPORTANT: This is a feature whose implementation is and likely will
3011 remain incomplete. Really, it is only here because past midnight seems to
3012 be the favorite working time of John Wiegley :-)"
3013 :group 'org-time
3014 :type 'integer)
3016 (defcustom org-use-effective-time nil
3017 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3018 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3019 \"effective time\" of any timestamps between midnight and 8am will be
3020 23:59 of the previous day."
3021 :group 'org-time
3022 :version "24.1"
3023 :type 'boolean)
3025 (defcustom org-use-last-clock-out-time-as-effective-time nil
3026 "When non-nil, use the last clock out time for `org-todo'.
3027 Note that this option has precedence over the combined use of
3028 `org-use-effective-time' and `org-extend-today-until'."
3029 :group 'org-time
3030 ;; :version "24.3"
3031 :type 'boolean)
3033 (defcustom org-edit-timestamp-down-means-later nil
3034 "Non-nil means S-down will increase the time in a time stamp.
3035 When nil, S-up will increase."
3036 :group 'org-time
3037 :type 'boolean)
3039 (defcustom org-calendar-follow-timestamp-change t
3040 "Non-nil means make the calendar window follow timestamp changes.
3041 When a timestamp is modified and the calendar window is visible, it will be
3042 moved to the new date."
3043 :group 'org-time
3044 :type 'boolean)
3046 (defgroup org-tags nil
3047 "Options concerning tags in Org-mode."
3048 :tag "Org Tags"
3049 :group 'org)
3051 (defcustom org-tag-alist nil
3052 "List of tags allowed in Org-mode files.
3053 When this list is nil, Org-mode will base TAG input on what is already in the
3054 buffer.
3055 The value of this variable is an alist, the car of each entry must be a
3056 keyword as a string, the cdr may be a character that is used to select
3057 that tag through the fast-tag-selection interface.
3058 See the manual for details."
3059 :group 'org-tags
3060 :type '(repeat
3061 (choice
3062 (cons (string :tag "Tag name")
3063 (character :tag "Access char"))
3064 (list :tag "Start radio group"
3065 (const :startgroup)
3066 (option (string :tag "Group description")))
3067 (list :tag "End radio group"
3068 (const :endgroup)
3069 (option (string :tag "Group description")))
3070 (const :tag "New line" (:newline)))))
3072 (defcustom org-tag-persistent-alist nil
3073 "List of tags that will always appear in all Org-mode files.
3074 This is in addition to any in buffer settings or customizations
3075 of `org-tag-alist'.
3076 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3077 The value of this variable is an alist, the car of each entry must be a
3078 keyword as a string, the cdr may be a character that is used to select
3079 that tag through the fast-tag-selection interface.
3080 See the manual for details.
3081 To disable these tags on a per-file basis, insert anywhere in the file:
3082 #+STARTUP: noptag"
3083 :group 'org-tags
3084 :type '(repeat
3085 (choice
3086 (cons (string :tag "Tag name")
3087 (character :tag "Access char"))
3088 (const :tag "Start radio group" (:startgroup))
3089 (const :tag "End radio group" (:endgroup))
3090 (const :tag "New line" (:newline)))))
3092 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3093 "If non-nil, always offer completion for all tags of all agenda files.
3094 Instead of customizing this variable directly, you might want to
3095 set it locally for capture buffers, because there no list of
3096 tags in that file can be created dynamically (there are none).
3098 (add-hook 'org-capture-mode-hook
3099 (lambda ()
3100 (set (make-local-variable
3101 'org-complete-tags-always-offer-all-agenda-tags)
3102 t)))"
3103 :group 'org-tags
3104 :version "24.1"
3105 :type 'boolean)
3107 (defvar org-file-tags nil
3108 "List of tags that can be inherited by all entries in the file.
3109 The tags will be inherited if the variable `org-use-tag-inheritance'
3110 says they should be.
3111 This variable is populated from #+FILETAGS lines.")
3113 (defcustom org-use-fast-tag-selection 'auto
3114 "Non-nil means use fast tag selection scheme.
3115 This is a special interface to select and deselect tags with single keys.
3116 When nil, fast selection is never used.
3117 When the symbol `auto', fast selection is used if and only if selection
3118 characters for tags have been configured, either through the variable
3119 `org-tag-alist' or through a #+TAGS line in the buffer.
3120 When t, fast selection is always used and selection keys are assigned
3121 automatically if necessary."
3122 :group 'org-tags
3123 :type '(choice
3124 (const :tag "Always" t)
3125 (const :tag "Never" nil)
3126 (const :tag "When selection characters are configured" 'auto)))
3128 (defcustom org-fast-tag-selection-single-key nil
3129 "Non-nil means fast tag selection exits after first change.
3130 When nil, you have to press RET to exit it.
3131 During fast tag selection, you can toggle this flag with `C-c'.
3132 This variable can also have the value `expert'. In this case, the window
3133 displaying the tags menu is not even shown, until you press C-c again."
3134 :group 'org-tags
3135 :type '(choice
3136 (const :tag "No" nil)
3137 (const :tag "Yes" t)
3138 (const :tag "Expert" expert)))
3140 (defvar org-fast-tag-selection-include-todo nil
3141 "Non-nil means fast tags selection interface will also offer TODO states.
3142 This is an undocumented feature, you should not rely on it.")
3144 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3145 "The column to which tags should be indented in a headline.
3146 If this number is positive, it specifies the column. If it is negative,
3147 it means that the tags should be flushright to that column. For example,
3148 -80 works well for a normal 80 character screen.
3149 When 0, place tags directly after headline text, with only one space in
3150 between."
3151 :group 'org-tags
3152 :type 'integer)
3154 (defcustom org-auto-align-tags t
3155 "Non-nil keeps tags aligned when modifying headlines.
3156 Some operations (i.e. demoting) change the length of a headline and
3157 therefore shift the tags around. With this option turned on, after
3158 each such operation the tags are again aligned to `org-tags-column'."
3159 :group 'org-tags
3160 :type 'boolean)
3162 (defcustom org-use-tag-inheritance t
3163 "Non-nil means tags in levels apply also for sublevels.
3164 When nil, only the tags directly given in a specific line apply there.
3165 This may also be a list of tags that should be inherited, or a regexp that
3166 matches tags that should be inherited. Additional control is possible
3167 with the variable `org-tags-exclude-from-inheritance' which gives an
3168 explicit list of tags to be excluded from inheritance, even if the value of
3169 `org-use-tag-inheritance' would select it for inheritance.
3171 If this option is t, a match early-on in a tree can lead to a large
3172 number of matches in the subtree when constructing the agenda or creating
3173 a sparse tree. If you only want to see the first match in a tree during
3174 a search, check out the variable `org-tags-match-list-sublevels'."
3175 :group 'org-tags
3176 :type '(choice
3177 (const :tag "Not" nil)
3178 (const :tag "Always" t)
3179 (repeat :tag "Specific tags" (string :tag "Tag"))
3180 (regexp :tag "Tags matched by regexp")))
3182 (defcustom org-tags-exclude-from-inheritance nil
3183 "List of tags that should never be inherited.
3184 This is a way to exclude a few tags from inheritance. For way to do
3185 the opposite, to actively allow inheritance for selected tags,
3186 see the variable `org-use-tag-inheritance'."
3187 :group 'org-tags
3188 :type '(repeat (string :tag "Tag")))
3190 (defun org-tag-inherit-p (tag)
3191 "Check if TAG is one that should be inherited."
3192 (cond
3193 ((member tag org-tags-exclude-from-inheritance) nil)
3194 ((eq org-use-tag-inheritance t) t)
3195 ((not org-use-tag-inheritance) nil)
3196 ((stringp org-use-tag-inheritance)
3197 (string-match org-use-tag-inheritance tag))
3198 ((listp org-use-tag-inheritance)
3199 (member tag org-use-tag-inheritance))
3200 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3202 (defcustom org-tags-match-list-sublevels t
3203 "Non-nil means list also sublevels of headlines matching a search.
3204 This variable applies to tags/property searches, and also to stuck
3205 projects because this search is based on a tags match as well.
3207 When set to the symbol `indented', sublevels are indented with
3208 leading dots.
3210 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3211 the sublevels of a headline matching a tag search often also match
3212 the same search. Listing all of them can create very long lists.
3213 Setting this variable to nil causes subtrees of a match to be skipped.
3215 This variable is semi-obsolete and probably should always be true. It
3216 is better to limit inheritance to certain tags using the variables
3217 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3218 :group 'org-tags
3219 :type '(choice
3220 (const :tag "No, don't list them" nil)
3221 (const :tag "Yes, do list them" t)
3222 (const :tag "List them, indented with leading dots" indented)))
3224 (defcustom org-tags-sort-function nil
3225 "When set, tags are sorted using this function as a comparator."
3226 :group 'org-tags
3227 :type '(choice
3228 (const :tag "No sorting" nil)
3229 (const :tag "Alphabetical" string<)
3230 (const :tag "Reverse alphabetical" string>)
3231 (function :tag "Custom function" nil)))
3233 (defvar org-tags-history nil
3234 "History of minibuffer reads for tags.")
3235 (defvar org-last-tags-completion-table nil
3236 "The last used completion table for tags.")
3237 (defvar org-after-tags-change-hook nil
3238 "Hook that is run after the tags in a line have changed.")
3240 (defgroup org-properties nil
3241 "Options concerning properties in Org-mode."
3242 :tag "Org Properties"
3243 :group 'org)
3245 (defcustom org-property-format "%-10s %s"
3246 "How property key/value pairs should be formatted by `indent-line'.
3247 When `indent-line' hits a property definition, it will format the line
3248 according to this format, mainly to make sure that the values are
3249 lined-up with respect to each other."
3250 :group 'org-properties
3251 :type 'string)
3253 (defcustom org-properties-postprocess-alist nil
3254 "Alist of properties and functions to adjust inserted values.
3255 Elements of this alist must be of the form
3257 ([string] [function])
3259 where [string] must be a property name and [function] must be a
3260 lambda expression: this lambda expression must take one argument,
3261 the value to adjust, and return the new value as a string.
3263 For example, this element will allow the property \"Remaining\"
3264 to be updated wrt the relation between the \"Effort\" property
3265 and the clock summary:
3267 ((\"Remaining\" (lambda(value)
3268 (let ((clocksum (org-clock-sum-current-item))
3269 (effort (org-duration-string-to-minutes
3270 (org-entry-get (point) \"Effort\"))))
3271 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3272 :group 'org-properties
3273 :version "24.1"
3274 :type '(alist :key-type (string :tag "Property")
3275 :value-type (function :tag "Function")))
3277 (defcustom org-use-property-inheritance nil
3278 "Non-nil means properties apply also for sublevels.
3280 This setting is chiefly used during property searches. Turning it on can
3281 cause significant overhead when doing a search, which is why it is not
3282 on by default.
3284 When nil, only the properties directly given in the current entry count.
3285 When t, every property is inherited. The value may also be a list of
3286 properties that should have inheritance, or a regular expression matching
3287 properties that should be inherited.
3289 However, note that some special properties use inheritance under special
3290 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3291 and the properties ending in \"_ALL\" when they are used as descriptor
3292 for valid values of a property.
3294 Note for programmers:
3295 When querying an entry with `org-entry-get', you can control if inheritance
3296 should be used. By default, `org-entry-get' looks only at the local
3297 properties. You can request inheritance by setting the inherit argument
3298 to t (to force inheritance) or to `selective' (to respect the setting
3299 in this variable)."
3300 :group 'org-properties
3301 :type '(choice
3302 (const :tag "Not" nil)
3303 (const :tag "Always" t)
3304 (repeat :tag "Specific properties" (string :tag "Property"))
3305 (regexp :tag "Properties matched by regexp")))
3307 (defun org-property-inherit-p (property)
3308 "Check if PROPERTY is one that should be inherited."
3309 (cond
3310 ((eq org-use-property-inheritance t) t)
3311 ((not org-use-property-inheritance) nil)
3312 ((stringp org-use-property-inheritance)
3313 (string-match org-use-property-inheritance property))
3314 ((listp org-use-property-inheritance)
3315 (member property org-use-property-inheritance))
3316 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3318 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3319 "The default column format, if no other format has been defined.
3320 This variable can be set on the per-file basis by inserting a line
3322 #+COLUMNS: %25ITEM ....."
3323 :group 'org-properties
3324 :type 'string)
3326 (defcustom org-columns-ellipses ".."
3327 "The ellipses to be used when a field in column view is truncated.
3328 When this is the empty string, as many characters as possible are shown,
3329 but then there will be no visual indication that the field has been truncated.
3330 When this is a string of length N, the last N characters of a truncated
3331 field are replaced by this string. If the column is narrower than the
3332 ellipses string, only part of the ellipses string will be shown."
3333 :group 'org-properties
3334 :type 'string)
3336 (defcustom org-columns-modify-value-for-display-function nil
3337 "Function that modifies values for display in column view.
3338 For example, it can be used to cut out a certain part from a time stamp.
3339 The function must take 2 arguments:
3341 column-title The title of the column (*not* the property name)
3342 value The value that should be modified.
3344 The function should return the value that should be displayed,
3345 or nil if the normal value should be used."
3346 :group 'org-properties
3347 :type 'function)
3349 (defcustom org-effort-property "Effort"
3350 "The property that is being used to keep track of effort estimates.
3351 Effort estimates given in this property need to have the format H:MM."
3352 :group 'org-properties
3353 :group 'org-progress
3354 :type '(string :tag "Property"))
3356 (defconst org-global-properties-fixed
3357 '(("VISIBILITY_ALL" . "folded children content all")
3358 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3359 "List of property/value pairs that can be inherited by any entry.
3361 These are fixed values, for the preset properties. The user variable
3362 that can be used to add to this list is `org-global-properties'.
3364 The entries in this list are cons cells where the car is a property
3365 name and cdr is a string with the value. If the value represents
3366 multiple items like an \"_ALL\" property, separate the items by
3367 spaces.")
3369 (defcustom org-global-properties nil
3370 "List of property/value pairs that can be inherited by any entry.
3372 This list will be combined with the constant `org-global-properties-fixed'.
3374 The entries in this list are cons cells where the car is a property
3375 name and cdr is a string with the value.
3377 You can set buffer-local values for the same purpose in the variable
3378 `org-file-properties' this by adding lines like
3380 #+PROPERTY: NAME VALUE"
3381 :group 'org-properties
3382 :type '(repeat
3383 (cons (string :tag "Property")
3384 (string :tag "Value"))))
3386 (defvar org-file-properties nil
3387 "List of property/value pairs that can be inherited by any entry.
3388 Valid for the current buffer.
3389 This variable is populated from #+PROPERTY lines.")
3390 (make-variable-buffer-local 'org-file-properties)
3392 (defgroup org-agenda nil
3393 "Options concerning agenda views in Org-mode."
3394 :tag "Org Agenda"
3395 :group 'org)
3397 (defvar org-category nil
3398 "Variable used by org files to set a category for agenda display.
3399 Such files should use a file variable to set it, for example
3401 # -*- mode: org; org-category: \"ELisp\"
3403 or contain a special line
3405 #+CATEGORY: ELisp
3407 If the file does not specify a category, then file's base name
3408 is used instead.")
3409 (make-variable-buffer-local 'org-category)
3410 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3412 (defcustom org-agenda-files nil
3413 "The files to be used for agenda display.
3414 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3415 \\[org-remove-file]. You can also use customize to edit the list.
3417 If an entry is a directory, all files in that directory that are matched by
3418 `org-agenda-file-regexp' will be part of the file list.
3420 If the value of the variable is not a list but a single file name, then
3421 the list of agenda files is actually stored and maintained in that file, one
3422 agenda file per line. In this file paths can be given relative to
3423 `org-directory'. Tilde expansion and environment variable substitution
3424 are also made."
3425 :group 'org-agenda
3426 :type '(choice
3427 (repeat :tag "List of files and directories" file)
3428 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3430 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3431 "Regular expression to match files for `org-agenda-files'.
3432 If any element in the list in that variable contains a directory instead
3433 of a normal file, all files in that directory that are matched by this
3434 regular expression will be included."
3435 :group 'org-agenda
3436 :type 'regexp)
3438 (defcustom org-agenda-text-search-extra-files nil
3439 "List of extra files to be searched by text search commands.
3440 These files will be search in addition to the agenda files by the
3441 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3442 Note that these files will only be searched for text search commands,
3443 not for the other agenda views like todo lists, tag searches or the weekly
3444 agenda. This variable is intended to list notes and possibly archive files
3445 that should also be searched by these two commands.
3446 In fact, if the first element in the list is the symbol `agenda-archives',
3447 than all archive files of all agenda files will be added to the search
3448 scope."
3449 :group 'org-agenda
3450 :type '(set :greedy t
3451 (const :tag "Agenda Archives" agenda-archives)
3452 (repeat :inline t (file))))
3454 (if (fboundp 'defvaralias)
3455 (defvaralias 'org-agenda-multi-occur-extra-files
3456 'org-agenda-text-search-extra-files))
3458 (defcustom org-agenda-skip-unavailable-files nil
3459 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3460 A nil value means to remove them, after a query, from the list."
3461 :group 'org-agenda
3462 :type 'boolean)
3464 (defcustom org-calendar-to-agenda-key [?c]
3465 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3466 The command `org-calendar-goto-agenda' will be bound to this key. The
3467 default is the character `c' because then `c' can be used to switch back and
3468 forth between agenda and calendar."
3469 :group 'org-agenda
3470 :type 'sexp)
3472 (defcustom org-calendar-insert-diary-entry-key [?i]
3473 "The key to be installed in `calendar-mode-map' for adding diary entries.
3474 This option is irrelevant until `org-agenda-diary-file' has been configured
3475 to point to an Org-mode file. When that is the case, the command
3476 `org-agenda-diary-entry' will be bound to the key given here, by default
3477 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3478 if you want to continue doing this, you need to change this to a different
3479 key."
3480 :group 'org-agenda
3481 :type 'sexp)
3483 (defcustom org-agenda-diary-file 'diary-file
3484 "File to which to add new entries with the `i' key in agenda and calendar.
3485 When this is the symbol `diary-file', the functionality in the Emacs
3486 calendar will be used to add entries to the `diary-file'. But when this
3487 points to a file, `org-agenda-diary-entry' will be used instead."
3488 :group 'org-agenda
3489 :type '(choice
3490 (const :tag "The standard Emacs diary file" diary-file)
3491 (file :tag "Special Org file diary entries")))
3493 (eval-after-load "calendar"
3494 '(progn
3495 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3496 'org-calendar-goto-agenda)
3497 (add-hook 'calendar-mode-hook
3498 (lambda ()
3499 (unless (eq org-agenda-diary-file 'diary-file)
3500 (define-key calendar-mode-map
3501 org-calendar-insert-diary-entry-key
3502 'org-agenda-diary-entry))))))
3504 (defgroup org-latex nil
3505 "Options for embedding LaTeX code into Org-mode."
3506 :tag "Org LaTeX"
3507 :group 'org)
3509 (defcustom org-format-latex-options
3510 '(:foreground default :background default :scale 1.0
3511 :html-foreground "Black" :html-background "Transparent"
3512 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3513 "Options for creating images from LaTeX fragments.
3514 This is a property list with the following properties:
3515 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3516 `default' means use the foreground of the default face.
3517 `auto' means use the foreground from the text face.
3518 :background the background color, or \"Transparent\".
3519 `default' means use the background of the default face.
3520 `auto' means use the background from the text face.
3521 :scale a scaling factor for the size of the images, to get more pixels
3522 :html-foreground, :html-background, :html-scale
3523 the same numbers for HTML export.
3524 :matchers a list indicating which matchers should be used to
3525 find LaTeX fragments. Valid members of this list are:
3526 \"begin\" find environments
3527 \"$1\" find single characters surrounded by $.$
3528 \"$\" find math expressions surrounded by $...$
3529 \"$$\" find math expressions surrounded by $$....$$
3530 \"\\(\" find math expressions surrounded by \\(...\\)
3531 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3532 :group 'org-latex
3533 :type 'plist)
3535 (defcustom org-format-latex-signal-error t
3536 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3537 When nil, just push out a message."
3538 :group 'org-latex
3539 :version "24.1"
3540 :type 'boolean)
3542 (defcustom org-latex-to-mathml-jar-file nil
3543 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3544 Use this to specify additional executable file say a jar file.
3546 When using MathToWeb as the converter, specify the full-path to
3547 your mathtoweb.jar file."
3548 :group 'org-latex
3549 :version "24.1"
3550 :type '(choice
3551 (const :tag "None" nil)
3552 (file :tag "JAR file" :must-match t)))
3554 (defcustom org-latex-to-mathml-convert-command nil
3555 "Command to convert LaTeX fragments to MathML.
3556 Replace format-specifiers in the command as noted below and use
3557 `shell-command' to convert LaTeX to MathML.
3558 %j: Executable file in fully expanded form as specified by
3559 `org-latex-to-mathml-jar-file'.
3560 %I: Input LaTeX file in fully expanded form
3561 %o: Output MathML file
3562 This command is used by `org-create-math-formula'.
3564 When using MathToWeb as the converter, set this to
3565 \"java -jar %j -unicode -force -df %o %I\"."
3566 :group 'org-latex
3567 :version "24.1"
3568 :type '(choice
3569 (const :tag "None" nil)
3570 (string :tag "\nShell command")))
3572 (defcustom org-latex-create-formula-image-program 'dvipng
3573 "Program to convert LaTeX fragments with.
3575 dvipng Process the LaTeX fragments to dvi file, then convert
3576 dvi files to png files using dvipng.
3577 This will also include processing of non-math environments.
3578 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3579 to convert pdf files to png files"
3580 :group 'org-latex
3581 :version "24.1"
3582 :type '(choice
3583 (const :tag "dvipng" dvipng)
3584 (const :tag "imagemagick" imagemagick)))
3586 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3587 "Path to store latex preview images.
3588 A relative path here creates many directories relative to the
3589 processed org files paths. An absolute path puts all preview
3590 images at the same place."
3591 :group 'org-latex
3592 :version "24.3"
3593 :type 'string)
3595 (defun org-format-latex-mathml-available-p ()
3596 "Return t if `org-latex-to-mathml-convert-command' is usable."
3597 (save-match-data
3598 (when (and (boundp 'org-latex-to-mathml-convert-command)
3599 org-latex-to-mathml-convert-command)
3600 (let ((executable (car (split-string
3601 org-latex-to-mathml-convert-command))))
3602 (when (executable-find executable)
3603 (if (string-match
3604 "%j" org-latex-to-mathml-convert-command)
3605 (file-readable-p org-latex-to-mathml-jar-file)
3606 t))))))
3608 (defcustom org-format-latex-header "\\documentclass{article}
3609 \\usepackage[usenames]{color}
3610 \\usepackage{amsmath}
3611 \\usepackage[mathscr]{eucal}
3612 \\pagestyle{empty} % do not remove
3613 \[PACKAGES]
3614 \[DEFAULT-PACKAGES]
3615 % The settings below are copied from fullpage.sty
3616 \\setlength{\\textwidth}{\\paperwidth}
3617 \\addtolength{\\textwidth}{-3cm}
3618 \\setlength{\\oddsidemargin}{1.5cm}
3619 \\addtolength{\\oddsidemargin}{-2.54cm}
3620 \\setlength{\\evensidemargin}{\\oddsidemargin}
3621 \\setlength{\\textheight}{\\paperheight}
3622 \\addtolength{\\textheight}{-\\headheight}
3623 \\addtolength{\\textheight}{-\\headsep}
3624 \\addtolength{\\textheight}{-\\footskip}
3625 \\addtolength{\\textheight}{-3cm}
3626 \\setlength{\\topmargin}{1.5cm}
3627 \\addtolength{\\topmargin}{-2.54cm}"
3628 "The document header used for processing LaTeX fragments.
3629 It is imperative that this header make sure that no page number
3630 appears on the page. The package defined in the variables
3631 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3632 will either replace the placeholder \"[PACKAGES]\" in this
3633 header, or they will be appended."
3634 :group 'org-latex
3635 :type 'string)
3637 (defun org-set-packages-alist (var val)
3638 "Set the packages alist and make sure it has 3 elements per entry."
3639 (set var (mapcar (lambda (x)
3640 (if (and (consp x) (= (length x) 2))
3641 (list (car x) (nth 1 x) t)
3643 val)))
3645 (defun org-get-packages-alist (var)
3646 "Get the packages alist and make sure it has 3 elements per entry."
3647 (mapcar (lambda (x)
3648 (if (and (consp x) (= (length x) 2))
3649 (list (car x) (nth 1 x) t)
3651 (default-value var)))
3653 (defcustom org-latex-default-packages-alist
3654 '(("AUTO" "inputenc" t)
3655 ("T1" "fontenc" t)
3656 ("" "fixltx2e" nil)
3657 ("" "graphicx" t)
3658 ("" "longtable" nil)
3659 ("" "float" nil)
3660 ("" "wrapfig" nil)
3661 ("" "soul" t)
3662 ("" "textcomp" t)
3663 ("" "marvosym" t)
3664 ("" "wasysym" t)
3665 ("" "latexsym" t)
3666 ("" "amssymb" t)
3667 ("" "hyperref" nil)
3668 "\\tolerance=1000")
3669 "Alist of default packages to be inserted in the header.
3671 Change this only if one of the packages here causes an
3672 incompatibility with another package you are using.
3674 The packages in this list are needed by one part or another of
3675 Org mode to function properly:
3677 - inputenc, fontenc: for basic font and character selection
3678 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3679 symbols used for interpreting the entities in `org-entities'.
3680 You can skip some of these packages if you don't use any of the
3681 symbols in it.
3682 - graphicx: for including images
3683 - float, wrapfig: for figure placement
3684 - longtable: for long tables
3685 - hyperref: for cross references
3687 Therefore you should not modify this variable unless you know
3688 what you are doing. The one reason to change it anyway is that
3689 you might be loading some other package that conflicts with one
3690 of the default packages. Each cell is of the format
3691 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3692 the package also needs to be included when compiling LaTeX
3693 snippets into images for inclusion into non-LaTeX output."
3694 :group 'org-latex
3695 :group 'org-export-latex
3696 :set 'org-set-packages-alist
3697 :get 'org-get-packages-alist
3698 :version "24.1"
3699 :type '(repeat
3700 (choice
3701 (list :tag "options/package pair"
3702 (string :tag "options")
3703 (string :tag "package")
3704 (boolean :tag "Snippet"))
3705 (string :tag "A line of LaTeX"))))
3707 (defcustom org-latex-packages-alist nil
3708 "Alist of packages to be inserted in every LaTeX header.
3710 These will be inserted after `org-latex-default-packages-alist'.
3711 Each cell is of the format:
3713 \(\"options\" \"package\" snippet-flag)
3715 SNIPPET-FLAG, when t, indicates that this package is also needed
3716 when turning LaTeX snippets into images for inclusion into
3717 non-LaTeX output.
3719 Make sure that you only list packages here which:
3721 - you want in every file
3722 - do not conflict with the setup in `org-format-latex-header'.
3723 - do not conflict with the default packages in
3724 `org-latex-default-packages-alist'."
3725 :group 'org-latex
3726 :group 'org-export-latex
3727 :set 'org-set-packages-alist
3728 :get 'org-get-packages-alist
3729 :type '(repeat
3730 (choice
3731 (list :tag "options/package pair"
3732 (string :tag "options")
3733 (string :tag "package")
3734 (boolean :tag "Snippet"))
3735 (string :tag "A line of LaTeX"))))
3737 (defgroup org-appearance nil
3738 "Settings for Org-mode appearance."
3739 :tag "Org Appearance"
3740 :group 'org)
3742 (defcustom org-level-color-stars-only nil
3743 "Non-nil means fontify only the stars in each headline.
3744 When nil, the entire headline is fontified.
3745 Changing it requires restart of `font-lock-mode' to become effective
3746 also in regions already fontified."
3747 :group 'org-appearance
3748 :type 'boolean)
3750 (defcustom org-hide-leading-stars nil
3751 "Non-nil means hide the first N-1 stars in a headline.
3752 This works by using the face `org-hide' for these stars. This
3753 face is white for a light background, and black for a dark
3754 background. You may have to customize the face `org-hide' to
3755 make this work.
3756 Changing it requires restart of `font-lock-mode' to become effective
3757 also in regions already fontified.
3758 You may also set this on a per-file basis by adding one of the following
3759 lines to the buffer:
3761 #+STARTUP: hidestars
3762 #+STARTUP: showstars"
3763 :group 'org-appearance
3764 :type 'boolean)
3766 (defcustom org-hidden-keywords nil
3767 "List of symbols corresponding to keywords to be hidden the org buffer.
3768 For example, a value '(title) for this list will make the document's title
3769 appear in the buffer without the initial #+TITLE: keyword."
3770 :group 'org-appearance
3771 :version "24.1"
3772 :type '(set (const :tag "#+AUTHOR" author)
3773 (const :tag "#+DATE" date)
3774 (const :tag "#+EMAIL" email)
3775 (const :tag "#+TITLE" title)))
3777 (defcustom org-custom-properties nil
3778 "List of properties (as strings) with a special meaning.
3779 The default use of these custom properties is to let the user
3780 hide them with `org-toggle-custom-properties-visibility'."
3781 :group 'org-properties
3782 :group 'org-appearance
3783 :version "24.3"
3784 :type '(repeat (string :tag "Property Name")))
3786 (defcustom org-fontify-done-headline nil
3787 "Non-nil means change the face of a headline if it is marked DONE.
3788 Normally, only the TODO/DONE keyword indicates the state of a headline.
3789 When this is non-nil, the headline after the keyword is set to the
3790 `org-headline-done' as an additional indication."
3791 :group 'org-appearance
3792 :type 'boolean)
3794 (defcustom org-fontify-emphasized-text t
3795 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3796 Changing this variable requires a restart of Emacs to take effect."
3797 :group 'org-appearance
3798 :type 'boolean)
3800 (defcustom org-fontify-whole-heading-line nil
3801 "Non-nil means fontify the whole line for headings.
3802 This is useful when setting a background color for the
3803 org-level-* faces."
3804 :group 'org-appearance
3805 :type 'boolean)
3807 (defcustom org-hide-emphasis-markers nil
3808 "Non-nil mean font-lock should hide the emphasis marker characters."
3809 :group 'org-appearance
3810 :type 'boolean)
3812 (defcustom org-pretty-entities nil
3813 "Non-nil means show entities as UTF8 characters.
3814 When nil, the \\name form remains in the buffer."
3815 :group 'org-appearance
3816 :version "24.1"
3817 :type 'boolean)
3819 (defcustom org-pretty-entities-include-sub-superscripts t
3820 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3821 :group 'org-appearance
3822 :version "24.1"
3823 :type 'boolean)
3825 (defvar org-emph-re nil
3826 "Regular expression for matching emphasis.
3827 After a match, the match groups contain these elements:
3828 0 The match of the full regular expression, including the characters
3829 before and after the proper match
3830 1 The character before the proper match, or empty at beginning of line
3831 2 The proper match, including the leading and trailing markers
3832 3 The leading marker like * or /, indicating the type of highlighting
3833 4 The text between the emphasis markers, not including the markers
3834 5 The character after the match, empty at the end of a line")
3835 (defvar org-verbatim-re nil
3836 "Regular expression for matching verbatim text.")
3837 (defvar org-emphasis-regexp-components) ; defined just below
3838 (defvar org-emphasis-alist) ; defined just below
3839 (defun org-set-emph-re (var val)
3840 "Set variable and compute the emphasis regular expression."
3841 (set var val)
3842 (when (and (boundp 'org-emphasis-alist)
3843 (boundp 'org-emphasis-regexp-components)
3844 org-emphasis-alist org-emphasis-regexp-components)
3845 (let* ((e org-emphasis-regexp-components)
3846 (pre (car e))
3847 (post (nth 1 e))
3848 (border (nth 2 e))
3849 (body (nth 3 e))
3850 (nl (nth 4 e))
3851 (body1 (concat body "*?"))
3852 (markers (mapconcat 'car org-emphasis-alist ""))
3853 (vmarkers (mapconcat
3854 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3855 org-emphasis-alist "")))
3856 ;; make sure special characters appear at the right position in the class
3857 (if (string-match "\\^" markers)
3858 (setq markers (concat (replace-match "" t t markers) "^")))
3859 (if (string-match "-" markers)
3860 (setq markers (concat (replace-match "" t t markers) "-")))
3861 (if (string-match "\\^" vmarkers)
3862 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3863 (if (string-match "-" vmarkers)
3864 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3865 (if (> nl 0)
3866 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3867 (int-to-string nl) "\\}")))
3868 ;; Make the regexp
3869 (setq org-emph-re
3870 (concat "\\([" pre "]\\|^\\)"
3871 "\\("
3872 "\\([" markers "]\\)"
3873 "\\("
3874 "[^" border "]\\|"
3875 "[^" border "]"
3876 body1
3877 "[^" border "]"
3878 "\\)"
3879 "\\3\\)"
3880 "\\([" post "]\\|$\\)"))
3881 (setq org-verbatim-re
3882 (concat "\\([" pre "]\\|^\\)"
3883 "\\("
3884 "\\([" vmarkers "]\\)"
3885 "\\("
3886 "[^" border "]\\|"
3887 "[^" border "]"
3888 body1
3889 "[^" border "]"
3890 "\\)"
3891 "\\3\\)"
3892 "\\([" post "]\\|$\\)")))))
3894 (defcustom org-emphasis-regexp-components
3895 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3896 "Components used to build the regular expression for emphasis.
3897 This is a list with five entries. Terminology: In an emphasis string
3898 like \" *strong word* \", we call the initial space PREMATCH, the final
3899 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3900 and \"trong wor\" is the body. The different components in this variable
3901 specify what is allowed/forbidden in each part:
3903 pre Chars allowed as prematch. Beginning of line will be allowed too.
3904 post Chars allowed as postmatch. End of line will be allowed too.
3905 border The chars *forbidden* as border characters.
3906 body-regexp A regexp like \".\" to match a body character. Don't use
3907 non-shy groups here, and don't allow newline here.
3908 newline The maximum number of newlines allowed in an emphasis exp.
3910 Use customize to modify this, or restart Emacs after changing it."
3911 :group 'org-appearance
3912 :set 'org-set-emph-re
3913 :type '(list
3914 (sexp :tag "Allowed chars in pre ")
3915 (sexp :tag "Allowed chars in post ")
3916 (sexp :tag "Forbidden chars in border ")
3917 (sexp :tag "Regexp for body ")
3918 (integer :tag "number of newlines allowed")
3919 (option (boolean :tag "Please ignore this button"))))
3921 (defcustom org-emphasis-alist
3922 `(("*" bold "<b>" "</b>")
3923 ("/" italic "<i>" "</i>")
3924 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3925 ("=" org-code "<code>" "</code>" verbatim)
3926 ("~" org-verbatim "<code>" "</code>" verbatim)
3927 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3928 "<del>" "</del>")
3930 "Special syntax for emphasized text.
3931 Text starting and ending with a special character will be emphasized, for
3932 example *bold*, _underlined_ and /italic/. This variable sets the marker
3933 characters, the face to be used by font-lock for highlighting in Org-mode
3934 Emacs buffers, and the HTML tags to be used for this.
3935 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3936 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3937 Use customize to modify this, or restart Emacs after changing it."
3938 :group 'org-appearance
3939 :set 'org-set-emph-re
3940 :type '(repeat
3941 (list
3942 (string :tag "Marker character")
3943 (choice
3944 (face :tag "Font-lock-face")
3945 (plist :tag "Face property list"))
3946 (string :tag "HTML start tag")
3947 (string :tag "HTML end tag")
3948 (option (const verbatim)))))
3950 (defvar org-syntax-table
3951 (let ((st (make-syntax-table)))
3952 (mapc (lambda(c) (modify-syntax-entry
3953 (string-to-char (car c)) "w p" st))
3954 org-emphasis-alist)
3955 st))
3957 (defvar org-protecting-blocks
3958 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3959 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3960 This is needed for font-lock setup.")
3962 ;;; Miscellaneous options
3964 (defgroup org-completion nil
3965 "Completion in Org-mode."
3966 :tag "Org Completion"
3967 :group 'org)
3969 (defcustom org-completion-use-ido nil
3970 "Non-nil means use ido completion wherever possible.
3971 Note that `ido-mode' must be active for this variable to be relevant.
3972 If you decide to turn this variable on, you might well want to turn off
3973 `org-outline-path-complete-in-steps'.
3974 See also `org-completion-use-iswitchb'."
3975 :group 'org-completion
3976 :type 'boolean)
3978 (defcustom org-completion-use-iswitchb nil
3979 "Non-nil means use iswitchb completion wherever possible.
3980 Note that `iswitchb-mode' must be active for this variable to be relevant.
3981 If you decide to turn this variable on, you might well want to turn off
3982 `org-outline-path-complete-in-steps'.
3983 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3984 :group 'org-completion
3985 :type 'boolean)
3987 (defcustom org-completion-fallback-command 'hippie-expand
3988 "The expansion command called by \\[pcomplete] in normal context.
3989 Normal means, no org-mode-specific context."
3990 :group 'org-completion
3991 :type 'function)
3993 ;;; Functions and variables from their packages
3994 ;; Declared here to avoid compiler warnings
3996 ;; XEmacs only
3997 (defvar outline-mode-menu-heading)
3998 (defvar outline-mode-menu-show)
3999 (defvar outline-mode-menu-hide)
4000 (defvar zmacs-regions) ; XEmacs regions
4002 ;; Emacs only
4003 (defvar mark-active)
4005 ;; Various packages
4006 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4007 (declare-function calendar-forward-day "cal-move" (arg))
4008 (declare-function calendar-goto-date "cal-move" (date))
4009 (declare-function calendar-goto-today "cal-move" ())
4010 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4011 (defvar calc-embedded-close-formula)
4012 (defvar calc-embedded-open-formula)
4013 (declare-function cdlatex-tab "ext:cdlatex" ())
4014 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4015 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4016 (defvar font-lock-unfontify-region-function)
4017 (declare-function iswitchb-read-buffer "iswitchb"
4018 (prompt &optional default require-match start matches-set))
4019 (defvar iswitchb-temp-buflist)
4020 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4021 (defvar org-agenda-tags-todo-honor-ignore-options)
4022 (declare-function org-agenda-skip "org-agenda" ())
4023 (declare-function
4024 org-agenda-format-item "org-agenda"
4025 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4026 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4027 (declare-function org-agenda-change-all-lines "org-agenda"
4028 (newhead hdmarker &optional fixface just-this))
4029 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4030 (declare-function org-agenda-maybe-redo "org-agenda" ())
4031 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4032 (beg end))
4033 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4034 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4035 "org-agenda" (&optional end))
4036 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4037 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4038 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4039 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4040 (declare-function org-indent-mode "org-indent" (&optional arg))
4041 (declare-function parse-time-string "parse-time" (string))
4042 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4043 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4044 (defvar remember-data-file)
4045 (defvar texmathp-why)
4046 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4047 (declare-function table--at-cell-p "table" (position &optional object at-column))
4049 (defvar org-latex-regexps)
4051 ;;; Autoload and prepare some org modules
4053 ;; Some table stuff that needs to be defined here, because it is used
4054 ;; by the functions setting up org-mode or checking for table context.
4056 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4057 "Detect an org-type or table-type table.")
4058 (defconst org-table-line-regexp "^[ \t]*|"
4059 "Detect an org-type table line.")
4060 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4061 "Detect an org-type table line.")
4062 (defconst org-table-hline-regexp "^[ \t]*|-"
4063 "Detect an org-type table hline.")
4064 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4065 "Detect a table-type table hline.")
4066 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4067 "Detect the first line outside a table when searching from within it.
4068 This works for both table types.")
4070 ;; Autoload the functions in org-table.el that are needed by functions here.
4072 (eval-and-compile
4073 (org-autoload "org-table"
4074 '(org-table-begin org-table-blank-field org-table-end)))
4076 ;;;###autoload
4077 (defun turn-on-orgtbl ()
4078 "Unconditionally turn on `orgtbl-mode'."
4079 (require 'org-table)
4080 (orgtbl-mode 1))
4082 (defun org-at-table-p (&optional table-type)
4083 "Return t if the cursor is inside an org-type table.
4084 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4085 (if org-enable-table-editor
4086 (save-excursion
4087 (beginning-of-line 1)
4088 (looking-at (if table-type org-table-any-line-regexp
4089 org-table-line-regexp)))
4090 nil))
4091 (defsubst org-table-p () (org-at-table-p))
4093 (defun org-at-table.el-p ()
4094 "Return t if and only if we are at a table.el table."
4095 (and (org-at-table-p 'any)
4096 (save-excursion
4097 (goto-char (org-table-begin 'any))
4098 (looking-at org-table1-hline-regexp))))
4099 (defun org-table-recognize-table.el ()
4100 "If there is a table.el table nearby, recognize it and move into it."
4101 (if org-table-tab-recognizes-table.el
4102 (if (org-at-table.el-p)
4103 (progn
4104 (beginning-of-line 1)
4105 (if (looking-at org-table-dataline-regexp)
4107 (if (looking-at org-table1-hline-regexp)
4108 (progn
4109 (beginning-of-line 2)
4110 (if (looking-at org-table-any-border-regexp)
4111 (beginning-of-line -1)))))
4112 (if (re-search-forward "|" (org-table-end t) t)
4113 (progn
4114 (require 'table)
4115 (if (table--at-cell-p (point))
4117 (message "recognizing table.el table...")
4118 (table-recognize-table)
4119 (message "recognizing table.el table...done")))
4120 (error "This should not happen"))
4122 nil)
4123 nil))
4125 (defun org-at-table-hline-p ()
4126 "Return t if the cursor is inside a hline in a table."
4127 (if org-enable-table-editor
4128 (save-excursion
4129 (beginning-of-line 1)
4130 (looking-at org-table-hline-regexp))
4131 nil))
4133 (defvar org-table-clean-did-remove-column nil)
4135 (defun org-table-map-tables (function &optional quietly)
4136 "Apply FUNCTION to the start of all tables in the buffer."
4137 (save-excursion
4138 (save-restriction
4139 (widen)
4140 (goto-char (point-min))
4141 (while (re-search-forward org-table-any-line-regexp nil t)
4142 (unless quietly
4143 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4144 (beginning-of-line 1)
4145 (when (and (looking-at org-table-line-regexp)
4146 ;; Exclude tables in src/example/verbatim/clocktable blocks
4147 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4148 (save-excursion (funcall function))
4149 (or (looking-at org-table-line-regexp)
4150 (forward-char 1)))
4151 (re-search-forward org-table-any-border-regexp nil 1))))
4152 (unless quietly (message "Mapping tables: done")))
4154 ;; Declare and autoload functions from ox.el and al.
4156 (declare-function org-export-get-environment "ox"
4157 (&optional backend subtreep ext-plist))
4158 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4160 ;; Declare and autoload functions from org-agenda.el
4162 (eval-and-compile
4163 (org-autoload "org-agenda"
4164 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4166 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4167 (declare-function org-clock-update-mode-line "org-clock" ())
4168 (declare-function org-resolve-clocks "org-clock"
4169 (&optional also-non-dangling-p prompt last-valid))
4170 (defvar org-clock-start-time)
4171 (defvar org-clock-marker (make-marker)
4172 "Marker recording the last clock-in.")
4173 (defvar org-clock-hd-marker (make-marker)
4174 "Marker recording the last clock-in, but the headline position.")
4175 (defvar org-clock-heading ""
4176 "The heading of the current clock entry.")
4177 (defun org-clock-is-active ()
4178 "Return non-nil if clock is currently running.
4179 The return value is actually the clock marker."
4180 (marker-buffer org-clock-marker))
4182 (eval-and-compile
4183 (org-autoload "org-clock" '(org-clock-remove-overlays
4184 org-clock-update-time-maybe
4185 org-clocktable-shift)))
4187 (defun org-check-running-clock ()
4188 "Check if the current buffer contains the running clock.
4189 If yes, offer to stop it and to save the buffer with the changes."
4190 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4191 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4192 (buffer-name))))
4193 (org-clock-out)
4194 (when (y-or-n-p "Save changed buffer?")
4195 (save-buffer))))
4197 (defun org-clocktable-try-shift (dir n)
4198 "Check if this line starts a clock table, if yes, shift the time block."
4199 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4200 (org-clocktable-shift dir n)))
4202 ;;;###autoload
4203 (defun org-clock-persistence-insinuate ()
4204 "Set up hooks for clock persistence."
4205 (require 'org-clock)
4206 (add-hook 'org-mode-hook 'org-clock-load)
4207 (add-hook 'kill-emacs-hook 'org-clock-save))
4209 ;; Define the variable already here, to make sure we have it.
4210 (defvar org-indent-mode nil
4211 "Non-nil if Org-Indent mode is enabled.
4212 Use the command `org-indent-mode' to change this variable.")
4214 ;; Autoload archiving code
4215 ;; The stuff that is needed for cycling and tags has to be defined here.
4217 (defgroup org-archive nil
4218 "Options concerning archiving in Org-mode."
4219 :tag "Org Archive"
4220 :group 'org-structure)
4222 (defcustom org-archive-location "%s_archive::"
4223 "The location where subtrees should be archived.
4225 The value of this variable is a string, consisting of two parts,
4226 separated by a double-colon. The first part is a filename and
4227 the second part is a headline.
4229 When the filename is omitted, archiving happens in the same file.
4230 %s in the filename will be replaced by the current file
4231 name (without the directory part). Archiving to a different file
4232 is useful to keep archived entries from contributing to the
4233 Org-mode Agenda.
4235 The archived entries will be filed as subtrees of the specified
4236 headline. When the headline is omitted, the subtrees are simply
4237 filed away at the end of the file, as top-level entries. Also in
4238 the heading you can use %s to represent the file name, this can be
4239 useful when using the same archive for a number of different files.
4241 Here are a few examples:
4242 \"%s_archive::\"
4243 If the current file is Projects.org, archive in file
4244 Projects.org_archive, as top-level trees. This is the default.
4246 \"::* Archived Tasks\"
4247 Archive in the current file, under the top-level headline
4248 \"* Archived Tasks\".
4250 \"~/org/archive.org::\"
4251 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4253 \"~/org/archive.org::* From %s\"
4254 Archive in file ~/org/archive.org (absolute path), under headlines
4255 \"From FILENAME\" where file name is the current file name.
4257 \"~/org/datetree.org::datetree/* Finished Tasks\"
4258 The \"datetree/\" string is special, signifying to archive
4259 items to the datetree. Items are placed in either the CLOSED
4260 date of the item, or the current date if there is no CLOSED date.
4261 The heading will be a subentry to the current date. There doesn't
4262 need to be a heading, but there always needs to be a slash after
4263 datetree. For example, to store archived items directly in the
4264 datetree, use \"~/org/datetree.org::datetree/\".
4266 \"basement::** Finished Tasks\"
4267 Archive in file ./basement (relative path), as level 3 trees
4268 below the level 2 heading \"** Finished Tasks\".
4270 You may set this option on a per-file basis by adding to the buffer a
4271 line like
4273 #+ARCHIVE: basement::** Finished Tasks
4275 You may also define it locally for a subtree by setting an ARCHIVE property
4276 in the entry. If such a property is found in an entry, or anywhere up
4277 the hierarchy, it will be used."
4278 :group 'org-archive
4279 :type 'string)
4281 (defcustom org-archive-tag "ARCHIVE"
4282 "The tag that marks a subtree as archived.
4283 An archived subtree does not open during visibility cycling, and does
4284 not contribute to the agenda listings.
4285 After changing this, font-lock must be restarted in the relevant buffers to
4286 get the proper fontification."
4287 :group 'org-archive
4288 :group 'org-keywords
4289 :type 'string)
4291 (defcustom org-agenda-skip-archived-trees t
4292 "Non-nil means the agenda will skip any items located in archived trees.
4293 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4294 variable is no longer recommended, you should leave it at the value t.
4295 Instead, use the key `v' to cycle the archives-mode in the agenda."
4296 :group 'org-archive
4297 :group 'org-agenda-skip
4298 :type 'boolean)
4300 (defcustom org-columns-skip-archived-trees t
4301 "Non-nil means ignore archived trees when creating column view."
4302 :group 'org-archive
4303 :group 'org-properties
4304 :type 'boolean)
4306 (defcustom org-cycle-open-archived-trees nil
4307 "Non-nil means `org-cycle' will open archived trees.
4308 An archived tree is a tree marked with the tag ARCHIVE.
4309 When nil, archived trees will stay folded. You can still open them with
4310 normal outline commands like `show-all', but not with the cycling commands."
4311 :group 'org-archive
4312 :group 'org-cycle
4313 :type 'boolean)
4315 (defcustom org-sparse-tree-open-archived-trees nil
4316 "Non-nil means sparse tree construction shows matches in archived trees.
4317 When nil, matches in these trees are highlighted, but the trees are kept in
4318 collapsed state."
4319 :group 'org-archive
4320 :group 'org-sparse-trees
4321 :type 'boolean)
4323 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4324 "The default date type when building a sparse tree.
4325 When this is nil, a date is a scheduled or a deadline timestamp.
4326 Otherwise, these types are allowed:
4328 all: all timestamps
4329 active: only active timestamps (<...>)
4330 inactive: only inactive timestamps (<...)
4331 scheduled: only scheduled timestamps
4332 deadline: only deadline timestamps"
4333 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4334 (const :tag "All timestamps" all)
4335 (const :tag "Only active timestamps" active)
4336 (const :tag "Only inactive timestamps" inactive)
4337 (const :tag "Only scheduled timestamps" scheduled)
4338 (const :tag "Only deadline timestamps" deadline))
4339 :version "24.3"
4340 :group 'org-sparse-trees)
4342 (defun org-cycle-hide-archived-subtrees (state)
4343 "Re-hide all archived subtrees after a visibility state change."
4344 (when (and (not org-cycle-open-archived-trees)
4345 (not (memq state '(overview folded))))
4346 (save-excursion
4347 (let* ((globalp (memq state '(contents all)))
4348 (beg (if globalp (point-min) (point)))
4349 (end (if globalp (point-max) (org-end-of-subtree t))))
4350 (org-hide-archived-subtrees beg end)
4351 (goto-char beg)
4352 (if (looking-at (concat ".*:" org-archive-tag ":"))
4353 (message "%s" (substitute-command-keys
4354 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4356 (defun org-force-cycle-archived ()
4357 "Cycle subtree even if it is archived."
4358 (interactive)
4359 (setq this-command 'org-cycle)
4360 (let ((org-cycle-open-archived-trees t))
4361 (call-interactively 'org-cycle)))
4363 (defun org-hide-archived-subtrees (beg end)
4364 "Re-hide all archived subtrees after a visibility state change."
4365 (save-excursion
4366 (let* ((re (concat ":" org-archive-tag ":")))
4367 (goto-char beg)
4368 (while (re-search-forward re end t)
4369 (when (org-at-heading-p)
4370 (org-flag-subtree t)
4371 (org-end-of-subtree t))))))
4373 (declare-function outline-end-of-heading "outline" ())
4374 (declare-function outline-flag-region "outline" (from to flag))
4375 (defun org-flag-subtree (flag)
4376 (save-excursion
4377 (org-back-to-heading t)
4378 (outline-end-of-heading)
4379 (outline-flag-region (point)
4380 (progn (org-end-of-subtree t) (point))
4381 flag)))
4383 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4385 (eval-and-compile
4386 (org-autoload "org-archive"
4387 '(org-add-archive-files)))
4389 ;; Autoload Column View Code
4391 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4392 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4393 (declare-function org-columns-compute "org-colview" (property))
4395 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4396 '(org-columns-number-to-string
4397 org-columns-get-format-and-top-level
4398 org-columns-compute
4399 org-columns-remove-overlays))
4401 ;; Autoload ID code
4403 (declare-function org-id-store-link "org-id")
4404 (declare-function org-id-locations-load "org-id")
4405 (declare-function org-id-locations-save "org-id")
4406 (defvar org-id-track-globally)
4407 (org-autoload "org-id"
4408 '(org-id-new
4409 org-id-copy
4410 org-id-get-with-outline-path-completion
4411 org-id-get-with-outline-drilling))
4413 ;;; Variables for pre-computed regular expressions, all buffer local
4415 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4416 "Matches first line of a hidden block.")
4417 (make-variable-buffer-local 'org-drawer-regexp)
4418 (defvar org-todo-regexp nil
4419 "Matches any of the TODO state keywords.")
4420 (make-variable-buffer-local 'org-todo-regexp)
4421 (defvar org-not-done-regexp nil
4422 "Matches any of the TODO state keywords except the last one.")
4423 (make-variable-buffer-local 'org-not-done-regexp)
4424 (defvar org-not-done-heading-regexp nil
4425 "Matches a TODO headline that is not done.")
4426 (make-variable-buffer-local 'org-not-done-regexp)
4427 (defvar org-todo-line-regexp nil
4428 "Matches a headline and puts TODO state into group 2 if present.")
4429 (make-variable-buffer-local 'org-todo-line-regexp)
4430 (defvar org-complex-heading-regexp nil
4431 "Matches a headline and puts everything into groups:
4432 group 1: the stars
4433 group 2: The todo keyword, maybe
4434 group 3: Priority cookie
4435 group 4: True headline
4436 group 5: Tags")
4437 (make-variable-buffer-local 'org-complex-heading-regexp)
4438 (defvar org-complex-heading-regexp-format nil
4439 "Printf format to make regexp to match an exact headline.
4440 This regexp will match the headline of any node which has the
4441 exact headline text that is put into the format, but may have any
4442 TODO state, priority and tags.")
4443 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4444 (defvar org-todo-line-tags-regexp nil
4445 "Matches a headline and puts TODO state into group 2 if present.
4446 Also put tags into group 4 if tags are present.")
4447 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4448 (defvar org-ds-keyword-length 12
4449 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4450 (make-variable-buffer-local 'org-ds-keyword-length)
4451 (defvar org-deadline-regexp nil
4452 "Matches the DEADLINE keyword.")
4453 (make-variable-buffer-local 'org-deadline-regexp)
4454 (defvar org-deadline-time-regexp nil
4455 "Matches the DEADLINE keyword together with a time stamp.")
4456 (make-variable-buffer-local 'org-deadline-time-regexp)
4457 (defvar org-deadline-line-regexp nil
4458 "Matches the DEADLINE keyword and the rest of the line.")
4459 (make-variable-buffer-local 'org-deadline-line-regexp)
4460 (defvar org-scheduled-regexp nil
4461 "Matches the SCHEDULED keyword.")
4462 (make-variable-buffer-local 'org-scheduled-regexp)
4463 (defvar org-scheduled-time-regexp nil
4464 "Matches the SCHEDULED keyword together with a time stamp.")
4465 (make-variable-buffer-local 'org-scheduled-time-regexp)
4466 (defvar org-closed-time-regexp nil
4467 "Matches the CLOSED keyword together with a time stamp.")
4468 (make-variable-buffer-local 'org-closed-time-regexp)
4470 (defvar org-keyword-time-regexp nil
4471 "Matches any of the 4 keywords, together with the time stamp.")
4472 (make-variable-buffer-local 'org-keyword-time-regexp)
4473 (defvar org-keyword-time-not-clock-regexp nil
4474 "Matches any of the 3 keywords, together with the time stamp.")
4475 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4476 (defvar org-maybe-keyword-time-regexp nil
4477 "Matches a timestamp, possibly preceded by a keyword.")
4478 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4479 (defvar org-all-time-keywords nil
4480 "List of time keywords.")
4481 (make-variable-buffer-local 'org-all-time-keywords)
4483 (defconst org-plain-time-of-day-regexp
4484 (concat
4485 "\\(\\<[012]?[0-9]"
4486 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4487 "\\(--?"
4488 "\\(\\<[012]?[0-9]"
4489 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4490 "\\)?")
4491 "Regular expression to match a plain time or time range.
4492 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4493 groups carry important information:
4494 0 the full match
4495 1 the first time, range or not
4496 8 the second time, if it is a range.")
4498 (defconst org-plain-time-extension-regexp
4499 (concat
4500 "\\(\\<[012]?[0-9]"
4501 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4502 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4503 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4504 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4505 groups carry important information:
4506 0 the full match
4507 7 hours of duration
4508 9 minutes of duration")
4510 (defconst org-stamp-time-of-day-regexp
4511 (concat
4512 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4513 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4514 "\\(--?"
4515 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4516 "Regular expression to match a timestamp time or time range.
4517 After a match, the following groups carry important information:
4518 0 the full match
4519 1 date plus weekday, for back referencing to make sure both times are on the same day
4520 2 the first time, range or not
4521 4 the second time, if it is a range.")
4523 (defconst org-startup-options
4524 '(("fold" org-startup-folded t)
4525 ("overview" org-startup-folded t)
4526 ("nofold" org-startup-folded nil)
4527 ("showall" org-startup-folded nil)
4528 ("showeverything" org-startup-folded showeverything)
4529 ("content" org-startup-folded content)
4530 ("indent" org-startup-indented t)
4531 ("noindent" org-startup-indented nil)
4532 ("hidestars" org-hide-leading-stars t)
4533 ("showstars" org-hide-leading-stars nil)
4534 ("odd" org-odd-levels-only t)
4535 ("oddeven" org-odd-levels-only nil)
4536 ("align" org-startup-align-all-tables t)
4537 ("noalign" org-startup-align-all-tables nil)
4538 ("inlineimages" org-startup-with-inline-images t)
4539 ("noinlineimages" org-startup-with-inline-images nil)
4540 ("customtime" org-display-custom-times t)
4541 ("logdone" org-log-done time)
4542 ("lognotedone" org-log-done note)
4543 ("nologdone" org-log-done nil)
4544 ("lognoteclock-out" org-log-note-clock-out t)
4545 ("nolognoteclock-out" org-log-note-clock-out nil)
4546 ("logrepeat" org-log-repeat state)
4547 ("lognoterepeat" org-log-repeat note)
4548 ("logdrawer" org-log-into-drawer t)
4549 ("nologdrawer" org-log-into-drawer nil)
4550 ("logstatesreversed" org-log-states-order-reversed t)
4551 ("nologstatesreversed" org-log-states-order-reversed nil)
4552 ("nologrepeat" org-log-repeat nil)
4553 ("logreschedule" org-log-reschedule time)
4554 ("lognotereschedule" org-log-reschedule note)
4555 ("nologreschedule" org-log-reschedule nil)
4556 ("logredeadline" org-log-redeadline time)
4557 ("lognoteredeadline" org-log-redeadline note)
4558 ("nologredeadline" org-log-redeadline nil)
4559 ("logrefile" org-log-refile time)
4560 ("lognoterefile" org-log-refile note)
4561 ("nologrefile" org-log-refile nil)
4562 ("fninline" org-footnote-define-inline t)
4563 ("nofninline" org-footnote-define-inline nil)
4564 ("fnlocal" org-footnote-section nil)
4565 ("fnauto" org-footnote-auto-label t)
4566 ("fnprompt" org-footnote-auto-label nil)
4567 ("fnconfirm" org-footnote-auto-label confirm)
4568 ("fnplain" org-footnote-auto-label plain)
4569 ("fnadjust" org-footnote-auto-adjust t)
4570 ("nofnadjust" org-footnote-auto-adjust nil)
4571 ("constcgs" constants-unit-system cgs)
4572 ("constSI" constants-unit-system SI)
4573 ("noptag" org-tag-persistent-alist nil)
4574 ("hideblocks" org-hide-block-startup t)
4575 ("nohideblocks" org-hide-block-startup nil)
4576 ("beamer" org-startup-with-beamer-mode t)
4577 ("entitiespretty" org-pretty-entities t)
4578 ("entitiesplain" org-pretty-entities nil))
4579 "Variable associated with STARTUP options for org-mode.
4580 Each element is a list of three items: the startup options (as written
4581 in the #+STARTUP line), the corresponding variable, and the value to set
4582 this variable to if the option is found. An optional forth element PUSH
4583 means to push this value onto the list in the variable.")
4585 (defun org-update-property-plist (key val props)
4586 "Update PROPS with KEY and VAL."
4587 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4588 (key (if appending (substring key 0 (- (length key) 1)) key))
4589 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4590 (previous (cdr (assoc key props))))
4591 (if appending
4592 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4593 (cons (cons key val) remainder))))
4595 (defconst org-block-regexp
4596 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4597 "Regular expression for hiding blocks.")
4598 (defconst org-heading-keyword-regexp-format
4599 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4600 "Printf format for a regexp matching an headline with some keyword.
4601 This regexp will match the headline of any node which has the
4602 exact keyword that is put into the format. The keyword isn't in
4603 any group by default, but the stars and the body are.")
4604 (defconst org-heading-keyword-maybe-regexp-format
4605 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4606 "Printf format for a regexp matching an headline, possibly with some keyword.
4607 This regexp can match any headline with the specified keyword, or
4608 without a keyword. The keyword isn't in any group by default,
4609 but the stars and the body are.")
4611 (defun org-set-regexps-and-options ()
4612 "Precompute regular expressions for current buffer."
4613 (when (derived-mode-p 'org-mode)
4614 (org-set-local 'org-todo-kwd-alist nil)
4615 (org-set-local 'org-todo-key-alist nil)
4616 (org-set-local 'org-todo-key-trigger nil)
4617 (org-set-local 'org-todo-keywords-1 nil)
4618 (org-set-local 'org-done-keywords nil)
4619 (org-set-local 'org-todo-heads nil)
4620 (org-set-local 'org-todo-sets nil)
4621 (org-set-local 'org-todo-log-states nil)
4622 (org-set-local 'org-file-properties nil)
4623 (org-set-local 'org-file-tags nil)
4624 (let ((re (org-make-options-regexp
4625 '("CATEGORY" "TODO" "COLUMNS"
4626 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4627 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4628 "OPTIONS")
4629 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4630 (splitre "[ \t]+")
4631 (scripts org-use-sub-superscripts)
4632 kwds kws0 kwsa key log value cat arch tags const links hw dws
4633 tail sep kws1 prio props ftags drawers beamer-p
4634 ext-setup-or-nil setup-contents (start 0))
4635 (save-excursion
4636 (save-restriction
4637 (widen)
4638 (goto-char (point-min))
4639 (while (or (and ext-setup-or-nil
4640 (string-match re ext-setup-or-nil start)
4641 (setq start (match-end 0)))
4642 (and (setq ext-setup-or-nil nil start 0)
4643 (re-search-forward re nil t)))
4644 (setq key (upcase (match-string 1 ext-setup-or-nil))
4645 value (org-match-string-no-properties 2 ext-setup-or-nil))
4646 (if (stringp value) (setq value (org-trim value)))
4647 (cond
4648 ((equal key "CATEGORY")
4649 (setq cat value))
4650 ((member key '("SEQ_TODO" "TODO"))
4651 (push (cons 'sequence (org-split-string value splitre)) kwds))
4652 ((equal key "TYP_TODO")
4653 (push (cons 'type (org-split-string value splitre)) kwds))
4654 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4655 ;; general TODO-like setup
4656 (push (cons (intern (downcase (match-string 1 key)))
4657 (org-split-string value splitre)) kwds))
4658 ((equal key "TAGS")
4659 (setq tags (append tags (if tags '("\\n") nil)
4660 (org-split-string value splitre))))
4661 ((equal key "COLUMNS")
4662 (org-set-local 'org-columns-default-format value))
4663 ((equal key "LINK")
4664 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4665 (push (cons (match-string 1 value)
4666 (org-trim (match-string 2 value)))
4667 links)))
4668 ((equal key "PRIORITIES")
4669 (setq prio (org-split-string value " +")))
4670 ((equal key "PROPERTY")
4671 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4672 (setq props (org-update-property-plist (match-string 1 value)
4673 (match-string 2 value)
4674 props))))
4675 ((equal key "FILETAGS")
4676 (when (string-match "\\S-" value)
4677 (setq ftags
4678 (append
4679 ftags
4680 (apply 'append
4681 (mapcar (lambda (x) (org-split-string x ":"))
4682 (org-split-string value)))))))
4683 ((equal key "DRAWERS")
4684 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4685 ((equal key "CONSTANTS")
4686 (setq const (append const (org-split-string value splitre))))
4687 ((equal key "STARTUP")
4688 (let ((opts (org-split-string value splitre))
4689 l var val)
4690 (while (setq l (pop opts))
4691 (when (setq l (assoc l org-startup-options))
4692 (setq var (nth 1 l) val (nth 2 l))
4693 (if (not (nth 3 l))
4694 (set (make-local-variable var) val)
4695 (if (not (listp (symbol-value var)))
4696 (set (make-local-variable var) nil))
4697 (set (make-local-variable var) (symbol-value var))
4698 (add-to-list var val))))))
4699 ((equal key "ARCHIVE")
4700 (setq arch value)
4701 (remove-text-properties 0 (length arch)
4702 '(face t fontified t) arch))
4703 ((equal key "LATEX_CLASS")
4704 (setq beamer-p (equal value "beamer")))
4705 ((equal key "OPTIONS")
4706 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4707 (setq scripts (read (match-string 2 value)))))
4708 ((equal key "SETUPFILE")
4709 (setq setup-contents (org-file-contents
4710 (expand-file-name
4711 (org-remove-double-quotes value))
4712 'noerror))
4713 (if (not ext-setup-or-nil)
4714 (setq ext-setup-or-nil setup-contents start 0)
4715 (setq ext-setup-or-nil
4716 (concat (substring ext-setup-or-nil 0 start)
4717 "\n" setup-contents "\n"
4718 (substring ext-setup-or-nil start)))))))
4719 ;; search for property blocks
4720 (goto-char (point-min))
4721 (while (re-search-forward org-block-regexp nil t)
4722 (when (equal "PROPERTY" (upcase (match-string 1)))
4723 (setq value (replace-regexp-in-string
4724 "[\n\r]" " " (match-string 4)))
4725 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4726 (setq props (org-update-property-plist (match-string 1 value)
4727 (match-string 2 value)
4728 props)))))))
4729 (org-set-local 'org-use-sub-superscripts scripts)
4730 (when cat
4731 (org-set-local 'org-category (intern cat))
4732 (push (cons "CATEGORY" cat) props))
4733 (when prio
4734 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4735 (setq prio (mapcar 'string-to-char prio))
4736 (org-set-local 'org-highest-priority (nth 0 prio))
4737 (org-set-local 'org-lowest-priority (nth 1 prio))
4738 (org-set-local 'org-default-priority (nth 2 prio)))
4739 (and props (org-set-local 'org-file-properties (nreverse props)))
4740 (and ftags (org-set-local 'org-file-tags
4741 (mapcar 'org-add-prop-inherited ftags)))
4742 (and drawers (org-set-local 'org-drawers drawers))
4743 (and arch (org-set-local 'org-archive-location arch))
4744 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4745 ;; Process the TODO keywords
4746 (unless kwds
4747 ;; Use the global values as if they had been given locally.
4748 (setq kwds (default-value 'org-todo-keywords))
4749 (if (stringp (car kwds))
4750 (setq kwds (list (cons org-todo-interpretation
4751 (default-value 'org-todo-keywords)))))
4752 (setq kwds (reverse kwds)))
4753 (setq kwds (nreverse kwds))
4754 (let (inter kws kw)
4755 (while (setq kws (pop kwds))
4756 (let ((kws (or
4757 (run-hook-with-args-until-success
4758 'org-todo-setup-filter-hook kws)
4759 kws)))
4760 (setq inter (pop kws) sep (member "|" kws)
4761 kws0 (delete "|" (copy-sequence kws))
4762 kwsa nil
4763 kws1 (mapcar
4764 (lambda (x)
4765 ;; 1 2
4766 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4767 (progn
4768 (setq kw (match-string 1 x)
4769 key (and (match-end 2) (match-string 2 x))
4770 log (org-extract-log-state-settings x))
4771 (push (cons kw (and key (string-to-char key))) kwsa)
4772 (and log (push log org-todo-log-states))
4774 (error "Invalid TODO keyword %s" x)))
4775 kws0)
4776 kwsa (if kwsa (append '((:startgroup))
4777 (nreverse kwsa)
4778 '((:endgroup))))
4779 hw (car kws1)
4780 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4781 tail (list inter hw (car dws) (org-last dws))))
4782 (add-to-list 'org-todo-heads hw 'append)
4783 (push kws1 org-todo-sets)
4784 (setq org-done-keywords (append org-done-keywords dws nil))
4785 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4786 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4787 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4788 (setq org-todo-sets (nreverse org-todo-sets)
4789 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4790 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4791 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4792 ;; Process the constants
4793 (when const
4794 (let (e cst)
4795 (while (setq e (pop const))
4796 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4797 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4798 (setq org-table-formula-constants-local cst)))
4800 ;; Process the tags.
4801 (when tags
4802 (let (e tgs)
4803 (while (setq e (pop tags))
4804 (cond
4805 ((equal e "{") (push '(:startgroup) tgs))
4806 ((equal e "}") (push '(:endgroup) tgs))
4807 ((equal e "\\n") (push '(:newline) tgs))
4808 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4809 (push (cons (match-string 1 e)
4810 (string-to-char (match-string 2 e)))
4811 tgs))
4812 (t (push (list e) tgs))))
4813 (org-set-local 'org-tag-alist nil)
4814 (while (setq e (pop tgs))
4815 (or (and (stringp (car e))
4816 (assoc (car e) org-tag-alist))
4817 (push e org-tag-alist)))))
4819 ;; Compute the regular expressions and other local variables.
4820 ;; Using `org-outline-regexp-bol' would complicate them much,
4821 ;; because of the fixed white space at the end of that string.
4822 (if (not org-done-keywords)
4823 (setq org-done-keywords (and org-todo-keywords-1
4824 (list (org-last org-todo-keywords-1)))))
4825 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4826 (length org-scheduled-string)
4827 (length org-clock-string)
4828 (length org-closed-string)))
4829 org-drawer-regexp
4830 (concat "^[ \t]*:\\("
4831 (mapconcat 'regexp-quote org-drawers "\\|")
4832 "\\):[ \t]*$")
4833 org-not-done-keywords
4834 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4835 org-todo-regexp
4836 (concat "\\("
4837 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4838 "\\)")
4839 org-not-done-regexp
4840 (concat "\\("
4841 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4842 "\\)")
4843 org-not-done-heading-regexp
4844 (format org-heading-keyword-regexp-format org-not-done-regexp)
4845 org-todo-line-regexp
4846 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4847 org-complex-heading-regexp
4848 (concat "^\\(\\*+\\)"
4849 "\\(?: +" org-todo-regexp "\\)?"
4850 "\\(?: +\\(\\[#.\\]\\)\\)?"
4851 "\\(?: +\\(.*?\\)\\)??"
4852 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4853 "[ \t]*$")
4854 org-complex-heading-regexp-format
4855 (concat "^\\(\\*+\\)"
4856 "\\(?: +" org-todo-regexp "\\)?"
4857 "\\(?: +\\(\\[#.\\]\\)\\)?"
4858 "\\(?: +"
4859 ;; Stats cookies can be stuck to body.
4860 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4861 "\\(%s\\)"
4862 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4863 "\\)"
4864 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4865 "[ \t]*$")
4866 org-todo-line-tags-regexp
4867 (concat "^\\(\\*+\\)"
4868 "\\(?: +" org-todo-regexp "\\)?"
4869 "\\(?: +\\(.*?\\)\\)??"
4870 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4871 "[ \t]*$")
4872 org-deadline-regexp (concat "\\<" org-deadline-string)
4873 org-deadline-time-regexp
4874 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4875 org-deadline-line-regexp
4876 (concat "\\<\\(" org-deadline-string "\\).*")
4877 org-scheduled-regexp
4878 (concat "\\<" org-scheduled-string)
4879 org-scheduled-time-regexp
4880 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4881 org-closed-time-regexp
4882 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4883 org-keyword-time-regexp
4884 (concat "\\<\\(" org-scheduled-string
4885 "\\|" org-deadline-string
4886 "\\|" org-closed-string
4887 "\\|" org-clock-string "\\)"
4888 " *[[<]\\([^]>]+\\)[]>]")
4889 org-keyword-time-not-clock-regexp
4890 (concat "\\<\\(" org-scheduled-string
4891 "\\|" org-deadline-string
4892 "\\|" org-closed-string
4893 "\\)"
4894 " *[[<]\\([^]>]+\\)[]>]")
4895 org-maybe-keyword-time-regexp
4896 (concat "\\(\\<\\(" org-scheduled-string
4897 "\\|" org-deadline-string
4898 "\\|" org-closed-string
4899 "\\|" org-clock-string "\\)\\)?"
4900 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4901 org-all-time-keywords
4902 (mapcar (lambda (w) (substring w 0 -1))
4903 (list org-scheduled-string org-deadline-string
4904 org-clock-string org-closed-string)))
4905 (org-set-font-lock-defaults))))
4907 (defun org-file-contents (file &optional noerror)
4908 "Return the contents of FILE, as a string."
4909 (if (or (not file)
4910 (not (file-readable-p file)))
4911 (if noerror
4912 (progn
4913 (message "Cannot read file \"%s\"" file)
4914 (ding) (sit-for 2)
4916 (error "Cannot read file \"%s\"" file))
4917 (with-temp-buffer
4918 (insert-file-contents file)
4919 (buffer-string))))
4921 (defun org-extract-log-state-settings (x)
4922 "Extract the log state setting from a TODO keyword string.
4923 This will extract info from a string like \"WAIT(w@/!)\"."
4924 (let (kw key log1 log2)
4925 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4926 (setq kw (match-string 1 x)
4927 key (and (match-end 2) (match-string 2 x))
4928 log1 (and (match-end 3) (match-string 3 x))
4929 log2 (and (match-end 4) (match-string 4 x)))
4930 (and (or log1 log2)
4931 (list kw
4932 (and log1 (if (equal log1 "!") 'time 'note))
4933 (and log2 (if (equal log2 "!") 'time 'note)))))))
4935 (defun org-remove-keyword-keys (list)
4936 "Remove a pair of parenthesis at the end of each string in LIST."
4937 (mapcar (lambda (x)
4938 (if (string-match "(.*)$" x)
4939 (substring x 0 (match-beginning 0))
4941 list))
4943 (defun org-assign-fast-keys (alist)
4944 "Assign fast keys to a keyword-key alist.
4945 Respect keys that are already there."
4946 (let (new e (alt ?0))
4947 (while (setq e (pop alist))
4948 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4949 (cdr e)) ;; Key already assigned.
4950 (push e new)
4951 (let ((clist (string-to-list (downcase (car e))))
4952 (used (append new alist)))
4953 (when (= (car clist) ?@)
4954 (pop clist))
4955 (while (and clist (rassoc (car clist) used))
4956 (pop clist))
4957 (unless clist
4958 (while (rassoc alt used)
4959 (incf alt)))
4960 (push (cons (car e) (or (car clist) alt)) new))))
4961 (nreverse new)))
4963 ;;; Some variables used in various places
4965 (defvar org-window-configuration nil
4966 "Used in various places to store a window configuration.")
4967 (defvar org-selected-window nil
4968 "Used in various places to store a window configuration.")
4969 (defvar org-finish-function nil
4970 "Function to be called when `C-c C-c' is used.
4971 This is for getting out of special buffers like capture.")
4974 ;; FIXME: Occasionally check by commenting these, to make sure
4975 ;; no other functions uses these, forgetting to let-bind them.
4976 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4977 (defvar org-last-state)
4978 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4980 ;; Defined somewhere in this file, but used before definition.
4981 (defvar org-entities) ;; defined in org-entities.el
4982 (defvar org-struct-menu)
4983 (defvar org-org-menu)
4984 (defvar org-tbl-menu)
4986 ;;;; Define the Org-mode
4988 ;; We use a before-change function to check if a table might need
4989 ;; an update.
4990 (defvar org-table-may-need-update t
4991 "Indicates that a table might need an update.
4992 This variable is set by `org-before-change-function'.
4993 `org-table-align' sets it back to nil.")
4994 (defun org-before-change-function (beg end)
4995 "Every change indicates that a table might need an update."
4996 (setq org-table-may-need-update t))
4997 (defvar org-mode-map)
4998 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4999 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5000 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5001 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5002 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5003 (defvar org-table-buffer-is-an nil)
5005 (defvar bidi-paragraph-direction)
5006 (defvar buffer-face-mode-face)
5008 (require 'outline)
5009 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5010 (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"))
5011 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5013 ;; Other stuff we need.
5014 (require 'time-date)
5015 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5016 (require 'easymenu)
5017 (require 'overlay)
5019 ;; (require 'org-macs) moved higher up in the file before it is first used
5020 (require 'org-entities)
5021 ;; (require 'org-compat) moved higher up in the file before it is first used
5022 (require 'org-faces)
5023 (require 'org-list)
5024 (require 'org-pcomplete)
5025 (require 'org-src)
5026 (require 'org-footnote)
5028 ;; babel
5029 (require 'ob)
5031 ;;;###autoload
5032 (define-derived-mode org-mode outline-mode "Org"
5033 "Outline-based notes management and organizer, alias
5034 \"Carsten's outline-mode for keeping track of everything.\"
5036 Org-mode develops organizational tasks around a NOTES file which
5037 contains information about projects as plain text. Org-mode is
5038 implemented on top of outline-mode, which is ideal to keep the content
5039 of large files well structured. It supports ToDo items, deadlines and
5040 time stamps, which magically appear in the diary listing of the Emacs
5041 calendar. Tables are easily created with a built-in table editor.
5042 Plain text URL-like links connect to websites, emails (VM), Usenet
5043 messages (Gnus), BBDB entries, and any files related to the project.
5044 For printing and sharing of notes, an Org-mode file (or a part of it)
5045 can be exported as a structured ASCII or HTML file.
5047 The following commands are available:
5049 \\{org-mode-map}"
5051 ;; Get rid of Outline menus, they are not needed
5052 ;; Need to do this here because define-derived-mode sets up
5053 ;; the keymap so late. Still, it is a waste to call this each time
5054 ;; we switch another buffer into org-mode.
5055 (if (featurep 'xemacs)
5056 (when (boundp 'outline-mode-menu-heading)
5057 ;; Assume this is Greg's port, it uses easymenu
5058 (easy-menu-remove outline-mode-menu-heading)
5059 (easy-menu-remove outline-mode-menu-show)
5060 (easy-menu-remove outline-mode-menu-hide))
5061 (define-key org-mode-map [menu-bar headings] 'undefined)
5062 (define-key org-mode-map [menu-bar hide] 'undefined)
5063 (define-key org-mode-map [menu-bar show] 'undefined))
5065 (org-load-modules-maybe)
5066 (easy-menu-add org-org-menu)
5067 (easy-menu-add org-tbl-menu)
5068 (org-install-agenda-files-menu)
5069 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5070 (add-to-invisibility-spec '(org-cwidth))
5071 (add-to-invisibility-spec '(org-hide-block . t))
5072 (when (featurep 'xemacs)
5073 (org-set-local 'line-move-ignore-invisible t))
5074 (org-set-local 'outline-regexp org-outline-regexp)
5075 (org-set-local 'outline-level 'org-outline-level)
5076 (setq bidi-paragraph-direction 'left-to-right)
5077 (when (and org-ellipsis
5078 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5079 (fboundp 'make-glyph-code))
5080 (unless org-display-table
5081 (setq org-display-table (make-display-table)))
5082 (set-display-table-slot
5083 org-display-table 4
5084 (vconcat (mapcar
5085 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5086 org-ellipsis)))
5087 (if (stringp org-ellipsis) org-ellipsis "..."))))
5088 (setq buffer-display-table org-display-table))
5089 (org-set-regexps-and-options)
5090 (when (and org-tag-faces (not org-tags-special-faces-re))
5091 ;; tag faces set outside customize.... force initialization.
5092 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5093 ;; Calc embedded
5094 (org-set-local 'calc-embedded-open-mode "# ")
5095 (modify-syntax-entry ?@ "w")
5096 (modify-syntax-entry ?\" "\"")
5097 (if org-startup-truncated (setq truncate-lines t))
5098 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5099 (org-set-local 'font-lock-unfontify-region-function
5100 'org-unfontify-region)
5101 ;; Activate before-change-function
5102 (org-set-local 'org-table-may-need-update t)
5103 (org-add-hook 'before-change-functions 'org-before-change-function nil
5104 'local)
5105 ;; Check for running clock before killing a buffer
5106 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5107 ;; Initialize macros templates.
5108 (org-macro-initialize-templates)
5109 ;; Initialize radio targets.
5110 (org-update-radio-target-regexp)
5111 ;; Indentation.
5112 (org-set-local 'indent-line-function 'org-indent-line)
5113 (org-set-local 'indent-region-function 'org-indent-region)
5114 ;; Filling and auto-filling.
5115 (org-setup-filling)
5116 ;; Comments.
5117 (org-setup-comments-handling)
5118 ;; Beginning/end of defun
5119 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5120 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5121 ;; Next error for sparse trees
5122 (org-set-local 'next-error-function 'org-occur-next-match)
5123 ;; Make sure dependence stuff works reliably, even for users who set it
5124 ;; too late :-(
5125 (if org-enforce-todo-dependencies
5126 (add-hook 'org-blocker-hook
5127 'org-block-todo-from-children-or-siblings-or-parent)
5128 (remove-hook 'org-blocker-hook
5129 'org-block-todo-from-children-or-siblings-or-parent))
5130 (if org-enforce-todo-checkbox-dependencies
5131 (add-hook 'org-blocker-hook
5132 'org-block-todo-from-checkboxes)
5133 (remove-hook 'org-blocker-hook
5134 'org-block-todo-from-checkboxes))
5136 ;; Align options lines
5137 (org-set-local
5138 'align-mode-rules-list
5139 '((org-in-buffer-settings
5140 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5141 (modes . '(org-mode)))))
5143 ;; Imenu
5144 (org-set-local 'imenu-create-index-function
5145 'org-imenu-get-tree)
5147 ;; Make isearch reveal context
5148 (if (or (featurep 'xemacs)
5149 (not (boundp 'outline-isearch-open-invisible-function)))
5150 ;; Emacs 21 and XEmacs make use of the hook
5151 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5152 ;; Emacs 22 deals with this through a special variable
5153 (org-set-local 'outline-isearch-open-invisible-function
5154 (lambda (&rest ignore) (org-show-context 'isearch))))
5156 ;; Setup the pcomplete hooks
5157 (set (make-local-variable 'pcomplete-command-completion-function)
5158 'org-pcomplete-initial)
5159 (set (make-local-variable 'pcomplete-command-name-function)
5160 'org-command-at-point)
5161 (set (make-local-variable 'pcomplete-default-completion-function)
5162 'ignore)
5163 (set (make-local-variable 'pcomplete-parse-arguments-function)
5164 'org-parse-arguments)
5165 (set (make-local-variable 'pcomplete-termination-string) "")
5166 (when (>= emacs-major-version 23)
5167 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5169 ;; If empty file that did not turn on org-mode automatically, make it to.
5170 (if (and org-insert-mode-line-in-empty-file
5171 (org-called-interactively-p 'any)
5172 (= (point-min) (point-max)))
5173 (insert "# -*- mode: org -*-\n\n"))
5174 (unless org-inhibit-startup
5175 (and org-startup-with-beamer-mode (org-beamer-mode))
5176 (when org-startup-align-all-tables
5177 (let ((bmp (buffer-modified-p)))
5178 (org-table-map-tables 'org-table-align 'quietly)
5179 (set-buffer-modified-p bmp)))
5180 (when org-startup-with-inline-images
5181 (org-display-inline-images))
5182 (unless org-inhibit-startup-visibility-stuff
5183 (org-set-startup-visibility)))
5184 ;; Try to set org-hide correctly
5185 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5187 (when (fboundp 'abbrev-table-put)
5188 (abbrev-table-put org-mode-abbrev-table
5189 :parents (list text-mode-abbrev-table)))
5191 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5194 (defun org-find-invisible-foreground ()
5195 (let ((candidates (remove
5196 "unspecified-bg"
5197 (nconc
5198 (list (face-background 'default)
5199 (face-background 'org-default))
5200 (mapcar
5201 (lambda (alist)
5202 (when (boundp alist)
5203 (cdr (assoc 'background-color (symbol-value alist)))))
5204 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5205 (list (face-foreground 'org-hide))))))
5206 (car (remove nil candidates))))
5208 (defun org-current-time (&optional rounding-minutes)
5209 "Current time, possibly rounded to ROUNDING-MINUTES.
5210 When ROUNDING-MINUTES is not an integer, fall back on the car of
5211 `org-time-stamp-rounding-minutes'."
5212 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5213 (car org-time-stamp-rounding-minutes)))
5214 (time (decode-time)))
5215 (if (> r 1)
5216 (apply 'encode-time
5217 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5218 (nthcdr 2 time)))
5219 (current-time))))
5221 (defun org-today ()
5222 "Return today date, considering `org-extend-today-until'."
5223 (time-to-days
5224 (time-subtract (current-time)
5225 (list 0 (* 3600 org-extend-today-until) 0))))
5227 ;;;; Font-Lock stuff, including the activators
5229 (defvar org-mouse-map (make-sparse-keymap))
5230 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5231 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5232 (when org-mouse-1-follows-link
5233 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5234 (when org-tab-follows-link
5235 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5236 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5238 (require 'font-lock)
5240 (defconst org-non-link-chars "]\t\n\r<>")
5241 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5242 "shell" "elisp" "doi" "message"))
5243 (defvar org-link-types-re nil
5244 "Matches a link that has a url-like prefix like \"http:\"")
5245 (defvar org-link-re-with-space nil
5246 "Matches a link with spaces, optional angular brackets around it.")
5247 (defvar org-link-re-with-space2 nil
5248 "Matches a link with spaces, optional angular brackets around it.")
5249 (defvar org-link-re-with-space3 nil
5250 "Matches a link with spaces, only for internal part in bracket links.")
5251 (defvar org-angle-link-re nil
5252 "Matches link with angular brackets, spaces are allowed.")
5253 (defvar org-plain-link-re nil
5254 "Matches plain link, without spaces.")
5255 (defvar org-bracket-link-regexp nil
5256 "Matches a link in double brackets.")
5257 (defvar org-bracket-link-analytic-regexp nil
5258 "Regular expression used to analyze links.
5259 Here is what the match groups contain after a match:
5260 1: http:
5261 2: http
5262 3: path
5263 4: [desc]
5264 5: desc")
5265 (defvar org-bracket-link-analytic-regexp++ nil
5266 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5267 (defvar org-any-link-re nil
5268 "Regular expression matching any link.")
5270 (defconst org-match-sexp-depth 3
5271 "Number of stacked braces for sub/superscript matching.")
5273 (defun org-create-multibrace-regexp (left right n)
5274 "Create a regular expression which will match a balanced sexp.
5275 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5276 as single character strings.
5277 The regexp returned will match the entire expression including the
5278 delimiters. It will also define a single group which contains the
5279 match except for the outermost delimiters. The maximum depth of
5280 stacked delimiters is N. Escaping delimiters is not possible."
5281 (let* ((nothing (concat "[^" left right "]*?"))
5282 (or "\\|")
5283 (re nothing)
5284 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5285 (while (> n 1)
5286 (setq n (1- n)
5287 re (concat re or next)
5288 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5289 (concat left "\\(" re "\\)" right)))
5291 (defvar org-match-substring-regexp
5292 (concat
5293 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5294 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5295 "\\|"
5296 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5297 "\\|"
5298 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5299 "The regular expression matching a sub- or superscript.")
5301 (defvar org-match-substring-with-braces-regexp
5302 (concat
5303 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5304 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5305 "\\)")
5306 "The regular expression matching a sub- or superscript, forcing braces.")
5308 (defun org-make-link-regexps ()
5309 "Update the link regular expressions.
5310 This should be called after the variable `org-link-types' has changed."
5311 (setq org-link-types-re
5312 (concat
5313 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5314 org-link-re-with-space
5315 (concat
5316 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5317 "\\([^" org-non-link-chars " ]"
5318 "[^" org-non-link-chars "]*"
5319 "[^" org-non-link-chars " ]\\)>?")
5320 org-link-re-with-space2
5321 (concat
5322 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5323 "\\([^" org-non-link-chars " ]"
5324 "[^\t\n\r]*"
5325 "[^" org-non-link-chars " ]\\)>?")
5326 org-link-re-with-space3
5327 (concat
5328 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5329 "\\([^" org-non-link-chars " ]"
5330 "[^\t\n\r]*\\)")
5331 org-angle-link-re
5332 (concat
5333 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5334 "\\([^" org-non-link-chars " ]"
5335 "[^" org-non-link-chars "]*"
5336 "\\)>")
5337 org-plain-link-re
5338 (concat
5339 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5340 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5341 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5342 org-bracket-link-regexp
5343 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5344 org-bracket-link-analytic-regexp
5345 (concat
5346 "\\[\\["
5347 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5348 "\\([^]]+\\)"
5349 "\\]"
5350 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5351 "\\]")
5352 org-bracket-link-analytic-regexp++
5353 (concat
5354 "\\[\\["
5355 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5356 "\\([^]]+\\)"
5357 "\\]"
5358 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5359 "\\]")
5360 org-any-link-re
5361 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5362 org-angle-link-re "\\)\\|\\("
5363 org-plain-link-re "\\)")))
5365 (org-make-link-regexps)
5367 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5368 "Regular expression for fast time stamp matching.")
5369 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5370 "Regular expression for fast time stamp matching.")
5371 (defconst org-ts-regexp0
5372 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5373 "Regular expression matching time strings for analysis.
5374 This one does not require the space after the date, so it can be used
5375 on a string that terminates immediately after the date.")
5376 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5377 "Regular expression matching time strings for analysis.")
5378 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5379 "Regular expression matching time stamps, with groups.")
5380 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5381 "Regular expression matching time stamps (also [..]), with groups.")
5382 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5383 "Regular expression matching a time stamp range.")
5384 (defconst org-tr-regexp-both
5385 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5386 "Regular expression matching a time stamp range.")
5387 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5388 org-ts-regexp "\\)?")
5389 "Regular expression matching a time stamp or time stamp range.")
5390 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5391 org-ts-regexp-both "\\)?")
5392 "Regular expression matching a time stamp or time stamp range.
5393 The time stamps may be either active or inactive.")
5395 (defvar org-emph-face nil)
5397 (defun org-do-emphasis-faces (limit)
5398 "Run through the buffer and add overlays to emphasized strings."
5399 (let (rtn a)
5400 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5401 (if (not (= (char-after (match-beginning 3))
5402 (char-after (match-beginning 4))))
5403 (progn
5404 (setq rtn t)
5405 (setq a (assoc (match-string 3) org-emphasis-alist))
5406 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5407 'face
5408 (nth 1 a))
5409 (and (nth 4 a)
5410 (org-remove-flyspell-overlays-in
5411 (match-beginning 0) (match-end 0)))
5412 (add-text-properties (match-beginning 2) (match-end 2)
5413 '(font-lock-multiline t org-emphasis t))
5414 (when org-hide-emphasis-markers
5415 (add-text-properties (match-end 4) (match-beginning 5)
5416 '(invisible org-link))
5417 (add-text-properties (match-beginning 3) (match-end 3)
5418 '(invisible org-link)))))
5419 (backward-char 1))
5420 rtn))
5422 (defun org-emphasize (&optional char)
5423 "Insert or change an emphasis, i.e. a font like bold or italic.
5424 If there is an active region, change that region to a new emphasis.
5425 If there is no region, just insert the marker characters and position
5426 the cursor between them.
5427 CHAR should be either the marker character, or the first character of the
5428 HTML tag associated with that emphasis. If CHAR is a space, the means
5429 to remove the emphasis of the selected region.
5430 If char is not given (for example in an interactive call) it
5431 will be prompted for."
5432 (interactive)
5433 (let ((eal org-emphasis-alist) e det
5434 (erc org-emphasis-regexp-components)
5435 (prompt "")
5436 (string "") beg end move tag c s)
5437 (if (org-region-active-p)
5438 (setq beg (region-beginning) end (region-end)
5439 string (buffer-substring beg end))
5440 (setq move t))
5442 (while (setq e (pop eal))
5443 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5444 c (aref tag 0))
5445 (push (cons c (string-to-char (car e))) det)
5446 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5447 (substring tag 1)))))
5448 (setq det (nreverse det))
5449 (unless char
5450 (message "%s" (concat "Emphasis marker or tag:" prompt))
5451 (setq char (read-char-exclusive)))
5452 (setq char (or (cdr (assoc char det)) char))
5453 (if (equal char ?\ )
5454 (setq s "" move nil)
5455 (unless (assoc (char-to-string char) org-emphasis-alist)
5456 (error "No such emphasis marker: \"%c\"" char))
5457 (setq s (char-to-string char)))
5458 (while (and (> (length string) 1)
5459 (equal (substring string 0 1) (substring string -1))
5460 (assoc (substring string 0 1) org-emphasis-alist))
5461 (setq string (substring string 1 -1)))
5462 (setq string (concat s string s))
5463 (if beg (delete-region beg end))
5464 (unless (or (bolp)
5465 (string-match (concat "[" (nth 0 erc) "\n]")
5466 (char-to-string (char-before (point)))))
5467 (insert " "))
5468 (unless (or (eobp)
5469 (string-match (concat "[" (nth 1 erc) "\n]")
5470 (char-to-string (char-after (point)))))
5471 (insert " ") (backward-char 1))
5472 (insert string)
5473 (and move (backward-char 1))))
5475 (defconst org-nonsticky-props
5476 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5478 (defsubst org-rear-nonsticky-at (pos)
5479 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5481 (defun org-activate-plain-links (limit)
5482 "Run through the buffer and add overlays to links."
5483 (catch 'exit
5484 (let (f hl)
5485 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5486 (not (org-in-src-block-p)))
5487 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5488 (setq f (get-text-property (match-beginning 0) 'face))
5489 (setq hl (org-match-string-no-properties 0))
5490 (if (or (eq f 'org-tag)
5491 (and (listp f) (memq 'org-tag f)))
5493 (add-text-properties (match-beginning 0) (match-end 0)
5494 (list 'mouse-face 'highlight
5495 'face 'org-link
5496 'htmlize-link `(:uri ,hl)
5497 'keymap org-mouse-map))
5498 (org-rear-nonsticky-at (match-end 0)))
5499 t))))
5501 (defun org-activate-code (limit)
5502 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5503 (progn
5504 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5505 (remove-text-properties (match-beginning 0) (match-end 0)
5506 '(display t invisible t intangible t))
5507 t)))
5509 (defcustom org-src-fontify-natively nil
5510 "When non-nil, fontify code in code blocks."
5511 :type 'boolean
5512 :version "24.1"
5513 :group 'org-appearance
5514 :group 'org-babel)
5516 (defcustom org-allow-promoting-top-level-subtree nil
5517 "When non-nil, allow promoting a top level subtree.
5518 The leading star of the top level headline will be replaced
5519 by a #."
5520 :type 'boolean
5521 :version "24.1"
5522 :group 'org-appearance)
5524 (defun org-fontify-meta-lines-and-blocks (limit)
5525 (condition-case nil
5526 (org-fontify-meta-lines-and-blocks-1 limit)
5527 (error (message "org-mode fontification error"))))
5529 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5530 "Fontify #+ lines and blocks, in the correct ways."
5531 (let ((case-fold-search t))
5532 (if (re-search-forward
5533 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5534 limit t)
5535 (let ((beg (match-beginning 0))
5536 (block-start (match-end 0))
5537 (block-end nil)
5538 (lang (match-string 7))
5539 (beg1 (line-beginning-position 2))
5540 (dc1 (downcase (match-string 2)))
5541 (dc3 (downcase (match-string 3)))
5542 end end1 quoting block-type ovl)
5543 (cond
5544 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5545 ;; a single line of backend-specific content
5546 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5547 (remove-text-properties (match-beginning 0) (match-end 0)
5548 '(display t invisible t intangible t))
5549 (add-text-properties (match-beginning 1) (match-end 3)
5550 '(font-lock-fontified t face org-meta-line))
5551 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5552 '(font-lock-fontified t face org-block))
5553 ; for backend-specific code
5555 ((and (match-end 4) (equal dc3 "+begin"))
5556 ;; Truly a block
5557 (setq block-type (downcase (match-string 5))
5558 quoting (member block-type org-protecting-blocks))
5559 (when (re-search-forward
5560 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5561 nil t) ;; on purpose, we look further than LIMIT
5562 (setq end (min (point-max) (match-end 0))
5563 end1 (min (point-max) (1- (match-beginning 0))))
5564 (setq block-end (match-beginning 0))
5565 (when quoting
5566 (remove-text-properties beg end
5567 '(display t invisible t intangible t)))
5568 (add-text-properties
5569 beg end
5570 '(font-lock-fontified t font-lock-multiline t))
5571 (add-text-properties beg beg1 '(face org-meta-line))
5572 (add-text-properties end1 (min (point-max) (1+ end))
5573 '(face org-meta-line)) ; for end_src
5574 (cond
5575 ((and lang (not (string= lang "")) org-src-fontify-natively)
5576 (org-src-font-lock-fontify-block lang block-start block-end)
5577 ;; remove old background overlays
5578 (mapc (lambda (ov)
5579 (if (eq (overlay-get ov 'face) 'org-block-background)
5580 (delete-overlay ov)))
5581 (overlays-at (/ (+ beg1 block-end) 2)))
5582 ;; add a background overlay
5583 (setq ovl (make-overlay beg1 block-end))
5584 (overlay-put ovl 'face 'org-block-background)
5585 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5586 (quoting
5587 (add-text-properties beg1 (min (point-max) (1+ end1))
5588 '(face org-block))) ; end of source block
5589 ((not org-fontify-quote-and-verse-blocks))
5590 ((string= block-type "quote")
5591 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5592 ((string= block-type "verse")
5593 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5594 (add-text-properties beg beg1 '(face org-block-begin-line))
5595 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5596 '(face org-block-end-line))
5598 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5599 (add-text-properties
5600 beg (match-end 3)
5601 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5602 '(font-lock-fontified t invisible t)
5603 '(font-lock-fontified t face org-document-info-keyword)))
5604 (add-text-properties
5605 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5606 (if (string-equal dc1 "+title:")
5607 '(font-lock-fontified t face org-document-title)
5608 '(font-lock-fontified t face org-document-info))))
5609 ((or (equal dc1 "+results")
5610 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5611 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5612 "+call:" "+header:" "+headers:" "+name:"))
5613 (and (match-end 4) (equal dc3 "+attr")))
5614 (add-text-properties
5615 beg (match-end 0)
5616 '(font-lock-fontified t face org-meta-line))
5618 ((member dc3 '(" " ""))
5619 (add-text-properties
5620 beg (match-end 0)
5621 '(font-lock-fontified t face font-lock-comment-face)))
5622 ((not (member (char-after beg) '(?\ ?\t)))
5623 ;; just any other in-buffer setting, but not indented
5624 (add-text-properties
5625 beg (match-end 0)
5626 '(font-lock-fontified t face org-meta-line))
5628 (t nil))))))
5630 (defun org-activate-angle-links (limit)
5631 "Run through the buffer and add overlays to links."
5632 (if (and (re-search-forward org-angle-link-re limit t)
5633 (not (org-in-src-block-p)))
5634 (progn
5635 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5636 (add-text-properties (match-beginning 0) (match-end 0)
5637 (list 'mouse-face 'highlight
5638 'keymap org-mouse-map))
5639 (org-rear-nonsticky-at (match-end 0))
5640 t)))
5642 (defun org-activate-footnote-links (limit)
5643 "Run through the buffer and add overlays to footnotes."
5644 (let ((fn (org-footnote-next-reference-or-definition limit)))
5645 (when fn
5646 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5647 (org-remove-flyspell-overlays-in beg end)
5648 (add-text-properties beg end
5649 (list 'mouse-face 'highlight
5650 'keymap org-mouse-map
5651 'help-echo
5652 (if (= (point-at-bol) beg)
5653 "Footnote definition"
5654 "Footnote reference")
5655 'font-lock-fontified t
5656 'font-lock-multiline t
5657 'face 'org-footnote))))))
5659 (defun org-activate-bracket-links (limit)
5660 "Run through the buffer and add overlays to bracketed links."
5661 (if (and (re-search-forward org-bracket-link-regexp limit t)
5662 (not (org-in-src-block-p)))
5663 (let* ((hl (org-match-string-no-properties 1))
5664 (help (concat "LINK: " hl))
5665 ;; FIXME: Above we should remove the escapes. But that
5666 ;; requires another match, protecting match data, a lot
5667 ;; of overhead for font-lock.
5668 (ip (org-maybe-intangible
5669 (list 'invisible 'org-link
5670 'keymap org-mouse-map 'mouse-face 'highlight
5671 'font-lock-multiline t 'help-echo help
5672 'htmlize-link `(:uri ,hl))))
5673 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5674 'font-lock-multiline t 'help-echo help
5675 'htmlize-link `(:uri ,hl))))
5676 ;; We need to remove the invisible property here. Table narrowing
5677 ;; may have made some of this invisible.
5678 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5679 (remove-text-properties (match-beginning 0) (match-end 0)
5680 '(invisible nil))
5681 (if (match-end 3)
5682 (progn
5683 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5684 (org-rear-nonsticky-at (match-beginning 3))
5685 (add-text-properties (match-beginning 3) (match-end 3) vp)
5686 (org-rear-nonsticky-at (match-end 3))
5687 (add-text-properties (match-end 3) (match-end 0) ip)
5688 (org-rear-nonsticky-at (match-end 0)))
5689 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5690 (org-rear-nonsticky-at (match-beginning 1))
5691 (add-text-properties (match-beginning 1) (match-end 1) vp)
5692 (org-rear-nonsticky-at (match-end 1))
5693 (add-text-properties (match-end 1) (match-end 0) ip)
5694 (org-rear-nonsticky-at (match-end 0)))
5695 t)))
5697 (defun org-activate-dates (limit)
5698 "Run through the buffer and add overlays to dates."
5699 (if (re-search-forward org-tsr-regexp-both limit t)
5700 (progn
5701 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5702 (add-text-properties (match-beginning 0) (match-end 0)
5703 (list 'mouse-face 'highlight
5704 'keymap org-mouse-map))
5705 (org-rear-nonsticky-at (match-end 0))
5706 (when org-display-custom-times
5707 (if (match-end 3)
5708 (org-display-custom-time (match-beginning 3) (match-end 3)))
5709 (org-display-custom-time (match-beginning 1) (match-end 1)))
5710 t)))
5712 (defvar org-target-link-regexp nil
5713 "Regular expression matching radio targets in plain text.")
5714 (make-variable-buffer-local 'org-target-link-regexp)
5715 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5716 "Regular expression matching a link target.")
5717 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5718 "Regular expression matching a radio target.")
5719 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5720 "Regular expression matching any target.")
5722 (defun org-activate-target-links (limit)
5723 "Run through the buffer and add overlays to target matches."
5724 (when org-target-link-regexp
5725 (let ((case-fold-search t))
5726 (if (re-search-forward org-target-link-regexp limit t)
5727 (progn
5728 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5729 (add-text-properties (match-beginning 0) (match-end 0)
5730 (list 'mouse-face 'highlight
5731 'keymap org-mouse-map
5732 'help-echo "Radio target link"
5733 'org-linked-text t))
5734 (org-rear-nonsticky-at (match-end 0))
5735 t)))))
5737 (defun org-update-radio-target-regexp ()
5738 "Find all radio targets in this file and update the regular expression."
5739 (interactive)
5740 (when (memq 'radio org-activate-links)
5741 (setq org-target-link-regexp
5742 (org-make-target-link-regexp (org-all-targets 'radio)))
5743 (org-restart-font-lock)))
5745 (defun org-hide-wide-columns (limit)
5746 (let (s e)
5747 (setq s (text-property-any (point) (or limit (point-max))
5748 'org-cwidth t))
5749 (when s
5750 (setq e (next-single-property-change s 'org-cwidth))
5751 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5752 (goto-char e)
5753 t)))
5755 (defvar org-match-substring-regexp)
5756 (defvar org-match-substring-with-braces-regexp)
5758 (defun org-restart-font-lock ()
5759 "Restart `font-lock-mode', to force refontification."
5760 (when (and (boundp 'font-lock-mode) font-lock-mode)
5761 (font-lock-mode -1)
5762 (font-lock-mode 1)))
5764 (defun org-all-targets (&optional radio)
5765 "Return a list of all targets in this file.
5766 When optional argument RADIO is non-nil, only find radio
5767 targets."
5768 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5769 (save-excursion
5770 (goto-char (point-min))
5771 (while (re-search-forward re nil t)
5772 ;; Make sure point is really within the object.
5773 (backward-char)
5774 (let ((obj (org-element-context)))
5775 (when (memq (org-element-type obj) '(radio-target target))
5776 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5777 rtn)))
5779 (defun org-make-target-link-regexp (targets)
5780 "Make regular expression matching all strings in TARGETS.
5781 The regular expression finds the targets also if there is a line break
5782 between words."
5783 (and targets
5784 (concat
5785 "\\<\\("
5786 (mapconcat
5787 (lambda (x)
5788 (setq x (regexp-quote x))
5789 (while (string-match " +" x)
5790 (setq x (replace-match "\\s-+" t t x)))
5792 targets
5793 "\\|")
5794 "\\)\\>")))
5796 (defun org-activate-tags (limit)
5797 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5798 (progn
5799 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5800 (add-text-properties (match-beginning 1) (match-end 1)
5801 (list 'mouse-face 'highlight
5802 'keymap org-mouse-map))
5803 (org-rear-nonsticky-at (match-end 1))
5804 t)))
5806 (defun org-outline-level ()
5807 "Compute the outline level of the heading at point.
5808 If this is called at a normal headline, the level is the number of stars.
5809 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5810 (save-excursion
5811 (if (not (condition-case nil
5812 (org-back-to-heading t)
5813 (error nil)))
5815 (looking-at org-outline-regexp)
5816 (1- (- (match-end 0) (match-beginning 0))))))
5818 (defvar org-font-lock-keywords nil)
5820 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5821 "Regular expression matching a property line.")
5823 (defvar org-font-lock-hook nil
5824 "Functions to be called for special font lock stuff.")
5826 (defvar org-font-lock-set-keywords-hook nil
5827 "Functions that can manipulate `org-font-lock-extra-keywords'.
5828 This is called after `org-font-lock-extra-keywords' is defined, but before
5829 it is installed to be used by font lock. This can be useful if something
5830 needs to be inserted at a specific position in the font-lock sequence.")
5832 (defun org-font-lock-hook (limit)
5833 "Run `org-font-lock-hook' within LIMIT."
5834 (run-hook-with-args 'org-font-lock-hook limit))
5836 (defun org-set-font-lock-defaults ()
5837 "Set font lock defaults for the current buffer."
5838 (let* ((em org-fontify-emphasized-text)
5839 (lk org-activate-links)
5840 (org-font-lock-extra-keywords
5841 (list
5842 ;; Call the hook
5843 '(org-font-lock-hook)
5844 ;; Headlines
5845 `(,(if org-fontify-whole-heading-line
5846 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5847 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5848 (1 (org-get-level-face 1))
5849 (2 (org-get-level-face 2))
5850 (3 (org-get-level-face 3)))
5851 ;; Table lines
5852 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5853 (1 'org-table t))
5854 ;; Table internals
5855 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5856 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5857 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5858 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5859 ;; Drawers
5860 (list org-drawer-regexp '(0 'org-special-keyword t))
5861 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5862 ;; Properties
5863 (list org-property-re
5864 '(1 'org-special-keyword t)
5865 '(3 'org-property-value t))
5866 ;; Links
5867 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5868 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5869 (if (memq 'plain lk) '(org-activate-plain-links))
5870 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5871 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5872 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5873 (if (memq 'footnote lk) '(org-activate-footnote-links))
5874 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5875 '(org-hide-wide-columns (0 nil append))
5876 ;; TODO keyword
5877 (list (format org-heading-keyword-regexp-format
5878 org-todo-regexp)
5879 '(2 (org-get-todo-face 2) t))
5880 ;; DONE
5881 (if org-fontify-done-headline
5882 (list (format org-heading-keyword-regexp-format
5883 (concat
5884 "\\(?:"
5885 (mapconcat 'regexp-quote org-done-keywords "\\|")
5886 "\\)"))
5887 '(2 'org-headline-done t))
5888 nil)
5889 ;; Priorities
5890 '(org-font-lock-add-priority-faces)
5891 ;; Tags
5892 '(org-font-lock-add-tag-faces)
5893 ;; Special keywords
5894 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5895 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5896 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5897 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5898 ;; Emphasis
5899 (if em
5900 (if (featurep 'xemacs)
5901 '(org-do-emphasis-faces (0 nil append))
5902 '(org-do-emphasis-faces)))
5903 ;; Checkboxes
5904 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5905 1 'org-checkbox prepend)
5906 (if (cdr (assq 'checkbox org-list-automatic-rules))
5907 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5908 (0 (org-get-checkbox-statistics-face) t)))
5909 ;; Description list items
5910 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5911 1 'org-list-dt prepend)
5912 ;; ARCHIVEd headings
5913 (list (concat
5914 org-outline-regexp-bol
5915 "\\(.*:" org-archive-tag ":.*\\)")
5916 '(1 'org-archived prepend))
5917 ;; Specials
5918 '(org-fontify-entities)
5919 '(org-raise-scripts)
5920 ;; Code
5921 '(org-activate-code (1 'org-code t))
5922 ;; COMMENT
5923 (list (format org-heading-keyword-regexp-format
5924 (concat "\\("
5925 org-comment-string "\\|" org-quote-string
5926 "\\)"))
5927 '(2 'org-special-keyword t))
5928 ;; Blocks and meta lines
5929 '(org-fontify-meta-lines-and-blocks)
5931 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5932 (run-hooks 'org-font-lock-set-keywords-hook)
5933 ;; Now set the full font-lock-keywords
5934 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5935 (org-set-local 'font-lock-defaults
5936 '(org-font-lock-keywords t nil nil backward-paragraph))
5937 (kill-local-variable 'font-lock-keywords) nil))
5939 (defun org-toggle-pretty-entities ()
5940 "Toggle the composition display of entities as UTF8 characters."
5941 (interactive)
5942 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5943 (org-restart-font-lock)
5944 (if org-pretty-entities
5945 (message "Entities are displayed as UTF8 characters")
5946 (save-restriction
5947 (widen)
5948 (org-decompose-region (point-min) (point-max))
5949 (message "Entities are displayed plain"))))
5951 (defvar org-custom-properties-overlays nil
5952 "List of overlays used for custom properties.")
5953 (make-variable-buffer-local 'org-custom-properties-overlays)
5955 (defun org-toggle-custom-properties-visibility ()
5956 "Display or hide properties in `org-custom-properties'."
5957 (interactive)
5958 (if org-custom-properties-overlays
5959 (progn (mapc 'delete-overlay org-custom-properties-overlays)
5960 (setq org-custom-properties-overlays nil))
5961 (unless (not org-custom-properties)
5962 (save-excursion
5963 (save-restriction
5964 (widen)
5965 (goto-char (point-min))
5966 (while (re-search-forward org-property-re nil t)
5967 (mapc (lambda(p)
5968 (when (equal p (substring (match-string 1) 1 -1))
5969 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
5970 (overlay-put o 'invisible t)
5971 (overlay-put o 'org-custom-property t)
5972 (push o org-custom-properties-overlays))))
5973 org-custom-properties)))))))
5975 (defun org-fontify-entities (limit)
5976 "Find an entity to fontify."
5977 (let (ee)
5978 (when org-pretty-entities
5979 (catch 'match
5980 (while (re-search-forward
5981 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
5982 limit t)
5983 (if (and (not (org-in-indented-comment-line))
5984 (setq ee (org-entity-get (match-string 1)))
5985 (= (length (nth 6 ee)) 1))
5986 (let*
5987 ((end (if (equal (match-string 2) "{}")
5988 (match-end 2)
5989 (match-end 1))))
5990 (add-text-properties
5991 (match-beginning 0) end
5992 (list 'font-lock-fontified t))
5993 (compose-region (match-beginning 0) end
5994 (nth 6 ee) nil)
5995 (backward-char 1)
5996 (throw 'match t))))
5997 nil))))
5999 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6000 "Fontify string S like in Org-mode."
6001 (with-temp-buffer
6002 (insert s)
6003 (let ((org-odd-levels-only odd-levels))
6004 (org-mode)
6005 (font-lock-fontify-buffer)
6006 (buffer-string))))
6008 (defvar org-m nil)
6009 (defvar org-l nil)
6010 (defvar org-f nil)
6011 (defun org-get-level-face (n)
6012 "Get the right face for match N in font-lock matching of headlines."
6013 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6014 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6015 (if org-cycle-level-faces
6016 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6017 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6018 (cond
6019 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6020 ((eq n 2) org-f)
6021 (t (if org-level-color-stars-only nil org-f))))
6024 (defun org-get-todo-face (kwd)
6025 "Get the right face for a TODO keyword KWD.
6026 If KWD is a number, get the corresponding match group."
6027 (if (numberp kwd) (setq kwd (match-string kwd)))
6028 (or (org-face-from-face-or-color
6029 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6030 (and (member kwd org-done-keywords) 'org-done)
6031 'org-todo))
6033 (defun org-face-from-face-or-color (context inherit face-or-color)
6034 "Create a face list that inherits INHERIT, but sets the foreground color.
6035 When FACE-OR-COLOR is not a string, just return it."
6036 (if (stringp face-or-color)
6037 (list :inherit inherit
6038 (cdr (assoc context org-faces-easy-properties))
6039 face-or-color)
6040 face-or-color))
6042 (defun org-font-lock-add-tag-faces (limit)
6043 "Add the special tag faces."
6044 (when (and org-tag-faces org-tags-special-faces-re)
6045 (while (re-search-forward org-tags-special-faces-re limit t)
6046 (add-text-properties (match-beginning 1) (match-end 1)
6047 (list 'face (org-get-tag-face 1)
6048 'font-lock-fontified t))
6049 (backward-char 1))))
6051 (defun org-font-lock-add-priority-faces (limit)
6052 "Add the special priority faces."
6053 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6054 (when (save-match-data (org-at-heading-p))
6055 (add-text-properties
6056 (match-beginning 0) (match-end 0)
6057 (list 'face (or (org-face-from-face-or-color
6058 'priority 'org-priority
6059 (cdr (assoc (char-after (match-beginning 1))
6060 org-priority-faces)))
6061 'org-priority)
6062 'font-lock-fontified t)))))
6064 (defun org-get-tag-face (kwd)
6065 "Get the right face for a TODO keyword KWD.
6066 If KWD is a number, get the corresponding match group."
6067 (if (numberp kwd) (setq kwd (match-string kwd)))
6068 (or (org-face-from-face-or-color
6069 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6070 'org-tag))
6072 (defun org-unfontify-region (beg end &optional maybe_loudly)
6073 "Remove fontification and activation overlays from links."
6074 (font-lock-default-unfontify-region beg end)
6075 (let* ((buffer-undo-list t)
6076 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6077 (inhibit-modification-hooks t)
6078 deactivate-mark buffer-file-name buffer-file-truename)
6079 (org-decompose-region beg end)
6080 (remove-text-properties beg end
6081 '(mouse-face t keymap t org-linked-text t
6082 invisible t intangible t
6083 org-no-flyspell t org-emphasis t))
6084 (org-remove-font-lock-display-properties beg end)))
6086 (defconst org-script-display '(((raise -0.3) (height 0.7))
6087 ((raise 0.3) (height 0.7))
6088 ((raise -0.5))
6089 ((raise 0.5)))
6090 "Display properties for showing superscripts and subscripts.")
6092 (defun org-remove-font-lock-display-properties (beg end)
6093 "Remove specific display properties that have been added by font lock.
6094 The will remove the raise properties that are used to show superscripts
6095 and subscripts."
6096 (let (next prop)
6097 (while (< beg end)
6098 (setq next (next-single-property-change beg 'display nil end)
6099 prop (get-text-property beg 'display))
6100 (if (member prop org-script-display)
6101 (put-text-property beg next 'display nil))
6102 (setq beg next))))
6104 (defun org-raise-scripts (limit)
6105 "Add raise properties to sub/superscripts."
6106 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6107 (if (re-search-forward
6108 (if (eq org-use-sub-superscripts t)
6109 org-match-substring-regexp
6110 org-match-substring-with-braces-regexp)
6111 limit t)
6112 (let* ((pos (point)) table-p comment-p
6113 (mpos (match-beginning 3))
6114 (emph-p (get-text-property mpos 'org-emphasis))
6115 (link-p (get-text-property mpos 'mouse-face))
6116 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6117 (goto-char (point-at-bol))
6118 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6119 comment-p (org-looking-at-p "[ \t]*#"))
6120 (goto-char pos)
6121 ;; FIXME: Should we go back one character here, for a_b^c
6122 ;; (goto-char (1- pos)) ;????????????????????
6123 (if (or comment-p emph-p link-p keyw-p)
6125 (put-text-property (match-beginning 3) (match-end 0)
6126 'display
6127 (if (equal (char-after (match-beginning 2)) ?^)
6128 (nth (if table-p 3 1) org-script-display)
6129 (nth (if table-p 2 0) org-script-display)))
6130 (add-text-properties (match-beginning 2) (match-end 2)
6131 (list 'invisible t
6132 'org-dwidth t 'org-dwidth-n 1))
6133 (if (and (eq (char-after (match-beginning 3)) ?{)
6134 (eq (char-before (match-end 3)) ?}))
6135 (progn
6136 (add-text-properties
6137 (match-beginning 3) (1+ (match-beginning 3))
6138 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6139 (add-text-properties
6140 (1- (match-end 3)) (match-end 3)
6141 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6142 t)))))
6144 ;;;; Visibility cycling, including org-goto and indirect buffer
6146 ;;; Cycling
6148 (defvar org-cycle-global-status nil)
6149 (make-variable-buffer-local 'org-cycle-global-status)
6150 (defvar org-cycle-subtree-status nil)
6151 (make-variable-buffer-local 'org-cycle-subtree-status)
6153 (defvar org-inlinetask-min-level)
6155 ;;;###autoload
6156 (defun org-cycle (&optional arg)
6157 "TAB-action and visibility cycling for Org-mode.
6159 This is the command invoked in Org-mode by the TAB key. Its main purpose
6160 is outline visibility cycling, but it also invokes other actions
6161 in special contexts.
6163 - When this function is called with a prefix argument, rotate the entire
6164 buffer through 3 states (global cycling)
6165 1. OVERVIEW: Show only top-level headlines.
6166 2. CONTENTS: Show all headlines of all levels, but no body text.
6167 3. SHOW ALL: Show everything.
6168 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6169 determined by the variable `org-startup-folded', and by any VISIBILITY
6170 properties in the buffer.
6171 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6172 including any drawers.
6174 - When inside a table, re-align the table and move to the next field.
6176 - When point is at the beginning of a headline, rotate the subtree started
6177 by this line through 3 different states (local cycling)
6178 1. FOLDED: Only the main headline is shown.
6179 2. CHILDREN: The main headline and the direct children are shown.
6180 From this state, you can move to one of the children
6181 and zoom in further.
6182 3. SUBTREE: Show the entire subtree, including body text.
6183 If there is no subtree, switch directly from CHILDREN to FOLDED.
6185 - When point is at the beginning of an empty headline and the variable
6186 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6187 of the headline by demoting and promoting it to likely levels. This
6188 speeds up creation document structure by pressing TAB once or several
6189 times right after creating a new headline.
6191 - When there is a numeric prefix, go up to a heading with level ARG, do
6192 a `show-subtree' and return to the previous cursor position. If ARG
6193 is negative, go up that many levels.
6195 - When point is not at the beginning of a headline, execute the global
6196 binding for TAB, which is re-indenting the line. See the option
6197 `org-cycle-emulate-tab' for details.
6199 - Special case: if point is at the beginning of the buffer and there is
6200 no headline in line 1, this function will act as if called with prefix arg
6201 (C-u TAB, same as S-TAB) also when called without prefix arg.
6202 But only if also the variable `org-cycle-global-at-bob' is t."
6203 (interactive "P")
6204 (org-load-modules-maybe)
6205 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6206 (and org-cycle-level-after-item/entry-creation
6207 (or (org-cycle-level)
6208 (org-cycle-item-indentation))))
6209 (let* (message-log-max ; Don't populate the *Messages* buffer
6210 (limit-level
6211 (or org-cycle-max-level
6212 (and (boundp 'org-inlinetask-min-level)
6213 org-inlinetask-min-level
6214 (1- org-inlinetask-min-level))))
6215 (nstars (and limit-level
6216 (if org-odd-levels-only
6217 (and limit-level (1- (* limit-level 2)))
6218 limit-level)))
6219 (org-outline-regexp
6220 (if (not (derived-mode-p 'org-mode))
6221 outline-regexp
6222 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6223 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6224 (not (looking-at org-outline-regexp))))
6225 (org-cycle-hook
6226 (if bob-special
6227 (delq 'org-optimize-window-after-visibility-change
6228 (copy-sequence org-cycle-hook))
6229 org-cycle-hook))
6230 (pos (point)))
6232 (if (or bob-special (equal arg '(4)))
6233 ;; special case: use global cycling
6234 (setq arg t))
6236 (cond
6238 ((equal arg '(16))
6239 (setq last-command 'dummy)
6240 (org-set-startup-visibility)
6241 (message "Startup visibility, plus VISIBILITY properties"))
6243 ((equal arg '(64))
6244 (show-all)
6245 (message "Entire buffer visible, including drawers"))
6247 ;; Table: enter it or move to the next field.
6248 ((org-at-table-p 'any)
6249 (if (org-at-table.el-p)
6250 (message "Use C-c ' to edit table.el tables")
6251 (if arg (org-table-edit-field t)
6252 (org-table-justify-field-maybe)
6253 (call-interactively 'org-table-next-field))))
6255 ((run-hook-with-args-until-success
6256 'org-tab-after-check-for-table-hook))
6258 ;; Global cycling: delegate to `org-cycle-internal-global'.
6259 ((eq arg t) (org-cycle-internal-global))
6261 ;; Drawers: delegate to `org-flag-drawer'.
6262 ((and org-drawers org-drawer-regexp
6263 (save-excursion
6264 (beginning-of-line 1)
6265 (looking-at org-drawer-regexp)))
6266 (org-flag-drawer ; toggle block visibility
6267 (not (get-char-property (match-end 0) 'invisible))))
6269 ;; Show-subtree, ARG levels up from here.
6270 ((integerp arg)
6271 (save-excursion
6272 (org-back-to-heading)
6273 (outline-up-heading (if (< arg 0) (- arg)
6274 (- (funcall outline-level) arg)))
6275 (org-show-subtree)))
6277 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6278 ((and (featurep 'org-inlinetask)
6279 (org-inlinetask-at-task-p)
6280 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6281 (org-inlinetask-toggle-visibility))
6283 ((org-try-cdlatex-tab))
6285 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6286 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6287 (save-excursion (beginning-of-line 1)
6288 (looking-at org-outline-regexp)))
6289 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6290 (org-cycle-internal-local))
6292 ;; From there: TAB emulation and template completion.
6293 (buffer-read-only (org-back-to-heading))
6295 ((run-hook-with-args-until-success
6296 'org-tab-after-check-for-cycling-hook))
6298 ((org-try-structure-completion))
6300 ((run-hook-with-args-until-success
6301 'org-tab-before-tab-emulation-hook))
6303 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6304 (or (not (bolp))
6305 (not (looking-at org-outline-regexp))))
6306 (call-interactively (global-key-binding "\t")))
6308 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6309 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6310 (or (and (eq org-cycle-emulate-tab 'white)
6311 (= (match-end 0) (point-at-eol)))
6312 (and (eq org-cycle-emulate-tab 'whitestart)
6313 (>= (match-end 0) pos))))
6315 (eq org-cycle-emulate-tab t))
6316 (call-interactively (global-key-binding "\t")))
6318 (t (save-excursion
6319 (org-back-to-heading)
6320 (org-cycle)))))))
6322 (defun org-cycle-internal-global ()
6323 "Do the global cycling action."
6324 ;; Hack to avoid display of messages for .org attachments in Gnus
6325 (let (message-log-max ; Don't populate the *Messages* buffer
6326 (ga (string-match "\\*fontification" (buffer-name))))
6327 (cond
6328 ((and (eq last-command this-command)
6329 (eq org-cycle-global-status 'overview))
6330 ;; We just created the overview - now do table of contents
6331 ;; This can be slow in very large buffers, so indicate action
6332 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6333 (unless ga (message "CONTENTS..."))
6334 (org-content)
6335 (unless ga (message "CONTENTS...done"))
6336 (setq org-cycle-global-status 'contents)
6337 (run-hook-with-args 'org-cycle-hook 'contents))
6339 ((and (eq last-command this-command)
6340 (eq org-cycle-global-status 'contents))
6341 ;; We just showed the table of contents - now show everything
6342 (run-hook-with-args 'org-pre-cycle-hook 'all)
6343 (show-all)
6344 (unless ga (message "SHOW ALL"))
6345 (setq org-cycle-global-status 'all)
6346 (run-hook-with-args 'org-cycle-hook 'all))
6349 ;; Default action: go to overview
6350 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6351 (org-overview)
6352 (unless ga (message "OVERVIEW"))
6353 (setq org-cycle-global-status 'overview)
6354 (run-hook-with-args 'org-cycle-hook 'overview)))))
6356 (defun org-cycle-internal-local ()
6357 "Do the local cycling action."
6358 (let (message-log-max ; Don't populate the *Messages* buffer
6359 (goal-column 0) eoh eol eos has-children children-skipped struct)
6360 ;; First, determine end of headline (EOH), end of subtree or item
6361 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6362 (save-excursion
6363 (if (org-at-item-p)
6364 (progn
6365 (beginning-of-line)
6366 (setq struct (org-list-struct))
6367 (setq eoh (point-at-eol))
6368 (setq eos (org-list-get-item-end-before-blank (point) struct))
6369 (setq has-children (org-list-has-child-p (point) struct)))
6370 (org-back-to-heading)
6371 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6372 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6373 (setq has-children
6374 (or (save-excursion
6375 (let ((level (funcall outline-level)))
6376 (outline-next-heading)
6377 (and (org-at-heading-p t)
6378 (> (funcall outline-level) level))))
6379 (save-excursion
6380 (org-list-search-forward (org-item-beginning-re) eos t)))))
6381 ;; Determine end invisible part of buffer (EOL)
6382 (beginning-of-line 2)
6383 ;; XEmacs doesn't have `next-single-char-property-change'
6384 (if (featurep 'xemacs)
6385 (while (and (not (eobp)) ;; this is like `next-line'
6386 (get-char-property (1- (point)) 'invisible))
6387 (beginning-of-line 2))
6388 (while (and (not (eobp)) ;; this is like `next-line'
6389 (get-char-property (1- (point)) 'invisible))
6390 (goto-char (next-single-char-property-change (point) 'invisible))
6391 (and (eolp) (beginning-of-line 2))))
6392 (setq eol (point)))
6393 ;; Find out what to do next and set `this-command'
6394 (cond
6395 ((= eos eoh)
6396 ;; Nothing is hidden behind this heading
6397 (unless (org-before-first-heading-p)
6398 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6399 (message "EMPTY ENTRY")
6400 (setq org-cycle-subtree-status nil)
6401 (save-excursion
6402 (goto-char eos)
6403 (outline-next-heading)
6404 (if (outline-invisible-p) (org-flag-heading nil))))
6405 ((and (or (>= eol eos)
6406 (not (string-match "\\S-" (buffer-substring eol eos))))
6407 (or has-children
6408 (not (setq children-skipped
6409 org-cycle-skip-children-state-if-no-children))))
6410 ;; Entire subtree is hidden in one line: children view
6411 (unless (org-before-first-heading-p)
6412 (run-hook-with-args 'org-pre-cycle-hook 'children))
6413 (if (org-at-item-p)
6414 (org-list-set-item-visibility (point-at-bol) struct 'children)
6415 (org-show-entry)
6416 (org-with-limited-levels (show-children))
6417 ;; FIXME: This slows down the func way too much.
6418 ;; How keep drawers hidden in subtree anyway?
6419 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6420 ;; (org-cycle-hide-drawers 'subtree))
6422 ;; Fold every list in subtree to top-level items.
6423 (when (eq org-cycle-include-plain-lists 'integrate)
6424 (save-excursion
6425 (org-back-to-heading)
6426 (while (org-list-search-forward (org-item-beginning-re) eos t)
6427 (beginning-of-line 1)
6428 (let* ((struct (org-list-struct))
6429 (prevs (org-list-prevs-alist struct))
6430 (end (org-list-get-bottom-point struct)))
6431 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6432 (org-list-get-all-items (point) struct prevs))
6433 (goto-char end))))))
6434 (message "CHILDREN")
6435 (save-excursion
6436 (goto-char eos)
6437 (outline-next-heading)
6438 (if (outline-invisible-p) (org-flag-heading nil)))
6439 (setq org-cycle-subtree-status 'children)
6440 (unless (org-before-first-heading-p)
6441 (run-hook-with-args 'org-cycle-hook 'children)))
6442 ((or children-skipped
6443 (and (eq last-command this-command)
6444 (eq org-cycle-subtree-status 'children)))
6445 ;; We just showed the children, or no children are there,
6446 ;; now show everything.
6447 (unless (org-before-first-heading-p)
6448 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6449 (outline-flag-region eoh eos nil)
6450 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6451 (setq org-cycle-subtree-status 'subtree)
6452 (unless (org-before-first-heading-p)
6453 (run-hook-with-args 'org-cycle-hook 'subtree)))
6455 ;; Default action: hide the subtree.
6456 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6457 (outline-flag-region eoh eos t)
6458 (message "FOLDED")
6459 (setq org-cycle-subtree-status 'folded)
6460 (unless (org-before-first-heading-p)
6461 (run-hook-with-args 'org-cycle-hook 'folded))))))
6463 ;;;###autoload
6464 (defun org-global-cycle (&optional arg)
6465 "Cycle the global visibility. For details see `org-cycle'.
6466 With \\[universal-argument] prefix arg, switch to startup visibility.
6467 With a numeric prefix, show all headlines up to that level."
6468 (interactive "P")
6469 (let ((org-cycle-include-plain-lists
6470 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6471 (cond
6472 ((integerp arg)
6473 (show-all)
6474 (hide-sublevels arg)
6475 (setq org-cycle-global-status 'contents))
6476 ((equal arg '(4))
6477 (org-set-startup-visibility)
6478 (message "Startup visibility, plus VISIBILITY properties."))
6480 (org-cycle '(4))))))
6482 (defun org-set-startup-visibility ()
6483 "Set the visibility required by startup options and properties."
6484 (cond
6485 ((eq org-startup-folded t)
6486 (org-cycle '(4)))
6487 ((eq org-startup-folded 'content)
6488 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6489 (org-cycle '(4)) (org-cycle '(4)))))
6490 (unless (eq org-startup-folded 'showeverything)
6491 (if org-hide-block-startup (org-hide-block-all))
6492 (org-set-visibility-according-to-property 'no-cleanup)
6493 (org-cycle-hide-archived-subtrees 'all)
6494 (org-cycle-hide-drawers 'all)
6495 (org-cycle-show-empty-lines t)))
6497 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6498 "Switch subtree visibilities according to :VISIBILITY: property."
6499 (interactive)
6500 (let (org-show-entry-below state)
6501 (save-excursion
6502 (goto-char (point-min))
6503 (while (re-search-forward
6504 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6505 nil t)
6506 (setq state (match-string 1))
6507 (save-excursion
6508 (org-back-to-heading t)
6509 (hide-subtree)
6510 (org-reveal)
6511 (cond
6512 ((equal state '("fold" "folded"))
6513 (hide-subtree))
6514 ((equal state "children")
6515 (org-show-hidden-entry)
6516 (show-children))
6517 ((equal state "content")
6518 (save-excursion
6519 (save-restriction
6520 (org-narrow-to-subtree)
6521 (org-content))))
6522 ((member state '("all" "showall"))
6523 (show-subtree)))))
6524 (unless no-cleanup
6525 (org-cycle-hide-archived-subtrees 'all)
6526 (org-cycle-hide-drawers 'all)
6527 (org-cycle-show-empty-lines 'all)))))
6529 ;; This function uses outline-regexp instead of the more fundamental
6530 ;; org-outline-regexp so that org-cycle-global works outside of Org
6531 ;; buffers, where outline-regexp is needed.
6532 (defun org-overview ()
6533 "Switch to overview mode, showing only top-level headlines.
6534 Really, this shows all headlines with level equal or greater than the level
6535 of the first headline in the buffer. This is important, because if the
6536 first headline is not level one, then (hide-sublevels 1) gives confusing
6537 results."
6538 (interactive)
6539 (let ((level (save-excursion
6540 (goto-char (point-min))
6541 (if (re-search-forward (concat "^" outline-regexp) nil t)
6542 (progn
6543 (goto-char (match-beginning 0))
6544 (funcall outline-level))))))
6545 (and level (hide-sublevels level))))
6547 (defun org-content (&optional arg)
6548 "Show all headlines in the buffer, like a table of contents.
6549 With numerical argument N, show content up to level N."
6550 (interactive "P")
6551 (save-excursion
6552 ;; Visit all headings and show their offspring
6553 (and (integerp arg) (org-overview))
6554 (goto-char (point-max))
6555 (catch 'exit
6556 (while (and (progn (condition-case nil
6557 (outline-previous-visible-heading 1)
6558 (error (goto-char (point-min))))
6560 (looking-at org-outline-regexp))
6561 (if (integerp arg)
6562 (show-children (1- arg))
6563 (show-branches))
6564 (if (bobp) (throw 'exit nil))))))
6567 (defun org-optimize-window-after-visibility-change (state)
6568 "Adjust the window after a change in outline visibility.
6569 This function is the default value of the hook `org-cycle-hook'."
6570 (when (get-buffer-window (current-buffer))
6571 (cond
6572 ((eq state 'content) nil)
6573 ((eq state 'all) nil)
6574 ((eq state 'folded) nil)
6575 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6576 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6578 (defun org-remove-empty-overlays-at (pos)
6579 "Remove outline overlays that do not contain non-white stuff."
6580 (mapc
6581 (lambda (o)
6582 (and (eq 'outline (overlay-get o 'invisible))
6583 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6584 (overlay-end o))))
6585 (delete-overlay o)))
6586 (overlays-at pos)))
6588 (defun org-clean-visibility-after-subtree-move ()
6589 "Fix visibility issues after moving a subtree."
6590 ;; First, find a reasonable region to look at:
6591 ;; Start two siblings above, end three below
6592 (let* ((beg (save-excursion
6593 (and (org-get-last-sibling)
6594 (org-get-last-sibling))
6595 (point)))
6596 (end (save-excursion
6597 (and (org-get-next-sibling)
6598 (org-get-next-sibling)
6599 (org-get-next-sibling))
6600 (if (org-at-heading-p)
6601 (point-at-eol)
6602 (point))))
6603 (level (looking-at "\\*+"))
6604 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6605 (save-excursion
6606 (save-restriction
6607 (narrow-to-region beg end)
6608 (when re
6609 ;; Properly fold already folded siblings
6610 (goto-char (point-min))
6611 (while (re-search-forward re nil t)
6612 (if (and (not (outline-invisible-p))
6613 (save-excursion
6614 (goto-char (point-at-eol)) (outline-invisible-p)))
6615 (hide-entry))))
6616 (org-cycle-show-empty-lines 'overview)
6617 (org-cycle-hide-drawers 'overview)))))
6619 (defun org-cycle-show-empty-lines (state)
6620 "Show empty lines above all visible headlines.
6621 The region to be covered depends on STATE when called through
6622 `org-cycle-hook'. Lisp program can use t for STATE to get the
6623 entire buffer covered. Note that an empty line is only shown if there
6624 are at least `org-cycle-separator-lines' empty lines before the headline."
6625 (when (not (= org-cycle-separator-lines 0))
6626 (save-excursion
6627 (let* ((n (abs org-cycle-separator-lines))
6628 (re (cond
6629 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6630 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6631 (t (let ((ns (number-to-string (- n 2))))
6632 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6633 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6634 beg end b e)
6635 (cond
6636 ((memq state '(overview contents t))
6637 (setq beg (point-min) end (point-max)))
6638 ((memq state '(children folded))
6639 (setq beg (point) end (progn (org-end-of-subtree t t)
6640 (beginning-of-line 2)
6641 (point)))))
6642 (when beg
6643 (goto-char beg)
6644 (while (re-search-forward re end t)
6645 (unless (get-char-property (match-end 1) 'invisible)
6646 (setq e (match-end 1))
6647 (if (< org-cycle-separator-lines 0)
6648 (setq b (save-excursion
6649 (goto-char (match-beginning 0))
6650 (org-back-over-empty-lines)
6651 (if (save-excursion
6652 (goto-char (max (point-min) (1- (point))))
6653 (org-at-heading-p))
6654 (1- (point))
6655 (point))))
6656 (setq b (match-beginning 1)))
6657 (outline-flag-region b e nil)))))))
6658 ;; Never hide empty lines at the end of the file.
6659 (save-excursion
6660 (goto-char (point-max))
6661 (outline-previous-heading)
6662 (outline-end-of-heading)
6663 (if (and (looking-at "[ \t\n]+")
6664 (= (match-end 0) (point-max)))
6665 (outline-flag-region (point) (match-end 0) nil))))
6667 (defun org-show-empty-lines-in-parent ()
6668 "Move to the parent and re-show empty lines before visible headlines."
6669 (save-excursion
6670 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6671 (org-cycle-show-empty-lines context))))
6673 (defun org-files-list ()
6674 "Return `org-agenda-files' list, plus all open org-mode files.
6675 This is useful for operations that need to scan all of a user's
6676 open and agenda-wise Org files."
6677 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6678 (dolist (buf (buffer-list))
6679 (with-current-buffer buf
6680 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6681 (let ((file (expand-file-name (buffer-file-name))))
6682 (unless (member file files)
6683 (push file files))))))
6684 files))
6686 (defsubst org-entry-beginning-position ()
6687 "Return the beginning position of the current entry."
6688 (save-excursion (outline-back-to-heading t) (point)))
6690 (defsubst org-entry-end-position ()
6691 "Return the end position of the current entry."
6692 (save-excursion (outline-next-heading) (point)))
6694 (defun org-cycle-hide-drawers (state)
6695 "Re-hide all drawers after a visibility state change."
6696 (when (and (derived-mode-p 'org-mode)
6697 (not (memq state '(overview folded contents))))
6698 (save-excursion
6699 (let* ((globalp (memq state '(contents all)))
6700 (beg (if globalp (point-min) (point)))
6701 (end (if globalp (point-max)
6702 (if (eq state 'children)
6703 (save-excursion (outline-next-heading) (point))
6704 (org-end-of-subtree t)))))
6705 (goto-char beg)
6706 (while (re-search-forward org-drawer-regexp end t)
6707 (org-flag-drawer t))))))
6709 (defun org-cycle-hide-inline-tasks (state)
6710 "Re-hide inline task when switching to 'contents visibility state."
6711 (when (and (eq state 'contents)
6712 (boundp 'org-inlinetask-min-level)
6713 org-inlinetask-min-level)
6714 (hide-sublevels (1- org-inlinetask-min-level))))
6716 (defun org-flag-drawer (flag)
6717 "When FLAG is non-nil, hide the drawer we are within.
6718 Otherwise make it visible."
6719 (save-excursion
6720 (beginning-of-line 1)
6721 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6722 (let ((b (match-end 0)))
6723 (if (re-search-forward
6724 "^[ \t]*:END:"
6725 (save-excursion (outline-next-heading) (point)) t)
6726 (outline-flag-region b (point-at-eol) flag)
6727 (error ":END: line missing at position %s" b))))))
6729 (defun org-subtree-end-visible-p ()
6730 "Is the end of the current subtree visible?"
6731 (pos-visible-in-window-p
6732 (save-excursion (org-end-of-subtree t) (point))))
6734 (defun org-first-headline-recenter (&optional N)
6735 "Move cursor to the first headline and recenter the headline.
6736 Optional argument N means put the headline into the Nth line of the window."
6737 (goto-char (point-min))
6738 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6739 (beginning-of-line)
6740 (recenter (prefix-numeric-value N))))
6742 ;;; Saving and restoring visibility
6744 (defun org-outline-overlay-data (&optional use-markers)
6745 "Return a list of the locations of all outline overlays.
6746 These are overlays with the `invisible' property value `outline'.
6747 The return value is a list of cons cells, with start and stop
6748 positions for each overlay.
6749 If USE-MARKERS is set, return the positions as markers."
6750 (let (beg end)
6751 (save-excursion
6752 (save-restriction
6753 (widen)
6754 (delq nil
6755 (mapcar (lambda (o)
6756 (when (eq (overlay-get o 'invisible) 'outline)
6757 (setq beg (overlay-start o)
6758 end (overlay-end o))
6759 (and beg end (> end beg)
6760 (if use-markers
6761 (cons (move-marker (make-marker) beg)
6762 (move-marker (make-marker) end))
6763 (cons beg end)))))
6764 (overlays-in (point-min) (point-max))))))))
6766 (defun org-set-outline-overlay-data (data)
6767 "Create visibility overlays for all positions in DATA.
6768 DATA should have been made by `org-outline-overlay-data'."
6769 (let (o)
6770 (save-excursion
6771 (save-restriction
6772 (widen)
6773 (show-all)
6774 (mapc (lambda (c)
6775 (outline-flag-region (car c) (cdr c) t))
6776 data)))))
6778 ;;; Folding of blocks
6780 (defvar org-hide-block-overlays nil
6781 "Overlays hiding blocks.")
6782 (make-variable-buffer-local 'org-hide-block-overlays)
6784 (defun org-block-map (function &optional start end)
6785 "Call FUNCTION at the head of all source blocks in the current buffer.
6786 Optional arguments START and END can be used to limit the range."
6787 (let ((start (or start (point-min)))
6788 (end (or end (point-max))))
6789 (save-excursion
6790 (goto-char start)
6791 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6792 (save-excursion
6793 (save-match-data
6794 (goto-char (match-beginning 0))
6795 (funcall function)))))))
6797 (defun org-hide-block-toggle-all ()
6798 "Toggle the visibility of all blocks in the current buffer."
6799 (org-block-map #'org-hide-block-toggle))
6801 (defun org-hide-block-all ()
6802 "Fold all blocks in the current buffer."
6803 (interactive)
6804 (org-show-block-all)
6805 (org-block-map #'org-hide-block-toggle-maybe))
6807 (defun org-show-block-all ()
6808 "Unfold all blocks in the current buffer."
6809 (interactive)
6810 (mapc 'delete-overlay org-hide-block-overlays)
6811 (setq org-hide-block-overlays nil))
6813 (defun org-hide-block-toggle-maybe ()
6814 "Toggle visibility of block at point."
6815 (interactive)
6816 (let ((case-fold-search t))
6817 (if (save-excursion
6818 (beginning-of-line 1)
6819 (looking-at org-block-regexp))
6820 (progn (org-hide-block-toggle)
6821 t) ;; to signal that we took action
6822 nil))) ;; to signal that we did not
6824 (defun org-hide-block-toggle (&optional force)
6825 "Toggle the visibility of the current block."
6826 (interactive)
6827 (save-excursion
6828 (beginning-of-line)
6829 (if (re-search-forward org-block-regexp nil t)
6830 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6831 (end (match-end 0)) ;; end of entire body
6833 (if (memq t (mapcar (lambda (overlay)
6834 (eq (overlay-get overlay 'invisible)
6835 'org-hide-block))
6836 (overlays-at start)))
6837 (if (or (not force) (eq force 'off))
6838 (mapc (lambda (ov)
6839 (when (member ov org-hide-block-overlays)
6840 (setq org-hide-block-overlays
6841 (delq ov org-hide-block-overlays)))
6842 (when (eq (overlay-get ov 'invisible)
6843 'org-hide-block)
6844 (delete-overlay ov)))
6845 (overlays-at start)))
6846 (setq ov (make-overlay start end))
6847 (overlay-put ov 'invisible 'org-hide-block)
6848 ;; make the block accessible to isearch
6849 (overlay-put
6850 ov 'isearch-open-invisible
6851 (lambda (ov)
6852 (when (member ov org-hide-block-overlays)
6853 (setq org-hide-block-overlays
6854 (delq ov org-hide-block-overlays)))
6855 (when (eq (overlay-get ov 'invisible)
6856 'org-hide-block)
6857 (delete-overlay ov))))
6858 (push ov org-hide-block-overlays)))
6859 (error "Not looking at a source block"))))
6861 ;; org-tab-after-check-for-cycling-hook
6862 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6863 ;; Remove overlays when changing major mode
6864 (add-hook 'org-mode-hook
6865 (lambda () (org-add-hook 'change-major-mode-hook
6866 'org-show-block-all 'append 'local)))
6868 ;;; Org-goto
6870 (defvar org-goto-window-configuration nil)
6871 (defvar org-goto-marker nil)
6872 (defvar org-goto-map)
6873 (defun org-goto-map ()
6874 "Set the keymap `org-goto'."
6875 (setq org-goto-map
6876 (let ((map (make-sparse-keymap)))
6877 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
6878 mouse-drag-region universal-argument org-occur))
6879 cmd)
6880 (while (setq cmd (pop cmds))
6881 (substitute-key-definition cmd cmd map global-map)))
6882 (suppress-keymap map)
6883 (org-defkey map "\C-m" 'org-goto-ret)
6884 (org-defkey map [(return)] 'org-goto-ret)
6885 (org-defkey map [(left)] 'org-goto-left)
6886 (org-defkey map [(right)] 'org-goto-right)
6887 (org-defkey map [(control ?g)] 'org-goto-quit)
6888 (org-defkey map "\C-i" 'org-cycle)
6889 (org-defkey map [(tab)] 'org-cycle)
6890 (org-defkey map [(down)] 'outline-next-visible-heading)
6891 (org-defkey map [(up)] 'outline-previous-visible-heading)
6892 (if org-goto-auto-isearch
6893 (if (fboundp 'define-key-after)
6894 (define-key-after map [t] 'org-goto-local-auto-isearch)
6895 nil)
6896 (org-defkey map "q" 'org-goto-quit)
6897 (org-defkey map "n" 'outline-next-visible-heading)
6898 (org-defkey map "p" 'outline-previous-visible-heading)
6899 (org-defkey map "f" 'outline-forward-same-level)
6900 (org-defkey map "b" 'outline-backward-same-level)
6901 (org-defkey map "u" 'outline-up-heading))
6902 (org-defkey map "/" 'org-occur)
6903 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6904 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6905 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6906 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6907 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6908 map)))
6910 (defconst org-goto-help
6911 "Browse buffer copy, to find location or copy text.%s
6912 RET=jump to location C-g=quit and return to previous location
6913 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6915 (defvar org-goto-start-pos) ; dynamically scoped parameter
6917 ;; FIXME: Docstring does not mention both interfaces
6918 (defun org-goto (&optional alternative-interface)
6919 "Look up a different location in the current file, keeping current visibility.
6921 When you want look-up or go to a different location in a
6922 document, the fastest way is often to fold the entire buffer and
6923 then dive into the tree. This method has the disadvantage, that
6924 the previous location will be folded, which may not be what you
6925 want.
6927 This command works around this by showing a copy of the current
6928 buffer in an indirect buffer, in overview mode. You can dive
6929 into the tree in that copy, use org-occur and incremental search
6930 to find a location. When pressing RET or `Q', the command
6931 returns to the original buffer in which the visibility is still
6932 unchanged. After RET it will also jump to the location selected
6933 in the indirect buffer and expose the headline hierarchy above.
6935 With a prefix argument, use the alternative interface: e.g. if
6936 `org-goto-interface' is 'outline use 'outline-path-completion."
6937 (interactive "P")
6938 (org-goto-map)
6939 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6940 (org-refile-use-outline-path t)
6941 (org-refile-target-verify-function nil)
6942 (interface
6943 (if (not alternative-interface)
6944 org-goto-interface
6945 (if (eq org-goto-interface 'outline)
6946 'outline-path-completion
6947 'outline)))
6948 (org-goto-start-pos (point))
6949 (selected-point
6950 (if (eq interface 'outline)
6951 (car (org-get-location (current-buffer) org-goto-help))
6952 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6953 (org-refile-check-position pa)
6954 (nth 3 pa)))))
6955 (if selected-point
6956 (progn
6957 (org-mark-ring-push org-goto-start-pos)
6958 (goto-char selected-point)
6959 (if (or (outline-invisible-p) (org-invisible-p2))
6960 (org-show-context 'org-goto)))
6961 (message "Quit"))))
6963 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6964 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6965 (defvar org-goto-local-auto-isearch-map) ; defined below
6967 (defun org-get-location (buf help)
6968 "Let the user select a location in the Org-mode buffer BUF.
6969 This function uses a recursive edit. It returns the selected position
6970 or nil."
6971 (org-no-popups
6972 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6973 (isearch-hide-immediately nil)
6974 (isearch-search-fun-function
6975 (lambda () 'org-goto-local-search-headings))
6976 (org-goto-selected-point org-goto-exit-command))
6977 (save-excursion
6978 (save-window-excursion
6979 (delete-other-windows)
6980 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6981 (org-pop-to-buffer-same-window
6982 (condition-case nil
6983 (make-indirect-buffer (current-buffer) "*org-goto*")
6984 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6985 (with-output-to-temp-buffer "*Org Help*"
6986 (princ (format help (if org-goto-auto-isearch
6987 " Just type for auto-isearch."
6988 " n/p/f/b/u to navigate, q to quit."))))
6989 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
6990 (setq buffer-read-only nil)
6991 (let ((org-startup-truncated t)
6992 (org-startup-folded nil)
6993 (org-startup-align-all-tables nil))
6994 (org-mode)
6995 (org-overview))
6996 (setq buffer-read-only t)
6997 (if (and (boundp 'org-goto-start-pos)
6998 (integer-or-marker-p org-goto-start-pos))
6999 (let ((org-show-hierarchy-above t)
7000 (org-show-siblings t)
7001 (org-show-following-heading t))
7002 (goto-char org-goto-start-pos)
7003 (and (outline-invisible-p) (org-show-context)))
7004 (goto-char (point-min)))
7005 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7006 (message "Select location and press RET")
7007 (use-local-map org-goto-map)
7008 (recursive-edit)))
7009 (kill-buffer "*org-goto*")
7010 (cons org-goto-selected-point org-goto-exit-command))))
7012 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7013 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7014 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7015 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7017 (defun org-goto-local-search-headings (string bound noerror)
7018 "Search and make sure that any matches are in headlines."
7019 (catch 'return
7020 (while (if isearch-forward
7021 (search-forward string bound noerror)
7022 (search-backward string bound noerror))
7023 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7024 (and (member :headline context)
7025 (not (member :tags context))))
7026 (throw 'return (point))))))
7028 (defun org-goto-local-auto-isearch ()
7029 "Start isearch."
7030 (interactive)
7031 (goto-char (point-min))
7032 (let ((keys (this-command-keys)))
7033 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7034 (isearch-mode t)
7035 (isearch-process-search-char (string-to-char keys)))))
7037 (defun org-goto-ret (&optional arg)
7038 "Finish `org-goto' by going to the new location."
7039 (interactive "P")
7040 (setq org-goto-selected-point (point)
7041 org-goto-exit-command 'return)
7042 (throw 'exit nil))
7044 (defun org-goto-left ()
7045 "Finish `org-goto' by going to the new location."
7046 (interactive)
7047 (if (org-at-heading-p)
7048 (progn
7049 (beginning-of-line 1)
7050 (setq org-goto-selected-point (point)
7051 org-goto-exit-command 'left)
7052 (throw 'exit nil))
7053 (error "Not on a heading")))
7055 (defun org-goto-right ()
7056 "Finish `org-goto' by going to the new location."
7057 (interactive)
7058 (if (org-at-heading-p)
7059 (progn
7060 (setq org-goto-selected-point (point)
7061 org-goto-exit-command 'right)
7062 (throw 'exit nil))
7063 (error "Not on a heading")))
7065 (defun org-goto-quit ()
7066 "Finish `org-goto' without cursor motion."
7067 (interactive)
7068 (setq org-goto-selected-point nil)
7069 (setq org-goto-exit-command 'quit)
7070 (throw 'exit nil))
7072 ;;; Indirect buffer display of subtrees
7074 (defvar org-indirect-dedicated-frame nil
7075 "This is the frame being used for indirect tree display.")
7076 (defvar org-last-indirect-buffer nil)
7078 (defun org-tree-to-indirect-buffer (&optional arg)
7079 "Create indirect buffer and narrow it to current subtree.
7080 With a numerical prefix ARG, go up to this level and then take that tree.
7081 If ARG is negative, go up that many levels.
7083 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7084 indirect buffer previously made with this command, to avoid proliferation of
7085 indirect buffers. However, when you call the command with a \
7086 \\[universal-argument] prefix, or
7087 when `org-indirect-buffer-display' is `new-frame', the last buffer
7088 is kept so that you can work with several indirect buffers at the same time.
7089 If `org-indirect-buffer-display' is `dedicated-frame', the \
7090 \\[universal-argument] prefix also
7091 requests that a new frame be made for the new buffer, so that the dedicated
7092 frame is not changed."
7093 (interactive "P")
7094 (let ((cbuf (current-buffer))
7095 (cwin (selected-window))
7096 (pos (point))
7097 beg end level heading ibuf)
7098 (save-excursion
7099 (org-back-to-heading t)
7100 (when (numberp arg)
7101 (setq level (org-outline-level))
7102 (if (< arg 0) (setq arg (+ level arg)))
7103 (while (> (setq level (org-outline-level)) arg)
7104 (org-up-heading-safe)))
7105 (setq beg (point)
7106 heading (org-get-heading))
7107 (org-end-of-subtree t t)
7108 (if (org-at-heading-p) (backward-char 1))
7109 (setq end (point)))
7110 (if (and (buffer-live-p org-last-indirect-buffer)
7111 (not (eq org-indirect-buffer-display 'new-frame))
7112 (not arg))
7113 (kill-buffer org-last-indirect-buffer))
7114 (setq ibuf (org-get-indirect-buffer cbuf)
7115 org-last-indirect-buffer ibuf)
7116 (cond
7117 ((or (eq org-indirect-buffer-display 'new-frame)
7118 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7119 (select-frame (make-frame))
7120 (delete-other-windows)
7121 (org-pop-to-buffer-same-window ibuf)
7122 (org-set-frame-title heading))
7123 ((eq org-indirect-buffer-display 'dedicated-frame)
7124 (raise-frame
7125 (select-frame (or (and org-indirect-dedicated-frame
7126 (frame-live-p org-indirect-dedicated-frame)
7127 org-indirect-dedicated-frame)
7128 (setq org-indirect-dedicated-frame (make-frame)))))
7129 (delete-other-windows)
7130 (org-pop-to-buffer-same-window ibuf)
7131 (org-set-frame-title (concat "Indirect: " heading)))
7132 ((eq org-indirect-buffer-display 'current-window)
7133 (org-pop-to-buffer-same-window ibuf))
7134 ((eq org-indirect-buffer-display 'other-window)
7135 (pop-to-buffer ibuf))
7136 (t (error "Invalid value")))
7137 (if (featurep 'xemacs)
7138 (save-excursion (org-mode) (turn-on-font-lock)))
7139 (narrow-to-region beg end)
7140 (show-all)
7141 (goto-char pos)
7142 (run-hook-with-args 'org-cycle-hook 'all)
7143 (and (window-live-p cwin) (select-window cwin))))
7145 (defun org-get-indirect-buffer (&optional buffer)
7146 (setq buffer (or buffer (current-buffer)))
7147 (let ((n 1) (base (buffer-name buffer)) bname)
7148 (while (buffer-live-p
7149 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7150 (setq n (1+ n)))
7151 (condition-case nil
7152 (make-indirect-buffer buffer bname 'clone)
7153 (error (make-indirect-buffer buffer bname)))))
7155 (defun org-set-frame-title (title)
7156 "Set the title of the current frame to the string TITLE."
7157 ;; FIXME: how to name a single frame in XEmacs???
7158 (unless (featurep 'xemacs)
7159 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7161 ;;;; Structure editing
7163 ;;; Inserting headlines
7165 (defun org-previous-line-empty-p ()
7166 (save-excursion
7167 (and (not (bobp))
7168 (or (beginning-of-line 0) t)
7169 (save-match-data
7170 (looking-at "[ \t]*$")))))
7172 (defun org-insert-heading (&optional force-heading invisible-ok)
7173 "Insert a new heading or item with same depth at point.
7174 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7175 If point is at the beginning of a headline, insert a sibling before the
7176 current headline. If point is not at the beginning, split the line,
7177 create the new headline with the text in the current line after point
7178 \(but see also the variable `org-M-RET-may-split-line').
7180 With a double prefix arg, force the heading to be inserted at the
7181 end of the parent subtree.
7183 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7184 This is important for non-interactive uses of the command."
7185 (interactive "P")
7186 (if (or (= (buffer-size) 0)
7187 (and (not (save-excursion
7188 (and (ignore-errors (org-back-to-heading invisible-ok))
7189 (org-at-heading-p))))
7190 (or force-heading (not (org-in-item-p)))))
7191 (progn
7192 (insert "\n* ")
7193 (run-hooks 'org-insert-heading-hook))
7194 (when (or force-heading (not (org-insert-item)))
7195 (let* ((empty-line-p nil)
7196 (level nil)
7197 (on-heading (org-at-heading-p))
7198 (head (save-excursion
7199 (condition-case nil
7200 (progn
7201 (org-back-to-heading invisible-ok)
7202 (when (and (not on-heading)
7203 (featurep 'org-inlinetask)
7204 (integerp org-inlinetask-min-level)
7205 (>= (length (match-string 0))
7206 org-inlinetask-min-level))
7207 ;; Find a heading level before the inline task
7208 (while (and (setq level (org-up-heading-safe))
7209 (>= level org-inlinetask-min-level)))
7210 (if (org-at-heading-p)
7211 (org-back-to-heading invisible-ok)
7212 (error "This should not happen")))
7213 (setq empty-line-p (org-previous-line-empty-p))
7214 (match-string 0))
7215 (error "*"))))
7216 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7217 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7218 pos hide-previous previous-pos)
7219 (cond
7220 ((and (org-at-heading-p) (bolp)
7221 (or (bobp)
7222 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7223 ;; insert before the current line
7224 (open-line (if blank 2 1)))
7225 ((and (bolp)
7226 (not org-insert-heading-respect-content)
7227 (or (bobp)
7228 (save-excursion
7229 (backward-char 1) (not (outline-invisible-p)))))
7230 ;; insert right here
7231 nil)
7233 ;; somewhere in the line
7234 (save-excursion
7235 (setq previous-pos (point-at-bol))
7236 (end-of-line)
7237 (setq hide-previous (outline-invisible-p)))
7238 (and org-insert-heading-respect-content (org-show-subtree))
7239 (let ((split
7240 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7241 (save-excursion
7242 (let ((p (point)))
7243 (goto-char (point-at-bol))
7244 (and (looking-at org-complex-heading-regexp)
7245 (match-beginning 4)
7246 (> p (match-beginning 4)))))))
7247 tags pos)
7248 (cond
7249 (org-insert-heading-respect-content
7250 (if (not (equal force-heading '(16)))
7251 (org-end-of-subtree nil t)
7252 (org-up-heading-safe)
7253 (org-end-of-subtree nil t))
7254 (when (featurep 'org-inlinetask)
7255 (while (and (not (eobp))
7256 (looking-at "\\(\\*+\\)[ \t]+")
7257 (>= (length (match-string 1))
7258 org-inlinetask-min-level))
7259 (org-end-of-subtree nil t)))
7260 (or (bolp) (newline))
7261 (or (org-previous-line-empty-p)
7262 (and blank (newline)))
7263 (open-line 1))
7264 ((org-at-heading-p)
7265 (when hide-previous
7266 (show-children)
7267 (org-show-entry))
7268 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7269 (setq tags (and (match-end 2) (match-string 2)))
7270 (and (match-end 1)
7271 (delete-region (match-beginning 1) (match-end 1)))
7272 (setq pos (point-at-bol))
7273 (or split (end-of-line 1))
7274 (delete-horizontal-space)
7275 (if (string-match "\\`\\*+\\'"
7276 (buffer-substring (point-at-bol) (point)))
7277 (insert " "))
7278 (newline (if blank 2 1))
7279 (when tags
7280 (save-excursion
7281 (goto-char pos)
7282 (end-of-line 1)
7283 (insert " " tags)
7284 (org-set-tags nil 'align))))
7286 (or split (end-of-line 1))
7287 (newline (if blank 2 1)))))))
7288 (insert head) (just-one-space)
7289 (setq pos (point))
7290 (end-of-line 1)
7291 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7292 (when (and org-insert-heading-respect-content hide-previous)
7293 (save-excursion
7294 (goto-char previous-pos)
7295 (hide-subtree)))
7296 (run-hooks 'org-insert-heading-hook)))))
7298 (defun org-get-heading (&optional no-tags no-todo)
7299 "Return the heading of the current entry, without the stars.
7300 When NO-TAGS is non-nil, don't include tags.
7301 When NO-TODO is non-nil, don't include TODO keywords."
7302 (save-excursion
7303 (org-back-to-heading t)
7304 (cond
7305 ((and no-tags no-todo)
7306 (looking-at org-complex-heading-regexp)
7307 (match-string 4))
7308 (no-tags
7309 (looking-at (concat org-outline-regexp
7310 "\\(.*?\\)"
7311 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7312 (match-string 1))
7313 (no-todo
7314 (looking-at org-todo-line-regexp)
7315 (match-string 3))
7316 (t (looking-at org-heading-regexp)
7317 (match-string 2)))))
7319 (defun org-heading-components ()
7320 "Return the components of the current heading.
7321 This is a list with the following elements:
7322 - the level as an integer
7323 - the reduced level, different if `org-odd-levels-only' is set.
7324 - the TODO keyword, or nil
7325 - the priority character, like ?A, or nil if no priority is given
7326 - the headline text itself, or the tags string if no headline text
7327 - the tags string, or nil."
7328 (save-excursion
7329 (org-back-to-heading t)
7330 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7331 (list (length (match-string 1))
7332 (org-reduced-level (length (match-string 1)))
7333 (org-match-string-no-properties 2)
7334 (and (match-end 3) (aref (match-string 3) 2))
7335 (org-match-string-no-properties 4)
7336 (org-match-string-no-properties 5)))))
7338 (defun org-get-entry ()
7339 "Get the entry text, after heading, entire subtree."
7340 (save-excursion
7341 (org-back-to-heading t)
7342 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7344 (defun org-insert-heading-after-current ()
7345 "Insert a new heading with same level as current, after current subtree."
7346 (interactive)
7347 (org-back-to-heading)
7348 (org-insert-heading)
7349 (org-move-subtree-down)
7350 (end-of-line 1))
7352 (defun org-insert-heading-respect-content ()
7353 (interactive)
7354 (let ((org-insert-heading-respect-content t))
7355 (org-insert-heading t)))
7357 (defun org-insert-todo-heading-respect-content (&optional force-state)
7358 (interactive "P")
7359 (let ((org-insert-heading-respect-content t))
7360 (org-insert-todo-heading force-state t)))
7362 (defun org-insert-todo-heading (arg &optional force-heading)
7363 "Insert a new heading with the same level and TODO state as current heading.
7364 If the heading has no TODO state, or if the state is DONE, use the first
7365 state (TODO by default). Also one prefix arg, force first state. With two
7366 prefix args, force inserting at the end of the parent subtree."
7367 (interactive "P")
7368 (when (or force-heading (not (org-insert-item 'checkbox)))
7369 (org-insert-heading (or (and (equal arg '(16)) '(16))
7370 force-heading))
7371 (save-excursion
7372 (org-back-to-heading)
7373 (outline-previous-heading)
7374 (looking-at org-todo-line-regexp))
7375 (let*
7376 ((new-mark-x
7377 (if (or arg
7378 (not (match-beginning 2))
7379 (member (match-string 2) org-done-keywords))
7380 (car org-todo-keywords-1)
7381 (match-string 2)))
7382 (new-mark
7384 (run-hook-with-args-until-success
7385 'org-todo-get-default-hook new-mark-x nil)
7386 new-mark-x)))
7387 (beginning-of-line 1)
7388 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7389 (if org-treat-insert-todo-heading-as-state-change
7390 (org-todo new-mark)
7391 (insert new-mark " "))))
7392 (when org-provide-todo-statistics
7393 (org-update-parent-todo-statistics))))
7395 (defun org-insert-subheading (arg)
7396 "Insert a new subheading and demote it.
7397 Works for outline headings and for plain lists alike."
7398 (interactive "P")
7399 (org-insert-heading arg)
7400 (cond
7401 ((org-at-heading-p) (org-do-demote))
7402 ((org-at-item-p) (org-indent-item))))
7404 (defun org-insert-todo-subheading (arg)
7405 "Insert a new subheading with TODO keyword or checkbox and demote it.
7406 Works for outline headings and for plain lists alike."
7407 (interactive "P")
7408 (org-insert-todo-heading arg)
7409 (cond
7410 ((org-at-heading-p) (org-do-demote))
7411 ((org-at-item-p) (org-indent-item))))
7413 ;;; Promotion and Demotion
7415 (defvar org-after-demote-entry-hook nil
7416 "Hook run after an entry has been demoted.
7417 The cursor will be at the beginning of the entry.
7418 When a subtree is being demoted, the hook will be called for each node.")
7420 (defvar org-after-promote-entry-hook nil
7421 "Hook run after an entry has been promoted.
7422 The cursor will be at the beginning of the entry.
7423 When a subtree is being promoted, the hook will be called for each node.")
7425 (defun org-promote-subtree ()
7426 "Promote the entire subtree.
7427 See also `org-promote'."
7428 (interactive)
7429 (save-excursion
7430 (org-with-limited-levels (org-map-tree 'org-promote)))
7431 (org-fix-position-after-promote))
7433 (defun org-demote-subtree ()
7434 "Demote the entire subtree. See `org-demote'.
7435 See also `org-promote'."
7436 (interactive)
7437 (save-excursion
7438 (org-with-limited-levels (org-map-tree 'org-demote)))
7439 (org-fix-position-after-promote))
7442 (defun org-do-promote ()
7443 "Promote the current heading higher up the tree.
7444 If the region is active in `transient-mark-mode', promote all headings
7445 in the region."
7446 (interactive)
7447 (save-excursion
7448 (if (org-region-active-p)
7449 (org-map-region 'org-promote (region-beginning) (region-end))
7450 (org-promote)))
7451 (org-fix-position-after-promote))
7453 (defun org-do-demote ()
7454 "Demote the current heading lower down the tree.
7455 If the region is active in `transient-mark-mode', demote all headings
7456 in the region."
7457 (interactive)
7458 (save-excursion
7459 (if (org-region-active-p)
7460 (org-map-region 'org-demote (region-beginning) (region-end))
7461 (org-demote)))
7462 (org-fix-position-after-promote))
7464 (defun org-fix-position-after-promote ()
7465 "Make sure that after pro/demotion cursor position is right."
7466 (let ((pos (point)))
7467 (when (save-excursion
7468 (beginning-of-line 1)
7469 (looking-at org-todo-line-regexp)
7470 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7471 (cond ((eobp) (insert " "))
7472 ((eolp) (insert " "))
7473 ((equal (char-after) ?\ ) (forward-char 1))))))
7475 (defun org-current-level ()
7476 "Return the level of the current entry, or nil if before the first headline.
7477 The level is the number of stars at the beginning of the headline."
7478 (save-excursion
7479 (org-with-limited-levels
7480 (if (ignore-errors (org-back-to-heading t))
7481 (funcall outline-level)))))
7483 (defun org-get-previous-line-level ()
7484 "Return the outline depth of the last headline before the current line.
7485 Returns 0 for the first headline in the buffer, and nil if before the
7486 first headline."
7487 (let ((current-level (org-current-level))
7488 (prev-level (when (> (line-number-at-pos) 1)
7489 (save-excursion
7490 (beginning-of-line 0)
7491 (org-current-level)))))
7492 (cond ((null current-level) nil) ; Before first headline
7493 ((null prev-level) 0) ; At first headline
7494 (prev-level))))
7496 (defun org-reduced-level (l)
7497 "Compute the effective level of a heading.
7498 This takes into account the setting of `org-odd-levels-only'."
7499 (cond
7500 ((zerop l) 0)
7501 (org-odd-levels-only (1+ (floor (/ l 2))))
7502 (t l)))
7504 (defun org-level-increment ()
7505 "Return the number of stars that will be added or removed at a
7506 time to headlines when structure editing, based on the value of
7507 `org-odd-levels-only'."
7508 (if org-odd-levels-only 2 1))
7510 (defun org-get-valid-level (level &optional change)
7511 "Rectify a level change under the influence of `org-odd-levels-only'
7512 LEVEL is a current level, CHANGE is by how much the level should be
7513 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7514 even level numbers will become the next higher odd number."
7515 (if org-odd-levels-only
7516 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7517 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7518 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7519 (max 1 (+ level (or change 0)))))
7521 (if (boundp 'define-obsolete-function-alias)
7522 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7523 (define-obsolete-function-alias 'org-get-legal-level
7524 'org-get-valid-level)
7525 (define-obsolete-function-alias 'org-get-legal-level
7526 'org-get-valid-level "23.1")))
7528 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7529 ;; ̀org-with-limited-levels'
7530 (defun org-promote ()
7531 "Promote the current heading higher up the tree.
7532 If the region is active in `transient-mark-mode', promote all headings
7533 in the region."
7534 (org-back-to-heading t)
7535 (let* ((level (save-match-data (funcall outline-level)))
7536 (after-change-functions (remove 'flyspell-after-change-function
7537 after-change-functions))
7538 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7539 (diff (abs (- level (length up-head) -1))))
7540 (cond ((and (= level 1) org-called-with-limited-levels
7541 org-allow-promoting-top-level-subtree)
7542 (replace-match "# " nil t))
7543 ((= level 1)
7544 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7545 (t (replace-match up-head nil t)))
7546 ;; Fixup tag positioning
7547 (unless (= level 1)
7548 (and org-auto-align-tags (org-set-tags nil t))
7549 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7550 (run-hooks 'org-after-promote-entry-hook)))
7552 (defun org-demote ()
7553 "Demote the current heading lower down the tree.
7554 If the region is active in `transient-mark-mode', demote all headings
7555 in the region."
7556 (org-back-to-heading t)
7557 (let* ((level (save-match-data (funcall outline-level)))
7558 (after-change-functions (remove 'flyspell-after-change-function
7559 after-change-functions))
7560 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7561 (diff (abs (- level (length down-head) -1))))
7562 (replace-match down-head nil t)
7563 ;; Fixup tag positioning
7564 (and org-auto-align-tags (org-set-tags nil t))
7565 (if org-adapt-indentation (org-fixup-indentation diff))
7566 (run-hooks 'org-after-demote-entry-hook)))
7568 (defun org-cycle-level ()
7569 "Cycle the level of an empty headline through possible states.
7570 This goes first to child, then to parent, level, then up the hierarchy.
7571 After top level, it switches back to sibling level."
7572 (interactive)
7573 (let ((org-adapt-indentation nil))
7574 (when (org-point-at-end-of-empty-headline)
7575 (setq this-command 'org-cycle-level) ; Only needed for caching
7576 (let ((cur-level (org-current-level))
7577 (prev-level (org-get-previous-line-level)))
7578 (cond
7579 ;; If first headline in file, promote to top-level.
7580 ((= prev-level 0)
7581 (loop repeat (/ (- cur-level 1) (org-level-increment))
7582 do (org-do-promote)))
7583 ;; If same level as prev, demote one.
7584 ((= prev-level cur-level)
7585 (org-do-demote))
7586 ;; If parent is top-level, promote to top level if not already.
7587 ((= prev-level 1)
7588 (loop repeat (/ (- cur-level 1) (org-level-increment))
7589 do (org-do-promote)))
7590 ;; If top-level, return to prev-level.
7591 ((= cur-level 1)
7592 (loop repeat (/ (- prev-level 1) (org-level-increment))
7593 do (org-do-demote)))
7594 ;; If less than prev-level, promote one.
7595 ((< cur-level prev-level)
7596 (org-do-promote))
7597 ;; If deeper than prev-level, promote until higher than
7598 ;; prev-level.
7599 ((> cur-level prev-level)
7600 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7601 do (org-do-promote))))
7602 t))))
7604 (defun org-map-tree (fun)
7605 "Call FUN for every heading underneath the current one."
7606 (org-back-to-heading)
7607 (let ((level (funcall outline-level)))
7608 (save-excursion
7609 (funcall fun)
7610 (while (and (progn
7611 (outline-next-heading)
7612 (> (funcall outline-level) level))
7613 (not (eobp)))
7614 (funcall fun)))))
7616 (defun org-map-region (fun beg end)
7617 "Call FUN for every heading between BEG and END."
7618 (let ((org-ignore-region t))
7619 (save-excursion
7620 (setq end (copy-marker end))
7621 (goto-char beg)
7622 (if (and (re-search-forward org-outline-regexp-bol nil t)
7623 (< (point) end))
7624 (funcall fun))
7625 (while (and (progn
7626 (outline-next-heading)
7627 (< (point) end))
7628 (not (eobp)))
7629 (funcall fun)))))
7631 (defvar org-property-end-re) ; silence byte-compiler
7632 (defun org-fixup-indentation (diff)
7633 "Change the indentation in the current entry by DIFF.
7634 However, if any line in the current entry has no indentation, or if it
7635 would end up with no indentation after the change, nothing at all is done."
7636 (save-excursion
7637 (let ((end (save-excursion (outline-next-heading)
7638 (point-marker)))
7639 (prohibit (if (> diff 0)
7640 "^\\S-"
7641 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7642 col)
7643 (unless (save-excursion (end-of-line 1)
7644 (re-search-forward prohibit end t))
7645 (while (and (< (point) end)
7646 (re-search-forward "^[ \t]+" end t))
7647 (goto-char (match-end 0))
7648 (setq col (current-column))
7649 (if (< diff 0) (replace-match ""))
7650 (org-indent-to-column (+ diff col))))
7651 (move-marker end nil))))
7653 (defun org-convert-to-odd-levels ()
7654 "Convert an org-mode file with all levels allowed to one with odd levels.
7655 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7656 level 5 etc."
7657 (interactive)
7658 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7659 (let ((outline-level 'org-outline-level)
7660 (org-odd-levels-only nil) n)
7661 (save-excursion
7662 (goto-char (point-min))
7663 (while (re-search-forward "^\\*\\*+ " nil t)
7664 (setq n (- (length (match-string 0)) 2))
7665 (while (>= (setq n (1- n)) 0)
7666 (org-demote))
7667 (end-of-line 1))))))
7669 (defun org-convert-to-oddeven-levels ()
7670 "Convert an org-mode file with only odd levels to one with odd/even levels.
7671 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7672 file contains a section with an even level, conversion would
7673 destroy the structure of the file. An error is signaled in this
7674 case."
7675 (interactive)
7676 (goto-char (point-min))
7677 ;; First check if there are no even levels
7678 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7679 (org-show-context t)
7680 (error "Not all levels are odd in this file. Conversion not possible"))
7681 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7682 (let ((outline-regexp org-outline-regexp)
7683 (outline-level 'org-outline-level)
7684 (org-odd-levels-only nil) n)
7685 (save-excursion
7686 (goto-char (point-min))
7687 (while (re-search-forward "^\\*\\*+ " nil t)
7688 (setq n (/ (1- (length (match-string 0))) 2))
7689 (while (>= (setq n (1- n)) 0)
7690 (org-promote))
7691 (end-of-line 1))))))
7693 (defun org-tr-level (n)
7694 "Make N odd if required."
7695 (if org-odd-levels-only (1+ (/ n 2)) n))
7697 ;;; Vertical tree motion, cutting and pasting of subtrees
7699 (defun org-move-subtree-up (&optional arg)
7700 "Move the current subtree up past ARG headlines of the same level."
7701 (interactive "p")
7702 (org-move-subtree-down (- (prefix-numeric-value arg))))
7704 (defun org-move-subtree-down (&optional arg)
7705 "Move the current subtree down past ARG headlines of the same level."
7706 (interactive "p")
7707 (setq arg (prefix-numeric-value arg))
7708 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7709 'org-get-last-sibling))
7710 (ins-point (make-marker))
7711 (cnt (abs arg))
7712 (col (current-column))
7713 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7714 ;; Select the tree
7715 (org-back-to-heading)
7716 (setq beg0 (point))
7717 (save-excursion
7718 (setq ne-beg (org-back-over-empty-lines))
7719 (setq beg (point)))
7720 (save-match-data
7721 (save-excursion (outline-end-of-heading)
7722 (setq folded (outline-invisible-p)))
7723 (outline-end-of-subtree))
7724 (outline-next-heading)
7725 (setq ne-end (org-back-over-empty-lines))
7726 (setq end (point))
7727 (goto-char beg0)
7728 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7729 ;; include less whitespace
7730 (save-excursion
7731 (goto-char beg)
7732 (forward-line (- ne-beg ne-end))
7733 (setq beg (point))))
7734 ;; Find insertion point, with error handling
7735 (while (> cnt 0)
7736 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7737 (progn (goto-char beg0)
7738 (error "Cannot move past superior level or buffer limit")))
7739 (setq cnt (1- cnt)))
7740 (if (> arg 0)
7741 ;; Moving forward - still need to move over subtree
7742 (progn (org-end-of-subtree t t)
7743 (save-excursion
7744 (org-back-over-empty-lines)
7745 (or (bolp) (newline)))))
7746 (setq ne-ins (org-back-over-empty-lines))
7747 (move-marker ins-point (point))
7748 (setq txt (buffer-substring beg end))
7749 (org-save-markers-in-region beg end)
7750 (delete-region beg end)
7751 (org-remove-empty-overlays-at beg)
7752 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7753 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7754 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7755 (let ((bbb (point)))
7756 (insert-before-markers txt)
7757 (org-reinstall-markers-in-region bbb)
7758 (move-marker ins-point bbb))
7759 (or (bolp) (insert "\n"))
7760 (setq ins-end (point))
7761 (goto-char ins-point)
7762 (org-skip-whitespace)
7763 (when (and (< arg 0)
7764 (org-first-sibling-p)
7765 (> ne-ins ne-beg))
7766 ;; Move whitespace back to beginning
7767 (save-excursion
7768 (goto-char ins-end)
7769 (let ((kill-whole-line t))
7770 (kill-line (- ne-ins ne-beg)) (point)))
7771 (insert (make-string (- ne-ins ne-beg) ?\n)))
7772 (move-marker ins-point nil)
7773 (if folded
7774 (hide-subtree)
7775 (org-show-entry)
7776 (show-children)
7777 (org-cycle-hide-drawers 'children))
7778 (org-clean-visibility-after-subtree-move)
7779 ;; move back to the initial column we were at
7780 (move-to-column col)))
7782 (defvar org-subtree-clip ""
7783 "Clipboard for cut and paste of subtrees.
7784 This is actually only a copy of the kill, because we use the normal kill
7785 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7787 (defvar org-subtree-clip-folded nil
7788 "Was the last copied subtree folded?
7789 This is used to fold the tree back after pasting.")
7791 (defun org-cut-subtree (&optional n)
7792 "Cut the current subtree into the clipboard.
7793 With prefix arg N, cut this many sequential subtrees.
7794 This is a short-hand for marking the subtree and then cutting it."
7795 (interactive "p")
7796 (org-copy-subtree n 'cut))
7798 (defun org-copy-subtree (&optional n cut force-store-markers)
7799 "Cut the current subtree into the clipboard.
7800 With prefix arg N, cut this many sequential subtrees.
7801 This is a short-hand for marking the subtree and then copying it.
7802 If CUT is non-nil, actually cut the subtree.
7803 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7804 of some markers in the region, even if CUT is non-nil. This is
7805 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7806 (interactive "p")
7807 (let (beg end folded (beg0 (point)))
7808 (if (org-called-interactively-p 'any)
7809 (org-back-to-heading nil) ; take what looks like a subtree
7810 (org-back-to-heading t)) ; take what is really there
7811 (setq beg (point))
7812 (skip-chars-forward " \t\r\n")
7813 (save-match-data
7814 (save-excursion (outline-end-of-heading)
7815 (setq folded (outline-invisible-p)))
7816 (condition-case nil
7817 (org-forward-heading-same-level (1- n) t)
7818 (error nil))
7819 (org-end-of-subtree t t))
7820 (setq end (point))
7821 (goto-char beg0)
7822 (when (> end beg)
7823 (setq org-subtree-clip-folded folded)
7824 (when (or cut force-store-markers)
7825 (org-save-markers-in-region beg end))
7826 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7827 (setq org-subtree-clip (current-kill 0))
7828 (message "%s: Subtree(s) with %d characters"
7829 (if cut "Cut" "Copied")
7830 (length org-subtree-clip)))))
7832 (defun org-paste-subtree (&optional level tree for-yank)
7833 "Paste the clipboard as a subtree, with modification of headline level.
7834 The entire subtree is promoted or demoted in order to match a new headline
7835 level.
7837 If the cursor is at the beginning of a headline, the same level as
7838 that headline is used to paste the tree
7840 If not, the new level is derived from the *visible* headings
7841 before and after the insertion point, and taken to be the inferior headline
7842 level of the two. So if the previous visible heading is level 3 and the
7843 next is level 4 (or vice versa), level 4 will be used for insertion.
7844 This makes sure that the subtree remains an independent subtree and does
7845 not swallow low level entries.
7847 You can also force a different level, either by using a numeric prefix
7848 argument, or by inserting the heading marker by hand. For example, if the
7849 cursor is after \"*****\", then the tree will be shifted to level 5.
7851 If optional TREE is given, use this text instead of the kill ring.
7853 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7854 move back over whitespace before inserting, and move point to the end of
7855 the inserted text when done."
7856 (interactive "P")
7857 (setq tree (or tree (and kill-ring (current-kill 0))))
7858 (unless (org-kill-is-subtree-p tree)
7859 (error "%s"
7860 (substitute-command-keys
7861 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7862 (org-with-limited-levels
7863 (let* ((visp (not (outline-invisible-p)))
7864 (txt tree)
7865 (^re_ "\\(\\*+\\)[ \t]*")
7866 (old-level (if (string-match org-outline-regexp-bol txt)
7867 (- (match-end 0) (match-beginning 0) 1)
7868 -1))
7869 (force-level (cond (level (prefix-numeric-value level))
7870 ((and (looking-at "[ \t]*$")
7871 (string-match
7872 "^\\*+$" (buffer-substring
7873 (point-at-bol) (point))))
7874 (- (match-end 1) (match-beginning 1)))
7875 ((and (bolp)
7876 (looking-at org-outline-regexp))
7877 (- (match-end 0) (point) 1))))
7878 (previous-level (save-excursion
7879 (condition-case nil
7880 (progn
7881 (outline-previous-visible-heading 1)
7882 (if (looking-at ^re_)
7883 (- (match-end 0) (match-beginning 0) 1)
7885 (error 1))))
7886 (next-level (save-excursion
7887 (condition-case nil
7888 (progn
7889 (or (looking-at org-outline-regexp)
7890 (outline-next-visible-heading 1))
7891 (if (looking-at ^re_)
7892 (- (match-end 0) (match-beginning 0) 1)
7894 (error 1))))
7895 (new-level (or force-level (max previous-level next-level)))
7896 (shift (if (or (= old-level -1)
7897 (= new-level -1)
7898 (= old-level new-level))
7900 (- new-level old-level)))
7901 (delta (if (> shift 0) -1 1))
7902 (func (if (> shift 0) 'org-demote 'org-promote))
7903 (org-odd-levels-only nil)
7904 beg end newend)
7905 ;; Remove the forced level indicator
7906 (if force-level
7907 (delete-region (point-at-bol) (point)))
7908 ;; Paste
7909 (beginning-of-line (if (bolp) 1 2))
7910 (setq beg (point))
7911 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7912 (insert-before-markers txt)
7913 (unless (string-match "\n\\'" txt) (insert "\n"))
7914 (setq newend (point))
7915 (org-reinstall-markers-in-region beg)
7916 (setq end (point))
7917 (goto-char beg)
7918 (skip-chars-forward " \t\n\r")
7919 (setq beg (point))
7920 (if (and (outline-invisible-p) visp)
7921 (save-excursion (outline-show-heading)))
7922 ;; Shift if necessary
7923 (unless (= shift 0)
7924 (save-restriction
7925 (narrow-to-region beg end)
7926 (while (not (= shift 0))
7927 (org-map-region func (point-min) (point-max))
7928 (setq shift (+ delta shift)))
7929 (goto-char (point-min))
7930 (setq newend (point-max))))
7931 (when (or (org-called-interactively-p 'interactive) for-yank)
7932 (message "Clipboard pasted as level %d subtree" new-level))
7933 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7934 kill-ring
7935 (eq org-subtree-clip (current-kill 0))
7936 org-subtree-clip-folded)
7937 ;; The tree was folded before it was killed/copied
7938 (hide-subtree))
7939 (and for-yank (goto-char newend)))))
7941 (defun org-kill-is-subtree-p (&optional txt)
7942 "Check if the current kill is an outline subtree, or a set of trees.
7943 Returns nil if kill does not start with a headline, or if the first
7944 headline level is not the largest headline level in the tree.
7945 So this will actually accept several entries of equal levels as well,
7946 which is OK for `org-paste-subtree'.
7947 If optional TXT is given, check this string instead of the current kill."
7948 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7949 (re (org-get-limited-outline-regexp))
7950 (^re (concat "^" re))
7951 (start-level (and kill
7952 (string-match
7953 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7954 kill)
7955 (- (match-end 2) (match-beginning 2) 1)))
7956 (start (1+ (or (match-beginning 2) -1))))
7957 (if (not start-level)
7958 (progn
7959 nil) ;; does not even start with a heading
7960 (catch 'exit
7961 (while (setq start (string-match ^re kill (1+ start)))
7962 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7963 (throw 'exit nil)))
7964 t))))
7966 (defvar org-markers-to-move nil
7967 "Markers that should be moved with a cut-and-paste operation.
7968 Those markers are stored together with their positions relative to
7969 the start of the region.")
7971 (defun org-save-markers-in-region (beg end)
7972 "Check markers in region.
7973 If these markers are between BEG and END, record their position relative
7974 to BEG, so that after moving the block of text, we can put the markers back
7975 into place.
7976 This function gets called just before an entry or tree gets cut from the
7977 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7978 called immediately, to move the markers with the entries."
7979 (setq org-markers-to-move nil)
7980 (when (featurep 'org-clock)
7981 (org-clock-save-markers-for-cut-and-paste beg end))
7982 (when (featurep 'org-agenda)
7983 (org-agenda-save-markers-for-cut-and-paste beg end)))
7985 (defun org-check-and-save-marker (marker beg end)
7986 "Check if MARKER is between BEG and END.
7987 If yes, remember the marker and the distance to BEG."
7988 (when (and (marker-buffer marker)
7989 (equal (marker-buffer marker) (current-buffer)))
7990 (if (and (>= marker beg) (< marker end))
7991 (push (cons marker (- marker beg)) org-markers-to-move))))
7993 (defun org-reinstall-markers-in-region (beg)
7994 "Move all remembered markers to their position relative to BEG."
7995 (mapc (lambda (x)
7996 (move-marker (car x) (+ beg (cdr x))))
7997 org-markers-to-move)
7998 (setq org-markers-to-move nil))
8000 (defun org-narrow-to-subtree ()
8001 "Narrow buffer to the current subtree."
8002 (interactive)
8003 (save-excursion
8004 (save-match-data
8005 (org-with-limited-levels
8006 (narrow-to-region
8007 (progn (org-back-to-heading t) (point))
8008 (progn (org-end-of-subtree t t)
8009 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8010 (point)))))))
8012 (defun org-narrow-to-block ()
8013 "Narrow buffer to the current block."
8014 (interactive)
8015 (let* ((case-fold-search t)
8016 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8017 "^[ \t]*#\\+end_.*")))
8018 (if blockp
8019 (narrow-to-region (car blockp) (cdr blockp))
8020 (error "Not in a block"))))
8022 (eval-when-compile
8023 (defvar org-property-drawer-re))
8025 (defvar org-property-start-re) ;; defined below
8026 (defun org-clone-subtree-with-time-shift (n &optional shift)
8027 "Clone the task (subtree) at point N times.
8028 The clones will be inserted as siblings.
8030 In interactive use, the user will be prompted for the number of
8031 clones to be produced, and for a time SHIFT, which may be a
8032 repeater as used in time stamps, for example `+3d'.
8034 When a valid repeater is given and the entry contains any time
8035 stamps, the clones will become a sequence in time, with time
8036 stamps in the subtree shifted for each clone produced. If SHIFT
8037 is nil or the empty string, time stamps will be left alone. The
8038 ID property of the original subtree is removed.
8040 If the original subtree did contain time stamps with a repeater,
8041 the following will happen:
8042 - the repeater will be removed in each clone
8043 - an additional clone will be produced, with the current, unshifted
8044 date(s) in the entry.
8045 - the original entry will be placed *after* all the clones, with
8046 repeater intact.
8047 - the start days in the repeater in the original entry will be shifted
8048 to past the last clone.
8049 In this way you can spell out a number of instances of a repeating task,
8050 and still retain the repeater to cover future instances of the task."
8051 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8052 (let (beg end template task idprop
8053 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8054 (drawer-re org-drawer-regexp))
8055 (if (not (and (integerp n) (> n 0)))
8056 (error "Invalid number of replications %s" n))
8057 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8058 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8059 shift)))
8060 (error "Invalid shift specification %s" shift))
8061 (when doshift
8062 (setq shift-n (string-to-number (match-string 1 shift))
8063 shift-what (cdr (assoc (match-string 2 shift)
8064 '(("d" . day) ("w" . week)
8065 ("m" . month) ("y" . year))))))
8066 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8067 (setq nmin 1 nmax n)
8068 (org-back-to-heading t)
8069 (setq beg (point))
8070 (setq idprop (org-entry-get nil "ID"))
8071 (org-end-of-subtree t t)
8072 (or (bolp) (insert "\n"))
8073 (setq end (point))
8074 (setq template (buffer-substring beg end))
8075 (when (and doshift
8076 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8077 (delete-region beg end)
8078 (setq end beg)
8079 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8080 (goto-char end)
8081 (loop for n from nmin to nmax do
8082 ;; prepare clone
8083 (with-temp-buffer
8084 (insert template)
8085 (org-mode)
8086 (goto-char (point-min))
8087 (org-show-subtree)
8088 (and idprop (if org-clone-delete-id
8089 (org-entry-delete nil "ID")
8090 (org-id-get-create t)))
8091 (unless (= n 0)
8092 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8093 (kill-whole-line))
8094 (goto-char (point-min))
8095 (while (re-search-forward drawer-re nil t)
8096 (mapc (lambda (d)
8097 (org-remove-empty-drawer-at d (point))) org-drawers)))
8098 (goto-char (point-min))
8099 (when doshift
8100 (while (re-search-forward org-ts-regexp-both nil t)
8101 (org-timestamp-change (* n shift-n) shift-what))
8102 (unless (= n n-no-remove)
8103 (goto-char (point-min))
8104 (while (re-search-forward org-ts-regexp nil t)
8105 (save-excursion
8106 (goto-char (match-beginning 0))
8107 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8108 (delete-region (match-beginning 1) (match-end 1)))))))
8109 (setq task (buffer-string)))
8110 (insert task))
8111 (goto-char beg)))
8113 ;;; Outline Sorting
8115 (defun org-sort (with-case)
8116 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8117 Optional argument WITH-CASE means sort case-sensitively."
8118 (interactive "P")
8119 (cond
8120 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8121 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8123 (org-call-with-arg 'org-sort-entries with-case))))
8125 (defun org-sort-remove-invisible (s)
8126 (remove-text-properties 0 (length s) org-rm-props s)
8127 (while (string-match org-bracket-link-regexp s)
8128 (setq s (replace-match (if (match-end 2)
8129 (match-string 3 s)
8130 (match-string 1 s)) t t s)))
8133 (defvar org-priority-regexp) ; defined later in the file
8135 (defvar org-after-sorting-entries-or-items-hook nil
8136 "Hook that is run after a bunch of entries or items have been sorted.
8137 When children are sorted, the cursor is in the parent line when this
8138 hook gets called. When a region or a plain list is sorted, the cursor
8139 will be in the first entry of the sorted region/list.")
8141 (defun org-sort-entries
8142 (&optional with-case sorting-type getkey-func compare-func property)
8143 "Sort entries on a certain level of an outline tree.
8144 If there is an active region, the entries in the region are sorted.
8145 Else, if the cursor is before the first entry, sort the top-level items.
8146 Else, the children of the entry at point are sorted.
8148 Sorting can be alphabetically, numerically, by date/time as given by
8149 a time stamp, by a property or by priority.
8151 The command prompts for the sorting type unless it has been given to the
8152 function through the SORTING-TYPE argument, which needs to be a character,
8153 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8154 precise meaning of each character:
8156 n Numerically, by converting the beginning of the entry/item to a number.
8157 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8158 o By order of TODO keywords.
8159 t By date/time, either the first active time stamp in the entry, or, if
8160 none exist, by the first inactive one.
8161 s By the scheduled date/time.
8162 d By deadline date/time.
8163 c By creation time, which is assumed to be the first inactive time stamp
8164 at the beginning of a line.
8165 p By priority according to the cookie.
8166 r By the value of a property.
8168 Capital letters will reverse the sort order.
8170 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8171 called with point at the beginning of the record. It must return either
8172 a string or a number that should serve as the sorting key for that record.
8174 Comparing entries ignores case by default. However, with an optional argument
8175 WITH-CASE, the sorting considers case as well."
8176 (interactive "P")
8177 (let ((case-func (if with-case 'identity 'downcase))
8178 (cmstr
8179 ;; The clock marker is lost when using `sort-subr', let's
8180 ;; store the clocking string.
8181 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8182 (save-excursion
8183 (goto-char org-clock-marker)
8184 (looking-back "^.*") (match-string-no-properties 0))))
8185 start beg end stars re re2
8186 txt what tmp)
8187 ;; Find beginning and end of region to sort
8188 (cond
8189 ((org-region-active-p)
8190 ;; we will sort the region
8191 (setq end (region-end)
8192 what "region")
8193 (goto-char (region-beginning))
8194 (if (not (org-at-heading-p)) (outline-next-heading))
8195 (setq start (point)))
8196 ((or (org-at-heading-p)
8197 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8198 ;; we will sort the children of the current headline
8199 (org-back-to-heading)
8200 (setq start (point)
8201 end (progn (org-end-of-subtree t t)
8202 (or (bolp) (insert "\n"))
8203 (org-back-over-empty-lines)
8204 (point))
8205 what "children")
8206 (goto-char start)
8207 (show-subtree)
8208 (outline-next-heading))
8210 ;; we will sort the top-level entries in this file
8211 (goto-char (point-min))
8212 (or (org-at-heading-p) (outline-next-heading))
8213 (setq start (point))
8214 (goto-char (point-max))
8215 (beginning-of-line 1)
8216 (when (looking-at ".*?\\S-")
8217 ;; File ends in a non-white line
8218 (end-of-line 1)
8219 (insert "\n"))
8220 (setq end (point-max))
8221 (setq what "top-level")
8222 (goto-char start)
8223 (show-all)))
8225 (setq beg (point))
8226 (if (>= beg end) (error "Nothing to sort"))
8228 (looking-at "\\(\\*+\\)")
8229 (setq stars (match-string 1)
8230 re (concat "^" (regexp-quote stars) " +")
8231 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8232 txt (buffer-substring beg end))
8233 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8234 (if (and (not (equal stars "*")) (string-match re2 txt))
8235 (error "Region to sort contains a level above the first entry"))
8237 (unless sorting-type
8238 (message
8239 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8240 [t]ime [s]cheduled [d]eadline [c]reated
8241 A/N/P/R/O/F/T/S/D/C means reversed:"
8242 what)
8243 (setq sorting-type (read-char-exclusive))
8245 (unless getkey-func
8246 (and (= (downcase sorting-type) ?f)
8247 (setq getkey-func
8248 (org-icompleting-read "Sort using function: "
8249 obarray 'fboundp t nil nil))
8250 (setq getkey-func (intern getkey-func))))
8252 (and (= (downcase sorting-type) ?r)
8253 (not property)
8254 (setq property
8255 (org-icompleting-read "Property: "
8256 (mapcar 'list (org-buffer-property-keys t))
8257 nil t))))
8259 (message "Sorting entries...")
8261 (save-restriction
8262 (narrow-to-region start end)
8263 (let ((dcst (downcase sorting-type))
8264 (case-fold-search nil)
8265 (now (current-time)))
8266 (sort-subr
8267 (/= dcst sorting-type)
8268 ;; This function moves to the beginning character of the "record" to
8269 ;; be sorted.
8270 (lambda nil
8271 (if (re-search-forward re nil t)
8272 (goto-char (match-beginning 0))
8273 (goto-char (point-max))))
8274 ;; This function moves to the last character of the "record" being
8275 ;; sorted.
8276 (lambda nil
8277 (save-match-data
8278 (condition-case nil
8279 (outline-forward-same-level 1)
8280 (error
8281 (goto-char (point-max))))))
8282 ;; This function returns the value that gets sorted against.
8283 (lambda nil
8284 (cond
8285 ((= dcst ?n)
8286 (if (looking-at org-complex-heading-regexp)
8287 (string-to-number (match-string 4))
8288 nil))
8289 ((= dcst ?a)
8290 (if (looking-at org-complex-heading-regexp)
8291 (funcall case-func (match-string 4))
8292 nil))
8293 ((= dcst ?t)
8294 (let ((end (save-excursion (outline-next-heading) (point))))
8295 (if (or (re-search-forward org-ts-regexp end t)
8296 (re-search-forward org-ts-regexp-both end t))
8297 (org-time-string-to-seconds (match-string 0))
8298 (org-float-time now))))
8299 ((= dcst ?c)
8300 (let ((end (save-excursion (outline-next-heading) (point))))
8301 (if (re-search-forward
8302 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8303 end t)
8304 (org-time-string-to-seconds (match-string 0))
8305 (org-float-time now))))
8306 ((= dcst ?s)
8307 (let ((end (save-excursion (outline-next-heading) (point))))
8308 (if (re-search-forward org-scheduled-time-regexp end t)
8309 (org-time-string-to-seconds (match-string 1))
8310 (org-float-time now))))
8311 ((= dcst ?d)
8312 (let ((end (save-excursion (outline-next-heading) (point))))
8313 (if (re-search-forward org-deadline-time-regexp end t)
8314 (org-time-string-to-seconds (match-string 1))
8315 (org-float-time now))))
8316 ((= dcst ?p)
8317 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8318 (string-to-char (match-string 2))
8319 org-default-priority))
8320 ((= dcst ?r)
8321 (or (org-entry-get nil property) ""))
8322 ((= dcst ?o)
8323 (if (looking-at org-complex-heading-regexp)
8324 (- 9999 (length (member (match-string 2)
8325 org-todo-keywords-1)))))
8326 ((= dcst ?f)
8327 (if getkey-func
8328 (progn
8329 (setq tmp (funcall getkey-func))
8330 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8331 tmp)
8332 (error "Invalid key function `%s'" getkey-func)))
8333 (t (error "Invalid sorting type `%c'" sorting-type))))
8335 (cond
8336 ((= dcst ?a) 'string<)
8337 ((= dcst ?f) compare-func)
8338 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8339 (run-hooks 'org-after-sorting-entries-or-items-hook)
8340 ;; Reset the clock marker if needed
8341 (when cmstr
8342 (save-excursion
8343 (goto-char start)
8344 (search-forward cmstr nil t)
8345 (move-marker org-clock-marker (point))))
8346 (message "Sorting entries...done")))
8348 (defun org-do-sort (table what &optional with-case sorting-type)
8349 "Sort TABLE of WHAT according to SORTING-TYPE.
8350 The user will be prompted for the SORTING-TYPE if the call to this
8351 function does not specify it. WHAT is only for the prompt, to indicate
8352 what is being sorted. The sorting key will be extracted from
8353 the car of the elements of the table.
8354 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8355 (unless sorting-type
8356 (message
8357 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8358 what)
8359 (setq sorting-type (read-char-exclusive)))
8360 (let ((dcst (downcase sorting-type))
8361 extractfun comparefun)
8362 ;; Define the appropriate functions
8363 (cond
8364 ((= dcst ?n)
8365 (setq extractfun 'string-to-number
8366 comparefun (if (= dcst sorting-type) '< '>)))
8367 ((= dcst ?a)
8368 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8369 (lambda(x) (downcase (org-sort-remove-invisible x))))
8370 comparefun (if (= dcst sorting-type)
8371 'string<
8372 (lambda (a b) (and (not (string< a b))
8373 (not (string= a b)))))))
8374 ((= dcst ?t)
8375 (setq extractfun
8376 (lambda (x)
8377 (if (or (string-match org-ts-regexp x)
8378 (string-match org-ts-regexp-both x))
8379 (org-float-time
8380 (org-time-string-to-time (match-string 0 x)))
8382 comparefun (if (= dcst sorting-type) '< '>)))
8383 (t (error "Invalid sorting type `%c'" sorting-type)))
8385 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8386 table)
8387 (lambda (a b) (funcall comparefun (car a) (car b))))))
8390 ;;; The orgstruct minor mode
8392 ;; Define a minor mode which can be used in other modes in order to
8393 ;; integrate the org-mode structure editing commands.
8395 ;; This is really a hack, because the org-mode structure commands use
8396 ;; keys which normally belong to the major mode. Here is how it
8397 ;; works: The minor mode defines all the keys necessary to operate the
8398 ;; structure commands, but wraps the commands into a function which
8399 ;; tests if the cursor is currently at a headline or a plain list
8400 ;; item. If that is the case, the structure command is used,
8401 ;; temporarily setting many Org-mode variables like regular
8402 ;; expressions for filling etc. However, when any of those keys is
8403 ;; used at a different location, function uses `key-binding' to look
8404 ;; up if the key has an associated command in another currently active
8405 ;; keymap (minor modes, major mode, global), and executes that
8406 ;; command. There might be problems if any of the keys is otherwise
8407 ;; used as a prefix key.
8409 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8410 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8411 ;; addresses this by checking explicitly for both bindings.
8413 (defvar orgstruct-mode-map (make-sparse-keymap)
8414 "Keymap for the minor `orgstruct-mode'.")
8416 (defvar org-local-vars nil
8417 "List of local variables, for use by `orgstruct-mode'.")
8419 ;;;###autoload
8420 (define-minor-mode orgstruct-mode
8421 "Toggle the minor mode `orgstruct-mode'.
8422 This mode is for using Org-mode structure commands in other
8423 modes. The following keys behave as if Org-mode were active, if
8424 the cursor is on a headline, or on a plain list item (both as
8425 defined by Org-mode).
8427 M-up Move entry/item up
8428 M-down Move entry/item down
8429 M-left Promote
8430 M-right Demote
8431 M-S-up Move entry/item up
8432 M-S-down Move entry/item down
8433 M-S-left Promote subtree
8434 M-S-right Demote subtree
8435 M-q Fill paragraph and items like in Org-mode
8436 C-c ^ Sort entries
8437 C-c - Cycle list bullet
8438 TAB Cycle item visibility
8439 M-RET Insert new heading/item
8440 S-M-RET Insert new TODO heading / Checkbox item
8441 C-c C-c Set tags / toggle checkbox"
8442 nil " OrgStruct" nil
8443 (org-load-modules-maybe)
8444 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8446 ;;;###autoload
8447 (defun turn-on-orgstruct ()
8448 "Unconditionally turn on `orgstruct-mode'."
8449 (orgstruct-mode 1))
8451 (defvar org-fb-vars nil)
8452 (make-variable-buffer-local 'org-fb-vars)
8453 (defun orgstruct++-mode (&optional arg)
8454 "Toggle `orgstruct-mode', the enhanced version of it.
8455 In addition to setting orgstruct-mode, this also exports all
8456 indentation and autofilling variables from org-mode into the
8457 buffer. It will also recognize item context in multiline items."
8458 (interactive "P")
8459 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8460 (if (< arg 1)
8461 (progn (orgstruct-mode -1)
8462 (mapc (lambda(v)
8463 (org-set-local (car v)
8464 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8465 org-fb-vars))
8466 (orgstruct-mode 1)
8467 (setq org-fb-vars nil)
8468 (let (var val)
8469 (mapc
8470 (lambda (x)
8471 (when (string-match
8472 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8473 (symbol-name (car x)))
8474 (setq var (car x) val (nth 1 x))
8475 (push (list var `(quote ,(eval var))) org-fb-vars)
8476 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8477 org-local-vars)
8478 (org-set-local 'orgstruct-is-++ t))))
8480 (defvar orgstruct-is-++ nil
8481 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8482 (make-variable-buffer-local 'orgstruct-is-++)
8484 ;;;###autoload
8485 (defun turn-on-orgstruct++ ()
8486 "Unconditionally turn on `orgstruct++-mode'."
8487 (orgstruct++-mode 1))
8489 (defun orgstruct-error ()
8490 "Error when there is no default binding for a structure key."
8491 (interactive)
8492 (error "This key has no function outside structure elements"))
8494 (defun orgstruct-setup ()
8495 "Setup orgstruct keymaps."
8496 (let ((nfunc 0)
8497 (bindings
8498 (list
8499 '([(meta up)] org-metaup)
8500 '([(meta down)] org-metadown)
8501 '([(meta left)] org-metaleft)
8502 '([(meta right)] org-metaright)
8503 '([(meta shift up)] org-shiftmetaup)
8504 '([(meta shift down)] org-shiftmetadown)
8505 '([(meta shift left)] org-shiftmetaleft)
8506 '([(meta shift right)] org-shiftmetaright)
8507 '([?\e (up)] org-metaup)
8508 '([?\e (down)] org-metadown)
8509 '([?\e (left)] org-metaleft)
8510 '([?\e (right)] org-metaright)
8511 '([?\e (shift up)] org-shiftmetaup)
8512 '([?\e (shift down)] org-shiftmetadown)
8513 '([?\e (shift left)] org-shiftmetaleft)
8514 '([?\e (shift right)] org-shiftmetaright)
8515 '([(shift up)] org-shiftup)
8516 '([(shift down)] org-shiftdown)
8517 '([(shift left)] org-shiftleft)
8518 '([(shift right)] org-shiftright)
8519 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8520 '("\M-q" fill-paragraph)
8521 '("\C-c^" org-sort)
8522 '("\C-c-" org-cycle-list-bullet)))
8523 elt key fun cmd)
8524 (while (setq elt (pop bindings))
8525 (setq nfunc (1+ nfunc))
8526 (setq key (org-key (car elt))
8527 fun (nth 1 elt)
8528 cmd (orgstruct-make-binding fun nfunc key))
8529 (org-defkey orgstruct-mode-map key cmd))
8531 ;; Prevent an error for users who forgot to make autoloads
8532 (require 'org-element)
8534 ;; Special treatment needed for TAB and RET
8535 (org-defkey orgstruct-mode-map [(tab)]
8536 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8537 (org-defkey orgstruct-mode-map "\C-i"
8538 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8540 (org-defkey orgstruct-mode-map "\M-\C-m"
8541 (orgstruct-make-binding 'org-insert-heading 105
8542 "\M-\C-m" [(meta return)]))
8543 (org-defkey orgstruct-mode-map [(meta return)]
8544 (orgstruct-make-binding 'org-insert-heading 106
8545 [(meta return)] "\M-\C-m"))
8547 (org-defkey orgstruct-mode-map [(shift meta return)]
8548 (orgstruct-make-binding 'org-insert-todo-heading 107
8549 [(meta return)] "\M-\C-m"))
8551 (org-defkey orgstruct-mode-map "\e\C-m"
8552 (orgstruct-make-binding 'org-insert-heading 108
8553 "\e\C-m" [?\e (return)]))
8554 (org-defkey orgstruct-mode-map [?\e (return)]
8555 (orgstruct-make-binding 'org-insert-heading 109
8556 [?\e (return)] "\e\C-m"))
8557 (org-defkey orgstruct-mode-map [?\e (shift return)]
8558 (orgstruct-make-binding 'org-insert-todo-heading 110
8559 [?\e (return)] "\e\C-m"))
8561 (unless org-local-vars
8562 (setq org-local-vars (org-get-local-variables)))
8566 (defun orgstruct-make-binding (fun n &rest keys)
8567 "Create a function for binding in the structure minor mode.
8568 FUN is the command to call inside a table. N is used to create a unique
8569 command name. KEYS are keys that should be checked in for a command
8570 to execute outside of tables."
8571 (eval
8572 (list 'defun
8573 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8574 '(arg)
8575 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8576 "Outside of structure, run the binding of `"
8577 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8578 "'.")
8579 '(interactive "p")
8580 (list 'if
8581 `(org-context-p 'headline 'item
8582 (and orgstruct-is-++
8583 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8584 'item-body))
8585 (list 'org-run-like-in-org-mode (list 'quote fun))
8586 (list 'let '(orgstruct-mode)
8587 (list 'call-interactively
8588 (append '(or)
8589 (mapcar (lambda (k)
8590 (list 'key-binding k))
8591 keys)
8592 '('orgstruct-error))))))))
8594 (defun org-contextualize-keys (alist contexts)
8595 "Return valid elements in ALIST depending on CONTEXTS.
8597 `org-agenda-custom-commands' or `org-capture-templates' are the
8598 values used for ALIST, and `org-agenda-custom-commands-contexts'
8599 or `org-capture-templates-contexts' are the associated contexts
8600 definitions."
8601 (let ((contexts
8602 ;; normalize contexts
8603 (mapcar
8604 (lambda(c) (cond ((listp (cadr c))
8605 (list (car c) (car c) (cadr c)))
8606 ((string= "" (cadr c))
8607 (list (car c) (car c) (caddr c)))
8608 (t c))) contexts))
8609 (a alist) c r s)
8610 ;; loop over all commands or templates
8611 (while (setq c (pop a))
8612 (let (vrules repl)
8613 (cond
8614 ((not (assoc (car c) contexts))
8615 (push c r))
8616 ((and (assoc (car c) contexts)
8617 (setq vrules (org-contextualize-validate-key
8618 (car c) contexts)))
8619 (mapc (lambda (vr)
8620 (when (not (equal (car vr) (cadr vr)))
8621 (setq repl vr))) vrules)
8622 (if (not repl) (push c r)
8623 (push (cadr repl) s)
8624 (push
8625 (cons (car c)
8626 (cdr (or (assoc (cadr repl) alist)
8627 (error "Undefined key `%s' as contextual replacement for `%s'"
8628 (cadr repl) (car c)))))
8629 r))))))
8630 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8631 (delq
8633 (delete-dups
8634 (mapcar (lambda (x)
8635 (let ((tpl (car x)))
8636 (when (not (delq
8638 (mapcar (lambda(y)
8639 (equal y tpl)) s))) x)))
8640 (reverse r))))))
8642 (defun org-contextualize-validate-key (key contexts)
8643 "Check CONTEXTS for agenda or capture KEY."
8644 (let (r rr res)
8645 (while (setq r (pop contexts))
8646 (mapc
8647 (lambda (rr)
8648 (when
8649 (and (equal key (car r))
8650 (if (functionp rr) (funcall rr)
8651 (or (and (eq (car rr) 'in-file)
8652 (buffer-file-name)
8653 (string-match (cdr rr) (buffer-file-name)))
8654 (and (eq (car rr) 'in-mode)
8655 (string-match (cdr rr) (symbol-name major-mode)))
8656 (and (eq (car rr) 'in-buffer)
8657 (string-match (cdr rr) (buffer-name)))
8658 (when (and (eq (car rr) 'not-in-file)
8659 (buffer-file-name))
8660 (not (string-match (cdr rr) (buffer-file-name))))
8661 (when (eq (car rr) 'not-in-mode)
8662 (not (string-match (cdr rr) (symbol-name major-mode))))
8663 (when (eq (car rr) 'not-in-buffer)
8664 (not (string-match (cdr rr) (buffer-name)))))))
8665 (push r res)))
8666 (car (last r))))
8667 (delete-dups (delq nil res))))
8669 (defun org-context-p (&rest contexts)
8670 "Check if local context is any of CONTEXTS.
8671 Possible values in the list of contexts are `table', `headline', and `item'."
8672 (let ((pos (point)))
8673 (goto-char (point-at-bol))
8674 (prog1 (or (and (memq 'table contexts)
8675 (looking-at "[ \t]*|"))
8676 (and (memq 'headline contexts)
8677 (looking-at org-outline-regexp))
8678 (and (memq 'item contexts)
8679 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8680 (and (memq 'item-body contexts)
8681 (org-in-item-p)))
8682 (goto-char pos))))
8684 (defun org-get-local-variables ()
8685 "Return a list of all local variables in an Org mode buffer."
8686 (let (varlist)
8687 (with-current-buffer (get-buffer-create "*Org tmp*")
8688 (erase-buffer)
8689 (org-mode)
8690 (setq varlist (buffer-local-variables)))
8691 (kill-buffer "*Org tmp*")
8692 (delq nil
8693 (mapcar
8694 (lambda (x)
8695 (setq x
8696 (if (symbolp x)
8697 (list x)
8698 (list (car x) (list 'quote (cdr x)))))
8699 (if (string-match
8700 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8701 (symbol-name (car x)))
8702 x nil))
8703 varlist))))
8705 (defun org-clone-local-variables (from-buffer &optional regexp)
8706 "Clone local variables from FROM-BUFFER.
8707 Optional argument REGEXP selects variables to clone."
8708 (mapc
8709 (lambda (pair)
8710 (and (symbolp (car pair))
8711 (or (null regexp)
8712 (string-match regexp (symbol-name (car pair))))
8713 (set (make-local-variable (car pair))
8714 (cdr pair))))
8715 (buffer-local-variables from-buffer)))
8717 ;;;###autoload
8718 (defun org-run-like-in-org-mode (cmd)
8719 "Run a command, pretending that the current buffer is in Org-mode.
8720 This will temporarily bind local variables that are typically bound in
8721 Org-mode to the values they have in Org-mode, and then interactively
8722 call CMD."
8723 (org-load-modules-maybe)
8724 (unless org-local-vars
8725 (setq org-local-vars (org-get-local-variables)))
8726 (eval (list 'let org-local-vars
8727 (list 'call-interactively (list 'quote cmd)))))
8729 ;;;; Archiving
8731 (defun org-get-category (&optional pos force-refresh)
8732 "Get the category applying to position POS."
8733 (save-match-data
8734 (if force-refresh (org-refresh-category-properties))
8735 (let ((pos (or pos (point))))
8736 (or (get-text-property pos 'org-category)
8737 (progn (org-refresh-category-properties)
8738 (get-text-property pos 'org-category))))))
8740 (defun org-refresh-category-properties ()
8741 "Refresh category text properties in the buffer."
8742 (let ((case-fold-search t)
8743 (inhibit-read-only t)
8744 (def-cat (cond
8745 ((null org-category)
8746 (if buffer-file-name
8747 (file-name-sans-extension
8748 (file-name-nondirectory buffer-file-name))
8749 "???"))
8750 ((symbolp org-category) (symbol-name org-category))
8751 (t org-category)))
8752 beg end cat pos optionp)
8753 (org-unmodified
8754 (save-excursion
8755 (save-restriction
8756 (widen)
8757 (goto-char (point-min))
8758 (put-text-property (point) (point-max) 'org-category def-cat)
8759 (while (re-search-forward
8760 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8761 (setq pos (match-end 0)
8762 optionp (equal (char-after (match-beginning 0)) ?#)
8763 cat (org-trim (match-string 2)))
8764 (if optionp
8765 (setq beg (point-at-bol) end (point-max))
8766 (org-back-to-heading t)
8767 (setq beg (point) end (org-end-of-subtree t t)))
8768 (put-text-property beg end 'org-category cat)
8769 (put-text-property beg end 'org-category-position beg)
8770 (goto-char pos)))))))
8772 (defun org-refresh-properties (dprop tprop)
8773 "Refresh buffer text properties.
8774 DPROP is the drawer property and TPROP is the corresponding text
8775 property to set."
8776 (let ((case-fold-search t)
8777 (inhibit-read-only t) p)
8778 (org-unmodified
8779 (save-excursion
8780 (save-restriction
8781 (widen)
8782 (goto-char (point-min))
8783 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
8784 (setq p (org-match-string-no-properties 1))
8785 (save-excursion
8786 (org-back-to-heading t)
8787 (put-text-property
8788 (point-at-bol) (point-at-eol) tprop p))))))))
8791 ;;;; Link Stuff
8793 ;;; Link abbreviations
8795 (defun org-link-expand-abbrev (link)
8796 "Apply replacements as defined in `org-link-abbrev-alist'."
8797 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8798 (let* ((key (match-string 1 link))
8799 (as (or (assoc key org-link-abbrev-alist-local)
8800 (assoc key org-link-abbrev-alist)))
8801 (tag (and (match-end 2) (match-string 3 link)))
8802 rpl)
8803 (if (not as)
8804 link
8805 (setq rpl (cdr as))
8806 (cond
8807 ((symbolp rpl) (funcall rpl tag))
8808 ((string-match "%(\\([^)]+\\))" rpl)
8809 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8810 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8811 ((string-match "%h" rpl)
8812 (replace-match (url-hexify-string (or tag "")) t t rpl))
8813 (t (concat rpl tag)))))
8814 link))
8816 ;;; Storing and inserting links
8818 (defvar org-insert-link-history nil
8819 "Minibuffer history for links inserted with `org-insert-link'.")
8821 (defvar org-stored-links nil
8822 "Contains the links stored with `org-store-link'.")
8824 (defvar org-store-link-plist nil
8825 "Plist with info about the most recently link created with `org-store-link'.")
8827 (defvar org-link-protocols nil
8828 "Link protocols added to Org-mode using `org-add-link-type'.")
8830 (defvar org-store-link-functions nil
8831 "List of functions that are called to create and store a link.
8832 Each function will be called in turn until one returns a non-nil
8833 value. Each function should check if it is responsible for creating
8834 this link (for example by looking at the major mode).
8835 If not, it must exit and return nil.
8836 If yes, it should return a non-nil value after a calling
8837 `org-store-link-props' with a list of properties and values.
8838 Special properties are:
8840 :type The link prefix, like \"http\". This must be given.
8841 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8842 This is obligatory as well.
8843 :description Optional default description for the second pair
8844 of brackets in an Org-mode link. The user can still change
8845 this when inserting this link into an Org-mode buffer.
8847 In addition to these, any additional properties can be specified
8848 and then used in capture templates.")
8850 (defun org-add-link-type (type &optional follow export)
8851 "Add TYPE to the list of `org-link-types'.
8852 Re-compute all regular expressions depending on `org-link-types'
8854 FOLLOW and EXPORT are two functions.
8856 FOLLOW should take the link path as the single argument and do whatever
8857 is necessary to follow the link, for example find a file or display
8858 a mail message.
8860 EXPORT should format the link path for export to one of the export formats.
8861 It should be a function accepting three arguments:
8863 path the path of the link, the text after the prefix (like \"http:\")
8864 desc the description of the link, if any, or a description added by
8865 org-export-normalize-links if there is none
8866 format the export format, a symbol like `html' or `latex' or `ascii'..
8868 The function may use the FORMAT information to return different values
8869 depending on the format. The return value will be put literally into
8870 the exported file. If the return value is nil, this means Org should
8871 do what it normally does with links which do not have EXPORT defined.
8873 Org-mode has a built-in default for exporting links. If you are happy with
8874 this default, there is no need to define an export function for the link
8875 type. For a simple example of an export function, see `org-bbdb.el'."
8876 (add-to-list 'org-link-types type t)
8877 (org-make-link-regexps)
8878 (if (assoc type org-link-protocols)
8879 (setcdr (assoc type org-link-protocols) (list follow export))
8880 (push (list type follow export) org-link-protocols)))
8882 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8883 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
8885 ;;;###autoload
8886 (defun org-store-link (arg)
8887 "\\<org-mode-map>Store an org-link to the current location.
8888 This link is added to `org-stored-links' and can later be inserted
8889 into an org-buffer with \\[org-insert-link].
8891 For some link types, a prefix arg is interpreted.
8892 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
8893 For file links, arg negates `org-context-in-file-links'.
8895 A double prefix arg force skipping storing functions that are not
8896 part of Org's core."
8897 (interactive "P")
8898 (org-load-modules-maybe)
8899 (setq org-store-link-plist nil) ; reset
8900 (org-with-limited-levels
8901 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
8902 (cond
8903 ((and (not (equal arg '(16)))
8904 (setq sfuns
8905 (delq
8906 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
8907 org-store-link-functions))
8908 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
8909 (or (and (cdr sfuns)
8910 (funcall (intern
8911 (completing-read "Which function for creating the link? "
8912 sfunsn t (car sfunsn)))))
8913 (funcall (caar sfuns)))
8914 (setq link (plist-get org-store-link-plist :link)
8915 desc (or (plist-get org-store-link-plist :description) link))))
8916 ((org-src-edit-buffer-p)
8917 (let (label gc)
8918 (while (or (not label)
8919 (save-excursion
8920 (save-restriction
8921 (widen)
8922 (goto-char (point-min))
8923 (re-search-forward
8924 (regexp-quote (format org-coderef-label-format label))
8925 nil t))))
8926 (when label (message "Label exists already") (sit-for 2))
8927 (setq label (read-string "Code line label: " label)))
8928 (end-of-line 1)
8929 (setq link (format org-coderef-label-format label))
8930 (setq gc (- 79 (length link)))
8931 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8932 (insert link)
8933 (setq link (concat "(" label ")") desc nil)))
8935 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8936 ;; We are in the agenda, link to referenced location
8937 (let ((m (or (get-text-property (point) 'org-hd-marker)
8938 (get-text-property (point) 'org-marker))))
8939 (when m
8940 (org-with-point-at m
8941 (setq agenda-link
8942 (if (org-called-interactively-p 'any)
8943 (call-interactively 'org-store-link)
8944 (org-store-link nil)))))))
8946 ((eq major-mode 'calendar-mode)
8947 (let ((cd (calendar-cursor-to-date)))
8948 (setq link
8949 (format-time-string
8950 (car org-time-stamp-formats)
8951 (apply 'encode-time
8952 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8953 nil nil nil))))
8954 (org-store-link-props :type "calendar" :date cd)))
8956 ((eq major-mode 'help-mode)
8957 (setq link (concat "help:" (save-excursion
8958 (goto-char (point-min))
8959 (looking-at "^[^ ]+")
8960 (match-string 0))))
8961 (org-store-link-props :type "help"))
8963 ((eq major-mode 'w3-mode)
8964 (setq cpltxt (if (and (buffer-name)
8965 (not (string-match "Untitled" (buffer-name))))
8966 (buffer-name)
8967 (url-view-url t))
8968 link (url-view-url t))
8969 (org-store-link-props :type "w3" :url (url-view-url t)))
8971 ((setq search (run-hook-with-args-until-success
8972 'org-create-file-search-functions))
8973 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8974 "::" search))
8975 (setq cpltxt (or description link)))
8977 ((eq major-mode 'image-mode)
8978 (setq cpltxt (concat "file:"
8979 (abbreviate-file-name buffer-file-name))
8980 link cpltxt)
8981 (org-store-link-props :type "image" :file buffer-file-name))
8983 ((eq major-mode 'dired-mode)
8984 ;; link to the file in the current line
8985 (let ((file (dired-get-filename nil t)))
8986 (setq file (if file
8987 (abbreviate-file-name
8988 (expand-file-name (dired-get-filename nil t)))
8989 ;; otherwise, no file so use current directory.
8990 default-directory))
8991 (setq cpltxt (concat "file:" file)
8992 link cpltxt)))
8994 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8995 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8996 (cond
8997 ((org-in-regexp "<<\\(.*?\\)>>")
8998 (setq cpltxt
8999 (concat "file:"
9000 (abbreviate-file-name
9001 (buffer-file-name (buffer-base-buffer)))
9002 "::" (match-string 1))
9003 link cpltxt))
9004 ((and (featurep 'org-id)
9005 (or (eq org-id-link-to-org-use-id t)
9006 (and (org-called-interactively-p 'any)
9007 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9008 (and (eq org-id-link-to-org-use-id
9009 'create-if-interactive-and-no-custom-id)
9010 (not custom-id))))
9011 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9012 ;; We can make a link using the ID.
9013 (setq link (condition-case nil
9014 (prog1 (org-id-store-link)
9015 (setq desc (plist-get org-store-link-plist :description)))
9016 (error
9017 ;; probably before first headline, link to file only
9018 (concat "file:"
9019 (abbreviate-file-name
9020 (buffer-file-name (buffer-base-buffer))))))))
9022 ;; Just link to current headline
9023 (setq cpltxt (concat "file:"
9024 (abbreviate-file-name
9025 (buffer-file-name (buffer-base-buffer)))))
9026 ;; Add a context search string
9027 (when (org-xor org-context-in-file-links arg)
9028 (let* ((ee (org-element-at-point))
9029 (et (org-element-type ee))
9030 (ev (plist-get (cadr ee) :value)))
9031 (setq txt (cond
9032 ((org-at-heading-p) nil)
9033 ((eq et 'keyword) ev)
9034 ((org-region-active-p)
9035 (buffer-substring (region-beginning) (region-end)))))
9036 (when (or (null txt) (string-match "\\S-" txt))
9037 (setq cpltxt
9038 (concat cpltxt "::"
9039 (condition-case nil
9040 (org-make-org-heading-search-string txt)
9041 (error "")))
9042 desc (or (and (eq et 'keyword) ev)
9043 (nth 4 (ignore-errors (org-heading-components)))
9044 "NONE")))))
9045 (if (string-match "::\\'" cpltxt)
9046 (setq cpltxt (substring cpltxt 0 -2)))
9047 (setq link cpltxt))))
9049 ((buffer-file-name (buffer-base-buffer))
9050 ;; Just link to this file here.
9051 (setq cpltxt (concat "file:"
9052 (abbreviate-file-name
9053 (buffer-file-name (buffer-base-buffer)))))
9054 ;; Add a context string
9055 (when (org-xor org-context-in-file-links arg)
9056 (setq txt (if (org-region-active-p)
9057 (buffer-substring (region-beginning) (region-end))
9058 (buffer-substring (point-at-bol) (point-at-eol))))
9059 ;; Only use search option if there is some text.
9060 (when (string-match "\\S-" txt)
9061 (setq cpltxt
9062 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9063 desc "NONE")))
9064 (setq link cpltxt))
9066 ((org-called-interactively-p 'interactive)
9067 (user-error "No method for storing a link from this buffer"))
9069 (t (setq link nil)))
9071 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9072 (setq link (or link cpltxt)
9073 desc (or desc cpltxt))
9074 (cond ((equal desc "NONE") (setq desc nil))
9075 ((string-match org-bracket-link-regexp desc)
9076 (setq desc (replace-regexp-in-string
9077 org-bracket-link-regexp
9078 (concat "\\3" (if (equal (length (match-string 0 desc))
9079 (length desc)) "*" "")) desc))))
9081 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9082 (progn
9083 (setq org-stored-links
9084 (cons (list link desc) org-stored-links))
9085 (message "Stored: %s" (or desc link))
9086 (when custom-id
9087 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9088 "::#" custom-id))
9089 (setq org-stored-links
9090 (cons (list link desc) org-stored-links))))
9091 (or agenda-link (and link (org-make-link-string link desc)))))))
9093 (defun org-store-link-props (&rest plist)
9094 "Store link properties, extract names and addresses."
9095 (let (x adr)
9096 (when (setq x (plist-get plist :from))
9097 (setq adr (mail-extract-address-components x))
9098 (setq plist (plist-put plist :fromname (car adr)))
9099 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9100 (when (setq x (plist-get plist :to))
9101 (setq adr (mail-extract-address-components x))
9102 (setq plist (plist-put plist :toname (car adr)))
9103 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9104 (let ((from (plist-get plist :from))
9105 (to (plist-get plist :to)))
9106 (when (and from to org-from-is-user-regexp)
9107 (setq plist
9108 (plist-put plist :fromto
9109 (if (string-match org-from-is-user-regexp from)
9110 (concat "to %t")
9111 (concat "from %f"))))))
9112 (setq org-store-link-plist plist))
9114 (defun org-add-link-props (&rest plist)
9115 "Add these properties to the link property list."
9116 (let (key value)
9117 (while plist
9118 (setq key (pop plist) value (pop plist))
9119 (setq org-store-link-plist
9120 (plist-put org-store-link-plist key value)))))
9122 (defun org-email-link-description (&optional fmt)
9123 "Return the description part of an email link.
9124 This takes information from `org-store-link-plist' and formats it
9125 according to FMT (default from `org-email-link-description-format')."
9126 (setq fmt (or fmt org-email-link-description-format))
9127 (let* ((p org-store-link-plist)
9128 (to (plist-get p :toaddress))
9129 (from (plist-get p :fromaddress))
9130 (table
9131 (list
9132 (cons "%c" (plist-get p :fromto))
9133 (cons "%F" (plist-get p :from))
9134 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9135 (cons "%T" (plist-get p :to))
9136 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9137 (cons "%s" (plist-get p :subject))
9138 (cons "%d" (plist-get p :date))
9139 (cons "%m" (plist-get p :message-id)))))
9140 (when (string-match "%c" fmt)
9141 ;; Check if the user wrote this message
9142 (if (and org-from-is-user-regexp from to
9143 (save-match-data (string-match org-from-is-user-regexp from)))
9144 (setq fmt (replace-match "to %t" t t fmt))
9145 (setq fmt (replace-match "from %f" t t fmt))))
9146 (org-replace-escapes fmt table)))
9148 (defun org-make-org-heading-search-string (&optional string)
9149 "Make search string for the current headline or STRING."
9150 (let ((s (or string
9151 (and (derived-mode-p 'org-mode)
9152 (save-excursion
9153 (org-back-to-heading t)
9154 (plist-get (cadr (org-element-at-point))
9155 :raw-value)))))
9156 (lines org-context-in-file-links))
9157 (or string (setq s (concat "*" s))) ; Add * for headlines
9158 (when (and string (integerp lines) (> lines 0))
9159 (let ((slines (org-split-string s "\n")))
9160 (when (< lines (length slines))
9161 (setq s (mapconcat
9162 'identity
9163 (reverse (nthcdr (- (length slines) lines)
9164 (reverse slines))) "\n")))))
9165 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9167 (defun org-make-link-string (link &optional description)
9168 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9169 (unless (string-match "\\S-" link)
9170 (error "Empty link"))
9171 (when (and description
9172 (stringp description)
9173 (not (string-match "\\S-" description)))
9174 (setq description nil))
9175 (when (stringp description)
9176 ;; Remove brackets from the description, they are fatal.
9177 (while (string-match "\\[" description)
9178 (setq description (replace-match "{" t t description)))
9179 (while (string-match "\\]" description)
9180 (setq description (replace-match "}" t t description))))
9181 (when (equal link description)
9182 ;; No description needed, it is identical
9183 (setq description nil))
9184 (when (and (not description)
9185 (not (string-match (org-image-file-name-regexp) link))
9186 (not (equal link (org-link-escape link))))
9187 (setq description (org-extract-attributes link)))
9188 (setq link
9189 (cond ((string-match (org-image-file-name-regexp) link) link)
9190 ((string-match org-link-types-re link)
9191 (concat (match-string 1 link)
9192 (org-link-escape (substring link (match-end 1)))))
9193 (t (org-link-escape link))))
9194 (concat "[[" link "]"
9195 (if description (concat "[" description "]") "")
9196 "]"))
9198 (defconst org-link-escape-chars
9199 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9200 "List of characters that should be escaped in link.
9201 This is the list that is used for internal purposes.")
9203 (defconst org-link-escape-chars-browser
9204 '(?\ )
9205 "List of escapes for characters that are problematic in links.
9206 This is the list that is used before handing over to the browser.")
9208 (defun org-link-escape (text &optional table merge)
9209 "Return percent escaped representation of TEXT.
9210 TEXT is a string with the text to escape.
9211 Optional argument TABLE is a list with characters that should be
9212 escaped. When nil, `org-link-escape-chars' is used.
9213 If optional argument MERGE is set, merge TABLE into
9214 `org-link-escape-chars'."
9215 (cond
9216 ((and table merge)
9217 (mapc (lambda (defchr)
9218 (unless (member defchr table)
9219 (setq table (cons defchr table)))) org-link-escape-chars))
9220 ((null table)
9221 (setq table org-link-escape-chars)))
9222 (mapconcat
9223 (lambda (char)
9224 (if (or (member char table)
9225 (and (or (< char 32) (= char 37) (> char 126))
9226 org-url-hexify-p))
9227 (mapconcat (lambda (sequence-element)
9228 (format "%%%.2X" sequence-element))
9229 (or (encode-coding-char char 'utf-8)
9230 (error "Unable to percent escape character: %s"
9231 (char-to-string char))) "")
9232 (char-to-string char))) text ""))
9234 (defun org-link-unescape (str)
9235 "Unhex hexified Unicode strings as returned from the JavaScript function
9236 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9237 (unless (and (null str) (string= "" str))
9238 (let ((pos 0) (case-fold-search t) unhexed)
9239 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9240 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9241 (setq str (replace-match unhexed t t str))
9242 (setq pos (+ pos (length unhexed))))))
9243 str)
9245 (defun org-link-unescape-compound (hex)
9246 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9247 Note: this function also decodes single byte encodings like
9248 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9249 (save-match-data
9250 (let* ((bytes (cdr (split-string hex "%")))
9251 (ret "")
9252 (eat 0)
9253 (sum 0))
9254 (while bytes
9255 (let* ((val (string-to-number (pop bytes) 16))
9256 (shift-xor
9257 (if (= 0 eat)
9258 (cond
9259 ((>= val 252) (cons 6 252))
9260 ((>= val 248) (cons 5 248))
9261 ((>= val 240) (cons 4 240))
9262 ((>= val 224) (cons 3 224))
9263 ((>= val 192) (cons 2 192))
9264 (t (cons 0 0)))
9265 (cons 6 128))))
9266 (if (>= val 192) (setq eat (car shift-xor)))
9267 (setq val (logxor val (cdr shift-xor)))
9268 (setq sum (+ (lsh sum (car shift-xor)) val))
9269 (if (> eat 0) (setq eat (- eat 1)))
9270 (cond
9271 ((= 0 eat) ;multi byte
9272 (setq ret (concat ret (org-char-to-string sum)))
9273 (setq sum 0))
9274 ((not bytes) ; single byte(s)
9275 (setq ret (org-link-unescape-single-byte-sequence hex))))
9276 )) ;; end (while bytes
9277 ret )))
9279 (defun org-link-unescape-single-byte-sequence (hex)
9280 "Unhexify hex-encoded single byte character sequences."
9281 (mapconcat (lambda (byte)
9282 (char-to-string (string-to-number byte 16)))
9283 (cdr (split-string hex "%")) ""))
9285 (defun org-xor (a b)
9286 "Exclusive or."
9287 (if a (not b) b))
9289 (defun org-fixup-message-id-for-http (s)
9290 "Replace special characters in a message id, so it can be used in an http query."
9291 (when (string-match "%" s)
9292 (setq s (mapconcat (lambda (c)
9293 (if (eq c ?%)
9294 "%25"
9295 (char-to-string c)))
9296 s "")))
9297 (while (string-match "<" s)
9298 (setq s (replace-match "%3C" t t s)))
9299 (while (string-match ">" s)
9300 (setq s (replace-match "%3E" t t s)))
9301 (while (string-match "@" s)
9302 (setq s (replace-match "%40" t t s)))
9305 (defun org-link-prettify (link)
9306 "Return a human-readable representation of LINK.
9307 The car of LINK must be a raw link the cdr of LINK must be either
9308 a link description or nil."
9309 (let ((desc (or (cadr link) "<no description>")))
9310 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9311 "<" (car link) ">")))
9313 ;;;###autoload
9314 (defun org-insert-link-global ()
9315 "Insert a link like Org-mode does.
9316 This command can be called in any mode to insert a link in Org-mode syntax."
9317 (interactive)
9318 (org-load-modules-maybe)
9319 (org-run-like-in-org-mode 'org-insert-link))
9321 (defun org-insert-all-links (&optional keep)
9322 "Insert all links in `org-stored-links'."
9323 (interactive "P")
9324 (let ((links (copy-sequence org-stored-links)) l)
9325 (while (setq l (if keep (pop links) (pop org-stored-links)))
9326 (insert "- ")
9327 (org-insert-link nil (car l) (cadr l))
9328 (insert "\n"))))
9330 (defun org-link-fontify-links-to-this-file ()
9331 "Fontify links to the current file in `org-stored-links'."
9332 (let ((f (buffer-file-name)) a b)
9333 (setq a (mapcar (lambda(l)
9334 (let ((ll (car l)))
9335 (when (and (string-match "^file:\\(.+\\)::" ll)
9336 (equal f (expand-file-name (match-string 1 ll))))
9337 ll)))
9338 org-stored-links))
9339 (when (featurep 'org-id)
9340 (setq b (mapcar (lambda(l)
9341 (let ((ll (car l)))
9342 (when (and (string-match "^id:\\(.+\\)$" ll)
9343 (equal f (expand-file-name
9344 (or (org-id-find-id-file
9345 (match-string 1 ll)) ""))))
9346 ll)))
9347 org-stored-links)))
9348 (mapcar (lambda(l)
9349 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9350 (delq nil (append a b)))))
9352 (defvar org-link-links-in-this-file nil)
9353 (defun org-insert-link (&optional complete-file link-location default-description)
9354 "Insert a link. At the prompt, enter the link.
9356 Completion can be used to insert any of the link protocol prefixes like
9357 http or ftp in use.
9359 The history can be used to select a link previously stored with
9360 `org-store-link'. When the empty string is entered (i.e. if you just
9361 press RET at the prompt), the link defaults to the most recently
9362 stored link. As SPC triggers completion in the minibuffer, you need to
9363 use M-SPC or C-q SPC to force the insertion of a space character.
9365 You will also be prompted for a description, and if one is given, it will
9366 be displayed in the buffer instead of the link.
9368 If there is already a link at point, this command will allow you to edit link
9369 and description parts.
9371 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9372 be selected using completion. The path to the file will be relative to the
9373 current directory if the file is in the current directory or a subdirectory.
9374 Otherwise, the link will be the absolute path as completed in the minibuffer
9375 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9376 option `org-link-file-path-type'.
9378 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9379 the current directory or below.
9381 With three \\[universal-argument] prefixes, negate the meaning of
9382 `org-keep-stored-link-after-insertion'.
9384 If `org-make-link-description-function' is non-nil, this function will be
9385 called with the link target, and the result will be the default
9386 link description.
9388 If the LINK-LOCATION parameter is non-nil, this value will be
9389 used as the link location instead of reading one interactively.
9391 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9392 be used as the default description."
9393 (interactive "P")
9394 (let* ((wcf (current-window-configuration))
9395 (origbuf (current-buffer))
9396 (region (if (org-region-active-p)
9397 (buffer-substring (region-beginning) (region-end))))
9398 (remove (and region (list (region-beginning) (region-end))))
9399 (desc region)
9400 tmphist ; byte-compile incorrectly complains about this
9401 (link link-location)
9402 (abbrevs org-link-abbrev-alist-local)
9403 entry file all-prefixes auto-desc)
9404 (cond
9405 (link-location) ; specified by arg, just use it.
9406 ((org-in-regexp org-bracket-link-regexp 1)
9407 ;; We do have a link at point, and we are going to edit it.
9408 (setq remove (list (match-beginning 0) (match-end 0)))
9409 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9410 (setq link (read-string "Link: "
9411 (org-link-unescape
9412 (org-match-string-no-properties 1)))))
9413 ((or (org-in-regexp org-angle-link-re)
9414 (org-in-regexp org-plain-link-re))
9415 ;; Convert to bracket link
9416 (setq remove (list (match-beginning 0) (match-end 0))
9417 link (read-string "Link: "
9418 (org-remove-angle-brackets (match-string 0)))))
9419 ((member complete-file '((4) (16)))
9420 ;; Completing read for file names.
9421 (setq link (org-file-complete-link complete-file)))
9423 ;; Read link, with completion for stored links.
9424 (org-link-fontify-links-to-this-file)
9425 (org-switch-to-buffer-other-window "*Org Links*")
9426 (with-current-buffer "*Org Links*"
9427 (erase-buffer)
9428 (insert "Insert a link.
9429 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9430 (when org-stored-links
9431 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9432 (insert (mapconcat 'org-link-prettify
9433 (reverse org-stored-links) "\n")))
9434 (goto-char (point-min)))
9435 (let ((cw (selected-window)))
9436 (select-window (get-buffer-window "*Org Links*" 'visible))
9437 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9438 (unless (pos-visible-in-window-p (point-max))
9439 (org-fit-window-to-buffer))
9440 (and (window-live-p cw) (select-window cw)))
9441 ;; Fake a link history, containing the stored links.
9442 (setq tmphist (append (mapcar 'car org-stored-links)
9443 org-insert-link-history))
9444 (setq all-prefixes (append (mapcar 'car abbrevs)
9445 (mapcar 'car org-link-abbrev-alist)
9446 org-link-types))
9447 (unwind-protect
9448 (progn
9449 (setq link
9450 (org-completing-read
9451 "Link: "
9452 (append
9453 (mapcar (lambda (x) (concat x ":"))
9454 all-prefixes)
9455 (mapcar 'car org-stored-links))
9456 nil nil nil
9457 'tmphist
9458 (caar org-stored-links)))
9459 (if (not (string-match "\\S-" link))
9460 (error "No link selected"))
9461 (mapc (lambda(l)
9462 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9463 org-stored-links)
9464 (if (or (member link all-prefixes)
9465 (and (equal ":" (substring link -1))
9466 (member (substring link 0 -1) all-prefixes)
9467 (setq link (substring link 0 -1))))
9468 (setq link (with-current-buffer origbuf
9469 (org-link-try-special-completion link)))))
9470 (set-window-configuration wcf)
9471 (kill-buffer "*Org Links*"))
9472 (setq entry (assoc link org-stored-links))
9473 (or entry (push link org-insert-link-history))
9474 (setq desc (or desc (nth 1 entry)))))
9476 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9477 (not org-keep-stored-link-after-insertion))
9478 (setq org-stored-links (delq (assoc link org-stored-links)
9479 org-stored-links)))
9481 (if (string-match org-plain-link-re link)
9482 ;; URL-like link, normalize the use of angular brackets.
9483 (setq link (org-remove-angle-brackets link)))
9485 ;; Check if we are linking to the current file with a search
9486 ;; option If yes, simplify the link by using only the search
9487 ;; option.
9488 (when (and buffer-file-name
9489 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9490 (let* ((path (match-string 1 link))
9491 (case-fold-search nil)
9492 (search (match-string 2 link)))
9493 (save-match-data
9494 (if (equal (file-truename buffer-file-name) (file-truename path))
9495 ;; We are linking to this same file, with a search option
9496 (setq link search)))))
9498 ;; Check if we can/should use a relative path. If yes, simplify the link
9499 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9500 (let* ((type (match-string 1 link))
9501 (path (match-string 2 link))
9502 (origpath path)
9503 (case-fold-search nil))
9504 (cond
9505 ((or (eq org-link-file-path-type 'absolute)
9506 (equal complete-file '(16)))
9507 (setq path (abbreviate-file-name (expand-file-name path))))
9508 ((eq org-link-file-path-type 'noabbrev)
9509 (setq path (expand-file-name path)))
9510 ((eq org-link-file-path-type 'relative)
9511 (setq path (file-relative-name path)))
9513 (save-match-data
9514 (if (string-match (concat "^" (regexp-quote
9515 (expand-file-name
9516 (file-name-as-directory
9517 default-directory))))
9518 (expand-file-name path))
9519 ;; We are linking a file with relative path name.
9520 (setq path (substring (expand-file-name path)
9521 (match-end 0)))
9522 (setq path (abbreviate-file-name (expand-file-name path)))))))
9523 (setq link (concat type path))
9524 (if (equal desc origpath)
9525 (setq desc path))))
9527 (if org-make-link-description-function
9528 (setq desc
9529 (or (condition-case nil
9530 (funcall org-make-link-description-function link desc)
9531 (error (progn (message "Can't get link description from `%s'"
9532 (symbol-name org-make-link-description-function))
9533 (sit-for 2) nil)))
9534 (read-string "Description: " default-description)))
9535 (if default-description (setq desc default-description)
9536 (setq desc (or (and auto-desc desc)
9537 (read-string "Description: " desc)))))
9539 (unless (string-match "\\S-" desc) (setq desc nil))
9540 (if remove (apply 'delete-region remove))
9541 (insert (org-make-link-string link desc))))
9543 (defun org-link-try-special-completion (type)
9544 "If there is completion support for link type TYPE, offer it."
9545 (let ((fun (intern (concat "org-" type "-complete-link"))))
9546 (if (functionp fun)
9547 (funcall fun)
9548 (read-string "Link (no completion support): " (concat type ":")))))
9550 (defun org-file-complete-link (&optional arg)
9551 "Create a file link using completion."
9552 (let (file link)
9553 (setq file (org-iread-file-name "File: "))
9554 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9555 (pwd1 (file-name-as-directory (abbreviate-file-name
9556 (expand-file-name ".")))))
9557 (cond
9558 ((equal arg '(16))
9559 (setq link (concat
9560 "file:"
9561 (abbreviate-file-name (expand-file-name file)))))
9562 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9563 (setq link (concat "file:" (match-string 1 file))))
9564 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9565 (expand-file-name file))
9566 (setq link (concat
9567 "file:" (match-string 1 (expand-file-name file)))))
9568 (t (setq link (concat "file:" file)))))
9569 link))
9571 (defun org-iread-file-name (&rest args)
9572 "Read-file-name using `ido-mode' speedup if available.
9573 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9574 See `read-file-name' for a description of parameters."
9575 (org-without-partial-completion
9576 (if (and org-completion-use-ido
9577 (fboundp 'ido-read-file-name)
9578 (boundp 'ido-mode) ido-mode
9579 (listp (second args)))
9580 (let ((ido-enter-matching-directory nil))
9581 (apply 'ido-read-file-name args))
9582 (apply 'read-file-name args))))
9584 (defun org-completing-read (&rest args)
9585 "Completing-read with SPACE being a normal character."
9586 (let ((enable-recursive-minibuffers t)
9587 (minibuffer-local-completion-map
9588 (copy-keymap minibuffer-local-completion-map)))
9589 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9590 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9591 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9592 (apply 'org-icompleting-read args)))
9594 (defun org-completing-read-no-i (&rest args)
9595 (let (org-completion-use-ido org-completion-use-iswitchb)
9596 (apply 'org-completing-read args)))
9598 (defun org-iswitchb-completing-read (prompt choices &rest args)
9599 "Use iswitch as a completing-read replacement to choose from choices.
9600 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9601 from."
9602 (let* ((iswitchb-use-virtual-buffers nil)
9603 (iswitchb-make-buflist-hook
9604 (lambda ()
9605 (setq iswitchb-temp-buflist choices))))
9606 (iswitchb-read-buffer prompt)))
9608 (defun org-icompleting-read (&rest args)
9609 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9610 (org-without-partial-completion
9611 (if (and org-completion-use-ido
9612 (fboundp 'ido-completing-read)
9613 (boundp 'ido-mode) ido-mode
9614 (listp (second args)))
9615 (let ((ido-enter-matching-directory nil))
9616 (apply 'ido-completing-read (concat (car args))
9617 (if (consp (car (nth 1 args)))
9618 (mapcar 'car (nth 1 args))
9619 (nth 1 args))
9620 (cddr args)))
9621 (if (and org-completion-use-iswitchb
9622 (boundp 'iswitchb-mode) iswitchb-mode
9623 (listp (second args)))
9624 (apply 'org-iswitchb-completing-read (concat (car args))
9625 (if (consp (car (nth 1 args)))
9626 (mapcar 'car (nth 1 args))
9627 (nth 1 args))
9628 (cddr args))
9629 (apply 'completing-read args)))))
9631 (defun org-extract-attributes (s)
9632 "Extract the attributes cookie from a string and set as text property."
9633 (let (a attr (start 0) key value)
9634 (save-match-data
9635 (when (string-match "{{\\([^}]+\\)}}$" s)
9636 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9637 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9638 (setq key (match-string 1 a) value (match-string 2 a)
9639 start (match-end 0)
9640 attr (plist-put attr (intern key) value))))
9641 (org-add-props s nil 'org-attr attr))
9644 (defun org-extract-attributes-from-string (tag)
9645 (let (key value attr)
9646 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9647 (setq key (match-string 1 tag) value (match-string 2 tag)
9648 tag (replace-match "" t t tag)
9649 attr (plist-put attr (intern key) value)))
9650 (cons tag attr)))
9652 (defun org-attributes-to-string (plist)
9653 "Format a property list into an HTML attribute list."
9654 (let ((s "") key value)
9655 (while plist
9656 (setq key (pop plist) value (pop plist))
9657 (and value
9658 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9661 ;;; Opening/following a link
9663 (defvar org-link-search-failed nil)
9665 (defvar org-open-link-functions nil
9666 "Hook for functions finding a plain text link.
9667 These functions must take a single argument, the link content.
9668 They will be called for links that look like [[link text][description]]
9669 when LINK TEXT does not have a protocol like \"http:\" and does not look
9670 like a filename (e.g. \"./blue.png\").
9672 These functions will be called *before* Org attempts to resolve the
9673 link by doing text searches in the current buffer - so if you want a
9674 link \"[[target]]\" to still find \"<<target>>\", your function should
9675 handle this as a special case.
9677 When the function does handle the link, it must return a non-nil value.
9678 If it decides that it is not responsible for this link, it must return
9679 nil to indicate that that Org-mode can continue with other options
9680 like exact and fuzzy text search.")
9682 (defun org-next-link ()
9683 "Move forward to the next link.
9684 If the link is in hidden text, expose it."
9685 (interactive)
9686 (when (and org-link-search-failed (eq this-command last-command))
9687 (goto-char (point-min))
9688 (message "Link search wrapped back to beginning of buffer"))
9689 (setq org-link-search-failed nil)
9690 (let* ((pos (point))
9691 (ct (org-context))
9692 (a (assoc :link ct)))
9693 (if a (goto-char (nth 2 a)))
9694 (if (re-search-forward org-any-link-re nil t)
9695 (progn
9696 (goto-char (match-beginning 0))
9697 (if (outline-invisible-p) (org-show-context)))
9698 (goto-char pos)
9699 (setq org-link-search-failed t)
9700 (error "No further link found"))))
9702 (defun org-previous-link ()
9703 "Move backward to the previous link.
9704 If the link is in hidden text, expose it."
9705 (interactive)
9706 (when (and org-link-search-failed (eq this-command last-command))
9707 (goto-char (point-max))
9708 (message "Link search wrapped back to end of buffer"))
9709 (setq org-link-search-failed nil)
9710 (let* ((pos (point))
9711 (ct (org-context))
9712 (a (assoc :link ct)))
9713 (if a (goto-char (nth 1 a)))
9714 (if (re-search-backward org-any-link-re nil t)
9715 (progn
9716 (goto-char (match-beginning 0))
9717 (if (outline-invisible-p) (org-show-context)))
9718 (goto-char pos)
9719 (setq org-link-search-failed t)
9720 (error "No further link found"))))
9722 (defun org-translate-link (s)
9723 "Translate a link string if a translation function has been defined."
9724 (if (and org-link-translation-function
9725 (fboundp org-link-translation-function)
9726 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9727 (progn
9728 (setq s (funcall org-link-translation-function
9729 (match-string 1 s) (match-string 2 s)))
9730 (concat (car s) ":" (cdr s)))
9733 (defun org-translate-link-from-planner (type path)
9734 "Translate a link from Emacs Planner syntax so that Org can follow it.
9735 This is still an experimental function, your mileage may vary."
9736 (cond
9737 ((member type '("http" "https" "news" "ftp"))
9738 ;; standard Internet links are the same.
9739 nil)
9740 ((and (equal type "irc") (string-match "^//" path))
9741 ;; Planner has two / at the beginning of an irc link, we have 1.
9742 ;; We should have zero, actually....
9743 (setq path (substring path 1)))
9744 ((and (equal type "lisp") (string-match "^/" path))
9745 ;; Planner has a slash, we do not.
9746 (setq type "elisp" path (substring path 1)))
9747 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9748 ;; A typical message link. Planner has the id after the final slash,
9749 ;; we separate it with a hash mark
9750 (setq path (concat (match-string 1 path) "#"
9751 (org-remove-angle-brackets (match-string 2 path)))))
9753 (cons type path))
9755 (defun org-find-file-at-mouse (ev)
9756 "Open file link or URL at mouse."
9757 (interactive "e")
9758 (mouse-set-point ev)
9759 (org-open-at-point 'in-emacs))
9761 (defun org-open-at-mouse (ev)
9762 "Open file link or URL at mouse.
9763 See the docstring of `org-open-file' for details."
9764 (interactive "e")
9765 (mouse-set-point ev)
9766 (if (eq major-mode 'org-agenda-mode)
9767 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9768 (org-open-at-point))
9770 (defvar org-window-config-before-follow-link nil
9771 "The window configuration before following a link.
9772 This is saved in case the need arises to restore it.")
9774 (defvar org-open-link-marker (make-marker)
9775 "Marker pointing to the location where `org-open-at-point; was called.")
9777 ;;;###autoload
9778 (defun org-open-at-point-global ()
9779 "Follow a link like Org-mode does.
9780 This command can be called in any mode to follow a link that has
9781 Org-mode syntax."
9782 (interactive)
9783 (org-run-like-in-org-mode 'org-open-at-point))
9785 ;;;###autoload
9786 (defun org-open-link-from-string (s &optional arg reference-buffer)
9787 "Open a link in the string S, as if it was in Org-mode."
9788 (interactive "sLink: \nP")
9789 (let ((reference-buffer (or reference-buffer (current-buffer))))
9790 (with-temp-buffer
9791 (let ((org-inhibit-startup (not reference-buffer)))
9792 (org-mode)
9793 (insert s)
9794 (goto-char (point-min))
9795 (when reference-buffer
9796 (setq org-link-abbrev-alist-local
9797 (with-current-buffer reference-buffer
9798 org-link-abbrev-alist-local)))
9799 (org-open-at-point arg reference-buffer)))))
9801 (defvar org-open-at-point-functions nil
9802 "Hook that is run when following a link at point.
9804 Functions in this hook must return t if they identify and follow
9805 a link at point. If they don't find anything interesting at point,
9806 they must return nil.")
9808 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9809 (defun org-open-at-point (&optional arg reference-buffer)
9810 "Open link at or after point.
9811 If there is no link at point, this function will search forward up to
9812 the end of the current line.
9813 Normally, files will be opened by an appropriate application. If the
9814 optional prefix argument ARG is non-nil, Emacs will visit the file.
9815 With a double prefix argument, try to open outside of Emacs, in the
9816 application the system uses for this file type."
9817 (interactive "P")
9818 ;; if in a code block, then open the block's results
9819 (unless (call-interactively #'org-babel-open-src-block-result)
9820 (org-load-modules-maybe)
9821 (move-marker org-open-link-marker (point))
9822 (setq org-window-config-before-follow-link (current-window-configuration))
9823 (org-remove-occur-highlights nil nil t)
9824 (cond
9825 ((and (org-at-heading-p)
9826 (not (org-at-timestamp-p t))
9827 (not (org-in-regexp
9828 (concat org-plain-link-re "\\|"
9829 org-bracket-link-regexp "\\|"
9830 org-angle-link-re "\\|"
9831 "[ \t]:[^ \t\n]+:[ \t]*$")))
9832 (not (get-text-property (point) 'org-linked-text)))
9833 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
9834 (lk0 (car lkall))
9835 (lk (if (stringp lk0) (list lk0) lk0))
9836 (lkend (cdr lkall)))
9837 (mapcar (lambda(l)
9838 (search-forward l nil lkend)
9839 (goto-char (match-beginning 0))
9840 (org-open-at-point))
9841 lk))
9842 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9843 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9844 ((and (org-at-timestamp-p t)
9845 (not (org-in-regexp org-bracket-link-regexp)))
9846 (org-follow-timestamp-link))
9847 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9848 (not (org-in-regexp org-any-link-re)))
9849 (org-footnote-action))
9851 (let (type path link line search (pos (point)))
9852 (catch 'match
9853 (save-excursion
9854 (skip-chars-forward "^]\n\r")
9855 (when (org-in-regexp org-bracket-link-regexp 1)
9856 (setq link (org-extract-attributes
9857 (org-link-unescape (org-match-string-no-properties 1))))
9858 (while (string-match " *\n *" link)
9859 (setq link (replace-match " " t t link)))
9860 (setq link (org-link-expand-abbrev link))
9861 (cond
9862 ((or (file-name-absolute-p link)
9863 (string-match "^\\.\\.?/" link))
9864 (setq type "file" path link))
9865 ((string-match org-link-re-with-space3 link)
9866 (setq type (match-string 1 link) path (match-string 2 link)))
9867 ((string-match "^help:+\\(.+\\)" link)
9868 (setq type "help" path (match-string 1 link)))
9869 (t (setq type "thisfile" path link)))
9870 (throw 'match t)))
9872 (when (get-text-property (point) 'org-linked-text)
9873 (setq type "thisfile"
9874 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9875 (1+ (point)) (point))
9876 path (buffer-substring
9877 (or (previous-single-property-change pos 'org-linked-text)
9878 (point-min))
9879 (or (next-single-property-change pos 'org-linked-text)
9880 (point-max))))
9881 (throw 'match t))
9883 (save-excursion
9884 (let ((plinkpos (org-in-regexp org-plain-link-re)))
9885 (when (or (org-in-regexp org-angle-link-re)
9886 (and plinkpos (goto-char (car plinkpos))
9887 (save-match-data (not (looking-back "\\[\\[")))))
9888 (setq type (match-string 1)
9889 path (org-link-unescape (match-string 2)))
9890 (throw 'match t))))
9891 (save-excursion
9892 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9893 (setq type "tags"
9894 path (match-string 1))
9895 (while (string-match ":" path)
9896 (setq path (replace-match "+" t t path)))
9897 (throw 'match t)))
9898 (when (org-in-regexp "<\\([^><\n]+\\)>")
9899 (setq type "tree-match"
9900 path (match-string 1))
9901 (throw 'match t)))
9902 (unless path
9903 (user-error "No link found"))
9905 ;; switch back to reference buffer
9906 ;; needed when if called in a temporary buffer through
9907 ;; org-open-link-from-string
9908 (with-current-buffer (or reference-buffer (current-buffer))
9910 ;; Remove any trailing spaces in path
9911 (if (string-match " +\\'" path)
9912 (setq path (replace-match "" t t path)))
9913 (if (and org-link-translation-function
9914 (fboundp org-link-translation-function))
9915 ;; Check if we need to translate the link
9916 (let ((tmp (funcall org-link-translation-function type path)))
9917 (setq type (car tmp) path (cdr tmp))))
9919 (cond
9921 ((assoc type org-link-protocols)
9922 (funcall (nth 1 (assoc type org-link-protocols)) path))
9924 ((equal type "help")
9925 (let ((f-or-v (intern path)))
9926 (cond ((fboundp f-or-v)
9927 (describe-function f-or-v))
9928 ((boundp f-or-v)
9929 (describe-variable f-or-v))
9930 (t (error "Not a known function or variable")))))
9932 ((equal type "mailto")
9933 (let ((cmd (car org-link-mailto-program))
9934 (args (cdr org-link-mailto-program)) args1
9935 (address path) (subject "") a)
9936 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9937 (setq address (match-string 1 path)
9938 subject (org-link-escape (match-string 2 path))))
9939 (while args
9940 (cond
9941 ((not (stringp (car args))) (push (pop args) args1))
9942 (t (setq a (pop args))
9943 (if (string-match "%a" a)
9944 (setq a (replace-match address t t a)))
9945 (if (string-match "%s" a)
9946 (setq a (replace-match subject t t a)))
9947 (push a args1))))
9948 (apply cmd (nreverse args1))))
9950 ((member type '("http" "https" "ftp" "news"))
9951 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9952 (org-link-escape
9953 path org-link-escape-chars-browser)
9954 path))))
9956 ((string= type "doi")
9957 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9958 (org-link-escape
9959 path org-link-escape-chars-browser)
9960 path))))
9962 ((member type '("message"))
9963 (browse-url (concat type ":" path)))
9965 ((string= type "tags")
9966 (org-tags-view arg path))
9968 ((string= type "tree-match")
9969 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9971 ((string= type "file")
9972 (if (string-match "::\\([0-9]+\\)\\'" path)
9973 (setq line (string-to-number (match-string 1 path))
9974 path (substring path 0 (match-beginning 0)))
9975 (if (string-match "::\\(.+\\)\\'" path)
9976 (setq search (match-string 1 path)
9977 path (substring path 0 (match-beginning 0)))))
9978 (if (string-match "[*?{]" (file-name-nondirectory path))
9979 (dired path)
9980 (org-open-file path arg line search)))
9982 ((string= type "shell")
9983 (let ((buf (generate-new-buffer "*Org Shell Output"))
9984 (cmd path))
9985 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9986 (string-match org-confirm-shell-link-not-regexp cmd))
9987 (not org-confirm-shell-link-function)
9988 (funcall org-confirm-shell-link-function
9989 (format "Execute \"%s\" in shell? "
9990 (org-add-props cmd nil
9991 'face 'org-warning))))
9992 (progn
9993 (message "Executing %s" cmd)
9994 (shell-command cmd buf)
9995 (if (featurep 'midnight)
9996 (setq clean-buffer-list-kill-buffer-names
9997 (cons buf clean-buffer-list-kill-buffer-names))))
9998 (error "Abort"))))
10000 ((string= type "elisp")
10001 (let ((cmd path))
10002 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10003 (string-match org-confirm-elisp-link-not-regexp cmd))
10004 (not org-confirm-elisp-link-function)
10005 (funcall org-confirm-elisp-link-function
10006 (format "Execute \"%s\" as elisp? "
10007 (org-add-props cmd nil
10008 'face 'org-warning))))
10009 (message "%s => %s" cmd
10010 (if (equal (string-to-char cmd) ?\()
10011 (eval (read cmd))
10012 (call-interactively (read cmd))))
10013 (error "Abort"))))
10015 ((and (string= type "thisfile")
10016 (run-hook-with-args-until-success
10017 'org-open-link-functions path)))
10019 ((string= type "thisfile")
10020 (if arg
10021 (switch-to-buffer-other-window
10022 (org-get-buffer-for-internal-link (current-buffer)))
10023 (org-mark-ring-push))
10024 (let ((cmd `(org-link-search
10025 ,path
10026 ,(cond ((equal arg '(4)) ''occur)
10027 ((equal arg '(16)) ''org-occur))
10028 ,pos)))
10029 (condition-case nil (let ((org-link-search-inhibit-query t))
10030 (eval cmd))
10031 (error (progn (widen) (eval cmd))))))
10033 (t (browse-url-at-point)))))))
10034 (move-marker org-open-link-marker nil)
10035 (run-hook-with-args 'org-follow-link-hook)))
10037 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10038 "Offer links in the current entry and return the selected link.
10039 If there is only one link, return it.
10040 If NTH is an integer, return the NTH link found.
10041 If ZERO is a string, check also this string for a link, and if
10042 there is one, return it."
10043 (with-current-buffer buffer
10044 (save-excursion
10045 (save-restriction
10046 (widen)
10047 (goto-char marker)
10048 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10049 "\\(" org-angle-link-re "\\)\\|"
10050 "\\(" org-plain-link-re "\\)"))
10051 (cnt ?0)
10052 (in-emacs (if (integerp nth) nil nth))
10053 have-zero end links link c)
10054 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10055 (push (match-string 0 zero) links)
10056 (setq cnt (1- cnt) have-zero t))
10057 (save-excursion
10058 (org-back-to-heading t)
10059 (setq end (save-excursion (outline-next-heading) (point)))
10060 (while (re-search-forward re end t)
10061 (push (match-string 0) links))
10062 (setq links (org-uniquify (reverse links))))
10063 (cond
10064 ((null links)
10065 (message "No links"))
10066 ((equal (length links) 1)
10067 (setq link (car links)))
10068 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10069 (setq link (nth (if have-zero nth (1- nth)) links)))
10070 (t ; we have to select a link
10071 (save-excursion
10072 (save-window-excursion
10073 (delete-other-windows)
10074 (with-output-to-temp-buffer "*Select Link*"
10075 (mapc (lambda (l)
10076 (if (not (string-match org-bracket-link-regexp l))
10077 (princ (format "[%c] %s\n" (incf cnt)
10078 (org-remove-angle-brackets l)))
10079 (if (match-end 3)
10080 (princ (format "[%c] %s (%s)\n" (incf cnt)
10081 (match-string 3 l) (match-string 1 l)))
10082 (princ (format "[%c] %s\n" (incf cnt)
10083 (match-string 1 l))))))
10084 links))
10085 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10086 (message "Select link to open, RET to open all:")
10087 (setq c (read-char-exclusive))
10088 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10089 (when (equal c ?q) (error "Abort"))
10090 (if (equal c ?\C-m)
10091 (setq link links)
10092 (setq nth (- c ?0))
10093 (if have-zero (setq nth (1+ nth)))
10094 (unless (and (integerp nth) (>= (length links) nth))
10095 (error "Invalid link selection"))
10096 (setq link (nth (1- nth) links)))))
10097 (cons link end))))))
10099 ;; Add special file links that specify the way of opening
10101 (org-add-link-type "file+sys" 'org-open-file-with-system)
10102 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10103 (defun org-open-file-with-system (path)
10104 "Open file at PATH using the system way of opening it."
10105 (org-open-file path 'system))
10106 (defun org-open-file-with-emacs (path)
10107 "Open file at PATH in Emacs."
10108 (org-open-file path 'emacs))
10111 ;;; File search
10113 (defvar org-create-file-search-functions nil
10114 "List of functions to construct the right search string for a file link.
10115 These functions are called in turn with point at the location to
10116 which the link should point.
10118 A function in the hook should first test if it would like to
10119 handle this file type, for example by checking the `major-mode'
10120 or the file extension. If it decides not to handle this file, it
10121 should just return nil to give other functions a chance. If it
10122 does handle the file, it must return the search string to be used
10123 when following the link. The search string will be part of the
10124 file link, given after a double colon, and `org-open-at-point'
10125 will automatically search for it. If special measures must be
10126 taken to make the search successful, another function should be
10127 added to the companion hook `org-execute-file-search-functions',
10128 which see.
10130 A function in this hook may also use `setq' to set the variable
10131 `description' to provide a suggestion for the descriptive text to
10132 be used for this link when it gets inserted into an Org-mode
10133 buffer with \\[org-insert-link].")
10135 (defvar org-execute-file-search-functions nil
10136 "List of functions to execute a file search triggered by a link.
10138 Functions added to this hook must accept a single argument, the
10139 search string that was part of the file link, the part after the
10140 double colon. The function must first check if it would like to
10141 handle this search, for example by checking the `major-mode' or
10142 the file extension. If it decides not to handle this search, it
10143 should just return nil to give other functions a chance. If it
10144 does handle the search, it must return a non-nil value to keep
10145 other functions from trying.
10147 Each function can access the current prefix argument through the
10148 variable `current-prefix-argument'. Note that a single prefix is
10149 used to force opening a link in Emacs, so it may be good to only
10150 use a numeric or double prefix to guide the search function.
10152 In case this is needed, a function in this hook can also restore
10153 the window configuration before `org-open-at-point' was called using:
10155 (set-window-configuration org-window-config-before-follow-link)")
10157 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10158 (defun org-link-search (s &optional type avoid-pos stealth)
10159 "Search for a link search option.
10160 If S is surrounded by forward slashes, it is interpreted as a
10161 regular expression. In org-mode files, this will create an `org-occur'
10162 sparse tree. In ordinary files, `occur' will be used to list matches.
10163 If the current buffer is in `dired-mode', grep will be used to search
10164 in all files. If AVOID-POS is given, ignore matches near that position.
10166 When optional argument STEALTH is non-nil, do not modify
10167 visibility around point, thus ignoring
10168 `org-show-hierarchy-above', `org-show-following-heading' and
10169 `org-show-siblings' variables."
10170 (let ((case-fold-search t)
10171 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10172 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10173 (append '(("") (" ") ("\t") ("\n"))
10174 org-emphasis-alist)
10175 "\\|") "\\)"))
10176 (pos (point))
10177 (pre nil) (post nil)
10178 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10179 (cond
10180 ;; First check if there are any special search functions
10181 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10182 ;; Now try the builtin stuff
10183 ((and (equal (string-to-char s0) ?#)
10184 (> (length s0) 1)
10185 (save-excursion
10186 (goto-char (point-min))
10187 (and
10188 (re-search-forward
10189 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10190 (setq type 'dedicated
10191 pos (match-beginning 0))))
10192 ;; There is an exact target for this
10193 (goto-char pos)
10194 (org-back-to-heading t)))
10195 ((save-excursion
10196 (goto-char (point-min))
10197 (and
10198 (re-search-forward
10199 (concat "<<" (regexp-quote s0) ">>") nil t)
10200 (setq type 'dedicated
10201 pos (match-beginning 0))))
10202 ;; There is an exact target for this
10203 (goto-char pos))
10204 ((save-excursion
10205 (goto-char (point-min))
10206 (and
10207 (re-search-forward
10208 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10209 (setq type 'dedicated pos (match-beginning 0))))
10210 ;; Found an invisible target.
10211 (goto-char pos))
10212 ((save-excursion
10213 (goto-char (point-min))
10214 (and
10215 (re-search-forward
10216 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10217 (setq type 'dedicated pos (match-beginning 0))))
10218 ;; Found an element with a matching #+name affiliated keyword.
10219 (goto-char pos))
10220 ((and (string-match "^(\\(.*\\))$" s0)
10221 (save-excursion
10222 (goto-char (point-min))
10223 (and
10224 (re-search-forward
10225 (concat "[^[]" (regexp-quote
10226 (format org-coderef-label-format
10227 (match-string 1 s0))))
10228 nil t)
10229 (setq type 'dedicated
10230 pos (1+ (match-beginning 0))))))
10231 ;; There is a coderef target for this
10232 (goto-char pos))
10233 ((string-match "^/\\(.*\\)/$" s)
10234 ;; A regular expression
10235 (cond
10236 ((derived-mode-p 'org-mode)
10237 (org-occur (match-string 1 s)))
10238 ;;((eq major-mode 'dired-mode)
10239 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10240 (t (org-do-occur (match-string 1 s)))))
10241 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10242 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10243 (goto-char (point-min))
10244 (cond
10245 ((let (case-fold-search)
10246 (re-search-forward (format org-complex-heading-regexp-format
10247 (regexp-quote s))
10248 nil t))
10249 ;; OK, found a match
10250 (setq type 'dedicated)
10251 (goto-char (match-beginning 0)))
10252 ((and (not org-link-search-inhibit-query)
10253 (eq org-link-search-must-match-exact-headline 'query-to-create)
10254 (y-or-n-p "No match - create this as a new heading? "))
10255 (goto-char (point-max))
10256 (or (bolp) (newline))
10257 (insert "* " s "\n")
10258 (beginning-of-line 0))
10260 (goto-char pos)
10261 (error "No match"))))
10263 ;; A normal search string
10264 (when (equal (string-to-char s) ?*)
10265 ;; Anchor on headlines, post may include tags.
10266 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10267 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10268 s (substring s 1)))
10269 (remove-text-properties
10270 0 (length s)
10271 '(face nil mouse-face nil keymap nil fontified nil) s)
10272 ;; Make a series of regular expressions to find a match
10273 (setq words (org-split-string s "[ \n\r\t]+")
10275 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10276 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10277 "\\)" markers)
10278 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10279 re2a (concat "[ \t\r\n]" re2a_)
10280 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10281 re4 (concat "[^a-zA-Z_]" re4_)
10283 re1 (concat pre re2 post)
10284 re3 (concat pre (if pre re4_ re4) post)
10285 re5 (concat pre ".*" re4)
10286 re2 (concat pre re2)
10287 re2a (concat pre (if pre re2a_ re2a))
10288 re4 (concat pre (if pre re4_ re4))
10289 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10290 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10291 re5 "\\)"
10293 (cond
10294 ((eq type 'org-occur) (org-occur reall))
10295 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10296 (t (goto-char (point-min))
10297 (setq type 'fuzzy)
10298 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10299 (org-search-not-self 1 re1 nil t)
10300 (org-search-not-self 1 re2 nil t)
10301 (org-search-not-self 1 re2a nil t)
10302 (org-search-not-self 1 re3 nil t)
10303 (org-search-not-self 1 re4 nil t)
10304 (org-search-not-self 1 re5 nil t)
10306 (goto-char (match-beginning 1))
10307 (goto-char pos)
10308 (error "No match"))))))
10309 (and (derived-mode-p 'org-mode)
10310 (not stealth)
10311 (org-show-context 'link-search))
10312 type))
10314 (defun org-search-not-self (group &rest args)
10315 "Execute `re-search-forward', but only accept matches that do not
10316 enclose the position of `org-open-link-marker'."
10317 (let ((m org-open-link-marker))
10318 (catch 'exit
10319 (while (apply 're-search-forward args)
10320 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10321 (goto-char (match-end group))
10322 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10323 (> (match-beginning 0) (marker-position m))
10324 (< (match-end 0) (marker-position m)))
10325 (save-match-data
10326 (or (not (org-in-regexp
10327 org-bracket-link-analytic-regexp 1))
10328 (not (match-end 4)) ; no description
10329 (and (<= (match-beginning 4) (point))
10330 (>= (match-end 4) (point))))))
10331 (throw 'exit (point))))))))
10333 (defun org-get-buffer-for-internal-link (buffer)
10334 "Return a buffer to be used for displaying the link target of internal links."
10335 (cond
10336 ((not org-display-internal-link-with-indirect-buffer)
10337 buffer)
10338 ((string-match "(Clone)$" (buffer-name buffer))
10339 (message "Buffer is already a clone, not making another one")
10340 ;; we also do not modify visibility in this case
10341 buffer)
10342 (t ; make a new indirect buffer for displaying the link
10343 (let* ((bn (buffer-name buffer))
10344 (ibn (concat bn "(Clone)"))
10345 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10346 (with-current-buffer ib (org-overview))
10347 ib))))
10349 (defun org-do-occur (regexp &optional cleanup)
10350 "Call the Emacs command `occur'.
10351 If CLEANUP is non-nil, remove the printout of the regular expression
10352 in the *Occur* buffer. This is useful if the regex is long and not useful
10353 to read."
10354 (occur regexp)
10355 (when cleanup
10356 (let ((cwin (selected-window)) win beg end)
10357 (when (setq win (get-buffer-window "*Occur*"))
10358 (select-window win))
10359 (goto-char (point-min))
10360 (when (re-search-forward "match[a-z]+" nil t)
10361 (setq beg (match-end 0))
10362 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10363 (setq end (1- (match-beginning 0)))))
10364 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10365 (goto-char (point-min))
10366 (select-window cwin))))
10368 ;;; The mark ring for links jumps
10370 (defvar org-mark-ring nil
10371 "Mark ring for positions before jumps in Org-mode.")
10372 (defvar org-mark-ring-last-goto nil
10373 "Last position in the mark ring used to go back.")
10374 ;; Fill and close the ring
10375 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10376 (loop for i from 1 to org-mark-ring-length do
10377 (push (make-marker) org-mark-ring))
10378 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10379 org-mark-ring)
10381 (defun org-mark-ring-push (&optional pos buffer)
10382 "Put the current position or POS into the mark ring and rotate it."
10383 (interactive)
10384 (setq pos (or pos (point)))
10385 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10386 (move-marker (car org-mark-ring)
10387 (or pos (point))
10388 (or buffer (current-buffer)))
10389 (message "%s"
10390 (substitute-command-keys
10391 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10393 (defun org-mark-ring-goto (&optional n)
10394 "Jump to the previous position in the mark ring.
10395 With prefix arg N, jump back that many stored positions. When
10396 called several times in succession, walk through the entire ring.
10397 Org-mode commands jumping to a different position in the current file,
10398 or to another Org-mode file, automatically push the old position
10399 onto the ring."
10400 (interactive "p")
10401 (let (p m)
10402 (if (eq last-command this-command)
10403 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10404 (setq p org-mark-ring))
10405 (setq org-mark-ring-last-goto p)
10406 (setq m (car p))
10407 (org-pop-to-buffer-same-window (marker-buffer m))
10408 (goto-char m)
10409 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10411 (defun org-remove-angle-brackets (s)
10412 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10413 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10415 (defun org-add-angle-brackets (s)
10416 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10417 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10419 (defun org-remove-double-quotes (s)
10420 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10421 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10424 ;;; Following specific links
10426 (defun org-follow-timestamp-link ()
10427 "Open an agenda view for the time-stamp date/range at point."
10428 (cond
10429 ((org-at-date-range-p t)
10430 (let ((org-agenda-start-on-weekday)
10431 (t1 (match-string 1))
10432 (t2 (match-string 2)) tt1 tt2)
10433 (setq tt1 (time-to-days (org-time-string-to-time t1))
10434 tt2 (time-to-days (org-time-string-to-time t2)))
10435 (let ((org-agenda-buffer-tmp-name
10436 (format "*Org Agenda(a:%s)"
10437 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10438 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10439 ((org-at-timestamp-p t)
10440 (let ((org-agenda-buffer-tmp-name
10441 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10442 (org-agenda-list nil (time-to-days (org-time-string-to-time
10443 (substring (match-string 1) 0 10)))
10444 1)))
10445 (t (error "This should not happen"))))
10448 ;;; Following file links
10449 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10450 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10451 (declare-function mailcap-mime-info
10452 "mailcap" (string &optional request no-decode))
10453 (defvar org-wait nil)
10454 (defun org-open-file (path &optional in-emacs line search)
10455 "Open the file at PATH.
10456 First, this expands any special file name abbreviations. Then the
10457 configuration variable `org-file-apps' is checked if it contains an
10458 entry for this file type, and if yes, the corresponding command is launched.
10460 If no application is found, Emacs simply visits the file.
10462 With optional prefix argument IN-EMACS, Emacs will visit the file.
10463 With a double \\[universal-argument] \\[universal-argument] \
10464 prefix arg, Org tries to avoid opening in Emacs
10465 and to use an external application to visit the file.
10467 Optional LINE specifies a line to go to, optional SEARCH a string
10468 to search for. If LINE or SEARCH is given, the file will be
10469 opened in Emacs, unless an entry from org-file-apps that makes
10470 use of groups in a regexp matches.
10472 If you want to change the way frames are used when following a
10473 link, please customize `org-link-frame-setup'.
10475 If the file does not exist, an error is thrown."
10476 (let* ((file (if (equal path "")
10477 buffer-file-name
10478 (substitute-in-file-name (expand-file-name path))))
10479 (file-apps (append org-file-apps (org-default-apps)))
10480 (apps (org-remove-if
10481 'org-file-apps-entry-match-against-dlink-p file-apps))
10482 (apps-dlink (org-remove-if-not
10483 'org-file-apps-entry-match-against-dlink-p file-apps))
10484 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10485 (dirp (if remp nil (file-directory-p file)))
10486 (file (if (and dirp org-open-directory-means-index-dot-org)
10487 (concat (file-name-as-directory file) "index.org")
10488 file))
10489 (a-m-a-p (assq 'auto-mode apps))
10490 (dfile (downcase file))
10491 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10492 (link (cond ((and (eq line nil)
10493 (eq search nil))
10494 file)
10495 (line
10496 (concat file "::" (number-to-string line)))
10497 (search
10498 (concat file "::" search))))
10499 (dlink (downcase link))
10500 (old-buffer (current-buffer))
10501 (old-pos (point))
10502 (old-mode major-mode)
10503 ext cmd link-match-data)
10504 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10505 (setq ext (match-string 1 dfile))
10506 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10507 (setq ext (match-string 1 dfile))))
10508 (cond
10509 ((member in-emacs '((16) system))
10510 (setq cmd (cdr (assoc 'system apps))))
10511 (in-emacs (setq cmd 'emacs))
10513 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10514 (and dirp (cdr (assoc 'directory apps)))
10515 ; first, try matching against apps-dlink
10516 ; if we get a match here, store the match data for later
10517 (let ((match (assoc-default dlink apps-dlink
10518 'string-match)))
10519 (if match
10520 (progn (setq link-match-data (match-data))
10521 match)
10522 (progn (setq in-emacs (or in-emacs line search))
10523 nil))) ; if we have no match in apps-dlink,
10524 ; always open the file in emacs if line or search
10525 ; is given (for backwards compatibility)
10526 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10527 'string-match)
10528 (cdr (assoc ext apps))
10529 (cdr (assoc t apps))))))
10530 (when (eq cmd 'system)
10531 (setq cmd (cdr (assoc 'system apps))))
10532 (when (eq cmd 'default)
10533 (setq cmd (cdr (assoc t apps))))
10534 (when (eq cmd 'mailcap)
10535 (require 'mailcap)
10536 (mailcap-parse-mailcaps)
10537 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10538 (command (mailcap-mime-info mime-type)))
10539 (if (stringp command)
10540 (setq cmd command)
10541 (setq cmd 'emacs))))
10542 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10543 (not (file-exists-p file))
10544 (not org-open-non-existing-files))
10545 (error "No such file: %s" file))
10546 (cond
10547 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10548 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10549 (while (string-match "['\"]%s['\"]" cmd)
10550 (setq cmd (replace-match "%s" t t cmd)))
10551 (while (string-match "%s" cmd)
10552 (setq cmd (replace-match
10553 (save-match-data
10554 (shell-quote-argument
10555 (convert-standard-filename file)))
10556 t t cmd)))
10558 ;; Replace "%1", "%2" etc. in command with group matches from regex
10559 (save-match-data
10560 (let ((match-index 1)
10561 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10562 (set-match-data link-match-data)
10563 (while (<= match-index number-of-groups)
10564 (let ((regex (concat "%" (number-to-string match-index)))
10565 (replace-with (match-string match-index dlink)))
10566 (while (string-match regex cmd)
10567 (setq cmd (replace-match replace-with t t cmd))))
10568 (setq match-index (+ match-index 1)))))
10570 (save-window-excursion
10571 (message "Running %s...done" cmd)
10572 (start-process-shell-command cmd nil cmd)
10573 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10574 ((or (stringp cmd)
10575 (eq cmd 'emacs))
10576 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10577 (widen)
10578 (if line (org-goto-line line)
10579 (if search (org-link-search search))))
10580 ((consp cmd)
10581 (let ((file (convert-standard-filename file)))
10582 (save-match-data
10583 (set-match-data link-match-data)
10584 (eval cmd))))
10585 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10586 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10587 (or (not (equal old-buffer (current-buffer)))
10588 (not (equal old-pos (point))))
10589 (org-mark-ring-push old-pos old-buffer))))
10591 (defun org-file-apps-entry-match-against-dlink-p (entry)
10592 "This function returns non-nil if `entry' uses a regular
10593 expression which should be matched against the whole link by
10594 org-open-file.
10596 It assumes that is the case when the entry uses a regular
10597 expression which has at least one grouping construct and the
10598 action is either a lisp form or a command string containing
10599 '%1', i.e. using at least one subexpression match as a
10600 parameter."
10601 (let ((selector (car entry))
10602 (action (cdr entry)))
10603 (if (stringp selector)
10604 (and (> (regexp-opt-depth selector) 0)
10605 (or (and (stringp action)
10606 (string-match "%[0-9]" action))
10607 (consp action)))
10608 nil)))
10610 (defun org-default-apps ()
10611 "Return the default applications for this operating system."
10612 (cond
10613 ((eq system-type 'darwin)
10614 org-file-apps-defaults-macosx)
10615 ((eq system-type 'windows-nt)
10616 org-file-apps-defaults-windowsnt)
10617 (t org-file-apps-defaults-gnu)))
10619 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10620 "Convert extensions to regular expressions in the cars of LIST.
10621 Also, weed out any non-string entries, because the return value is used
10622 only for regexp matching.
10623 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10624 point to the symbol `emacs', indicating that the file should
10625 be opened in Emacs."
10626 (append
10627 (delq nil
10628 (mapcar (lambda (x)
10629 (if (not (stringp (car x)))
10631 (if (string-match "\\W" (car x))
10633 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10634 list))
10635 (if add-auto-mode
10636 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10638 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10639 (defun org-file-remote-p (file)
10640 "Test whether FILE specifies a location on a remote system.
10641 Return non-nil if the location is indeed remote.
10643 For example, the filename \"/user@host:/foo\" specifies a location
10644 on the system \"/user@host:\"."
10645 (cond ((fboundp 'file-remote-p)
10646 (file-remote-p file))
10647 ((fboundp 'tramp-handle-file-remote-p)
10648 (tramp-handle-file-remote-p file))
10649 ((and (boundp 'ange-ftp-name-format)
10650 (string-match (car ange-ftp-name-format) file))
10651 t)))
10654 ;;;; Refiling
10656 (defun org-get-org-file ()
10657 "Read a filename, with default directory `org-directory'."
10658 (let ((default (or org-default-notes-file remember-data-file)))
10659 (read-file-name (format "File name [%s]: " default)
10660 (file-name-as-directory org-directory)
10661 default)))
10663 (defun org-notes-order-reversed-p ()
10664 "Check if the current file should receive notes in reversed order."
10665 (cond
10666 ((not org-reverse-note-order) nil)
10667 ((eq t org-reverse-note-order) t)
10668 ((not (listp org-reverse-note-order)) nil)
10669 (t (catch 'exit
10670 (let ((all org-reverse-note-order)
10671 entry)
10672 (while (setq entry (pop all))
10673 (if (string-match (car entry) buffer-file-name)
10674 (throw 'exit (cdr entry))))
10675 nil)))))
10677 (defvar org-refile-target-table nil
10678 "The list of refile targets, created by `org-refile'.")
10680 (defvar org-agenda-new-buffers nil
10681 "Buffers created to visit agenda files.")
10683 (defvar org-refile-cache nil
10684 "Cache for refile targets.")
10686 (defvar org-refile-markers nil
10687 "All the markers used for caching refile locations.")
10689 (defun org-refile-marker (pos)
10690 "Get a new refile marker, but only if caching is in use."
10691 (if (not org-refile-use-cache)
10693 (let ((m (make-marker)))
10694 (move-marker m pos)
10695 (push m org-refile-markers)
10696 m)))
10698 (defun org-refile-cache-clear ()
10699 "Clear the refile cache and disable all the markers."
10700 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10701 (setq org-refile-markers nil)
10702 (setq org-refile-cache nil)
10703 (message "Refile cache has been cleared"))
10705 (defun org-refile-cache-check-set (set)
10706 "Check if all the markers in the cache still have live buffers."
10707 (let (marker)
10708 (catch 'exit
10709 (while (and set (setq marker (nth 3 (pop set))))
10710 ;; if org-refile-use-outline-path is 'file, marker may be nil
10711 (when (and marker (null (marker-buffer marker)))
10712 (message "not found") (sit-for 3)
10713 (throw 'exit nil)))
10714 t)))
10716 (defun org-refile-cache-put (set &rest identifiers)
10717 "Push the refile targets SET into the cache, under IDENTIFIERS."
10718 (let* ((key (sha1 (prin1-to-string identifiers)))
10719 (entry (assoc key org-refile-cache)))
10720 (if entry
10721 (setcdr entry set)
10722 (push (cons key set) org-refile-cache))))
10724 (defun org-refile-cache-get (&rest identifiers)
10725 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10726 (cond
10727 ((not org-refile-cache) nil)
10728 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10730 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10731 org-refile-cache))))
10732 (and set (org-refile-cache-check-set set) set)))))
10734 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10735 "Produce a table with refile targets."
10736 (let ((case-fold-search nil)
10737 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10738 (entries (or org-refile-targets '((nil . (:level . 1)))))
10739 targets tgs txt re files f desc descre fast-path-p level pos0)
10740 (message "Getting targets...")
10741 (with-current-buffer (or default-buffer (current-buffer))
10742 (while (setq entry (pop entries))
10743 (setq files (car entry) desc (cdr entry))
10744 (setq fast-path-p nil)
10745 (cond
10746 ((null files) (setq files (list (current-buffer))))
10747 ((eq files 'org-agenda-files)
10748 (setq files (org-agenda-files 'unrestricted)))
10749 ((and (symbolp files) (fboundp files))
10750 (setq files (funcall files)))
10751 ((and (symbolp files) (boundp files))
10752 (setq files (symbol-value files))))
10753 (if (stringp files) (setq files (list files)))
10754 (cond
10755 ((eq (car desc) :tag)
10756 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10757 ((eq (car desc) :todo)
10758 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10759 ((eq (car desc) :regexp)
10760 (setq descre (cdr desc)))
10761 ((eq (car desc) :level)
10762 (setq descre (concat "^\\*\\{" (number-to-string
10763 (if org-odd-levels-only
10764 (1- (* 2 (cdr desc)))
10765 (cdr desc)))
10766 "\\}[ \t]")))
10767 ((eq (car desc) :maxlevel)
10768 (setq fast-path-p t)
10769 (setq descre (concat "^\\*\\{1," (number-to-string
10770 (if org-odd-levels-only
10771 (1- (* 2 (cdr desc)))
10772 (cdr desc)))
10773 "\\}[ \t]")))
10774 (t (error "Bad refiling target description %s" desc)))
10775 (while (setq f (pop files))
10776 (with-current-buffer
10777 (if (bufferp f) f (org-get-agenda-file-buffer f))
10779 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10780 (progn
10781 (if (bufferp f) (setq f (buffer-file-name
10782 (buffer-base-buffer f))))
10783 (setq f (and f (expand-file-name f)))
10784 (if (eq org-refile-use-outline-path 'file)
10785 (push (list (file-name-nondirectory f) f nil nil) tgs))
10786 (save-excursion
10787 (save-restriction
10788 (widen)
10789 (goto-char (point-min))
10790 (while (re-search-forward descre nil t)
10791 (goto-char (setq pos0 (point-at-bol)))
10792 (catch 'next
10793 (when org-refile-target-verify-function
10794 (save-match-data
10795 (or (funcall org-refile-target-verify-function)
10796 (throw 'next t))))
10797 (when (and (looking-at org-complex-heading-regexp)
10798 (not (member (match-string 4) excluded-entries))
10799 (match-string 4))
10800 (setq level (org-reduced-level
10801 (- (match-end 1) (match-beginning 1)))
10802 txt (org-link-display-format (match-string 4))
10803 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10804 re (format org-complex-heading-regexp-format
10805 (regexp-quote (match-string 4))))
10806 (when org-refile-use-outline-path
10807 (setq txt (mapconcat
10808 'org-protect-slash
10809 (append
10810 (if (eq org-refile-use-outline-path
10811 'file)
10812 (list (file-name-nondirectory
10813 (buffer-file-name
10814 (buffer-base-buffer))))
10815 (if (eq org-refile-use-outline-path
10816 'full-file-path)
10817 (list (buffer-file-name
10818 (buffer-base-buffer)))))
10819 (org-get-outline-path fast-path-p
10820 level txt)
10821 (list txt))
10822 "/")))
10823 (push (list txt f re (org-refile-marker (point)))
10824 tgs)))
10825 (when (= (point) pos0)
10826 ;; verification function has not moved point
10827 (goto-char (point-at-eol))))))))
10828 (when org-refile-use-cache
10829 (org-refile-cache-put tgs (buffer-file-name) descre))
10830 (setq targets (append tgs targets))
10831 ))))
10832 (message "Getting targets...done")
10833 (nreverse targets)))
10835 (defun org-protect-slash (s)
10836 (while (string-match "/" s)
10837 (setq s (replace-match "\\" t t s)))
10840 (defvar org-olpa (make-vector 20 nil))
10842 (defun org-get-outline-path (&optional fastp level heading)
10843 "Return the outline path to the current entry, as a list.
10845 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10846 routine which makes outline path derivations for an entire file,
10847 avoiding backtracing. Refile target collection makes use of that."
10848 (if fastp
10849 (progn
10850 (if (> level 19)
10851 (error "Outline path failure, more than 19 levels"))
10852 (loop for i from level upto 19 do
10853 (aset org-olpa i nil))
10854 (prog1
10855 (delq nil (append org-olpa nil))
10856 (aset org-olpa level heading)))
10857 (let (rtn case-fold-search)
10858 (save-excursion
10859 (save-restriction
10860 (widen)
10861 (while (org-up-heading-safe)
10862 (when (looking-at org-complex-heading-regexp)
10863 (push (org-match-string-no-properties 4) rtn)))
10864 rtn)))))
10866 (defun org-format-outline-path (path &optional width prefix separator)
10867 "Format the outline path PATH for display.
10868 WIDTH is the maximum number of characters that is available.
10869 PREFIX is a prefix to be included in the returned string,
10870 such as the file name.
10871 SEPARATOR is inserted between the different parts of the path,
10872 the default is \"/\"."
10873 (setq width (or width 79))
10874 (if prefix (setq width (- width (length prefix))))
10875 (if (not path)
10876 (or prefix "")
10877 (let* ((nsteps (length path))
10878 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10879 (maxwidth (if (<= total-width width)
10880 10000 ;; everything fits
10881 ;; we need to shorten the level headings
10882 (/ (- width nsteps) nsteps)))
10883 (org-odd-levels-only nil)
10884 (n 0)
10885 (total (1+ (length prefix))))
10886 (setq maxwidth (max maxwidth 10))
10887 (concat prefix
10888 (if prefix (or separator "/"))
10889 (mapconcat
10890 (lambda (h)
10891 (setq n (1+ n))
10892 (if (and (= n nsteps) (< maxwidth 10000))
10893 (setq maxwidth (- total-width total)))
10894 (if (< (length h) maxwidth)
10895 (progn (setq total (+ total (length h) 1)) h)
10896 (setq h (substring h 0 (- maxwidth 2))
10897 total (+ total maxwidth 1))
10898 (if (string-match "[ \t]+\\'" h)
10899 (setq h (substring h 0 (match-beginning 0))))
10900 (setq h (concat h "..")))
10901 (org-add-props h nil 'face
10902 (nth (% (1- n) org-n-level-faces)
10903 org-level-faces))
10905 path (or separator "/"))))))
10907 (defun org-display-outline-path (&optional file current separator just-return-string)
10908 "Display the current outline path in the echo area.
10910 If FILE is non-nil, prepend the output with the file name.
10911 If CURRENT is non-nil, append the current heading to the output.
10912 SEPARATOR is passed through to `org-format-outline-path'. It separates
10913 the different parts of the path and defaults to \"/\".
10914 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
10915 (interactive "P")
10916 (let* (case-fold-search
10917 message-log-max ; Don't populate the *Messages* buffer
10918 (bfn (buffer-file-name (buffer-base-buffer)))
10919 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
10920 res)
10921 (if current (setq path (append path
10922 (save-excursion
10923 (org-back-to-heading t)
10924 (if (looking-at org-complex-heading-regexp)
10925 (list (match-string 4)))))))
10926 (setq res
10927 (org-format-outline-path
10928 path
10929 (1- (frame-width))
10930 (and file bfn (concat (file-name-nondirectory bfn) separator))
10931 separator))
10932 (if just-return-string
10933 (org-no-properties res)
10934 (message "%s" res))))
10936 (defvar org-refile-history nil
10937 "History for refiling operations.")
10939 (defvar org-after-refile-insert-hook nil
10940 "Hook run after `org-refile' has inserted its stuff at the new location.
10941 Note that this is still *before* the stuff will be removed from
10942 the *old* location.")
10944 (defvar org-capture-last-stored-marker)
10945 (defvar org-refile-keep nil
10946 "Non-nil means `org-refile' will copy instead of refile.")
10948 (defun org-copy ()
10949 "Like `org-refile', but copy."
10950 (interactive)
10951 (let ((org-refile-keep t))
10952 (funcall 'org-refile nil nil nil "Copy")))
10954 (defun org-refile (&optional goto default-buffer rfloc msg)
10955 "Move the entry or entries at point to another heading.
10956 The list of target headings is compiled using the information in
10957 `org-refile-targets', which see.
10959 At the target location, the entry is filed as a subitem of the target
10960 heading. Depending on `org-reverse-note-order', the new subitem will
10961 either be the first or the last subitem.
10963 If there is an active region, all entries in that region will be moved.
10964 However, the region must fulfill the requirement that the first heading
10965 is the first one sets the top-level of the moved text - at most siblings
10966 below it are allowed.
10968 With prefix arg GOTO, the command will only visit the target location
10969 and not actually move anything.
10971 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10972 go to the location where the last refiling operation has put the subtree.
10973 With a prefix argument of `2', refile to the running clock.
10975 RFLOC can be a refile location obtained in a different way.
10977 MSG is a string to replace \"Refile\" in the default prompt with
10978 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
10980 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10982 If you are using target caching (see `org-refile-use-cache'),
10983 you have to clear the target cache in order to find new targets.
10984 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10985 prefix argument (`C-u C-u C-u C-c C-w')."
10987 (interactive "P")
10988 (if (member goto '(0 (64)))
10989 (org-refile-cache-clear)
10990 (let* ((actionmsg (or msg "Refile"))
10991 (cbuf (current-buffer))
10992 (regionp (org-region-active-p))
10993 (region-start (and regionp (region-beginning)))
10994 (region-end (and regionp (region-end)))
10995 (region-length (and regionp (- region-end region-start)))
10996 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10997 pos it nbuf file re level reversed)
10998 (setq last-command nil)
10999 (when regionp
11000 (goto-char region-start)
11001 (or (bolp) (goto-char (point-at-bol)))
11002 (setq region-start (point))
11003 (unless (or (org-kill-is-subtree-p
11004 (buffer-substring region-start region-end))
11005 (prog1 org-refile-active-region-within-subtree
11006 (org-toggle-heading)))
11007 (error "The region is not a (sequence of) subtree(s)")))
11008 (if (equal goto '(16))
11009 (org-refile-goto-last-stored)
11010 (when (or
11011 (and (equal goto 2)
11012 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11013 (prog1
11014 (setq it (list (or org-clock-heading "running clock")
11015 (buffer-file-name
11016 (marker-buffer org-clock-hd-marker))
11018 (marker-position org-clock-hd-marker)))
11019 (setq goto nil)))
11020 (setq it (or rfloc
11021 (let (heading-text)
11022 (save-excursion
11023 (unless goto
11024 (org-back-to-heading t)
11025 (setq heading-text
11026 (nth 4 (org-heading-components))))
11028 (org-refile-get-location
11029 (cond (goto "Goto")
11030 (regionp (concat actionmsg " region to"))
11031 (t (concat actionmsg " subtree \""
11032 heading-text "\" to")))
11033 default-buffer
11034 (and (not (equal '(4) goto))
11035 org-refile-allow-creating-parent-nodes)
11036 goto))))))
11037 (setq file (nth 1 it)
11038 re (nth 2 it)
11039 pos (nth 3 it))
11040 (if (and (not goto)
11042 (equal (buffer-file-name) file)
11043 (if regionp
11044 (and (>= pos region-start)
11045 (<= pos region-end))
11046 (and (>= pos (point))
11047 (< pos (save-excursion
11048 (org-end-of-subtree t t))))))
11049 (error "Cannot refile to position inside the tree or region"))
11051 (setq nbuf (or (find-buffer-visiting file)
11052 (find-file-noselect file)))
11053 (if goto
11054 (progn
11055 (org-pop-to-buffer-same-window nbuf)
11056 (goto-char pos)
11057 (org-show-context 'org-goto))
11058 (if regionp
11059 (progn
11060 (org-kill-new (buffer-substring region-start region-end))
11061 (org-save-markers-in-region region-start region-end))
11062 (org-copy-subtree 1 nil t))
11063 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11064 (find-file-noselect file)))
11065 (setq reversed (org-notes-order-reversed-p))
11066 (save-excursion
11067 (save-restriction
11068 (widen)
11069 (if pos
11070 (progn
11071 (goto-char pos)
11072 (looking-at org-outline-regexp)
11073 (setq level (org-get-valid-level (funcall outline-level) 1))
11074 (goto-char
11075 (if reversed
11076 (or (outline-next-heading) (point-max))
11077 (or (save-excursion (org-get-next-sibling))
11078 (org-end-of-subtree t t)
11079 (point-max)))))
11080 (setq level 1)
11081 (if (not reversed)
11082 (goto-char (point-max))
11083 (goto-char (point-min))
11084 (or (outline-next-heading) (goto-char (point-max)))))
11085 (if (not (bolp)) (newline))
11086 (org-paste-subtree level)
11087 (when org-log-refile
11088 (org-add-log-setup 'refile nil nil 'findpos
11089 org-log-refile)
11090 (unless (eq org-log-refile 'note)
11091 (save-excursion (org-add-log-note))))
11092 (and org-auto-align-tags
11093 (let ((org-loop-over-headlines-in-active-region nil))
11094 (org-set-tags nil t)))
11095 (with-demoted-errors
11096 (bookmark-set "org-refile-last-stored"))
11097 ;; If we are refiling for capture, make sure that the
11098 ;; last-capture pointers point here
11099 (when (org-bound-and-true-p org-refile-for-capture)
11100 (with-demoted-errors
11101 (bookmark-set "org-capture-last-stored-marker"))
11102 (move-marker org-capture-last-stored-marker (point)))
11103 (if (fboundp 'deactivate-mark) (deactivate-mark))
11104 (run-hooks 'org-after-refile-insert-hook))))
11105 (unless org-refile-keep
11106 (if regionp
11107 (delete-region (point) (+ (point) region-length))
11108 (org-cut-subtree)))
11109 (when (featurep 'org-inlinetask)
11110 (org-inlinetask-remove-END-maybe))
11111 (setq org-markers-to-move nil)
11112 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11114 (defun org-refile-goto-last-stored ()
11115 "Go to the location where the last refile was stored."
11116 (interactive)
11117 (bookmark-jump "org-refile-last-stored")
11118 (message "This is the location of the last refile"))
11120 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11121 no-exclude)
11122 "Prompt the user for a refile location, using PROMPT.
11123 PROMPT should not be suffixed with a colon and a space, because
11124 this function appends the default value from
11125 `org-refile-history' automatically, if that is not empty.
11126 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11127 this is used for the GOTO interface."
11128 (let ((org-refile-targets org-refile-targets)
11129 (org-refile-use-outline-path org-refile-use-outline-path)
11130 excluded-entries)
11131 (when (and (derived-mode-p 'org-mode)
11132 (not org-refile-use-cache)
11133 (not no-exclude))
11134 (org-map-tree
11135 (lambda()
11136 (setq excluded-entries
11137 (append excluded-entries (list (org-get-heading t t)))))))
11138 (setq org-refile-target-table
11139 (org-refile-get-targets default-buffer excluded-entries)))
11140 (unless org-refile-target-table
11141 (error "No refile targets"))
11142 (let* ((cbuf (current-buffer))
11143 (partial-completion-mode nil)
11144 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11145 (cfunc (if (and org-refile-use-outline-path
11146 org-outline-path-complete-in-steps)
11147 'org-olpath-completing-read
11148 'org-icompleting-read))
11149 (extra (if org-refile-use-outline-path "/" ""))
11150 (cbnex (concat (buffer-name) extra))
11151 (filename (and cfn (expand-file-name cfn)))
11152 (tbl (mapcar
11153 (lambda (x)
11154 (if (and (not (member org-refile-use-outline-path
11155 '(file full-file-path)))
11156 (not (equal filename (nth 1 x))))
11157 (cons (concat (car x) extra " ("
11158 (file-name-nondirectory (nth 1 x)) ")")
11159 (cdr x))
11160 (cons (concat (car x) extra) (cdr x))))
11161 org-refile-target-table))
11162 (completion-ignore-case t)
11163 cdef
11164 (prompt (concat prompt
11165 (or (and (car org-refile-history)
11166 (concat " (default " (car org-refile-history) ")"))
11167 (and (assoc cbnex tbl) (setq cdef cbnex)
11168 (concat " (default " cbnex ")"))) ": "))
11169 pa answ parent-target child parent old-hist)
11170 (setq old-hist org-refile-history)
11171 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11172 nil 'org-refile-history (or cdef (car org-refile-history))))
11173 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11174 (org-refile-check-position pa)
11175 (if pa
11176 (progn
11177 (when (or (not org-refile-history)
11178 (not (eq old-hist org-refile-history))
11179 (not (equal (car pa) (car org-refile-history))))
11180 (setq org-refile-history
11181 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11182 org-refile-history
11183 (cdr org-refile-history))))
11184 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11185 (pop org-refile-history)))
11187 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11188 (progn
11189 (setq parent (match-string 1 answ)
11190 child (match-string 2 answ))
11191 (setq parent-target (or (assoc parent tbl)
11192 (assoc (concat parent "/") tbl)))
11193 (when (and parent-target
11194 (or (eq new-nodes t)
11195 (and (eq new-nodes 'confirm)
11196 (y-or-n-p (format "Create new node \"%s\"? "
11197 child)))))
11198 (org-refile-new-child parent-target child)))
11199 (error "Invalid target location")))))
11201 (declare-function org-string-nw-p "org-macs" (s))
11202 (defun org-refile-check-position (refile-pointer)
11203 "Check if the refile pointer matches the headline to which it points."
11204 (let* ((file (nth 1 refile-pointer))
11205 (re (nth 2 refile-pointer))
11206 (pos (nth 3 refile-pointer))
11207 buffer)
11208 (if (and (not (markerp pos)) (not file))
11209 (error "Please save the buffer to a file before refiling")
11210 (when (org-string-nw-p re)
11211 (setq buffer (if (markerp pos)
11212 (marker-buffer pos)
11213 (or (find-buffer-visiting file)
11214 (find-file-noselect file))))
11215 (with-current-buffer buffer
11216 (save-excursion
11217 (save-restriction
11218 (widen)
11219 (goto-char pos)
11220 (beginning-of-line 1)
11221 (unless (org-looking-at-p re)
11222 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11224 (defun org-refile-new-child (parent-target child)
11225 "Use refile target PARENT-TARGET to add new CHILD below it."
11226 (unless parent-target
11227 (error "Cannot find parent for new node"))
11228 (let ((file (nth 1 parent-target))
11229 (pos (nth 3 parent-target))
11230 level)
11231 (with-current-buffer (or (find-buffer-visiting file)
11232 (find-file-noselect file))
11233 (save-excursion
11234 (save-restriction
11235 (widen)
11236 (if pos
11237 (goto-char pos)
11238 (goto-char (point-max))
11239 (if (not (bolp)) (newline)))
11240 (when (looking-at org-outline-regexp)
11241 (setq level (funcall outline-level))
11242 (org-end-of-subtree t t))
11243 (org-back-over-empty-lines)
11244 (insert "\n" (make-string
11245 (if pos (org-get-valid-level level 1) 1) ?*)
11246 " " child "\n")
11247 (beginning-of-line 0)
11248 (list (concat (car parent-target) "/" child) file "" (point)))))))
11250 (defun org-olpath-completing-read (prompt collection &rest args)
11251 "Read an outline path like a file name."
11252 (let ((thetable collection)
11253 (org-completion-use-ido nil) ; does not work with ido.
11254 (org-completion-use-iswitchb nil)) ; or iswitchb
11255 (apply
11256 'org-icompleting-read prompt
11257 (lambda (string predicate &optional flag)
11258 (let (rtn r f (l (length string)))
11259 (cond
11260 ((eq flag nil)
11261 ;; try completion
11262 (try-completion string thetable))
11263 ((eq flag t)
11264 ;; all-completions
11265 (setq rtn (all-completions string thetable predicate))
11266 (mapcar
11267 (lambda (x)
11268 (setq r (substring x l))
11269 (if (string-match " ([^)]*)$" x)
11270 (setq f (match-string 0 x))
11271 (setq f ""))
11272 (if (string-match "/" r)
11273 (concat string (substring r 0 (match-end 0)) f)
11275 rtn))
11276 ((eq flag 'lambda)
11277 ;; exact match?
11278 (assoc string thetable)))))
11279 args)))
11281 ;;;; Dynamic blocks
11283 (defun org-find-dblock (name)
11284 "Find the first dynamic block with name NAME in the buffer.
11285 If not found, stay at current position and return nil."
11286 (let ((case-fold-search t) pos)
11287 (save-excursion
11288 (goto-char (point-min))
11289 (setq pos (and (re-search-forward
11290 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11291 (match-beginning 0))))
11292 (if pos (goto-char pos))
11293 pos))
11295 (defconst org-dblock-start-re
11296 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11297 "Matches the start line of a dynamic block, with parameters.")
11299 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11300 "Matches the end of a dynamic block.")
11302 (defun org-create-dblock (plist)
11303 "Create a dynamic block section, with parameters taken from PLIST.
11304 PLIST must contain a :name entry which is used as name of the block."
11305 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11306 (end-of-line 1)
11307 (newline))
11308 (let ((col (current-column))
11309 (name (plist-get plist :name)))
11310 (insert "#+BEGIN: " name)
11311 (while plist
11312 (if (eq (car plist) :name)
11313 (setq plist (cddr plist))
11314 (insert " " (prin1-to-string (pop plist)))))
11315 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11316 (beginning-of-line -2)))
11318 (defun org-prepare-dblock ()
11319 "Prepare dynamic block for refresh.
11320 This empties the block, puts the cursor at the insert position and returns
11321 the property list including an extra property :name with the block name."
11322 (unless (looking-at org-dblock-start-re)
11323 (error "Not at a dynamic block"))
11324 (let* ((begdel (1+ (match-end 0)))
11325 (name (org-no-properties (match-string 1)))
11326 (params (append (list :name name)
11327 (read (concat "(" (match-string 3) ")")))))
11328 (save-excursion
11329 (beginning-of-line 1)
11330 (skip-chars-forward " \t")
11331 (setq params (plist-put params :indentation-column (current-column))))
11332 (unless (re-search-forward org-dblock-end-re nil t)
11333 (error "Dynamic block not terminated"))
11334 (setq params
11335 (append params
11336 (list :content (buffer-substring
11337 begdel (match-beginning 0)))))
11338 (delete-region begdel (match-beginning 0))
11339 (goto-char begdel)
11340 (open-line 1)
11341 params))
11343 (defun org-map-dblocks (&optional command)
11344 "Apply COMMAND to all dynamic blocks in the current buffer.
11345 If COMMAND is not given, use `org-update-dblock'."
11346 (let ((cmd (or command 'org-update-dblock)))
11347 (save-excursion
11348 (goto-char (point-min))
11349 (while (re-search-forward org-dblock-start-re nil t)
11350 (goto-char (match-beginning 0))
11351 (save-excursion
11352 (condition-case nil
11353 (funcall cmd)
11354 (error (message "Error during update of dynamic block"))))
11355 (unless (re-search-forward org-dblock-end-re nil t)
11356 (error "Dynamic block not terminated"))))))
11358 (defun org-dblock-update (&optional arg)
11359 "User command for updating dynamic blocks.
11360 Update the dynamic block at point. With prefix ARG, update all dynamic
11361 blocks in the buffer."
11362 (interactive "P")
11363 (if arg
11364 (org-update-all-dblocks)
11365 (or (looking-at org-dblock-start-re)
11366 (org-beginning-of-dblock))
11367 (org-update-dblock)))
11369 (defun org-update-dblock ()
11370 "Update the dynamic block at point.
11371 This means to empty the block, parse for parameters and then call
11372 the correct writing function."
11373 (interactive)
11374 (save-window-excursion
11375 (let* ((pos (point))
11376 (line (org-current-line))
11377 (params (org-prepare-dblock))
11378 (name (plist-get params :name))
11379 (indent (plist-get params :indentation-column))
11380 (cmd (intern (concat "org-dblock-write:" name))))
11381 (message "Updating dynamic block `%s' at line %d..." name line)
11382 (funcall cmd params)
11383 (message "Updating dynamic block `%s' at line %d...done" name line)
11384 (goto-char pos)
11385 (when (and indent (> indent 0))
11386 (setq indent (make-string indent ?\ ))
11387 (save-excursion
11388 (org-beginning-of-dblock)
11389 (forward-line 1)
11390 (while (not (looking-at org-dblock-end-re))
11391 (insert indent)
11392 (beginning-of-line 2))
11393 (when (looking-at org-dblock-end-re)
11394 (and (looking-at "[ \t]+")
11395 (replace-match ""))
11396 (insert indent)))))))
11398 (defun org-beginning-of-dblock ()
11399 "Find the beginning of the dynamic block at point.
11400 Error if there is no such block at point."
11401 (let ((pos (point))
11402 beg)
11403 (end-of-line 1)
11404 (if (and (re-search-backward org-dblock-start-re nil t)
11405 (setq beg (match-beginning 0))
11406 (re-search-forward org-dblock-end-re nil t)
11407 (> (match-end 0) pos))
11408 (goto-char beg)
11409 (goto-char pos)
11410 (error "Not in a dynamic block"))))
11412 (defun org-update-all-dblocks ()
11413 "Update all dynamic blocks in the buffer.
11414 This function can be used in a hook."
11415 (interactive)
11416 (when (derived-mode-p 'org-mode)
11417 (org-map-dblocks 'org-update-dblock)))
11420 ;;;; Completion
11422 (defun org-get-export-keywords ()
11423 "Return a list of all currently understood export keywords.
11424 Export keywords include options, block names, attributes and
11425 keywords relative to each registered export back-end."
11426 (delq nil
11427 (let (keywords)
11428 (mapc
11429 (lambda (back-end)
11430 (let ((props (cdr back-end)))
11431 ;; Back-end name (for keywords, like #+LATEX:)
11432 (push (upcase (symbol-name (car back-end))) keywords)
11433 ;; Back-end options.
11434 (mapc (lambda (option) (push (cadr option) keywords))
11435 (plist-get (cdr back-end) :options-alist))))
11436 (org-bound-and-true-p org-export-registered-backends))
11437 keywords)))
11439 (defconst org-options-keywords
11440 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE"
11441 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11442 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY"
11443 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11444 "TITLE:" "TODO:" "TYP_TODO:"))
11446 (defcustom org-structure-template-alist
11447 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11448 "<src lang=\"?\">\n\n</src>")
11449 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11450 "<example>\n?\n</example>")
11451 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11452 "<quote>\n?\n</quote>")
11453 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11454 "<verse>\n?\n</verse>")
11455 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11456 "<verbatim>\n?\n</verbatim>")
11457 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11458 "<center>\n?\n</center>")
11459 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11460 "<literal style=\"latex\">\n?\n</literal>")
11461 ("L" "#+LaTeX: "
11462 "<literal style=\"latex\">?</literal>")
11463 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11464 "<literal style=\"html\">\n?\n</literal>")
11465 ("H" "#+HTML: "
11466 "<literal style=\"html\">?</literal>")
11467 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11468 ("A" "#+ASCII: ")
11469 ("i" "#+INDEX: ?"
11470 "#+INDEX: ?")
11471 ("I" "#+INCLUDE: %file ?"
11472 "<include file=%file markup=\"?\">"))
11473 "Structure completion elements.
11474 This is a list of abbreviation keys and values. The value gets inserted
11475 if you type `<' followed by the key and then press the completion key,
11476 usually `M-TAB'. %file will be replaced by a file name after prompting
11477 for the file using completion. The cursor will be placed at the position
11478 of the `?` in the template.
11479 There are two templates for each key, the first uses the original Org syntax,
11480 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11481 the default when the /org-mtags.el/ module has been loaded. See also the
11482 variable `org-mtags-prefer-muse-templates'."
11483 :group 'org-completion
11484 :type '(repeat
11485 (string :tag "Key")
11486 (string :tag "Template")
11487 (string :tag "Muse Template")))
11489 (defun org-try-structure-completion ()
11490 "Try to complete a structure template before point.
11491 This looks for strings like \"<e\" on an otherwise empty line and
11492 expands them."
11493 (let ((l (buffer-substring (point-at-bol) (point)))
11495 (when (and (looking-at "[ \t]*$")
11496 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11497 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11498 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11499 (match-beginning 1)) a)
11500 t)))
11502 (defun org-complete-expand-structure-template (start cell)
11503 "Expand a structure template."
11504 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11505 (rpl (nth (if musep 2 1) cell))
11506 (ind ""))
11507 (delete-region start (point))
11508 (when (string-match "\\`#\\+" rpl)
11509 (cond
11510 ((bolp))
11511 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11512 (setq ind (buffer-substring (point-at-bol) (point))))
11513 (t (newline))))
11514 (setq start (point))
11515 (if (string-match "%file" rpl)
11516 (setq rpl (replace-match
11517 (concat
11518 "\""
11519 (save-match-data
11520 (abbreviate-file-name (read-file-name "Include file: ")))
11521 "\"")
11522 t t rpl)))
11523 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11524 (concat "\n" ind)))
11525 (insert rpl)
11526 (if (re-search-backward "\\?" start t) (delete-char 1))))
11528 ;;;; TODO, DEADLINE, Comments
11530 (defun org-toggle-comment ()
11531 "Change the COMMENT state of an entry."
11532 (interactive)
11533 (save-excursion
11534 (org-back-to-heading)
11535 (let (case-fold-search)
11536 (cond
11537 ((looking-at (format org-heading-keyword-regexp-format
11538 org-comment-string))
11539 (goto-char (match-end 1))
11540 (looking-at (concat " +" org-comment-string))
11541 (replace-match "" t t)
11542 (when (eolp) (insert " ")))
11543 ((looking-at org-outline-regexp)
11544 (goto-char (match-end 0))
11545 (insert org-comment-string " "))))))
11547 (defvar org-last-todo-state-is-todo nil
11548 "This is non-nil when the last TODO state change led to a TODO state.
11549 If the last change removed the TODO tag or switched to DONE, then
11550 this is nil.")
11552 (defvar org-setting-tags nil) ; dynamically skipped
11554 (defvar org-todo-setup-filter-hook nil
11555 "Hook for functions that pre-filter todo specs.
11556 Each function takes a todo spec and returns either nil or the spec
11557 transformed into canonical form." )
11559 (defvar org-todo-get-default-hook nil
11560 "Hook for functions that get a default item for todo.
11561 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11562 nil or a string to be used for the todo mark." )
11564 (defvar org-agenda-headline-snapshot-before-repeat)
11566 (defun org-current-effective-time ()
11567 "Return current time adjusted for `org-extend-today-until' variable."
11568 (let* ((ct (org-current-time))
11569 (dct (decode-time ct))
11570 (ct1
11571 (cond
11572 (org-use-last-clock-out-time-as-effective-time
11573 (or (org-clock-get-last-clock-out-time) ct))
11574 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11575 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11576 (t ct))))
11577 ct1))
11579 (defun org-todo-yesterday (&optional arg)
11580 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11581 (interactive "P")
11582 (if (eq major-mode 'org-agenda-mode)
11583 (apply 'org-agenda-todo-yesterday arg)
11584 (let* ((hour (third (decode-time
11585 (org-current-time))))
11586 (org-extend-today-until (1+ hour)))
11587 (org-todo arg))))
11589 (defvar org-block-entry-blocking ""
11590 "First entry preventing the TODO state change.")
11592 (defun org-todo (&optional arg)
11593 "Change the TODO state of an item.
11594 The state of an item is given by a keyword at the start of the heading,
11595 like
11596 *** TODO Write paper
11597 *** DONE Call mom
11599 The different keywords are specified in the variable `org-todo-keywords'.
11600 By default the available states are \"TODO\" and \"DONE\".
11601 So for this example: when the item starts with TODO, it is changed to DONE.
11602 When it starts with DONE, the DONE is removed. And when neither TODO nor
11603 DONE are present, add TODO at the beginning of the heading.
11605 With \\[universal-argument] prefix arg, use completion to determine the new \
11606 state.
11607 With numeric prefix arg, switch to that state.
11608 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11609 keywords (nextset).
11610 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11611 With a numeric prefix arg of 0, inhibit note taking for the change.
11613 For calling through lisp, arg is also interpreted in the following way:
11614 'none -> empty state
11615 \"\"(empty string) -> switch to empty state
11616 'done -> switch to DONE
11617 'nextset -> switch to the next set of keywords
11618 'previousset -> switch to the previous set of keywords
11619 \"WAITING\" -> switch to the specified keyword, but only if it
11620 really is a member of `org-todo-keywords'."
11621 (interactive "P")
11622 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11623 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11624 'region-start-level 'region))
11625 org-loop-over-headlines-in-active-region)
11626 (org-map-entries
11627 `(org-todo ,arg)
11628 org-loop-over-headlines-in-active-region
11629 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11630 (if (equal arg '(16)) (setq arg 'nextset))
11631 (let ((org-blocker-hook org-blocker-hook)
11632 commentp
11633 case-fold-search)
11634 (when (equal arg '(64))
11635 (setq arg nil org-blocker-hook nil))
11636 (when (and org-blocker-hook
11637 (or org-inhibit-blocking
11638 (org-entry-get nil "NOBLOCKING")))
11639 (setq org-blocker-hook nil))
11640 (save-excursion
11641 (catch 'exit
11642 (org-back-to-heading t)
11643 (when (looking-at (concat "^\\*+ " org-comment-string))
11644 (org-toggle-comment)
11645 (setq commentp t))
11646 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11647 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11648 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11649 (let* ((match-data (match-data))
11650 (startpos (point-at-bol))
11651 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11652 (org-log-done org-log-done)
11653 (org-log-repeat org-log-repeat)
11654 (org-todo-log-states org-todo-log-states)
11655 (org-inhibit-logging
11656 (if (equal arg 0)
11657 (progn (setq arg nil) 'note) org-inhibit-logging))
11658 (this (match-string 1))
11659 (hl-pos (match-beginning 0))
11660 (head (org-get-todo-sequence-head this))
11661 (ass (assoc head org-todo-kwd-alist))
11662 (interpret (nth 1 ass))
11663 (done-word (nth 3 ass))
11664 (final-done-word (nth 4 ass))
11665 (org-last-state (or this ""))
11666 (completion-ignore-case t)
11667 (member (member this org-todo-keywords-1))
11668 (tail (cdr member))
11669 (org-state (cond
11670 ((and org-todo-key-trigger
11671 (or (and (equal arg '(4))
11672 (eq org-use-fast-todo-selection 'prefix))
11673 (and (not arg) org-use-fast-todo-selection
11674 (not (eq org-use-fast-todo-selection
11675 'prefix)))))
11676 ;; Use fast selection
11677 (org-fast-todo-selection))
11678 ((and (equal arg '(4))
11679 (or (not org-use-fast-todo-selection)
11680 (not org-todo-key-trigger)))
11681 ;; Read a state with completion
11682 (org-icompleting-read
11683 "State: " (mapcar (lambda(x) (list x))
11684 org-todo-keywords-1)
11685 nil t))
11686 ((eq arg 'right)
11687 (if this
11688 (if tail (car tail) nil)
11689 (car org-todo-keywords-1)))
11690 ((eq arg 'left)
11691 (if (equal member org-todo-keywords-1)
11693 (if this
11694 (nth (- (length org-todo-keywords-1)
11695 (length tail) 2)
11696 org-todo-keywords-1)
11697 (org-last org-todo-keywords-1))))
11698 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11699 (setq arg nil))) ; hack to fall back to cycling
11700 (arg
11701 ;; user or caller requests a specific state
11702 (cond
11703 ((equal arg "") nil)
11704 ((eq arg 'none) nil)
11705 ((eq arg 'done) (or done-word (car org-done-keywords)))
11706 ((eq arg 'nextset)
11707 (or (car (cdr (member head org-todo-heads)))
11708 (car org-todo-heads)))
11709 ((eq arg 'previousset)
11710 (let ((org-todo-heads (reverse org-todo-heads)))
11711 (or (car (cdr (member head org-todo-heads)))
11712 (car org-todo-heads))))
11713 ((car (member arg org-todo-keywords-1)))
11714 ((stringp arg)
11715 (error "State `%s' not valid in this file" arg))
11716 ((nth (1- (prefix-numeric-value arg))
11717 org-todo-keywords-1))))
11718 ((null member) (or head (car org-todo-keywords-1)))
11719 ((equal this final-done-word) nil) ;; -> make empty
11720 ((null tail) nil) ;; -> first entry
11721 ((memq interpret '(type priority))
11722 (if (eq this-command last-command)
11723 (car tail)
11724 (if (> (length tail) 0)
11725 (or done-word (car org-done-keywords))
11726 nil)))
11728 (car tail))))
11729 (org-state (or
11730 (run-hook-with-args-until-success
11731 'org-todo-get-default-hook org-state org-last-state)
11732 org-state))
11733 (next (if org-state (concat " " org-state " ") " "))
11734 (change-plist (list :type 'todo-state-change :from this :to org-state
11735 :position startpos))
11736 dolog now-done-p)
11737 (when org-blocker-hook
11738 (setq org-last-todo-state-is-todo
11739 (not (member this org-done-keywords)))
11740 (unless (save-excursion
11741 (save-match-data
11742 (org-with-wide-buffer
11743 (run-hook-with-args-until-failure
11744 'org-blocker-hook change-plist))))
11745 (if (org-called-interactively-p 'interactive)
11746 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
11747 this org-state org-block-entry-blocking)
11748 ;; fail silently
11749 (message "TODO state change from %s to %s blocked (by \"%s\")"
11750 this org-state org-block-entry-blocking)
11751 (throw 'exit nil))))
11752 (store-match-data match-data)
11753 (replace-match next t t)
11754 (unless (pos-visible-in-window-p hl-pos)
11755 (message "TODO state changed to %s" (org-trim next)))
11756 (unless head
11757 (setq head (org-get-todo-sequence-head org-state)
11758 ass (assoc head org-todo-kwd-alist)
11759 interpret (nth 1 ass)
11760 done-word (nth 3 ass)
11761 final-done-word (nth 4 ass)))
11762 (when (memq arg '(nextset previousset))
11763 (message "Keyword-Set %d/%d: %s"
11764 (- (length org-todo-sets) -1
11765 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11766 (length org-todo-sets)
11767 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11768 (setq org-last-todo-state-is-todo
11769 (not (member org-state org-done-keywords)))
11770 (setq now-done-p (and (member org-state org-done-keywords)
11771 (not (member this org-done-keywords))))
11772 (and logging (org-local-logging logging))
11773 (when (and (or org-todo-log-states org-log-done)
11774 (not (eq org-inhibit-logging t))
11775 (not (memq arg '(nextset previousset))))
11776 ;; we need to look at recording a time and note
11777 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11778 (nth 2 (assoc this org-todo-log-states))))
11779 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11780 (setq dolog 'time))
11781 (when (and org-state
11782 (member org-state org-not-done-keywords)
11783 (not (member this org-not-done-keywords)))
11784 ;; This is now a todo state and was not one before
11785 ;; If there was a CLOSED time stamp, get rid of it.
11786 (org-add-planning-info nil nil 'closed))
11787 (when (and now-done-p org-log-done)
11788 ;; It is now done, and it was not done before
11789 (org-add-planning-info 'closed (org-current-effective-time))
11790 (if (and (not dolog) (eq 'note org-log-done))
11791 (org-add-log-setup 'done org-state this 'findpos 'note)))
11792 (when (and org-state dolog)
11793 ;; This is a non-nil state, and we need to log it
11794 (org-add-log-setup 'state org-state this 'findpos dolog)))
11795 ;; Fixup tag positioning
11796 (org-todo-trigger-tag-changes org-state)
11797 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11798 (when org-provide-todo-statistics
11799 (org-update-parent-todo-statistics))
11800 (run-hooks 'org-after-todo-state-change-hook)
11801 (if (and arg (not (member org-state org-done-keywords)))
11802 (setq head (org-get-todo-sequence-head org-state)))
11803 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11804 ;; Do we need to trigger a repeat?
11805 (when now-done-p
11806 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11807 ;; This is for the agenda, take a snapshot of the headline.
11808 (save-match-data
11809 (setq org-agenda-headline-snapshot-before-repeat
11810 (org-get-heading))))
11811 (org-auto-repeat-maybe org-state))
11812 ;; Fixup cursor location if close to the keyword
11813 (if (and (outline-on-heading-p)
11814 (not (bolp))
11815 (save-excursion (beginning-of-line 1)
11816 (looking-at org-todo-line-regexp))
11817 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11818 (progn
11819 (goto-char (or (match-end 2) (match-end 1)))
11820 (and (looking-at " ") (just-one-space))))
11821 (when org-trigger-hook
11822 (save-excursion
11823 (run-hook-with-args 'org-trigger-hook change-plist)))
11824 (when commentp (org-toggle-comment))))))))
11826 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11827 "Block turning an entry into a TODO, using the hierarchy.
11828 This checks whether the current task should be blocked from state
11829 changes. Such blocking occurs when:
11831 1. The task has children which are not all in a completed state.
11833 2. A task has a parent with the property :ORDERED:, and there
11834 are siblings prior to the current task with incomplete
11835 status.
11837 3. The parent of the task is blocked because it has siblings that should
11838 be done first, or is child of a block grandparent TODO entry."
11840 (if (not org-enforce-todo-dependencies)
11841 t ; if locally turned off don't block
11842 (catch 'dont-block
11843 ;; If this is not a todo state change, or if this entry is already DONE,
11844 ;; do not block
11845 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11846 (member (plist-get change-plist :from)
11847 (cons 'done org-done-keywords))
11848 (member (plist-get change-plist :to)
11849 (cons 'todo org-not-done-keywords))
11850 (not (plist-get change-plist :to)))
11851 (throw 'dont-block t))
11852 ;; If this task has children, and any are undone, it's blocked
11853 (save-excursion
11854 (org-back-to-heading t)
11855 (let ((this-level (funcall outline-level)))
11856 (outline-next-heading)
11857 (let ((child-level (funcall outline-level)))
11858 (while (and (not (eobp))
11859 (> child-level this-level))
11860 ;; this todo has children, check whether they are all
11861 ;; completed
11862 (if (and (not (org-entry-is-done-p))
11863 (org-entry-is-todo-p))
11864 (progn (setq org-block-entry-blocking (org-get-heading))
11865 (throw 'dont-block nil)))
11866 (outline-next-heading)
11867 (setq child-level (funcall outline-level))))))
11868 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11869 ;; any previous siblings are undone, it's blocked
11870 (save-excursion
11871 (org-back-to-heading t)
11872 (let* ((pos (point))
11873 (parent-pos (and (org-up-heading-safe) (point))))
11874 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11875 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11876 (forward-line 1)
11877 (re-search-forward org-not-done-heading-regexp pos t))
11878 (setq org-block-entry-blocking (match-string 0))
11879 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11880 ;; Search further up the hierarchy, to see if an ancestor is blocked
11881 (while t
11882 (goto-char parent-pos)
11883 (if (not (looking-at org-not-done-heading-regexp))
11884 (throw 'dont-block t)) ; do not block, parent is not a TODO
11885 (setq pos (point))
11886 (setq parent-pos (and (org-up-heading-safe) (point)))
11887 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11888 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11889 (forward-line 1)
11890 (re-search-forward org-not-done-heading-regexp pos t)
11891 (setq org-block-entry-blocking (org-get-heading)))
11892 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11894 (defcustom org-track-ordered-property-with-tag nil
11895 "Should the ORDERED property also be shown as a tag?
11896 The ORDERED property decides if an entry should require subtasks to be
11897 completed in sequence. Since a property is not very visible, setting
11898 this option means that toggling the ORDERED property with the command
11899 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11900 not relevant for the behavior, but it makes things more visible.
11902 Note that toggling the tag with tags commands will not change the property
11903 and therefore not influence behavior!
11905 This can be t, meaning the tag ORDERED should be used, It can also be a
11906 string to select a different tag for this task."
11907 :group 'org-todo
11908 :type '(choice
11909 (const :tag "No tracking" nil)
11910 (const :tag "Track with ORDERED tag" t)
11911 (string :tag "Use other tag")))
11913 (defun org-toggle-ordered-property ()
11914 "Toggle the ORDERED property of the current entry.
11915 For better visibility, you can track the value of this property with a tag.
11916 See variable `org-track-ordered-property-with-tag'."
11917 (interactive)
11918 (let* ((t1 org-track-ordered-property-with-tag)
11919 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11920 (save-excursion
11921 (org-back-to-heading)
11922 (if (org-entry-get nil "ORDERED")
11923 (progn
11924 (org-delete-property "ORDERED")
11925 (and tag (org-toggle-tag tag 'off))
11926 (message "Subtasks can be completed in arbitrary order"))
11927 (org-entry-put nil "ORDERED" "t")
11928 (and tag (org-toggle-tag tag 'on))
11929 (message "Subtasks must be completed in sequence")))))
11931 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11932 (defun org-block-todo-from-checkboxes (change-plist)
11933 "Block turning an entry into a TODO, using checkboxes.
11934 This checks whether the current task should be blocked from state
11935 changes because there are unchecked boxes in this entry."
11936 (if (not org-enforce-todo-checkbox-dependencies)
11937 t ; if locally turned off don't block
11938 (catch 'dont-block
11939 ;; If this is not a todo state change, or if this entry is already DONE,
11940 ;; do not block
11941 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11942 (member (plist-get change-plist :from)
11943 (cons 'done org-done-keywords))
11944 (member (plist-get change-plist :to)
11945 (cons 'todo org-not-done-keywords))
11946 (not (plist-get change-plist :to)))
11947 (throw 'dont-block t))
11948 ;; If this task has checkboxes that are not checked, it's blocked
11949 (save-excursion
11950 (org-back-to-heading t)
11951 (let ((beg (point)) end)
11952 (outline-next-heading)
11953 (setq end (point))
11954 (goto-char beg)
11955 (if (org-list-search-forward
11956 (concat (org-item-beginning-re)
11957 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11958 "\\[[- ]\\]")
11959 end t)
11960 (progn
11961 (if (boundp 'org-blocked-by-checkboxes)
11962 (setq org-blocked-by-checkboxes t))
11963 (throw 'dont-block nil)))))
11964 t))) ; do not block
11966 (defun org-entry-blocked-p ()
11967 "Is the current entry blocked?"
11968 (org-with-buffer-modified-unmodified
11969 (if (org-entry-get nil "NOBLOCKING")
11970 nil ;; Never block this entry
11971 (not
11972 (run-hook-with-args-until-failure
11973 'org-blocker-hook
11974 (list :type 'todo-state-change
11975 :position (point)
11976 :from 'todo
11977 :to 'done))))))
11979 (defun org-update-statistics-cookies (all)
11980 "Update the statistics cookie, either from TODO or from checkboxes.
11981 This should be called with the cursor in a line with a statistics cookie."
11982 (interactive "P")
11983 (if all
11984 (progn
11985 (org-update-checkbox-count 'all)
11986 (org-map-entries 'org-update-parent-todo-statistics))
11987 (if (not (org-at-heading-p))
11988 (org-update-checkbox-count)
11989 (let ((pos (point-marker))
11990 end l1 l2)
11991 (ignore-errors (org-back-to-heading t))
11992 (if (not (org-at-heading-p))
11993 (org-update-checkbox-count)
11994 (setq l1 (org-outline-level))
11995 (setq end (save-excursion
11996 (outline-next-heading)
11997 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11998 (point)))
11999 (if (and (save-excursion
12000 (re-search-forward
12001 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12002 (not (save-excursion (re-search-forward
12003 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12004 (org-update-checkbox-count)
12005 (if (and l2 (> l2 l1))
12006 (progn
12007 (goto-char end)
12008 (org-update-parent-todo-statistics))
12009 (goto-char pos)
12010 (beginning-of-line 1)
12011 (while (re-search-forward
12012 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12013 (point-at-eol) t)
12014 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12015 (goto-char pos)
12016 (move-marker pos nil)))))
12018 (defvar org-entry-property-inherited-from) ;; defined below
12019 (defun org-update-parent-todo-statistics ()
12020 "Update any statistics cookie in the parent of the current headline.
12021 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12022 the entire subtree and this will travel up the hierarchy and update
12023 statistics everywhere."
12024 (let* ((prop (save-excursion (org-up-heading-safe)
12025 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12026 (recursive (or (not org-hierarchical-todo-statistics)
12027 (and prop (string-match "\\<recursive\\>" prop))))
12028 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12030 (first t)
12031 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12032 level ltoggle l1 new ndel
12033 (cnt-all 0) (cnt-done 0) is-percent kwd
12034 checkbox-beg ov ovs ove cookie-present)
12035 (catch 'exit
12036 (save-excursion
12037 (beginning-of-line 1)
12038 (setq ltoggle (funcall outline-level))
12039 ;; Three situations are to consider:
12041 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12042 ;; to the top-level ancestor on the headline;
12044 ;; 2. If parent has "recursive" property, repeat up to the
12045 ;; headline setting that property, taking inheritance into
12046 ;; account;
12048 ;; 3. Else, move up to direct parent and proceed only once.
12049 (while (and (setq level (org-up-heading-safe))
12050 (or recursive first)
12051 (>= (point) lim))
12052 (setq first nil cookie-present nil)
12053 (unless (and level
12054 (not (string-match
12055 "\\<checkbox\\>"
12056 (downcase (or (org-entry-get nil "COOKIE_DATA")
12057 "")))))
12058 (throw 'exit nil))
12059 (while (re-search-forward box-re (point-at-eol) t)
12060 (setq cnt-all 0 cnt-done 0 cookie-present t)
12061 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12062 (save-match-data
12063 (unless (outline-next-heading) (throw 'exit nil))
12064 (while (and (looking-at org-complex-heading-regexp)
12065 (> (setq l1 (length (match-string 1))) level))
12066 (setq kwd (and (or recursive (= l1 ltoggle))
12067 (match-string 2)))
12068 (if (or (eq org-provide-todo-statistics 'all-headlines)
12069 (and (listp org-provide-todo-statistics)
12070 (or (member kwd org-provide-todo-statistics)
12071 (member kwd org-done-keywords))))
12072 (setq cnt-all (1+ cnt-all))
12073 (if (eq org-provide-todo-statistics t)
12074 (and kwd (setq cnt-all (1+ cnt-all)))))
12075 (and (member kwd org-done-keywords)
12076 (setq cnt-done (1+ cnt-done)))
12077 (outline-next-heading)))
12078 (setq new
12079 (if is-percent
12080 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12081 (format "[%d/%d]" cnt-done cnt-all))
12082 ndel (- (match-end 0) checkbox-beg))
12083 ;; handle overlays when updating cookie from column view
12084 (when (setq ov (car (overlays-at checkbox-beg)))
12085 (setq ovs (overlay-start ov) ove (overlay-end ov))
12086 (delete-overlay ov))
12087 (goto-char checkbox-beg)
12088 (insert new)
12089 (delete-region (point) (+ (point) ndel))
12090 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12091 (when ov (move-overlay ov ovs ove)))
12092 (when cookie-present
12093 (run-hook-with-args 'org-after-todo-statistics-hook
12094 cnt-done (- cnt-all cnt-done))))))
12095 (run-hooks 'org-todo-statistics-hook)))
12097 (defvar org-after-todo-statistics-hook nil
12098 "Hook that is called after a TODO statistics cookie has been updated.
12099 Each function is called with two arguments: the number of not-done entries
12100 and the number of done entries.
12102 For example, the following function, when added to this hook, will switch
12103 an entry to DONE when all children are done, and back to TODO when new
12104 entries are set to a TODO status. Note that this hook is only called
12105 when there is a statistics cookie in the headline!
12107 (defun org-summary-todo (n-done n-not-done)
12108 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12109 (let (org-log-done org-log-states) ; turn off logging
12110 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12113 (defvar org-todo-statistics-hook nil
12114 "Hook that is run whenever Org thinks TODO statistics should be updated.
12115 This hook runs even if there is no statistics cookie present, in which case
12116 `org-after-todo-statistics-hook' would not run.")
12118 (defun org-todo-trigger-tag-changes (state)
12119 "Apply the changes defined in `org-todo-state-tags-triggers'."
12120 (let ((l org-todo-state-tags-triggers)
12121 changes)
12122 (when (or (not state) (equal state ""))
12123 (setq changes (append changes (cdr (assoc "" l)))))
12124 (when (and (stringp state) (> (length state) 0))
12125 (setq changes (append changes (cdr (assoc state l)))))
12126 (when (member state org-not-done-keywords)
12127 (setq changes (append changes (cdr (assoc 'todo l)))))
12128 (when (member state org-done-keywords)
12129 (setq changes (append changes (cdr (assoc 'done l)))))
12130 (dolist (c changes)
12131 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12133 (defun org-local-logging (value)
12134 "Get logging settings from a property VALUE."
12135 (let* (words w a)
12136 ;; directly set the variables, they are already local.
12137 (setq org-log-done nil
12138 org-log-repeat nil
12139 org-todo-log-states nil)
12140 (setq words (org-split-string value))
12141 (while (setq w (pop words))
12142 (cond
12143 ((setq a (assoc w org-startup-options))
12144 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12145 (set (nth 1 a) (nth 2 a))))
12146 ((setq a (org-extract-log-state-settings w))
12147 (and (member (car a) org-todo-keywords-1)
12148 (push a org-todo-log-states)))))))
12150 (defun org-get-todo-sequence-head (kwd)
12151 "Return the head of the TODO sequence to which KWD belongs.
12152 If KWD is not set, check if there is a text property remembering the
12153 right sequence."
12154 (let (p)
12155 (cond
12156 ((not kwd)
12157 (or (get-text-property (point-at-bol) 'org-todo-head)
12158 (progn
12159 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12160 nil (point-at-eol)))
12161 (get-text-property p 'org-todo-head))))
12162 ((not (member kwd org-todo-keywords-1))
12163 (car org-todo-keywords-1))
12164 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12166 (defun org-fast-todo-selection ()
12167 "Fast TODO keyword selection with single keys.
12168 Returns the new TODO keyword, or nil if no state change should occur."
12169 (let* ((fulltable org-todo-key-alist)
12170 (done-keywords org-done-keywords) ;; needed for the faces.
12171 (maxlen (apply 'max (mapcar
12172 (lambda (x)
12173 (if (stringp (car x)) (string-width (car x)) 0))
12174 fulltable)))
12175 (expert nil)
12176 (fwidth (+ maxlen 3 1 3))
12177 (ncol (/ (- (window-width) 4) fwidth))
12178 tg cnt e c tbl
12179 groups ingroup)
12180 (save-excursion
12181 (save-window-excursion
12182 (if expert
12183 (set-buffer (get-buffer-create " *Org todo*"))
12184 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12185 (erase-buffer)
12186 (org-set-local 'org-done-keywords done-keywords)
12187 (setq tbl fulltable cnt 0)
12188 (while (setq e (pop tbl))
12189 (cond
12190 ((equal e '(:startgroup))
12191 (push '() groups) (setq ingroup t)
12192 (when (not (= cnt 0))
12193 (setq cnt 0)
12194 (insert "\n"))
12195 (insert "{ "))
12196 ((equal e '(:endgroup))
12197 (setq ingroup nil cnt 0)
12198 (insert "}\n"))
12199 ((equal e '(:newline))
12200 (when (not (= cnt 0))
12201 (setq cnt 0)
12202 (insert "\n")
12203 (setq e (car tbl))
12204 (while (equal (car tbl) '(:newline))
12205 (insert "\n")
12206 (setq tbl (cdr tbl)))))
12208 (setq tg (car e) c (cdr e))
12209 (if ingroup (push tg (car groups)))
12210 (setq tg (org-add-props tg nil 'face
12211 (org-get-todo-face tg)))
12212 (if (and (= cnt 0) (not ingroup)) (insert " "))
12213 (insert "[" c "] " tg (make-string
12214 (- fwidth 4 (length tg)) ?\ ))
12215 (when (= (setq cnt (1+ cnt)) ncol)
12216 (insert "\n")
12217 (if ingroup (insert " "))
12218 (setq cnt 0)))))
12219 (insert "\n")
12220 (goto-char (point-min))
12221 (if (not expert) (org-fit-window-to-buffer))
12222 (message "[a-z..]:Set [SPC]:clear")
12223 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12224 (cond
12225 ((or (= c ?\C-g)
12226 (and (= c ?q) (not (rassoc c fulltable))))
12227 (setq quit-flag t))
12228 ((= c ?\ ) nil)
12229 ((setq e (rassoc c fulltable) tg (car e))
12231 (t (setq quit-flag t)))))))
12233 (defun org-entry-is-todo-p ()
12234 (member (org-get-todo-state) org-not-done-keywords))
12236 (defun org-entry-is-done-p ()
12237 (member (org-get-todo-state) org-done-keywords))
12239 (defun org-get-todo-state ()
12240 (save-excursion
12241 (org-back-to-heading t)
12242 (and (looking-at org-todo-line-regexp)
12243 (match-end 2)
12244 (match-string 2))))
12246 (defun org-at-date-range-p (&optional inactive-ok)
12247 "Is the cursor inside a date range?"
12248 (interactive)
12249 (save-excursion
12250 (catch 'exit
12251 (let ((pos (point)))
12252 (skip-chars-backward "^[<\r\n")
12253 (skip-chars-backward "<[")
12254 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12255 (>= (match-end 0) pos)
12256 (throw 'exit t))
12257 (skip-chars-backward "^<[\r\n")
12258 (skip-chars-backward "<[")
12259 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12260 (>= (match-end 0) pos)
12261 (throw 'exit t)))
12262 nil)))
12264 (defun org-get-repeat (&optional tagline)
12265 "Check if there is a deadline/schedule with repeater in this entry."
12266 (save-match-data
12267 (save-excursion
12268 (org-back-to-heading t)
12269 (and (re-search-forward (if tagline
12270 (concat tagline "\\s-*" org-repeat-re)
12271 org-repeat-re)
12272 (org-entry-end-position) t)
12273 (match-string-no-properties 1)))))
12275 (defvar org-last-changed-timestamp)
12276 (defvar org-last-inserted-timestamp)
12277 (defvar org-log-post-message)
12278 (defvar org-log-note-purpose)
12279 (defvar org-log-note-how)
12280 (defvar org-log-note-extra)
12281 (defun org-auto-repeat-maybe (done-word)
12282 "Check if the current headline contains a repeated deadline/schedule.
12283 If yes, set TODO state back to what it was and change the base date
12284 of repeating deadline/scheduled time stamps to new date.
12285 This function is run automatically after each state change to a DONE state."
12286 ;; last-state is dynamically scoped into this function
12287 (let* ((repeat (org-get-repeat))
12288 (aa (assoc org-last-state org-todo-kwd-alist))
12289 (interpret (nth 1 aa))
12290 (head (nth 2 aa))
12291 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12292 (msg "Entry repeats: ")
12293 (org-log-done nil)
12294 (org-todo-log-states nil)
12295 re type n what ts time to-state)
12296 (when repeat
12297 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12298 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12299 org-todo-repeat-to-state))
12300 (unless (and to-state (member to-state org-todo-keywords-1))
12301 (setq to-state (if (eq interpret 'type) org-last-state head)))
12302 (org-todo to-state)
12303 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12304 (org-entry-put nil "LAST_REPEAT" (format-time-string
12305 (org-time-stamp-format t t))))
12306 (when org-log-repeat
12307 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12308 (memq 'org-add-log-note post-command-hook))
12309 ;; OK, we are already setup for some record
12310 (if (eq org-log-repeat 'note)
12311 ;; make sure we take a note, not only a time stamp
12312 (setq org-log-note-how 'note))
12313 ;; Set up for taking a record
12314 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12315 org-last-state
12316 'findpos org-log-repeat)))
12317 (org-back-to-heading t)
12318 (org-add-planning-info nil nil 'closed)
12319 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12320 org-deadline-time-regexp "\\)\\|\\("
12321 org-ts-regexp "\\)"))
12322 (while (re-search-forward
12323 re (save-excursion (outline-next-heading) (point)) t)
12324 (setq type (if (match-end 1) org-scheduled-string
12325 (if (match-end 3) org-deadline-string "Plain:"))
12326 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12327 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12328 (setq n (string-to-number (match-string 2 ts))
12329 what (match-string 3 ts))
12330 (if (equal what "w") (setq n (* n 7) what "d"))
12331 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12332 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12333 ;; Preparation, see if we need to modify the start date for the change
12334 (when (match-end 1)
12335 (setq time (save-match-data (org-time-string-to-time ts)))
12336 (cond
12337 ((equal (match-string 1 ts) ".")
12338 ;; Shift starting date to today
12339 (org-timestamp-change
12340 (- (org-today) (time-to-days time))
12341 'day))
12342 ((equal (match-string 1 ts) "+")
12343 (let ((nshiftmax 10) (nshift 0))
12344 (while (or (= nshift 0)
12345 (<= (time-to-days time)
12346 (time-to-days (current-time))))
12347 (when (= (incf nshift) nshiftmax)
12348 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12349 (error "Abort")))
12350 (org-timestamp-change n (cdr (assoc what whata)))
12351 (org-at-timestamp-p t)
12352 (setq ts (match-string 1))
12353 (setq time (save-match-data (org-time-string-to-time ts)))))
12354 (org-timestamp-change (- n) (cdr (assoc what whata)))
12355 ;; rematch, so that we have everything in place for the real shift
12356 (org-at-timestamp-p t)
12357 (setq ts (match-string 1))
12358 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12359 (org-timestamp-change n (cdr (assoc what whata)))
12360 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12361 (setq org-log-post-message msg)
12362 (message "%s" msg))))
12364 (defun org-show-todo-tree (arg)
12365 "Make a compact tree which shows all headlines marked with TODO.
12366 The tree will show the lines where the regexp matches, and all higher
12367 headlines above the match.
12368 With a \\[universal-argument] prefix, prompt for a regexp to match.
12369 With a numeric prefix N, construct a sparse tree for the Nth element
12370 of `org-todo-keywords-1'."
12371 (interactive "P")
12372 (let ((case-fold-search nil)
12373 (kwd-re
12374 (cond ((null arg) org-not-done-regexp)
12375 ((equal arg '(4))
12376 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12377 (mapcar 'list org-todo-keywords-1))))
12378 (concat "\\("
12379 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12380 "\\)\\>")))
12381 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12382 (regexp-quote (nth (1- (prefix-numeric-value arg))
12383 org-todo-keywords-1)))
12384 (t (error "Invalid prefix argument: %s" arg)))))
12385 (message "%d TODO entries found"
12386 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12388 (defun org-deadline (&optional arg time)
12389 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12390 With one universal prefix argument, remove any deadline from the item.
12391 With two universal prefix arguments, prompt for a warning delay.
12392 With argument TIME, set the deadline at the corresponding date. TIME
12393 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12394 (interactive "P")
12395 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12396 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12397 'region-start-level 'region))
12398 org-loop-over-headlines-in-active-region)
12399 (org-map-entries
12400 `(org-deadline ',arg ,time)
12401 org-loop-over-headlines-in-active-region
12402 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12403 (let* ((old-date (org-entry-get nil "DEADLINE"))
12404 (repeater (and old-date
12405 (string-match
12406 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12407 old-date)
12408 (match-string 1 old-date))))
12409 (cond
12410 ((equal arg '(4))
12411 (when (and old-date org-log-redeadline)
12412 (org-add-log-setup 'deldeadline nil old-date 'findpos
12413 org-log-redeadline))
12414 (org-remove-timestamp-with-keyword org-deadline-string)
12415 (message "Item no longer has a deadline."))
12416 ((equal arg '(16))
12417 (save-excursion
12418 (if (re-search-forward
12419 org-deadline-time-regexp
12420 (save-excursion (outline-next-heading) (point)) t)
12421 (let* ((rpl0 (match-string 1))
12422 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12423 (replace-match
12424 (concat org-deadline-string
12425 " <" rpl
12426 (format " -%dd" (abs
12427 (- (time-to-days
12428 (save-match-data
12429 (org-read-date nil t nil "Warn starting from")))
12430 (time-to-days nil))))
12431 ">") t t))
12432 (user-error "No deadline information to update"))))
12434 (org-add-planning-info 'deadline time 'closed)
12435 (when (and old-date org-log-redeadline
12436 (not (equal old-date
12437 (substring org-last-inserted-timestamp 1 -1))))
12438 (org-add-log-setup 'redeadline nil old-date 'findpos
12439 org-log-redeadline))
12440 (when repeater
12441 (save-excursion
12442 (org-back-to-heading t)
12443 (when (re-search-forward (concat org-deadline-string " "
12444 org-last-inserted-timestamp)
12445 (save-excursion
12446 (outline-next-heading) (point)) t)
12447 (goto-char (1- (match-end 0)))
12448 (insert " " repeater)
12449 (setq org-last-inserted-timestamp
12450 (concat (substring org-last-inserted-timestamp 0 -1)
12451 " " repeater
12452 (substring org-last-inserted-timestamp -1))))))
12453 (message "Deadline on %s" org-last-inserted-timestamp))))))
12455 (defun org-schedule (&optional arg time)
12456 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12457 With one universal prefix argument, remove any scheduling date from the item.
12458 With two universal prefix arguments, prompt for a delay cookie.
12459 With argument TIME, scheduled at the corresponding date. TIME can
12460 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12461 (interactive "P")
12462 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12463 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12464 'region-start-level 'region))
12465 org-loop-over-headlines-in-active-region)
12466 (org-map-entries
12467 `(org-schedule ',arg ,time)
12468 org-loop-over-headlines-in-active-region
12469 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12470 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12471 (repeater (and old-date
12472 (string-match
12473 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12474 old-date)
12475 (match-string 1 old-date))))
12476 (cond
12477 ((equal arg '(4))
12478 (progn
12479 (when (and old-date org-log-reschedule)
12480 (org-add-log-setup 'delschedule nil old-date 'findpos
12481 org-log-reschedule))
12482 (org-remove-timestamp-with-keyword org-scheduled-string)
12483 (message "Item is no longer scheduled.")))
12484 ((equal arg '(16))
12485 (save-excursion
12486 (if (re-search-forward
12487 org-scheduled-time-regexp
12488 (save-excursion (outline-next-heading) (point)) t)
12489 (let* ((rpl0 (match-string 1))
12490 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12491 (replace-match
12492 (concat org-scheduled-string
12493 " <" rpl
12494 (format " -%dd" (abs
12495 (- (time-to-days
12496 (save-match-data
12497 (org-read-date nil t nil "Delay until")))
12498 (time-to-days nil))))
12499 ">") t t))
12500 (user-error "No scheduled information to update"))))
12502 (org-add-planning-info 'scheduled time 'closed)
12503 (when (and old-date org-log-reschedule
12504 (not (equal old-date
12505 (substring org-last-inserted-timestamp 1 -1))))
12506 (org-add-log-setup 'reschedule nil old-date 'findpos
12507 org-log-reschedule))
12508 (when repeater
12509 (save-excursion
12510 (org-back-to-heading t)
12511 (when (re-search-forward (concat org-scheduled-string " "
12512 org-last-inserted-timestamp)
12513 (save-excursion
12514 (outline-next-heading) (point)) t)
12515 (goto-char (1- (match-end 0)))
12516 (insert " " repeater)
12517 (setq org-last-inserted-timestamp
12518 (concat (substring org-last-inserted-timestamp 0 -1)
12519 " " repeater
12520 (substring org-last-inserted-timestamp -1))))))
12521 (message "Scheduled to %s" org-last-inserted-timestamp))))))
12523 (defun org-get-scheduled-time (pom &optional inherit)
12524 "Get the scheduled time as a time tuple, of a format suitable
12525 for calling org-schedule with, or if there is no scheduling,
12526 returns nil."
12527 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12528 (when time
12529 (apply 'encode-time (org-parse-time-string time)))))
12531 (defun org-get-deadline-time (pom &optional inherit)
12532 "Get the deadline as a time tuple, of a format suitable for
12533 calling org-deadline with, or if there is no scheduling, returns
12534 nil."
12535 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12536 (when time
12537 (apply 'encode-time (org-parse-time-string time)))))
12539 (defun org-remove-timestamp-with-keyword (keyword)
12540 "Remove all time stamps with KEYWORD in the current entry."
12541 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12542 beg)
12543 (save-excursion
12544 (org-back-to-heading t)
12545 (setq beg (point))
12546 (outline-next-heading)
12547 (while (re-search-backward re beg t)
12548 (replace-match "")
12549 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12550 (equal (char-before) ?\ ))
12551 (backward-delete-char 1)
12552 (if (string-match "^[ \t]*$" (buffer-substring
12553 (point-at-bol) (point-at-eol)))
12554 (delete-region (point-at-bol)
12555 (min (point-max) (1+ (point-at-eol))))))))))
12557 (defun org-add-planning-info (what &optional time &rest remove)
12558 "Insert new timestamp with keyword in the line directly after the headline.
12559 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12560 If non is given, the user is prompted for a date.
12561 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12562 be removed."
12563 (interactive)
12564 (let (org-time-was-given org-end-time-was-given ts
12565 end default-time default-input)
12567 (catch 'exit
12568 (when (and (memq what '(scheduled deadline))
12569 (or (not time)
12570 (and (stringp time)
12571 (string-match "^[-+]+[0-9]" time))))
12572 ;; Try to get a default date/time from existing timestamp
12573 (save-excursion
12574 (org-back-to-heading t)
12575 (setq end (save-excursion (outline-next-heading) (point)))
12576 (when (re-search-forward (if (eq what 'scheduled)
12577 org-scheduled-time-regexp
12578 org-deadline-time-regexp)
12579 end t)
12580 (setq ts (match-string 1)
12581 default-time
12582 (apply 'encode-time (org-parse-time-string ts))
12583 default-input (and ts (org-get-compact-tod ts))))))
12584 (when what
12585 (setq time
12586 (if (stringp time)
12587 ;; This is a string (relative or absolute), set proper date
12588 (apply 'encode-time
12589 (org-read-date-analyze
12590 time default-time (decode-time default-time)))
12591 ;; If necessary, get the time from the user
12592 (or time (org-read-date nil 'to-time nil nil
12593 default-time default-input)))))
12595 (when (and org-insert-labeled-timestamps-at-point
12596 (member what '(scheduled deadline)))
12597 (insert
12598 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12599 (org-insert-time-stamp time org-time-was-given
12600 nil nil nil (list org-end-time-was-given))
12601 (setq what nil))
12602 (save-excursion
12603 (save-restriction
12604 (let (col list elt ts buffer-invisibility-spec)
12605 (org-back-to-heading t)
12606 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12607 (goto-char (match-end 1))
12608 (setq col (current-column))
12609 (goto-char (match-end 0))
12610 (if (eobp) (insert "\n") (forward-char 1))
12611 (when (and (not what)
12612 (not (looking-at
12613 (concat "[ \t]*"
12614 org-keyword-time-not-clock-regexp))))
12615 ;; Nothing to add, nothing to remove...... :-)
12616 (throw 'exit nil))
12617 (if (and (not (looking-at org-outline-regexp))
12618 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12619 "[^\r\n]*"))
12620 (not (equal (match-string 1) org-clock-string)))
12621 (narrow-to-region (match-beginning 0) (match-end 0))
12622 (insert-before-markers "\n")
12623 (backward-char 1)
12624 (narrow-to-region (point) (point))
12625 (and org-adapt-indentation (org-indent-to-column col)))
12626 ;; Check if we have to remove something.
12627 (setq list (cons what remove))
12628 (while list
12629 (setq elt (pop list))
12630 (when (or (and (eq elt 'scheduled)
12631 (re-search-forward org-scheduled-time-regexp nil t))
12632 (and (eq elt 'deadline)
12633 (re-search-forward org-deadline-time-regexp nil t))
12634 (and (eq elt 'closed)
12635 (re-search-forward org-closed-time-regexp nil t)))
12636 (replace-match "")
12637 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12638 (and (looking-at "[ \t]+") (replace-match ""))
12639 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12640 (when what
12641 (insert
12642 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12643 (cond ((eq what 'scheduled) org-scheduled-string)
12644 ((eq what 'deadline) org-deadline-string)
12645 ((eq what 'closed) org-closed-string))
12646 " ")
12647 (setq ts (org-insert-time-stamp
12648 time
12649 (or org-time-was-given
12650 (and (eq what 'closed) org-log-done-with-time))
12651 (eq what 'closed)
12652 nil nil (list org-end-time-was-given)))
12653 (insert
12654 (if (not (or (bolp) (eq (char-before) ?\ )
12655 (memq (char-after) '(32 10))
12656 (eobp))) " " ""))
12657 (end-of-line 1))
12658 (goto-char (point-min))
12659 (widen)
12660 (if (and (looking-at "[ \t]*\n")
12661 (equal (char-before) ?\n))
12662 (delete-region (1- (point)) (point-at-eol)))
12663 ts))))))
12665 (defvar org-log-note-marker (make-marker))
12666 (defvar org-log-note-purpose nil)
12667 (defvar org-log-note-state nil)
12668 (defvar org-log-note-previous-state nil)
12669 (defvar org-log-note-how nil)
12670 (defvar org-log-note-extra nil)
12671 (defvar org-log-note-window-configuration nil)
12672 (defvar org-log-note-return-to (make-marker))
12673 (defvar org-log-note-effective-time nil
12674 "Remembered current time so that dynamically scoped
12675 `org-extend-today-until' affects tha timestamps in state change
12676 log")
12678 (defvar org-log-post-message nil
12679 "Message to be displayed after a log note has been stored.
12680 The auto-repeater uses this.")
12682 (defun org-add-note ()
12683 "Add a note to the current entry.
12684 This is done in the same way as adding a state change note."
12685 (interactive)
12686 (org-add-log-setup 'note nil nil 'findpos nil))
12688 (defvar org-property-end-re)
12689 (defun org-add-log-setup (&optional purpose state prev-state
12690 findpos how extra)
12691 "Set up the post command hook to take a note.
12692 If this is about to TODO state change, the new state is expected in STATE.
12693 When FINDPOS is non-nil, find the correct position for the note in
12694 the current entry. If not, assume that it can be inserted at point.
12695 HOW is an indicator what kind of note should be created.
12696 EXTRA is additional text that will be inserted into the notes buffer."
12697 (let* ((org-log-into-drawer (org-log-into-drawer))
12698 (drawer (cond ((stringp org-log-into-drawer)
12699 org-log-into-drawer)
12700 (org-log-into-drawer "LOGBOOK"))))
12701 (save-restriction
12702 (save-excursion
12703 (when findpos
12704 (org-back-to-heading t)
12705 (narrow-to-region (point) (save-excursion
12706 (outline-next-heading) (point)))
12707 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12708 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12709 "[^\r\n]*\\)?"))
12710 (goto-char (match-end 0))
12711 (cond
12712 (drawer
12713 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12714 nil t)
12715 (progn
12716 (goto-char (match-end 0))
12717 (or org-log-states-order-reversed
12718 (and (re-search-forward org-property-end-re nil t)
12719 (goto-char (1- (match-beginning 0))))))
12720 (insert "\n:" drawer ":\n:END:")
12721 (beginning-of-line 0)
12722 (org-indent-line)
12723 (beginning-of-line 2)
12724 (org-indent-line)
12725 (end-of-line 0)))
12726 ((and org-log-state-notes-insert-after-drawers
12727 (save-excursion
12728 (forward-line) (looking-at org-drawer-regexp)))
12729 (forward-line)
12730 (while (looking-at org-drawer-regexp)
12731 (goto-char (match-end 0))
12732 (re-search-forward org-property-end-re (point-max) t)
12733 (forward-line))
12734 (forward-line -1)))
12735 (unless org-log-states-order-reversed
12736 (and (= (char-after) ?\n) (forward-char 1))
12737 (org-skip-over-state-notes)
12738 (skip-chars-backward " \t\n\r")))
12739 (move-marker org-log-note-marker (point))
12740 (setq org-log-note-purpose purpose
12741 org-log-note-state state
12742 org-log-note-previous-state prev-state
12743 org-log-note-how how
12744 org-log-note-extra extra
12745 org-log-note-effective-time (org-current-effective-time))
12746 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12748 (defun org-skip-over-state-notes ()
12749 "Skip past the list of State notes in an entry."
12750 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12751 (when (ignore-errors (goto-char (org-in-item-p)))
12752 (let* ((struct (org-list-struct))
12753 (prevs (org-list-prevs-alist struct)))
12754 (while (looking-at "[ \t]*- State")
12755 (goto-char (or (org-list-get-next-item (point) struct prevs)
12756 (org-list-get-item-end (point) struct)))))))
12758 (defun org-add-log-note (&optional purpose)
12759 "Pop up a window for taking a note, and add this note later at point."
12760 (remove-hook 'post-command-hook 'org-add-log-note)
12761 (setq org-log-note-window-configuration (current-window-configuration))
12762 (delete-other-windows)
12763 (move-marker org-log-note-return-to (point))
12764 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12765 (goto-char org-log-note-marker)
12766 (org-switch-to-buffer-other-window "*Org Note*")
12767 (erase-buffer)
12768 (if (memq org-log-note-how '(time state))
12769 (let (current-prefix-arg) (org-store-log-note))
12770 (let ((org-inhibit-startup t)) (org-mode))
12771 (insert (format "# Insert note for %s.
12772 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12773 (cond
12774 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12775 ((eq org-log-note-purpose 'done) "closed todo item")
12776 ((eq org-log-note-purpose 'state)
12777 (format "state change from \"%s\" to \"%s\""
12778 (or org-log-note-previous-state "")
12779 (or org-log-note-state "")))
12780 ((eq org-log-note-purpose 'reschedule)
12781 "rescheduling")
12782 ((eq org-log-note-purpose 'delschedule)
12783 "no longer scheduled")
12784 ((eq org-log-note-purpose 'redeadline)
12785 "changing deadline")
12786 ((eq org-log-note-purpose 'deldeadline)
12787 "removing deadline")
12788 ((eq org-log-note-purpose 'refile)
12789 "refiling")
12790 ((eq org-log-note-purpose 'note)
12791 "this entry")
12792 (t (error "This should not happen")))))
12793 (if org-log-note-extra (insert org-log-note-extra))
12794 (org-set-local 'org-finish-function 'org-store-log-note)
12795 (run-hooks 'org-log-buffer-setup-hook)))
12797 (defvar org-note-abort nil) ; dynamically scoped
12798 (defun org-store-log-note ()
12799 "Finish taking a log note, and insert it to where it belongs."
12800 (let ((txt (buffer-string)))
12801 (kill-buffer (current-buffer))
12802 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
12803 lines ind bul)
12804 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12805 (setq txt (replace-match "" t t txt)))
12806 (if (string-match "\\s-+\\'" txt)
12807 (setq txt (replace-match "" t t txt)))
12808 (setq lines (org-split-string txt "\n"))
12809 (when (and note (string-match "\\S-" note))
12810 (setq note
12811 (org-replace-escapes
12812 note
12813 (list (cons "%u" (user-login-name))
12814 (cons "%U" user-full-name)
12815 (cons "%t" (format-time-string
12816 (org-time-stamp-format 'long 'inactive)
12817 org-log-note-effective-time))
12818 (cons "%T" (format-time-string
12819 (org-time-stamp-format 'long nil)
12820 org-log-note-effective-time))
12821 (cons "%d" (format-time-string
12822 (org-time-stamp-format nil 'inactive)
12823 org-log-note-effective-time))
12824 (cons "%D" (format-time-string
12825 (org-time-stamp-format nil nil)
12826 org-log-note-effective-time))
12827 (cons "%s" (if org-log-note-state
12828 (concat "\"" org-log-note-state "\"")
12829 ""))
12830 (cons "%S" (if org-log-note-previous-state
12831 (concat "\"" org-log-note-previous-state "\"")
12832 "\"\"")))))
12833 (if lines (setq note (concat note " \\\\")))
12834 (push note lines))
12835 (when (or current-prefix-arg org-note-abort)
12836 (when org-log-into-drawer
12837 (org-remove-empty-drawer-at
12838 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12839 org-log-note-marker))
12840 (setq lines nil))
12841 (when lines
12842 (with-current-buffer (marker-buffer org-log-note-marker)
12843 (save-excursion
12844 (goto-char org-log-note-marker)
12845 (move-marker org-log-note-marker nil)
12846 (end-of-line 1)
12847 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12848 (setq ind (save-excursion
12849 (if (ignore-errors (goto-char (org-in-item-p)))
12850 (let ((struct (org-list-struct)))
12851 (org-list-get-ind
12852 (org-list-get-top-point struct) struct))
12853 (skip-chars-backward " \r\t\n")
12854 (cond
12855 ((and (org-at-heading-p)
12856 org-adapt-indentation)
12857 (1+ (org-current-level)))
12858 ((org-at-heading-p) 0)
12859 (t (org-get-indentation))))))
12860 (setq bul (org-list-bullet-string "-"))
12861 (org-indent-line-to ind)
12862 (insert bul (pop lines))
12863 (let ((ind-body (+ (length bul) ind)))
12864 (while lines
12865 (insert "\n")
12866 (org-indent-line-to ind-body)
12867 (insert (pop lines))))
12868 (message "Note stored")
12869 (org-back-to-heading t)
12870 (org-cycle-hide-drawers 'children))))))
12871 (set-window-configuration org-log-note-window-configuration)
12872 (with-current-buffer (marker-buffer org-log-note-return-to)
12873 (goto-char org-log-note-return-to))
12874 (move-marker org-log-note-return-to nil)
12875 (and org-log-post-message (message "%s" org-log-post-message)))
12877 (defun org-remove-empty-drawer-at (drawer pos)
12878 "Remove an empty drawer DRAWER at position POS.
12879 POS may also be a marker."
12880 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12881 (save-excursion
12882 (save-restriction
12883 (widen)
12884 (goto-char pos)
12885 (if (org-in-regexp
12886 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12887 (replace-match ""))))))
12889 (defvar org-ts-type nil)
12890 (defun org-sparse-tree (&optional arg type)
12891 "Create a sparse tree, prompt for the details.
12892 This command can create sparse trees. You first need to select the type
12893 of match used to create the tree:
12895 t Show all TODO entries.
12896 T Show entries with a specific TODO keyword.
12897 m Show entries selected by a tags/property match.
12898 p Enter a property name and its value (both with completion on existing
12899 names/values) and show entries with that property.
12900 r Show entries matching a regular expression (`/' can be used as well).
12901 b Show deadlines and scheduled items before a date.
12902 a Show deadlines and scheduled items after a date.
12903 d Show deadlines due within `org-deadline-warning-days'.
12904 D Show deadlines and scheduled items between a date range."
12905 (interactive "P")
12906 (let (ans kwd value ts-type)
12907 (setq type (or type org-sparse-tree-default-date-type))
12908 (setq org-ts-type type)
12909 (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"
12910 (cond ((eq type 'all) "all timestamps")
12911 ((eq type 'scheduled) "only scheduled")
12912 ((eq type 'deadline) "only deadline")
12913 ((eq type 'active) "only active timestamps")
12914 ((eq type 'inactive) "only inactive timestamps")
12915 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12916 (t "scheduled/deadline")))
12917 (setq ans (read-char-exclusive))
12918 (cond
12919 ((equal ans ?c)
12920 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12921 ((equal ans ?d)
12922 (call-interactively 'org-check-deadlines))
12923 ((equal ans ?b)
12924 (call-interactively 'org-check-before-date))
12925 ((equal ans ?a)
12926 (call-interactively 'org-check-after-date))
12927 ((equal ans ?D)
12928 (call-interactively 'org-check-dates-range))
12929 ((equal ans ?t)
12930 (call-interactively 'org-show-todo-tree))
12931 ((equal ans ?T)
12932 (org-show-todo-tree '(4)))
12933 ((member ans '(?T ?m))
12934 (call-interactively 'org-match-sparse-tree))
12935 ((member ans '(?p ?P))
12936 (setq kwd (org-icompleting-read "Property: "
12937 (mapcar 'list (org-buffer-property-keys))))
12938 (setq value (org-icompleting-read "Value: "
12939 (mapcar 'list (org-property-values kwd))))
12940 (unless (string-match "\\`{.*}\\'" value)
12941 (setq value (concat "\"" value "\"")))
12942 (org-match-sparse-tree arg (concat kwd "=" value)))
12943 ((member ans '(?r ?R ?/))
12944 (call-interactively 'org-occur))
12945 (t (error "No such sparse tree command \"%c\"" ans)))))
12947 (defvar org-occur-highlights nil
12948 "List of overlays used for occur matches.")
12949 (make-variable-buffer-local 'org-occur-highlights)
12950 (defvar org-occur-parameters nil
12951 "Parameters of the active org-occur calls.
12952 This is a list, each call to org-occur pushes as cons cell,
12953 containing the regular expression and the callback, onto the list.
12954 The list can contain several entries if `org-occur' has been called
12955 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12956 will only contain one set of parameters. When the highlights are
12957 removed (for example with `C-c C-c', or with the next edit (depending
12958 on `org-remove-highlights-with-change'), this variable is emptied
12959 as well.")
12960 (make-variable-buffer-local 'org-occur-parameters)
12962 (defun org-occur (regexp &optional keep-previous callback)
12963 "Make a compact tree which shows all matches of REGEXP.
12964 The tree will show the lines where the regexp matches, and all higher
12965 headlines above the match. It will also show the heading after the match,
12966 to make sure editing the matching entry is easy.
12967 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12968 call to `org-occur' will be kept, to allow stacking of calls to this
12969 command.
12970 If CALLBACK is non-nil, it is a function which is called to confirm
12971 that the match should indeed be shown."
12972 (interactive "sRegexp: \nP")
12973 (when (equal regexp "")
12974 (error "Regexp cannot be empty"))
12975 (unless keep-previous
12976 (org-remove-occur-highlights nil nil t))
12977 (push (cons regexp callback) org-occur-parameters)
12978 (let ((cnt 0))
12979 (save-excursion
12980 (goto-char (point-min))
12981 (if (or (not keep-previous) ; do not want to keep
12982 (not org-occur-highlights)) ; no previous matches
12983 ;; hide everything
12984 (org-overview))
12985 (while (re-search-forward regexp nil t)
12986 (when (or (not callback)
12987 (save-match-data (funcall callback)))
12988 (setq cnt (1+ cnt))
12989 (when org-highlight-sparse-tree-matches
12990 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12991 (org-show-context 'occur-tree))))
12992 (when org-remove-highlights-with-change
12993 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12994 nil 'local))
12995 (unless org-sparse-tree-open-archived-trees
12996 (org-hide-archived-subtrees (point-min) (point-max)))
12997 (run-hooks 'org-occur-hook)
12998 (if (org-called-interactively-p 'interactive)
12999 (message "%d match(es) for regexp %s" cnt regexp))
13000 cnt))
13002 (defun org-occur-next-match (&optional n reset)
13003 "Function for `next-error-function' to find sparse tree matches.
13004 N is the number of matches to move, when negative move backwards.
13005 RESET is entirely ignored - this function always goes back to the
13006 starting point when no match is found."
13007 (let* ((limit (if (< n 0) (point-min) (point-max)))
13008 (search-func (if (< n 0)
13009 'previous-single-char-property-change
13010 'next-single-char-property-change))
13011 (n (abs n))
13012 (pos (point))
13014 (catch 'exit
13015 (while (setq p1 (funcall search-func (point) 'org-type))
13016 (when (equal p1 limit)
13017 (goto-char pos)
13018 (error "No more matches"))
13019 (when (equal (get-char-property p1 'org-type) 'org-occur)
13020 (setq n (1- n))
13021 (when (= n 0)
13022 (goto-char p1)
13023 (throw 'exit (point))))
13024 (goto-char p1))
13025 (goto-char p1)
13026 (error "No more matches"))))
13028 (defun org-show-context (&optional key)
13029 "Make sure point and context are visible.
13030 How much context is shown depends upon the variables
13031 `org-show-hierarchy-above', `org-show-following-heading',
13032 `org-show-entry-below' and `org-show-siblings'."
13033 (let ((heading-p (org-at-heading-p t))
13034 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13035 (following-p (org-get-alist-option org-show-following-heading key))
13036 (entry-p (org-get-alist-option org-show-entry-below key))
13037 (siblings-p (org-get-alist-option org-show-siblings key)))
13038 (catch 'exit
13039 ;; Show heading or entry text
13040 (if (and heading-p (not entry-p))
13041 (org-flag-heading nil) ; only show the heading
13042 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13043 (org-show-hidden-entry))) ; show entire entry
13044 (when following-p
13045 ;; Show next sibling, or heading below text
13046 (save-excursion
13047 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13048 (org-flag-heading nil))))
13049 (when siblings-p (org-show-siblings))
13050 (when hierarchy-p
13051 ;; show all higher headings, possibly with siblings
13052 (save-excursion
13053 (while (and (condition-case nil
13054 (progn (org-up-heading-all 1) t)
13055 (error nil))
13056 (not (bobp)))
13057 (org-flag-heading nil)
13058 (when siblings-p (org-show-siblings))))))))
13060 (defvar org-reveal-start-hook nil
13061 "Hook run before revealing a location.")
13063 (defun org-reveal (&optional siblings)
13064 "Show current entry, hierarchy above it, and the following headline.
13065 This can be used to show a consistent set of context around locations
13066 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13067 not t for the search context.
13069 With optional argument SIBLINGS, on each level of the hierarchy all
13070 siblings are shown. This repairs the tree structure to what it would
13071 look like when opened with hierarchical calls to `org-cycle'.
13072 With double optional argument \\[universal-argument] \\[universal-argument], \
13073 go to the parent and show the
13074 entire tree."
13075 (interactive "P")
13076 (run-hooks 'org-reveal-start-hook)
13077 (let ((org-show-hierarchy-above t)
13078 (org-show-following-heading t)
13079 (org-show-siblings (if siblings t org-show-siblings)))
13080 (org-show-context nil))
13081 (when (equal siblings '(16))
13082 (save-excursion
13083 (when (org-up-heading-safe)
13084 (org-show-subtree)
13085 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13087 (defun org-highlight-new-match (beg end)
13088 "Highlight from BEG to END and mark the highlight is an occur headline."
13089 (let ((ov (make-overlay beg end)))
13090 (overlay-put ov 'face 'secondary-selection)
13091 (overlay-put ov 'org-type 'org-occur)
13092 (push ov org-occur-highlights)))
13094 (defun org-remove-occur-highlights (&optional beg end noremove)
13095 "Remove the occur highlights from the buffer.
13096 BEG and END are ignored. If NOREMOVE is nil, remove this function
13097 from the `before-change-functions' in the current buffer."
13098 (interactive)
13099 (unless org-inhibit-highlight-removal
13100 (mapc 'delete-overlay org-occur-highlights)
13101 (setq org-occur-highlights nil)
13102 (setq org-occur-parameters nil)
13103 (unless noremove
13104 (remove-hook 'before-change-functions
13105 'org-remove-occur-highlights 'local))))
13107 ;;;; Priorities
13109 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13110 "Regular expression matching the priority indicator.")
13112 (defvar org-remove-priority-next-time nil)
13114 (defun org-priority-up ()
13115 "Increase the priority of the current item."
13116 (interactive)
13117 (org-priority 'up))
13119 (defun org-priority-down ()
13120 "Decrease the priority of the current item."
13121 (interactive)
13122 (org-priority 'down))
13124 (defun org-priority (&optional action show)
13125 "Change the priority of an item.
13126 ACTION can be `set', `up', `down', or a character."
13127 (interactive "P")
13128 (if (equal action '(4))
13129 (org-show-priority)
13130 (unless org-enable-priority-commands
13131 (error "Priority commands are disabled"))
13132 (setq action (or action 'set))
13133 (let (current new news have remove)
13134 (save-excursion
13135 (org-back-to-heading t)
13136 (if (looking-at org-priority-regexp)
13137 (setq current (string-to-char (match-string 2))
13138 have t))
13139 (cond
13140 ((eq action 'remove)
13141 (setq remove t new ?\ ))
13142 ((or (eq action 'set)
13143 (if (featurep 'xemacs) (characterp action) (integerp action)))
13144 (if (not (eq action 'set))
13145 (setq new action)
13146 (message "Priority %c-%c, SPC to remove: "
13147 org-highest-priority org-lowest-priority)
13148 (save-match-data
13149 (setq new (read-char-exclusive))))
13150 (if (and (= (upcase org-highest-priority) org-highest-priority)
13151 (= (upcase org-lowest-priority) org-lowest-priority))
13152 (setq new (upcase new)))
13153 (cond ((equal new ?\ ) (setq remove t))
13154 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13155 (error "Priority must be between `%c' and `%c'"
13156 org-highest-priority org-lowest-priority))))
13157 ((eq action 'up)
13158 (setq new (if have
13159 (1- current) ; normal cycling
13160 ;; last priority was empty
13161 (if (eq last-command this-command)
13162 org-lowest-priority ; wrap around empty to lowest
13163 ;; default
13164 (if org-priority-start-cycle-with-default
13165 org-default-priority
13166 (1- org-default-priority))))))
13167 ((eq action 'down)
13168 (setq new (if have
13169 (1+ current) ; normal cycling
13170 ;; last priority was empty
13171 (if (eq last-command this-command)
13172 org-highest-priority ; wrap around empty to highest
13173 ;; default
13174 (if org-priority-start-cycle-with-default
13175 org-default-priority
13176 (1+ org-default-priority))))))
13177 (t (error "Invalid action")))
13178 (if (or (< (upcase new) org-highest-priority)
13179 (> (upcase new) org-lowest-priority))
13180 (if (and (memq action '(up down))
13181 (not have) (not (eq last-command this-command)))
13182 ;; `new' is from default priority
13183 (error
13184 "The default can not be set, see `org-default-priority' why")
13185 ;; normal cycling: `new' is beyond highest/lowest priority
13186 ;; and is wrapped around to the empty priority
13187 (setq remove t)))
13188 (setq news (format "%c" new))
13189 (if have
13190 (if remove
13191 (replace-match "" t t nil 1)
13192 (replace-match news t t nil 2))
13193 (if remove
13194 (error "No priority cookie found in line")
13195 (let ((case-fold-search nil))
13196 (looking-at org-todo-line-regexp))
13197 (if (match-end 2)
13198 (progn
13199 (goto-char (match-end 2))
13200 (insert " [#" news "]"))
13201 (goto-char (match-beginning 3))
13202 (insert "[#" news "] "))))
13203 (org-preserve-lc (org-set-tags nil 'align)))
13204 (if remove
13205 (message "Priority removed")
13206 (message "Priority of current item set to %s" news)))))
13208 (defun org-show-priority ()
13209 "Show the priority of the current item.
13210 This priority is composed of the main priority given with the [#A] cookies,
13211 and by additional input from the age of a schedules or deadline entry."
13212 (interactive)
13213 (let ((pri (if (eq major-mode 'org-agenda-mode)
13214 (org-get-at-bol 'priority)
13215 (save-excursion
13216 (save-match-data
13217 (beginning-of-line)
13218 (and (looking-at org-heading-regexp)
13219 (org-get-priority (match-string 0))))))))
13220 (message "Priority is %d" (if pri pri -1000))))
13222 (defun org-get-priority (s)
13223 "Find priority cookie and return priority."
13224 (save-match-data
13225 (if (functionp org-get-priority-function)
13226 (funcall org-get-priority-function)
13227 (if (not (string-match org-priority-regexp s))
13228 (* 1000 (- org-lowest-priority org-default-priority))
13229 (* 1000 (- org-lowest-priority
13230 (string-to-char (match-string 2 s))))))))
13232 ;;;; Tags
13234 (defvar org-agenda-archives-mode)
13235 (defvar org-map-continue-from nil
13236 "Position from where mapping should continue.
13237 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13239 (defvar org-scanner-tags nil
13240 "The current tag list while the tags scanner is running.")
13241 (defvar org-trust-scanner-tags nil
13242 "Should `org-get-tags-at' use the tags for the scanner.
13243 This is for internal dynamical scoping only.
13244 When this is non-nil, the function `org-get-tags-at' will return the value
13245 of `org-scanner-tags' instead of building the list by itself. This
13246 can lead to large speed-ups when the tags scanner is used in a file with
13247 many entries, and when the list of tags is retrieved, for example to
13248 obtain a list of properties. Building the tags list for each entry in such
13249 a file becomes an N^2 operation - but with this variable set, it scales
13250 as N.")
13252 (defun org-scan-tags (action matcher todo-only &optional start-level)
13253 "Scan headline tags with inheritance and produce output ACTION.
13255 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13256 or `agenda' to produce an entry list for an agenda view. It can also be
13257 a Lisp form or a function that should be called at each matched headline, in
13258 this case the return value is a list of all return values from these calls.
13260 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13261 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13262 only lines with a not-done TODO keyword are included in the output.
13263 This should be the same variable that was scoped into
13264 and set by `org-make-tags-matcher' when it constructed MATCHER.
13266 START-LEVEL can be a string with asterisks, reducing the scope to
13267 headlines matching this string."
13268 (require 'org-agenda)
13269 (let* ((re (concat "^"
13270 (if start-level
13271 ;; Get the correct level to match
13272 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13273 org-outline-regexp)
13274 " *\\(\\<\\("
13275 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13276 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13277 (props (list 'face 'default
13278 'done-face 'org-agenda-done
13279 'undone-face 'default
13280 'mouse-face 'highlight
13281 'org-not-done-regexp org-not-done-regexp
13282 'org-todo-regexp org-todo-regexp
13283 'org-complex-heading-regexp org-complex-heading-regexp
13284 'help-echo
13285 (format "mouse-2 or RET jump to org file %s"
13286 (abbreviate-file-name
13287 (or (buffer-file-name (buffer-base-buffer))
13288 (buffer-name (buffer-base-buffer)))))))
13289 (case-fold-search nil)
13290 (org-map-continue-from nil)
13291 lspos tags tags-list
13292 (tags-alist (list (cons 0 org-file-tags)))
13293 (llast 0) rtn rtn1 level category i txt
13294 todo marker entry priority)
13295 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13296 (setq action (list 'lambda nil action)))
13297 (save-excursion
13298 (goto-char (point-min))
13299 (when (eq action 'sparse-tree)
13300 (org-overview)
13301 (org-remove-occur-highlights))
13302 (while (re-search-forward re nil t)
13303 (setq org-map-continue-from nil)
13304 (catch :skip
13305 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13306 tags (if (match-end 4) (org-match-string-no-properties 4)))
13307 (goto-char (setq lspos (match-beginning 0)))
13308 (setq level (org-reduced-level (org-outline-level))
13309 category (org-get-category))
13310 (setq i llast llast level)
13311 ;; remove tag lists from same and sublevels
13312 (while (>= i level)
13313 (when (setq entry (assoc i tags-alist))
13314 (setq tags-alist (delete entry tags-alist)))
13315 (setq i (1- i)))
13316 ;; add the next tags
13317 (when tags
13318 (setq tags (org-split-string tags ":")
13319 tags-alist
13320 (cons (cons level tags) tags-alist)))
13321 ;; compile tags for current headline
13322 (setq tags-list
13323 (if org-use-tag-inheritance
13324 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13325 tags)
13326 org-scanner-tags tags-list)
13327 (when org-use-tag-inheritance
13328 (setcdr (car tags-alist)
13329 (mapcar (lambda (x)
13330 (setq x (copy-sequence x))
13331 (org-add-prop-inherited x))
13332 (cdar tags-alist))))
13333 (when (and tags org-use-tag-inheritance
13334 (or (not (eq t org-use-tag-inheritance))
13335 org-tags-exclude-from-inheritance))
13336 ;; selective inheritance, remove uninherited ones
13337 (setcdr (car tags-alist)
13338 (org-remove-uninherited-tags (cdar tags-alist))))
13339 (when (and
13341 ;; eval matcher only when the todo condition is OK
13342 (and (or (not todo-only) (member todo org-not-done-keywords))
13343 (let ((case-fold-search t) (org-trust-scanner-tags t))
13344 (eval matcher)))
13346 ;; Call the skipper, but return t if it does not skip,
13347 ;; so that the `and' form continues evaluating
13348 (progn
13349 (unless (eq action 'sparse-tree) (org-agenda-skip))
13352 ;; Check if timestamps are deselecting this entry
13353 (or (not todo-only)
13354 (and (member todo org-not-done-keywords)
13355 (or (not org-agenda-tags-todo-honor-ignore-options)
13356 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13358 ;; select this headline
13359 (cond
13360 ((eq action 'sparse-tree)
13361 (and org-highlight-sparse-tree-matches
13362 (org-get-heading) (match-end 0)
13363 (org-highlight-new-match
13364 (match-beginning 1) (match-end 1)))
13365 (org-show-context 'tags-tree))
13366 ((eq action 'agenda)
13367 (setq txt (org-agenda-format-item
13369 (concat
13370 (if (eq org-tags-match-list-sublevels 'indented)
13371 (make-string (1- level) ?.) "")
13372 (org-get-heading))
13373 level category
13374 tags-list)
13375 priority (org-get-priority txt))
13376 (goto-char lspos)
13377 (setq marker (org-agenda-new-marker))
13378 (org-add-props txt props
13379 'org-marker marker 'org-hd-marker marker 'org-category category
13380 'todo-state todo
13381 'priority priority 'type "tagsmatch")
13382 (push txt rtn))
13383 ((functionp action)
13384 (setq org-map-continue-from nil)
13385 (save-excursion
13386 (setq rtn1 (funcall action))
13387 (push rtn1 rtn)))
13388 (t (error "Invalid action")))
13390 ;; if we are to skip sublevels, jump to end of subtree
13391 (unless org-tags-match-list-sublevels
13392 (org-end-of-subtree t)
13393 (backward-char 1))))
13394 ;; Get the correct position from where to continue
13395 (if org-map-continue-from
13396 (goto-char org-map-continue-from)
13397 (and (= (point) lspos) (end-of-line 1)))))
13398 (when (and (eq action 'sparse-tree)
13399 (not org-sparse-tree-open-archived-trees))
13400 (org-hide-archived-subtrees (point-min) (point-max)))
13401 (nreverse rtn)))
13403 (defun org-remove-uninherited-tags (tags)
13404 "Remove all tags that are not inherited from the list TAGS."
13405 (cond
13406 ((eq org-use-tag-inheritance t)
13407 (if org-tags-exclude-from-inheritance
13408 (org-delete-all org-tags-exclude-from-inheritance tags)
13409 tags))
13410 ((not org-use-tag-inheritance) nil)
13411 ((stringp org-use-tag-inheritance)
13412 (delq nil (mapcar
13413 (lambda (x)
13414 (if (and (string-match org-use-tag-inheritance x)
13415 (not (member x org-tags-exclude-from-inheritance)))
13416 x nil))
13417 tags)))
13418 ((listp org-use-tag-inheritance)
13419 (delq nil (mapcar
13420 (lambda (x)
13421 (if (member x org-use-tag-inheritance) x nil))
13422 tags)))))
13424 (defun org-match-sparse-tree (&optional todo-only match)
13425 "Create a sparse tree according to tags string MATCH.
13426 MATCH can contain positive and negative selection of tags, like
13427 \"+WORK+URGENT-WITHBOSS\".
13428 If optional argument TODO-ONLY is non-nil, only select lines that are
13429 also TODO lines."
13430 (interactive "P")
13431 (org-agenda-prepare-buffers (list (current-buffer)))
13432 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13434 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13436 (defvar org-cached-props nil)
13437 (defun org-cached-entry-get (pom property)
13438 (if (or (eq t org-use-property-inheritance)
13439 (and (stringp org-use-property-inheritance)
13440 (string-match org-use-property-inheritance property))
13441 (and (listp org-use-property-inheritance)
13442 (member property org-use-property-inheritance)))
13443 ;; Caching is not possible, check it directly
13444 (org-entry-get pom property 'inherit)
13445 ;; Get all properties, so that we can do complicated checks easily
13446 (cdr (assoc property (or org-cached-props
13447 (setq org-cached-props
13448 (org-entry-properties pom)))))))
13450 (defun org-global-tags-completion-table (&optional files)
13451 "Return the list of all tags in all agenda buffer/files.
13452 Optional FILES argument is a list of files which can be used
13453 instead of the agenda files."
13454 (save-excursion
13455 (org-uniquify
13456 (delq nil
13457 (apply 'append
13458 (mapcar
13459 (lambda (file)
13460 (set-buffer (find-file-noselect file))
13461 (append (org-get-buffer-tags)
13462 (mapcar (lambda (x) (if (stringp (car-safe x))
13463 (list (car-safe x)) nil))
13464 org-tag-alist)))
13465 (if (and files (car files))
13466 files
13467 (org-agenda-files))))))))
13469 (defun org-make-tags-matcher (match)
13470 "Create the TAGS/TODO matcher form for the selection string MATCH.
13472 The variable `todo-only' is scoped dynamically into this function.
13473 It will be set to t if the matcher restricts matching to TODO entries,
13474 otherwise will not be touched.
13476 Returns a cons of the selection string MATCH and the constructed
13477 lisp form implementing the matcher. The matcher is to be evaluated
13478 at an Org entry, with point on the headline, and returns t if the
13479 entry matches the selection string MATCH. The returned lisp form
13480 references two variables with information about the entry, which
13481 must be bound around the form's evaluation: todo, the TODO keyword
13482 at the entry (or nil of none); and tags-list, the list of all tags
13483 at the entry including inherited ones. Additionally, the category
13484 of the entry (if any) must be specified as the text property
13485 'org-category on the headline.
13487 See also `org-scan-tags'.
13489 (declare (special todo-only))
13490 (unless (boundp 'todo-only)
13491 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13492 (unless match
13493 ;; Get a new match request, with completion
13494 (let ((org-last-tags-completion-table
13495 (org-global-tags-completion-table)))
13496 (setq match (org-completing-read-no-i
13497 "Match: " 'org-tags-completion-function nil nil nil
13498 'org-tags-history))))
13500 ;; Parse the string and create a lisp form
13501 (let ((match0 match)
13502 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13503 minus tag mm
13504 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13505 orterms term orlist re-p str-p level-p level-op time-p
13506 prop-p pn pv po gv rest)
13507 (if (string-match "/+" match)
13508 ;; match contains also a todo-matching request
13509 (progn
13510 (setq tagsmatch (substring match 0 (match-beginning 0))
13511 todomatch (substring match (match-end 0)))
13512 (if (string-match "^!" todomatch)
13513 (setq todo-only t todomatch (substring todomatch 1)))
13514 (if (string-match "^\\s-*$" todomatch)
13515 (setq todomatch nil)))
13516 ;; only matching tags
13517 (setq tagsmatch match todomatch nil))
13519 ;; Make the tags matcher
13520 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13521 (setq tagsmatcher t)
13522 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13523 (while (setq term (pop orterms))
13524 (while (and (equal (substring term -1) "\\") orterms)
13525 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13526 (while (string-match re term)
13527 (setq rest (substring term (match-end 0))
13528 minus (and (match-end 1)
13529 (equal (match-string 1 term) "-"))
13530 tag (save-match-data (replace-regexp-in-string
13531 "\\\\-" "-"
13532 (match-string 2 term)))
13533 re-p (equal (string-to-char tag) ?{)
13534 level-p (match-end 4)
13535 prop-p (match-end 5)
13536 mm (cond
13537 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13538 (level-p
13539 (setq level-op (org-op-to-function (match-string 3 term)))
13540 `(,level-op level ,(string-to-number
13541 (match-string 4 term))))
13542 (prop-p
13543 (setq pn (match-string 5 term)
13544 po (match-string 6 term)
13545 pv (match-string 7 term)
13546 re-p (equal (string-to-char pv) ?{)
13547 str-p (equal (string-to-char pv) ?\")
13548 time-p (save-match-data
13549 (string-match "^\"[[<].*[]>]\"$" pv))
13550 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13551 (if time-p (setq pv (org-matcher-time pv)))
13552 (setq po (org-op-to-function po (if time-p 'time str-p)))
13553 (cond
13554 ((equal pn "CATEGORY")
13555 (setq gv '(get-text-property (point) 'org-category)))
13556 ((equal pn "TODO")
13557 (setq gv 'todo))
13559 (setq gv `(org-cached-entry-get nil ,pn))))
13560 (if re-p
13561 (if (eq po 'org<>)
13562 `(not (string-match ,pv (or ,gv "")))
13563 `(string-match ,pv (or ,gv "")))
13564 (if str-p
13565 `(,po (or ,gv "") ,pv)
13566 `(,po (string-to-number (or ,gv ""))
13567 ,(string-to-number pv) ))))
13568 (t `(member ,tag tags-list)))
13569 mm (if minus (list 'not mm) mm)
13570 term rest)
13571 (push mm tagsmatcher))
13572 (push (if (> (length tagsmatcher) 1)
13573 (cons 'and tagsmatcher)
13574 (car tagsmatcher))
13575 orlist)
13576 (setq tagsmatcher nil))
13577 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13578 (setq tagsmatcher
13579 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13580 ;; Make the todo matcher
13581 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13582 (setq todomatcher t)
13583 (setq orterms (org-split-string todomatch "|") orlist nil)
13584 (while (setq term (pop orterms))
13585 (while (string-match re term)
13586 (setq minus (and (match-end 1)
13587 (equal (match-string 1 term) "-"))
13588 kwd (match-string 2 term)
13589 re-p (equal (string-to-char kwd) ?{)
13590 term (substring term (match-end 0))
13591 mm (if re-p
13592 `(string-match ,(substring kwd 1 -1) todo)
13593 (list 'equal 'todo kwd))
13594 mm (if minus (list 'not mm) mm))
13595 (push mm todomatcher))
13596 (push (if (> (length todomatcher) 1)
13597 (cons 'and todomatcher)
13598 (car todomatcher))
13599 orlist)
13600 (setq todomatcher nil))
13601 (setq todomatcher (if (> (length orlist) 1)
13602 (cons 'or orlist) (car orlist))))
13604 ;; Return the string and lisp forms of the matcher
13605 (setq matcher (if todomatcher
13606 (list 'and tagsmatcher todomatcher)
13607 tagsmatcher))
13608 (when todo-only
13609 (setq matcher (list 'and '(member todo org-not-done-keywords)
13610 matcher)))
13611 (cons match0 matcher)))
13613 (defun org-op-to-function (op &optional stringp)
13614 "Turn an operator into the appropriate function."
13615 (setq op
13616 (cond
13617 ((equal op "<" ) '(< string< org-time<))
13618 ((equal op ">" ) '(> org-string> org-time>))
13619 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13620 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13621 ((member op '("=" "==")) '(= string= org-time=))
13622 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13623 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13625 (defun org<> (a b) (not (= a b)))
13626 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13627 (defun org-string>= (a b) (not (string< a b)))
13628 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13629 (defun org-string<> (a b) (not (string= a b)))
13630 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13631 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13632 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13633 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13634 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13635 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13636 (defun org-2ft (s)
13637 "Convert S to a floating point time.
13638 If S is already a number, just return it. If it is a string, parse
13639 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13640 (cond
13641 ((numberp s) s)
13642 ((stringp s)
13643 (condition-case nil
13644 (float-time (apply 'encode-time (org-parse-time-string s)))
13645 (error 0.)))
13646 (t 0.)))
13648 (defun org-time-today ()
13649 "Time in seconds today at 0:00.
13650 Returns the float number of seconds since the beginning of the
13651 epoch to the beginning of today (00:00)."
13652 (float-time (apply 'encode-time
13653 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13655 (defun org-matcher-time (s)
13656 "Interpret a time comparison value."
13657 (save-match-data
13658 (cond
13659 ((string= s "<now>") (float-time))
13660 ((string= s "<today>") (org-time-today))
13661 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13662 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13663 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13664 (+ (org-time-today)
13665 (* (string-to-number (match-string 1 s))
13666 (cdr (assoc (match-string 2 s)
13667 '(("d" . 86400.0) ("w" . 604800.0)
13668 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13669 (t (org-2ft s)))))
13671 (defun org-match-any-p (re list)
13672 "Does re match any element of list?"
13673 (setq list (mapcar (lambda (x) (string-match re x)) list))
13674 (delq nil list))
13676 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13677 (defvar org-tags-overlay (make-overlay 1 1))
13678 (org-detach-overlay org-tags-overlay)
13680 (defun org-get-local-tags-at (&optional pos)
13681 "Get a list of tags defined in the current headline."
13682 (org-get-tags-at pos 'local))
13684 (defun org-get-local-tags ()
13685 "Get a list of tags defined in the current headline."
13686 (org-get-tags-at nil 'local))
13688 (defun org-get-tags-at (&optional pos local)
13689 "Get a list of all headline tags applicable at POS.
13690 POS defaults to point. If tags are inherited, the list contains
13691 the targets in the same sequence as the headlines appear, i.e.
13692 the tags of the current headline come last.
13693 When LOCAL is non-nil, only return tags from the current headline,
13694 ignore inherited ones."
13695 (interactive)
13696 (if (and org-trust-scanner-tags
13697 (or (not pos) (equal pos (point)))
13698 (not local))
13699 org-scanner-tags
13700 (let (tags ltags lastpos parent)
13701 (save-excursion
13702 (save-restriction
13703 (widen)
13704 (goto-char (or pos (point)))
13705 (save-match-data
13706 (catch 'done
13707 (condition-case nil
13708 (progn
13709 (org-back-to-heading t)
13710 (while (not (equal lastpos (point)))
13711 (setq lastpos (point))
13712 (when (looking-at
13713 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13714 (setq ltags (org-split-string
13715 (org-match-string-no-properties 1) ":"))
13716 (when parent
13717 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13718 (setq tags (append
13719 (if parent
13720 (org-remove-uninherited-tags ltags)
13721 ltags)
13722 tags)))
13723 (or org-use-tag-inheritance (throw 'done t))
13724 (if local (throw 'done t))
13725 (or (org-up-heading-safe) (error nil))
13726 (setq parent t)))
13727 (error nil)))))
13728 (if local
13729 tags
13730 (reverse (delete-dups
13731 (reverse (append
13732 (org-remove-uninherited-tags
13733 org-file-tags) tags)))))))))
13735 (defun org-add-prop-inherited (s)
13736 (add-text-properties 0 (length s) '(inherited t) s)
13739 (defun org-toggle-tag (tag &optional onoff)
13740 "Toggle the tag TAG for the current line.
13741 If ONOFF is `on' or `off', don't toggle but set to this state."
13742 (let (res current)
13743 (save-excursion
13744 (org-back-to-heading t)
13745 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13746 (point-at-eol) t)
13747 (progn
13748 (setq current (match-string 1))
13749 (replace-match ""))
13750 (setq current ""))
13751 (setq current (nreverse (org-split-string current ":")))
13752 (cond
13753 ((eq onoff 'on)
13754 (setq res t)
13755 (or (member tag current) (push tag current)))
13756 ((eq onoff 'off)
13757 (or (not (member tag current)) (setq current (delete tag current))))
13758 (t (if (member tag current)
13759 (setq current (delete tag current))
13760 (setq res t)
13761 (push tag current))))
13762 (end-of-line 1)
13763 (if current
13764 (progn
13765 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13766 (org-set-tags nil t))
13767 (delete-horizontal-space))
13768 (run-hooks 'org-after-tags-change-hook))
13769 res))
13771 (defun org-align-tags-here (to-col)
13772 ;; Assumes that this is a headline
13773 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13774 (beginning-of-line 1)
13775 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13776 (< pos (match-beginning 2)))
13777 (progn
13778 (setq tags-l (- (match-end 2) (match-beginning 2)))
13779 (goto-char (match-beginning 1))
13780 (insert " ")
13781 (delete-region (point) (1+ (match-beginning 2)))
13782 (setq ncol (max (current-column)
13783 (1+ col)
13784 (if (> to-col 0)
13785 to-col
13786 (- (abs to-col) tags-l))))
13787 (setq p (point))
13788 (insert (make-string (- ncol (current-column)) ?\ ))
13789 (setq ncol (current-column))
13790 (when indent-tabs-mode (tabify p (point-at-eol)))
13791 (org-move-to-column (min ncol col) t))
13792 (goto-char pos))))
13794 (defun org-set-tags-command (&optional arg just-align)
13795 "Call the set-tags command for the current entry."
13796 (interactive "P")
13797 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13798 (org-set-tags arg just-align)
13799 (save-excursion
13800 (org-back-to-heading t)
13801 (org-set-tags arg just-align))))
13803 (defun org-set-tags-to (data)
13804 "Set the tags of the current entry to DATA, replacing the current tags.
13805 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13806 If DATA is nil or the empty string, any tags will be removed."
13807 (interactive "sTags: ")
13808 (setq data
13809 (cond
13810 ((eq data nil) "")
13811 ((equal data "") "")
13812 ((stringp data)
13813 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13814 ":"))
13815 ((listp data)
13816 (concat ":" (mapconcat 'identity data ":") ":"))))
13817 (when data
13818 (save-excursion
13819 (org-back-to-heading t)
13820 (when (looking-at org-complex-heading-regexp)
13821 (if (match-end 5)
13822 (progn
13823 (goto-char (match-beginning 5))
13824 (insert data)
13825 (delete-region (point) (point-at-eol))
13826 (org-set-tags nil 'align))
13827 (goto-char (point-at-eol))
13828 (insert " " data)
13829 (org-set-tags nil 'align)))
13830 (beginning-of-line 1)
13831 (if (looking-at ".*?\\([ \t]+\\)$")
13832 (delete-region (match-beginning 1) (match-end 1))))))
13834 (defun org-align-all-tags ()
13835 "Align the tags i all headings."
13836 (interactive)
13837 (save-excursion
13838 (or (ignore-errors (org-back-to-heading t))
13839 (outline-next-heading))
13840 (if (org-at-heading-p)
13841 (org-set-tags t)
13842 (message "No headings"))))
13844 (defvar org-indent-indentation-per-level)
13845 (defun org-set-tags (&optional arg just-align)
13846 "Set the tags for the current headline.
13847 With prefix ARG, realign all tags in headings in the current buffer."
13848 (interactive "P")
13849 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13850 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13851 'region-start-level 'region))
13852 org-loop-over-headlines-in-active-region)
13853 (org-map-entries
13854 ;; We don't use ARG and JUST-ALIGN here these args are not
13855 ;; useful when looping over headlines
13856 `(org-set-tags)
13857 org-loop-over-headlines-in-active-region
13858 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13859 (let* ((re org-outline-regexp-bol)
13860 (current (unless arg (org-get-tags-string)))
13861 (col (current-column))
13862 (org-setting-tags t)
13863 table current-tags inherited-tags ; computed below when needed
13864 tags p0 c0 c1 rpl di tc level)
13865 (if arg
13866 (save-excursion
13867 (goto-char (point-min))
13868 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13869 (while (re-search-forward re nil t)
13870 (org-set-tags nil t)
13871 (end-of-line 1)))
13872 (message "All tags realigned to column %d" org-tags-column))
13873 (if just-align
13874 (setq tags current)
13875 ;; Get a new set of tags from the user
13876 (save-excursion
13877 (setq table (append org-tag-persistent-alist
13878 (or org-tag-alist (org-get-buffer-tags))
13879 (and
13880 org-complete-tags-always-offer-all-agenda-tags
13881 (org-global-tags-completion-table
13882 (org-agenda-files))))
13883 org-last-tags-completion-table table
13884 current-tags (org-split-string current ":")
13885 inherited-tags (nreverse
13886 (nthcdr (length current-tags)
13887 (nreverse (org-get-tags-at))))
13888 tags
13889 (if (or (eq t org-use-fast-tag-selection)
13890 (and org-use-fast-tag-selection
13891 (delq nil (mapcar 'cdr table))))
13892 (org-fast-tag-selection
13893 current-tags inherited-tags table
13894 (if org-fast-tag-selection-include-todo
13895 org-todo-key-alist))
13896 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13897 (org-trim
13898 (org-icompleting-read "Tags: "
13899 'org-tags-completion-function
13900 nil nil current 'org-tags-history))))))
13901 (while (string-match "[-+&]+" tags)
13902 ;; No boolean logic, just a list
13903 (setq tags (replace-match ":" t t tags))))
13905 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13907 (if org-tags-sort-function
13908 (setq tags (mapconcat 'identity
13909 (sort (org-split-string
13910 tags (org-re "[^[:alnum:]_@#%]+"))
13911 org-tags-sort-function) ":")))
13913 (if (string-match "\\`[\t ]*\\'" tags)
13914 (setq tags "")
13915 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13916 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13918 ;; Insert new tags at the correct column
13919 (beginning-of-line 1)
13920 (setq level (or (and (looking-at org-outline-regexp)
13921 (- (match-end 0) (point) 1))
13923 (cond
13924 ((and (equal current "") (equal tags "")))
13925 ((re-search-forward
13926 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13927 (point-at-eol) t)
13928 (if (equal tags "")
13929 (setq rpl "")
13930 (goto-char (match-beginning 0))
13931 (setq c0 (current-column)
13932 ;; compute offset for the case of org-indent-mode active
13933 di (if org-indent-mode
13934 (* (1- org-indent-indentation-per-level) (1- level))
13936 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13937 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13938 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13939 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13940 (replace-match rpl t t)
13941 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13942 tags)
13943 (t (error "Tags alignment failed")))
13944 (org-move-to-column col)
13945 (unless just-align
13946 (run-hooks 'org-after-tags-change-hook))))))
13948 (defun org-change-tag-in-region (beg end tag off)
13949 "Add or remove TAG for each entry in the region.
13950 This works in the agenda, and also in an org-mode buffer."
13951 (interactive
13952 (list (region-beginning) (region-end)
13953 (let ((org-last-tags-completion-table
13954 (if (derived-mode-p 'org-mode)
13955 (org-get-buffer-tags)
13956 (org-global-tags-completion-table))))
13957 (org-icompleting-read
13958 "Tag: " 'org-tags-completion-function nil nil nil
13959 'org-tags-history))
13960 (progn
13961 (message "[s]et or [r]emove? ")
13962 (equal (read-char-exclusive) ?r))))
13963 (if (fboundp 'deactivate-mark) (deactivate-mark))
13964 (let ((agendap (equal major-mode 'org-agenda-mode))
13965 l1 l2 m buf pos newhead (cnt 0))
13966 (goto-char end)
13967 (setq l2 (1- (org-current-line)))
13968 (goto-char beg)
13969 (setq l1 (org-current-line))
13970 (loop for l from l1 to l2 do
13971 (org-goto-line l)
13972 (setq m (get-text-property (point) 'org-hd-marker))
13973 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13974 (and agendap m))
13975 (setq buf (if agendap (marker-buffer m) (current-buffer))
13976 pos (if agendap m (point)))
13977 (with-current-buffer buf
13978 (save-excursion
13979 (save-restriction
13980 (goto-char pos)
13981 (setq cnt (1+ cnt))
13982 (org-toggle-tag tag (if off 'off 'on))
13983 (setq newhead (org-get-heading)))))
13984 (and agendap (org-agenda-change-all-lines newhead m))))
13985 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13987 (defun org-tags-completion-function (string predicate &optional flag)
13988 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13989 (confirm (lambda (x) (stringp (car x)))))
13990 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13991 (setq s1 (match-string 1 string)
13992 s2 (match-string 2 string))
13993 (setq s1 "" s2 string))
13994 (cond
13995 ((eq flag nil)
13996 ;; try completion
13997 (setq rtn (try-completion s2 ctable confirm))
13998 (if (stringp rtn)
13999 (setq rtn
14000 (concat s1 s2 (substring rtn (length s2))
14001 (if (and org-add-colon-after-tag-completion
14002 (assoc rtn ctable))
14003 ":" ""))))
14004 rtn)
14005 ((eq flag t)
14006 ;; all-completions
14007 (all-completions s2 ctable confirm)
14009 ((eq flag 'lambda)
14010 ;; exact match?
14011 (assoc s2 ctable)))
14014 (defun org-fast-tag-insert (kwd tags face &optional end)
14015 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14016 (insert (format "%-12s" (concat kwd ":"))
14017 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14018 (or end "")))
14020 (defun org-fast-tag-show-exit (flag)
14021 (save-excursion
14022 (org-goto-line 3)
14023 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14024 (replace-match ""))
14025 (when flag
14026 (end-of-line 1)
14027 (org-move-to-column (- (window-width) 19) t)
14028 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14030 (defun org-set-current-tags-overlay (current prefix)
14031 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14032 (if (featurep 'xemacs)
14033 (org-overlay-display org-tags-overlay (concat prefix s)
14034 'secondary-selection)
14035 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14036 (org-overlay-display org-tags-overlay (concat prefix s)))))
14038 (defvar org-last-tag-selection-key nil)
14039 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14040 "Fast tag selection with single keys.
14041 CURRENT is the current list of tags in the headline, INHERITED is the
14042 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14043 possibly with grouping information. TODO-TABLE is a similar table with
14044 TODO keywords, should these have keys assigned to them.
14045 If the keys are nil, a-z are automatically assigned.
14046 Returns the new tags string, or nil to not change the current settings."
14047 (let* ((fulltable (append table todo-table))
14048 (maxlen (apply 'max (mapcar
14049 (lambda (x)
14050 (if (stringp (car x)) (string-width (car x)) 0))
14051 fulltable)))
14052 (buf (current-buffer))
14053 (expert (eq org-fast-tag-selection-single-key 'expert))
14054 (buffer-tags nil)
14055 (fwidth (+ maxlen 3 1 3))
14056 (ncol (/ (- (window-width) 4) fwidth))
14057 (i-face 'org-done)
14058 (c-face 'org-todo)
14059 tg cnt e c char c1 c2 ntable tbl rtn
14060 ov-start ov-end ov-prefix
14061 (exit-after-next org-fast-tag-selection-single-key)
14062 (done-keywords org-done-keywords)
14063 groups ingroup)
14064 (save-excursion
14065 (beginning-of-line 1)
14066 (if (looking-at
14067 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14068 (setq ov-start (match-beginning 1)
14069 ov-end (match-end 1)
14070 ov-prefix "")
14071 (setq ov-start (1- (point-at-eol))
14072 ov-end (1+ ov-start))
14073 (skip-chars-forward "^\n\r")
14074 (setq ov-prefix
14075 (concat
14076 (buffer-substring (1- (point)) (point))
14077 (if (> (current-column) org-tags-column)
14079 (make-string (- org-tags-column (current-column)) ?\ ))))))
14080 (move-overlay org-tags-overlay ov-start ov-end)
14081 (save-window-excursion
14082 (if expert
14083 (set-buffer (get-buffer-create " *Org tags*"))
14084 (delete-other-windows)
14085 (split-window-vertically)
14086 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14087 (erase-buffer)
14088 (org-set-local 'org-done-keywords done-keywords)
14089 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14090 (org-fast-tag-insert "Current" current c-face "\n\n")
14091 (org-fast-tag-show-exit exit-after-next)
14092 (org-set-current-tags-overlay current ov-prefix)
14093 (setq tbl fulltable char ?a cnt 0)
14094 (while (setq e (pop tbl))
14095 (cond
14096 ((equal (car e) :startgroup)
14097 (push '() groups) (setq ingroup t)
14098 (when (not (= cnt 0))
14099 (setq cnt 0)
14100 (insert "\n"))
14101 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14102 ((equal (car e) :endgroup)
14103 (setq ingroup nil cnt 0)
14104 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14105 ((equal e '(:newline))
14106 (when (not (= cnt 0))
14107 (setq cnt 0)
14108 (insert "\n")
14109 (setq e (car tbl))
14110 (while (equal (car tbl) '(:newline))
14111 (insert "\n")
14112 (setq tbl (cdr tbl)))))
14114 (setq tg (copy-sequence (car e)) c2 nil)
14115 (if (cdr e)
14116 (setq c (cdr e))
14117 ;; automatically assign a character.
14118 (setq c1 (string-to-char
14119 (downcase (substring
14120 tg (if (= (string-to-char tg) ?@) 1 0)))))
14121 (if (or (rassoc c1 ntable) (rassoc c1 table))
14122 (while (or (rassoc char ntable) (rassoc char table))
14123 (setq char (1+ char)))
14124 (setq c2 c1))
14125 (setq c (or c2 char)))
14126 (if ingroup (push tg (car groups)))
14127 (setq tg (org-add-props tg nil 'face
14128 (cond
14129 ((not (assoc tg table))
14130 (org-get-todo-face tg))
14131 ((member tg current) c-face)
14132 ((member tg inherited) i-face))))
14133 (if (and (= cnt 0) (not ingroup)) (insert " "))
14134 (insert "[" c "] " tg (make-string
14135 (- fwidth 4 (length tg)) ?\ ))
14136 (push (cons tg c) ntable)
14137 (when (= (setq cnt (1+ cnt)) ncol)
14138 (insert "\n")
14139 (if ingroup (insert " "))
14140 (setq cnt 0)))))
14141 (setq ntable (nreverse ntable))
14142 (insert "\n")
14143 (goto-char (point-min))
14144 (if (not expert) (org-fit-window-to-buffer))
14145 (setq rtn
14146 (catch 'exit
14147 (while t
14148 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14149 (if (not groups) "no " "")
14150 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14151 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14152 (setq org-last-tag-selection-key c)
14153 (cond
14154 ((= c ?\r) (throw 'exit t))
14155 ((= c ?!)
14156 (setq groups (not groups))
14157 (goto-char (point-min))
14158 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14159 ((= c ?\C-c)
14160 (if (not expert)
14161 (org-fast-tag-show-exit
14162 (setq exit-after-next (not exit-after-next)))
14163 (setq expert nil)
14164 (delete-other-windows)
14165 (set-window-buffer (split-window-vertically) " *Org tags*")
14166 (org-switch-to-buffer-other-window " *Org tags*")
14167 (org-fit-window-to-buffer)))
14168 ((or (= c ?\C-g)
14169 (and (= c ?q) (not (rassoc c ntable))))
14170 (org-detach-overlay org-tags-overlay)
14171 (setq quit-flag t))
14172 ((= c ?\ )
14173 (setq current nil)
14174 (if exit-after-next (setq exit-after-next 'now)))
14175 ((= c ?\t)
14176 (condition-case nil
14177 (setq tg (org-icompleting-read
14178 "Tag: "
14179 (or buffer-tags
14180 (with-current-buffer buf
14181 (org-get-buffer-tags)))))
14182 (quit (setq tg "")))
14183 (when (string-match "\\S-" tg)
14184 (add-to-list 'buffer-tags (list tg))
14185 (if (member tg current)
14186 (setq current (delete tg current))
14187 (push tg current)))
14188 (if exit-after-next (setq exit-after-next 'now)))
14189 ((setq e (rassoc c todo-table) tg (car e))
14190 (with-current-buffer buf
14191 (save-excursion (org-todo tg)))
14192 (if exit-after-next (setq exit-after-next 'now)))
14193 ((setq e (rassoc c ntable) tg (car e))
14194 (if (member tg current)
14195 (setq current (delete tg current))
14196 (loop for g in groups do
14197 (if (member tg g)
14198 (mapc (lambda (x)
14199 (setq current (delete x current)))
14200 g)))
14201 (push tg current))
14202 (if exit-after-next (setq exit-after-next 'now))))
14204 ;; Create a sorted list
14205 (setq current
14206 (sort current
14207 (lambda (a b)
14208 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14209 (if (eq exit-after-next 'now) (throw 'exit t))
14210 (goto-char (point-min))
14211 (beginning-of-line 2)
14212 (delete-region (point) (point-at-eol))
14213 (org-fast-tag-insert "Current" current c-face)
14214 (org-set-current-tags-overlay current ov-prefix)
14215 (while (re-search-forward
14216 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14217 (setq tg (match-string 1))
14218 (add-text-properties
14219 (match-beginning 1) (match-end 1)
14220 (list 'face
14221 (cond
14222 ((member tg current) c-face)
14223 ((member tg inherited) i-face)
14224 (t (get-text-property (match-beginning 1) 'face))))))
14225 (goto-char (point-min)))))
14226 (org-detach-overlay org-tags-overlay)
14227 (if rtn
14228 (mapconcat 'identity current ":")
14229 nil))))
14231 (defun org-get-tags-string ()
14232 "Get the TAGS string in the current headline."
14233 (unless (org-at-heading-p t)
14234 (error "Not on a heading"))
14235 (save-excursion
14236 (beginning-of-line 1)
14237 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14238 (org-match-string-no-properties 1)
14239 "")))
14241 (defun org-get-tags ()
14242 "Get the list of tags specified in the current headline."
14243 (org-split-string (org-get-tags-string) ":"))
14245 (defun org-get-buffer-tags ()
14246 "Get a table of all tags used in the buffer, for completion."
14247 (let (tags)
14248 (save-excursion
14249 (goto-char (point-min))
14250 (while (re-search-forward
14251 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14252 (when (equal (char-after (point-at-bol 0)) ?*)
14253 (mapc (lambda (x) (add-to-list 'tags x))
14254 (org-split-string (org-match-string-no-properties 1) ":")))))
14255 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14256 (mapcar 'list tags)))
14258 ;;;; The mapping API
14260 (defun org-map-entries (func &optional match scope &rest skip)
14261 "Call FUNC at each headline selected by MATCH in SCOPE.
14263 FUNC is a function or a lisp form. The function will be called without
14264 arguments, with the cursor positioned at the beginning of the headline.
14265 The return values of all calls to the function will be collected and
14266 returned as a list.
14268 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14269 does not need to preserve point. After evaluation, the cursor will be
14270 moved to the end of the line (presumably of the headline of the
14271 processed entry) and search continues from there. Under some
14272 circumstances, this may not produce the wanted results. For example,
14273 if you have removed (e.g. archived) the current (sub)tree it could
14274 mean that the next entry will be skipped entirely. In such cases, you
14275 can specify the position from where search should continue by making
14276 FUNC set the variable `org-map-continue-from' to the desired buffer
14277 position.
14279 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14280 Only headlines that are matched by this query will be considered during
14281 the iteration. When MATCH is nil or t, all headlines will be
14282 visited by the iteration.
14284 SCOPE determines the scope of this command. It can be any of:
14286 nil The current buffer, respecting the restriction if any
14287 tree The subtree started with the entry at point
14288 region The entries within the active region, if any
14289 region-start-level
14290 The entries within the active region, but only those at
14291 the same level than the first one.
14292 file The current buffer, without restriction
14293 file-with-archives
14294 The current buffer, and any archives associated with it
14295 agenda All agenda files
14296 agenda-with-archives
14297 All agenda files with any archive files associated with them
14298 \(file1 file2 ...)
14299 If this is a list, all files in the list will be scanned
14301 The remaining args are treated as settings for the skipping facilities of
14302 the scanner. The following items can be given here:
14304 archive skip trees with the archive tag.
14305 comment skip trees with the COMMENT keyword
14306 function or Emacs Lisp form:
14307 will be used as value for `org-agenda-skip-function', so whenever
14308 the function returns t, FUNC will not be called for that
14309 entry and search will continue from the point where the
14310 function leaves it.
14312 If your function needs to retrieve the tags including inherited tags
14313 at the *current* entry, you can use the value of the variable
14314 `org-scanner-tags' which will be much faster than getting the value
14315 with `org-get-tags-at'. If your function gets properties with
14316 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14317 to t around the call to `org-entry-properties' to get the same speedup.
14318 Note that if your function moves around to retrieve tags and properties at
14319 a *different* entry, you cannot use these techniques."
14320 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14321 (not (org-region-active-p)))
14322 (let* ((org-agenda-archives-mode nil) ; just to make sure
14323 (org-agenda-skip-archived-trees (memq 'archive skip))
14324 (org-agenda-skip-comment-trees (memq 'comment skip))
14325 (org-agenda-skip-function
14326 (car (org-delete-all '(comment archive) skip)))
14327 (org-tags-match-list-sublevels t)
14328 (start-level (eq scope 'region-start-level))
14329 matcher file res
14330 org-todo-keywords-for-agenda
14331 org-done-keywords-for-agenda
14332 org-todo-keyword-alist-for-agenda
14333 org-drawers-for-agenda
14334 org-tag-alist-for-agenda
14335 todo-only)
14337 (cond
14338 ((eq match t) (setq matcher t))
14339 ((eq match nil) (setq matcher t))
14340 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14342 (save-excursion
14343 (save-restriction
14344 (cond ((eq scope 'tree)
14345 (org-back-to-heading t)
14346 (org-narrow-to-subtree)
14347 (setq scope nil))
14348 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14349 (org-region-active-p))
14350 ;; If needed, set start-level to a string like "2"
14351 (when start-level
14352 (save-excursion
14353 (goto-char (region-beginning))
14354 (unless (org-at-heading-p) (outline-next-heading))
14355 (setq start-level (org-current-level))))
14356 (narrow-to-region (region-beginning)
14357 (save-excursion
14358 (goto-char (region-end))
14359 (unless (and (bolp) (org-at-heading-p))
14360 (outline-next-heading))
14361 (point)))
14362 (setq scope nil)))
14364 (if (not scope)
14365 (progn
14366 (org-agenda-prepare-buffers
14367 (list (buffer-file-name (current-buffer))))
14368 (setq res (org-scan-tags func matcher todo-only start-level)))
14369 ;; Get the right scope
14370 (cond
14371 ((and scope (listp scope) (symbolp (car scope)))
14372 (setq scope (eval scope)))
14373 ((eq scope 'agenda)
14374 (setq scope (org-agenda-files t)))
14375 ((eq scope 'agenda-with-archives)
14376 (setq scope (org-agenda-files t))
14377 (setq scope (org-add-archive-files scope)))
14378 ((eq scope 'file)
14379 (setq scope (list (buffer-file-name))))
14380 ((eq scope 'file-with-archives)
14381 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14382 (org-agenda-prepare-buffers scope)
14383 (while (setq file (pop scope))
14384 (with-current-buffer (org-find-base-buffer-visiting file)
14385 (save-excursion
14386 (save-restriction
14387 (widen)
14388 (goto-char (point-min))
14389 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14390 res)))
14392 ;;;; Properties
14394 ;;; Setting and retrieving properties
14396 (defconst org-special-properties
14397 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14398 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14399 "The special properties valid in Org-mode.
14401 These are properties that are not defined in the property drawer,
14402 but in some other way.")
14404 (defconst org-default-properties
14405 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14406 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14407 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14408 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14409 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14410 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14411 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14412 "Some properties that are used by Org-mode for various purposes.
14413 Being in this list makes sure that they are offered for completion.")
14415 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14416 "Regular expression matching the first line of a property drawer.")
14418 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14419 "Regular expression matching the last line of a property drawer.")
14421 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14422 "Regular expression matching the first line of a property drawer.")
14424 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14425 "Regular expression matching the first line of a property drawer.")
14427 (defconst org-property-drawer-re
14428 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14429 org-property-end-re "\\)\n?")
14430 "Matches an entire property drawer.")
14432 (defconst org-clock-drawer-re
14433 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14434 org-property-end-re "\\)\n?")
14435 "Matches an entire clock drawer.")
14437 (defsubst org-re-property (property)
14438 "Return a regexp matching a PROPERTY line.
14439 Match group 1 will be set to the value."
14440 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14442 (defsubst org-re-property-keyword (property)
14443 "Return a regexp matching a PROPERTY line, possibly with no
14444 value for the property."
14445 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14447 (defun org-property-action ()
14448 "Do an action on properties."
14449 (interactive)
14450 (let (c)
14451 (org-at-property-p)
14452 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14453 (setq c (read-char-exclusive))
14454 (cond
14455 ((equal c ?s)
14456 (call-interactively 'org-set-property))
14457 ((equal c ?d)
14458 (call-interactively 'org-delete-property))
14459 ((equal c ?D)
14460 (call-interactively 'org-delete-property-globally))
14461 ((equal c ?c)
14462 (call-interactively 'org-compute-property-at-point))
14463 (t (error "No such property action %c" c)))))
14465 (defun org-inc-effort ()
14466 "Increment the value of the effort property in the current entry."
14467 (interactive)
14468 (org-set-effort nil t))
14470 (defun org-set-effort (&optional value increment)
14471 "Set the effort property of the current entry.
14472 With numerical prefix arg, use the nth allowed value, 0 stands for the
14473 10th allowed value.
14475 When INCREMENT is non-nil, set the property to the next allowed value."
14476 (interactive "P")
14477 (if (equal value 0) (setq value 10))
14478 (let* ((completion-ignore-case t)
14479 (prop org-effort-property)
14480 (cur (org-entry-get nil prop))
14481 (allowed (org-property-get-allowed-values nil prop 'table))
14482 (existing (mapcar 'list (org-property-values prop)))
14484 (val (cond
14485 ((stringp value) value)
14486 ((and allowed (integerp value))
14487 (or (car (nth (1- value) allowed))
14488 (car (org-last allowed))))
14489 ((and allowed increment)
14490 (or (caadr (member (list cur) allowed))
14491 (error "Allowed effort values are not set")))
14492 (allowed
14493 (message "Select 1-9,0, [RET%s]: %s"
14494 (if cur (concat "=" cur) "")
14495 (mapconcat 'car allowed " "))
14496 (setq rpl (read-char-exclusive))
14497 (if (equal rpl ?\r)
14499 (setq rpl (- rpl ?0))
14500 (if (equal rpl 0) (setq rpl 10))
14501 (if (and (> rpl 0) (<= rpl (length allowed)))
14502 (car (nth (1- rpl) allowed))
14503 (org-completing-read "Effort: " allowed nil))))
14505 (let (org-completion-use-ido org-completion-use-iswitchb)
14506 (org-completing-read
14507 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14508 (concat "[" cur "]") "")
14509 ": ")
14510 existing nil nil "" nil cur))))))
14511 (unless (equal (org-entry-get nil prop) val)
14512 (org-entry-put nil prop val))
14513 (save-excursion
14514 (org-back-to-heading t)
14515 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14516 (message "%s is now %s" prop val)))
14518 (defun org-at-property-p ()
14519 "Is cursor inside a property drawer?"
14520 (save-excursion
14521 (beginning-of-line 1)
14522 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14523 (save-match-data ;; Used by calling procedures
14524 (let ((p (point))
14525 (range (unless (org-before-first-heading-p)
14526 (org-get-property-block))))
14527 (and range (<= (car range) p) (< p (cdr range))))))))
14529 (defun org-get-property-block (&optional beg end force)
14530 "Return the (beg . end) range of the body of the property drawer.
14531 BEG and END are the beginning and end of the current subtree, or of
14532 the part before the first headline. If they are not given, they will
14533 be found. If the drawer does not exist and FORCE is non-nil, create
14534 the drawer."
14535 (catch 'exit
14536 (save-excursion
14537 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14538 (progn (org-back-to-heading t) (point))))
14539 (end (or end (and (not (outline-next-heading)) (point-max))
14540 (point))))
14541 (goto-char beg)
14542 (if (re-search-forward org-property-start-re end t)
14543 (setq beg (1+ (match-end 0)))
14544 (if force
14545 (save-excursion
14546 (org-insert-property-drawer)
14547 (setq end (progn (outline-next-heading) (point))))
14548 (throw 'exit nil))
14549 (goto-char beg)
14550 (if (re-search-forward org-property-start-re end t)
14551 (setq beg (1+ (match-end 0)))))
14552 (if (re-search-forward org-property-end-re end t)
14553 (setq end (match-beginning 0))
14554 (or force (throw 'exit nil))
14555 (goto-char beg)
14556 (setq end beg)
14557 (org-indent-line)
14558 (insert ":END:\n"))
14559 (cons beg end)))))
14561 (defun org-entry-properties (&optional pom which specific)
14562 "Get all properties of the entry at point-or-marker POM.
14563 This includes the TODO keyword, the tags, time strings for deadline,
14564 scheduled, and clocking, and any additional properties defined in the
14565 entry. The return value is an alist, keys may occur multiple times
14566 if the property key was used several times.
14567 POM may also be nil, in which case the current entry is used.
14568 If WHICH is nil or `all', get all properties. If WHICH is
14569 `special' or `standard', only get that subclass. If WHICH
14570 is a string only get exactly this property. SPECIFIC can be a string, the
14571 specific property we are interested in. Specifying it can speed
14572 things up because then unnecessary parsing is avoided."
14573 (setq which (or which 'all))
14574 (org-with-point-at pom
14575 (let ((clockstr (substring org-clock-string 0 -1))
14576 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14577 (case-fold-search nil)
14578 beg end range props sum-props key key1 value string clocksum clocksumt)
14579 (save-excursion
14580 (when (condition-case nil
14581 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14582 (error nil))
14583 (setq beg (point))
14584 (setq sum-props (get-text-property (point) 'org-summaries))
14585 (setq clocksum (get-text-property (point) :org-clock-minutes)
14586 clocksumt (get-text-property (point) :org-clock-minutes-today))
14587 (outline-next-heading)
14588 (setq end (point))
14589 (when (memq which '(all special))
14590 ;; Get the special properties, like TODO and tags
14591 (goto-char beg)
14592 (when (and (or (not specific) (string= specific "TODO"))
14593 (looking-at org-todo-line-regexp) (match-end 2))
14594 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14595 (when (and (or (not specific) (string= specific "PRIORITY"))
14596 (looking-at org-priority-regexp))
14597 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14598 (when (or (not specific) (string= specific "FILE"))
14599 (push (cons "FILE" buffer-file-name) props))
14600 (when (and (or (not specific) (string= specific "TAGS"))
14601 (setq value (org-get-tags-string))
14602 (string-match "\\S-" value))
14603 (push (cons "TAGS" value) props))
14604 (when (and (or (not specific) (string= specific "ALLTAGS"))
14605 (setq value (org-get-tags-at)))
14606 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14607 ":"))
14608 props))
14609 (when (or (not specific) (string= specific "BLOCKED"))
14610 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14611 (when (or (not specific)
14612 (member specific
14613 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14614 "TIMESTAMP" "TIMESTAMP_IA")))
14615 (catch 'match
14616 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14617 (setq key (if (match-end 1)
14618 (substring (org-match-string-no-properties 1)
14619 0 -1))
14620 string (if (equal key clockstr)
14621 (org-trim
14622 (buffer-substring-no-properties
14623 (match-beginning 3) (goto-char
14624 (point-at-eol))))
14625 (substring (org-match-string-no-properties 3)
14626 1 -1)))
14627 ;; Get the correct property name from the key. This is
14628 ;; necessary if the user has configured time keywords.
14629 (setq key1 (concat key ":"))
14630 (cond
14631 ((not key)
14632 (setq key
14633 (if (= (char-after (match-beginning 3)) ?\[)
14634 "TIMESTAMP_IA" "TIMESTAMP")))
14635 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14636 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14637 ((equal key1 org-closed-string) (setq key "CLOSED"))
14638 ((equal key1 org-clock-string) (setq key "CLOCK")))
14639 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14640 (progn
14641 (push (cons key string) props)
14642 ;; no need to search further if match is found
14643 (throw 'match t))
14644 (when (or (equal key "CLOCK") (not (assoc key props)))
14645 (push (cons key string) props)))))))
14647 (when (memq which '(all standard))
14648 ;; Get the standard properties, like :PROP: ...
14649 (setq range (org-get-property-block beg end))
14650 (when range
14651 (goto-char (car range))
14652 (while (re-search-forward
14653 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14654 (cdr range) t)
14655 (setq key (org-match-string-no-properties 1)
14656 value (org-trim (or (org-match-string-no-properties 2) "")))
14657 (unless (member key excluded)
14658 (push (cons key (or value "")) props)))))
14659 (if clocksum
14660 (push (cons "CLOCKSUM"
14661 (org-columns-number-to-string (/ (float clocksum) 60.)
14662 'add_times))
14663 props))
14664 (if clocksumt
14665 (push (cons "CLOCKSUM_T"
14666 (org-columns-number-to-string (/ (float clocksumt) 60.)
14667 'add_times))
14668 props))
14669 (unless (assoc "CATEGORY" props)
14670 (push (cons "CATEGORY" (org-get-category)) props))
14671 (append sum-props (nreverse props)))))))
14673 (defun org-entry-get (pom property &optional inherit literal-nil)
14674 "Get value of PROPERTY for entry or content at point-or-marker POM.
14675 If INHERIT is non-nil and the entry does not have the property,
14676 then also check higher levels of the hierarchy.
14677 If INHERIT is the symbol `selective', use inheritance only if the setting
14678 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14679 If the property is present but empty, the return value is the empty string.
14680 If the property is not present at all, nil is returned.
14682 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14683 do not interpret it as the list atom nil. This is used for inheritance
14684 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14685 (org-with-point-at pom
14686 (if (and inherit (if (eq inherit 'selective)
14687 (org-property-inherit-p property)
14689 (org-entry-get-with-inheritance property literal-nil)
14690 (if (member property org-special-properties)
14691 ;; We need a special property. Use `org-entry-properties' to
14692 ;; retrieve it, but specify the wanted property
14693 (cdr (assoc property (org-entry-properties nil 'special property)))
14694 (let ((range (org-get-property-block)))
14695 (when (and range (not (eq (car range) (cdr range))))
14696 (let* ((props (list (or (assoc property org-file-properties)
14697 (assoc property org-global-properties)
14698 (assoc property org-global-properties-fixed))))
14699 (ap (lambda (key)
14700 (when (re-search-forward
14701 (org-re-property key) (cdr range) t)
14702 (setq props
14703 (org-update-property-plist
14705 (if (match-end 1)
14706 (org-match-string-no-properties 1) "")
14707 props)))))
14708 val)
14709 (goto-char (car range))
14710 (funcall ap property)
14711 (goto-char (car range))
14712 (while (funcall ap (concat property "+")))
14713 (setq val (cdr (assoc property props)))
14714 (when val (if literal-nil val (org-not-nil val))))))))))
14716 (defun org-property-or-variable-value (var &optional inherit)
14717 "Check if there is a property fixing the value of VAR.
14718 If yes, return this value. If not, return the current value of the variable."
14719 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14720 (if (and prop (stringp prop) (string-match "\\S-" prop))
14721 (read prop)
14722 (symbol-value var))))
14724 (defun org-entry-delete (pom property)
14725 "Delete the property PROPERTY from entry at point-or-marker POM."
14726 (org-with-point-at pom
14727 (if (member property org-special-properties)
14728 nil ; cannot delete these properties.
14729 (let ((range (org-get-property-block)))
14730 (if (and range
14731 (goto-char (car range))
14732 (re-search-forward
14733 (org-re-property property)
14734 (cdr range) t))
14735 (progn
14736 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14738 nil)))))
14740 ;; Multi-values properties are properties that contain multiple values
14741 ;; These values are assumed to be single words, separated by whitespace.
14742 (defun org-entry-add-to-multivalued-property (pom property value)
14743 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14744 (let* ((old (org-entry-get pom property))
14745 (values (and old (org-split-string old "[ \t]"))))
14746 (setq value (org-entry-protect-space value))
14747 (unless (member value values)
14748 (setq values (cons value values))
14749 (org-entry-put pom property
14750 (mapconcat 'identity values " ")))))
14752 (defun org-entry-remove-from-multivalued-property (pom property value)
14753 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14754 (let* ((old (org-entry-get pom property))
14755 (values (and old (org-split-string old "[ \t]"))))
14756 (setq value (org-entry-protect-space value))
14757 (when (member value values)
14758 (setq values (delete value values))
14759 (org-entry-put pom property
14760 (mapconcat 'identity values " ")))))
14762 (defun org-entry-member-in-multivalued-property (pom property value)
14763 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14764 (let* ((old (org-entry-get pom property))
14765 (values (and old (org-split-string old "[ \t]"))))
14766 (setq value (org-entry-protect-space value))
14767 (member value values)))
14769 (defun org-entry-get-multivalued-property (pom property)
14770 "Return a list of values in a multivalued property."
14771 (let* ((value (org-entry-get pom property))
14772 (values (and value (org-split-string value "[ \t]"))))
14773 (mapcar 'org-entry-restore-space values)))
14775 (defun org-entry-put-multivalued-property (pom property &rest values)
14776 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14777 VALUES should be a list of strings. Spaces will be protected."
14778 (org-entry-put pom property
14779 (mapconcat 'org-entry-protect-space values " "))
14780 (let* ((value (org-entry-get pom property))
14781 (values (and value (org-split-string value "[ \t]"))))
14782 (mapcar 'org-entry-restore-space values)))
14784 (defun org-entry-protect-space (s)
14785 "Protect spaces and newline in string S."
14786 (while (string-match " " s)
14787 (setq s (replace-match "%20" t t s)))
14788 (while (string-match "\n" s)
14789 (setq s (replace-match "%0A" t t s)))
14792 (defun org-entry-restore-space (s)
14793 "Restore spaces and newline in string S."
14794 (while (string-match "%20" s)
14795 (setq s (replace-match " " t t s)))
14796 (while (string-match "%0A" s)
14797 (setq s (replace-match "\n" t t s)))
14800 (defvar org-entry-property-inherited-from (make-marker)
14801 "Marker pointing to the entry from where a property was inherited.
14802 Each call to `org-entry-get-with-inheritance' will set this marker to the
14803 location of the entry where the inheritance search matched. If there was
14804 no match, the marker will point nowhere.
14805 Note that also `org-entry-get' calls this function, if the INHERIT flag
14806 is set.")
14808 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14809 "Get PROPERTY of entry or content at point, search higher levels if needed.
14810 The search will stop at the first ancestor which has the property defined.
14811 If the value found is \"nil\", return nil to show that the property
14812 should be considered as undefined (this is the meaning of nil here).
14813 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14814 (move-marker org-entry-property-inherited-from nil)
14815 (let (tmp)
14816 (save-excursion
14817 (save-restriction
14818 (widen)
14819 (catch 'ex
14820 (while t
14821 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14822 (or (ignore-errors (org-back-to-heading t))
14823 (goto-char (point-min)))
14824 (move-marker org-entry-property-inherited-from (point))
14825 (throw 'ex tmp))
14826 (or (ignore-errors (org-up-heading-safe))
14827 (throw 'ex nil))))))
14828 (setq tmp (or tmp
14829 (cdr (assoc property org-file-properties))
14830 (cdr (assoc property org-global-properties))
14831 (cdr (assoc property org-global-properties-fixed))))
14832 (if literal-nil tmp (org-not-nil tmp))))
14834 (defvar org-property-changed-functions nil
14835 "Hook called when the value of a property has changed.
14836 Each hook function should accept two arguments, the name of the property
14837 and the new value.")
14839 (defun org-entry-put (pom property value)
14840 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14841 (org-with-point-at pom
14842 (org-back-to-heading t)
14843 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14844 range)
14845 (cond
14846 ((equal property "TODO")
14847 (when (and (stringp value) (string-match "\\S-" value)
14848 (not (member value org-todo-keywords-1)))
14849 (error "\"%s\" is not a valid TODO state" value))
14850 (if (or (not value)
14851 (not (string-match "\\S-" value)))
14852 (setq value 'none))
14853 (org-todo value)
14854 (org-set-tags nil 'align))
14855 ((equal property "PRIORITY")
14856 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14857 (string-to-char value) ?\ ))
14858 (org-set-tags nil 'align))
14859 ((equal property "CLOCKSUM")
14860 (if (not (re-search-forward
14861 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
14862 (error "Cannot find a clock log")
14863 (goto-char (- (match-end 1) 2))
14864 (cond
14865 ((eq value 'earlier) (org-timestamp-down))
14866 ((eq value 'later) (org-timestamp-up)))
14867 (org-clock-sum-current-item)))
14868 ((equal property "SCHEDULED")
14869 (if (re-search-forward org-scheduled-time-regexp end t)
14870 (cond
14871 ((eq value 'earlier) (org-timestamp-change -1 'day))
14872 ((eq value 'later) (org-timestamp-change 1 'day))
14873 (t (call-interactively 'org-schedule)))
14874 (call-interactively 'org-schedule)))
14875 ((equal property "DEADLINE")
14876 (if (re-search-forward org-deadline-time-regexp end t)
14877 (cond
14878 ((eq value 'earlier) (org-timestamp-change -1 'day))
14879 ((eq value 'later) (org-timestamp-change 1 'day))
14880 (t (call-interactively 'org-deadline)))
14881 (call-interactively 'org-deadline)))
14882 ((member property org-special-properties)
14883 (error "The %s property can not yet be set with `org-entry-put'"
14884 property))
14885 (t ; a non-special property
14886 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14887 (setq range (org-get-property-block beg end 'force))
14888 (goto-char (car range))
14889 (if (re-search-forward
14890 (org-re-property-keyword property) (cdr range) t)
14891 (progn
14892 (delete-region (match-beginning 0) (match-end 0))
14893 (goto-char (match-beginning 0)))
14894 (goto-char (cdr range))
14895 (insert "\n")
14896 (backward-char 1)
14897 (org-indent-line))
14898 (insert ":" property ":")
14899 (and value (insert " " value))
14900 (org-indent-line)))))
14901 (run-hook-with-args 'org-property-changed-functions property value)))
14903 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14904 "Get all property keys in the current buffer.
14905 With INCLUDE-SPECIALS, also list the special properties that reflect things
14906 like tags and TODO state.
14907 With INCLUDE-DEFAULTS, also include properties that has special meaning
14908 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14909 and others.
14910 With INCLUDE-COLUMNS, also include property names given in COLUMN
14911 formats in the current buffer."
14912 (let (rtn range cfmt s p)
14913 (save-excursion
14914 (save-restriction
14915 (widen)
14916 (goto-char (point-min))
14917 (while (re-search-forward org-property-start-re nil t)
14918 (setq range (org-get-property-block))
14919 (goto-char (car range))
14920 (while (re-search-forward
14921 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14922 (cdr range) t)
14923 (add-to-list 'rtn (org-match-string-no-properties 1)))
14924 (outline-next-heading))))
14926 (when include-specials
14927 (setq rtn (append org-special-properties rtn)))
14929 (when include-defaults
14930 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14931 (add-to-list 'rtn org-effort-property))
14933 (when include-columns
14934 (save-excursion
14935 (save-restriction
14936 (widen)
14937 (goto-char (point-min))
14938 (while (re-search-forward
14939 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14940 nil t)
14941 (setq cfmt (match-string 2) s 0)
14942 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14943 cfmt s)
14944 (setq s (match-end 0)
14945 p (match-string 1 cfmt))
14946 (unless (or (equal p "ITEM")
14947 (member p org-special-properties))
14948 (add-to-list 'rtn (match-string 1 cfmt))))))))
14950 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14952 (defun org-property-values (key)
14953 "Return a list of all values of property KEY in the current buffer."
14954 (save-excursion
14955 (save-restriction
14956 (widen)
14957 (goto-char (point-min))
14958 (let ((re (org-re-property key))
14959 values)
14960 (while (re-search-forward re nil t)
14961 (add-to-list 'values (org-trim (match-string 1))))
14962 (delete "" values)))))
14964 (defun org-insert-property-drawer ()
14965 "Insert a property drawer into the current entry."
14966 (org-back-to-heading t)
14967 (looking-at org-outline-regexp)
14968 (let ((indent (if org-adapt-indentation
14969 (- (match-end 0) (match-beginning 0))
14971 (beg (point))
14972 (re (concat "^[ \t]*" org-keyword-time-regexp))
14973 end hiddenp)
14974 (outline-next-heading)
14975 (setq end (point))
14976 (goto-char beg)
14977 (while (re-search-forward re end t))
14978 (setq hiddenp (outline-invisible-p))
14979 (end-of-line 1)
14980 (and (equal (char-after) ?\n) (forward-char 1))
14981 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14982 (if (member (match-string 1) '("CLOCK:" ":END:"))
14983 ;; just skip this line
14984 (beginning-of-line 2)
14985 ;; Drawer start, find the end
14986 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14987 (beginning-of-line 1)))
14988 (org-skip-over-state-notes)
14989 (skip-chars-backward " \t\n\r")
14990 (if (eq (char-before) ?*) (forward-char 1))
14991 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14992 (beginning-of-line 0)
14993 (org-indent-to-column indent)
14994 (beginning-of-line 2)
14995 (org-indent-to-column indent)
14996 (beginning-of-line 0)
14997 (if hiddenp
14998 (save-excursion
14999 (org-back-to-heading t)
15000 (hide-entry))
15001 (org-flag-drawer t))))
15003 (defun org-insert-drawer (&optional arg drawer)
15004 "Insert a drawer at point.
15006 Optional argument DRAWER, when non-nil, is a string representing
15007 drawer's name. Otherwise, the user is prompted for a name.
15009 If a region is active, insert the drawer around that region
15010 instead.
15012 Point is left between drawer's boundaries."
15013 (interactive "P")
15014 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15015 "LOGBOOK"))
15016 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15017 ;; internally by Org. They are meant to be inserted
15018 ;; automatically.
15019 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15020 ;; Remove system drawers from list. Note: For some reason,
15021 ;; `org-completing-read' ignores the predicate while
15022 ;; `completing-read' handles it fine.
15023 (drawer (if arg "PROPERTIES"
15024 (or drawer
15025 (completing-read
15026 "Drawer: " org-drawers
15027 (lambda (d) (not (member d system-drawers))))))))
15028 (cond
15029 ;; With C-u, fall back on `org-insert-property-drawer'
15030 (arg (org-insert-property-drawer))
15031 ;; With an active region, insert a drawer at point.
15032 ((not (org-region-active-p))
15033 (progn
15034 (unless (bolp) (insert "\n"))
15035 (insert (format ":%s:\n\n:END:\n" drawer))
15036 (forward-line -2)))
15037 ;; Otherwise, insert the drawer at point
15039 (let ((rbeg (region-beginning))
15040 (rend (copy-marker (region-end))))
15041 (unwind-protect
15042 (progn
15043 (goto-char rbeg)
15044 (beginning-of-line)
15045 (when (save-excursion
15046 (re-search-forward org-outline-regexp-bol rend t))
15047 (error "Drawers cannot contain headlines"))
15048 ;; Position point at the beginning of the first
15049 ;; non-blank line in region. Insert drawer's opening
15050 ;; there, then indent it.
15051 (org-skip-whitespace)
15052 (beginning-of-line)
15053 (insert ":" drawer ":\n")
15054 (forward-line -1)
15055 (indent-for-tab-command)
15056 ;; Move point to the beginning of the first blank line
15057 ;; after the last non-blank line in region. Insert
15058 ;; drawer's closing, then indent it.
15059 (goto-char rend)
15060 (skip-chars-backward " \r\t\n")
15061 (insert "\n:END:")
15062 (deactivate-mark t)
15063 (indent-for-tab-command)
15064 (unless (eolp) (insert "\n")))
15065 ;; Clear marker, whatever the outcome of insertion is.
15066 (set-marker rend nil)))))))
15068 (defvar org-property-set-functions-alist nil
15069 "Property set function alist.
15070 Each entry should have the following format:
15072 (PROPERTY . READ-FUNCTION)
15074 The read function will be called with the same argument as
15075 `org-completing-read'.")
15077 (defun org-set-property-function (property)
15078 "Get the function that should be used to set PROPERTY.
15079 This is computed according to `org-property-set-functions-alist'."
15080 (or (cdr (assoc property org-property-set-functions-alist))
15081 'org-completing-read))
15083 (defun org-read-property-value (property)
15084 "Read PROPERTY value from user."
15085 (let* ((completion-ignore-case t)
15086 (allowed (org-property-get-allowed-values nil property 'table))
15087 (cur (org-entry-get nil property))
15088 (prompt (concat property " value"
15089 (if (and cur (string-match "\\S-" cur))
15090 (concat " [" cur "]") "") ": "))
15091 (set-function (org-set-property-function property))
15092 (val (if allowed
15093 (funcall set-function prompt allowed nil
15094 (not (get-text-property 0 'org-unrestricted
15095 (caar allowed))))
15096 (let (org-completion-use-ido org-completion-use-iswitchb)
15097 (funcall set-function prompt
15098 (mapcar 'list (org-property-values property))
15099 nil nil "" nil cur)))))
15100 (if (equal val "")
15102 val)))
15104 (defvar org-last-set-property nil)
15105 (defvar org-last-set-property-value nil)
15106 (defun org-read-property-name ()
15107 "Read a property name."
15108 (let* ((completion-ignore-case t)
15109 (keys (org-buffer-property-keys nil t t))
15110 (default-prop (or (save-excursion
15111 (save-match-data
15112 (beginning-of-line)
15113 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15114 (null (string= (match-string 1) "END"))
15115 (match-string 1))))
15116 org-last-set-property))
15117 (property (org-icompleting-read
15118 (concat "Property"
15119 (if default-prop (concat " [" default-prop "]") "")
15120 ": ")
15121 (mapcar 'list keys)
15122 nil nil nil nil
15123 default-prop)))
15124 (if (member property keys)
15125 property
15126 (or (cdr (assoc (downcase property)
15127 (mapcar (lambda (x) (cons (downcase x) x))
15128 keys)))
15129 property))))
15131 (defun org-set-property-and-value (use-last)
15132 "Allow to set [PROPERTY]: [value] direction from prompt.
15133 When use-default, don't even ask, just use the last
15134 \"[PROPERTY]: [value]\" string from the history."
15135 (interactive "P")
15136 (let* ((completion-ignore-case t)
15137 (pv (or (and use-last org-last-set-property-value)
15138 (org-completing-read
15139 "Enter a \"[Property]: [value]\" pair: "
15140 nil nil nil nil nil
15141 org-last-set-property-value)))
15142 prop val)
15143 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15144 (setq prop (match-string 1 pv)
15145 val (match-string 2 pv))
15146 (org-set-property prop val))))
15148 (defun org-set-property (property value)
15149 "In the current entry, set PROPERTY to VALUE.
15150 When called interactively, this will prompt for a property name, offering
15151 completion on existing and default properties. And then it will prompt
15152 for a value, offering completion either on allowed values (via an inherited
15153 xxx_ALL property) or on existing values in other instances of this property
15154 in the current file."
15155 (interactive (list nil nil))
15156 (let* ((property (or property (org-read-property-name)))
15157 (value (or value (org-read-property-value property)))
15158 (fn (cdr (assoc property org-properties-postprocess-alist))))
15159 (setq org-last-set-property property)
15160 (setq org-last-set-property-value (concat property ": " value))
15161 ;; Possibly postprocess the inserted value:
15162 (when fn (setq value (funcall fn value)))
15163 (unless (equal (org-entry-get nil property) value)
15164 (org-entry-put nil property value))))
15166 (defun org-delete-property (property)
15167 "In the current entry, delete PROPERTY."
15168 (interactive
15169 (let* ((completion-ignore-case t)
15170 (prop (org-icompleting-read "Property: "
15171 (org-entry-properties nil 'standard))))
15172 (list prop)))
15173 (message "Property %s %s" property
15174 (if (org-entry-delete nil property)
15175 "deleted"
15176 "was not present in the entry")))
15178 (defun org-delete-property-globally (property)
15179 "Remove PROPERTY globally, from all entries."
15180 (interactive
15181 (let* ((completion-ignore-case t)
15182 (prop (org-icompleting-read
15183 "Globally remove property: "
15184 (mapcar 'list (org-buffer-property-keys)))))
15185 (list prop)))
15186 (save-excursion
15187 (save-restriction
15188 (widen)
15189 (goto-char (point-min))
15190 (let ((cnt 0))
15191 (while (re-search-forward
15192 (org-re-property property)
15193 nil t)
15194 (setq cnt (1+ cnt))
15195 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15196 (message "Property \"%s\" removed from %d entries" property cnt)))))
15198 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15200 (defun org-compute-property-at-point ()
15201 "Compute the property at point.
15202 This looks for an enclosing column format, extracts the operator and
15203 then applies it to the property in the column format's scope."
15204 (interactive)
15205 (unless (org-at-property-p)
15206 (error "Not at a property"))
15207 (let ((prop (org-match-string-no-properties 2)))
15208 (org-columns-get-format-and-top-level)
15209 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15210 (error "No operator defined for property %s" prop))
15211 (org-columns-compute prop)))
15213 (defvar org-property-allowed-value-functions nil
15214 "Hook for functions supplying allowed values for a specific property.
15215 The functions must take a single argument, the name of the property, and
15216 return a flat list of allowed values. If \":ETC\" is one of
15217 the values, this means that these values are intended as defaults for
15218 completion, but that other values should be allowed too.
15219 The functions must return nil if they are not responsible for this
15220 property.")
15222 (defun org-property-get-allowed-values (pom property &optional table)
15223 "Get allowed values for the property PROPERTY.
15224 When TABLE is non-nil, return an alist that can directly be used for
15225 completion."
15226 (let (vals)
15227 (cond
15228 ((equal property "TODO")
15229 (setq vals (org-with-point-at pom
15230 (append org-todo-keywords-1 '("")))))
15231 ((equal property "PRIORITY")
15232 (let ((n org-lowest-priority))
15233 (while (>= n org-highest-priority)
15234 (push (char-to-string n) vals)
15235 (setq n (1- n)))))
15236 ((member property org-special-properties))
15237 ((setq vals (run-hook-with-args-until-success
15238 'org-property-allowed-value-functions property)))
15240 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15241 (when (and vals (string-match "\\S-" vals))
15242 (setq vals (car (read-from-string (concat "(" vals ")"))))
15243 (setq vals (mapcar (lambda (x)
15244 (cond ((stringp x) x)
15245 ((numberp x) (number-to-string x))
15246 ((symbolp x) (symbol-name x))
15247 (t "???")))
15248 vals)))))
15249 (when (member ":ETC" vals)
15250 (setq vals (remove ":ETC" vals))
15251 (org-add-props (car vals) '(org-unrestricted t)))
15252 (if table (mapcar 'list vals) vals)))
15254 (defun org-property-previous-allowed-value (&optional previous)
15255 "Switch to the next allowed value for this property."
15256 (interactive)
15257 (org-property-next-allowed-value t))
15259 (defun org-property-next-allowed-value (&optional previous)
15260 "Switch to the next allowed value for this property."
15261 (interactive)
15262 (unless (org-at-property-p)
15263 (error "Not at a property"))
15264 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15265 (key (match-string 2))
15266 (value (match-string 3))
15267 (allowed (or (org-property-get-allowed-values (point) key)
15268 (and (member value '("[ ]" "[-]" "[X]"))
15269 '("[ ]" "[X]"))))
15270 nval)
15271 (unless allowed
15272 (error "Allowed values for this property have not been defined"))
15273 (if previous (setq allowed (reverse allowed)))
15274 (if (member value allowed)
15275 (setq nval (car (cdr (member value allowed)))))
15276 (setq nval (or nval (car allowed)))
15277 (if (equal nval value)
15278 (error "Only one allowed value for this property"))
15279 (org-at-property-p)
15280 (replace-match (concat " :" key ": " nval) t t)
15281 (org-indent-line)
15282 (beginning-of-line 1)
15283 (skip-chars-forward " \t")
15284 (when (equal prop org-effort-property)
15285 (save-excursion
15286 (org-back-to-heading t)
15287 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval)))
15288 (run-hook-with-args 'org-property-changed-functions key nval)))
15290 (defun org-find-olp (path &optional this-buffer)
15291 "Return a marker pointing to the entry at outline path OLP.
15292 If anything goes wrong, throw an error.
15293 You can wrap this call to catch the error like this:
15295 (condition-case msg
15296 (org-mobile-locate-entry (match-string 4))
15297 (error (nth 1 msg)))
15299 The return value will then be either a string with the error message,
15300 or a marker if everything is OK.
15302 If THIS-BUFFER is set, the outline path does not contain a file,
15303 only headings."
15304 (let* ((file (if this-buffer buffer-file-name (pop path)))
15305 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15306 (level 1)
15307 (lmin 1)
15308 (lmax 1)
15309 limit re end found pos heading cnt flevel)
15310 (unless buffer (error "File not found :%s" file))
15311 (with-current-buffer buffer
15312 (save-excursion
15313 (save-restriction
15314 (widen)
15315 (setq limit (point-max))
15316 (goto-char (point-min))
15317 (while (setq heading (pop path))
15318 (setq re (format org-complex-heading-regexp-format
15319 (regexp-quote heading)))
15320 (setq cnt 0 pos (point))
15321 (while (re-search-forward re end t)
15322 (setq level (- (match-end 1) (match-beginning 1)))
15323 (if (and (>= level lmin) (<= level lmax))
15324 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15325 (when (= cnt 0) (error "Heading not found on level %d: %s"
15326 lmax heading))
15327 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15328 lmax heading))
15329 (goto-char found)
15330 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15331 (setq end (save-excursion (org-end-of-subtree t t))))
15332 (when (org-at-heading-p)
15333 (point-marker)))))))
15335 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15336 "Find node HEADING in BUFFER.
15337 Return a marker to the heading if it was found, or nil if not.
15338 If POS-ONLY is set, return just the position instead of a marker.
15340 The heading text must match exact, but it may have a TODO keyword,
15341 a priority cookie and tags in the standard locations."
15342 (with-current-buffer (or buffer (current-buffer))
15343 (save-excursion
15344 (save-restriction
15345 (widen)
15346 (goto-char (point-min))
15347 (let (case-fold-search)
15348 (if (re-search-forward
15349 (format org-complex-heading-regexp-format
15350 (regexp-quote heading)) nil t)
15351 (if pos-only
15352 (match-beginning 0)
15353 (move-marker (make-marker) (match-beginning 0)))))))))
15355 (defun org-find-exact-heading-in-directory (heading &optional dir)
15356 "Find Org node headline HEADING in all .org files in directory DIR.
15357 When the target headline is found, return a marker to this location."
15358 (let ((files (directory-files (or dir default-directory)
15359 nil "\\`[^.#].*\\.org\\'"))
15360 file visiting m buffer)
15361 (catch 'found
15362 (while (setq file (pop files))
15363 (message "trying %s" file)
15364 (setq visiting (org-find-base-buffer-visiting file))
15365 (setq buffer (or visiting (find-file-noselect file)))
15366 (setq m (org-find-exact-headline-in-buffer
15367 heading buffer))
15368 (when (and (not m) (not visiting)) (kill-buffer buffer))
15369 (and m (throw 'found m))))))
15371 (defun org-find-entry-with-id (ident)
15372 "Locate the entry that contains the ID property with exact value IDENT.
15373 IDENT can be a string, a symbol or a number, this function will search for
15374 the string representation of it.
15375 Return the position where this entry starts, or nil if there is no such entry."
15376 (interactive "sID: ")
15377 (let ((id (cond
15378 ((stringp ident) ident)
15379 ((symbol-name ident) (symbol-name ident))
15380 ((numberp ident) (number-to-string ident))
15381 (t (error "IDENT %s must be a string, symbol or number" ident))))
15382 (case-fold-search nil))
15383 (save-excursion
15384 (save-restriction
15385 (widen)
15386 (goto-char (point-min))
15387 (when (re-search-forward
15388 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15389 nil t)
15390 (org-back-to-heading t)
15391 (point))))))
15393 ;;;; Timestamps
15395 (defvar org-last-changed-timestamp nil)
15396 (defvar org-last-inserted-timestamp nil
15397 "The last time stamp inserted with `org-insert-time-stamp'.")
15398 (defvar org-time-was-given) ; dynamically scoped parameter
15399 (defvar org-end-time-was-given) ; dynamically scoped parameter
15400 (defvar org-ts-what) ; dynamically scoped parameter
15402 (defun org-time-stamp (arg &optional inactive)
15403 "Prompt for a date/time and insert a time stamp.
15404 If the user specifies a time like HH:MM or if this command is
15405 called with at least one prefix argument, the time stamp contains
15406 the date and the time. Otherwise, only the date is be included.
15408 All parts of a date not specified by the user is filled in from
15409 the current date/time. So if you just press return without
15410 typing anything, the time stamp will represent the current
15411 date/time.
15413 If there is already a timestamp at the cursor, it will be
15414 modified.
15416 With two universal prefix arguments, insert an active timestamp
15417 with the current time without prompting the user."
15418 (interactive "P")
15419 (let* ((ts nil)
15420 (default-time
15421 ;; Default time is either today, or, when entering a range,
15422 ;; the range start.
15423 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15424 (save-excursion
15425 (re-search-backward
15426 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15427 (- (point) 20) t)))
15428 (apply 'encode-time (org-parse-time-string (match-string 1)))
15429 (current-time)))
15430 (default-input (and ts (org-get-compact-tod ts)))
15431 (repeater (save-excursion
15432 (save-match-data
15433 (beginning-of-line)
15434 (when (re-search-forward
15435 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15436 (save-excursion (progn (end-of-line) (point))) t)
15437 (match-string 0)))))
15438 org-time-was-given org-end-time-was-given time)
15439 (cond
15440 ((and (org-at-timestamp-p t)
15441 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15442 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15443 (insert "--")
15444 (setq time (let ((this-command this-command))
15445 (org-read-date arg 'totime nil nil
15446 default-time default-input inactive)))
15447 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15448 ((org-at-timestamp-p t)
15449 (setq time (let ((this-command this-command))
15450 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15451 (when (org-at-timestamp-p t) ; just to get the match data
15452 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15453 (replace-match "")
15454 (setq org-last-changed-timestamp
15455 (org-insert-time-stamp
15456 time (or org-time-was-given arg)
15457 inactive nil nil (list org-end-time-was-given)))
15458 (when repeater (goto-char (1- (point))) (insert " " repeater)
15459 (setq org-last-changed-timestamp
15460 (concat (substring org-last-inserted-timestamp 0 -1)
15461 " " repeater ">"))))
15462 (message "Timestamp updated"))
15463 ((equal arg '(16))
15464 (org-insert-time-stamp (current-time) t))
15466 (setq time (let ((this-command this-command))
15467 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15468 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15469 nil nil (list org-end-time-was-given))))))
15471 ;; FIXME: can we use this for something else, like computing time differences?
15472 (defun org-get-compact-tod (s)
15473 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15474 (let* ((t1 (match-string 1 s))
15475 (h1 (string-to-number (match-string 2 s)))
15476 (m1 (string-to-number (match-string 3 s)))
15477 (t2 (and (match-end 4) (match-string 5 s)))
15478 (h2 (and t2 (string-to-number (match-string 6 s))))
15479 (m2 (and t2 (string-to-number (match-string 7 s))))
15480 dh dm)
15481 (if (not t2)
15483 (setq dh (- h2 h1) dm (- m2 m1))
15484 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15485 (concat t1 "+" (number-to-string dh)
15486 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15488 (defun org-time-stamp-inactive (&optional arg)
15489 "Insert an inactive time stamp.
15490 An inactive time stamp is enclosed in square brackets instead of angle
15491 brackets. It is inactive in the sense that it does not trigger agenda entries,
15492 does not link to the calendar and cannot be changed with the S-cursor keys.
15493 So these are more for recording a certain time/date."
15494 (interactive "P")
15495 (org-time-stamp arg 'inactive))
15497 (defvar org-date-ovl (make-overlay 1 1))
15498 (overlay-put org-date-ovl 'face 'org-date-selected)
15499 (org-detach-overlay org-date-ovl)
15501 (defvar org-ans1) ; dynamically scoped parameter
15502 (defvar org-ans2) ; dynamically scoped parameter
15504 (defvar org-plain-time-of-day-regexp) ; defined below
15506 (defvar org-overriding-default-time nil) ; dynamically scoped
15507 (defvar org-read-date-overlay nil)
15508 (defvar org-dcst nil) ; dynamically scoped
15509 (defvar org-read-date-history nil)
15510 (defvar org-read-date-final-answer nil)
15511 (defvar org-read-date-analyze-futurep nil)
15512 (defvar org-read-date-analyze-forced-year nil)
15513 (defvar org-read-date-inactive)
15515 (defvar org-read-date-minibuffer-local-map
15516 (let ((map (make-sparse-keymap)))
15517 (set-keymap-parent map minibuffer-local-map)
15518 (org-defkey map [(meta shift left)]
15519 (lambda () (interactive)
15520 (org-eval-in-calendar '(calendar-backward-month 1))))
15521 (org-defkey map [(meta shift right)]
15522 (lambda () (interactive)
15523 (org-eval-in-calendar '(calendar-forward-month 1))))
15524 (org-defkey map [(meta shift up)]
15525 (lambda () (interactive)
15526 (org-eval-in-calendar '(calendar-backward-year 1))))
15527 (org-defkey map [(meta shift down)]
15528 (lambda () (interactive)
15529 (org-eval-in-calendar '(calendar-forward-year 1))))
15530 (org-defkey map [?\e (shift left)]
15531 (lambda () (interactive)
15532 (org-eval-in-calendar '(calendar-backward-month 1))))
15533 (org-defkey map [?\e (shift right)]
15534 (lambda () (interactive)
15535 (org-eval-in-calendar '(calendar-forward-month 1))))
15536 (org-defkey map [?\e (shift up)]
15537 (lambda () (interactive)
15538 (org-eval-in-calendar '(calendar-backward-year 1))))
15539 (org-defkey map [?\e (shift down)]
15540 (lambda () (interactive)
15541 (org-eval-in-calendar '(calendar-forward-year 1))))
15542 (org-defkey map [(shift up)]
15543 (lambda () (interactive)
15544 (org-eval-in-calendar '(calendar-backward-week 1))))
15545 (org-defkey map [(shift down)]
15546 (lambda () (interactive)
15547 (org-eval-in-calendar '(calendar-forward-week 1))))
15548 (org-defkey map [(shift left)]
15549 (lambda () (interactive)
15550 (org-eval-in-calendar '(calendar-backward-day 1))))
15551 (org-defkey map [(shift right)]
15552 (lambda () (interactive)
15553 (org-eval-in-calendar '(calendar-forward-day 1))))
15554 (org-defkey map "?"
15555 (lambda () (interactive)
15556 (org-eval-in-calendar '(diary-view-entries))
15557 (message "")))
15558 (org-defkey map ">"
15559 (lambda () (interactive)
15560 (org-eval-in-calendar '(scroll-calendar-left 1))))
15561 (org-defkey map "<"
15562 (lambda () (interactive)
15563 (org-eval-in-calendar '(scroll-calendar-right 1))))
15564 (org-defkey map "\C-v"
15565 (lambda () (interactive)
15566 (org-eval-in-calendar
15567 '(calendar-scroll-left-three-months 1))))
15568 (org-defkey map "\M-v"
15569 (lambda () (interactive)
15570 (org-eval-in-calendar
15571 '(calendar-scroll-right-three-months 1))))
15572 map)
15573 "Keymap for minibuffer commands when using `org-read-date'.")
15575 (defun org-read-date (&optional org-with-time to-time from-string prompt
15576 default-time default-input inactive)
15577 "Read a date, possibly a time, and make things smooth for the user.
15578 The prompt will suggest to enter an ISO date, but you can also enter anything
15579 which will at least partially be understood by `parse-time-string'.
15580 Unrecognized parts of the date will default to the current day, month, year,
15581 hour and minute. If this command is called to replace a timestamp at point,
15582 or to enter the second timestamp of a range, the default time is taken
15583 from the existing stamp. Furthermore, the command prefers the future,
15584 so if you are giving a date where the year is not given, and the day-month
15585 combination is already past in the current year, it will assume you
15586 mean next year. For details, see the manual. A few examples:
15588 3-2-5 --> 2003-02-05
15589 feb 15 --> currentyear-02-15
15590 2/15 --> currentyear-02-15
15591 sep 12 9 --> 2009-09-12
15592 12:45 --> today 12:45
15593 22 sept 0:34 --> currentyear-09-22 0:34
15594 12 --> currentyear-currentmonth-12
15595 Fri --> nearest Friday (today or later)
15596 etc.
15598 Furthermore you can specify a relative date by giving, as the *first* thing
15599 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15600 change in days weeks, months, years.
15601 With a single plus or minus, the date is relative to today. With a double
15602 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15603 +4d --> four days from today
15604 +4 --> same as above
15605 +2w --> two weeks from today
15606 ++5 --> five days from default date
15608 The function understands only English month and weekday abbreviations.
15610 While prompting, a calendar is popped up - you can also select the
15611 date with the mouse (button 1). The calendar shows a period of three
15612 months. To scroll it to other months, use the keys `>' and `<'.
15613 If you don't like the calendar, turn it off with
15614 \(setq org-read-date-popup-calendar nil)
15616 With optional argument TO-TIME, the date will immediately be converted
15617 to an internal time.
15618 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15619 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15620 still enter a time, and this function will inform the calling routine
15621 about this change. The calling routine may then choose to change the
15622 format used to insert the time stamp into the buffer to include the time.
15623 With optional argument FROM-STRING, read from this string instead from
15624 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15625 the time/date that is used for everything that is not specified by the
15626 user."
15627 (require 'parse-time)
15628 (let* ((org-time-stamp-rounding-minutes
15629 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15630 (org-dcst org-display-custom-times)
15631 (ct (org-current-time))
15632 (org-def (or org-overriding-default-time default-time ct))
15633 (org-defdecode (decode-time org-def))
15634 (dummy (progn
15635 (when (< (nth 2 org-defdecode) org-extend-today-until)
15636 (setcar (nthcdr 2 org-defdecode) -1)
15637 (setcar (nthcdr 1 org-defdecode) 59)
15638 (setq org-def (apply 'encode-time org-defdecode)
15639 org-defdecode (decode-time org-def)))))
15640 (mouse-autoselect-window nil) ; Don't let the mouse jump
15641 (calendar-frame-setup nil)
15642 (calendar-setup nil)
15643 (calendar-move-hook nil)
15644 (calendar-view-diary-initially-flag nil)
15645 (calendar-view-holidays-initially-flag nil)
15646 (timestr (format-time-string
15647 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15648 (prompt (concat (if prompt (concat prompt " ") "")
15649 (format "Date+time [%s]: " timestr)))
15650 ans (org-ans0 "") org-ans1 org-ans2 final)
15652 (cond
15653 (from-string (setq ans from-string))
15654 (org-read-date-popup-calendar
15655 (save-excursion
15656 (save-window-excursion
15657 (calendar)
15658 (org-eval-in-calendar '(setq cursor-type nil) t)
15659 (unwind-protect
15660 (progn
15661 (calendar-forward-day (- (time-to-days org-def)
15662 (calendar-absolute-from-gregorian
15663 (calendar-current-date))))
15664 (org-eval-in-calendar nil t)
15665 (let* ((old-map (current-local-map))
15666 (map (copy-keymap calendar-mode-map))
15667 (minibuffer-local-map
15668 (copy-keymap org-read-date-minibuffer-local-map)))
15669 (org-defkey map (kbd "RET") 'org-calendar-select)
15670 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15671 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15672 (unwind-protect
15673 (progn
15674 (use-local-map map)
15675 (setq org-read-date-inactive inactive)
15676 (add-hook 'post-command-hook 'org-read-date-display)
15677 (setq org-ans0 (read-string prompt default-input
15678 'org-read-date-history nil))
15679 ;; org-ans0: from prompt
15680 ;; org-ans1: from mouse click
15681 ;; org-ans2: from calendar motion
15682 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15683 (remove-hook 'post-command-hook 'org-read-date-display)
15684 (use-local-map old-map)
15685 (when org-read-date-overlay
15686 (delete-overlay org-read-date-overlay)
15687 (setq org-read-date-overlay nil)))))
15688 (bury-buffer "*Calendar*")))))
15690 (t ; Naked prompt only
15691 (unwind-protect
15692 (setq ans (read-string prompt default-input
15693 'org-read-date-history timestr))
15694 (when org-read-date-overlay
15695 (delete-overlay org-read-date-overlay)
15696 (setq org-read-date-overlay nil)))))
15698 (setq final (org-read-date-analyze ans org-def org-defdecode))
15700 (when org-read-date-analyze-forced-year
15701 (message "Year was forced into %s"
15702 (if org-read-date-force-compatible-dates
15703 "compatible range (1970-2037)"
15704 "range representable on this machine"))
15705 (ding))
15707 ;; One round trip to get rid of 34th of August and stuff like that....
15708 (setq final (decode-time (apply 'encode-time final)))
15710 (setq org-read-date-final-answer ans)
15712 (if to-time
15713 (apply 'encode-time final)
15714 (if (and (boundp 'org-time-was-given) org-time-was-given)
15715 (format "%04d-%02d-%02d %02d:%02d"
15716 (nth 5 final) (nth 4 final) (nth 3 final)
15717 (nth 2 final) (nth 1 final))
15718 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15720 (defvar org-def)
15721 (defvar org-defdecode)
15722 (defvar org-with-time)
15723 (defun org-read-date-display ()
15724 "Display the current date prompt interpretation in the minibuffer."
15725 (when org-read-date-display-live
15726 (when org-read-date-overlay
15727 (delete-overlay org-read-date-overlay))
15728 (when (minibufferp (current-buffer))
15729 (save-excursion
15730 (end-of-line 1)
15731 (while (not (equal (buffer-substring
15732 (max (point-min) (- (point) 4)) (point))
15733 " "))
15734 (insert " ")))
15735 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15736 " " (or org-ans1 org-ans2)))
15737 (org-end-time-was-given nil)
15738 (f (org-read-date-analyze ans org-def org-defdecode))
15739 (fmts (if org-dcst
15740 org-time-stamp-custom-formats
15741 org-time-stamp-formats))
15742 (fmt (if (or org-with-time
15743 (and (boundp 'org-time-was-given) org-time-was-given))
15744 (cdr fmts)
15745 (car fmts)))
15746 (txt (format-time-string fmt (apply 'encode-time f)))
15747 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15748 (txt (concat "=> " txt)))
15749 (when (and org-end-time-was-given
15750 (string-match org-plain-time-of-day-regexp txt))
15751 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15752 org-end-time-was-given
15753 (substring txt (match-end 0)))))
15754 (when org-read-date-analyze-futurep
15755 (setq txt (concat txt " (=>F)")))
15756 (setq org-read-date-overlay
15757 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15758 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15760 (defun org-read-date-analyze (ans org-def org-defdecode)
15761 "Analyze the combined answer of the date prompt."
15762 ;; FIXME: cleanup and comment
15763 (let ((nowdecode (decode-time (current-time)))
15764 delta deltan deltaw deltadef year month day
15765 hour minute second wday pm h2 m2 tl wday1
15766 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15767 (setq org-read-date-analyze-futurep nil
15768 org-read-date-analyze-forced-year nil)
15769 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15770 (setq ans "+0"))
15772 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15773 (setq ans (replace-match "" t t ans)
15774 deltan (car delta)
15775 deltaw (nth 1 delta)
15776 deltadef (nth 2 delta)))
15778 ;; Check if there is an iso week date in there. If yes, store the
15779 ;; info and postpone interpreting it until the rest of the parsing
15780 ;; is done.
15781 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15782 (setq iso-year (if (match-end 1)
15783 (org-small-year-to-year
15784 (string-to-number (match-string 1 ans))))
15785 iso-weekday (if (match-end 3)
15786 (string-to-number (match-string 3 ans)))
15787 iso-week (string-to-number (match-string 2 ans)))
15788 (setq ans (replace-match "" t t ans)))
15790 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15791 (when (string-match
15792 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15793 (setq year (if (match-end 2)
15794 (string-to-number (match-string 2 ans))
15795 (progn (setq kill-year t)
15796 (string-to-number (format-time-string "%Y"))))
15797 month (string-to-number (match-string 3 ans))
15798 day (string-to-number (match-string 4 ans)))
15799 (if (< year 100) (setq year (+ 2000 year)))
15800 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15801 t nil ans)))
15803 ;; Help matching dotted european dates
15804 (when (string-match
15805 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15806 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15807 (setq kill-year t)
15808 (string-to-number (format-time-string "%Y")))
15809 day (string-to-number (match-string 1 ans))
15810 month (string-to-number (match-string 2 ans))
15811 ans (replace-match (format "%04d-%02d-%02d" year month day)
15812 t nil ans)))
15814 ;; Help matching american dates, like 5/30 or 5/30/7
15815 (when (string-match
15816 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15817 (setq year (if (match-end 4)
15818 (string-to-number (match-string 4 ans))
15819 (progn (setq kill-year t)
15820 (string-to-number (format-time-string "%Y"))))
15821 month (string-to-number (match-string 1 ans))
15822 day (string-to-number (match-string 2 ans)))
15823 (if (< year 100) (setq year (+ 2000 year)))
15824 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15825 t nil ans)))
15826 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15827 ;; If there is a time with am/pm, and *no* time without it, we convert
15828 ;; so that matching will be successful.
15829 (loop for i from 1 to 2 do ; twice, for end time as well
15830 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15831 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15832 (setq hour (string-to-number (match-string 1 ans))
15833 minute (if (match-end 3)
15834 (string-to-number (match-string 3 ans))
15836 pm (equal ?p
15837 (string-to-char (downcase (match-string 4 ans)))))
15838 (if (and (= hour 12) (not pm))
15839 (setq hour 0)
15840 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15841 (setq ans (replace-match (format "%02d:%02d" hour minute)
15842 t t ans))))
15844 ;; Check if a time range is given as a duration
15845 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15846 (setq hour (string-to-number (match-string 1 ans))
15847 h2 (+ hour (string-to-number (match-string 3 ans)))
15848 minute (string-to-number (match-string 2 ans))
15849 m2 (+ minute (if (match-end 5) (string-to-number
15850 (match-string 5 ans))0)))
15851 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15852 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15853 t t ans)))
15855 ;; Check if there is a time range
15856 (when (boundp 'org-end-time-was-given)
15857 (setq org-time-was-given nil)
15858 (when (and (string-match org-plain-time-of-day-regexp ans)
15859 (match-end 8))
15860 (setq org-end-time-was-given (match-string 8 ans))
15861 (setq ans (concat (substring ans 0 (match-beginning 7))
15862 (substring ans (match-end 7))))))
15864 (setq tl (parse-time-string ans)
15865 day (or (nth 3 tl) (nth 3 org-defdecode))
15866 month (or (nth 4 tl)
15867 (if (and org-read-date-prefer-future
15868 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15869 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15870 (nth 4 org-defdecode)))
15871 year (or (and (not kill-year) (nth 5 tl))
15872 (if (and org-read-date-prefer-future
15873 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15874 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15875 (nth 5 org-defdecode)))
15876 hour (or (nth 2 tl) (nth 2 org-defdecode))
15877 minute (or (nth 1 tl) (nth 1 org-defdecode))
15878 second (or (nth 0 tl) 0)
15879 wday (nth 6 tl))
15881 (when (and (eq org-read-date-prefer-future 'time)
15882 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15883 (equal day (nth 3 nowdecode))
15884 (equal month (nth 4 nowdecode))
15885 (equal year (nth 5 nowdecode))
15886 (nth 2 tl)
15887 (or (< (nth 2 tl) (nth 2 nowdecode))
15888 (and (= (nth 2 tl) (nth 2 nowdecode))
15889 (nth 1 tl)
15890 (< (nth 1 tl) (nth 1 nowdecode)))))
15891 (setq day (1+ day)
15892 futurep t))
15894 ;; Special date definitions below
15895 (cond
15896 (iso-week
15897 ;; There was an iso week
15898 (require 'cal-iso)
15899 (setq futurep nil)
15900 (setq year (or iso-year year)
15901 day (or iso-weekday wday 1)
15902 wday nil ; to make sure that the trigger below does not match
15903 iso-date (calendar-gregorian-from-absolute
15904 (calendar-absolute-from-iso
15905 (list iso-week day year))))
15906 ; FIXME: Should we also push ISO weeks into the future?
15907 ; (when (and org-read-date-prefer-future
15908 ; (not iso-year)
15909 ; (< (calendar-absolute-from-gregorian iso-date)
15910 ; (time-to-days (current-time))))
15911 ; (setq year (1+ year)
15912 ; iso-date (calendar-gregorian-from-absolute
15913 ; (calendar-absolute-from-iso
15914 ; (list iso-week day year)))))
15915 (setq month (car iso-date)
15916 year (nth 2 iso-date)
15917 day (nth 1 iso-date)))
15918 (deltan
15919 (setq futurep nil)
15920 (unless deltadef
15921 (let ((now (decode-time (current-time))))
15922 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15923 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15924 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15925 ((equal deltaw "m") (setq month (+ month deltan)))
15926 ((equal deltaw "y") (setq year (+ year deltan)))))
15927 ((and wday (not (nth 3 tl)))
15928 ;; Weekday was given, but no day, so pick that day in the week
15929 ;; on or after the derived date.
15930 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15931 (unless (equal wday wday1)
15932 (setq day (+ day (% (- wday wday1 -7) 7))))))
15933 (if (and (boundp 'org-time-was-given)
15934 (nth 2 tl))
15935 (setq org-time-was-given t))
15936 (if (< year 100) (setq year (+ 2000 year)))
15937 ;; Check of the date is representable
15938 (if org-read-date-force-compatible-dates
15939 (progn
15940 (if (< year 1970)
15941 (setq year 1970 org-read-date-analyze-forced-year t))
15942 (if (> year 2037)
15943 (setq year 2037 org-read-date-analyze-forced-year t)))
15944 (condition-case nil
15945 (ignore (encode-time second minute hour day month year))
15946 (error
15947 (setq year (nth 5 org-defdecode))
15948 (setq org-read-date-analyze-forced-year t))))
15949 (setq org-read-date-analyze-futurep futurep)
15950 (list second minute hour day month year)))
15952 (defvar parse-time-weekdays)
15953 (defun org-read-date-get-relative (s today default)
15954 "Check string S for special relative date string.
15955 TODAY and DEFAULT are internal times, for today and for a default.
15956 Return shift list (N what def-flag)
15957 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15958 N is the number of WHATs to shift.
15959 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15960 the DEFAULT date rather than TODAY."
15961 (require 'parse-time)
15962 (when (and
15963 (string-match
15964 (concat
15965 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15966 "\\([0-9]+\\)?"
15967 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15968 "\\([ \t]\\|$\\)") s)
15969 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15970 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15971 (string-to-char (substring (match-string 1 s) -1))
15972 ?+))
15973 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15974 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15975 (what (if (match-end 3) (match-string 3 s) "d"))
15976 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15977 (date (if rel default today))
15978 (wday (nth 6 (decode-time date)))
15979 delta)
15980 (if wday1
15981 (progn
15982 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15983 (if (= dir ?-) (setq delta (- delta 7)))
15984 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15985 (list delta "d" rel))
15986 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15988 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15989 "Turn a user-specified date into the internal representation.
15990 The internal representation needed by the calendar is (month day year).
15991 This is a wrapper to handle the brain-dead convention in calendar that
15992 user function argument order change dependent on argument order."
15993 (if (boundp 'calendar-date-style)
15994 (cond
15995 ((eq calendar-date-style 'american)
15996 (list arg1 arg2 arg3))
15997 ((eq calendar-date-style 'european)
15998 (list arg2 arg1 arg3))
15999 ((eq calendar-date-style 'iso)
16000 (list arg2 arg3 arg1)))
16001 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16002 (if (org-bound-and-true-p european-calendar-style)
16003 (list arg2 arg1 arg3)
16004 (list arg1 arg2 arg3)))))
16006 (defun org-eval-in-calendar (form &optional keepdate)
16007 "Eval FORM in the calendar window and return to current window.
16008 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16009 otherwise stick to the current value of `org-ans2'."
16010 (let ((sf (selected-frame))
16011 (sw (selected-window)))
16012 (select-window (get-buffer-window "*Calendar*" t))
16013 (eval form)
16014 (when (and (not keepdate) (calendar-cursor-to-date))
16015 (let* ((date (calendar-cursor-to-date))
16016 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16017 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16018 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16019 (select-window sw)
16020 (org-select-frame-set-input-focus sf)))
16022 (defun org-calendar-select ()
16023 "Return to `org-read-date' with the date currently selected.
16024 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16025 (interactive)
16026 (when (calendar-cursor-to-date)
16027 (let* ((date (calendar-cursor-to-date))
16028 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16029 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16030 (if (active-minibuffer-window) (exit-minibuffer))))
16032 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16033 "Insert a date stamp for the date given by the internal TIME.
16034 WITH-HM means use the stamp format that includes the time of the day.
16035 INACTIVE means use square brackets instead of angular ones, so that the
16036 stamp will not contribute to the agenda.
16037 PRE and POST are optional strings to be inserted before and after the
16038 stamp.
16039 The command returns the inserted time stamp."
16040 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16041 stamp)
16042 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16043 (insert-before-markers (or pre ""))
16044 (when (listp extra)
16045 (setq extra (car extra))
16046 (if (and (stringp extra)
16047 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16048 (setq extra (format "-%02d:%02d"
16049 (string-to-number (match-string 1 extra))
16050 (string-to-number (match-string 2 extra))))
16051 (setq extra nil)))
16052 (when extra
16053 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16054 (insert-before-markers (setq stamp (format-time-string fmt time)))
16055 (insert-before-markers (or post ""))
16056 (setq org-last-inserted-timestamp stamp)))
16058 (defun org-toggle-time-stamp-overlays ()
16059 "Toggle the use of custom time stamp formats."
16060 (interactive)
16061 (setq org-display-custom-times (not org-display-custom-times))
16062 (unless org-display-custom-times
16063 (let ((p (point-min)) (bmp (buffer-modified-p)))
16064 (while (setq p (next-single-property-change p 'display))
16065 (if (and (get-text-property p 'display)
16066 (eq (get-text-property p 'face) 'org-date))
16067 (remove-text-properties
16068 p (setq p (next-single-property-change p 'display))
16069 '(display t))))
16070 (set-buffer-modified-p bmp)))
16071 (if (featurep 'xemacs)
16072 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16073 (org-restart-font-lock)
16074 (setq org-table-may-need-update t)
16075 (if org-display-custom-times
16076 (message "Time stamps are overlaid with custom format")
16077 (message "Time stamp overlays removed")))
16079 (defun org-display-custom-time (beg end)
16080 "Overlay modified time stamp format over timestamp between BEG and END."
16081 (let* ((ts (buffer-substring beg end))
16082 t1 w1 with-hm tf time str w2 (off 0))
16083 (save-match-data
16084 (setq t1 (org-parse-time-string ts t))
16085 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16086 (setq off (- (match-end 0) (match-beginning 0)))))
16087 (setq end (- end off))
16088 (setq w1 (- end beg)
16089 with-hm (and (nth 1 t1) (nth 2 t1))
16090 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16091 time (org-fix-decoded-time t1)
16092 str (org-add-props
16093 (format-time-string
16094 (substring tf 1 -1) (apply 'encode-time time))
16095 nil 'mouse-face 'highlight)
16096 w2 (length str))
16097 (if (not (= w2 w1))
16098 (add-text-properties (1+ beg) (+ 2 beg)
16099 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16100 (if (featurep 'xemacs)
16101 (progn
16102 (put-text-property beg end 'invisible t)
16103 (put-text-property beg end 'end-glyph (make-glyph str)))
16104 (put-text-property beg end 'display str))))
16106 (defun org-translate-time (string)
16107 "Translate all timestamps in STRING to custom format.
16108 But do this only if the variable `org-display-custom-times' is set."
16109 (when org-display-custom-times
16110 (save-match-data
16111 (let* ((start 0)
16112 (re org-ts-regexp-both)
16113 t1 with-hm inactive tf time str beg end)
16114 (while (setq start (string-match re string start))
16115 (setq beg (match-beginning 0)
16116 end (match-end 0)
16117 t1 (save-match-data
16118 (org-parse-time-string (substring string beg end) t))
16119 with-hm (and (nth 1 t1) (nth 2 t1))
16120 inactive (equal (substring string beg (1+ beg)) "[")
16121 tf (funcall (if with-hm 'cdr 'car)
16122 org-time-stamp-custom-formats)
16123 time (org-fix-decoded-time t1)
16124 str (format-time-string
16125 (concat
16126 (if inactive "[" "<") (substring tf 1 -1)
16127 (if inactive "]" ">"))
16128 (apply 'encode-time time))
16129 string (replace-match str t t string)
16130 start (+ start (length str)))))))
16131 string)
16133 (defun org-fix-decoded-time (time)
16134 "Set 0 instead of nil for the first 6 elements of time.
16135 Don't touch the rest."
16136 (let ((n 0))
16137 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16139 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.3")
16141 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16142 "Difference between TIMESTAMP-STRING and now in days.
16143 If SECONDS is non-nil, return the difference in seconds."
16144 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16145 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16146 (funcall fdiff (current-time)))))
16148 (defun org-deadline-close (timestamp-string &optional ndays)
16149 "Is the time in TIMESTAMP-STRING close to the current date?"
16150 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16151 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16152 (not (org-entry-is-done-p))))
16154 (defun org-get-wdays (ts &optional delay zero-delay)
16155 "Get the deadline lead time appropriate for timestring TS.
16156 When DELAY is non-nil, get the delay time for scheduled items
16157 instead of the deadline lead time. When ZERO-DELAY is non-nil
16158 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16159 don't try to find the delay cookie in the scheduled timestamp."
16160 (let ((tv (if delay org-scheduled-delay-days
16161 org-deadline-warning-days)))
16162 (cond
16163 ((or (and delay (< tv 0))
16164 (and delay zero-delay (<= tv 0))
16165 (and (not delay) (<= tv 0)))
16166 ;; Enforce this value no matter what
16167 (- tv))
16168 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16169 ;; lead time is specified.
16170 (floor (* (string-to-number (match-string 1 ts))
16171 (cdr (assoc (match-string 2 ts)
16172 '(("d" . 1) ("w" . 7)
16173 ("m" . 30.4) ("y" . 365.25)
16174 ("h" . 0.041667)))))))
16175 ;; go for the default.
16176 (t tv))))
16178 (defun org-calendar-select-mouse (ev)
16179 "Return to `org-read-date' with the date currently selected.
16180 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16181 (interactive "e")
16182 (mouse-set-point ev)
16183 (when (calendar-cursor-to-date)
16184 (let* ((date (calendar-cursor-to-date))
16185 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16186 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16187 (if (active-minibuffer-window) (exit-minibuffer))))
16189 (defun org-check-deadlines (ndays)
16190 "Check if there are any deadlines due or past due.
16191 A deadline is considered due if it happens within `org-deadline-warning-days'
16192 days from today's date. If the deadline appears in an entry marked DONE,
16193 it is not shown. The prefix arg NDAYS can be used to test that many
16194 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16195 (interactive "P")
16196 (let* ((org-warn-days
16197 (cond
16198 ((equal ndays '(4)) 100000)
16199 (ndays (prefix-numeric-value ndays))
16200 (t (abs org-deadline-warning-days))))
16201 (case-fold-search nil)
16202 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16203 (callback
16204 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16206 (message "%d deadlines past-due or due within %d days"
16207 (org-occur regexp nil callback)
16208 org-warn-days)))
16210 (defsubst org-re-timestamp (type)
16211 "Return a regexp for timestamp TYPE.
16212 Allowed values for TYPE are:
16214 all: all timestamps
16215 active: only active timestamps (<...>)
16216 inactive: only inactive timestamps ([...])
16217 scheduled: only scheduled timestamps
16218 deadline: only deadline timestamps
16220 When TYPE is nil, fall back on returning a regexp that matches
16221 both scheduled and deadline timestamps."
16222 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16223 ((eq type 'active) org-ts-regexp)
16224 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16225 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16226 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16227 ((eq type 'scheduled-or-deadline)
16228 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16230 (defun org-check-before-date (date)
16231 "Check if there are deadlines or scheduled entries before DATE."
16232 (interactive (list (org-read-date)))
16233 (let ((case-fold-search nil)
16234 (regexp (org-re-timestamp org-ts-type))
16235 (callback
16236 (lambda () (time-less-p
16237 (org-time-string-to-time (match-string 1))
16238 (org-time-string-to-time date)))))
16239 (message "%d entries before %s"
16240 (org-occur regexp nil callback) date)))
16242 (defun org-check-after-date (date)
16243 "Check if there are deadlines or scheduled entries after DATE."
16244 (interactive (list (org-read-date)))
16245 (let ((case-fold-search nil)
16246 (regexp (org-re-timestamp org-ts-type))
16247 (callback
16248 (lambda () (not
16249 (time-less-p
16250 (org-time-string-to-time (match-string 1))
16251 (org-time-string-to-time date))))))
16252 (message "%d entries after %s"
16253 (org-occur regexp nil callback) date)))
16255 (defun org-check-dates-range (start-date end-date)
16256 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16257 (interactive (list (org-read-date nil nil nil "Range starts")
16258 (org-read-date nil nil nil "Range end")))
16259 (let ((case-fold-search nil)
16260 (regexp (org-re-timestamp org-ts-type))
16261 (callback
16262 (lambda ()
16263 (let ((match (match-string 1)))
16264 (and
16265 (not (time-less-p
16266 (org-time-string-to-time match)
16267 (org-time-string-to-time start-date)))
16268 (time-less-p
16269 (org-time-string-to-time match)
16270 (org-time-string-to-time end-date)))))))
16271 (message "%d entries between %s and %s"
16272 (org-occur regexp nil callback) start-date end-date)))
16274 (defun org-evaluate-time-range (&optional to-buffer)
16275 "Evaluate a time range by computing the difference between start and end.
16276 Normally the result is just printed in the echo area, but with prefix arg
16277 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16278 If the time range is actually in a table, the result is inserted into the
16279 next column.
16280 For time difference computation, a year is assumed to be exactly 365
16281 days in order to avoid rounding problems."
16282 (interactive "P")
16284 (org-clock-update-time-maybe)
16285 (save-excursion
16286 (unless (org-at-date-range-p t)
16287 (goto-char (point-at-bol))
16288 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16289 (if (not (org-at-date-range-p t))
16290 (error "Not at a time-stamp range, and none found in current line")))
16291 (let* ((ts1 (match-string 1))
16292 (ts2 (match-string 2))
16293 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16294 (match-end (match-end 0))
16295 (time1 (org-time-string-to-time ts1))
16296 (time2 (org-time-string-to-time ts2))
16297 (t1 (org-float-time time1))
16298 (t2 (org-float-time time2))
16299 (diff (abs (- t2 t1)))
16300 (negative (< (- t2 t1) 0))
16301 ;; (ys (floor (* 365 24 60 60)))
16302 (ds (* 24 60 60))
16303 (hs (* 60 60))
16304 (fy "%dy %dd %02d:%02d")
16305 (fy1 "%dy %dd")
16306 (fd "%dd %02d:%02d")
16307 (fd1 "%dd")
16308 (fh "%02d:%02d")
16309 y d h m align)
16310 (if havetime
16311 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16313 d (floor (/ diff ds)) diff (mod diff ds)
16314 h (floor (/ diff hs)) diff (mod diff hs)
16315 m (floor (/ diff 60)))
16316 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16318 d (floor (+ (/ diff ds) 0.5))
16319 h 0 m 0))
16320 (if (not to-buffer)
16321 (message "%s" (org-make-tdiff-string y d h m))
16322 (if (org-at-table-p)
16323 (progn
16324 (goto-char match-end)
16325 (setq align t)
16326 (and (looking-at " *|") (goto-char (match-end 0))))
16327 (goto-char match-end))
16328 (if (looking-at
16329 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16330 (replace-match ""))
16331 (if negative (insert " -"))
16332 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16333 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16334 (insert " " (format fh h m))))
16335 (if align (org-table-align))
16336 (message "Time difference inserted")))))
16338 (defun org-make-tdiff-string (y d h m)
16339 (let ((fmt "")
16340 (l nil))
16341 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16342 l (push y l)))
16343 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16344 l (push d l)))
16345 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16346 l (push h l)))
16347 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16348 l (push m l)))
16349 (apply 'format fmt (nreverse l))))
16351 (defun org-time-string-to-time (s &optional buffer pos)
16352 "Convert a timestamp string into internal time."
16353 (condition-case errdata
16354 (apply 'encode-time (org-parse-time-string s))
16355 (error (error "Bad timestamp `%s'%s\nError was: %s"
16356 s (if (not (and buffer pos))
16358 (format " at %d in buffer `%s'" pos buffer))
16359 (cdr errdata)))))
16361 (defun org-time-string-to-seconds (s)
16362 "Convert a timestamp string to a number of seconds."
16363 (org-float-time (org-time-string-to-time s)))
16365 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16366 "Convert a time stamp to an absolute day number.
16367 If there is a specifier for a cyclic time stamp, get the closest date to
16368 DAYNR.
16369 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16370 The variable date is bound by the calendar when this is called."
16371 (cond
16372 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16373 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16374 daynr
16375 (+ daynr 1000)))
16376 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16377 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16378 (time-to-days (current-time))) (match-string 0 s)
16379 prefer show-all))
16380 (t (time-to-days
16381 (condition-case errdata
16382 (apply 'encode-time (org-parse-time-string s))
16383 (error (error "Bad timestamp `%s'%s\nError was: %s"
16384 s (if (not (and buffer pos))
16386 (format " at %d in buffer `%s'" pos buffer))
16387 (cdr errdata))))))))
16389 (defun org-days-to-iso-week (days)
16390 "Return the iso week number."
16391 (require 'cal-iso)
16392 (car (calendar-iso-from-absolute days)))
16394 (defun org-small-year-to-year (year)
16395 "Convert 2-digit years into 4-digit years.
16396 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16397 The year 2000 cannot be abbreviated. Any year larger than 99
16398 is returned unchanged."
16399 (if (< year 38)
16400 (setq year (+ 2000 year))
16401 (if (< year 100)
16402 (setq year (+ 1900 year))))
16403 year)
16405 (defun org-time-from-absolute (d)
16406 "Return the time corresponding to date D.
16407 D may be an absolute day number, or a calendar-type list (month day year)."
16408 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16409 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16411 (defun org-calendar-holiday ()
16412 "List of holidays, for Diary display in Org-mode."
16413 (require 'holidays)
16414 (let ((hl (funcall
16415 (if (fboundp 'calendar-check-holidays)
16416 'calendar-check-holidays 'check-calendar-holidays) date)))
16417 (if hl (mapconcat 'identity hl "; "))))
16419 (defun org-diary-sexp-entry (sexp entry date)
16420 "Process a SEXP diary ENTRY for DATE."
16421 (require 'diary-lib)
16422 (let ((result (if calendar-debug-sexp
16423 (let ((stack-trace-on-error t))
16424 (eval (car (read-from-string sexp))))
16425 (condition-case nil
16426 (eval (car (read-from-string sexp)))
16427 (error
16428 (beep)
16429 (message "Bad sexp at line %d in %s: %s"
16430 (org-current-line)
16431 (buffer-file-name) sexp)
16432 (sleep-for 2))))))
16433 (cond ((stringp result) (split-string result "; "))
16434 ((and (consp result)
16435 (not (consp (cdr result)))
16436 (stringp (cdr result))) (cdr result))
16437 ((and (consp result)
16438 (stringp (car result))) result)
16439 (result entry))))
16441 (defun org-diary-to-ical-string (frombuf)
16442 "Get iCalendar entries from diary entries in buffer FROMBUF.
16443 This uses the icalendar.el library."
16444 (let* ((tmpdir (if (featurep 'xemacs)
16445 (temp-directory)
16446 temporary-file-directory))
16447 (tmpfile (make-temp-name
16448 (expand-file-name "orgics" tmpdir)))
16449 buf rtn b e)
16450 (with-current-buffer frombuf
16451 (icalendar-export-region (point-min) (point-max) tmpfile)
16452 (setq buf (find-buffer-visiting tmpfile))
16453 (set-buffer buf)
16454 (goto-char (point-min))
16455 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16456 (setq b (match-beginning 0)))
16457 (goto-char (point-max))
16458 (if (re-search-backward "^END:VEVENT" nil t)
16459 (setq e (match-end 0)))
16460 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16461 (kill-buffer buf)
16462 (delete-file tmpfile)
16463 rtn))
16465 (defun org-closest-date (start current change prefer show-all)
16466 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16467 When PREFER is `past', return a date that is either CURRENT or past.
16468 When PREFER is `future', return a date that is either CURRENT or future.
16469 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16470 ;; Make the proper lists from the dates
16471 (catch 'exit
16472 (let ((a1 '(("h" . hour)
16473 ("d" . day)
16474 ("w" . week)
16475 ("m" . month)
16476 ("y" . year)))
16477 (shour (nth 2 (org-parse-time-string start)))
16478 dn dw sday cday n1 n2 n0
16479 d m y y1 y2 date1 date2 nmonths nm ny m2)
16481 (setq start (org-date-to-gregorian start)
16482 current (org-date-to-gregorian
16483 (if show-all
16484 current
16485 (time-to-days (current-time))))
16486 sday (calendar-absolute-from-gregorian start)
16487 cday (calendar-absolute-from-gregorian current))
16489 (if (<= cday sday) (throw 'exit sday))
16491 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16492 (setq dn (string-to-number (match-string 1 change))
16493 dw (cdr (assoc (match-string 2 change) a1)))
16494 (error "Invalid change specifier: %s" change))
16495 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16496 (cond
16497 ((eq dw 'hour)
16498 (let ((missing-hours
16499 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16500 dn)))
16501 (setq n1 (if (zerop missing-hours) cday
16502 (- cday (1+ (floor (/ missing-hours 24)))))
16503 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16504 ((eq dw 'day)
16505 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16506 n2 (+ n1 dn)))
16507 ((eq dw 'year)
16508 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16509 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16510 (setq date1 (list m d y1)
16511 n1 (calendar-absolute-from-gregorian date1)
16512 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16513 n2 (calendar-absolute-from-gregorian date2)))
16514 ((eq dw 'month)
16515 ;; approx number of month between the two dates
16516 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16517 ;; How often does dn fit in there?
16518 (setq d (nth 1 start) m (car start) y (nth 2 start)
16519 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16520 m (+ m nm)
16521 ny (floor (/ m 12))
16522 y (+ y ny)
16523 m (- m (* ny 12)))
16524 (while (> m 12) (setq m (- m 12) y (1+ y)))
16525 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16526 (setq m2 (+ m dn) y2 y)
16527 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16528 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16529 (while (<= n2 cday)
16530 (setq n1 n2 m m2 y y2)
16531 (setq m2 (+ m dn) y2 y)
16532 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16533 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16534 ;; Make sure n1 is the earlier date
16535 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16536 (if show-all
16537 (cond
16538 ((eq prefer 'past) (if (= cday n2) n2 n1))
16539 ((eq prefer 'future) (if (= cday n1) n1 n2))
16540 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16541 (cond
16542 ((eq prefer 'past) (if (= cday n2) n2 n1))
16543 ((eq prefer 'future) (if (= cday n1) n1 n2))
16544 (t (if (= cday n1) n1 n2)))))))
16546 (defun org-date-to-gregorian (date)
16547 "Turn any specification of DATE into a Gregorian date for the calendar."
16548 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16549 ((and (listp date) (= (length date) 3)) date)
16550 ((stringp date)
16551 (setq date (org-parse-time-string date))
16552 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16553 ((listp date)
16554 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16556 (defun org-parse-time-string (s &optional nodefault)
16557 "Parse the standard Org-mode time string.
16558 This should be a lot faster than the normal `parse-time-string'.
16559 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16560 hour and minute fields will be nil if not given."
16561 (cond ((string-match org-ts-regexp0 s)
16562 (list 0
16563 (if (or (match-beginning 8) (not nodefault))
16564 (string-to-number (or (match-string 8 s) "0")))
16565 (if (or (match-beginning 7) (not nodefault))
16566 (string-to-number (or (match-string 7 s) "0")))
16567 (string-to-number (match-string 4 s))
16568 (string-to-number (match-string 3 s))
16569 (string-to-number (match-string 2 s))
16570 nil nil nil))
16571 ((string-match "^<[^>]+>$" s)
16572 (decode-time (seconds-to-time (org-matcher-time s))))
16573 (t (error "Not a standard Org-mode time string: %s" s))))
16575 (defun org-timestamp-up (&optional arg)
16576 "Increase the date item at the cursor by one.
16577 If the cursor is on the year, change the year. If it is on the month,
16578 the day or the time, change that.
16579 With prefix ARG, change by that many units."
16580 (interactive "p")
16581 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16583 (defun org-timestamp-down (&optional arg)
16584 "Decrease the date item at the cursor by one.
16585 If the cursor is on the year, change the year. If it is on the month,
16586 the day or the time, change that.
16587 With prefix ARG, change by that many units."
16588 (interactive "p")
16589 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16591 (defun org-timestamp-up-day (&optional arg)
16592 "Increase the date in the time stamp by one day.
16593 With prefix ARG, change that many days."
16594 (interactive "p")
16595 (if (and (not (org-at-timestamp-p t))
16596 (org-at-heading-p))
16597 (org-todo 'up)
16598 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16600 (defun org-timestamp-down-day (&optional arg)
16601 "Decrease the date in the time stamp by one day.
16602 With prefix ARG, change that many days."
16603 (interactive "p")
16604 (if (and (not (org-at-timestamp-p t))
16605 (org-at-heading-p))
16606 (org-todo 'down)
16607 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16609 (defun org-at-timestamp-p (&optional inactive-ok)
16610 "Determine if the cursor is in or at a timestamp."
16611 (interactive)
16612 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16613 (pos (point))
16614 (ans (or (looking-at tsr)
16615 (save-excursion
16616 (skip-chars-backward "^[<\n\r\t")
16617 (if (> (point) (point-min)) (backward-char 1))
16618 (and (looking-at tsr)
16619 (> (- (match-end 0) pos) -1))))))
16620 (and ans
16621 (boundp 'org-ts-what)
16622 (setq org-ts-what
16623 (cond
16624 ((= pos (match-beginning 0)) 'bracket)
16625 ;; Point is considered to be "on the bracket" whether
16626 ;; it's really on it or right after it.
16627 ((= pos (1- (match-end 0))) 'bracket)
16628 ((= pos (match-end 0)) 'after)
16629 ((org-pos-in-match-range pos 2) 'year)
16630 ((org-pos-in-match-range pos 3) 'month)
16631 ((org-pos-in-match-range pos 7) 'hour)
16632 ((org-pos-in-match-range pos 8) 'minute)
16633 ((or (org-pos-in-match-range pos 4)
16634 (org-pos-in-match-range pos 5)) 'day)
16635 ((and (> pos (or (match-end 8) (match-end 5)))
16636 (< pos (match-end 0)))
16637 (- pos (or (match-end 8) (match-end 5))))
16638 (t 'day))))
16639 ans))
16641 (defun org-toggle-timestamp-type ()
16642 "Toggle the type (<active> or [inactive]) of a time stamp."
16643 (interactive)
16644 (when (org-at-timestamp-p t)
16645 (let ((beg (match-beginning 0)) (end (match-end 0))
16646 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16647 (save-excursion
16648 (goto-char beg)
16649 (while (re-search-forward "[][<>]" end t)
16650 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16651 t t)))
16652 (message "Timestamp is now %sactive"
16653 (if (equal (char-after beg) ?<) "" "in")))))
16655 (defvar org-clock-history) ; defined in org-clock.el
16656 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16657 (defun org-timestamp-change (n &optional what updown)
16658 "Change the date in the time stamp at point.
16659 The date will be changed by N times WHAT. WHAT can be `day', `month',
16660 `year', `minute', `second'. If WHAT is not given, the cursor position
16661 in the timestamp determines what will be changed."
16662 (let ((origin (point)) origin-cat
16663 with-hm inactive
16664 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16665 org-ts-what
16666 extra rem
16667 ts time time0 fixnext clrgx)
16668 (if (not (org-at-timestamp-p t))
16669 (error "Not at a timestamp"))
16670 (if (and (not what) (eq org-ts-what 'bracket))
16671 (org-toggle-timestamp-type)
16672 ;; Point isn't on brackets. Remember the part of the time-stamp
16673 ;; the point was in. Indeed, size of time-stamps may change,
16674 ;; but point must be kept in the same category nonetheless.
16675 (setq origin-cat org-ts-what)
16676 (if (and (not what) (not (eq org-ts-what 'day))
16677 org-display-custom-times
16678 (get-text-property (point) 'display)
16679 (not (get-text-property (1- (point)) 'display)))
16680 (setq org-ts-what 'day))
16681 (setq org-ts-what (or what org-ts-what)
16682 inactive (= (char-after (match-beginning 0)) ?\[)
16683 ts (match-string 0))
16684 (replace-match "")
16685 (if (string-match
16686 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16688 (setq extra (match-string 1 ts)))
16689 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16690 (setq with-hm t))
16691 (setq time0 (org-parse-time-string ts))
16692 (when (and updown
16693 (eq org-ts-what 'minute)
16694 (not current-prefix-arg))
16695 ;; This looks like s-up and s-down. Change by one rounding step.
16696 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16697 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16698 (setcar (cdr time0) (+ (nth 1 time0)
16699 (if (> n 0) (- rem) (- dm rem))))))
16700 (setq time
16701 (encode-time (or (car time0) 0)
16702 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16703 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16704 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16705 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16706 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16707 (nthcdr 6 time0)))
16708 (when (and (member org-ts-what '(hour minute))
16709 extra
16710 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16711 (setq extra (org-modify-ts-extra
16712 extra
16713 (if (eq org-ts-what 'hour) 2 5)
16714 n dm)))
16715 (when (integerp org-ts-what)
16716 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16717 (if (eq what 'calendar)
16718 (let ((cal-date (org-get-date-from-calendar)))
16719 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16720 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16721 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16722 (setcar time0 (or (car time0) 0))
16723 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16724 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16725 (setq time (apply 'encode-time time0))))
16726 ;; Insert the new time-stamp, and ensure point stays in the same
16727 ;; category as before (i.e. not after the last position in that
16728 ;; category).
16729 (let ((pos (point)))
16730 ;; Stay before inserted string. `save-excursion' is of no use.
16731 (setq org-last-changed-timestamp
16732 (org-insert-time-stamp time with-hm inactive nil nil extra))
16733 (goto-char pos))
16734 (save-match-data
16735 (looking-at org-ts-regexp3)
16736 (goto-char (cond
16737 ;; `day' category ends before `hour' if any, or at
16738 ;; the end of the day name.
16739 ((eq origin-cat 'day)
16740 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16741 ((eq origin-cat 'hour) (min (match-end 7) origin))
16742 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16743 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16744 ;; `year' and `month' have both fixed size: point
16745 ;; couldn't have moved into another part.
16746 (t origin))))
16747 ;; Update clock if on a CLOCK line.
16748 (org-clock-update-time-maybe)
16749 ;; Maybe adjust the closest clock in `org-clock-history'
16750 (when org-clock-adjust-closest
16751 (if (not (and (org-at-clock-log-p)
16752 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16753 org-clock-history))))))
16754 (message "No clock to adjust")
16755 (cond ((save-excursion ; fix previous clock?
16756 (re-search-backward org-ts-regexp0 nil t)
16757 (org-looking-back (concat org-clock-string " \\[")))
16758 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16759 ((save-excursion ; fix next clock?
16760 (re-search-backward org-ts-regexp0 nil t)
16761 (looking-at (concat org-ts-regexp0 "\\] =>")))
16762 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16763 (save-window-excursion
16764 ;; Find closest clock to point, adjust the previous/next one in history
16765 (let* ((p (save-excursion (org-back-to-heading t)))
16766 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16767 (clfixnth
16768 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16769 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16770 (if (not clfixpos)
16771 (message "No clock to adjust")
16772 (save-excursion
16773 (org-goto-marker-or-bmk clfixpos)
16774 (org-show-subtree)
16775 (when (re-search-forward clrgx nil t)
16776 (goto-char (match-beginning 1))
16777 (let (org-clock-adjust-closest)
16778 (org-timestamp-change n org-ts-what updown))
16779 (message "Clock adjusted in %s for heading: %s"
16780 (file-name-nondirectory (buffer-file-name))
16781 (org-get-heading t t)))))))))
16782 ;; Try to recenter the calendar window, if any.
16783 (if (and org-calendar-follow-timestamp-change
16784 (get-buffer-window "*Calendar*" t)
16785 (memq org-ts-what '(day month year)))
16786 (org-recenter-calendar (time-to-days time))))))
16788 (defun org-modify-ts-extra (s pos n dm)
16789 "Change the different parts of the lead-time and repeat fields in timestamp."
16790 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16791 ng h m new rem)
16792 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16793 (cond
16794 ((or (org-pos-in-match-range pos 2)
16795 (org-pos-in-match-range pos 3))
16796 (setq m (string-to-number (match-string 3 s))
16797 h (string-to-number (match-string 2 s)))
16798 (if (org-pos-in-match-range pos 2)
16799 (setq h (+ h n))
16800 (setq n (* dm (org-no-warnings (signum n))))
16801 (when (not (= 0 (setq rem (% m dm))))
16802 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16803 (setq m (+ m n)))
16804 (if (< m 0) (setq m (+ m 60) h (1- h)))
16805 (if (> m 59) (setq m (- m 60) h (1+ h)))
16806 (setq h (min 24 (max 0 h)))
16807 (setq ng 1 new (format "-%02d:%02d" h m)))
16808 ((org-pos-in-match-range pos 6)
16809 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16810 ((org-pos-in-match-range pos 5)
16811 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16813 ((org-pos-in-match-range pos 9)
16814 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16815 ((org-pos-in-match-range pos 8)
16816 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16818 (when ng
16819 (setq s (concat
16820 (substring s 0 (match-beginning ng))
16822 (substring s (match-end ng))))))
16825 (defun org-recenter-calendar (date)
16826 "If the calendar is visible, recenter it to DATE."
16827 (let ((cwin (get-buffer-window "*Calendar*" t)))
16828 (when cwin
16829 (let ((calendar-move-hook nil))
16830 (with-selected-window cwin
16831 (calendar-goto-date (if (listp date) date
16832 (calendar-gregorian-from-absolute date))))))))
16834 (defun org-goto-calendar (&optional arg)
16835 "Go to the Emacs calendar at the current date.
16836 If there is a time stamp in the current line, go to that date.
16837 A prefix ARG can be used to force the current date."
16838 (interactive "P")
16839 (let ((tsr org-ts-regexp) diff
16840 (calendar-move-hook nil)
16841 (calendar-view-holidays-initially-flag nil)
16842 (calendar-view-diary-initially-flag nil))
16843 (if (or (org-at-timestamp-p)
16844 (save-excursion
16845 (beginning-of-line 1)
16846 (looking-at (concat ".*" tsr))))
16847 (let ((d1 (time-to-days (current-time)))
16848 (d2 (time-to-days
16849 (org-time-string-to-time (match-string 1)))))
16850 (setq diff (- d2 d1))))
16851 (calendar)
16852 (calendar-goto-today)
16853 (if (and diff (not arg)) (calendar-forward-day diff))))
16855 (defun org-get-date-from-calendar ()
16856 "Return a list (month day year) of date at point in calendar."
16857 (with-current-buffer "*Calendar*"
16858 (save-match-data
16859 (calendar-cursor-to-date))))
16861 (defun org-date-from-calendar ()
16862 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16863 If there is already a time stamp at the cursor position, update it."
16864 (interactive)
16865 (if (org-at-timestamp-p t)
16866 (org-timestamp-change 0 'calendar)
16867 (let ((cal-date (org-get-date-from-calendar)))
16868 (org-insert-time-stamp
16869 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16871 (defcustom org-effort-durations
16872 `(("h" . 60)
16873 ("d" . ,(* 60 8))
16874 ("w" . ,(* 60 8 5))
16875 ("m" . ,(* 60 8 5 4))
16876 ("y" . ,(* 60 8 5 40)))
16877 "Conversion factor to minutes for an effort modifier.
16879 Each entry has the form (MODIFIER . MINUTES).
16881 In an effort string, a number followed by MODIFIER is multiplied
16882 by the specified number of MINUTES to obtain an effort in
16883 minutes.
16885 For example, if the value of this variable is ((\"hours\" . 60)), then an
16886 effort string \"2hours\" is equivalent to 120 minutes."
16887 :group 'org-agenda
16888 :version "24.1"
16889 :type '(alist :key-type (string :tag "Modifier")
16890 :value-type (number :tag "Minutes")))
16892 (defun org-minutes-to-clocksum-string (m)
16893 "Format number of minutes as a clocksum string.
16894 The format is determined by `org-time-clocksum-format',
16895 `org-time-clocksum-use-fractional' and
16896 `org-time-clocksum-fractional-format' and
16897 `org-time-clocksum-use-effort-durations'."
16898 (let ((clocksum "") h d w mo y fmt n)
16899 (setq h (if org-time-clocksum-use-effort-durations
16900 (cdr (assoc "h" org-effort-durations)) 60)
16901 d (if org-time-clocksum-use-effort-durations
16902 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
16903 w (if org-time-clocksum-use-effort-durations
16904 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
16905 mo (if org-time-clocksum-use-effort-durations
16906 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
16907 y (if org-time-clocksum-use-effort-durations
16908 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
16909 ;; fractional format
16910 (if org-time-clocksum-use-fractional
16911 (cond
16912 ;; single format string
16913 ((stringp org-time-clocksum-fractional-format)
16914 (format org-time-clocksum-fractional-format (/ m (float h))))
16915 ;; choice of fractional formats for different time units
16916 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
16917 (> (/ (truncate m) (* y d h)) 0))
16918 (format fmt (/ m (* y d (float h)))))
16919 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
16920 (> (/ (truncate m) (* mo d h)) 0))
16921 (format fmt (/ m (* mo d (float h)))))
16922 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
16923 (> (/ (truncate m) (* w d h)) 0))
16924 (format fmt (/ m (* w d (float h)))))
16925 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
16926 (> (/ (truncate m) (* d h)) 0))
16927 (format fmt (/ m (* d (float h)))))
16928 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
16929 (> (/ (truncate m) h) 0))
16930 (format fmt (/ m (float h))))
16931 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
16932 (format fmt m))
16933 ;; fall back to smallest time unit with a format
16934 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
16935 (format fmt (/ m (float h))))
16936 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
16937 (format fmt (/ m (* d (float h)))))
16938 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
16939 (format fmt (/ m (* w d (float h)))))
16940 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
16941 (format fmt (/ m (* mo d (float h)))))
16942 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
16943 (format fmt (/ m (* y d (float h))))))
16944 ;; standard (non-fractional) format, with single format string
16945 (if (stringp org-time-clocksum-format)
16946 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
16947 ;; separate formats components
16948 (and (setq fmt (plist-get org-time-clocksum-format :years))
16949 (or (> (setq n (/ (truncate m) (* y d h))) 0)
16950 (plist-get org-time-clocksum-format :require-years))
16951 (setq clocksum (concat clocksum (format fmt n))
16952 m (- m (* n y d h))))
16953 (and (setq fmt (plist-get org-time-clocksum-format :months))
16954 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
16955 (plist-get org-time-clocksum-format :require-months))
16956 (setq clocksum (concat clocksum (format fmt n))
16957 m (- m (* n mo d h))))
16958 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
16959 (or (> (setq n (/ (truncate m) (* w d h))) 0)
16960 (plist-get org-time-clocksum-format :require-weeks))
16961 (setq clocksum (concat clocksum (format fmt n))
16962 m (- m (* n w d h))))
16963 (and (setq fmt (plist-get org-time-clocksum-format :days))
16964 (or (> (setq n (/ (truncate m) (* d h))) 0)
16965 (plist-get org-time-clocksum-format :require-days))
16966 (setq clocksum (concat clocksum (format fmt n))
16967 m (- m (* n d h))))
16968 (and (setq fmt (plist-get org-time-clocksum-format :hours))
16969 (or (> (setq n (/ (truncate m) h)) 0)
16970 (plist-get org-time-clocksum-format :require-hours))
16971 (setq clocksum (concat clocksum (format fmt n))
16972 m (- m (* n h))))
16973 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
16974 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
16975 (setq clocksum (concat clocksum (format fmt m))))
16976 ;; return formatted time duration
16977 clocksum))))
16979 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
16980 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
16981 "Org mode version 8.0")
16983 (defun org-hours-to-clocksum-string (n)
16984 (org-minutes-to-clocksum-string (* n 60)))
16986 (defun org-hh:mm-string-to-minutes (s)
16987 "Convert a string H:MM to a number of minutes.
16988 If the string is just a number, interpret it as minutes.
16989 In fact, the first hh:mm or number in the string will be taken,
16990 there can be extra stuff in the string.
16991 If no number is found, the return value is 0."
16992 (cond
16993 ((integerp s) s)
16994 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16995 (+ (* (string-to-number (match-string 1 s)) 60)
16996 (string-to-number (match-string 2 s))))
16997 ((string-match "\\([0-9]+\\)" s)
16998 (string-to-number (match-string 1 s)))
16999 (t 0)))
17001 (defcustom org-image-actual-width t
17002 "Should we use the actual width of images when inlining them?
17004 When set to `t', always use the image width.
17006 When set to a number, use imagemagick (when available) to set
17007 the image's width to this value.
17009 When set to a number in a list, try to get the width from the
17010 #+ATTR.* keyword if it matches a width specification like
17011 width=\"[0-9]+\", and fall back on that number if none is found.
17013 When set to nil, try to get the width from an #+ATTR.* keyword
17014 and fall back on the original width if none is found.
17016 This requires Emacs >= 24.1, build with imagemagick support."
17017 :group 'org-appearance
17018 :version "24.3"
17019 :type '(choice
17020 (const :tag "Use the image width" t)
17021 (integer :tag "Use a number of pixels")
17022 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17023 (const :tag "Use #+ATTR* or don't resize" nil)))
17025 (defcustom org-agenda-inhibit-startup t
17026 "Inhibit startup when preparing agenda buffers.
17027 When this variable is `t' (the default), the initialization of
17028 the Org agenda buffers is inhibited: e.g. the visibility state
17029 is not set, the tables are not re-aligned, etc."
17030 :type 'boolean
17031 :version "24.3"
17032 :group 'org-agenda)
17034 (defun org-duration-string-to-minutes (s &optional output-to-string)
17035 "Convert a duration string S to minutes.
17037 A bare number is interpreted as minutes, modifiers can be set by
17038 customizing `org-effort-durations' (which see).
17040 Entries containing a colon are interpreted as H:MM by
17041 `org-hh:mm-string-to-minutes'."
17042 (let ((result 0)
17043 (re (concat "\\([0-9.]+\\) *\\("
17044 (regexp-opt (mapcar 'car org-effort-durations))
17045 "\\)")))
17046 (while (string-match re s)
17047 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17048 (string-to-number (match-string 1 s))))
17049 (setq s (replace-match "" nil t s)))
17050 (setq result (floor result))
17051 (incf result (org-hh:mm-string-to-minutes s))
17052 (if output-to-string (number-to-string result) result)))
17054 ;;;; Files
17056 (defun org-save-all-org-buffers ()
17057 "Save all Org-mode buffers without user confirmation."
17058 (interactive)
17059 (message "Saving all Org-mode buffers...")
17060 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17061 (when (featurep 'org-id) (org-id-locations-save))
17062 (message "Saving all Org-mode buffers... done"))
17064 (defun org-revert-all-org-buffers ()
17065 "Revert all Org-mode buffers.
17066 Prompt for confirmation when there are unsaved changes.
17067 Be sure you know what you are doing before letting this function
17068 overwrite your changes.
17070 This function is useful in a setup where one tracks org files
17071 with a version control system, to revert on one machine after pulling
17072 changes from another. I believe the procedure must be like this:
17074 1. M-x org-save-all-org-buffers
17075 2. Pull changes from the other machine, resolve conflicts
17076 3. M-x org-revert-all-org-buffers"
17077 (interactive)
17078 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17079 (error "Abort"))
17080 (save-excursion
17081 (save-window-excursion
17082 (mapc
17083 (lambda (b)
17084 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17085 (with-current-buffer b buffer-file-name))
17086 (org-pop-to-buffer-same-window b)
17087 (revert-buffer t 'no-confirm)))
17088 (buffer-list))
17089 (when (and (featurep 'org-id) org-id-track-globally)
17090 (org-id-locations-load)))))
17092 ;;;; Agenda files
17094 ;;;###autoload
17095 (defun org-switchb (&optional arg)
17096 "Switch between Org buffers.
17097 With one prefix argument, restrict available buffers to files.
17098 With two prefix arguments, restrict available buffers to agenda files.
17100 Defaults to `iswitchb' for buffer name completion.
17101 Set `org-completion-use-ido' to make it use ido instead."
17102 (interactive "P")
17103 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17104 ((equal arg '(16)) (org-buffer-list 'agenda))
17105 (t (org-buffer-list))))
17106 (org-completion-use-iswitchb org-completion-use-iswitchb)
17107 (org-completion-use-ido org-completion-use-ido))
17108 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17109 (setq org-completion-use-iswitchb t))
17110 (org-pop-to-buffer-same-window
17111 (org-icompleting-read "Org buffer: "
17112 (mapcar 'list (mapcar 'buffer-name blist))
17113 nil t))))
17115 ;;; Define some older names previously used for this functionality
17116 ;;;###autoload
17117 (defalias 'org-ido-switchb 'org-switchb)
17118 ;;;###autoload
17119 (defalias 'org-iswitchb 'org-switchb)
17121 (defun org-buffer-list (&optional predicate exclude-tmp)
17122 "Return a list of Org buffers.
17123 PREDICATE can be `export', `files' or `agenda'.
17125 export restrict the list to Export buffers.
17126 files restrict the list to buffers visiting Org files.
17127 agenda restrict the list to buffers visiting agenda files.
17129 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17130 (let* ((bfn nil)
17131 (agenda-files (and (eq predicate 'agenda)
17132 (mapcar 'file-truename (org-agenda-files t))))
17133 (filter
17134 (cond
17135 ((eq predicate 'files)
17136 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17137 ((eq predicate 'export)
17138 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17139 ((eq predicate 'agenda)
17140 (lambda (b)
17141 (with-current-buffer b
17142 (and (derived-mode-p 'org-mode)
17143 (setq bfn (buffer-file-name b))
17144 (member (file-truename bfn) agenda-files)))))
17145 (t (lambda (b) (with-current-buffer b
17146 (or (derived-mode-p 'org-mode)
17147 (string-match "\*Org .*Export"
17148 (buffer-name b)))))))))
17149 (delq nil
17150 (mapcar
17151 (lambda(b)
17152 (if (and (funcall filter b)
17153 (or (not exclude-tmp)
17154 (not (string-match "tmp" (buffer-name b)))))
17156 nil))
17157 (buffer-list)))))
17159 (defun org-agenda-files (&optional unrestricted archives)
17160 "Get the list of agenda files.
17161 Optional UNRESTRICTED means return the full list even if a restriction
17162 is currently in place.
17163 When ARCHIVES is t, include all archive files that are really being
17164 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17165 `org-agenda-archives-mode' is t."
17166 (let ((files
17167 (cond
17168 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17169 ((stringp org-agenda-files) (org-read-agenda-file-list))
17170 ((listp org-agenda-files) org-agenda-files)
17171 (t (error "Invalid value of `org-agenda-files'")))))
17172 (setq files (apply 'append
17173 (mapcar (lambda (f)
17174 (if (file-directory-p f)
17175 (directory-files
17176 f t org-agenda-file-regexp)
17177 (list f)))
17178 files)))
17179 (when org-agenda-skip-unavailable-files
17180 (setq files (delq nil
17181 (mapcar (function
17182 (lambda (file)
17183 (and (file-readable-p file) file)))
17184 files))))
17185 (when (or (eq archives t)
17186 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17187 (setq files (org-add-archive-files files)))
17188 files))
17190 (defun org-agenda-file-p (&optional file)
17191 "Return non-nil, if FILE is an agenda file.
17192 If FILE is omitted, use the file associated with the current
17193 buffer."
17194 (member (or file (buffer-file-name))
17195 (org-agenda-files t)))
17197 (defun org-edit-agenda-file-list ()
17198 "Edit the list of agenda files.
17199 Depending on setup, this either uses customize to edit the variable
17200 `org-agenda-files', or it visits the file that is holding the list. In the
17201 latter case, the buffer is set up in a way that saving it automatically kills
17202 the buffer and restores the previous window configuration."
17203 (interactive)
17204 (if (stringp org-agenda-files)
17205 (let ((cw (current-window-configuration)))
17206 (find-file org-agenda-files)
17207 (org-set-local 'org-window-configuration cw)
17208 (org-add-hook 'after-save-hook
17209 (lambda ()
17210 (set-window-configuration
17211 (prog1 org-window-configuration
17212 (kill-buffer (current-buffer))))
17213 (org-install-agenda-files-menu)
17214 (message "New agenda file list installed"))
17215 nil 'local)
17216 (message "%s" (substitute-command-keys
17217 "Edit list and finish with \\[save-buffer]")))
17218 (customize-variable 'org-agenda-files)))
17220 (defun org-store-new-agenda-file-list (list)
17221 "Set new value for the agenda file list and save it correctly."
17222 (if (stringp org-agenda-files)
17223 (let ((fe (org-read-agenda-file-list t)) b u)
17224 (while (setq b (find-buffer-visiting org-agenda-files))
17225 (kill-buffer b))
17226 (with-temp-file org-agenda-files
17227 (insert
17228 (mapconcat
17229 (lambda (f) ;; Keep un-expanded entries.
17230 (if (setq u (assoc f fe))
17231 (cdr u)
17233 list "\n")
17234 "\n")))
17235 (let ((org-mode-hook nil) (org-inhibit-startup t)
17236 (org-insert-mode-line-in-empty-file nil))
17237 (setq org-agenda-files list)
17238 (customize-save-variable 'org-agenda-files org-agenda-files))))
17240 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17241 "Read the list of agenda files from a file.
17242 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17243 filenames, used by `org-store-new-agenda-file-list' to write back
17244 un-expanded file names."
17245 (when (file-directory-p org-agenda-files)
17246 (error "`org-agenda-files' cannot be a single directory"))
17247 (when (stringp org-agenda-files)
17248 (with-temp-buffer
17249 (insert-file-contents org-agenda-files)
17250 (mapcar
17251 (lambda (f)
17252 (let ((e (expand-file-name (substitute-in-file-name f)
17253 org-directory)))
17254 (if pair-with-expansion
17255 (cons e f)
17256 e)))
17257 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17259 ;;;###autoload
17260 (defun org-cycle-agenda-files ()
17261 "Cycle through the files in `org-agenda-files'.
17262 If the current buffer visits an agenda file, find the next one in the list.
17263 If the current buffer does not, find the first agenda file."
17264 (interactive)
17265 (let* ((fs (org-agenda-files t))
17266 (files (append fs (list (car fs))))
17267 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17268 file)
17269 (unless files (error "No agenda files"))
17270 (catch 'exit
17271 (while (setq file (pop files))
17272 (if (equal (file-truename file) tcf)
17273 (when (car files)
17274 (find-file (car files))
17275 (throw 'exit t))))
17276 (find-file (car fs)))
17277 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17279 (defun org-agenda-file-to-front (&optional to-end)
17280 "Move/add the current file to the top of the agenda file list.
17281 If the file is not present in the list, it is added to the front. If it is
17282 present, it is moved there. With optional argument TO-END, add/move to the
17283 end of the list."
17284 (interactive "P")
17285 (let ((org-agenda-skip-unavailable-files nil)
17286 (file-alist (mapcar (lambda (x)
17287 (cons (file-truename x) x))
17288 (org-agenda-files t)))
17289 (ctf (file-truename
17290 (or buffer-file-name
17291 (error "Please save the current buffer to a file"))))
17292 x had)
17293 (setq x (assoc ctf file-alist) had x)
17295 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17296 (if to-end
17297 (setq file-alist (append (delq x file-alist) (list x)))
17298 (setq file-alist (cons x (delq x file-alist))))
17299 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17300 (org-install-agenda-files-menu)
17301 (message "File %s to %s of agenda file list"
17302 (if had "moved" "added") (if to-end "end" "front"))))
17304 (defun org-remove-file (&optional file)
17305 "Remove current file from the list of files in variable `org-agenda-files'.
17306 These are the files which are being checked for agenda entries.
17307 Optional argument FILE means use this file instead of the current."
17308 (interactive)
17309 (let* ((org-agenda-skip-unavailable-files nil)
17310 (file (or file buffer-file-name
17311 (error "Current buffer does not visit a file")))
17312 (true-file (file-truename file))
17313 (afile (abbreviate-file-name file))
17314 (files (delq nil (mapcar
17315 (lambda (x)
17316 (if (equal true-file
17317 (file-truename x))
17318 nil x))
17319 (org-agenda-files t)))))
17320 (if (not (= (length files) (length (org-agenda-files t))))
17321 (progn
17322 (org-store-new-agenda-file-list files)
17323 (org-install-agenda-files-menu)
17324 (message "Removed file: %s" afile))
17325 (message "File was not in list: %s (not removed)" afile))))
17327 (defun org-file-menu-entry (file)
17328 (vector file (list 'find-file file) t))
17330 (defun org-check-agenda-file (file)
17331 "Make sure FILE exists. If not, ask user what to do."
17332 (when (not (file-exists-p file))
17333 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17334 (abbreviate-file-name file))
17335 (let ((r (downcase (read-char-exclusive))))
17336 (cond
17337 ((equal r ?r)
17338 (org-remove-file file)
17339 (throw 'nextfile t))
17340 (t (error "Abort"))))))
17342 (defun org-get-agenda-file-buffer (file)
17343 "Get a buffer visiting FILE. If the buffer needs to be created, add
17344 it to the list of buffers which might be released later."
17345 (let ((buf (org-find-base-buffer-visiting file)))
17346 (if buf
17347 buf ; just return it
17348 ;; Make a new buffer and remember it
17349 (setq buf (find-file-noselect file))
17350 (if buf (push buf org-agenda-new-buffers))
17351 buf)))
17353 (defun org-release-buffers (blist)
17354 "Release all buffers in list, asking the user for confirmation when needed.
17355 When a buffer is unmodified, it is just killed. When modified, it is saved
17356 \(if the user agrees) and then killed."
17357 (let (buf file)
17358 (while (setq buf (pop blist))
17359 (setq file (buffer-file-name buf))
17360 (when (and (buffer-modified-p buf)
17361 file
17362 (y-or-n-p (format "Save file %s? " file)))
17363 (with-current-buffer buf (save-buffer)))
17364 (kill-buffer buf))))
17366 (defun org-agenda-prepare-buffers (files)
17367 "Create buffers for all agenda files, protect archived trees and comments."
17368 (interactive)
17369 (let ((pa '(:org-archived t))
17370 (pc '(:org-comment t))
17371 (pall '(:org-archived t :org-comment t))
17372 (inhibit-read-only t)
17373 (org-inhibit-startup org-agenda-inhibit-startup)
17374 (rea (concat ":" org-archive-tag ":"))
17375 bmp file re)
17376 (save-excursion
17377 (save-restriction
17378 (while (setq file (pop files))
17379 (catch 'nextfile
17380 (if (bufferp file)
17381 (set-buffer file)
17382 (org-check-agenda-file file)
17383 (set-buffer (org-get-agenda-file-buffer file)))
17384 (widen)
17385 (setq bmp (buffer-modified-p))
17386 (org-refresh-category-properties)
17387 (org-refresh-properties org-effort-property 'org-effort)
17388 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17389 (setq org-todo-keywords-for-agenda
17390 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17391 (setq org-done-keywords-for-agenda
17392 (append org-done-keywords-for-agenda org-done-keywords))
17393 (setq org-todo-keyword-alist-for-agenda
17394 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17395 (setq org-drawers-for-agenda
17396 (append org-drawers-for-agenda org-drawers))
17397 (setq org-tag-alist-for-agenda
17398 (append org-tag-alist-for-agenda org-tag-alist))
17400 (save-excursion
17401 (remove-text-properties (point-min) (point-max) pall)
17402 (when org-agenda-skip-archived-trees
17403 (goto-char (point-min))
17404 (while (re-search-forward rea nil t)
17405 (if (org-at-heading-p t)
17406 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17407 (goto-char (point-min))
17408 (setq re (format org-heading-keyword-regexp-format
17409 org-comment-string))
17410 (while (re-search-forward re nil t)
17411 (add-text-properties
17412 (match-beginning 0) (org-end-of-subtree t) pc)))
17413 (set-buffer-modified-p bmp)))))
17414 (setq org-todo-keywords-for-agenda
17415 (org-uniquify org-todo-keywords-for-agenda))
17416 (setq org-todo-keyword-alist-for-agenda
17417 (org-uniquify org-todo-keyword-alist-for-agenda)
17418 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17422 ;;;; CDLaTeX minor mode
17424 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17425 "Keymap for the minor `org-cdlatex-mode'.")
17427 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17428 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17429 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17430 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17431 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17433 (defvar org-cdlatex-texmathp-advice-is-done nil
17434 "Flag remembering if we have applied the advice to texmathp already.")
17436 (define-minor-mode org-cdlatex-mode
17437 "Toggle the minor `org-cdlatex-mode'.
17438 This mode supports entering LaTeX environment and math in LaTeX fragments
17439 in Org-mode.
17440 \\{org-cdlatex-mode-map}"
17441 nil " OCDL" nil
17442 (when org-cdlatex-mode
17443 (require 'cdlatex)
17444 (run-hooks 'cdlatex-mode-hook)
17445 (cdlatex-compute-tables))
17446 (unless org-cdlatex-texmathp-advice-is-done
17447 (setq org-cdlatex-texmathp-advice-is-done t)
17448 (defadvice texmathp (around org-math-always-on activate)
17449 "Always return t in org-mode buffers.
17450 This is because we want to insert math symbols without dollars even outside
17451 the LaTeX math segments. If Orgmode thinks that point is actually inside
17452 an embedded LaTeX fragment, let texmathp do its job.
17453 \\[org-cdlatex-mode-map]"
17454 (interactive)
17455 (let (p)
17456 (cond
17457 ((not (derived-mode-p 'org-mode)) ad-do-it)
17458 ((eq this-command 'cdlatex-math-symbol)
17459 (setq ad-return-value t
17460 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17462 (let ((p (org-inside-LaTeX-fragment-p)))
17463 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17464 (setq ad-return-value t
17465 texmathp-why '("Org-mode embedded math" . 0))
17466 (if p ad-do-it)))))))))
17468 (defun turn-on-org-cdlatex ()
17469 "Unconditionally turn on `org-cdlatex-mode'."
17470 (org-cdlatex-mode 1))
17472 (defun org-try-cdlatex-tab ()
17473 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17474 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17475 - inside a LaTeX fragment, or
17476 - after the first word in a line, where an abbreviation expansion could
17477 insert a LaTeX environment."
17478 (when org-cdlatex-mode
17479 (cond
17480 ;; Before any word on the line: No expansion possible.
17481 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17482 ;; Just after first word on the line: Expand it. Make sure it
17483 ;; cannot happen on headlines, though.
17484 ((save-excursion
17485 (skip-chars-backward "a-zA-Z0-9*")
17486 (skip-chars-backward " \t")
17487 (and (bolp) (not (org-at-heading-p))))
17488 (cdlatex-tab) t)
17489 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17491 (defun org-cdlatex-underscore-caret (&optional arg)
17492 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17493 Revert to the normal definition outside of these fragments."
17494 (interactive "P")
17495 (if (org-inside-LaTeX-fragment-p)
17496 (call-interactively 'cdlatex-sub-superscript)
17497 (let (org-cdlatex-mode)
17498 (call-interactively (key-binding (vector last-input-event))))))
17500 (defun org-cdlatex-math-modify (&optional arg)
17501 "Execute `cdlatex-math-modify' in LaTeX fragments.
17502 Revert to the normal definition outside of these fragments."
17503 (interactive "P")
17504 (if (org-inside-LaTeX-fragment-p)
17505 (call-interactively 'cdlatex-math-modify)
17506 (let (org-cdlatex-mode)
17507 (call-interactively (key-binding (vector last-input-event))))))
17511 ;;;; LaTeX fragments
17513 (defvar org-latex-regexps
17514 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17515 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17516 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17517 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17518 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17519 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17520 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17521 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17522 "Regular expressions for matching embedded LaTeX.")
17524 (defun org-inside-LaTeX-fragment-p ()
17525 "Test if point is inside a LaTeX fragment.
17526 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17527 sequence appearing also before point.
17528 Even though the matchers for math are configurable, this function assumes
17529 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17530 delimiters are skipped when they have been removed by customization.
17531 The return value is nil, or a cons cell with the delimiter and the
17532 position of this delimiter.
17534 This function does a reasonably good job, but can locally be fooled by
17535 for example currency specifications. For example it will assume being in
17536 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17537 fragments that are properly closed, but during editing, we have to live
17538 with the uncertainty caused by missing closing delimiters. This function
17539 looks only before point, not after."
17540 (catch 'exit
17541 (let ((pos (point))
17542 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17543 (lim (progn
17544 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17545 (point)))
17546 dd-on str (start 0) m re)
17547 (goto-char pos)
17548 (when dodollar
17549 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17550 re (nth 1 (assoc "$" org-latex-regexps)))
17551 (while (string-match re str start)
17552 (cond
17553 ((= (match-end 0) (length str))
17554 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17555 ((= (match-end 0) (- (length str) 5))
17556 (throw 'exit nil))
17557 (t (setq start (match-end 0))))))
17558 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17559 (goto-char pos)
17560 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17561 (and (match-beginning 2) (throw 'exit nil))
17562 ;; count $$
17563 (while (re-search-backward "\\$\\$" lim t)
17564 (setq dd-on (not dd-on)))
17565 (goto-char pos)
17566 (if dd-on (cons "$$" m))))))
17568 (defun org-inside-latex-macro-p ()
17569 "Is point inside a LaTeX macro or its arguments?"
17570 (save-match-data
17571 (org-in-regexp
17572 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17574 (defvar org-latex-fragment-image-overlays nil
17575 "List of overlays carrying the images of latex fragments.")
17576 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17578 (defun org-remove-latex-fragment-image-overlays ()
17579 "Remove all overlays with LaTeX fragment images in current buffer."
17580 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17581 (setq org-latex-fragment-image-overlays nil))
17583 (defun org-preview-latex-fragment (&optional subtree)
17584 "Preview the LaTeX fragment at point, or all locally or globally.
17585 If the cursor is in a LaTeX fragment, create the image and overlay
17586 it over the source code. If there is no fragment at point, display
17587 all fragments in the current text, from one headline to the next. With
17588 prefix SUBTREE, display all fragments in the current subtree. With a
17589 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17590 the cursor is before the first headline,
17591 display all fragments in the buffer.
17592 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17593 (interactive "P")
17594 (unless buffer-file-name
17595 (error "Can't preview LaTeX fragment in a non-file buffer"))
17596 (org-remove-latex-fragment-image-overlays)
17597 (save-excursion
17598 (save-restriction
17599 (let (beg end at msg)
17600 (cond
17601 ((or (equal subtree '(16))
17602 (not (save-excursion
17603 (re-search-backward org-outline-regexp-bol nil t))))
17604 (setq beg (point-min) end (point-max)
17605 msg "Creating images for buffer...%s"))
17606 ((equal subtree '(4))
17607 (org-back-to-heading)
17608 (setq beg (point) end (org-end-of-subtree t)
17609 msg "Creating images for subtree...%s"))
17611 (if (setq at (org-inside-LaTeX-fragment-p))
17612 (goto-char (max (point-min) (- (cdr at) 2)))
17613 (org-back-to-heading))
17614 (setq beg (point) end (progn (outline-next-heading) (point))
17615 msg (if at "Creating image...%s"
17616 "Creating images for entry...%s"))))
17617 (message msg "")
17618 (narrow-to-region beg end)
17619 (goto-char beg)
17620 (org-format-latex
17621 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17622 (file-name-nondirectory
17623 buffer-file-name)))
17624 default-directory 'overlays msg at 'forbuffer
17625 org-latex-create-formula-image-program)
17626 (message msg "done. Use `C-c C-c' to remove images.")))))
17628 (defun org-format-latex (prefix &optional dir overlays msg at
17629 forbuffer processing-type)
17630 "Replace LaTeX fragments with links to an image, and produce images.
17631 Some of the options can be changed using the variable
17632 `org-format-latex-options'."
17633 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17634 (let* ((prefixnodir (file-name-nondirectory prefix))
17635 (absprefix (expand-file-name prefix dir))
17636 (todir (file-name-directory absprefix))
17637 (opt org-format-latex-options)
17638 (optnew org-format-latex-options)
17639 (matchers (plist-get opt :matchers))
17640 (re-list org-latex-regexps)
17641 (cnt 0) txt hash link beg end re e checkdir
17642 string
17643 m n block-type block linkfile movefile ov)
17644 ;; Check the different regular expressions
17645 (while (setq e (pop re-list))
17646 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17647 block (if block-type "\n\n" ""))
17648 (when (member m matchers)
17649 (goto-char (point-min))
17650 (while (re-search-forward re nil t)
17651 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17652 (or (not overlays)
17653 (not (eq (get-char-property (match-beginning n)
17654 'org-overlay-type)
17655 'org-latex-overlay))))
17656 (cond
17657 ((eq processing-type 'verbatim))
17658 ((eq processing-type 'mathjax)
17659 ;; Prepare for MathJax processing.
17660 (setq string (match-string n))
17661 (when (member m '("$" "$1"))
17662 (save-excursion
17663 (delete-region (match-beginning n) (match-end n))
17664 (goto-char (match-beginning n))
17665 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
17666 ((or (eq processing-type 'dvipng)
17667 (eq processing-type 'imagemagick))
17668 ;; Process to an image.
17669 (setq txt (match-string n)
17670 beg (match-beginning n) end (match-end n)
17671 cnt (1+ cnt))
17672 (let ((face (face-at-point))
17673 (fg (plist-get opt :foreground))
17674 (bg (plist-get opt :background))
17675 ;; Ensure full list is printed.
17676 print-length print-level)
17677 (when forbuffer
17678 ;; Get the colors from the face at point.
17679 (goto-char beg)
17680 (when (eq fg 'auto)
17681 (setq fg (face-attribute face :foreground nil 'default)))
17682 (when (eq bg 'auto)
17683 (setq bg (face-attribute face :background nil 'default)))
17684 (setq optnew (copy-sequence opt))
17685 (plist-put optnew :foreground fg)
17686 (plist-put optnew :background bg))
17687 (setq hash (sha1 (prin1-to-string
17688 (list org-format-latex-header
17689 org-latex-default-packages-alist
17690 org-latex-packages-alist
17691 org-format-latex-options
17692 forbuffer txt fg bg)))
17693 linkfile (format "%s_%s.png" prefix hash)
17694 movefile (format "%s_%s.png" absprefix hash)))
17695 (setq link (concat block "[[file:" linkfile "]]" block))
17696 (if msg (message msg cnt))
17697 (goto-char beg)
17698 (unless checkdir ; Ensure the directory exists.
17699 (setq checkdir t)
17700 (or (file-directory-p todir) (make-directory todir t)))
17701 (unless (file-exists-p movefile)
17702 (org-create-formula-image
17703 txt movefile optnew forbuffer processing-type))
17704 (if overlays
17705 (progn
17706 (mapc (lambda (o)
17707 (if (eq (overlay-get o 'org-overlay-type)
17708 'org-latex-overlay)
17709 (delete-overlay o)))
17710 (overlays-in beg end))
17711 (setq ov (make-overlay beg end))
17712 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17713 (if (featurep 'xemacs)
17714 (progn
17715 (overlay-put ov 'invisible t)
17716 (overlay-put
17717 ov 'end-glyph
17718 (make-glyph (vector 'png :file movefile))))
17719 (overlay-put
17720 ov 'display
17721 (list 'image :type 'png :file movefile :ascent 'center)))
17722 (push ov org-latex-fragment-image-overlays)
17723 (goto-char end))
17724 (delete-region beg end)
17725 (insert (org-add-props link
17726 (list 'org-latex-src
17727 (replace-regexp-in-string
17728 "\"" "" txt)
17729 'org-latex-src-embed-type
17730 (if block-type 'paragraph 'character))))))
17731 ((eq processing-type 'mathml)
17732 ;; Process to MathML
17733 (unless (save-match-data (org-format-latex-mathml-available-p))
17734 (error "LaTeX to MathML converter not configured"))
17735 (setq txt (match-string n)
17736 beg (match-beginning n) end (match-end n)
17737 cnt (1+ cnt))
17738 (if msg (message msg cnt))
17739 (goto-char beg)
17740 (delete-region beg end)
17741 (insert (org-format-latex-as-mathml
17742 txt block-type prefix dir)))
17744 (error "Unknown conversion type %s for latex fragments"
17745 processing-type)))))))))
17747 (defun org-create-math-formula (latex-frag &optional mathml-file)
17748 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17749 Use `org-latex-to-mathml-convert-command'. If the conversion is
17750 sucessful, return the portion between \"<math...> </math>\"
17751 elements otherwise return nil. When MATHML-FILE is specified,
17752 write the results in to that file. When invoked as an
17753 interactive command, prompt for LATEX-FRAG, with initial value
17754 set to the current active region and echo the results for user
17755 inspection."
17756 (interactive (list (let ((frag (when (org-region-active-p)
17757 (buffer-substring-no-properties
17758 (region-beginning) (region-end)))))
17759 (read-string "LaTeX Fragment: " frag nil frag))))
17760 (unless latex-frag (error "Invalid latex-frag"))
17761 (let* ((tmp-in-file (file-relative-name
17762 (make-temp-name (expand-file-name "ltxmathml-in"))))
17763 (ignore (write-region latex-frag nil tmp-in-file))
17764 (tmp-out-file (file-relative-name
17765 (make-temp-name (expand-file-name "ltxmathml-out"))))
17766 (cmd (format-spec
17767 org-latex-to-mathml-convert-command
17768 `((?j . ,(shell-quote-argument
17769 (expand-file-name org-latex-to-mathml-jar-file)))
17770 (?I . ,(shell-quote-argument tmp-in-file))
17771 (?o . ,(shell-quote-argument tmp-out-file)))))
17772 mathml shell-command-output)
17773 (when (org-called-interactively-p 'any)
17774 (unless (org-format-latex-mathml-available-p)
17775 (error "LaTeX to MathML converter not configured")))
17776 (message "Running %s" cmd)
17777 (setq shell-command-output (shell-command-to-string cmd))
17778 (setq mathml
17779 (when (file-readable-p tmp-out-file)
17780 (with-current-buffer (find-file-noselect tmp-out-file t)
17781 (goto-char (point-min))
17782 (when (re-search-forward
17783 (concat
17784 (regexp-quote
17785 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17786 "\\(.\\|\n\\)*"
17787 (regexp-quote "</math>")) nil t)
17788 (prog1 (match-string 0) (kill-buffer))))))
17789 (cond
17790 (mathml
17791 (setq mathml
17792 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17793 (when mathml-file
17794 (write-region mathml nil mathml-file))
17795 (when (org-called-interactively-p 'any)
17796 (message mathml)))
17797 ((message "LaTeX to MathML conversion failed")
17798 (message shell-command-output)))
17799 (delete-file tmp-in-file)
17800 (when (file-exists-p tmp-out-file)
17801 (delete-file tmp-out-file))
17802 mathml))
17804 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17805 prefix &optional dir)
17806 "Use `org-create-math-formula' but check local cache first."
17807 (let* ((absprefix (expand-file-name prefix dir))
17808 (print-length nil) (print-level nil)
17809 (formula-id (concat
17810 "formula-"
17811 (sha1
17812 (prin1-to-string
17813 (list latex-frag
17814 org-latex-to-mathml-convert-command)))))
17815 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17816 (formula-cache-dir (file-name-directory formula-cache)))
17818 (unless (file-directory-p formula-cache-dir)
17819 (make-directory formula-cache-dir t))
17821 (unless (file-exists-p formula-cache)
17822 (org-create-math-formula latex-frag formula-cache))
17824 (if (file-exists-p formula-cache)
17825 ;; Successful conversion. Return the link to MathML file.
17826 (org-add-props
17827 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17828 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17829 'org-latex-src-embed-type (if latex-frag-type
17830 'paragraph 'character)))
17831 ;; Failed conversion. Return the LaTeX fragment verbatim
17832 latex-frag)))
17834 (defun org-create-formula-image (string tofile options buffer &optional type)
17835 "Create an image from LaTeX source using dvipng or convert.
17836 This function calls either `org-create-formula-image-with-dvipng'
17837 or `org-create-formula-image-with-imagemagick' depending on the
17838 value of `org-latex-create-formula-image-program' or on the value
17839 of the optional TYPE variable.
17841 Note: ultimately these two function should be combined as they
17842 share a good deal of logic."
17843 (org-check-external-command
17844 "latex" "needed to convert LaTeX fragments to images")
17845 (funcall
17846 (case (or type org-latex-create-formula-image-program)
17847 ('dvipng
17848 (org-check-external-command
17849 "dvipng" "needed to convert LaTeX fragments to images")
17850 #'org-create-formula-image-with-dvipng)
17851 ('imagemagick
17852 (org-check-external-command
17853 "convert" "you need to install imagemagick")
17854 #'org-create-formula-image-with-imagemagick)
17855 (t (error
17856 "invalid value of `org-latex-create-formula-image-program'")))
17857 string tofile options buffer))
17859 ;; This function borrows from Ganesh Swami's latex2png.el
17860 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17861 "This calls dvipng."
17862 (let* ((tmpdir (if (featurep 'xemacs)
17863 (temp-directory)
17864 temporary-file-directory))
17865 (texfilebase (make-temp-name
17866 (expand-file-name "orgtex" tmpdir)))
17867 (texfile (concat texfilebase ".tex"))
17868 (dvifile (concat texfilebase ".dvi"))
17869 (pngfile (concat texfilebase ".png"))
17870 (fnh (if (featurep 'xemacs)
17871 (font-height (face-font 'default))
17872 (face-attribute 'default :height nil)))
17873 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17874 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17875 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17876 "Black"))
17877 (bg (or (plist-get options (if buffer :background :html-background))
17878 "Transparent")))
17879 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
17880 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
17881 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
17882 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
17883 (with-temp-file texfile
17884 (require 'ox-latex)
17885 (insert (org-latex-guess-inputenc
17886 (org-splice-latex-header
17887 org-format-latex-header
17888 org-latex-default-packages-alist
17889 org-latex-packages-alist t)))
17890 (insert "\n\\begin{document}\n" string "\n\\end{document}\n"))
17891 (let ((dir default-directory))
17892 (condition-case nil
17893 (progn
17894 (cd tmpdir)
17895 (call-process "latex" nil nil nil texfile))
17896 (error nil))
17897 (cd dir))
17898 (if (not (file-exists-p dvifile))
17899 (progn (message "Failed to create dvi file from %s" texfile) nil)
17900 (condition-case nil
17901 (if (featurep 'xemacs)
17902 (call-process "dvipng" nil nil nil
17903 "-fg" fg "-bg" bg
17904 "-T" "tight"
17905 "-o" pngfile
17906 dvifile)
17907 (call-process "dvipng" nil nil nil
17908 "-fg" fg "-bg" bg
17909 "-D" dpi
17910 ;;"-x" scale "-y" scale
17911 "-T" "tight"
17912 "-o" pngfile
17913 dvifile))
17914 (error nil))
17915 (if (not (file-exists-p pngfile))
17916 (if org-format-latex-signal-error
17917 (error "Failed to create png file from %s" texfile)
17918 (message "Failed to create png file from %s" texfile)
17919 nil)
17920 ;; Use the requested file name and clean up
17921 (copy-file pngfile tofile 'replace)
17922 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17923 (if (file-exists-p (concat texfilebase e))
17924 (delete-file (concat texfilebase e))))
17925 pngfile))))
17927 (defvar org-latex-pdf-process) ; From ox-latex.el
17928 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17929 "This calls convert, which is included into imagemagick."
17930 (let* ((tmpdir (if (featurep 'xemacs)
17931 (temp-directory)
17932 temporary-file-directory))
17933 (texfilebase (make-temp-name
17934 (expand-file-name "orgtex" tmpdir)))
17935 (texfile (concat texfilebase ".tex"))
17936 (pdffile (concat texfilebase ".pdf"))
17937 (pngfile (concat texfilebase ".png"))
17938 (fnh (if (featurep 'xemacs)
17939 (font-height (face-font 'default))
17940 (face-attribute 'default :height nil)))
17941 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17942 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17943 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17944 "black"))
17945 (bg (or (plist-get options (if buffer :background :html-background))
17946 "white")))
17947 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17948 (setq fg (org-latex-color-format fg)))
17949 (if (eq bg 'default) (setq bg (org-latex-color :background))
17950 (setq bg (org-latex-color-format
17951 (if (string= bg "Transparent") "white" bg))))
17952 (with-temp-file texfile
17953 (require 'ox-latex)
17954 (insert (org-latex-guess-inputenc
17955 (org-splice-latex-header
17956 org-format-latex-header
17957 org-latex-default-packages-alist
17958 org-latex-packages-alist t)))
17959 (insert "\n\\begin{document}\n"
17960 "\\definecolor{fg}{rgb}{" fg "}\n"
17961 "\\definecolor{bg}{rgb}{" bg "}\n"
17962 "\n\\pagecolor{bg}\n"
17963 "\n{\\color{fg}\n"
17964 string
17965 "\n}\n"
17966 "\n\\end{document}\n"))
17967 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17968 (condition-case nil
17969 (progn
17970 (cd tmpdir)
17971 (setq cmds org-latex-pdf-process)
17972 (while cmds
17973 (setq latex-frags-cmds (pop cmds))
17974 (if (listp latex-frags-cmds)
17975 (setq cmds nil)
17976 (setq latex-frags-cmds (list (car org-latex-pdf-process)))))
17977 (while latex-frags-cmds
17978 (setq cmd (pop latex-frags-cmds))
17979 (while (string-match "%b" cmd)
17980 (setq cmd (replace-match
17981 (save-match-data
17982 (shell-quote-argument texfile))
17983 t t cmd)))
17984 (while (string-match "%f" cmd)
17985 (setq cmd (replace-match
17986 (save-match-data
17987 (shell-quote-argument
17988 (file-name-nondirectory texfile)))
17989 t t cmd)))
17990 (while (string-match "%o" cmd)
17991 (setq cmd (replace-match
17992 (save-match-data
17993 (shell-quote-argument
17994 (file-name-directory texfile)))
17995 t t cmd)))
17996 (setq cmd (split-string cmd))
17997 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17998 (error nil))
17999 (cd dir))
18000 (if (not (file-exists-p pdffile))
18001 (progn (message "Failed to create pdf file from %s" texfile) nil)
18002 (condition-case nil
18003 (if (featurep 'xemacs)
18004 (call-process "convert" nil nil nil
18005 "-density" "96"
18006 "-trim"
18007 "-antialias"
18008 pdffile
18009 "-quality" "100"
18010 ;; "-sharpen" "0x1.0"
18011 pngfile)
18012 (call-process "convert" nil nil nil
18013 "-density" dpi
18014 "-trim"
18015 "-antialias"
18016 pdffile
18017 "-quality" "100"
18018 ;; "-sharpen" "0x1.0"
18019 pngfile))
18020 (error nil))
18021 (if (not (file-exists-p pngfile))
18022 (if org-format-latex-signal-error
18023 (error "Failed to create png file from %s" texfile)
18024 (message "Failed to create png file from %s" texfile)
18025 nil)
18026 ;; Use the requested file name and clean up
18027 (copy-file pngfile tofile 'replace)
18028 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18029 (if (file-exists-p (concat texfilebase e))
18030 (delete-file (concat texfilebase e))))
18031 pngfile))))
18033 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18034 "Fill a LaTeX header template TPL.
18035 In the template, the following place holders will be recognized:
18037 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18038 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18039 [PACKAGES] \\usepackage statements for PKG
18040 [NO-PACKAGES] do not include PKG
18041 [EXTRA] the string EXTRA
18042 [NO-EXTRA] do not include EXTRA
18044 For backward compatibility, if both the positive and the negative place
18045 holder is missing, the positive one (without the \"NO-\") will be
18046 assumed to be present at the end of the template.
18047 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18048 EXTRA is a string.
18049 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18050 (let (rpl (end ""))
18051 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18052 (setq rpl (if (or (match-end 1) (not def-pkg))
18053 "" (org-latex-packages-to-string def-pkg snippets-p t))
18054 tpl (replace-match rpl t t tpl))
18055 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18057 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18058 (setq rpl (if (or (match-end 1) (not pkg))
18059 "" (org-latex-packages-to-string pkg snippets-p t))
18060 tpl (replace-match rpl t t tpl))
18061 (if pkg (setq end
18062 (concat end "\n"
18063 (org-latex-packages-to-string pkg snippets-p)))))
18065 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18066 (setq rpl (if (or (match-end 1) (not extra))
18067 "" (concat extra "\n"))
18068 tpl (replace-match rpl t t tpl))
18069 (if (and extra (string-match "\\S-" extra))
18070 (setq end (concat end "\n" extra))))
18072 (if (string-match "\\S-" end)
18073 (concat tpl "\n" end)
18074 tpl)))
18076 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18077 "Turn an alist of packages into a string with the \\usepackage macros."
18078 (setq pkg (mapconcat (lambda(p)
18079 (cond
18080 ((stringp p) p)
18081 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18082 (format "%% Package %s omitted" (cadr p)))
18083 ((equal "" (car p))
18084 (format "\\usepackage{%s}" (cadr p)))
18086 (format "\\usepackage[%s]{%s}"
18087 (car p) (cadr p)))))
18089 "\n"))
18090 (if newline (concat pkg "\n") pkg))
18092 (defun org-dvipng-color (attr)
18093 "Return a RGB color specification for dvipng."
18094 (apply 'format "rgb %s %s %s"
18095 (mapcar 'org-normalize-color
18096 (if (featurep 'xemacs)
18097 (color-rgb-components
18098 (face-property 'default
18099 (cond ((eq attr :foreground) 'foreground)
18100 ((eq attr :background) 'background))))
18101 (color-values (face-attribute 'default attr nil))))))
18103 (defun org-dvipng-color-format (color-name)
18104 "Convert COLOR-NAME to a RGB color value for dvipng."
18105 (apply 'format "rgb %s %s %s"
18106 (mapcar 'org-normalize-color
18107 (color-values color-name))))
18109 (defun org-latex-color (attr)
18110 "Return a RGB color for the LaTeX color package."
18111 (apply 'format "%s,%s,%s"
18112 (mapcar 'org-normalize-color
18113 (if (featurep 'xemacs)
18114 (color-rgb-components
18115 (face-property 'default
18116 (cond ((eq attr :foreground) 'foreground)
18117 ((eq attr :background) 'background))))
18118 (color-values (face-attribute 'default attr nil))))))
18120 (defun org-latex-color-format (color-name)
18121 "Convert COLOR-NAME to a RGB color value."
18122 (apply 'format "%s,%s,%s"
18123 (mapcar 'org-normalize-color
18124 (color-values color-name))))
18126 (defun org-normalize-color (value)
18127 "Return string to be used as color value for an RGB component."
18128 (format "%g" (/ value 65535.0)))
18132 ;; Image display
18134 (defvar org-inline-image-overlays nil)
18135 (make-variable-buffer-local 'org-inline-image-overlays)
18137 (defun org-toggle-inline-images (&optional include-linked)
18138 "Toggle the display of inline images.
18139 INCLUDE-LINKED is passed to `org-display-inline-images'."
18140 (interactive "P")
18141 (if org-inline-image-overlays
18142 (progn
18143 (org-remove-inline-images)
18144 (message "Inline image display turned off"))
18145 (org-display-inline-images include-linked)
18146 (if (and (org-called-interactively-p)
18147 org-inline-image-overlays)
18148 (message "%d images displayed inline"
18149 (length org-inline-image-overlays))
18150 (message "No images to display inline"))))
18152 (defun org-redisplay-inline-images ()
18153 "Refresh the display of inline images."
18154 (interactive)
18155 (if (not org-inline-image-overlays)
18156 (org-toggle-inline-images)
18157 (org-toggle-inline-images)
18158 (org-toggle-inline-images)))
18160 (defun org-display-inline-images (&optional include-linked refresh beg end)
18161 "Display inline images.
18162 Normally only links without a description part are inlined, because this
18163 is how it will work for export. When INCLUDE-LINKED is set, also links
18164 with a description part will be inlined. This can be nice for a quick
18165 look at those images, but it does not reflect what exported files will look
18166 like.
18167 When REFRESH is set, refresh existing images between BEG and END.
18168 This will create new image displays only if necessary.
18169 BEG and END default to the buffer boundaries."
18170 (interactive "P")
18171 (unless refresh
18172 (org-remove-inline-images)
18173 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18174 (save-excursion
18175 (save-restriction
18176 (widen)
18177 (setq beg (or beg (point-min)) end (or end (point-max)))
18178 (goto-char beg)
18179 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18180 (substring (org-image-file-name-regexp) 0 -2)
18181 "\\)\\]" (if include-linked "" "\\]")))
18182 old file ov img type attrwidth width)
18183 (while (re-search-forward re end t)
18184 (setq old (get-char-property-and-overlay (match-beginning 1)
18185 'org-image-overlay)
18186 file (expand-file-name
18187 (concat (or (match-string 3) "") (match-string 4))))
18188 (when (image-type-available-p 'imagemagick)
18189 (setq attrwidth (if (or (listp org-image-actual-width)
18190 (null org-image-actual-width))
18191 (save-excursion
18192 (save-match-data
18193 (when (re-search-backward
18194 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18195 (save-excursion
18196 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18197 (string-to-number (match-string 1))))))
18198 width (cond ((eq org-image-actual-width t) nil)
18199 ((null org-image-actual-width) attrwidth)
18200 ((numberp org-image-actual-width)
18201 org-image-actual-width)
18202 ((listp org-image-actual-width)
18203 (or attrwidth (car org-image-actual-width))))
18204 type (if width 'imagemagick)))
18205 (when (file-exists-p file)
18206 (if (and (car-safe old) refresh)
18207 (image-refresh (overlay-get (cdr old) 'display))
18208 (setq img (save-match-data (create-image file type nil :width width)))
18209 (when img
18210 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18211 (overlay-put ov 'display img)
18212 (overlay-put ov 'face 'default)
18213 (overlay-put ov 'org-image-overlay t)
18214 (overlay-put ov 'modification-hooks
18215 (list 'org-display-inline-remove-overlay))
18216 (push ov org-inline-image-overlays)))))))))
18218 (define-obsolete-function-alias
18219 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18221 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18222 "Remove inline-display overlay if a corresponding region is modified."
18223 (let ((inhibit-modification-hooks t))
18224 (when (and ov after)
18225 (delete ov org-inline-image-overlays)
18226 (delete-overlay ov))))
18228 (defun org-remove-inline-images ()
18229 "Remove inline display of images."
18230 (interactive)
18231 (mapc 'delete-overlay org-inline-image-overlays)
18232 (setq org-inline-image-overlays nil))
18234 ;;;; Key bindings
18236 ;; Outline functions from `outline-mode-prefix-map'
18237 ;; that can be remapped in Org:
18238 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18239 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18240 (define-key org-mode-map [remap outline-forward-same-level]
18241 'org-forward-heading-same-level)
18242 (define-key org-mode-map [remap outline-backward-same-level]
18243 'org-backward-heading-same-level)
18244 (define-key org-mode-map [remap show-branches]
18245 'org-kill-note-or-show-branches)
18246 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18247 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18248 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18250 ;; Outline functions from `outline-mode-prefix-map' that can not
18251 ;; be remapped in Org:
18253 ;; - the column "key binding" shows whether the Outline function is still
18254 ;; available in Org mode on the same key that it has been bound to in
18255 ;; Outline mode:
18256 ;; - "overridden": key used for a different functionality in Org mode
18257 ;; - else: key still bound to the same Outline function in Org mode
18259 ;; | Outline function | key binding | Org replacement |
18260 ;; |------------------------------------+-------------+-----------------------|
18261 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18262 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18263 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18264 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18265 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18266 ;; | `show-entry' | overridden | no replacement |
18267 ;; | `show-children' | `C-c C-i' | visibility cycling |
18268 ;; | `show-branches' | `C-c C-k' | still same function |
18269 ;; | `show-subtree' | overridden | visibility cycling |
18270 ;; | `show-all' | overridden | no replacement |
18271 ;; | `hide-subtree' | overridden | visibility cycling |
18272 ;; | `hide-body' | overridden | no replacement |
18273 ;; | `hide-entry' | overridden | visibility cycling |
18274 ;; | `hide-leaves' | overridden | no replacement |
18275 ;; | `hide-sublevels' | overridden | no replacement |
18276 ;; | `hide-other' | overridden | no replacement |
18278 ;; Make `C-c C-x' a prefix key
18279 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18281 ;; TAB key with modifiers
18282 (org-defkey org-mode-map "\C-i" 'org-cycle)
18283 (org-defkey org-mode-map [(tab)] 'org-cycle)
18284 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18285 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18286 ;; The following line is necessary under Suse GNU/Linux
18287 (unless (featurep 'xemacs)
18288 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18289 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18290 (define-key org-mode-map [backtab] 'org-shifttab)
18292 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18293 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18294 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18296 ;; Cursor keys with modifiers
18297 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18298 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18299 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18300 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18302 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18303 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18304 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18305 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18307 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18308 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18309 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18310 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18312 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18313 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18314 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18315 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18317 ;; Babel keys
18318 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18319 (mapc (lambda (pair)
18320 (define-key org-babel-map (car pair) (cdr pair)))
18321 org-babel-key-bindings)
18323 ;;; Extra keys for tty access.
18324 ;; We only set them when really needed because otherwise the
18325 ;; menus don't show the simple keys
18327 (when (or org-use-extra-keys
18328 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18329 (not window-system))
18330 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18331 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18332 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18333 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18334 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18335 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18336 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18337 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18338 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18339 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18340 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18341 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18342 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18343 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18344 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18345 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18346 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18347 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18348 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18349 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18350 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18351 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18352 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18353 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18354 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18355 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18356 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18357 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18359 ;; All the other keys
18361 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18362 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18363 (if (boundp 'narrow-map)
18364 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18365 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18366 (if (boundp 'narrow-map)
18367 (org-defkey narrow-map "b" 'org-narrow-to-block)
18368 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18369 (if (boundp 'narrow-map)
18370 (org-defkey narrow-map "e" 'org-narrow-to-element)
18371 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18372 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18373 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18374 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18375 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18376 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18377 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18378 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18379 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18380 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18381 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18382 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18383 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18384 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18385 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18386 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18387 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18388 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18389 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18390 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18391 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18392 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18393 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18394 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18395 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18396 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18397 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18398 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18399 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18400 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18401 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18402 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18403 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18404 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18405 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18406 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18407 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18408 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18409 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18410 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18411 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18412 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18413 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18414 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18415 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18416 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18417 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18418 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18419 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18420 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18421 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18422 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18423 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18424 (org-defkey org-mode-map "\C-c^" 'org-sort)
18425 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18426 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18427 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18428 (org-defkey org-mode-map "\C-m" 'org-return)
18429 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18430 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18431 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18432 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18433 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18434 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18435 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18436 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18437 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18438 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18439 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18440 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18441 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18442 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
18443 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18444 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18445 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18446 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18447 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18448 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18449 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18450 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18451 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18453 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18454 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18455 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18457 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18458 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18459 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18460 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18461 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18462 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18463 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18464 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18465 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18466 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18467 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18468 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18469 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18470 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18471 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18472 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18473 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18474 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18475 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18476 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18477 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18478 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18479 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18481 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18482 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18483 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18484 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18485 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18487 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18489 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18491 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18492 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18494 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18497 (when (featurep 'xemacs)
18498 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18501 (defconst org-speed-commands-default
18503 ("Outline Navigation")
18504 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18505 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18506 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18507 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18508 ("u" . (org-speed-move-safe 'outline-up-heading))
18509 ("j" . org-goto)
18510 ("g" . (org-refile t))
18511 ("Outline Visibility")
18512 ("c" . org-cycle)
18513 ("C" . org-shifttab)
18514 (" " . org-display-outline-path)
18515 ("=" . org-columns)
18516 ("Outline Structure Editing")
18517 ("U" . org-shiftmetaup)
18518 ("D" . org-shiftmetadown)
18519 ("r" . org-metaright)
18520 ("l" . org-metaleft)
18521 ("R" . org-shiftmetaright)
18522 ("L" . org-shiftmetaleft)
18523 ("i" . (progn (forward-char 1) (call-interactively
18524 'org-insert-heading-respect-content)))
18525 ("^" . org-sort)
18526 ("w" . org-refile)
18527 ("a" . org-archive-subtree-default-with-confirmation)
18528 ("." . org-mark-subtree)
18529 ("#" . org-toggle-comment)
18530 ("Clock Commands")
18531 ("I" . org-clock-in)
18532 ("O" . org-clock-out)
18533 ("Meta Data Editing")
18534 ("t" . org-todo)
18535 ("," . (org-priority))
18536 ("0" . (org-priority ?\ ))
18537 ("1" . (org-priority ?A))
18538 ("2" . (org-priority ?B))
18539 ("3" . (org-priority ?C))
18540 (":" . org-set-tags-command)
18541 ("e" . org-set-effort)
18542 ("E" . org-inc-effort)
18543 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18544 (org-entry-put (point) "APPT_WARNTIME" m)))
18545 ("Agenda Views etc")
18546 ("v" . org-agenda)
18547 ("/" . org-sparse-tree)
18548 ("Misc")
18549 ("o" . org-open-at-point)
18550 ("?" . org-speed-command-help)
18551 ("<" . (org-agenda-set-restriction-lock 'subtree))
18552 (">" . (org-agenda-remove-restriction-lock))
18554 "The default speed commands.")
18556 (defun org-print-speed-command (e)
18557 (if (> (length (car e)) 1)
18558 (progn
18559 (princ "\n")
18560 (princ (car e))
18561 (princ "\n")
18562 (princ (make-string (length (car e)) ?-))
18563 (princ "\n"))
18564 (princ (car e))
18565 (princ " ")
18566 (if (symbolp (cdr e))
18567 (princ (symbol-name (cdr e)))
18568 (prin1 (cdr e)))
18569 (princ "\n")))
18571 (defun org-speed-command-help ()
18572 "Show the available speed commands."
18573 (interactive)
18574 (if (not org-use-speed-commands)
18575 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18576 (with-output-to-temp-buffer "*Help*"
18577 (princ "User-defined Speed commands\n===========================\n")
18578 (mapc 'org-print-speed-command org-speed-commands-user)
18579 (princ "\n")
18580 (princ "Built-in Speed commands\n=======================\n")
18581 (mapc 'org-print-speed-command org-speed-commands-default))
18582 (with-current-buffer "*Help*"
18583 (setq truncate-lines t))))
18585 (defun org-speed-move-safe (cmd)
18586 "Execute CMD, but make sure that the cursor always ends up in a headline.
18587 If not, return to the original position and throw an error."
18588 (interactive)
18589 (let ((pos (point)))
18590 (call-interactively cmd)
18591 (unless (and (bolp) (org-at-heading-p))
18592 (goto-char pos)
18593 (error "Boundary reached while executing %s" cmd))))
18595 (defvar org-self-insert-command-undo-counter 0)
18597 (defvar org-table-auto-blank-field) ; defined in org-table.el
18598 (defvar org-speed-command nil)
18600 (define-obsolete-function-alias
18601 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18603 (defun org-speed-command-activate (keys)
18604 "Hook for activating single-letter speed commands.
18605 `org-speed-commands-default' specifies a minimal command set.
18606 Use `org-speed-commands-user' for further customization."
18607 (when (or (and (bolp) (looking-at org-outline-regexp))
18608 (and (functionp org-use-speed-commands)
18609 (funcall org-use-speed-commands)))
18610 (cdr (assoc keys (append org-speed-commands-user
18611 org-speed-commands-default)))))
18613 (define-obsolete-function-alias
18614 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18616 (defun org-babel-speed-command-activate (keys)
18617 "Hook for activating single-letter code block commands."
18618 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18619 (cdr (assoc keys org-babel-key-bindings))))
18621 (defcustom org-speed-command-hook
18622 '(org-speed-command-default-hook org-babel-speed-command-hook)
18623 "Hook for activating speed commands at strategic locations.
18624 Hook functions are called in sequence until a valid handler is
18625 found.
18627 Each hook takes a single argument, a user-pressed command key
18628 which is also a `self-insert-command' from the global map.
18630 Within the hook, examine the cursor position and the command key
18631 and return nil or a valid handler as appropriate. Handler could
18632 be one of an interactive command, a function, or a form.
18634 Set `org-use-speed-commands' to non-nil value to enable this
18635 hook. The default setting is `org-speed-command-activate'."
18636 :group 'org-structure
18637 :version "24.1"
18638 :type 'hook)
18640 (defun org-self-insert-command (N)
18641 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18642 If the cursor is in a table looking at whitespace, the whitespace is
18643 overwritten, and the table is not marked as requiring realignment."
18644 (interactive "p")
18645 (org-check-before-invisible-edit 'insert)
18646 (cond
18647 ((and org-use-speed-commands
18648 (setq org-speed-command
18649 (run-hook-with-args-until-success
18650 'org-speed-command-hook (this-command-keys))))
18651 (cond
18652 ((commandp org-speed-command)
18653 (setq this-command org-speed-command)
18654 (call-interactively org-speed-command))
18655 ((functionp org-speed-command)
18656 (funcall org-speed-command))
18657 ((and org-speed-command (listp org-speed-command))
18658 (eval org-speed-command))
18659 (t (let (org-use-speed-commands)
18660 (call-interactively 'org-self-insert-command)))))
18661 ((and
18662 (org-table-p)
18663 (progn
18664 ;; check if we blank the field, and if that triggers align
18665 (and (featurep 'org-table) org-table-auto-blank-field
18666 (member last-command
18667 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18668 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18669 ;; got extra space, this field does not determine column width
18670 (let (org-table-may-need-update) (org-table-blank-field))
18671 ;; no extra space, this field may determine column width
18672 (org-table-blank-field)))
18674 (eq N 1)
18675 (looking-at "[^|\n]* |"))
18676 (let (org-table-may-need-update)
18677 (goto-char (1- (match-end 0)))
18678 (backward-delete-char 1)
18679 (goto-char (match-beginning 0))
18680 (self-insert-command N)))
18682 (setq org-table-may-need-update t)
18683 (self-insert-command N)
18684 (org-fix-tags-on-the-fly)
18685 (if org-self-insert-cluster-for-undo
18686 (if (not (eq last-command 'org-self-insert-command))
18687 (setq org-self-insert-command-undo-counter 1)
18688 (if (>= org-self-insert-command-undo-counter 20)
18689 (setq org-self-insert-command-undo-counter 1)
18690 (and (> org-self-insert-command-undo-counter 0)
18691 buffer-undo-list (listp buffer-undo-list)
18692 (not (cadr buffer-undo-list)) ; remove nil entry
18693 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18694 (setq org-self-insert-command-undo-counter
18695 (1+ org-self-insert-command-undo-counter))))))))
18697 (defun org-check-before-invisible-edit (kind)
18698 "Check is editing if kind KIND would be dangerous with invisible text around.
18699 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18700 ;; First, try to get out of here as quickly as possible, to reduce overhead
18701 (if (and org-catch-invisible-edits
18702 (or (not (boundp 'visible-mode)) (not visible-mode))
18703 (or (get-char-property (point) 'invisible)
18704 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18705 ;; OK, we need to take a closer look
18706 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18707 (invisible-before-point (if (bobp) nil (get-char-property
18708 (1- (point)) 'invisible)))
18709 (border-and-ok-direction
18711 ;; Check if we are acting predictably before invisible text
18712 (and invisible-at-point (not invisible-before-point)
18713 (memq kind '(insert delete-backward)))
18714 ;; Check if we are acting predictably after invisible text
18715 ;; This works not well, and I have turned it off. It seems
18716 ;; better to always show and stop after invisible text.
18717 ;; (and (not invisible-at-point) invisible-before-point
18718 ;; (memq kind '(insert delete)))
18720 (when (or (memq invisible-at-point '(outline org-hide-block t))
18721 (memq invisible-before-point '(outline org-hide-block t)))
18722 (if (eq org-catch-invisible-edits 'error)
18723 (error "Editing in invisible areas is prohibited - make visible first"))
18724 (if (and org-custom-properties-overlays
18725 (y-or-n-p "Display invisible properties in this buffer? "))
18726 (org-toggle-custom-properties-visibility)
18727 ;; Make the area visible
18728 (save-excursion
18729 (if invisible-before-point
18730 (goto-char (previous-single-char-property-change
18731 (point) 'invisible)))
18732 (org-cycle))
18733 (cond
18734 ((eq org-catch-invisible-edits 'show)
18735 ;; That's it, we do the edit after showing
18736 (message
18737 "Unfolding invisible region around point before editing")
18738 (sit-for 1))
18739 ((and (eq org-catch-invisible-edits 'smart)
18740 border-and-ok-direction)
18741 (message "Unfolding invisible region around point before editing"))
18743 ;; Don't do the edit, make the user repeat it in full visibility
18744 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18746 (defun org-fix-tags-on-the-fly ()
18747 (when (and (equal (char-after (point-at-bol)) ?*)
18748 (org-at-heading-p))
18749 (org-align-tags-here org-tags-column)))
18751 (defun org-delete-backward-char (N)
18752 "Like `delete-backward-char', insert whitespace at field end in tables.
18753 When deleting backwards, in tables this function will insert whitespace in
18754 front of the next \"|\" separator, to keep the table aligned. The table will
18755 still be marked for re-alignment if the field did fill the entire column,
18756 because, in this case the deletion might narrow the column."
18757 (interactive "p")
18758 (save-match-data
18759 (org-check-before-invisible-edit 'delete-backward)
18760 (if (and (org-table-p)
18761 (eq N 1)
18762 (string-match "|" (buffer-substring (point-at-bol) (point)))
18763 (looking-at ".*?|"))
18764 (let ((pos (point))
18765 (noalign (looking-at "[^|\n\r]* |"))
18766 (c org-table-may-need-update))
18767 (backward-delete-char N)
18768 (if (not overwrite-mode)
18769 (progn
18770 (skip-chars-forward "^|")
18771 (insert " ")
18772 (goto-char (1- pos))))
18773 ;; noalign: if there were two spaces at the end, this field
18774 ;; does not determine the width of the column.
18775 (if noalign (setq org-table-may-need-update c)))
18776 (backward-delete-char N)
18777 (org-fix-tags-on-the-fly))))
18779 (defun org-delete-char (N)
18780 "Like `delete-char', but insert whitespace at field end in tables.
18781 When deleting characters, in tables this function will insert whitespace in
18782 front of the next \"|\" separator, to keep the table aligned. The table will
18783 still be marked for re-alignment if the field did fill the entire column,
18784 because, in this case the deletion might narrow the column."
18785 (interactive "p")
18786 (save-match-data
18787 (org-check-before-invisible-edit 'delete)
18788 (if (and (org-table-p)
18789 (not (bolp))
18790 (not (= (char-after) ?|))
18791 (eq N 1))
18792 (if (looking-at ".*?|")
18793 (let ((pos (point))
18794 (noalign (looking-at "[^|\n\r]* |"))
18795 (c org-table-may-need-update))
18796 (replace-match (concat
18797 (substring (match-string 0) 1 -1)
18798 " |"))
18799 (goto-char pos)
18800 ;; noalign: if there were two spaces at the end, this field
18801 ;; does not determine the width of the column.
18802 (if noalign (setq org-table-may-need-update c)))
18803 (delete-char N))
18804 (delete-char N)
18805 (org-fix-tags-on-the-fly))))
18807 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18808 (put 'org-self-insert-command 'delete-selection t)
18809 (put 'orgtbl-self-insert-command 'delete-selection t)
18810 (put 'org-delete-char 'delete-selection 'supersede)
18811 (put 'org-delete-backward-char 'delete-selection 'supersede)
18812 (put 'org-yank 'delete-selection 'yank)
18814 ;; Make `flyspell-mode' delay after some commands
18815 (put 'org-self-insert-command 'flyspell-delayed t)
18816 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18817 (put 'org-delete-char 'flyspell-delayed t)
18818 (put 'org-delete-backward-char 'flyspell-delayed t)
18820 ;; Make pabbrev-mode expand after org-mode commands
18821 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18822 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18824 ;; How to do this: Measure non-white length of current string
18825 ;; If equal to column width, we should realign.
18827 (defun org-remap (map &rest commands)
18828 "In MAP, remap the functions given in COMMANDS.
18829 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18830 (let (new old)
18831 (while commands
18832 (setq old (pop commands) new (pop commands))
18833 (if (fboundp 'command-remapping)
18834 (org-defkey map (vector 'remap old) new)
18835 (substitute-key-definition old new map global-map)))))
18837 (when (eq org-enable-table-editor 'optimized)
18838 ;; If the user wants maximum table support, we need to hijack
18839 ;; some standard editing functions
18840 (org-remap org-mode-map
18841 'self-insert-command 'org-self-insert-command
18842 'delete-char 'org-delete-char
18843 'delete-backward-char 'org-delete-backward-char)
18844 (org-defkey org-mode-map "|" 'org-force-self-insert))
18846 (defvar org-ctrl-c-ctrl-c-hook nil
18847 "Hook for functions attaching themselves to `C-c C-c'.
18849 This can be used to add additional functionality to the C-c C-c
18850 key which executes context-dependent commands. This hook is run
18851 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18852 run after the last test.
18854 Each function will be called with no arguments. The function
18855 must check if the context is appropriate for it to act. If yes,
18856 it should do its thing and then return a non-nil value. If the
18857 context is wrong, just do nothing and return nil.")
18859 (defvar org-ctrl-c-ctrl-c-final-hook nil
18860 "Hook for functions attaching themselves to `C-c C-c'.
18862 This can be used to add additional functionality to the C-c C-c
18863 key which executes context-dependent commands. This hook is run
18864 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18865 before the first test.
18867 Each function will be called with no arguments. The function
18868 must check if the context is appropriate for it to act. If yes,
18869 it should do its thing and then return a non-nil value. If the
18870 context is wrong, just do nothing and return nil.")
18872 (defvar org-tab-first-hook nil
18873 "Hook for functions to attach themselves to TAB.
18874 See `org-ctrl-c-ctrl-c-hook' for more information.
18875 This hook runs as the first action when TAB is pressed, even before
18876 `org-cycle' messes around with the `outline-regexp' to cater for
18877 inline tasks and plain list item folding.
18878 If any function in this hook returns t, any other actions that
18879 would have been caused by TAB (such as table field motion or visibility
18880 cycling) will not occur.")
18882 (defvar org-tab-after-check-for-table-hook nil
18883 "Hook for functions to attach themselves to TAB.
18884 See `org-ctrl-c-ctrl-c-hook' for more information.
18885 This hook runs after it has been established that the cursor is not in a
18886 table, but before checking if the cursor is in a headline or if global cycling
18887 should be done.
18888 If any function in this hook returns t, not other actions like visibility
18889 cycling will be done.")
18891 (defvar org-tab-after-check-for-cycling-hook nil
18892 "Hook for functions to attach themselves to TAB.
18893 See `org-ctrl-c-ctrl-c-hook' for more information.
18894 This hook runs after it has been established that not table field motion and
18895 not visibility should be done because of current context. This is probably
18896 the place where a package like yasnippets can hook in.")
18898 (defvar org-tab-before-tab-emulation-hook nil
18899 "Hook for functions to attach themselves to TAB.
18900 See `org-ctrl-c-ctrl-c-hook' for more information.
18901 This hook runs after every other options for TAB have been exhausted, but
18902 before indentation and \t insertion takes place.")
18904 (defvar org-metaleft-hook nil
18905 "Hook for functions attaching themselves to `M-left'.
18906 See `org-ctrl-c-ctrl-c-hook' for more information.")
18907 (defvar org-metaright-hook nil
18908 "Hook for functions attaching themselves to `M-right'.
18909 See `org-ctrl-c-ctrl-c-hook' for more information.")
18910 (defvar org-metaup-hook nil
18911 "Hook for functions attaching themselves to `M-up'.
18912 See `org-ctrl-c-ctrl-c-hook' for more information.")
18913 (defvar org-metadown-hook nil
18914 "Hook for functions attaching themselves to `M-down'.
18915 See `org-ctrl-c-ctrl-c-hook' for more information.")
18916 (defvar org-shiftmetaleft-hook nil
18917 "Hook for functions attaching themselves to `M-S-left'.
18918 See `org-ctrl-c-ctrl-c-hook' for more information.")
18919 (defvar org-shiftmetaright-hook nil
18920 "Hook for functions attaching themselves to `M-S-right'.
18921 See `org-ctrl-c-ctrl-c-hook' for more information.")
18922 (defvar org-shiftmetaup-hook nil
18923 "Hook for functions attaching themselves to `M-S-up'.
18924 See `org-ctrl-c-ctrl-c-hook' for more information.")
18925 (defvar org-shiftmetadown-hook nil
18926 "Hook for functions attaching themselves to `M-S-down'.
18927 See `org-ctrl-c-ctrl-c-hook' for more information.")
18928 (defvar org-metareturn-hook nil
18929 "Hook for functions attaching themselves to `M-RET'.
18930 See `org-ctrl-c-ctrl-c-hook' for more information.")
18931 (defvar org-shiftup-hook nil
18932 "Hook for functions attaching themselves to `S-up'.
18933 See `org-ctrl-c-ctrl-c-hook' for more information.")
18934 (defvar org-shiftup-final-hook nil
18935 "Hook for functions attaching themselves to `S-up'.
18936 This one runs after all other options except shift-select have been excluded.
18937 See `org-ctrl-c-ctrl-c-hook' for more information.")
18938 (defvar org-shiftdown-hook nil
18939 "Hook for functions attaching themselves to `S-down'.
18940 See `org-ctrl-c-ctrl-c-hook' for more information.")
18941 (defvar org-shiftdown-final-hook nil
18942 "Hook for functions attaching themselves to `S-down'.
18943 This one runs after all other options except shift-select have been excluded.
18944 See `org-ctrl-c-ctrl-c-hook' for more information.")
18945 (defvar org-shiftleft-hook nil
18946 "Hook for functions attaching themselves to `S-left'.
18947 See `org-ctrl-c-ctrl-c-hook' for more information.")
18948 (defvar org-shiftleft-final-hook nil
18949 "Hook for functions attaching themselves to `S-left'.
18950 This one runs after all other options except shift-select have been excluded.
18951 See `org-ctrl-c-ctrl-c-hook' for more information.")
18952 (defvar org-shiftright-hook nil
18953 "Hook for functions attaching themselves to `S-right'.
18954 See `org-ctrl-c-ctrl-c-hook' for more information.")
18955 (defvar org-shiftright-final-hook nil
18956 "Hook for functions attaching themselves to `S-right'.
18957 This one runs after all other options except shift-select have been excluded.
18958 See `org-ctrl-c-ctrl-c-hook' for more information.")
18960 (defun org-modifier-cursor-error ()
18961 "Throw an error, a modified cursor command was applied in wrong context."
18962 (error "This command is active in special context like tables, headlines or items"))
18964 (defun org-shiftselect-error ()
18965 "Throw an error because Shift-Cursor command was applied in wrong context."
18966 (if (and (boundp 'shift-select-mode) shift-select-mode)
18967 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18968 (error "This command works only in special context like headlines or timestamps")))
18970 (defun org-call-for-shift-select (cmd)
18971 (let ((this-command-keys-shift-translated t))
18972 (call-interactively cmd)))
18974 (defun org-shifttab (&optional arg)
18975 "Global visibility cycling or move to previous table field.
18976 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18977 on context.
18978 See the individual commands for more information."
18979 (interactive "P")
18980 (cond
18981 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18982 ((integerp arg)
18983 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18984 (message "Content view to level: %d" arg)
18985 (org-content (prefix-numeric-value arg2))
18986 (setq org-cycle-global-status 'overview)))
18987 (t (call-interactively 'org-global-cycle))))
18989 (defun org-shiftmetaleft ()
18990 "Promote subtree or delete table column.
18991 Calls `org-promote-subtree', `org-outdent-item-tree', or
18992 `org-table-delete-column', depending on context. See the
18993 individual commands for more information."
18994 (interactive)
18995 (cond
18996 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18997 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18998 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18999 ((if (not (org-region-active-p)) (org-at-item-p)
19000 (save-excursion (goto-char (region-beginning))
19001 (org-at-item-p)))
19002 (call-interactively 'org-outdent-item-tree))
19003 (t (org-modifier-cursor-error))))
19005 (defun org-shiftmetaright ()
19006 "Demote subtree or insert table column.
19007 Calls `org-demote-subtree', `org-indent-item-tree', or
19008 `org-table-insert-column', depending on context. See the
19009 individual commands for more information."
19010 (interactive)
19011 (cond
19012 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19013 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19014 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19015 ((if (not (org-region-active-p)) (org-at-item-p)
19016 (save-excursion (goto-char (region-beginning))
19017 (org-at-item-p)))
19018 (call-interactively 'org-indent-item-tree))
19019 (t (org-modifier-cursor-error))))
19021 (defun org-shiftmetaup (&optional arg)
19022 "Move subtree up or kill table row.
19023 Calls `org-move-subtree-up' or `org-table-kill-row' or
19024 `org-move-item-up' or `org-timestamp-up', depending on context.
19025 See the individual commands for more information."
19026 (interactive "P")
19027 (cond
19028 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19029 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19030 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19031 ((org-at-item-p) (call-interactively 'org-move-item-up))
19032 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19033 (call-interactively 'org-timestamp-up)))
19034 (t (org-modifier-cursor-error))))
19036 (defun org-shiftmetadown (&optional arg)
19037 "Move subtree down or insert table row.
19038 Calls `org-move-subtree-down' or `org-table-insert-row' or
19039 `org-move-item-down' or `org-timestamp-up', depending on context.
19040 See the individual commands for more information."
19041 (interactive "P")
19042 (cond
19043 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19044 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19045 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19046 ((org-at-item-p) (call-interactively 'org-move-item-down))
19047 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19048 (call-interactively 'org-timestamp-down)))
19049 (t (org-modifier-cursor-error))))
19051 (defsubst org-hidden-tree-error ()
19052 (error
19053 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19055 (defun org-metaleft (&optional arg)
19056 "Promote heading or move table column to left.
19057 Calls `org-do-promote' or `org-table-move-column', depending on context.
19058 With no specific context, calls the Emacs default `backward-word'.
19059 See the individual commands for more information."
19060 (interactive "P")
19061 (cond
19062 ((run-hook-with-args-until-success 'org-metaleft-hook))
19063 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19064 ((org-with-limited-levels
19065 (or (org-at-heading-p)
19066 (and (org-region-active-p)
19067 (save-excursion
19068 (goto-char (region-beginning))
19069 (org-at-heading-p)))))
19070 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19071 (call-interactively 'org-do-promote))
19072 ;; At an inline task.
19073 ((org-at-heading-p)
19074 (call-interactively 'org-inlinetask-promote))
19075 ((or (org-at-item-p)
19076 (and (org-region-active-p)
19077 (save-excursion
19078 (goto-char (region-beginning))
19079 (org-at-item-p))))
19080 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19081 (call-interactively 'org-outdent-item))
19082 (t (call-interactively 'backward-word))))
19084 (defun org-metaright (&optional arg)
19085 "Demote a subtree, a list item or move table column to right.
19086 In front of a drawer or a block keyword, indent it correctly.
19087 With no specific context, calls the Emacs default `forward-word'.
19088 See the individual commands for more information."
19089 (interactive "P")
19090 (cond
19091 ((run-hook-with-args-until-success 'org-metaright-hook))
19092 ((org-at-table-p) (call-interactively 'org-table-move-column))
19093 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19094 ((org-at-block-p) (call-interactively 'org-indent-block))
19095 ((org-with-limited-levels
19096 (or (org-at-heading-p)
19097 (and (org-region-active-p)
19098 (save-excursion
19099 (goto-char (region-beginning))
19100 (org-at-heading-p)))))
19101 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19102 (call-interactively 'org-do-demote))
19103 ;; At an inline task.
19104 ((org-at-heading-p)
19105 (call-interactively 'org-inlinetask-demote))
19106 ((or (org-at-item-p)
19107 (and (org-region-active-p)
19108 (save-excursion
19109 (goto-char (region-beginning))
19110 (org-at-item-p))))
19111 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19112 (call-interactively 'org-indent-item))
19113 (t (call-interactively 'forward-word))))
19115 (defun org-check-for-hidden (what)
19116 "Check if there are hidden headlines/items in the current visual line.
19117 WHAT can be either `headlines' or `items'. If the current line is
19118 an outline or item heading and it has a folded subtree below it,
19119 this function returns t, nil otherwise."
19120 (let ((re (cond
19121 ((eq what 'headlines) org-outline-regexp-bol)
19122 ((eq what 'items) (org-item-beginning-re))
19123 (t (error "This should not happen"))))
19124 beg end)
19125 (save-excursion
19126 (catch 'exit
19127 (unless (org-region-active-p)
19128 (setq beg (point-at-bol))
19129 (beginning-of-line 2)
19130 (while (and (not (eobp)) ;; this is like `next-line'
19131 (get-char-property (1- (point)) 'invisible))
19132 (beginning-of-line 2))
19133 (setq end (point))
19134 (goto-char beg)
19135 (goto-char (point-at-eol))
19136 (setq end (max end (point)))
19137 (while (re-search-forward re end t)
19138 (if (get-char-property (match-beginning 0) 'invisible)
19139 (throw 'exit t))))
19140 nil))))
19142 (defun org-metaup (&optional arg)
19143 "Move subtree up or move table row up.
19144 Calls `org-move-subtree-up' or `org-table-move-row' or
19145 `org-move-item-up', depending on context. See the individual commands
19146 for more information."
19147 (interactive "P")
19148 (cond
19149 ((run-hook-with-args-until-success 'org-metaup-hook))
19150 ((org-region-active-p)
19151 (let* ((a (min (region-beginning) (region-end)))
19152 (b (1- (max (region-beginning) (region-end))))
19153 (c (save-excursion (goto-char a)
19154 (move-beginning-of-line 0)))
19155 (d (save-excursion (goto-char a)
19156 (move-end-of-line 0) (point))))
19157 (transpose-regions a b c d)
19158 (goto-char c)))
19159 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19160 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19161 ((org-at-item-p) (call-interactively 'org-move-item-up))
19162 (t (org-drag-element-backward))))
19164 (defun org-metadown (&optional arg)
19165 "Move subtree down or move table row down.
19166 Calls `org-move-subtree-down' or `org-table-move-row' or
19167 `org-move-item-down', depending on context. See the individual
19168 commands for more information."
19169 (interactive "P")
19170 (cond
19171 ((run-hook-with-args-until-success 'org-metadown-hook))
19172 ((org-region-active-p)
19173 (let* ((a (min (region-beginning) (region-end)))
19174 (b (max (region-beginning) (region-end)))
19175 (c (save-excursion (goto-char b)
19176 (move-beginning-of-line 1)))
19177 (d (save-excursion (goto-char b)
19178 (move-end-of-line 1) (1+ (point)))))
19179 (transpose-regions a b c d)
19180 (goto-char d)))
19181 ((org-at-table-p) (call-interactively 'org-table-move-row))
19182 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19183 ((org-at-item-p) (call-interactively 'org-move-item-down))
19184 (t (org-drag-element-forward))))
19186 (defun org-shiftup (&optional arg)
19187 "Increase item in timestamp or increase priority of current headline.
19188 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19189 depending on context. See the individual commands for more information."
19190 (interactive "P")
19191 (cond
19192 ((run-hook-with-args-until-success 'org-shiftup-hook))
19193 ((and org-support-shift-select (org-region-active-p))
19194 (org-call-for-shift-select 'previous-line))
19195 ((org-at-timestamp-p t)
19196 (call-interactively (if org-edit-timestamp-down-means-later
19197 'org-timestamp-down 'org-timestamp-up)))
19198 ((and (not (eq org-support-shift-select 'always))
19199 org-enable-priority-commands
19200 (org-at-heading-p))
19201 (call-interactively 'org-priority-up))
19202 ((and (not org-support-shift-select) (org-at-item-p))
19203 (call-interactively 'org-previous-item))
19204 ((org-clocktable-try-shift 'up arg))
19205 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19206 (org-support-shift-select
19207 (org-call-for-shift-select 'previous-line))
19208 (t (org-shiftselect-error))))
19210 (defun org-shiftdown (&optional arg)
19211 "Decrease item in timestamp or decrease priority of current headline.
19212 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19213 depending on context. See the individual commands for more information."
19214 (interactive "P")
19215 (cond
19216 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19217 ((and org-support-shift-select (org-region-active-p))
19218 (org-call-for-shift-select 'next-line))
19219 ((org-at-timestamp-p t)
19220 (call-interactively (if org-edit-timestamp-down-means-later
19221 'org-timestamp-up 'org-timestamp-down)))
19222 ((and (not (eq org-support-shift-select 'always))
19223 org-enable-priority-commands
19224 (org-at-heading-p))
19225 (call-interactively 'org-priority-down))
19226 ((and (not org-support-shift-select) (org-at-item-p))
19227 (call-interactively 'org-next-item))
19228 ((org-clocktable-try-shift 'down arg))
19229 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19230 (org-support-shift-select
19231 (org-call-for-shift-select 'next-line))
19232 (t (org-shiftselect-error))))
19234 (defun org-shiftright (&optional arg)
19235 "Cycle the thing at point or in the current line, depending on context.
19236 Depending on context, this does one of the following:
19238 - switch a timestamp at point one day into the future
19239 - on a headline, switch to the next TODO keyword.
19240 - on an item, switch entire list to the next bullet type
19241 - on a property line, switch to the next allowed value
19242 - on a clocktable definition line, move time block into the future"
19243 (interactive "P")
19244 (cond
19245 ((run-hook-with-args-until-success 'org-shiftright-hook))
19246 ((and org-support-shift-select (org-region-active-p))
19247 (org-call-for-shift-select 'forward-char))
19248 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19249 ((and (not (eq org-support-shift-select 'always))
19250 (org-at-heading-p))
19251 (let ((org-inhibit-logging
19252 (not org-treat-S-cursor-todo-selection-as-state-change))
19253 (org-inhibit-blocking
19254 (not org-treat-S-cursor-todo-selection-as-state-change)))
19255 (org-call-with-arg 'org-todo 'right)))
19256 ((or (and org-support-shift-select
19257 (not (eq org-support-shift-select 'always))
19258 (org-at-item-bullet-p))
19259 (and (not org-support-shift-select) (org-at-item-p)))
19260 (org-call-with-arg 'org-cycle-list-bullet nil))
19261 ((and (not (eq org-support-shift-select 'always))
19262 (org-at-property-p))
19263 (call-interactively 'org-property-next-allowed-value))
19264 ((org-clocktable-try-shift 'right arg))
19265 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19266 (org-support-shift-select
19267 (org-call-for-shift-select 'forward-char))
19268 (t (org-shiftselect-error))))
19270 (defun org-shiftleft (&optional arg)
19271 "Cycle the thing at point or in the current line, depending on context.
19272 Depending on context, this does one of the following:
19274 - switch a timestamp at point one day into the past
19275 - on a headline, switch to the previous TODO keyword.
19276 - on an item, switch entire list to the previous bullet type
19277 - on a property line, switch to the previous allowed value
19278 - on a clocktable definition line, move time block into the past"
19279 (interactive "P")
19280 (cond
19281 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19282 ((and org-support-shift-select (org-region-active-p))
19283 (org-call-for-shift-select 'backward-char))
19284 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19285 ((and (not (eq org-support-shift-select 'always))
19286 (org-at-heading-p))
19287 (let ((org-inhibit-logging
19288 (not org-treat-S-cursor-todo-selection-as-state-change))
19289 (org-inhibit-blocking
19290 (not org-treat-S-cursor-todo-selection-as-state-change)))
19291 (org-call-with-arg 'org-todo 'left)))
19292 ((or (and org-support-shift-select
19293 (not (eq org-support-shift-select 'always))
19294 (org-at-item-bullet-p))
19295 (and (not org-support-shift-select) (org-at-item-p)))
19296 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19297 ((and (not (eq org-support-shift-select 'always))
19298 (org-at-property-p))
19299 (call-interactively 'org-property-previous-allowed-value))
19300 ((org-clocktable-try-shift 'left arg))
19301 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19302 (org-support-shift-select
19303 (org-call-for-shift-select 'backward-char))
19304 (t (org-shiftselect-error))))
19306 (defun org-shiftcontrolright ()
19307 "Switch to next TODO set."
19308 (interactive)
19309 (cond
19310 ((and org-support-shift-select (org-region-active-p))
19311 (org-call-for-shift-select 'forward-word))
19312 ((and (not (eq org-support-shift-select 'always))
19313 (org-at-heading-p))
19314 (org-call-with-arg 'org-todo 'nextset))
19315 (org-support-shift-select
19316 (org-call-for-shift-select 'forward-word))
19317 (t (org-shiftselect-error))))
19319 (defun org-shiftcontrolleft ()
19320 "Switch to previous TODO set."
19321 (interactive)
19322 (cond
19323 ((and org-support-shift-select (org-region-active-p))
19324 (org-call-for-shift-select 'backward-word))
19325 ((and (not (eq org-support-shift-select 'always))
19326 (org-at-heading-p))
19327 (org-call-with-arg 'org-todo 'previousset))
19328 (org-support-shift-select
19329 (org-call-for-shift-select 'backward-word))
19330 (t (org-shiftselect-error))))
19332 (defun org-shiftcontrolup (&optional n)
19333 "Change timestamps synchronously up in CLOCK log lines.
19334 Optional argument N tells to change by that many units."
19335 (interactive "P")
19336 (cond ((and (not org-support-shift-select)
19337 (org-at-clock-log-p)
19338 (org-at-timestamp-p t))
19339 (org-clock-timestamps-up n))
19340 (t (org-shiftselect-error))))
19342 (defun org-shiftcontroldown (&optional n)
19343 "Change timestamps synchronously down in CLOCK log lines.
19344 Optional argument N tells to change by that many units."
19345 (interactive "P")
19346 (cond ((and (not org-support-shift-select)
19347 (org-at-clock-log-p)
19348 (org-at-timestamp-p t))
19349 (org-clock-timestamps-down n))
19350 (t (org-shiftselect-error))))
19352 (defun org-ctrl-c-ret ()
19353 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19354 (interactive)
19355 (cond
19356 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19357 (t (call-interactively 'org-insert-heading))))
19359 (defun org-find-visible ()
19360 (let ((s (point)))
19361 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19362 (get-char-property s 'invisible)))
19364 (defun org-find-invisible ()
19365 (let ((s (point)))
19366 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19367 (not (get-char-property s 'invisible))))
19370 (defun org-copy-visible (beg end)
19371 "Copy the visible parts of the region."
19372 (interactive "r")
19373 (let (snippets s)
19374 (save-excursion
19375 (save-restriction
19376 (narrow-to-region beg end)
19377 (setq s (goto-char (point-min)))
19378 (while (not (= (point) (point-max)))
19379 (goto-char (org-find-invisible))
19380 (push (buffer-substring s (point)) snippets)
19381 (setq s (goto-char (org-find-visible))))))
19382 (kill-new (apply 'concat (nreverse snippets)))))
19384 (defun org-copy-special ()
19385 "Copy region in table or copy current subtree.
19386 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19387 See the individual commands for more information."
19388 (interactive)
19389 (call-interactively
19390 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19392 (defun org-cut-special ()
19393 "Cut region in table or cut current subtree.
19394 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19395 See the individual commands for more information."
19396 (interactive)
19397 (call-interactively
19398 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19400 (defun org-paste-special (arg)
19401 "Paste rectangular region into table, or past subtree relative to level.
19402 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19403 See the individual commands for more information."
19404 (interactive "P")
19405 (if (org-at-table-p)
19406 (org-table-paste-rectangle)
19407 (org-paste-subtree arg)))
19409 (defsubst org-in-fixed-width-region-p ()
19410 "Is point in a fixed-width region?"
19411 (save-match-data
19412 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19414 (defun org-edit-special (&optional arg)
19415 "Call a special editor for the element at point.
19416 When at a table, call the formula editor with `org-table-edit-formulas'.
19417 When in a source code block, call `org-edit-src-code'.
19418 When in a fixed-width region, call `org-edit-fixed-width-region'.
19419 When at an #+INCLUDE keyword, visit the included file.
19420 On a link, call `ffap' to visit the link at point.
19421 Otherwise, return a user error."
19422 (interactive)
19423 (let ((element (org-element-at-point)))
19424 (case (org-element-type element)
19425 (src-block
19426 (if (not arg) (org-edit-src-code)
19427 (let* ((info (org-babel-get-src-block-info))
19428 (lang (nth 0 info))
19429 (params (nth 2 info))
19430 (session (cdr (assq :session params))))
19431 (if (not session) (org-edit-src-code)
19432 ;; At a src-block with a session and function called with
19433 ;; an ARG: switch to the buffer related to the inferior
19434 ;; process.
19435 (funcall (intern (concat "org-babel-prep-session:" lang))
19436 session params)))))
19437 (keyword
19438 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
19439 (find-file
19440 (org-remove-double-quotes
19441 (car (org-split-string (org-element-property :value element)))))
19442 (user-error "No special environment to edit here")))
19443 (table
19444 (if (eq (org-element-property :type element) 'table.el)
19445 (org-edit-src-code)
19446 (call-interactively 'org-table-edit-formulas)))
19447 ;; Only Org tables contain `table-row' type elements.
19448 (table-row (call-interactively 'org-table-edit-formulas))
19449 ((example-block export-block) (org-edit-src-code))
19450 (fixed-width (org-edit-fixed-width-region))
19451 (otherwise
19452 ;; No notable element at point. Though, we may be at a link,
19453 ;; which is an object. Thus, scan deeper.
19454 (if (eq (org-element-type (org-element-context element)) 'link)
19455 (call-interactively 'ffap)
19456 (user-error "No special environment to edit here"))))))
19458 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19459 (defun org-ctrl-c-ctrl-c (&optional arg)
19460 "Set tags in headline, or update according to changed information at point.
19462 This command does many different things, depending on context:
19464 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19465 this is what we do.
19467 - If the cursor is on a statistics cookie, update it.
19469 - If the cursor is in a headline, prompt for tags and insert them
19470 into the current line, aligned to `org-tags-column'. When called
19471 with prefix arg, realign all tags in the current buffer.
19473 - If the cursor is in one of the special #+KEYWORD lines, this
19474 triggers scanning the buffer for these lines and updating the
19475 information.
19477 - If the cursor is inside a table, realign the table. This command
19478 works even if the automatic table editor has been turned off.
19480 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19481 the entire table.
19483 - If the cursor is at a footnote reference or definition, jump to
19484 the corresponding definition or references, respectively.
19486 - If the cursor is a the beginning of a dynamic block, update it.
19488 - If the current buffer is a capture buffer, close note and file it.
19490 - If the cursor is on a <<<target>>>, update radio targets and
19491 corresponding links in this buffer.
19493 - If the cursor is on a numbered item in a plain list, renumber the
19494 ordered list.
19496 - If the cursor is on a checkbox, toggle it.
19498 - If the cursor is on a code block, evaluate it. The variable
19499 `org-confirm-babel-evaluate' can be used to control prompting
19500 before code block evaluation, by default every code block
19501 evaluation requires confirmation. Code block evaluation can be
19502 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19503 (interactive "P")
19504 (cond
19505 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19506 org-occur-highlights
19507 org-latex-fragment-image-overlays)
19508 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19509 (org-remove-occur-highlights)
19510 (org-remove-latex-fragment-image-overlays)
19511 (message "Temporary highlights/overlays removed from current buffer"))
19512 ((and (local-variable-p 'org-finish-function (current-buffer))
19513 (fboundp org-finish-function))
19514 (funcall org-finish-function))
19515 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19517 (let* ((context (org-element-context)) (type (org-element-type context)))
19518 ;; Test if point is within blanks at the end of an element.
19519 (if (save-excursion
19520 (or (not context)
19521 (beginning-of-line)
19522 (and (looking-at "[ \t]*$")
19523 (skip-chars-forward " \r\t\n")
19524 (>= (point) (org-element-property :end context)))))
19525 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19526 (user-error "C-c C-c can do nothing useful at this location"))
19527 ;; For convenience: at the first line of a paragraph on the
19528 ;; same line as an item, apply function on that item instead.
19529 (when (eq type 'paragraph)
19530 (let ((parent (org-element-property :parent context)))
19531 (when (and (eq (org-element-type parent) 'item)
19532 (= (point-at-bol) (org-element-property :begin parent)))
19533 (setq context parent type 'item))))
19534 ;; Act according to type of element or object at point.
19535 (case type
19536 (clock (org-clock-update-time-maybe))
19537 (dynamic-block
19538 (save-excursion
19539 (goto-char (org-element-property :post-affiliated context))
19540 (org-update-dblock)))
19541 (footnote-definition
19542 (goto-char (org-element-property :post-affiliated context))
19543 (call-interactively 'org-footnote-action))
19544 (footnote-reference (call-interactively 'org-footnote-action))
19545 ((headline inlinetask)
19546 (save-excursion (goto-char (org-element-property :begin context))
19547 (call-interactively 'org-set-tags)))
19548 (item
19549 ;; At an item: a double C-u set checkbox to "[-]"
19550 ;; unconditionally, whereas a single one will toggle its
19551 ;; presence. Without an universal argument, if the item
19552 ;; has a checkbox, toggle it. Otherwise repair the list.
19553 (let* ((box (org-element-property :checkbox context))
19554 (struct (org-element-property :structure context))
19555 (old-struct (copy-tree struct))
19556 (parents (org-list-parents-alist struct))
19557 (prevs (org-list-prevs-alist struct))
19558 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
19559 (org-list-set-checkbox
19560 (org-element-property :begin context) struct
19561 (cond ((equal arg '(16)) "[-]")
19562 ((and (not box) (equal arg '(4))) "[ ]")
19563 ((or (not box) (equal arg '(4))) nil)
19564 ((eq box 'on) "[ ]")
19565 (t "[X]")))
19566 ;; Mimic `org-list-write-struct' but with grabbing
19567 ;; a return value from `org-list-struct-fix-box'.
19568 (org-list-struct-fix-ind struct parents 2)
19569 (org-list-struct-fix-item-end struct)
19570 (org-list-struct-fix-bul struct prevs)
19571 (org-list-struct-fix-ind struct parents)
19572 (let ((block-item
19573 (org-list-struct-fix-box struct parents prevs orderedp)))
19574 (if (and box (equal struct old-struct))
19575 (if (equal arg '(16))
19576 (message "Checkboxes already reset")
19577 (user-error "Cannot toggle this checkbox: %s"
19578 (if (eq box 'on)
19579 "all subitems checked"
19580 "unchecked subitems")))
19581 (org-list-struct-apply-struct struct old-struct)
19582 (org-update-checkbox-count-maybe))
19583 (when block-item
19584 (message "Checkboxes were removed due to empty box at line %d"
19585 (org-current-line block-item))))))
19586 (keyword
19587 (let ((org-inhibit-startup-visibility-stuff t)
19588 (org-startup-align-all-tables nil))
19589 (when (boundp 'org-table-coordinate-overlays)
19590 (mapc 'delete-overlay org-table-coordinate-overlays)
19591 (setq org-table-coordinate-overlays nil))
19592 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19593 (message "Local setup has been refreshed"))
19594 (plain-list
19595 ;; At a plain list, with a double C-u argument, set
19596 ;; checkboxes of each item to "[-]", whereas a single one
19597 ;; will toggle their presence according to the state of the
19598 ;; first item in the list. Without an argument, repair the
19599 ;; list.
19600 (let* ((begin (org-element-property :contents-begin context))
19601 (struct (org-element-property :structure context))
19602 (old-struct (copy-tree struct))
19603 (first-box (save-excursion
19604 (goto-char begin)
19605 (looking-at org-list-full-item-re)
19606 (match-string-no-properties 3)))
19607 (new-box (cond ((equal arg '(16)) "[-]")
19608 ((equal arg '(4)) (unless first-box "[ ]"))
19609 ((equal first-box "[X]") "[ ]")
19610 (t "[X]"))))
19611 (cond
19612 (arg
19613 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
19614 (org-list-get-all-items
19615 begin struct (org-list-prevs-alist struct))))
19616 ((and first-box (eq (point) begin))
19617 ;; For convenience, when point is at bol on the first
19618 ;; item of the list and no argument is provided, simply
19619 ;; toggle checkbox of that item, if any.
19620 (org-list-set-checkbox begin struct new-box)))
19621 (org-list-write-struct
19622 struct (org-list-parents-alist struct) old-struct)
19623 (org-update-checkbox-count-maybe)
19624 (save-excursion (goto-char begin) (org-list-send-list 'maybe))))
19625 ((property-drawer node-property)
19626 (call-interactively 'org-property-action))
19627 ((radio-target target)
19628 (call-interactively 'org-update-radio-target-regexp))
19629 (statistics-cookie
19630 (call-interactively 'org-update-statistics-cookies))
19631 ((table table-cell table-row)
19632 ;; At a table, recalculate every field and align it. Also
19633 ;; send the table if necessary. If the table has
19634 ;; a `table.el' type, just give up. At a table row or
19635 ;; cell, maybe recalculate line but always align table.
19636 (if (eq (org-element-property :type context) 'table.el)
19637 (message "Use C-c ' to edit table.el tables")
19638 (let ((org-enable-table-editor t))
19639 (if (or (eq type 'table)
19640 ;; Check if point is at a TBLFM line.
19641 (and (eq type 'table-row)
19642 (= (point) (org-element-property :end context))))
19643 (save-excursion
19644 (goto-char (org-element-property :contents-begin context))
19645 (org-call-with-arg 'org-table-recalculate (or arg t))
19646 (orgtbl-send-table 'maybe))
19647 (org-table-maybe-eval-formula)
19648 (cond (arg (call-interactively 'org-table-recalculate))
19649 ((org-table-maybe-recalculate-line))
19650 (t (org-table-align)))))))
19651 (timestamp (org-timestamp-change 0 'day))
19652 (otherwise
19653 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19654 (user-error
19655 "C-c C-c can do nothing useful at this location")))))))))
19657 (defun org-mode-restart ()
19658 "Restart Org-mode, to scan again for special lines.
19659 Also updates the keyword regular expressions."
19660 (interactive)
19661 (org-mode)
19662 (message "Org-mode restarted"))
19664 (defun org-kill-note-or-show-branches ()
19665 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19666 (interactive)
19667 (if (not org-finish-function)
19668 (progn
19669 (hide-subtree)
19670 (call-interactively 'show-branches))
19671 (let ((org-note-abort t))
19672 (funcall org-finish-function))))
19674 (defun org-return (&optional indent)
19675 "Goto next table row or insert a newline.
19676 Calls `org-table-next-row' or `newline', depending on context.
19677 See the individual commands for more information."
19678 (interactive)
19679 (let (org-ts-what)
19680 (cond
19681 ((or (bobp) (org-in-src-block-p))
19682 (if indent (newline-and-indent) (newline)))
19683 ((org-at-table-p)
19684 (org-table-justify-field-maybe)
19685 (call-interactively 'org-table-next-row))
19686 ;; when `newline-and-indent' is called within a list, make sure
19687 ;; text moved stays inside the item.
19688 ((and (org-in-item-p) indent)
19689 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19690 (progn
19691 (save-match-data (newline))
19692 (org-indent-line-to (length (match-string 0))))
19693 (let ((ind (org-get-indentation)))
19694 (newline)
19695 (if (org-looking-back org-list-end-re)
19696 (org-indent-line)
19697 (org-indent-line-to ind)))))
19698 ((and org-return-follows-link
19699 (org-at-timestamp-p t)
19700 (not (eq org-ts-what 'after)))
19701 (org-follow-timestamp-link))
19702 ((and org-return-follows-link
19703 (let ((tprop (get-text-property (point) 'face)))
19704 (or (eq tprop 'org-link)
19705 (and (listp tprop) (memq 'org-link tprop)))))
19706 (call-interactively 'org-open-at-point))
19707 ((and (org-at-heading-p)
19708 (looking-at
19709 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19710 (org-show-entry)
19711 (end-of-line 1)
19712 (newline))
19713 (t (if indent (newline-and-indent) (newline))))))
19715 (defun org-return-indent ()
19716 "Goto next table row or insert a newline and indent.
19717 Calls `org-table-next-row' or `newline-and-indent', depending on
19718 context. See the individual commands for more information."
19719 (interactive)
19720 (org-return t))
19722 (defun org-ctrl-c-star ()
19723 "Compute table, or change heading status of lines.
19724 Calls `org-table-recalculate' or `org-toggle-heading',
19725 depending on context."
19726 (interactive)
19727 (cond
19728 ((org-at-table-p)
19729 (call-interactively 'org-table-recalculate))
19731 ;; Convert all lines in region to list items
19732 (call-interactively 'org-toggle-heading))))
19734 (defun org-ctrl-c-minus ()
19735 "Insert separator line in table or modify bullet status of line.
19736 Also turns a plain line or a region of lines into list items.
19737 Calls `org-table-insert-hline', `org-toggle-item', or
19738 `org-cycle-list-bullet', depending on context."
19739 (interactive)
19740 (cond
19741 ((org-at-table-p)
19742 (call-interactively 'org-table-insert-hline))
19743 ((org-region-active-p)
19744 (call-interactively 'org-toggle-item))
19745 ((org-in-item-p)
19746 (call-interactively 'org-cycle-list-bullet))
19748 (call-interactively 'org-toggle-item))))
19750 (defun org-toggle-item (arg)
19751 "Convert headings or normal lines to items, items to normal lines.
19752 If there is no active region, only the current line is considered.
19754 If the first non blank line in the region is an headline, convert
19755 all headlines to items, shifting text accordingly.
19757 If it is an item, convert all items to normal lines.
19759 If it is normal text, change region into an item. With a prefix
19760 argument ARG, change each line in region into an item."
19761 (interactive "P")
19762 (let ((shift-text
19763 (function
19764 ;; Shift text in current section to IND, from point to END.
19765 ;; The function leaves point to END line.
19766 (lambda (ind end)
19767 (let ((min-i 1000) (end (copy-marker end)))
19768 ;; First determine the minimum indentation (MIN-I) of
19769 ;; the text.
19770 (save-excursion
19771 (catch 'exit
19772 (while (< (point) end)
19773 (let ((i (org-get-indentation)))
19774 (cond
19775 ;; Skip blank lines and inline tasks.
19776 ((looking-at "^[ \t]*$"))
19777 ((looking-at org-outline-regexp-bol))
19778 ;; We can't find less than 0 indentation.
19779 ((zerop i) (throw 'exit (setq min-i 0)))
19780 ((< i min-i) (setq min-i i))))
19781 (forward-line))))
19782 ;; Then indent each line so that a line indented to
19783 ;; MIN-I becomes indented to IND. Ignore blank lines
19784 ;; and inline tasks in the process.
19785 (let ((delta (- ind min-i)))
19786 (while (< (point) end)
19787 (unless (or (looking-at "^[ \t]*$")
19788 (looking-at org-outline-regexp-bol))
19789 (org-indent-line-to (+ (org-get-indentation) delta)))
19790 (forward-line)))))))
19791 (skip-blanks
19792 (function
19793 ;; Return beginning of first non-blank line, starting from
19794 ;; line at POS.
19795 (lambda (pos)
19796 (save-excursion
19797 (goto-char pos)
19798 (skip-chars-forward " \r\t\n")
19799 (point-at-bol)))))
19800 beg end)
19801 ;; Determine boundaries of changes.
19802 (if (org-region-active-p)
19803 (setq beg (funcall skip-blanks (region-beginning))
19804 end (copy-marker (region-end)))
19805 (setq beg (funcall skip-blanks (point-at-bol))
19806 end (copy-marker (point-at-eol))))
19807 ;; Depending on the starting line, choose an action on the text
19808 ;; between BEG and END.
19809 (org-with-limited-levels
19810 (save-excursion
19811 (goto-char beg)
19812 (cond
19813 ;; Case 1. Start at an item: de-itemize. Note that it only
19814 ;; happens when a region is active: `org-ctrl-c-minus'
19815 ;; would call `org-cycle-list-bullet' otherwise.
19816 ((org-at-item-p)
19817 (while (< (point) end)
19818 (when (org-at-item-p)
19819 (skip-chars-forward " \t")
19820 (delete-region (point) (match-end 0)))
19821 (forward-line)))
19822 ;; Case 2. Start at an heading: convert to items.
19823 ((org-at-heading-p)
19824 (let* ((bul (org-list-bullet-string "-"))
19825 (bul-len (length bul))
19826 ;; Indentation of the first heading. It should be
19827 ;; relative to the indentation of its parent, if any.
19828 (start-ind (save-excursion
19829 (cond
19830 ((not org-adapt-indentation) 0)
19831 ((not (outline-previous-heading)) 0)
19832 (t (length (match-string 0))))))
19833 ;; Level of first heading. Further headings will be
19834 ;; compared to it to determine hierarchy in the list.
19835 (ref-level (org-reduced-level (org-outline-level))))
19836 (while (< (point) end)
19837 (let* ((level (org-reduced-level (org-outline-level)))
19838 (delta (max 0 (- level ref-level))))
19839 ;; If current headline is less indented than the first
19840 ;; one, set it as reference, in order to preserve
19841 ;; subtrees.
19842 (when (< level ref-level) (setq ref-level level))
19843 (replace-match bul t t)
19844 (org-indent-line-to (+ start-ind (* delta bul-len)))
19845 ;; Ensure all text down to END (or SECTION-END) belongs
19846 ;; to the newly created item.
19847 (let ((section-end (save-excursion
19848 (or (outline-next-heading) (point)))))
19849 (forward-line)
19850 (funcall shift-text
19851 (+ start-ind (* (1+ delta) bul-len))
19852 (min end section-end)))))))
19853 ;; Case 3. Normal line with ARG: turn each non-item line into
19854 ;; an item.
19855 (arg
19856 (while (< (point) end)
19857 (unless (or (org-at-heading-p) (org-at-item-p))
19858 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19859 (replace-match
19860 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19861 (forward-line)))
19862 ;; Case 4. Normal line without ARG: make the first line of
19863 ;; region an item, and shift indentation of others
19864 ;; lines to set them as item's body.
19865 (t (let* ((bul (org-list-bullet-string "-"))
19866 (bul-len (length bul))
19867 (ref-ind (org-get-indentation)))
19868 (skip-chars-forward " \t")
19869 (insert bul)
19870 (forward-line)
19871 (while (< (point) end)
19872 ;; Ensure that lines less indented than first one
19873 ;; still get included in item body.
19874 (funcall shift-text
19875 (+ ref-ind bul-len)
19876 (min end (save-excursion (or (outline-next-heading)
19877 (point)))))
19878 (forward-line)))))))))
19880 (defun org-toggle-heading (&optional nstars)
19881 "Convert headings to normal text, or items or text to headings.
19882 If there is no active region, only the current line is considered.
19884 With a \\[universal-argument] prefix, convert the whole list at
19885 point into heading.
19887 In a region:
19889 - If the first non blank line is an headline, remove the stars
19890 from all headlines in the region.
19892 - If it is a normal line turn each and every normal line (i.e. not an
19893 heading or an item) in the region into a heading.
19895 - If it is a plain list item, turn all plain list items into headings.
19897 When converting a line into a heading, the number of stars is chosen
19898 such that the lines become children of the current entry. However,
19899 when a prefix argument is given, its value determines the number of
19900 stars to add."
19901 (interactive "P")
19902 (let ((skip-blanks
19903 (function
19904 ;; Return beginning of first non-blank line, starting from
19905 ;; line at POS.
19906 (lambda (pos)
19907 (save-excursion
19908 (goto-char pos)
19909 (while (org-at-comment-p) (forward-line))
19910 (skip-chars-forward " \r\t\n")
19911 (point-at-bol)))))
19912 beg end toggled)
19913 ;; Determine boundaries of changes. If a universal prefix has
19914 ;; been given, put the list in a region. If region ends at a bol,
19915 ;; do not consider the last line to be in the region.
19917 (when (and current-prefix-arg (org-at-item-p))
19918 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19919 (org-mark-element))
19921 (if (org-region-active-p)
19922 (setq beg (funcall skip-blanks (region-beginning))
19923 end (copy-marker (save-excursion
19924 (goto-char (region-end))
19925 (if (bolp) (point) (point-at-eol)))))
19926 (setq beg (funcall skip-blanks (point-at-bol))
19927 end (copy-marker (point-at-eol))))
19928 ;; Ensure inline tasks don't count as headings.
19929 (org-with-limited-levels
19930 (save-excursion
19931 (goto-char beg)
19932 (cond
19933 ;; Case 1. Started at an heading: de-star headings.
19934 ((org-at-heading-p)
19935 (while (< (point) end)
19936 (when (org-at-heading-p t)
19937 (looking-at org-outline-regexp) (replace-match "")
19938 (setq toggled t))
19939 (forward-line)))
19940 ;; Case 2. Started at an item: change items into headlines.
19941 ;; One star will be added by `org-list-to-subtree'.
19942 ((org-at-item-p)
19943 (let* ((stars (make-string
19944 (if nstars
19945 ;; subtract the star that will be added again by
19946 ;; `org-list-to-subtree'
19947 (1- (prefix-numeric-value current-prefix-arg))
19948 (or (org-current-level) 0))
19949 ?*))
19950 (add-stars
19951 (cond (nstars "") ; stars from prefix only
19952 ((equal stars "") "") ; before first heading
19953 (org-odd-levels-only "*") ; inside heading, odd
19954 (t "")))) ; inside heading, oddeven
19955 (while (< (point) end)
19956 (when (org-at-item-p)
19957 ;; Pay attention to cases when region ends before list.
19958 (let* ((struct (org-list-struct))
19959 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19960 (save-restriction
19961 (narrow-to-region (point) list-end)
19962 (insert
19963 (org-list-to-subtree
19964 (org-list-parse-list t)
19965 '(:istart (concat stars add-stars (funcall get-stars depth))
19966 :icount (concat stars add-stars (funcall get-stars depth)))))))
19967 (setq toggled t))
19968 (forward-line))))
19969 ;; Case 3. Started at normal text: make every line an heading,
19970 ;; skipping headlines and items.
19971 (t (let* ((stars (make-string
19972 (if nstars
19973 (prefix-numeric-value current-prefix-arg)
19974 (or (org-current-level) 0))
19975 ?*))
19976 (add-stars
19977 (cond (nstars "") ; stars from prefix only
19978 ((equal stars "") "*") ; before first heading
19979 (org-odd-levels-only "**") ; inside heading, odd
19980 (t "*"))) ; inside heading, oddeven
19981 (rpl (concat stars add-stars " ")))
19982 (while (< (point) end)
19983 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19984 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19985 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19986 (forward-line)))))))
19987 (unless toggled (message "Cannot toggle heading from here"))))
19989 (defun org-meta-return (&optional arg)
19990 "Insert a new heading or wrap a region in a table.
19991 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19992 See the individual commands for more information."
19993 (interactive "P")
19994 (cond
19995 ((run-hook-with-args-until-success 'org-metareturn-hook))
19996 ((or (org-at-drawer-p) (org-at-property-p))
19997 (newline-and-indent))
19998 ((org-at-table-p)
19999 (call-interactively 'org-table-wrap-region))
20000 (t (call-interactively 'org-insert-heading))))
20002 ;;; Menu entries
20004 (defsubst org-in-subtree-not-table-p ()
20005 "Are we in a subtree and not in a table?"
20006 (and (not (org-before-first-heading-p))
20007 (not (org-at-table-p))))
20009 ;; Define the Org-mode menus
20010 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20011 '("Tbl"
20012 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20013 ["Next Field" org-cycle (org-at-table-p)]
20014 ["Previous Field" org-shifttab (org-at-table-p)]
20015 ["Next Row" org-return (org-at-table-p)]
20016 "--"
20017 ["Blank Field" org-table-blank-field (org-at-table-p)]
20018 ["Edit Field" org-table-edit-field (org-at-table-p)]
20019 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20020 "--"
20021 ("Column"
20022 ["Move Column Left" org-metaleft (org-at-table-p)]
20023 ["Move Column Right" org-metaright (org-at-table-p)]
20024 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20025 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20026 ("Row"
20027 ["Move Row Up" org-metaup (org-at-table-p)]
20028 ["Move Row Down" org-metadown (org-at-table-p)]
20029 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20030 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20031 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20032 "--"
20033 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20034 ("Rectangle"
20035 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20036 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20037 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20038 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20039 "--"
20040 ("Calculate"
20041 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20042 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20043 ["Edit Formulas" org-edit-special (org-at-table-p)]
20044 "--"
20045 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20046 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20047 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20048 "--"
20049 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20050 "--"
20051 ["Sum Column/Rectangle" org-table-sum
20052 (or (org-at-table-p) (org-region-active-p))]
20053 ["Which Column?" org-table-current-column (org-at-table-p)])
20054 ["Debug Formulas"
20055 org-table-toggle-formula-debugger
20056 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20057 ["Show Col/Row Numbers"
20058 org-table-toggle-coordinate-overlays
20059 :style toggle
20060 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20061 "--"
20062 ["Create" org-table-create (and (not (org-at-table-p))
20063 org-enable-table-editor)]
20064 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20065 ["Import from File" org-table-import (not (org-at-table-p))]
20066 ["Export to File" org-table-export (org-at-table-p)]
20067 "--"
20068 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20070 (easy-menu-define org-org-menu org-mode-map "Org menu"
20071 '("Org"
20072 ("Show/Hide"
20073 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20074 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20075 ["Sparse Tree..." org-sparse-tree t]
20076 ["Reveal Context" org-reveal t]
20077 ["Show All" show-all t]
20078 "--"
20079 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20080 "--"
20081 ["New Heading" org-insert-heading t]
20082 ("Navigate Headings"
20083 ["Up" outline-up-heading t]
20084 ["Next" outline-next-visible-heading t]
20085 ["Previous" outline-previous-visible-heading t]
20086 ["Next Same Level" outline-forward-same-level t]
20087 ["Previous Same Level" outline-backward-same-level t]
20088 "--"
20089 ["Jump" org-goto t])
20090 ("Edit Structure"
20091 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20092 "--"
20093 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20094 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20095 "--"
20096 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20097 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20098 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20099 "--"
20100 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20101 "--"
20102 ["Copy visible text" org-copy-visible t]
20103 "--"
20104 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20105 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20106 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20107 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20108 "--"
20109 ["Sort Region/Children" org-sort t]
20110 "--"
20111 ["Convert to odd levels" org-convert-to-odd-levels t]
20112 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20113 ("Editing"
20114 ["Emphasis..." org-emphasize t]
20115 ["Edit Source Example" org-edit-special t]
20116 "--"
20117 ["Footnote new/jump" org-footnote-action t]
20118 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20119 ("Archive"
20120 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20121 "--"
20122 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20123 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20124 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20126 "--"
20127 ("Hyperlinks"
20128 ["Store Link (Global)" org-store-link t]
20129 ["Find existing link to here" org-occur-link-in-agenda-files t]
20130 ["Insert Link" org-insert-link t]
20131 ["Follow Link" org-open-at-point t]
20132 "--"
20133 ["Next link" org-next-link t]
20134 ["Previous link" org-previous-link t]
20135 "--"
20136 ["Descriptive Links"
20137 org-toggle-link-display
20138 :style radio
20139 :selected org-descriptive-links
20141 ["Literal Links"
20142 org-toggle-link-display
20143 :style radio
20144 :selected (not org-descriptive-links)])
20145 "--"
20146 ("TODO Lists"
20147 ["TODO/DONE/-" org-todo t]
20148 ("Select keyword"
20149 ["Next keyword" org-shiftright (org-at-heading-p)]
20150 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20151 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20152 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20153 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20154 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20155 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20156 "--"
20157 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20158 :selected org-enforce-todo-dependencies :style toggle :active t]
20159 "Settings for tree at point"
20160 ["Do Children sequentially" org-toggle-ordered-property :style radio
20161 :selected (org-entry-get nil "ORDERED")
20162 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20163 ["Do Children parallel" org-toggle-ordered-property :style radio
20164 :selected (not (org-entry-get nil "ORDERED"))
20165 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20166 "--"
20167 ["Set Priority" org-priority t]
20168 ["Priority Up" org-shiftup t]
20169 ["Priority Down" org-shiftdown t]
20170 "--"
20171 ["Get news from all feeds" org-feed-update-all t]
20172 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20173 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20174 ("TAGS and Properties"
20175 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20176 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20177 "--"
20178 ["Set property" org-set-property (not (org-before-first-heading-p))]
20179 ["Column view of properties" org-columns t]
20180 ["Insert Column View DBlock" org-insert-columns-dblock t])
20181 ("Dates and Scheduling"
20182 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20183 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20184 ("Change Date"
20185 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20186 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20187 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20188 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20189 ["Compute Time Range" org-evaluate-time-range t]
20190 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20191 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20192 "--"
20193 ["Custom time format" org-toggle-time-stamp-overlays
20194 :style radio :selected org-display-custom-times]
20195 "--"
20196 ["Goto Calendar" org-goto-calendar t]
20197 ["Date from Calendar" org-date-from-calendar t]
20198 "--"
20199 ["Start/Restart Timer" org-timer-start t]
20200 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20201 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20202 ["Insert Timer String" org-timer t]
20203 ["Insert Timer Item" org-timer-item t])
20204 ("Logging work"
20205 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20206 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20207 ["Clock out" org-clock-out t]
20208 ["Clock cancel" org-clock-cancel t]
20209 "--"
20210 ["Mark as default task" org-clock-mark-default-task t]
20211 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20212 ["Goto running clock" org-clock-goto t]
20213 "--"
20214 ["Display times" org-clock-display t]
20215 ["Create clock table" org-clock-report t]
20216 "--"
20217 ["Record DONE time"
20218 (progn (setq org-log-done (not org-log-done))
20219 (message "Switching to %s will %s record a timestamp"
20220 (car org-done-keywords)
20221 (if org-log-done "automatically" "not")))
20222 :style toggle :selected org-log-done])
20223 "--"
20224 ["Agenda Command..." org-agenda t]
20225 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20226 ("File List for Agenda")
20227 ("Special views current file"
20228 ["TODO Tree" org-show-todo-tree t]
20229 ["Check Deadlines" org-check-deadlines t]
20230 ["Timeline" org-timeline t]
20231 ["Tags/Property tree" org-match-sparse-tree t])
20232 "--"
20233 ["Export/Publish..." org-export-dispatch t]
20234 ("LaTeX"
20235 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20236 :selected org-cdlatex-mode]
20237 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20238 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20239 ["Modify math symbol" org-cdlatex-math-modify
20240 (org-inside-LaTeX-fragment-p)]
20241 ["Insert citation" org-reftex-citation t]
20242 "--"
20243 ["Template for BEAMER" (progn (require 'ox-beamer)
20244 (org-insert-beamer-options-template)) t])
20245 "--"
20246 ("MobileOrg"
20247 ["Push Files and Views" org-mobile-push t]
20248 ["Get Captured and Flagged" org-mobile-pull t]
20249 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20250 "--"
20251 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20252 "--"
20253 ("Documentation"
20254 ["Show Version" org-version t]
20255 ["Info Documentation" org-info t])
20256 ("Customize"
20257 ["Browse Org Group" org-customize t]
20258 "--"
20259 ["Expand This Menu" org-create-customize-menu
20260 (fboundp 'customize-menu-create)])
20261 ["Send bug report" org-submit-bug-report t]
20262 "--"
20263 ("Refresh/Reload"
20264 ["Refresh setup current buffer" org-mode-restart t]
20265 ["Reload Org (after update)" org-reload t]
20266 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
20269 (defun org-info (&optional node)
20270 "Read documentation for Org-mode in the info system.
20271 With optional NODE, go directly to that node."
20272 (interactive)
20273 (info (format "(org)%s" (or node ""))))
20275 ;;;###autoload
20276 (defun org-submit-bug-report ()
20277 "Submit a bug report on Org-mode via mail.
20279 Don't hesitate to report any problems or inaccurate documentation.
20281 If you don't have setup sending mail from (X)Emacs, please copy the
20282 output buffer into your mail program, as it gives us important
20283 information about your Org-mode version and configuration."
20284 (interactive)
20285 (require 'reporter)
20286 (org-load-modules-maybe)
20287 (org-require-autoloaded-modules)
20288 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20289 (reporter-submit-bug-report
20290 "emacs-orgmode@gnu.org"
20291 (org-version nil 'full)
20292 (let (list)
20293 (save-window-excursion
20294 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20295 (delete-other-windows)
20296 (erase-buffer)
20297 (insert "You are about to submit a bug report to the Org-mode mailing list.
20299 We would like to add your full Org-mode and Outline configuration to the
20300 bug report. This greatly simplifies the work of the maintainer and
20301 other experts on the mailing list.
20303 HOWEVER, some variables you have customized may contain private
20304 information. The names of customers, colleagues, or friends, might
20305 appear in the form of file names, tags, todo states, or search strings.
20306 If you answer yes to the prompt, you might want to check and remove
20307 such private information before sending the email.")
20308 (add-text-properties (point-min) (point-max) '(face org-warning))
20309 (when (yes-or-no-p "Include your Org-mode configuration ")
20310 (mapatoms
20311 (lambda (v)
20312 (and (boundp v)
20313 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20314 (or (and (symbol-value v)
20315 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20316 (and
20317 (get v 'custom-type) (get v 'standard-value)
20318 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20319 (push v list)))))
20320 (kill-buffer (get-buffer "*Warn about privacy*"))
20321 list))
20322 nil nil
20323 "Remember to cover the basics, that is, what you expected to happen and
20324 what in fact did happen. You don't know how to make a good report? See
20326 http://orgmode.org/manual/Feedback.html#Feedback
20328 Your bug report will be posted to the Org-mode mailing list.
20329 ------------------------------------------------------------------------")
20330 (save-excursion
20331 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20332 (replace-match "\\1Bug: \\3 [\\2]")))))
20335 (defun org-install-agenda-files-menu ()
20336 (let ((bl (buffer-list)))
20337 (save-excursion
20338 (while bl
20339 (set-buffer (pop bl))
20340 (if (derived-mode-p 'org-mode) (setq bl nil)))
20341 (when (derived-mode-p 'org-mode)
20342 (easy-menu-change
20343 '("Org") "File List for Agenda"
20344 (append
20345 (list
20346 ["Edit File List" (org-edit-agenda-file-list) t]
20347 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20348 ["Remove Current File from List" org-remove-file t]
20349 ["Cycle through agenda files" org-cycle-agenda-files t]
20350 ["Occur in all agenda files" org-occur-in-agenda-files t]
20351 "--")
20352 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20354 ;;;; Documentation
20356 (defun org-require-autoloaded-modules ()
20357 (interactive)
20358 (mapc 'require
20359 '(org-agenda org-archive org-attach org-clock org-colview org-id
20360 org-remember org-table org-timer)))
20362 ;;;###autoload
20363 (defun org-reload (&optional uncompiled)
20364 "Reload all org lisp files.
20365 With prefix arg UNCOMPILED, load the uncompiled versions."
20366 (interactive "P")
20367 (require 'loadhist)
20368 (let* ((org-dir (org-find-library-dir "org"))
20369 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20370 (feature-re "^\\(org\\|ob\\)\\(-.*\\)?")
20371 (remove-re (mapconcat 'identity
20372 (mapcar (lambda (f) (concat "^" f "$"))
20373 (list (if (featurep 'xemacs)
20374 "org-colview"
20375 "org-colview-xemacs")
20376 "org" "org-loaddefs" "org-version"))
20377 "\\|"))
20378 (feats (delete-dups
20379 (mapcar 'file-name-sans-extension
20380 (mapcar 'file-name-nondirectory
20381 (delq nil
20382 (mapcar 'feature-file
20383 features))))))
20384 (lfeat (append
20385 (sort
20386 (setq feats
20387 (delq nil (mapcar
20388 (lambda (f)
20389 (if (and (string-match feature-re f)
20390 (not (string-match remove-re f)))
20391 f nil))
20392 feats)))
20393 'string-lessp)
20394 (list "org-version" "org")))
20395 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20396 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20397 load-uncore load-misses)
20398 (setq load-misses
20399 (delq 't
20400 (mapcar (lambda (f)
20401 (or (org-load-noerror-mustsuffix (concat org-dir f))
20402 (and (string= org-dir contrib-dir)
20403 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20404 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20405 (add-to-list 'load-uncore f 'append)
20408 lfeat)))
20409 (if load-uncore
20410 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20411 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20412 (if load-misses
20413 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20414 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20415 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20417 ;;;###autoload
20418 (defun org-customize ()
20419 "Call the customize function with org as argument."
20420 (interactive)
20421 (org-load-modules-maybe)
20422 (org-require-autoloaded-modules)
20423 (customize-browse 'org))
20425 (defun org-create-customize-menu ()
20426 "Create a full customization menu for Org-mode, insert it into the menu."
20427 (interactive)
20428 (org-load-modules-maybe)
20429 (org-require-autoloaded-modules)
20430 (if (fboundp 'customize-menu-create)
20431 (progn
20432 (easy-menu-change
20433 '("Org") "Customize"
20434 `(["Browse Org group" org-customize t]
20435 "--"
20436 ,(customize-menu-create 'org)
20437 ["Set" Custom-set t]
20438 ["Save" Custom-save t]
20439 ["Reset to Current" Custom-reset-current t]
20440 ["Reset to Saved" Custom-reset-saved t]
20441 ["Reset to Standard Settings" Custom-reset-standard t]))
20442 (message "\"Org\"-menu now contains full customization menu"))
20443 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20445 ;;;; Miscellaneous stuff
20447 ;;; Generally useful functions
20449 (defun org-get-at-bol (property)
20450 "Get text property PROPERTY at beginning of line."
20451 (get-text-property (point-at-bol) property))
20453 (defun org-find-text-property-in-string (prop s)
20454 "Return the first non-nil value of property PROP in string S."
20455 (or (get-text-property 0 prop s)
20456 (get-text-property (or (next-single-property-change 0 prop s) 0)
20457 prop s)))
20459 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20460 "Display the given MESSAGE as a warning."
20461 (if (fboundp 'display-warning)
20462 (display-warning 'org message
20463 (if (featurep 'xemacs) 'warning :warning))
20464 (let ((buf (get-buffer-create "*Org warnings*")))
20465 (with-current-buffer buf
20466 (goto-char (point-max))
20467 (insert "Warning (Org): " message)
20468 (unless (bolp)
20469 (newline)))
20470 (display-buffer buf)
20471 (sit-for 0))))
20473 (defun org-eval (form)
20474 "Eval FORM and return result."
20475 (condition-case error
20476 (eval form)
20477 (error (format "%%![Error: %s]" error))))
20479 (defun org-in-clocktable-p ()
20480 "Check if the cursor is in a clocktable."
20481 (let ((pos (point)) start)
20482 (save-excursion
20483 (end-of-line 1)
20484 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20485 (setq start (match-beginning 0))
20486 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20487 (>= (match-end 0) pos)
20488 start))))
20490 (defun org-in-commented-line ()
20491 "Is point in a line starting with `#'?"
20492 (equal (char-after (point-at-bol)) ?#))
20494 (defun org-in-indented-comment-line ()
20495 "Is point in a line starting with `#' after some white space?"
20496 (save-excursion
20497 (save-match-data
20498 (goto-char (point-at-bol))
20499 (looking-at "[ \t]*#"))))
20501 (defun org-in-verbatim-emphasis ()
20502 (save-match-data
20503 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20505 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20506 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20507 (if (and marker (marker-buffer marker)
20508 (buffer-live-p (marker-buffer marker)))
20509 (progn
20510 (org-pop-to-buffer-same-window (marker-buffer marker))
20511 (if (or (> marker (point-max)) (< marker (point-min)))
20512 (widen))
20513 (goto-char marker)
20514 (org-show-context 'org-goto))
20515 (if bookmark
20516 (bookmark-jump bookmark)
20517 (error "Cannot find location"))))
20519 (defun org-quote-csv-field (s)
20520 "Quote field for inclusion in CSV material."
20521 (if (string-match "[\",]" s)
20522 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20525 (defun org-force-self-insert (N)
20526 "Needed to enforce self-insert under remapping."
20527 (interactive "p")
20528 (self-insert-command N))
20530 (defun org-string-width (s)
20531 "Compute width of string, ignoring invisible characters.
20532 This ignores character with invisibility property `org-link', and also
20533 characters with property `org-cwidth', because these will become invisible
20534 upon the next fontification round."
20535 (let (b l)
20536 (when (or (eq t buffer-invisibility-spec)
20537 (assq 'org-link buffer-invisibility-spec))
20538 (while (setq b (text-property-any 0 (length s)
20539 'invisible 'org-link s))
20540 (setq s (concat (substring s 0 b)
20541 (substring s (or (next-single-property-change
20542 b 'invisible s) (length s)))))))
20543 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20544 (setq s (concat (substring s 0 b)
20545 (substring s (or (next-single-property-change
20546 b 'org-cwidth s) (length s))))))
20547 (setq l (string-width s) b -1)
20548 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20549 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20552 (defun org-shorten-string (s maxlength)
20553 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20554 If the string is shorter or has length MAXLENGTH, just return the
20555 original string. If it is longer, the functions finds a space in the
20556 string, breaks this string off at that locations and adds three dots
20557 as ellipsis. Including the ellipsis, the string will not be longer
20558 than MAXLENGTH. If finding a good breaking point in the string does
20559 not work, the string is just chopped off in the middle of a word
20560 if necessary."
20561 (if (<= (length s) maxlength)
20563 (let* ((n (max (- maxlength 4) 1))
20564 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20565 (if (string-match re s)
20566 (concat (match-string 1 s) "...")
20567 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20569 (defun org-get-indentation (&optional line)
20570 "Get the indentation of the current line, interpreting tabs.
20571 When LINE is given, assume it represents a line and compute its indentation."
20572 (if line
20573 (if (string-match "^ *" (org-remove-tabs line))
20574 (match-end 0))
20575 (save-excursion
20576 (beginning-of-line 1)
20577 (skip-chars-forward " \t")
20578 (current-column))))
20580 (defun org-get-string-indentation (s)
20581 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20582 (let ((n -1) (i 0) (w tab-width) c)
20583 (catch 'exit
20584 (while (< (setq n (1+ n)) (length s))
20585 (setq c (aref s n))
20586 (cond ((= c ?\ ) (setq i (1+ i)))
20587 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20588 (t (throw 'exit t)))))
20591 (defun org-remove-tabs (s &optional width)
20592 "Replace tabulators in S with spaces.
20593 Assumes that s is a single line, starting in column 0."
20594 (setq width (or width tab-width))
20595 (while (string-match "\t" s)
20596 (setq s (replace-match
20597 (make-string
20598 (- (* width (/ (+ (match-beginning 0) width) width))
20599 (match-beginning 0)) ?\ )
20600 t t s)))
20603 (defun org-fix-indentation (line ind)
20604 "Fix indentation in LINE.
20605 IND is a cons cell with target and minimum indentation.
20606 If the current indentation in LINE is smaller than the minimum,
20607 leave it alone. If it is larger than ind, set it to the target."
20608 (let* ((l (org-remove-tabs line))
20609 (i (org-get-indentation l))
20610 (i1 (car ind)) (i2 (cdr ind)))
20611 (if (>= i i2) (setq l (substring line i2)))
20612 (if (> i1 0)
20613 (concat (make-string i1 ?\ ) l)
20614 l)))
20616 (defun org-remove-indentation (code &optional n)
20617 "Remove the maximum common indentation from the lines in CODE.
20618 N may optionally be the number of spaces to remove."
20619 (with-temp-buffer
20620 (insert code)
20621 (org-do-remove-indentation n)
20622 (buffer-string)))
20624 (defun org-do-remove-indentation (&optional n)
20625 "Remove the maximum common indentation from the buffer."
20626 (untabify (point-min) (point-max))
20627 (let ((min 10000) re)
20628 (if n
20629 (setq min n)
20630 (goto-char (point-min))
20631 (while (re-search-forward "^ *[^ \n]" nil t)
20632 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20633 (unless (or (= min 0) (= min 10000))
20634 (setq re (format "^ \\{%d\\}" min))
20635 (goto-char (point-min))
20636 (while (re-search-forward re nil t)
20637 (replace-match "")
20638 (end-of-line 1))
20639 min)))
20641 (defun org-fill-template (template alist)
20642 "Find each %key of ALIST in TEMPLATE and replace it."
20643 (let ((case-fold-search nil)
20644 entry key value)
20645 (setq alist (sort (copy-sequence alist)
20646 (lambda (a b) (< (length (car a)) (length (car b))))))
20647 (while (setq entry (pop alist))
20648 (setq template
20649 (replace-regexp-in-string
20650 (concat "%" (regexp-quote (car entry)))
20651 (or (cdr entry) "") template t t)))
20652 template))
20654 (defun org-base-buffer (buffer)
20655 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20656 (if (not buffer)
20657 buffer
20658 (or (buffer-base-buffer buffer)
20659 buffer)))
20661 (defun org-trim (s)
20662 "Remove whitespace at beginning and end of string."
20663 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20664 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20667 (defun org-wrap (string &optional width lines)
20668 "Wrap string to either a number of lines, or a width in characters.
20669 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20670 that costs. If there is a word longer than WIDTH, the text is actually
20671 wrapped to the length of that word.
20672 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20673 many lines, whatever width that takes.
20674 The return value is a list of lines, without newlines at the end."
20675 (let* ((words (org-split-string string "[ \t\n]+"))
20676 (maxword (apply 'max (mapcar 'org-string-width words)))
20677 w ll)
20678 (cond (width
20679 (org-do-wrap words (max maxword width)))
20680 (lines
20681 (setq w maxword)
20682 (setq ll (org-do-wrap words maxword))
20683 (if (<= (length ll) lines)
20685 (setq ll words)
20686 (while (> (length ll) lines)
20687 (setq w (1+ w))
20688 (setq ll (org-do-wrap words w)))
20689 ll))
20690 (t (error "Cannot wrap this")))))
20692 (defun org-do-wrap (words width)
20693 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20694 (let (lines line)
20695 (while words
20696 (setq line (pop words))
20697 (while (and words (< (+ (length line) (length (car words))) width))
20698 (setq line (concat line " " (pop words))))
20699 (setq lines (push line lines)))
20700 (nreverse lines)))
20702 (defun org-split-string (string &optional separators)
20703 "Splits STRING into substrings at SEPARATORS.
20704 No empty strings are returned if there are matches at the beginning
20705 and end of string."
20706 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20707 (start 0)
20708 notfirst
20709 (list nil))
20710 (while (and (string-match rexp string
20711 (if (and notfirst
20712 (= start (match-beginning 0))
20713 (< start (length string)))
20714 (1+ start) start))
20715 (< (match-beginning 0) (length string)))
20716 (setq notfirst t)
20717 (or (eq (match-beginning 0) 0)
20718 (and (eq (match-beginning 0) (match-end 0))
20719 (eq (match-beginning 0) start))
20720 (setq list
20721 (cons (substring string start (match-beginning 0))
20722 list)))
20723 (setq start (match-end 0)))
20724 (or (eq start (length string))
20725 (setq list
20726 (cons (substring string start)
20727 list)))
20728 (nreverse list)))
20730 (defun org-quote-vert (s)
20731 "Replace \"|\" with \"\\vert\"."
20732 (while (string-match "|" s)
20733 (setq s (replace-match "\\vert" t t s)))
20736 (defun org-uuidgen-p (s)
20737 "Is S an ID created by UUIDGEN?"
20738 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20740 (defun org-in-src-block-p (&optional inside)
20741 "Whether point is in a code source block.
20742 When INSIDE is non-nil, don't consider we are within a src block
20743 when point is at #+BEGIN_SRC or #+END_SRC."
20744 (let ((case-fold-search t) ov)
20745 (or (and (setq ov (overlays-at (point)))
20746 (memq 'org-block-background
20747 (overlay-properties (car ov))))
20748 (and (not inside)
20749 (save-match-data
20750 (save-excursion
20751 (beginning-of-line)
20752 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20754 (defun org-context ()
20755 "Return a list of contexts of the current cursor position.
20756 If several contexts apply, all are returned.
20757 Each context entry is a list with a symbol naming the context, and
20758 two positions indicating start and end of the context. Possible
20759 contexts are:
20761 :headline anywhere in a headline
20762 :headline-stars on the leading stars in a headline
20763 :todo-keyword on a TODO keyword (including DONE) in a headline
20764 :tags on the TAGS in a headline
20765 :priority on the priority cookie in a headline
20766 :item on the first line of a plain list item
20767 :item-bullet on the bullet/number of a plain list item
20768 :checkbox on the checkbox in a plain list item
20769 :table in an org-mode table
20770 :table-special on a special filed in a table
20771 :table-table in a table.el table
20772 :clocktable in a clocktable
20773 :src-block in a source block
20774 :link on a hyperlink
20775 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20776 :target on a <<target>>
20777 :radio-target on a <<<radio-target>>>
20778 :latex-fragment on a LaTeX fragment
20779 :latex-preview on a LaTeX fragment with overlaid preview image
20781 This function expects the position to be visible because it uses font-lock
20782 faces as a help to recognize the following contexts: :table-special, :link,
20783 and :keyword."
20784 (let* ((f (get-text-property (point) 'face))
20785 (faces (if (listp f) f (list f)))
20786 (case-fold-search t)
20787 (p (point)) clist o)
20788 ;; First the large context
20789 (cond
20790 ((org-at-heading-p t)
20791 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20792 (when (progn
20793 (beginning-of-line 1)
20794 (looking-at org-todo-line-tags-regexp))
20795 (push (org-point-in-group p 1 :headline-stars) clist)
20796 (push (org-point-in-group p 2 :todo-keyword) clist)
20797 (push (org-point-in-group p 4 :tags) clist))
20798 (goto-char p)
20799 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20800 (if (looking-at "\\[#[A-Z0-9]\\]")
20801 (push (org-point-in-group p 0 :priority) clist)))
20803 ((org-at-item-p)
20804 (push (org-point-in-group p 2 :item-bullet) clist)
20805 (push (list :item (point-at-bol)
20806 (save-excursion (org-end-of-item) (point)))
20807 clist)
20808 (and (org-at-item-checkbox-p)
20809 (push (org-point-in-group p 0 :checkbox) clist)))
20811 ((org-at-table-p)
20812 (push (list :table (org-table-begin) (org-table-end)) clist)
20813 (if (memq 'org-formula faces)
20814 (push (list :table-special
20815 (previous-single-property-change p 'face)
20816 (next-single-property-change p 'face)) clist)))
20817 ((org-at-table-p 'any)
20818 (push (list :table-table) clist)))
20819 (goto-char p)
20821 (let ((case-fold-search t))
20822 ;; New the "medium" contexts: clocktables, source blocks
20823 (cond ((org-in-clocktable-p)
20824 (push (list :clocktable
20825 (and (or (looking-at "#\\+BEGIN: clocktable")
20826 (search-backward "#+BEGIN: clocktable" nil t))
20827 (match-beginning 0))
20828 (and (re-search-forward "#\\+END:?" nil t)
20829 (match-end 0))) clist))
20830 ((org-in-src-block-p)
20831 (push (list :src-block
20832 (and (or (looking-at "#\\+BEGIN_SRC")
20833 (search-backward "#+BEGIN_SRC" nil t))
20834 (match-beginning 0))
20835 (and (search-forward "#+END_SRC" nil t)
20836 (match-beginning 0))) clist))))
20837 (goto-char p)
20839 ;; Now the small context
20840 (cond
20841 ((org-at-timestamp-p)
20842 (push (org-point-in-group p 0 :timestamp) clist))
20843 ((memq 'org-link faces)
20844 (push (list :link
20845 (previous-single-property-change p 'face)
20846 (next-single-property-change p 'face)) clist))
20847 ((memq 'org-special-keyword faces)
20848 (push (list :keyword
20849 (previous-single-property-change p 'face)
20850 (next-single-property-change p 'face)) clist))
20851 ((org-at-target-p)
20852 (push (org-point-in-group p 0 :target) clist)
20853 (goto-char (1- (match-beginning 0)))
20854 (if (looking-at org-radio-target-regexp)
20855 (push (org-point-in-group p 0 :radio-target) clist))
20856 (goto-char p))
20857 ((setq o (car (delq nil
20858 (mapcar
20859 (lambda (x)
20860 (if (memq x org-latex-fragment-image-overlays) x))
20861 (overlays-at (point))))))
20862 (push (list :latex-fragment
20863 (overlay-start o) (overlay-end o)) clist)
20864 (push (list :latex-preview
20865 (overlay-start o) (overlay-end o)) clist))
20866 ((org-inside-LaTeX-fragment-p)
20867 ;; FIXME: positions wrong.
20868 (push (list :latex-fragment (point) (point)) clist)))
20870 (setq clist (nreverse (delq nil clist)))
20871 clist))
20873 ;; FIXME: Compare with at-regexp-p Do we need both?
20874 (defun org-in-regexp (re &optional nlines visually)
20875 "Check if point is inside a match of regexp.
20876 Normally only the current line is checked, but you can include NLINES extra
20877 lines both before and after point into the search.
20878 If VISUALLY is set, require that the cursor is not after the match but
20879 really on, so that the block visually is on the match."
20880 (catch 'exit
20881 (let ((pos (point))
20882 (eol (point-at-eol (+ 1 (or nlines 0))))
20883 (inc (if visually 1 0)))
20884 (save-excursion
20885 (beginning-of-line (- 1 (or nlines 0)))
20886 (while (re-search-forward re eol t)
20887 (if (and (<= (match-beginning 0) pos)
20888 (>= (+ inc (match-end 0)) pos))
20889 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20891 (defun org-at-regexp-p (regexp)
20892 "Is point inside a match of REGEXP in the current line?"
20893 (catch 'exit
20894 (save-excursion
20895 (let ((pos (point)) (end (point-at-eol)))
20896 (beginning-of-line 1)
20897 (while (re-search-forward regexp end t)
20898 (if (and (<= (match-beginning 0) pos)
20899 (>= (match-end 0) pos))
20900 (throw 'exit t)))
20901 nil))))
20903 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20904 "Non-nil when point is between matches of START-RE and END-RE.
20906 Also return a non-nil value when point is on one of the matches.
20908 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20909 buffer positions. Default values are the positions of headlines
20910 surrounding the point.
20912 The functions returns a cons cell whose car (resp. cdr) is the
20913 position before START-RE (resp. after END-RE)."
20914 (save-match-data
20915 (let ((pos (point))
20916 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20917 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20918 beg end)
20919 (save-excursion
20920 ;; Point is on a block when on START-RE or if START-RE can be
20921 ;; found before it...
20922 (and (or (org-at-regexp-p start-re)
20923 (re-search-backward start-re limit-up t))
20924 (setq beg (match-beginning 0))
20925 ;; ... and END-RE after it...
20926 (goto-char (match-end 0))
20927 (re-search-forward end-re limit-down t)
20928 (> (setq end (match-end 0)) pos)
20929 ;; ... without another START-RE in-between.
20930 (goto-char (match-beginning 0))
20931 (not (re-search-backward start-re (1+ beg) t))
20932 ;; Return value.
20933 (cons beg end))))))
20935 (defun org-in-block-p (names)
20936 "Non-nil when point belongs to a block whose name belongs to NAMES.
20938 NAMES is a list of strings containing names of blocks.
20940 Return first block name matched, or nil. Beware that in case of
20941 nested blocks, the returned name may not belong to the closest
20942 block from point."
20943 (save-match-data
20944 (catch 'exit
20945 (let ((case-fold-search t)
20946 (lim-up (save-excursion (outline-previous-heading)))
20947 (lim-down (save-excursion (outline-next-heading))))
20948 (mapc (lambda (name)
20949 (let ((n (regexp-quote name)))
20950 (when (org-between-regexps-p
20951 (concat "^[ \t]*#\\+begin_" n)
20952 (concat "^[ \t]*#\\+end_" n)
20953 lim-up lim-down)
20954 (throw 'exit n))))
20955 names))
20956 nil)))
20958 (defun org-occur-in-agenda-files (regexp &optional nlines)
20959 "Call `multi-occur' with buffers for all agenda files."
20960 (interactive "sOrg-files matching: \np")
20961 (let* ((files (org-agenda-files))
20962 (tnames (mapcar 'file-truename files))
20963 (extra org-agenda-text-search-extra-files)
20965 (when (eq (car extra) 'agenda-archives)
20966 (setq extra (cdr extra))
20967 (setq files (org-add-archive-files files)))
20968 (while (setq f (pop extra))
20969 (unless (member (file-truename f) tnames)
20970 (add-to-list 'files f 'append)
20971 (add-to-list 'tnames (file-truename f) 'append)))
20972 (multi-occur
20973 (mapcar (lambda (x)
20974 (with-current-buffer
20975 (or (get-file-buffer x) (find-file-noselect x))
20976 (widen)
20977 (current-buffer)))
20978 files)
20979 regexp)))
20981 (if (boundp 'occur-mode-find-occurrence-hook)
20982 ;; Emacs 23
20983 (add-hook 'occur-mode-find-occurrence-hook
20984 (lambda ()
20985 (when (derived-mode-p 'org-mode)
20986 (org-reveal))))
20987 ;; Emacs 22
20988 (defadvice occur-mode-goto-occurrence
20989 (after org-occur-reveal activate)
20990 (and (derived-mode-p 'org-mode) (org-reveal)))
20991 (defadvice occur-mode-goto-occurrence-other-window
20992 (after org-occur-reveal activate)
20993 (and (derived-mode-p 'org-mode) (org-reveal)))
20994 (defadvice occur-mode-display-occurrence
20995 (after org-occur-reveal activate)
20996 (when (derived-mode-p 'org-mode)
20997 (let ((pos (occur-mode-find-occurrence)))
20998 (with-current-buffer (marker-buffer pos)
20999 (save-excursion
21000 (goto-char pos)
21001 (org-reveal)))))))
21003 (defun org-occur-link-in-agenda-files ()
21004 "Create a link and search for it in the agendas.
21005 The link is not stored in `org-stored-links', it is just created
21006 for the search purpose."
21007 (interactive)
21008 (let ((link (condition-case nil
21009 (org-store-link nil)
21010 (error "Unable to create a link to here"))))
21011 (org-occur-in-agenda-files (regexp-quote link))))
21013 (defun org-uniquify (list)
21014 "Remove duplicate elements from LIST."
21015 (let (res)
21016 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21017 res))
21019 (defun org-delete-all (elts list)
21020 "Remove all elements in ELTS from LIST."
21021 (while elts
21022 (setq list (delete (pop elts) list)))
21023 list)
21025 (defun org-count (cl-item cl-seq)
21026 "Count the number of occurrences of ITEM in SEQ.
21027 Taken from `count' in cl-seq.el with all keyword arguments removed."
21028 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21029 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21030 (while (< cl-start cl-end)
21031 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21032 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21033 (setq cl-start (1+ cl-start)))
21034 cl-count))
21036 (defun org-remove-if (predicate seq)
21037 "Remove everything from SEQ that fulfills PREDICATE."
21038 (let (res e)
21039 (while seq
21040 (setq e (pop seq))
21041 (if (not (funcall predicate e)) (push e res)))
21042 (nreverse res)))
21044 (defun org-remove-if-not (predicate seq)
21045 "Remove everything from SEQ that does not fulfill PREDICATE."
21046 (let (res e)
21047 (while seq
21048 (setq e (pop seq))
21049 (if (funcall predicate e) (push e res)))
21050 (nreverse res)))
21052 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21053 "Reduce two-argument FUNCTION across SEQ.
21054 Taken from `reduce' in cl-seq.el with all keyword arguments but
21055 \":initial-value\" removed."
21056 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21057 (cadr (memq :initial-value cl-keys)))
21058 (cl-seq (pop cl-seq))
21059 (t (funcall cl-func)))))
21060 (while cl-seq
21061 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21062 cl-accum))
21064 (defun org-back-over-empty-lines ()
21065 "Move backwards over whitespace, to the beginning of the first empty line.
21066 Returns the number of empty lines passed."
21067 (let ((pos (point)))
21068 (if (cdr (assoc 'heading org-blank-before-new-entry))
21069 (skip-chars-backward " \t\n\r")
21070 (unless (eobp)
21071 (forward-line -1)))
21072 (beginning-of-line 2)
21073 (goto-char (min (point) pos))
21074 (count-lines (point) pos)))
21076 (defun org-skip-whitespace ()
21077 (skip-chars-forward " \t\n\r"))
21079 (defun org-point-in-group (point group &optional context)
21080 "Check if POINT is in match-group GROUP.
21081 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21082 match. If the match group does not exist or point is not inside it,
21083 return nil."
21084 (and (match-beginning group)
21085 (>= point (match-beginning group))
21086 (<= point (match-end group))
21087 (if context
21088 (list context (match-beginning group) (match-end group))
21089 t)))
21091 (defun org-switch-to-buffer-other-window (&rest args)
21092 "Switch to buffer in a second window on the current frame.
21093 In particular, do not allow pop-up frames.
21094 Returns the newly created buffer."
21095 (org-no-popups
21096 (apply 'switch-to-buffer-other-window args)))
21098 (defun org-combine-plists (&rest plists)
21099 "Create a single property list from all plists in PLISTS.
21100 The process starts by copying the first list, and then setting properties
21101 from the other lists. Settings in the last list are the most significant
21102 ones and overrule settings in the other lists."
21103 (let ((rtn (copy-sequence (pop plists)))
21104 p v ls)
21105 (while plists
21106 (setq ls (pop plists))
21107 (while ls
21108 (setq p (pop ls) v (pop ls))
21109 (setq rtn (plist-put rtn p v))))
21110 rtn))
21112 (defun org-replace-escapes (string table)
21113 "Replace %-escapes in STRING with values in TABLE.
21114 TABLE is an association list with keys like \"%a\" and string values.
21115 The sequences in STRING may contain normal field width and padding information,
21116 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21117 so values can contain further %-escapes if they are define later in TABLE."
21118 (let ((tbl (copy-alist table))
21119 (case-fold-search nil)
21120 (pchg 0)
21121 e re rpl)
21122 (while (setq e (pop tbl))
21123 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21124 (when (and (cdr e) (string-match re (cdr e)))
21125 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21126 (safe "SREF"))
21127 (add-text-properties 0 3 (list 'sref sref) safe)
21128 (setcdr e (replace-match safe t t (cdr e)))))
21129 (while (string-match re string)
21130 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21131 (cdr e)))
21132 (setq string (replace-match rpl t t string))))
21133 (while (setq pchg (next-property-change pchg string))
21134 (let ((sref (get-text-property pchg 'sref string)))
21135 (when (and sref (string-match "SREF" string pchg))
21136 (setq string (replace-match sref t t string)))))
21137 string))
21139 (defun org-sublist (list start end)
21140 "Return a section of LIST, from START to END.
21141 Counting starts at 1."
21142 (let (rtn (c start))
21143 (setq list (nthcdr (1- start) list))
21144 (while (and list (<= c end))
21145 (push (pop list) rtn)
21146 (setq c (1+ c)))
21147 (nreverse rtn)))
21149 (defun org-find-base-buffer-visiting (file)
21150 "Like `find-buffer-visiting' but always return the base buffer and
21151 not an indirect buffer."
21152 (let ((buf (or (get-file-buffer file)
21153 (find-buffer-visiting file))))
21154 (if buf
21155 (or (buffer-base-buffer buf) buf)
21156 nil)))
21158 (defun org-image-file-name-regexp (&optional extensions)
21159 "Return regexp matching the file names of images.
21160 If EXTENSIONS is given, only match these."
21161 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21162 (image-file-name-regexp)
21163 (let ((image-file-name-extensions
21164 (or extensions
21165 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21166 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21167 (concat "\\."
21168 (regexp-opt (nconc (mapcar 'upcase
21169 image-file-name-extensions)
21170 image-file-name-extensions)
21172 "\\'"))))
21174 (defun org-file-image-p (file &optional extensions)
21175 "Return non-nil if FILE is an image."
21176 (save-match-data
21177 (string-match (org-image-file-name-regexp extensions) file)))
21179 (defun org-get-cursor-date (&optional with-time)
21180 "Return the date at cursor in as a time.
21181 This works in the calendar and in the agenda, anywhere else it just
21182 returns the current time.
21183 If WITH-TIME is non-nil, returns the time of the event at point (in
21184 the agenda) or the current time of the day."
21185 (let (date day defd tp tm hod mod)
21186 (when with-time
21187 (setq tp (get-text-property (point) 'time))
21188 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21189 (setq hod (string-to-number (match-string 1 tp))
21190 mod (string-to-number (match-string 2 tp))))
21191 (or tp (setq hod (nth 2 (decode-time (current-time)))
21192 mod (nth 1 (decode-time (current-time))))))
21193 (cond
21194 ((eq major-mode 'calendar-mode)
21195 (setq date (calendar-cursor-to-date)
21196 defd (encode-time 0 (or mod 0) (or hod 0)
21197 (nth 1 date) (nth 0 date) (nth 2 date))))
21198 ((eq major-mode 'org-agenda-mode)
21199 (setq day (get-text-property (point) 'day))
21200 (if day
21201 (setq date (calendar-gregorian-from-absolute day)
21202 defd (encode-time 0 (or mod 0) (or hod 0)
21203 (nth 1 date) (nth 0 date) (nth 2 date))))))
21204 (or defd (current-time))))
21206 (defun org-mark-subtree (&optional up)
21207 "Mark the current subtree.
21208 This puts point at the start of the current subtree, and mark at
21209 the end. If a numeric prefix UP is given, move up into the
21210 hierarchy of headlines by UP levels before marking the subtree."
21211 (interactive "P")
21212 (org-with-limited-levels
21213 (cond ((org-at-heading-p) (beginning-of-line))
21214 ((org-before-first-heading-p) (error "Not in a subtree"))
21215 (t (outline-previous-visible-heading 1))))
21216 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21217 (if (org-called-interactively-p 'any)
21218 (call-interactively 'org-mark-element)
21219 (org-mark-element)))
21222 ;;; Macros
21224 ;; Macros are expanded with `org-macro-replace-all', which relies
21225 ;; internally on `org-macro-expand'.
21227 ;; Default templates for expansion are stored in the buffer-local
21228 ;; variable `org-macro-templates'. This variable is updated by
21229 ;; `org-macro-initialize-templates'.
21231 ;; Along with macros defined through #+MACRO: keyword, default
21232 ;; templates include the following hard-coded macros:
21233 ;; {{{time(format-string)}}}, {{{property(node-property)}}},
21234 ;; {{{input-file}}} and {{{modification-time(format-string)}}}.
21236 ;; During export, {{{author}}}, {{{date}}}, {{{email}}} and
21237 ;; {{{title}}} will also be provided.
21240 (defvar org-macro-templates nil
21241 "Alist containing all macro templates in current buffer.
21242 Associations are in the shape of (NAME . TEMPLATE) where NAME
21243 stands for macro's name and template for its replacement value,
21244 both as strings. This is an internal variable. Do not set it
21245 directly, use instead:
21247 #+MACRO: name template")
21248 (make-variable-buffer-local 'org-macro-templates)
21250 (defun org-macro-expand (macro templates)
21251 "Return expanded MACRO, as a string.
21252 MACRO is an object, obtained, for example, with
21253 `org-element-context'. TEMPLATES is an alist of templates used
21254 for expansion. See `org-macro-templates' for a buffer-local
21255 default value. Return nil if no template was found."
21256 (let ((template
21257 ;; Macro names are case-insensitive.
21258 (cdr (assoc-string (org-element-property :key macro) templates t))))
21259 (when template
21260 (let ((value (replace-regexp-in-string
21261 "\\$[0-9]+"
21262 (lambda (arg)
21263 (or (nth (1- (string-to-number (substring arg 1)))
21264 (org-element-property :args macro))
21265 ;; No argument provided: remove
21266 ;; place-holder.
21267 ""))
21268 template)))
21269 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
21270 (when (string-match "\\`(eval\\>" value)
21271 (setq value (eval (read value))))
21272 ;; Return string.
21273 (format "%s" (or value ""))))))
21275 (defun org-macro-replace-all (templates)
21276 "Replace all macros in current buffer by their expansion.
21277 TEMPLATES is an alist of templates used for expansion. See
21278 `org-macro-templates' for a buffer-local default value."
21279 (save-excursion
21280 (goto-char (point-min))
21281 (let (record)
21282 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
21283 (let ((object (org-element-context)))
21284 (when (eq (org-element-type object) 'macro)
21285 (let* ((value (org-macro-expand object templates))
21286 (begin (org-element-property :begin object))
21287 (signature (list begin
21288 object
21289 (org-element-property :args object))))
21290 ;; Avoid circular dependencies by checking if the same
21291 ;; macro with the same arguments is expanded at the same
21292 ;; position twice.
21293 (if (member signature record)
21294 (error "Circular macro expansion: %s"
21295 (org-element-property :key object))
21296 (when value
21297 (push signature record)
21298 (delete-region
21299 begin
21300 ;; Preserve white spaces after the macro.
21301 (progn (goto-char (org-element-property :end object))
21302 (skip-chars-backward " \t")
21303 (point)))
21304 ;; Leave point before replacement in case of recursive
21305 ;; expansions.
21306 (save-excursion (insert value)))))))))))
21308 (defun org-macro-initialize-templates ()
21309 "Collect macro templates defined in current buffer.
21310 Templates are stored in buffer-local variable
21311 `org-macro-templates'. In addition to buffer-defined macros, the
21312 function installs the following ones: \"property\",
21313 \"time\". and, if the buffer is associated to a file,
21314 \"input-file\" and \"modification-time\"."
21315 (let ((case-fold-search t)
21316 (set-template
21317 (lambda (cell)
21318 ;; Add CELL to `org-macro-templates' if there's no
21319 ;; association matching its name already. Otherwise,
21320 ;; replace old association with the new one in that
21321 ;; variable.
21322 (let ((old-template (assoc (car cell) org-macro-templates)))
21323 (if old-template (setcdr old-template (cdr cell))
21324 (push cell org-macro-templates))))))
21325 ;; Install buffer-local macros.
21326 (org-with-wide-buffer
21327 (goto-char (point-min))
21328 (while (re-search-forward "^[ \t]*#\\+MACRO:" nil t)
21329 (let ((element (org-element-at-point)))
21330 (when (eq (org-element-type element) 'keyword)
21331 (let ((value (org-element-property :value element)))
21332 (when (string-match "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" value)
21333 (funcall set-template
21334 (cons (match-string 1 value)
21335 (or (match-string 2 value) "")))))))))
21336 ;; Install hard-coded macros.
21337 (mapc (lambda (cell) (funcall set-template cell))
21338 (list
21339 (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
21340 (cons "time" "(eval (format-time-string \"$1\"))")))
21341 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
21342 (when (and visited-file (file-exists-p visited-file))
21343 (mapc (lambda (cell) (funcall set-template cell))
21344 (list
21345 (cons "input-file" (file-name-nondirectory visited-file))
21346 (cons "modification-time"
21347 (format "(eval (format-time-string \"$1\" '%s))"
21348 (prin1-to-string
21349 (nth 5 (file-attributes visited-file)))))))))))
21352 ;;; Indentation
21354 (defun org-indent-line ()
21355 "Indent line depending on context."
21356 (interactive)
21357 (let* ((pos (point))
21358 (itemp (org-at-item-p))
21359 (case-fold-search t)
21360 (org-drawer-regexp (or org-drawer-regexp "\000"))
21361 (inline-task-p (and (featurep 'org-inlinetask)
21362 (org-inlinetask-in-task-p)))
21363 (inline-re (and inline-task-p
21364 (org-inlinetask-outline-regexp)))
21365 column)
21366 (if (and orgstruct-is-++ (eq pos (point)))
21367 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21368 (indent-according-to-mode))
21369 (beginning-of-line 1)
21370 (cond
21371 ;; Headings
21372 ((looking-at org-outline-regexp) (setq column 0))
21373 ;; Footnote definition
21374 ((looking-at org-footnote-definition-re) (setq column 0))
21375 ;; Literal examples
21376 ((looking-at "[ \t]*:\\( \\|$\\)")
21377 (setq column (org-get-indentation))) ; do nothing
21378 ;; Lists
21379 ((ignore-errors (goto-char (org-in-item-p)))
21380 (setq column (if itemp
21381 (org-get-indentation)
21382 (org-list-item-body-column (point))))
21383 (goto-char pos))
21384 ;; Drawers
21385 ((and (looking-at "[ \t]*:END:")
21386 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21387 (save-excursion
21388 (goto-char (1- (match-beginning 1)))
21389 (setq column (current-column))))
21390 ;; Special blocks
21391 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21392 (save-excursion
21393 (re-search-backward
21394 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21395 (setq column (org-get-indentation (match-string 0))))
21396 ((and (not (looking-at "[ \t]*#\\+begin_"))
21397 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21398 (save-excursion
21399 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21400 (setq column
21401 (cond ((equal (downcase (match-string 1)) "src")
21402 ;; src blocks: let `org-edit-src-exit' handle them
21403 (org-get-indentation))
21404 ((equal (downcase (match-string 1)) "example")
21405 (max (org-get-indentation)
21406 (org-get-indentation (match-string 0))))
21408 (org-get-indentation (match-string 0))))))
21409 ;; This line has nothing special, look at the previous relevant
21410 ;; line to compute indentation
21412 (beginning-of-line 0)
21413 (while (and (not (bobp))
21414 (not (looking-at org-table-line-regexp))
21415 (not (looking-at org-drawer-regexp))
21416 ;; When point started in an inline task, do not move
21417 ;; above task starting line.
21418 (not (and inline-task-p (looking-at inline-re)))
21419 ;; Skip drawers, blocks, empty lines, verbatim,
21420 ;; comments, tables, footnotes definitions, lists,
21421 ;; inline tasks.
21422 (or (and (looking-at "[ \t]*:END:")
21423 (re-search-backward org-drawer-regexp nil t))
21424 (and (looking-at "[ \t]*#\\+end_")
21425 (re-search-backward "[ \t]*#\\+begin_"nil t))
21426 (looking-at "[ \t]*[\n:#|]")
21427 (looking-at org-footnote-definition-re)
21428 (and (ignore-errors (goto-char (org-in-item-p)))
21429 (goto-char
21430 (org-list-get-top-point (org-list-struct))))
21431 (and (not inline-task-p)
21432 (featurep 'org-inlinetask)
21433 (org-inlinetask-in-task-p)
21434 (or (org-inlinetask-goto-beginning) t))))
21435 (beginning-of-line 0))
21436 (cond
21437 ;; There was an heading above.
21438 ((looking-at "\\*+[ \t]+")
21439 (if (not org-adapt-indentation)
21440 (setq column 0)
21441 (goto-char (match-end 0))
21442 (setq column (current-column))))
21443 ;; A drawer had started and is unfinished
21444 ((looking-at org-drawer-regexp)
21445 (goto-char (1- (match-beginning 1)))
21446 (setq column (current-column)))
21447 ;; Else, nothing noticeable found: get indentation and go on.
21448 (t (setq column (org-get-indentation))))))
21449 ;; Now apply indentation and move cursor accordingly
21450 (goto-char pos)
21451 (if (<= (current-column) (current-indentation))
21452 (org-indent-line-to column)
21453 (save-excursion (org-indent-line-to column)))
21454 ;; Special polishing for properties, see `org-property-format'
21455 (setq column (current-column))
21456 (beginning-of-line 1)
21457 (if (looking-at
21458 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21459 (replace-match (concat (match-string 1)
21460 (format org-property-format
21461 (match-string 2) (match-string 3)))
21462 t t))
21463 (org-move-to-column column))))
21465 (defun org-indent-drawer ()
21466 "Indent the drawer at point."
21467 (interactive)
21468 (let ((p (point))
21469 (e (and (save-excursion (re-search-forward ":END:" nil t))
21470 (match-end 0)))
21471 (folded
21472 (save-excursion
21473 (end-of-line)
21474 (when (overlays-at (point))
21475 (member 'invisible (overlay-properties
21476 (car (overlays-at (point)))))))))
21477 (when folded (org-cycle))
21478 (indent-for-tab-command)
21479 (while (and (move-beginning-of-line 2) (< (point) e))
21480 (indent-for-tab-command))
21481 (goto-char p)
21482 (when folded (org-cycle)))
21483 (message "Drawer at point indented"))
21485 (defun org-indent-block ()
21486 "Indent the block at point."
21487 (interactive)
21488 (let ((p (point))
21489 (case-fold-search t)
21490 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21491 (match-end 0)))
21492 (folded
21493 (save-excursion
21494 (end-of-line)
21495 (when (overlays-at (point))
21496 (member 'invisible (overlay-properties
21497 (car (overlays-at (point)))))))))
21498 (when folded (org-cycle))
21499 (indent-for-tab-command)
21500 (while (and (move-beginning-of-line 2) (< (point) e))
21501 (indent-for-tab-command))
21502 (goto-char p)
21503 (when folded (org-cycle)))
21504 (message "Block at point indented"))
21506 (defun org-indent-region (start end)
21507 "Indent region."
21508 (interactive "r")
21509 (save-excursion
21510 (let ((line-end (org-current-line end)))
21511 (goto-char start)
21512 (while (< (org-current-line) line-end)
21513 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21514 (t (call-interactively 'org-indent-line)))
21515 (move-beginning-of-line 2)))))
21518 ;;; Filling
21520 ;; We use our own fill-paragraph and auto-fill functions.
21522 ;; `org-fill-paragraph' relies on adaptive filling and context
21523 ;; checking. Appropriate `fill-prefix' is computed with
21524 ;; `org-adaptive-fill-function'.
21526 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21527 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21528 ;; `org-adaptive-fill-function' value. Internally,
21529 ;; `org-comment-line-break-function' breaks the line.
21531 ;; `org-setup-filling' installs filling and auto-filling related
21532 ;; variables during `org-mode' initialization.
21534 (defun org-setup-filling ()
21535 (interactive)
21536 ;; Prevent auto-fill from inserting unwanted new items.
21537 (when (boundp 'fill-nobreak-predicate)
21538 (org-set-local
21539 'fill-nobreak-predicate
21540 (org-uniquify
21541 (append fill-nobreak-predicate
21542 '(org-fill-paragraph-separate-nobreak-p
21543 org-fill-line-break-nobreak-p)))))
21544 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21545 (org-set-local 'auto-fill-inhibit-regexp nil)
21546 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21547 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21548 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21550 (defvar org-element-paragraph-separate) ; org-element.el
21551 (defun org-fill-paragraph-separate-nobreak-p ()
21552 "Non-nil when a line break at point would insert a new item."
21553 (looking-at (substring org-element-paragraph-separate 1)))
21555 (defun org-fill-line-break-nobreak-p ()
21556 "Non-nil when a line break at point would create an Org line break."
21557 (save-excursion
21558 (skip-chars-backward "[ \t]")
21559 (skip-chars-backward "\\\\")
21560 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21562 (declare-function message-in-body-p "message" ())
21563 (defvar orgtbl-line-start-regexp) ; From org-table.el
21564 (defun org-adaptive-fill-function ()
21565 "Compute a fill prefix for the current line.
21566 Return fill prefix, as a string, or nil if current line isn't
21567 meant to be filled."
21568 (let (prefix)
21569 (catch 'exit
21570 (when (derived-mode-p 'message-mode)
21571 (save-excursion
21572 (beginning-of-line)
21573 (cond ((or (not (message-in-body-p))
21574 (looking-at orgtbl-line-start-regexp))
21575 (throw 'exit nil))
21576 ((looking-at message-cite-prefix-regexp)
21577 (throw 'exit (match-string-no-properties 0)))
21578 ((looking-at org-outline-regexp)
21579 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21580 (org-with-wide-buffer
21581 (let* ((p (line-beginning-position))
21582 (element (save-excursion (beginning-of-line)
21583 (org-element-at-point)))
21584 (type (org-element-type element))
21585 (post-affiliated (org-element-property :post-affiliated element)))
21586 (unless (and post-affiliated (< p post-affiliated))
21587 (case type
21588 (comment (looking-at "[ \t]*# ?") (match-string 0))
21589 (footnote-definition "")
21590 ((item plain-list)
21591 (make-string (org-list-item-body-column
21592 (or post-affiliated
21593 (org-element-property :begin element)))
21594 ? ))
21595 (paragraph
21596 ;; Fill prefix is usually the same as the current line,
21597 ;; except if the paragraph is at the beginning of an item.
21598 (let ((parent (org-element-property :parent element)))
21599 (cond ((eq (org-element-type parent) 'item)
21600 (make-string (org-list-item-body-column
21601 (org-element-property :begin parent))
21602 ? ))
21603 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21604 (match-string 0))
21605 (t ""))))
21606 (comment-block
21607 ;; Only fill contents if P is within block boundaries.
21608 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21609 (forward-line)
21610 (point)))
21611 (cend (save-excursion
21612 (goto-char (org-element-property :end element))
21613 (skip-chars-backward " \r\t\n")
21614 (line-beginning-position))))
21615 (when (and (>= p cbeg) (< p cend))
21616 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21617 (match-string 0)
21618 "")))))))))))
21620 (declare-function message-goto-body "message" ())
21621 (defvar message-cite-prefix-regexp) ; From message.el
21622 (defvar org-element-all-objects) ; From org-element.el
21623 (defun org-fill-paragraph (&optional justify)
21624 "Fill element at point, when applicable.
21626 This function only applies to comment blocks, comments, example
21627 blocks and paragraphs. Also, as a special case, re-align table
21628 when point is at one.
21630 If JUSTIFY is non-nil (interactively, with prefix argument),
21631 justify as well. If `sentence-end-double-space' is non-nil, then
21632 period followed by one space does not end a sentence, so don't
21633 break a line there. The variable `fill-column' controls the
21634 width for filling.
21636 For convenience, when point is at a plain list, an item or
21637 a footnote definition, try to fill the first paragraph within."
21638 (interactive)
21639 (if (and (derived-mode-p 'message-mode)
21640 (or (not (message-in-body-p))
21641 (save-excursion (move-beginning-of-line 1)
21642 (looking-at message-cite-prefix-regexp))))
21643 ;; First ensure filling is correct in message-mode.
21644 (let ((fill-paragraph-function
21645 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21646 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21647 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21648 (paragraph-separate
21649 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21650 (fill-paragraph nil))
21651 (save-excursion
21652 ;; Move to end of line in order to get the first paragraph
21653 ;; within a plain list or a footnote definition.
21654 (end-of-line)
21655 (let ((element (org-element-at-point)))
21656 ;; First check if point is in a blank line at the beginning of
21657 ;; the buffer. In that case, ignore filling.
21658 (if (< (point) (org-element-property :begin element)) t
21659 (case (org-element-type element)
21660 ;; Use major mode filling function is src blocks.
21661 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21662 ;; Align Org tables, leave table.el tables as-is.
21663 (table-row (org-table-align) t)
21664 (table
21665 (when (eq (org-element-property :type element) 'org)
21666 (org-table-align))
21668 (paragraph
21669 ;; Paragraphs may contain `line-break' type objects.
21670 (let ((beg (max (point-min)
21671 (org-element-property :contents-begin element)))
21672 (end (min (point-max)
21673 (org-element-property :contents-end element))))
21674 ;; Do nothing if point is at an affiliated keyword.
21675 (if (< (point) beg) t
21676 (when (derived-mode-p 'message-mode)
21677 ;; In `message-mode', do not fill following
21678 ;; citation in current paragraph nor text before
21679 ;; message body.
21680 (let ((body-start (save-excursion (message-goto-body))))
21681 (when body-start (setq beg (max body-start beg))))
21682 (when (save-excursion
21683 (re-search-forward
21684 (concat "^" message-cite-prefix-regexp) end t))
21685 (setq end (match-beginning 0))))
21686 ;; Fill paragraph, taking line breaks into
21687 ;; consideration. For that, slice the paragraph
21688 ;; using line breaks as separators, and fill the
21689 ;; parts in reverse order to avoid messing with
21690 ;; markers.
21691 (save-excursion
21692 (goto-char end)
21693 (mapc
21694 (lambda (pos)
21695 (fill-region-as-paragraph pos (point) justify)
21696 (goto-char pos))
21697 ;; Find the list of ending positions for line
21698 ;; breaks in the current paragraph. Add paragraph
21699 ;; beginning to include first slice.
21700 (nreverse
21701 (cons
21703 (org-element-map
21704 (org-element--parse-objects
21705 beg end nil org-element-all-objects)
21706 'line-break
21707 (lambda (lb) (org-element-property :end lb)))))))
21708 t)))
21709 ;; Contents of `comment-block' type elements should be
21710 ;; filled as plain text, but only if point is within block
21711 ;; markers.
21712 (comment-block
21713 (let* ((case-fold-search t)
21714 (beg (save-excursion
21715 (goto-char (org-element-property :begin element))
21716 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21717 (forward-line)
21718 (point)))
21719 (end (save-excursion
21720 (goto-char (org-element-property :end element))
21721 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21722 (line-beginning-position))))
21723 (when (and (>= (point) beg) (< (point) end))
21724 (fill-region-as-paragraph
21725 (save-excursion
21726 (end-of-line)
21727 (re-search-backward "^[ \t]*$" beg 'move)
21728 (line-beginning-position))
21729 (save-excursion
21730 (beginning-of-line)
21731 (re-search-forward "^[ \t]*$" end 'move)
21732 (line-beginning-position))
21733 justify)))
21735 ;; Fill comments.
21736 (comment (fill-comment-paragraph justify))
21737 ;; Ignore every other element.
21738 (otherwise t)))))))
21740 (defun org-auto-fill-function ()
21741 "Auto-fill function."
21742 ;; Check if auto-filling is meaningful.
21743 (let ((fc (current-fill-column)))
21744 (when (and fc (> (current-column) fc))
21745 (let* ((fill-prefix (org-adaptive-fill-function))
21746 ;; Enforce empty fill prefix, if required. Otherwise, it
21747 ;; will be computed again.
21748 (adaptive-fill-mode (not (equal fill-prefix ""))))
21749 (when fill-prefix (do-auto-fill))))))
21751 (defun org-comment-line-break-function (&optional soft)
21752 "Break line at point and indent, continuing comment if within one.
21753 The inserted newline is marked hard if variable
21754 `use-hard-newlines' is true, unless optional argument SOFT is
21755 non-nil."
21756 (if soft (insert-and-inherit ?\n) (newline 1))
21757 (save-excursion (forward-char -1) (delete-horizontal-space))
21758 (delete-horizontal-space)
21759 (indent-to-left-margin)
21760 (insert-before-markers-and-inherit fill-prefix))
21763 ;;; Comments
21765 ;; Org comments syntax is quite complex. It requires the entire line
21766 ;; to be just a comment. Also, even with the right syntax at the
21767 ;; beginning of line, some some elements (i.e. verse-block or
21768 ;; example-block) don't accept comments. Usual Emacs comment commands
21769 ;; cannot cope with those requirements. Therefore, Org replaces them.
21771 ;; Org still relies on `comment-dwim', but cannot trust
21772 ;; `comment-only-p'. So, `comment-region-function' and
21773 ;; `uncomment-region-function' both point
21774 ;; to`org-comment-or-uncomment-region'. Eventually,
21775 ;; `org-insert-comment' takes care of insertion of comments at the
21776 ;; beginning of line.
21778 ;; `org-setup-comments-handling' install comments related variables
21779 ;; during `org-mode' initialization.
21781 (defun org-setup-comments-handling ()
21782 (interactive)
21783 (org-set-local 'comment-use-syntax nil)
21784 (org-set-local 'comment-start "# ")
21785 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21786 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21787 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21788 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21790 (defun org-insert-comment ()
21791 "Insert an empty comment above current line.
21792 If the line is empty, insert comment at its beginning."
21793 (beginning-of-line)
21794 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21795 (org-indent-line)
21796 (insert "# "))
21798 (defvar comment-empty-lines) ; From newcomment.el.
21799 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21800 "Comment or uncomment each non-blank line in the region.
21801 Uncomment each non-blank line between BEG and END if it only
21802 contains commented lines. Otherwise, comment them."
21803 (save-restriction
21804 ;; Restrict region
21805 (narrow-to-region (save-excursion (goto-char beg)
21806 (skip-chars-forward " \r\t\n" end)
21807 (line-beginning-position))
21808 (save-excursion (goto-char end)
21809 (skip-chars-backward " \r\t\n" beg)
21810 (line-end-position)))
21811 (let ((uncommentp
21812 ;; UNCOMMENTP is non-nil when every non blank line between
21813 ;; BEG and END is a comment.
21814 (save-excursion
21815 (goto-char (point-min))
21816 (while (and (not (eobp))
21817 (let ((element (org-element-at-point)))
21818 (and (eq (org-element-type element) 'comment)
21819 (goto-char (min (point-max)
21820 (org-element-property
21821 :end element)))))))
21822 (eobp))))
21823 (if uncommentp
21824 ;; Only blank lines and comments in region: uncomment it.
21825 (save-excursion
21826 (goto-char (point-min))
21827 (while (not (eobp))
21828 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21829 (replace-match "" nil nil nil 1))
21830 (forward-line)))
21831 ;; Comment each line in region.
21832 (let ((min-indent (point-max)))
21833 ;; First find the minimum indentation across all lines.
21834 (save-excursion
21835 (goto-char (point-min))
21836 (while (and (not (eobp)) (not (zerop min-indent)))
21837 (unless (looking-at "[ \t]*$")
21838 (setq min-indent (min min-indent (current-indentation))))
21839 (forward-line)))
21840 ;; Then loop over all lines.
21841 (save-excursion
21842 (goto-char (point-min))
21843 (while (not (eobp))
21844 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21845 (org-move-to-column min-indent t)
21846 (insert comment-start))
21847 (forward-line))))))))
21850 ;;; Planning
21852 ;; This section contains tools to operate on timestamp objects, as
21853 ;; returned by, e.g. `org-element-context'.
21855 (defun org-timestamp-has-time-p (timestamp)
21856 "Non-nil when TIMESTAMP has a time specified."
21857 (org-element-property :hour-start timestamp))
21859 (defun org-timestamp-format (timestamp format &optional end utc)
21860 "Format a TIMESTAMP element into a string.
21862 FORMAT is a format specifier to be passed to
21863 `format-time-string'.
21865 When optional argument END is non-nil, use end of date-range or
21866 time-range, if possible.
21868 When optional argument UTC is non-nil, time will be expressed as
21869 Universal Time."
21870 (format-time-string
21871 format
21872 (apply 'encode-time
21873 (cons 0
21874 (mapcar
21875 (lambda (prop) (or (org-element-property prop timestamp) 0))
21876 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
21877 '(:minute-start :hour-start :day-start :month-start
21878 :year-start)))))
21879 utc))
21881 (defun org-timestamp-split-range (timestamp &optional end)
21882 "Extract a timestamp object from a date or time range.
21884 TIMESTAMP is a timestamp object. END, when non-nil, means extract
21885 the end of the range. Otherwise, extract its start.
21887 Return a new timestamp object sharing the same parent as
21888 TIMESTAMP."
21889 (let ((type (org-element-property :type timestamp)))
21890 (if (memq type '(active inactive diary)) timestamp
21891 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
21892 ;; Set new type.
21893 (org-element-put-property
21894 split-ts :type (if (eq type 'active-range) 'active 'inactive))
21895 ;; Copy start properties over end properties if END is
21896 ;; non-nil. Otherwise, copy end properties over `start' ones.
21897 (let ((p-alist '((:minute-start . :minute-end)
21898 (:hour-start . :hour-end)
21899 (:day-start . :day-end)
21900 (:month-start . :month-end)
21901 (:year-start . :year-end))))
21902 (dolist (p-cell p-alist)
21903 (org-element-put-property
21904 split-ts
21905 (funcall (if end 'car 'cdr) p-cell)
21906 (org-element-property
21907 (funcall (if end 'cdr 'car) p-cell) split-ts)))
21908 ;; Eventually refresh `:raw-value'.
21909 (org-element-put-property split-ts :raw-value nil)
21910 (org-element-put-property
21911 split-ts :raw-value (org-element-interpret-data split-ts)))))))
21913 (defun org-timestamp-translate (timestamp &optional boundary)
21914 "Apply `org-translate-time' on a TIMESTAMP object.
21915 When optional argument BOUNDARY is non-nil, it is either the
21916 symbol `start' or `end'. In this case, only translate the
21917 starting or ending part of TIMESTAMP if it is a date or time
21918 range. Otherwise, translate both parts."
21919 (if (and (not boundary)
21920 (memq (org-element-property :type timestamp)
21921 '(active-range inactive-range)))
21922 (concat
21923 (org-translate-time
21924 (org-element-property :raw-value
21925 (org-timestamp-split-range timestamp)))
21926 "--"
21927 (org-translate-time
21928 (org-element-property :raw-value
21929 (org-timestamp-split-range timestamp t))))
21930 (org-translate-time
21931 (org-element-property
21932 :raw-value
21933 (if (not boundary) timestamp
21934 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
21938 ;;; Other stuff.
21940 (defun org-toggle-fixed-width-section (arg)
21941 "Toggle the fixed-width export.
21942 If there is no active region, the QUOTE keyword at the current headline is
21943 inserted or removed. When present, it causes the text between this headline
21944 and the next to be exported as fixed-width text, and unmodified.
21945 If there is an active region, this command adds or removes a colon as the
21946 first character of this line. If the first character of a line is a colon,
21947 this line is also exported in fixed-width font."
21948 (interactive "P")
21949 (let* ((cc 0)
21950 (regionp (org-region-active-p))
21951 (beg (if regionp (region-beginning) (point)))
21952 (end (if regionp (region-end)))
21953 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21954 (case-fold-search nil)
21955 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21956 off)
21957 (if regionp
21958 (save-excursion
21959 (goto-char beg)
21960 (setq cc (current-column))
21961 (beginning-of-line 1)
21962 (setq off (looking-at re))
21963 (while (> nlines 0)
21964 (setq nlines (1- nlines))
21965 (beginning-of-line 1)
21966 (cond
21967 (arg
21968 (org-move-to-column cc t)
21969 (insert ": \n")
21970 (forward-line -1))
21971 ((and off (looking-at re))
21972 (replace-match "" t t nil 1))
21973 ((not off) (org-move-to-column cc t) (insert ": ")))
21974 (forward-line 1)))
21975 (save-excursion
21976 (org-back-to-heading)
21977 (cond
21978 ((looking-at (format org-heading-keyword-regexp-format
21979 org-quote-string))
21980 (goto-char (match-end 1))
21981 (looking-at (concat " +" org-quote-string))
21982 (replace-match "" t t)
21983 (when (eolp) (insert " ")))
21984 ((looking-at org-outline-regexp)
21985 (goto-char (match-end 0))
21986 (insert org-quote-string " ")))))))
21988 (defun org-reftex-citation ()
21989 "Use reftex-citation to insert a citation into the buffer.
21990 This looks for a line like
21992 #+BIBLIOGRAPHY: foo plain option:-d
21994 and derives from it that foo.bib is the bibliography file relevant
21995 for this document. It then installs the necessary environment for RefTeX
21996 to work in this buffer and calls `reftex-citation' to insert a citation
21997 into the buffer.
21999 Export of such citations to both LaTeX and HTML is handled by the contributed
22000 package org-exp-bibtex by Taru Karttunen."
22001 (interactive)
22002 (let ((reftex-docstruct-symbol 'rds)
22003 (reftex-cite-format "\\cite{%l}")
22004 rds bib)
22005 (save-excursion
22006 (save-restriction
22007 (widen)
22008 (let ((case-fold-search t)
22009 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22010 (if (not (save-excursion
22011 (or (re-search-forward re nil t)
22012 (re-search-backward re nil t))))
22013 (error "No bibliography defined in file")
22014 (setq bib (concat (match-string 1) ".bib")
22015 rds (list (list 'bib bib)))))))
22016 (call-interactively 'reftex-citation)))
22018 ;;;; Functions extending outline functionality
22020 (defun org-beginning-of-line (&optional arg)
22021 "Go to the beginning of the current line. If that is invisible, continue
22022 to a visible line beginning. This makes the function of C-a more intuitive.
22023 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22024 first attempt, and only move to after the tags when the cursor is already
22025 beyond the end of the headline."
22026 (interactive "P")
22027 (let ((pos (point))
22028 (special (if (consp org-special-ctrl-a/e)
22029 (car org-special-ctrl-a/e)
22030 org-special-ctrl-a/e))
22031 refpos)
22032 (if (org-bound-and-true-p visual-line-mode)
22033 (beginning-of-visual-line 1)
22034 (beginning-of-line 1))
22035 (if (and arg (fboundp 'move-beginning-of-line))
22036 (call-interactively 'move-beginning-of-line)
22037 (if (bobp)
22039 (backward-char 1)
22040 (if (org-truely-invisible-p)
22041 (while (and (not (bobp)) (org-truely-invisible-p))
22042 (backward-char 1)
22043 (beginning-of-line 1))
22044 (forward-char 1))))
22045 (when special
22046 (cond
22047 ((and (looking-at org-complex-heading-regexp)
22048 (= (char-after (match-end 1)) ?\ ))
22049 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22050 (point-at-eol)))
22051 (goto-char
22052 (if (eq special t)
22053 (cond ((> pos refpos) refpos)
22054 ((= pos (point)) refpos)
22055 (t (point)))
22056 (cond ((> pos (point)) (point))
22057 ((not (eq last-command this-command)) (point))
22058 (t refpos)))))
22059 ((org-at-item-p)
22060 ;; Being at an item and not looking at an the item means point
22061 ;; was previously moved to beginning of a visual line, which
22062 ;; doesn't contain the item. Therefore, do nothing special,
22063 ;; just stay here.
22064 (when (looking-at org-list-full-item-re)
22065 ;; Set special position at first white space character after
22066 ;; bullet, and check-box, if any.
22067 (let ((after-bullet
22068 (let ((box (match-end 3)))
22069 (if (not box) (match-end 1)
22070 (let ((after (char-after box)))
22071 (if (and after (= after ? )) (1+ box) box))))))
22072 ;; Special case: Move point to special position when
22073 ;; currently after it or at beginning of line.
22074 (if (eq special t)
22075 (when (or (> pos after-bullet) (= (point) pos))
22076 (goto-char after-bullet))
22077 ;; Reversed case: Move point to special position when
22078 ;; point was already at beginning of line and command is
22079 ;; repeated.
22080 (when (and (= (point) pos) (eq last-command this-command))
22081 (goto-char after-bullet))))))))
22082 (org-no-warnings
22083 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22085 (defun org-end-of-line (&optional arg)
22086 "Go to the end of the line.
22087 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22088 tags on the first attempt, and only move to after the tags when
22089 the cursor is already beyond the end of the headline."
22090 (interactive "P")
22091 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22092 org-special-ctrl-a/e))
22093 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22094 'end-of-visual-line)
22095 ((fboundp 'move-end-of-line) 'move-end-of-line)
22096 (t 'end-of-line))))
22097 (if (or (not special) arg) (call-interactively move-fun)
22098 (let* ((element (save-excursion (beginning-of-line)
22099 (org-element-at-point)))
22100 (type (org-element-type element)))
22101 (cond
22102 ((memq type '(headline inlinetask))
22103 (let ((pos (point)))
22104 (beginning-of-line 1)
22105 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22106 (if (eq special t)
22107 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22108 (goto-char (match-beginning 1))
22109 (goto-char (match-end 0)))
22110 (if (or (< pos (match-end 0))
22111 (not (eq this-command last-command)))
22112 (goto-char (match-end 0))
22113 (goto-char (match-beginning 1))))
22114 (call-interactively move-fun))))
22115 ((org-element-property :hiddenp element)
22116 ;; If element is hidden, `move-end-of-line' would put point
22117 ;; after it. Use `end-of-line' to stay on current line.
22118 (call-interactively 'end-of-line))
22119 (t (call-interactively move-fun)))))
22120 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22122 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22123 (define-key org-mode-map "\C-e" 'org-end-of-line)
22125 (defun org-backward-sentence (&optional arg)
22126 "Go to beginning of sentence, or beginning of table field.
22127 This will call `backward-sentence' or `org-table-beginning-of-field',
22128 depending on context."
22129 (interactive "P")
22130 (cond
22131 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22132 (t (call-interactively 'backward-sentence))))
22134 (defun org-forward-sentence (&optional arg)
22135 "Go to end of sentence, or end of table field.
22136 This will call `forward-sentence' or `org-table-end-of-field',
22137 depending on context."
22138 (interactive "P")
22139 (cond
22140 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22141 (t (call-interactively 'forward-sentence))))
22143 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22144 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22146 (defun org-kill-line (&optional arg)
22147 "Kill line, to tags or end of line."
22148 (interactive "P")
22149 (cond
22150 ((or (not org-special-ctrl-k)
22151 (bolp)
22152 (not (org-at-heading-p)))
22153 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22154 org-ctrl-k-protect-subtree)
22155 (if (or (eq org-ctrl-k-protect-subtree 'error)
22156 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22157 (error "C-k aborted - would kill hidden subtree")))
22158 (call-interactively
22159 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22160 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22161 (kill-region (point) (match-beginning 1))
22162 (org-set-tags nil t))
22163 (t (kill-region (point) (point-at-eol)))))
22165 (define-key org-mode-map "\C-k" 'org-kill-line)
22167 (defun org-yank (&optional arg)
22168 "Yank. If the kill is a subtree, treat it specially.
22169 This command will look at the current kill and check if is a single
22170 subtree, or a series of subtrees[1]. If it passes the test, and if the
22171 cursor is at the beginning of a line or after the stars of a currently
22172 empty headline, then the yank is handled specially. How exactly depends
22173 on the value of the following variables, both set by default.
22175 org-yank-folded-subtrees
22176 When set, the subtree(s) will be folded after insertion, but only
22177 if doing so would now swallow text after the yanked text.
22179 org-yank-adjusted-subtrees
22180 When set, the subtree will be promoted or demoted in order to
22181 fit into the local outline tree structure, which means that the level
22182 will be adjusted so that it becomes the smaller one of the two
22183 *visible* surrounding headings.
22185 Any prefix to this command will cause `yank' to be called directly with
22186 no special treatment. In particular, a simple \\[universal-argument] prefix \
22187 will just
22188 plainly yank the text as it is.
22190 \[1] The test checks if the first non-white line is a heading
22191 and if there are no other headings with fewer stars."
22192 (interactive "P")
22193 (org-yank-generic 'yank arg))
22195 (defun org-yank-generic (command arg)
22196 "Perform some yank-like command.
22198 This function implements the behavior described in the `org-yank'
22199 documentation. However, it has been generalized to work for any
22200 interactive command with similar behavior."
22202 ;; pretend to be command COMMAND
22203 (setq this-command command)
22205 (if arg
22206 (call-interactively command)
22208 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22209 (and (org-kill-is-subtree-p)
22210 (or (bolp)
22211 (and (looking-at "[ \t]*$")
22212 (string-match
22213 "\\`\\*+\\'"
22214 (buffer-substring (point-at-bol) (point)))))))
22215 swallowp)
22216 (cond
22217 ((and subtreep org-yank-folded-subtrees)
22218 (let ((beg (point))
22219 end)
22220 (if (and subtreep org-yank-adjusted-subtrees)
22221 (org-paste-subtree nil nil 'for-yank)
22222 (call-interactively command))
22224 (setq end (point))
22225 (goto-char beg)
22226 (when (and (bolp) subtreep
22227 (not (setq swallowp
22228 (org-yank-folding-would-swallow-text beg end))))
22229 (org-with-limited-levels
22230 (or (looking-at org-outline-regexp)
22231 (re-search-forward org-outline-regexp-bol end t))
22232 (while (and (< (point) end) (looking-at org-outline-regexp))
22233 (hide-subtree)
22234 (org-cycle-show-empty-lines 'folded)
22235 (condition-case nil
22236 (outline-forward-same-level 1)
22237 (error (goto-char end))))))
22238 (when swallowp
22239 (message
22240 "Inserted text not folded because that would swallow text"))
22242 (goto-char end)
22243 (skip-chars-forward " \t\n\r")
22244 (beginning-of-line 1)
22245 (push-mark beg 'nomsg)))
22246 ((and subtreep org-yank-adjusted-subtrees)
22247 (let ((beg (point-at-bol)))
22248 (org-paste-subtree nil nil 'for-yank)
22249 (push-mark beg 'nomsg)))
22251 (call-interactively command))))))
22253 (defun org-yank-folding-would-swallow-text (beg end)
22254 "Would hide-subtree at BEG swallow any text after END?"
22255 (let (level)
22256 (org-with-limited-levels
22257 (save-excursion
22258 (goto-char beg)
22259 (when (or (looking-at org-outline-regexp)
22260 (re-search-forward org-outline-regexp-bol end t))
22261 (setq level (org-outline-level)))
22262 (goto-char end)
22263 (skip-chars-forward " \t\r\n\v\f")
22264 (if (or (eobp)
22265 (and (bolp) (looking-at org-outline-regexp)
22266 (<= (org-outline-level) level)))
22267 nil ; Nothing would be swallowed
22268 t))))) ; something would swallow
22270 (define-key org-mode-map "\C-y" 'org-yank)
22272 (defun org-truely-invisible-p ()
22273 "Check if point is at a character currently not visible.
22274 This version does not only check the character property, but also
22275 `visible-mode'."
22276 ;; Early versions of noutline don't have `outline-invisible-p'.
22277 (if (org-bound-and-true-p visible-mode)
22279 (outline-invisible-p)))
22281 (defun org-invisible-p2 ()
22282 "Check if point is at a character currently not visible."
22283 (save-excursion
22284 (if (and (eolp) (not (bobp))) (backward-char 1))
22285 ;; Early versions of noutline don't have `outline-invisible-p'.
22286 (outline-invisible-p)))
22288 (defun org-back-to-heading (&optional invisible-ok)
22289 "Call `outline-back-to-heading', but provide a better error message."
22290 (condition-case nil
22291 (outline-back-to-heading invisible-ok)
22292 (error (error "Before first headline at position %d in buffer %s"
22293 (point) (current-buffer)))))
22295 (defun org-before-first-heading-p ()
22296 "Before first heading?"
22297 (save-excursion
22298 (end-of-line)
22299 (null (re-search-backward org-outline-regexp-bol nil t))))
22301 (defun org-at-heading-p (&optional ignored)
22302 (outline-on-heading-p t))
22303 ;; Compatibility alias with Org versions < 7.8.03
22304 (defalias 'org-on-heading-p 'org-at-heading-p)
22306 (defun org-at-comment-p nil
22307 "Is cursor in a line starting with a # character?"
22308 (save-excursion
22309 (beginning-of-line)
22310 (looking-at "^#")))
22312 (defun org-at-drawer-p nil
22313 "Is cursor at a drawer keyword?"
22314 (save-excursion
22315 (move-beginning-of-line 1)
22316 (looking-at org-drawer-regexp)))
22318 (defun org-at-block-p nil
22319 "Is cursor at a block keyword?"
22320 (save-excursion
22321 (move-beginning-of-line 1)
22322 (looking-at org-block-regexp)))
22324 (defun org-point-at-end-of-empty-headline ()
22325 "If point is at the end of an empty headline, return t, else nil.
22326 If the heading only contains a TODO keyword, it is still still considered
22327 empty."
22328 (and (looking-at "[ \t]*$")
22329 (when org-todo-line-regexp
22330 (save-excursion
22331 (beginning-of-line 1)
22332 (let ((case-fold-search nil))
22333 (looking-at org-todo-line-regexp)
22334 (string= (match-string 3) ""))))))
22336 (defun org-at-heading-or-item-p ()
22337 (or (org-at-heading-p) (org-at-item-p)))
22339 (defun org-at-target-p ()
22340 (or (org-in-regexp org-radio-target-regexp)
22341 (org-in-regexp org-target-regexp)))
22342 ;; Compatibility alias with Org versions < 7.8.03
22343 (defalias 'org-on-target-p 'org-at-target-p)
22345 (defun org-up-heading-all (arg)
22346 "Move to the heading line of which the present line is a subheading.
22347 This function considers both visible and invisible heading lines.
22348 With argument, move up ARG levels."
22349 (if (fboundp 'outline-up-heading-all)
22350 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22351 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22353 (defun org-up-heading-safe ()
22354 "Move to the heading line of which the present line is a subheading.
22355 This version will not throw an error. It will return the level of the
22356 headline found, or nil if no higher level is found.
22358 Also, this function will be a lot faster than `outline-up-heading',
22359 because it relies on stars being the outline starters. This can really
22360 make a significant difference in outlines with very many siblings."
22361 (let (start-level re)
22362 (org-back-to-heading t)
22363 (setq start-level (funcall outline-level))
22364 (if (equal start-level 1)
22366 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22367 (if (re-search-backward re nil t)
22368 (funcall outline-level)))))
22370 (defun org-first-sibling-p ()
22371 "Is this heading the first child of its parents?"
22372 (interactive)
22373 (let ((re org-outline-regexp-bol)
22374 level l)
22375 (unless (org-at-heading-p t)
22376 (error "Not at a heading"))
22377 (setq level (funcall outline-level))
22378 (save-excursion
22379 (if (not (re-search-backward re nil t))
22381 (setq l (funcall outline-level))
22382 (< l level)))))
22384 (defun org-goto-sibling (&optional previous)
22385 "Goto the next sibling, even if it is invisible.
22386 When PREVIOUS is set, go to the previous sibling instead. Returns t
22387 when a sibling was found. When none is found, return nil and don't
22388 move point."
22389 (let ((fun (if previous 're-search-backward 're-search-forward))
22390 (pos (point))
22391 (re org-outline-regexp-bol)
22392 level l)
22393 (when (condition-case nil (org-back-to-heading t) (error nil))
22394 (setq level (funcall outline-level))
22395 (catch 'exit
22396 (or previous (forward-char 1))
22397 (while (funcall fun re nil t)
22398 (setq l (funcall outline-level))
22399 (when (< l level) (goto-char pos) (throw 'exit nil))
22400 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22401 (goto-char pos)
22402 nil))))
22404 (defun org-show-siblings ()
22405 "Show all siblings of the current headline."
22406 (save-excursion
22407 (while (org-goto-sibling) (org-flag-heading nil)))
22408 (save-excursion
22409 (while (org-goto-sibling 'previous)
22410 (org-flag-heading nil))))
22412 (defun org-goto-first-child ()
22413 "Goto the first child, even if it is invisible.
22414 Return t when a child was found. Otherwise don't move point and
22415 return nil."
22416 (let (level (pos (point)) (re org-outline-regexp-bol))
22417 (when (condition-case nil (org-back-to-heading t) (error nil))
22418 (setq level (outline-level))
22419 (forward-char 1)
22420 (if (and (re-search-forward re nil t) (> (outline-level) level))
22421 (progn (goto-char (match-beginning 0)) t)
22422 (goto-char pos) nil))))
22424 (defun org-show-hidden-entry ()
22425 "Show an entry where even the heading is hidden."
22426 (save-excursion
22427 (org-show-entry)))
22429 (defun org-flag-heading (flag &optional entry)
22430 "Flag the current heading. FLAG non-nil means make invisible.
22431 When ENTRY is non-nil, show the entire entry."
22432 (save-excursion
22433 (org-back-to-heading t)
22434 ;; Check if we should show the entire entry
22435 (if entry
22436 (progn
22437 (org-show-entry)
22438 (save-excursion
22439 (and (outline-next-heading)
22440 (org-flag-heading nil))))
22441 (outline-flag-region (max (point-min) (1- (point)))
22442 (save-excursion (outline-end-of-heading) (point))
22443 flag))))
22445 (defun org-get-next-sibling ()
22446 "Move to next heading of the same level, and return point.
22447 If there is no such heading, return nil.
22448 This is like outline-next-sibling, but invisible headings are ok."
22449 (let ((level (funcall outline-level)))
22450 (outline-next-heading)
22451 (while (and (not (eobp)) (> (funcall outline-level) level))
22452 (outline-next-heading))
22453 (if (or (eobp) (< (funcall outline-level) level))
22455 (point))))
22457 (defun org-get-last-sibling ()
22458 "Move to previous heading of the same level, and return point.
22459 If there is no such heading, return nil."
22460 (let ((opoint (point))
22461 (level (funcall outline-level)))
22462 (outline-previous-heading)
22463 (when (and (/= (point) opoint) (outline-on-heading-p t))
22464 (while (and (> (funcall outline-level) level)
22465 (not (bobp)))
22466 (outline-previous-heading))
22467 (if (< (funcall outline-level) level)
22469 (point)))))
22471 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22472 "Goto to the end of a subtree."
22473 ;; This contains an exact copy of the original function, but it uses
22474 ;; `org-back-to-heading', to make it work also in invisible
22475 ;; trees. And is uses an invisible-ok argument.
22476 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22477 ;; Furthermore, when used inside Org, finding the end of a large subtree
22478 ;; with many children and grandchildren etc, this can be much faster
22479 ;; than the outline version.
22480 (org-back-to-heading invisible-ok)
22481 (let ((first t)
22482 (level (funcall outline-level)))
22483 (if (and (derived-mode-p 'org-mode) (< level 1000))
22484 ;; A true heading (not a plain list item), in Org-mode
22485 ;; This means we can easily find the end by looking
22486 ;; only for the right number of stars. Using a regexp to do
22487 ;; this is so much faster than using a Lisp loop.
22488 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22489 (forward-char 1)
22490 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22491 ;; something else, do it the slow way
22492 (while (and (not (eobp))
22493 (or first (> (funcall outline-level) level)))
22494 (setq first nil)
22495 (outline-next-heading)))
22496 (unless to-heading
22497 (if (memq (preceding-char) '(?\n ?\^M))
22498 (progn
22499 ;; Go to end of line before heading
22500 (forward-char -1)
22501 (if (memq (preceding-char) '(?\n ?\^M))
22502 ;; leave blank line before heading
22503 (forward-char -1))))))
22504 (point))
22506 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22507 "Use Org version in org-mode, for dramatic speed-up."
22508 (if (derived-mode-p 'org-mode)
22509 (progn
22510 (org-end-of-subtree nil t)
22511 (unless (eobp) (backward-char 1)))
22512 ad-do-it))
22514 (defun org-end-of-meta-data-and-drawers ()
22515 "Jump to the first text after meta data and drawers in the current entry.
22516 This will move over empty lines, lines with planning time stamps,
22517 clocking lines, and drawers."
22518 (org-back-to-heading t)
22519 (let ((end (save-excursion (outline-next-heading) (point)))
22520 (re (concat "\\(" org-drawer-regexp "\\)"
22521 "\\|" "[ \t]*" org-keyword-time-regexp)))
22522 (forward-line 1)
22523 (while (re-search-forward re end t)
22524 (if (not (match-end 1))
22525 ;; empty or planning line
22526 (forward-line 1)
22527 ;; a drawer, find the end
22528 (re-search-forward "^[ \t]*:END:" end 'move)
22529 (forward-line 1)))
22530 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22531 (point)))
22533 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22534 "Move forward to the arg'th subheading at same level as this one.
22535 Stop at the first and last subheadings of a superior heading.
22536 Normally this only looks at visible headings, but when INVISIBLE-OK is
22537 non-nil it will also look at invisible ones."
22538 (interactive "p")
22539 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22540 (outline-next-heading)
22541 (org-at-heading-p)
22542 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22543 (re (format "^\\*\\{1,%d\\} " level))
22545 (forward-char 1)
22546 (while (> arg 0)
22547 (while (and (re-search-forward re nil 'move)
22548 (setq l (- (match-end 0) (match-beginning 0) 1))
22549 (= l level)
22550 (not invisible-ok)
22551 (progn (backward-char 1) (outline-invisible-p)))
22552 (if (< l level) (setq arg 1)))
22553 (setq arg (1- arg)))
22554 (beginning-of-line 1))))
22556 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22557 "Move backward to the arg'th subheading at same level as this one.
22558 Stop at the first and last subheadings of a superior heading."
22559 (interactive "p")
22560 (if (not (ignore-errors (org-back-to-heading)))
22561 (goto-char (point-min))
22562 (org-at-heading-p)
22563 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22564 (re (format "^\\*\\{1,%d\\} " level))
22566 (while (> arg 0)
22567 (while (and (re-search-backward re nil 'move)
22568 (setq l (- (match-end 0) (match-beginning 0) 1))
22569 (= l level)
22570 (not invisible-ok)
22571 (outline-invisible-p))
22572 (if (< l level) (setq arg 1)))
22573 (setq arg (1- arg))))))
22575 (defun org-forward-element ()
22576 "Move forward by one element.
22577 Move to the next element at the same level, when possible."
22578 (interactive)
22579 (cond ((eobp) (error "Cannot move further down"))
22580 ((org-with-limited-levels (org-at-heading-p))
22581 (let ((origin (point)))
22582 (org-forward-heading-same-level 1)
22583 (unless (org-with-limited-levels (org-at-heading-p))
22584 (goto-char origin)
22585 (error "Cannot move further down"))))
22587 (let* ((elem (org-element-at-point))
22588 (end (org-element-property :end elem))
22589 (parent (org-element-property :parent elem)))
22590 (if (and parent (= (org-element-property :contents-end parent) end))
22591 (goto-char (org-element-property :end parent))
22592 (goto-char end))))))
22594 (defun org-backward-element ()
22595 "Move backward by one element.
22596 Move to the previous element at the same level, when possible."
22597 (interactive)
22598 (cond ((bobp) (error "Cannot move further up"))
22599 ((org-with-limited-levels (org-at-heading-p))
22600 ;; At an headline, move to the previous one, if any, or stay
22601 ;; here.
22602 (let ((origin (point)))
22603 (org-backward-heading-same-level 1)
22604 (unless (org-with-limited-levels (org-at-heading-p))
22605 (goto-char origin)
22606 (error "Cannot move further up"))))
22608 (let* ((trail (org-element-at-point 'keep-trail))
22609 (elem (car trail))
22610 (prev-elem (nth 1 trail))
22611 (beg (org-element-property :begin elem)))
22612 (cond
22613 ;; Move to beginning of current element if point isn't
22614 ;; there already.
22615 ((/= (point) beg) (goto-char beg))
22616 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22617 ((org-before-first-heading-p) (goto-char (point-min)))
22618 (t (org-back-to-heading)))))))
22620 (defun org-up-element ()
22621 "Move to upper element."
22622 (interactive)
22623 (if (org-with-limited-levels (org-at-heading-p))
22624 (unless (org-up-heading-safe) (error "No surrounding element"))
22625 (let* ((elem (org-element-at-point))
22626 (parent (org-element-property :parent elem)))
22627 (if parent (goto-char (org-element-property :begin parent))
22628 (if (org-with-limited-levels (org-before-first-heading-p))
22629 (error "No surrounding element")
22630 (org-with-limited-levels (org-back-to-heading)))))))
22632 (defvar org-element-greater-elements)
22633 (defun org-down-element ()
22634 "Move to inner element."
22635 (interactive)
22636 (let ((element (org-element-at-point)))
22637 (cond
22638 ((memq (org-element-type element) '(plain-list table))
22639 (goto-char (org-element-property :contents-begin element))
22640 (forward-char))
22641 ((memq (org-element-type element) org-element-greater-elements)
22642 ;; If contents are hidden, first disclose them.
22643 (when (org-element-property :hiddenp element) (org-cycle))
22644 (goto-char (or (org-element-property :contents-begin element)
22645 (error "No content for this element"))))
22646 (t (error "No inner element")))))
22648 (defun org-drag-element-backward ()
22649 "Move backward element at point."
22650 (interactive)
22651 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22652 (let* ((trail (org-element-at-point 'keep-trail))
22653 (elem (car trail))
22654 (prev-elem (nth 1 trail)))
22655 ;; Error out if no previous element or previous element is
22656 ;; a parent of the current one.
22657 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22658 (error "Cannot drag element backward")
22659 (let ((pos (point)))
22660 (org-element-swap-A-B prev-elem elem)
22661 (goto-char (+ (org-element-property :begin prev-elem)
22662 (- pos (org-element-property :begin elem)))))))))
22664 (defun org-drag-element-forward ()
22665 "Move forward element at point."
22666 (interactive)
22667 (let* ((pos (point))
22668 (elem (org-element-at-point)))
22669 (when (= (point-max) (org-element-property :end elem))
22670 (error "Cannot drag element forward"))
22671 (goto-char (org-element-property :end elem))
22672 (let ((next-elem (org-element-at-point)))
22673 (when (or (org-element-nested-p elem next-elem)
22674 (and (eq (org-element-type next-elem) 'headline)
22675 (not (eq (org-element-type elem) 'headline))))
22676 (goto-char pos)
22677 (error "Cannot drag element forward"))
22678 ;; Compute new position of point: it's shifted by NEXT-ELEM
22679 ;; body's length (without final blanks) and by the length of
22680 ;; blanks between ELEM and NEXT-ELEM.
22681 (let ((size-next (- (save-excursion
22682 (goto-char (org-element-property :end next-elem))
22683 (skip-chars-backward " \r\t\n")
22684 (forward-line)
22685 ;; Small correction if buffer doesn't end
22686 ;; with a newline character.
22687 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22688 (org-element-property :begin next-elem)))
22689 (size-blank (- (org-element-property :end elem)
22690 (save-excursion
22691 (goto-char (org-element-property :end elem))
22692 (skip-chars-backward " \r\t\n")
22693 (forward-line)
22694 (point)))))
22695 (org-element-swap-A-B elem next-elem)
22696 (goto-char (+ pos size-next size-blank))))))
22698 (defun org-mark-element ()
22699 "Put point at beginning of this element, mark at end.
22701 Interactively, if this command is repeated or (in Transient Mark
22702 mode) if the mark is active, it marks the next element after the
22703 ones already marked."
22704 (interactive)
22705 (let (deactivate-mark)
22706 (if (and (org-called-interactively-p 'any)
22707 (or (and (eq last-command this-command) (mark t))
22708 (and transient-mark-mode mark-active)))
22709 (set-mark
22710 (save-excursion
22711 (goto-char (mark))
22712 (goto-char (org-element-property :end (org-element-at-point)))))
22713 (let ((element (org-element-at-point)))
22714 (end-of-line)
22715 (push-mark (org-element-property :end element) t t)
22716 (goto-char (org-element-property :begin element))))))
22718 (defun org-narrow-to-element ()
22719 "Narrow buffer to current element."
22720 (interactive)
22721 (let ((elem (org-element-at-point)))
22722 (cond
22723 ((eq (car elem) 'headline)
22724 (narrow-to-region
22725 (org-element-property :begin elem)
22726 (org-element-property :end elem)))
22727 ((memq (car elem) org-element-greater-elements)
22728 (narrow-to-region
22729 (org-element-property :contents-begin elem)
22730 (org-element-property :contents-end elem)))
22732 (narrow-to-region
22733 (org-element-property :begin elem)
22734 (org-element-property :end elem))))))
22736 (defun org-transpose-words ()
22737 "Transpose words, using `org-mode' syntax table."
22738 (interactive)
22739 (with-syntax-table org-syntax-table
22740 (call-interactively 'transpose-words)))
22741 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
22743 (defun org-transpose-element ()
22744 "Transpose current and previous elements, keeping blank lines between.
22745 Point is moved after both elements."
22746 (interactive)
22747 (org-skip-whitespace)
22748 (let ((end (org-element-property :end (org-element-at-point))))
22749 (org-drag-element-backward)
22750 (goto-char end)))
22752 (defun org-unindent-buffer ()
22753 "Un-indent the visible part of the buffer.
22754 Relative indentation (between items, inside blocks, etc.) isn't
22755 modified."
22756 (interactive)
22757 (unless (eq major-mode 'org-mode)
22758 (error "Cannot un-indent a buffer not in Org mode"))
22759 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22760 unindent-tree ; For byte-compiler.
22761 (unindent-tree
22762 (function
22763 (lambda (contents)
22764 (mapc
22765 (lambda (element)
22766 (if (memq (org-element-type element) '(headline section))
22767 (funcall unindent-tree (org-element-contents element))
22768 (save-excursion
22769 (save-restriction
22770 (narrow-to-region
22771 (org-element-property :begin element)
22772 (org-element-property :end element))
22773 (org-do-remove-indentation)))))
22774 (reverse contents))))))
22775 (funcall unindent-tree (org-element-contents parse-tree))))
22777 (defun org-show-subtree ()
22778 "Show everything after this heading at deeper levels."
22779 (interactive)
22780 (outline-flag-region
22781 (point)
22782 (save-excursion
22783 (org-end-of-subtree t t))
22784 nil))
22786 (defun org-show-entry ()
22787 "Show the body directly following this heading.
22788 Show the heading too, if it is currently invisible."
22789 (interactive)
22790 (save-excursion
22791 (condition-case nil
22792 (progn
22793 (org-back-to-heading t)
22794 (outline-flag-region
22795 (max (point-min) (1- (point)))
22796 (save-excursion
22797 (if (re-search-forward
22798 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22799 (match-beginning 1)
22800 (point-max)))
22801 nil)
22802 (org-cycle-hide-drawers 'children))
22803 (error nil))))
22805 (defun org-make-options-regexp (kwds &optional extra)
22806 "Make a regular expression for keyword lines."
22807 (concat
22808 "^#\\+\\("
22809 (mapconcat 'regexp-quote kwds "\\|")
22810 (if extra (concat "\\|" extra))
22811 "\\):[ \t]*\\(.*\\)"))
22813 ;; Make isearch reveal the necessary context
22814 (defun org-isearch-end ()
22815 "Reveal context after isearch exits."
22816 (when isearch-success ; only if search was successful
22817 (if (featurep 'xemacs)
22818 ;; Under XEmacs, the hook is run in the correct place,
22819 ;; we directly show the context.
22820 (org-show-context 'isearch)
22821 ;; In Emacs the hook runs *before* restoring the overlays.
22822 ;; So we have to use a one-time post-command-hook to do this.
22823 ;; (Emacs 22 has a special variable, see function `org-mode')
22824 (unless (and (boundp 'isearch-mode-end-hook-quit)
22825 isearch-mode-end-hook-quit)
22826 ;; Only when the isearch was not quitted.
22827 (org-add-hook 'post-command-hook 'org-isearch-post-command
22828 'append 'local)))))
22830 (defun org-isearch-post-command ()
22831 "Remove self from hook, and show context."
22832 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22833 (org-show-context 'isearch))
22836 ;;;; Integration with and fixes for other packages
22838 ;;; Imenu support
22840 (defvar org-imenu-markers nil
22841 "All markers currently used by Imenu.")
22842 (make-variable-buffer-local 'org-imenu-markers)
22844 (defun org-imenu-new-marker (&optional pos)
22845 "Return a new marker for use by Imenu, and remember the marker."
22846 (let ((m (make-marker)))
22847 (move-marker m (or pos (point)))
22848 (push m org-imenu-markers)
22851 (defun org-imenu-get-tree ()
22852 "Produce the index for Imenu."
22853 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22854 (setq org-imenu-markers nil)
22855 (let* ((n org-imenu-depth)
22856 (re (concat "^" (org-get-limited-outline-regexp)))
22857 (subs (make-vector (1+ n) nil))
22858 (last-level 0)
22859 m level head)
22860 (save-excursion
22861 (save-restriction
22862 (widen)
22863 (goto-char (point-max))
22864 (while (re-search-backward re nil t)
22865 (setq level (org-reduced-level (funcall outline-level)))
22866 (when (and (<= level n)
22867 (looking-at org-complex-heading-regexp))
22868 (setq head (org-link-display-format
22869 (org-match-string-no-properties 4))
22870 m (org-imenu-new-marker))
22871 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22872 (if (>= level last-level)
22873 (push (cons head m) (aref subs level))
22874 (push (cons head (aref subs (1+ level))) (aref subs level))
22875 (loop for i from (1+ level) to n do (aset subs i nil)))
22876 (setq last-level level)))))
22877 (aref subs 1)))
22879 (eval-after-load "imenu"
22880 '(progn
22881 (add-hook 'imenu-after-jump-hook
22882 (lambda ()
22883 (if (derived-mode-p 'org-mode)
22884 (org-show-context 'org-goto))))))
22886 (defun org-link-display-format (link)
22887 "Replace a link with either the description, or the link target
22888 if no description is present"
22889 (save-match-data
22890 (if (string-match org-bracket-link-analytic-regexp link)
22891 (replace-match (if (match-end 5)
22892 (match-string 5 link)
22893 (concat (match-string 1 link)
22894 (match-string 3 link)))
22895 nil t link)
22896 link)))
22898 (defun org-toggle-link-display ()
22899 "Toggle the literal or descriptive display of links."
22900 (interactive)
22901 (if org-descriptive-links
22902 (progn (org-remove-from-invisibility-spec '(org-link))
22903 (org-restart-font-lock)
22904 (setq org-descriptive-links nil))
22905 (progn (add-to-invisibility-spec '(org-link))
22906 (org-restart-font-lock)
22907 (setq org-descriptive-links t))))
22909 ;; Speedbar support
22911 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22912 "Overlay marking the agenda restriction line in speedbar.")
22913 (overlay-put org-speedbar-restriction-lock-overlay
22914 'face 'org-agenda-restriction-lock)
22915 (overlay-put org-speedbar-restriction-lock-overlay
22916 'help-echo "Agendas are currently limited to this item.")
22917 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22919 (defun org-speedbar-set-agenda-restriction ()
22920 "Restrict future agenda commands to the location at point in speedbar.
22921 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22922 (interactive)
22923 (require 'org-agenda)
22924 (let (p m tp np dir txt)
22925 (cond
22926 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22927 'org-imenu t))
22928 (setq m (get-text-property p 'org-imenu-marker))
22929 (with-current-buffer (marker-buffer m)
22930 (goto-char m)
22931 (org-agenda-set-restriction-lock 'subtree)))
22932 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22933 'speedbar-function 'speedbar-find-file))
22934 (setq tp (previous-single-property-change
22935 (1+ p) 'speedbar-function)
22936 np (next-single-property-change
22937 tp 'speedbar-function)
22938 dir (speedbar-line-directory)
22939 txt (buffer-substring-no-properties (or tp (point-min))
22940 (or np (point-max))))
22941 (with-current-buffer (find-file-noselect
22942 (let ((default-directory dir))
22943 (expand-file-name txt)))
22944 (unless (derived-mode-p 'org-mode)
22945 (error "Cannot restrict to non-Org-mode file"))
22946 (org-agenda-set-restriction-lock 'file)))
22947 (t (error "Don't know how to restrict Org-mode's agenda")))
22948 (move-overlay org-speedbar-restriction-lock-overlay
22949 (point-at-bol) (point-at-eol))
22950 (setq current-prefix-arg nil)
22951 (org-agenda-maybe-redo)))
22953 (eval-after-load "speedbar"
22954 '(progn
22955 (speedbar-add-supported-extension ".org")
22956 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22957 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22958 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22959 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22960 (add-hook 'speedbar-visiting-tag-hook
22961 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22963 ;;; Fixes and Hacks for problems with other packages
22965 ;; Make flyspell not check words in links, to not mess up our keymap
22966 (defvar org-element-affiliated-keywords) ; From org-element.el
22967 (defvar org-element-block-name-alist) ; From org-element.el
22968 (defun org-mode-flyspell-verify ()
22969 "Don't let flyspell put overlays at active buttons, or on
22970 {todo,all-time,additional-option-like}-keywords."
22971 (let ((pos (max (1- (point)) (point-min)))
22972 (word (thing-at-point 'word)))
22973 (and (not (get-text-property pos 'keymap))
22974 (not (get-text-property pos 'org-no-flyspell))
22975 (not (member word org-todo-keywords-1))
22976 (not (member word org-all-time-keywords))
22977 (not (member word org-options-keywords))
22978 (not (member word (mapcar 'car org-startup-options)))
22979 (not (member-ignore-case word org-element-affiliated-keywords))
22980 (not (member-ignore-case word (org-get-export-keywords)))
22981 (not (member-ignore-case
22982 word (mapcar 'car org-element-block-name-alist)))
22983 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
22985 (defun org-remove-flyspell-overlays-in (beg end)
22986 "Remove flyspell overlays in region."
22987 (and (org-bound-and-true-p flyspell-mode)
22988 (fboundp 'flyspell-delete-region-overlays)
22989 (flyspell-delete-region-overlays beg end))
22990 (add-text-properties beg end '(org-no-flyspell t)))
22992 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22993 (eval-after-load "bookmark"
22994 '(if (boundp 'bookmark-after-jump-hook)
22995 ;; We can use the hook
22996 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22997 ;; Hook not available, use advice
22998 (defadvice bookmark-jump (after org-make-visible activate)
22999 "Make the position visible."
23000 (org-bookmark-jump-unhide))))
23002 ;; Make sure saveplace shows the location if it was hidden
23003 (eval-after-load "saveplace"
23004 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23005 "Make the position visible."
23006 (org-bookmark-jump-unhide)))
23008 ;; Make sure ecb shows the location if it was hidden
23009 (eval-after-load "ecb"
23010 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23011 "Make hierarchy visible when jumping into location from ECB tree buffer."
23012 (if (derived-mode-p 'org-mode)
23013 (org-show-context))))
23015 (defun org-bookmark-jump-unhide ()
23016 "Unhide the current position, to show the bookmark location."
23017 (and (derived-mode-p 'org-mode)
23018 (or (outline-invisible-p)
23019 (save-excursion (goto-char (max (point-min) (1- (point))))
23020 (outline-invisible-p)))
23021 (org-show-context 'bookmark-jump)))
23023 ;; Make session.el ignore our circular variable
23024 (eval-after-load "session"
23025 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23027 ;;;; Experimental code
23029 (defun org-closed-in-range ()
23030 "Sparse tree of items closed in a certain time range.
23031 Still experimental, may disappear in the future."
23032 (interactive)
23033 ;; Get the time interval from the user.
23034 (let* ((time1 (org-float-time
23035 (org-read-date nil 'to-time nil "Starting date: ")))
23036 (time2 (org-float-time
23037 (org-read-date nil 'to-time nil "End date:")))
23038 ;; callback function
23039 (callback (lambda ()
23040 (let ((time
23041 (org-float-time
23042 (apply 'encode-time
23043 (org-parse-time-string
23044 (match-string 1))))))
23045 ;; check if time in interval
23046 (and (>= time time1) (<= time time2))))))
23047 ;; make tree, check each match with the callback
23048 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
23050 ;;;; Finish up
23052 (provide 'org)
23054 (run-hooks 'org-load-hook)
23056 ;;; org.el ends here