cycle tables for :results org and :results wrap
[org-mode.git] / lisp / org.el
blobe2274a84c3895cce08cc888276ba85b50c017d29
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 a 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 (unless (boundp 'calendar-view-holidays-initially-flag)
107 (org-defvaralias 'calendar-view-holidays-initially-flag
108 'view-calendar-holidays-initially))
109 (unless (boundp 'calendar-view-diary-initially-flag)
110 (org-defvaralias 'calendar-view-diary-initially-flag
111 'view-diary-entries-initially))
112 (unless (boundp 'diary-fancy-buffer)
113 (org-defvaralias 'diary-fancy-buffer 'fancy-diary-buffer))
115 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
116 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
117 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
118 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
119 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
120 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
121 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
122 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
124 (declare-function orgtbl-mode "org-table" (&optional arg))
125 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
126 (declare-function org-beamer-mode "ox-beamer" ())
127 (declare-function org-table-edit-field "org-table" (arg))
128 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
129 (declare-function org-table-set-constants "org-table" ())
130 (declare-function org-id-get-create "org-id" (&optional force))
131 (declare-function org-id-find-id-file "org-id" (id))
132 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
133 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
134 (declare-function org-agenda-redo "org-agenda" (&optional all))
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 (declare-function org-element--parse-objects "org-element"
141 (beg end acc restriction))
142 (declare-function org-element-at-point "org-element" (&optional keep-trail))
143 (declare-function org-element-contents "org-element" (element))
144 (declare-function org-element-context "org-element" (&optional element))
145 (declare-function org-element-interpret-data "org-element"
146 (data &optional parent))
147 (declare-function org-element-map "org-element"
148 (data types fun &optional info first-match no-recursion))
149 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
150 (declare-function org-element-parse-buffer "org-element"
151 (&optional granularity visible-only))
152 (declare-function org-element-property "org-element" (property element))
153 (declare-function org-element-put-property "org-element"
154 (element property value))
155 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
156 (declare-function org-element--parse-objects "org-element"
157 (beg end acc restriction))
158 (declare-function org-element-parse-buffer "org-element"
159 (&optional granularity visible-only))
160 (declare-function org-element-restriction "org-element" (element))
161 (declare-function org-element-type "org-element" (element))
163 ;; load languages based on value of `org-babel-load-languages'
164 (defvar org-babel-load-languages)
166 ;;;###autoload
167 (defun org-babel-do-load-languages (sym value)
168 "Load the languages defined in `org-babel-load-languages'."
169 (set-default sym value)
170 (mapc (lambda (pair)
171 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
172 (if active
173 (progn
174 (require (intern (concat "ob-" lang))))
175 (progn
176 (funcall 'fmakunbound
177 (intern (concat "org-babel-execute:" lang)))
178 (funcall 'fmakunbound
179 (intern (concat "org-babel-expand-body:" lang)))))))
180 org-babel-load-languages))
182 (defcustom org-babel-load-languages '((emacs-lisp . t))
183 "Languages which can be evaluated in Org-mode buffers.
184 This list can be used to load support for any of the languages
185 below, note that each language will depend on a different set of
186 system executables and/or Emacs modes. When a language is
187 \"loaded\", then code blocks in that language can be evaluated
188 with `org-babel-execute-src-block' bound by default to C-c
189 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
190 be set to remove code block evaluation from the C-c C-c
191 keybinding. By default only Emacs Lisp (which has no
192 requirements) is loaded."
193 :group 'org-babel
194 :set 'org-babel-do-load-languages
195 :version "24.1"
196 :type '(alist :tag "Babel Languages"
197 :key-type
198 (choice
199 (const :tag "Awk" awk)
200 (const :tag "C" C)
201 (const :tag "R" R)
202 (const :tag "Asymptote" asymptote)
203 (const :tag "Calc" calc)
204 (const :tag "Clojure" clojure)
205 (const :tag "CSS" css)
206 (const :tag "Ditaa" ditaa)
207 (const :tag "Dot" dot)
208 (const :tag "Emacs Lisp" emacs-lisp)
209 (const :tag "Fortran" fortran)
210 (const :tag "Gnuplot" gnuplot)
211 (const :tag "Haskell" haskell)
212 (const :tag "IO" io)
213 (const :tag "Java" java)
214 (const :tag "Javascript" js)
215 (const :tag "LaTeX" latex)
216 (const :tag "Ledger" ledger)
217 (const :tag "Lilypond" lilypond)
218 (const :tag "Lisp" lisp)
219 (const :tag "Makefile" makefile)
220 (const :tag "Maxima" maxima)
221 (const :tag "Matlab" matlab)
222 (const :tag "Mscgen" mscgen)
223 (const :tag "Ocaml" ocaml)
224 (const :tag "Octave" octave)
225 (const :tag "Org" org)
226 (const :tag "Perl" perl)
227 (const :tag "Pico Lisp" picolisp)
228 (const :tag "PlantUML" plantuml)
229 (const :tag "Python" python)
230 (const :tag "Ruby" ruby)
231 (const :tag "Sass" sass)
232 (const :tag "Scala" scala)
233 (const :tag "Scheme" scheme)
234 (const :tag "Screen" screen)
235 (const :tag "Shell Script" sh)
236 (const :tag "Shen" shen)
237 (const :tag "Sql" sql)
238 (const :tag "Sqlite" sqlite))
239 :value-type (boolean :tag "Activate" :value t)))
241 ;;;; Customization variables
242 (defcustom org-clone-delete-id nil
243 "Remove ID property of clones of a subtree.
244 When non-nil, clones of a subtree don't inherit the ID property.
245 Otherwise they inherit the ID property with a new unique
246 identifier."
247 :type 'boolean
248 :version "24.1"
249 :group 'org-id)
251 ;;; Version
252 (org-check-version)
254 ;;;###autoload
255 (defun org-version (&optional here full message)
256 "Show the org-mode version in the echo area.
257 With prefix argument HERE, insert it at point.
258 When FULL is non-nil, use a verbose version string.
259 When MESSAGE is non-nil, display a message with the version."
260 (interactive "P")
261 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
262 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
263 (load-suffixes (list ".el"))
264 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
265 (org-trash (or
266 (and (fboundp 'org-release) (fboundp 'org-git-version))
267 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
268 (load-suffixes save-load-suffixes)
269 (org-version (org-release))
270 (git-version (org-git-version))
271 (version (format "Org-mode version %s (%s @ %s)"
272 org-version
273 git-version
274 (if org-install-dir
275 (if (string= org-dir org-install-dir)
276 org-install-dir
277 (concat "mixed installation! " org-install-dir " and " org-dir))
278 "org-loaddefs.el can not be found!")))
279 (_version (if full version org-version)))
280 (if (org-called-interactively-p 'interactive)
281 (if here
282 (insert version)
283 (message version))
284 (if message (message _version))
285 _version)))
287 (defconst org-version (org-version))
289 ;;; Compatibility constants
291 ;;; The custom variables
293 (defgroup org nil
294 "Outline-based notes management and organizer."
295 :tag "Org"
296 :group 'outlines
297 :group 'calendar)
299 (defcustom org-mode-hook nil
300 "Mode hook for Org-mode, run after the mode was turned on."
301 :group 'org
302 :type 'hook)
304 (defcustom org-load-hook nil
305 "Hook that is run after org.el has been loaded."
306 :group 'org
307 :type 'hook)
309 (defcustom org-log-buffer-setup-hook nil
310 "Hook that is run after an Org log buffer is created."
311 :group 'org
312 :version "24.1"
313 :type 'hook)
315 (defvar org-modules) ; defined below
316 (defvar org-modules-loaded nil
317 "Have the modules been loaded already?")
319 (defun org-load-modules-maybe (&optional force)
320 "Load all extensions listed in `org-modules'."
321 (when (or force (not org-modules-loaded))
322 (mapc (lambda (ext)
323 (condition-case nil (require ext)
324 (error (message "Problems while trying to load feature `%s'" ext))))
325 org-modules)
326 (setq org-modules-loaded t)))
328 (defun org-set-modules (var value)
329 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
330 (set var value)
331 (when (featurep 'org)
332 (org-load-modules-maybe 'force)))
334 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
335 "Modules that should always be loaded together with org.el.
337 If a description starts with <C>, the file is not part of Emacs
338 and loading it will require that you have downloaded and properly
339 installed the Org mode distribution.
341 You can also use this system to load external packages (i.e. neither Org
342 core modules, nor modules from the CONTRIB directory). Just add symbols
343 to the end of the list. If the package is called org-xyz.el, then you need
344 to add the symbol `xyz', and the package must have a call to:
346 \(provide 'org-xyz)
348 For export specific modules, see also `org-export-backends'."
349 :group 'org
350 :set 'org-set-modules
351 :version "24.4"
352 :package-version '(Org . "8.0")
353 :type
354 '(set :greedy t
355 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
356 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
357 (const :tag " crypt: Encryption of subtrees" org-crypt)
358 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
359 (const :tag " docview: Links to doc-view buffers" org-docview)
360 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
361 (const :tag " id: Global IDs for identifying entries" org-id)
362 (const :tag " info: Links to Info nodes" org-info)
363 (const :tag " habit: Track your consistency with habits" org-habit)
364 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
365 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
366 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
367 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
368 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
369 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
370 (const :tag " mouse: Additional mouse support" org-mouse)
372 (const :tag "C vm: Links to VM folders/messages" org-vm)
373 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
374 (const :tag "C w3m: Special cut/paste from w3m to Org-mode." org-w3m)
375 (const :tag "C mew: Links to Mew folders/messages" org-mew)
376 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
377 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
378 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
379 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
380 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
381 (const :tag "C collector: Collect properties into tables" org-collector)
382 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
383 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
384 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
385 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
386 (const :tag "C eval: Include command output as text" org-eval)
387 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
388 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
389 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
390 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
391 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
393 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
395 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
396 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
397 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
398 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
399 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
400 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
401 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
402 (const :tag "C mtags: Support for muse-like tags" org-mtags)
403 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
404 (const :tag "C registry: A registry for Org-mode links" org-registry)
405 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
406 (const :tag "C secretary: Team management with org-mode" org-secretary)
407 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
408 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
409 (const :tag "C track: Keep up with Org-mode development" org-track)
410 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
411 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
412 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
414 (defvar org-export-registered-backends) ; From ox.el
415 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
416 (defcustom org-export-backends '(ascii html icalendar latex)
417 "List of export back-ends that should be always available.
419 If a description starts with <C>, the file is not part of Emacs
420 and loading it will require that you have downloaded and properly
421 installed the Org mode distribution.
423 Unlike to `org-modules', libraries in this list will not be
424 loaded along with Org, but only once the export framework is
425 needed.
427 This variable needs to be set before org.el is loaded. If you
428 need to make a change while Emacs is running, use the customize
429 interface or run the following code, where VALUE stands for the
430 new value of the variable, after updating it:
432 \(progn
433 \(setq org-export-registered-backends
434 \(org-remove-if-not
435 \(lambda (backend)
436 \(or (memq backend val)
437 \(catch 'parentp
438 \(mapc
439 \(lambda (b)
440 \(and (org-export-derived-backend-p b (car backend))
441 \(throw 'parentp t)))
442 val)
443 nil)))
444 org-export-registered-backends))
445 \(let ((new-list (mapcar 'car org-export-registered-backends)))
446 \(dolist (backend val)
447 \(cond
448 \((not (load (format \"ox-%s\" backend) t t))
449 \(message \"Problems while trying to load export back-end `%s'\"
450 backend))
451 \((not (memq backend new-list)) (push backend new-list))))
452 \(set-default var new-list)))
454 Adding a back-end to this list will also pull the back-end it
455 depends on, if any."
456 :group 'org
457 :group 'org-export
458 :version "24.4"
459 :package-version '(Org . "8.0")
460 :initialize 'custom-initialize-set
461 :set (lambda (var val)
462 (if (not (featurep 'ox)) (set-default var val)
463 ;; Any back-end not required anymore (not present in VAL and not
464 ;; a parent of any back-end in the new value) is removed from the
465 ;; list of registered back-ends.
466 (setq org-export-registered-backends
467 (org-remove-if-not
468 (lambda (backend)
469 (or (memq backend val)
470 (catch 'parentp
471 (mapc
472 (lambda (b)
473 (and (org-export-derived-backend-p b (car backend))
474 (throw 'parentp t)))
475 val)
476 nil)))
477 org-export-registered-backends))
478 ;; Now build NEW-LIST of both new back-ends and required
479 ;; parents.
480 (let ((new-list (mapcar 'car org-export-registered-backends)))
481 (dolist (backend val)
482 (cond
483 ((not (load (format "ox-%s" backend) t t))
484 (message "Problems while trying to load export back-end `%s'"
485 backend))
486 ((not (memq backend new-list)) (push backend new-list))))
487 ;; Set VAR to that list with fixed dependencies.
488 (set-default var new-list))))
489 :type '(set :greedy t
490 (const :tag " ascii Export buffer to ASCII format" ascii)
491 (const :tag " beamer Export buffer to Beamer presentation" beamer)
492 (const :tag " html Export buffer to HTML format" html)
493 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
494 (const :tag " latex Export buffer to LaTeX format" latex)
495 (const :tag " man Export buffer to MAN format" man)
496 (const :tag " md Export buffer to Markdown format" md)
497 (const :tag " odt Export buffer to ODT format" odt)
498 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
499 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
500 (const :tag "C deck Export buffer to deck.js presentations" deck)
501 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
502 (const :tag "C groff Export buffer to Groff format" groff)
503 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
504 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
505 (const :tag "C s5 Export buffer to s5 presentations" s5)
506 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
508 (eval-after-load 'ox
509 '(mapc
510 (lambda (backend)
511 (condition-case nil (require (intern (format "ox-%s" backend)))
512 (error (message "Problems while trying to load export back-end `%s'"
513 backend))))
514 org-export-backends))
516 (defcustom org-support-shift-select nil
517 "Non-nil means make shift-cursor commands select text when possible.
519 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
520 start selecting a region, or enlarge regions started in this way.
521 In Org-mode, in special contexts, these same keys are used for
522 other purposes, important enough to compete with shift selection.
523 Org tries to balance these needs by supporting `shift-select-mode'
524 outside these special contexts, under control of this variable.
526 The default of this variable is nil, to avoid confusing behavior. Shifted
527 cursor keys will then execute Org commands in the following contexts:
528 - on a headline, changing TODO state (left/right) and priority (up/down)
529 - on a time stamp, changing the time
530 - in a plain list item, changing the bullet type
531 - in a property definition line, switching between allowed values
532 - in the BEGIN line of a clock table (changing the time block).
533 Outside these contexts, the commands will throw an error.
535 When this variable is t and the cursor is not in a special
536 context, Org-mode will support shift-selection for making and
537 enlarging regions. To make this more effective, the bullet
538 cycling will no longer happen anywhere in an item line, but only
539 if the cursor is exactly on the bullet.
541 If you set this variable to the symbol `always', then the keys
542 will not be special in headlines, property lines, and item lines,
543 to make shift selection work there as well. If this is what you
544 want, you can use the following alternative commands: `C-c C-t'
545 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
546 can be used to switch TODO sets, `C-c -' to cycle item bullet
547 types, and properties can be edited by hand or in column view.
549 However, when the cursor is on a timestamp, shift-cursor commands
550 will still edit the time stamp - this is just too good to give up.
552 XEmacs user should have this variable set to nil, because
553 `shift-select-mode' is in Emacs 23 or later only."
554 :group 'org
555 :type '(choice
556 (const :tag "Never" nil)
557 (const :tag "When outside special context" t)
558 (const :tag "Everywhere except timestamps" always)))
560 (defcustom org-loop-over-headlines-in-active-region nil
561 "Shall some commands act upon headlines in the active region?
563 When set to `t', some commands will be performed in all headlines
564 within the active region.
566 When set to `start-level', some commands will be performed in all
567 headlines within the active region, provided that these headlines
568 are of the same level than the first one.
570 When set to a string, those commands will be performed on the
571 matching headlines within the active region. Such string must be
572 a tags/property/todo match as it is used in the agenda tags view.
574 The list of commands is: `org-schedule', `org-deadline',
575 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
576 `org-archive-to-archive-sibling'. The archiving commands skip
577 already archived entries."
578 :type '(choice (const :tag "Don't loop" nil)
579 (const :tag "All headlines in active region" t)
580 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
581 (string :tag "Tags/Property/Todo matcher"))
582 :version "24.1"
583 :group 'org-todo
584 :group 'org-archive)
586 (defgroup org-startup nil
587 "Options concerning startup of Org-mode."
588 :tag "Org Startup"
589 :group 'org)
591 (defcustom org-startup-folded t
592 "Non-nil means entering Org-mode will switch to OVERVIEW.
593 This can also be configured on a per-file basis by adding one of
594 the following lines anywhere in the buffer:
596 #+STARTUP: fold (or `overview', this is equivalent)
597 #+STARTUP: nofold (or `showall', this is equivalent)
598 #+STARTUP: content
599 #+STARTUP: showeverything
601 By default, this option is ignored when Org opens agenda files
602 for the first time. If you want the agenda to honor the startup
603 option, set `org-agenda-inhibit-startup' to nil."
604 :group 'org-startup
605 :type '(choice
606 (const :tag "nofold: show all" nil)
607 (const :tag "fold: overview" t)
608 (const :tag "content: all headlines" content)
609 (const :tag "show everything, even drawers" showeverything)))
611 (defcustom org-startup-truncated t
612 "Non-nil means entering Org-mode will set `truncate-lines'.
613 This is useful since some lines containing links can be very long and
614 uninteresting. Also tables look terrible when wrapped."
615 :group 'org-startup
616 :type 'boolean)
618 (defcustom org-startup-indented nil
619 "Non-nil means turn on `org-indent-mode' on startup.
620 This can also be configured on a per-file basis by adding one of
621 the following lines anywhere in the buffer:
623 #+STARTUP: indent
624 #+STARTUP: noindent"
625 :group 'org-structure
626 :type '(choice
627 (const :tag "Not" nil)
628 (const :tag "Globally (slow on startup in large files)" t)))
630 (defcustom org-use-sub-superscripts t
631 "Non-nil means interpret \"_\" and \"^\" for display.
632 When this option is turned on, you can use TeX-like syntax for sub- and
633 superscripts. Several characters after \"_\" or \"^\" will be
634 considered as a single item - so grouping with {} is normally not
635 needed. For example, the following things will be parsed as single
636 sub- or superscripts.
638 10^24 or 10^tau several digits will be considered 1 item.
639 10^-12 or 10^-tau a leading sign with digits or a word
640 x^2-y^3 will be read as x^2 - y^3, because items are
641 terminated by almost any nonword/nondigit char.
642 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
644 Still, ambiguity is possible - so when in doubt use {} to enclose
645 the sub/superscript. If you set this variable to the symbol
646 `{}', the braces are *required* in order to trigger
647 interpretations as sub/superscript. This can be helpful in
648 documents that need \"_\" frequently in plain text."
649 :group 'org-startup
650 :version "24.1"
651 :type '(choice
652 (const :tag "Always interpret" t)
653 (const :tag "Only with braces" {})
654 (const :tag "Never interpret" nil)))
656 (defcustom org-startup-with-beamer-mode nil
657 "Non-nil means turn on `org-beamer-mode' on startup.
658 This can also be configured on a per-file basis by adding one of
659 the following lines anywhere in the buffer:
661 #+STARTUP: beamer"
662 :group 'org-startup
663 :version "24.1"
664 :type 'boolean)
666 (defcustom org-startup-align-all-tables nil
667 "Non-nil means align all tables when visiting a file.
668 This is useful when the column width in tables is forced with <N> cookies
669 in table fields. Such tables will look correct only after the first re-align.
670 This can also be configured on a per-file basis by adding one of
671 the following lines anywhere in the buffer:
672 #+STARTUP: align
673 #+STARTUP: noalign"
674 :group 'org-startup
675 :type 'boolean)
677 (defcustom org-startup-with-inline-images nil
678 "Non-nil means show inline images when loading a new Org file.
679 This can also be configured on a per-file basis by adding one of
680 the following lines anywhere in the buffer:
681 #+STARTUP: inlineimages
682 #+STARTUP: noinlineimages"
683 :group 'org-startup
684 :version "24.1"
685 :type 'boolean)
687 (defcustom org-startup-with-latex-preview nil
688 "Non-nil means preview LaTeX fragments when loading a new Org file.
690 This can also be configured on a per-file basis by adding one of
691 the followinglines anywhere in the buffer:
692 #+STARTUP: latexpreview
693 #+STARTUP: nolatexpreview"
694 :group 'org-startup
695 :version "24.4"
696 :package-version '(Org . "8.0")
697 :type 'boolean)
699 (defcustom org-insert-mode-line-in-empty-file nil
700 "Non-nil means insert the first line setting Org-mode in empty files.
701 When the function `org-mode' is called interactively in an empty file, this
702 normally means that the file name does not automatically trigger Org-mode.
703 To ensure that the file will always be in Org-mode in the future, a
704 line enforcing Org-mode will be inserted into the buffer, if this option
705 has been set."
706 :group 'org-startup
707 :type 'boolean)
709 (defcustom org-replace-disputed-keys nil
710 "Non-nil means use alternative key bindings for some keys.
711 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
712 These keys are also used by other packages like shift-selection-mode'
713 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
714 If you want to use Org-mode together with one of these other modes,
715 or more generally if you would like to move some Org-mode commands to
716 other keys, set this variable and configure the keys with the variable
717 `org-disputed-keys'.
719 This option is only relevant at load-time of Org-mode, and must be set
720 *before* org.el is loaded. Changing it requires a restart of Emacs to
721 become effective."
722 :group 'org-startup
723 :type 'boolean)
725 (defcustom org-use-extra-keys nil
726 "Non-nil means use extra key sequence definitions for certain commands.
727 This happens automatically if you run XEmacs or if `window-system'
728 is nil. This variable lets you do the same manually. You must
729 set it before loading org.
731 Example: on Carbon Emacs 22 running graphically, with an external
732 keyboard on a Powerbook, the default way of setting M-left might
733 not work for either Alt or ESC. Setting this variable will make
734 it work for ESC."
735 :group 'org-startup
736 :type 'boolean)
738 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
740 (defcustom org-disputed-keys
741 '(([(shift up)] . [(meta p)])
742 ([(shift down)] . [(meta n)])
743 ([(shift left)] . [(meta -)])
744 ([(shift right)] . [(meta +)])
745 ([(control shift right)] . [(meta shift +)])
746 ([(control shift left)] . [(meta shift -)]))
747 "Keys for which Org-mode and other modes compete.
748 This is an alist, cars are the default keys, second element specifies
749 the alternative to use when `org-replace-disputed-keys' is t.
751 Keys can be specified in any syntax supported by `define-key'.
752 The value of this option takes effect only at Org-mode's startup,
753 therefore you'll have to restart Emacs to apply it after changing."
754 :group 'org-startup
755 :type 'alist)
757 (defun org-key (key)
758 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
759 Or return the original if not disputed.
760 Also apply the translations defined in `org-xemacs-key-equivalents'."
761 (when org-replace-disputed-keys
762 (let* ((nkey (key-description key))
763 (x (org-find-if (lambda (x)
764 (equal (key-description (car x)) nkey))
765 org-disputed-keys)))
766 (setq key (if x (cdr x) key))))
767 (when (featurep 'xemacs)
768 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
769 key)
771 (defun org-find-if (predicate seq)
772 (catch 'exit
773 (while seq
774 (if (funcall predicate (car seq))
775 (throw 'exit (car seq))
776 (pop seq)))))
778 (defun org-defkey (keymap key def)
779 "Define a key, possibly translated, as returned by `org-key'."
780 (define-key keymap (org-key key) def))
782 (defcustom org-ellipsis nil
783 "The ellipsis to use in the Org-mode outline.
784 When nil, just use the standard three dots. When a string, use that instead,
785 When a face, use the standard 3 dots, but with the specified face.
786 The change affects only Org-mode (which will then use its own display table).
787 Changing this requires executing `M-x org-mode' in a buffer to become
788 effective."
789 :group 'org-startup
790 :type '(choice (const :tag "Default" nil)
791 (face :tag "Face" :value org-warning)
792 (string :tag "String" :value "...#")))
794 (defvar org-display-table nil
795 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
797 (defgroup org-keywords nil
798 "Keywords in Org-mode."
799 :tag "Org Keywords"
800 :group 'org)
802 (defcustom org-deadline-string "DEADLINE:"
803 "String to mark deadline entries.
804 A deadline is this string, followed by a time stamp. Should be a word,
805 terminated by a colon. You can insert a schedule keyword and
806 a timestamp with \\[org-deadline].
807 Changes become only effective after restarting Emacs."
808 :group 'org-keywords
809 :type 'string)
811 (defcustom org-scheduled-string "SCHEDULED:"
812 "String to mark scheduled TODO entries.
813 A schedule is this string, followed by a time stamp. Should be a word,
814 terminated by a colon. You can insert a schedule keyword and
815 a timestamp with \\[org-schedule].
816 Changes become only effective after restarting Emacs."
817 :group 'org-keywords
818 :type 'string)
820 (defcustom org-closed-string "CLOSED:"
821 "String used as the prefix for timestamps logging closing a TODO entry."
822 :group 'org-keywords
823 :type 'string)
825 (defcustom org-clock-string "CLOCK:"
826 "String used as prefix for timestamps clocking work hours on an item."
827 :group 'org-keywords
828 :type 'string)
830 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
831 org-scheduled-string "\\|"
832 org-deadline-string "\\|"
833 org-closed-string "\\|"
834 org-clock-string "\\)")
835 "Matches a line with planning or clock info.")
837 (defcustom org-comment-string "COMMENT"
838 "Entries starting with this keyword will never be exported.
839 An entry can be toggled between COMMENT and normal with
840 \\[org-toggle-comment].
841 Changes become only effective after restarting Emacs."
842 :group 'org-keywords
843 :type 'string)
845 (defcustom org-quote-string "QUOTE"
846 "Entries starting with this keyword will be exported in fixed-width font.
847 Quoting applies only to the text in the entry following the headline, and does
848 not extend beyond the next headline, even if that is lower level.
849 An entry can be toggled between QUOTE and normal with
850 \\[org-toggle-fixed-width-section]."
851 :group 'org-keywords
852 :type 'string)
854 (defconst org-repeat-re
855 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
856 "Regular expression for specifying repeated events.
857 After a match, group 1 contains the repeat expression.")
859 (defgroup org-structure nil
860 "Options concerning the general structure of Org-mode files."
861 :tag "Org Structure"
862 :group 'org)
864 (defgroup org-reveal-location nil
865 "Options about how to make context of a location visible."
866 :tag "Org Reveal Location"
867 :group 'org-structure)
869 (defconst org-context-choice
870 '(choice
871 (const :tag "Always" t)
872 (const :tag "Never" nil)
873 (repeat :greedy t :tag "Individual contexts"
874 (cons
875 (choice :tag "Context"
876 (const agenda)
877 (const org-goto)
878 (const occur-tree)
879 (const tags-tree)
880 (const link-search)
881 (const mark-goto)
882 (const bookmark-jump)
883 (const isearch)
884 (const default))
885 (boolean))))
886 "Contexts for the reveal options.")
888 (defcustom org-show-hierarchy-above '((default . t))
889 "Non-nil means show full hierarchy when revealing a location.
890 Org-mode often shows locations in an org-mode file which might have
891 been invisible before. When this is set, the hierarchy of headings
892 above the exposed location is shown.
893 Turning this off for example for sparse trees makes them very compact.
894 Instead of t, this can also be an alist specifying this option for different
895 contexts. Valid contexts are
896 agenda when exposing an entry from the agenda
897 org-goto when using the command `org-goto' on key C-c C-j
898 occur-tree when using the command `org-occur' on key C-c /
899 tags-tree when constructing a sparse tree based on tags matches
900 link-search when exposing search matches associated with a link
901 mark-goto when exposing the jump goal of a mark
902 bookmark-jump when exposing a bookmark location
903 isearch when exiting from an incremental search
904 default default for all contexts not set explicitly"
905 :group 'org-reveal-location
906 :type org-context-choice)
908 (defcustom org-show-following-heading '((default . nil))
909 "Non-nil means show following heading when revealing a location.
910 Org-mode often shows locations in an org-mode file which might have
911 been invisible before. When this is set, the heading following the
912 match is shown.
913 Turning this off for example for sparse trees makes them very compact,
914 but makes it harder to edit the location of the match. In such a case,
915 use the command \\[org-reveal] to show more context.
916 Instead of t, this can also be an alist specifying this option for different
917 contexts. See `org-show-hierarchy-above' for valid contexts."
918 :group 'org-reveal-location
919 :type org-context-choice)
921 (defcustom org-show-siblings '((default . nil) (isearch t))
922 "Non-nil means show all sibling heading when revealing a location.
923 Org-mode often shows locations in an org-mode file which might have
924 been invisible before. When this is set, the sibling of the current entry
925 heading are all made visible. If `org-show-hierarchy-above' is t,
926 the same happens on each level of the hierarchy above the current entry.
928 By default this is on for the isearch context, off for all other contexts.
929 Turning this off for example for sparse trees makes them very compact,
930 but makes it harder to edit the location of the match. In such a case,
931 use the command \\[org-reveal] to show more context.
932 Instead of t, this can also be an alist specifying this option for different
933 contexts. See `org-show-hierarchy-above' for valid contexts."
934 :group 'org-reveal-location
935 :type org-context-choice)
937 (defcustom org-show-entry-below '((default . nil))
938 "Non-nil means show the entry below a headline when revealing a location.
939 Org-mode often shows locations in an org-mode file which might have
940 been invisible before. When this is set, the text below the headline that is
941 exposed is also shown.
943 By default this is off for all contexts.
944 Instead of t, this can also be an alist specifying this option for different
945 contexts. See `org-show-hierarchy-above' for valid contexts."
946 :group 'org-reveal-location
947 :type org-context-choice)
949 (defcustom org-indirect-buffer-display 'other-window
950 "How should indirect tree buffers be displayed?
951 This applies to indirect buffers created with the commands
952 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
953 Valid values are:
954 current-window Display in the current window
955 other-window Just display in another window.
956 dedicated-frame Create one new frame, and re-use it each time.
957 new-frame Make a new frame each time. Note that in this case
958 previously-made indirect buffers are kept, and you need to
959 kill these buffers yourself."
960 :group 'org-structure
961 :group 'org-agenda-windows
962 :type '(choice
963 (const :tag "In current window" current-window)
964 (const :tag "In current frame, other window" other-window)
965 (const :tag "Each time a new frame" new-frame)
966 (const :tag "One dedicated frame" dedicated-frame)))
968 (defcustom org-use-speed-commands nil
969 "Non-nil means activate single letter commands at beginning of a headline.
970 This may also be a function to test for appropriate locations where speed
971 commands should be active."
972 :group 'org-structure
973 :type '(choice
974 (const :tag "Never" nil)
975 (const :tag "At beginning of headline stars" t)
976 (function)))
978 (defcustom org-speed-commands-user nil
979 "Alist of additional speed commands.
980 This list will be checked before `org-speed-commands-default'
981 when the variable `org-use-speed-commands' is non-nil
982 and when the cursor is at the beginning of a headline.
983 The car if each entry is a string with a single letter, which must
984 be assigned to `self-insert-command' in the global map.
985 The cdr is either a command to be called interactively, a function
986 to be called, or a form to be evaluated.
987 An entry that is just a list with a single string will be interpreted
988 as a descriptive headline that will be added when listing the speed
989 commands in the Help buffer using the `?' speed command."
990 :group 'org-structure
991 :type '(repeat :value ("k" . ignore)
992 (choice :value ("k" . ignore)
993 (list :tag "Descriptive Headline" (string :tag "Headline"))
994 (cons :tag "Letter and Command"
995 (string :tag "Command letter")
996 (choice
997 (function)
998 (sexp))))))
1000 (defgroup org-cycle nil
1001 "Options concerning visibility cycling in Org-mode."
1002 :tag "Org Cycle"
1003 :group 'org-structure)
1005 (defcustom org-cycle-skip-children-state-if-no-children t
1006 "Non-nil means skip CHILDREN state in entries that don't have any."
1007 :group 'org-cycle
1008 :type 'boolean)
1010 (defcustom org-cycle-max-level nil
1011 "Maximum level which should still be subject to visibility cycling.
1012 Levels higher than this will, for cycling, be treated as text, not a headline.
1013 When `org-odd-levels-only' is set, a value of N in this variable actually
1014 means 2N-1 stars as the limiting headline.
1015 When nil, cycle all levels.
1016 Note that the limiting level of cycling is also influenced by
1017 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1018 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1019 than its value."
1020 :group 'org-cycle
1021 :type '(choice
1022 (const :tag "No limit" nil)
1023 (integer :tag "Maximum level")))
1025 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1026 "Names of drawers. Drawers are not opened by cycling on the headline above.
1027 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1028 this:
1029 :DRAWERNAME:
1030 .....
1031 :END:
1032 The drawer \"PROPERTIES\" is special for capturing properties through
1033 the property API.
1035 Drawers can be defined on the per-file basis with a line like:
1037 #+DRAWERS: HIDDEN STATE PROPERTIES"
1038 :group 'org-structure
1039 :group 'org-cycle
1040 :type '(repeat (string :tag "Drawer Name")))
1042 (defcustom org-hide-block-startup nil
1043 "Non-nil means entering Org-mode will fold all blocks.
1044 This can also be set in on a per-file basis with
1046 #+STARTUP: hideblocks
1047 #+STARTUP: showblocks"
1048 :group 'org-startup
1049 :group 'org-cycle
1050 :type 'boolean)
1052 (defcustom org-cycle-global-at-bob nil
1053 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1054 This makes it possible to do global cycling without having to use S-TAB or
1055 \\[universal-argument] TAB. For this special case to work, the first line
1056 of the buffer must not be a headline -- it may be empty or some other text.
1057 When used in this way, `org-cycle-hook' is disabled temporarily to make
1058 sure the cursor stays at the beginning of the buffer. When this option is
1059 nil, don't do anything special at the beginning of the buffer."
1060 :group 'org-cycle
1061 :type 'boolean)
1063 (defcustom org-cycle-level-after-item/entry-creation t
1064 "Non-nil means cycle entry level or item indentation in new empty entries.
1066 When the cursor is at the end of an empty headline, i.e., with only stars
1067 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1068 and then all possible ancestor states, before returning to the original state.
1069 This makes data entry extremely fast: M-RET to create a new headline,
1070 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1072 When the cursor is at the end of an empty plain list item, one TAB will
1073 make it a subitem, two or more tabs will back up to make this an item
1074 higher up in the item hierarchy."
1075 :group 'org-cycle
1076 :type 'boolean)
1078 (defcustom org-cycle-emulate-tab t
1079 "Where should `org-cycle' emulate TAB.
1080 nil Never
1081 white Only in completely white lines
1082 whitestart Only at the beginning of lines, before the first non-white char
1083 t Everywhere except in headlines
1084 exc-hl-bol Everywhere except at the start of a headline
1085 If TAB is used in a place where it does not emulate TAB, the current subtree
1086 visibility is cycled."
1087 :group 'org-cycle
1088 :type '(choice (const :tag "Never" nil)
1089 (const :tag "Only in completely white lines" white)
1090 (const :tag "Before first char in a line" whitestart)
1091 (const :tag "Everywhere except in headlines" t)
1092 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
1095 (defcustom org-cycle-separator-lines 2
1096 "Number of empty lines needed to keep an empty line between collapsed trees.
1097 If you leave an empty line between the end of a subtree and the following
1098 headline, this empty line is hidden when the subtree is folded.
1099 Org-mode will leave (exactly) one empty line visible if the number of
1100 empty lines is equal or larger to the number given in this variable.
1101 So the default 2 means at least 2 empty lines after the end of a subtree
1102 are needed to produce free space between a collapsed subtree and the
1103 following headline.
1105 If the number is negative, and the number of empty lines is at least -N,
1106 all empty lines are shown.
1108 Special case: when 0, never leave empty lines in collapsed view."
1109 :group 'org-cycle
1110 :type 'integer)
1111 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1113 (defcustom org-pre-cycle-hook nil
1114 "Hook that is run before visibility cycling is happening.
1115 The function(s) in this hook must accept a single argument which indicates
1116 the new state that will be set right after running this hook. The
1117 argument is a symbol. Before a global state change, it can have the values
1118 `overview', `content', or `all'. Before a local state change, it can have
1119 the values `folded', `children', or `subtree'."
1120 :group 'org-cycle
1121 :type 'hook)
1123 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1124 org-cycle-hide-drawers
1125 org-cycle-hide-inline-tasks
1126 org-cycle-show-empty-lines
1127 org-optimize-window-after-visibility-change)
1128 "Hook that is run after `org-cycle' has changed the buffer visibility.
1129 The function(s) in this hook must accept a single argument which indicates
1130 the new state that was set by the most recent `org-cycle' command. The
1131 argument is a symbol. After a global state change, it can have the values
1132 `overview', `contents', or `all'. After a local state change, it can have
1133 the values `folded', `children', or `subtree'."
1134 :group 'org-cycle
1135 :type 'hook)
1137 (defgroup org-edit-structure nil
1138 "Options concerning structure editing in Org-mode."
1139 :tag "Org Edit Structure"
1140 :group 'org-structure)
1142 (defcustom org-odd-levels-only nil
1143 "Non-nil means skip even levels and only use odd levels for the outline.
1144 This has the effect that two stars are being added/taken away in
1145 promotion/demotion commands. It also influences how levels are
1146 handled by the exporters.
1147 Changing it requires restart of `font-lock-mode' to become effective
1148 for fontification also in regions already fontified.
1149 You may also set this on a per-file basis by adding one of the following
1150 lines to the buffer:
1152 #+STARTUP: odd
1153 #+STARTUP: oddeven"
1154 :group 'org-edit-structure
1155 :group 'org-appearance
1156 :type 'boolean)
1158 (defcustom org-adapt-indentation t
1159 "Non-nil means adapt indentation to outline node level.
1161 When this variable is set, Org assumes that you write outlines by
1162 indenting text in each node to align with the headline (after the stars).
1163 The following issues are influenced by this variable:
1165 - When this is set and the *entire* text in an entry is indented, the
1166 indentation is increased by one space in a demotion command, and
1167 decreased by one in a promotion command. If any line in the entry
1168 body starts with text at column 0, indentation is not changed at all.
1170 - Property drawers and planning information is inserted indented when
1171 this variable s set. When nil, they will not be indented.
1173 - TAB indents a line relative to context. The lines below a headline
1174 will be indented when this variable is set.
1176 Note that this is all about true indentation, by adding and removing
1177 space characters. See also `org-indent.el' which does level-dependent
1178 indentation in a virtual way, i.e. at display time in Emacs."
1179 :group 'org-edit-structure
1180 :type 'boolean)
1182 (defcustom org-special-ctrl-a/e nil
1183 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1185 When t, `C-a' will bring back the cursor to the beginning of the
1186 headline text, i.e. after the stars and after a possible TODO
1187 keyword. In an item, this will be the position after bullet and
1188 check-box, if any. When the cursor is already at that position,
1189 another `C-a' will bring it to the beginning of the line.
1191 `C-e' will jump to the end of the headline, ignoring the presence
1192 of tags in the headline. A second `C-e' will then jump to the
1193 true end of the line, after any tags. This also means that, when
1194 this variable is non-nil, `C-e' also will never jump beyond the
1195 end of the heading of a folded section, i.e. not after the
1196 ellipses.
1198 When set to the symbol `reversed', the first `C-a' or `C-e' works
1199 normally, going to the true line boundary first. Only a directly
1200 following, identical keypress will bring the cursor to the
1201 special positions.
1203 This may also be a cons cell where the behavior for `C-a' and
1204 `C-e' is set separately."
1205 :group 'org-edit-structure
1206 :type '(choice
1207 (const :tag "off" nil)
1208 (const :tag "on: after stars/bullet and before tags first" t)
1209 (const :tag "reversed: true line boundary first" reversed)
1210 (cons :tag "Set C-a and C-e separately"
1211 (choice :tag "Special C-a"
1212 (const :tag "off" nil)
1213 (const :tag "on: after stars/bullet first" t)
1214 (const :tag "reversed: before stars/bullet first" reversed))
1215 (choice :tag "Special C-e"
1216 (const :tag "off" nil)
1217 (const :tag "on: before tags first" t)
1218 (const :tag "reversed: after tags first" reversed)))))
1219 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1221 (defcustom org-special-ctrl-k nil
1222 "Non-nil means `C-k' will behave specially in headlines.
1223 When nil, `C-k' will call the default `kill-line' command.
1224 When t, the following will happen while the cursor is in the headline:
1226 - When the cursor is at the beginning of a headline, kill the entire
1227 line and possible the folded subtree below the line.
1228 - When in the middle of the headline text, kill the headline up to the tags.
1229 - When after the headline text, kill the tags."
1230 :group 'org-edit-structure
1231 :type 'boolean)
1233 (defcustom org-ctrl-k-protect-subtree nil
1234 "Non-nil means, do not delete a hidden subtree with C-k.
1235 When set to the symbol `error', simply throw an error when C-k is
1236 used to kill (part-of) a headline that has hidden text behind it.
1237 Any other non-nil value will result in a query to the user, if it is
1238 OK to kill that hidden subtree. When nil, kill without remorse."
1239 :group 'org-edit-structure
1240 :version "24.1"
1241 :type '(choice
1242 (const :tag "Do not protect hidden subtrees" nil)
1243 (const :tag "Protect hidden subtrees with a security query" t)
1244 (const :tag "Never kill a hidden subtree with C-k" error)))
1246 (defcustom org-catch-invisible-edits nil
1247 "Check if in invisible region before inserting or deleting a character.
1248 Valid values are:
1250 nil Do not check, so just do invisible edits.
1251 error Throw an error and do nothing.
1252 show Make point visible, and do the requested edit.
1253 show-and-error Make point visible, then throw an error and abort the edit.
1254 smart Make point visible, and do insertion/deletion if it is
1255 adjacent to visible text and the change feels predictable.
1256 Never delete a previously invisible character or add in the
1257 middle or right after an invisible region. Basically, this
1258 allows insertion and backward-delete right before ellipses.
1259 FIXME: maybe in this case we should not even show?"
1260 :group 'org-edit-structure
1261 :version "24.1"
1262 :type '(choice
1263 (const :tag "Do not check" nil)
1264 (const :tag "Throw error when trying to edit" error)
1265 (const :tag "Unhide, but do not do the edit" show-and-error)
1266 (const :tag "Show invisible part and do the edit" show)
1267 (const :tag "Be smart and do the right thing" smart)))
1269 (defcustom org-yank-folded-subtrees t
1270 "Non-nil means when yanking subtrees, fold them.
1271 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1272 it starts with a heading and all other headings in it are either children
1273 or siblings, then fold all the subtrees. However, do this only if no
1274 text after the yank would be swallowed into a folded tree by this action."
1275 :group 'org-edit-structure
1276 :type 'boolean)
1278 (defcustom org-yank-adjusted-subtrees nil
1279 "Non-nil means when yanking subtrees, adjust the level.
1280 With this setting, `org-paste-subtree' is used to insert the subtree, see
1281 this function for details."
1282 :group 'org-edit-structure
1283 :type 'boolean)
1285 (defcustom org-M-RET-may-split-line '((default . t))
1286 "Non-nil means M-RET will split the line at the cursor position.
1287 When nil, it will go to the end of the line before making a
1288 new line.
1289 You may also set this option in a different way for different
1290 contexts. Valid contexts are:
1292 headline when creating a new headline
1293 item when creating a new item
1294 table in a table field
1295 default the value to be used for all contexts not explicitly
1296 customized"
1297 :group 'org-structure
1298 :group 'org-table
1299 :type '(choice
1300 (const :tag "Always" t)
1301 (const :tag "Never" nil)
1302 (repeat :greedy t :tag "Individual contexts"
1303 (cons
1304 (choice :tag "Context"
1305 (const headline)
1306 (const item)
1307 (const table)
1308 (const default))
1309 (boolean)))))
1312 (defcustom org-insert-heading-respect-content nil
1313 "Non-nil means insert new headings after the current subtree.
1314 When nil, the new heading is created directly after the current line.
1315 The commands \\[org-insert-heading-respect-content] and
1316 \\[org-insert-todo-heading-respect-content] turn this variable on
1317 for the duration of the command."
1318 :group 'org-structure
1319 :type 'boolean)
1321 (defcustom org-blank-before-new-entry '((heading . auto)
1322 (plain-list-item . auto))
1323 "Should `org-insert-heading' leave a blank line before new heading/item?
1324 The value is an alist, with `heading' and `plain-list-item' as CAR,
1325 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1326 which case Org will look at the surrounding headings/items and try to
1327 make an intelligent decision whether to insert a blank line or not.
1329 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1330 the setting here is ignored and no empty line is inserted to avoid breaking
1331 the list structure."
1332 :group 'org-edit-structure
1333 :type '(list
1334 (cons (const heading)
1335 (choice (const :tag "Never" nil)
1336 (const :tag "Always" t)
1337 (const :tag "Auto" auto)))
1338 (cons (const plain-list-item)
1339 (choice (const :tag "Never" nil)
1340 (const :tag "Always" t)
1341 (const :tag "Auto" auto)))))
1343 (defcustom org-insert-heading-hook nil
1344 "Hook being run after inserting a new heading."
1345 :group 'org-edit-structure
1346 :type 'hook)
1348 (defcustom org-enable-fixed-width-editor t
1349 "Non-nil means lines starting with \":\" are treated as fixed-width.
1350 This currently only means they are never auto-wrapped.
1351 When nil, such lines will be treated like ordinary lines.
1352 See also the QUOTE keyword."
1353 :group 'org-edit-structure
1354 :type 'boolean)
1356 (defcustom org-goto-auto-isearch t
1357 "Non-nil means typing characters in `org-goto' starts incremental search.
1358 When nil, you can use these keybindings to navigate the buffer:
1360 q Quit the org-goto interface
1361 n Go to the next visible heading
1362 p Go to the previous visible heading
1363 f Go one heading forward on same level
1364 b Go one heading backward on same level
1365 u Go one heading up"
1366 :group 'org-edit-structure
1367 :type 'boolean)
1369 (defgroup org-sparse-trees nil
1370 "Options concerning sparse trees in Org-mode."
1371 :tag "Org Sparse Trees"
1372 :group 'org-structure)
1374 (defcustom org-highlight-sparse-tree-matches t
1375 "Non-nil means highlight all matches that define a sparse tree.
1376 The highlights will automatically disappear the next time the buffer is
1377 changed by an edit command."
1378 :group 'org-sparse-trees
1379 :type 'boolean)
1381 (defcustom org-remove-highlights-with-change t
1382 "Non-nil means any change to the buffer will remove temporary highlights.
1383 Such highlights are created by `org-occur' and `org-clock-display'.
1384 When nil, `C-c C-c needs to be used to get rid of the highlights.
1385 The highlights created by `org-preview-latex-fragment' always need
1386 `C-c C-c' to be removed."
1387 :group 'org-sparse-trees
1388 :group 'org-time
1389 :type 'boolean)
1392 (defcustom org-occur-hook '(org-first-headline-recenter)
1393 "Hook that is run after `org-occur' has constructed a sparse tree.
1394 This can be used to recenter the window to show as much of the structure
1395 as possible."
1396 :group 'org-sparse-trees
1397 :type 'hook)
1399 (defgroup org-imenu-and-speedbar nil
1400 "Options concerning imenu and speedbar in Org-mode."
1401 :tag "Org Imenu and Speedbar"
1402 :group 'org-structure)
1404 (defcustom org-imenu-depth 2
1405 "The maximum level for Imenu access to Org-mode headlines.
1406 This also applied for speedbar access."
1407 :group 'org-imenu-and-speedbar
1408 :type 'integer)
1410 (defgroup org-table nil
1411 "Options concerning tables in Org-mode."
1412 :tag "Org Table"
1413 :group 'org)
1415 (defcustom org-enable-table-editor 'optimized
1416 "Non-nil means lines starting with \"|\" are handled by the table editor.
1417 When nil, such lines will be treated like ordinary lines.
1419 When equal to the symbol `optimized', the table editor will be optimized to
1420 do the following:
1421 - Automatic overwrite mode in front of whitespace in table fields.
1422 This makes the structure of the table stay in tact as long as the edited
1423 field does not exceed the column width.
1424 - Minimize the number of realigns. Normally, the table is aligned each time
1425 TAB or RET are pressed to move to another field. With optimization this
1426 happens only if changes to a field might have changed the column width.
1427 Optimization requires replacing the functions `self-insert-command',
1428 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1429 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1430 very good at guessing when a re-align will be necessary, but you can always
1431 force one with \\[org-ctrl-c-ctrl-c].
1433 If you would like to use the optimized version in Org-mode, but the
1434 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1436 This variable can be used to turn on and off the table editor during a session,
1437 but in order to toggle optimization, a restart is required.
1439 See also the variable `org-table-auto-blank-field'."
1440 :group 'org-table
1441 :type '(choice
1442 (const :tag "off" nil)
1443 (const :tag "on" t)
1444 (const :tag "on, optimized" optimized)))
1446 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1447 (version<= emacs-version "24.1"))
1448 "Non-nil means cluster self-insert commands for undo when possible.
1449 If this is set, then, like in the Emacs command loop, 20 consecutive
1450 characters will be undone together.
1451 This is configurable, because there is some impact on typing performance."
1452 :group 'org-table
1453 :type 'boolean)
1455 (defcustom org-table-tab-recognizes-table.el t
1456 "Non-nil means TAB will automatically notice a table.el table.
1457 When it sees such a table, it moves point into it and - if necessary -
1458 calls `table-recognize-table'."
1459 :group 'org-table-editing
1460 :type 'boolean)
1462 (defgroup org-link nil
1463 "Options concerning links in Org-mode."
1464 :tag "Org Link"
1465 :group 'org)
1467 (defvar org-link-abbrev-alist-local nil
1468 "Buffer-local version of `org-link-abbrev-alist', which see.
1469 The value of this is taken from the #+LINK lines.")
1470 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1472 (defcustom org-link-abbrev-alist nil
1473 "Alist of link abbreviations.
1474 The car of each element is a string, to be replaced at the start of a link.
1475 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1476 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1478 [[linkkey:tag][description]]
1480 The 'linkkey' must be a word word, starting with a letter, followed
1481 by letters, numbers, '-' or '_'.
1483 If REPLACE is a string, the tag will simply be appended to create the link.
1484 If the string contains \"%s\", the tag will be inserted there. If the string
1485 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1486 at that point (see the function `url-hexify-string'). If the string contains
1487 the specifier \"%(my-function)\", then the custom function `my-function' will
1488 be invoked: this function takes the tag as its only argument and must return
1489 a string.
1491 REPLACE may also be a function that will be called with the tag as the
1492 only argument to create the link, which should be returned as a string.
1494 See the manual for examples."
1495 :group 'org-link
1496 :type '(repeat
1497 (cons
1498 (string :tag "Protocol")
1499 (choice
1500 (string :tag "Format")
1501 (function)))))
1503 (defcustom org-descriptive-links t
1504 "Non-nil means Org will display descriptive links.
1505 E.g. [[http://orgmode.org][Org website]] will be displayed as
1506 \"Org Website\", hiding the link itself and just displaying its
1507 description. When set to `nil', Org will display the full links
1508 literally.
1510 You can interactively set the value of this variable by calling
1511 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1512 :group 'org-link
1513 :type 'boolean)
1515 (defcustom org-link-file-path-type 'adaptive
1516 "How the path name in file links should be stored.
1517 Valid values are:
1519 relative Relative to the current directory, i.e. the directory of the file
1520 into which the link is being inserted.
1521 absolute Absolute path, if possible with ~ for home directory.
1522 noabbrev Absolute path, no abbreviation of home directory.
1523 adaptive Use relative path for files in the current directory and sub-
1524 directories of it. For other files, use an absolute path."
1525 :group 'org-link
1526 :type '(choice
1527 (const relative)
1528 (const absolute)
1529 (const noabbrev)
1530 (const adaptive)))
1532 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1533 "Types of links that should be activated in Org-mode files.
1534 This is a list of symbols, each leading to the activation of a certain link
1535 type. In principle, it does not hurt to turn on most link types - there may
1536 be a small gain when turning off unused link types. The types are:
1538 bracket The recommended [[link][description]] or [[link]] links with hiding.
1539 angle Links in angular brackets that may contain whitespace like
1540 <bbdb:Carsten Dominik>.
1541 plain Plain links in normal text, no whitespace, like http://google.com.
1542 radio Text that is matched by a radio target, see manual for details.
1543 tag Tag settings in a headline (link to tag search).
1544 date Time stamps (link to calendar).
1545 footnote Footnote labels.
1547 Changing this variable requires a restart of Emacs to become effective."
1548 :group 'org-link
1549 :type '(set :greedy t
1550 (const :tag "Double bracket links" bracket)
1551 (const :tag "Angular bracket links" angle)
1552 (const :tag "Plain text links" plain)
1553 (const :tag "Radio target matches" radio)
1554 (const :tag "Tags" tag)
1555 (const :tag "Timestamps" date)
1556 (const :tag "Footnotes" footnote)))
1558 (defcustom org-make-link-description-function nil
1559 "Function to use for generating link descriptions from links.
1560 When nil, the link location will be used. This function must take
1561 two parameters: the first one is the link, the second one is the
1562 description generated by `org-insert-link'. The function should
1563 return the description to use."
1564 :group 'org-link
1565 :type 'function)
1567 (defgroup org-link-store nil
1568 "Options concerning storing links in Org-mode."
1569 :tag "Org Store Link"
1570 :group 'org-link)
1572 (defcustom org-url-hexify-p t
1573 "When non-nil, hexify URL when creating a link."
1574 :type 'boolean
1575 :version "24.3"
1576 :group 'org-link-store)
1578 (defcustom org-email-link-description-format "Email %c: %.30s"
1579 "Format of the description part of a link to an email or usenet message.
1580 The following %-escapes will be replaced by corresponding information:
1582 %F full \"From\" field
1583 %f name, taken from \"From\" field, address if no name
1584 %T full \"To\" field
1585 %t first name in \"To\" field, address if no name
1586 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1587 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1588 %s subject
1589 %d date
1590 %m message-id.
1592 You may use normal field width specification between the % and the letter.
1593 This is for example useful to limit the length of the subject.
1595 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1596 :group 'org-link-store
1597 :type 'string)
1599 (defcustom org-from-is-user-regexp
1600 (let (r1 r2)
1601 (when (and user-mail-address (not (string= user-mail-address "")))
1602 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1603 (when (and user-full-name (not (string= user-full-name "")))
1604 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1605 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1606 "Regexp matched against the \"From:\" header of an email or usenet message.
1607 It should match if the message is from the user him/herself."
1608 :group 'org-link-store
1609 :type 'regexp)
1611 (defcustom org-context-in-file-links t
1612 "Non-nil means file links from `org-store-link' contain context.
1613 A search string will be added to the file name with :: as separator and
1614 used to find the context when the link is activated by the command
1615 `org-open-at-point'. When this option is t, the entire active region
1616 will be placed in the search string of the file link. If set to a
1617 positive integer, only the first n lines of context will be stored.
1619 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1620 negates this setting for the duration of the command."
1621 :group 'org-link-store
1622 :type '(choice boolean integer))
1624 (defcustom org-keep-stored-link-after-insertion nil
1625 "Non-nil means keep link in list for entire session.
1627 The command `org-store-link' adds a link pointing to the current
1628 location to an internal list. These links accumulate during a session.
1629 The command `org-insert-link' can be used to insert links into any
1630 Org-mode file (offering completion for all stored links). When this
1631 option is nil, every link which has been inserted once using \\[org-insert-link]
1632 will be removed from the list, to make completing the unused links
1633 more efficient."
1634 :group 'org-link-store
1635 :type 'boolean)
1637 (defgroup org-link-follow nil
1638 "Options concerning following links in Org-mode."
1639 :tag "Org Follow Link"
1640 :group 'org-link)
1642 (defcustom org-link-translation-function nil
1643 "Function to translate links with different syntax to Org syntax.
1644 This can be used to translate links created for example by the Planner
1645 or emacs-wiki packages to Org syntax.
1646 The function must accept two parameters, a TYPE containing the link
1647 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1648 which is everything after the link protocol. It should return a cons
1649 with possibly modified values of type and path.
1650 Org contains a function for this, so if you set this variable to
1651 `org-translate-link-from-planner', you should be able follow many
1652 links created by planner."
1653 :group 'org-link-follow
1654 :type 'function)
1656 (defcustom org-follow-link-hook nil
1657 "Hook that is run after a link has been followed."
1658 :group 'org-link-follow
1659 :type 'hook)
1661 (defcustom org-tab-follows-link nil
1662 "Non-nil means on links TAB will follow the link.
1663 Needs to be set before org.el is loaded.
1664 This really should not be used, it does not make sense, and the
1665 implementation is bad."
1666 :group 'org-link-follow
1667 :type 'boolean)
1669 (defcustom org-return-follows-link nil
1670 "Non-nil means on links RET will follow the link.
1671 In tables, the special behavior of RET has precedence."
1672 :group 'org-link-follow
1673 :type 'boolean)
1675 (defcustom org-mouse-1-follows-link
1676 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1677 "Non-nil means mouse-1 on a link will follow the link.
1678 A longer mouse click will still set point. Does not work on XEmacs.
1679 Needs to be set before org.el is loaded."
1680 :group 'org-link-follow
1681 :type 'boolean)
1683 (defcustom org-mark-ring-length 4
1684 "Number of different positions to be recorded in the ring.
1685 Changing this requires a restart of Emacs to work correctly."
1686 :group 'org-link-follow
1687 :type 'integer)
1689 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1690 "Non-nil means internal links in Org files must exactly match a headline.
1691 When nil, the link search tries to match a phrase with all words
1692 in the search text."
1693 :group 'org-link-follow
1694 :version "24.1"
1695 :type '(choice
1696 (const :tag "Use fuzzy text search" nil)
1697 (const :tag "Match only exact headline" t)
1698 (const :tag "Match exact headline or query to create it"
1699 query-to-create)))
1701 (defcustom org-link-frame-setup
1702 '((vm . vm-visit-folder-other-frame)
1703 (vm-imap . vm-visit-imap-folder-other-frame)
1704 (gnus . org-gnus-no-new-news)
1705 (file . find-file-other-window)
1706 (wl . wl-other-frame))
1707 "Setup the frame configuration for following links.
1708 When following a link with Emacs, it may often be useful to display
1709 this link in another window or frame. This variable can be used to
1710 set this up for the different types of links.
1711 For VM, use any of
1712 `vm-visit-folder'
1713 `vm-visit-folder-other-window'
1714 `vm-visit-folder-other-frame'
1715 For Gnus, use any of
1716 `gnus'
1717 `gnus-other-frame'
1718 `org-gnus-no-new-news'
1719 For FILE, use any of
1720 `find-file'
1721 `find-file-other-window'
1722 `find-file-other-frame'
1723 For Wanderlust use any of
1724 `wl'
1725 `wl-other-frame'
1726 For the calendar, use the variable `calendar-setup'.
1727 For BBDB, it is currently only possible to display the matches in
1728 another window."
1729 :group 'org-link-follow
1730 :type '(list
1731 (cons (const vm)
1732 (choice
1733 (const vm-visit-folder)
1734 (const vm-visit-folder-other-window)
1735 (const vm-visit-folder-other-frame)))
1736 (cons (const gnus)
1737 (choice
1738 (const gnus)
1739 (const gnus-other-frame)
1740 (const org-gnus-no-new-news)))
1741 (cons (const file)
1742 (choice
1743 (const find-file)
1744 (const find-file-other-window)
1745 (const find-file-other-frame)))
1746 (cons (const wl)
1747 (choice
1748 (const wl)
1749 (const wl-other-frame)))))
1751 (defcustom org-display-internal-link-with-indirect-buffer nil
1752 "Non-nil means use indirect buffer to display infile links.
1753 Activating internal links (from one location in a file to another location
1754 in the same file) normally just jumps to the location. When the link is
1755 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1756 is displayed in
1757 another window. When this option is set, the other window actually displays
1758 an indirect buffer clone of the current buffer, to avoid any visibility
1759 changes to the current buffer."
1760 :group 'org-link-follow
1761 :type 'boolean)
1763 (defcustom org-open-non-existing-files nil
1764 "Non-nil means `org-open-file' will open non-existing files.
1765 When nil, an error will be generated.
1766 This variable applies only to external applications because they
1767 might choke on non-existing files. If the link is to a file that
1768 will be opened in Emacs, the variable is ignored."
1769 :group 'org-link-follow
1770 :type 'boolean)
1772 (defcustom org-open-directory-means-index-dot-org nil
1773 "Non-nil means a link to a directory really means to index.org.
1774 When nil, following a directory link will run dired or open a finder/explorer
1775 window on that directory."
1776 :group 'org-link-follow
1777 :type 'boolean)
1779 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1780 "Function and arguments to call for following mailto links.
1781 This is a list with the first element being a Lisp function, and the
1782 remaining elements being arguments to the function. In string arguments,
1783 %a will be replaced by the address, and %s will be replaced by the subject
1784 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1785 :group 'org-link-follow
1786 :type '(choice
1787 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1788 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1789 (const :tag "message-mail" (message-mail "%a" "%s"))
1790 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1792 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1793 "Non-nil means ask for confirmation before executing shell links.
1794 Shell links can be dangerous: just think about a link
1796 [[shell:rm -rf ~/*][Google Search]]
1798 This link would show up in your Org-mode document as \"Google Search\",
1799 but really it would remove your entire home directory.
1800 Therefore we advise against setting this variable to nil.
1801 Just change it to `y-or-n-p' if you want to confirm with a
1802 single keystroke rather than having to type \"yes\"."
1803 :group 'org-link-follow
1804 :type '(choice
1805 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1806 (const :tag "with y-or-n (faster)" y-or-n-p)
1807 (const :tag "no confirmation (dangerous)" nil)))
1808 (put 'org-confirm-shell-link-function
1809 'safe-local-variable
1810 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1812 (defcustom org-confirm-shell-link-not-regexp ""
1813 "A regexp to skip confirmation for shell links."
1814 :group 'org-link-follow
1815 :version "24.1"
1816 :type 'regexp)
1818 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1819 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1820 Elisp links can be dangerous: just think about a link
1822 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1824 This link would show up in your Org-mode document as \"Google Search\",
1825 but really it would remove your entire home directory.
1826 Therefore we advise against setting this variable to nil.
1827 Just change it to `y-or-n-p' if you want to confirm with a
1828 single keystroke rather than having to type \"yes\"."
1829 :group 'org-link-follow
1830 :type '(choice
1831 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1832 (const :tag "with y-or-n (faster)" y-or-n-p)
1833 (const :tag "no confirmation (dangerous)" nil)))
1834 (put 'org-confirm-shell-link-function
1835 'safe-local-variable
1836 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1838 (defcustom org-confirm-elisp-link-not-regexp ""
1839 "A regexp to skip confirmation for Elisp links."
1840 :group 'org-link-follow
1841 :version "24.1"
1842 :type 'regexp)
1844 (defconst org-file-apps-defaults-gnu
1845 '((remote . emacs)
1846 (system . mailcap)
1847 (t . mailcap))
1848 "Default file applications on a UNIX or GNU/Linux system.
1849 See `org-file-apps'.")
1851 (defconst org-file-apps-defaults-macosx
1852 '((remote . emacs)
1853 (t . "open %s")
1854 (system . "open %s")
1855 ("ps.gz" . "gv %s")
1856 ("eps.gz" . "gv %s")
1857 ("dvi" . "xdvi %s")
1858 ("fig" . "xfig %s"))
1859 "Default file applications on a MacOS X system.
1860 The system \"open\" is known as a default, but we use X11 applications
1861 for some files for which the OS does not have a good default.
1862 See `org-file-apps'.")
1864 (defconst org-file-apps-defaults-windowsnt
1865 (list
1866 '(remote . emacs)
1867 (cons t
1868 (list (if (featurep 'xemacs)
1869 'mswindows-shell-execute
1870 'w32-shell-execute)
1871 "open" 'file))
1872 (cons 'system
1873 (list (if (featurep 'xemacs)
1874 'mswindows-shell-execute
1875 'w32-shell-execute)
1876 "open" 'file)))
1877 "Default file applications on a Windows NT system.
1878 The system \"open\" is used for most files.
1879 See `org-file-apps'.")
1881 (defcustom org-file-apps
1883 (auto-mode . emacs)
1884 ("\\.mm\\'" . default)
1885 ("\\.x?html?\\'" . default)
1886 ("\\.pdf\\'" . default)
1888 "External applications for opening `file:path' items in a document.
1889 Org-mode uses system defaults for different file types, but
1890 you can use this variable to set the application for a given file
1891 extension. The entries in this list are cons cells where the car identifies
1892 files and the cdr the corresponding command. Possible values for the
1893 file identifier are
1894 \"string\" A string as a file identifier can be interpreted in different
1895 ways, depending on its contents:
1897 - Alphanumeric characters only:
1898 Match links with this file extension.
1899 Example: (\"pdf\" . \"evince %s\")
1900 to open PDFs with evince.
1902 - Regular expression: Match links where the
1903 filename matches the regexp. If you want to
1904 use groups here, use shy groups.
1906 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1907 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1908 to open *.html and *.xhtml with firefox.
1910 - Regular expression which contains (non-shy) groups:
1911 Match links where the whole link, including \"::\", and
1912 anything after that, matches the regexp.
1913 In a custom command string, %1, %2, etc. are replaced with
1914 the parts of the link that were matched by the groups.
1915 For backwards compatibility, if a command string is given
1916 that does not use any of the group matches, this case is
1917 handled identically to the second one (i.e. match against
1918 file name only).
1919 In a custom lisp form, you can access the group matches with
1920 (match-string n link).
1922 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1923 to open [[file:document.pdf::5]] with evince at page 5.
1925 `directory' Matches a directory
1926 `remote' Matches a remote file, accessible through tramp or efs.
1927 Remote files most likely should be visited through Emacs
1928 because external applications cannot handle such paths.
1929 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1930 so all files Emacs knows how to handle. Using this with
1931 command `emacs' will open most files in Emacs. Beware that this
1932 will also open html files inside Emacs, unless you add
1933 (\"html\" . default) to the list as well.
1934 t Default for files not matched by any of the other options.
1935 `system' The system command to open files, like `open' on Windows
1936 and Mac OS X, and mailcap under GNU/Linux. This is the command
1937 that will be selected if you call `C-c C-o' with a double
1938 \\[universal-argument] \\[universal-argument] prefix.
1940 Possible values for the command are:
1941 `emacs' The file will be visited by the current Emacs process.
1942 `default' Use the default application for this file type, which is the
1943 association for t in the list, most likely in the system-specific
1944 part.
1945 This can be used to overrule an unwanted setting in the
1946 system-specific variable.
1947 `system' Use the system command for opening files, like \"open\".
1948 This command is specified by the entry whose car is `system'.
1949 Most likely, the system-specific version of this variable
1950 does define this command, but you can overrule/replace it
1951 here.
1952 string A command to be executed by a shell; %s will be replaced
1953 by the path to the file.
1954 sexp A Lisp form which will be evaluated. The file path will
1955 be available in the Lisp variable `file'.
1956 For more examples, see the system specific constants
1957 `org-file-apps-defaults-macosx'
1958 `org-file-apps-defaults-windowsnt'
1959 `org-file-apps-defaults-gnu'."
1960 :group 'org-link-follow
1961 :type '(repeat
1962 (cons (choice :value ""
1963 (string :tag "Extension")
1964 (const :tag "System command to open files" system)
1965 (const :tag "Default for unrecognized files" t)
1966 (const :tag "Remote file" remote)
1967 (const :tag "Links to a directory" directory)
1968 (const :tag "Any files that have Emacs modes"
1969 auto-mode))
1970 (choice :value ""
1971 (const :tag "Visit with Emacs" emacs)
1972 (const :tag "Use default" default)
1973 (const :tag "Use the system command" system)
1974 (string :tag "Command")
1975 (sexp :tag "Lisp form")))))
1977 (defcustom org-doi-server-url "http://dx.doi.org/"
1978 "The URL of the DOI server."
1979 :type 'string
1980 :version "24.3"
1981 :group 'org-link-follow)
1983 (defgroup org-refile nil
1984 "Options concerning refiling entries in Org-mode."
1985 :tag "Org Refile"
1986 :group 'org)
1988 (defcustom org-directory "~/org"
1989 "Directory with org files.
1990 This is just a default location to look for Org files. There is no need
1991 at all to put your files into this directory. It is only used in the
1992 following situations:
1994 1. When a capture template specifies a target file that is not an
1995 absolute path. The path will then be interpreted relative to
1996 `org-directory'
1997 2. When a capture note is filed away in an interactive way (when exiting the
1998 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1999 with `org-directory' as the default path."
2000 :group 'org-refile
2001 :group 'org-remember
2002 :group 'org-capture
2003 :type 'directory)
2005 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2006 "Default target for storing notes.
2007 Used as a fall back file for org-remember.el and org-capture.el, for
2008 templates that do not specify a target file."
2009 :group 'org-refile
2010 :group 'org-remember
2011 :group 'org-capture
2012 :type '(choice
2013 (const :tag "Default from remember-data-file" nil)
2014 file))
2016 (defcustom org-goto-interface 'outline
2017 "The default interface to be used for `org-goto'.
2018 Allowed values are:
2019 outline The interface shows an outline of the relevant file
2020 and the correct heading is found by moving through
2021 the outline or by searching with incremental search.
2022 outline-path-completion Headlines in the current buffer are offered via
2023 completion. This is the interface also used by
2024 the refile command."
2025 :group 'org-refile
2026 :type '(choice
2027 (const :tag "Outline" outline)
2028 (const :tag "Outline-path-completion" outline-path-completion)))
2030 (defcustom org-goto-max-level 5
2031 "Maximum target level when running `org-goto' with refile interface."
2032 :group 'org-refile
2033 :type 'integer)
2035 (defcustom org-reverse-note-order nil
2036 "Non-nil means store new notes at the beginning of a file or entry.
2037 When nil, new notes will be filed to the end of a file or entry.
2038 This can also be a list with cons cells of regular expressions that
2039 are matched against file names, and values."
2040 :group 'org-remember
2041 :group 'org-capture
2042 :group 'org-refile
2043 :type '(choice
2044 (const :tag "Reverse always" t)
2045 (const :tag "Reverse never" nil)
2046 (repeat :tag "By file name regexp"
2047 (cons regexp boolean))))
2049 (defcustom org-log-refile nil
2050 "Information to record when a task is refiled.
2052 Possible values are:
2054 nil Don't add anything
2055 time Add a time stamp to the task
2056 note Prompt for a note and add it with template `org-log-note-headings'
2058 This option can also be set with on a per-file-basis with
2060 #+STARTUP: nologrefile
2061 #+STARTUP: logrefile
2062 #+STARTUP: lognoterefile
2064 You can have local logging settings for a subtree by setting the LOGGING
2065 property to one or more of these keywords.
2067 When bulk-refiling from the agenda, the value `note' is forbidden and
2068 will temporarily be changed to `time'."
2069 :group 'org-refile
2070 :group 'org-progress
2071 :version "24.1"
2072 :type '(choice
2073 (const :tag "No logging" nil)
2074 (const :tag "Record timestamp" time)
2075 (const :tag "Record timestamp with note." note)))
2077 (defcustom org-refile-targets nil
2078 "Targets for refiling entries with \\[org-refile].
2079 This is a list of cons cells. Each cell contains:
2080 - a specification of the files to be considered, either a list of files,
2081 or a symbol whose function or variable value will be used to retrieve
2082 a file name or a list of file names. If you use `org-agenda-files' for
2083 that, all agenda files will be scanned for targets. Nil means consider
2084 headings in the current buffer.
2085 - A specification of how to find candidate refile targets. This may be
2086 any of:
2087 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2088 This tag has to be present in all target headlines, inheritance will
2089 not be considered.
2090 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2091 todo keyword.
2092 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2093 headlines that are refiling targets.
2094 - a cons cell (:level . N). Any headline of level N is considered a target.
2095 Note that, when `org-odd-levels-only' is set, level corresponds to
2096 order in hierarchy, not to the number of stars.
2097 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2098 Note that, when `org-odd-levels-only' is set, level corresponds to
2099 order in hierarchy, not to the number of stars.
2101 Each element of this list generates a set of possible targets.
2102 The union of these sets is presented (with completion) to
2103 the user by `org-refile'.
2105 You can set the variable `org-refile-target-verify-function' to a function
2106 to verify each headline found by the simple criteria above.
2108 When this variable is nil, all top-level headlines in the current buffer
2109 are used, equivalent to the value `((nil . (:level . 1))'."
2110 :group 'org-refile
2111 :type '(repeat
2112 (cons
2113 (choice :value org-agenda-files
2114 (const :tag "All agenda files" org-agenda-files)
2115 (const :tag "Current buffer" nil)
2116 (function) (variable) (file))
2117 (choice :tag "Identify target headline by"
2118 (cons :tag "Specific tag" (const :value :tag) (string))
2119 (cons :tag "TODO keyword" (const :value :todo) (string))
2120 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2121 (cons :tag "Level number" (const :value :level) (integer))
2122 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2124 (defcustom org-refile-target-verify-function nil
2125 "Function to verify if the headline at point should be a refile target.
2126 The function will be called without arguments, with point at the
2127 beginning of the headline. It should return t and leave point
2128 where it is if the headline is a valid target for refiling.
2130 If the target should not be selected, the function must return nil.
2131 In addition to this, it may move point to a place from where the search
2132 should be continued. For example, the function may decide that the entire
2133 subtree of the current entry should be excluded and move point to the end
2134 of the subtree."
2135 :group 'org-refile
2136 :type 'function)
2138 (defcustom org-refile-use-cache nil
2139 "Non-nil means cache refile targets to speed up the process.
2140 The cache for a particular file will be updated automatically when
2141 the buffer has been killed, or when any of the marker used for flagging
2142 refile targets no longer points at a live buffer.
2143 If you have added new entries to a buffer that might themselves be targets,
2144 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2145 find that easier, `C-u C-u C-u C-c C-w'."
2146 :group 'org-refile
2147 :version "24.1"
2148 :type 'boolean)
2150 (defcustom org-refile-use-outline-path nil
2151 "Non-nil means provide refile targets as paths.
2152 So a level 3 headline will be available as level1/level2/level3.
2154 When the value is `file', also include the file name (without directory)
2155 into the path. In this case, you can also stop the completion after
2156 the file name, to get entries inserted as top level in the file.
2158 When `full-file-path', include the full file path."
2159 :group 'org-refile
2160 :type '(choice
2161 (const :tag "Not" nil)
2162 (const :tag "Yes" t)
2163 (const :tag "Start with file name" file)
2164 (const :tag "Start with full file path" full-file-path)))
2166 (defcustom org-outline-path-complete-in-steps t
2167 "Non-nil means complete the outline path in hierarchical steps.
2168 When Org-mode uses the refile interface to select an outline path
2169 \(see variable `org-refile-use-outline-path'), the completion of
2170 the path can be done is a single go, or if can be done in steps down
2171 the headline hierarchy. Going in steps is probably the best if you
2172 do not use a special completion package like `ido' or `icicles'.
2173 However, when using these packages, going in one step can be very
2174 fast, while still showing the whole path to the entry."
2175 :group 'org-refile
2176 :type 'boolean)
2178 (defcustom org-refile-allow-creating-parent-nodes nil
2179 "Non-nil means allow to create new nodes as refile targets.
2180 New nodes are then created by adding \"/new node name\" to the completion
2181 of an existing node. When the value of this variable is `confirm',
2182 new node creation must be confirmed by the user (recommended)
2183 When nil, the completion must match an existing entry.
2185 Note that, if the new heading is not seen by the criteria
2186 listed in `org-refile-targets', multiple instances of the same
2187 heading would be created by trying again to file under the new
2188 heading."
2189 :group 'org-refile
2190 :type '(choice
2191 (const :tag "Never" nil)
2192 (const :tag "Always" t)
2193 (const :tag "Prompt for confirmation" confirm)))
2195 (defcustom org-refile-active-region-within-subtree nil
2196 "Non-nil means also refile active region within a subtree.
2198 By default `org-refile' doesn't allow refiling regions if they
2199 don't contain a set of subtrees, but it might be convenient to
2200 do so sometimes: in that case, the first line of the region is
2201 converted to a headline before refiling."
2202 :group 'org-refile
2203 :version "24.1"
2204 :type 'boolean)
2206 (defgroup org-todo nil
2207 "Options concerning TODO items in Org-mode."
2208 :tag "Org TODO"
2209 :group 'org)
2211 (defgroup org-progress nil
2212 "Options concerning Progress logging in Org-mode."
2213 :tag "Org Progress"
2214 :group 'org-time)
2216 (defvar org-todo-interpretation-widgets
2217 '((:tag "Sequence (cycling hits every state)" sequence)
2218 (:tag "Type (cycling directly to DONE)" type))
2219 "The available interpretation symbols for customizing `org-todo-keywords'.
2220 Interested libraries should add to this list.")
2222 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2223 "List of TODO entry keyword sequences and their interpretation.
2224 \\<org-mode-map>This is a list of sequences.
2226 Each sequence starts with a symbol, either `sequence' or `type',
2227 indicating if the keywords should be interpreted as a sequence of
2228 action steps, or as different types of TODO items. The first
2229 keywords are states requiring action - these states will select a headline
2230 for inclusion into the global TODO list Org-mode produces. If one of
2231 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2232 signify that no further action is necessary. If \"|\" is not found,
2233 the last keyword is treated as the only DONE state of the sequence.
2235 The command \\[org-todo] cycles an entry through these states, and one
2236 additional state where no keyword is present. For details about this
2237 cycling, see the manual.
2239 TODO keywords and interpretation can also be set on a per-file basis with
2240 the special #+SEQ_TODO and #+TYP_TODO lines.
2242 Each keyword can optionally specify a character for fast state selection
2243 \(in combination with the variable `org-use-fast-todo-selection')
2244 and specifiers for state change logging, using the same syntax that
2245 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2246 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2247 indicates to record a time stamp each time this state is selected.
2249 Each keyword may also specify if a timestamp or a note should be
2250 recorded when entering or leaving the state, by adding additional
2251 characters in the parenthesis after the keyword. This looks like this:
2252 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2253 record only the time of the state change. With X and Y being either
2254 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2255 Y when leaving the state if and only if the *target* state does not
2256 define X. You may omit any of the fast-selection key or X or /Y,
2257 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2259 For backward compatibility, this variable may also be just a list
2260 of keywords. In this case the interpretation (sequence or type) will be
2261 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2262 :group 'org-todo
2263 :group 'org-keywords
2264 :type '(choice
2265 (repeat :tag "Old syntax, just keywords"
2266 (string :tag "Keyword"))
2267 (repeat :tag "New syntax"
2268 (cons
2269 (choice
2270 :tag "Interpretation"
2271 ;;Quick and dirty way to see
2272 ;;`org-todo-interpretations'. This takes the
2273 ;;place of item arguments
2274 :convert-widget
2275 (lambda (widget)
2276 (widget-put widget
2277 :args (mapcar
2278 #'(lambda (x)
2279 (widget-convert
2280 (cons 'const x)))
2281 org-todo-interpretation-widgets))
2282 widget))
2283 (repeat
2284 (string :tag "Keyword"))))))
2286 (defvar org-todo-keywords-1 nil
2287 "All TODO and DONE keywords active in a buffer.")
2288 (make-variable-buffer-local 'org-todo-keywords-1)
2289 (defvar org-todo-keywords-for-agenda nil)
2290 (defvar org-done-keywords-for-agenda nil)
2291 (defvar org-drawers-for-agenda nil)
2292 (defvar org-todo-keyword-alist-for-agenda nil)
2293 (defvar org-tag-alist-for-agenda nil
2294 "Alist of all tags from all agenda files.")
2295 (defvar org-tag-groups-alist-for-agenda nil
2296 "Alist of all groups tags from all current agenda files.")
2297 (defvar org-tag-groups-alist nil)
2298 (make-variable-buffer-local 'org-tag-groups-alist)
2299 (defvar org-agenda-contributing-files nil)
2300 (defvar org-not-done-keywords nil)
2301 (make-variable-buffer-local 'org-not-done-keywords)
2302 (defvar org-done-keywords nil)
2303 (make-variable-buffer-local 'org-done-keywords)
2304 (defvar org-todo-heads nil)
2305 (make-variable-buffer-local 'org-todo-heads)
2306 (defvar org-todo-sets nil)
2307 (make-variable-buffer-local 'org-todo-sets)
2308 (defvar org-todo-log-states nil)
2309 (make-variable-buffer-local 'org-todo-log-states)
2310 (defvar org-todo-kwd-alist nil)
2311 (make-variable-buffer-local 'org-todo-kwd-alist)
2312 (defvar org-todo-key-alist nil)
2313 (make-variable-buffer-local 'org-todo-key-alist)
2314 (defvar org-todo-key-trigger nil)
2315 (make-variable-buffer-local 'org-todo-key-trigger)
2317 (defcustom org-todo-interpretation 'sequence
2318 "Controls how TODO keywords are interpreted.
2319 This variable is in principle obsolete and is only used for
2320 backward compatibility, if the interpretation of todo keywords is
2321 not given already in `org-todo-keywords'. See that variable for
2322 more information."
2323 :group 'org-todo
2324 :group 'org-keywords
2325 :type '(choice (const sequence)
2326 (const type)))
2328 (defcustom org-use-fast-todo-selection t
2329 "Non-nil means use the fast todo selection scheme with C-c C-t.
2330 This variable describes if and under what circumstances the cycling
2331 mechanism for TODO keywords will be replaced by a single-key, direct
2332 selection scheme.
2334 When nil, fast selection is never used.
2336 When the symbol `prefix', it will be used when `org-todo' is called
2337 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2338 `C-u t' in an agenda buffer.
2340 When t, fast selection is used by default. In this case, the prefix
2341 argument forces cycling instead.
2343 In all cases, the special interface is only used if access keys have
2344 actually been assigned by the user, i.e. if keywords in the configuration
2345 are followed by a letter in parenthesis, like TODO(t)."
2346 :group 'org-todo
2347 :type '(choice
2348 (const :tag "Never" nil)
2349 (const :tag "By default" t)
2350 (const :tag "Only with C-u C-c C-t" prefix)))
2352 (defcustom org-provide-todo-statistics t
2353 "Non-nil means update todo statistics after insert and toggle.
2354 ALL-HEADLINES means update todo statistics by including headlines
2355 with no TODO keyword as well, counting them as not done.
2356 A list of TODO keywords means the same, but skip keywords that are
2357 not in this list.
2359 When this is set, todo statistics is updated in the parent of the
2360 current entry each time a todo state is changed."
2361 :group 'org-todo
2362 :type '(choice
2363 (const :tag "Yes, only for TODO entries" t)
2364 (const :tag "Yes, including all entries" 'all-headlines)
2365 (repeat :tag "Yes, for TODOs in this list"
2366 (string :tag "TODO keyword"))
2367 (other :tag "No TODO statistics" nil)))
2369 (defcustom org-hierarchical-todo-statistics t
2370 "Non-nil means TODO statistics covers just direct children.
2371 When nil, all entries in the subtree are considered.
2372 This has only an effect if `org-provide-todo-statistics' is set.
2373 To set this to nil for only a single subtree, use a COOKIE_DATA
2374 property and include the word \"recursive\" into the value."
2375 :group 'org-todo
2376 :type 'boolean)
2378 (defcustom org-after-todo-state-change-hook nil
2379 "Hook which is run after the state of a TODO item was changed.
2380 The new state (a string with a TODO keyword, or nil) is available in the
2381 Lisp variable `org-state'."
2382 :group 'org-todo
2383 :type 'hook)
2385 (defvar org-blocker-hook nil
2386 "Hook for functions that are allowed to block a state change.
2388 Functions in this hook should not modify the buffer.
2389 Each function gets as its single argument a property list,
2390 see `org-trigger-hook' for more information about this list.
2392 If any of the functions in this hook returns nil, the state change
2393 is blocked.")
2395 (defvar org-trigger-hook nil
2396 "Hook for functions that are triggered by a state change.
2398 Each function gets as its single argument a property list with at
2399 least the following elements:
2401 (:type type-of-change :position pos-at-entry-start
2402 :from old-state :to new-state)
2404 Depending on the type, more properties may be present.
2406 This mechanism is currently implemented for:
2408 TODO state changes
2409 ------------------
2410 :type todo-state-change
2411 :from previous state (keyword as a string), or nil, or a symbol
2412 'todo' or 'done', to indicate the general type of state.
2413 :to new state, like in :from")
2415 (defcustom org-enforce-todo-dependencies nil
2416 "Non-nil means undone TODO entries will block switching the parent to DONE.
2417 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2418 be blocked if any prior sibling is not yet done.
2419 Finally, if the parent is blocked because of ordered siblings of its own,
2420 the child will also be blocked."
2421 :set (lambda (var val)
2422 (set var val)
2423 (if val
2424 (add-hook 'org-blocker-hook
2425 'org-block-todo-from-children-or-siblings-or-parent)
2426 (remove-hook 'org-blocker-hook
2427 'org-block-todo-from-children-or-siblings-or-parent)))
2428 :group 'org-todo
2429 :type 'boolean)
2431 (defcustom org-enforce-todo-checkbox-dependencies nil
2432 "Non-nil means unchecked boxes will block switching the parent to DONE.
2433 When this is nil, checkboxes have no influence on switching TODO states.
2434 When non-nil, you first need to check off all check boxes before the TODO
2435 entry can be switched to DONE.
2436 This variable needs to be set before org.el is loaded, and you need to
2437 restart Emacs after a change to make the change effective. The only way
2438 to change is while Emacs is running is through the customize interface."
2439 :set (lambda (var val)
2440 (set var val)
2441 (if val
2442 (add-hook 'org-blocker-hook
2443 'org-block-todo-from-checkboxes)
2444 (remove-hook 'org-blocker-hook
2445 'org-block-todo-from-checkboxes)))
2446 :group 'org-todo
2447 :type 'boolean)
2449 (defcustom org-treat-insert-todo-heading-as-state-change nil
2450 "Non-nil means inserting a TODO heading is treated as state change.
2451 So when the command \\[org-insert-todo-heading] is used, state change
2452 logging will apply if appropriate. When nil, the new TODO item will
2453 be inserted directly, and no logging will take place."
2454 :group 'org-todo
2455 :type 'boolean)
2457 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2458 "Non-nil means switching TODO states with S-cursor counts as state change.
2459 This is the default behavior. However, setting this to nil allows a
2460 convenient way to select a TODO state and bypass any logging associated
2461 with that."
2462 :group 'org-todo
2463 :type 'boolean)
2465 (defcustom org-todo-state-tags-triggers nil
2466 "Tag changes that should be triggered by TODO state changes.
2467 This is a list. Each entry is
2469 (state-change (tag . flag) .......)
2471 State-change can be a string with a state, and empty string to indicate the
2472 state that has no TODO keyword, or it can be one of the symbols `todo'
2473 or `done', meaning any not-done or done state, respectively."
2474 :group 'org-todo
2475 :group 'org-tags
2476 :type '(repeat
2477 (cons (choice :tag "When changing to"
2478 (const :tag "Not-done state" todo)
2479 (const :tag "Done state" done)
2480 (string :tag "State"))
2481 (repeat
2482 (cons :tag "Tag action"
2483 (string :tag "Tag")
2484 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2486 (defcustom org-log-done nil
2487 "Information to record when a task moves to the DONE state.
2489 Possible values are:
2491 nil Don't add anything, just change the keyword
2492 time Add a time stamp to the task
2493 note Prompt for a note and add it with template `org-log-note-headings'
2495 This option can also be set with on a per-file-basis with
2497 #+STARTUP: nologdone
2498 #+STARTUP: logdone
2499 #+STARTUP: lognotedone
2501 You can have local logging settings for a subtree by setting the LOGGING
2502 property to one or more of these keywords."
2503 :group 'org-todo
2504 :group 'org-progress
2505 :type '(choice
2506 (const :tag "No logging" nil)
2507 (const :tag "Record CLOSED timestamp" time)
2508 (const :tag "Record CLOSED timestamp with note." note)))
2510 ;; Normalize old uses of org-log-done.
2511 (cond
2512 ((eq org-log-done t) (setq org-log-done 'time))
2513 ((and (listp org-log-done) (memq 'done org-log-done))
2514 (setq org-log-done 'note)))
2516 (defcustom org-log-reschedule nil
2517 "Information to record when the scheduling date of a tasks is modified.
2519 Possible values are:
2521 nil Don't add anything, just change the date
2522 time Add a time stamp to the task
2523 note Prompt for a note and add it with template `org-log-note-headings'
2525 This option can also be set with on a per-file-basis with
2527 #+STARTUP: nologreschedule
2528 #+STARTUP: logreschedule
2529 #+STARTUP: lognotereschedule"
2530 :group 'org-todo
2531 :group 'org-progress
2532 :type '(choice
2533 (const :tag "No logging" nil)
2534 (const :tag "Record timestamp" time)
2535 (const :tag "Record timestamp with note." note)))
2537 (defcustom org-log-redeadline nil
2538 "Information to record when the deadline date of a tasks is modified.
2540 Possible values are:
2542 nil Don't add anything, just change the date
2543 time Add a time stamp to the task
2544 note Prompt for a note and add it with template `org-log-note-headings'
2546 This option can also be set with on a per-file-basis with
2548 #+STARTUP: nologredeadline
2549 #+STARTUP: logredeadline
2550 #+STARTUP: lognoteredeadline
2552 You can have local logging settings for a subtree by setting the LOGGING
2553 property to one or more of these keywords."
2554 :group 'org-todo
2555 :group 'org-progress
2556 :type '(choice
2557 (const :tag "No logging" nil)
2558 (const :tag "Record timestamp" time)
2559 (const :tag "Record timestamp with note." note)))
2561 (defcustom org-log-note-clock-out nil
2562 "Non-nil means record a note when clocking out of an item.
2563 This can also be configured on a per-file basis by adding one of
2564 the following lines anywhere in the buffer:
2566 #+STARTUP: lognoteclock-out
2567 #+STARTUP: nolognoteclock-out"
2568 :group 'org-todo
2569 :group 'org-progress
2570 :type 'boolean)
2572 (defcustom org-log-done-with-time t
2573 "Non-nil means the CLOSED time stamp will contain date and time.
2574 When nil, only the date will be recorded."
2575 :group 'org-progress
2576 :type 'boolean)
2578 (defcustom org-log-note-headings
2579 '((done . "CLOSING NOTE %t")
2580 (state . "State %-12s from %-12S %t")
2581 (note . "Note taken on %t")
2582 (reschedule . "Rescheduled from %S on %t")
2583 (delschedule . "Not scheduled, was %S on %t")
2584 (redeadline . "New deadline from %S on %t")
2585 (deldeadline . "Removed deadline, was %S on %t")
2586 (refile . "Refiled on %t")
2587 (clock-out . ""))
2588 "Headings for notes added to entries.
2589 The value is an alist, with the car being a symbol indicating the note
2590 context, and the cdr is the heading to be used. The heading may also be the
2591 empty string.
2592 %t in the heading will be replaced by a time stamp.
2593 %T will be an active time stamp instead the default inactive one
2594 %d will be replaced by a short-format time stamp.
2595 %D will be replaced by an active short-format time stamp.
2596 %s will be replaced by the new TODO state, in double quotes.
2597 %S will be replaced by the old TODO state, in double quotes.
2598 %u will be replaced by the user name.
2599 %U will be replaced by the full user name.
2601 In fact, it is not a good idea to change the `state' entry, because
2602 agenda log mode depends on the format of these entries."
2603 :group 'org-todo
2604 :group 'org-progress
2605 :type '(list :greedy t
2606 (cons (const :tag "Heading when closing an item" done) string)
2607 (cons (const :tag
2608 "Heading when changing todo state (todo sequence only)"
2609 state) string)
2610 (cons (const :tag "Heading when just taking a note" note) string)
2611 (cons (const :tag "Heading when clocking out" clock-out) string)
2612 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2613 (cons (const :tag "Heading when rescheduling" reschedule) string)
2614 (cons (const :tag "Heading when changing deadline" redeadline) string)
2615 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2616 (cons (const :tag "Heading when refiling" refile) string)))
2618 (unless (assq 'note org-log-note-headings)
2619 (push '(note . "%t") org-log-note-headings))
2621 (defcustom org-log-into-drawer nil
2622 "Non-nil means insert state change notes and time stamps into a drawer.
2623 When nil, state changes notes will be inserted after the headline and
2624 any scheduling and clock lines, but not inside a drawer.
2626 The value of this variable should be the name of the drawer to use.
2627 LOGBOOK is proposed as the default drawer for this purpose, you can
2628 also set this to a string to define the drawer of your choice.
2630 A value of t is also allowed, representing \"LOGBOOK\".
2632 A value of t or nil can also be set with on a per-file-basis with
2634 #+STARTUP: logdrawer
2635 #+STARTUP: nologdrawer
2637 If this variable is set, `org-log-state-notes-insert-after-drawers'
2638 will be ignored.
2640 You can set the property LOG_INTO_DRAWER to overrule this setting for
2641 a subtree."
2642 :group 'org-todo
2643 :group 'org-progress
2644 :type '(choice
2645 (const :tag "Not into a drawer" nil)
2646 (const :tag "LOGBOOK" t)
2647 (string :tag "Other")))
2649 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2651 (defun org-log-into-drawer ()
2652 "Return the value of `org-log-into-drawer', but let properties overrule.
2653 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2654 used instead of the default value."
2655 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2656 (cond
2657 ((not p) org-log-into-drawer)
2658 ((equal p "nil") nil)
2659 ((equal p "t") "LOGBOOK")
2660 (t p))))
2662 (defcustom org-log-state-notes-insert-after-drawers nil
2663 "Non-nil means insert state change notes after any drawers in entry.
2664 Only the drawers that *immediately* follow the headline and the
2665 deadline/scheduled line are skipped.
2666 When nil, insert notes right after the heading and perhaps the line
2667 with deadline/scheduling if present.
2669 This variable will have no effect if `org-log-into-drawer' is
2670 set."
2671 :group 'org-todo
2672 :group 'org-progress
2673 :type 'boolean)
2675 (defcustom org-log-states-order-reversed t
2676 "Non-nil means the latest state note will be directly after heading.
2677 When nil, the state change notes will be ordered according to time.
2679 This option can also be set with on a per-file-basis with
2681 #+STARTUP: logstatesreversed
2682 #+STARTUP: nologstatesreversed"
2683 :group 'org-todo
2684 :group 'org-progress
2685 :type 'boolean)
2687 (defcustom org-todo-repeat-to-state nil
2688 "The TODO state to which a repeater should return the repeating task.
2689 By default this is the first task in a TODO sequence, or the previous state
2690 in a TODO_TYP set. But you can specify another task here.
2691 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2692 :group 'org-todo
2693 :version "24.1"
2694 :type '(choice (const :tag "Head of sequence" nil)
2695 (string :tag "Specific state")))
2697 (defcustom org-log-repeat 'time
2698 "Non-nil means record moving through the DONE state when triggering repeat.
2699 An auto-repeating task is immediately switched back to TODO when
2700 marked DONE. If you are not logging state changes (by adding \"@\"
2701 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2702 record a closing note, there will be no record of the task moving
2703 through DONE. This variable forces taking a note anyway.
2705 nil Don't force a record
2706 time Record a time stamp
2707 note Prompt for a note and add it with template `org-log-note-headings'
2709 This option can also be set with on a per-file-basis with
2711 #+STARTUP: nologrepeat
2712 #+STARTUP: logrepeat
2713 #+STARTUP: lognoterepeat
2715 You can have local logging settings for a subtree by setting the LOGGING
2716 property to one or more of these keywords."
2717 :group 'org-todo
2718 :group 'org-progress
2719 :type '(choice
2720 (const :tag "Don't force a record" nil)
2721 (const :tag "Force recording the DONE state" time)
2722 (const :tag "Force recording a note with the DONE state" note)))
2725 (defgroup org-priorities nil
2726 "Priorities in Org-mode."
2727 :tag "Org Priorities"
2728 :group 'org-todo)
2730 (defcustom org-enable-priority-commands t
2731 "Non-nil means priority commands are active.
2732 When nil, these commands will be disabled, so that you never accidentally
2733 set a priority."
2734 :group 'org-priorities
2735 :type 'boolean)
2737 (defcustom org-highest-priority ?A
2738 "The highest priority of TODO items. A character like ?A, ?B etc.
2739 Must have a smaller ASCII number than `org-lowest-priority'."
2740 :group 'org-priorities
2741 :type 'character)
2743 (defcustom org-lowest-priority ?C
2744 "The lowest priority of TODO items. A character like ?A, ?B etc.
2745 Must have a larger ASCII number than `org-highest-priority'."
2746 :group 'org-priorities
2747 :type 'character)
2749 (defcustom org-default-priority ?B
2750 "The default priority of TODO items.
2751 This is the priority an item gets if no explicit priority is given.
2752 When starting to cycle on an empty priority the first step in the cycle
2753 depends on `org-priority-start-cycle-with-default'. The resulting first
2754 step priority must not exceed the range from `org-highest-priority' to
2755 `org-lowest-priority' which means that `org-default-priority' has to be
2756 in this range exclusive or inclusive the range boundaries. Else the
2757 first step refuses to set the default and the second will fall back
2758 to (depending on the command used) the highest or lowest priority."
2759 :group 'org-priorities
2760 :type 'character)
2762 (defcustom org-priority-start-cycle-with-default t
2763 "Non-nil means start with default priority when starting to cycle.
2764 When this is nil, the first step in the cycle will be (depending on the
2765 command used) one higher or lower than the default priority.
2766 See also `org-default-priority'."
2767 :group 'org-priorities
2768 :type 'boolean)
2770 (defcustom org-get-priority-function nil
2771 "Function to extract the priority from a string.
2772 The string is normally the headline. If this is nil Org computes the
2773 priority from the priority cookie like [#A] in the headline. It returns
2774 an integer, increasing by 1000 for each priority level.
2775 The user can set a different function here, which should take a string
2776 as an argument and return the numeric priority."
2777 :group 'org-priorities
2778 :version "24.1"
2779 :type 'function)
2781 (defgroup org-time nil
2782 "Options concerning time stamps and deadlines in Org-mode."
2783 :tag "Org Time"
2784 :group 'org)
2786 (defcustom org-insert-labeled-timestamps-at-point nil
2787 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2788 When nil, these labeled time stamps are forces into the second line of an
2789 entry, just after the headline. When scheduling from the global TODO list,
2790 the time stamp will always be forced into the second line."
2791 :group 'org-time
2792 :type 'boolean)
2794 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2795 "Formats for `format-time-string' which are used for time stamps.
2796 It is not recommended to change this constant.")
2798 (defcustom org-time-stamp-rounding-minutes '(0 5)
2799 "Number of minutes to round time stamps to.
2800 These are two values, the first applies when first creating a time stamp.
2801 The second applies when changing it with the commands `S-up' and `S-down'.
2802 When changing the time stamp, this means that it will change in steps
2803 of N minutes, as given by the second value.
2805 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2806 numbers should be factors of 60, so for example 5, 10, 15.
2808 When this is larger than 1, you can still force an exact time stamp by using
2809 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2810 and by using a prefix arg to `S-up/down' to specify the exact number
2811 of minutes to shift."
2812 :group 'org-time
2813 :get #'(lambda (var) ; Make sure both elements are there
2814 (if (integerp (default-value var))
2815 (list (default-value var) 5)
2816 (default-value var)))
2817 :type '(list
2818 (integer :tag "when inserting times")
2819 (integer :tag "when modifying times")))
2821 ;; Normalize old customizations of this variable.
2822 (when (integerp org-time-stamp-rounding-minutes)
2823 (setq org-time-stamp-rounding-minutes
2824 (list org-time-stamp-rounding-minutes
2825 org-time-stamp-rounding-minutes)))
2827 (defcustom org-display-custom-times nil
2828 "Non-nil means overlay custom formats over all time stamps.
2829 The formats are defined through the variable `org-time-stamp-custom-formats'.
2830 To turn this on on a per-file basis, insert anywhere in the file:
2831 #+STARTUP: customtime"
2832 :group 'org-time
2833 :set 'set-default
2834 :type 'sexp)
2835 (make-variable-buffer-local 'org-display-custom-times)
2837 (defcustom org-time-stamp-custom-formats
2838 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2839 "Custom formats for time stamps. See `format-time-string' for the syntax.
2840 These are overlaid over the default ISO format if the variable
2841 `org-display-custom-times' is set. Time like %H:%M should be at the
2842 end of the second format. The custom formats are also honored by export
2843 commands, if custom time display is turned on at the time of export."
2844 :group 'org-time
2845 :type 'sexp)
2847 (defun org-time-stamp-format (&optional long inactive)
2848 "Get the right format for a time string."
2849 (let ((f (if long (cdr org-time-stamp-formats)
2850 (car org-time-stamp-formats))))
2851 (if inactive
2852 (concat "[" (substring f 1 -1) "]")
2853 f)))
2855 (defcustom org-time-clocksum-format
2856 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2857 "The format string used when creating CLOCKSUM lines.
2858 This is also used when Org mode generates a time duration.
2860 The value can be a single format string containing two
2861 %-sequences, which will be filled with the number of hours and
2862 minutes in that order.
2864 Alternatively, the value can be a plist associating any of the
2865 keys :years, :months, :weeks, :days, :hours or :minutes with
2866 format strings. The time duration is formatted using only the
2867 time components that are needed and concatenating the results.
2868 If a time unit in absent, it falls back to the next smallest
2869 unit.
2871 The keys :require-years, :require-months, :require-days,
2872 :require-weeks, :require-hours, :require-minutes are also
2873 meaningful. A non-nil value for these keys indicates that the
2874 corresponding time component should always be included, even if
2875 its value is 0.
2878 For example,
2880 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2881 :require-minutes t)
2883 means durations longer than a day will be expressed in days,
2884 hours and minutes, and durations less than a day will always be
2885 expressed in hours and minutes (even for durations less than an
2886 hour).
2888 The value
2890 \(:days \"%dd\" :minutes \"%dm\")
2892 means durations longer than a day will be expressed in days and
2893 minutes, and durations less than a day will be expressed entirely
2894 in minutes (even for durations longer than an hour)."
2895 :group 'org-time
2896 :group 'org-clock
2897 :version "24.4"
2898 :package-version '(Org . "8.0")
2899 :type '(choice (string :tag "Format string")
2900 (set :tag "Plist"
2901 (group :inline t (const :tag "Years" :years)
2902 (string :tag "Format string"))
2903 (group :inline t
2904 (const :tag "Always show years" :require-years)
2905 (const t))
2906 (group :inline t (const :tag "Months" :months)
2907 (string :tag "Format string"))
2908 (group :inline t
2909 (const :tag "Always show months" :require-months)
2910 (const t))
2911 (group :inline t (const :tag "Weeks" :weeks)
2912 (string :tag "Format string"))
2913 (group :inline t
2914 (const :tag "Always show weeks" :require-weeks)
2915 (const t))
2916 (group :inline t (const :tag "Days" :days)
2917 (string :tag "Format string"))
2918 (group :inline t
2919 (const :tag "Always show days" :require-days)
2920 (const t))
2921 (group :inline t (const :tag "Hours" :hours)
2922 (string :tag "Format string"))
2923 (group :inline t
2924 (const :tag "Always show hours" :require-hours)
2925 (const t))
2926 (group :inline t (const :tag "Minutes" :minutes)
2927 (string :tag "Format string"))
2928 (group :inline t
2929 (const :tag "Always show minutes" :require-minutes)
2930 (const t)))))
2932 (defcustom org-time-clocksum-use-fractional nil
2933 "When non-nil, \\[org-clock-display] uses fractional times.
2934 See `org-time-clocksum-format' for more on time clock formats."
2935 :group 'org-time
2936 :group 'org-clock
2937 :version "24.3"
2938 :type 'boolean)
2940 (defcustom org-time-clocksum-use-effort-durations nil
2941 "When non-nil, \\[org-clock-display] uses effort durations.
2942 E.g. by default, one day is considered to be a 8 hours effort,
2943 so a task that has been clocked for 16 hours will be displayed
2944 as during 2 days in the clock display or in the clocktable.
2946 See `org-effort-durations' on how to set effort durations
2947 and `org-time-clocksum-format' for more on time clock formats."
2948 :group 'org-time
2949 :group 'org-clock
2950 :version "24.4"
2951 :package-version '(Org . "8.0")
2952 :type 'boolean)
2954 (defcustom org-time-clocksum-fractional-format "%.2f"
2955 "The format string used when creating CLOCKSUM lines,
2956 or when Org mode generates a time duration, if
2957 `org-time-clocksum-use-fractional' is enabled.
2959 The value can be a single format string containing one
2960 %-sequence, which will be filled with the number of hours as
2961 a float.
2963 Alternatively, the value can be a plist associating any of the
2964 keys :years, :months, :weeks, :days, :hours or :minutes with
2965 a format string. The time duration is formatted using the
2966 largest time unit which gives a non-zero integer part. If all
2967 specified formats have zero integer part, the smallest time unit
2968 is used."
2969 :group 'org-time
2970 :type '(choice (string :tag "Format string")
2971 (set (group :inline t (const :tag "Years" :years)
2972 (string :tag "Format string"))
2973 (group :inline t (const :tag "Months" :months)
2974 (string :tag "Format string"))
2975 (group :inline t (const :tag "Weeks" :weeks)
2976 (string :tag "Format string"))
2977 (group :inline t (const :tag "Days" :days)
2978 (string :tag "Format string"))
2979 (group :inline t (const :tag "Hours" :hours)
2980 (string :tag "Format string"))
2981 (group :inline t (const :tag "Minutes" :minutes)
2982 (string :tag "Format string")))))
2984 (defcustom org-deadline-warning-days 14
2985 "Number of days before expiration during which a deadline becomes active.
2986 This variable governs the display in sparse trees and in the agenda.
2987 When 0 or negative, it means use this number (the absolute value of it)
2988 even if a deadline has a different individual lead time specified.
2990 Custom commands can set this variable in the options section."
2991 :group 'org-time
2992 :group 'org-agenda-daily/weekly
2993 :type 'integer)
2995 (defcustom org-scheduled-delay-days 0
2996 "Number of days before a scheduled item becomes active.
2997 This variable governs the display in sparse trees and in the agenda.
2998 The default value (i.e. 0) means: don't delay scheduled item.
2999 When negative, it means use this number (the absolute value of it)
3000 even if a scheduled item has a different individual delay time
3001 specified.
3003 Custom commands can set this variable in the options section."
3004 :group 'org-time
3005 :group 'org-agenda-daily/weekly
3006 :version "24.4"
3007 :package-version '(Org . "8.0")
3008 :type 'integer)
3010 (defcustom org-read-date-prefer-future t
3011 "Non-nil means assume future for incomplete date input from user.
3012 This affects the following situations:
3013 1. The user gives a month but not a year.
3014 For example, if it is April and you enter \"feb 2\", this will be read
3015 as Feb 2, *next* year. \"May 5\", however, will be this year.
3016 2. The user gives a day, but no month.
3017 For example, if today is the 15th, and you enter \"3\", Org-mode will
3018 read this as the third of *next* month. However, if you enter \"17\",
3019 it will be considered as *this* month.
3021 If you set this variable to the symbol `time', then also the following
3022 will work:
3024 3. If the user gives a time.
3025 If the time is before now, it will be interpreted as tomorrow.
3027 Currently none of this works for ISO week specifications.
3029 When this option is nil, the current day, month and year will always be
3030 used as defaults.
3032 See also `org-agenda-jump-prefer-future'."
3033 :group 'org-time
3034 :type '(choice
3035 (const :tag "Never" nil)
3036 (const :tag "Check month and day" t)
3037 (const :tag "Check month, day, and time" time)))
3039 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3040 "Should the agenda jump command prefer the future for incomplete dates?
3041 The default is to do the same as configured in `org-read-date-prefer-future'.
3042 But you can also set a deviating value here.
3043 This may t or nil, or the symbol `org-read-date-prefer-future'."
3044 :group 'org-agenda
3045 :group 'org-time
3046 :version "24.1"
3047 :type '(choice
3048 (const :tag "Use org-read-date-prefer-future"
3049 org-read-date-prefer-future)
3050 (const :tag "Never" nil)
3051 (const :tag "Always" t)))
3053 (defcustom org-read-date-force-compatible-dates t
3054 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3056 Depending on the system Emacs is running on, certain dates cannot
3057 be represented with the type used internally to represent time.
3058 Dates between 1970-1-1 and 2038-1-1 can always be represented
3059 correctly. Some systems allow for earlier dates, some for later,
3060 some for both. One way to find out it to insert any date into an
3061 Org buffer, putting the cursor on the year and hitting S-up and
3062 S-down to test the range.
3064 When this variable is set to t, the date/time prompt will not let
3065 you specify dates outside the 1970-2037 range, so it is certain that
3066 these dates will work in whatever version of Emacs you are
3067 running, and also that you can move a file from one Emacs implementation
3068 to another. WHenever Org is forcing the year for you, it will display
3069 a message and beep.
3071 When this variable is nil, Org will check if the date is
3072 representable in the specific Emacs implementation you are using.
3073 If not, it will force a year, usually the current year, and beep
3074 to remind you. Currently this setting is not recommended because
3075 the likelihood that you will open your Org files in an Emacs that
3076 has limited date range is not negligible.
3078 A workaround for this problem is to use diary sexp dates for time
3079 stamps outside of this range."
3080 :group 'org-time
3081 :version "24.1"
3082 :type 'boolean)
3084 (defcustom org-read-date-display-live t
3085 "Non-nil means display current interpretation of date prompt live.
3086 This display will be in an overlay, in the minibuffer."
3087 :group 'org-time
3088 :type 'boolean)
3090 (defcustom org-read-date-popup-calendar t
3091 "Non-nil means pop up a calendar when prompting for a date.
3092 In the calendar, the date can be selected with mouse-1. However, the
3093 minibuffer will also be active, and you can simply enter the date as well.
3094 When nil, only the minibuffer will be available."
3095 :group 'org-time
3096 :type 'boolean)
3097 (org-defvaralias 'org-popup-calendar-for-date-prompt
3098 'org-read-date-popup-calendar)
3100 (make-obsolete-variable
3101 'org-read-date-minibuffer-setup-hook
3102 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3103 (defcustom org-read-date-minibuffer-setup-hook nil
3104 "Hook to be used to set up keys for the date/time interface.
3105 Add key definitions to `minibuffer-local-map', which will be a
3106 temporary copy.
3108 WARNING: This option is obsolete, you should use
3109 `org-read-date-minibuffer-local-map' to set up keys."
3110 :group 'org-time
3111 :type 'hook)
3113 (defcustom org-extend-today-until 0
3114 "The hour when your day really ends. Must be an integer.
3115 This has influence for the following applications:
3116 - When switching the agenda to \"today\". It it is still earlier than
3117 the time given here, the day recognized as TODAY is actually yesterday.
3118 - When a date is read from the user and it is still before the time given
3119 here, the current date and time will be assumed to be yesterday, 23:59.
3120 Also, timestamps inserted in capture templates follow this rule.
3122 IMPORTANT: This is a feature whose implementation is and likely will
3123 remain incomplete. Really, it is only here because past midnight seems to
3124 be the favorite working time of John Wiegley :-)"
3125 :group 'org-time
3126 :type 'integer)
3128 (defcustom org-use-effective-time nil
3129 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3130 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3131 \"effective time\" of any timestamps between midnight and 8am will be
3132 23:59 of the previous day."
3133 :group 'org-time
3134 :version "24.1"
3135 :type 'boolean)
3137 (defcustom org-use-last-clock-out-time-as-effective-time nil
3138 "When non-nil, use the last clock out time for `org-todo'.
3139 Note that this option has precedence over the combined use of
3140 `org-use-effective-time' and `org-extend-today-until'."
3141 :group 'org-time
3142 :version "24.4"
3143 :package-version '(Org . "8.0")
3144 :type 'boolean)
3146 (defcustom org-edit-timestamp-down-means-later nil
3147 "Non-nil means S-down will increase the time in a time stamp.
3148 When nil, S-up will increase."
3149 :group 'org-time
3150 :type 'boolean)
3152 (defcustom org-calendar-follow-timestamp-change t
3153 "Non-nil means make the calendar window follow timestamp changes.
3154 When a timestamp is modified and the calendar window is visible, it will be
3155 moved to the new date."
3156 :group 'org-time
3157 :type 'boolean)
3159 (defgroup org-tags nil
3160 "Options concerning tags in Org-mode."
3161 :tag "Org Tags"
3162 :group 'org)
3164 (defcustom org-tag-alist nil
3165 "List of tags allowed in Org-mode files.
3166 When this list is nil, Org-mode will base TAG input on what is already in the
3167 buffer.
3168 The value of this variable is an alist, the car of each entry must be a
3169 keyword as a string, the cdr may be a character that is used to select
3170 that tag through the fast-tag-selection interface.
3171 See the manual for details."
3172 :group 'org-tags
3173 :type '(repeat
3174 (choice
3175 (cons (string :tag "Tag name")
3176 (character :tag "Access char"))
3177 (list :tag "Start radio group"
3178 (const :startgroup)
3179 (option (string :tag "Group description")))
3180 (list :tag "Group tags delimiter"
3181 (const :grouptags))
3182 (list :tag "End radio group"
3183 (const :endgroup)
3184 (option (string :tag "Group description")))
3185 (const :tag "New line" (:newline)))))
3187 (defcustom org-tag-persistent-alist nil
3188 "List of tags that will always appear in all Org-mode files.
3189 This is in addition to any in buffer settings or customizations
3190 of `org-tag-alist'.
3191 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3192 The value of this variable is an alist, the car of each entry must be a
3193 keyword as a string, the cdr may be a character that is used to select
3194 that tag through the fast-tag-selection interface.
3195 See the manual for details.
3196 To disable these tags on a per-file basis, insert anywhere in the file:
3197 #+STARTUP: noptag"
3198 :group 'org-tags
3199 :type '(repeat
3200 (choice
3201 (cons (string :tag "Tag name")
3202 (character :tag "Access char"))
3203 (const :tag "Start radio group" (:startgroup))
3204 (const :tag "Group tags delimiter" (:grouptags))
3205 (const :tag "End radio group" (:endgroup))
3206 (const :tag "New line" (:newline)))))
3208 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3209 "If non-nil, always offer completion for all tags of all agenda files.
3210 Instead of customizing this variable directly, you might want to
3211 set it locally for capture buffers, because there no list of
3212 tags in that file can be created dynamically (there are none).
3214 (add-hook 'org-capture-mode-hook
3215 (lambda ()
3216 (set (make-local-variable
3217 'org-complete-tags-always-offer-all-agenda-tags)
3218 t)))"
3219 :group 'org-tags
3220 :version "24.1"
3221 :type 'boolean)
3223 (defvar org-file-tags nil
3224 "List of tags that can be inherited by all entries in the file.
3225 The tags will be inherited if the variable `org-use-tag-inheritance'
3226 says they should be.
3227 This variable is populated from #+FILETAGS lines.")
3229 (defcustom org-use-fast-tag-selection 'auto
3230 "Non-nil means use fast tag selection scheme.
3231 This is a special interface to select and deselect tags with single keys.
3232 When nil, fast selection is never used.
3233 When the symbol `auto', fast selection is used if and only if selection
3234 characters for tags have been configured, either through the variable
3235 `org-tag-alist' or through a #+TAGS line in the buffer.
3236 When t, fast selection is always used and selection keys are assigned
3237 automatically if necessary."
3238 :group 'org-tags
3239 :type '(choice
3240 (const :tag "Always" t)
3241 (const :tag "Never" nil)
3242 (const :tag "When selection characters are configured" 'auto)))
3244 (defcustom org-fast-tag-selection-single-key nil
3245 "Non-nil means fast tag selection exits after first change.
3246 When nil, you have to press RET to exit it.
3247 During fast tag selection, you can toggle this flag with `C-c'.
3248 This variable can also have the value `expert'. In this case, the window
3249 displaying the tags menu is not even shown, until you press C-c again."
3250 :group 'org-tags
3251 :type '(choice
3252 (const :tag "No" nil)
3253 (const :tag "Yes" t)
3254 (const :tag "Expert" expert)))
3256 (defvar org-fast-tag-selection-include-todo nil
3257 "Non-nil means fast tags selection interface will also offer TODO states.
3258 This is an undocumented feature, you should not rely on it.")
3260 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3261 "The column to which tags should be indented in a headline.
3262 If this number is positive, it specifies the column. If it is negative,
3263 it means that the tags should be flushright to that column. For example,
3264 -80 works well for a normal 80 character screen.
3265 When 0, place tags directly after headline text, with only one space in
3266 between."
3267 :group 'org-tags
3268 :type 'integer)
3270 (defcustom org-auto-align-tags t
3271 "Non-nil keeps tags aligned when modifying headlines.
3272 Some operations (i.e. demoting) change the length of a headline and
3273 therefore shift the tags around. With this option turned on, after
3274 each such operation the tags are again aligned to `org-tags-column'."
3275 :group 'org-tags
3276 :type 'boolean)
3278 (defcustom org-use-tag-inheritance t
3279 "Non-nil means tags in levels apply also for sublevels.
3280 When nil, only the tags directly given in a specific line apply there.
3281 This may also be a list of tags that should be inherited, or a regexp that
3282 matches tags that should be inherited. Additional control is possible
3283 with the variable `org-tags-exclude-from-inheritance' which gives an
3284 explicit list of tags to be excluded from inheritance, even if the value of
3285 `org-use-tag-inheritance' would select it for inheritance.
3287 If this option is t, a match early-on in a tree can lead to a large
3288 number of matches in the subtree when constructing the agenda or creating
3289 a sparse tree. If you only want to see the first match in a tree during
3290 a search, check out the variable `org-tags-match-list-sublevels'."
3291 :group 'org-tags
3292 :type '(choice
3293 (const :tag "Not" nil)
3294 (const :tag "Always" t)
3295 (repeat :tag "Specific tags" (string :tag "Tag"))
3296 (regexp :tag "Tags matched by regexp")))
3298 (defcustom org-tags-exclude-from-inheritance nil
3299 "List of tags that should never be inherited.
3300 This is a way to exclude a few tags from inheritance. For way to do
3301 the opposite, to actively allow inheritance for selected tags,
3302 see the variable `org-use-tag-inheritance'."
3303 :group 'org-tags
3304 :type '(repeat (string :tag "Tag")))
3306 (defun org-tag-inherit-p (tag)
3307 "Check if TAG is one that should be inherited."
3308 (cond
3309 ((member tag org-tags-exclude-from-inheritance) nil)
3310 ((eq org-use-tag-inheritance t) t)
3311 ((not org-use-tag-inheritance) nil)
3312 ((stringp org-use-tag-inheritance)
3313 (string-match org-use-tag-inheritance tag))
3314 ((listp org-use-tag-inheritance)
3315 (member tag org-use-tag-inheritance))
3316 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3318 (defcustom org-tags-match-list-sublevels t
3319 "Non-nil means list also sublevels of headlines matching a search.
3320 This variable applies to tags/property searches, and also to stuck
3321 projects because this search is based on a tags match as well.
3323 When set to the symbol `indented', sublevels are indented with
3324 leading dots.
3326 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3327 the sublevels of a headline matching a tag search often also match
3328 the same search. Listing all of them can create very long lists.
3329 Setting this variable to nil causes subtrees of a match to be skipped.
3331 This variable is semi-obsolete and probably should always be true. It
3332 is better to limit inheritance to certain tags using the variables
3333 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3334 :group 'org-tags
3335 :type '(choice
3336 (const :tag "No, don't list them" nil)
3337 (const :tag "Yes, do list them" t)
3338 (const :tag "List them, indented with leading dots" indented)))
3340 (defcustom org-tags-sort-function nil
3341 "When set, tags are sorted using this function as a comparator."
3342 :group 'org-tags
3343 :type '(choice
3344 (const :tag "No sorting" nil)
3345 (const :tag "Alphabetical" string<)
3346 (const :tag "Reverse alphabetical" string>)
3347 (function :tag "Custom function" nil)))
3349 (defvar org-tags-history nil
3350 "History of minibuffer reads for tags.")
3351 (defvar org-last-tags-completion-table nil
3352 "The last used completion table for tags.")
3353 (defvar org-after-tags-change-hook nil
3354 "Hook that is run after the tags in a line have changed.")
3356 (defgroup org-properties nil
3357 "Options concerning properties in Org-mode."
3358 :tag "Org Properties"
3359 :group 'org)
3361 (defcustom org-property-format "%-10s %s"
3362 "How property key/value pairs should be formatted by `indent-line'.
3363 When `indent-line' hits a property definition, it will format the line
3364 according to this format, mainly to make sure that the values are
3365 lined-up with respect to each other."
3366 :group 'org-properties
3367 :type 'string)
3369 (defcustom org-properties-postprocess-alist nil
3370 "Alist of properties and functions to adjust inserted values.
3371 Elements of this alist must be of the form
3373 ([string] [function])
3375 where [string] must be a property name and [function] must be a
3376 lambda expression: this lambda expression must take one argument,
3377 the value to adjust, and return the new value as a string.
3379 For example, this element will allow the property \"Remaining\"
3380 to be updated wrt the relation between the \"Effort\" property
3381 and the clock summary:
3383 ((\"Remaining\" (lambda(value)
3384 (let ((clocksum (org-clock-sum-current-item))
3385 (effort (org-duration-string-to-minutes
3386 (org-entry-get (point) \"Effort\"))))
3387 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3388 :group 'org-properties
3389 :version "24.1"
3390 :type '(alist :key-type (string :tag "Property")
3391 :value-type (function :tag "Function")))
3393 (defcustom org-use-property-inheritance nil
3394 "Non-nil means properties apply also for sublevels.
3396 This setting is chiefly used during property searches. Turning it on can
3397 cause significant overhead when doing a search, which is why it is not
3398 on by default.
3400 When nil, only the properties directly given in the current entry count.
3401 When t, every property is inherited. The value may also be a list of
3402 properties that should have inheritance, or a regular expression matching
3403 properties that should be inherited.
3405 However, note that some special properties use inheritance under special
3406 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3407 and the properties ending in \"_ALL\" when they are used as descriptor
3408 for valid values of a property.
3410 Note for programmers:
3411 When querying an entry with `org-entry-get', you can control if inheritance
3412 should be used. By default, `org-entry-get' looks only at the local
3413 properties. You can request inheritance by setting the inherit argument
3414 to t (to force inheritance) or to `selective' (to respect the setting
3415 in this variable)."
3416 :group 'org-properties
3417 :type '(choice
3418 (const :tag "Not" nil)
3419 (const :tag "Always" t)
3420 (repeat :tag "Specific properties" (string :tag "Property"))
3421 (regexp :tag "Properties matched by regexp")))
3423 (defun org-property-inherit-p (property)
3424 "Check if PROPERTY is one that should be inherited."
3425 (cond
3426 ((eq org-use-property-inheritance t) t)
3427 ((not org-use-property-inheritance) nil)
3428 ((stringp org-use-property-inheritance)
3429 (string-match org-use-property-inheritance property))
3430 ((listp org-use-property-inheritance)
3431 (member property org-use-property-inheritance))
3432 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3434 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3435 "The default column format, if no other format has been defined.
3436 This variable can be set on the per-file basis by inserting a line
3438 #+COLUMNS: %25ITEM ....."
3439 :group 'org-properties
3440 :type 'string)
3442 (defcustom org-columns-ellipses ".."
3443 "The ellipses to be used when a field in column view is truncated.
3444 When this is the empty string, as many characters as possible are shown,
3445 but then there will be no visual indication that the field has been truncated.
3446 When this is a string of length N, the last N characters of a truncated
3447 field are replaced by this string. If the column is narrower than the
3448 ellipses string, only part of the ellipses string will be shown."
3449 :group 'org-properties
3450 :type 'string)
3452 (defcustom org-columns-modify-value-for-display-function nil
3453 "Function that modifies values for display in column view.
3454 For example, it can be used to cut out a certain part from a time stamp.
3455 The function must take 2 arguments:
3457 column-title The title of the column (*not* the property name)
3458 value The value that should be modified.
3460 The function should return the value that should be displayed,
3461 or nil if the normal value should be used."
3462 :group 'org-properties
3463 :type 'function)
3465 (defcustom org-effort-property "Effort"
3466 "The property that is being used to keep track of effort estimates.
3467 Effort estimates given in this property need to have the format H:MM."
3468 :group 'org-properties
3469 :group 'org-progress
3470 :type '(string :tag "Property"))
3472 (defconst org-global-properties-fixed
3473 '(("VISIBILITY_ALL" . "folded children content all")
3474 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3475 "List of property/value pairs that can be inherited by any entry.
3477 These are fixed values, for the preset properties. The user variable
3478 that can be used to add to this list is `org-global-properties'.
3480 The entries in this list are cons cells where the car is a property
3481 name and cdr is a string with the value. If the value represents
3482 multiple items like an \"_ALL\" property, separate the items by
3483 spaces.")
3485 (defcustom org-global-properties nil
3486 "List of property/value pairs that can be inherited by any entry.
3488 This list will be combined with the constant `org-global-properties-fixed'.
3490 The entries in this list are cons cells where the car is a property
3491 name and cdr is a string with the value.
3493 You can set buffer-local values for the same purpose in the variable
3494 `org-file-properties' this by adding lines like
3496 #+PROPERTY: NAME VALUE"
3497 :group 'org-properties
3498 :type '(repeat
3499 (cons (string :tag "Property")
3500 (string :tag "Value"))))
3502 (defvar org-file-properties nil
3503 "List of property/value pairs that can be inherited by any entry.
3504 Valid for the current buffer.
3505 This variable is populated from #+PROPERTY lines.")
3506 (make-variable-buffer-local 'org-file-properties)
3508 (defgroup org-agenda nil
3509 "Options concerning agenda views in Org-mode."
3510 :tag "Org Agenda"
3511 :group 'org)
3513 (defvar org-category nil
3514 "Variable used by org files to set a category for agenda display.
3515 Such files should use a file variable to set it, for example
3517 # -*- mode: org; org-category: \"ELisp\"
3519 or contain a special line
3521 #+CATEGORY: ELisp
3523 If the file does not specify a category, then file's base name
3524 is used instead.")
3525 (make-variable-buffer-local 'org-category)
3526 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3528 (defcustom org-agenda-files nil
3529 "The files to be used for agenda display.
3530 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3531 \\[org-remove-file]. You can also use customize to edit the list.
3533 If an entry is a directory, all files in that directory that are matched by
3534 `org-agenda-file-regexp' will be part of the file list.
3536 If the value of the variable is not a list but a single file name, then
3537 the list of agenda files is actually stored and maintained in that file, one
3538 agenda file per line. In this file paths can be given relative to
3539 `org-directory'. Tilde expansion and environment variable substitution
3540 are also made."
3541 :group 'org-agenda
3542 :type '(choice
3543 (repeat :tag "List of files and directories" file)
3544 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3546 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3547 "Regular expression to match files for `org-agenda-files'.
3548 If any element in the list in that variable contains a directory instead
3549 of a normal file, all files in that directory that are matched by this
3550 regular expression will be included."
3551 :group 'org-agenda
3552 :type 'regexp)
3554 (defcustom org-agenda-text-search-extra-files nil
3555 "List of extra files to be searched by text search commands.
3556 These files will be search in addition to the agenda files by the
3557 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3558 Note that these files will only be searched for text search commands,
3559 not for the other agenda views like todo lists, tag searches or the weekly
3560 agenda. This variable is intended to list notes and possibly archive files
3561 that should also be searched by these two commands.
3562 In fact, if the first element in the list is the symbol `agenda-archives',
3563 than all archive files of all agenda files will be added to the search
3564 scope."
3565 :group 'org-agenda
3566 :type '(set :greedy t
3567 (const :tag "Agenda Archives" agenda-archives)
3568 (repeat :inline t (file))))
3570 (org-defvaralias 'org-agenda-multi-occur-extra-files
3571 'org-agenda-text-search-extra-files)
3573 (defcustom org-agenda-skip-unavailable-files nil
3574 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3575 A nil value means to remove them, after a query, from the list."
3576 :group 'org-agenda
3577 :type 'boolean)
3579 (defcustom org-calendar-to-agenda-key [?c]
3580 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3581 The command `org-calendar-goto-agenda' will be bound to this key. The
3582 default is the character `c' because then `c' can be used to switch back and
3583 forth between agenda and calendar."
3584 :group 'org-agenda
3585 :type 'sexp)
3587 (defcustom org-calendar-insert-diary-entry-key [?i]
3588 "The key to be installed in `calendar-mode-map' for adding diary entries.
3589 This option is irrelevant until `org-agenda-diary-file' has been configured
3590 to point to an Org-mode file. When that is the case, the command
3591 `org-agenda-diary-entry' will be bound to the key given here, by default
3592 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3593 if you want to continue doing this, you need to change this to a different
3594 key."
3595 :group 'org-agenda
3596 :type 'sexp)
3598 (defcustom org-agenda-diary-file 'diary-file
3599 "File to which to add new entries with the `i' key in agenda and calendar.
3600 When this is the symbol `diary-file', the functionality in the Emacs
3601 calendar will be used to add entries to the `diary-file'. But when this
3602 points to a file, `org-agenda-diary-entry' will be used instead."
3603 :group 'org-agenda
3604 :type '(choice
3605 (const :tag "The standard Emacs diary file" diary-file)
3606 (file :tag "Special Org file diary entries")))
3608 (eval-after-load "calendar"
3609 '(progn
3610 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3611 'org-calendar-goto-agenda)
3612 (add-hook 'calendar-mode-hook
3613 (lambda ()
3614 (unless (eq org-agenda-diary-file 'diary-file)
3615 (define-key calendar-mode-map
3616 org-calendar-insert-diary-entry-key
3617 'org-agenda-diary-entry))))))
3619 (defgroup org-latex nil
3620 "Options for embedding LaTeX code into Org-mode."
3621 :tag "Org LaTeX"
3622 :group 'org)
3624 (defcustom org-format-latex-options
3625 '(:foreground default :background default :scale 1.0
3626 :html-foreground "Black" :html-background "Transparent"
3627 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3628 "Options for creating images from LaTeX fragments.
3629 This is a property list with the following properties:
3630 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3631 `default' means use the foreground of the default face.
3632 `auto' means use the foreground from the text face.
3633 :background the background color, or \"Transparent\".
3634 `default' means use the background of the default face.
3635 `auto' means use the background from the text face.
3636 :scale a scaling factor for the size of the images, to get more pixels
3637 :html-foreground, :html-background, :html-scale
3638 the same numbers for HTML export.
3639 :matchers a list indicating which matchers should be used to
3640 find LaTeX fragments. Valid members of this list are:
3641 \"begin\" find environments
3642 \"$1\" find single characters surrounded by $.$
3643 \"$\" find math expressions surrounded by $...$
3644 \"$$\" find math expressions surrounded by $$....$$
3645 \"\\(\" find math expressions surrounded by \\(...\\)
3646 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3647 :group 'org-latex
3648 :type 'plist)
3650 (defcustom org-format-latex-signal-error t
3651 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3652 When nil, just push out a message."
3653 :group 'org-latex
3654 :version "24.1"
3655 :type 'boolean)
3657 (defcustom org-latex-to-mathml-jar-file nil
3658 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3659 Use this to specify additional executable file say a jar file.
3661 When using MathToWeb as the converter, specify the full-path to
3662 your mathtoweb.jar file."
3663 :group 'org-latex
3664 :version "24.1"
3665 :type '(choice
3666 (const :tag "None" nil)
3667 (file :tag "JAR file" :must-match t)))
3669 (defcustom org-latex-to-mathml-convert-command nil
3670 "Command to convert LaTeX fragments to MathML.
3671 Replace format-specifiers in the command as noted below and use
3672 `shell-command' to convert LaTeX to MathML.
3673 %j: Executable file in fully expanded form as specified by
3674 `org-latex-to-mathml-jar-file'.
3675 %I: Input LaTeX file in fully expanded form
3676 %o: Output MathML file
3677 This command is used by `org-create-math-formula'.
3679 When using MathToWeb as the converter, set this to
3680 \"java -jar %j -unicode -force -df %o %I\"."
3681 :group 'org-latex
3682 :version "24.1"
3683 :type '(choice
3684 (const :tag "None" nil)
3685 (string :tag "\nShell command")))
3687 (defcustom org-latex-create-formula-image-program 'dvipng
3688 "Program to convert LaTeX fragments with.
3690 dvipng Process the LaTeX fragments to dvi file, then convert
3691 dvi files to png files using dvipng.
3692 This will also include processing of non-math environments.
3693 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3694 to convert pdf files to png files"
3695 :group 'org-latex
3696 :version "24.1"
3697 :type '(choice
3698 (const :tag "dvipng" dvipng)
3699 (const :tag "imagemagick" imagemagick)))
3701 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3702 "Path to store latex preview images.
3703 A relative path here creates many directories relative to the
3704 processed org files paths. An absolute path puts all preview
3705 images at the same place."
3706 :group 'org-latex
3707 :version "24.3"
3708 :type 'string)
3710 (defun org-format-latex-mathml-available-p ()
3711 "Return t if `org-latex-to-mathml-convert-command' is usable."
3712 (save-match-data
3713 (when (and (boundp 'org-latex-to-mathml-convert-command)
3714 org-latex-to-mathml-convert-command)
3715 (let ((executable (car (split-string
3716 org-latex-to-mathml-convert-command))))
3717 (when (executable-find executable)
3718 (if (string-match
3719 "%j" org-latex-to-mathml-convert-command)
3720 (file-readable-p org-latex-to-mathml-jar-file)
3721 t))))))
3723 (defcustom org-format-latex-header "\\documentclass{article}
3724 \\usepackage[usenames]{color}
3725 \\usepackage{amsmath}
3726 \\usepackage[mathscr]{eucal}
3727 \\pagestyle{empty} % do not remove
3728 \[PACKAGES]
3729 \[DEFAULT-PACKAGES]
3730 % The settings below are copied from fullpage.sty
3731 \\setlength{\\textwidth}{\\paperwidth}
3732 \\addtolength{\\textwidth}{-3cm}
3733 \\setlength{\\oddsidemargin}{1.5cm}
3734 \\addtolength{\\oddsidemargin}{-2.54cm}
3735 \\setlength{\\evensidemargin}{\\oddsidemargin}
3736 \\setlength{\\textheight}{\\paperheight}
3737 \\addtolength{\\textheight}{-\\headheight}
3738 \\addtolength{\\textheight}{-\\headsep}
3739 \\addtolength{\\textheight}{-\\footskip}
3740 \\addtolength{\\textheight}{-3cm}
3741 \\setlength{\\topmargin}{1.5cm}
3742 \\addtolength{\\topmargin}{-2.54cm}"
3743 "The document header used for processing LaTeX fragments.
3744 It is imperative that this header make sure that no page number
3745 appears on the page. The package defined in the variables
3746 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3747 will either replace the placeholder \"[PACKAGES]\" in this
3748 header, or they will be appended."
3749 :group 'org-latex
3750 :type 'string)
3752 (defun org-set-packages-alist (var val)
3753 "Set the packages alist and make sure it has 3 elements per entry."
3754 (set var (mapcar (lambda (x)
3755 (if (and (consp x) (= (length x) 2))
3756 (list (car x) (nth 1 x) t)
3758 val)))
3760 (defun org-get-packages-alist (var)
3761 "Get the packages alist and make sure it has 3 elements per entry."
3762 (mapcar (lambda (x)
3763 (if (and (consp x) (= (length x) 2))
3764 (list (car x) (nth 1 x) t)
3766 (default-value var)))
3768 (defcustom org-latex-default-packages-alist
3769 '(("AUTO" "inputenc" t)
3770 ("T1" "fontenc" t)
3771 ("" "fixltx2e" nil)
3772 ("" "graphicx" t)
3773 ("" "longtable" nil)
3774 ("" "float" nil)
3775 ("" "wrapfig" nil)
3776 ("" "soul" t)
3777 ("" "textcomp" t)
3778 ("" "marvosym" t)
3779 ("" "wasysym" t)
3780 ("" "latexsym" t)
3781 ("" "amssymb" t)
3782 ("" "hyperref" nil)
3783 "\\tolerance=1000")
3784 "Alist of default packages to be inserted in the header.
3786 Change this only if one of the packages here causes an
3787 incompatibility with another package you are using.
3789 The packages in this list are needed by one part or another of
3790 Org mode to function properly:
3792 - inputenc, fontenc: for basic font and character selection
3793 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3794 symbols used for interpreting the entities in `org-entities'.
3795 You can skip some of these packages if you don't use any of the
3796 symbols in it.
3797 - graphicx: for including images
3798 - float, wrapfig: for figure placement
3799 - longtable: for long tables
3800 - hyperref: for cross references
3802 Therefore you should not modify this variable unless you know
3803 what you are doing. The one reason to change it anyway is that
3804 you might be loading some other package that conflicts with one
3805 of the default packages. Each cell is of the format
3806 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3807 the package also needs to be included when compiling LaTeX
3808 snippets into images for inclusion into non-LaTeX output."
3809 :group 'org-latex
3810 :group 'org-export-latex
3811 :set 'org-set-packages-alist
3812 :get 'org-get-packages-alist
3813 :version "24.1"
3814 :type '(repeat
3815 (choice
3816 (list :tag "options/package pair"
3817 (string :tag "options")
3818 (string :tag "package")
3819 (boolean :tag "Snippet"))
3820 (string :tag "A line of LaTeX"))))
3822 (defcustom org-latex-packages-alist nil
3823 "Alist of packages to be inserted in every LaTeX header.
3825 These will be inserted after `org-latex-default-packages-alist'.
3826 Each cell is of the format:
3828 \(\"options\" \"package\" snippet-flag)
3830 SNIPPET-FLAG, when t, indicates that this package is also needed
3831 when turning LaTeX snippets into images for inclusion into
3832 non-LaTeX output.
3834 Make sure that you only list packages here which:
3836 - you want in every file
3837 - do not conflict with the setup in `org-format-latex-header'.
3838 - do not conflict with the default packages in
3839 `org-latex-default-packages-alist'."
3840 :group 'org-latex
3841 :group 'org-export-latex
3842 :set 'org-set-packages-alist
3843 :get 'org-get-packages-alist
3844 :type '(repeat
3845 (choice
3846 (list :tag "options/package pair"
3847 (string :tag "options")
3848 (string :tag "package")
3849 (boolean :tag "Snippet"))
3850 (string :tag "A line of LaTeX"))))
3852 (defgroup org-appearance nil
3853 "Settings for Org-mode appearance."
3854 :tag "Org Appearance"
3855 :group 'org)
3857 (defcustom org-level-color-stars-only nil
3858 "Non-nil means fontify only the stars in each headline.
3859 When nil, the entire headline is fontified.
3860 Changing it requires restart of `font-lock-mode' to become effective
3861 also in regions already fontified."
3862 :group 'org-appearance
3863 :type 'boolean)
3865 (defcustom org-hide-leading-stars nil
3866 "Non-nil means hide the first N-1 stars in a headline.
3867 This works by using the face `org-hide' for these stars. This
3868 face is white for a light background, and black for a dark
3869 background. You may have to customize the face `org-hide' to
3870 make this work.
3871 Changing it requires restart of `font-lock-mode' to become effective
3872 also in regions already fontified.
3873 You may also set this on a per-file basis by adding one of the following
3874 lines to the buffer:
3876 #+STARTUP: hidestars
3877 #+STARTUP: showstars"
3878 :group 'org-appearance
3879 :type 'boolean)
3881 (defcustom org-hidden-keywords nil
3882 "List of symbols corresponding to keywords to be hidden the org buffer.
3883 For example, a value '(title) for this list will make the document's title
3884 appear in the buffer without the initial #+TITLE: keyword."
3885 :group 'org-appearance
3886 :version "24.1"
3887 :type '(set (const :tag "#+AUTHOR" author)
3888 (const :tag "#+DATE" date)
3889 (const :tag "#+EMAIL" email)
3890 (const :tag "#+TITLE" title)))
3892 (defcustom org-custom-properties nil
3893 "List of properties (as strings) with a special meaning.
3894 The default use of these custom properties is to let the user
3895 hide them with `org-toggle-custom-properties-visibility'."
3896 :group 'org-properties
3897 :group 'org-appearance
3898 :version "24.3"
3899 :type '(repeat (string :tag "Property Name")))
3901 (defcustom org-fontify-done-headline nil
3902 "Non-nil means change the face of a headline if it is marked DONE.
3903 Normally, only the TODO/DONE keyword indicates the state of a headline.
3904 When this is non-nil, the headline after the keyword is set to the
3905 `org-headline-done' as an additional indication."
3906 :group 'org-appearance
3907 :type 'boolean)
3909 (defcustom org-fontify-emphasized-text t
3910 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3911 Changing this variable requires a restart of Emacs to take effect."
3912 :group 'org-appearance
3913 :type 'boolean)
3915 (defcustom org-fontify-whole-heading-line nil
3916 "Non-nil means fontify the whole line for headings.
3917 This is useful when setting a background color for the
3918 org-level-* faces."
3919 :group 'org-appearance
3920 :type 'boolean)
3922 (defcustom org-highlight-latex-and-related nil
3923 "Non-nil means highlight LaTeX related syntax in the buffer.
3924 When non nil, the value should be a list containing any of the
3925 following symbols:
3926 `latex' Highlight LaTeX snippets and environments.
3927 `script' Highlight subscript and superscript.
3928 `entities' Highlight entities."
3929 :group 'org-appearance
3930 :version "24.4"
3931 :package-version '(Org . "8.0")
3932 :type '(choice
3933 (const :tag "No highlighting" nil)
3934 (set :greedy t :tag "Highlight"
3935 (const :tag "LaTeX snippets and environments" latex)
3936 (const :tag "Subscript and superscript" script)
3937 (const :tag "Entities" entities))))
3939 (defcustom org-hide-emphasis-markers nil
3940 "Non-nil mean font-lock should hide the emphasis marker characters."
3941 :group 'org-appearance
3942 :type 'boolean)
3944 (defcustom org-pretty-entities nil
3945 "Non-nil means show entities as UTF8 characters.
3946 When nil, the \\name form remains in the buffer."
3947 :group 'org-appearance
3948 :version "24.1"
3949 :type 'boolean)
3951 (defcustom org-pretty-entities-include-sub-superscripts t
3952 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3953 :group 'org-appearance
3954 :version "24.1"
3955 :type 'boolean)
3957 (defvar org-emph-re nil
3958 "Regular expression for matching emphasis.
3959 After a match, the match groups contain these elements:
3960 0 The match of the full regular expression, including the characters
3961 before and after the proper match
3962 1 The character before the proper match, or empty at beginning of line
3963 2 The proper match, including the leading and trailing markers
3964 3 The leading marker like * or /, indicating the type of highlighting
3965 4 The text between the emphasis markers, not including the markers
3966 5 The character after the match, empty at the end of a line")
3967 (defvar org-verbatim-re nil
3968 "Regular expression for matching verbatim text.")
3969 (defvar org-emphasis-regexp-components) ; defined just below
3970 (defvar org-emphasis-alist) ; defined just below
3971 (defun org-set-emph-re (var val)
3972 "Set variable and compute the emphasis regular expression."
3973 (set var val)
3974 (when (and (boundp 'org-emphasis-alist)
3975 (boundp 'org-emphasis-regexp-components)
3976 org-emphasis-alist org-emphasis-regexp-components)
3977 (let* ((e org-emphasis-regexp-components)
3978 (pre (car e))
3979 (post (nth 1 e))
3980 (border (nth 2 e))
3981 (body (nth 3 e))
3982 (nl (nth 4 e))
3983 (body1 (concat body "*?"))
3984 (markers (mapconcat 'car org-emphasis-alist ""))
3985 (vmarkers (mapconcat
3986 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3987 org-emphasis-alist "")))
3988 ;; make sure special characters appear at the right position in the class
3989 (if (string-match "\\^" markers)
3990 (setq markers (concat (replace-match "" t t markers) "^")))
3991 (if (string-match "-" markers)
3992 (setq markers (concat (replace-match "" t t markers) "-")))
3993 (if (string-match "\\^" vmarkers)
3994 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3995 (if (string-match "-" vmarkers)
3996 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3997 (if (> nl 0)
3998 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3999 (int-to-string nl) "\\}")))
4000 ;; Make the regexp
4001 (setq org-emph-re
4002 (concat "\\([" pre "]\\|^\\)"
4003 "\\("
4004 "\\([" markers "]\\)"
4005 "\\("
4006 "[^" border "]\\|"
4007 "[^" border "]"
4008 body1
4009 "[^" border "]"
4010 "\\)"
4011 "\\3\\)"
4012 "\\([" post "]\\|$\\)"))
4013 (setq org-verbatim-re
4014 (concat "\\([" pre "]\\|^\\)"
4015 "\\("
4016 "\\([" vmarkers "]\\)"
4017 "\\("
4018 "[^" border "]\\|"
4019 "[^" border "]"
4020 body1
4021 "[^" border "]"
4022 "\\)"
4023 "\\3\\)"
4024 "\\([" post "]\\|$\\)")))))
4026 (defcustom org-emphasis-regexp-components
4027 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4028 "Components used to build the regular expression for emphasis.
4029 This is a list with five entries. Terminology: In an emphasis string
4030 like \" *strong word* \", we call the initial space PREMATCH, the final
4031 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4032 and \"trong wor\" is the body. The different components in this variable
4033 specify what is allowed/forbidden in each part:
4035 pre Chars allowed as prematch. Beginning of line will be allowed too.
4036 post Chars allowed as postmatch. End of line will be allowed too.
4037 border The chars *forbidden* as border characters.
4038 body-regexp A regexp like \".\" to match a body character. Don't use
4039 non-shy groups here, and don't allow newline here.
4040 newline The maximum number of newlines allowed in an emphasis exp.
4042 Use customize to modify this, or restart Emacs after changing it."
4043 :group 'org-appearance
4044 :set 'org-set-emph-re
4045 :type '(list
4046 (sexp :tag "Allowed chars in pre ")
4047 (sexp :tag "Allowed chars in post ")
4048 (sexp :tag "Forbidden chars in border ")
4049 (sexp :tag "Regexp for body ")
4050 (integer :tag "number of newlines allowed")
4051 (option (boolean :tag "Please ignore this button"))))
4053 (defcustom org-emphasis-alist
4054 `(("*" bold "<b>" "</b>")
4055 ("/" italic "<i>" "</i>")
4056 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
4057 ("=" org-code "<code>" "</code>" verbatim)
4058 ("~" org-verbatim "<code>" "</code>" verbatim)
4059 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
4060 "<del>" "</del>")
4062 "Special syntax for emphasized text.
4063 Text starting and ending with a special character will be emphasized, for
4064 example *bold*, _underlined_ and /italic/. This variable sets the marker
4065 characters, the face to be used by font-lock for highlighting in Org-mode
4066 Emacs buffers, and the HTML tags to be used for this.
4067 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
4068 Use customize to modify this, or restart Emacs after changing it."
4069 :group 'org-appearance
4070 :set 'org-set-emph-re
4071 :type '(repeat
4072 (list
4073 (string :tag "Marker character")
4074 (choice
4075 (face :tag "Font-lock-face")
4076 (plist :tag "Face property list"))
4077 (string :tag "HTML start tag")
4078 (string :tag "HTML end tag")
4079 (option (const verbatim)))))
4081 (defvar org-protecting-blocks
4082 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4083 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4084 This is needed for font-lock setup.")
4086 ;;; Miscellaneous options
4088 (defgroup org-completion nil
4089 "Completion in Org-mode."
4090 :tag "Org Completion"
4091 :group 'org)
4093 (defcustom org-completion-use-ido nil
4094 "Non-nil means use ido completion wherever possible.
4095 Note that `ido-mode' must be active for this variable to be relevant.
4096 If you decide to turn this variable on, you might well want to turn off
4097 `org-outline-path-complete-in-steps'.
4098 See also `org-completion-use-iswitchb'."
4099 :group 'org-completion
4100 :type 'boolean)
4102 (defcustom org-completion-use-iswitchb nil
4103 "Non-nil means use iswitchb completion wherever possible.
4104 Note that `iswitchb-mode' must be active for this variable to be relevant.
4105 If you decide to turn this variable on, you might well want to turn off
4106 `org-outline-path-complete-in-steps'.
4107 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4108 :group 'org-completion
4109 :type 'boolean)
4111 (defcustom org-completion-fallback-command 'hippie-expand
4112 "The expansion command called by \\[pcomplete] in normal context.
4113 Normal means, no org-mode-specific context."
4114 :group 'org-completion
4115 :type 'function)
4117 ;;; Functions and variables from their packages
4118 ;; Declared here to avoid compiler warnings
4120 ;; XEmacs only
4121 (defvar outline-mode-menu-heading)
4122 (defvar outline-mode-menu-show)
4123 (defvar outline-mode-menu-hide)
4124 (defvar zmacs-regions) ; XEmacs regions
4126 ;; Emacs only
4127 (defvar mark-active)
4129 ;; Various packages
4130 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4131 (declare-function calendar-forward-day "cal-move" (arg))
4132 (declare-function calendar-goto-date "cal-move" (date))
4133 (declare-function calendar-goto-today "cal-move" ())
4134 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4135 (defvar calc-embedded-close-formula)
4136 (defvar calc-embedded-open-formula)
4137 (declare-function cdlatex-tab "ext:cdlatex" ())
4138 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4139 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4140 (defvar font-lock-unfontify-region-function)
4141 (declare-function iswitchb-read-buffer "iswitchb"
4142 (prompt &optional default require-match start matches-set))
4143 (defvar iswitchb-temp-buflist)
4144 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4145 (defvar org-agenda-tags-todo-honor-ignore-options)
4146 (declare-function org-agenda-skip "org-agenda" ())
4147 (declare-function
4148 org-agenda-format-item "org-agenda"
4149 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4150 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4151 (declare-function org-agenda-change-all-lines "org-agenda"
4152 (newhead hdmarker &optional fixface just-this))
4153 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4154 (declare-function org-agenda-maybe-redo "org-agenda" ())
4155 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4156 (beg end))
4157 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4158 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4159 "org-agenda" (&optional end))
4160 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4161 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4162 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4163 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4164 (declare-function org-indent-mode "org-indent" (&optional arg))
4165 (declare-function parse-time-string "parse-time" (string))
4166 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4167 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4168 (defvar remember-data-file)
4169 (defvar texmathp-why)
4170 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4171 (declare-function table--at-cell-p "table" (position &optional object at-column))
4173 (defvar org-latex-regexps)
4175 ;;; Autoload and prepare some org modules
4177 ;; Some table stuff that needs to be defined here, because it is used
4178 ;; by the functions setting up org-mode or checking for table context.
4180 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4181 "Detect an org-type or table-type table.")
4182 (defconst org-table-line-regexp "^[ \t]*|"
4183 "Detect an org-type table line.")
4184 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4185 "Detect an org-type table line.")
4186 (defconst org-table-hline-regexp "^[ \t]*|-"
4187 "Detect an org-type table hline.")
4188 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4189 "Detect a table-type table hline.")
4190 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4191 "Detect the first line outside a table when searching from within it.
4192 This works for both table types.")
4194 ;; Autoload the functions in org-table.el that are needed by functions here.
4196 (eval-and-compile
4197 (org-autoload "org-table"
4198 '(org-table-begin org-table-blank-field org-table-end)))
4200 ;;;###autoload
4201 (defun turn-on-orgtbl ()
4202 "Unconditionally turn on `orgtbl-mode'."
4203 (require 'org-table)
4204 (orgtbl-mode 1))
4206 (defun org-at-table-p (&optional table-type)
4207 "Return t if the cursor is inside an org-type table.
4208 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4209 (if org-enable-table-editor
4210 (save-excursion
4211 (beginning-of-line 1)
4212 (looking-at (if table-type org-table-any-line-regexp
4213 org-table-line-regexp)))
4214 nil))
4215 (defsubst org-table-p () (org-at-table-p))
4217 (defun org-at-table.el-p ()
4218 "Return t if and only if we are at a table.el table."
4219 (and (org-at-table-p 'any)
4220 (save-excursion
4221 (goto-char (org-table-begin 'any))
4222 (looking-at org-table1-hline-regexp))))
4224 (defun org-table-recognize-table.el ()
4225 "If there is a table.el table nearby, recognize it and move into it."
4226 (if org-table-tab-recognizes-table.el
4227 (if (org-at-table.el-p)
4228 (progn
4229 (beginning-of-line 1)
4230 (if (looking-at org-table-dataline-regexp)
4232 (if (looking-at org-table1-hline-regexp)
4233 (progn
4234 (beginning-of-line 2)
4235 (if (looking-at org-table-any-border-regexp)
4236 (beginning-of-line -1)))))
4237 (if (re-search-forward "|" (org-table-end t) t)
4238 (progn
4239 (require 'table)
4240 (if (table--at-cell-p (point))
4242 (message "recognizing table.el table...")
4243 (table-recognize-table)
4244 (message "recognizing table.el table...done")))
4245 (error "This should not happen"))
4247 nil)
4248 nil))
4250 (defun org-at-table-hline-p ()
4251 "Return t if the cursor is inside a hline in a table."
4252 (if org-enable-table-editor
4253 (save-excursion
4254 (beginning-of-line 1)
4255 (looking-at org-table-hline-regexp))
4256 nil))
4258 (defvar org-table-clean-did-remove-column nil)
4259 (defun org-table-map-tables (function &optional quietly)
4260 "Apply FUNCTION to the start of all tables in the buffer."
4261 (save-excursion
4262 (save-restriction
4263 (widen)
4264 (goto-char (point-min))
4265 (while (re-search-forward org-table-any-line-regexp nil t)
4266 (unless quietly
4267 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4268 (beginning-of-line 1)
4269 (when (and (looking-at org-table-line-regexp)
4270 ;; Exclude tables in src/example/verbatim/clocktable blocks
4271 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4272 (save-excursion (funcall function))
4273 (or (looking-at org-table-line-regexp)
4274 (forward-char 1)))
4275 (re-search-forward org-table-any-border-regexp nil 1))))
4276 (unless quietly (message "Mapping tables: done")))
4278 ;; Declare and autoload functions from ox.el and al.
4280 (declare-function org-export-get-environment "ox"
4281 (&optional backend subtreep ext-plist))
4282 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4284 ;; Declare and autoload functions from org-agenda.el
4286 (eval-and-compile
4287 (org-autoload "org-agenda"
4288 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4290 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4291 (declare-function org-clock-update-mode-line "org-clock" ())
4292 (declare-function org-resolve-clocks "org-clock"
4293 (&optional also-non-dangling-p prompt last-valid))
4294 (defvar org-clock-start-time)
4295 (defvar org-clock-marker (make-marker)
4296 "Marker recording the last clock-in.")
4297 (defvar org-clock-hd-marker (make-marker)
4298 "Marker recording the last clock-in, but the headline position.")
4299 (defvar org-clock-heading ""
4300 "The heading of the current clock entry.")
4301 (defun org-clock-is-active ()
4302 "Return non-nil if clock is currently running.
4303 The return value is actually the clock marker."
4304 (marker-buffer org-clock-marker))
4306 (eval-and-compile
4307 (org-autoload "org-clock" '(org-clock-remove-overlays
4308 org-clock-update-time-maybe
4309 org-clocktable-shift)))
4311 (defun org-check-running-clock ()
4312 "Check if the current buffer contains the running clock.
4313 If yes, offer to stop it and to save the buffer with the changes."
4314 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4315 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4316 (buffer-name))))
4317 (org-clock-out)
4318 (when (y-or-n-p "Save changed buffer?")
4319 (save-buffer))))
4321 (defun org-clocktable-try-shift (dir n)
4322 "Check if this line starts a clock table, if yes, shift the time block."
4323 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4324 (org-clocktable-shift dir n)))
4326 ;;;###autoload
4327 (defun org-clock-persistence-insinuate ()
4328 "Set up hooks for clock persistence."
4329 (require 'org-clock)
4330 (add-hook 'org-mode-hook 'org-clock-load)
4331 (add-hook 'kill-emacs-hook 'org-clock-save))
4333 ;; Define the variable already here, to make sure we have it.
4334 (defvar org-indent-mode nil
4335 "Non-nil if Org-Indent mode is enabled.
4336 Use the command `org-indent-mode' to change this variable.")
4338 ;; Autoload archiving code
4339 ;; The stuff that is needed for cycling and tags has to be defined here.
4341 (defgroup org-archive nil
4342 "Options concerning archiving in Org-mode."
4343 :tag "Org Archive"
4344 :group 'org-structure)
4346 (defcustom org-archive-location "%s_archive::"
4347 "The location where subtrees should be archived.
4349 The value of this variable is a string, consisting of two parts,
4350 separated by a double-colon. The first part is a filename and
4351 the second part is a headline.
4353 When the filename is omitted, archiving happens in the same file.
4354 %s in the filename will be replaced by the current file
4355 name (without the directory part). Archiving to a different file
4356 is useful to keep archived entries from contributing to the
4357 Org-mode Agenda.
4359 The archived entries will be filed as subtrees of the specified
4360 headline. When the headline is omitted, the subtrees are simply
4361 filed away at the end of the file, as top-level entries. Also in
4362 the heading you can use %s to represent the file name, this can be
4363 useful when using the same archive for a number of different files.
4365 Here are a few examples:
4366 \"%s_archive::\"
4367 If the current file is Projects.org, archive in file
4368 Projects.org_archive, as top-level trees. This is the default.
4370 \"::* Archived Tasks\"
4371 Archive in the current file, under the top-level headline
4372 \"* Archived Tasks\".
4374 \"~/org/archive.org::\"
4375 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4377 \"~/org/archive.org::* From %s\"
4378 Archive in file ~/org/archive.org (absolute path), under headlines
4379 \"From FILENAME\" where file name is the current file name.
4381 \"~/org/datetree.org::datetree/* Finished Tasks\"
4382 The \"datetree/\" string is special, signifying to archive
4383 items to the datetree. Items are placed in either the CLOSED
4384 date of the item, or the current date if there is no CLOSED date.
4385 The heading will be a subentry to the current date. There doesn't
4386 need to be a heading, but there always needs to be a slash after
4387 datetree. For example, to store archived items directly in the
4388 datetree, use \"~/org/datetree.org::datetree/\".
4390 \"basement::** Finished Tasks\"
4391 Archive in file ./basement (relative path), as level 3 trees
4392 below the level 2 heading \"** Finished Tasks\".
4394 You may set this option on a per-file basis by adding to the buffer a
4395 line like
4397 #+ARCHIVE: basement::** Finished Tasks
4399 You may also define it locally for a subtree by setting an ARCHIVE property
4400 in the entry. If such a property is found in an entry, or anywhere up
4401 the hierarchy, it will be used."
4402 :group 'org-archive
4403 :type 'string)
4405 (defcustom org-archive-tag "ARCHIVE"
4406 "The tag that marks a subtree as archived.
4407 An archived subtree does not open during visibility cycling, and does
4408 not contribute to the agenda listings.
4409 After changing this, font-lock must be restarted in the relevant buffers to
4410 get the proper fontification."
4411 :group 'org-archive
4412 :group 'org-keywords
4413 :type 'string)
4415 (defcustom org-agenda-skip-archived-trees t
4416 "Non-nil means the agenda will skip any items located in archived trees.
4417 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4418 variable is no longer recommended, you should leave it at the value t.
4419 Instead, use the key `v' to cycle the archives-mode in the agenda."
4420 :group 'org-archive
4421 :group 'org-agenda-skip
4422 :type 'boolean)
4424 (defcustom org-columns-skip-archived-trees t
4425 "Non-nil means ignore archived trees when creating column view."
4426 :group 'org-archive
4427 :group 'org-properties
4428 :type 'boolean)
4430 (defcustom org-cycle-open-archived-trees nil
4431 "Non-nil means `org-cycle' will open archived trees.
4432 An archived tree is a tree marked with the tag ARCHIVE.
4433 When nil, archived trees will stay folded. You can still open them with
4434 normal outline commands like `show-all', but not with the cycling commands."
4435 :group 'org-archive
4436 :group 'org-cycle
4437 :type 'boolean)
4439 (defcustom org-sparse-tree-open-archived-trees nil
4440 "Non-nil means sparse tree construction shows matches in archived trees.
4441 When nil, matches in these trees are highlighted, but the trees are kept in
4442 collapsed state."
4443 :group 'org-archive
4444 :group 'org-sparse-trees
4445 :type 'boolean)
4447 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4448 "The default date type when building a sparse tree.
4449 When this is nil, a date is a scheduled or a deadline timestamp.
4450 Otherwise, these types are allowed:
4452 all: all timestamps
4453 active: only active timestamps (<...>)
4454 inactive: only inactive timestamps (<...)
4455 scheduled: only scheduled timestamps
4456 deadline: only deadline timestamps"
4457 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4458 (const :tag "All timestamps" all)
4459 (const :tag "Only active timestamps" active)
4460 (const :tag "Only inactive timestamps" inactive)
4461 (const :tag "Only scheduled timestamps" scheduled)
4462 (const :tag "Only deadline timestamps" deadline))
4463 :version "24.3"
4464 :group 'org-sparse-trees)
4466 (defun org-cycle-hide-archived-subtrees (state)
4467 "Re-hide all archived subtrees after a visibility state change."
4468 (when (and (not org-cycle-open-archived-trees)
4469 (not (memq state '(overview folded))))
4470 (save-excursion
4471 (let* ((globalp (memq state '(contents all)))
4472 (beg (if globalp (point-min) (point)))
4473 (end (if globalp (point-max) (org-end-of-subtree t))))
4474 (org-hide-archived-subtrees beg end)
4475 (goto-char beg)
4476 (if (looking-at (concat ".*:" org-archive-tag ":"))
4477 (message "%s" (substitute-command-keys
4478 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4480 (defun org-force-cycle-archived ()
4481 "Cycle subtree even if it is archived."
4482 (interactive)
4483 (setq this-command 'org-cycle)
4484 (let ((org-cycle-open-archived-trees t))
4485 (call-interactively 'org-cycle)))
4487 (defun org-hide-archived-subtrees (beg end)
4488 "Re-hide all archived subtrees after a visibility state change."
4489 (save-excursion
4490 (let* ((re (concat ":" org-archive-tag ":")))
4491 (goto-char beg)
4492 (while (re-search-forward re end t)
4493 (when (org-at-heading-p)
4494 (org-flag-subtree t)
4495 (org-end-of-subtree t))))))
4497 (declare-function outline-end-of-heading "outline" ())
4498 (declare-function outline-flag-region "outline" (from to flag))
4499 (defun org-flag-subtree (flag)
4500 (save-excursion
4501 (org-back-to-heading t)
4502 (outline-end-of-heading)
4503 (outline-flag-region (point)
4504 (progn (org-end-of-subtree t) (point))
4505 flag)))
4507 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4509 (eval-and-compile
4510 (org-autoload "org-archive"
4511 '(org-add-archive-files)))
4513 ;; Autoload Column View Code
4515 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4516 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4517 (declare-function org-columns-compute "org-colview" (property))
4519 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4520 '(org-columns-number-to-string
4521 org-columns-get-format-and-top-level
4522 org-columns-compute
4523 org-columns-remove-overlays))
4525 ;; Autoload ID code
4527 (declare-function org-id-store-link "org-id")
4528 (declare-function org-id-locations-load "org-id")
4529 (declare-function org-id-locations-save "org-id")
4530 (defvar org-id-track-globally)
4531 (org-autoload "org-id"
4532 '(org-id-new
4533 org-id-copy
4534 org-id-get-with-outline-path-completion
4535 org-id-get-with-outline-drilling))
4537 ;;; Variables for pre-computed regular expressions, all buffer local
4539 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4540 "Matches first line of a hidden block.")
4541 (make-variable-buffer-local 'org-drawer-regexp)
4542 (defvar org-todo-regexp nil
4543 "Matches any of the TODO state keywords.")
4544 (make-variable-buffer-local 'org-todo-regexp)
4545 (defvar org-not-done-regexp nil
4546 "Matches any of the TODO state keywords except the last one.")
4547 (make-variable-buffer-local 'org-not-done-regexp)
4548 (defvar org-not-done-heading-regexp nil
4549 "Matches a TODO headline that is not done.")
4550 (make-variable-buffer-local 'org-not-done-regexp)
4551 (defvar org-todo-line-regexp nil
4552 "Matches a headline and puts TODO state into group 2 if present.")
4553 (make-variable-buffer-local 'org-todo-line-regexp)
4554 (defvar org-complex-heading-regexp nil
4555 "Matches a headline and puts everything into groups:
4556 group 1: the stars
4557 group 2: The todo keyword, maybe
4558 group 3: Priority cookie
4559 group 4: True headline
4560 group 5: Tags")
4561 (make-variable-buffer-local 'org-complex-heading-regexp)
4562 (defvar org-complex-heading-regexp-format nil
4563 "Printf format to make regexp to match an exact headline.
4564 This regexp will match the headline of any node which has the
4565 exact headline text that is put into the format, but may have any
4566 TODO state, priority and tags.")
4567 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4568 (defvar org-todo-line-tags-regexp nil
4569 "Matches a headline and puts TODO state into group 2 if present.
4570 Also put tags into group 4 if tags are present.")
4571 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4572 (defvar org-ds-keyword-length 12
4573 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4574 (make-variable-buffer-local 'org-ds-keyword-length)
4575 (defvar org-deadline-regexp nil
4576 "Matches the DEADLINE keyword.")
4577 (make-variable-buffer-local 'org-deadline-regexp)
4578 (defvar org-deadline-time-regexp nil
4579 "Matches the DEADLINE keyword together with a time stamp.")
4580 (make-variable-buffer-local 'org-deadline-time-regexp)
4581 (defvar org-deadline-time-hour-regexp nil
4582 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4583 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4584 (defvar org-deadline-line-regexp nil
4585 "Matches the DEADLINE keyword and the rest of the line.")
4586 (make-variable-buffer-local 'org-deadline-line-regexp)
4587 (defvar org-scheduled-regexp nil
4588 "Matches the SCHEDULED keyword.")
4589 (make-variable-buffer-local 'org-scheduled-regexp)
4590 (defvar org-scheduled-time-regexp nil
4591 "Matches the SCHEDULED keyword together with a time stamp.")
4592 (make-variable-buffer-local 'org-scheduled-time-regexp)
4593 (defvar org-scheduled-time-hour-regexp nil
4594 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4595 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4596 (defvar org-closed-time-regexp nil
4597 "Matches the CLOSED keyword together with a time stamp.")
4598 (make-variable-buffer-local 'org-closed-time-regexp)
4600 (defvar org-keyword-time-regexp nil
4601 "Matches any of the 4 keywords, together with the time stamp.")
4602 (make-variable-buffer-local 'org-keyword-time-regexp)
4603 (defvar org-keyword-time-not-clock-regexp nil
4604 "Matches any of the 3 keywords, together with the time stamp.")
4605 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4606 (defvar org-maybe-keyword-time-regexp nil
4607 "Matches a timestamp, possibly preceded by a keyword.")
4608 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4609 (defvar org-all-time-keywords nil
4610 "List of time keywords.")
4611 (make-variable-buffer-local 'org-all-time-keywords)
4613 (defconst org-plain-time-of-day-regexp
4614 (concat
4615 "\\(\\<[012]?[0-9]"
4616 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4617 "\\(--?"
4618 "\\(\\<[012]?[0-9]"
4619 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4620 "\\)?")
4621 "Regular expression to match a plain time or time range.
4622 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4623 groups carry important information:
4624 0 the full match
4625 1 the first time, range or not
4626 8 the second time, if it is a range.")
4628 (defconst org-plain-time-extension-regexp
4629 (concat
4630 "\\(\\<[012]?[0-9]"
4631 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4632 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4633 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4634 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4635 groups carry important information:
4636 0 the full match
4637 7 hours of duration
4638 9 minutes of duration")
4640 (defconst org-stamp-time-of-day-regexp
4641 (concat
4642 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4643 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4644 "\\(--?"
4645 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4646 "Regular expression to match a timestamp time or time range.
4647 After a match, the following groups carry important information:
4648 0 the full match
4649 1 date plus weekday, for back referencing to make sure both times are on the same day
4650 2 the first time, range or not
4651 4 the second time, if it is a range.")
4653 (defconst org-startup-options
4654 '(("fold" org-startup-folded t)
4655 ("overview" org-startup-folded t)
4656 ("nofold" org-startup-folded nil)
4657 ("showall" org-startup-folded nil)
4658 ("showeverything" org-startup-folded showeverything)
4659 ("content" org-startup-folded content)
4660 ("indent" org-startup-indented t)
4661 ("noindent" org-startup-indented nil)
4662 ("hidestars" org-hide-leading-stars t)
4663 ("showstars" org-hide-leading-stars nil)
4664 ("odd" org-odd-levels-only t)
4665 ("oddeven" org-odd-levels-only nil)
4666 ("align" org-startup-align-all-tables t)
4667 ("noalign" org-startup-align-all-tables nil)
4668 ("inlineimages" org-startup-with-inline-images t)
4669 ("noinlineimages" org-startup-with-inline-images nil)
4670 ("latexpreview" org-startup-with-latex-preview t)
4671 ("nolatexpreview" org-startup-with-latex-preview nil)
4672 ("customtime" org-display-custom-times t)
4673 ("logdone" org-log-done time)
4674 ("lognotedone" org-log-done note)
4675 ("nologdone" org-log-done nil)
4676 ("lognoteclock-out" org-log-note-clock-out t)
4677 ("nolognoteclock-out" org-log-note-clock-out nil)
4678 ("logrepeat" org-log-repeat state)
4679 ("lognoterepeat" org-log-repeat note)
4680 ("logdrawer" org-log-into-drawer t)
4681 ("nologdrawer" org-log-into-drawer nil)
4682 ("logstatesreversed" org-log-states-order-reversed t)
4683 ("nologstatesreversed" org-log-states-order-reversed nil)
4684 ("nologrepeat" org-log-repeat nil)
4685 ("logreschedule" org-log-reschedule time)
4686 ("lognotereschedule" org-log-reschedule note)
4687 ("nologreschedule" org-log-reschedule nil)
4688 ("logredeadline" org-log-redeadline time)
4689 ("lognoteredeadline" org-log-redeadline note)
4690 ("nologredeadline" org-log-redeadline nil)
4691 ("logrefile" org-log-refile time)
4692 ("lognoterefile" org-log-refile note)
4693 ("nologrefile" org-log-refile nil)
4694 ("fninline" org-footnote-define-inline t)
4695 ("nofninline" org-footnote-define-inline nil)
4696 ("fnlocal" org-footnote-section nil)
4697 ("fnauto" org-footnote-auto-label t)
4698 ("fnprompt" org-footnote-auto-label nil)
4699 ("fnconfirm" org-footnote-auto-label confirm)
4700 ("fnplain" org-footnote-auto-label plain)
4701 ("fnadjust" org-footnote-auto-adjust t)
4702 ("nofnadjust" org-footnote-auto-adjust nil)
4703 ("constcgs" constants-unit-system cgs)
4704 ("constSI" constants-unit-system SI)
4705 ("noptag" org-tag-persistent-alist nil)
4706 ("hideblocks" org-hide-block-startup t)
4707 ("nohideblocks" org-hide-block-startup nil)
4708 ("beamer" org-startup-with-beamer-mode t)
4709 ("entitiespretty" org-pretty-entities t)
4710 ("entitiesplain" org-pretty-entities nil))
4711 "Variable associated with STARTUP options for org-mode.
4712 Each element is a list of three items: the startup options (as written
4713 in the #+STARTUP line), the corresponding variable, and the value to set
4714 this variable to if the option is found. An optional forth element PUSH
4715 means to push this value onto the list in the variable.")
4717 (defun org-update-property-plist (key val props)
4718 "Update PROPS with KEY and VAL."
4719 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4720 (key (if appending (substring key 0 (- (length key) 1)) key))
4721 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4722 (previous (cdr (assoc key props))))
4723 (if appending
4724 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4725 (cons (cons key val) remainder))))
4727 (defconst org-block-regexp
4728 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4729 "Regular expression for hiding blocks.")
4730 (defconst org-heading-keyword-regexp-format
4731 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4732 "Printf format for a regexp matching a headline with some keyword.
4733 This regexp will match the headline of any node which has the
4734 exact keyword that is put into the format. The keyword isn't in
4735 any group by default, but the stars and the body are.")
4736 (defconst org-heading-keyword-maybe-regexp-format
4737 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4738 "Printf format for a regexp matching a headline, possibly with some keyword.
4739 This regexp can match any headline with the specified keyword, or
4740 without a keyword. The keyword isn't in any group by default,
4741 but the stars and the body are.")
4743 (defcustom org-group-tags t
4744 "When non-nil (the default), use group tags.
4745 This can be turned on/off through `org-toggle-tags-groups'."
4746 :group 'org-tags
4747 :group 'org-startup
4748 :type 'boolean)
4750 (defun org-toggle-tags-groups ()
4751 "Toggle support for group tags.
4752 Support for group tags is controlled by the option
4753 `org-group-tags', which is non-nil by default."
4754 (interactive)
4755 (setq org-group-tags (not org-group-tags))
4756 (cond ((and (derived-mode-p 'org-agenda-mode)
4757 org-group-tags)
4758 (org-agenda-redo))
4759 ((derived-mode-p 'org-mode)
4760 (let ((org-inhibit-startup t)) (org-mode))))
4761 (message "Groups tags support has been turned %s"
4762 (if org-group-tags "on" "off")))
4764 (defun org-set-regexps-and-options-for-tags ()
4765 "Precompute regular expressions used for tags in the current buffer."
4766 (when (derived-mode-p 'org-mode)
4767 (org-set-local 'org-file-tags nil)
4768 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4769 (splitre "[ \t]+")
4770 tags ftags key value
4771 (start 0))
4772 (save-excursion
4773 (save-restriction
4774 (widen)
4775 (goto-char (point-min))
4776 (while (re-search-forward re nil t)
4777 (setq key (upcase (org-match-string-no-properties 1))
4778 value (org-match-string-no-properties 2))
4779 (if (stringp value) (setq value (org-trim value)))
4780 (cond
4781 ((equal key "TAGS")
4782 (setq tags (append tags (if tags '("\\n") nil)
4783 (org-split-string value splitre))))
4784 ((equal key "FILETAGS")
4785 (when (string-match "\\S-" value)
4786 (setq ftags
4787 (append
4788 ftags
4789 (apply 'append
4790 (mapcar (lambda (x) (org-split-string x ":"))
4791 (org-split-string value)))))))))))
4792 ;; Process the file tags.
4793 (and ftags (org-set-local 'org-file-tags
4794 (mapcar 'org-add-prop-inherited ftags)))
4795 (org-set-local 'org-tag-groups-alist nil)
4796 ;; Process the tags.
4797 ;; FIXME
4798 (when tags
4799 (let (e tgs g)
4800 (while (setq e (pop tags))
4801 (cond
4802 ((equal e "{")
4803 (progn (push '(:startgroup) tgs)
4804 (when (equal (nth 1 tags) ":")
4805 (push (list (replace-regexp-in-string
4806 "(.+)$" "" (nth 0 tags)))
4807 org-tag-groups-alist)
4808 (setq g 0))))
4809 ((equal e ":") (push '(:grouptags) tgs))
4810 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4811 ((equal e "\\n") (push '(:newline) tgs))
4812 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4813 (push (cons (match-string 1 e)
4814 (string-to-char (match-string 2 e))) tgs)
4815 (if (and g (> g 0))
4816 (setcar org-tag-groups-alist
4817 (append (car org-tag-groups-alist)
4818 (list (match-string 1 e)))))
4819 (if g (setq g (1+ g))))
4820 (t (push (list e) tgs)
4821 (if (and g (> g 0))
4822 (setcar org-tag-groups-alist
4823 (append (car org-tag-groups-alist) (list e))))
4824 (if g (setq g (1+ g))))))
4825 (org-set-local 'org-tag-alist nil)
4826 (while (setq e (pop tgs))
4827 (or (and (stringp (car e))
4828 (assoc (car e) org-tag-alist))
4829 (push e org-tag-alist))))))))
4831 (defun org-set-regexps-and-options ()
4832 "Precompute regular expressions used in the current buffer."
4833 (when (derived-mode-p 'org-mode)
4834 (org-set-local 'org-todo-kwd-alist nil)
4835 (org-set-local 'org-todo-key-alist nil)
4836 (org-set-local 'org-todo-key-trigger nil)
4837 (org-set-local 'org-todo-keywords-1 nil)
4838 (org-set-local 'org-done-keywords nil)
4839 (org-set-local 'org-todo-heads nil)
4840 (org-set-local 'org-todo-sets nil)
4841 (org-set-local 'org-todo-log-states nil)
4842 (org-set-local 'org-file-properties nil)
4843 (let ((re (org-make-options-regexp
4844 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4845 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4846 "SETUPFILE" "OPTIONS")
4847 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4848 (splitre "[ \t]+")
4849 (scripts org-use-sub-superscripts)
4850 kwds kws0 kwsa key log value cat arch const links hw dws
4851 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4852 (start 0))
4853 (save-excursion
4854 (save-restriction
4855 (widen)
4856 (goto-char (point-min))
4857 (while (or (and ext-setup-or-nil
4858 (string-match re ext-setup-or-nil start)
4859 (setq start (match-end 0)))
4860 (and (setq ext-setup-or-nil nil start 0)
4861 (re-search-forward re nil t)))
4862 (setq key (upcase (match-string 1 ext-setup-or-nil))
4863 value (org-match-string-no-properties 2 ext-setup-or-nil))
4864 (if (stringp value) (setq value (org-trim value)))
4865 (cond
4866 ((equal key "CATEGORY")
4867 (setq cat value))
4868 ((member key '("SEQ_TODO" "TODO"))
4869 (push (cons 'sequence (org-split-string value splitre)) kwds))
4870 ((equal key "TYP_TODO")
4871 (push (cons 'type (org-split-string value splitre)) kwds))
4872 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4873 ;; general TODO-like setup
4874 (push (cons (intern (downcase (match-string 1 key)))
4875 (org-split-string value splitre)) kwds))
4876 ((equal key "COLUMNS")
4877 (org-set-local 'org-columns-default-format value))
4878 ((equal key "LINK")
4879 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4880 (push (cons (match-string 1 value)
4881 (org-trim (match-string 2 value)))
4882 links)))
4883 ((equal key "PRIORITIES")
4884 (setq prio (org-split-string value " +")))
4885 ((equal key "PROPERTY")
4886 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4887 (setq props (org-update-property-plist (match-string 1 value)
4888 (match-string 2 value)
4889 props))))
4890 ((equal key "DRAWERS")
4891 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4892 ((equal key "CONSTANTS")
4893 (org-table-set-constants))
4894 ((equal key "STARTUP")
4895 (let ((opts (org-split-string value splitre))
4896 l var val)
4897 (while (setq l (pop opts))
4898 (when (setq l (assoc l org-startup-options))
4899 (setq var (nth 1 l) val (nth 2 l))
4900 (if (not (nth 3 l))
4901 (set (make-local-variable var) val)
4902 (if (not (listp (symbol-value var)))
4903 (set (make-local-variable var) nil))
4904 (set (make-local-variable var) (symbol-value var))
4905 (add-to-list var val))))))
4906 ((equal key "ARCHIVE")
4907 (setq arch value)
4908 (remove-text-properties 0 (length arch)
4909 '(face t fontified t) arch))
4910 ((equal key "OPTIONS")
4911 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4912 (setq scripts (read (match-string 2 value)))))
4913 ((and (equal key "SETUPFILE")
4914 ;; Prevent checking in Gnus messages
4915 (not buffer-read-only))
4916 (setq setup-contents (org-file-contents
4917 (expand-file-name
4918 (org-remove-double-quotes value))
4919 'noerror))
4920 (if (not ext-setup-or-nil)
4921 (setq ext-setup-or-nil setup-contents start 0)
4922 (setq ext-setup-or-nil
4923 (concat (substring ext-setup-or-nil 0 start)
4924 "\n" setup-contents "\n"
4925 (substring ext-setup-or-nil start)))))))
4926 ;; search for property blocks
4927 (goto-char (point-min))
4928 (while (re-search-forward org-block-regexp nil t)
4929 (when (equal "PROPERTY" (upcase (match-string 1)))
4930 (setq value (replace-regexp-in-string
4931 "[\n\r]" " " (match-string 4)))
4932 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4933 (setq props (org-update-property-plist (match-string 1 value)
4934 (match-string 2 value)
4935 props)))))))
4936 (org-set-local 'org-use-sub-superscripts scripts)
4937 (when cat
4938 (org-set-local 'org-category (intern cat))
4939 (push (cons "CATEGORY" cat) props))
4940 (when prio
4941 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4942 (setq prio (mapcar 'string-to-char prio))
4943 (org-set-local 'org-highest-priority (nth 0 prio))
4944 (org-set-local 'org-lowest-priority (nth 1 prio))
4945 (org-set-local 'org-default-priority (nth 2 prio)))
4946 (and props (org-set-local 'org-file-properties (nreverse props)))
4947 (and drawers (org-set-local 'org-drawers drawers))
4948 (and arch (org-set-local 'org-archive-location arch))
4949 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4950 ;; Process the TODO keywords
4951 (unless kwds
4952 ;; Use the global values as if they had been given locally.
4953 (setq kwds (default-value 'org-todo-keywords))
4954 (if (stringp (car kwds))
4955 (setq kwds (list (cons org-todo-interpretation
4956 (default-value 'org-todo-keywords)))))
4957 (setq kwds (reverse kwds)))
4958 (setq kwds (nreverse kwds))
4959 (let (inter kws kw)
4960 (while (setq kws (pop kwds))
4961 (let ((kws (or
4962 (run-hook-with-args-until-success
4963 'org-todo-setup-filter-hook kws)
4964 kws)))
4965 (setq inter (pop kws) sep (member "|" kws)
4966 kws0 (delete "|" (copy-sequence kws))
4967 kwsa nil
4968 kws1 (mapcar
4969 (lambda (x)
4970 ;; 1 2
4971 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4972 (progn
4973 (setq kw (match-string 1 x)
4974 key (and (match-end 2) (match-string 2 x))
4975 log (org-extract-log-state-settings x))
4976 (push (cons kw (and key (string-to-char key))) kwsa)
4977 (and log (push log org-todo-log-states))
4979 (error "Invalid TODO keyword %s" x)))
4980 kws0)
4981 kwsa (if kwsa (append '((:startgroup))
4982 (nreverse kwsa)
4983 '((:endgroup))))
4984 hw (car kws1)
4985 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4986 tail (list inter hw (car dws) (org-last dws))))
4987 (add-to-list 'org-todo-heads hw 'append)
4988 (push kws1 org-todo-sets)
4989 (setq org-done-keywords (append org-done-keywords dws nil))
4990 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4991 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4992 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4993 (setq org-todo-sets (nreverse org-todo-sets)
4994 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4995 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4996 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4997 ;; Compute the regular expressions and other local variables.
4998 ;; Using `org-outline-regexp-bol' would complicate them much,
4999 ;; because of the fixed white space at the end of that string.
5000 (if (not org-done-keywords)
5001 (setq org-done-keywords (and org-todo-keywords-1
5002 (list (org-last org-todo-keywords-1)))))
5003 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5004 (length org-scheduled-string)
5005 (length org-clock-string)
5006 (length org-closed-string)))
5007 org-drawer-regexp
5008 (concat "^[ \t]*:\\("
5009 (mapconcat 'regexp-quote org-drawers "\\|")
5010 "\\):[ \t]*$")
5011 org-not-done-keywords
5012 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5013 org-todo-regexp
5014 (concat "\\("
5015 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5016 "\\)")
5017 org-not-done-regexp
5018 (concat "\\("
5019 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5020 "\\)")
5021 org-not-done-heading-regexp
5022 (format org-heading-keyword-regexp-format org-not-done-regexp)
5023 org-todo-line-regexp
5024 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5025 org-complex-heading-regexp
5026 (concat "^\\(\\*+\\)"
5027 "\\(?: +" org-todo-regexp "\\)?"
5028 "\\(?: +\\(\\[#.\\]\\)\\)?"
5029 "\\(?: +\\(.*?\\)\\)??"
5030 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5031 "[ \t]*$")
5032 org-complex-heading-regexp-format
5033 (concat "^\\(\\*+\\)"
5034 "\\(?: +" org-todo-regexp "\\)?"
5035 "\\(?: +\\(\\[#.\\]\\)\\)?"
5036 "\\(?: +"
5037 ;; Stats cookies can be stuck to body.
5038 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5039 "\\(%s\\)"
5040 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5041 "\\)"
5042 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5043 "[ \t]*$")
5044 org-todo-line-tags-regexp
5045 (concat "^\\(\\*+\\)"
5046 "\\(?: +" org-todo-regexp "\\)?"
5047 "\\(?: +\\(.*?\\)\\)??"
5048 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5049 "[ \t]*$")
5050 org-deadline-regexp (concat "\\<" org-deadline-string)
5051 org-deadline-time-regexp
5052 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5053 org-deadline-time-hour-regexp
5054 (concat "\\<" org-deadline-string
5055 " *<\\(.+[0-9]\\{1,2\\}:[0-9]\\{2\\}[^>]*\\)>")
5056 org-deadline-line-regexp
5057 (concat "\\<\\(" org-deadline-string "\\).*")
5058 org-scheduled-regexp
5059 (concat "\\<" org-scheduled-string)
5060 org-scheduled-time-regexp
5061 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5062 org-scheduled-time-hour-regexp
5063 (concat "\\<" org-scheduled-string
5064 " *<\\(.+[0-9]\\{1,2\\}:[0-9]\\{2\\}[^>]*\\)>")
5065 org-closed-time-regexp
5066 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5067 org-keyword-time-regexp
5068 (concat "\\<\\(" org-scheduled-string
5069 "\\|" org-deadline-string
5070 "\\|" org-closed-string
5071 "\\|" org-clock-string "\\)"
5072 " *[[<]\\([^]>]+\\)[]>]")
5073 org-keyword-time-not-clock-regexp
5074 (concat "\\<\\(" org-scheduled-string
5075 "\\|" org-deadline-string
5076 "\\|" org-closed-string
5077 "\\)"
5078 " *[[<]\\([^]>]+\\)[]>]")
5079 org-maybe-keyword-time-regexp
5080 (concat "\\(\\<\\(" org-scheduled-string
5081 "\\|" org-deadline-string
5082 "\\|" org-closed-string
5083 "\\|" org-clock-string "\\)\\)?"
5084 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5085 org-all-time-keywords
5086 (mapcar (lambda (w) (substring w 0 -1))
5087 (list org-scheduled-string org-deadline-string
5088 org-clock-string org-closed-string)))
5089 (org-compute-latex-and-related-regexp)
5090 (org-set-font-lock-defaults))))
5092 (defun org-file-contents (file &optional noerror)
5093 "Return the contents of FILE, as a string."
5094 (if (or (not file)
5095 (not (file-readable-p file)))
5096 (if noerror
5097 (message "Cannot read file \"%s\"" file)
5098 (error "Cannot read file \"%s\"" file))
5099 (with-temp-buffer
5100 (insert-file-contents file)
5101 (buffer-string))))
5103 (defun org-extract-log-state-settings (x)
5104 "Extract the log state setting from a TODO keyword string.
5105 This will extract info from a string like \"WAIT(w@/!)\"."
5106 (let (kw key log1 log2)
5107 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5108 (setq kw (match-string 1 x)
5109 key (and (match-end 2) (match-string 2 x))
5110 log1 (and (match-end 3) (match-string 3 x))
5111 log2 (and (match-end 4) (match-string 4 x)))
5112 (and (or log1 log2)
5113 (list kw
5114 (and log1 (if (equal log1 "!") 'time 'note))
5115 (and log2 (if (equal log2 "!") 'time 'note)))))))
5117 (defun org-remove-keyword-keys (list)
5118 "Remove a pair of parenthesis at the end of each string in LIST."
5119 (mapcar (lambda (x)
5120 (if (string-match "(.*)$" x)
5121 (substring x 0 (match-beginning 0))
5123 list))
5125 (defun org-assign-fast-keys (alist)
5126 "Assign fast keys to a keyword-key alist.
5127 Respect keys that are already there."
5128 (let (new e (alt ?0))
5129 (while (setq e (pop alist))
5130 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5131 (cdr e)) ;; Key already assigned.
5132 (push e new)
5133 (let ((clist (string-to-list (downcase (car e))))
5134 (used (append new alist)))
5135 (when (= (car clist) ?@)
5136 (pop clist))
5137 (while (and clist (rassoc (car clist) used))
5138 (pop clist))
5139 (unless clist
5140 (while (rassoc alt used)
5141 (incf alt)))
5142 (push (cons (car e) (or (car clist) alt)) new))))
5143 (nreverse new)))
5145 ;;; Some variables used in various places
5147 (defvar org-window-configuration nil
5148 "Used in various places to store a window configuration.")
5149 (defvar org-selected-window nil
5150 "Used in various places to store a window configuration.")
5151 (defvar org-finish-function nil
5152 "Function to be called when `C-c C-c' is used.
5153 This is for getting out of special buffers like capture.")
5156 ;; FIXME: Occasionally check by commenting these, to make sure
5157 ;; no other functions uses these, forgetting to let-bind them.
5158 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5159 (defvar org-last-state)
5160 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5162 ;; Defined somewhere in this file, but used before definition.
5163 (defvar org-entities) ;; defined in org-entities.el
5164 (defvar org-struct-menu)
5165 (defvar org-org-menu)
5166 (defvar org-tbl-menu)
5168 ;;;; Define the Org-mode
5170 ;; We use a before-change function to check if a table might need
5171 ;; an update.
5172 (defvar org-table-may-need-update t
5173 "Indicates that a table might need an update.
5174 This variable is set by `org-before-change-function'.
5175 `org-table-align' sets it back to nil.")
5176 (defun org-before-change-function (beg end)
5177 "Every change indicates that a table might need an update."
5178 (setq org-table-may-need-update t))
5179 (defvar org-mode-map)
5180 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5181 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5182 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5183 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5184 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5185 (defvar org-table-buffer-is-an nil)
5187 (defvar bidi-paragraph-direction)
5188 (defvar buffer-face-mode-face)
5190 (require 'outline)
5191 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5192 (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"))
5193 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5195 ;; Other stuff we need.
5196 (require 'time-date)
5197 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5198 (require 'easymenu)
5199 (require 'overlay)
5201 ;; (require 'org-macs) moved higher up in the file before it is first used
5202 (require 'org-entities)
5203 ;; (require 'org-compat) moved higher up in the file before it is first used
5204 (require 'org-faces)
5205 (require 'org-list)
5206 (require 'org-pcomplete)
5207 (require 'org-src)
5208 (require 'org-footnote)
5209 (require 'org-macro)
5211 ;; babel
5212 (require 'ob)
5214 ;;;###autoload
5215 (define-derived-mode org-mode outline-mode "Org"
5216 "Outline-based notes management and organizer, alias
5217 \"Carsten's outline-mode for keeping track of everything.\"
5219 Org-mode develops organizational tasks around a NOTES file which
5220 contains information about projects as plain text. Org-mode is
5221 implemented on top of outline-mode, which is ideal to keep the content
5222 of large files well structured. It supports ToDo items, deadlines and
5223 time stamps, which magically appear in the diary listing of the Emacs
5224 calendar. Tables are easily created with a built-in table editor.
5225 Plain text URL-like links connect to websites, emails (VM), Usenet
5226 messages (Gnus), BBDB entries, and any files related to the project.
5227 For printing and sharing of notes, an Org-mode file (or a part of it)
5228 can be exported as a structured ASCII or HTML file.
5230 The following commands are available:
5232 \\{org-mode-map}"
5234 ;; Get rid of Outline menus, they are not needed
5235 ;; Need to do this here because define-derived-mode sets up
5236 ;; the keymap so late. Still, it is a waste to call this each time
5237 ;; we switch another buffer into org-mode.
5238 (if (featurep 'xemacs)
5239 (when (boundp 'outline-mode-menu-heading)
5240 ;; Assume this is Greg's port, it uses easymenu
5241 (easy-menu-remove outline-mode-menu-heading)
5242 (easy-menu-remove outline-mode-menu-show)
5243 (easy-menu-remove outline-mode-menu-hide))
5244 (define-key org-mode-map [menu-bar headings] 'undefined)
5245 (define-key org-mode-map [menu-bar hide] 'undefined)
5246 (define-key org-mode-map [menu-bar show] 'undefined))
5248 (org-load-modules-maybe)
5249 (easy-menu-add org-org-menu)
5250 (easy-menu-add org-tbl-menu)
5251 (org-install-agenda-files-menu)
5252 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5253 (add-to-invisibility-spec '(org-cwidth))
5254 (add-to-invisibility-spec '(org-hide-block . t))
5255 (when (featurep 'xemacs)
5256 (org-set-local 'line-move-ignore-invisible t))
5257 (org-set-local 'outline-regexp org-outline-regexp)
5258 (org-set-local 'outline-level 'org-outline-level)
5259 (setq bidi-paragraph-direction 'left-to-right)
5260 ;; FIXME Circumvent a bug in outline.el (Emacs <24.4)
5261 (set (make-local-variable 'paragraph-start) "\f\\|[ \t]*$\\|\\*+ ")
5262 (when (and org-ellipsis
5263 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5264 (fboundp 'make-glyph-code))
5265 (unless org-display-table
5266 (setq org-display-table (make-display-table)))
5267 (set-display-table-slot
5268 org-display-table 4
5269 (vconcat (mapcar
5270 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5271 org-ellipsis)))
5272 (if (stringp org-ellipsis) org-ellipsis "..."))))
5273 (setq buffer-display-table org-display-table))
5274 (org-set-regexps-and-options-for-tags)
5275 (org-set-regexps-and-options)
5276 (when (and org-tag-faces (not org-tags-special-faces-re))
5277 ;; tag faces set outside customize.... force initialization.
5278 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5279 ;; Calc embedded
5280 (org-set-local 'calc-embedded-open-mode "# ")
5281 ;; Modify a few syntax entries
5282 (modify-syntax-entry ?@ "w")
5283 (modify-syntax-entry ?\" "\"")
5284 (if org-startup-truncated (setq truncate-lines t))
5285 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5286 (org-set-local 'font-lock-unfontify-region-function
5287 'org-unfontify-region)
5288 ;; Activate before-change-function
5289 (org-set-local 'org-table-may-need-update t)
5290 (org-add-hook 'before-change-functions 'org-before-change-function nil
5291 'local)
5292 ;; Check for running clock before killing a buffer
5293 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5294 ;; Initialize macros templates.
5295 (org-macro-initialize-templates)
5296 ;; Initialize radio targets.
5297 (org-update-radio-target-regexp)
5298 ;; Indentation.
5299 (org-set-local 'indent-line-function 'org-indent-line)
5300 (org-set-local 'indent-region-function 'org-indent-region)
5301 ;; Filling and auto-filling.
5302 (org-setup-filling)
5303 ;; Comments.
5304 (org-setup-comments-handling)
5305 ;; Beginning/end of defun
5306 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5307 (org-set-local 'end-of-defun-function 'org-forward-element)
5308 ;; Next error for sparse trees
5309 (org-set-local 'next-error-function 'org-occur-next-match)
5310 ;; Make sure dependence stuff works reliably, even for users who set it
5311 ;; too late :-(
5312 (if org-enforce-todo-dependencies
5313 (add-hook 'org-blocker-hook
5314 'org-block-todo-from-children-or-siblings-or-parent)
5315 (remove-hook 'org-blocker-hook
5316 'org-block-todo-from-children-or-siblings-or-parent))
5317 (if org-enforce-todo-checkbox-dependencies
5318 (add-hook 'org-blocker-hook
5319 'org-block-todo-from-checkboxes)
5320 (remove-hook 'org-blocker-hook
5321 'org-block-todo-from-checkboxes))
5323 ;; Align options lines
5324 (org-set-local
5325 'align-mode-rules-list
5326 '((org-in-buffer-settings
5327 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5328 (modes . '(org-mode)))))
5330 ;; Imenu
5331 (org-set-local 'imenu-create-index-function
5332 'org-imenu-get-tree)
5334 ;; Make isearch reveal context
5335 (if (or (featurep 'xemacs)
5336 (not (boundp 'outline-isearch-open-invisible-function)))
5337 ;; Emacs 21 and XEmacs make use of the hook
5338 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5339 ;; Emacs 22 deals with this through a special variable
5340 (org-set-local 'outline-isearch-open-invisible-function
5341 (lambda (&rest ignore) (org-show-context 'isearch)))
5342 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5344 ;; Setup the pcomplete hooks
5345 (set (make-local-variable 'pcomplete-command-completion-function)
5346 'org-pcomplete-initial)
5347 (set (make-local-variable 'pcomplete-command-name-function)
5348 'org-command-at-point)
5349 (set (make-local-variable 'pcomplete-default-completion-function)
5350 'ignore)
5351 (set (make-local-variable 'pcomplete-parse-arguments-function)
5352 'org-parse-arguments)
5353 (set (make-local-variable 'pcomplete-termination-string) "")
5354 (when (>= emacs-major-version 23)
5355 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5357 ;; If empty file that did not turn on org-mode automatically, make it to.
5358 (if (and org-insert-mode-line-in-empty-file
5359 (org-called-interactively-p 'any)
5360 (= (point-min) (point-max)))
5361 (insert "# -*- mode: org -*-\n\n"))
5362 (unless org-inhibit-startup
5363 (org-unmodified
5364 (and org-startup-with-beamer-mode (org-beamer-mode))
5365 (when org-startup-align-all-tables
5366 (org-table-map-tables 'org-table-align 'quietly))
5367 (when org-startup-with-inline-images
5368 (org-display-inline-images))
5369 (when org-startup-with-latex-preview
5370 (org-preview-latex-fragment))
5371 (unless org-inhibit-startup-visibility-stuff
5372 (org-set-startup-visibility))))
5373 ;; Try to set org-hide correctly
5374 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5376 ;; Update `customize-package-emacs-version-alist'
5377 (add-to-list 'customize-package-emacs-version-alist
5378 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5379 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5380 ("8.0" . "24.4")))
5382 (defvar org-mode-transpose-word-syntax-table
5383 (let ((st (make-syntax-table)))
5384 (mapc (lambda(c) (modify-syntax-entry
5385 (string-to-char (car c)) "w p" st))
5386 org-emphasis-alist)
5387 st))
5389 (when (fboundp 'abbrev-table-put)
5390 (abbrev-table-put org-mode-abbrev-table
5391 :parents (list text-mode-abbrev-table)))
5393 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5395 (defsubst org-fix-ellipsis-at-bol ()
5396 (save-excursion (goto-char (window-start)) (recenter 0)))
5398 (defun org-find-invisible-foreground ()
5399 (let ((candidates (remove
5400 "unspecified-bg"
5401 (nconc
5402 (list (face-background 'default)
5403 (face-background 'org-default))
5404 (mapcar
5405 (lambda (alist)
5406 (when (boundp alist)
5407 (cdr (assoc 'background-color (symbol-value alist)))))
5408 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5409 (list (face-foreground 'org-hide))))))
5410 (car (remove nil candidates))))
5412 (defun org-current-time (&optional rounding-minutes past)
5413 "Current time, possibly rounded to ROUNDING-MINUTES.
5414 When ROUNDING-MINUTES is not an integer, fall back on the car of
5415 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5416 the rounding returns a past time."
5417 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5418 (car org-time-stamp-rounding-minutes)))
5419 (time (decode-time)) res)
5420 (if (< r 1)
5421 (current-time)
5422 (setq res
5423 (apply 'encode-time
5424 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5425 (nthcdr 2 time))))
5426 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5427 (seconds-to-time (- (org-float-time res) (* r 60)))
5428 res))))
5430 (defun org-today ()
5431 "Return today date, considering `org-extend-today-until'."
5432 (time-to-days
5433 (time-subtract (current-time)
5434 (list 0 (* 3600 org-extend-today-until) 0))))
5436 ;;;; Font-Lock stuff, including the activators
5438 (defvar org-mouse-map (make-sparse-keymap))
5439 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5440 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5441 (when org-mouse-1-follows-link
5442 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5443 (when org-tab-follows-link
5444 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5445 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5447 (require 'font-lock)
5449 (defconst org-non-link-chars "]\t\n\r<>")
5450 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5451 "shell" "elisp" "doi" "message"))
5452 (defvar org-link-types-re nil
5453 "Matches a link that has a url-like prefix like \"http:\"")
5454 (defvar org-link-re-with-space nil
5455 "Matches a link with spaces, optional angular brackets around it.")
5456 (defvar org-link-re-with-space2 nil
5457 "Matches a link with spaces, optional angular brackets around it.")
5458 (defvar org-link-re-with-space3 nil
5459 "Matches a link with spaces, only for internal part in bracket links.")
5460 (defvar org-angle-link-re nil
5461 "Matches link with angular brackets, spaces are allowed.")
5462 (defvar org-plain-link-re nil
5463 "Matches plain link, without spaces.")
5464 (defvar org-bracket-link-regexp nil
5465 "Matches a link in double brackets.")
5466 (defvar org-bracket-link-analytic-regexp nil
5467 "Regular expression used to analyze links.
5468 Here is what the match groups contain after a match:
5469 1: http:
5470 2: http
5471 3: path
5472 4: [desc]
5473 5: desc")
5474 (defvar org-bracket-link-analytic-regexp++ nil
5475 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5476 (defvar org-any-link-re nil
5477 "Regular expression matching any link.")
5479 (defconst org-match-sexp-depth 3
5480 "Number of stacked braces for sub/superscript matching.")
5482 (defun org-create-multibrace-regexp (left right n)
5483 "Create a regular expression which will match a balanced sexp.
5484 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5485 as single character strings.
5486 The regexp returned will match the entire expression including the
5487 delimiters. It will also define a single group which contains the
5488 match except for the outermost delimiters. The maximum depth of
5489 stacked delimiters is N. Escaping delimiters is not possible."
5490 (let* ((nothing (concat "[^" left right "]*?"))
5491 (or "\\|")
5492 (re nothing)
5493 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5494 (while (> n 1)
5495 (setq n (1- n)
5496 re (concat re or next)
5497 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5498 (concat left "\\(" re "\\)" right)))
5500 (defvar org-match-substring-regexp
5501 (concat
5502 "\\(\\S-\\)\\([_^]\\)\\("
5503 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5504 "\\|"
5505 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5506 "\\|"
5507 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5508 "The regular expression matching a sub- or superscript.")
5510 (defvar org-match-substring-with-braces-regexp
5511 (concat
5512 "\\(\\S-\\)\\([_^]\\)\\("
5513 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5514 "\\)")
5515 "The regular expression matching a sub- or superscript, forcing braces.")
5517 (defun org-make-link-regexps ()
5518 "Update the link regular expressions.
5519 This should be called after the variable `org-link-types' has changed."
5520 (setq org-link-types-re
5521 (concat
5522 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5523 org-link-re-with-space
5524 (concat
5525 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5526 "\\([^" org-non-link-chars " ]"
5527 "[^" org-non-link-chars "]*"
5528 "[^" org-non-link-chars " ]\\)>?")
5529 org-link-re-with-space2
5530 (concat
5531 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5532 "\\([^" org-non-link-chars " ]"
5533 "[^\t\n\r]*"
5534 "[^" org-non-link-chars " ]\\)>?")
5535 org-link-re-with-space3
5536 (concat
5537 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5538 "\\([^" org-non-link-chars " ]"
5539 "[^\t\n\r]*\\)")
5540 org-angle-link-re
5541 (concat
5542 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5543 "\\([^" org-non-link-chars " ]"
5544 "[^" org-non-link-chars "]*"
5545 "\\)>")
5546 org-plain-link-re
5547 (concat
5548 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5549 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5550 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5551 org-bracket-link-regexp
5552 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5553 org-bracket-link-analytic-regexp
5554 (concat
5555 "\\[\\["
5556 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5557 "\\([^]]+\\)"
5558 "\\]"
5559 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5560 "\\]")
5561 org-bracket-link-analytic-regexp++
5562 (concat
5563 "\\[\\["
5564 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5565 "\\([^]]+\\)"
5566 "\\]"
5567 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5568 "\\]")
5569 org-any-link-re
5570 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5571 org-angle-link-re "\\)\\|\\("
5572 org-plain-link-re "\\)")))
5574 (org-make-link-regexps)
5576 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5577 "Regular expression for fast time stamp matching.")
5578 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5579 "Regular expression for fast time stamp matching.")
5580 (defconst org-ts-regexp0
5581 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5582 "Regular expression matching time strings for analysis.
5583 This one does not require the space after the date, so it can be used
5584 on a string that terminates immediately after the date.")
5585 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5586 "Regular expression matching time strings for analysis.")
5587 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5588 "Regular expression matching time stamps, with groups.")
5589 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5590 "Regular expression matching time stamps (also [..]), with groups.")
5591 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5592 "Regular expression matching a time stamp range.")
5593 (defconst org-tr-regexp-both
5594 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5595 "Regular expression matching a time stamp range.")
5596 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5597 org-ts-regexp "\\)?")
5598 "Regular expression matching a time stamp or time stamp range.")
5599 (defconst org-tsr-regexp-both
5600 (concat org-ts-regexp-both "\\(--?-?"
5601 org-ts-regexp-both "\\)?")
5602 "Regular expression matching a time stamp or time stamp range.
5603 The time stamps may be either active or inactive.")
5605 (defvar org-emph-face nil)
5607 (defun org-do-emphasis-faces (limit)
5608 "Run through the buffer and add overlays to emphasized strings."
5609 (let (rtn a)
5610 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5611 (if (not (= (char-after (match-beginning 3))
5612 (char-after (match-beginning 4))))
5613 (progn
5614 (setq rtn t)
5615 (setq a (assoc (match-string 3) org-emphasis-alist))
5616 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5617 'face
5618 (nth 1 a))
5619 (and (nth 4 a)
5620 (org-remove-flyspell-overlays-in
5621 (match-beginning 0) (match-end 0)))
5622 (add-text-properties (match-beginning 2) (match-end 2)
5623 '(font-lock-multiline t org-emphasis t))
5624 (when org-hide-emphasis-markers
5625 (add-text-properties (match-end 4) (match-beginning 5)
5626 '(invisible org-link))
5627 (add-text-properties (match-beginning 3) (match-end 3)
5628 '(invisible org-link)))))
5629 (backward-char 1))
5630 rtn))
5632 (defun org-emphasize (&optional char)
5633 "Insert or change an emphasis, i.e. a font like bold or italic.
5634 If there is an active region, change that region to a new emphasis.
5635 If there is no region, just insert the marker characters and position
5636 the cursor between them.
5637 CHAR should be either the marker character, or the first character of the
5638 HTML tag associated with that emphasis. If CHAR is a space, the means
5639 to remove the emphasis of the selected region.
5640 If char is not given (for example in an interactive call) it
5641 will be prompted for."
5642 (interactive)
5643 (let ((eal org-emphasis-alist) e det
5644 (erc org-emphasis-regexp-components)
5645 (prompt "")
5646 (string "") beg end move tag c s)
5647 (if (org-region-active-p)
5648 (setq beg (region-beginning) end (region-end)
5649 string (buffer-substring beg end))
5650 (setq move t))
5652 (while (setq e (pop eal))
5653 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5654 c (aref tag 0))
5655 (push (cons c (string-to-char (car e))) det)
5656 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5657 (substring tag 1)))))
5658 (setq det (nreverse det))
5659 (unless char
5660 (message "%s" (concat "Emphasis marker or tag:" prompt))
5661 (setq char (read-char-exclusive)))
5662 (setq char (or (cdr (assoc char det)) char))
5663 (if (equal char ?\ )
5664 (setq s "" move nil)
5665 (unless (assoc (char-to-string char) org-emphasis-alist)
5666 (error "No such emphasis marker: \"%c\"" char))
5667 (setq s (char-to-string char)))
5668 (while (and (> (length string) 1)
5669 (equal (substring string 0 1) (substring string -1))
5670 (assoc (substring string 0 1) org-emphasis-alist))
5671 (setq string (substring string 1 -1)))
5672 (setq string (concat s string s))
5673 (if beg (delete-region beg end))
5674 (unless (or (bolp)
5675 (string-match (concat "[" (nth 0 erc) "\n]")
5676 (char-to-string (char-before (point)))))
5677 (insert " "))
5678 (unless (or (eobp)
5679 (string-match (concat "[" (nth 1 erc) "\n]")
5680 (char-to-string (char-after (point)))))
5681 (insert " ") (backward-char 1))
5682 (insert string)
5683 (and move (backward-char 1))))
5685 (defconst org-nonsticky-props
5686 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5688 (defsubst org-rear-nonsticky-at (pos)
5689 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5691 (defun org-activate-plain-links (limit)
5692 "Run through the buffer and add overlays to links."
5693 (let (f hl)
5694 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5695 (not (org-in-src-block-p)))
5696 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5697 (setq f (get-text-property (match-beginning 0) 'face))
5698 (setq hl (org-match-string-no-properties 0))
5699 (if (or (eq f 'org-tag)
5700 (and (listp f) (memq 'org-tag f)))
5702 (add-text-properties (match-beginning 0) (match-end 0)
5703 (list 'mouse-face 'highlight
5704 'face 'org-link
5705 'htmlize-link `(:uri ,hl)
5706 'keymap org-mouse-map))
5707 (org-rear-nonsticky-at (match-end 0)))
5708 t)))
5710 (defun org-activate-code (limit)
5711 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5712 (progn
5713 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5714 (remove-text-properties (match-beginning 0) (match-end 0)
5715 '(display t invisible t intangible t))
5716 t)))
5718 (defcustom org-src-fontify-natively nil
5719 "When non-nil, fontify code in code blocks."
5720 :type 'boolean
5721 :version "24.1"
5722 :group 'org-appearance
5723 :group 'org-babel)
5725 (defcustom org-allow-promoting-top-level-subtree nil
5726 "When non-nil, allow promoting a top level subtree.
5727 The leading star of the top level headline will be replaced
5728 by a #."
5729 :type 'boolean
5730 :version "24.1"
5731 :group 'org-appearance)
5733 (defun org-fontify-meta-lines-and-blocks (limit)
5734 (condition-case nil
5735 (org-fontify-meta-lines-and-blocks-1 limit)
5736 (error (message "org-mode fontification error"))))
5738 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5739 "Fontify #+ lines and blocks."
5740 (let ((case-fold-search t))
5741 (if (re-search-forward
5742 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5743 limit t)
5744 (let ((beg (match-beginning 0))
5745 (block-start (match-end 0))
5746 (block-end nil)
5747 (lang (match-string 7))
5748 (beg1 (line-beginning-position 2))
5749 (dc1 (downcase (match-string 2)))
5750 (dc3 (downcase (match-string 3)))
5751 end end1 quoting block-type ovl)
5752 (cond
5753 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5754 ;; a single line of backend-specific content
5755 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5756 (remove-text-properties (match-beginning 0) (match-end 0)
5757 '(display t invisible t intangible t))
5758 (add-text-properties (match-beginning 1) (match-end 3)
5759 '(font-lock-fontified t face org-meta-line))
5760 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5761 '(font-lock-fontified t face org-block))
5762 ; for backend-specific code
5764 ((and (match-end 4) (equal dc3 "+begin"))
5765 ;; Truly a block
5766 (setq block-type (downcase (match-string 5))
5767 quoting (member block-type org-protecting-blocks))
5768 (when (re-search-forward
5769 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5770 nil t) ;; on purpose, we look further than LIMIT
5771 (setq end (min (point-max) (match-end 0))
5772 end1 (min (point-max) (1- (match-beginning 0))))
5773 (setq block-end (match-beginning 0))
5774 (when quoting
5775 (remove-text-properties beg end
5776 '(display t invisible t intangible t)))
5777 (add-text-properties
5778 beg end
5779 '(font-lock-fontified t font-lock-multiline t))
5780 (add-text-properties beg beg1 '(face org-meta-line))
5781 (add-text-properties end1 (min (point-max) (1+ end))
5782 '(face org-meta-line)) ; for end_src
5783 (cond
5784 ((and lang (not (string= lang "")) org-src-fontify-natively)
5785 (org-src-font-lock-fontify-block lang block-start block-end)
5786 ;; remove old background overlays
5787 (mapc (lambda (ov)
5788 (if (eq (overlay-get ov 'face) 'org-block-background)
5789 (delete-overlay ov)))
5790 (overlays-at (/ (+ beg1 block-end) 2)))
5791 ;; add a background overlay
5792 (setq ovl (make-overlay beg1 block-end))
5793 (overlay-put ovl 'face 'org-block-background)
5794 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5795 (quoting
5796 (add-text-properties beg1 (min (point-max) (1+ end1))
5797 '(face org-block))) ; end of source block
5798 ((not org-fontify-quote-and-verse-blocks))
5799 ((string= block-type "quote")
5800 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5801 ((string= block-type "verse")
5802 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5803 (add-text-properties beg beg1 '(face org-block-begin-line))
5804 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5805 '(face org-block-end-line))
5807 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5808 (add-text-properties
5809 beg (match-end 3)
5810 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5811 '(font-lock-fontified t invisible t)
5812 '(font-lock-fontified t face org-document-info-keyword)))
5813 (add-text-properties
5814 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5815 (if (string-equal dc1 "+title:")
5816 '(font-lock-fontified t face org-document-title)
5817 '(font-lock-fontified t face org-document-info))))
5818 ((or (equal dc1 "+results")
5819 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5820 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5821 "+call:" "+header:" "+headers:" "+name:"))
5822 (and (match-end 4) (equal dc3 "+attr")))
5823 (add-text-properties
5824 beg (match-end 0)
5825 '(font-lock-fontified t face org-meta-line))
5827 ((member dc3 '(" " ""))
5828 (add-text-properties
5829 beg (match-end 0)
5830 '(font-lock-fontified t face font-lock-comment-face)))
5831 ((not (member (char-after beg) '(?\ ?\t)))
5832 ;; just any other in-buffer setting, but not indented
5833 (add-text-properties
5834 beg (match-end 0)
5835 '(font-lock-fontified t face org-meta-line))
5837 (t nil))))))
5839 (defun org-activate-angle-links (limit)
5840 "Run through the buffer and add overlays to links."
5841 (if (and (re-search-forward org-angle-link-re limit t)
5842 (not (org-in-src-block-p)))
5843 (progn
5844 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5845 (add-text-properties (match-beginning 0) (match-end 0)
5846 (list 'mouse-face 'highlight
5847 'keymap org-mouse-map))
5848 (org-rear-nonsticky-at (match-end 0))
5849 t)))
5851 (defun org-activate-footnote-links (limit)
5852 "Run through the buffer and add overlays to footnotes."
5853 (let ((fn (org-footnote-next-reference-or-definition limit)))
5854 (when fn
5855 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5856 (org-remove-flyspell-overlays-in beg end)
5857 (add-text-properties beg end
5858 (list 'mouse-face 'highlight
5859 'keymap org-mouse-map
5860 'help-echo
5861 (if (= (point-at-bol) beg)
5862 "Footnote definition"
5863 "Footnote reference")
5864 'font-lock-fontified t
5865 'font-lock-multiline t
5866 'face 'org-footnote))))))
5868 (defun org-activate-bracket-links (limit)
5869 "Run through the buffer and add overlays to bracketed links."
5870 (if (and (re-search-forward org-bracket-link-regexp limit t)
5871 (not (org-in-src-block-p)))
5872 (let* ((hl (org-match-string-no-properties 1))
5873 (help (concat "LINK: " hl))
5874 ;; FIXME: Above we should remove the escapes. But that
5875 ;; requires another match, protecting match data, a lot
5876 ;; of overhead for font-lock.
5877 (ip (org-maybe-intangible
5878 (list 'invisible 'org-link
5879 'keymap org-mouse-map 'mouse-face 'highlight
5880 'font-lock-multiline t 'help-echo help
5881 'htmlize-link `(:uri ,hl))))
5882 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5883 'font-lock-multiline t 'help-echo help
5884 'htmlize-link `(:uri ,hl))))
5885 ;; We need to remove the invisible property here. Table narrowing
5886 ;; may have made some of this invisible.
5887 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5888 (remove-text-properties (match-beginning 0) (match-end 0)
5889 '(invisible nil))
5890 (if (match-end 3)
5891 (progn
5892 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5893 (org-rear-nonsticky-at (match-beginning 3))
5894 (add-text-properties (match-beginning 3) (match-end 3) vp)
5895 (org-rear-nonsticky-at (match-end 3))
5896 (add-text-properties (match-end 3) (match-end 0) ip)
5897 (org-rear-nonsticky-at (match-end 0)))
5898 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5899 (org-rear-nonsticky-at (match-beginning 1))
5900 (add-text-properties (match-beginning 1) (match-end 1) vp)
5901 (org-rear-nonsticky-at (match-end 1))
5902 (add-text-properties (match-end 1) (match-end 0) ip)
5903 (org-rear-nonsticky-at (match-end 0)))
5904 t)))
5906 (defun org-activate-dates (limit)
5907 "Run through the buffer and add overlays to dates."
5908 (if (and (re-search-forward org-tsr-regexp-both limit t)
5909 (not (equal (char-before (match-beginning 0)) 91)))
5910 (progn
5911 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5912 (add-text-properties (match-beginning 0) (match-end 0)
5913 (list 'mouse-face 'highlight
5914 'keymap org-mouse-map))
5915 (org-rear-nonsticky-at (match-end 0))
5916 (when org-display-custom-times
5917 (if (match-end 3)
5918 (org-display-custom-time (match-beginning 3) (match-end 3)))
5919 (org-display-custom-time (match-beginning 1) (match-end 1)))
5920 t)))
5922 (defvar org-target-link-regexp nil
5923 "Regular expression matching radio targets in plain text.")
5924 (make-variable-buffer-local 'org-target-link-regexp)
5925 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5926 "Regular expression matching a link target.")
5927 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5928 "Regular expression matching a radio target.")
5929 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5930 "Regular expression matching any target.")
5932 (defun org-activate-target-links (limit)
5933 "Run through the buffer and add overlays to target matches."
5934 (when org-target-link-regexp
5935 (let ((case-fold-search t))
5936 (if (re-search-forward org-target-link-regexp limit t)
5937 (progn
5938 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5939 (add-text-properties (match-beginning 0) (match-end 0)
5940 (list 'mouse-face 'highlight
5941 'keymap org-mouse-map
5942 'help-echo "Radio target link"
5943 'org-linked-text t))
5944 (org-rear-nonsticky-at (match-end 0))
5945 t)))))
5947 (defun org-update-radio-target-regexp ()
5948 "Find all radio targets in this file and update the regular expression."
5949 (interactive)
5950 (when (memq 'radio org-activate-links)
5951 (setq org-target-link-regexp
5952 (org-make-target-link-regexp (org-all-targets 'radio)))
5953 (org-restart-font-lock)))
5955 (defun org-hide-wide-columns (limit)
5956 (let (s e)
5957 (setq s (text-property-any (point) (or limit (point-max))
5958 'org-cwidth t))
5959 (when s
5960 (setq e (next-single-property-change s 'org-cwidth))
5961 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5962 (goto-char e)
5963 t)))
5965 (defvar org-latex-and-related-regexp nil
5966 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
5967 (defvar org-match-substring-regexp)
5968 (defvar org-match-substring-with-braces-regexp)
5970 (defun org-compute-latex-and-related-regexp ()
5971 "Compute regular expression for LaTeX, entities and sub/superscript.
5972 Result depends on variable `org-highlight-latex-and-related'."
5973 (org-set-local
5974 'org-latex-and-related-regexp
5975 (let* ((re-sub
5976 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
5977 ((eq org-use-sub-superscripts '{})
5978 (list org-match-substring-with-braces-regexp))
5979 (org-use-sub-superscripts (list org-match-substring-regexp))))
5980 (re-latex
5981 (when (memq 'latex org-highlight-latex-and-related)
5982 (let ((matchers (plist-get org-format-latex-options :matchers)))
5983 (delq nil
5984 (mapcar (lambda (x)
5985 (and (member (car x) matchers) (nth 1 x)))
5986 org-latex-regexps)))))
5987 (re-entities
5988 (when (memq 'entities org-highlight-latex-and-related)
5989 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
5990 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
5992 (defun org-do-latex-and-related (limit)
5993 "Highlight LaTeX snippets and environments, entities and sub/superscript.
5994 LIMIT bounds the search for syntax to highlight. Stop at first
5995 highlighted object, if any. Return t if some highlighting was
5996 done, nil otherwise."
5997 (when (org-string-nw-p org-latex-and-related-regexp)
5998 (catch 'found
5999 (while (re-search-forward org-latex-and-related-regexp limit t)
6000 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6001 'face))
6002 '(org-code org-verbatim underline))
6003 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6004 '(?_ ?^))
6006 0)))
6007 (font-lock-prepend-text-property
6008 (+ offset (match-beginning 0)) (match-end 0)
6009 'face 'org-latex-and-related)
6010 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6011 '(font-lock-multiline t)))
6012 (throw 'found t)))
6013 nil)))
6015 (defun org-restart-font-lock ()
6016 "Restart `font-lock-mode', to force refontification."
6017 (when (and (boundp 'font-lock-mode) font-lock-mode)
6018 (font-lock-mode -1)
6019 (font-lock-mode 1)))
6021 (defun org-all-targets (&optional radio)
6022 "Return a list of all targets in this file.
6023 When optional argument RADIO is non-nil, only find radio
6024 targets."
6025 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6026 (save-excursion
6027 (goto-char (point-min))
6028 (while (re-search-forward re nil t)
6029 ;; Make sure point is really within the object.
6030 (backward-char)
6031 (let ((obj (org-element-context)))
6032 (when (memq (org-element-type obj) '(radio-target target))
6033 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6034 rtn)))
6036 (defun org-make-target-link-regexp (targets)
6037 "Make regular expression matching all strings in TARGETS.
6038 The regular expression finds the targets also if there is a line break
6039 between words."
6040 (and targets
6041 (concat
6042 "\\<\\("
6043 (mapconcat
6044 (lambda (x)
6045 (setq x (regexp-quote x))
6046 (while (string-match " +" x)
6047 (setq x (replace-match "\\s-+" t t x)))
6049 targets
6050 "\\|")
6051 "\\)\\>")))
6053 (defun org-activate-tags (limit)
6054 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6055 (progn
6056 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6057 (add-text-properties (match-beginning 1) (match-end 1)
6058 (list 'mouse-face 'highlight
6059 'keymap org-mouse-map))
6060 (org-rear-nonsticky-at (match-end 1))
6061 t)))
6063 (defun org-outline-level ()
6064 "Compute the outline level of the heading at point.
6065 If this is called at a normal headline, the level is the number of stars.
6066 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6067 (save-excursion
6068 (if (not (condition-case nil
6069 (org-back-to-heading t)
6070 (error nil)))
6072 (looking-at org-outline-regexp)
6073 (1- (- (match-end 0) (match-beginning 0))))))
6075 (defvar org-font-lock-keywords nil)
6077 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
6078 "Regular expression matching a property line.")
6080 (defvar org-font-lock-hook nil
6081 "Functions to be called for special font lock stuff.")
6083 (defvar org-font-lock-set-keywords-hook nil
6084 "Functions that can manipulate `org-font-lock-extra-keywords'.
6085 This is called after `org-font-lock-extra-keywords' is defined, but before
6086 it is installed to be used by font lock. This can be useful if something
6087 needs to be inserted at a specific position in the font-lock sequence.")
6089 (defun org-font-lock-hook (limit)
6090 "Run `org-font-lock-hook' within LIMIT."
6091 (run-hook-with-args 'org-font-lock-hook limit))
6093 (defun org-set-font-lock-defaults ()
6094 "Set font lock defaults for the current buffer."
6095 (let* ((em org-fontify-emphasized-text)
6096 (lk org-activate-links)
6097 (org-font-lock-extra-keywords
6098 (list
6099 ;; Call the hook
6100 '(org-font-lock-hook)
6101 ;; Headlines
6102 `(,(if org-fontify-whole-heading-line
6103 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6104 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6105 (1 (org-get-level-face 1))
6106 (2 (org-get-level-face 2))
6107 (3 (org-get-level-face 3)))
6108 ;; Table lines
6109 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6110 (1 'org-table t))
6111 ;; Table internals
6112 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6113 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6114 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6115 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6116 ;; Drawers
6117 (list org-drawer-regexp '(0 'org-special-keyword t))
6118 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6119 ;; Properties
6120 (list org-property-re
6121 '(1 'org-special-keyword t)
6122 '(3 'org-property-value t))
6123 ;; Links
6124 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6125 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6126 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6127 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6128 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6129 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6130 (if (memq 'footnote lk) '(org-activate-footnote-links))
6131 ;; Targets.
6132 (list org-any-target-regexp '(0 'org-target t))
6133 ;; Diary sexps.
6134 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6135 ;; Macro
6136 '("{{{.+}}}" (0 'org-macro t))
6137 '(org-hide-wide-columns (0 nil append))
6138 ;; TODO keyword
6139 (list (format org-heading-keyword-regexp-format
6140 org-todo-regexp)
6141 '(2 (org-get-todo-face 2) t))
6142 ;; DONE
6143 (if org-fontify-done-headline
6144 (list (format org-heading-keyword-regexp-format
6145 (concat
6146 "\\(?:"
6147 (mapconcat 'regexp-quote org-done-keywords "\\|")
6148 "\\)"))
6149 '(2 'org-headline-done t))
6150 nil)
6151 ;; Priorities
6152 '(org-font-lock-add-priority-faces)
6153 ;; Tags
6154 '(org-font-lock-add-tag-faces)
6155 ;; Tags groups
6156 (if (and org-group-tags org-tag-groups-alist)
6157 (list (concat org-outline-regexp-bol ".+\\(:"
6158 (regexp-opt (mapcar 'car org-tag-groups-alist))
6159 ":\\).*$")
6160 '(1 'org-tag-group prepend)))
6161 ;; Special keywords
6162 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6163 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6164 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6165 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6166 ;; Emphasis
6167 (if em
6168 (if (featurep 'xemacs)
6169 '(org-do-emphasis-faces (0 nil append))
6170 '(org-do-emphasis-faces)))
6171 ;; Checkboxes
6172 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6173 1 'org-checkbox prepend)
6174 (if (cdr (assq 'checkbox org-list-automatic-rules))
6175 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6176 (0 (org-get-checkbox-statistics-face) t)))
6177 ;; Description list items
6178 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6179 1 'org-list-dt prepend)
6180 ;; ARCHIVEd headings
6181 (list (concat
6182 org-outline-regexp-bol
6183 "\\(.*:" org-archive-tag ":.*\\)")
6184 '(1 'org-archived prepend))
6185 ;; Specials
6186 '(org-do-latex-and-related)
6187 '(org-fontify-entities)
6188 '(org-raise-scripts)
6189 ;; Code
6190 '(org-activate-code (1 'org-code t))
6191 ;; COMMENT
6192 (list (format org-heading-keyword-regexp-format
6193 (concat "\\("
6194 org-comment-string "\\|" org-quote-string
6195 "\\)"))
6196 '(2 'org-special-keyword t))
6197 ;; Blocks and meta lines
6198 '(org-fontify-meta-lines-and-blocks)
6200 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6201 (run-hooks 'org-font-lock-set-keywords-hook)
6202 ;; Now set the full font-lock-keywords
6203 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6204 (org-set-local 'font-lock-defaults
6205 '(org-font-lock-keywords t nil nil backward-paragraph))
6206 (kill-local-variable 'font-lock-keywords) nil))
6208 (defun org-toggle-pretty-entities ()
6209 "Toggle the composition display of entities as UTF8 characters."
6210 (interactive)
6211 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6212 (org-restart-font-lock)
6213 (if org-pretty-entities
6214 (message "Entities are displayed as UTF8 characters")
6215 (save-restriction
6216 (widen)
6217 (org-decompose-region (point-min) (point-max))
6218 (message "Entities are displayed plain"))))
6220 (defvar org-custom-properties-overlays nil
6221 "List of overlays used for custom properties.")
6222 (make-variable-buffer-local 'org-custom-properties-overlays)
6224 (defun org-toggle-custom-properties-visibility ()
6225 "Display or hide properties in `org-custom-properties'."
6226 (interactive)
6227 (if org-custom-properties-overlays
6228 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6229 (setq org-custom-properties-overlays nil))
6230 (unless (not org-custom-properties)
6231 (save-excursion
6232 (save-restriction
6233 (widen)
6234 (goto-char (point-min))
6235 (while (re-search-forward org-property-re nil t)
6236 (mapc (lambda(p)
6237 (when (equal p (substring (match-string 1) 1 -1))
6238 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6239 (overlay-put o 'invisible t)
6240 (overlay-put o 'org-custom-property t)
6241 (push o org-custom-properties-overlays))))
6242 org-custom-properties)))))))
6244 (defun org-fontify-entities (limit)
6245 "Find an entity to fontify."
6246 (let (ee)
6247 (when org-pretty-entities
6248 (catch 'match
6249 (while (re-search-forward
6250 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6251 limit t)
6252 (if (and (not (org-in-indented-comment-line))
6253 (setq ee (org-entity-get (match-string 1)))
6254 (= (length (nth 6 ee)) 1))
6255 (let*
6256 ((end (if (equal (match-string 2) "{}")
6257 (match-end 2)
6258 (match-end 1))))
6259 (add-text-properties
6260 (match-beginning 0) end
6261 (list 'font-lock-fontified t))
6262 (compose-region (match-beginning 0) end
6263 (nth 6 ee) nil)
6264 (backward-char 1)
6265 (throw 'match t))))
6266 nil))))
6268 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6269 "Fontify string S like in Org-mode."
6270 (with-temp-buffer
6271 (insert s)
6272 (let ((org-odd-levels-only odd-levels))
6273 (org-mode)
6274 (font-lock-fontify-buffer)
6275 (buffer-string))))
6277 (defvar org-m nil)
6278 (defvar org-l nil)
6279 (defvar org-f nil)
6280 (defun org-get-level-face (n)
6281 "Get the right face for match N in font-lock matching of headlines."
6282 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6283 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6284 (if org-cycle-level-faces
6285 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6286 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6287 (cond
6288 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6289 ((eq n 2) org-f)
6290 (t (if org-level-color-stars-only nil org-f))))
6293 (defun org-get-todo-face (kwd)
6294 "Get the right face for a TODO keyword KWD.
6295 If KWD is a number, get the corresponding match group."
6296 (if (numberp kwd) (setq kwd (match-string kwd)))
6297 (or (org-face-from-face-or-color
6298 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6299 (and (member kwd org-done-keywords) 'org-done)
6300 'org-todo))
6302 (defun org-face-from-face-or-color (context inherit face-or-color)
6303 "Create a face list that inherits INHERIT, but sets the foreground color.
6304 When FACE-OR-COLOR is not a string, just return it."
6305 (if (stringp face-or-color)
6306 (list :inherit inherit
6307 (cdr (assoc context org-faces-easy-properties))
6308 face-or-color)
6309 face-or-color))
6311 (defun org-font-lock-add-tag-faces (limit)
6312 "Add the special tag faces."
6313 (when (and org-tag-faces org-tags-special-faces-re)
6314 (while (re-search-forward org-tags-special-faces-re limit t)
6315 (add-text-properties (match-beginning 1) (match-end 1)
6316 (list 'face (org-get-tag-face 1)
6317 'font-lock-fontified t))
6318 (backward-char 1))))
6320 (defun org-font-lock-add-priority-faces (limit)
6321 "Add the special priority faces."
6322 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6323 (when (save-match-data (org-at-heading-p))
6324 (add-text-properties
6325 (match-beginning 0) (match-end 0)
6326 (list 'face (or (org-face-from-face-or-color
6327 'priority 'org-priority
6328 (cdr (assoc (char-after (match-beginning 1))
6329 org-priority-faces)))
6330 'org-priority)
6331 'font-lock-fontified t)))))
6333 (defun org-get-tag-face (kwd)
6334 "Get the right face for a TODO keyword KWD.
6335 If KWD is a number, get the corresponding match group."
6336 (if (numberp kwd) (setq kwd (match-string kwd)))
6337 (or (org-face-from-face-or-color
6338 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6339 'org-tag))
6341 (defun org-unfontify-region (beg end &optional maybe_loudly)
6342 "Remove fontification and activation overlays from links."
6343 (font-lock-default-unfontify-region beg end)
6344 (let* ((buffer-undo-list t)
6345 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6346 (inhibit-modification-hooks t)
6347 deactivate-mark buffer-file-name buffer-file-truename)
6348 (org-decompose-region beg end)
6349 (remove-text-properties beg end
6350 '(mouse-face t keymap t org-linked-text t
6351 invisible t intangible t
6352 org-no-flyspell t org-emphasis t))
6353 (org-remove-font-lock-display-properties beg end)))
6355 (defconst org-script-display '(((raise -0.3) (height 0.7))
6356 ((raise 0.3) (height 0.7))
6357 ((raise -0.5))
6358 ((raise 0.5)))
6359 "Display properties for showing superscripts and subscripts.")
6361 (defun org-remove-font-lock-display-properties (beg end)
6362 "Remove specific display properties that have been added by font lock.
6363 The will remove the raise properties that are used to show superscripts
6364 and subscripts."
6365 (let (next prop)
6366 (while (< beg end)
6367 (setq next (next-single-property-change beg 'display nil end)
6368 prop (get-text-property beg 'display))
6369 (if (member prop org-script-display)
6370 (put-text-property beg next 'display nil))
6371 (setq beg next))))
6373 (defun org-raise-scripts (limit)
6374 "Add raise properties to sub/superscripts."
6375 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6376 (if (re-search-forward
6377 (if (eq org-use-sub-superscripts t)
6378 org-match-substring-regexp
6379 org-match-substring-with-braces-regexp)
6380 limit t)
6381 (let* ((pos (point)) table-p comment-p
6382 (mpos (match-beginning 3))
6383 (emph-p (get-text-property mpos 'org-emphasis))
6384 (link-p (get-text-property mpos 'mouse-face))
6385 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6386 (goto-char (point-at-bol))
6387 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6388 comment-p (org-looking-at-p "[ \t]*#"))
6389 (goto-char pos)
6390 ;; FIXME: Should we go back one character here, for a_b^c
6391 ;; (goto-char (1- pos)) ;????????????????????
6392 (if (or comment-p emph-p link-p keyw-p)
6394 (put-text-property (match-beginning 3) (match-end 0)
6395 'display
6396 (if (equal (char-after (match-beginning 2)) ?^)
6397 (nth (if table-p 3 1) org-script-display)
6398 (nth (if table-p 2 0) org-script-display)))
6399 (add-text-properties (match-beginning 2) (match-end 2)
6400 (list 'invisible t
6401 'org-dwidth t 'org-dwidth-n 1))
6402 (if (and (eq (char-after (match-beginning 3)) ?{)
6403 (eq (char-before (match-end 3)) ?}))
6404 (progn
6405 (add-text-properties
6406 (match-beginning 3) (1+ (match-beginning 3))
6407 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6408 (add-text-properties
6409 (1- (match-end 3)) (match-end 3)
6410 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6411 t)))))
6413 ;;;; Visibility cycling, including org-goto and indirect buffer
6415 ;;; Cycling
6417 (defvar org-cycle-global-status nil)
6418 (make-variable-buffer-local 'org-cycle-global-status)
6419 (put 'org-cycle-global-status 'org-state t)
6420 (defvar org-cycle-subtree-status nil)
6421 (make-variable-buffer-local 'org-cycle-subtree-status)
6422 (put 'org-cycle-subtree-status 'org-state t)
6424 (defvar org-inlinetask-min-level)
6426 ;;;###autoload
6427 (defun org-cycle (&optional arg)
6428 "TAB-action and visibility cycling for Org-mode.
6430 This is the command invoked in Org-mode by the TAB key. Its main purpose
6431 is outline visibility cycling, but it also invokes other actions
6432 in special contexts.
6434 - When this function is called with a prefix argument, rotate the entire
6435 buffer through 3 states (global cycling)
6436 1. OVERVIEW: Show only top-level headlines.
6437 2. CONTENTS: Show all headlines of all levels, but no body text.
6438 3. SHOW ALL: Show everything.
6439 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6440 determined by the variable `org-startup-folded', and by any VISIBILITY
6441 properties in the buffer.
6442 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6443 including any drawers.
6445 - When inside a table, re-align the table and move to the next field.
6447 - When point is at the beginning of a headline, rotate the subtree started
6448 by this line through 3 different states (local cycling)
6449 1. FOLDED: Only the main headline is shown.
6450 2. CHILDREN: The main headline and the direct children are shown.
6451 From this state, you can move to one of the children
6452 and zoom in further.
6453 3. SUBTREE: Show the entire subtree, including body text.
6454 If there is no subtree, switch directly from CHILDREN to FOLDED.
6456 - When point is at the beginning of an empty headline and the variable
6457 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6458 of the headline by demoting and promoting it to likely levels. This
6459 speeds up creation document structure by pressing TAB once or several
6460 times right after creating a new headline.
6462 - When there is a numeric prefix, go up to a heading with level ARG, do
6463 a `show-subtree' and return to the previous cursor position. If ARG
6464 is negative, go up that many levels.
6466 - When point is not at the beginning of a headline, execute the global
6467 binding for TAB, which is re-indenting the line. See the option
6468 `org-cycle-emulate-tab' for details.
6470 - Special case: if point is at the beginning of the buffer and there is
6471 no headline in line 1, this function will act as if called with prefix arg
6472 (C-u TAB, same as S-TAB) also when called without prefix arg.
6473 But only if also the variable `org-cycle-global-at-bob' is t."
6474 (interactive "P")
6475 (org-load-modules-maybe)
6476 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6477 (and org-cycle-level-after-item/entry-creation
6478 (or (org-cycle-level)
6479 (org-cycle-item-indentation))))
6480 (let* (message-log-max ; Don't populate the *Messages* buffer
6481 (limit-level
6482 (or org-cycle-max-level
6483 (and (boundp 'org-inlinetask-min-level)
6484 org-inlinetask-min-level
6485 (1- org-inlinetask-min-level))))
6486 (nstars (and limit-level
6487 (if org-odd-levels-only
6488 (and limit-level (1- (* limit-level 2)))
6489 limit-level)))
6490 (org-outline-regexp
6491 (if (not (derived-mode-p 'org-mode))
6492 outline-regexp
6493 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6494 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6495 (not (looking-at org-outline-regexp))))
6496 (org-cycle-hook
6497 (if bob-special
6498 (delq 'org-optimize-window-after-visibility-change
6499 (copy-sequence org-cycle-hook))
6500 org-cycle-hook))
6501 (pos (point)))
6503 (if (or bob-special (equal arg '(4)))
6504 ;; special case: use global cycling
6505 (setq arg t))
6507 (cond
6509 ((equal arg '(16))
6510 (setq last-command 'dummy)
6511 (org-set-startup-visibility)
6512 (message "Startup visibility, plus VISIBILITY properties"))
6514 ((equal arg '(64))
6515 (show-all)
6516 (message "Entire buffer visible, including drawers"))
6518 ;; Table: enter it or move to the next field.
6519 ((org-at-table-p 'any)
6520 (if (org-at-table.el-p)
6521 (message "Use C-c ' to edit table.el tables")
6522 (if arg (org-table-edit-field t)
6523 (org-table-justify-field-maybe)
6524 (call-interactively 'org-table-next-field))))
6526 ((run-hook-with-args-until-success
6527 'org-tab-after-check-for-table-hook))
6529 ;; Global cycling: delegate to `org-cycle-internal-global'.
6530 ((eq arg t) (org-cycle-internal-global))
6532 ;; Drawers: delegate to `org-flag-drawer'.
6533 ((and org-drawers org-drawer-regexp
6534 (save-excursion
6535 (beginning-of-line 1)
6536 (looking-at org-drawer-regexp)))
6537 (org-flag-drawer ; toggle block visibility
6538 (not (get-char-property (match-end 0) 'invisible))))
6540 ;; Show-subtree, ARG levels up from here.
6541 ((integerp arg)
6542 (save-excursion
6543 (org-back-to-heading)
6544 (outline-up-heading (if (< arg 0) (- arg)
6545 (- (funcall outline-level) arg)))
6546 (org-show-subtree)))
6548 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6549 ((and (featurep 'org-inlinetask)
6550 (org-inlinetask-at-task-p)
6551 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6552 (org-inlinetask-toggle-visibility))
6554 ((org-try-cdlatex-tab))
6556 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6557 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6558 (save-excursion (beginning-of-line 1)
6559 (looking-at org-outline-regexp)))
6560 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6561 (org-cycle-internal-local))
6563 ;; From there: TAB emulation and template completion.
6564 (buffer-read-only (org-back-to-heading))
6566 ((run-hook-with-args-until-success
6567 'org-tab-after-check-for-cycling-hook))
6569 ((org-try-structure-completion))
6571 ((run-hook-with-args-until-success
6572 'org-tab-before-tab-emulation-hook))
6574 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6575 (or (not (bolp))
6576 (not (looking-at org-outline-regexp))))
6577 (call-interactively (global-key-binding "\t")))
6579 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6580 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6581 (or (and (eq org-cycle-emulate-tab 'white)
6582 (= (match-end 0) (point-at-eol)))
6583 (and (eq org-cycle-emulate-tab 'whitestart)
6584 (>= (match-end 0) pos))))
6586 (eq org-cycle-emulate-tab t))
6587 (call-interactively (global-key-binding "\t")))
6589 (t (save-excursion
6590 (org-back-to-heading)
6591 (org-cycle)))))))
6593 (defun org-cycle-internal-global ()
6594 "Do the global cycling action."
6595 ;; Hack to avoid display of messages for .org attachments in Gnus
6596 (let (message-log-max ; Don't populate the *Messages* buffer
6597 (ga (string-match "\\*fontification" (buffer-name))))
6598 (cond
6599 ((and (eq last-command this-command)
6600 (eq org-cycle-global-status 'overview))
6601 ;; We just created the overview - now do table of contents
6602 ;; This can be slow in very large buffers, so indicate action
6603 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6604 (unless ga (message "CONTENTS..."))
6605 (org-content)
6606 (unless ga (message "CONTENTS...done"))
6607 (setq org-cycle-global-status 'contents)
6608 (run-hook-with-args 'org-cycle-hook 'contents))
6610 ((and (eq last-command this-command)
6611 (eq org-cycle-global-status 'contents))
6612 ;; We just showed the table of contents - now show everything
6613 (run-hook-with-args 'org-pre-cycle-hook 'all)
6614 (show-all)
6615 (unless ga (message "SHOW ALL"))
6616 (setq org-cycle-global-status 'all)
6617 (run-hook-with-args 'org-cycle-hook 'all))
6620 ;; Default action: go to overview
6621 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6622 (org-overview)
6623 (unless ga (message "OVERVIEW"))
6624 (setq org-cycle-global-status 'overview)
6625 (run-hook-with-args 'org-cycle-hook 'overview)))))
6627 (defun org-cycle-internal-local ()
6628 "Do the local cycling action."
6629 (let (message-log-max ; Don't populate the *Messages* buffer
6630 (goal-column 0) eoh eol eos has-children children-skipped struct)
6631 ;; First, determine end of headline (EOH), end of subtree or item
6632 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6633 (save-excursion
6634 (if (org-at-item-p)
6635 (progn
6636 (beginning-of-line)
6637 (setq struct (org-list-struct))
6638 (setq eoh (point-at-eol))
6639 (setq eos (org-list-get-item-end-before-blank (point) struct))
6640 (setq has-children (org-list-has-child-p (point) struct)))
6641 (org-back-to-heading)
6642 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6643 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6644 (setq has-children
6645 (or (save-excursion
6646 (let ((level (funcall outline-level)))
6647 (outline-next-heading)
6648 (and (org-at-heading-p t)
6649 (> (funcall outline-level) level))))
6650 (save-excursion
6651 (org-list-search-forward (org-item-beginning-re) eos t)))))
6652 ;; Determine end invisible part of buffer (EOL)
6653 (beginning-of-line 2)
6654 ;; XEmacs doesn't have `next-single-char-property-change'
6655 (if (featurep 'xemacs)
6656 (while (and (not (eobp)) ;; this is like `next-line'
6657 (get-char-property (1- (point)) 'invisible))
6658 (beginning-of-line 2))
6659 (while (and (not (eobp)) ;; this is like `next-line'
6660 (get-char-property (1- (point)) 'invisible))
6661 (goto-char (next-single-char-property-change (point) 'invisible))
6662 (and (eolp) (beginning-of-line 2))))
6663 (setq eol (point)))
6664 ;; Find out what to do next and set `this-command'
6665 (cond
6666 ((= eos eoh)
6667 ;; Nothing is hidden behind this heading
6668 (unless (org-before-first-heading-p)
6669 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6670 (message "EMPTY ENTRY")
6671 (setq org-cycle-subtree-status nil)
6672 (save-excursion
6673 (goto-char eos)
6674 (outline-next-heading)
6675 (if (outline-invisible-p) (org-flag-heading nil))))
6676 ((and (or (>= eol eos)
6677 (not (string-match "\\S-" (buffer-substring eol eos))))
6678 (or has-children
6679 (not (setq children-skipped
6680 org-cycle-skip-children-state-if-no-children))))
6681 ;; Entire subtree is hidden in one line: children view
6682 (unless (org-before-first-heading-p)
6683 (run-hook-with-args 'org-pre-cycle-hook 'children))
6684 (if (org-at-item-p)
6685 (org-list-set-item-visibility (point-at-bol) struct 'children)
6686 (org-show-entry)
6687 (org-with-limited-levels (show-children))
6688 ;; FIXME: This slows down the func way too much.
6689 ;; How keep drawers hidden in subtree anyway?
6690 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6691 ;; (org-cycle-hide-drawers 'subtree))
6693 ;; Fold every list in subtree to top-level items.
6694 (when (eq org-cycle-include-plain-lists 'integrate)
6695 (save-excursion
6696 (org-back-to-heading)
6697 (while (org-list-search-forward (org-item-beginning-re) eos t)
6698 (beginning-of-line 1)
6699 (let* ((struct (org-list-struct))
6700 (prevs (org-list-prevs-alist struct))
6701 (end (org-list-get-bottom-point struct)))
6702 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6703 (org-list-get-all-items (point) struct prevs))
6704 (goto-char end))))))
6705 (message "CHILDREN")
6706 (save-excursion
6707 (goto-char eos)
6708 (outline-next-heading)
6709 (if (outline-invisible-p) (org-flag-heading nil)))
6710 (setq org-cycle-subtree-status 'children)
6711 (unless (org-before-first-heading-p)
6712 (run-hook-with-args 'org-cycle-hook 'children)))
6713 ((or children-skipped
6714 (and (eq last-command this-command)
6715 (eq org-cycle-subtree-status 'children)))
6716 ;; We just showed the children, or no children are there,
6717 ;; now show everything.
6718 (unless (org-before-first-heading-p)
6719 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6720 (outline-flag-region eoh eos nil)
6721 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6722 (setq org-cycle-subtree-status 'subtree)
6723 (unless (org-before-first-heading-p)
6724 (run-hook-with-args 'org-cycle-hook 'subtree)))
6726 ;; Default action: hide the subtree.
6727 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6728 (outline-flag-region eoh eos t)
6729 (message "FOLDED")
6730 (setq org-cycle-subtree-status 'folded)
6731 (unless (org-before-first-heading-p)
6732 (run-hook-with-args 'org-cycle-hook 'folded))))))
6734 ;;;###autoload
6735 (defun org-global-cycle (&optional arg)
6736 "Cycle the global visibility. For details see `org-cycle'.
6737 With \\[universal-argument] prefix arg, switch to startup visibility.
6738 With a numeric prefix, show all headlines up to that level."
6739 (interactive "P")
6740 (let ((org-cycle-include-plain-lists
6741 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6742 (cond
6743 ((integerp arg)
6744 (show-all)
6745 (hide-sublevels arg)
6746 (setq org-cycle-global-status 'contents))
6747 ((equal arg '(4))
6748 (org-set-startup-visibility)
6749 (message "Startup visibility, plus VISIBILITY properties."))
6751 (org-cycle '(4))))))
6753 (defun org-set-startup-visibility ()
6754 "Set the visibility required by startup options and properties."
6755 (cond
6756 ((eq org-startup-folded t)
6757 (org-cycle '(4)))
6758 ((eq org-startup-folded 'content)
6759 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6760 (org-cycle '(4)) (org-cycle '(4)))))
6761 (unless (eq org-startup-folded 'showeverything)
6762 (if org-hide-block-startup (org-hide-block-all))
6763 (org-set-visibility-according-to-property 'no-cleanup)
6764 (org-cycle-hide-archived-subtrees 'all)
6765 (org-cycle-hide-drawers 'all)
6766 (org-cycle-show-empty-lines t)))
6768 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6769 "Switch subtree visibilities according to :VISIBILITY: property."
6770 (interactive)
6771 (let (org-show-entry-below state)
6772 (save-excursion
6773 (goto-char (point-min))
6774 (while (re-search-forward
6775 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6776 nil t)
6777 (setq state (match-string 1))
6778 (save-excursion
6779 (org-back-to-heading t)
6780 (hide-subtree)
6781 (org-reveal)
6782 (cond
6783 ((equal state '("fold" "folded"))
6784 (hide-subtree))
6785 ((equal state "children")
6786 (org-show-hidden-entry)
6787 (show-children))
6788 ((equal state "content")
6789 (save-excursion
6790 (save-restriction
6791 (org-narrow-to-subtree)
6792 (org-content))))
6793 ((member state '("all" "showall"))
6794 (show-subtree)))))
6795 (unless no-cleanup
6796 (org-cycle-hide-archived-subtrees 'all)
6797 (org-cycle-hide-drawers 'all)
6798 (org-cycle-show-empty-lines 'all)))))
6800 ;; This function uses outline-regexp instead of the more fundamental
6801 ;; org-outline-regexp so that org-cycle-global works outside of Org
6802 ;; buffers, where outline-regexp is needed.
6803 (defun org-overview ()
6804 "Switch to overview mode, showing only top-level headlines.
6805 Really, this shows all headlines with level equal or greater than the level
6806 of the first headline in the buffer. This is important, because if the
6807 first headline is not level one, then (hide-sublevels 1) gives confusing
6808 results."
6809 (interactive)
6810 (let ((l (org-current-line))
6811 (level (save-excursion
6812 (goto-char (point-min))
6813 (if (re-search-forward (concat "^" outline-regexp) nil t)
6814 (progn
6815 (goto-char (match-beginning 0))
6816 (funcall outline-level))))))
6817 (and level (hide-sublevels level))
6818 (recenter '(4))
6819 (org-goto-line l)))
6821 (defun org-content (&optional arg)
6822 "Show all headlines in the buffer, like a table of contents.
6823 With numerical argument N, show content up to level N."
6824 (interactive "P")
6825 (save-excursion
6826 ;; Visit all headings and show their offspring
6827 (and (integerp arg) (org-overview))
6828 (goto-char (point-max))
6829 (catch 'exit
6830 (while (and (progn (condition-case nil
6831 (outline-previous-visible-heading 1)
6832 (error (goto-char (point-min))))
6834 (looking-at org-outline-regexp))
6835 (if (integerp arg)
6836 (show-children (1- arg))
6837 (show-branches))
6838 (if (bobp) (throw 'exit nil))))))
6841 (defun org-optimize-window-after-visibility-change (state)
6842 "Adjust the window after a change in outline visibility.
6843 This function is the default value of the hook `org-cycle-hook'."
6844 (when (get-buffer-window (current-buffer))
6845 (cond
6846 ((eq state 'content) nil)
6847 ((eq state 'all) nil)
6848 ((eq state 'folded) nil)
6849 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6850 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6852 (defun org-remove-empty-overlays-at (pos)
6853 "Remove outline overlays that do not contain non-white stuff."
6854 (mapc
6855 (lambda (o)
6856 (and (eq 'outline (overlay-get o 'invisible))
6857 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6858 (overlay-end o))))
6859 (delete-overlay o)))
6860 (overlays-at pos)))
6862 (defun org-clean-visibility-after-subtree-move ()
6863 "Fix visibility issues after moving a subtree."
6864 ;; First, find a reasonable region to look at:
6865 ;; Start two siblings above, end three below
6866 (let* ((beg (save-excursion
6867 (and (org-get-last-sibling)
6868 (org-get-last-sibling))
6869 (point)))
6870 (end (save-excursion
6871 (and (org-get-next-sibling)
6872 (org-get-next-sibling)
6873 (org-get-next-sibling))
6874 (if (org-at-heading-p)
6875 (point-at-eol)
6876 (point))))
6877 (level (looking-at "\\*+"))
6878 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6879 (save-excursion
6880 (save-restriction
6881 (narrow-to-region beg end)
6882 (when re
6883 ;; Properly fold already folded siblings
6884 (goto-char (point-min))
6885 (while (re-search-forward re nil t)
6886 (if (and (not (outline-invisible-p))
6887 (save-excursion
6888 (goto-char (point-at-eol)) (outline-invisible-p)))
6889 (hide-entry))))
6890 (org-cycle-show-empty-lines 'overview)
6891 (org-cycle-hide-drawers 'overview)))))
6893 (defun org-cycle-show-empty-lines (state)
6894 "Show empty lines above all visible headlines.
6895 The region to be covered depends on STATE when called through
6896 `org-cycle-hook'. Lisp program can use t for STATE to get the
6897 entire buffer covered. Note that an empty line is only shown if there
6898 are at least `org-cycle-separator-lines' empty lines before the headline."
6899 (when (not (= org-cycle-separator-lines 0))
6900 (save-excursion
6901 (let* ((n (abs org-cycle-separator-lines))
6902 (re (cond
6903 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6904 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6905 (t (let ((ns (number-to-string (- n 2))))
6906 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6907 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6908 beg end b e)
6909 (cond
6910 ((memq state '(overview contents t))
6911 (setq beg (point-min) end (point-max)))
6912 ((memq state '(children folded))
6913 (setq beg (point) end (progn (org-end-of-subtree t t)
6914 (beginning-of-line 2)
6915 (point)))))
6916 (when beg
6917 (goto-char beg)
6918 (while (re-search-forward re end t)
6919 (unless (get-char-property (match-end 1) 'invisible)
6920 (setq e (match-end 1))
6921 (if (< org-cycle-separator-lines 0)
6922 (setq b (save-excursion
6923 (goto-char (match-beginning 0))
6924 (org-back-over-empty-lines)
6925 (if (save-excursion
6926 (goto-char (max (point-min) (1- (point))))
6927 (org-at-heading-p))
6928 (1- (point))
6929 (point))))
6930 (setq b (match-beginning 1)))
6931 (outline-flag-region b e nil)))))))
6932 ;; Never hide empty lines at the end of the file.
6933 (save-excursion
6934 (goto-char (point-max))
6935 (outline-previous-heading)
6936 (outline-end-of-heading)
6937 (if (and (looking-at "[ \t\n]+")
6938 (= (match-end 0) (point-max)))
6939 (outline-flag-region (point) (match-end 0) nil))))
6941 (defun org-show-empty-lines-in-parent ()
6942 "Move to the parent and re-show empty lines before visible headlines."
6943 (save-excursion
6944 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6945 (org-cycle-show-empty-lines context))))
6947 (defun org-files-list ()
6948 "Return `org-agenda-files' list, plus all open org-mode files.
6949 This is useful for operations that need to scan all of a user's
6950 open and agenda-wise Org files."
6951 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6952 (dolist (buf (buffer-list))
6953 (with-current-buffer buf
6954 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6955 (let ((file (expand-file-name (buffer-file-name))))
6956 (unless (member file files)
6957 (push file files))))))
6958 files))
6960 (defsubst org-entry-beginning-position ()
6961 "Return the beginning position of the current entry."
6962 (save-excursion (outline-back-to-heading t) (point)))
6964 (defsubst org-entry-end-position ()
6965 "Return the end position of the current entry."
6966 (save-excursion (outline-next-heading) (point)))
6968 (defun org-cycle-hide-drawers (state)
6969 "Re-hide all drawers after a visibility state change."
6970 (when (and (derived-mode-p 'org-mode)
6971 (not (memq state '(overview folded contents))))
6972 (save-excursion
6973 (let* ((globalp (memq state '(contents all)))
6974 (beg (if globalp (point-min) (point)))
6975 (end (if globalp (point-max)
6976 (if (eq state 'children)
6977 (save-excursion (outline-next-heading) (point))
6978 (org-end-of-subtree t)))))
6979 (goto-char beg)
6980 (while (re-search-forward org-drawer-regexp end t)
6981 (org-flag-drawer t))))))
6983 (defun org-cycle-hide-inline-tasks (state)
6984 "Re-hide inline task when switching to 'contents visibility state."
6985 (when (and (eq state 'contents)
6986 (boundp 'org-inlinetask-min-level)
6987 org-inlinetask-min-level)
6988 (hide-sublevels (1- org-inlinetask-min-level))))
6990 (defun org-flag-drawer (flag)
6991 "When FLAG is non-nil, hide the drawer we are within.
6992 Otherwise make it visible."
6993 (save-excursion
6994 (beginning-of-line 1)
6995 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6996 (let ((b (match-end 0)))
6997 (if (re-search-forward
6998 "^[ \t]*:END:"
6999 (save-excursion (outline-next-heading) (point)) t)
7000 (outline-flag-region b (point-at-eol) flag)
7001 (error ":END: line missing at position %s" b))))))
7003 (defun org-subtree-end-visible-p ()
7004 "Is the end of the current subtree visible?"
7005 (pos-visible-in-window-p
7006 (save-excursion (org-end-of-subtree t) (point))))
7008 (defun org-first-headline-recenter (&optional N)
7009 "Move cursor to the first headline and recenter the headline.
7010 Optional argument N means put the headline into the Nth line of the window."
7011 (goto-char (point-min))
7012 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7013 (beginning-of-line)
7014 (recenter (prefix-numeric-value N))))
7016 ;;; Saving and restoring visibility
7018 (defun org-outline-overlay-data (&optional use-markers)
7019 "Return a list of the locations of all outline overlays.
7020 These are overlays with the `invisible' property value `outline'.
7021 The return value is a list of cons cells, with start and stop
7022 positions for each overlay.
7023 If USE-MARKERS is set, return the positions as markers."
7024 (let (beg end)
7025 (save-excursion
7026 (save-restriction
7027 (widen)
7028 (delq nil
7029 (mapcar (lambda (o)
7030 (when (eq (overlay-get o 'invisible) 'outline)
7031 (setq beg (overlay-start o)
7032 end (overlay-end o))
7033 (and beg end (> end beg)
7034 (if use-markers
7035 (cons (move-marker (make-marker) beg)
7036 (move-marker (make-marker) end))
7037 (cons beg end)))))
7038 (overlays-in (point-min) (point-max))))))))
7040 (defun org-set-outline-overlay-data (data)
7041 "Create visibility overlays for all positions in DATA.
7042 DATA should have been made by `org-outline-overlay-data'."
7043 (let (o)
7044 (save-excursion
7045 (save-restriction
7046 (widen)
7047 (show-all)
7048 (mapc (lambda (c)
7049 (outline-flag-region (car c) (cdr c) t))
7050 data)))))
7052 ;;; Folding of blocks
7054 (defvar org-hide-block-overlays nil
7055 "Overlays hiding blocks.")
7056 (make-variable-buffer-local 'org-hide-block-overlays)
7058 (defun org-block-map (function &optional start end)
7059 "Call FUNCTION at the head of all source blocks in the current buffer.
7060 Optional arguments START and END can be used to limit the range."
7061 (let ((start (or start (point-min)))
7062 (end (or end (point-max))))
7063 (save-excursion
7064 (goto-char start)
7065 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7066 (save-excursion
7067 (save-match-data
7068 (goto-char (match-beginning 0))
7069 (funcall function)))))))
7071 (defun org-hide-block-toggle-all ()
7072 "Toggle the visibility of all blocks in the current buffer."
7073 (org-block-map #'org-hide-block-toggle))
7075 (defun org-hide-block-all ()
7076 "Fold all blocks in the current buffer."
7077 (interactive)
7078 (org-show-block-all)
7079 (org-block-map #'org-hide-block-toggle-maybe))
7081 (defun org-show-block-all ()
7082 "Unfold all blocks in the current buffer."
7083 (interactive)
7084 (mapc 'delete-overlay org-hide-block-overlays)
7085 (setq org-hide-block-overlays nil))
7087 (defun org-hide-block-toggle-maybe ()
7088 "Toggle visibility of block at point."
7089 (interactive)
7090 (let ((case-fold-search t))
7091 (if (save-excursion
7092 (beginning-of-line 1)
7093 (looking-at org-block-regexp))
7094 (progn (org-hide-block-toggle)
7095 t) ;; to signal that we took action
7096 nil))) ;; to signal that we did not
7098 (defun org-hide-block-toggle (&optional force)
7099 "Toggle the visibility of the current block."
7100 (interactive)
7101 (save-excursion
7102 (beginning-of-line)
7103 (if (re-search-forward org-block-regexp nil t)
7104 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7105 (end (match-end 0)) ;; end of entire body
7107 (if (memq t (mapcar (lambda (overlay)
7108 (eq (overlay-get overlay 'invisible)
7109 'org-hide-block))
7110 (overlays-at start)))
7111 (if (or (not force) (eq force 'off))
7112 (mapc (lambda (ov)
7113 (when (member ov org-hide-block-overlays)
7114 (setq org-hide-block-overlays
7115 (delq ov org-hide-block-overlays)))
7116 (when (eq (overlay-get ov 'invisible)
7117 'org-hide-block)
7118 (delete-overlay ov)))
7119 (overlays-at start)))
7120 (setq ov (make-overlay start end))
7121 (overlay-put ov 'invisible 'org-hide-block)
7122 ;; make the block accessible to isearch
7123 (overlay-put
7124 ov 'isearch-open-invisible
7125 (lambda (ov)
7126 (when (member ov org-hide-block-overlays)
7127 (setq org-hide-block-overlays
7128 (delq ov org-hide-block-overlays)))
7129 (when (eq (overlay-get ov 'invisible)
7130 'org-hide-block)
7131 (delete-overlay ov))))
7132 (push ov org-hide-block-overlays)))
7133 (error "Not looking at a source block"))))
7135 ;; org-tab-after-check-for-cycling-hook
7136 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7137 ;; Remove overlays when changing major mode
7138 (add-hook 'org-mode-hook
7139 (lambda () (org-add-hook 'change-major-mode-hook
7140 'org-show-block-all 'append 'local)))
7142 ;;; Org-goto
7144 (defvar org-goto-window-configuration nil)
7145 (defvar org-goto-marker nil)
7146 (defvar org-goto-map)
7147 (defun org-goto-map ()
7148 "Set the keymap `org-goto'."
7149 (setq org-goto-map
7150 (let ((map (make-sparse-keymap)))
7151 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7152 mouse-drag-region universal-argument org-occur))
7153 cmd)
7154 (while (setq cmd (pop cmds))
7155 (substitute-key-definition cmd cmd map global-map)))
7156 (suppress-keymap map)
7157 (org-defkey map "\C-m" 'org-goto-ret)
7158 (org-defkey map [(return)] 'org-goto-ret)
7159 (org-defkey map [(left)] 'org-goto-left)
7160 (org-defkey map [(right)] 'org-goto-right)
7161 (org-defkey map [(control ?g)] 'org-goto-quit)
7162 (org-defkey map "\C-i" 'org-cycle)
7163 (org-defkey map [(tab)] 'org-cycle)
7164 (org-defkey map [(down)] 'outline-next-visible-heading)
7165 (org-defkey map [(up)] 'outline-previous-visible-heading)
7166 (if org-goto-auto-isearch
7167 (if (fboundp 'define-key-after)
7168 (define-key-after map [t] 'org-goto-local-auto-isearch)
7169 nil)
7170 (org-defkey map "q" 'org-goto-quit)
7171 (org-defkey map "n" 'outline-next-visible-heading)
7172 (org-defkey map "p" 'outline-previous-visible-heading)
7173 (org-defkey map "f" 'outline-forward-same-level)
7174 (org-defkey map "b" 'outline-backward-same-level)
7175 (org-defkey map "u" 'outline-up-heading))
7176 (org-defkey map "/" 'org-occur)
7177 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7178 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7179 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7180 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7181 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7182 map)))
7184 (defconst org-goto-help
7185 "Browse buffer copy, to find location or copy text.%s
7186 RET=jump to location C-g=quit and return to previous location
7187 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7189 (defvar org-goto-start-pos) ; dynamically scoped parameter
7191 (defun org-goto (&optional alternative-interface)
7192 "Look up a different location in the current file, keeping current visibility.
7194 When you want look-up or go to a different location in a
7195 document, the fastest way is often to fold the entire buffer and
7196 then dive into the tree. This method has the disadvantage, that
7197 the previous location will be folded, which may not be what you
7198 want.
7200 This command works around this by showing a copy of the current
7201 buffer in an indirect buffer, in overview mode. You can dive
7202 into the tree in that copy, use org-occur and incremental search
7203 to find a location. When pressing RET or `Q', the command
7204 returns to the original buffer in which the visibility is still
7205 unchanged. After RET it will also jump to the location selected
7206 in the indirect buffer and expose the headline hierarchy above.
7208 With a prefix argument, use the alternative interface: e.g. if
7209 `org-goto-interface' is 'outline use 'outline-path-completion."
7210 (interactive "P")
7211 (org-goto-map)
7212 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7213 (org-refile-use-outline-path t)
7214 (org-refile-target-verify-function nil)
7215 (interface
7216 (if (not alternative-interface)
7217 org-goto-interface
7218 (if (eq org-goto-interface 'outline)
7219 'outline-path-completion
7220 'outline)))
7221 (org-goto-start-pos (point))
7222 (selected-point
7223 (if (eq interface 'outline)
7224 (car (org-get-location (current-buffer) org-goto-help))
7225 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7226 (org-refile-check-position pa)
7227 (nth 3 pa)))))
7228 (if selected-point
7229 (progn
7230 (org-mark-ring-push org-goto-start-pos)
7231 (goto-char selected-point)
7232 (if (or (outline-invisible-p) (org-invisible-p2))
7233 (org-show-context 'org-goto)))
7234 (message "Quit"))))
7236 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7237 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7238 (defvar org-goto-local-auto-isearch-map) ; defined below
7240 (defun org-get-location (buf help)
7241 "Let the user select a location in the Org-mode buffer BUF.
7242 This function uses a recursive edit. It returns the selected position
7243 or nil."
7244 (org-no-popups
7245 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7246 (isearch-hide-immediately nil)
7247 (isearch-search-fun-function
7248 (lambda () 'org-goto-local-search-headings))
7249 (org-goto-selected-point org-goto-exit-command))
7250 (save-excursion
7251 (save-window-excursion
7252 (delete-other-windows)
7253 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7254 (org-pop-to-buffer-same-window
7255 (condition-case nil
7256 (make-indirect-buffer (current-buffer) "*org-goto*")
7257 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7258 (with-output-to-temp-buffer "*Org Help*"
7259 (princ (format help (if org-goto-auto-isearch
7260 " Just type for auto-isearch."
7261 " n/p/f/b/u to navigate, q to quit."))))
7262 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7263 (setq buffer-read-only nil)
7264 (let ((org-startup-truncated t)
7265 (org-startup-folded nil)
7266 (org-startup-align-all-tables nil))
7267 (org-mode)
7268 (org-overview))
7269 (setq buffer-read-only t)
7270 (if (and (boundp 'org-goto-start-pos)
7271 (integer-or-marker-p org-goto-start-pos))
7272 (let ((org-show-hierarchy-above t)
7273 (org-show-siblings t)
7274 (org-show-following-heading t))
7275 (goto-char org-goto-start-pos)
7276 (and (outline-invisible-p) (org-show-context)))
7277 (goto-char (point-min)))
7278 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7279 (message "Select location and press RET")
7280 (use-local-map org-goto-map)
7281 (recursive-edit)))
7282 (kill-buffer "*org-goto*")
7283 (cons org-goto-selected-point org-goto-exit-command))))
7285 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7286 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7287 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7288 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7290 (defun org-goto-local-search-headings (string bound noerror)
7291 "Search and make sure that any matches are in headlines."
7292 (catch 'return
7293 (while (if isearch-forward
7294 (search-forward string bound noerror)
7295 (search-backward string bound noerror))
7296 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7297 (and (member :headline context)
7298 (not (member :tags context))))
7299 (throw 'return (point))))))
7301 (defun org-goto-local-auto-isearch ()
7302 "Start isearch."
7303 (interactive)
7304 (goto-char (point-min))
7305 (let ((keys (this-command-keys)))
7306 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7307 (isearch-mode t)
7308 (isearch-process-search-char (string-to-char keys)))))
7310 (defun org-goto-ret (&optional arg)
7311 "Finish `org-goto' by going to the new location."
7312 (interactive "P")
7313 (setq org-goto-selected-point (point)
7314 org-goto-exit-command 'return)
7315 (throw 'exit nil))
7317 (defun org-goto-left ()
7318 "Finish `org-goto' by going to the new location."
7319 (interactive)
7320 (if (org-at-heading-p)
7321 (progn
7322 (beginning-of-line 1)
7323 (setq org-goto-selected-point (point)
7324 org-goto-exit-command 'left)
7325 (throw 'exit nil))
7326 (error "Not on a heading")))
7328 (defun org-goto-right ()
7329 "Finish `org-goto' by going to the new location."
7330 (interactive)
7331 (if (org-at-heading-p)
7332 (progn
7333 (setq org-goto-selected-point (point)
7334 org-goto-exit-command 'right)
7335 (throw 'exit nil))
7336 (error "Not on a heading")))
7338 (defun org-goto-quit ()
7339 "Finish `org-goto' without cursor motion."
7340 (interactive)
7341 (setq org-goto-selected-point nil)
7342 (setq org-goto-exit-command 'quit)
7343 (throw 'exit nil))
7345 ;;; Indirect buffer display of subtrees
7347 (defvar org-indirect-dedicated-frame nil
7348 "This is the frame being used for indirect tree display.")
7349 (defvar org-last-indirect-buffer nil)
7351 (defun org-tree-to-indirect-buffer (&optional arg)
7352 "Create indirect buffer and narrow it to current subtree.
7353 With a numerical prefix ARG, go up to this level and then take that tree.
7354 If ARG is negative, go up that many levels.
7356 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7357 indirect buffer previously made with this command, to avoid proliferation of
7358 indirect buffers. However, when you call the command with a \
7359 \\[universal-argument] prefix, or
7360 when `org-indirect-buffer-display' is `new-frame', the last buffer
7361 is kept so that you can work with several indirect buffers at the same time.
7362 If `org-indirect-buffer-display' is `dedicated-frame', the \
7363 \\[universal-argument] prefix also
7364 requests that a new frame be made for the new buffer, so that the dedicated
7365 frame is not changed."
7366 (interactive "P")
7367 (let ((cbuf (current-buffer))
7368 (cwin (selected-window))
7369 (pos (point))
7370 beg end level heading ibuf)
7371 (save-excursion
7372 (org-back-to-heading t)
7373 (when (numberp arg)
7374 (setq level (org-outline-level))
7375 (if (< arg 0) (setq arg (+ level arg)))
7376 (while (> (setq level (org-outline-level)) arg)
7377 (org-up-heading-safe)))
7378 (setq beg (point)
7379 heading (org-get-heading))
7380 (org-end-of-subtree t t)
7381 (if (org-at-heading-p) (backward-char 1))
7382 (setq end (point)))
7383 (if (and (buffer-live-p org-last-indirect-buffer)
7384 (not (eq org-indirect-buffer-display 'new-frame))
7385 (not arg))
7386 (kill-buffer org-last-indirect-buffer))
7387 (setq ibuf (org-get-indirect-buffer cbuf)
7388 org-last-indirect-buffer ibuf)
7389 (cond
7390 ((or (eq org-indirect-buffer-display 'new-frame)
7391 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7392 (select-frame (make-frame))
7393 (delete-other-windows)
7394 (org-pop-to-buffer-same-window ibuf)
7395 (org-set-frame-title heading))
7396 ((eq org-indirect-buffer-display 'dedicated-frame)
7397 (raise-frame
7398 (select-frame (or (and org-indirect-dedicated-frame
7399 (frame-live-p org-indirect-dedicated-frame)
7400 org-indirect-dedicated-frame)
7401 (setq org-indirect-dedicated-frame (make-frame)))))
7402 (delete-other-windows)
7403 (org-pop-to-buffer-same-window ibuf)
7404 (org-set-frame-title (concat "Indirect: " heading)))
7405 ((eq org-indirect-buffer-display 'current-window)
7406 (org-pop-to-buffer-same-window ibuf))
7407 ((eq org-indirect-buffer-display 'other-window)
7408 (pop-to-buffer ibuf))
7409 (t (error "Invalid value")))
7410 (if (featurep 'xemacs)
7411 (save-excursion (org-mode) (turn-on-font-lock)))
7412 (narrow-to-region beg end)
7413 (show-all)
7414 (goto-char pos)
7415 (run-hook-with-args 'org-cycle-hook 'all)
7416 (and (window-live-p cwin) (select-window cwin))))
7418 (defun org-get-indirect-buffer (&optional buffer)
7419 (setq buffer (or buffer (current-buffer)))
7420 (let ((n 1) (base (buffer-name buffer)) bname)
7421 (while (buffer-live-p
7422 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7423 (setq n (1+ n)))
7424 (condition-case nil
7425 (make-indirect-buffer buffer bname 'clone)
7426 (error (make-indirect-buffer buffer bname)))))
7428 (defun org-set-frame-title (title)
7429 "Set the title of the current frame to the string TITLE."
7430 ;; FIXME: how to name a single frame in XEmacs???
7431 (unless (featurep 'xemacs)
7432 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7434 ;;;; Structure editing
7436 ;;; Inserting headlines
7438 (defun org-previous-line-empty-p (&optional next)
7439 "Is the previous line a blank line?
7440 When NEXT is non-nil, check the next line instead."
7441 (save-excursion
7442 (and (not (bobp))
7443 (or (beginning-of-line (if next 2 0)) t)
7444 (save-match-data
7445 (looking-at "[ \t]*$")))))
7447 (defun org-insert-heading (&optional arg invisible-ok)
7448 "Insert a new heading or item with same depth at point.
7449 If point is in a plain list and ARG is nil, create a new list item.
7450 With one universal prefix argument, insert a heading even in lists.
7451 With two universal prefix arguments, insert the heading at the end
7452 of the parent subtree.
7454 If point is at the beginning of a headline, insert a sibling before
7455 the current headline. If point is not at the beginning, split the line
7456 and create a new headline with the text in the current line after point
7457 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7459 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7460 This is important for non-interactive uses of the command."
7461 (interactive "P")
7462 (cond
7463 ((or (= (buffer-size) 0)
7464 (and (not (save-excursion
7465 (and (ignore-errors (org-back-to-heading invisible-ok))
7466 (org-at-heading-p))))
7467 (or arg (not (org-in-item-p)))))
7468 (insert
7469 (if (org-previous-line-empty-p) "" "\n")
7470 (if (org-in-src-block-p) ",* " "* "))
7471 (run-hooks 'org-insert-heading-hook))
7472 ((or arg (not (org-insert-item
7473 (save-excursion
7474 (beginning-of-line)
7475 (looking-at org-list-full-item-re)
7476 (match-string 3)))))
7477 (let (begn endn)
7478 (when (org-buffer-narrowed-p)
7479 (setq begn (point-min) endn (point-max))
7480 (widen))
7481 (let* ((empty-line-p nil)
7482 (eops (equal arg '(16))) ; insert at end of parent subtree
7483 (org-insert-heading-respect-content
7484 (or (not (null arg)) org-insert-heading-respect-content))
7485 (level nil)
7486 (on-heading (org-at-heading-p))
7487 (head (save-excursion
7488 (condition-case nil
7489 (progn
7490 (org-back-to-heading invisible-ok)
7491 (when (and (not on-heading)
7492 (featurep 'org-inlinetask)
7493 (integerp org-inlinetask-min-level)
7494 (>= (length (match-string 0))
7495 org-inlinetask-min-level))
7496 ;; Find a heading level before the inline task
7497 (while (and (setq level (org-up-heading-safe))
7498 (>= level org-inlinetask-min-level)))
7499 (if (org-at-heading-p)
7500 (org-back-to-heading invisible-ok)
7501 (error "This should not happen")))
7502 (unless (and (save-excursion
7503 (save-match-data
7504 (org-backward-heading-same-level 1 invisible-ok))
7505 (= (point) (match-beginning 0)))
7506 (not (org-previous-line-empty-p t)))
7507 (setq empty-line-p (org-previous-line-empty-p)))
7508 (match-string 0))
7509 (error "* "))))
7510 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7511 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7512 pos hide-previous previous-pos)
7513 (if ;; At the beginning of a heading, open a new line for insertiong
7514 (and (bolp) (org-at-heading-p)
7515 (not eops)
7516 (or (bobp)
7517 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7518 (open-line (if blank 2 1))
7519 (save-excursion
7520 (setq previous-pos (point-at-bol))
7521 (end-of-line)
7522 (setq hide-previous (outline-invisible-p)))
7523 (and org-insert-heading-respect-content
7524 (save-excursion
7525 (while (outline-invisible-p)
7526 (org-show-subtree)
7527 (org-up-heading-safe))))
7528 (let ((split
7529 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7530 (save-excursion
7531 (let ((p (point)))
7532 (goto-char (point-at-bol))
7533 (and (looking-at org-complex-heading-regexp)
7534 (match-beginning 4)
7535 (> p (match-beginning 4)))))))
7536 tags pos)
7537 (cond
7538 ;; Insert a new line, possibly at end of parent subtree
7539 (org-insert-heading-respect-content
7540 (if (not eops)
7541 (progn
7542 (org-end-of-subtree nil t)
7543 (and (looking-at "^\\*") (backward-char 1))
7544 (while (and (not (bobp))
7545 ;; Don't delete spaces in empty headlines
7546 (not (looking-back org-outline-regexp))
7547 (member (char-before) '(?\ ?\t ?\n)))
7548 (backward-delete-char 1)))
7549 (let ((p (point)))
7550 (org-up-heading-safe)
7551 (if (= p (point))
7552 (goto-char (point-max))
7553 (org-end-of-subtree nil t))))
7554 (when (featurep 'org-inlinetask)
7555 (while (and (not (eobp))
7556 (looking-at "\\(\\*+\\)[ \t]+")
7557 (>= (length (match-string 1))
7558 org-inlinetask-min-level))
7559 (org-end-of-subtree nil t)))
7560 (or (bolp) (newline))
7561 (or (org-previous-line-empty-p)
7562 (and blank (newline)))
7563 (if (or empty-line-p eops) (open-line 1)))
7564 ;; Insert a headling containing text after point
7565 ((org-at-heading-p)
7566 (when hide-previous
7567 (show-children)
7568 (org-show-entry))
7569 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7570 (setq tags (and (match-end 2) (match-string 2)))
7571 (and (match-end 1)
7572 (delete-region (match-beginning 1) (match-end 1)))
7573 (setq pos (point-at-bol))
7574 (or split (end-of-line 1))
7575 (delete-horizontal-space)
7576 (if (string-match "\\`\\*+\\'"
7577 (buffer-substring (point-at-bol) (point)))
7578 (insert " "))
7579 (newline (if blank 2 1))
7580 (when tags
7581 (save-excursion
7582 (goto-char pos)
7583 (end-of-line 1)
7584 (insert " " tags)
7585 (org-set-tags nil 'align))))
7587 (or split (end-of-line 1))
7588 (newline (if blank 2 1))))))
7589 (insert head) (just-one-space)
7590 (setq pos (point))
7591 (end-of-line 1)
7592 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7593 (when (and org-insert-heading-respect-content hide-previous)
7594 (save-excursion
7595 (goto-char previous-pos)
7596 (hide-subtree)))
7597 (when (and begn endn)
7598 (narrow-to-region (min (point) begn) (max (point) endn)))
7599 (run-hooks 'org-insert-heading-hook))))))
7601 (defun org-get-heading (&optional no-tags no-todo)
7602 "Return the heading of the current entry, without the stars.
7603 When NO-TAGS is non-nil, don't include tags.
7604 When NO-TODO is non-nil, don't include TODO keywords."
7605 (save-excursion
7606 (org-back-to-heading t)
7607 (cond
7608 ((and no-tags no-todo)
7609 (looking-at org-complex-heading-regexp)
7610 (match-string 4))
7611 (no-tags
7612 (looking-at (concat org-outline-regexp
7613 "\\(.*?\\)"
7614 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7615 (match-string 1))
7616 (no-todo
7617 (looking-at org-todo-line-regexp)
7618 (match-string 3))
7619 (t (looking-at org-heading-regexp)
7620 (match-string 2)))))
7622 (defvar orgstruct-mode) ; defined below
7624 (defun org-heading-components ()
7625 "Return the components of the current heading.
7626 This is a list with the following elements:
7627 - the level as an integer
7628 - the reduced level, different if `org-odd-levels-only' is set.
7629 - the TODO keyword, or nil
7630 - the priority character, like ?A, or nil if no priority is given
7631 - the headline text itself, or the tags string if no headline text
7632 - the tags string, or nil."
7633 (save-excursion
7634 (org-back-to-heading t)
7635 (if (let (case-fold-search)
7636 (looking-at
7637 (if orgstruct-mode
7638 org-heading-regexp
7639 org-complex-heading-regexp)))
7640 (if orgstruct-mode
7641 (list (length (match-string 1))
7642 (org-reduced-level (length (match-string 1)))
7645 (match-string 2)
7646 nil)
7647 (list (length (match-string 1))
7648 (org-reduced-level (length (match-string 1)))
7649 (org-match-string-no-properties 2)
7650 (and (match-end 3) (aref (match-string 3) 2))
7651 (org-match-string-no-properties 4)
7652 (org-match-string-no-properties 5))))))
7654 (defun org-get-entry ()
7655 "Get the entry text, after heading, entire subtree."
7656 (save-excursion
7657 (org-back-to-heading t)
7658 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7660 (defun org-insert-heading-after-current ()
7661 "Insert a new heading with same level as current, after current subtree."
7662 (interactive)
7663 (org-back-to-heading)
7664 (org-insert-heading)
7665 (org-move-subtree-down)
7666 (end-of-line 1))
7668 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7669 "Insert heading with `org-insert-heading-respect-content' set to t."
7670 (interactive "P")
7671 (let ((org-insert-heading-respect-content t))
7672 (org-insert-heading arg invisible-ok)))
7674 (defun org-insert-todo-heading-respect-content (&optional force-state)
7675 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7676 (interactive "P")
7677 (let ((org-insert-heading-respect-content t))
7678 (org-insert-todo-heading force-state t)))
7680 (defun org-insert-todo-heading (arg &optional force-heading)
7681 "Insert a new heading with the same level and TODO state as current heading.
7682 If the heading has no TODO state, or if the state is DONE, use the first
7683 state (TODO by default). Also one prefix arg, force first state. With two
7684 prefix args, force inserting at the end of the parent subtree."
7685 (interactive "P")
7686 (when (or force-heading (not (org-insert-item 'checkbox)))
7687 (org-insert-heading (or (and (equal arg '(16)) '(16))
7688 force-heading))
7689 (save-excursion
7690 (org-back-to-heading)
7691 (outline-previous-heading)
7692 (looking-at org-todo-line-regexp))
7693 (let*
7694 ((new-mark-x
7695 (if (or arg
7696 (not (match-beginning 2))
7697 (member (match-string 2) org-done-keywords))
7698 (car org-todo-keywords-1)
7699 (match-string 2)))
7700 (new-mark
7702 (run-hook-with-args-until-success
7703 'org-todo-get-default-hook new-mark-x nil)
7704 new-mark-x)))
7705 (beginning-of-line 1)
7706 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7707 (if org-treat-insert-todo-heading-as-state-change
7708 (org-todo new-mark)
7709 (insert new-mark " "))))
7710 (when org-provide-todo-statistics
7711 (org-update-parent-todo-statistics))))
7713 (defun org-insert-subheading (arg)
7714 "Insert a new subheading and demote it.
7715 Works for outline headings and for plain lists alike."
7716 (interactive "P")
7717 (org-insert-heading arg)
7718 (cond
7719 ((org-at-heading-p) (org-do-demote))
7720 ((org-at-item-p) (org-indent-item))))
7722 (defun org-insert-todo-subheading (arg)
7723 "Insert a new subheading with TODO keyword or checkbox and demote it.
7724 Works for outline headings and for plain lists alike."
7725 (interactive "P")
7726 (org-insert-todo-heading arg)
7727 (cond
7728 ((org-at-heading-p) (org-do-demote))
7729 ((org-at-item-p) (org-indent-item))))
7731 ;;; Promotion and Demotion
7733 (defvar org-after-demote-entry-hook nil
7734 "Hook run after an entry has been demoted.
7735 The cursor will be at the beginning of the entry.
7736 When a subtree is being demoted, the hook will be called for each node.")
7738 (defvar org-after-promote-entry-hook nil
7739 "Hook run after an entry has been promoted.
7740 The cursor will be at the beginning of the entry.
7741 When a subtree is being promoted, the hook will be called for each node.")
7743 (defun org-promote-subtree ()
7744 "Promote the entire subtree.
7745 See also `org-promote'."
7746 (interactive)
7747 (save-excursion
7748 (org-with-limited-levels (org-map-tree 'org-promote)))
7749 (org-fix-position-after-promote))
7751 (defun org-demote-subtree ()
7752 "Demote the entire subtree. See `org-demote'.
7753 See also `org-promote'."
7754 (interactive)
7755 (save-excursion
7756 (org-with-limited-levels (org-map-tree 'org-demote)))
7757 (org-fix-position-after-promote))
7760 (defun org-do-promote ()
7761 "Promote the current heading higher up the tree.
7762 If the region is active in `transient-mark-mode', promote all headings
7763 in the region."
7764 (interactive)
7765 (save-excursion
7766 (if (org-region-active-p)
7767 (org-map-region 'org-promote (region-beginning) (region-end))
7768 (org-promote)))
7769 (org-fix-position-after-promote))
7771 (defun org-do-demote ()
7772 "Demote the current heading lower down the tree.
7773 If the region is active in `transient-mark-mode', demote all headings
7774 in the region."
7775 (interactive)
7776 (save-excursion
7777 (if (org-region-active-p)
7778 (org-map-region 'org-demote (region-beginning) (region-end))
7779 (org-demote)))
7780 (org-fix-position-after-promote))
7782 (defun org-fix-position-after-promote ()
7783 "Make sure that after pro/demotion cursor position is right."
7784 (let ((pos (point)))
7785 (when (save-excursion
7786 (beginning-of-line 1)
7787 (looking-at org-todo-line-regexp)
7788 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7789 (cond ((eobp) (insert " "))
7790 ((eolp) (insert " "))
7791 ((equal (char-after) ?\ ) (forward-char 1))))))
7793 (defun org-current-level ()
7794 "Return the level of the current entry, or nil if before the first headline.
7795 The level is the number of stars at the beginning of the headline."
7796 (save-excursion
7797 (org-with-limited-levels
7798 (if (ignore-errors (org-back-to-heading t))
7799 (funcall outline-level)))))
7801 (defun org-get-previous-line-level ()
7802 "Return the outline depth of the last headline before the current line.
7803 Returns 0 for the first headline in the buffer, and nil if before the
7804 first headline."
7805 (let ((current-level (org-current-level))
7806 (prev-level (when (> (line-number-at-pos) 1)
7807 (save-excursion
7808 (beginning-of-line 0)
7809 (org-current-level)))))
7810 (cond ((null current-level) nil) ; Before first headline
7811 ((null prev-level) 0) ; At first headline
7812 (prev-level))))
7814 (defun org-reduced-level (l)
7815 "Compute the effective level of a heading.
7816 This takes into account the setting of `org-odd-levels-only'."
7817 (cond
7818 ((zerop l) 0)
7819 (org-odd-levels-only (1+ (floor (/ l 2))))
7820 (t l)))
7822 (defun org-level-increment ()
7823 "Return the number of stars that will be added or removed at a
7824 time to headlines when structure editing, based on the value of
7825 `org-odd-levels-only'."
7826 (if org-odd-levels-only 2 1))
7828 (defun org-get-valid-level (level &optional change)
7829 "Rectify a level change under the influence of `org-odd-levels-only'
7830 LEVEL is a current level, CHANGE is by how much the level should be
7831 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7832 even level numbers will become the next higher odd number."
7833 (if org-odd-levels-only
7834 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7835 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7836 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7837 (max 1 (+ level (or change 0)))))
7839 (if (boundp 'define-obsolete-function-alias)
7840 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7841 (define-obsolete-function-alias 'org-get-legal-level
7842 'org-get-valid-level)
7843 (define-obsolete-function-alias 'org-get-legal-level
7844 'org-get-valid-level "23.1")))
7846 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7847 ;; ̀org-with-limited-levels'
7848 (defun org-promote ()
7849 "Promote the current heading higher up the tree.
7850 If the region is active in `transient-mark-mode', promote all headings
7851 in the region."
7852 (org-back-to-heading t)
7853 (let* ((level (save-match-data (funcall outline-level)))
7854 (after-change-functions (remove 'flyspell-after-change-function
7855 after-change-functions))
7856 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7857 (diff (abs (- level (length up-head) -1))))
7858 (cond ((and (= level 1) org-called-with-limited-levels
7859 org-allow-promoting-top-level-subtree)
7860 (replace-match "# " nil t))
7861 ((= level 1)
7862 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7863 (t (replace-match up-head nil t)))
7864 ;; Fixup tag positioning
7865 (unless (= level 1)
7866 (and org-auto-align-tags (org-set-tags nil t))
7867 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7868 (run-hooks 'org-after-promote-entry-hook)))
7870 (defun org-demote ()
7871 "Demote the current heading lower down the tree.
7872 If the region is active in `transient-mark-mode', demote all headings
7873 in the region."
7874 (org-back-to-heading t)
7875 (let* ((level (save-match-data (funcall outline-level)))
7876 (after-change-functions (remove 'flyspell-after-change-function
7877 after-change-functions))
7878 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7879 (diff (abs (- level (length down-head) -1))))
7880 (replace-match down-head nil t)
7881 ;; Fixup tag positioning
7882 (and org-auto-align-tags (org-set-tags nil t))
7883 (if org-adapt-indentation (org-fixup-indentation diff))
7884 (run-hooks 'org-after-demote-entry-hook)))
7886 (defun org-cycle-level ()
7887 "Cycle the level of an empty headline through possible states.
7888 This goes first to child, then to parent, level, then up the hierarchy.
7889 After top level, it switches back to sibling level."
7890 (interactive)
7891 (let ((org-adapt-indentation nil))
7892 (when (org-point-at-end-of-empty-headline)
7893 (setq this-command 'org-cycle-level) ; Only needed for caching
7894 (let ((cur-level (org-current-level))
7895 (prev-level (org-get-previous-line-level)))
7896 (cond
7897 ;; If first headline in file, promote to top-level.
7898 ((= prev-level 0)
7899 (loop repeat (/ (- cur-level 1) (org-level-increment))
7900 do (org-do-promote)))
7901 ;; If same level as prev, demote one.
7902 ((= prev-level cur-level)
7903 (org-do-demote))
7904 ;; If parent is top-level, promote to top level if not already.
7905 ((= prev-level 1)
7906 (loop repeat (/ (- cur-level 1) (org-level-increment))
7907 do (org-do-promote)))
7908 ;; If top-level, return to prev-level.
7909 ((= cur-level 1)
7910 (loop repeat (/ (- prev-level 1) (org-level-increment))
7911 do (org-do-demote)))
7912 ;; If less than prev-level, promote one.
7913 ((< cur-level prev-level)
7914 (org-do-promote))
7915 ;; If deeper than prev-level, promote until higher than
7916 ;; prev-level.
7917 ((> cur-level prev-level)
7918 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7919 do (org-do-promote))))
7920 t))))
7922 (defun org-map-tree (fun)
7923 "Call FUN for every heading underneath the current one."
7924 (org-back-to-heading)
7925 (let ((level (funcall outline-level)))
7926 (save-excursion
7927 (funcall fun)
7928 (while (and (progn
7929 (outline-next-heading)
7930 (> (funcall outline-level) level))
7931 (not (eobp)))
7932 (funcall fun)))))
7934 (defun org-map-region (fun beg end)
7935 "Call FUN for every heading between BEG and END."
7936 (let ((org-ignore-region t))
7937 (save-excursion
7938 (setq end (copy-marker end))
7939 (goto-char beg)
7940 (if (and (re-search-forward org-outline-regexp-bol nil t)
7941 (< (point) end))
7942 (funcall fun))
7943 (while (and (progn
7944 (outline-next-heading)
7945 (< (point) end))
7946 (not (eobp)))
7947 (funcall fun)))))
7949 (defvar org-property-end-re) ; silence byte-compiler
7950 (defun org-fixup-indentation (diff)
7951 "Change the indentation in the current entry by DIFF.
7952 However, if any line in the current entry has no indentation, or if it
7953 would end up with no indentation after the change, nothing at all is done."
7954 (save-excursion
7955 (let ((end (save-excursion (outline-next-heading)
7956 (point-marker)))
7957 (prohibit (if (> diff 0)
7958 "^\\S-"
7959 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7960 col)
7961 (unless (save-excursion (end-of-line 1)
7962 (re-search-forward prohibit end t))
7963 (while (and (< (point) end)
7964 (re-search-forward "^[ \t]+" end t))
7965 (goto-char (match-end 0))
7966 (setq col (current-column))
7967 (if (< diff 0) (replace-match ""))
7968 (org-indent-to-column (+ diff col))))
7969 (move-marker end nil))))
7971 (defun org-convert-to-odd-levels ()
7972 "Convert an org-mode file with all levels allowed to one with odd levels.
7973 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7974 level 5 etc."
7975 (interactive)
7976 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7977 (let ((outline-level 'org-outline-level)
7978 (org-odd-levels-only nil) n)
7979 (save-excursion
7980 (goto-char (point-min))
7981 (while (re-search-forward "^\\*\\*+ " nil t)
7982 (setq n (- (length (match-string 0)) 2))
7983 (while (>= (setq n (1- n)) 0)
7984 (org-demote))
7985 (end-of-line 1))))))
7987 (defun org-convert-to-oddeven-levels ()
7988 "Convert an org-mode file with only odd levels to one with odd/even levels.
7989 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7990 file contains a section with an even level, conversion would
7991 destroy the structure of the file. An error is signaled in this
7992 case."
7993 (interactive)
7994 (goto-char (point-min))
7995 ;; First check if there are no even levels
7996 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7997 (org-show-context t)
7998 (error "Not all levels are odd in this file. Conversion not possible"))
7999 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8000 (let ((outline-regexp org-outline-regexp)
8001 (outline-level 'org-outline-level)
8002 (org-odd-levels-only nil) n)
8003 (save-excursion
8004 (goto-char (point-min))
8005 (while (re-search-forward "^\\*\\*+ " nil t)
8006 (setq n (/ (1- (length (match-string 0))) 2))
8007 (while (>= (setq n (1- n)) 0)
8008 (org-promote))
8009 (end-of-line 1))))))
8011 (defun org-tr-level (n)
8012 "Make N odd if required."
8013 (if org-odd-levels-only (1+ (/ n 2)) n))
8015 ;;; Vertical tree motion, cutting and pasting of subtrees
8017 (defun org-move-subtree-up (&optional arg)
8018 "Move the current subtree up past ARG headlines of the same level."
8019 (interactive "p")
8020 (org-move-subtree-down (- (prefix-numeric-value arg))))
8022 (defun org-move-subtree-down (&optional arg)
8023 "Move the current subtree down past ARG headlines of the same level."
8024 (interactive "p")
8025 (setq arg (prefix-numeric-value arg))
8026 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8027 'org-get-last-sibling))
8028 (ins-point (make-marker))
8029 (cnt (abs arg))
8030 (col (current-column))
8031 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8032 ;; Select the tree
8033 (org-back-to-heading)
8034 (setq beg0 (point))
8035 (save-excursion
8036 (setq ne-beg (org-back-over-empty-lines))
8037 (setq beg (point)))
8038 (save-match-data
8039 (save-excursion (outline-end-of-heading)
8040 (setq folded (outline-invisible-p)))
8041 (outline-end-of-subtree))
8042 (outline-next-heading)
8043 (setq ne-end (org-back-over-empty-lines))
8044 (setq end (point))
8045 (goto-char beg0)
8046 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8047 ;; include less whitespace
8048 (save-excursion
8049 (goto-char beg)
8050 (forward-line (- ne-beg ne-end))
8051 (setq beg (point))))
8052 ;; Find insertion point, with error handling
8053 (while (> cnt 0)
8054 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8055 (progn (goto-char beg0)
8056 (user-error "Cannot move past superior level or buffer limit")))
8057 (setq cnt (1- cnt)))
8058 (if (> arg 0)
8059 ;; Moving forward - still need to move over subtree
8060 (progn (org-end-of-subtree t t)
8061 (save-excursion
8062 (org-back-over-empty-lines)
8063 (or (bolp) (newline)))))
8064 (setq ne-ins (org-back-over-empty-lines))
8065 (move-marker ins-point (point))
8066 (setq txt (buffer-substring beg end))
8067 (org-save-markers-in-region beg end)
8068 (delete-region beg end)
8069 (org-remove-empty-overlays-at beg)
8070 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8071 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8072 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8073 (let ((bbb (point)))
8074 (insert-before-markers txt)
8075 (org-reinstall-markers-in-region bbb)
8076 (move-marker ins-point bbb))
8077 (or (bolp) (insert "\n"))
8078 (setq ins-end (point))
8079 (goto-char ins-point)
8080 (org-skip-whitespace)
8081 (when (and (< arg 0)
8082 (org-first-sibling-p)
8083 (> ne-ins ne-beg))
8084 ;; Move whitespace back to beginning
8085 (save-excursion
8086 (goto-char ins-end)
8087 (let ((kill-whole-line t))
8088 (kill-line (- ne-ins ne-beg)) (point)))
8089 (insert (make-string (- ne-ins ne-beg) ?\n)))
8090 (move-marker ins-point nil)
8091 (if folded
8092 (hide-subtree)
8093 (org-show-entry)
8094 (show-children)
8095 (org-cycle-hide-drawers 'children))
8096 (org-clean-visibility-after-subtree-move)
8097 ;; move back to the initial column we were at
8098 (move-to-column col)))
8100 (defvar org-subtree-clip ""
8101 "Clipboard for cut and paste of subtrees.
8102 This is actually only a copy of the kill, because we use the normal kill
8103 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8105 (defvar org-subtree-clip-folded nil
8106 "Was the last copied subtree folded?
8107 This is used to fold the tree back after pasting.")
8109 (defun org-cut-subtree (&optional n)
8110 "Cut the current subtree into the clipboard.
8111 With prefix arg N, cut this many sequential subtrees.
8112 This is a short-hand for marking the subtree and then cutting it."
8113 (interactive "p")
8114 (org-copy-subtree n 'cut))
8116 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8117 "Cut the current subtree into the clipboard.
8118 With prefix arg N, cut this many sequential subtrees.
8119 This is a short-hand for marking the subtree and then copying it.
8120 If CUT is non-nil, actually cut the subtree.
8121 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8122 of some markers in the region, even if CUT is non-nil. This is
8123 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8124 (interactive "p")
8125 (let (beg end folded (beg0 (point)))
8126 (if (org-called-interactively-p 'any)
8127 (org-back-to-heading nil) ; take what looks like a subtree
8128 (org-back-to-heading t)) ; take what is really there
8129 (setq beg (point))
8130 (skip-chars-forward " \t\r\n")
8131 (save-match-data
8132 (if nosubtrees
8133 (outline-next-heading)
8134 (save-excursion (outline-end-of-heading)
8135 (setq folded (outline-invisible-p)))
8136 (condition-case nil
8137 (org-forward-heading-same-level (1- n) t)
8138 (error nil))
8139 (org-end-of-subtree t t)))
8140 (setq end (point))
8141 (goto-char beg0)
8142 (when (> end beg)
8143 (setq org-subtree-clip-folded folded)
8144 (when (or cut force-store-markers)
8145 (org-save-markers-in-region beg end))
8146 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8147 (setq org-subtree-clip (current-kill 0))
8148 (message "%s: Subtree(s) with %d characters"
8149 (if cut "Cut" "Copied")
8150 (length org-subtree-clip)))))
8152 (defun org-paste-subtree (&optional level tree for-yank)
8153 "Paste the clipboard as a subtree, with modification of headline level.
8154 The entire subtree is promoted or demoted in order to match a new headline
8155 level.
8157 If the cursor is at the beginning of a headline, the same level as
8158 that headline is used to paste the tree.
8160 If not, the new level is derived from the *visible* headings
8161 before and after the insertion point, and taken to be the inferior headline
8162 level of the two. So if the previous visible heading is level 3 and the
8163 next is level 4 (or vice versa), level 4 will be used for insertion.
8164 This makes sure that the subtree remains an independent subtree and does
8165 not swallow low level entries.
8167 You can also force a different level, either by using a numeric prefix
8168 argument, or by inserting the heading marker by hand. For example, if the
8169 cursor is after \"*****\", then the tree will be shifted to level 5.
8171 If optional TREE is given, use this text instead of the kill ring.
8173 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8174 move back over whitespace before inserting, and move point to the end of
8175 the inserted text when done."
8176 (interactive "P")
8177 (setq tree (or tree (and kill-ring (current-kill 0))))
8178 (unless (org-kill-is-subtree-p tree)
8179 (error "%s"
8180 (substitute-command-keys
8181 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8182 (org-with-limited-levels
8183 (let* ((visp (not (outline-invisible-p)))
8184 (txt tree)
8185 (^re_ "\\(\\*+\\)[ \t]*")
8186 (old-level (if (string-match org-outline-regexp-bol txt)
8187 (- (match-end 0) (match-beginning 0) 1)
8188 -1))
8189 (force-level (cond (level (prefix-numeric-value level))
8190 ((and (looking-at "[ \t]*$")
8191 (string-match
8192 "^\\*+$" (buffer-substring
8193 (point-at-bol) (point))))
8194 (- (match-end 1) (match-beginning 1)))
8195 ((and (bolp)
8196 (looking-at org-outline-regexp))
8197 (- (match-end 0) (point) 1))))
8198 (previous-level (save-excursion
8199 (condition-case nil
8200 (progn
8201 (outline-previous-visible-heading 1)
8202 (if (looking-at ^re_)
8203 (- (match-end 0) (match-beginning 0) 1)
8205 (error 1))))
8206 (next-level (save-excursion
8207 (condition-case nil
8208 (progn
8209 (or (looking-at org-outline-regexp)
8210 (outline-next-visible-heading 1))
8211 (if (looking-at ^re_)
8212 (- (match-end 0) (match-beginning 0) 1)
8214 (error 1))))
8215 (new-level (or force-level (max previous-level next-level)))
8216 (shift (if (or (= old-level -1)
8217 (= new-level -1)
8218 (= old-level new-level))
8220 (- new-level old-level)))
8221 (delta (if (> shift 0) -1 1))
8222 (func (if (> shift 0) 'org-demote 'org-promote))
8223 (org-odd-levels-only nil)
8224 beg end newend)
8225 ;; Remove the forced level indicator
8226 (if force-level
8227 (delete-region (point-at-bol) (point)))
8228 ;; Paste
8229 (beginning-of-line (if (bolp) 1 2))
8230 (setq beg (point))
8231 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8232 (insert-before-markers txt)
8233 (unless (string-match "\n\\'" txt) (insert "\n"))
8234 (setq newend (point))
8235 (org-reinstall-markers-in-region beg)
8236 (setq end (point))
8237 (goto-char beg)
8238 (skip-chars-forward " \t\n\r")
8239 (setq beg (point))
8240 (if (and (outline-invisible-p) visp)
8241 (save-excursion (outline-show-heading)))
8242 ;; Shift if necessary
8243 (unless (= shift 0)
8244 (save-restriction
8245 (narrow-to-region beg end)
8246 (while (not (= shift 0))
8247 (org-map-region func (point-min) (point-max))
8248 (setq shift (+ delta shift)))
8249 (goto-char (point-min))
8250 (setq newend (point-max))))
8251 (when (or (org-called-interactively-p 'interactive) for-yank)
8252 (message "Clipboard pasted as level %d subtree" new-level))
8253 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8254 kill-ring
8255 (eq org-subtree-clip (current-kill 0))
8256 org-subtree-clip-folded)
8257 ;; The tree was folded before it was killed/copied
8258 (hide-subtree))
8259 (and for-yank (goto-char newend)))))
8261 (defun org-kill-is-subtree-p (&optional txt)
8262 "Check if the current kill is an outline subtree, or a set of trees.
8263 Returns nil if kill does not start with a headline, or if the first
8264 headline level is not the largest headline level in the tree.
8265 So this will actually accept several entries of equal levels as well,
8266 which is OK for `org-paste-subtree'.
8267 If optional TXT is given, check this string instead of the current kill."
8268 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8269 (re (org-get-limited-outline-regexp))
8270 (^re (concat "^" re))
8271 (start-level (and kill
8272 (string-match
8273 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8274 kill)
8275 (- (match-end 2) (match-beginning 2) 1)))
8276 (start (1+ (or (match-beginning 2) -1))))
8277 (if (not start-level)
8278 (progn
8279 nil) ;; does not even start with a heading
8280 (catch 'exit
8281 (while (setq start (string-match ^re kill (1+ start)))
8282 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8283 (throw 'exit nil)))
8284 t))))
8286 (defvar org-markers-to-move nil
8287 "Markers that should be moved with a cut-and-paste operation.
8288 Those markers are stored together with their positions relative to
8289 the start of the region.")
8291 (defun org-save-markers-in-region (beg end)
8292 "Check markers in region.
8293 If these markers are between BEG and END, record their position relative
8294 to BEG, so that after moving the block of text, we can put the markers back
8295 into place.
8296 This function gets called just before an entry or tree gets cut from the
8297 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8298 called immediately, to move the markers with the entries."
8299 (setq org-markers-to-move nil)
8300 (when (featurep 'org-clock)
8301 (org-clock-save-markers-for-cut-and-paste beg end))
8302 (when (featurep 'org-agenda)
8303 (org-agenda-save-markers-for-cut-and-paste beg end)))
8305 (defun org-check-and-save-marker (marker beg end)
8306 "Check if MARKER is between BEG and END.
8307 If yes, remember the marker and the distance to BEG."
8308 (when (and (marker-buffer marker)
8309 (equal (marker-buffer marker) (current-buffer)))
8310 (if (and (>= marker beg) (< marker end))
8311 (push (cons marker (- marker beg)) org-markers-to-move))))
8313 (defun org-reinstall-markers-in-region (beg)
8314 "Move all remembered markers to their position relative to BEG."
8315 (mapc (lambda (x)
8316 (move-marker (car x) (+ beg (cdr x))))
8317 org-markers-to-move)
8318 (setq org-markers-to-move nil))
8320 (defun org-narrow-to-subtree ()
8321 "Narrow buffer to the current subtree."
8322 (interactive)
8323 (save-excursion
8324 (save-match-data
8325 (org-with-limited-levels
8326 (narrow-to-region
8327 (progn (org-back-to-heading t) (point))
8328 (progn (org-end-of-subtree t t)
8329 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8330 (point)))))))
8332 (defun org-narrow-to-block ()
8333 "Narrow buffer to the current block."
8334 (interactive)
8335 (let* ((case-fold-search t)
8336 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8337 "^[ \t]*#\\+end_.*")))
8338 (if blockp
8339 (narrow-to-region (car blockp) (cdr blockp))
8340 (error "Not in a block"))))
8342 (eval-when-compile
8343 (defvar org-property-drawer-re))
8345 (defvar org-property-start-re) ;; defined below
8346 (defun org-clone-subtree-with-time-shift (n &optional shift)
8347 "Clone the task (subtree) at point N times.
8348 The clones will be inserted as siblings.
8350 In interactive use, the user will be prompted for the number of
8351 clones to be produced. When called with a universal prefix argument
8352 and if the entry has a timestamp, the user will also be prompted for
8353 a time shift, which may be a repeater as used in time stamps, for
8354 example `+3d'.
8356 When a valid repeater is given and the entry contains any time
8357 stamps, the clones will become a sequence in time, with time
8358 stamps in the subtree shifted for each clone produced. If SHIFT
8359 is nil or the empty string, time stamps will be left alone. The
8360 ID property of the original subtree is removed.
8362 If the original subtree did contain time stamps with a repeater,
8363 the following will happen:
8364 - the repeater will be removed in each clone
8365 - an additional clone will be produced, with the current, unshifted
8366 date(s) in the entry.
8367 - the original entry will be placed *after* all the clones, with
8368 repeater intact.
8369 - the start days in the repeater in the original entry will be shifted
8370 to past the last clone.
8371 In this way you can spell out a number of instances of a repeating task,
8372 and still retain the repeater to cover future instances of the task."
8373 (interactive "nNumber of clones to produce: ")
8374 (let ((shift
8375 (or shift
8376 (if (and (equal current-prefix-arg '(4))
8377 (save-excursion
8378 (re-search-forward org-ts-regexp-both
8379 (save-excursion
8380 (org-end-of-subtree t)
8381 (point)) t)))
8382 (read-from-minibuffer
8383 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8384 ""))) ;; No time shift
8385 (n-no-remove -1)
8386 (drawer-re org-drawer-regexp)
8387 beg end template task idprop
8388 shift-n shift-what doshift nmin nmax)
8389 (if (not (and (integerp n) (> n 0)))
8390 (error "Invalid number of replications %s" n))
8391 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8392 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8393 shift)))
8394 (error "Invalid shift specification %s" shift))
8395 (when doshift
8396 (setq shift-n (string-to-number (match-string 1 shift))
8397 shift-what (cdr (assoc (match-string 2 shift)
8398 '(("d" . day) ("w" . week)
8399 ("m" . month) ("y" . year))))))
8400 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8401 (setq nmin 1 nmax n)
8402 (org-back-to-heading t)
8403 (setq beg (point))
8404 (setq idprop (org-entry-get nil "ID"))
8405 (org-end-of-subtree t t)
8406 (or (bolp) (insert "\n"))
8407 (setq end (point))
8408 (setq template (buffer-substring beg end))
8409 (when (and doshift
8410 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8411 (delete-region beg end)
8412 (setq end beg)
8413 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8414 (goto-char end)
8415 (loop for n from nmin to nmax do
8416 ;; prepare clone
8417 (with-temp-buffer
8418 (insert template)
8419 (org-mode)
8420 (goto-char (point-min))
8421 (org-show-subtree)
8422 (and idprop (if org-clone-delete-id
8423 (org-entry-delete nil "ID")
8424 (org-id-get-create t)))
8425 (unless (= n 0)
8426 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8427 (kill-whole-line))
8428 (goto-char (point-min))
8429 (while (re-search-forward drawer-re nil t)
8430 (mapc (lambda (d)
8431 (org-remove-empty-drawer-at d (point))) org-drawers)))
8432 (goto-char (point-min))
8433 (when doshift
8434 (while (re-search-forward org-ts-regexp-both nil t)
8435 (org-timestamp-change (* n shift-n) shift-what))
8436 (unless (= n n-no-remove)
8437 (goto-char (point-min))
8438 (while (re-search-forward org-ts-regexp nil t)
8439 (save-excursion
8440 (goto-char (match-beginning 0))
8441 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8442 (delete-region (match-beginning 1) (match-end 1)))))))
8443 (setq task (buffer-string)))
8444 (insert task))
8445 (goto-char beg)))
8447 ;;; Outline Sorting
8449 (defun org-sort (with-case)
8450 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8451 Optional argument WITH-CASE means sort case-sensitively."
8452 (interactive "P")
8453 (cond
8454 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8455 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8457 (org-call-with-arg 'org-sort-entries with-case))))
8459 (defun org-sort-remove-invisible (s)
8460 "Remove invisible links from string S."
8461 (remove-text-properties 0 (length s) org-rm-props s)
8462 (while (string-match org-bracket-link-regexp s)
8463 (setq s (replace-match (if (match-end 2)
8464 (match-string 3 s)
8465 (match-string 1 s)) t t s)))
8466 (let ((st (format " %s " s)))
8467 (while (string-match org-emph-re st)
8468 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8469 (setq s (substring st 1 -1)))
8472 (defvar org-priority-regexp) ; defined later in the file
8474 (defvar org-after-sorting-entries-or-items-hook nil
8475 "Hook that is run after a bunch of entries or items have been sorted.
8476 When children are sorted, the cursor is in the parent line when this
8477 hook gets called. When a region or a plain list is sorted, the cursor
8478 will be in the first entry of the sorted region/list.")
8480 (defun org-sort-entries
8481 (&optional with-case sorting-type getkey-func compare-func property)
8482 "Sort entries on a certain level of an outline tree.
8483 If there is an active region, the entries in the region are sorted.
8484 Else, if the cursor is before the first entry, sort the top-level items.
8485 Else, the children of the entry at point are sorted.
8487 Sorting can be alphabetically, numerically, by date/time as given by
8488 a time stamp, by a property, by priority order, or by a custom function.
8490 The command prompts for the sorting type unless it has been given to the
8491 function through the SORTING-TYPE argument, which needs to be a character,
8492 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8493 precise meaning of each character:
8495 n Numerically, by converting the beginning of the entry/item to a number.
8496 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8497 o By order of TODO keywords.
8498 t By date/time, either the first active time stamp in the entry, or, if
8499 none exist, by the first inactive one.
8500 s By the scheduled date/time.
8501 d By deadline date/time.
8502 c By creation time, which is assumed to be the first inactive time stamp
8503 at the beginning of a line.
8504 p By priority according to the cookie.
8505 r By the value of a property.
8507 Capital letters will reverse the sort order.
8509 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8510 called with point at the beginning of the record. It must return either
8511 a string or a number that should serve as the sorting key for that record.
8513 Comparing entries ignores case by default. However, with an optional argument
8514 WITH-CASE, the sorting considers case as well.
8516 Sorting is done against the visible part of the headlines, it ignores hidden
8517 links."
8518 (interactive "P")
8519 (let ((case-func (if with-case 'identity 'downcase))
8520 (cmstr
8521 ;; The clock marker is lost when using `sort-subr', let's
8522 ;; store the clocking string.
8523 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8524 (save-excursion
8525 (goto-char org-clock-marker)
8526 (looking-back "^.*") (match-string-no-properties 0))))
8527 start beg end stars re re2
8528 txt what tmp)
8529 ;; Find beginning and end of region to sort
8530 (cond
8531 ((org-region-active-p)
8532 ;; we will sort the region
8533 (setq end (region-end)
8534 what "region")
8535 (goto-char (region-beginning))
8536 (if (not (org-at-heading-p)) (outline-next-heading))
8537 (setq start (point)))
8538 ((or (org-at-heading-p)
8539 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8540 ;; we will sort the children of the current headline
8541 (org-back-to-heading)
8542 (setq start (point)
8543 end (progn (org-end-of-subtree t t)
8544 (or (bolp) (insert "\n"))
8545 (org-back-over-empty-lines)
8546 (point))
8547 what "children")
8548 (goto-char start)
8549 (show-subtree)
8550 (outline-next-heading))
8552 ;; we will sort the top-level entries in this file
8553 (goto-char (point-min))
8554 (or (org-at-heading-p) (outline-next-heading))
8555 (setq start (point))
8556 (goto-char (point-max))
8557 (beginning-of-line 1)
8558 (when (looking-at ".*?\\S-")
8559 ;; File ends in a non-white line
8560 (end-of-line 1)
8561 (insert "\n"))
8562 (setq end (point-max))
8563 (setq what "top-level")
8564 (goto-char start)
8565 (show-all)))
8567 (setq beg (point))
8568 (if (>= beg end) (error "Nothing to sort"))
8570 (looking-at "\\(\\*+\\)")
8571 (setq stars (match-string 1)
8572 re (concat "^" (regexp-quote stars) " +")
8573 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8574 txt (buffer-substring beg end))
8575 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8576 (if (and (not (equal stars "*")) (string-match re2 txt))
8577 (error "Region to sort contains a level above the first entry"))
8579 (unless sorting-type
8580 (message
8581 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8582 [t]ime [s]cheduled [d]eadline [c]reated
8583 A/N/P/R/O/F/T/S/D/C means reversed:"
8584 what)
8585 (setq sorting-type (read-char-exclusive))
8587 (unless getkey-func
8588 (and (= (downcase sorting-type) ?f)
8589 (setq getkey-func
8590 (org-icompleting-read "Sort using function: "
8591 obarray 'fboundp t nil nil))
8592 (setq getkey-func (intern getkey-func))))
8594 (and (= (downcase sorting-type) ?r)
8595 (not property)
8596 (setq property
8597 (org-icompleting-read "Property: "
8598 (mapcar 'list (org-buffer-property-keys t))
8599 nil t))))
8601 (message "Sorting entries...")
8603 (save-restriction
8604 (narrow-to-region start end)
8605 (let ((dcst (downcase sorting-type))
8606 (case-fold-search nil)
8607 (now (current-time)))
8608 (sort-subr
8609 (/= dcst sorting-type)
8610 ;; This function moves to the beginning character of the "record" to
8611 ;; be sorted.
8612 (lambda nil
8613 (if (re-search-forward re nil t)
8614 (goto-char (match-beginning 0))
8615 (goto-char (point-max))))
8616 ;; This function moves to the last character of the "record" being
8617 ;; sorted.
8618 (lambda nil
8619 (save-match-data
8620 (condition-case nil
8621 (outline-forward-same-level 1)
8622 (error
8623 (goto-char (point-max))))))
8624 ;; This function returns the value that gets sorted against.
8625 (lambda nil
8626 (cond
8627 ((= dcst ?n)
8628 (if (looking-at org-complex-heading-regexp)
8629 (string-to-number (org-sort-remove-invisible (match-string 4)))
8630 nil))
8631 ((= dcst ?a)
8632 (if (looking-at org-complex-heading-regexp)
8633 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8634 nil))
8635 ((= dcst ?t)
8636 (let ((end (save-excursion (outline-next-heading) (point))))
8637 (if (or (re-search-forward org-ts-regexp end t)
8638 (re-search-forward org-ts-regexp-both end t))
8639 (org-time-string-to-seconds (match-string 0))
8640 (org-float-time now))))
8641 ((= dcst ?c)
8642 (let ((end (save-excursion (outline-next-heading) (point))))
8643 (if (re-search-forward
8644 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8645 end t)
8646 (org-time-string-to-seconds (match-string 0))
8647 (org-float-time now))))
8648 ((= dcst ?s)
8649 (let ((end (save-excursion (outline-next-heading) (point))))
8650 (if (re-search-forward org-scheduled-time-regexp end t)
8651 (org-time-string-to-seconds (match-string 1))
8652 (org-float-time now))))
8653 ((= dcst ?d)
8654 (let ((end (save-excursion (outline-next-heading) (point))))
8655 (if (re-search-forward org-deadline-time-regexp end t)
8656 (org-time-string-to-seconds (match-string 1))
8657 (org-float-time now))))
8658 ((= dcst ?p)
8659 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8660 (string-to-char (match-string 2))
8661 org-default-priority))
8662 ((= dcst ?r)
8663 (or (org-entry-get nil property) ""))
8664 ((= dcst ?o)
8665 (if (looking-at org-complex-heading-regexp)
8666 (- 9999 (length (member (match-string 2)
8667 org-todo-keywords-1)))))
8668 ((= dcst ?f)
8669 (if getkey-func
8670 (progn
8671 (setq tmp (funcall getkey-func))
8672 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8673 tmp)
8674 (error "Invalid key function `%s'" getkey-func)))
8675 (t (error "Invalid sorting type `%c'" sorting-type))))
8677 (cond
8678 ((= dcst ?a) 'string<)
8679 ((= dcst ?f) compare-func)
8680 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8681 (run-hooks 'org-after-sorting-entries-or-items-hook)
8682 ;; Reset the clock marker if needed
8683 (when cmstr
8684 (save-excursion
8685 (goto-char start)
8686 (search-forward cmstr nil t)
8687 (move-marker org-clock-marker (point))))
8688 (message "Sorting entries...done")))
8690 (defun org-do-sort (table what &optional with-case sorting-type)
8691 "Sort TABLE of WHAT according to SORTING-TYPE.
8692 The user will be prompted for the SORTING-TYPE if the call to this
8693 function does not specify it. WHAT is only for the prompt, to indicate
8694 what is being sorted. The sorting key will be extracted from
8695 the car of the elements of the table.
8696 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8697 (unless sorting-type
8698 (message
8699 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8700 what)
8701 (setq sorting-type (read-char-exclusive)))
8702 (let ((dcst (downcase sorting-type))
8703 extractfun comparefun)
8704 ;; Define the appropriate functions
8705 (cond
8706 ((= dcst ?n)
8707 (setq extractfun 'string-to-number
8708 comparefun (if (= dcst sorting-type) '< '>)))
8709 ((= dcst ?a)
8710 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8711 (lambda(x) (downcase (org-sort-remove-invisible x))))
8712 comparefun (if (= dcst sorting-type)
8713 'string<
8714 (lambda (a b) (and (not (string< a b))
8715 (not (string= a b)))))))
8716 ((= dcst ?t)
8717 (setq extractfun
8718 (lambda (x)
8719 (if (or (string-match org-ts-regexp x)
8720 (string-match org-ts-regexp-both x))
8721 (org-float-time
8722 (org-time-string-to-time (match-string 0 x)))
8724 comparefun (if (= dcst sorting-type) '< '>)))
8725 (t (error "Invalid sorting type `%c'" sorting-type)))
8727 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8728 table)
8729 (lambda (a b) (funcall comparefun (car a) (car b))))))
8732 ;;; The orgstruct minor mode
8734 ;; Define a minor mode which can be used in other modes in order to
8735 ;; integrate the org-mode structure editing commands.
8737 ;; This is really a hack, because the org-mode structure commands use
8738 ;; keys which normally belong to the major mode. Here is how it
8739 ;; works: The minor mode defines all the keys necessary to operate the
8740 ;; structure commands, but wraps the commands into a function which
8741 ;; tests if the cursor is currently at a headline or a plain list
8742 ;; item. If that is the case, the structure command is used,
8743 ;; temporarily setting many Org-mode variables like regular
8744 ;; expressions for filling etc. However, when any of those keys is
8745 ;; used at a different location, function uses `key-binding' to look
8746 ;; up if the key has an associated command in another currently active
8747 ;; keymap (minor modes, major mode, global), and executes that
8748 ;; command. There might be problems if any of the keys is otherwise
8749 ;; used as a prefix key.
8751 (defcustom orgstruct-heading-prefix-regexp nil
8752 "Regexp that matches the custom prefix of Org headlines in
8753 orgstruct(++)-mode."
8754 :group 'org
8755 :version "24.4"
8756 :package-version '(Org . "8.0")
8757 :type 'string)
8758 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8760 (defcustom orgstruct-setup-hook nil
8761 "Hook run after orgstruct-mode-map is filled."
8762 :group 'org
8763 :version "24.4"
8764 :package-version '(Org . "8.0")
8765 :type 'hook)
8767 (defvar orgstruct-initialized nil)
8769 (defvar org-local-vars nil
8770 "List of local variables, for use by `orgstruct-mode'.")
8772 ;;;###autoload
8773 (define-minor-mode orgstruct-mode
8774 "Toggle the minor mode `orgstruct-mode'.
8775 This mode is for using Org-mode structure commands in other
8776 modes. The following keys behave as if Org-mode were active, if
8777 the cursor is on a headline, or on a plain list item (both as
8778 defined by Org-mode)."
8779 nil " OrgStruct" (make-sparse-keymap)
8780 (funcall (if orgstruct-mode
8781 'add-to-invisibility-spec
8782 'remove-from-invisibility-spec)
8783 '(outline . t))
8784 (when orgstruct-mode
8785 (org-load-modules-maybe)
8786 (unless orgstruct-initialized
8787 (orgstruct-setup)
8788 (setq orgstruct-initialized t))))
8790 ;;;###autoload
8791 (defun turn-on-orgstruct ()
8792 "Unconditionally turn on `orgstruct-mode'."
8793 (orgstruct-mode 1))
8795 (defvar org-fb-vars nil)
8796 (make-variable-buffer-local 'org-fb-vars)
8797 (defun orgstruct++-mode (&optional arg)
8798 "Toggle `orgstruct-mode', the enhanced version of it.
8799 In addition to setting orgstruct-mode, this also exports all
8800 indentation and autofilling variables from org-mode into the
8801 buffer. It will also recognize item context in multiline items."
8802 (interactive "P")
8803 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8804 (if (< arg 1)
8805 (progn (orgstruct-mode -1)
8806 (mapc (lambda(v)
8807 (org-set-local (car v)
8808 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8809 org-fb-vars))
8810 (orgstruct-mode 1)
8811 (setq org-fb-vars nil)
8812 (let (var val)
8813 (mapc
8814 (lambda (x)
8815 (when (string-match
8816 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8817 (symbol-name (car x)))
8818 (setq var (car x) val (nth 1 x))
8819 (push (list var `(quote ,(eval var))) org-fb-vars)
8820 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8821 org-local-vars)
8822 (org-set-local 'orgstruct-is-++ t))))
8824 (defvar orgstruct-is-++ nil
8825 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8826 (make-variable-buffer-local 'orgstruct-is-++)
8828 ;;;###autoload
8829 (defun turn-on-orgstruct++ ()
8830 "Unconditionally turn on `orgstruct++-mode'."
8831 (orgstruct++-mode 1))
8833 (defun orgstruct-error ()
8834 "Error when there is no default binding for a structure key."
8835 (interactive)
8836 (funcall (if (fboundp 'user-error)
8837 'user-error
8838 'error)
8839 "This key has no function outside structure elements"))
8841 (defun orgstruct-setup ()
8842 "Setup orgstruct keymap."
8843 (dolist (cell '((org-demote . t)
8844 (org-metaleft . t)
8845 (org-metaright . t)
8846 (org-promote . t)
8847 (org-shiftmetaleft . t)
8848 (org-shiftmetaright . t)
8849 org-backward-element
8850 org-backward-heading-same-level
8851 org-ctrl-c-ret
8852 org-ctrl-c-minus
8853 org-ctrl-c-star
8854 org-cycle
8855 org-forward-heading-same-level
8856 org-insert-heading
8857 org-insert-heading-respect-content
8858 org-kill-note-or-show-branches
8859 org-mark-subtree
8860 org-meta-return
8861 org-metadown
8862 org-metaup
8863 org-narrow-to-subtree
8864 org-promote-subtree
8865 org-reveal
8866 org-shiftdown
8867 org-shiftleft
8868 org-shiftmetadown
8869 org-shiftmetaup
8870 org-shiftright
8871 org-shifttab
8872 org-shifttab
8873 org-shiftup
8874 org-show-subtree
8875 org-sort
8876 org-up-element
8877 outline-demote
8878 outline-next-visible-heading
8879 outline-previous-visible-heading
8880 outline-promote
8881 outline-up-heading
8882 show-children))
8883 (let ((f (or (car-safe cell) cell))
8884 (disable-when-heading-prefix (cdr-safe cell)))
8885 (when (fboundp f)
8886 (dolist (binding (nconc (where-is-internal f org-mode-map)
8887 (where-is-internal f outline-mode-map)))
8888 ;; TODO use local-function-key-map
8889 (dolist (rep '(("<tab>" . "TAB")
8890 ("<return>" . "RET")
8891 ("<escape>" . "ESC")
8892 ("<delete>" . "DEL")))
8893 (setq binding (read-kbd-macro
8894 (let ((case-fold-search))
8895 (replace-regexp-in-string
8896 (regexp-quote (cdr rep))
8897 (car rep)
8898 (key-description binding))))))
8899 (let ((key (lookup-key orgstruct-mode-map binding)))
8900 (when (or (not key) (numberp key))
8901 (condition-case nil
8902 (org-defkey orgstruct-mode-map
8903 binding
8904 (orgstruct-make-binding f binding disable-when-heading-prefix))
8905 (error nil))))))))
8906 (run-hooks 'orgstruct-setup-hook))
8908 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
8909 "Create a function for binding in the structure minor mode.
8910 FUN is the command to call inside a table. KEY is the key that
8911 should be checked in for a command to execute outside of tables.
8912 Non-nil DISABLE-WHEN-HEADING-PREFIX means to disable the command
8913 if `orgstruct-heading-prefix-regexp' is non-nil."
8914 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8915 (let ((nname name)
8916 (i 0))
8917 (while (fboundp (intern nname))
8918 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8919 (setq name (intern nname)))
8920 (eval
8921 (let ((bindings '((org-heading-regexp
8922 (concat "^"
8923 orgstruct-heading-prefix-regexp
8924 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8925 (org-outline-regexp
8926 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8927 (org-outline-regexp-bol
8928 (concat "^" org-outline-regexp))
8929 (outline-regexp org-outline-regexp)
8930 (outline-heading-end-regexp "\n")
8931 (outline-level 'org-outline-level)
8932 (outline-heading-alist))))
8933 `(defun ,name (arg)
8934 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
8935 "Outside of structure, run the binding of `"
8936 (key-description key) "'."
8937 (when disable-when-heading-prefix
8938 (concat
8939 "\nIf `orgstruct-heading-prefix-regexp' is non-nil, this command will always fall\n"
8940 "back to the default binding due to limitations of Org's implementation of\n"
8941 "`" (symbol-name fun) "'.")))
8942 (interactive "p")
8943 (let* ((disable
8944 ,(when disable-when-heading-prefix
8945 '(and orgstruct-heading-prefix-regexp
8946 (not (string= orgstruct-heading-prefix-regexp "")))))
8947 (fallback
8948 (or disable
8949 (not
8950 (let* ,bindings
8951 (org-context-p 'headline 'item
8952 ,(when (memq fun '(org-insert-heading))
8953 '(when orgstruct-is-++
8954 'item-body))))))))
8955 (if fallback
8956 (let* ((orgstruct-mode)
8957 (binding
8958 (loop with key = ,key
8959 for rep in
8960 '(nil
8961 ("<\\([^>]*\\)tab>" . "\\1TAB")
8962 ("<\\([^>]*\\)return>" . "\\1RET")
8963 ("<\\([^>]*\\)escape>" . "\\1ESC")
8964 ("<\\([^>]*\\)delete>" . "\\1DEL"))
8966 (when rep
8967 (setq key (read-kbd-macro
8968 (let ((case-fold-search))
8969 (replace-regexp-in-string
8970 (car rep)
8971 (cdr rep)
8972 (key-description key))))))
8973 thereis (key-binding key))))
8974 (if (keymapp binding)
8975 (set-temporary-overlay-map binding)
8976 (let ((func (or binding
8977 (unless disable
8978 'orgstruct-error))))
8979 (when func
8980 (call-interactively func)))))
8981 (org-run-like-in-org-mode
8982 (lambda ()
8983 (interactive)
8984 (let* ,bindings
8985 (call-interactively ',fun)))))))))
8986 name))
8988 (defun org-contextualize-keys (alist contexts)
8989 "Return valid elements in ALIST depending on CONTEXTS.
8991 `org-agenda-custom-commands' or `org-capture-templates' are the
8992 values used for ALIST, and `org-agenda-custom-commands-contexts'
8993 or `org-capture-templates-contexts' are the associated contexts
8994 definitions."
8995 (let ((contexts
8996 ;; normalize contexts
8997 (mapcar
8998 (lambda(c) (cond ((listp (cadr c))
8999 (list (car c) (car c) (cadr c)))
9000 ((string= "" (cadr c))
9001 (list (car c) (car c) (caddr c)))
9002 (t c))) contexts))
9003 (a alist) c r s)
9004 ;; loop over all commands or templates
9005 (while (setq c (pop a))
9006 (let (vrules repl)
9007 (cond
9008 ((not (assoc (car c) contexts))
9009 (push c r))
9010 ((and (assoc (car c) contexts)
9011 (setq vrules (org-contextualize-validate-key
9012 (car c) contexts)))
9013 (mapc (lambda (vr)
9014 (when (not (equal (car vr) (cadr vr)))
9015 (setq repl vr))) vrules)
9016 (if (not repl) (push c r)
9017 (push (cadr repl) s)
9018 (push
9019 (cons (car c)
9020 (cdr (or (assoc (cadr repl) alist)
9021 (error "Undefined key `%s' as contextual replacement for `%s'"
9022 (cadr repl) (car c)))))
9023 r))))))
9024 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9025 (delq
9027 (delete-dups
9028 (mapcar (lambda (x)
9029 (let ((tpl (car x)))
9030 (when (not (delq
9032 (mapcar (lambda(y)
9033 (equal y tpl)) s))) x)))
9034 (reverse r))))))
9036 (defun org-contextualize-validate-key (key contexts)
9037 "Check CONTEXTS for agenda or capture KEY."
9038 (let (r rr res)
9039 (while (setq r (pop contexts))
9040 (mapc
9041 (lambda (rr)
9042 (when
9043 (and (equal key (car r))
9044 (if (functionp rr) (funcall rr)
9045 (or (and (eq (car rr) 'in-file)
9046 (buffer-file-name)
9047 (string-match (cdr rr) (buffer-file-name)))
9048 (and (eq (car rr) 'in-mode)
9049 (string-match (cdr rr) (symbol-name major-mode)))
9050 (and (eq (car rr) 'in-buffer)
9051 (string-match (cdr rr) (buffer-name)))
9052 (when (and (eq (car rr) 'not-in-file)
9053 (buffer-file-name))
9054 (not (string-match (cdr rr) (buffer-file-name))))
9055 (when (eq (car rr) 'not-in-mode)
9056 (not (string-match (cdr rr) (symbol-name major-mode))))
9057 (when (eq (car rr) 'not-in-buffer)
9058 (not (string-match (cdr rr) (buffer-name)))))))
9059 (push r res)))
9060 (car (last r))))
9061 (delete-dups (delq nil res))))
9063 (defun org-context-p (&rest contexts)
9064 "Check if local context is any of CONTEXTS.
9065 Possible values in the list of contexts are `table', `headline', and `item'."
9066 (let ((pos (point)))
9067 (goto-char (point-at-bol))
9068 (prog1 (or (and (memq 'table contexts)
9069 (looking-at "[ \t]*|"))
9070 (and (memq 'headline contexts)
9071 (looking-at org-outline-regexp))
9072 (and (memq 'item contexts)
9073 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9074 (and (memq 'item-body contexts)
9075 (org-in-item-p)))
9076 (goto-char pos))))
9078 (defun org-get-local-variables ()
9079 "Return a list of all local variables in an Org mode buffer."
9080 (let (varlist)
9081 (with-current-buffer (get-buffer-create "*Org tmp*")
9082 (erase-buffer)
9083 (org-mode)
9084 (setq varlist (buffer-local-variables)))
9085 (kill-buffer "*Org tmp*")
9086 (delq nil
9087 (mapcar
9088 (lambda (x)
9089 (setq x
9090 (if (symbolp x)
9091 (list x)
9092 (list (car x) (cdr x))))
9093 (if (and (not (get (car x) 'org-state))
9094 (string-match
9095 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9096 (symbol-name (car x))))
9097 x nil))
9098 varlist))))
9100 (defun org-clone-local-variables (from-buffer &optional regexp)
9101 "Clone local variables from FROM-BUFFER.
9102 Optional argument REGEXP selects variables to clone."
9103 (mapc
9104 (lambda (pair)
9105 (and (symbolp (car pair))
9106 (or (null regexp)
9107 (string-match regexp (symbol-name (car pair))))
9108 (set (make-local-variable (car pair))
9109 (cdr pair))))
9110 (buffer-local-variables from-buffer)))
9112 ;;;###autoload
9113 (defun org-run-like-in-org-mode (cmd)
9114 "Run a command, pretending that the current buffer is in Org-mode.
9115 This will temporarily bind local variables that are typically bound in
9116 Org-mode to the values they have in Org-mode, and then interactively
9117 call CMD."
9118 (org-load-modules-maybe)
9119 (unless org-local-vars
9120 (setq org-local-vars (org-get-local-variables)))
9121 (let (binds)
9122 (dolist (var org-local-vars)
9123 (when (or (not (boundp (car var)))
9124 (eq (symbol-value (car var))
9125 (default-value (car var))))
9126 (push (list (car var) `(quote ,(cadr var))) binds)))
9127 (eval `(let ,binds
9128 (call-interactively (quote ,cmd))))))
9130 ;;;; Archiving
9132 (defun org-get-category (&optional pos force-refresh)
9133 "Get the category applying to position POS."
9134 (save-match-data
9135 (if force-refresh (org-refresh-category-properties))
9136 (let ((pos (or pos (point))))
9137 (or (get-text-property pos 'org-category)
9138 (progn (org-refresh-category-properties)
9139 (get-text-property pos 'org-category))))))
9141 (defun org-refresh-category-properties ()
9142 "Refresh category text properties in the buffer."
9143 (let ((case-fold-search t)
9144 (inhibit-read-only t)
9145 (def-cat (cond
9146 ((null org-category)
9147 (if buffer-file-name
9148 (file-name-sans-extension
9149 (file-name-nondirectory buffer-file-name))
9150 "???"))
9151 ((symbolp org-category) (symbol-name org-category))
9152 (t org-category)))
9153 beg end cat pos optionp)
9154 (org-with-silent-modifications
9155 (save-excursion
9156 (save-restriction
9157 (widen)
9158 (goto-char (point-min))
9159 (put-text-property (point) (point-max) 'org-category def-cat)
9160 (while (re-search-forward
9161 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9162 (setq pos (match-end 0)
9163 optionp (equal (char-after (match-beginning 0)) ?#)
9164 cat (org-trim (match-string 2)))
9165 (if optionp
9166 (setq beg (point-at-bol) end (point-max))
9167 (org-back-to-heading t)
9168 (setq beg (point) end (org-end-of-subtree t t)))
9169 (put-text-property beg end 'org-category cat)
9170 (put-text-property beg end 'org-category-position beg)
9171 (goto-char pos)))))))
9173 (defun org-refresh-properties (dprop tprop)
9174 "Refresh buffer text properties.
9175 DPROP is the drawer property and TPROP is the corresponding text
9176 property to set."
9177 (let ((case-fold-search t)
9178 (inhibit-read-only t) p)
9179 (org-with-silent-modifications
9180 (save-excursion
9181 (save-restriction
9182 (widen)
9183 (goto-char (point-min))
9184 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9185 (setq p (org-match-string-no-properties 1))
9186 (save-excursion
9187 (org-back-to-heading t)
9188 (put-text-property
9189 (point-at-bol) (point-at-eol) tprop p))))))))
9192 ;;;; Link Stuff
9194 ;;; Link abbreviations
9196 (defun org-link-expand-abbrev (link)
9197 "Apply replacements as defined in `org-link-abbrev-alist'."
9198 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9199 (let* ((key (match-string 1 link))
9200 (as (or (assoc key org-link-abbrev-alist-local)
9201 (assoc key org-link-abbrev-alist)))
9202 (tag (and (match-end 2) (match-string 3 link)))
9203 rpl)
9204 (if (not as)
9205 link
9206 (setq rpl (cdr as))
9207 (cond
9208 ((symbolp rpl) (funcall rpl tag))
9209 ((string-match "%(\\([^)]+\\))" rpl)
9210 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
9211 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9212 ((string-match "%h" rpl)
9213 (replace-match (url-hexify-string (or tag "")) t t rpl))
9214 (t (concat rpl tag)))))
9215 link))
9217 ;;; Storing and inserting links
9219 (defvar org-insert-link-history nil
9220 "Minibuffer history for links inserted with `org-insert-link'.")
9222 (defvar org-stored-links nil
9223 "Contains the links stored with `org-store-link'.")
9225 (defvar org-store-link-plist nil
9226 "Plist with info about the most recently link created with `org-store-link'.")
9228 (defvar org-link-protocols nil
9229 "Link protocols added to Org-mode using `org-add-link-type'.")
9231 (defvar org-store-link-functions nil
9232 "List of functions that are called to create and store a link.
9233 Each function will be called in turn until one returns a non-nil
9234 value. Each function should check if it is responsible for creating
9235 this link (for example by looking at the major mode).
9236 If not, it must exit and return nil.
9237 If yes, it should return a non-nil value after a calling
9238 `org-store-link-props' with a list of properties and values.
9239 Special properties are:
9241 :type The link prefix, like \"http\". This must be given.
9242 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9243 This is obligatory as well.
9244 :description Optional default description for the second pair
9245 of brackets in an Org-mode link. The user can still change
9246 this when inserting this link into an Org-mode buffer.
9248 In addition to these, any additional properties can be specified
9249 and then used in capture templates.")
9251 (defun org-add-link-type (type &optional follow export)
9252 "Add TYPE to the list of `org-link-types'.
9253 Re-compute all regular expressions depending on `org-link-types'
9255 FOLLOW and EXPORT are two functions.
9257 FOLLOW should take the link path as the single argument and do whatever
9258 is necessary to follow the link, for example find a file or display
9259 a mail message.
9261 EXPORT should format the link path for export to one of the export formats.
9262 It should be a function accepting three arguments:
9264 path the path of the link, the text after the prefix (like \"http:\")
9265 desc the description of the link, if any, or a description added by
9266 org-export-normalize-links if there is none
9267 format the export format, a symbol like `html' or `latex' or `ascii'..
9269 The function may use the FORMAT information to return different values
9270 depending on the format. The return value will be put literally into
9271 the exported file. If the return value is nil, this means Org should
9272 do what it normally does with links which do not have EXPORT defined.
9274 Org-mode has a built-in default for exporting links. If you are happy with
9275 this default, there is no need to define an export function for the link
9276 type. For a simple example of an export function, see `org-bbdb.el'."
9277 (add-to-list 'org-link-types type t)
9278 (org-make-link-regexps)
9279 (if (assoc type org-link-protocols)
9280 (setcdr (assoc type org-link-protocols) (list follow export))
9281 (push (list type follow export) org-link-protocols)))
9283 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9284 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9286 ;;;###autoload
9287 (defun org-store-link (arg)
9288 "\\<org-mode-map>Store an org-link to the current location.
9289 This link is added to `org-stored-links' and can later be inserted
9290 into an org-buffer with \\[org-insert-link].
9292 For some link types, a prefix arg is interpreted.
9293 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9294 For file links, arg negates `org-context-in-file-links'.
9296 A double prefix arg force skipping storing functions that are not
9297 part of Org's core.
9299 A triple prefix arg force storing a link for each line in the
9300 active region."
9301 (interactive "P")
9302 (org-load-modules-maybe)
9303 (if (and (equal arg '(64)) (org-region-active-p))
9304 (save-excursion
9305 (let ((end (region-end)))
9306 (goto-char (region-beginning))
9307 (set-mark (point))
9308 (while (< (point-at-eol) end)
9309 (move-end-of-line 1) (activate-mark)
9310 (let (current-prefix-arg)
9311 (call-interactively 'org-store-link))
9312 (move-beginning-of-line 2)
9313 (set-mark (point)))))
9314 (org-with-limited-levels
9315 (setq org-store-link-plist nil)
9316 (let (link cpltxt desc description search
9317 txt custom-id agenda-link sfuns sfunsn)
9318 (cond
9320 ;; Store a link using an external link type
9321 ((and (not (equal arg '(16)))
9322 (setq sfuns
9323 (delq
9324 nil (mapcar (lambda (f)
9325 (let (fs) (if (funcall f) (push f fs))))
9326 org-store-link-functions))
9327 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9328 (or (and (cdr sfuns)
9329 (funcall (intern
9330 (completing-read
9331 "Which function for creating the link? "
9332 sfunsn t (car sfunsn)))))
9333 (funcall (caar sfuns)))
9334 (setq link (plist-get org-store-link-plist :link)
9335 desc (or (plist-get org-store-link-plist
9336 :description) link))))
9338 ;; Store a link from a source code buffer
9339 ((org-src-edit-buffer-p)
9340 (let (label gc)
9341 (while (or (not label)
9342 (save-excursion
9343 (save-restriction
9344 (widen)
9345 (goto-char (point-min))
9346 (re-search-forward
9347 (regexp-quote (format org-coderef-label-format label))
9348 nil t))))
9349 (when label (message "Label exists already") (sit-for 2))
9350 (setq label (read-string "Code line label: " label)))
9351 (end-of-line 1)
9352 (setq link (format org-coderef-label-format label))
9353 (setq gc (- 79 (length link)))
9354 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9355 (insert link)
9356 (setq link (concat "(" label ")") desc nil)))
9358 ;; We are in the agenda, link to referenced location
9359 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9360 (let ((m (or (get-text-property (point) 'org-hd-marker)
9361 (get-text-property (point) 'org-marker))))
9362 (when m
9363 (org-with-point-at m
9364 (setq agenda-link
9365 (if (org-called-interactively-p 'any)
9366 (call-interactively 'org-store-link)
9367 (org-store-link nil)))))))
9369 ((eq major-mode 'calendar-mode)
9370 (let ((cd (calendar-cursor-to-date)))
9371 (setq link
9372 (format-time-string
9373 (car org-time-stamp-formats)
9374 (apply 'encode-time
9375 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9376 nil nil nil))))
9377 (org-store-link-props :type "calendar" :date cd)))
9379 ((eq major-mode 'help-mode)
9380 (setq link (concat "help:" (save-excursion
9381 (goto-char (point-min))
9382 (looking-at "^[^ ]+")
9383 (match-string 0))))
9384 (org-store-link-props :type "help"))
9386 ((eq major-mode 'w3-mode)
9387 (setq cpltxt (if (and (buffer-name)
9388 (not (string-match "Untitled" (buffer-name))))
9389 (buffer-name)
9390 (url-view-url t))
9391 link (url-view-url t))
9392 (org-store-link-props :type "w3" :url (url-view-url t)))
9394 ((eq major-mode 'image-mode)
9395 (setq cpltxt (concat "file:"
9396 (abbreviate-file-name buffer-file-name))
9397 link cpltxt)
9398 (org-store-link-props :type "image" :file buffer-file-name))
9400 ;; In dired, store a link to the file of the current line
9401 ((eq major-mode 'dired-mode)
9402 (let ((file (dired-get-filename nil t)))
9403 (setq file (if file
9404 (abbreviate-file-name
9405 (expand-file-name (dired-get-filename nil t)))
9406 ;; otherwise, no file so use current directory.
9407 default-directory))
9408 (setq cpltxt (concat "file:" file)
9409 link cpltxt)))
9411 ((setq search (run-hook-with-args-until-success
9412 'org-create-file-search-functions))
9413 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9414 "::" search))
9415 (setq cpltxt (or description link)))
9417 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9418 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9419 (cond
9420 ;; Store a link using the radio target at point
9421 ((org-in-regexp "<<\\(.*?\\)>>")
9422 (setq cpltxt
9423 (concat "file:"
9424 (abbreviate-file-name
9425 (buffer-file-name (buffer-base-buffer)))
9426 "::" (match-string 1))
9427 link cpltxt))
9428 ((and (featurep 'org-id)
9429 (or (eq org-id-link-to-org-use-id t)
9430 (and (org-called-interactively-p 'any)
9431 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9432 (and (eq org-id-link-to-org-use-id
9433 'create-if-interactive-and-no-custom-id)
9434 (not custom-id))))
9435 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9436 ;; Store a link using the ID at point
9437 (setq link (condition-case nil
9438 (prog1 (org-id-store-link)
9439 (setq desc (plist-get org-store-link-plist
9440 :description)))
9441 (error
9442 ;; Probably before first headline, link only to file
9443 (concat "file:"
9444 (abbreviate-file-name
9445 (buffer-file-name (buffer-base-buffer))))))))
9447 ;; Just link to current headline
9448 (setq cpltxt (concat "file:"
9449 (abbreviate-file-name
9450 (buffer-file-name (buffer-base-buffer)))))
9451 ;; Add a context search string
9452 (when (org-xor org-context-in-file-links arg)
9453 (let* ((ee (org-element-at-point))
9454 (et (org-element-type ee))
9455 (ev (plist-get (cadr ee) :value))
9456 (ek (plist-get (cadr ee) :key))
9457 (eok (and (stringp ek) (string-match "name\\|target" ek))))
9458 (setq txt (cond
9459 ((org-at-heading-p) nil)
9460 ((and (eq et 'keyword) eok) ev)
9461 ((org-region-active-p)
9462 (buffer-substring (region-beginning) (region-end)))))
9463 (when (or (null txt) (string-match "\\S-" txt))
9464 (setq cpltxt
9465 (concat cpltxt "::"
9466 (condition-case nil
9467 (org-make-org-heading-search-string txt)
9468 (error "")))
9469 desc (or (and (eq et 'keyword) eok ev)
9470 (nth 4 (ignore-errors (org-heading-components)))
9471 "NONE")))))
9472 (if (string-match "::\\'" cpltxt)
9473 (setq cpltxt (substring cpltxt 0 -2)))
9474 (setq link cpltxt))))
9476 ((buffer-file-name (buffer-base-buffer))
9477 ;; Just link to this file here.
9478 (setq cpltxt (concat "file:"
9479 (abbreviate-file-name
9480 (buffer-file-name (buffer-base-buffer)))))
9481 ;; Add a context string.
9482 (when (org-xor org-context-in-file-links arg)
9483 (setq txt (if (org-region-active-p)
9484 (buffer-substring (region-beginning) (region-end))
9485 (buffer-substring (point-at-bol) (point-at-eol))))
9486 ;; Only use search option if there is some text.
9487 (when (string-match "\\S-" txt)
9488 (setq cpltxt
9489 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9490 desc "NONE")))
9491 (setq link cpltxt))
9493 ((org-called-interactively-p 'interactive)
9494 (user-error "No method for storing a link from this buffer"))
9496 (t (setq link nil)))
9498 ;; We're done setting link and desc, clean up
9499 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9500 (setq link (or link cpltxt)
9501 desc (or desc cpltxt))
9502 (cond ((equal desc "NONE") (setq desc nil))
9503 ((string-match org-bracket-link-regexp desc)
9504 (setq desc
9505 (replace-regexp-in-string
9506 org-bracket-link-regexp
9507 (concat "\\3" (if (equal (length (match-string 0 desc))
9508 (length desc)) "*" "")) desc))))
9510 ;; Return the link
9511 (if (not (and (or (org-called-interactively-p 'any)
9512 executing-kbd-macro) link))
9513 (or agenda-link (and link (org-make-link-string link desc)))
9514 (push (list link desc) org-stored-links)
9515 (message "Stored: %s" (or desc link))
9516 (when custom-id
9517 (setq link (concat "file:" (abbreviate-file-name
9518 (buffer-file-name)) "::#" custom-id))
9519 (push (list link desc) org-stored-links)))))))
9521 (defun org-store-link-props (&rest plist)
9522 "Store link properties, extract names and addresses."
9523 (let (x adr)
9524 (when (setq x (plist-get plist :from))
9525 (setq adr (mail-extract-address-components x))
9526 (setq plist (plist-put plist :fromname (car adr)))
9527 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9528 (when (setq x (plist-get plist :to))
9529 (setq adr (mail-extract-address-components x))
9530 (setq plist (plist-put plist :toname (car adr)))
9531 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9532 (let ((from (plist-get plist :from))
9533 (to (plist-get plist :to)))
9534 (when (and from to org-from-is-user-regexp)
9535 (setq plist
9536 (plist-put plist :fromto
9537 (if (string-match org-from-is-user-regexp from)
9538 (concat "to %t")
9539 (concat "from %f"))))))
9540 (setq org-store-link-plist plist))
9542 (defun org-add-link-props (&rest plist)
9543 "Add these properties to the link property list."
9544 (let (key value)
9545 (while plist
9546 (setq key (pop plist) value (pop plist))
9547 (setq org-store-link-plist
9548 (plist-put org-store-link-plist key value)))))
9550 (defun org-email-link-description (&optional fmt)
9551 "Return the description part of an email link.
9552 This takes information from `org-store-link-plist' and formats it
9553 according to FMT (default from `org-email-link-description-format')."
9554 (setq fmt (or fmt org-email-link-description-format))
9555 (let* ((p org-store-link-plist)
9556 (to (plist-get p :toaddress))
9557 (from (plist-get p :fromaddress))
9558 (table
9559 (list
9560 (cons "%c" (plist-get p :fromto))
9561 (cons "%F" (plist-get p :from))
9562 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9563 (cons "%T" (plist-get p :to))
9564 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9565 (cons "%s" (plist-get p :subject))
9566 (cons "%d" (plist-get p :date))
9567 (cons "%m" (plist-get p :message-id)))))
9568 (when (string-match "%c" fmt)
9569 ;; Check if the user wrote this message
9570 (if (and org-from-is-user-regexp from to
9571 (save-match-data (string-match org-from-is-user-regexp from)))
9572 (setq fmt (replace-match "to %t" t t fmt))
9573 (setq fmt (replace-match "from %f" t t fmt))))
9574 (org-replace-escapes fmt table)))
9576 (defun org-make-org-heading-search-string (&optional string)
9577 "Make search string for the current headline or STRING."
9578 (let ((s (or string
9579 (and (derived-mode-p 'org-mode)
9580 (save-excursion
9581 (org-back-to-heading t)
9582 (org-element-property :raw-value (org-element-at-point))))))
9583 (lines org-context-in-file-links))
9584 (or string (setq s (concat "*" s))) ; Add * for headlines
9585 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9586 (when (and string (integerp lines) (> lines 0))
9587 (let ((slines (org-split-string s "\n")))
9588 (when (< lines (length slines))
9589 (setq s (mapconcat
9590 'identity
9591 (reverse (nthcdr (- (length slines) lines)
9592 (reverse slines))) "\n")))))
9593 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9595 (defun org-make-link-string (link &optional description)
9596 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9597 (unless (string-match "\\S-" link)
9598 (error "Empty link"))
9599 (when (and description
9600 (stringp description)
9601 (not (string-match "\\S-" description)))
9602 (setq description nil))
9603 (when (stringp description)
9604 ;; Remove brackets from the description, they are fatal.
9605 (while (string-match "\\[" description)
9606 (setq description (replace-match "{" t t description)))
9607 (while (string-match "\\]" description)
9608 (setq description (replace-match "}" t t description))))
9609 (when (equal link description)
9610 ;; No description needed, it is identical
9611 (setq description nil))
9612 (when (and (not description)
9613 (not (string-match (org-image-file-name-regexp) link))
9614 (not (equal link (org-link-escape link))))
9615 (setq description (org-extract-attributes link)))
9616 (setq link
9617 (cond ((string-match (org-image-file-name-regexp) link) link)
9618 ((string-match org-link-types-re link)
9619 (concat (match-string 1 link)
9620 (org-link-escape (substring link (match-end 1)))))
9621 (t (org-link-escape link))))
9622 (concat "[[" link "]"
9623 (if description (concat "[" description "]") "")
9624 "]"))
9626 (defconst org-link-escape-chars
9627 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9628 "List of characters that should be escaped in link.
9629 This is the list that is used for internal purposes.")
9631 (defconst org-link-escape-chars-browser
9632 '(?\ )
9633 "List of escapes for characters that are problematic in links.
9634 This is the list that is used before handing over to the browser.")
9636 (defun org-link-escape (text &optional table merge)
9637 "Return percent escaped representation of TEXT.
9638 TEXT is a string with the text to escape.
9639 Optional argument TABLE is a list with characters that should be
9640 escaped. When nil, `org-link-escape-chars' is used.
9641 If optional argument MERGE is set, merge TABLE into
9642 `org-link-escape-chars'."
9643 (cond
9644 ((and table merge)
9645 (mapc (lambda (defchr)
9646 (unless (member defchr table)
9647 (setq table (cons defchr table)))) org-link-escape-chars))
9648 ((null table)
9649 (setq table org-link-escape-chars)))
9650 (mapconcat
9651 (lambda (char)
9652 (if (or (member char table)
9653 (and (or (< char 32) (= char 37) (> char 126))
9654 org-url-hexify-p))
9655 (mapconcat (lambda (sequence-element)
9656 (format "%%%.2X" sequence-element))
9657 (or (encode-coding-char char 'utf-8)
9658 (error "Unable to percent escape character: %s"
9659 (char-to-string char))) "")
9660 (char-to-string char))) text ""))
9662 (defun org-link-unescape (str)
9663 "Unhex hexified Unicode strings as returned from the JavaScript function
9664 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9665 (unless (and (null str) (string= "" str))
9666 (let ((pos 0) (case-fold-search t) unhexed)
9667 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9668 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9669 (setq str (replace-match unhexed t t str))
9670 (setq pos (+ pos (length unhexed))))))
9671 str)
9673 (defun org-link-unescape-compound (hex)
9674 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9675 Note: this function also decodes single byte encodings like
9676 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9677 (save-match-data
9678 (let* ((bytes (cdr (split-string hex "%")))
9679 (ret "")
9680 (eat 0)
9681 (sum 0))
9682 (while bytes
9683 (let* ((val (string-to-number (pop bytes) 16))
9684 (shift-xor
9685 (if (= 0 eat)
9686 (cond
9687 ((>= val 252) (cons 6 252))
9688 ((>= val 248) (cons 5 248))
9689 ((>= val 240) (cons 4 240))
9690 ((>= val 224) (cons 3 224))
9691 ((>= val 192) (cons 2 192))
9692 (t (cons 0 0)))
9693 (cons 6 128))))
9694 (if (>= val 192) (setq eat (car shift-xor)))
9695 (setq val (logxor val (cdr shift-xor)))
9696 (setq sum (+ (lsh sum (car shift-xor)) val))
9697 (if (> eat 0) (setq eat (- eat 1)))
9698 (cond
9699 ((= 0 eat) ;multi byte
9700 (setq ret (concat ret (org-char-to-string sum)))
9701 (setq sum 0))
9702 ((not bytes) ; single byte(s)
9703 (setq ret (org-link-unescape-single-byte-sequence hex))))
9704 )) ;; end (while bytes
9705 ret )))
9707 (defun org-link-unescape-single-byte-sequence (hex)
9708 "Unhexify hex-encoded single byte character sequences."
9709 (mapconcat (lambda (byte)
9710 (char-to-string (string-to-number byte 16)))
9711 (cdr (split-string hex "%")) ""))
9713 (defun org-xor (a b)
9714 "Exclusive or."
9715 (if a (not b) b))
9717 (defun org-fixup-message-id-for-http (s)
9718 "Replace special characters in a message id, so it can be used in an http query."
9719 (when (string-match "%" s)
9720 (setq s (mapconcat (lambda (c)
9721 (if (eq c ?%)
9722 "%25"
9723 (char-to-string c)))
9724 s "")))
9725 (while (string-match "<" s)
9726 (setq s (replace-match "%3C" t t s)))
9727 (while (string-match ">" s)
9728 (setq s (replace-match "%3E" t t s)))
9729 (while (string-match "@" s)
9730 (setq s (replace-match "%40" t t s)))
9733 (defun org-link-prettify (link)
9734 "Return a human-readable representation of LINK.
9735 The car of LINK must be a raw link the cdr of LINK must be either
9736 a link description or nil."
9737 (let ((desc (or (cadr link) "<no description>")))
9738 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9739 "<" (car link) ">")))
9741 ;;;###autoload
9742 (defun org-insert-link-global ()
9743 "Insert a link like Org-mode does.
9744 This command can be called in any mode to insert a link in Org-mode syntax."
9745 (interactive)
9746 (org-load-modules-maybe)
9747 (org-run-like-in-org-mode 'org-insert-link))
9749 (defun org-insert-all-links (&optional keep)
9750 "Insert all links in `org-stored-links'."
9751 (interactive "P")
9752 (let ((links (copy-sequence org-stored-links)) l)
9753 (while (setq l (if keep (pop links) (pop org-stored-links)))
9754 (insert "- ")
9755 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9756 (insert "\n"))))
9758 (defun org-link-fontify-links-to-this-file ()
9759 "Fontify links to the current file in `org-stored-links'."
9760 (let ((f (buffer-file-name)) a b)
9761 (setq a (mapcar (lambda(l)
9762 (let ((ll (car l)))
9763 (when (and (string-match "^file:\\(.+\\)::" ll)
9764 (equal f (expand-file-name (match-string 1 ll))))
9765 ll)))
9766 org-stored-links))
9767 (when (featurep 'org-id)
9768 (setq b (mapcar (lambda(l)
9769 (let ((ll (car l)))
9770 (when (and (string-match "^id:\\(.+\\)$" ll)
9771 (equal f (expand-file-name
9772 (or (org-id-find-id-file
9773 (match-string 1 ll)) ""))))
9774 ll)))
9775 org-stored-links)))
9776 (mapcar (lambda(l)
9777 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9778 (delq nil (append a b)))))
9780 (defvar org-link-links-in-this-file nil)
9781 (defun org-insert-link (&optional complete-file link-location default-description)
9782 "Insert a link. At the prompt, enter the link.
9784 Completion can be used to insert any of the link protocol prefixes like
9785 http or ftp in use.
9787 The history can be used to select a link previously stored with
9788 `org-store-link'. When the empty string is entered (i.e. if you just
9789 press RET at the prompt), the link defaults to the most recently
9790 stored link. As SPC triggers completion in the minibuffer, you need to
9791 use M-SPC or C-q SPC to force the insertion of a space character.
9793 You will also be prompted for a description, and if one is given, it will
9794 be displayed in the buffer instead of the link.
9796 If there is already a link at point, this command will allow you to edit link
9797 and description parts.
9799 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9800 be selected using completion. The path to the file will be relative to the
9801 current directory if the file is in the current directory or a subdirectory.
9802 Otherwise, the link will be the absolute path as completed in the minibuffer
9803 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9804 option `org-link-file-path-type'.
9806 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9807 the current directory or below.
9809 With three \\[universal-argument] prefixes, negate the meaning of
9810 `org-keep-stored-link-after-insertion'.
9812 If `org-make-link-description-function' is non-nil, this function will be
9813 called with the link target, and the result will be the default
9814 link description.
9816 If the LINK-LOCATION parameter is non-nil, this value will be
9817 used as the link location instead of reading one interactively.
9819 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9820 be used as the default description."
9821 (interactive "P")
9822 (let* ((wcf (current-window-configuration))
9823 (origbuf (current-buffer))
9824 (region (if (org-region-active-p)
9825 (buffer-substring (region-beginning) (region-end))))
9826 (remove (and region (list (region-beginning) (region-end))))
9827 (desc region)
9828 tmphist ; byte-compile incorrectly complains about this
9829 (link link-location)
9830 (abbrevs org-link-abbrev-alist-local)
9831 entry file all-prefixes auto-desc)
9832 (cond
9833 (link-location) ; specified by arg, just use it.
9834 ((org-in-regexp org-bracket-link-regexp 1)
9835 ;; We do have a link at point, and we are going to edit it.
9836 (setq remove (list (match-beginning 0) (match-end 0)))
9837 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9838 (setq link (read-string "Link: "
9839 (org-link-unescape
9840 (org-match-string-no-properties 1)))))
9841 ((or (org-in-regexp org-angle-link-re)
9842 (org-in-regexp org-plain-link-re))
9843 ;; Convert to bracket link
9844 (setq remove (list (match-beginning 0) (match-end 0))
9845 link (read-string "Link: "
9846 (org-remove-angle-brackets (match-string 0)))))
9847 ((member complete-file '((4) (16)))
9848 ;; Completing read for file names.
9849 (setq link (org-file-complete-link complete-file)))
9851 ;; Read link, with completion for stored links.
9852 (org-link-fontify-links-to-this-file)
9853 (org-switch-to-buffer-other-window "*Org Links*")
9854 (with-current-buffer "*Org Links*"
9855 (erase-buffer)
9856 (insert "Insert a link.
9857 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9858 (when org-stored-links
9859 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9860 (insert (mapconcat 'org-link-prettify
9861 (reverse org-stored-links) "\n")))
9862 (goto-char (point-min)))
9863 (let ((cw (selected-window)))
9864 (select-window (get-buffer-window "*Org Links*" 'visible))
9865 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9866 (unless (pos-visible-in-window-p (point-max))
9867 (org-fit-window-to-buffer))
9868 (and (window-live-p cw) (select-window cw)))
9869 ;; Fake a link history, containing the stored links.
9870 (setq tmphist (append (mapcar 'car org-stored-links)
9871 org-insert-link-history))
9872 (setq all-prefixes (append (mapcar 'car abbrevs)
9873 (mapcar 'car org-link-abbrev-alist)
9874 org-link-types))
9875 (unwind-protect
9876 (progn
9877 (setq link
9878 (org-completing-read
9879 "Link: "
9880 (append
9881 (mapcar (lambda (x) (concat x ":"))
9882 all-prefixes)
9883 (mapcar 'car org-stored-links))
9884 nil nil nil
9885 'tmphist
9886 (caar org-stored-links)))
9887 (if (not (string-match "\\S-" link))
9888 (error "No link selected"))
9889 (mapc (lambda(l)
9890 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9891 org-stored-links)
9892 (if (or (member link all-prefixes)
9893 (and (equal ":" (substring link -1))
9894 (member (substring link 0 -1) all-prefixes)
9895 (setq link (substring link 0 -1))))
9896 (setq link (with-current-buffer origbuf
9897 (org-link-try-special-completion link)))))
9898 (set-window-configuration wcf)
9899 (kill-buffer "*Org Links*"))
9900 (setq entry (assoc link org-stored-links))
9901 (or entry (push link org-insert-link-history))
9902 (setq desc (or desc (nth 1 entry)))))
9904 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9905 (not org-keep-stored-link-after-insertion))
9906 (setq org-stored-links (delq (assoc link org-stored-links)
9907 org-stored-links)))
9909 (if (string-match org-plain-link-re link)
9910 ;; URL-like link, normalize the use of angular brackets.
9911 (setq link (org-remove-angle-brackets link)))
9913 ;; Check if we are linking to the current file with a search
9914 ;; option If yes, simplify the link by using only the search
9915 ;; option.
9916 (when (and buffer-file-name
9917 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9918 (let* ((path (match-string 1 link))
9919 (case-fold-search nil)
9920 (search (match-string 2 link)))
9921 (save-match-data
9922 (if (equal (file-truename buffer-file-name) (file-truename path))
9923 ;; We are linking to this same file, with a search option
9924 (setq link search)))))
9926 ;; Check if we can/should use a relative path. If yes, simplify the link
9927 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9928 (let* ((type (match-string 1 link))
9929 (path (match-string 2 link))
9930 (origpath path)
9931 (case-fold-search nil))
9932 (cond
9933 ((or (eq org-link-file-path-type 'absolute)
9934 (equal complete-file '(16)))
9935 (setq path (abbreviate-file-name (expand-file-name path))))
9936 ((eq org-link-file-path-type 'noabbrev)
9937 (setq path (expand-file-name path)))
9938 ((eq org-link-file-path-type 'relative)
9939 (setq path (file-relative-name path)))
9941 (save-match-data
9942 (if (string-match (concat "^" (regexp-quote
9943 (expand-file-name
9944 (file-name-as-directory
9945 default-directory))))
9946 (expand-file-name path))
9947 ;; We are linking a file with relative path name.
9948 (setq path (substring (expand-file-name path)
9949 (match-end 0)))
9950 (setq path (abbreviate-file-name (expand-file-name path)))))))
9951 (setq link (concat type path))
9952 (if (equal desc origpath)
9953 (setq desc path))))
9955 (if org-make-link-description-function
9956 (setq desc
9957 (or (condition-case nil
9958 (funcall org-make-link-description-function link desc)
9959 (error (progn (message "Can't get link description from `%s'"
9960 (symbol-name org-make-link-description-function))
9961 (sit-for 2) nil)))
9962 (read-string "Description: " default-description)))
9963 (if default-description (setq desc default-description)
9964 (setq desc (or (and auto-desc desc)
9965 (read-string "Description: " desc)))))
9967 (unless (string-match "\\S-" desc) (setq desc nil))
9968 (if remove (apply 'delete-region remove))
9969 (insert (org-make-link-string link desc))))
9971 (defun org-link-try-special-completion (type)
9972 "If there is completion support for link type TYPE, offer it."
9973 (let ((fun (intern (concat "org-" type "-complete-link"))))
9974 (if (functionp fun)
9975 (funcall fun)
9976 (read-string "Link (no completion support): " (concat type ":")))))
9978 (defun org-file-complete-link (&optional arg)
9979 "Create a file link using completion."
9980 (let (file link)
9981 (setq file (org-iread-file-name "File: "))
9982 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9983 (pwd1 (file-name-as-directory (abbreviate-file-name
9984 (expand-file-name ".")))))
9985 (cond
9986 ((equal arg '(16))
9987 (setq link (concat
9988 "file:"
9989 (abbreviate-file-name (expand-file-name file)))))
9990 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9991 (setq link (concat "file:" (match-string 1 file))))
9992 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9993 (expand-file-name file))
9994 (setq link (concat
9995 "file:" (match-string 1 (expand-file-name file)))))
9996 (t (setq link (concat "file:" file)))))
9997 link))
9999 (defun org-iread-file-name (&rest args)
10000 "Read-file-name using `ido-mode' speedup if available.
10001 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10002 See `read-file-name' for a description of parameters."
10003 (org-without-partial-completion
10004 (if (and org-completion-use-ido
10005 (fboundp 'ido-read-file-name)
10006 (boundp 'ido-mode) ido-mode
10007 (listp (second args)))
10008 (let ((ido-enter-matching-directory nil))
10009 (apply 'ido-read-file-name args))
10010 (apply 'read-file-name args))))
10012 (defun org-completing-read (&rest args)
10013 "Completing-read with SPACE being a normal character."
10014 (let ((enable-recursive-minibuffers t)
10015 (minibuffer-local-completion-map
10016 (copy-keymap minibuffer-local-completion-map)))
10017 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10018 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10019 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10020 (apply 'org-icompleting-read args)))
10022 (defun org-completing-read-no-i (&rest args)
10023 (let (org-completion-use-ido org-completion-use-iswitchb)
10024 (apply 'org-completing-read args)))
10026 (defun org-iswitchb-completing-read (prompt choices &rest args)
10027 "Use iswitch as a completing-read replacement to choose from choices.
10028 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10029 from."
10030 (let* ((iswitchb-use-virtual-buffers nil)
10031 (iswitchb-make-buflist-hook
10032 (lambda ()
10033 (setq iswitchb-temp-buflist choices))))
10034 (iswitchb-read-buffer prompt)))
10036 (defun org-icompleting-read (&rest args)
10037 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10038 (org-without-partial-completion
10039 (if (and org-completion-use-ido
10040 (fboundp 'ido-completing-read)
10041 (boundp 'ido-mode) ido-mode
10042 (listp (second args)))
10043 (let ((ido-enter-matching-directory nil))
10044 (apply 'ido-completing-read (concat (car args))
10045 (if (consp (car (nth 1 args)))
10046 (mapcar 'car (nth 1 args))
10047 (nth 1 args))
10048 (cddr args)))
10049 (if (and org-completion-use-iswitchb
10050 (boundp 'iswitchb-mode) iswitchb-mode
10051 (listp (second args)))
10052 (apply 'org-iswitchb-completing-read (concat (car args))
10053 (if (consp (car (nth 1 args)))
10054 (mapcar 'car (nth 1 args))
10055 (nth 1 args))
10056 (cddr args))
10057 (apply 'completing-read args)))))
10059 (defun org-extract-attributes (s)
10060 "Extract the attributes cookie from a string and set as text property."
10061 (let (a attr (start 0) key value)
10062 (save-match-data
10063 (when (string-match "{{\\([^}]+\\)}}$" s)
10064 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10065 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10066 (setq key (match-string 1 a) value (match-string 2 a)
10067 start (match-end 0)
10068 attr (plist-put attr (intern key) value))))
10069 (org-add-props s nil 'org-attr attr))
10072 (defun org-extract-attributes-from-string (tag)
10073 (let (key value attr)
10074 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
10075 (setq key (match-string 1 tag) value (match-string 2 tag)
10076 tag (replace-match "" t t tag)
10077 attr (plist-put attr (intern key) value)))
10078 (cons tag attr)))
10080 (defun org-attributes-to-string (plist)
10081 "Format a property list into an HTML attribute list."
10082 (let ((s "") key value)
10083 (while plist
10084 (setq key (pop plist) value (pop plist))
10085 (and value
10086 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
10089 ;;; Opening/following a link
10091 (defvar org-link-search-failed nil)
10093 (defvar org-open-link-functions nil
10094 "Hook for functions finding a plain text link.
10095 These functions must take a single argument, the link content.
10096 They will be called for links that look like [[link text][description]]
10097 when LINK TEXT does not have a protocol like \"http:\" and does not look
10098 like a filename (e.g. \"./blue.png\").
10100 These functions will be called *before* Org attempts to resolve the
10101 link by doing text searches in the current buffer - so if you want a
10102 link \"[[target]]\" to still find \"<<target>>\", your function should
10103 handle this as a special case.
10105 When the function does handle the link, it must return a non-nil value.
10106 If it decides that it is not responsible for this link, it must return
10107 nil to indicate that that Org-mode can continue with other options
10108 like exact and fuzzy text search.")
10110 (defun org-next-link (&optional search-backward)
10111 "Move forward to the next link.
10112 If the link is in hidden text, expose it."
10113 (interactive "P")
10114 (when (and org-link-search-failed (eq this-command last-command))
10115 (goto-char (point-min))
10116 (message "Link search wrapped back to beginning of buffer"))
10117 (setq org-link-search-failed nil)
10118 (let* ((pos (point))
10119 (ct (org-context))
10120 (a (assoc :link ct))
10121 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10122 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10123 ((looking-at org-any-link-re)
10124 ;; Don't stay stuck at link without an org-link face
10125 (forward-char (if search-backward -1 1))))
10126 (if (funcall srch-fun org-any-link-re nil t)
10127 (progn
10128 (goto-char (match-beginning 0))
10129 (if (outline-invisible-p) (org-show-context)))
10130 (goto-char pos)
10131 (setq org-link-search-failed t)
10132 (message "No further link found"))))
10134 (defun org-previous-link ()
10135 "Move backward to the previous link.
10136 If the link is in hidden text, expose it."
10137 (interactive)
10138 (funcall 'org-next-link t))
10140 (defun org-translate-link (s)
10141 "Translate a link string if a translation function has been defined."
10142 (if (and org-link-translation-function
10143 (fboundp org-link-translation-function)
10144 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10145 (progn
10146 (setq s (funcall org-link-translation-function
10147 (match-string 1 s) (match-string 2 s)))
10148 (concat (car s) ":" (cdr s)))
10151 (defun org-translate-link-from-planner (type path)
10152 "Translate a link from Emacs Planner syntax so that Org can follow it.
10153 This is still an experimental function, your mileage may vary."
10154 (cond
10155 ((member type '("http" "https" "news" "ftp"))
10156 ;; standard Internet links are the same.
10157 nil)
10158 ((and (equal type "irc") (string-match "^//" path))
10159 ;; Planner has two / at the beginning of an irc link, we have 1.
10160 ;; We should have zero, actually....
10161 (setq path (substring path 1)))
10162 ((and (equal type "lisp") (string-match "^/" path))
10163 ;; Planner has a slash, we do not.
10164 (setq type "elisp" path (substring path 1)))
10165 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10166 ;; A typical message link. Planner has the id after the final slash,
10167 ;; we separate it with a hash mark
10168 (setq path (concat (match-string 1 path) "#"
10169 (org-remove-angle-brackets (match-string 2 path)))))
10171 (cons type path))
10173 (defun org-find-file-at-mouse (ev)
10174 "Open file link or URL at mouse."
10175 (interactive "e")
10176 (mouse-set-point ev)
10177 (org-open-at-point 'in-emacs))
10179 (defun org-open-at-mouse (ev)
10180 "Open file link or URL at mouse.
10181 See the docstring of `org-open-file' for details."
10182 (interactive "e")
10183 (mouse-set-point ev)
10184 (if (eq major-mode 'org-agenda-mode)
10185 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10186 (org-open-at-point))
10188 (defvar org-window-config-before-follow-link nil
10189 "The window configuration before following a link.
10190 This is saved in case the need arises to restore it.")
10192 (defvar org-open-link-marker (make-marker)
10193 "Marker pointing to the location where `org-open-at-point; was called.")
10195 ;;;###autoload
10196 (defun org-open-at-point-global ()
10197 "Follow a link like Org-mode does.
10198 This command can be called in any mode to follow a link that has
10199 Org-mode syntax."
10200 (interactive)
10201 (org-run-like-in-org-mode 'org-open-at-point))
10203 ;;;###autoload
10204 (defun org-open-link-from-string (s &optional arg reference-buffer)
10205 "Open a link in the string S, as if it was in Org-mode."
10206 (interactive "sLink: \nP")
10207 (let ((reference-buffer (or reference-buffer (current-buffer))))
10208 (with-temp-buffer
10209 (let ((org-inhibit-startup (not reference-buffer)))
10210 (org-mode)
10211 (insert s)
10212 (goto-char (point-min))
10213 (when reference-buffer
10214 (setq org-link-abbrev-alist-local
10215 (with-current-buffer reference-buffer
10216 org-link-abbrev-alist-local)))
10217 (org-open-at-point arg reference-buffer)))))
10219 (defvar org-open-at-point-functions nil
10220 "Hook that is run when following a link at point.
10222 Functions in this hook must return t if they identify and follow
10223 a link at point. If they don't find anything interesting at point,
10224 they must return nil.")
10226 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10227 (defun org-open-at-point (&optional arg reference-buffer)
10228 "Open link at or after point.
10229 If there is no link at point, this function will search forward up to
10230 the end of the current line.
10231 Normally, files will be opened by an appropriate application. If the
10232 optional prefix argument ARG is non-nil, Emacs will visit the file.
10233 With a double prefix argument, try to open outside of Emacs, in the
10234 application the system uses for this file type."
10235 (interactive "P")
10236 ;; if in a code block, then open the block's results
10237 (unless (call-interactively #'org-babel-open-src-block-result)
10238 (org-load-modules-maybe)
10239 (move-marker org-open-link-marker (point))
10240 (setq org-window-config-before-follow-link (current-window-configuration))
10241 (org-remove-occur-highlights nil nil t)
10242 (cond
10243 ((and (org-at-heading-p)
10244 (not (org-at-timestamp-p t))
10245 (not (org-in-regexp
10246 (concat org-plain-link-re "\\|"
10247 org-bracket-link-regexp "\\|"
10248 org-angle-link-re "\\|"
10249 "[ \t]:[^ \t\n]+:[ \t]*$")))
10250 (not (get-text-property (point) 'org-linked-text)))
10251 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10252 (lk0 (car lkall))
10253 (lk (if (stringp lk0) (list lk0) lk0))
10254 (lkend (cdr lkall)))
10255 (mapcar (lambda(l)
10256 (search-forward l nil lkend)
10257 (goto-char (match-beginning 0))
10258 (org-open-at-point))
10259 lk))
10260 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10261 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10262 ((and (org-at-timestamp-p t)
10263 (not (org-in-regexp org-bracket-link-regexp)))
10264 (org-follow-timestamp-link))
10265 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10266 (not (org-in-regexp org-any-link-re)))
10267 (org-footnote-action))
10269 (let (type path link line search (pos (point)))
10270 (catch 'match
10271 (save-excursion
10272 (skip-chars-forward "^]\n\r")
10273 (when (org-in-regexp org-bracket-link-regexp 1)
10274 (setq link (org-extract-attributes
10275 (org-link-unescape (org-match-string-no-properties 1))))
10276 (while (string-match " *\n *" link)
10277 (setq link (replace-match " " t t link)))
10278 (setq link (org-link-expand-abbrev link))
10279 (cond
10280 ((or (file-name-absolute-p link)
10281 (string-match "^\\.\\.?/" link))
10282 (setq type "file" path link))
10283 ((string-match org-link-re-with-space3 link)
10284 (setq type (match-string 1 link) path (match-string 2 link)))
10285 ((string-match "^help:+\\(.+\\)" link)
10286 (setq type "help" path (match-string 1 link)))
10287 (t (setq type "thisfile" path link)))
10288 (throw 'match t)))
10290 (when (get-text-property (point) 'org-linked-text)
10291 (setq type "thisfile"
10292 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10293 (1+ (point)) (point))
10294 path (buffer-substring
10295 (or (previous-single-property-change pos 'org-linked-text)
10296 (point-min))
10297 (or (next-single-property-change pos 'org-linked-text)
10298 (point-max))))
10299 (throw 'match t))
10301 (save-excursion
10302 (when (or (org-in-regexp org-angle-link-re)
10303 (let ((match (org-in-regexp org-plain-link-re)))
10304 ;; Check a plain link is not within a bracket link
10305 (and match
10306 (save-excursion
10307 (progn
10308 (goto-char (car match))
10309 (not (org-in-regexp org-bracket-link-regexp))))))
10310 (let ((line_ending (save-excursion (end-of-line) (point))))
10311 ;; We are in a line before a plain or bracket link
10312 (or (re-search-forward org-plain-link-re line_ending t)
10313 (re-search-forward org-bracket-link-regexp line_ending t))))
10314 (setq type (match-string 1)
10315 path (org-link-unescape (match-string 2)))
10316 (throw 'match t)))
10317 (save-excursion
10318 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10319 (setq type "tags"
10320 path (match-string 1))
10321 (while (string-match ":" path)
10322 (setq path (replace-match "+" t t path)))
10323 (throw 'match t)))
10324 (when (org-in-regexp "<\\([^><\n]+\\)>")
10325 (setq type "tree-match"
10326 path (match-string 1))
10327 (throw 'match t)))
10328 (unless path
10329 (user-error "No link found"))
10331 ;; switch back to reference buffer
10332 ;; needed when if called in a temporary buffer through
10333 ;; org-open-link-from-string
10334 (with-current-buffer (or reference-buffer (current-buffer))
10336 ;; Remove any trailing spaces in path
10337 (if (string-match " +\\'" path)
10338 (setq path (replace-match "" t t path)))
10339 (if (and org-link-translation-function
10340 (fboundp org-link-translation-function))
10341 ;; Check if we need to translate the link
10342 (let ((tmp (funcall org-link-translation-function type path)))
10343 (setq type (car tmp) path (cdr tmp))))
10345 (cond
10347 ((assoc type org-link-protocols)
10348 (funcall (nth 1 (assoc type org-link-protocols)) path))
10350 ((equal type "help")
10351 (let ((f-or-v (intern path)))
10352 (cond ((fboundp f-or-v)
10353 (describe-function f-or-v))
10354 ((boundp f-or-v)
10355 (describe-variable f-or-v))
10356 (t (error "Not a known function or variable")))))
10358 ((equal type "mailto")
10359 (let ((cmd (car org-link-mailto-program))
10360 (args (cdr org-link-mailto-program)) args1
10361 (address path) (subject "") a)
10362 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10363 (setq address (match-string 1 path)
10364 subject (org-link-escape (match-string 2 path))))
10365 (while args
10366 (cond
10367 ((not (stringp (car args))) (push (pop args) args1))
10368 (t (setq a (pop args))
10369 (if (string-match "%a" a)
10370 (setq a (replace-match address t t a)))
10371 (if (string-match "%s" a)
10372 (setq a (replace-match subject t t a)))
10373 (push a args1))))
10374 (apply cmd (nreverse args1))))
10376 ((member type '("http" "https" "ftp" "news"))
10377 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10378 (org-link-escape
10379 path org-link-escape-chars-browser)
10380 path))))
10382 ((string= type "doi")
10383 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10384 (org-link-escape
10385 path org-link-escape-chars-browser)
10386 path))))
10388 ((member type '("message"))
10389 (browse-url (concat type ":" path)))
10391 ((string= type "tags")
10392 (org-tags-view arg path))
10394 ((string= type "tree-match")
10395 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10397 ((string= type "file")
10398 (if (string-match "::\\([0-9]+\\)\\'" path)
10399 (setq line (string-to-number (match-string 1 path))
10400 path (substring path 0 (match-beginning 0)))
10401 (if (string-match "::\\(.+\\)\\'" path)
10402 (setq search (match-string 1 path)
10403 path (substring path 0 (match-beginning 0)))))
10404 (if (string-match "[*?{]" (file-name-nondirectory path))
10405 (dired path)
10406 (org-open-file path arg line search)))
10408 ((string= type "shell")
10409 (let ((buf (generate-new-buffer "*Org Shell Output"))
10410 (cmd path))
10411 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10412 (string-match org-confirm-shell-link-not-regexp cmd))
10413 (not org-confirm-shell-link-function)
10414 (funcall org-confirm-shell-link-function
10415 (format "Execute \"%s\" in shell? "
10416 (org-add-props cmd nil
10417 'face 'org-warning))))
10418 (progn
10419 (message "Executing %s" cmd)
10420 (shell-command cmd buf)
10421 (if (featurep 'midnight)
10422 (setq clean-buffer-list-kill-buffer-names
10423 (cons buf clean-buffer-list-kill-buffer-names))))
10424 (error "Abort"))))
10426 ((string= type "elisp")
10427 (let ((cmd path))
10428 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10429 (string-match org-confirm-elisp-link-not-regexp cmd))
10430 (not org-confirm-elisp-link-function)
10431 (funcall org-confirm-elisp-link-function
10432 (format "Execute \"%s\" as elisp? "
10433 (org-add-props cmd nil
10434 'face 'org-warning))))
10435 (message "%s => %s" cmd
10436 (if (equal (string-to-char cmd) ?\()
10437 (eval (read cmd))
10438 (call-interactively (read cmd))))
10439 (error "Abort"))))
10441 ((and (string= type "thisfile")
10442 (run-hook-with-args-until-success
10443 'org-open-link-functions path)))
10445 ((string= type "thisfile")
10446 (if arg
10447 (switch-to-buffer-other-window
10448 (org-get-buffer-for-internal-link (current-buffer)))
10449 (org-mark-ring-push))
10450 (let ((cmd `(org-link-search
10451 ,path
10452 ,(cond ((equal arg '(4)) ''occur)
10453 ((equal arg '(16)) ''org-occur))
10454 ,pos)))
10455 (condition-case nil (let ((org-link-search-inhibit-query t))
10456 (eval cmd))
10457 (error (progn (widen) (eval cmd))))))
10459 (t (browse-url-at-point)))))))
10460 (move-marker org-open-link-marker nil)
10461 (run-hook-with-args 'org-follow-link-hook)))
10463 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10464 "Offer links in the current entry and return the selected link.
10465 If there is only one link, return it.
10466 If NTH is an integer, return the NTH link found.
10467 If ZERO is a string, check also this string for a link, and if
10468 there is one, return it."
10469 (with-current-buffer buffer
10470 (save-excursion
10471 (save-restriction
10472 (widen)
10473 (goto-char marker)
10474 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10475 "\\(" org-angle-link-re "\\)\\|"
10476 "\\(" org-plain-link-re "\\)"))
10477 (cnt ?0)
10478 (in-emacs (if (integerp nth) nil nth))
10479 have-zero end links link c)
10480 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10481 (push (match-string 0 zero) links)
10482 (setq cnt (1- cnt) have-zero t))
10483 (save-excursion
10484 (org-back-to-heading t)
10485 (setq end (save-excursion (outline-next-heading) (point)))
10486 (while (re-search-forward re end t)
10487 (push (match-string 0) links))
10488 (setq links (org-uniquify (reverse links))))
10489 (cond
10490 ((null links)
10491 (message "No links"))
10492 ((equal (length links) 1)
10493 (setq link (car links)))
10494 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10495 (setq link (nth (if have-zero nth (1- nth)) links)))
10496 (t ; we have to select a link
10497 (save-excursion
10498 (save-window-excursion
10499 (delete-other-windows)
10500 (with-output-to-temp-buffer "*Select Link*"
10501 (mapc (lambda (l)
10502 (if (not (string-match org-bracket-link-regexp l))
10503 (princ (format "[%c] %s\n" (incf cnt)
10504 (org-remove-angle-brackets l)))
10505 (if (match-end 3)
10506 (princ (format "[%c] %s (%s)\n" (incf cnt)
10507 (match-string 3 l) (match-string 1 l)))
10508 (princ (format "[%c] %s\n" (incf cnt)
10509 (match-string 1 l))))))
10510 links))
10511 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10512 (message "Select link to open, RET to open all:")
10513 (setq c (read-char-exclusive))
10514 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10515 (when (equal c ?q) (error "Abort"))
10516 (if (equal c ?\C-m)
10517 (setq link links)
10518 (setq nth (- c ?0))
10519 (if have-zero (setq nth (1+ nth)))
10520 (unless (and (integerp nth) (>= (length links) nth))
10521 (error "Invalid link selection"))
10522 (setq link (nth (1- nth) links)))))
10523 (cons link end))))))
10525 ;; Add special file links that specify the way of opening
10527 (org-add-link-type "file+sys" 'org-open-file-with-system)
10528 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10529 (defun org-open-file-with-system (path)
10530 "Open file at PATH using the system way of opening it."
10531 (org-open-file path 'system))
10532 (defun org-open-file-with-emacs (path)
10533 "Open file at PATH in Emacs."
10534 (org-open-file path 'emacs))
10537 ;;; File search
10539 (defvar org-create-file-search-functions nil
10540 "List of functions to construct the right search string for a file link.
10541 These functions are called in turn with point at the location to
10542 which the link should point.
10544 A function in the hook should first test if it would like to
10545 handle this file type, for example by checking the `major-mode'
10546 or the file extension. If it decides not to handle this file, it
10547 should just return nil to give other functions a chance. If it
10548 does handle the file, it must return the search string to be used
10549 when following the link. The search string will be part of the
10550 file link, given after a double colon, and `org-open-at-point'
10551 will automatically search for it. If special measures must be
10552 taken to make the search successful, another function should be
10553 added to the companion hook `org-execute-file-search-functions',
10554 which see.
10556 A function in this hook may also use `setq' to set the variable
10557 `description' to provide a suggestion for the descriptive text to
10558 be used for this link when it gets inserted into an Org-mode
10559 buffer with \\[org-insert-link].")
10561 (defvar org-execute-file-search-functions nil
10562 "List of functions to execute a file search triggered by a link.
10564 Functions added to this hook must accept a single argument, the
10565 search string that was part of the file link, the part after the
10566 double colon. The function must first check if it would like to
10567 handle this search, for example by checking the `major-mode' or
10568 the file extension. If it decides not to handle this search, it
10569 should just return nil to give other functions a chance. If it
10570 does handle the search, it must return a non-nil value to keep
10571 other functions from trying.
10573 Each function can access the current prefix argument through the
10574 variable `current-prefix-arg'. Note that a single prefix is used
10575 to force opening a link in Emacs, so it may be good to only use a
10576 numeric or double prefix to guide the search function.
10578 In case this is needed, a function in this hook can also restore
10579 the window configuration before `org-open-at-point' was called using:
10581 (set-window-configuration org-window-config-before-follow-link)")
10583 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10584 (defun org-link-search (s &optional type avoid-pos stealth)
10585 "Search for a link search option.
10586 If S is surrounded by forward slashes, it is interpreted as a
10587 regular expression. In org-mode files, this will create an `org-occur'
10588 sparse tree. In ordinary files, `occur' will be used to list matches.
10589 If the current buffer is in `dired-mode', grep will be used to search
10590 in all files. If AVOID-POS is given, ignore matches near that position.
10592 When optional argument STEALTH is non-nil, do not modify
10593 visibility around point, thus ignoring
10594 `org-show-hierarchy-above', `org-show-following-heading' and
10595 `org-show-siblings' variables."
10596 (let ((case-fold-search t)
10597 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10598 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10599 (append '(("") (" ") ("\t") ("\n"))
10600 org-emphasis-alist)
10601 "\\|") "\\)"))
10602 (pos (point))
10603 (pre nil) (post nil)
10604 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10605 (cond
10606 ;; First check if there are any special search functions
10607 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10608 ;; Now try the builtin stuff
10609 ((and (equal (string-to-char s0) ?#)
10610 (> (length s0) 1)
10611 (save-excursion
10612 (goto-char (point-min))
10613 (and
10614 (re-search-forward
10615 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10616 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10617 (setq type 'dedicated
10618 pos (match-beginning 0))))
10619 ;; There is an exact target for this
10620 (goto-char pos)
10621 (org-back-to-heading t)))
10622 ((save-excursion
10623 (goto-char (point-min))
10624 (and
10625 (re-search-forward
10626 (concat "<<" (regexp-quote s0) ">>") nil t)
10627 (setq type 'dedicated
10628 pos (match-beginning 0))))
10629 ;; There is an exact target for this
10630 (goto-char pos))
10631 ((save-excursion
10632 (goto-char (point-min))
10633 (and
10634 (re-search-forward
10635 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10636 (setq type 'dedicated pos (match-beginning 0))))
10637 ;; Found an invisible target.
10638 (goto-char pos))
10639 ((save-excursion
10640 (goto-char (point-min))
10641 (and
10642 (re-search-forward
10643 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10644 (setq type 'dedicated pos (match-beginning 0))))
10645 ;; Found an element with a matching #+name affiliated keyword.
10646 (goto-char pos))
10647 ((and (string-match "^(\\(.*\\))$" s0)
10648 (save-excursion
10649 (goto-char (point-min))
10650 (and
10651 (re-search-forward
10652 (concat "[^[]" (regexp-quote
10653 (format org-coderef-label-format
10654 (match-string 1 s0))))
10655 nil t)
10656 (setq type 'dedicated
10657 pos (1+ (match-beginning 0))))))
10658 ;; There is a coderef target for this
10659 (goto-char pos))
10660 ((string-match "^/\\(.*\\)/$" s)
10661 ;; A regular expression
10662 (cond
10663 ((derived-mode-p 'org-mode)
10664 (org-occur (match-string 1 s)))
10665 (t (org-do-occur (match-string 1 s)))))
10666 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10667 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10668 (goto-char (point-min))
10669 (cond
10670 ((let (case-fold-search)
10671 (re-search-forward (format org-complex-heading-regexp-format
10672 (regexp-quote s))
10673 nil t))
10674 ;; OK, found a match
10675 (setq type 'dedicated)
10676 (goto-char (match-beginning 0)))
10677 ((and (not org-link-search-inhibit-query)
10678 (eq org-link-search-must-match-exact-headline 'query-to-create)
10679 (y-or-n-p "No match - create this as a new heading? "))
10680 (goto-char (point-max))
10681 (or (bolp) (newline))
10682 (insert "* " s "\n")
10683 (beginning-of-line 0))
10685 (goto-char pos)
10686 (error "No match"))))
10688 ;; A normal search string
10689 (when (equal (string-to-char s) ?*)
10690 ;; Anchor on headlines, post may include tags.
10691 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10692 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10693 s (substring s 1)))
10694 (remove-text-properties
10695 0 (length s)
10696 '(face nil mouse-face nil keymap nil fontified nil) s)
10697 ;; Make a series of regular expressions to find a match
10698 (setq words (org-split-string s "[ \n\r\t]+")
10700 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10701 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10702 "\\)" markers)
10703 re2a_ (concat "\\(" (mapconcat 'downcase words
10704 "[ \t\r\n]+") "\\)[ \t\r\n]")
10705 re2a (concat "[ \t\r\n]" re2a_)
10706 re4_ (concat "\\(" (mapconcat 'downcase words
10707 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10708 re4 (concat "[^a-zA-Z_]" re4_)
10710 re1 (concat pre re2 post)
10711 re3 (concat pre (if pre re4_ re4) post)
10712 re5 (concat pre ".*" re4)
10713 re2 (concat pre re2)
10714 re2a (concat pre (if pre re2a_ re2a))
10715 re4 (concat pre (if pre re4_ re4))
10716 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10717 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10718 re5 "\\)"
10720 (cond
10721 ((eq type 'org-occur) (org-occur reall))
10722 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10723 (t (goto-char (point-min))
10724 (setq type 'fuzzy)
10725 (if (or (and (org-search-not-self 1 re0 nil t)
10726 (setq type 'dedicated))
10727 (org-search-not-self 1 re1 nil t)
10728 (org-search-not-self 1 re2 nil t)
10729 (org-search-not-self 1 re2a nil t)
10730 (org-search-not-self 1 re3 nil t)
10731 (org-search-not-self 1 re4 nil t)
10732 (org-search-not-self 1 re5 nil t))
10733 (goto-char (match-beginning 1))
10734 (goto-char pos)
10735 (error "No match"))))))
10736 (and (derived-mode-p 'org-mode)
10737 (not stealth)
10738 (org-show-context 'link-search))
10739 type))
10741 (defun org-search-not-self (group &rest args)
10742 "Execute `re-search-forward', but only accept matches that do not
10743 enclose the position of `org-open-link-marker'."
10744 (let ((m org-open-link-marker))
10745 (catch 'exit
10746 (while (apply 're-search-forward args)
10747 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10748 (goto-char (match-end group))
10749 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10750 (> (match-beginning 0) (marker-position m))
10751 (< (match-end 0) (marker-position m)))
10752 (save-match-data
10753 (or (not (org-in-regexp
10754 org-bracket-link-analytic-regexp 1))
10755 (not (match-end 4)) ; no description
10756 (and (<= (match-beginning 4) (point))
10757 (>= (match-end 4) (point))))))
10758 (throw 'exit (point))))))))
10760 (defun org-get-buffer-for-internal-link (buffer)
10761 "Return a buffer to be used for displaying the link target of internal links."
10762 (cond
10763 ((not org-display-internal-link-with-indirect-buffer)
10764 buffer)
10765 ((string-match "(Clone)$" (buffer-name buffer))
10766 (message "Buffer is already a clone, not making another one")
10767 ;; we also do not modify visibility in this case
10768 buffer)
10769 (t ; make a new indirect buffer for displaying the link
10770 (let* ((bn (buffer-name buffer))
10771 (ibn (concat bn "(Clone)"))
10772 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10773 (with-current-buffer ib (org-overview))
10774 ib))))
10776 (defun org-do-occur (regexp &optional cleanup)
10777 "Call the Emacs command `occur'.
10778 If CLEANUP is non-nil, remove the printout of the regular expression
10779 in the *Occur* buffer. This is useful if the regex is long and not useful
10780 to read."
10781 (occur regexp)
10782 (when cleanup
10783 (let ((cwin (selected-window)) win beg end)
10784 (when (setq win (get-buffer-window "*Occur*"))
10785 (select-window win))
10786 (goto-char (point-min))
10787 (when (re-search-forward "match[a-z]+" nil t)
10788 (setq beg (match-end 0))
10789 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10790 (setq end (1- (match-beginning 0)))))
10791 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10792 (goto-char (point-min))
10793 (select-window cwin))))
10795 ;;; The mark ring for links jumps
10797 (defvar org-mark-ring nil
10798 "Mark ring for positions before jumps in Org-mode.")
10799 (defvar org-mark-ring-last-goto nil
10800 "Last position in the mark ring used to go back.")
10801 ;; Fill and close the ring
10802 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10803 (loop for i from 1 to org-mark-ring-length do
10804 (push (make-marker) org-mark-ring))
10805 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10806 org-mark-ring)
10808 (defun org-mark-ring-push (&optional pos buffer)
10809 "Put the current position or POS into the mark ring and rotate it."
10810 (interactive)
10811 (setq pos (or pos (point)))
10812 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10813 (move-marker (car org-mark-ring)
10814 (or pos (point))
10815 (or buffer (current-buffer)))
10816 (message "%s"
10817 (substitute-command-keys
10818 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10820 (defun org-mark-ring-goto (&optional n)
10821 "Jump to the previous position in the mark ring.
10822 With prefix arg N, jump back that many stored positions. When
10823 called several times in succession, walk through the entire ring.
10824 Org-mode commands jumping to a different position in the current file,
10825 or to another Org-mode file, automatically push the old position
10826 onto the ring."
10827 (interactive "p")
10828 (let (p m)
10829 (if (eq last-command this-command)
10830 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10831 (setq p org-mark-ring))
10832 (setq org-mark-ring-last-goto p)
10833 (setq m (car p))
10834 (org-pop-to-buffer-same-window (marker-buffer m))
10835 (goto-char m)
10836 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10838 (defun org-remove-angle-brackets (s)
10839 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10840 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10842 (defun org-add-angle-brackets (s)
10843 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10844 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10846 (defun org-remove-double-quotes (s)
10847 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10848 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10851 ;;; Following specific links
10853 (defun org-follow-timestamp-link ()
10854 "Open an agenda view for the time-stamp date/range at point."
10855 (cond
10856 ((org-at-date-range-p t)
10857 (let ((org-agenda-start-on-weekday)
10858 (t1 (match-string 1))
10859 (t2 (match-string 2)) tt1 tt2)
10860 (setq tt1 (time-to-days (org-time-string-to-time t1))
10861 tt2 (time-to-days (org-time-string-to-time t2)))
10862 (let ((org-agenda-buffer-tmp-name
10863 (format "*Org Agenda(a:%s)"
10864 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10865 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10866 ((org-at-timestamp-p t)
10867 (let ((org-agenda-buffer-tmp-name
10868 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10869 (org-agenda-list nil (time-to-days (org-time-string-to-time
10870 (substring (match-string 1) 0 10)))
10871 1)))
10872 (t (error "This should not happen"))))
10875 ;;; Following file links
10876 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10877 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10878 (declare-function mailcap-mime-info
10879 "mailcap" (string &optional request no-decode))
10880 (defvar org-wait nil)
10881 (defun org-open-file (path &optional in-emacs line search)
10882 "Open the file at PATH.
10883 First, this expands any special file name abbreviations. Then the
10884 configuration variable `org-file-apps' is checked if it contains an
10885 entry for this file type, and if yes, the corresponding command is launched.
10887 If no application is found, Emacs simply visits the file.
10889 With optional prefix argument IN-EMACS, Emacs will visit the file.
10890 With a double \\[universal-argument] \\[universal-argument] \
10891 prefix arg, Org tries to avoid opening in Emacs
10892 and to use an external application to visit the file.
10894 Optional LINE specifies a line to go to, optional SEARCH a string
10895 to search for. If LINE or SEARCH is given, the file will be
10896 opened in Emacs, unless an entry from org-file-apps that makes
10897 use of groups in a regexp matches.
10899 If you want to change the way frames are used when following a
10900 link, please customize `org-link-frame-setup'.
10902 If the file does not exist, an error is thrown."
10903 (let* ((file (if (equal path "")
10904 buffer-file-name
10905 (substitute-in-file-name (expand-file-name path))))
10906 (file-apps (append org-file-apps (org-default-apps)))
10907 (apps (org-remove-if
10908 'org-file-apps-entry-match-against-dlink-p file-apps))
10909 (apps-dlink (org-remove-if-not
10910 'org-file-apps-entry-match-against-dlink-p file-apps))
10911 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10912 (dirp (if remp nil (file-directory-p file)))
10913 (file (if (and dirp org-open-directory-means-index-dot-org)
10914 (concat (file-name-as-directory file) "index.org")
10915 file))
10916 (a-m-a-p (assq 'auto-mode apps))
10917 (dfile (downcase file))
10918 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10919 (link (cond ((and (eq line nil)
10920 (eq search nil))
10921 file)
10922 (line
10923 (concat file "::" (number-to-string line)))
10924 (search
10925 (concat file "::" search))))
10926 (dlink (downcase link))
10927 (old-buffer (current-buffer))
10928 (old-pos (point))
10929 (old-mode major-mode)
10930 ext cmd link-match-data)
10931 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10932 (setq ext (match-string 1 dfile))
10933 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10934 (setq ext (match-string 1 dfile))))
10935 (cond
10936 ((member in-emacs '((16) system))
10937 (setq cmd (cdr (assoc 'system apps))))
10938 (in-emacs (setq cmd 'emacs))
10940 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10941 (and dirp (cdr (assoc 'directory apps)))
10942 ; first, try matching against apps-dlink
10943 ; if we get a match here, store the match data for later
10944 (let ((match (assoc-default dlink apps-dlink
10945 'string-match)))
10946 (if match
10947 (progn (setq link-match-data (match-data))
10948 match)
10949 (progn (setq in-emacs (or in-emacs line search))
10950 nil))) ; if we have no match in apps-dlink,
10951 ; always open the file in emacs if line or search
10952 ; is given (for backwards compatibility)
10953 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10954 'string-match)
10955 (cdr (assoc ext apps))
10956 (cdr (assoc t apps))))))
10957 (when (eq cmd 'system)
10958 (setq cmd (cdr (assoc 'system apps))))
10959 (when (eq cmd 'default)
10960 (setq cmd (cdr (assoc t apps))))
10961 (when (eq cmd 'mailcap)
10962 (require 'mailcap)
10963 (mailcap-parse-mailcaps)
10964 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10965 (command (mailcap-mime-info mime-type)))
10966 (if (stringp command)
10967 (setq cmd command)
10968 (setq cmd 'emacs))))
10969 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10970 (not (file-exists-p file))
10971 (not org-open-non-existing-files))
10972 (error "No such file: %s" file))
10973 (cond
10974 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10975 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10976 (while (string-match "['\"]%s['\"]" cmd)
10977 (setq cmd (replace-match "%s" t t cmd)))
10978 (while (string-match "%s" cmd)
10979 (setq cmd (replace-match
10980 (save-match-data
10981 (shell-quote-argument
10982 (convert-standard-filename file)))
10983 t t cmd)))
10985 ;; Replace "%1", "%2" etc. in command with group matches from regex
10986 (save-match-data
10987 (let ((match-index 1)
10988 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10989 (set-match-data link-match-data)
10990 (while (<= match-index number-of-groups)
10991 (let ((regex (concat "%" (number-to-string match-index)))
10992 (replace-with (match-string match-index dlink)))
10993 (while (string-match regex cmd)
10994 (setq cmd (replace-match replace-with t t cmd))))
10995 (setq match-index (+ match-index 1)))))
10997 (save-window-excursion
10998 (message "Running %s...done" cmd)
10999 (start-process-shell-command cmd nil cmd)
11000 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11001 ((or (stringp cmd)
11002 (eq cmd 'emacs))
11003 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11004 (widen)
11005 (if line (org-goto-line line)
11006 (if search (org-link-search search))))
11007 ((consp cmd)
11008 (let ((file (convert-standard-filename file)))
11009 (save-match-data
11010 (set-match-data link-match-data)
11011 (eval cmd))))
11012 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11013 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11014 (or (not (equal old-buffer (current-buffer)))
11015 (not (equal old-pos (point))))
11016 (org-mark-ring-push old-pos old-buffer))))
11018 (defun org-file-apps-entry-match-against-dlink-p (entry)
11019 "This function returns non-nil if `entry' uses a regular
11020 expression which should be matched against the whole link by
11021 org-open-file.
11023 It assumes that is the case when the entry uses a regular
11024 expression which has at least one grouping construct and the
11025 action is either a lisp form or a command string containing
11026 '%1', i.e. using at least one subexpression match as a
11027 parameter."
11028 (let ((selector (car entry))
11029 (action (cdr entry)))
11030 (if (stringp selector)
11031 (and (> (regexp-opt-depth selector) 0)
11032 (or (and (stringp action)
11033 (string-match "%[0-9]" action))
11034 (consp action)))
11035 nil)))
11037 (defun org-default-apps ()
11038 "Return the default applications for this operating system."
11039 (cond
11040 ((eq system-type 'darwin)
11041 org-file-apps-defaults-macosx)
11042 ((eq system-type 'windows-nt)
11043 org-file-apps-defaults-windowsnt)
11044 (t org-file-apps-defaults-gnu)))
11046 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11047 "Convert extensions to regular expressions in the cars of LIST.
11048 Also, weed out any non-string entries, because the return value is used
11049 only for regexp matching.
11050 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11051 point to the symbol `emacs', indicating that the file should
11052 be opened in Emacs."
11053 (append
11054 (delq nil
11055 (mapcar (lambda (x)
11056 (if (not (stringp (car x)))
11058 (if (string-match "\\W" (car x))
11060 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11061 list))
11062 (if add-auto-mode
11063 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11065 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11066 (defun org-file-remote-p (file)
11067 "Test whether FILE specifies a location on a remote system.
11068 Return non-nil if the location is indeed remote.
11070 For example, the filename \"/user@host:/foo\" specifies a location
11071 on the system \"/user@host:\"."
11072 (cond ((fboundp 'file-remote-p)
11073 (file-remote-p file))
11074 ((fboundp 'tramp-handle-file-remote-p)
11075 (tramp-handle-file-remote-p file))
11076 ((and (boundp 'ange-ftp-name-format)
11077 (string-match (car ange-ftp-name-format) file))
11078 t)))
11081 ;;;; Refiling
11083 (defun org-get-org-file ()
11084 "Read a filename, with default directory `org-directory'."
11085 (let ((default (or org-default-notes-file remember-data-file)))
11086 (read-file-name (format "File name [%s]: " default)
11087 (file-name-as-directory org-directory)
11088 default)))
11090 (defun org-notes-order-reversed-p ()
11091 "Check if the current file should receive notes in reversed order."
11092 (cond
11093 ((not org-reverse-note-order) nil)
11094 ((eq t org-reverse-note-order) t)
11095 ((not (listp org-reverse-note-order)) nil)
11096 (t (catch 'exit
11097 (let ((all org-reverse-note-order)
11098 entry)
11099 (while (setq entry (pop all))
11100 (if (string-match (car entry) buffer-file-name)
11101 (throw 'exit (cdr entry))))
11102 nil)))))
11104 (defvar org-refile-target-table nil
11105 "The list of refile targets, created by `org-refile'.")
11107 (defvar org-agenda-new-buffers nil
11108 "Buffers created to visit agenda files.")
11110 (defvar org-refile-cache nil
11111 "Cache for refile targets.")
11113 (defvar org-refile-markers nil
11114 "All the markers used for caching refile locations.")
11116 (defun org-refile-marker (pos)
11117 "Get a new refile marker, but only if caching is in use."
11118 (if (not org-refile-use-cache)
11120 (let ((m (make-marker)))
11121 (move-marker m pos)
11122 (push m org-refile-markers)
11123 m)))
11125 (defun org-refile-cache-clear ()
11126 "Clear the refile cache and disable all the markers."
11127 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11128 (setq org-refile-markers nil)
11129 (setq org-refile-cache nil)
11130 (message "Refile cache has been cleared"))
11132 (defun org-refile-cache-check-set (set)
11133 "Check if all the markers in the cache still have live buffers."
11134 (let (marker)
11135 (catch 'exit
11136 (while (and set (setq marker (nth 3 (pop set))))
11137 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11138 (when (and marker (null (marker-buffer marker)))
11139 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11140 (sit-for 3)
11141 (throw 'exit nil)))
11142 t)))
11144 (defun org-refile-cache-put (set &rest identifiers)
11145 "Push the refile targets SET into the cache, under IDENTIFIERS."
11146 (let* ((key (sha1 (prin1-to-string identifiers)))
11147 (entry (assoc key org-refile-cache)))
11148 (if entry
11149 (setcdr entry set)
11150 (push (cons key set) org-refile-cache))))
11152 (defun org-refile-cache-get (&rest identifiers)
11153 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11154 (cond
11155 ((not org-refile-cache) nil)
11156 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11158 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11159 org-refile-cache))))
11160 (and set (org-refile-cache-check-set set) set)))))
11162 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11163 "Produce a table with refile targets."
11164 (let ((case-fold-search nil)
11165 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11166 (entries (or org-refile-targets '((nil . (:level . 1)))))
11167 targets tgs txt re files f desc descre fast-path-p level pos0)
11168 (message "Getting targets...")
11169 (with-current-buffer (or default-buffer (current-buffer))
11170 (while (setq entry (pop entries))
11171 (setq files (car entry) desc (cdr entry))
11172 (setq fast-path-p nil)
11173 (cond
11174 ((null files) (setq files (list (current-buffer))))
11175 ((eq files 'org-agenda-files)
11176 (setq files (org-agenda-files 'unrestricted)))
11177 ((and (symbolp files) (fboundp files))
11178 (setq files (funcall files)))
11179 ((and (symbolp files) (boundp files))
11180 (setq files (symbol-value files))))
11181 (if (stringp files) (setq files (list files)))
11182 (cond
11183 ((eq (car desc) :tag)
11184 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11185 ((eq (car desc) :todo)
11186 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11187 ((eq (car desc) :regexp)
11188 (setq descre (cdr desc)))
11189 ((eq (car desc) :level)
11190 (setq descre (concat "^\\*\\{" (number-to-string
11191 (if org-odd-levels-only
11192 (1- (* 2 (cdr desc)))
11193 (cdr desc)))
11194 "\\}[ \t]")))
11195 ((eq (car desc) :maxlevel)
11196 (setq fast-path-p t)
11197 (setq descre (concat "^\\*\\{1," (number-to-string
11198 (if org-odd-levels-only
11199 (1- (* 2 (cdr desc)))
11200 (cdr desc)))
11201 "\\}[ \t]")))
11202 (t (error "Bad refiling target description %s" desc)))
11203 (while (setq f (pop files))
11204 (with-current-buffer
11205 (if (bufferp f) f (org-get-agenda-file-buffer f))
11207 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11208 (progn
11209 (if (bufferp f) (setq f (buffer-file-name
11210 (buffer-base-buffer f))))
11211 (setq f (and f (expand-file-name f)))
11212 (if (eq org-refile-use-outline-path 'file)
11213 (push (list (file-name-nondirectory f) f nil nil) tgs))
11214 (save-excursion
11215 (save-restriction
11216 (widen)
11217 (goto-char (point-min))
11218 (while (re-search-forward descre nil t)
11219 (goto-char (setq pos0 (point-at-bol)))
11220 (catch 'next
11221 (when org-refile-target-verify-function
11222 (save-match-data
11223 (or (funcall org-refile-target-verify-function)
11224 (throw 'next t))))
11225 (when (and (looking-at org-complex-heading-regexp)
11226 (not (member (match-string 4) excluded-entries))
11227 (match-string 4))
11228 (setq level (org-reduced-level
11229 (- (match-end 1) (match-beginning 1)))
11230 txt (org-link-display-format (match-string 4))
11231 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11232 re (format org-complex-heading-regexp-format
11233 (regexp-quote (match-string 4))))
11234 (when org-refile-use-outline-path
11235 (setq txt (mapconcat
11236 'org-protect-slash
11237 (append
11238 (if (eq org-refile-use-outline-path
11239 'file)
11240 (list (file-name-nondirectory
11241 (buffer-file-name
11242 (buffer-base-buffer))))
11243 (if (eq org-refile-use-outline-path
11244 'full-file-path)
11245 (list (buffer-file-name
11246 (buffer-base-buffer)))))
11247 (org-get-outline-path fast-path-p
11248 level txt)
11249 (list txt))
11250 "/")))
11251 (push (list txt f re (org-refile-marker (point)))
11252 tgs)))
11253 (when (= (point) pos0)
11254 ;; verification function has not moved point
11255 (goto-char (point-at-eol))))))))
11256 (when org-refile-use-cache
11257 (org-refile-cache-put tgs (buffer-file-name) descre))
11258 (setq targets (append tgs targets))
11259 ))))
11260 (message "Getting targets...done")
11261 (nreverse targets)))
11263 (defun org-protect-slash (s)
11264 (while (string-match "/" s)
11265 (setq s (replace-match "\\" t t s)))
11268 (defvar org-olpa (make-vector 20 nil))
11270 (defun org-get-outline-path (&optional fastp level heading)
11271 "Return the outline path to the current entry, as a list.
11273 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11274 routine which makes outline path derivations for an entire file,
11275 avoiding backtracing. Refile target collection makes use of that."
11276 (if fastp
11277 (progn
11278 (if (> level 19)
11279 (error "Outline path failure, more than 19 levels"))
11280 (loop for i from level upto 19 do
11281 (aset org-olpa i nil))
11282 (prog1
11283 (delq nil (append org-olpa nil))
11284 (aset org-olpa level heading)))
11285 (let (rtn case-fold-search)
11286 (save-excursion
11287 (save-restriction
11288 (widen)
11289 (while (org-up-heading-safe)
11290 (when (looking-at org-complex-heading-regexp)
11291 (push (org-match-string-no-properties 4) rtn)))
11292 rtn)))))
11294 (defun org-format-outline-path (path &optional width prefix separator)
11295 "Format the outline path PATH for display.
11296 WIDTH is the maximum number of characters that is available.
11297 PREFIX is a prefix to be included in the returned string,
11298 such as the file name.
11299 SEPARATOR is inserted between the different parts of the path,
11300 the default is \"/\"."
11301 (setq width (or width 79))
11302 (if prefix (setq width (- width (length prefix))))
11303 (if (not path)
11304 (or prefix "")
11305 (let* ((nsteps (length path))
11306 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11307 (maxwidth (if (<= total-width width)
11308 10000 ;; everything fits
11309 ;; we need to shorten the level headings
11310 (/ (- width nsteps) nsteps)))
11311 (org-odd-levels-only nil)
11312 (n 0)
11313 (total (1+ (length prefix))))
11314 (setq maxwidth (max maxwidth 10))
11315 (concat prefix
11316 (if prefix (or separator "/"))
11317 (mapconcat
11318 (lambda (h)
11319 (setq n (1+ n))
11320 (if (and (= n nsteps) (< maxwidth 10000))
11321 (setq maxwidth (- total-width total)))
11322 (if (< (length h) maxwidth)
11323 (progn (setq total (+ total (length h) 1)) h)
11324 (setq h (substring h 0 (- maxwidth 2))
11325 total (+ total maxwidth 1))
11326 (if (string-match "[ \t]+\\'" h)
11327 (setq h (substring h 0 (match-beginning 0))))
11328 (setq h (concat h "..")))
11329 (org-add-props h nil 'face
11330 (nth (% (1- n) org-n-level-faces)
11331 org-level-faces))
11333 path (or separator "/"))))))
11335 (defun org-display-outline-path (&optional file current separator just-return-string)
11336 "Display the current outline path in the echo area.
11338 If FILE is non-nil, prepend the output with the file name.
11339 If CURRENT is non-nil, append the current heading to the output.
11340 SEPARATOR is passed through to `org-format-outline-path'. It separates
11341 the different parts of the path and defaults to \"/\".
11342 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11343 (interactive "P")
11344 (let* (case-fold-search
11345 message-log-max ; Don't populate the *Messages* buffer
11346 (bfn (buffer-file-name (buffer-base-buffer)))
11347 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11348 res)
11349 (if current (setq path (append path
11350 (save-excursion
11351 (org-back-to-heading t)
11352 (if (looking-at org-complex-heading-regexp)
11353 (list (match-string 4)))))))
11354 (setq res
11355 (org-format-outline-path
11356 path
11357 (1- (frame-width))
11358 (and file bfn (concat (file-name-nondirectory bfn) separator))
11359 separator))
11360 (if just-return-string
11361 (org-no-properties res)
11362 (message "%s" res))))
11364 (defvar org-refile-history nil
11365 "History for refiling operations.")
11367 (defvar org-after-refile-insert-hook nil
11368 "Hook run after `org-refile' has inserted its stuff at the new location.
11369 Note that this is still *before* the stuff will be removed from
11370 the *old* location.")
11372 (defvar org-capture-last-stored-marker)
11373 (defvar org-refile-keep nil
11374 "Non-nil means `org-refile' will copy instead of refile.")
11376 (defun org-copy ()
11377 "Like `org-refile', but copy."
11378 (interactive)
11379 (let ((org-refile-keep t))
11380 (funcall 'org-refile nil nil nil "Copy")))
11382 (defun org-refile (&optional goto default-buffer rfloc msg)
11383 "Move the entry or entries at point to another heading.
11384 The list of target headings is compiled using the information in
11385 `org-refile-targets', which see.
11387 At the target location, the entry is filed as a subitem of the target
11388 heading. Depending on `org-reverse-note-order', the new subitem will
11389 either be the first or the last subitem.
11391 If there is an active region, all entries in that region will be moved.
11392 However, the region must fulfill the requirement that the first heading
11393 is the first one sets the top-level of the moved text - at most siblings
11394 below it are allowed.
11396 With prefix arg GOTO, the command will only visit the target location
11397 and not actually move anything.
11399 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11400 go to the location where the last refiling operation has put the subtree.
11401 With a prefix argument of `2', refile to the running clock.
11403 RFLOC can be a refile location obtained in a different way.
11405 MSG is a string to replace \"Refile\" in the default prompt with
11406 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11408 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11410 If you are using target caching (see `org-refile-use-cache'),
11411 you have to clear the target cache in order to find new targets.
11412 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11413 prefix argument (`C-u C-u C-u C-c C-w')."
11415 (interactive "P")
11416 (if (member goto '(0 (64)))
11417 (org-refile-cache-clear)
11418 (let* ((actionmsg (or msg "Refile"))
11419 (cbuf (current-buffer))
11420 (regionp (org-region-active-p))
11421 (region-start (and regionp (region-beginning)))
11422 (region-end (and regionp (region-end)))
11423 (region-length (and regionp (- region-end region-start)))
11424 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11425 pos it nbuf file re level reversed)
11426 (setq last-command nil)
11427 (when regionp
11428 (goto-char region-start)
11429 (or (bolp) (goto-char (point-at-bol)))
11430 (setq region-start (point))
11431 (unless (or (org-kill-is-subtree-p
11432 (buffer-substring region-start region-end))
11433 (prog1 org-refile-active-region-within-subtree
11434 (org-toggle-heading)))
11435 (error "The region is not a (sequence of) subtree(s)")))
11436 (if (equal goto '(16))
11437 (org-refile-goto-last-stored)
11438 (when (or
11439 (and (equal goto 2)
11440 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11441 (prog1
11442 (setq it (list (or org-clock-heading "running clock")
11443 (buffer-file-name
11444 (marker-buffer org-clock-hd-marker))
11446 (marker-position org-clock-hd-marker)))
11447 (setq goto nil)))
11448 (setq it (or rfloc
11449 (let (heading-text)
11450 (save-excursion
11451 (unless goto
11452 (org-back-to-heading t)
11453 (setq heading-text
11454 (nth 4 (org-heading-components))))
11456 (org-refile-get-location
11457 (cond (goto "Goto")
11458 (regionp (concat actionmsg " region to"))
11459 (t (concat actionmsg " subtree \""
11460 heading-text "\" to")))
11461 default-buffer
11462 (and (not (equal '(4) goto))
11463 org-refile-allow-creating-parent-nodes)
11464 goto))))))
11465 (setq file (nth 1 it)
11466 re (nth 2 it)
11467 pos (nth 3 it))
11468 (if (and (not goto)
11470 (equal (buffer-file-name) file)
11471 (if regionp
11472 (and (>= pos region-start)
11473 (<= pos region-end))
11474 (and (>= pos (point))
11475 (< pos (save-excursion
11476 (org-end-of-subtree t t))))))
11477 (error "Cannot refile to position inside the tree or region"))
11479 (setq nbuf (or (find-buffer-visiting file)
11480 (find-file-noselect file)))
11481 (if goto
11482 (progn
11483 (org-pop-to-buffer-same-window nbuf)
11484 (goto-char pos)
11485 (org-show-context 'org-goto))
11486 (if regionp
11487 (progn
11488 (org-kill-new (buffer-substring region-start region-end))
11489 (org-save-markers-in-region region-start region-end))
11490 (org-copy-subtree 1 nil t))
11491 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11492 (find-file-noselect file)))
11493 (setq reversed (org-notes-order-reversed-p))
11494 (save-excursion
11495 (save-restriction
11496 (widen)
11497 (if pos
11498 (progn
11499 (goto-char pos)
11500 (looking-at org-outline-regexp)
11501 (setq level (org-get-valid-level (funcall outline-level) 1))
11502 (goto-char
11503 (if reversed
11504 (or (outline-next-heading) (point-max))
11505 (or (save-excursion (org-get-next-sibling))
11506 (org-end-of-subtree t t)
11507 (point-max)))))
11508 (setq level 1)
11509 (if (not reversed)
11510 (goto-char (point-max))
11511 (goto-char (point-min))
11512 (or (outline-next-heading) (goto-char (point-max)))))
11513 (if (not (bolp)) (newline))
11514 (org-paste-subtree level)
11515 (when org-log-refile
11516 (org-add-log-setup 'refile nil nil 'findpos
11517 org-log-refile)
11518 (unless (eq org-log-refile 'note)
11519 (save-excursion (org-add-log-note))))
11520 (and org-auto-align-tags
11521 (let ((org-loop-over-headlines-in-active-region nil))
11522 (org-set-tags nil t)))
11523 (with-demoted-errors
11524 (bookmark-set "org-refile-last-stored"))
11525 ;; If we are refiling for capture, make sure that the
11526 ;; last-capture pointers point here
11527 (when (org-bound-and-true-p org-refile-for-capture)
11528 (with-demoted-errors
11529 (bookmark-set "org-capture-last-stored-marker"))
11530 (move-marker org-capture-last-stored-marker (point)))
11531 (if (fboundp 'deactivate-mark) (deactivate-mark))
11532 (run-hooks 'org-after-refile-insert-hook))))
11533 (unless org-refile-keep
11534 (if regionp
11535 (delete-region (point) (+ (point) region-length))
11536 (org-cut-subtree)))
11537 (when (featurep 'org-inlinetask)
11538 (org-inlinetask-remove-END-maybe))
11539 (setq org-markers-to-move nil)
11540 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11542 (defun org-refile-goto-last-stored ()
11543 "Go to the location where the last refile was stored."
11544 (interactive)
11545 (bookmark-jump "org-refile-last-stored")
11546 (message "This is the location of the last refile"))
11548 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11549 no-exclude)
11550 "Prompt the user for a refile location, using PROMPT.
11551 PROMPT should not be suffixed with a colon and a space, because
11552 this function appends the default value from
11553 `org-refile-history' automatically, if that is not empty.
11554 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11555 this is used for the GOTO interface."
11556 (let ((org-refile-targets org-refile-targets)
11557 (org-refile-use-outline-path org-refile-use-outline-path)
11558 excluded-entries)
11559 (when (and (derived-mode-p 'org-mode)
11560 (not org-refile-use-cache)
11561 (not no-exclude))
11562 (org-map-tree
11563 (lambda()
11564 (setq excluded-entries
11565 (append excluded-entries (list (org-get-heading t t)))))))
11566 (setq org-refile-target-table
11567 (org-refile-get-targets default-buffer excluded-entries)))
11568 (unless org-refile-target-table
11569 (error "No refile targets"))
11570 (let* ((cbuf (current-buffer))
11571 (partial-completion-mode nil)
11572 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11573 (cfunc (if (and org-refile-use-outline-path
11574 org-outline-path-complete-in-steps)
11575 'org-olpath-completing-read
11576 'org-icompleting-read))
11577 (extra (if org-refile-use-outline-path "/" ""))
11578 (cbnex (concat (buffer-name) extra))
11579 (filename (and cfn (expand-file-name cfn)))
11580 (tbl (mapcar
11581 (lambda (x)
11582 (if (and (not (member org-refile-use-outline-path
11583 '(file full-file-path)))
11584 (not (equal filename (nth 1 x))))
11585 (cons (concat (car x) extra " ("
11586 (file-name-nondirectory (nth 1 x)) ")")
11587 (cdr x))
11588 (cons (concat (car x) extra) (cdr x))))
11589 org-refile-target-table))
11590 (completion-ignore-case t)
11591 cdef
11592 (prompt (concat prompt
11593 (or (and (car org-refile-history)
11594 (concat " (default " (car org-refile-history) ")"))
11595 (and (assoc cbnex tbl) (setq cdef cbnex)
11596 (concat " (default " cbnex ")"))) ": "))
11597 pa answ parent-target child parent old-hist)
11598 (setq old-hist org-refile-history)
11599 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11600 nil 'org-refile-history (or cdef (car org-refile-history))))
11601 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11602 (org-refile-check-position pa)
11603 (if pa
11604 (progn
11605 (when (or (not org-refile-history)
11606 (not (eq old-hist org-refile-history))
11607 (not (equal (car pa) (car org-refile-history))))
11608 (setq org-refile-history
11609 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11610 org-refile-history
11611 (cdr org-refile-history))))
11612 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11613 (pop org-refile-history)))
11615 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11616 (progn
11617 (setq parent (match-string 1 answ)
11618 child (match-string 2 answ))
11619 (setq parent-target (or (assoc parent tbl)
11620 (assoc (concat parent "/") tbl)))
11621 (when (and parent-target
11622 (or (eq new-nodes t)
11623 (and (eq new-nodes 'confirm)
11624 (y-or-n-p (format "Create new node \"%s\"? "
11625 child)))))
11626 (org-refile-new-child parent-target child)))
11627 (error "Invalid target location")))))
11629 (declare-function org-string-nw-p "org-macs" (s))
11630 (defun org-refile-check-position (refile-pointer)
11631 "Check if the refile pointer matches the headline to which it points."
11632 (let* ((file (nth 1 refile-pointer))
11633 (re (nth 2 refile-pointer))
11634 (pos (nth 3 refile-pointer))
11635 buffer)
11636 (if (and (not (markerp pos)) (not file))
11637 (error "Please save the buffer to a file before refiling")
11638 (when (org-string-nw-p re)
11639 (setq buffer (if (markerp pos)
11640 (marker-buffer pos)
11641 (or (find-buffer-visiting file)
11642 (find-file-noselect file))))
11643 (with-current-buffer buffer
11644 (save-excursion
11645 (save-restriction
11646 (widen)
11647 (goto-char pos)
11648 (beginning-of-line 1)
11649 (unless (org-looking-at-p re)
11650 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11652 (defun org-refile-new-child (parent-target child)
11653 "Use refile target PARENT-TARGET to add new CHILD below it."
11654 (unless parent-target
11655 (error "Cannot find parent for new node"))
11656 (let ((file (nth 1 parent-target))
11657 (pos (nth 3 parent-target))
11658 level)
11659 (with-current-buffer (or (find-buffer-visiting file)
11660 (find-file-noselect file))
11661 (save-excursion
11662 (save-restriction
11663 (widen)
11664 (if pos
11665 (goto-char pos)
11666 (goto-char (point-max))
11667 (if (not (bolp)) (newline)))
11668 (when (looking-at org-outline-regexp)
11669 (setq level (funcall outline-level))
11670 (org-end-of-subtree t t))
11671 (org-back-over-empty-lines)
11672 (insert "\n" (make-string
11673 (if pos (org-get-valid-level level 1) 1) ?*)
11674 " " child "\n")
11675 (beginning-of-line 0)
11676 (list (concat (car parent-target) "/" child) file "" (point)))))))
11678 (defun org-olpath-completing-read (prompt collection &rest args)
11679 "Read an outline path like a file name."
11680 (let ((thetable collection)
11681 (org-completion-use-ido nil) ; does not work with ido.
11682 (org-completion-use-iswitchb nil)) ; or iswitchb
11683 (apply
11684 'org-icompleting-read prompt
11685 (lambda (string predicate &optional flag)
11686 (let (rtn r f (l (length string)))
11687 (cond
11688 ((eq flag nil)
11689 ;; try completion
11690 (try-completion string thetable))
11691 ((eq flag t)
11692 ;; all-completions
11693 (setq rtn (all-completions string thetable predicate))
11694 (mapcar
11695 (lambda (x)
11696 (setq r (substring x l))
11697 (if (string-match " ([^)]*)$" x)
11698 (setq f (match-string 0 x))
11699 (setq f ""))
11700 (if (string-match "/" r)
11701 (concat string (substring r 0 (match-end 0)) f)
11703 rtn))
11704 ((eq flag 'lambda)
11705 ;; exact match?
11706 (assoc string thetable)))))
11707 args)))
11709 ;;;; Dynamic blocks
11711 (defun org-find-dblock (name)
11712 "Find the first dynamic block with name NAME in the buffer.
11713 If not found, stay at current position and return nil."
11714 (let ((case-fold-search t) pos)
11715 (save-excursion
11716 (goto-char (point-min))
11717 (setq pos (and (re-search-forward
11718 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11719 (match-beginning 0))))
11720 (if pos (goto-char pos))
11721 pos))
11723 (defconst org-dblock-start-re
11724 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11725 "Matches the start line of a dynamic block, with parameters.")
11727 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11728 "Matches the end of a dynamic block.")
11730 (defun org-create-dblock (plist)
11731 "Create a dynamic block section, with parameters taken from PLIST.
11732 PLIST must contain a :name entry which is used as name of the block."
11733 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11734 (end-of-line 1)
11735 (newline))
11736 (let ((col (current-column))
11737 (name (plist-get plist :name)))
11738 (insert "#+BEGIN: " name)
11739 (while plist
11740 (if (eq (car plist) :name)
11741 (setq plist (cddr plist))
11742 (insert " " (prin1-to-string (pop plist)))))
11743 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11744 (beginning-of-line -2)))
11746 (defun org-prepare-dblock ()
11747 "Prepare dynamic block for refresh.
11748 This empties the block, puts the cursor at the insert position and returns
11749 the property list including an extra property :name with the block name."
11750 (unless (looking-at org-dblock-start-re)
11751 (error "Not at a dynamic block"))
11752 (let* ((begdel (1+ (match-end 0)))
11753 (name (org-no-properties (match-string 1)))
11754 (params (append (list :name name)
11755 (read (concat "(" (match-string 3) ")")))))
11756 (save-excursion
11757 (beginning-of-line 1)
11758 (skip-chars-forward " \t")
11759 (setq params (plist-put params :indentation-column (current-column))))
11760 (unless (re-search-forward org-dblock-end-re nil t)
11761 (error "Dynamic block not terminated"))
11762 (setq params
11763 (append params
11764 (list :content (buffer-substring
11765 begdel (match-beginning 0)))))
11766 (delete-region begdel (match-beginning 0))
11767 (goto-char begdel)
11768 (open-line 1)
11769 params))
11771 (defun org-map-dblocks (&optional command)
11772 "Apply COMMAND to all dynamic blocks in the current buffer.
11773 If COMMAND is not given, use `org-update-dblock'."
11774 (let ((cmd (or command 'org-update-dblock)))
11775 (save-excursion
11776 (goto-char (point-min))
11777 (while (re-search-forward org-dblock-start-re nil t)
11778 (goto-char (match-beginning 0))
11779 (save-excursion
11780 (condition-case nil
11781 (funcall cmd)
11782 (error (message "Error during update of dynamic block"))))
11783 (unless (re-search-forward org-dblock-end-re nil t)
11784 (error "Dynamic block not terminated"))))))
11786 (defun org-dblock-update (&optional arg)
11787 "User command for updating dynamic blocks.
11788 Update the dynamic block at point. With prefix ARG, update all dynamic
11789 blocks in the buffer."
11790 (interactive "P")
11791 (if arg
11792 (org-update-all-dblocks)
11793 (or (looking-at org-dblock-start-re)
11794 (org-beginning-of-dblock))
11795 (org-update-dblock)))
11797 (defun org-update-dblock ()
11798 "Update the dynamic block at point.
11799 This means to empty the block, parse for parameters and then call
11800 the correct writing function."
11801 (interactive)
11802 (save-window-excursion
11803 (let* ((pos (point))
11804 (line (org-current-line))
11805 (params (org-prepare-dblock))
11806 (name (plist-get params :name))
11807 (indent (plist-get params :indentation-column))
11808 (cmd (intern (concat "org-dblock-write:" name))))
11809 (message "Updating dynamic block `%s' at line %d..." name line)
11810 (funcall cmd params)
11811 (message "Updating dynamic block `%s' at line %d...done" name line)
11812 (goto-char pos)
11813 (when (and indent (> indent 0))
11814 (setq indent (make-string indent ?\ ))
11815 (save-excursion
11816 (org-beginning-of-dblock)
11817 (forward-line 1)
11818 (while (not (looking-at org-dblock-end-re))
11819 (insert indent)
11820 (beginning-of-line 2))
11821 (when (looking-at org-dblock-end-re)
11822 (and (looking-at "[ \t]+")
11823 (replace-match ""))
11824 (insert indent)))))))
11826 (defun org-beginning-of-dblock ()
11827 "Find the beginning of the dynamic block at point.
11828 Error if there is no such block at point."
11829 (let ((pos (point))
11830 beg)
11831 (end-of-line 1)
11832 (if (and (re-search-backward org-dblock-start-re nil t)
11833 (setq beg (match-beginning 0))
11834 (re-search-forward org-dblock-end-re nil t)
11835 (> (match-end 0) pos))
11836 (goto-char beg)
11837 (goto-char pos)
11838 (error "Not in a dynamic block"))))
11840 (defun org-update-all-dblocks ()
11841 "Update all dynamic blocks in the buffer.
11842 This function can be used in a hook."
11843 (interactive)
11844 (when (derived-mode-p 'org-mode)
11845 (org-map-dblocks 'org-update-dblock)))
11848 ;;;; Completion
11850 (defun org-get-export-keywords ()
11851 "Return a list of all currently understood export keywords.
11852 Export keywords include options, block names, attributes and
11853 keywords relative to each registered export back-end."
11854 (delq nil
11855 (let (keywords)
11856 (mapc
11857 (lambda (back-end)
11858 (let ((props (cdr back-end)))
11859 ;; Back-end name (for keywords, like #+LATEX:)
11860 (push (upcase (symbol-name (car back-end))) keywords)
11861 ;; Back-end options.
11862 (mapc (lambda (option) (push (cadr option) keywords))
11863 (plist-get (cdr back-end) :options-alist))))
11864 (org-bound-and-true-p org-export-registered-backends))
11865 keywords)))
11867 (defconst org-options-keywords
11868 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11869 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11870 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11871 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11872 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11874 (defcustom org-structure-template-alist
11875 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11876 "<src lang=\"?\">\n\n</src>")
11877 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11878 "<example>\n?\n</example>")
11879 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11880 "<quote>\n?\n</quote>")
11881 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11882 "<verse>\n?\n</verse>")
11883 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11884 "<verbatim>\n?\n</verbatim>")
11885 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11886 "<center>\n?\n</center>")
11887 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11888 "<literal style=\"latex\">\n?\n</literal>")
11889 ("L" "#+LaTeX: "
11890 "<literal style=\"latex\">?</literal>")
11891 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11892 "<literal style=\"html\">\n?\n</literal>")
11893 ("H" "#+HTML: "
11894 "<literal style=\"html\">?</literal>")
11895 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11896 ("A" "#+ASCII: ")
11897 ("i" "#+INDEX: ?"
11898 "#+INDEX: ?")
11899 ("I" "#+INCLUDE: %file ?"
11900 "<include file=%file markup=\"?\">"))
11901 "Structure completion elements.
11902 This is a list of abbreviation keys and values. The value gets inserted
11903 if you type `<' followed by the key and then press the completion key,
11904 usually `M-TAB'. %file will be replaced by a file name after prompting
11905 for the file using completion. The cursor will be placed at the position
11906 of the `?` in the template.
11907 There are two templates for each key, the first uses the original Org syntax,
11908 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11909 the default when the /org-mtags.el/ module has been loaded. See also the
11910 variable `org-mtags-prefer-muse-templates'."
11911 :group 'org-completion
11912 :type '(repeat
11913 (string :tag "Key")
11914 (string :tag "Template")
11915 (string :tag "Muse Template")))
11917 (defun org-try-structure-completion ()
11918 "Try to complete a structure template before point.
11919 This looks for strings like \"<e\" on an otherwise empty line and
11920 expands them."
11921 (let ((l (buffer-substring (point-at-bol) (point)))
11923 (when (and (looking-at "[ \t]*$")
11924 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11925 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11926 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11927 (match-beginning 1)) a)
11928 t)))
11930 (defun org-complete-expand-structure-template (start cell)
11931 "Expand a structure template."
11932 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11933 (rpl (nth (if musep 2 1) cell))
11934 (ind ""))
11935 (delete-region start (point))
11936 (when (string-match "\\`#\\+" rpl)
11937 (cond
11938 ((bolp))
11939 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11940 (setq ind (buffer-substring (point-at-bol) (point))))
11941 (t (newline))))
11942 (setq start (point))
11943 (if (string-match "%file" rpl)
11944 (setq rpl (replace-match
11945 (concat
11946 "\""
11947 (save-match-data
11948 (abbreviate-file-name (read-file-name "Include file: ")))
11949 "\"")
11950 t t rpl)))
11951 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11952 (concat "\n" ind)))
11953 (insert rpl)
11954 (if (re-search-backward "\\?" start t) (delete-char 1))))
11956 ;;;; TODO, DEADLINE, Comments
11958 (defun org-toggle-comment ()
11959 "Change the COMMENT state of an entry."
11960 (interactive)
11961 (save-excursion
11962 (org-back-to-heading)
11963 (let (case-fold-search)
11964 (cond
11965 ((looking-at (format org-heading-keyword-regexp-format
11966 org-comment-string))
11967 (goto-char (match-end 1))
11968 (looking-at (concat " +" org-comment-string))
11969 (replace-match "" t t)
11970 (when (eolp) (insert " ")))
11971 ((looking-at org-outline-regexp)
11972 (goto-char (match-end 0))
11973 (insert org-comment-string " "))))))
11975 (defvar org-last-todo-state-is-todo nil
11976 "This is non-nil when the last TODO state change led to a TODO state.
11977 If the last change removed the TODO tag or switched to DONE, then
11978 this is nil.")
11980 (defvar org-setting-tags nil) ; dynamically skipped
11982 (defvar org-todo-setup-filter-hook nil
11983 "Hook for functions that pre-filter todo specs.
11984 Each function takes a todo spec and returns either nil or the spec
11985 transformed into canonical form." )
11987 (defvar org-todo-get-default-hook nil
11988 "Hook for functions that get a default item for todo.
11989 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11990 nil or a string to be used for the todo mark." )
11992 (defvar org-agenda-headline-snapshot-before-repeat)
11994 (defun org-current-effective-time ()
11995 "Return current time adjusted for `org-extend-today-until' variable."
11996 (let* ((ct (org-current-time))
11997 (dct (decode-time ct))
11998 (ct1
11999 (cond
12000 (org-use-last-clock-out-time-as-effective-time
12001 (or (org-clock-get-last-clock-out-time) ct))
12002 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12003 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12004 (t ct))))
12005 ct1))
12007 (defun org-todo-yesterday (&optional arg)
12008 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12009 (interactive "P")
12010 (if (eq major-mode 'org-agenda-mode)
12011 (apply 'org-agenda-todo-yesterday arg)
12012 (let* ((hour (third (decode-time
12013 (org-current-time))))
12014 (org-extend-today-until (1+ hour)))
12015 (org-todo arg))))
12017 (defvar org-block-entry-blocking ""
12018 "First entry preventing the TODO state change.")
12020 (defun org-todo (&optional arg)
12021 "Change the TODO state of an item.
12022 The state of an item is given by a keyword at the start of the heading,
12023 like
12024 *** TODO Write paper
12025 *** DONE Call mom
12027 The different keywords are specified in the variable `org-todo-keywords'.
12028 By default the available states are \"TODO\" and \"DONE\".
12029 So for this example: when the item starts with TODO, it is changed to DONE.
12030 When it starts with DONE, the DONE is removed. And when neither TODO nor
12031 DONE are present, add TODO at the beginning of the heading.
12033 With \\[universal-argument] prefix arg, use completion to determine the new \
12034 state.
12035 With numeric prefix arg, switch to that state.
12036 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12037 keywords (nextset).
12038 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12039 With a numeric prefix arg of 0, inhibit note taking for the change.
12041 For calling through lisp, arg is also interpreted in the following way:
12042 'none -> empty state
12043 \"\"(empty string) -> switch to empty state
12044 'done -> switch to DONE
12045 'nextset -> switch to the next set of keywords
12046 'previousset -> switch to the previous set of keywords
12047 \"WAITING\" -> switch to the specified keyword, but only if it
12048 really is a member of `org-todo-keywords'."
12049 (interactive "P")
12050 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12051 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12052 'region-start-level 'region))
12053 org-loop-over-headlines-in-active-region)
12054 (org-map-entries
12055 `(org-todo ,arg)
12056 org-loop-over-headlines-in-active-region
12057 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12058 (if (equal arg '(16)) (setq arg 'nextset))
12059 (let ((org-blocker-hook org-blocker-hook)
12060 commentp
12061 case-fold-search)
12062 (when (equal arg '(64))
12063 (setq arg nil org-blocker-hook nil))
12064 (when (and org-blocker-hook
12065 (or org-inhibit-blocking
12066 (org-entry-get nil "NOBLOCKING")))
12067 (setq org-blocker-hook nil))
12068 (save-excursion
12069 (catch 'exit
12070 (org-back-to-heading t)
12071 (when (looking-at (concat "^\\*+ " org-comment-string))
12072 (org-toggle-comment)
12073 (setq commentp t))
12074 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12075 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12076 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12077 (let* ((match-data (match-data))
12078 (startpos (point-at-bol))
12079 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12080 (org-log-done org-log-done)
12081 (org-log-repeat org-log-repeat)
12082 (org-todo-log-states org-todo-log-states)
12083 (org-inhibit-logging
12084 (if (equal arg 0)
12085 (progn (setq arg nil) 'note) org-inhibit-logging))
12086 (this (match-string 1))
12087 (hl-pos (match-beginning 0))
12088 (head (org-get-todo-sequence-head this))
12089 (ass (assoc head org-todo-kwd-alist))
12090 (interpret (nth 1 ass))
12091 (done-word (nth 3 ass))
12092 (final-done-word (nth 4 ass))
12093 (org-last-state (or this ""))
12094 (completion-ignore-case t)
12095 (member (member this org-todo-keywords-1))
12096 (tail (cdr member))
12097 (org-state (cond
12098 ((and org-todo-key-trigger
12099 (or (and (equal arg '(4))
12100 (eq org-use-fast-todo-selection 'prefix))
12101 (and (not arg) org-use-fast-todo-selection
12102 (not (eq org-use-fast-todo-selection
12103 'prefix)))))
12104 ;; Use fast selection
12105 (org-fast-todo-selection))
12106 ((and (equal arg '(4))
12107 (or (not org-use-fast-todo-selection)
12108 (not org-todo-key-trigger)))
12109 ;; Read a state with completion
12110 (org-icompleting-read
12111 "State: " (mapcar 'list org-todo-keywords-1)
12112 nil t))
12113 ((eq arg 'right)
12114 (if this
12115 (if tail (car tail) nil)
12116 (car org-todo-keywords-1)))
12117 ((eq arg 'left)
12118 (if (equal member org-todo-keywords-1)
12120 (if this
12121 (nth (- (length org-todo-keywords-1)
12122 (length tail) 2)
12123 org-todo-keywords-1)
12124 (org-last org-todo-keywords-1))))
12125 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12126 (setq arg nil))) ; hack to fall back to cycling
12127 (arg
12128 ;; user or caller requests a specific state
12129 (cond
12130 ((equal arg "") nil)
12131 ((eq arg 'none) nil)
12132 ((eq arg 'done) (or done-word (car org-done-keywords)))
12133 ((eq arg 'nextset)
12134 (or (car (cdr (member head org-todo-heads)))
12135 (car org-todo-heads)))
12136 ((eq arg 'previousset)
12137 (let ((org-todo-heads (reverse org-todo-heads)))
12138 (or (car (cdr (member head org-todo-heads)))
12139 (car org-todo-heads))))
12140 ((car (member arg org-todo-keywords-1)))
12141 ((stringp arg)
12142 (error "State `%s' not valid in this file" arg))
12143 ((nth (1- (prefix-numeric-value arg))
12144 org-todo-keywords-1))))
12145 ((null member) (or head (car org-todo-keywords-1)))
12146 ((equal this final-done-word) nil) ;; -> make empty
12147 ((null tail) nil) ;; -> first entry
12148 ((memq interpret '(type priority))
12149 (if (eq this-command last-command)
12150 (car tail)
12151 (if (> (length tail) 0)
12152 (or done-word (car org-done-keywords))
12153 nil)))
12155 (car tail))))
12156 (org-state (or
12157 (run-hook-with-args-until-success
12158 'org-todo-get-default-hook org-state org-last-state)
12159 org-state))
12160 (next (if org-state (concat " " org-state " ") " "))
12161 (change-plist (list :type 'todo-state-change :from this :to org-state
12162 :position startpos))
12163 dolog now-done-p)
12164 (when org-blocker-hook
12165 (setq org-last-todo-state-is-todo
12166 (not (member this org-done-keywords)))
12167 (unless (save-excursion
12168 (save-match-data
12169 (org-with-wide-buffer
12170 (run-hook-with-args-until-failure
12171 'org-blocker-hook change-plist))))
12172 (if (org-called-interactively-p 'interactive)
12173 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12174 this org-state org-block-entry-blocking)
12175 ;; fail silently
12176 (message "TODO state change from %s to %s blocked (by \"%s\")"
12177 this org-state org-block-entry-blocking)
12178 (throw 'exit nil))))
12179 (store-match-data match-data)
12180 (replace-match next t t)
12181 (unless (pos-visible-in-window-p hl-pos)
12182 (message "TODO state changed to %s" (org-trim next)))
12183 (unless head
12184 (setq head (org-get-todo-sequence-head org-state)
12185 ass (assoc head org-todo-kwd-alist)
12186 interpret (nth 1 ass)
12187 done-word (nth 3 ass)
12188 final-done-word (nth 4 ass)))
12189 (when (memq arg '(nextset previousset))
12190 (message "Keyword-Set %d/%d: %s"
12191 (- (length org-todo-sets) -1
12192 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12193 (length org-todo-sets)
12194 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12195 (setq org-last-todo-state-is-todo
12196 (not (member org-state org-done-keywords)))
12197 (setq now-done-p (and (member org-state org-done-keywords)
12198 (not (member this org-done-keywords))))
12199 (and logging (org-local-logging logging))
12200 (when (and (or org-todo-log-states org-log-done)
12201 (not (eq org-inhibit-logging t))
12202 (not (memq arg '(nextset previousset))))
12203 ;; we need to look at recording a time and note
12204 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12205 (nth 2 (assoc this org-todo-log-states))))
12206 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12207 (setq dolog 'time))
12208 (when (and org-state
12209 (member org-state org-not-done-keywords)
12210 (not (member this org-not-done-keywords)))
12211 ;; This is now a todo state and was not one before
12212 ;; If there was a CLOSED time stamp, get rid of it.
12213 (org-add-planning-info nil nil 'closed))
12214 (when (and now-done-p org-log-done)
12215 ;; It is now done, and it was not done before
12216 (org-add-planning-info 'closed (org-current-effective-time))
12217 (if (and (not dolog) (eq 'note org-log-done))
12218 (org-add-log-setup 'done org-state this 'findpos 'note)))
12219 (when (and org-state dolog)
12220 ;; This is a non-nil state, and we need to log it
12221 (org-add-log-setup 'state org-state this 'findpos dolog)))
12222 ;; Fixup tag positioning
12223 (org-todo-trigger-tag-changes org-state)
12224 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12225 (when org-provide-todo-statistics
12226 (org-update-parent-todo-statistics))
12227 (run-hooks 'org-after-todo-state-change-hook)
12228 (if (and arg (not (member org-state org-done-keywords)))
12229 (setq head (org-get-todo-sequence-head org-state)))
12230 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12231 ;; Do we need to trigger a repeat?
12232 (when now-done-p
12233 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12234 ;; This is for the agenda, take a snapshot of the headline.
12235 (save-match-data
12236 (setq org-agenda-headline-snapshot-before-repeat
12237 (org-get-heading))))
12238 (org-auto-repeat-maybe org-state))
12239 ;; Fixup cursor location if close to the keyword
12240 (if (and (outline-on-heading-p)
12241 (not (bolp))
12242 (save-excursion (beginning-of-line 1)
12243 (looking-at org-todo-line-regexp))
12244 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12245 (progn
12246 (goto-char (or (match-end 2) (match-end 1)))
12247 (and (looking-at " ") (just-one-space))))
12248 (when org-trigger-hook
12249 (save-excursion
12250 (run-hook-with-args 'org-trigger-hook change-plist)))
12251 (when commentp (org-toggle-comment))))))))
12253 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12254 "Block turning an entry into a TODO, using the hierarchy.
12255 This checks whether the current task should be blocked from state
12256 changes. Such blocking occurs when:
12258 1. The task has children which are not all in a completed state.
12260 2. A task has a parent with the property :ORDERED:, and there
12261 are siblings prior to the current task with incomplete
12262 status.
12264 3. The parent of the task is blocked because it has siblings that should
12265 be done first, or is child of a block grandparent TODO entry."
12267 (if (not org-enforce-todo-dependencies)
12268 t ; if locally turned off don't block
12269 (catch 'dont-block
12270 ;; If this is not a todo state change, or if this entry is already DONE,
12271 ;; do not block
12272 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12273 (member (plist-get change-plist :from)
12274 (cons 'done org-done-keywords))
12275 (member (plist-get change-plist :to)
12276 (cons 'todo org-not-done-keywords))
12277 (not (plist-get change-plist :to)))
12278 (throw 'dont-block t))
12279 ;; If this task has children, and any are undone, it's blocked
12280 (save-excursion
12281 (org-back-to-heading t)
12282 (let ((this-level (funcall outline-level)))
12283 (outline-next-heading)
12284 (let ((child-level (funcall outline-level)))
12285 (while (and (not (eobp))
12286 (> child-level this-level))
12287 ;; this todo has children, check whether they are all
12288 ;; completed
12289 (if (and (not (org-entry-is-done-p))
12290 (org-entry-is-todo-p))
12291 (progn (setq org-block-entry-blocking (org-get-heading))
12292 (throw 'dont-block nil)))
12293 (outline-next-heading)
12294 (setq child-level (funcall outline-level))))))
12295 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12296 ;; any previous siblings are undone, it's blocked
12297 (save-excursion
12298 (org-back-to-heading t)
12299 (let* ((pos (point))
12300 (parent-pos (and (org-up-heading-safe) (point))))
12301 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12302 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12303 (forward-line 1)
12304 (re-search-forward org-not-done-heading-regexp pos t))
12305 (setq org-block-entry-blocking (match-string 0))
12306 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12307 ;; Search further up the hierarchy, to see if an ancestor is blocked
12308 (while t
12309 (goto-char parent-pos)
12310 (if (not (looking-at org-not-done-heading-regexp))
12311 (throw 'dont-block t)) ; do not block, parent is not a TODO
12312 (setq pos (point))
12313 (setq parent-pos (and (org-up-heading-safe) (point)))
12314 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12315 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12316 (forward-line 1)
12317 (re-search-forward org-not-done-heading-regexp pos t)
12318 (setq org-block-entry-blocking (org-get-heading)))
12319 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12321 (defcustom org-track-ordered-property-with-tag nil
12322 "Should the ORDERED property also be shown as a tag?
12323 The ORDERED property decides if an entry should require subtasks to be
12324 completed in sequence. Since a property is not very visible, setting
12325 this option means that toggling the ORDERED property with the command
12326 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12327 not relevant for the behavior, but it makes things more visible.
12329 Note that toggling the tag with tags commands will not change the property
12330 and therefore not influence behavior!
12332 This can be t, meaning the tag ORDERED should be used, It can also be a
12333 string to select a different tag for this task."
12334 :group 'org-todo
12335 :type '(choice
12336 (const :tag "No tracking" nil)
12337 (const :tag "Track with ORDERED tag" t)
12338 (string :tag "Use other tag")))
12340 (defun org-toggle-ordered-property ()
12341 "Toggle the ORDERED property of the current entry.
12342 For better visibility, you can track the value of this property with a tag.
12343 See variable `org-track-ordered-property-with-tag'."
12344 (interactive)
12345 (let* ((t1 org-track-ordered-property-with-tag)
12346 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12347 (save-excursion
12348 (org-back-to-heading)
12349 (if (org-entry-get nil "ORDERED")
12350 (progn
12351 (org-delete-property "ORDERED" "PROPERTIES")
12352 (and tag (org-toggle-tag tag 'off))
12353 (message "Subtasks can be completed in arbitrary order"))
12354 (org-entry-put nil "ORDERED" "t")
12355 (and tag (org-toggle-tag tag 'on))
12356 (message "Subtasks must be completed in sequence")))))
12358 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12359 (defun org-block-todo-from-checkboxes (change-plist)
12360 "Block turning an entry into a TODO, using checkboxes.
12361 This checks whether the current task should be blocked from state
12362 changes because there are unchecked boxes in this entry."
12363 (if (not org-enforce-todo-checkbox-dependencies)
12364 t ; if locally turned off don't block
12365 (catch 'dont-block
12366 ;; If this is not a todo state change, or if this entry is already DONE,
12367 ;; do not block
12368 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12369 (member (plist-get change-plist :from)
12370 (cons 'done org-done-keywords))
12371 (member (plist-get change-plist :to)
12372 (cons 'todo org-not-done-keywords))
12373 (not (plist-get change-plist :to)))
12374 (throw 'dont-block t))
12375 ;; If this task has checkboxes that are not checked, it's blocked
12376 (save-excursion
12377 (org-back-to-heading t)
12378 (let ((beg (point)) end)
12379 (outline-next-heading)
12380 (setq end (point))
12381 (goto-char beg)
12382 (if (org-list-search-forward
12383 (concat (org-item-beginning-re)
12384 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12385 "\\[[- ]\\]")
12386 end t)
12387 (progn
12388 (if (boundp 'org-blocked-by-checkboxes)
12389 (setq org-blocked-by-checkboxes t))
12390 (throw 'dont-block nil)))))
12391 t))) ; do not block
12393 (defun org-entry-blocked-p ()
12394 "Is the current entry blocked?"
12395 (org-with-silent-modifications
12396 (if (org-entry-get nil "NOBLOCKING")
12397 nil ;; Never block this entry
12398 (not (run-hook-with-args-until-failure
12399 'org-blocker-hook
12400 (list :type 'todo-state-change
12401 :position (point)
12402 :from 'todo
12403 :to 'done))))))
12405 (defun org-update-statistics-cookies (all)
12406 "Update the statistics cookie, either from TODO or from checkboxes.
12407 This should be called with the cursor in a line with a statistics cookie."
12408 (interactive "P")
12409 (if all
12410 (progn
12411 (org-update-checkbox-count 'all)
12412 (org-map-entries 'org-update-parent-todo-statistics))
12413 (if (not (org-at-heading-p))
12414 (org-update-checkbox-count)
12415 (let ((pos (point-marker))
12416 end l1 l2)
12417 (ignore-errors (org-back-to-heading t))
12418 (if (not (org-at-heading-p))
12419 (org-update-checkbox-count)
12420 (setq l1 (org-outline-level))
12421 (setq end (save-excursion
12422 (outline-next-heading)
12423 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12424 (point)))
12425 (if (and (save-excursion
12426 (re-search-forward
12427 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12428 (not (save-excursion (re-search-forward
12429 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12430 (org-update-checkbox-count)
12431 (if (and l2 (> l2 l1))
12432 (progn
12433 (goto-char end)
12434 (org-update-parent-todo-statistics))
12435 (goto-char pos)
12436 (beginning-of-line 1)
12437 (while (re-search-forward
12438 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12439 (point-at-eol) t)
12440 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12441 (goto-char pos)
12442 (move-marker pos nil)))))
12444 (defvar org-entry-property-inherited-from) ;; defined below
12445 (defun org-update-parent-todo-statistics ()
12446 "Update any statistics cookie in the parent of the current headline.
12447 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12448 the entire subtree and this will travel up the hierarchy and update
12449 statistics everywhere."
12450 (let* ((prop (save-excursion (org-up-heading-safe)
12451 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12452 (recursive (or (not org-hierarchical-todo-statistics)
12453 (and prop (string-match "\\<recursive\\>" prop))))
12454 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12456 (first t)
12457 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12458 level ltoggle l1 new ndel
12459 (cnt-all 0) (cnt-done 0) is-percent kwd
12460 checkbox-beg ov ovs ove cookie-present)
12461 (catch 'exit
12462 (save-excursion
12463 (beginning-of-line 1)
12464 (setq ltoggle (funcall outline-level))
12465 ;; Three situations are to consider:
12467 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12468 ;; to the top-level ancestor on the headline;
12470 ;; 2. If parent has "recursive" property, repeat up to the
12471 ;; headline setting that property, taking inheritance into
12472 ;; account;
12474 ;; 3. Else, move up to direct parent and proceed only once.
12475 (while (and (setq level (org-up-heading-safe))
12476 (or recursive first)
12477 (>= (point) lim))
12478 (setq first nil cookie-present nil)
12479 (unless (and level
12480 (not (string-match
12481 "\\<checkbox\\>"
12482 (downcase (or (org-entry-get nil "COOKIE_DATA")
12483 "")))))
12484 (throw 'exit nil))
12485 (while (re-search-forward box-re (point-at-eol) t)
12486 (setq cnt-all 0 cnt-done 0 cookie-present t)
12487 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12488 (save-match-data
12489 (unless (outline-next-heading) (throw 'exit nil))
12490 (while (and (looking-at org-complex-heading-regexp)
12491 (> (setq l1 (length (match-string 1))) level))
12492 (setq kwd (and (or recursive (= l1 ltoggle))
12493 (match-string 2)))
12494 (if (or (eq org-provide-todo-statistics 'all-headlines)
12495 (and (listp org-provide-todo-statistics)
12496 (or (member kwd org-provide-todo-statistics)
12497 (member kwd org-done-keywords))))
12498 (setq cnt-all (1+ cnt-all))
12499 (if (eq org-provide-todo-statistics t)
12500 (and kwd (setq cnt-all (1+ cnt-all)))))
12501 (and (member kwd org-done-keywords)
12502 (setq cnt-done (1+ cnt-done)))
12503 (outline-next-heading)))
12504 (setq new
12505 (if is-percent
12506 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12507 (format "[%d/%d]" cnt-done cnt-all))
12508 ndel (- (match-end 0) checkbox-beg))
12509 ;; handle overlays when updating cookie from column view
12510 (when (setq ov (car (overlays-at checkbox-beg)))
12511 (setq ovs (overlay-start ov) ove (overlay-end ov))
12512 (delete-overlay ov))
12513 (goto-char checkbox-beg)
12514 (insert new)
12515 (delete-region (point) (+ (point) ndel))
12516 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12517 (when ov (move-overlay ov ovs ove)))
12518 (when cookie-present
12519 (run-hook-with-args 'org-after-todo-statistics-hook
12520 cnt-done (- cnt-all cnt-done))))))
12521 (run-hooks 'org-todo-statistics-hook)))
12523 (defvar org-after-todo-statistics-hook nil
12524 "Hook that is called after a TODO statistics cookie has been updated.
12525 Each function is called with two arguments: the number of not-done entries
12526 and the number of done entries.
12528 For example, the following function, when added to this hook, will switch
12529 an entry to DONE when all children are done, and back to TODO when new
12530 entries are set to a TODO status. Note that this hook is only called
12531 when there is a statistics cookie in the headline!
12533 (defun org-summary-todo (n-done n-not-done)
12534 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12535 (let (org-log-done org-log-states) ; turn off logging
12536 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12539 (defvar org-todo-statistics-hook nil
12540 "Hook that is run whenever Org thinks TODO statistics should be updated.
12541 This hook runs even if there is no statistics cookie present, in which case
12542 `org-after-todo-statistics-hook' would not run.")
12544 (defun org-todo-trigger-tag-changes (state)
12545 "Apply the changes defined in `org-todo-state-tags-triggers'."
12546 (let ((l org-todo-state-tags-triggers)
12547 changes)
12548 (when (or (not state) (equal state ""))
12549 (setq changes (append changes (cdr (assoc "" l)))))
12550 (when (and (stringp state) (> (length state) 0))
12551 (setq changes (append changes (cdr (assoc state l)))))
12552 (when (member state org-not-done-keywords)
12553 (setq changes (append changes (cdr (assoc 'todo l)))))
12554 (when (member state org-done-keywords)
12555 (setq changes (append changes (cdr (assoc 'done l)))))
12556 (dolist (c changes)
12557 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12559 (defun org-local-logging (value)
12560 "Get logging settings from a property VALUE."
12561 (let* (words w a)
12562 ;; directly set the variables, they are already local.
12563 (setq org-log-done nil
12564 org-log-repeat nil
12565 org-todo-log-states nil)
12566 (setq words (org-split-string value))
12567 (while (setq w (pop words))
12568 (cond
12569 ((setq a (assoc w org-startup-options))
12570 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12571 (set (nth 1 a) (nth 2 a))))
12572 ((setq a (org-extract-log-state-settings w))
12573 (and (member (car a) org-todo-keywords-1)
12574 (push a org-todo-log-states)))))))
12576 (defun org-get-todo-sequence-head (kwd)
12577 "Return the head of the TODO sequence to which KWD belongs.
12578 If KWD is not set, check if there is a text property remembering the
12579 right sequence."
12580 (let (p)
12581 (cond
12582 ((not kwd)
12583 (or (get-text-property (point-at-bol) 'org-todo-head)
12584 (progn
12585 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12586 nil (point-at-eol)))
12587 (get-text-property p 'org-todo-head))))
12588 ((not (member kwd org-todo-keywords-1))
12589 (car org-todo-keywords-1))
12590 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12592 (defun org-fast-todo-selection ()
12593 "Fast TODO keyword selection with single keys.
12594 Returns the new TODO keyword, or nil if no state change should occur."
12595 (let* ((fulltable org-todo-key-alist)
12596 (done-keywords org-done-keywords) ;; needed for the faces.
12597 (maxlen (apply 'max (mapcar
12598 (lambda (x)
12599 (if (stringp (car x)) (string-width (car x)) 0))
12600 fulltable)))
12601 (expert nil)
12602 (fwidth (+ maxlen 3 1 3))
12603 (ncol (/ (- (window-width) 4) fwidth))
12604 tg cnt e c tbl
12605 groups ingroup)
12606 (save-excursion
12607 (save-window-excursion
12608 (if expert
12609 (set-buffer (get-buffer-create " *Org todo*"))
12610 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12611 (erase-buffer)
12612 (org-set-local 'org-done-keywords done-keywords)
12613 (setq tbl fulltable cnt 0)
12614 (while (setq e (pop tbl))
12615 (cond
12616 ((equal e '(:startgroup))
12617 (push '() groups) (setq ingroup t)
12618 (when (not (= cnt 0))
12619 (setq cnt 0)
12620 (insert "\n"))
12621 (insert "{ "))
12622 ((equal e '(:endgroup))
12623 (setq ingroup nil cnt 0)
12624 (insert "}\n"))
12625 ((equal e '(:newline))
12626 (when (not (= cnt 0))
12627 (setq cnt 0)
12628 (insert "\n")
12629 (setq e (car tbl))
12630 (while (equal (car tbl) '(:newline))
12631 (insert "\n")
12632 (setq tbl (cdr tbl)))))
12634 (setq tg (car e) c (cdr e))
12635 (if ingroup (push tg (car groups)))
12636 (setq tg (org-add-props tg nil 'face
12637 (org-get-todo-face tg)))
12638 (if (and (= cnt 0) (not ingroup)) (insert " "))
12639 (insert "[" c "] " tg (make-string
12640 (- fwidth 4 (length tg)) ?\ ))
12641 (when (= (setq cnt (1+ cnt)) ncol)
12642 (insert "\n")
12643 (if ingroup (insert " "))
12644 (setq cnt 0)))))
12645 (insert "\n")
12646 (goto-char (point-min))
12647 (if (not expert) (org-fit-window-to-buffer))
12648 (message "[a-z..]:Set [SPC]:clear")
12649 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12650 (cond
12651 ((or (= c ?\C-g)
12652 (and (= c ?q) (not (rassoc c fulltable))))
12653 (setq quit-flag t))
12654 ((= c ?\ ) nil)
12655 ((setq e (rassoc c fulltable) tg (car e))
12657 (t (setq quit-flag t)))))))
12659 (defun org-entry-is-todo-p ()
12660 (member (org-get-todo-state) org-not-done-keywords))
12662 (defun org-entry-is-done-p ()
12663 (member (org-get-todo-state) org-done-keywords))
12665 (defun org-get-todo-state ()
12666 (save-excursion
12667 (org-back-to-heading t)
12668 (and (looking-at org-todo-line-regexp)
12669 (match-end 2)
12670 (match-string 2))))
12672 (defun org-at-date-range-p (&optional inactive-ok)
12673 "Is the cursor inside a date range?"
12674 (interactive)
12675 (save-excursion
12676 (catch 'exit
12677 (let ((pos (point)))
12678 (skip-chars-backward "^[<\r\n")
12679 (skip-chars-backward "<[")
12680 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12681 (>= (match-end 0) pos)
12682 (throw 'exit t))
12683 (skip-chars-backward "^<[\r\n")
12684 (skip-chars-backward "<[")
12685 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12686 (>= (match-end 0) pos)
12687 (throw 'exit t)))
12688 nil)))
12690 (defun org-get-repeat (&optional tagline)
12691 "Check if there is a deadline/schedule with repeater in this entry."
12692 (save-match-data
12693 (save-excursion
12694 (org-back-to-heading t)
12695 (and (re-search-forward (if tagline
12696 (concat tagline "\\s-*" org-repeat-re)
12697 org-repeat-re)
12698 (org-entry-end-position) t)
12699 (match-string-no-properties 1)))))
12701 (defvar org-last-changed-timestamp)
12702 (defvar org-last-inserted-timestamp)
12703 (defvar org-log-post-message)
12704 (defvar org-log-note-purpose)
12705 (defvar org-log-note-how)
12706 (defvar org-log-note-extra)
12707 (defun org-auto-repeat-maybe (done-word)
12708 "Check if the current headline contains a repeated deadline/schedule.
12709 If yes, set TODO state back to what it was and change the base date
12710 of repeating deadline/scheduled time stamps to new date.
12711 This function is run automatically after each state change to a DONE state."
12712 ;; last-state is dynamically scoped into this function
12713 (let* ((repeat (org-get-repeat))
12714 (aa (assoc org-last-state org-todo-kwd-alist))
12715 (interpret (nth 1 aa))
12716 (head (nth 2 aa))
12717 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12718 (msg "Entry repeats: ")
12719 (org-log-done nil)
12720 (org-todo-log-states nil)
12721 re type n what ts time to-state)
12722 (when repeat
12723 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12724 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12725 org-todo-repeat-to-state))
12726 (unless (and to-state (member to-state org-todo-keywords-1))
12727 (setq to-state (if (eq interpret 'type) org-last-state head)))
12728 (org-todo to-state)
12729 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12730 (org-entry-put nil "LAST_REPEAT" (format-time-string
12731 (org-time-stamp-format t t))))
12732 (when org-log-repeat
12733 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12734 (memq 'org-add-log-note post-command-hook))
12735 ;; OK, we are already setup for some record
12736 (if (eq org-log-repeat 'note)
12737 ;; make sure we take a note, not only a time stamp
12738 (setq org-log-note-how 'note))
12739 ;; Set up for taking a record
12740 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12741 org-last-state
12742 'findpos org-log-repeat)))
12743 (org-back-to-heading t)
12744 (org-add-planning-info nil nil 'closed)
12745 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12746 org-deadline-time-regexp "\\)\\|\\("
12747 org-ts-regexp "\\)"))
12748 (while (re-search-forward
12749 re (save-excursion (outline-next-heading) (point)) t)
12750 (setq type (if (match-end 1) org-scheduled-string
12751 (if (match-end 3) org-deadline-string "Plain:"))
12752 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12753 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12754 (setq n (string-to-number (match-string 2 ts))
12755 what (match-string 3 ts))
12756 (if (equal what "w") (setq n (* n 7) what "d"))
12757 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12758 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12759 ;; Preparation, see if we need to modify the start date for the change
12760 (when (match-end 1)
12761 (setq time (save-match-data (org-time-string-to-time ts)))
12762 (cond
12763 ((equal (match-string 1 ts) ".")
12764 ;; Shift starting date to today
12765 (org-timestamp-change
12766 (- (org-today) (time-to-days time))
12767 'day))
12768 ((equal (match-string 1 ts) "+")
12769 (let ((nshiftmax 10) (nshift 0))
12770 (while (or (= nshift 0)
12771 (<= (time-to-days time)
12772 (time-to-days (current-time))))
12773 (when (= (incf nshift) nshiftmax)
12774 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12775 (error "Abort")))
12776 (org-timestamp-change n (cdr (assoc what whata)))
12777 (org-at-timestamp-p t)
12778 (setq ts (match-string 1))
12779 (setq time (save-match-data (org-time-string-to-time ts)))))
12780 (org-timestamp-change (- n) (cdr (assoc what whata)))
12781 ;; rematch, so that we have everything in place for the real shift
12782 (org-at-timestamp-p t)
12783 (setq ts (match-string 1))
12784 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12785 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12786 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12787 (setq org-log-post-message msg)
12788 (message "%s" msg))))
12790 (defun org-show-todo-tree (arg)
12791 "Make a compact tree which shows all headlines marked with TODO.
12792 The tree will show the lines where the regexp matches, and all higher
12793 headlines above the match.
12794 With a \\[universal-argument] prefix, prompt for a regexp to match.
12795 With a numeric prefix N, construct a sparse tree for the Nth element
12796 of `org-todo-keywords-1'."
12797 (interactive "P")
12798 (let ((case-fold-search nil)
12799 (kwd-re
12800 (cond ((null arg) org-not-done-regexp)
12801 ((equal arg '(4))
12802 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12803 (mapcar 'list org-todo-keywords-1))))
12804 (concat "\\("
12805 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12806 "\\)\\>")))
12807 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12808 (regexp-quote (nth (1- (prefix-numeric-value arg))
12809 org-todo-keywords-1)))
12810 (t (error "Invalid prefix argument: %s" arg)))))
12811 (message "%d TODO entries found"
12812 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12814 (defun org-deadline (arg &optional time)
12815 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12816 With one universal prefix argument, remove any deadline from the item.
12817 With two universal prefix arguments, prompt for a warning delay.
12818 With argument TIME, set the deadline at the corresponding date. TIME
12819 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12820 (interactive "P")
12821 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12822 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12823 'region-start-level 'region))
12824 org-loop-over-headlines-in-active-region)
12825 (org-map-entries
12826 `(org-deadline ',arg ,time)
12827 org-loop-over-headlines-in-active-region
12828 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12829 (let* ((old-date (org-entry-get nil "DEADLINE"))
12830 (old-date-time (if old-date (org-time-string-to-time old-date)))
12831 (repeater (and old-date
12832 (string-match
12833 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12834 old-date)
12835 (match-string 1 old-date))))
12836 (cond
12837 ((equal arg '(4))
12838 (when (and old-date org-log-redeadline)
12839 (org-add-log-setup 'deldeadline nil old-date 'findpos
12840 org-log-redeadline))
12841 (org-remove-timestamp-with-keyword org-deadline-string)
12842 (message "Item no longer has a deadline."))
12843 ((equal arg '(16))
12844 (save-excursion
12845 (if (re-search-forward
12846 org-deadline-time-regexp
12847 (save-excursion (outline-next-heading) (point)) t)
12848 (let* ((rpl0 (match-string 1))
12849 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12850 (replace-match
12851 (concat org-deadline-string
12852 " <" rpl
12853 (format " -%dd"
12854 (abs
12855 (- (time-to-days
12856 (save-match-data
12857 (org-read-date nil t nil "Warn starting from" old-date-time)))
12858 (time-to-days old-date-time))))
12859 ">") t t))
12860 (user-error "No deadline information to update"))))
12862 (org-add-planning-info 'deadline time 'closed)
12863 (when (and old-date org-log-redeadline
12864 (not (equal old-date
12865 (substring org-last-inserted-timestamp 1 -1))))
12866 (org-add-log-setup 'redeadline nil old-date 'findpos
12867 org-log-redeadline))
12868 (when repeater
12869 (save-excursion
12870 (org-back-to-heading t)
12871 (when (re-search-forward (concat org-deadline-string " "
12872 org-last-inserted-timestamp)
12873 (save-excursion
12874 (outline-next-heading) (point)) t)
12875 (goto-char (1- (match-end 0)))
12876 (insert " " repeater)
12877 (setq org-last-inserted-timestamp
12878 (concat (substring org-last-inserted-timestamp 0 -1)
12879 " " repeater
12880 (substring org-last-inserted-timestamp -1))))))
12881 (message "Deadline on %s" org-last-inserted-timestamp))))))
12883 (defun org-schedule (arg &optional time)
12884 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12885 With one universal prefix argument, remove any scheduling date from the item.
12886 With two universal prefix arguments, prompt for a delay cookie.
12887 With argument TIME, scheduled at the corresponding date. TIME can
12888 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12889 (interactive "P")
12890 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12891 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12892 'region-start-level 'region))
12893 org-loop-over-headlines-in-active-region)
12894 (org-map-entries
12895 `(org-schedule ',arg ,time)
12896 org-loop-over-headlines-in-active-region
12897 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12898 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12899 (old-date-time (if old-date (org-time-string-to-time old-date)))
12900 (repeater (and old-date
12901 (string-match
12902 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12903 old-date)
12904 (match-string 1 old-date))))
12905 (cond
12906 ((equal arg '(4))
12907 (progn
12908 (when (and old-date org-log-reschedule)
12909 (org-add-log-setup 'delschedule nil old-date 'findpos
12910 org-log-reschedule))
12911 (org-remove-timestamp-with-keyword org-scheduled-string)
12912 (message "Item is no longer scheduled.")))
12913 ((equal arg '(16))
12914 (save-excursion
12915 (if (re-search-forward
12916 org-scheduled-time-regexp
12917 (save-excursion (outline-next-heading) (point)) t)
12918 (let* ((rpl0 (match-string 1))
12919 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12920 (replace-match
12921 (concat org-scheduled-string
12922 " <" rpl
12923 (format " -%dd"
12924 (abs
12925 (- (time-to-days
12926 (save-match-data
12927 (org-read-date nil t nil "Delay until" old-date-time)))
12928 (time-to-days old-date-time))))
12929 ">") t t))
12930 (user-error "No scheduled information to update"))))
12932 (org-add-planning-info 'scheduled time 'closed)
12933 (when (and old-date org-log-reschedule
12934 (not (equal old-date
12935 (substring org-last-inserted-timestamp 1 -1))))
12936 (org-add-log-setup 'reschedule nil old-date 'findpos
12937 org-log-reschedule))
12938 (when repeater
12939 (save-excursion
12940 (org-back-to-heading t)
12941 (when (re-search-forward (concat org-scheduled-string " "
12942 org-last-inserted-timestamp)
12943 (save-excursion
12944 (outline-next-heading) (point)) t)
12945 (goto-char (1- (match-end 0)))
12946 (insert " " repeater)
12947 (setq org-last-inserted-timestamp
12948 (concat (substring org-last-inserted-timestamp 0 -1)
12949 " " repeater
12950 (substring org-last-inserted-timestamp -1))))))
12951 (message "Scheduled to %s" org-last-inserted-timestamp))))))
12953 (defun org-get-scheduled-time (pom &optional inherit)
12954 "Get the scheduled time as a time tuple, of a format suitable
12955 for calling org-schedule with, or if there is no scheduling,
12956 returns nil."
12957 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12958 (when time
12959 (apply 'encode-time (org-parse-time-string time)))))
12961 (defun org-get-deadline-time (pom &optional inherit)
12962 "Get the deadline as a time tuple, of a format suitable for
12963 calling org-deadline with, or if there is no scheduling, returns
12964 nil."
12965 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12966 (when time
12967 (apply 'encode-time (org-parse-time-string time)))))
12969 (defun org-remove-timestamp-with-keyword (keyword)
12970 "Remove all time stamps with KEYWORD in the current entry."
12971 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12972 beg)
12973 (save-excursion
12974 (org-back-to-heading t)
12975 (setq beg (point))
12976 (outline-next-heading)
12977 (while (re-search-backward re beg t)
12978 (replace-match "")
12979 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12980 (equal (char-before) ?\ ))
12981 (backward-delete-char 1)
12982 (if (string-match "^[ \t]*$" (buffer-substring
12983 (point-at-bol) (point-at-eol)))
12984 (delete-region (point-at-bol)
12985 (min (point-max) (1+ (point-at-eol))))))))))
12987 (defun org-add-planning-info (what &optional time &rest remove)
12988 "Insert new timestamp with keyword in the line directly after the headline.
12989 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12990 If non is given, the user is prompted for a date.
12991 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12992 be removed."
12993 (interactive)
12994 (let (org-time-was-given org-end-time-was-given ts
12995 end default-time default-input)
12997 (catch 'exit
12998 (when (and (memq what '(scheduled deadline))
12999 (or (not time)
13000 (and (stringp time)
13001 (string-match "^[-+]+[0-9]" time))))
13002 ;; Try to get a default date/time from existing timestamp
13003 (save-excursion
13004 (org-back-to-heading t)
13005 (setq end (save-excursion (outline-next-heading) (point)))
13006 (when (re-search-forward (if (eq what 'scheduled)
13007 org-scheduled-time-regexp
13008 org-deadline-time-regexp)
13009 end t)
13010 (setq ts (match-string 1)
13011 default-time
13012 (apply 'encode-time (org-parse-time-string ts))
13013 default-input (and ts (org-get-compact-tod ts))))))
13014 (when what
13015 (setq time
13016 (if (stringp time)
13017 ;; This is a string (relative or absolute), set proper date
13018 (apply 'encode-time
13019 (org-read-date-analyze
13020 time default-time (decode-time default-time)))
13021 ;; If necessary, get the time from the user
13022 (or time (org-read-date nil 'to-time nil nil
13023 default-time default-input)))))
13025 (when (and org-insert-labeled-timestamps-at-point
13026 (member what '(scheduled deadline)))
13027 (insert
13028 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13029 (org-insert-time-stamp time org-time-was-given
13030 nil nil nil (list org-end-time-was-given))
13031 (setq what nil))
13032 (save-excursion
13033 (save-restriction
13034 (let (col list elt ts buffer-invisibility-spec)
13035 (org-back-to-heading t)
13036 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13037 (goto-char (match-end 1))
13038 (setq col (current-column))
13039 (goto-char (match-end 0))
13040 (if (eobp) (insert "\n") (forward-char 1))
13041 (when (and (not what)
13042 (not (looking-at
13043 (concat "[ \t]*"
13044 org-keyword-time-not-clock-regexp))))
13045 ;; Nothing to add, nothing to remove...... :-)
13046 (throw 'exit nil))
13047 (if (and (not (looking-at org-outline-regexp))
13048 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13049 "[^\r\n]*"))
13050 (not (equal (match-string 1) org-clock-string)))
13051 (narrow-to-region (match-beginning 0) (match-end 0))
13052 (insert-before-markers "\n")
13053 (backward-char 1)
13054 (narrow-to-region (point) (point))
13055 (and org-adapt-indentation (org-indent-to-column col)))
13056 ;; Check if we have to remove something.
13057 (setq list (cons what remove))
13058 (while list
13059 (setq elt (pop list))
13060 (when (or (and (eq elt 'scheduled)
13061 (re-search-forward org-scheduled-time-regexp nil t))
13062 (and (eq elt 'deadline)
13063 (re-search-forward org-deadline-time-regexp nil t))
13064 (and (eq elt 'closed)
13065 (re-search-forward org-closed-time-regexp nil t)))
13066 (replace-match "")
13067 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13068 (and (looking-at "[ \t]+") (replace-match ""))
13069 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13070 (when what
13071 (insert
13072 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13073 (cond ((eq what 'scheduled) org-scheduled-string)
13074 ((eq what 'deadline) org-deadline-string)
13075 ((eq what 'closed) org-closed-string))
13076 " ")
13077 (setq ts (org-insert-time-stamp
13078 time
13079 (or org-time-was-given
13080 (and (eq what 'closed) org-log-done-with-time))
13081 (eq what 'closed)
13082 nil nil (list org-end-time-was-given)))
13083 (insert
13084 (if (not (or (bolp) (eq (char-before) ?\ )
13085 (memq (char-after) '(32 10))
13086 (eobp))) " " ""))
13087 (end-of-line 1))
13088 (goto-char (point-min))
13089 (widen)
13090 (if (and (looking-at "[ \t]*\n")
13091 (equal (char-before) ?\n))
13092 (delete-region (1- (point)) (point-at-eol)))
13093 ts))))))
13095 (defvar org-log-note-marker (make-marker))
13096 (defvar org-log-note-purpose nil)
13097 (defvar org-log-note-state nil)
13098 (defvar org-log-note-previous-state nil)
13099 (defvar org-log-note-how nil)
13100 (defvar org-log-note-extra nil)
13101 (defvar org-log-note-window-configuration nil)
13102 (defvar org-log-note-return-to (make-marker))
13103 (defvar org-log-note-effective-time nil
13104 "Remembered current time so that dynamically scoped
13105 `org-extend-today-until' affects tha timestamps in state change
13106 log")
13108 (defvar org-log-post-message nil
13109 "Message to be displayed after a log note has been stored.
13110 The auto-repeater uses this.")
13112 (defun org-add-note ()
13113 "Add a note to the current entry.
13114 This is done in the same way as adding a state change note."
13115 (interactive)
13116 (org-add-log-setup 'note nil nil 'findpos nil))
13118 (defvar org-property-end-re)
13119 (defun org-add-log-setup (&optional purpose state prev-state
13120 findpos how extra)
13121 "Set up the post command hook to take a note.
13122 If this is about to TODO state change, the new state is expected in STATE.
13123 When FINDPOS is non-nil, find the correct position for the note in
13124 the current entry. If not, assume that it can be inserted at point.
13125 HOW is an indicator what kind of note should be created.
13126 EXTRA is additional text that will be inserted into the notes buffer."
13127 (let* ((org-log-into-drawer (org-log-into-drawer))
13128 (drawer (cond ((stringp org-log-into-drawer)
13129 org-log-into-drawer)
13130 (org-log-into-drawer "LOGBOOK"))))
13131 (save-restriction
13132 (save-excursion
13133 (when findpos
13134 (org-back-to-heading t)
13135 (narrow-to-region (point) (save-excursion
13136 (outline-next-heading) (point)))
13137 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13138 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13139 "[^\r\n]*\\)?"))
13140 (goto-char (match-end 0))
13141 (cond
13142 (drawer
13143 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13144 nil t)
13145 (progn
13146 (goto-char (match-end 0))
13147 (or org-log-states-order-reversed
13148 (and (re-search-forward org-property-end-re nil t)
13149 (goto-char (1- (match-beginning 0))))))
13150 (insert "\n:" drawer ":\n:END:")
13151 (beginning-of-line 0)
13152 (org-indent-line)
13153 (beginning-of-line 2)
13154 (org-indent-line)
13155 (end-of-line 0)))
13156 ((and org-log-state-notes-insert-after-drawers
13157 (save-excursion
13158 (forward-line) (looking-at org-drawer-regexp)))
13159 (forward-line)
13160 (while (looking-at org-drawer-regexp)
13161 (goto-char (match-end 0))
13162 (re-search-forward org-property-end-re (point-max) t)
13163 (forward-line))
13164 (forward-line -1)))
13165 (unless org-log-states-order-reversed
13166 (and (= (char-after) ?\n) (forward-char 1))
13167 (org-skip-over-state-notes)
13168 (skip-chars-backward " \t\n\r")))
13169 (move-marker org-log-note-marker (point))
13170 (setq org-log-note-purpose purpose
13171 org-log-note-state state
13172 org-log-note-previous-state prev-state
13173 org-log-note-how how
13174 org-log-note-extra extra
13175 org-log-note-effective-time (org-current-effective-time))
13176 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13178 (defun org-skip-over-state-notes ()
13179 "Skip past the list of State notes in an entry."
13180 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13181 (when (ignore-errors (goto-char (org-in-item-p)))
13182 (let* ((struct (org-list-struct))
13183 (prevs (org-list-prevs-alist struct)))
13184 (while (looking-at "[ \t]*- State")
13185 (goto-char (or (org-list-get-next-item (point) struct prevs)
13186 (org-list-get-item-end (point) struct)))))))
13188 (defun org-add-log-note (&optional purpose)
13189 "Pop up a window for taking a note, and add this note later at point."
13190 (remove-hook 'post-command-hook 'org-add-log-note)
13191 (setq org-log-note-window-configuration (current-window-configuration))
13192 (delete-other-windows)
13193 (move-marker org-log-note-return-to (point))
13194 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13195 (goto-char org-log-note-marker)
13196 (org-switch-to-buffer-other-window "*Org Note*")
13197 (erase-buffer)
13198 (if (memq org-log-note-how '(time state))
13199 (let (current-prefix-arg) (org-store-log-note))
13200 (let ((org-inhibit-startup t)) (org-mode))
13201 (insert (format "# Insert note for %s.
13202 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13203 (cond
13204 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13205 ((eq org-log-note-purpose 'done) "closed todo item")
13206 ((eq org-log-note-purpose 'state)
13207 (format "state change from \"%s\" to \"%s\""
13208 (or org-log-note-previous-state "")
13209 (or org-log-note-state "")))
13210 ((eq org-log-note-purpose 'reschedule)
13211 "rescheduling")
13212 ((eq org-log-note-purpose 'delschedule)
13213 "no longer scheduled")
13214 ((eq org-log-note-purpose 'redeadline)
13215 "changing deadline")
13216 ((eq org-log-note-purpose 'deldeadline)
13217 "removing deadline")
13218 ((eq org-log-note-purpose 'refile)
13219 "refiling")
13220 ((eq org-log-note-purpose 'note)
13221 "this entry")
13222 (t (error "This should not happen")))))
13223 (if org-log-note-extra (insert org-log-note-extra))
13224 (org-set-local 'org-finish-function 'org-store-log-note)
13225 (run-hooks 'org-log-buffer-setup-hook)))
13227 (defvar org-note-abort nil) ; dynamically scoped
13228 (defun org-store-log-note ()
13229 "Finish taking a log note, and insert it to where it belongs."
13230 (let ((txt (buffer-string)))
13231 (kill-buffer (current-buffer))
13232 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13233 lines ind bul)
13234 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13235 (setq txt (replace-match "" t t txt)))
13236 (if (string-match "\\s-+\\'" txt)
13237 (setq txt (replace-match "" t t txt)))
13238 (setq lines (org-split-string txt "\n"))
13239 (when (and note (string-match "\\S-" note))
13240 (setq note
13241 (org-replace-escapes
13242 note
13243 (list (cons "%u" (user-login-name))
13244 (cons "%U" user-full-name)
13245 (cons "%t" (format-time-string
13246 (org-time-stamp-format 'long 'inactive)
13247 org-log-note-effective-time))
13248 (cons "%T" (format-time-string
13249 (org-time-stamp-format 'long nil)
13250 org-log-note-effective-time))
13251 (cons "%d" (format-time-string
13252 (org-time-stamp-format nil 'inactive)
13253 org-log-note-effective-time))
13254 (cons "%D" (format-time-string
13255 (org-time-stamp-format nil nil)
13256 org-log-note-effective-time))
13257 (cons "%s" (if org-log-note-state
13258 (concat "\"" org-log-note-state "\"")
13259 ""))
13260 (cons "%S" (if org-log-note-previous-state
13261 (concat "\"" org-log-note-previous-state "\"")
13262 "\"\"")))))
13263 (if lines (setq note (concat note " \\\\")))
13264 (push note lines))
13265 (when (or current-prefix-arg org-note-abort)
13266 (when org-log-into-drawer
13267 (org-remove-empty-drawer-at
13268 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13269 org-log-note-marker))
13270 (setq lines nil))
13271 (when lines
13272 (with-current-buffer (marker-buffer org-log-note-marker)
13273 (save-excursion
13274 (goto-char org-log-note-marker)
13275 (move-marker org-log-note-marker nil)
13276 (end-of-line 1)
13277 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13278 (setq ind (save-excursion
13279 (if (ignore-errors (goto-char (org-in-item-p)))
13280 (let ((struct (org-list-struct)))
13281 (org-list-get-ind
13282 (org-list-get-top-point struct) struct))
13283 (skip-chars-backward " \r\t\n")
13284 (cond
13285 ((and (org-at-heading-p)
13286 org-adapt-indentation)
13287 (1+ (org-current-level)))
13288 ((org-at-heading-p) 0)
13289 (t (org-get-indentation))))))
13290 (setq bul (org-list-bullet-string "-"))
13291 (org-indent-line-to ind)
13292 (insert bul (pop lines))
13293 (let ((ind-body (+ (length bul) ind)))
13294 (while lines
13295 (insert "\n")
13296 (org-indent-line-to ind-body)
13297 (insert (pop lines))))
13298 (message "Note stored")
13299 (org-back-to-heading t)
13300 (org-cycle-hide-drawers 'children))))))
13301 (set-window-configuration org-log-note-window-configuration)
13302 (with-current-buffer (marker-buffer org-log-note-return-to)
13303 (goto-char org-log-note-return-to))
13304 (move-marker org-log-note-return-to nil)
13305 (and org-log-post-message (message "%s" org-log-post-message)))
13307 (defun org-remove-empty-drawer-at (drawer pos)
13308 "Remove an empty drawer DRAWER at position POS.
13309 POS may also be a marker."
13310 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13311 (save-excursion
13312 (save-restriction
13313 (widen)
13314 (goto-char pos)
13315 (if (org-in-regexp
13316 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13317 (replace-match ""))))))
13319 (defvar org-ts-type nil)
13320 (defun org-sparse-tree (&optional arg type)
13321 "Create a sparse tree, prompt for the details.
13322 This command can create sparse trees. You first need to select the type
13323 of match used to create the tree:
13325 t Show all TODO entries.
13326 T Show entries with a specific TODO keyword.
13327 m Show entries selected by a tags/property match.
13328 p Enter a property name and its value (both with completion on existing
13329 names/values) and show entries with that property.
13330 r Show entries matching a regular expression (`/' can be used as well).
13331 b Show deadlines and scheduled items before a date.
13332 a Show deadlines and scheduled items after a date.
13333 d Show deadlines due within `org-deadline-warning-days'.
13334 D Show deadlines and scheduled items between a date range."
13335 (interactive "P")
13336 (let (ans kwd value ts-type)
13337 (setq type (or type org-sparse-tree-default-date-type))
13338 (setq org-ts-type type)
13339 (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"
13340 (cond ((eq type 'all) "all timestamps")
13341 ((eq type 'scheduled) "only scheduled")
13342 ((eq type 'deadline) "only deadline")
13343 ((eq type 'active) "only active timestamps")
13344 ((eq type 'inactive) "only inactive timestamps")
13345 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13346 (t "scheduled/deadline")))
13347 (setq ans (read-char-exclusive))
13348 (cond
13349 ((equal ans ?c)
13350 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
13351 ((equal ans ?d)
13352 (call-interactively 'org-check-deadlines))
13353 ((equal ans ?b)
13354 (call-interactively 'org-check-before-date))
13355 ((equal ans ?a)
13356 (call-interactively 'org-check-after-date))
13357 ((equal ans ?D)
13358 (call-interactively 'org-check-dates-range))
13359 ((equal ans ?t)
13360 (call-interactively 'org-show-todo-tree))
13361 ((equal ans ?T)
13362 (org-show-todo-tree '(4)))
13363 ((member ans '(?T ?m))
13364 (call-interactively 'org-match-sparse-tree))
13365 ((member ans '(?p ?P))
13366 (setq kwd (org-icompleting-read "Property: "
13367 (mapcar 'list (org-buffer-property-keys))))
13368 (setq value (org-icompleting-read "Value: "
13369 (mapcar 'list (org-property-values kwd))))
13370 (unless (string-match "\\`{.*}\\'" value)
13371 (setq value (concat "\"" value "\"")))
13372 (org-match-sparse-tree arg (concat kwd "=" value)))
13373 ((member ans '(?r ?R ?/))
13374 (call-interactively 'org-occur))
13375 (t (error "No such sparse tree command \"%c\"" ans)))))
13377 (defvar org-occur-highlights nil
13378 "List of overlays used for occur matches.")
13379 (make-variable-buffer-local 'org-occur-highlights)
13380 (defvar org-occur-parameters nil
13381 "Parameters of the active org-occur calls.
13382 This is a list, each call to org-occur pushes as cons cell,
13383 containing the regular expression and the callback, onto the list.
13384 The list can contain several entries if `org-occur' has been called
13385 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13386 will only contain one set of parameters. When the highlights are
13387 removed (for example with `C-c C-c', or with the next edit (depending
13388 on `org-remove-highlights-with-change'), this variable is emptied
13389 as well.")
13390 (make-variable-buffer-local 'org-occur-parameters)
13392 (defun org-occur (regexp &optional keep-previous callback)
13393 "Make a compact tree which shows all matches of REGEXP.
13394 The tree will show the lines where the regexp matches, and all higher
13395 headlines above the match. It will also show the heading after the match,
13396 to make sure editing the matching entry is easy.
13397 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13398 call to `org-occur' will be kept, to allow stacking of calls to this
13399 command.
13400 If CALLBACK is non-nil, it is a function which is called to confirm
13401 that the match should indeed be shown."
13402 (interactive "sRegexp: \nP")
13403 (when (equal regexp "")
13404 (error "Regexp cannot be empty"))
13405 (unless keep-previous
13406 (org-remove-occur-highlights nil nil t))
13407 (push (cons regexp callback) org-occur-parameters)
13408 (let ((cnt 0))
13409 (save-excursion
13410 (goto-char (point-min))
13411 (if (or (not keep-previous) ; do not want to keep
13412 (not org-occur-highlights)) ; no previous matches
13413 ;; hide everything
13414 (org-overview))
13415 (while (re-search-forward regexp nil t)
13416 (when (or (not callback)
13417 (save-match-data (funcall callback)))
13418 (setq cnt (1+ cnt))
13419 (when org-highlight-sparse-tree-matches
13420 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13421 (org-show-context 'occur-tree))))
13422 (when org-remove-highlights-with-change
13423 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13424 nil 'local))
13425 (unless org-sparse-tree-open-archived-trees
13426 (org-hide-archived-subtrees (point-min) (point-max)))
13427 (run-hooks 'org-occur-hook)
13428 (if (org-called-interactively-p 'interactive)
13429 (message "%d match(es) for regexp %s" cnt regexp))
13430 cnt))
13432 (defun org-occur-next-match (&optional n reset)
13433 "Function for `next-error-function' to find sparse tree matches.
13434 N is the number of matches to move, when negative move backwards.
13435 RESET is entirely ignored - this function always goes back to the
13436 starting point when no match is found."
13437 (let* ((limit (if (< n 0) (point-min) (point-max)))
13438 (search-func (if (< n 0)
13439 'previous-single-char-property-change
13440 'next-single-char-property-change))
13441 (n (abs n))
13442 (pos (point))
13444 (catch 'exit
13445 (while (setq p1 (funcall search-func (point) 'org-type))
13446 (when (equal p1 limit)
13447 (goto-char pos)
13448 (error "No more matches"))
13449 (when (equal (get-char-property p1 'org-type) 'org-occur)
13450 (setq n (1- n))
13451 (when (= n 0)
13452 (goto-char p1)
13453 (throw 'exit (point))))
13454 (goto-char p1))
13455 (goto-char p1)
13456 (error "No more matches"))))
13458 (defun org-show-context (&optional key)
13459 "Make sure point and context are visible.
13460 How much context is shown depends upon the variables
13461 `org-show-hierarchy-above', `org-show-following-heading',
13462 `org-show-entry-below' and `org-show-siblings'."
13463 (let ((heading-p (org-at-heading-p t))
13464 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13465 (following-p (org-get-alist-option org-show-following-heading key))
13466 (entry-p (org-get-alist-option org-show-entry-below key))
13467 (siblings-p (org-get-alist-option org-show-siblings key)))
13468 ;; Show heading or entry text
13469 (if (and heading-p (not entry-p))
13470 (org-flag-heading nil) ; only show the heading
13471 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13472 (org-show-hidden-entry))) ; show entire entry
13473 (when following-p
13474 ;; Show next sibling, or heading below text
13475 (save-excursion
13476 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13477 (org-flag-heading nil))))
13478 (when siblings-p (org-show-siblings))
13479 (when hierarchy-p
13480 ;; show all higher headings, possibly with siblings
13481 (save-excursion
13482 (while (and (condition-case nil
13483 (progn (org-up-heading-all 1) t)
13484 (error nil))
13485 (not (bobp)))
13486 (org-flag-heading nil)
13487 (when siblings-p (org-show-siblings)))))
13488 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13490 (defvar org-reveal-start-hook nil
13491 "Hook run before revealing a location.")
13493 (defun org-reveal (&optional siblings)
13494 "Show current entry, hierarchy above it, and the following headline.
13495 This can be used to show a consistent set of context around locations
13496 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13497 not t for the search context.
13499 With optional argument SIBLINGS, on each level of the hierarchy all
13500 siblings are shown. This repairs the tree structure to what it would
13501 look like when opened with hierarchical calls to `org-cycle'.
13502 With double optional argument \\[universal-argument] \\[universal-argument], \
13503 go to the parent and show the
13504 entire tree."
13505 (interactive "P")
13506 (run-hooks 'org-reveal-start-hook)
13507 (let ((org-show-hierarchy-above t)
13508 (org-show-following-heading t)
13509 (org-show-siblings (if siblings t org-show-siblings)))
13510 (org-show-context nil))
13511 (when (equal siblings '(16))
13512 (save-excursion
13513 (when (org-up-heading-safe)
13514 (org-show-subtree)
13515 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13517 (defun org-highlight-new-match (beg end)
13518 "Highlight from BEG to END and mark the highlight is an occur headline."
13519 (let ((ov (make-overlay beg end)))
13520 (overlay-put ov 'face 'secondary-selection)
13521 (overlay-put ov 'org-type 'org-occur)
13522 (push ov org-occur-highlights)))
13524 (defun org-remove-occur-highlights (&optional beg end noremove)
13525 "Remove the occur highlights from the buffer.
13526 BEG and END are ignored. If NOREMOVE is nil, remove this function
13527 from the `before-change-functions' in the current buffer."
13528 (interactive)
13529 (unless org-inhibit-highlight-removal
13530 (mapc 'delete-overlay org-occur-highlights)
13531 (setq org-occur-highlights nil)
13532 (setq org-occur-parameters nil)
13533 (unless noremove
13534 (remove-hook 'before-change-functions
13535 'org-remove-occur-highlights 'local))))
13537 ;;;; Priorities
13539 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13540 "Regular expression matching the priority indicator.")
13542 (defvar org-remove-priority-next-time nil)
13544 (defun org-priority-up ()
13545 "Increase the priority of the current item."
13546 (interactive)
13547 (org-priority 'up))
13549 (defun org-priority-down ()
13550 "Decrease the priority of the current item."
13551 (interactive)
13552 (org-priority 'down))
13554 (defun org-priority (&optional action show)
13555 "Change the priority of an item.
13556 ACTION can be `set', `up', `down', or a character."
13557 (interactive "P")
13558 (if (equal action '(4))
13559 (org-show-priority)
13560 (unless org-enable-priority-commands
13561 (error "Priority commands are disabled"))
13562 (setq action (or action 'set))
13563 (let (current new news have remove)
13564 (save-excursion
13565 (org-back-to-heading t)
13566 (if (looking-at org-priority-regexp)
13567 (setq current (string-to-char (match-string 2))
13568 have t))
13569 (cond
13570 ((eq action 'remove)
13571 (setq remove t new ?\ ))
13572 ((or (eq action 'set)
13573 (if (featurep 'xemacs) (characterp action) (integerp action)))
13574 (if (not (eq action 'set))
13575 (setq new action)
13576 (message "Priority %c-%c, SPC to remove: "
13577 org-highest-priority org-lowest-priority)
13578 (save-match-data
13579 (setq new (read-char-exclusive))))
13580 (if (and (= (upcase org-highest-priority) org-highest-priority)
13581 (= (upcase org-lowest-priority) org-lowest-priority))
13582 (setq new (upcase new)))
13583 (cond ((equal new ?\ ) (setq remove t))
13584 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13585 (error "Priority must be between `%c' and `%c'"
13586 org-highest-priority org-lowest-priority))))
13587 ((eq action 'up)
13588 (setq new (if have
13589 (1- current) ; normal cycling
13590 ;; last priority was empty
13591 (if (eq last-command this-command)
13592 org-lowest-priority ; wrap around empty to lowest
13593 ;; default
13594 (if org-priority-start-cycle-with-default
13595 org-default-priority
13596 (1- org-default-priority))))))
13597 ((eq action 'down)
13598 (setq new (if have
13599 (1+ current) ; normal cycling
13600 ;; last priority was empty
13601 (if (eq last-command this-command)
13602 org-highest-priority ; wrap around empty to highest
13603 ;; default
13604 (if org-priority-start-cycle-with-default
13605 org-default-priority
13606 (1+ org-default-priority))))))
13607 (t (error "Invalid action")))
13608 (if (or (< (upcase new) org-highest-priority)
13609 (> (upcase new) org-lowest-priority))
13610 (if (and (memq action '(up down))
13611 (not have) (not (eq last-command this-command)))
13612 ;; `new' is from default priority
13613 (error
13614 "The default can not be set, see `org-default-priority' why")
13615 ;; normal cycling: `new' is beyond highest/lowest priority
13616 ;; and is wrapped around to the empty priority
13617 (setq remove t)))
13618 (setq news (format "%c" new))
13619 (if have
13620 (if remove
13621 (replace-match "" t t nil 1)
13622 (replace-match news t t nil 2))
13623 (if remove
13624 (error "No priority cookie found in line")
13625 (let ((case-fold-search nil))
13626 (looking-at org-todo-line-regexp))
13627 (if (match-end 2)
13628 (progn
13629 (goto-char (match-end 2))
13630 (insert " [#" news "]"))
13631 (goto-char (match-beginning 3))
13632 (insert "[#" news "] "))))
13633 (org-preserve-lc (org-set-tags nil 'align)))
13634 (if remove
13635 (message "Priority removed")
13636 (message "Priority of current item set to %s" news)))))
13638 (defun org-show-priority ()
13639 "Show the priority of the current item.
13640 This priority is composed of the main priority given with the [#A] cookies,
13641 and by additional input from the age of a schedules or deadline entry."
13642 (interactive)
13643 (let ((pri (if (eq major-mode 'org-agenda-mode)
13644 (org-get-at-bol 'priority)
13645 (save-excursion
13646 (save-match-data
13647 (beginning-of-line)
13648 (and (looking-at org-heading-regexp)
13649 (org-get-priority (match-string 0))))))))
13650 (message "Priority is %d" (if pri pri -1000))))
13652 (defun org-get-priority (s)
13653 "Find priority cookie and return priority."
13654 (save-match-data
13655 (if (functionp org-get-priority-function)
13656 (funcall org-get-priority-function)
13657 (if (not (string-match org-priority-regexp s))
13658 (* 1000 (- org-lowest-priority org-default-priority))
13659 (* 1000 (- org-lowest-priority
13660 (string-to-char (match-string 2 s))))))))
13662 ;;;; Tags
13664 (defvar org-agenda-archives-mode)
13665 (defvar org-map-continue-from nil
13666 "Position from where mapping should continue.
13667 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13669 (defvar org-scanner-tags nil
13670 "The current tag list while the tags scanner is running.")
13671 (defvar org-trust-scanner-tags nil
13672 "Should `org-get-tags-at' use the tags for the scanner.
13673 This is for internal dynamical scoping only.
13674 When this is non-nil, the function `org-get-tags-at' will return the value
13675 of `org-scanner-tags' instead of building the list by itself. This
13676 can lead to large speed-ups when the tags scanner is used in a file with
13677 many entries, and when the list of tags is retrieved, for example to
13678 obtain a list of properties. Building the tags list for each entry in such
13679 a file becomes an N^2 operation - but with this variable set, it scales
13680 as N.")
13682 (defun org-scan-tags (action matcher todo-only &optional start-level)
13683 "Sca headline tags with inheritance and produce output ACTION.
13685 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13686 or `agenda' to produce an entry list for an agenda view. It can also be
13687 a Lisp form or a function that should be called at each matched headline, in
13688 this case the return value is a list of all return values from these calls.
13690 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13691 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13692 only lines with a not-done TODO keyword are included in the output.
13693 This should be the same variable that was scoped into
13694 and set by `org-make-tags-matcher' when it constructed MATCHER.
13696 START-LEVEL can be a string with asterisks, reducing the scope to
13697 headlines matching this string."
13698 (require 'org-agenda)
13699 (let* ((re (concat "^"
13700 (if start-level
13701 ;; Get the correct level to match
13702 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13703 org-outline-regexp)
13704 " *\\(\\<\\("
13705 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13706 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13707 (props (list 'face 'default
13708 'done-face 'org-agenda-done
13709 'undone-face 'default
13710 'mouse-face 'highlight
13711 'org-not-done-regexp org-not-done-regexp
13712 'org-todo-regexp org-todo-regexp
13713 'org-complex-heading-regexp org-complex-heading-regexp
13714 'help-echo
13715 (format "mouse-2 or RET jump to org file %s"
13716 (abbreviate-file-name
13717 (or (buffer-file-name (buffer-base-buffer))
13718 (buffer-name (buffer-base-buffer)))))))
13719 (case-fold-search nil)
13720 (org-map-continue-from nil)
13721 lspos tags tags-list
13722 (tags-alist (list (cons 0 org-file-tags)))
13723 (llast 0) rtn rtn1 level category i txt
13724 todo marker entry priority)
13725 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13726 (setq action (list 'lambda nil action)))
13727 (save-excursion
13728 (goto-char (point-min))
13729 (when (eq action 'sparse-tree)
13730 (org-overview)
13731 (org-remove-occur-highlights))
13732 (while (re-search-forward re nil t)
13733 (setq org-map-continue-from nil)
13734 (catch :skip
13735 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13736 tags (if (match-end 4) (org-match-string-no-properties 4)))
13737 (goto-char (setq lspos (match-beginning 0)))
13738 (setq level (org-reduced-level (org-outline-level))
13739 category (org-get-category))
13740 (setq i llast llast level)
13741 ;; remove tag lists from same and sublevels
13742 (while (>= i level)
13743 (when (setq entry (assoc i tags-alist))
13744 (setq tags-alist (delete entry tags-alist)))
13745 (setq i (1- i)))
13746 ;; add the next tags
13747 (when tags
13748 (setq tags (org-split-string tags ":")
13749 tags-alist
13750 (cons (cons level tags) tags-alist)))
13751 ;; compile tags for current headline
13752 (setq tags-list
13753 (if org-use-tag-inheritance
13754 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13755 tags)
13756 org-scanner-tags tags-list)
13757 (when org-use-tag-inheritance
13758 (setcdr (car tags-alist)
13759 (mapcar (lambda (x)
13760 (setq x (copy-sequence x))
13761 (org-add-prop-inherited x))
13762 (cdar tags-alist))))
13763 (when (and tags org-use-tag-inheritance
13764 (or (not (eq t org-use-tag-inheritance))
13765 org-tags-exclude-from-inheritance))
13766 ;; selective inheritance, remove uninherited ones
13767 (setcdr (car tags-alist)
13768 (org-remove-uninherited-tags (cdar tags-alist))))
13769 (when (and
13771 ;; eval matcher only when the todo condition is OK
13772 (and (or (not todo-only) (member todo org-not-done-keywords))
13773 (let ((case-fold-search t) (org-trust-scanner-tags t))
13774 (eval matcher)))
13776 ;; Call the skipper, but return t if it does not skip,
13777 ;; so that the `and' form continues evaluating
13778 (progn
13779 (unless (eq action 'sparse-tree) (org-agenda-skip))
13782 ;; Check if timestamps are deselecting this entry
13783 (or (not todo-only)
13784 (and (member todo org-not-done-keywords)
13785 (or (not org-agenda-tags-todo-honor-ignore-options)
13786 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13788 ;; select this headline
13789 (cond
13790 ((eq action 'sparse-tree)
13791 (and org-highlight-sparse-tree-matches
13792 (org-get-heading) (match-end 0)
13793 (org-highlight-new-match
13794 (match-beginning 1) (match-end 1)))
13795 (org-show-context 'tags-tree))
13796 ((eq action 'agenda)
13797 (setq txt (org-agenda-format-item
13799 (concat
13800 (if (eq org-tags-match-list-sublevels 'indented)
13801 (make-string (1- level) ?.) "")
13802 (org-get-heading))
13803 level category
13804 tags-list)
13805 priority (org-get-priority txt))
13806 (goto-char lspos)
13807 (setq marker (org-agenda-new-marker))
13808 (org-add-props txt props
13809 'org-marker marker 'org-hd-marker marker 'org-category category
13810 'todo-state todo
13811 'priority priority 'type "tagsmatch")
13812 (push txt rtn))
13813 ((functionp action)
13814 (setq org-map-continue-from nil)
13815 (save-excursion
13816 (setq rtn1 (funcall action))
13817 (push rtn1 rtn)))
13818 (t (error "Invalid action")))
13820 ;; if we are to skip sublevels, jump to end of subtree
13821 (unless org-tags-match-list-sublevels
13822 (org-end-of-subtree t)
13823 (backward-char 1))))
13824 ;; Get the correct position from where to continue
13825 (if org-map-continue-from
13826 (goto-char org-map-continue-from)
13827 (and (= (point) lspos) (end-of-line 1)))))
13828 (when (and (eq action 'sparse-tree)
13829 (not org-sparse-tree-open-archived-trees))
13830 (org-hide-archived-subtrees (point-min) (point-max)))
13831 (nreverse rtn)))
13833 (defun org-remove-uninherited-tags (tags)
13834 "Remove all tags that are not inherited from the list TAGS."
13835 (cond
13836 ((eq org-use-tag-inheritance t)
13837 (if org-tags-exclude-from-inheritance
13838 (org-delete-all org-tags-exclude-from-inheritance tags)
13839 tags))
13840 ((not org-use-tag-inheritance) nil)
13841 ((stringp org-use-tag-inheritance)
13842 (delq nil (mapcar
13843 (lambda (x)
13844 (if (and (string-match org-use-tag-inheritance x)
13845 (not (member x org-tags-exclude-from-inheritance)))
13846 x nil))
13847 tags)))
13848 ((listp org-use-tag-inheritance)
13849 (delq nil (mapcar
13850 (lambda (x)
13851 (if (member x org-use-tag-inheritance) x nil))
13852 tags)))))
13854 (defun org-match-sparse-tree (&optional todo-only match)
13855 "Create a sparse tree according to tags string MATCH.
13856 MATCH can contain positive and negative selection of tags, like
13857 \"+WORK+URGENT-WITHBOSS\".
13858 If optional argument TODO-ONLY is non-nil, only select lines that are
13859 also TODO lines."
13860 (interactive "P")
13861 (org-agenda-prepare-buffers (list (current-buffer)))
13862 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13864 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13866 (defvar org-cached-props nil)
13867 (defun org-cached-entry-get (pom property)
13868 (if (or (eq t org-use-property-inheritance)
13869 (and (stringp org-use-property-inheritance)
13870 (string-match org-use-property-inheritance property))
13871 (and (listp org-use-property-inheritance)
13872 (member property org-use-property-inheritance)))
13873 ;; Caching is not possible, check it directly
13874 (org-entry-get pom property 'inherit)
13875 ;; Get all properties, so that we can do complicated checks easily
13876 (cdr (assoc property (or org-cached-props
13877 (setq org-cached-props
13878 (org-entry-properties pom)))))))
13880 (defun org-global-tags-completion-table (&optional files)
13881 "Return the list of all tags in all agenda buffer/files.
13882 Optional FILES argument is a list of files which can be used
13883 instead of the agenda files."
13884 (save-excursion
13885 (org-uniquify
13886 (delq nil
13887 (apply 'append
13888 (mapcar
13889 (lambda (file)
13890 (set-buffer (find-file-noselect file))
13891 (append (org-get-buffer-tags)
13892 (mapcar (lambda (x) (if (stringp (car-safe x))
13893 (list (car-safe x)) nil))
13894 org-tag-alist)))
13895 (if (and files (car files))
13896 files
13897 (org-agenda-files))))))))
13899 (defun org-make-tags-matcher (match)
13900 "Create the TAGS/TODO matcher form for the selection string MATCH.
13902 The variable `todo-only' is scoped dynamically into this function.
13903 It will be set to t if the matcher restricts matching to TODO entries,
13904 otherwise will not be touched.
13906 Returns a cons of the selection string MATCH and the constructed
13907 lisp form implementing the matcher. The matcher is to be evaluated
13908 at an Org entry, with point on the headline, and returns t if the
13909 entry matches the selection string MATCH. The returned lisp form
13910 references two variables with information about the entry, which
13911 must be bound around the form's evaluation: todo, the TODO keyword
13912 at the entry (or nil of none); and tags-list, the list of all tags
13913 at the entry including inherited ones. Additionally, the category
13914 of the entry (if any) must be specified as the text property
13915 'org-category on the headline.
13917 See also `org-scan-tags'.
13919 (declare (special todo-only))
13920 (unless (boundp 'todo-only)
13921 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
13922 (unless match
13923 ;; Get a new match request, with completion
13924 (let ((org-last-tags-completion-table
13925 (org-global-tags-completion-table)))
13926 (setq match (org-completing-read-no-i
13927 "Match: " 'org-tags-completion-function nil nil nil
13928 'org-tags-history))))
13930 ;; Parse the string and create a lisp form
13931 (let ((match0 match)
13932 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13933 minus tag mm
13934 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13935 orterms term orlist re-p str-p level-p level-op time-p
13936 prop-p pn pv po gv rest)
13937 ;; Expand group tags
13938 (setq match (org-tags-expand match))
13939 (if (string-match "/+" match)
13940 ;; match contains also a todo-matching request
13941 (progn
13942 (setq tagsmatch (substring match 0 (match-beginning 0))
13943 todomatch (substring match (match-end 0)))
13944 (if (string-match "^!" todomatch)
13945 (setq todo-only t todomatch (substring todomatch 1)))
13946 (if (string-match "^\\s-*$" todomatch)
13947 (setq todomatch nil)))
13948 ;; only matching tags
13949 (setq tagsmatch match todomatch nil))
13951 ;; Make the tags matcher
13952 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13953 (setq tagsmatcher t)
13954 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13955 (while (setq term (pop orterms))
13956 (while (and (equal (substring term -1) "\\") orterms)
13957 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13958 (while (string-match re term)
13959 (setq rest (substring term (match-end 0))
13960 minus (and (match-end 1)
13961 (equal (match-string 1 term) "-"))
13962 tag (save-match-data (replace-regexp-in-string
13963 "\\\\-" "-"
13964 (match-string 2 term)))
13965 re-p (equal (string-to-char tag) ?{)
13966 level-p (match-end 4)
13967 prop-p (match-end 5)
13968 mm (cond
13969 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13970 (level-p
13971 (setq level-op (org-op-to-function (match-string 3 term)))
13972 `(,level-op level ,(string-to-number
13973 (match-string 4 term))))
13974 (prop-p
13975 (setq pn (match-string 5 term)
13976 po (match-string 6 term)
13977 pv (match-string 7 term)
13978 re-p (equal (string-to-char pv) ?{)
13979 str-p (equal (string-to-char pv) ?\")
13980 time-p (save-match-data
13981 (string-match "^\"[[<].*[]>]\"$" pv))
13982 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13983 (if time-p (setq pv (org-matcher-time pv)))
13984 (setq po (org-op-to-function po (if time-p 'time str-p)))
13985 (cond
13986 ((equal pn "CATEGORY")
13987 (setq gv '(get-text-property (point) 'org-category)))
13988 ((equal pn "TODO")
13989 (setq gv 'todo))
13991 (setq gv `(org-cached-entry-get nil ,pn))))
13992 (if re-p
13993 (if (eq po 'org<>)
13994 `(not (string-match ,pv (or ,gv "")))
13995 `(string-match ,pv (or ,gv "")))
13996 (if str-p
13997 `(,po (or ,gv "") ,pv)
13998 `(,po (string-to-number (or ,gv ""))
13999 ,(string-to-number pv) ))))
14000 (t `(member ,tag tags-list)))
14001 mm (if minus (list 'not mm) mm)
14002 term rest)
14003 (push mm tagsmatcher))
14004 (push (if (> (length tagsmatcher) 1)
14005 (cons 'and tagsmatcher)
14006 (car tagsmatcher))
14007 orlist)
14008 (setq tagsmatcher nil))
14009 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14010 (setq tagsmatcher
14011 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14012 ;; Make the todo matcher
14013 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14014 (setq todomatcher t)
14015 (setq orterms (org-split-string todomatch "|") orlist nil)
14016 (while (setq term (pop orterms))
14017 (while (string-match re term)
14018 (setq minus (and (match-end 1)
14019 (equal (match-string 1 term) "-"))
14020 kwd (match-string 2 term)
14021 re-p (equal (string-to-char kwd) ?{)
14022 term (substring term (match-end 0))
14023 mm (if re-p
14024 `(string-match ,(substring kwd 1 -1) todo)
14025 (list 'equal 'todo kwd))
14026 mm (if minus (list 'not mm) mm))
14027 (push mm todomatcher))
14028 (push (if (> (length todomatcher) 1)
14029 (cons 'and todomatcher)
14030 (car todomatcher))
14031 orlist)
14032 (setq todomatcher nil))
14033 (setq todomatcher (if (> (length orlist) 1)
14034 (cons 'or orlist) (car orlist))))
14036 ;; Return the string and lisp forms of the matcher
14037 (setq matcher (if todomatcher
14038 (list 'and tagsmatcher todomatcher)
14039 tagsmatcher))
14040 (when todo-only
14041 (setq matcher (list 'and '(member todo org-not-done-keywords)
14042 matcher)))
14043 (cons match0 matcher)))
14045 (defun org-tags-expand (match &optional single-as-list downcased)
14046 "Expand group tags in MATCH.
14048 This replaces every group tag in MATCH with a regexp tag search.
14049 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14050 will be replaced like this:
14052 Work => {\(?:Work\|Lab\|Conf\}
14053 +Work => +{\(?:Work\|Lab\|Conf\}
14054 -Work => -{\(?:Work\|Lab\|Conf\}
14056 Replacing by a regexp preserves the structure of the match.
14057 E.g., this expansion
14059 Work|Home => {\(?:Work\|Lab\|Conf\}|Home
14061 will match anything tagged with \"Lab\" and \"Home\", or tagged
14062 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14064 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14065 assumed to be a single group tag, and the function will return
14066 the list of tags in this group.
14068 When DOWNCASE is non-nil, expand downcased TAGS."
14069 (if org-group-tags
14070 (let* ((case-fold-search t)
14071 (stable org-mode-syntax-table)
14072 (tal (or org-tag-groups-alist-for-agenda
14073 org-tag-groups-alist))
14074 (tal (if downcased (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14075 (tml (mapcar 'car tal))
14076 (rtnmatch match) rpl)
14077 ;; @ and _ are allowed as word-components in tags
14078 (modify-syntax-entry ?@ "w" stable)
14079 (modify-syntax-entry ?_ "w" stable)
14080 (while (and tml (string-match
14081 (concat "\\(?1:[+-]?\\)\\(?2:\\<" (regexp-opt tml) "\\>\\)")
14082 rtnmatch))
14083 (let* ((dir (match-string 1 rtnmatch))
14084 (tag (match-string 2 rtnmatch))
14085 (tag (if downcased (downcase tag) tag)))
14086 (setq tml (delete tag tml))
14087 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14088 (setq rtnmatch
14089 (replace-match
14090 (concat dir "{" (regexp-opt rpl) "}") t t rtnmatch))))
14091 (if single-as-list
14092 (or (reverse rpl) (list rtnmatch))
14093 rtnmatch))
14094 (if single-as-list (list (if downcased (downcase match) match))
14095 match)))
14097 (defun org-op-to-function (op &optional stringp)
14098 "Turn an operator into the appropriate function."
14099 (setq op
14100 (cond
14101 ((equal op "<" ) '(< string< org-time<))
14102 ((equal op ">" ) '(> org-string> org-time>))
14103 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14104 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14105 ((member op '("=" "==")) '(= string= org-time=))
14106 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14107 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14109 (defun org<> (a b) (not (= a b)))
14110 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14111 (defun org-string>= (a b) (not (string< a b)))
14112 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14113 (defun org-string<> (a b) (not (string= a b)))
14114 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14115 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14116 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14117 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14118 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14119 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14120 (defun org-2ft (s)
14121 "Convert S to a floating point time.
14122 If S is already a number, just return it. If it is a string, parse
14123 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14124 (cond
14125 ((numberp s) s)
14126 ((stringp s)
14127 (condition-case nil
14128 (float-time (apply 'encode-time (org-parse-time-string s)))
14129 (error 0.)))
14130 (t 0.)))
14132 (defun org-time-today ()
14133 "Time in seconds today at 0:00.
14134 Returns the float number of seconds since the beginning of the
14135 epoch to the beginning of today (00:00)."
14136 (float-time (apply 'encode-time
14137 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14139 (defun org-matcher-time (s)
14140 "Interpret a time comparison value."
14141 (save-match-data
14142 (cond
14143 ((string= s "<now>") (float-time))
14144 ((string= s "<today>") (org-time-today))
14145 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14146 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14147 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14148 (+ (org-time-today)
14149 (* (string-to-number (match-string 1 s))
14150 (cdr (assoc (match-string 2 s)
14151 '(("d" . 86400.0) ("w" . 604800.0)
14152 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14153 (t (org-2ft s)))))
14155 (defun org-match-any-p (re list)
14156 "Does re match any element of list?"
14157 (setq list (mapcar (lambda (x) (string-match re x)) list))
14158 (delq nil list))
14160 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14161 (defvar org-tags-overlay (make-overlay 1 1))
14162 (org-detach-overlay org-tags-overlay)
14164 (defun org-get-local-tags-at (&optional pos)
14165 "Get a list of tags defined in the current headline."
14166 (org-get-tags-at pos 'local))
14168 (defun org-get-local-tags ()
14169 "Get a list of tags defined in the current headline."
14170 (org-get-tags-at nil 'local))
14172 (defun org-get-tags-at (&optional pos local)
14173 "Get a list of all headline tags applicable at POS.
14174 POS defaults to point. If tags are inherited, the list contains
14175 the targets in the same sequence as the headlines appear, i.e.
14176 the tags of the current headline come last.
14177 When LOCAL is non-nil, only return tags from the current headline,
14178 ignore inherited ones."
14179 (interactive)
14180 (if (and org-trust-scanner-tags
14181 (or (not pos) (equal pos (point)))
14182 (not local))
14183 org-scanner-tags
14184 (let (tags ltags lastpos parent)
14185 (save-excursion
14186 (save-restriction
14187 (widen)
14188 (goto-char (or pos (point)))
14189 (save-match-data
14190 (catch 'done
14191 (condition-case nil
14192 (progn
14193 (org-back-to-heading t)
14194 (while (not (equal lastpos (point)))
14195 (setq lastpos (point))
14196 (when (looking-at
14197 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14198 (setq ltags (org-split-string
14199 (org-match-string-no-properties 1) ":"))
14200 (when parent
14201 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14202 (setq tags (append
14203 (if parent
14204 (org-remove-uninherited-tags ltags)
14205 ltags)
14206 tags)))
14207 (or org-use-tag-inheritance (throw 'done t))
14208 (if local (throw 'done t))
14209 (or (org-up-heading-safe) (error nil))
14210 (setq parent t)))
14211 (error nil)))))
14212 (if local
14213 tags
14214 (reverse (delete-dups
14215 (reverse (append
14216 (org-remove-uninherited-tags
14217 org-file-tags) tags)))))))))
14219 (defun org-add-prop-inherited (s)
14220 (add-text-properties 0 (length s) '(inherited t) s)
14223 (defun org-toggle-tag (tag &optional onoff)
14224 "Toggle the tag TAG for the current line.
14225 If ONOFF is `on' or `off', don't toggle but set to this state."
14226 (let (res current)
14227 (save-excursion
14228 (org-back-to-heading t)
14229 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14230 (point-at-eol) t)
14231 (progn
14232 (setq current (match-string 1))
14233 (replace-match ""))
14234 (setq current ""))
14235 (setq current (nreverse (org-split-string current ":")))
14236 (cond
14237 ((eq onoff 'on)
14238 (setq res t)
14239 (or (member tag current) (push tag current)))
14240 ((eq onoff 'off)
14241 (or (not (member tag current)) (setq current (delete tag current))))
14242 (t (if (member tag current)
14243 (setq current (delete tag current))
14244 (setq res t)
14245 (push tag current))))
14246 (end-of-line 1)
14247 (if current
14248 (progn
14249 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14250 (org-set-tags nil t))
14251 (delete-horizontal-space))
14252 (run-hooks 'org-after-tags-change-hook))
14253 res))
14255 (defun org-align-tags-here (to-col)
14256 ;; Assumes that this is a headline
14257 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14258 (beginning-of-line 1)
14259 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14260 (< pos (match-beginning 2)))
14261 (progn
14262 (setq tags-l (- (match-end 2) (match-beginning 2)))
14263 (goto-char (match-beginning 1))
14264 (insert " ")
14265 (delete-region (point) (1+ (match-beginning 2)))
14266 (setq ncol (max (current-column)
14267 (1+ col)
14268 (if (> to-col 0)
14269 to-col
14270 (- (abs to-col) tags-l))))
14271 (setq p (point))
14272 (insert (make-string (- ncol (current-column)) ?\ ))
14273 (setq ncol (current-column))
14274 (when indent-tabs-mode (tabify p (point-at-eol)))
14275 (org-move-to-column (min ncol col) t))
14276 (goto-char pos))))
14278 (defun org-set-tags-command (&optional arg just-align)
14279 "Call the set-tags command for the current entry."
14280 (interactive "P")
14281 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14282 (org-set-tags arg just-align)
14283 (save-excursion
14284 (unless (and (org-region-active-p)
14285 org-loop-over-headlines-in-active-region)
14286 (org-back-to-heading t))
14287 (org-set-tags arg just-align))))
14289 (defun org-set-tags-to (data)
14290 "Set the tags of the current entry to DATA, replacing the current tags.
14291 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14292 If DATA is nil or the empty string, any tags will be removed."
14293 (interactive "sTags: ")
14294 (setq data
14295 (cond
14296 ((eq data nil) "")
14297 ((equal data "") "")
14298 ((stringp data)
14299 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14300 ":"))
14301 ((listp data)
14302 (concat ":" (mapconcat 'identity data ":") ":"))))
14303 (when data
14304 (save-excursion
14305 (org-back-to-heading t)
14306 (when (looking-at org-complex-heading-regexp)
14307 (if (match-end 5)
14308 (progn
14309 (goto-char (match-beginning 5))
14310 (insert data)
14311 (delete-region (point) (point-at-eol))
14312 (org-set-tags nil 'align))
14313 (goto-char (point-at-eol))
14314 (insert " " data)
14315 (org-set-tags nil 'align)))
14316 (beginning-of-line 1)
14317 (if (looking-at ".*?\\([ \t]+\\)$")
14318 (delete-region (match-beginning 1) (match-end 1))))))
14320 (defun org-align-all-tags ()
14321 "Align the tags i all headings."
14322 (interactive)
14323 (save-excursion
14324 (or (ignore-errors (org-back-to-heading t))
14325 (outline-next-heading))
14326 (if (org-at-heading-p)
14327 (org-set-tags t)
14328 (message "No headings"))))
14330 (defvar org-indent-indentation-per-level)
14331 (defun org-set-tags (&optional arg just-align)
14332 "Set the tags for the current headline.
14333 With prefix ARG, realign all tags in headings in the current buffer."
14334 (interactive "P")
14335 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14336 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14337 'region-start-level 'region))
14338 org-loop-over-headlines-in-active-region)
14339 (org-map-entries
14340 ;; We don't use ARG and JUST-ALIGN here these args are not
14341 ;; useful when looping over headlines
14342 `(org-set-tags)
14343 org-loop-over-headlines-in-active-region
14344 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14345 (let* ((re org-outline-regexp-bol)
14346 (current (unless arg (org-get-tags-string)))
14347 (col (current-column))
14348 (org-setting-tags t)
14349 table current-tags inherited-tags ; computed below when needed
14350 tags p0 c0 c1 rpl di tc level)
14351 (if arg
14352 (save-excursion
14353 (goto-char (point-min))
14354 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14355 (while (re-search-forward re nil t)
14356 (org-set-tags nil t)
14357 (end-of-line 1)))
14358 (message "All tags realigned to column %d" org-tags-column))
14359 (if just-align
14360 (setq tags current)
14361 ;; Get a new set of tags from the user
14362 (save-excursion
14363 (setq table (append org-tag-persistent-alist
14364 (or org-tag-alist (org-get-buffer-tags))
14365 (and
14366 org-complete-tags-always-offer-all-agenda-tags
14367 (org-global-tags-completion-table
14368 (org-agenda-files))))
14369 org-last-tags-completion-table table
14370 current-tags (org-split-string current ":")
14371 inherited-tags (nreverse
14372 (nthcdr (length current-tags)
14373 (nreverse (org-get-tags-at))))
14374 tags
14375 (if (or (eq t org-use-fast-tag-selection)
14376 (and org-use-fast-tag-selection
14377 (delq nil (mapcar 'cdr table))))
14378 (org-fast-tag-selection
14379 current-tags inherited-tags table
14380 (if org-fast-tag-selection-include-todo
14381 org-todo-key-alist))
14382 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14383 (org-trim
14384 (org-icompleting-read "Tags: "
14385 'org-tags-completion-function
14386 nil nil current 'org-tags-history))))))
14387 (while (string-match "[-+&]+" tags)
14388 ;; No boolean logic, just a list
14389 (setq tags (replace-match ":" t t tags))))
14391 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14393 (if org-tags-sort-function
14394 (setq tags (mapconcat 'identity
14395 (sort (org-split-string
14396 tags (org-re "[^[:alnum:]_@#%]+"))
14397 org-tags-sort-function) ":")))
14399 (if (string-match "\\`[\t ]*\\'" tags)
14400 (setq tags "")
14401 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14402 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14404 ;; Insert new tags at the correct column
14405 (beginning-of-line 1)
14406 (setq level (or (and (looking-at org-outline-regexp)
14407 (- (match-end 0) (point) 1))
14409 (cond
14410 ((and (equal current "") (equal tags "")))
14411 ((re-search-forward
14412 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14413 (point-at-eol) t)
14414 (if (equal tags "")
14415 (setq rpl "")
14416 (goto-char (match-beginning 0))
14417 (setq c0 (current-column)
14418 ;; compute offset for the case of org-indent-mode active
14419 di (if org-indent-mode
14420 (* (1- org-indent-indentation-per-level) (1- level))
14422 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14423 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14424 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14425 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14426 (replace-match rpl t t)
14427 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14428 tags)
14429 (t (error "Tags alignment failed")))
14430 (org-move-to-column col)
14431 (unless just-align
14432 (run-hooks 'org-after-tags-change-hook))))))
14434 (defun org-change-tag-in-region (beg end tag off)
14435 "Add or remove TAG for each entry in the region.
14436 This works in the agenda, and also in an org-mode buffer."
14437 (interactive
14438 (list (region-beginning) (region-end)
14439 (let ((org-last-tags-completion-table
14440 (if (derived-mode-p 'org-mode)
14441 (org-get-buffer-tags)
14442 (org-global-tags-completion-table))))
14443 (org-icompleting-read
14444 "Tag: " 'org-tags-completion-function nil nil nil
14445 'org-tags-history))
14446 (progn
14447 (message "[s]et or [r]emove? ")
14448 (equal (read-char-exclusive) ?r))))
14449 (if (fboundp 'deactivate-mark) (deactivate-mark))
14450 (let ((agendap (equal major-mode 'org-agenda-mode))
14451 l1 l2 m buf pos newhead (cnt 0))
14452 (goto-char end)
14453 (setq l2 (1- (org-current-line)))
14454 (goto-char beg)
14455 (setq l1 (org-current-line))
14456 (loop for l from l1 to l2 do
14457 (org-goto-line l)
14458 (setq m (get-text-property (point) 'org-hd-marker))
14459 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14460 (and agendap m))
14461 (setq buf (if agendap (marker-buffer m) (current-buffer))
14462 pos (if agendap m (point)))
14463 (with-current-buffer buf
14464 (save-excursion
14465 (save-restriction
14466 (goto-char pos)
14467 (setq cnt (1+ cnt))
14468 (org-toggle-tag tag (if off 'off 'on))
14469 (setq newhead (org-get-heading)))))
14470 (and agendap (org-agenda-change-all-lines newhead m))))
14471 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14473 (defun org-tags-completion-function (string predicate &optional flag)
14474 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14475 (confirm (lambda (x) (stringp (car x)))))
14476 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14477 (setq s1 (match-string 1 string)
14478 s2 (match-string 2 string))
14479 (setq s1 "" s2 string))
14480 (cond
14481 ((eq flag nil)
14482 ;; try completion
14483 (setq rtn (try-completion s2 ctable confirm))
14484 (if (stringp rtn)
14485 (setq rtn
14486 (concat s1 s2 (substring rtn (length s2))
14487 (if (and org-add-colon-after-tag-completion
14488 (assoc rtn ctable))
14489 ":" ""))))
14490 rtn)
14491 ((eq flag t)
14492 ;; all-completions
14493 (all-completions s2 ctable confirm))
14494 ((eq flag 'lambda)
14495 ;; exact match?
14496 (assoc s2 ctable)))))
14498 (defun org-fast-tag-insert (kwd tags face &optional end)
14499 "Insert KDW, and the TAGS, the latter with face FACE.
14500 Also insert END."
14501 (insert (format "%-12s" (concat kwd ":"))
14502 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14503 (or end "")))
14505 (defun org-fast-tag-show-exit (flag)
14506 (save-excursion
14507 (org-goto-line 3)
14508 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14509 (replace-match ""))
14510 (when flag
14511 (end-of-line 1)
14512 (org-move-to-column (- (window-width) 19) t)
14513 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14515 (defun org-set-current-tags-overlay (current prefix)
14516 "Add an overlay to CURRENT tag with PREFIX."
14517 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14518 (if (featurep 'xemacs)
14519 (org-overlay-display org-tags-overlay (concat prefix s)
14520 'secondary-selection)
14521 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14522 (org-overlay-display org-tags-overlay (concat prefix s)))))
14524 (defvar org-last-tag-selection-key nil)
14525 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14526 "Fast tag selection with single keys.
14527 CURRENT is the current list of tags in the headline, INHERITED is the
14528 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14529 possibly with grouping information. TODO-TABLE is a similar table with
14530 TODO keywords, should these have keys assigned to them.
14531 If the keys are nil, a-z are automatically assigned.
14532 Returns the new tags string, or nil to not change the current settings."
14533 (let* ((fulltable (append table todo-table))
14534 (maxlen (apply 'max (mapcar
14535 (lambda (x)
14536 (if (stringp (car x)) (string-width (car x)) 0))
14537 fulltable)))
14538 (buf (current-buffer))
14539 (expert (eq org-fast-tag-selection-single-key 'expert))
14540 (buffer-tags nil)
14541 (fwidth (+ maxlen 3 1 3))
14542 (ncol (/ (- (window-width) 4) fwidth))
14543 (i-face 'org-done)
14544 (c-face 'org-todo)
14545 tg cnt e c char c1 c2 ntable tbl rtn
14546 ov-start ov-end ov-prefix
14547 (exit-after-next org-fast-tag-selection-single-key)
14548 (done-keywords org-done-keywords)
14549 groups ingroup)
14550 (save-excursion
14551 (beginning-of-line 1)
14552 (if (looking-at
14553 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14554 (setq ov-start (match-beginning 1)
14555 ov-end (match-end 1)
14556 ov-prefix "")
14557 (setq ov-start (1- (point-at-eol))
14558 ov-end (1+ ov-start))
14559 (skip-chars-forward "^\n\r")
14560 (setq ov-prefix
14561 (concat
14562 (buffer-substring (1- (point)) (point))
14563 (if (> (current-column) org-tags-column)
14565 (make-string (- org-tags-column (current-column)) ?\ ))))))
14566 (move-overlay org-tags-overlay ov-start ov-end)
14567 (save-window-excursion
14568 (if expert
14569 (set-buffer (get-buffer-create " *Org tags*"))
14570 (delete-other-windows)
14571 (split-window-vertically)
14572 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14573 (erase-buffer)
14574 (org-set-local 'org-done-keywords done-keywords)
14575 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14576 (org-fast-tag-insert "Current" current c-face "\n\n")
14577 (org-fast-tag-show-exit exit-after-next)
14578 (org-set-current-tags-overlay current ov-prefix)
14579 (setq tbl fulltable char ?a cnt 0)
14580 (while (setq e (pop tbl))
14581 (cond
14582 ((equal (car e) :startgroup)
14583 (push '() groups) (setq ingroup t)
14584 (when (not (= cnt 0))
14585 (setq cnt 0)
14586 (insert "\n"))
14587 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14588 ((equal (car e) :endgroup)
14589 (setq ingroup nil cnt 0)
14590 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14591 ((equal e '(:newline))
14592 (when (not (= cnt 0))
14593 (setq cnt 0)
14594 (insert "\n")
14595 (setq e (car tbl))
14596 (while (equal (car tbl) '(:newline))
14597 (insert "\n")
14598 (setq tbl (cdr tbl)))))
14599 ((equal e '(:grouptags)) nil)
14601 (setq tg (copy-sequence (car e)) c2 nil)
14602 (if (cdr e)
14603 (setq c (cdr e))
14604 ;; automatically assign a character.
14605 (setq c1 (string-to-char
14606 (downcase (substring
14607 tg (if (= (string-to-char tg) ?@) 1 0)))))
14608 (if (or (rassoc c1 ntable) (rassoc c1 table))
14609 (while (or (rassoc char ntable) (rassoc char table))
14610 (setq char (1+ char)))
14611 (setq c2 c1))
14612 (setq c (or c2 char)))
14613 (if ingroup (push tg (car groups)))
14614 (setq tg (org-add-props tg nil 'face
14615 (cond
14616 ((not (assoc tg table))
14617 (org-get-todo-face tg))
14618 ((member tg current) c-face)
14619 ((member tg inherited) i-face))))
14620 (if (equal (caar tbl) :grouptags)
14621 (org-add-props tg nil 'face 'org-tag-group))
14622 (if (and (= cnt 0) (not ingroup)) (insert " "))
14623 (insert "[" c "] " tg (make-string
14624 (- fwidth 4 (length tg)) ?\ ))
14625 (push (cons tg c) ntable)
14626 (when (= (setq cnt (1+ cnt)) ncol)
14627 (insert "\n")
14628 (if ingroup (insert " "))
14629 (setq cnt 0)))))
14630 (setq ntable (nreverse ntable))
14631 (insert "\n")
14632 (goto-char (point-min))
14633 (if (not expert) (org-fit-window-to-buffer))
14634 (setq rtn
14635 (catch 'exit
14636 (while t
14637 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14638 (if (not groups) "no " "")
14639 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14640 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14641 (setq org-last-tag-selection-key c)
14642 (cond
14643 ((= c ?\r) (throw 'exit t))
14644 ((= c ?!)
14645 (setq groups (not groups))
14646 (goto-char (point-min))
14647 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14648 ((= c ?\C-c)
14649 (if (not expert)
14650 (org-fast-tag-show-exit
14651 (setq exit-after-next (not exit-after-next)))
14652 (setq expert nil)
14653 (delete-other-windows)
14654 (set-window-buffer (split-window-vertically) " *Org tags*")
14655 (org-switch-to-buffer-other-window " *Org tags*")
14656 (org-fit-window-to-buffer)))
14657 ((or (= c ?\C-g)
14658 (and (= c ?q) (not (rassoc c ntable))))
14659 (org-detach-overlay org-tags-overlay)
14660 (setq quit-flag t))
14661 ((= c ?\ )
14662 (setq current nil)
14663 (if exit-after-next (setq exit-after-next 'now)))
14664 ((= c ?\t)
14665 (condition-case nil
14666 (setq tg (org-icompleting-read
14667 "Tag: "
14668 (or buffer-tags
14669 (with-current-buffer buf
14670 (org-get-buffer-tags)))))
14671 (quit (setq tg "")))
14672 (when (string-match "\\S-" tg)
14673 (add-to-list 'buffer-tags (list tg))
14674 (if (member tg current)
14675 (setq current (delete tg current))
14676 (push tg current)))
14677 (if exit-after-next (setq exit-after-next 'now)))
14678 ((setq e (rassoc c todo-table) tg (car e))
14679 (with-current-buffer buf
14680 (save-excursion (org-todo tg)))
14681 (if exit-after-next (setq exit-after-next 'now)))
14682 ((setq e (rassoc c ntable) tg (car e))
14683 (if (member tg current)
14684 (setq current (delete tg current))
14685 (loop for g in groups do
14686 (if (member tg g)
14687 (mapc (lambda (x)
14688 (setq current (delete x current)))
14689 g)))
14690 (push tg current))
14691 (if exit-after-next (setq exit-after-next 'now))))
14693 ;; Create a sorted list
14694 (setq current
14695 (sort current
14696 (lambda (a b)
14697 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14698 (if (eq exit-after-next 'now) (throw 'exit t))
14699 (goto-char (point-min))
14700 (beginning-of-line 2)
14701 (delete-region (point) (point-at-eol))
14702 (org-fast-tag-insert "Current" current c-face)
14703 (org-set-current-tags-overlay current ov-prefix)
14704 (while (re-search-forward
14705 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14706 (setq tg (match-string 1))
14707 (add-text-properties
14708 (match-beginning 1) (match-end 1)
14709 (list 'face
14710 (cond
14711 ((member tg current) c-face)
14712 ((member tg inherited) i-face)
14713 (t (get-text-property (match-beginning 1) 'face))))))
14714 (goto-char (point-min)))))
14715 (org-detach-overlay org-tags-overlay)
14716 (if rtn
14717 (mapconcat 'identity current ":")
14718 nil))))
14720 (defun org-get-tags-string ()
14721 "Get the TAGS string in the current headline."
14722 (unless (org-at-heading-p t)
14723 (error "Not on a heading"))
14724 (save-excursion
14725 (beginning-of-line 1)
14726 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14727 (org-match-string-no-properties 1)
14728 "")))
14730 (defun org-get-tags ()
14731 "Get the list of tags specified in the current headline."
14732 (org-split-string (org-get-tags-string) ":"))
14734 (defun org-get-buffer-tags ()
14735 "Get a table of all tags used in the buffer, for completion."
14736 (let (tags)
14737 (save-excursion
14738 (goto-char (point-min))
14739 (while (re-search-forward
14740 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14741 (when (equal (char-after (point-at-bol 0)) ?*)
14742 (mapc (lambda (x) (add-to-list 'tags x))
14743 (org-split-string (org-match-string-no-properties 1) ":")))))
14744 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14745 (mapcar 'list tags)))
14747 ;;;; The mapping API
14749 (defun org-map-entries (func &optional match scope &rest skip)
14750 "Call FUNC at each headline selected by MATCH in SCOPE.
14752 FUNC is a function or a lisp form. The function will be called without
14753 arguments, with the cursor positioned at the beginning of the headline.
14754 The return values of all calls to the function will be collected and
14755 returned as a list.
14757 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14758 does not need to preserve point. After evaluation, the cursor will be
14759 moved to the end of the line (presumably of the headline of the
14760 processed entry) and search continues from there. Under some
14761 circumstances, this may not produce the wanted results. For example,
14762 if you have removed (e.g. archived) the current (sub)tree it could
14763 mean that the next entry will be skipped entirely. In such cases, you
14764 can specify the position from where search should continue by making
14765 FUNC set the variable `org-map-continue-from' to the desired buffer
14766 position.
14768 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14769 Only headlines that are matched by this query will be considered during
14770 the iteration. When MATCH is nil or t, all headlines will be
14771 visited by the iteration.
14773 SCOPE determines the scope of this command. It can be any of:
14775 nil The current buffer, respecting the restriction if any
14776 tree The subtree started with the entry at point
14777 region The entries within the active region, if any
14778 region-start-level
14779 The entries within the active region, but only those at
14780 the same level than the first one.
14781 file The current buffer, without restriction
14782 file-with-archives
14783 The current buffer, and any archives associated with it
14784 agenda All agenda files
14785 agenda-with-archives
14786 All agenda files with any archive files associated with them
14787 \(file1 file2 ...)
14788 If this is a list, all files in the list will be scanned
14790 The remaining args are treated as settings for the skipping facilities of
14791 the scanner. The following items can be given here:
14793 archive skip trees with the archive tag
14794 comment skip trees with the COMMENT keyword
14795 function or Emacs Lisp form:
14796 will be used as value for `org-agenda-skip-function', so
14797 whenever the function returns a position, FUNC will not be
14798 called for that entry and search will continue from the
14799 position returned
14801 If your function needs to retrieve the tags including inherited tags
14802 at the *current* entry, you can use the value of the variable
14803 `org-scanner-tags' which will be much faster than getting the value
14804 with `org-get-tags-at'. If your function gets properties with
14805 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14806 to t around the call to `org-entry-properties' to get the same speedup.
14807 Note that if your function moves around to retrieve tags and properties at
14808 a *different* entry, you cannot use these techniques."
14809 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14810 (not (org-region-active-p)))
14811 (let* ((org-agenda-archives-mode nil) ; just to make sure
14812 (org-agenda-skip-archived-trees (memq 'archive skip))
14813 (org-agenda-skip-comment-trees (memq 'comment skip))
14814 (org-agenda-skip-function
14815 (car (org-delete-all '(comment archive) skip)))
14816 (org-tags-match-list-sublevels t)
14817 (start-level (eq scope 'region-start-level))
14818 matcher file res
14819 org-todo-keywords-for-agenda
14820 org-done-keywords-for-agenda
14821 org-todo-keyword-alist-for-agenda
14822 org-drawers-for-agenda
14823 org-tag-alist-for-agenda
14824 todo-only)
14826 (cond
14827 ((eq match t) (setq matcher t))
14828 ((eq match nil) (setq matcher t))
14829 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14831 (save-window-excursion
14832 (save-restriction
14833 (cond ((eq scope 'tree)
14834 (org-back-to-heading t)
14835 (org-narrow-to-subtree)
14836 (setq scope nil))
14837 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14838 (org-region-active-p))
14839 ;; If needed, set start-level to a string like "2"
14840 (when start-level
14841 (save-excursion
14842 (goto-char (region-beginning))
14843 (unless (org-at-heading-p) (outline-next-heading))
14844 (setq start-level (org-current-level))))
14845 (narrow-to-region (region-beginning)
14846 (save-excursion
14847 (goto-char (region-end))
14848 (unless (and (bolp) (org-at-heading-p))
14849 (outline-next-heading))
14850 (point)))
14851 (setq scope nil)))
14853 (if (not scope)
14854 (progn
14855 (org-agenda-prepare-buffers
14856 (list (buffer-file-name (current-buffer))))
14857 (setq res (org-scan-tags func matcher todo-only start-level)))
14858 ;; Get the right scope
14859 (cond
14860 ((and scope (listp scope) (symbolp (car scope)))
14861 (setq scope (eval scope)))
14862 ((eq scope 'agenda)
14863 (setq scope (org-agenda-files t)))
14864 ((eq scope 'agenda-with-archives)
14865 (setq scope (org-agenda-files t))
14866 (setq scope (org-add-archive-files scope)))
14867 ((eq scope 'file)
14868 (setq scope (list (buffer-file-name))))
14869 ((eq scope 'file-with-archives)
14870 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14871 (org-agenda-prepare-buffers scope)
14872 (while (setq file (pop scope))
14873 (with-current-buffer (org-find-base-buffer-visiting file)
14874 (save-excursion
14875 (save-restriction
14876 (widen)
14877 (goto-char (point-min))
14878 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14879 res)))
14881 ;;;; Properties
14883 ;;; Setting and retrieving properties
14885 (defconst org-special-properties
14886 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14887 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14888 "The special properties valid in Org-mode.
14890 These are properties that are not defined in the property drawer,
14891 but in some other way.")
14893 (defconst org-default-properties
14894 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14895 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14896 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14897 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14898 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14899 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14900 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14901 "Some properties that are used by Org-mode for various purposes.
14902 Being in this list makes sure that they are offered for completion.")
14904 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14905 "Regular expression matching the first line of a property drawer.")
14907 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14908 "Regular expression matching the last line of a property drawer.")
14910 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14911 "Regular expression matching the first line of a property drawer.")
14913 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14914 "Regular expression matching the first line of a property drawer.")
14916 (defconst org-property-drawer-re
14917 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14918 org-property-end-re "\\)\n?")
14919 "Matches an entire property drawer.")
14921 (defconst org-clock-drawer-re
14922 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14923 org-property-end-re "\\)\n?")
14924 "Matches an entire clock drawer.")
14926 (defsubst org-re-property (property)
14927 "Return a regexp matching a PROPERTY line.
14928 Match group 1 will be set to the value."
14929 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14931 (defsubst org-re-property-keyword (property)
14932 "Return a regexp matching a PROPERTY line, possibly with no
14933 value for the property."
14934 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14936 (defun org-property-action ()
14937 "Do an action on properties."
14938 (interactive)
14939 (let (c)
14940 (org-at-property-p)
14941 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14942 (setq c (read-char-exclusive))
14943 (cond
14944 ((equal c ?s)
14945 (call-interactively 'org-set-property))
14946 ((equal c ?d)
14947 (call-interactively 'org-delete-property))
14948 ((equal c ?D)
14949 (call-interactively 'org-delete-property-globally))
14950 ((equal c ?c)
14951 (call-interactively 'org-compute-property-at-point))
14952 (t (error "No such property action %c" c)))))
14954 (defun org-inc-effort ()
14955 "Increment the value of the effort property in the current entry."
14956 (interactive)
14957 (org-set-effort nil t))
14959 (defvar org-clock-effort) ;; Defined in org-clock.el
14960 (defvar org-clock-current-task) ;; Defined in org-clock.el
14961 (defun org-set-effort (&optional value increment)
14962 "Set the effort property of the current entry.
14963 With numerical prefix arg, use the nth allowed value, 0 stands for the
14964 10th allowed value.
14966 When INCREMENT is non-nil, set the property to the next allowed value."
14967 (interactive "P")
14968 (if (equal value 0) (setq value 10))
14969 (let* ((completion-ignore-case t)
14970 (prop org-effort-property)
14971 (cur (org-entry-get nil prop))
14972 (allowed (org-property-get-allowed-values nil prop 'table))
14973 (existing (mapcar 'list (org-property-values prop)))
14974 (heading (nth 4 (org-heading-components)))
14976 (val (cond
14977 ((stringp value) value)
14978 ((and allowed (integerp value))
14979 (or (car (nth (1- value) allowed))
14980 (car (org-last allowed))))
14981 ((and allowed increment)
14982 (or (caadr (member (list cur) allowed))
14983 (error "Allowed effort values are not set")))
14984 (allowed
14985 (message "Select 1-9,0, [RET%s]: %s"
14986 (if cur (concat "=" cur) "")
14987 (mapconcat 'car allowed " "))
14988 (setq rpl (read-char-exclusive))
14989 (if (equal rpl ?\r)
14991 (setq rpl (- rpl ?0))
14992 (if (equal rpl 0) (setq rpl 10))
14993 (if (and (> rpl 0) (<= rpl (length allowed)))
14994 (car (nth (1- rpl) allowed))
14995 (org-completing-read "Effort: " allowed nil))))
14997 (let (org-completion-use-ido org-completion-use-iswitchb)
14998 (org-completing-read
14999 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15000 (concat "[" cur "]") "")
15001 ": ")
15002 existing nil nil "" nil cur))))))
15003 (unless (equal (org-entry-get nil prop) val)
15004 (org-entry-put nil prop val))
15005 (save-excursion
15006 (org-back-to-heading t)
15007 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15008 (when (string= heading org-clock-current-task)
15009 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15010 (org-clock-update-mode-line))
15011 (message "%s is now %s" prop val)))
15013 (defun org-at-property-p ()
15014 "Is cursor inside a property drawer?"
15015 (save-excursion
15016 (beginning-of-line 1)
15017 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
15018 (save-match-data ;; Used by calling procedures
15019 (let ((p (point))
15020 (range (unless (org-before-first-heading-p)
15021 (org-get-property-block))))
15022 (and range (<= (car range) p) (< p (cdr range))))))))
15024 (defun org-get-property-block (&optional beg end force)
15025 "Return the (beg . end) range of the body of the property drawer.
15026 BEG and END are the beginning and end of the current subtree, or of
15027 the part before the first headline. If they are not given, they will
15028 be found. If the drawer does not exist and FORCE is non-nil, create
15029 the drawer."
15030 (catch 'exit
15031 (save-excursion
15032 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15033 (progn (org-back-to-heading t) (point))))
15034 (end (or end (and (not (outline-next-heading)) (point-max))
15035 (point))))
15036 (goto-char beg)
15037 (if (re-search-forward org-property-start-re end t)
15038 (setq beg (1+ (match-end 0)))
15039 (if force
15040 (save-excursion
15041 (org-insert-property-drawer)
15042 (setq end (progn (outline-next-heading) (point))))
15043 (throw 'exit nil))
15044 (goto-char beg)
15045 (if (re-search-forward org-property-start-re end t)
15046 (setq beg (1+ (match-end 0)))))
15047 (if (re-search-forward org-property-end-re end t)
15048 (setq end (match-beginning 0))
15049 (or force (throw 'exit nil))
15050 (goto-char beg)
15051 (setq end beg)
15052 (org-indent-line)
15053 (insert ":END:\n"))
15054 (cons beg end)))))
15056 (defun org-entry-properties (&optional pom which specific)
15057 "Get all properties of the entry at point-or-marker POM.
15058 This includes the TODO keyword, the tags, time strings for deadline,
15059 scheduled, and clocking, and any additional properties defined in the
15060 entry. The return value is an alist, keys may occur multiple times
15061 if the property key was used several times.
15062 POM may also be nil, in which case the current entry is used.
15063 If WHICH is nil or `all', get all properties. If WHICH is
15064 `special' or `standard', only get that subclass. If WHICH
15065 is a string only get exactly this property. SPECIFIC can be a string, the
15066 specific property we are interested in. Specifying it can speed
15067 things up because then unnecessary parsing is avoided."
15068 (setq which (or which 'all))
15069 (org-with-point-at pom
15070 (let ((clockstr (substring org-clock-string 0 -1))
15071 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15072 (case-fold-search nil)
15073 beg end range props sum-props key key1 value string clocksum clocksumt)
15074 (save-excursion
15075 (when (condition-case nil
15076 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
15077 (error nil))
15078 (setq beg (point))
15079 (setq sum-props (get-text-property (point) 'org-summaries))
15080 (setq clocksum (get-text-property (point) :org-clock-minutes)
15081 clocksumt (get-text-property (point) :org-clock-minutes-today))
15082 (outline-next-heading)
15083 (setq end (point))
15084 (when (memq which '(all special))
15085 ;; Get the special properties, like TODO and tags
15086 (goto-char beg)
15087 (when (and (or (not specific) (string= specific "TODO"))
15088 (looking-at org-todo-line-regexp) (match-end 2))
15089 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15090 (when (and (or (not specific) (string= specific "PRIORITY"))
15091 (looking-at org-priority-regexp))
15092 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15093 (when (or (not specific) (string= specific "FILE"))
15094 (push (cons "FILE" buffer-file-name) props))
15095 (when (and (or (not specific) (string= specific "TAGS"))
15096 (setq value (org-get-tags-string))
15097 (string-match "\\S-" value))
15098 (push (cons "TAGS" value) props))
15099 (when (and (or (not specific) (string= specific "ALLTAGS"))
15100 (setq value (org-get-tags-at)))
15101 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15102 ":"))
15103 props))
15104 (when (or (not specific) (string= specific "BLOCKED"))
15105 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15106 (when (or (not specific)
15107 (member specific
15108 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15109 "TIMESTAMP" "TIMESTAMP_IA")))
15110 (catch 'match
15111 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15112 (setq key (if (match-end 1)
15113 (substring (org-match-string-no-properties 1)
15114 0 -1))
15115 string (if (equal key clockstr)
15116 (org-trim
15117 (buffer-substring-no-properties
15118 (match-beginning 3) (goto-char
15119 (point-at-eol))))
15120 (substring (org-match-string-no-properties 3)
15121 1 -1)))
15122 ;; Get the correct property name from the key. This is
15123 ;; necessary if the user has configured time keywords.
15124 (setq key1 (concat key ":"))
15125 (cond
15126 ((not key)
15127 (setq key
15128 (if (= (char-after (match-beginning 3)) ?\[)
15129 "TIMESTAMP_IA" "TIMESTAMP")))
15130 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15131 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15132 ((equal key1 org-closed-string) (setq key "CLOSED"))
15133 ((equal key1 org-clock-string) (setq key "CLOCK")))
15134 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15135 (progn
15136 (push (cons key string) props)
15137 ;; no need to search further if match is found
15138 (throw 'match t))
15139 (when (or (equal key "CLOCK") (not (assoc key props)))
15140 (push (cons key string) props)))))))
15142 (when (memq which '(all standard))
15143 ;; Get the standard properties, like :PROP: ...
15144 (setq range (org-get-property-block beg end))
15145 (when range
15146 (goto-char (car range))
15147 (while (re-search-forward
15148 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15149 (cdr range) t)
15150 (setq key (org-match-string-no-properties 1)
15151 value (org-trim (or (org-match-string-no-properties 2) "")))
15152 (unless (member key excluded)
15153 (push (cons key (or value "")) props)))))
15154 (if clocksum
15155 (push (cons "CLOCKSUM"
15156 (org-columns-number-to-string (/ (float clocksum) 60.)
15157 'add_times))
15158 props))
15159 (if clocksumt
15160 (push (cons "CLOCKSUM_T"
15161 (org-columns-number-to-string (/ (float clocksumt) 60.)
15162 'add_times))
15163 props))
15164 (unless (assoc "CATEGORY" props)
15165 (push (cons "CATEGORY" (org-get-category)) props))
15166 (append sum-props (nreverse props)))))))
15168 (defun org-entry-get (pom property &optional inherit literal-nil)
15169 "Get value of PROPERTY for entry or content at point-or-marker POM.
15170 If INHERIT is non-nil and the entry does not have the property,
15171 then also check higher levels of the hierarchy.
15172 If INHERIT is the symbol `selective', use inheritance only if the setting
15173 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15174 If the property is present but empty, the return value is the empty string.
15175 If the property is not present at all, nil is returned.
15177 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15178 do not interpret it as the list atom nil. This is used for inheritance
15179 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15180 (org-with-point-at pom
15181 (if (and inherit (if (eq inherit 'selective)
15182 (org-property-inherit-p property)
15184 (org-entry-get-with-inheritance property literal-nil)
15185 (if (member property org-special-properties)
15186 ;; We need a special property. Use `org-entry-properties' to
15187 ;; retrieve it, but specify the wanted property
15188 (cdr (assoc property (org-entry-properties nil 'special property)))
15189 (let ((range (org-get-property-block)))
15190 (when (and range (not (eq (car range) (cdr range))))
15191 (let* ((props (list (or (assoc property org-file-properties)
15192 (assoc property org-global-properties)
15193 (assoc property org-global-properties-fixed))))
15194 (ap (lambda (key)
15195 (when (re-search-forward
15196 (org-re-property key) (cdr range) t)
15197 (setq props
15198 (org-update-property-plist
15200 (if (match-end 1)
15201 (org-match-string-no-properties 1) "")
15202 props)))))
15203 val)
15204 (goto-char (car range))
15205 (funcall ap property)
15206 (goto-char (car range))
15207 (while (funcall ap (concat property "+")))
15208 (setq val (cdr (assoc property props)))
15209 (when val (if literal-nil val (org-not-nil val))))))))))
15211 (defun org-property-or-variable-value (var &optional inherit)
15212 "Check if there is a property fixing the value of VAR.
15213 If yes, return this value. If not, return the current value of the variable."
15214 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15215 (if (and prop (stringp prop) (string-match "\\S-" prop))
15216 (read prop)
15217 (symbol-value var))))
15219 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15220 "Delete the property PROPERTY from entry at point-or-marker POM.
15221 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15222 an empty drawer to delete."
15223 (org-with-point-at pom
15224 (if (member property org-special-properties)
15225 nil ; cannot delete these properties.
15226 (let ((range (org-get-property-block)))
15227 (if (and range
15228 (goto-char (car range))
15229 (re-search-forward
15230 (org-re-property property)
15231 (cdr range) t))
15232 (progn
15233 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15234 (and delete-empty-drawer
15235 (org-remove-empty-drawer-at
15236 delete-empty-drawer (car range)))
15238 nil)))))
15240 ;; Multi-values properties are properties that contain multiple values
15241 ;; These values are assumed to be single words, separated by whitespace.
15242 (defun org-entry-add-to-multivalued-property (pom property value)
15243 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15244 (let* ((old (org-entry-get pom property))
15245 (values (and old (org-split-string old "[ \t]"))))
15246 (setq value (org-entry-protect-space value))
15247 (unless (member value values)
15248 (setq values (append values (list value)))
15249 (org-entry-put pom property
15250 (mapconcat 'identity values " ")))))
15252 (defun org-entry-remove-from-multivalued-property (pom property value)
15253 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15254 (let* ((old (org-entry-get pom property))
15255 (values (and old (org-split-string old "[ \t]"))))
15256 (setq value (org-entry-protect-space value))
15257 (when (member value values)
15258 (setq values (delete value values))
15259 (org-entry-put pom property
15260 (mapconcat 'identity values " ")))))
15262 (defun org-entry-member-in-multivalued-property (pom property value)
15263 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15264 (let* ((old (org-entry-get pom property))
15265 (values (and old (org-split-string old "[ \t]"))))
15266 (setq value (org-entry-protect-space value))
15267 (member value values)))
15269 (defun org-entry-get-multivalued-property (pom property)
15270 "Return a list of values in a multivalued property."
15271 (let* ((value (org-entry-get pom property))
15272 (values (and value (org-split-string value "[ \t]"))))
15273 (mapcar 'org-entry-restore-space values)))
15275 (defun org-entry-put-multivalued-property (pom property &rest values)
15276 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15277 VALUES should be a list of strings. Spaces will be protected."
15278 (org-entry-put pom property
15279 (mapconcat 'org-entry-protect-space values " "))
15280 (let* ((value (org-entry-get pom property))
15281 (values (and value (org-split-string value "[ \t]"))))
15282 (mapcar 'org-entry-restore-space values)))
15284 (defun org-entry-protect-space (s)
15285 "Protect spaces and newline in string S."
15286 (while (string-match " " s)
15287 (setq s (replace-match "%20" t t s)))
15288 (while (string-match "\n" s)
15289 (setq s (replace-match "%0A" t t s)))
15292 (defun org-entry-restore-space (s)
15293 "Restore spaces and newline in string S."
15294 (while (string-match "%20" s)
15295 (setq s (replace-match " " t t s)))
15296 (while (string-match "%0A" s)
15297 (setq s (replace-match "\n" t t s)))
15300 (defvar org-entry-property-inherited-from (make-marker)
15301 "Marker pointing to the entry from where a property was inherited.
15302 Each call to `org-entry-get-with-inheritance' will set this marker to the
15303 location of the entry where the inheritance search matched. If there was
15304 no match, the marker will point nowhere.
15305 Note that also `org-entry-get' calls this function, if the INHERIT flag
15306 is set.")
15308 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15309 "Get PROPERTY of entry or content at point, search higher levels if needed.
15310 The search will stop at the first ancestor which has the property defined.
15311 If the value found is \"nil\", return nil to show that the property
15312 should be considered as undefined (this is the meaning of nil here).
15313 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15314 (move-marker org-entry-property-inherited-from nil)
15315 (let (tmp)
15316 (save-excursion
15317 (save-restriction
15318 (widen)
15319 (catch 'ex
15320 (while t
15321 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15322 (or (ignore-errors (org-back-to-heading t))
15323 (goto-char (point-min)))
15324 (move-marker org-entry-property-inherited-from (point))
15325 (throw 'ex tmp))
15326 (or (ignore-errors (org-up-heading-safe))
15327 (throw 'ex nil))))))
15328 (setq tmp (or tmp
15329 (cdr (assoc property org-file-properties))
15330 (cdr (assoc property org-global-properties))
15331 (cdr (assoc property org-global-properties-fixed))))
15332 (if literal-nil tmp (org-not-nil tmp))))
15334 (defvar org-property-changed-functions nil
15335 "Hook called when the value of a property has changed.
15336 Each hook function should accept two arguments, the name of the property
15337 and the new value.")
15339 (defun org-entry-put (pom property value)
15340 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15341 (org-with-point-at pom
15342 (org-back-to-heading t)
15343 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15344 range)
15345 (cond
15346 ((equal property "TODO")
15347 (when (and (stringp value) (string-match "\\S-" value)
15348 (not (member value org-todo-keywords-1)))
15349 (error "\"%s\" is not a valid TODO state" value))
15350 (if (or (not value)
15351 (not (string-match "\\S-" value)))
15352 (setq value 'none))
15353 (org-todo value)
15354 (org-set-tags nil 'align))
15355 ((equal property "PRIORITY")
15356 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15357 (string-to-char value) ?\ ))
15358 (org-set-tags nil 'align))
15359 ((equal property "CLOCKSUM")
15360 (if (not (re-search-forward
15361 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15362 (error "Cannot find a clock log")
15363 (goto-char (- (match-end 1) 2))
15364 (cond
15365 ((eq value 'earlier) (org-timestamp-down))
15366 ((eq value 'later) (org-timestamp-up)))
15367 (org-clock-sum-current-item)))
15368 ((equal property "SCHEDULED")
15369 (if (re-search-forward org-scheduled-time-regexp end t)
15370 (cond
15371 ((eq value 'earlier) (org-timestamp-change -1 'day))
15372 ((eq value 'later) (org-timestamp-change 1 'day))
15373 (t (call-interactively 'org-schedule)))
15374 (call-interactively 'org-schedule)))
15375 ((equal property "DEADLINE")
15376 (if (re-search-forward org-deadline-time-regexp end t)
15377 (cond
15378 ((eq value 'earlier) (org-timestamp-change -1 'day))
15379 ((eq value 'later) (org-timestamp-change 1 'day))
15380 (t (call-interactively 'org-deadline)))
15381 (call-interactively 'org-deadline)))
15382 ((member property org-special-properties)
15383 (error "The %s property can not yet be set with `org-entry-put'"
15384 property))
15385 (t ; a non-special property
15386 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15387 (setq range (org-get-property-block beg end 'force))
15388 (goto-char (car range))
15389 (if (re-search-forward
15390 (org-re-property-keyword property) (cdr range) t)
15391 (progn
15392 (delete-region (match-beginning 0) (match-end 0))
15393 (goto-char (match-beginning 0)))
15394 (goto-char (cdr range))
15395 (insert "\n")
15396 (backward-char 1)
15397 (org-indent-line))
15398 (insert ":" property ":")
15399 (and value (insert " " value))
15400 (org-indent-line)))))
15401 (run-hook-with-args 'org-property-changed-functions property value)))
15403 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15404 "Get all property keys in the current buffer.
15405 With INCLUDE-SPECIALS, also list the special properties that reflect things
15406 like tags and TODO state.
15407 With INCLUDE-DEFAULTS, also include properties that has special meaning
15408 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15409 and others.
15410 With INCLUDE-COLUMNS, also include property names given in COLUMN
15411 formats in the current buffer."
15412 (let (rtn range cfmt s p)
15413 (save-excursion
15414 (save-restriction
15415 (widen)
15416 (goto-char (point-min))
15417 (while (re-search-forward org-property-start-re nil t)
15418 (setq range (org-get-property-block))
15419 (goto-char (car range))
15420 (while (re-search-forward
15421 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15422 (cdr range) t)
15423 (add-to-list 'rtn (org-match-string-no-properties 1)))
15424 (outline-next-heading))))
15426 (when include-specials
15427 (setq rtn (append org-special-properties rtn)))
15429 (when include-defaults
15430 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15431 (add-to-list 'rtn org-effort-property))
15433 (when include-columns
15434 (save-excursion
15435 (save-restriction
15436 (widen)
15437 (goto-char (point-min))
15438 (while (re-search-forward
15439 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15440 nil t)
15441 (setq cfmt (match-string 2) s 0)
15442 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15443 cfmt s)
15444 (setq s (match-end 0)
15445 p (match-string 1 cfmt))
15446 (unless (or (equal p "ITEM")
15447 (member p org-special-properties))
15448 (add-to-list 'rtn (match-string 1 cfmt))))))))
15450 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15452 (defun org-property-values (key)
15453 "Return a list of all values of property KEY in the current buffer."
15454 (save-excursion
15455 (save-restriction
15456 (widen)
15457 (goto-char (point-min))
15458 (let ((re (org-re-property key))
15459 values)
15460 (while (re-search-forward re nil t)
15461 (add-to-list 'values (org-trim (match-string 1))))
15462 (delete "" values)))))
15464 (defun org-insert-property-drawer ()
15465 "Insert a property drawer into the current entry."
15466 (org-back-to-heading t)
15467 (looking-at org-outline-regexp)
15468 (let ((indent (if org-adapt-indentation
15469 (- (match-end 0) (match-beginning 0))
15471 (beg (point))
15472 (re (concat "^[ \t]*" org-keyword-time-regexp))
15473 end hiddenp)
15474 (outline-next-heading)
15475 (setq end (point))
15476 (goto-char beg)
15477 (while (re-search-forward re end t))
15478 (setq hiddenp (outline-invisible-p))
15479 (end-of-line 1)
15480 (and (equal (char-after) ?\n) (forward-char 1))
15481 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15482 (if (member (match-string 1) '("CLOCK:" ":END:"))
15483 ;; just skip this line
15484 (beginning-of-line 2)
15485 ;; Drawer start, find the end
15486 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15487 (beginning-of-line 1)))
15488 (org-skip-over-state-notes)
15489 (skip-chars-backward " \t\n\r")
15490 (if (eq (char-before) ?*) (forward-char 1))
15491 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15492 (beginning-of-line 0)
15493 (org-indent-to-column indent)
15494 (beginning-of-line 2)
15495 (org-indent-to-column indent)
15496 (beginning-of-line 0)
15497 (if hiddenp
15498 (save-excursion
15499 (org-back-to-heading t)
15500 (hide-entry))
15501 (org-flag-drawer t))))
15503 (defun org-insert-drawer (&optional arg drawer)
15504 "Insert a drawer at point.
15506 Optional argument DRAWER, when non-nil, is a string representing
15507 drawer's name. Otherwise, the user is prompted for a name.
15509 If a region is active, insert the drawer around that region
15510 instead.
15512 Point is left between drawer's boundaries."
15513 (interactive "P")
15514 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15515 "LOGBOOK"))
15516 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15517 ;; internally by Org. They are meant to be inserted
15518 ;; automatically.
15519 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15520 ;; Remove system drawers from list. Note: For some reason,
15521 ;; `org-completing-read' ignores the predicate while
15522 ;; `completing-read' handles it fine.
15523 (drawer (if arg "PROPERTIES"
15524 (or drawer
15525 (completing-read
15526 "Drawer: " org-drawers
15527 (lambda (d) (not (member d system-drawers))))))))
15528 (cond
15529 ;; With C-u, fall back on `org-insert-property-drawer'
15530 (arg (org-insert-property-drawer))
15531 ;; With an active region, insert a drawer at point.
15532 ((not (org-region-active-p))
15533 (progn
15534 (unless (bolp) (insert "\n"))
15535 (insert (format ":%s:\n\n:END:\n" drawer))
15536 (forward-line -2)))
15537 ;; Otherwise, insert the drawer at point
15539 (let ((rbeg (region-beginning))
15540 (rend (copy-marker (region-end))))
15541 (unwind-protect
15542 (progn
15543 (goto-char rbeg)
15544 (beginning-of-line)
15545 (when (save-excursion
15546 (re-search-forward org-outline-regexp-bol rend t))
15547 (error "Drawers cannot contain headlines"))
15548 ;; Position point at the beginning of the first
15549 ;; non-blank line in region. Insert drawer's opening
15550 ;; there, then indent it.
15551 (org-skip-whitespace)
15552 (beginning-of-line)
15553 (insert ":" drawer ":\n")
15554 (forward-line -1)
15555 (indent-for-tab-command)
15556 ;; Move point to the beginning of the first blank line
15557 ;; after the last non-blank line in region. Insert
15558 ;; drawer's closing, then indent it.
15559 (goto-char rend)
15560 (skip-chars-backward " \r\t\n")
15561 (insert "\n:END:")
15562 (deactivate-mark t)
15563 (indent-for-tab-command)
15564 (unless (eolp) (insert "\n")))
15565 ;; Clear marker, whatever the outcome of insertion is.
15566 (set-marker rend nil)))))))
15568 (defvar org-property-set-functions-alist nil
15569 "Property set function alist.
15570 Each entry should have the following format:
15572 (PROPERTY . READ-FUNCTION)
15574 The read function will be called with the same argument as
15575 `org-completing-read'.")
15577 (defun org-set-property-function (property)
15578 "Get the function that should be used to set PROPERTY.
15579 This is computed according to `org-property-set-functions-alist'."
15580 (or (cdr (assoc property org-property-set-functions-alist))
15581 'org-completing-read))
15583 (defun org-read-property-value (property)
15584 "Read PROPERTY value from user."
15585 (let* ((completion-ignore-case t)
15586 (allowed (org-property-get-allowed-values nil property 'table))
15587 (cur (org-entry-get nil property))
15588 (prompt (concat property " value"
15589 (if (and cur (string-match "\\S-" cur))
15590 (concat " [" cur "]") "") ": "))
15591 (set-function (org-set-property-function property))
15592 (val (if allowed
15593 (funcall set-function prompt allowed nil
15594 (not (get-text-property 0 'org-unrestricted
15595 (caar allowed))))
15596 (let (org-completion-use-ido org-completion-use-iswitchb)
15597 (funcall set-function prompt
15598 (mapcar 'list (org-property-values property))
15599 nil nil "" nil cur)))))
15600 (if (equal val "")
15602 val)))
15604 (defvar org-last-set-property nil)
15605 (defvar org-last-set-property-value nil)
15606 (defun org-read-property-name ()
15607 "Read a property name."
15608 (let* ((completion-ignore-case t)
15609 (keys (org-buffer-property-keys nil t t))
15610 (default-prop (or (save-excursion
15611 (save-match-data
15612 (beginning-of-line)
15613 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15614 (null (string= (match-string 1) "END"))
15615 (match-string 1))))
15616 org-last-set-property))
15617 (property (org-icompleting-read
15618 (concat "Property"
15619 (if default-prop (concat " [" default-prop "]") "")
15620 ": ")
15621 (mapcar 'list keys)
15622 nil nil nil nil
15623 default-prop)))
15624 (if (member property keys)
15625 property
15626 (or (cdr (assoc (downcase property)
15627 (mapcar (lambda (x) (cons (downcase x) x))
15628 keys)))
15629 property))))
15631 (defun org-set-property-and-value (use-last)
15632 "Allow to set [PROPERTY]: [value] direction from prompt.
15633 When use-default, don't even ask, just use the last
15634 \"[PROPERTY]: [value]\" string from the history."
15635 (interactive "P")
15636 (let* ((completion-ignore-case t)
15637 (pv (or (and use-last org-last-set-property-value)
15638 (org-completing-read
15639 "Enter a \"[Property]: [value]\" pair: "
15640 nil nil nil nil nil
15641 org-last-set-property-value)))
15642 prop val)
15643 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15644 (setq prop (match-string 1 pv)
15645 val (match-string 2 pv))
15646 (org-set-property prop val))))
15648 (defun org-set-property (property value)
15649 "In the current entry, set PROPERTY to VALUE.
15650 When called interactively, this will prompt for a property name, offering
15651 completion on existing and default properties. And then it will prompt
15652 for a value, offering completion either on allowed values (via an inherited
15653 xxx_ALL property) or on existing values in other instances of this property
15654 in the current file."
15655 (interactive (list nil nil))
15656 (let* ((property (or property (org-read-property-name)))
15657 (value (or value (org-read-property-value property)))
15658 (fn (cdr (assoc property org-properties-postprocess-alist))))
15659 (setq org-last-set-property property)
15660 (setq org-last-set-property-value (concat property ": " value))
15661 ;; Possibly postprocess the inserted value:
15662 (when fn (setq value (funcall fn value)))
15663 (unless (equal (org-entry-get nil property) value)
15664 (org-entry-put nil property value))))
15666 (defun org-delete-property (property &optional delete-empty-drawer)
15667 "In the current entry, delete PROPERTY.
15668 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15669 an empty drawer to delete."
15670 (interactive
15671 (let* ((completion-ignore-case t)
15672 (prop (org-icompleting-read "Property: "
15673 (org-entry-properties nil 'standard))))
15674 (list prop)))
15675 (message "Property %s %s" property
15676 (if (org-entry-delete nil property delete-empty-drawer)
15677 "deleted"
15678 "was not present in the entry")))
15680 (defun org-delete-property-globally (property)
15681 "Remove PROPERTY globally, from all entries."
15682 (interactive
15683 (let* ((completion-ignore-case t)
15684 (prop (org-icompleting-read
15685 "Globally remove property: "
15686 (mapcar 'list (org-buffer-property-keys)))))
15687 (list prop)))
15688 (save-excursion
15689 (save-restriction
15690 (widen)
15691 (goto-char (point-min))
15692 (let ((cnt 0))
15693 (while (re-search-forward
15694 (org-re-property property)
15695 nil t)
15696 (setq cnt (1+ cnt))
15697 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15698 (message "Property \"%s\" removed from %d entries" property cnt)))))
15700 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15702 (defun org-compute-property-at-point ()
15703 "Compute the property at point.
15704 This looks for an enclosing column format, extracts the operator and
15705 then applies it to the property in the column format's scope."
15706 (interactive)
15707 (unless (org-at-property-p)
15708 (error "Not at a property"))
15709 (let ((prop (org-match-string-no-properties 2)))
15710 (org-columns-get-format-and-top-level)
15711 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15712 (error "No operator defined for property %s" prop))
15713 (org-columns-compute prop)))
15715 (defvar org-property-allowed-value-functions nil
15716 "Hook for functions supplying allowed values for a specific property.
15717 The functions must take a single argument, the name of the property, and
15718 return a flat list of allowed values. If \":ETC\" is one of
15719 the values, this means that these values are intended as defaults for
15720 completion, but that other values should be allowed too.
15721 The functions must return nil if they are not responsible for this
15722 property.")
15724 (defun org-property-get-allowed-values (pom property &optional table)
15725 "Get allowed values for the property PROPERTY.
15726 When TABLE is non-nil, return an alist that can directly be used for
15727 completion."
15728 (let (vals)
15729 (cond
15730 ((equal property "TODO")
15731 (setq vals (org-with-point-at pom
15732 (append org-todo-keywords-1 '("")))))
15733 ((equal property "PRIORITY")
15734 (let ((n org-lowest-priority))
15735 (while (>= n org-highest-priority)
15736 (push (char-to-string n) vals)
15737 (setq n (1- n)))))
15738 ((member property org-special-properties))
15739 ((setq vals (run-hook-with-args-until-success
15740 'org-property-allowed-value-functions property)))
15742 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15743 (when (and vals (string-match "\\S-" vals))
15744 (setq vals (car (read-from-string (concat "(" vals ")"))))
15745 (setq vals (mapcar (lambda (x)
15746 (cond ((stringp x) x)
15747 ((numberp x) (number-to-string x))
15748 ((symbolp x) (symbol-name x))
15749 (t "???")))
15750 vals)))))
15751 (when (member ":ETC" vals)
15752 (setq vals (remove ":ETC" vals))
15753 (org-add-props (car vals) '(org-unrestricted t)))
15754 (if table (mapcar 'list vals) vals)))
15756 (defun org-property-previous-allowed-value (&optional previous)
15757 "Switch to the next allowed value for this property."
15758 (interactive)
15759 (org-property-next-allowed-value t))
15761 (defun org-property-next-allowed-value (&optional previous)
15762 "Switch to the next allowed value for this property."
15763 (interactive)
15764 (unless (org-at-property-p)
15765 (error "Not at a property"))
15766 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15767 (key (match-string 2))
15768 (value (match-string 3))
15769 (allowed (or (org-property-get-allowed-values (point) key)
15770 (and (member value '("[ ]" "[-]" "[X]"))
15771 '("[ ]" "[X]"))))
15772 (heading (save-match-data (nth 4 (org-heading-components))))
15773 nval)
15774 (unless allowed
15775 (error "Allowed values for this property have not been defined"))
15776 (if previous (setq allowed (reverse allowed)))
15777 (if (member value allowed)
15778 (setq nval (car (cdr (member value allowed)))))
15779 (setq nval (or nval (car allowed)))
15780 (if (equal nval value)
15781 (error "Only one allowed value for this property"))
15782 (org-at-property-p)
15783 (replace-match (concat " :" key ": " nval) t t)
15784 (org-indent-line)
15785 (beginning-of-line 1)
15786 (skip-chars-forward " \t")
15787 (when (equal prop org-effort-property)
15788 (save-excursion
15789 (org-back-to-heading t)
15790 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15791 (when (string= org-clock-current-task heading)
15792 (setq org-clock-effort nval)
15793 (org-clock-update-mode-line)))
15794 (run-hook-with-args 'org-property-changed-functions key nval)))
15796 (defun org-find-olp (path &optional this-buffer)
15797 "Return a marker pointing to the entry at outline path OLP.
15798 If anything goes wrong, throw an error.
15799 You can wrap this call to catch the error like this:
15801 (condition-case msg
15802 (org-mobile-locate-entry (match-string 4))
15803 (error (nth 1 msg)))
15805 The return value will then be either a string with the error message,
15806 or a marker if everything is OK.
15808 If THIS-BUFFER is set, the outline path does not contain a file,
15809 only headings."
15810 (let* ((file (if this-buffer buffer-file-name (pop path)))
15811 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15812 (level 1)
15813 (lmin 1)
15814 (lmax 1)
15815 limit re end found pos heading cnt flevel)
15816 (unless buffer (error "File not found :%s" file))
15817 (with-current-buffer buffer
15818 (save-excursion
15819 (save-restriction
15820 (widen)
15821 (setq limit (point-max))
15822 (goto-char (point-min))
15823 (while (setq heading (pop path))
15824 (setq re (format org-complex-heading-regexp-format
15825 (regexp-quote heading)))
15826 (setq cnt 0 pos (point))
15827 (while (re-search-forward re end t)
15828 (setq level (- (match-end 1) (match-beginning 1)))
15829 (if (and (>= level lmin) (<= level lmax))
15830 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15831 (when (= cnt 0) (error "Heading not found on level %d: %s"
15832 lmax heading))
15833 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15834 lmax heading))
15835 (goto-char found)
15836 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15837 (setq end (save-excursion (org-end-of-subtree t t))))
15838 (when (org-at-heading-p)
15839 (point-marker)))))))
15841 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15842 "Find node HEADING in BUFFER.
15843 Return a marker to the heading if it was found, or nil if not.
15844 If POS-ONLY is set, return just the position instead of a marker.
15846 The heading text must match exact, but it may have a TODO keyword,
15847 a priority cookie and tags in the standard locations."
15848 (with-current-buffer (or buffer (current-buffer))
15849 (save-excursion
15850 (save-restriction
15851 (widen)
15852 (goto-char (point-min))
15853 (let (case-fold-search)
15854 (if (re-search-forward
15855 (format org-complex-heading-regexp-format
15856 (regexp-quote heading)) nil t)
15857 (if pos-only
15858 (match-beginning 0)
15859 (move-marker (make-marker) (match-beginning 0)))))))))
15861 (defun org-find-exact-heading-in-directory (heading &optional dir)
15862 "Find Org node headline HEADING in all .org files in directory DIR.
15863 When the target headline is found, return a marker to this location."
15864 (let ((files (directory-files (or dir default-directory)
15865 nil "\\`[^.#].*\\.org\\'"))
15866 file visiting m buffer)
15867 (catch 'found
15868 (while (setq file (pop files))
15869 (message "trying %s" file)
15870 (setq visiting (org-find-base-buffer-visiting file))
15871 (setq buffer (or visiting (find-file-noselect file)))
15872 (setq m (org-find-exact-headline-in-buffer
15873 heading buffer))
15874 (when (and (not m) (not visiting)) (kill-buffer buffer))
15875 (and m (throw 'found m))))))
15877 (defun org-find-entry-with-id (ident)
15878 "Locate the entry that contains the ID property with exact value IDENT.
15879 IDENT can be a string, a symbol or a number, this function will search for
15880 the string representation of it.
15881 Return the position where this entry starts, or nil if there is no such entry."
15882 (interactive "sID: ")
15883 (let ((id (cond
15884 ((stringp ident) ident)
15885 ((symbol-name ident) (symbol-name ident))
15886 ((numberp ident) (number-to-string ident))
15887 (t (error "IDENT %s must be a string, symbol or number" ident))))
15888 (case-fold-search nil))
15889 (save-excursion
15890 (save-restriction
15891 (widen)
15892 (goto-char (point-min))
15893 (when (re-search-forward
15894 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15895 nil t)
15896 (org-back-to-heading t)
15897 (point))))))
15899 ;;;; Timestamps
15901 (defvar org-last-changed-timestamp nil)
15902 (defvar org-last-inserted-timestamp nil
15903 "The last time stamp inserted with `org-insert-time-stamp'.")
15904 (defvar org-time-was-given) ; dynamically scoped parameter
15905 (defvar org-end-time-was-given) ; dynamically scoped parameter
15906 (defvar org-ts-what) ; dynamically scoped parameter
15908 (defun org-time-stamp (arg &optional inactive)
15909 "Prompt for a date/time and insert a time stamp.
15910 If the user specifies a time like HH:MM or if this command is
15911 called with at least one prefix argument, the time stamp contains
15912 the date and the time. Otherwise, only the date is be included.
15914 All parts of a date not specified by the user is filled in from
15915 the current date/time. So if you just press return without
15916 typing anything, the time stamp will represent the current
15917 date/time.
15919 If there is already a timestamp at the cursor, it will be
15920 modified.
15922 With two universal prefix arguments, insert an active timestamp
15923 with the current time without prompting the user."
15924 (interactive "P")
15925 (let* ((ts nil)
15926 (default-time
15927 ;; Default time is either today, or, when entering a range,
15928 ;; the range start.
15929 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15930 (save-excursion
15931 (re-search-backward
15932 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15933 (- (point) 20) t)))
15934 (apply 'encode-time (org-parse-time-string (match-string 1)))
15935 (current-time)))
15936 (default-input (and ts (org-get-compact-tod ts)))
15937 (repeater (save-excursion
15938 (save-match-data
15939 (beginning-of-line)
15940 (when (re-search-forward
15941 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15942 (save-excursion (progn (end-of-line) (point))) t)
15943 (match-string 0)))))
15944 org-time-was-given org-end-time-was-given time)
15945 (cond
15946 ((and (org-at-timestamp-p t)
15947 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15948 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15949 (insert "--")
15950 (setq time (let ((this-command this-command))
15951 (org-read-date arg 'totime nil nil
15952 default-time default-input inactive)))
15953 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15954 ((org-at-timestamp-p t)
15955 (setq time (let ((this-command this-command))
15956 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15957 (when (org-at-timestamp-p t) ; just to get the match data
15958 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15959 (replace-match "")
15960 (setq org-last-changed-timestamp
15961 (org-insert-time-stamp
15962 time (or org-time-was-given arg)
15963 inactive nil nil (list org-end-time-was-given)))
15964 (when repeater (goto-char (1- (point))) (insert " " repeater)
15965 (setq org-last-changed-timestamp
15966 (concat (substring org-last-inserted-timestamp 0 -1)
15967 " " repeater ">"))))
15968 (message "Timestamp updated"))
15969 ((equal arg '(16))
15970 (org-insert-time-stamp (current-time) t))
15972 (setq time (let ((this-command this-command))
15973 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15974 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15975 nil nil (list org-end-time-was-given))))))
15977 ;; FIXME: can we use this for something else, like computing time differences?
15978 (defun org-get-compact-tod (s)
15979 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15980 (let* ((t1 (match-string 1 s))
15981 (h1 (string-to-number (match-string 2 s)))
15982 (m1 (string-to-number (match-string 3 s)))
15983 (t2 (and (match-end 4) (match-string 5 s)))
15984 (h2 (and t2 (string-to-number (match-string 6 s))))
15985 (m2 (and t2 (string-to-number (match-string 7 s))))
15986 dh dm)
15987 (if (not t2)
15989 (setq dh (- h2 h1) dm (- m2 m1))
15990 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15991 (concat t1 "+" (number-to-string dh)
15992 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15994 (defun org-time-stamp-inactive (&optional arg)
15995 "Insert an inactive time stamp.
15996 An inactive time stamp is enclosed in square brackets instead of angle
15997 brackets. It is inactive in the sense that it does not trigger agenda entries,
15998 does not link to the calendar and cannot be changed with the S-cursor keys.
15999 So these are more for recording a certain time/date."
16000 (interactive "P")
16001 (org-time-stamp arg 'inactive))
16003 (defvar org-date-ovl (make-overlay 1 1))
16004 (overlay-put org-date-ovl 'face 'org-date-selected)
16005 (org-detach-overlay org-date-ovl)
16007 (defvar org-ans1) ; dynamically scoped parameter
16008 (defvar org-ans2) ; dynamically scoped parameter
16010 (defvar org-plain-time-of-day-regexp) ; defined below
16012 (defvar org-overriding-default-time nil) ; dynamically scoped
16013 (defvar org-read-date-overlay nil)
16014 (defvar org-dcst nil) ; dynamically scoped
16015 (defvar org-read-date-history nil)
16016 (defvar org-read-date-final-answer nil)
16017 (defvar org-read-date-analyze-futurep nil)
16018 (defvar org-read-date-analyze-forced-year nil)
16019 (defvar org-read-date-inactive)
16021 (defvar org-read-date-minibuffer-local-map
16022 (let ((map (make-sparse-keymap)))
16023 (set-keymap-parent map minibuffer-local-map)
16024 (org-defkey map (kbd ".")
16025 (lambda () (interactive)
16026 (org-eval-in-calendar '(calendar-goto-today))))
16027 (org-defkey map [(meta shift left)]
16028 (lambda () (interactive)
16029 (org-eval-in-calendar '(calendar-backward-month 1))))
16030 (org-defkey map [(meta shift right)]
16031 (lambda () (interactive)
16032 (org-eval-in-calendar '(calendar-forward-month 1))))
16033 (org-defkey map [(meta shift up)]
16034 (lambda () (interactive)
16035 (org-eval-in-calendar '(calendar-backward-year 1))))
16036 (org-defkey map [(meta shift down)]
16037 (lambda () (interactive)
16038 (org-eval-in-calendar '(calendar-forward-year 1))))
16039 (org-defkey map [?\e (shift left)]
16040 (lambda () (interactive)
16041 (org-eval-in-calendar '(calendar-backward-month 1))))
16042 (org-defkey map [?\e (shift right)]
16043 (lambda () (interactive)
16044 (org-eval-in-calendar '(calendar-forward-month 1))))
16045 (org-defkey map [?\e (shift up)]
16046 (lambda () (interactive)
16047 (org-eval-in-calendar '(calendar-backward-year 1))))
16048 (org-defkey map [?\e (shift down)]
16049 (lambda () (interactive)
16050 (org-eval-in-calendar '(calendar-forward-year 1))))
16051 (org-defkey map [(shift up)]
16052 (lambda () (interactive)
16053 (org-eval-in-calendar '(calendar-backward-week 1))))
16054 (org-defkey map [(shift down)]
16055 (lambda () (interactive)
16056 (org-eval-in-calendar '(calendar-forward-week 1))))
16057 (org-defkey map [(shift left)]
16058 (lambda () (interactive)
16059 (org-eval-in-calendar '(calendar-backward-day 1))))
16060 (org-defkey map [(shift right)]
16061 (lambda () (interactive)
16062 (org-eval-in-calendar '(calendar-forward-day 1))))
16063 (org-defkey map "!"
16064 (lambda () (interactive)
16065 (org-eval-in-calendar '(diary-view-entries))
16066 (message "")))
16067 (org-defkey map ">"
16068 (lambda () (interactive)
16069 (org-eval-in-calendar '(scroll-calendar-left 1))))
16070 (org-defkey map "<"
16071 (lambda () (interactive)
16072 (org-eval-in-calendar '(scroll-calendar-right 1))))
16073 (org-defkey map "\C-v"
16074 (lambda () (interactive)
16075 (org-eval-in-calendar
16076 '(calendar-scroll-left-three-months 1))))
16077 (org-defkey map "\M-v"
16078 (lambda () (interactive)
16079 (org-eval-in-calendar
16080 '(calendar-scroll-right-three-months 1))))
16081 map)
16082 "Keymap for minibuffer commands when using `org-read-date'.")
16084 (defun org-read-date (&optional org-with-time to-time from-string prompt
16085 default-time default-input inactive)
16086 "Read a date, possibly a time, and make things smooth for the user.
16087 The prompt will suggest to enter an ISO date, but you can also enter anything
16088 which will at least partially be understood by `parse-time-string'.
16089 Unrecognized parts of the date will default to the current day, month, year,
16090 hour and minute. If this command is called to replace a timestamp at point,
16091 or to enter the second timestamp of a range, the default time is taken
16092 from the existing stamp. Furthermore, the command prefers the future,
16093 so if you are giving a date where the year is not given, and the day-month
16094 combination is already past in the current year, it will assume you
16095 mean next year. For details, see the manual. A few examples:
16097 3-2-5 --> 2003-02-05
16098 feb 15 --> currentyear-02-15
16099 2/15 --> currentyear-02-15
16100 sep 12 9 --> 2009-09-12
16101 12:45 --> today 12:45
16102 22 sept 0:34 --> currentyear-09-22 0:34
16103 12 --> currentyear-currentmonth-12
16104 Fri --> nearest Friday (today or later)
16105 etc.
16107 Furthermore you can specify a relative date by giving, as the *first* thing
16108 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16109 change in days weeks, months, years.
16110 With a single plus or minus, the date is relative to today. With a double
16111 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16112 +4d --> four days from today
16113 +4 --> same as above
16114 +2w --> two weeks from today
16115 ++5 --> five days from default date
16117 The function understands only English month and weekday abbreviations.
16119 While prompting, a calendar is popped up - you can also select the
16120 date with the mouse (button 1). The calendar shows a period of three
16121 months. To scroll it to other months, use the keys `>' and `<'.
16122 If you don't like the calendar, turn it off with
16123 \(setq org-read-date-popup-calendar nil)
16125 With optional argument TO-TIME, the date will immediately be converted
16126 to an internal time.
16127 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16128 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16129 still enter a time, and this function will inform the calling routine
16130 about this change. The calling routine may then choose to change the
16131 format used to insert the time stamp into the buffer to include the time.
16132 With optional argument FROM-STRING, read from this string instead from
16133 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16134 the time/date that is used for everything that is not specified by the
16135 user."
16136 (require 'parse-time)
16137 (let* ((org-time-stamp-rounding-minutes
16138 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16139 (org-dcst org-display-custom-times)
16140 (ct (org-current-time))
16141 (org-def (or org-overriding-default-time default-time ct))
16142 (org-defdecode (decode-time org-def))
16143 (dummy (progn
16144 (when (< (nth 2 org-defdecode) org-extend-today-until)
16145 (setcar (nthcdr 2 org-defdecode) -1)
16146 (setcar (nthcdr 1 org-defdecode) 59)
16147 (setq org-def (apply 'encode-time org-defdecode)
16148 org-defdecode (decode-time org-def)))))
16149 (mouse-autoselect-window nil) ; Don't let the mouse jump
16150 (calendar-frame-setup nil)
16151 (calendar-setup nil)
16152 (calendar-move-hook nil)
16153 (calendar-view-diary-initially-flag nil)
16154 (calendar-view-holidays-initially-flag nil)
16155 (timestr (format-time-string
16156 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16157 (prompt (concat (if prompt (concat prompt " ") "")
16158 (format "Date+time [%s]: " timestr)))
16159 ans (org-ans0 "") org-ans1 org-ans2 final)
16161 (cond
16162 (from-string (setq ans from-string))
16163 (org-read-date-popup-calendar
16164 (save-excursion
16165 (save-window-excursion
16166 (calendar)
16167 (org-eval-in-calendar '(setq cursor-type nil) t)
16168 (unwind-protect
16169 (progn
16170 (calendar-forward-day (- (time-to-days org-def)
16171 (calendar-absolute-from-gregorian
16172 (calendar-current-date))))
16173 (org-eval-in-calendar nil t)
16174 (let* ((old-map (current-local-map))
16175 (map (copy-keymap calendar-mode-map))
16176 (minibuffer-local-map
16177 (copy-keymap org-read-date-minibuffer-local-map)))
16178 (org-defkey map (kbd "RET") 'org-calendar-select)
16179 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16180 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16181 (unwind-protect
16182 (progn
16183 (use-local-map map)
16184 (setq org-read-date-inactive inactive)
16185 (add-hook 'post-command-hook 'org-read-date-display)
16186 (setq org-ans0 (read-string prompt default-input
16187 'org-read-date-history nil))
16188 ;; org-ans0: from prompt
16189 ;; org-ans1: from mouse click
16190 ;; org-ans2: from calendar motion
16191 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16192 (remove-hook 'post-command-hook 'org-read-date-display)
16193 (use-local-map old-map)
16194 (when org-read-date-overlay
16195 (delete-overlay org-read-date-overlay)
16196 (setq org-read-date-overlay nil)))))
16197 (bury-buffer "*Calendar*")))))
16199 (t ; Naked prompt only
16200 (unwind-protect
16201 (setq ans (read-string prompt default-input
16202 'org-read-date-history timestr))
16203 (when org-read-date-overlay
16204 (delete-overlay org-read-date-overlay)
16205 (setq org-read-date-overlay nil)))))
16207 (setq final (org-read-date-analyze ans org-def org-defdecode))
16209 (when org-read-date-analyze-forced-year
16210 (message "Year was forced into %s"
16211 (if org-read-date-force-compatible-dates
16212 "compatible range (1970-2037)"
16213 "range representable on this machine"))
16214 (ding))
16216 ;; One round trip to get rid of 34th of August and stuff like that....
16217 (setq final (decode-time (apply 'encode-time final)))
16219 (setq org-read-date-final-answer ans)
16221 (if to-time
16222 (apply 'encode-time final)
16223 (if (and (boundp 'org-time-was-given) org-time-was-given)
16224 (format "%04d-%02d-%02d %02d:%02d"
16225 (nth 5 final) (nth 4 final) (nth 3 final)
16226 (nth 2 final) (nth 1 final))
16227 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16229 (defvar org-def)
16230 (defvar org-defdecode)
16231 (defvar org-with-time)
16232 (defun org-read-date-display ()
16233 "Display the current date prompt interpretation in the minibuffer."
16234 (when org-read-date-display-live
16235 (when org-read-date-overlay
16236 (delete-overlay org-read-date-overlay))
16237 (when (minibufferp (current-buffer))
16238 (save-excursion
16239 (end-of-line 1)
16240 (while (not (equal (buffer-substring
16241 (max (point-min) (- (point) 4)) (point))
16242 " "))
16243 (insert " ")))
16244 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16245 " " (or org-ans1 org-ans2)))
16246 (org-end-time-was-given nil)
16247 (f (org-read-date-analyze ans org-def org-defdecode))
16248 (fmts (if org-dcst
16249 org-time-stamp-custom-formats
16250 org-time-stamp-formats))
16251 (fmt (if (or org-with-time
16252 (and (boundp 'org-time-was-given) org-time-was-given))
16253 (cdr fmts)
16254 (car fmts)))
16255 (txt (format-time-string fmt (apply 'encode-time f)))
16256 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16257 (txt (concat "=> " txt)))
16258 (when (and org-end-time-was-given
16259 (string-match org-plain-time-of-day-regexp txt))
16260 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16261 org-end-time-was-given
16262 (substring txt (match-end 0)))))
16263 (when org-read-date-analyze-futurep
16264 (setq txt (concat txt " (=>F)")))
16265 (setq org-read-date-overlay
16266 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16267 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16269 (defun org-read-date-analyze (ans org-def org-defdecode)
16270 "Analyze the combined answer of the date prompt."
16271 ;; FIXME: cleanup and comment
16272 (let ((nowdecode (decode-time (current-time)))
16273 delta deltan deltaw deltadef year month day
16274 hour minute second wday pm h2 m2 tl wday1
16275 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16276 (setq org-read-date-analyze-futurep nil
16277 org-read-date-analyze-forced-year nil)
16278 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16279 (setq ans "+0"))
16281 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16282 (setq ans (replace-match "" t t ans)
16283 deltan (car delta)
16284 deltaw (nth 1 delta)
16285 deltadef (nth 2 delta)))
16287 ;; Check if there is an iso week date in there. If yes, store the
16288 ;; info and postpone interpreting it until the rest of the parsing
16289 ;; is done.
16290 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16291 (setq iso-year (if (match-end 1)
16292 (org-small-year-to-year
16293 (string-to-number (match-string 1 ans))))
16294 iso-weekday (if (match-end 3)
16295 (string-to-number (match-string 3 ans)))
16296 iso-week (string-to-number (match-string 2 ans)))
16297 (setq ans (replace-match "" t t ans)))
16299 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16300 (when (string-match
16301 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16302 (setq year (if (match-end 2)
16303 (string-to-number (match-string 2 ans))
16304 (progn (setq kill-year t)
16305 (string-to-number (format-time-string "%Y"))))
16306 month (string-to-number (match-string 3 ans))
16307 day (string-to-number (match-string 4 ans)))
16308 (if (< year 100) (setq year (+ 2000 year)))
16309 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16310 t nil ans)))
16312 ;; Help matching dotted european dates
16313 (when (string-match
16314 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16315 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16316 (setq kill-year t)
16317 (string-to-number (format-time-string "%Y")))
16318 day (string-to-number (match-string 1 ans))
16319 month (string-to-number (match-string 2 ans))
16320 ans (replace-match (format "%04d-%02d-%02d" year month day)
16321 t nil ans)))
16323 ;; Help matching american dates, like 5/30 or 5/30/7
16324 (when (string-match
16325 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16326 (setq year (if (match-end 4)
16327 (string-to-number (match-string 4 ans))
16328 (progn (setq kill-year t)
16329 (string-to-number (format-time-string "%Y"))))
16330 month (string-to-number (match-string 1 ans))
16331 day (string-to-number (match-string 2 ans)))
16332 (if (< year 100) (setq year (+ 2000 year)))
16333 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16334 t nil ans)))
16335 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16336 ;; If there is a time with am/pm, and *no* time without it, we convert
16337 ;; so that matching will be successful.
16338 (loop for i from 1 to 2 do ; twice, for end time as well
16339 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16340 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16341 (setq hour (string-to-number (match-string 1 ans))
16342 minute (if (match-end 3)
16343 (string-to-number (match-string 3 ans))
16345 pm (equal ?p
16346 (string-to-char (downcase (match-string 4 ans)))))
16347 (if (and (= hour 12) (not pm))
16348 (setq hour 0)
16349 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16350 (setq ans (replace-match (format "%02d:%02d" hour minute)
16351 t t ans))))
16353 ;; Check if a time range is given as a duration
16354 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16355 (setq hour (string-to-number (match-string 1 ans))
16356 h2 (+ hour (string-to-number (match-string 3 ans)))
16357 minute (string-to-number (match-string 2 ans))
16358 m2 (+ minute (if (match-end 5) (string-to-number
16359 (match-string 5 ans))0)))
16360 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16361 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16362 t t ans)))
16364 ;; Check if there is a time range
16365 (when (boundp 'org-end-time-was-given)
16366 (setq org-time-was-given nil)
16367 (when (and (string-match org-plain-time-of-day-regexp ans)
16368 (match-end 8))
16369 (setq org-end-time-was-given (match-string 8 ans))
16370 (setq ans (concat (substring ans 0 (match-beginning 7))
16371 (substring ans (match-end 7))))))
16373 (setq tl (parse-time-string ans)
16374 day (or (nth 3 tl) (nth 3 org-defdecode))
16375 month (or (nth 4 tl)
16376 (if (and org-read-date-prefer-future
16377 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16378 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16379 (nth 4 org-defdecode)))
16380 year (or (and (not kill-year) (nth 5 tl))
16381 (if (and org-read-date-prefer-future
16382 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16383 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16384 (nth 5 org-defdecode)))
16385 hour (or (nth 2 tl) (nth 2 org-defdecode))
16386 minute (or (nth 1 tl) (nth 1 org-defdecode))
16387 second (or (nth 0 tl) 0)
16388 wday (nth 6 tl))
16390 (when (and (eq org-read-date-prefer-future 'time)
16391 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16392 (equal day (nth 3 nowdecode))
16393 (equal month (nth 4 nowdecode))
16394 (equal year (nth 5 nowdecode))
16395 (nth 2 tl)
16396 (or (< (nth 2 tl) (nth 2 nowdecode))
16397 (and (= (nth 2 tl) (nth 2 nowdecode))
16398 (nth 1 tl)
16399 (< (nth 1 tl) (nth 1 nowdecode)))))
16400 (setq day (1+ day)
16401 futurep t))
16403 ;; Special date definitions below
16404 (cond
16405 (iso-week
16406 ;; There was an iso week
16407 (require 'cal-iso)
16408 (setq futurep nil)
16409 (setq year (or iso-year year)
16410 day (or iso-weekday wday 1)
16411 wday nil ; to make sure that the trigger below does not match
16412 iso-date (calendar-gregorian-from-absolute
16413 (calendar-absolute-from-iso
16414 (list iso-week day year))))
16415 ; FIXME: Should we also push ISO weeks into the future?
16416 ; (when (and org-read-date-prefer-future
16417 ; (not iso-year)
16418 ; (< (calendar-absolute-from-gregorian iso-date)
16419 ; (time-to-days (current-time))))
16420 ; (setq year (1+ year)
16421 ; iso-date (calendar-gregorian-from-absolute
16422 ; (calendar-absolute-from-iso
16423 ; (list iso-week day year)))))
16424 (setq month (car iso-date)
16425 year (nth 2 iso-date)
16426 day (nth 1 iso-date)))
16427 (deltan
16428 (setq futurep nil)
16429 (unless deltadef
16430 (let ((now (decode-time (current-time))))
16431 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16432 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16433 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16434 ((equal deltaw "m") (setq month (+ month deltan)))
16435 ((equal deltaw "y") (setq year (+ year deltan)))))
16436 ((and wday (not (nth 3 tl)))
16437 ;; Weekday was given, but no day, so pick that day in the week
16438 ;; on or after the derived date.
16439 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16440 (unless (equal wday wday1)
16441 (setq day (+ day (% (- wday wday1 -7) 7))))))
16442 (if (and (boundp 'org-time-was-given)
16443 (nth 2 tl))
16444 (setq org-time-was-given t))
16445 (if (< year 100) (setq year (+ 2000 year)))
16446 ;; Check of the date is representable
16447 (if org-read-date-force-compatible-dates
16448 (progn
16449 (if (< year 1970)
16450 (setq year 1970 org-read-date-analyze-forced-year t))
16451 (if (> year 2037)
16452 (setq year 2037 org-read-date-analyze-forced-year t)))
16453 (condition-case nil
16454 (ignore (encode-time second minute hour day month year))
16455 (error
16456 (setq year (nth 5 org-defdecode))
16457 (setq org-read-date-analyze-forced-year t))))
16458 (setq org-read-date-analyze-futurep futurep)
16459 (list second minute hour day month year)))
16461 (defvar parse-time-weekdays)
16462 (defun org-read-date-get-relative (s today default)
16463 "Check string S for special relative date string.
16464 TODAY and DEFAULT are internal times, for today and for a default.
16465 Return shift list (N what def-flag)
16466 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16467 N is the number of WHATs to shift.
16468 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16469 the DEFAULT date rather than TODAY."
16470 (require 'parse-time)
16471 (when (and
16472 (string-match
16473 (concat
16474 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16475 "\\([0-9]+\\)?"
16476 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16477 "\\([ \t]\\|$\\)") s)
16478 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16479 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16480 (string-to-char (substring (match-string 1 s) -1))
16481 ?+))
16482 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16483 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16484 (what (if (match-end 3) (match-string 3 s) "d"))
16485 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16486 (date (if rel default today))
16487 (wday (nth 6 (decode-time date)))
16488 delta)
16489 (if wday1
16490 (progn
16491 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16492 (if (= dir ?-) (setq delta (- delta 7)))
16493 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16494 (list delta "d" rel))
16495 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16497 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16498 "Turn a user-specified date into the internal representation.
16499 The internal representation needed by the calendar is (month day year).
16500 This is a wrapper to handle the brain-dead convention in calendar that
16501 user function argument order change dependent on argument order."
16502 (if (boundp 'calendar-date-style)
16503 (cond
16504 ((eq calendar-date-style 'american)
16505 (list arg1 arg2 arg3))
16506 ((eq calendar-date-style 'european)
16507 (list arg2 arg1 arg3))
16508 ((eq calendar-date-style 'iso)
16509 (list arg2 arg3 arg1)))
16510 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16511 (if (org-bound-and-true-p european-calendar-style)
16512 (list arg2 arg1 arg3)
16513 (list arg1 arg2 arg3)))))
16515 (defun org-eval-in-calendar (form &optional keepdate)
16516 "Eval FORM in the calendar window and return to current window.
16517 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16518 otherwise stick to the current value of `org-ans2'."
16519 (let ((sf (selected-frame))
16520 (sw (selected-window)))
16521 (select-window (get-buffer-window "*Calendar*" t))
16522 (eval form)
16523 (when (and (not keepdate) (calendar-cursor-to-date))
16524 (let* ((date (calendar-cursor-to-date))
16525 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16526 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16527 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16528 (select-window sw)
16529 (org-select-frame-set-input-focus sf)))
16531 (defun org-calendar-select ()
16532 "Return to `org-read-date' with the date currently selected.
16533 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16534 (interactive)
16535 (when (calendar-cursor-to-date)
16536 (let* ((date (calendar-cursor-to-date))
16537 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16538 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16539 (if (active-minibuffer-window) (exit-minibuffer))))
16541 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16542 "Insert a date stamp for the date given by the internal TIME.
16543 WITH-HM means use the stamp format that includes the time of the day.
16544 INACTIVE means use square brackets instead of angular ones, so that the
16545 stamp will not contribute to the agenda.
16546 PRE and POST are optional strings to be inserted before and after the
16547 stamp.
16548 The command returns the inserted time stamp."
16549 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16550 stamp)
16551 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16552 (insert-before-markers (or pre ""))
16553 (when (listp extra)
16554 (setq extra (car extra))
16555 (if (and (stringp extra)
16556 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16557 (setq extra (format "-%02d:%02d"
16558 (string-to-number (match-string 1 extra))
16559 (string-to-number (match-string 2 extra))))
16560 (setq extra nil)))
16561 (when extra
16562 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16563 (insert-before-markers (setq stamp (format-time-string fmt time)))
16564 (insert-before-markers (or post ""))
16565 (setq org-last-inserted-timestamp stamp)))
16567 (defun org-toggle-time-stamp-overlays ()
16568 "Toggle the use of custom time stamp formats."
16569 (interactive)
16570 (setq org-display-custom-times (not org-display-custom-times))
16571 (unless org-display-custom-times
16572 (let ((p (point-min)) (bmp (buffer-modified-p)))
16573 (while (setq p (next-single-property-change p 'display))
16574 (if (and (get-text-property p 'display)
16575 (eq (get-text-property p 'face) 'org-date))
16576 (remove-text-properties
16577 p (setq p (next-single-property-change p 'display))
16578 '(display t))))
16579 (set-buffer-modified-p bmp)))
16580 (if (featurep 'xemacs)
16581 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16582 (org-restart-font-lock)
16583 (setq org-table-may-need-update t)
16584 (if org-display-custom-times
16585 (message "Time stamps are overlaid with custom format")
16586 (message "Time stamp overlays removed")))
16588 (defun org-display-custom-time (beg end)
16589 "Overlay modified time stamp format over timestamp between BEG and END."
16590 (let* ((ts (buffer-substring beg end))
16591 t1 w1 with-hm tf time str w2 (off 0))
16592 (save-match-data
16593 (setq t1 (org-parse-time-string ts t))
16594 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16595 (setq off (- (match-end 0) (match-beginning 0)))))
16596 (setq end (- end off))
16597 (setq w1 (- end beg)
16598 with-hm (and (nth 1 t1) (nth 2 t1))
16599 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16600 time (org-fix-decoded-time t1)
16601 str (org-add-props
16602 (format-time-string
16603 (substring tf 1 -1) (apply 'encode-time time))
16604 nil 'mouse-face 'highlight)
16605 w2 (length str))
16606 (if (not (= w2 w1))
16607 (add-text-properties (1+ beg) (+ 2 beg)
16608 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16609 (if (featurep 'xemacs)
16610 (progn
16611 (put-text-property beg end 'invisible t)
16612 (put-text-property beg end 'end-glyph (make-glyph str)))
16613 (put-text-property beg end 'display str))))
16615 (defun org-translate-time (string)
16616 "Translate all timestamps in STRING to custom format.
16617 But do this only if the variable `org-display-custom-times' is set."
16618 (when org-display-custom-times
16619 (save-match-data
16620 (let* ((start 0)
16621 (re org-ts-regexp-both)
16622 t1 with-hm inactive tf time str beg end)
16623 (while (setq start (string-match re string start))
16624 (setq beg (match-beginning 0)
16625 end (match-end 0)
16626 t1 (save-match-data
16627 (org-parse-time-string (substring string beg end) t))
16628 with-hm (and (nth 1 t1) (nth 2 t1))
16629 inactive (equal (substring string beg (1+ beg)) "[")
16630 tf (funcall (if with-hm 'cdr 'car)
16631 org-time-stamp-custom-formats)
16632 time (org-fix-decoded-time t1)
16633 str (format-time-string
16634 (concat
16635 (if inactive "[" "<") (substring tf 1 -1)
16636 (if inactive "]" ">"))
16637 (apply 'encode-time time))
16638 string (replace-match str t t string)
16639 start (+ start (length str)))))))
16640 string)
16642 (defun org-fix-decoded-time (time)
16643 "Set 0 instead of nil for the first 6 elements of time.
16644 Don't touch the rest."
16645 (let ((n 0))
16646 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16648 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16650 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16651 "Difference between TIMESTAMP-STRING and now in days.
16652 If SECONDS is non-nil, return the difference in seconds."
16653 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16654 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16655 (funcall fdiff (current-time)))))
16657 (defun org-deadline-close (timestamp-string &optional ndays)
16658 "Is the time in TIMESTAMP-STRING close to the current date?"
16659 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16660 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16661 (not (org-entry-is-done-p))))
16663 (defun org-get-wdays (ts &optional delay zero-delay)
16664 "Get the deadline lead time appropriate for timestring TS.
16665 When DELAY is non-nil, get the delay time for scheduled items
16666 instead of the deadline lead time. When ZERO-DELAY is non-nil
16667 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16668 don't try to find the delay cookie in the scheduled timestamp."
16669 (let ((tv (if delay org-scheduled-delay-days
16670 org-deadline-warning-days)))
16671 (cond
16672 ((or (and delay (< tv 0))
16673 (and delay zero-delay (<= tv 0))
16674 (and (not delay) (<= tv 0)))
16675 ;; Enforce this value no matter what
16676 (- tv))
16677 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16678 ;; lead time is specified.
16679 (floor (* (string-to-number (match-string 1 ts))
16680 (cdr (assoc (match-string 2 ts)
16681 '(("d" . 1) ("w" . 7)
16682 ("m" . 30.4) ("y" . 365.25)
16683 ("h" . 0.041667)))))))
16684 ;; go for the default.
16685 (t tv))))
16687 (defun org-calendar-select-mouse (ev)
16688 "Return to `org-read-date' with the date currently selected.
16689 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16690 (interactive "e")
16691 (mouse-set-point ev)
16692 (when (calendar-cursor-to-date)
16693 (let* ((date (calendar-cursor-to-date))
16694 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16695 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16696 (if (active-minibuffer-window) (exit-minibuffer))))
16698 (defun org-check-deadlines (ndays)
16699 "Check if there are any deadlines due or past due.
16700 A deadline is considered due if it happens within `org-deadline-warning-days'
16701 days from today's date. If the deadline appears in an entry marked DONE,
16702 it is not shown. The prefix arg NDAYS can be used to test that many
16703 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16704 (interactive "P")
16705 (let* ((org-warn-days
16706 (cond
16707 ((equal ndays '(4)) 100000)
16708 (ndays (prefix-numeric-value ndays))
16709 (t (abs org-deadline-warning-days))))
16710 (case-fold-search nil)
16711 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16712 (callback
16713 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16715 (message "%d deadlines past-due or due within %d days"
16716 (org-occur regexp nil callback)
16717 org-warn-days)))
16719 (defsubst org-re-timestamp (type)
16720 "Return a regexp for timestamp TYPE.
16721 Allowed values for TYPE are:
16723 all: all timestamps
16724 active: only active timestamps (<...>)
16725 inactive: only inactive timestamps ([...])
16726 scheduled: only scheduled timestamps
16727 deadline: only deadline timestamps
16729 When TYPE is nil, fall back on returning a regexp that matches
16730 both scheduled and deadline timestamps."
16731 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16732 ((eq type 'active) org-ts-regexp)
16733 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16734 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16735 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16736 ((eq type 'scheduled-or-deadline)
16737 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16739 (defun org-check-before-date (date)
16740 "Check if there are deadlines or scheduled entries before DATE."
16741 (interactive (list (org-read-date)))
16742 (let ((case-fold-search nil)
16743 (regexp (org-re-timestamp org-ts-type))
16744 (callback
16745 (lambda () (time-less-p
16746 (org-time-string-to-time (match-string 1))
16747 (org-time-string-to-time date)))))
16748 (message "%d entries before %s"
16749 (org-occur regexp nil callback) date)))
16751 (defun org-check-after-date (date)
16752 "Check if there are deadlines or scheduled entries after DATE."
16753 (interactive (list (org-read-date)))
16754 (let ((case-fold-search nil)
16755 (regexp (org-re-timestamp org-ts-type))
16756 (callback
16757 (lambda () (not
16758 (time-less-p
16759 (org-time-string-to-time (match-string 1))
16760 (org-time-string-to-time date))))))
16761 (message "%d entries after %s"
16762 (org-occur regexp nil callback) date)))
16764 (defun org-check-dates-range (start-date end-date)
16765 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16766 (interactive (list (org-read-date nil nil nil "Range starts")
16767 (org-read-date nil nil nil "Range end")))
16768 (let ((case-fold-search nil)
16769 (regexp (org-re-timestamp org-ts-type))
16770 (callback
16771 (lambda ()
16772 (let ((match (match-string 1)))
16773 (and
16774 (not (time-less-p
16775 (org-time-string-to-time match)
16776 (org-time-string-to-time start-date)))
16777 (time-less-p
16778 (org-time-string-to-time match)
16779 (org-time-string-to-time end-date)))))))
16780 (message "%d entries between %s and %s"
16781 (org-occur regexp nil callback) start-date end-date)))
16783 (defun org-evaluate-time-range (&optional to-buffer)
16784 "Evaluate a time range by computing the difference between start and end.
16785 Normally the result is just printed in the echo area, but with prefix arg
16786 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16787 If the time range is actually in a table, the result is inserted into the
16788 next column.
16789 For time difference computation, a year is assumed to be exactly 365
16790 days in order to avoid rounding problems."
16791 (interactive "P")
16793 (org-clock-update-time-maybe)
16794 (save-excursion
16795 (unless (org-at-date-range-p t)
16796 (goto-char (point-at-bol))
16797 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16798 (if (not (org-at-date-range-p t))
16799 (error "Not at a time-stamp range, and none found in current line")))
16800 (let* ((ts1 (match-string 1))
16801 (ts2 (match-string 2))
16802 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16803 (match-end (match-end 0))
16804 (time1 (org-time-string-to-time ts1))
16805 (time2 (org-time-string-to-time ts2))
16806 (t1 (org-float-time time1))
16807 (t2 (org-float-time time2))
16808 (diff (abs (- t2 t1)))
16809 (negative (< (- t2 t1) 0))
16810 ;; (ys (floor (* 365 24 60 60)))
16811 (ds (* 24 60 60))
16812 (hs (* 60 60))
16813 (fy "%dy %dd %02d:%02d")
16814 (fy1 "%dy %dd")
16815 (fd "%dd %02d:%02d")
16816 (fd1 "%dd")
16817 (fh "%02d:%02d")
16818 y d h m align)
16819 (if havetime
16820 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16822 d (floor (/ diff ds)) diff (mod diff ds)
16823 h (floor (/ diff hs)) diff (mod diff hs)
16824 m (floor (/ diff 60)))
16825 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16827 d (floor (+ (/ diff ds) 0.5))
16828 h 0 m 0))
16829 (if (not to-buffer)
16830 (message "%s" (org-make-tdiff-string y d h m))
16831 (if (org-at-table-p)
16832 (progn
16833 (goto-char match-end)
16834 (setq align t)
16835 (and (looking-at " *|") (goto-char (match-end 0))))
16836 (goto-char match-end))
16837 (if (looking-at
16838 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16839 (replace-match ""))
16840 (if negative (insert " -"))
16841 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16842 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16843 (insert " " (format fh h m))))
16844 (if align (org-table-align))
16845 (message "Time difference inserted")))))
16847 (defun org-make-tdiff-string (y d h m)
16848 (let ((fmt "")
16849 (l nil))
16850 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16851 l (push y l)))
16852 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16853 l (push d l)))
16854 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16855 l (push h l)))
16856 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16857 l (push m l)))
16858 (apply 'format fmt (nreverse l))))
16860 (defun org-time-string-to-time (s &optional buffer pos)
16861 "Convert a timestamp string into internal time."
16862 (condition-case errdata
16863 (apply 'encode-time (org-parse-time-string s))
16864 (error (error "Bad timestamp `%s'%s\nError was: %s"
16865 s (if (not (and buffer pos))
16867 (format " at %d in buffer `%s'" pos buffer))
16868 (cdr errdata)))))
16870 (defun org-time-string-to-seconds (s)
16871 "Convert a timestamp string to a number of seconds."
16872 (org-float-time (org-time-string-to-time s)))
16874 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16875 "Convert a time stamp to an absolute day number.
16876 If there is a specifier for a cyclic time stamp, get the closest
16877 date to DAYNR.
16878 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16879 The variable `date' is bound by the calendar when this is called."
16880 (cond
16881 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16882 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16883 daynr
16884 (+ daynr 1000)))
16885 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16886 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16887 (time-to-days (current-time))) (match-string 0 s)
16888 prefer show-all))
16889 (t (time-to-days
16890 (condition-case errdata
16891 (apply 'encode-time (org-parse-time-string s))
16892 (error (error "Bad timestamp `%s'%s\nError was: %s"
16893 s (if (not (and buffer pos))
16895 (format " at %d in buffer `%s'" pos buffer))
16896 (cdr errdata))))))))
16898 (defun org-days-to-iso-week (days)
16899 "Return the iso week number."
16900 (require 'cal-iso)
16901 (car (calendar-iso-from-absolute days)))
16903 (defun org-small-year-to-year (year)
16904 "Convert 2-digit years into 4-digit years.
16905 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16906 The year 2000 cannot be abbreviated. Any year larger than 99
16907 is returned unchanged."
16908 (if (< year 38)
16909 (setq year (+ 2000 year))
16910 (if (< year 100)
16911 (setq year (+ 1900 year))))
16912 year)
16914 (defun org-time-from-absolute (d)
16915 "Return the time corresponding to date D.
16916 D may be an absolute day number, or a calendar-type list (month day year)."
16917 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16918 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16920 (defun org-calendar-holiday ()
16921 "List of holidays, for Diary display in Org-mode."
16922 (require 'holidays)
16923 (let ((hl (funcall
16924 (if (fboundp 'calendar-check-holidays)
16925 'calendar-check-holidays 'check-calendar-holidays) date)))
16926 (if hl (mapconcat 'identity hl "; "))))
16928 (defun org-diary-sexp-entry (sexp entry date)
16929 "Process a SEXP diary ENTRY for DATE."
16930 (require 'diary-lib)
16931 (let ((result (if calendar-debug-sexp
16932 (let ((stack-trace-on-error t))
16933 (eval (car (read-from-string sexp))))
16934 (condition-case nil
16935 (eval (car (read-from-string sexp)))
16936 (error
16937 (beep)
16938 (message "Bad sexp at line %d in %s: %s"
16939 (org-current-line)
16940 (buffer-file-name) sexp)
16941 (sleep-for 2))))))
16942 (cond ((stringp result) (split-string result "; "))
16943 ((and (consp result)
16944 (not (consp (cdr result)))
16945 (stringp (cdr result))) (cdr result))
16946 ((and (consp result)
16947 (stringp (car result))) result)
16948 (result entry))))
16950 (defun org-diary-to-ical-string (frombuf)
16951 "Get iCalendar entries from diary entries in buffer FROMBUF.
16952 This uses the icalendar.el library."
16953 (let* ((tmpdir (if (featurep 'xemacs)
16954 (temp-directory)
16955 temporary-file-directory))
16956 (tmpfile (make-temp-name
16957 (expand-file-name "orgics" tmpdir)))
16958 buf rtn b e)
16959 (with-current-buffer frombuf
16960 (icalendar-export-region (point-min) (point-max) tmpfile)
16961 (setq buf (find-buffer-visiting tmpfile))
16962 (set-buffer buf)
16963 (goto-char (point-min))
16964 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16965 (setq b (match-beginning 0)))
16966 (goto-char (point-max))
16967 (if (re-search-backward "^END:VEVENT" nil t)
16968 (setq e (match-end 0)))
16969 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16970 (kill-buffer buf)
16971 (delete-file tmpfile)
16972 rtn))
16974 (defun org-closest-date (start current change prefer show-all)
16975 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16976 When PREFER is `past', return a date that is either CURRENT or past.
16977 When PREFER is `future', return a date that is either CURRENT or future.
16978 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16979 ;; Make the proper lists from the dates
16980 (catch 'exit
16981 (let ((a1 '(("h" . hour)
16982 ("d" . day)
16983 ("w" . week)
16984 ("m" . month)
16985 ("y" . year)))
16986 (shour (nth 2 (org-parse-time-string start)))
16987 dn dw sday cday n1 n2 n0
16988 d m y y1 y2 date1 date2 nmonths nm ny m2)
16990 (setq start (org-date-to-gregorian start)
16991 current (org-date-to-gregorian
16992 (if show-all
16993 current
16994 (time-to-days (current-time))))
16995 sday (calendar-absolute-from-gregorian start)
16996 cday (calendar-absolute-from-gregorian current))
16998 (if (<= cday sday) (throw 'exit sday))
17000 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17001 (setq dn (string-to-number (match-string 1 change))
17002 dw (cdr (assoc (match-string 2 change) a1)))
17003 (error "Invalid change specifier: %s" change))
17004 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17005 (cond
17006 ((eq dw 'hour)
17007 (let ((missing-hours
17008 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17009 dn)))
17010 (setq n1 (if (zerop missing-hours) cday
17011 (- cday (1+ (floor (/ missing-hours 24)))))
17012 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17013 ((eq dw 'day)
17014 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17015 n2 (+ n1 dn)))
17016 ((eq dw 'year)
17017 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17018 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17019 (setq date1 (list m d y1)
17020 n1 (calendar-absolute-from-gregorian date1)
17021 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17022 n2 (calendar-absolute-from-gregorian date2)))
17023 ((eq dw 'month)
17024 ;; approx number of month between the two dates
17025 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17026 ;; How often does dn fit in there?
17027 (setq d (nth 1 start) m (car start) y (nth 2 start)
17028 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17029 m (+ m nm)
17030 ny (floor (/ m 12))
17031 y (+ y ny)
17032 m (- m (* ny 12)))
17033 (while (> m 12) (setq m (- m 12) y (1+ y)))
17034 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17035 (setq m2 (+ m dn) y2 y)
17036 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17037 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17038 (while (<= n2 cday)
17039 (setq n1 n2 m m2 y y2)
17040 (setq m2 (+ m dn) y2 y)
17041 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17042 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17043 ;; Make sure n1 is the earlier date
17044 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17045 (if show-all
17046 (cond
17047 ((eq prefer 'past) (if (= cday n2) n2 n1))
17048 ((eq prefer 'future) (if (= cday n1) n1 n2))
17049 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17050 (cond
17051 ((eq prefer 'past) (if (= cday n2) n2 n1))
17052 ((eq prefer 'future) (if (= cday n1) n1 n2))
17053 (t (if (= cday n1) n1 n2)))))))
17055 (defun org-date-to-gregorian (date)
17056 "Turn any specification of DATE into a Gregorian date for the calendar."
17057 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17058 ((and (listp date) (= (length date) 3)) date)
17059 ((stringp date)
17060 (setq date (org-parse-time-string date))
17061 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17062 ((listp date)
17063 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17065 (defun org-parse-time-string (s &optional nodefault)
17066 "Parse the standard Org-mode time string.
17067 This should be a lot faster than the normal `parse-time-string'.
17068 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17069 hour and minute fields will be nil if not given."
17070 (cond ((string-match org-ts-regexp0 s)
17071 (list 0
17072 (if (or (match-beginning 8) (not nodefault))
17073 (string-to-number (or (match-string 8 s) "0")))
17074 (if (or (match-beginning 7) (not nodefault))
17075 (string-to-number (or (match-string 7 s) "0")))
17076 (string-to-number (match-string 4 s))
17077 (string-to-number (match-string 3 s))
17078 (string-to-number (match-string 2 s))
17079 nil nil nil))
17080 ((string-match "^<[^>]+>$" s)
17081 (decode-time (seconds-to-time (org-matcher-time s))))
17082 (t (error "Not a standard Org-mode time string: %s" s))))
17084 (defun org-timestamp-up (&optional arg)
17085 "Increase the date item at the cursor by one.
17086 If the cursor is on the year, change the year. If it is on the month,
17087 the day or the time, change that.
17088 With prefix ARG, change by that many units."
17089 (interactive "p")
17090 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17092 (defun org-timestamp-down (&optional arg)
17093 "Decrease the date item at the cursor by one.
17094 If the cursor is on the year, change the year. If it is on the month,
17095 the day or the time, change that.
17096 With prefix ARG, change by that many units."
17097 (interactive "p")
17098 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17100 (defun org-timestamp-up-day (&optional arg)
17101 "Increase the date in the time stamp by one day.
17102 With prefix ARG, change that many days."
17103 (interactive "p")
17104 (if (and (not (org-at-timestamp-p t))
17105 (org-at-heading-p))
17106 (org-todo 'up)
17107 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17109 (defun org-timestamp-down-day (&optional arg)
17110 "Decrease the date in the time stamp by one day.
17111 With prefix ARG, change that many days."
17112 (interactive "p")
17113 (if (and (not (org-at-timestamp-p t))
17114 (org-at-heading-p))
17115 (org-todo 'down)
17116 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17118 (defun org-at-timestamp-p (&optional inactive-ok)
17119 "Determine if the cursor is in or at a timestamp."
17120 (interactive)
17121 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17122 (pos (point))
17123 (ans (or (looking-at tsr)
17124 (save-excursion
17125 (skip-chars-backward "^[<\n\r\t")
17126 (if (> (point) (point-min)) (backward-char 1))
17127 (and (looking-at tsr)
17128 (> (- (match-end 0) pos) -1))))))
17129 (and ans
17130 (boundp 'org-ts-what)
17131 (setq org-ts-what
17132 (cond
17133 ((= pos (match-beginning 0)) 'bracket)
17134 ;; Point is considered to be "on the bracket" whether
17135 ;; it's really on it or right after it.
17136 ((= pos (1- (match-end 0))) 'bracket)
17137 ((= pos (match-end 0)) 'after)
17138 ((org-pos-in-match-range pos 2) 'year)
17139 ((org-pos-in-match-range pos 3) 'month)
17140 ((org-pos-in-match-range pos 7) 'hour)
17141 ((org-pos-in-match-range pos 8) 'minute)
17142 ((or (org-pos-in-match-range pos 4)
17143 (org-pos-in-match-range pos 5)) 'day)
17144 ((and (> pos (or (match-end 8) (match-end 5)))
17145 (< pos (match-end 0)))
17146 (- pos (or (match-end 8) (match-end 5))))
17147 (t 'day))))
17148 ans))
17150 (defun org-toggle-timestamp-type ()
17151 "Toggle the type (<active> or [inactive]) of a time stamp."
17152 (interactive)
17153 (when (org-at-timestamp-p t)
17154 (let ((beg (match-beginning 0)) (end (match-end 0))
17155 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17156 (save-excursion
17157 (goto-char beg)
17158 (while (re-search-forward "[][<>]" end t)
17159 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17160 t t)))
17161 (message "Timestamp is now %sactive"
17162 (if (equal (char-after beg) ?<) "" "in")))))
17164 (defun org-at-clock-log-p nil
17165 "Is the cursor on the clock log line?"
17166 (save-excursion
17167 (move-beginning-of-line 1)
17168 (looking-at "^[ \t]*CLOCK:")))
17170 (defvar org-clock-history) ; defined in org-clock.el
17171 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17172 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17173 "Change the date in the time stamp at point.
17174 The date will be changed by N times WHAT. WHAT can be `day', `month',
17175 `year', `minute', `second'. If WHAT is not given, the cursor position
17176 in the timestamp determines what will be changed.
17177 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17178 (let ((origin (point)) origin-cat
17179 with-hm inactive
17180 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17181 org-ts-what
17182 extra rem
17183 ts time time0 fixnext clrgx)
17184 (if (not (org-at-timestamp-p t))
17185 (error "Not at a timestamp"))
17186 (if (and (not what) (eq org-ts-what 'bracket))
17187 (org-toggle-timestamp-type)
17188 ;; Point isn't on brackets. Remember the part of the time-stamp
17189 ;; the point was in. Indeed, size of time-stamps may change,
17190 ;; but point must be kept in the same category nonetheless.
17191 (setq origin-cat org-ts-what)
17192 (if (and (not what) (not (eq org-ts-what 'day))
17193 org-display-custom-times
17194 (get-text-property (point) 'display)
17195 (not (get-text-property (1- (point)) 'display)))
17196 (setq org-ts-what 'day))
17197 (setq org-ts-what (or what org-ts-what)
17198 inactive (= (char-after (match-beginning 0)) ?\[)
17199 ts (match-string 0))
17200 (replace-match "")
17201 (when (string-match
17202 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17204 (setq extra (match-string 1 ts))
17205 (if suppress-tmp-delay
17206 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17207 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17208 (setq with-hm t))
17209 (setq time0 (org-parse-time-string ts))
17210 (when (and updown
17211 (eq org-ts-what 'minute)
17212 (not current-prefix-arg))
17213 ;; This looks like s-up and s-down. Change by one rounding step.
17214 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17215 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17216 (setcar (cdr time0) (+ (nth 1 time0)
17217 (if (> n 0) (- rem) (- dm rem))))))
17218 (setq time
17219 (encode-time (or (car time0) 0)
17220 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17221 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17222 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17223 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17224 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17225 (nthcdr 6 time0)))
17226 (when (and (member org-ts-what '(hour minute))
17227 extra
17228 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17229 (setq extra (org-modify-ts-extra
17230 extra
17231 (if (eq org-ts-what 'hour) 2 5)
17232 n dm)))
17233 (when (integerp org-ts-what)
17234 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17235 (if (eq what 'calendar)
17236 (let ((cal-date (org-get-date-from-calendar)))
17237 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17238 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17239 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17240 (setcar time0 (or (car time0) 0))
17241 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17242 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17243 (setq time (apply 'encode-time time0))))
17244 ;; Insert the new time-stamp, and ensure point stays in the same
17245 ;; category as before (i.e. not after the last position in that
17246 ;; category).
17247 (let ((pos (point)))
17248 ;; Stay before inserted string. `save-excursion' is of no use.
17249 (setq org-last-changed-timestamp
17250 (org-insert-time-stamp time with-hm inactive nil nil extra))
17251 (goto-char pos))
17252 (save-match-data
17253 (looking-at org-ts-regexp3)
17254 (goto-char (cond
17255 ;; `day' category ends before `hour' if any, or at
17256 ;; the end of the day name.
17257 ((eq origin-cat 'day)
17258 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17259 ((eq origin-cat 'hour) (min (match-end 7) origin))
17260 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17261 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17262 ;; `year' and `month' have both fixed size: point
17263 ;; couldn't have moved into another part.
17264 (t origin))))
17265 ;; Update clock if on a CLOCK line.
17266 (org-clock-update-time-maybe)
17267 ;; Maybe adjust the closest clock in `org-clock-history'
17268 (when org-clock-adjust-closest
17269 (if (not (and (org-at-clock-log-p)
17270 (< 1 (length (delq nil (mapcar 'marker-position
17271 org-clock-history))))))
17272 (message "No clock to adjust")
17273 (cond ((save-excursion ; fix previous clock?
17274 (re-search-backward org-ts-regexp0 nil t)
17275 (org-looking-back (concat org-clock-string " \\[")))
17276 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17277 ((save-excursion ; fix next clock?
17278 (re-search-backward org-ts-regexp0 nil t)
17279 (looking-at (concat org-ts-regexp0 "\\] =>")))
17280 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17281 (save-window-excursion
17282 ;; Find closest clock to point, adjust the previous/next one in history
17283 (let* ((p (save-excursion (org-back-to-heading t)))
17284 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17285 (clfixnth
17286 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17287 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17288 (if (not clfixpos)
17289 (message "No clock to adjust")
17290 (save-excursion
17291 (org-goto-marker-or-bmk clfixpos)
17292 (org-show-subtree)
17293 (when (re-search-forward clrgx nil t)
17294 (goto-char (match-beginning 1))
17295 (let (org-clock-adjust-closest)
17296 (org-timestamp-change n org-ts-what updown))
17297 (message "Clock adjusted in %s for heading: %s"
17298 (file-name-nondirectory (buffer-file-name))
17299 (org-get-heading t t)))))))))
17300 ;; Try to recenter the calendar window, if any.
17301 (if (and org-calendar-follow-timestamp-change
17302 (get-buffer-window "*Calendar*" t)
17303 (memq org-ts-what '(day month year)))
17304 (org-recenter-calendar (time-to-days time))))))
17306 (defun org-modify-ts-extra (s pos n dm)
17307 "Change the different parts of the lead-time and repeat fields in timestamp."
17308 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17309 ng h m new rem)
17310 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17311 (cond
17312 ((or (org-pos-in-match-range pos 2)
17313 (org-pos-in-match-range pos 3))
17314 (setq m (string-to-number (match-string 3 s))
17315 h (string-to-number (match-string 2 s)))
17316 (if (org-pos-in-match-range pos 2)
17317 (setq h (+ h n))
17318 (setq n (* dm (org-no-warnings (signum n))))
17319 (when (not (= 0 (setq rem (% m dm))))
17320 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17321 (setq m (+ m n)))
17322 (if (< m 0) (setq m (+ m 60) h (1- h)))
17323 (if (> m 59) (setq m (- m 60) h (1+ h)))
17324 (setq h (min 24 (max 0 h)))
17325 (setq ng 1 new (format "-%02d:%02d" h m)))
17326 ((org-pos-in-match-range pos 6)
17327 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17328 ((org-pos-in-match-range pos 5)
17329 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17331 ((org-pos-in-match-range pos 9)
17332 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17333 ((org-pos-in-match-range pos 8)
17334 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17336 (when ng
17337 (setq s (concat
17338 (substring s 0 (match-beginning ng))
17340 (substring s (match-end ng))))))
17343 (defun org-recenter-calendar (date)
17344 "If the calendar is visible, recenter it to DATE."
17345 (let ((cwin (get-buffer-window "*Calendar*" t)))
17346 (when cwin
17347 (let ((calendar-move-hook nil))
17348 (with-selected-window cwin
17349 (calendar-goto-date (if (listp date) date
17350 (calendar-gregorian-from-absolute date))))))))
17352 (defun org-goto-calendar (&optional arg)
17353 "Go to the Emacs calendar at the current date.
17354 If there is a time stamp in the current line, go to that date.
17355 A prefix ARG can be used to force the current date."
17356 (interactive "P")
17357 (let ((tsr org-ts-regexp) diff
17358 (calendar-move-hook nil)
17359 (calendar-view-holidays-initially-flag nil)
17360 (calendar-view-diary-initially-flag nil))
17361 (if (or (org-at-timestamp-p)
17362 (save-excursion
17363 (beginning-of-line 1)
17364 (looking-at (concat ".*" tsr))))
17365 (let ((d1 (time-to-days (current-time)))
17366 (d2 (time-to-days
17367 (org-time-string-to-time (match-string 1)))))
17368 (setq diff (- d2 d1))))
17369 (calendar)
17370 (calendar-goto-today)
17371 (if (and diff (not arg)) (calendar-forward-day diff))))
17373 (defun org-get-date-from-calendar ()
17374 "Return a list (month day year) of date at point in calendar."
17375 (with-current-buffer "*Calendar*"
17376 (save-match-data
17377 (calendar-cursor-to-date))))
17379 (defun org-date-from-calendar ()
17380 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17381 If there is already a time stamp at the cursor position, update it."
17382 (interactive)
17383 (if (org-at-timestamp-p t)
17384 (org-timestamp-change 0 'calendar)
17385 (let ((cal-date (org-get-date-from-calendar)))
17386 (org-insert-time-stamp
17387 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17389 (defcustom org-effort-durations
17390 `(("h" . 60)
17391 ("d" . ,(* 60 8))
17392 ("w" . ,(* 60 8 5))
17393 ("m" . ,(* 60 8 5 4))
17394 ("y" . ,(* 60 8 5 40)))
17395 "Conversion factor to minutes for an effort modifier.
17397 Each entry has the form (MODIFIER . MINUTES).
17399 In an effort string, a number followed by MODIFIER is multiplied
17400 by the specified number of MINUTES to obtain an effort in
17401 minutes.
17403 For example, if the value of this variable is ((\"hours\" . 60)), then an
17404 effort string \"2hours\" is equivalent to 120 minutes."
17405 :group 'org-agenda
17406 :version "24.1"
17407 :type '(alist :key-type (string :tag "Modifier")
17408 :value-type (number :tag "Minutes")))
17410 (defun org-minutes-to-clocksum-string (m)
17411 "Format number of minutes as a clocksum string.
17412 The format is determined by `org-time-clocksum-format',
17413 `org-time-clocksum-use-fractional' and
17414 `org-time-clocksum-fractional-format' and
17415 `org-time-clocksum-use-effort-durations'."
17416 (let ((clocksum "") h d w mo y fmt n)
17417 (setq h (if org-time-clocksum-use-effort-durations
17418 (cdr (assoc "h" org-effort-durations)) 60)
17419 d (if org-time-clocksum-use-effort-durations
17420 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17421 w (if org-time-clocksum-use-effort-durations
17422 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17423 mo (if org-time-clocksum-use-effort-durations
17424 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17425 y (if org-time-clocksum-use-effort-durations
17426 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17427 ;; fractional format
17428 (if org-time-clocksum-use-fractional
17429 (cond
17430 ;; single format string
17431 ((stringp org-time-clocksum-fractional-format)
17432 (format org-time-clocksum-fractional-format (/ m (float h))))
17433 ;; choice of fractional formats for different time units
17434 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17435 (> (/ (truncate m) (* y d h)) 0))
17436 (format fmt (/ m (* y d (float h)))))
17437 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17438 (> (/ (truncate m) (* mo d h)) 0))
17439 (format fmt (/ m (* mo d (float h)))))
17440 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17441 (> (/ (truncate m) (* w d h)) 0))
17442 (format fmt (/ m (* w d (float h)))))
17443 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17444 (> (/ (truncate m) (* d h)) 0))
17445 (format fmt (/ m (* d (float h)))))
17446 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17447 (> (/ (truncate m) h) 0))
17448 (format fmt (/ m (float h))))
17449 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17450 (format fmt m))
17451 ;; fall back to smallest time unit with a format
17452 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17453 (format fmt (/ m (float h))))
17454 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17455 (format fmt (/ m (* d (float h)))))
17456 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17457 (format fmt (/ m (* w d (float h)))))
17458 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17459 (format fmt (/ m (* mo d (float h)))))
17460 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17461 (format fmt (/ m (* y d (float h))))))
17462 ;; standard (non-fractional) format, with single format string
17463 (if (stringp org-time-clocksum-format)
17464 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17465 ;; separate formats components
17466 (and (setq fmt (plist-get org-time-clocksum-format :years))
17467 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17468 (plist-get org-time-clocksum-format :require-years))
17469 (setq clocksum (concat clocksum (format fmt n))
17470 m (- m (* n y d h))))
17471 (and (setq fmt (plist-get org-time-clocksum-format :months))
17472 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17473 (plist-get org-time-clocksum-format :require-months))
17474 (setq clocksum (concat clocksum (format fmt n))
17475 m (- m (* n mo d h))))
17476 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17477 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17478 (plist-get org-time-clocksum-format :require-weeks))
17479 (setq clocksum (concat clocksum (format fmt n))
17480 m (- m (* n w d h))))
17481 (and (setq fmt (plist-get org-time-clocksum-format :days))
17482 (or (> (setq n (/ (truncate m) (* d h))) 0)
17483 (plist-get org-time-clocksum-format :require-days))
17484 (setq clocksum (concat clocksum (format fmt n))
17485 m (- m (* n d h))))
17486 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17487 (or (> (setq n (/ (truncate m) h)) 0)
17488 (plist-get org-time-clocksum-format :require-hours))
17489 (setq clocksum (concat clocksum (format fmt n))
17490 m (- m (* n h))))
17491 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17492 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17493 (setq clocksum (concat clocksum (format fmt m))))
17494 ;; return formatted time duration
17495 clocksum))))
17497 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17498 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17499 "Org mode version 8.0")
17501 (defun org-hours-to-clocksum-string (n)
17502 (org-minutes-to-clocksum-string (* n 60)))
17504 (defun org-hh:mm-string-to-minutes (s)
17505 "Convert a string H:MM to a number of minutes.
17506 If the string is just a number, interpret it as minutes.
17507 In fact, the first hh:mm or number in the string will be taken,
17508 there can be extra stuff in the string.
17509 If no number is found, the return value is 0."
17510 (cond
17511 ((integerp s) s)
17512 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17513 (+ (* (string-to-number (match-string 1 s)) 60)
17514 (string-to-number (match-string 2 s))))
17515 ((string-match "\\([0-9]+\\)" s)
17516 (string-to-number (match-string 1 s)))
17517 (t 0)))
17519 (defcustom org-image-actual-width t
17520 "Should we use the actual width of images when inlining them?
17522 When set to `t', always use the image width.
17524 When set to a number, use imagemagick (when available) to set
17525 the image's width to this value.
17527 When set to a number in a list, try to get the width from any
17528 #+ATTR.* keyword if it matches a width specification like
17530 #+ATTR_HTML: :width 300px
17532 and fall back on that number if none is found.
17534 When set to nil, try to get the width from an #+ATTR.* keyword
17535 and fall back on the original width if none is found.
17537 This requires Emacs >= 24.1, build with imagemagick support."
17538 :group 'org-appearance
17539 :version "24.4"
17540 :package-version '(Org . "8.0")
17541 :type '(choice
17542 (const :tag "Use the image width" t)
17543 (integer :tag "Use a number of pixels")
17544 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17545 (const :tag "Use #+ATTR* or don't resize" nil)))
17547 (defcustom org-agenda-inhibit-startup nil
17548 "Inhibit startup when preparing agenda buffers.
17549 When this variable is `t' (the default), the initialization of
17550 the Org agenda buffers is inhibited: e.g. the visibility state
17551 is not set, the tables are not re-aligned, etc."
17552 :type 'boolean
17553 :version "24.3"
17554 :group 'org-agenda)
17556 (defun org-duration-string-to-minutes (s &optional output-to-string)
17557 "Convert a duration string S to minutes.
17559 A bare number is interpreted as minutes, modifiers can be set by
17560 customizing `org-effort-durations' (which see).
17562 Entries containing a colon are interpreted as H:MM by
17563 `org-hh:mm-string-to-minutes'."
17564 (let ((result 0)
17565 (re (concat "\\([0-9.]+\\) *\\("
17566 (regexp-opt (mapcar 'car org-effort-durations))
17567 "\\)")))
17568 (while (string-match re s)
17569 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17570 (string-to-number (match-string 1 s))))
17571 (setq s (replace-match "" nil t s)))
17572 (setq result (floor result))
17573 (incf result (org-hh:mm-string-to-minutes s))
17574 (if output-to-string (number-to-string result) result)))
17576 ;;;; Files
17578 (defun org-save-all-org-buffers ()
17579 "Save all Org-mode buffers without user confirmation."
17580 (interactive)
17581 (message "Saving all Org-mode buffers...")
17582 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17583 (when (featurep 'org-id) (org-id-locations-save))
17584 (message "Saving all Org-mode buffers... done"))
17586 (defun org-revert-all-org-buffers ()
17587 "Revert all Org-mode buffers.
17588 Prompt for confirmation when there are unsaved changes.
17589 Be sure you know what you are doing before letting this function
17590 overwrite your changes.
17592 This function is useful in a setup where one tracks org files
17593 with a version control system, to revert on one machine after pulling
17594 changes from another. I believe the procedure must be like this:
17596 1. M-x org-save-all-org-buffers
17597 2. Pull changes from the other machine, resolve conflicts
17598 3. M-x org-revert-all-org-buffers"
17599 (interactive)
17600 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17601 (error "Abort"))
17602 (save-excursion
17603 (save-window-excursion
17604 (mapc
17605 (lambda (b)
17606 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17607 (with-current-buffer b buffer-file-name))
17608 (org-pop-to-buffer-same-window b)
17609 (revert-buffer t 'no-confirm)))
17610 (buffer-list))
17611 (when (and (featurep 'org-id) org-id-track-globally)
17612 (org-id-locations-load)))))
17614 ;;;; Agenda files
17616 ;;;###autoload
17617 (defun org-switchb (&optional arg)
17618 "Switch between Org buffers.
17619 With one prefix argument, restrict available buffers to files.
17620 With two prefix arguments, restrict available buffers to agenda files.
17622 Defaults to `iswitchb' for buffer name completion.
17623 Set `org-completion-use-ido' to make it use ido instead."
17624 (interactive "P")
17625 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17626 ((equal arg '(16)) (org-buffer-list 'agenda))
17627 (t (org-buffer-list))))
17628 (org-completion-use-iswitchb org-completion-use-iswitchb)
17629 (org-completion-use-ido org-completion-use-ido))
17630 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17631 (setq org-completion-use-iswitchb t))
17632 (org-pop-to-buffer-same-window
17633 (org-icompleting-read "Org buffer: "
17634 (mapcar 'list (mapcar 'buffer-name blist))
17635 nil t))))
17637 ;;; Define some older names previously used for this functionality
17638 ;;;###autoload
17639 (defalias 'org-ido-switchb 'org-switchb)
17640 ;;;###autoload
17641 (defalias 'org-iswitchb 'org-switchb)
17643 (defun org-buffer-list (&optional predicate exclude-tmp)
17644 "Return a list of Org buffers.
17645 PREDICATE can be `export', `files' or `agenda'.
17647 export restrict the list to Export buffers.
17648 files restrict the list to buffers visiting Org files.
17649 agenda restrict the list to buffers visiting agenda files.
17651 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17652 (let* ((bfn nil)
17653 (agenda-files (and (eq predicate 'agenda)
17654 (mapcar 'file-truename (org-agenda-files t))))
17655 (filter
17656 (cond
17657 ((eq predicate 'files)
17658 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17659 ((eq predicate 'export)
17660 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17661 ((eq predicate 'agenda)
17662 (lambda (b)
17663 (with-current-buffer b
17664 (and (derived-mode-p 'org-mode)
17665 (setq bfn (buffer-file-name b))
17666 (member (file-truename bfn) agenda-files)))))
17667 (t (lambda (b) (with-current-buffer b
17668 (or (derived-mode-p 'org-mode)
17669 (string-match "\*Org .*Export"
17670 (buffer-name b)))))))))
17671 (delq nil
17672 (mapcar
17673 (lambda(b)
17674 (if (and (funcall filter b)
17675 (or (not exclude-tmp)
17676 (not (string-match "tmp" (buffer-name b)))))
17678 nil))
17679 (buffer-list)))))
17681 (defun org-agenda-files (&optional unrestricted archives)
17682 "Get the list of agenda files.
17683 Optional UNRESTRICTED means return the full list even if a restriction
17684 is currently in place.
17685 When ARCHIVES is t, include all archive files that are really being
17686 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17687 `org-agenda-archives-mode' is t."
17688 (let ((files
17689 (cond
17690 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17691 ((stringp org-agenda-files) (org-read-agenda-file-list))
17692 ((listp org-agenda-files) org-agenda-files)
17693 (t (error "Invalid value of `org-agenda-files'")))))
17694 (setq files (apply 'append
17695 (mapcar (lambda (f)
17696 (if (file-directory-p f)
17697 (directory-files
17698 f t org-agenda-file-regexp)
17699 (list f)))
17700 files)))
17701 (when org-agenda-skip-unavailable-files
17702 (setq files (delq nil
17703 (mapcar (function
17704 (lambda (file)
17705 (and (file-readable-p file) file)))
17706 files))))
17707 (when (or (eq archives t)
17708 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17709 (setq files (org-add-archive-files files)))
17710 files))
17712 (defun org-agenda-file-p (&optional file)
17713 "Return non-nil, if FILE is an agenda file.
17714 If FILE is omitted, use the file associated with the current
17715 buffer."
17716 (member (or file (buffer-file-name))
17717 (org-agenda-files t)))
17719 (defun org-edit-agenda-file-list ()
17720 "Edit the list of agenda files.
17721 Depending on setup, this either uses customize to edit the variable
17722 `org-agenda-files', or it visits the file that is holding the list. In the
17723 latter case, the buffer is set up in a way that saving it automatically kills
17724 the buffer and restores the previous window configuration."
17725 (interactive)
17726 (if (stringp org-agenda-files)
17727 (let ((cw (current-window-configuration)))
17728 (find-file org-agenda-files)
17729 (org-set-local 'org-window-configuration cw)
17730 (org-add-hook 'after-save-hook
17731 (lambda ()
17732 (set-window-configuration
17733 (prog1 org-window-configuration
17734 (kill-buffer (current-buffer))))
17735 (org-install-agenda-files-menu)
17736 (message "New agenda file list installed"))
17737 nil 'local)
17738 (message "%s" (substitute-command-keys
17739 "Edit list and finish with \\[save-buffer]")))
17740 (customize-variable 'org-agenda-files)))
17742 (defun org-store-new-agenda-file-list (list)
17743 "Set new value for the agenda file list and save it correctly."
17744 (if (stringp org-agenda-files)
17745 (let ((fe (org-read-agenda-file-list t)) b u)
17746 (while (setq b (find-buffer-visiting org-agenda-files))
17747 (kill-buffer b))
17748 (with-temp-file org-agenda-files
17749 (insert
17750 (mapconcat
17751 (lambda (f) ;; Keep un-expanded entries.
17752 (if (setq u (assoc f fe))
17753 (cdr u)
17755 list "\n")
17756 "\n")))
17757 (let ((org-mode-hook nil) (org-inhibit-startup t)
17758 (org-insert-mode-line-in-empty-file nil))
17759 (setq org-agenda-files list)
17760 (customize-save-variable 'org-agenda-files org-agenda-files))))
17762 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17763 "Read the list of agenda files from a file.
17764 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17765 filenames, used by `org-store-new-agenda-file-list' to write back
17766 un-expanded file names."
17767 (when (file-directory-p org-agenda-files)
17768 (error "`org-agenda-files' cannot be a single directory"))
17769 (when (stringp org-agenda-files)
17770 (with-temp-buffer
17771 (insert-file-contents org-agenda-files)
17772 (mapcar
17773 (lambda (f)
17774 (let ((e (expand-file-name (substitute-in-file-name f)
17775 org-directory)))
17776 (if pair-with-expansion
17777 (cons e f)
17778 e)))
17779 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17781 ;;;###autoload
17782 (defun org-cycle-agenda-files ()
17783 "Cycle through the files in `org-agenda-files'.
17784 If the current buffer visits an agenda file, find the next one in the list.
17785 If the current buffer does not, find the first agenda file."
17786 (interactive)
17787 (let* ((fs (org-agenda-files t))
17788 (files (append fs (list (car fs))))
17789 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17790 file)
17791 (unless files (error "No agenda files"))
17792 (catch 'exit
17793 (while (setq file (pop files))
17794 (if (equal (file-truename file) tcf)
17795 (when (car files)
17796 (find-file (car files))
17797 (throw 'exit t))))
17798 (find-file (car fs)))
17799 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17801 (defun org-agenda-file-to-front (&optional to-end)
17802 "Move/add the current file to the top of the agenda file list.
17803 If the file is not present in the list, it is added to the front. If it is
17804 present, it is moved there. With optional argument TO-END, add/move to the
17805 end of the list."
17806 (interactive "P")
17807 (let ((org-agenda-skip-unavailable-files nil)
17808 (file-alist (mapcar (lambda (x)
17809 (cons (file-truename x) x))
17810 (org-agenda-files t)))
17811 (ctf (file-truename
17812 (or buffer-file-name
17813 (error "Please save the current buffer to a file"))))
17814 x had)
17815 (setq x (assoc ctf file-alist) had x)
17817 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17818 (if to-end
17819 (setq file-alist (append (delq x file-alist) (list x)))
17820 (setq file-alist (cons x (delq x file-alist))))
17821 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17822 (org-install-agenda-files-menu)
17823 (message "File %s to %s of agenda file list"
17824 (if had "moved" "added") (if to-end "end" "front"))))
17826 (defun org-remove-file (&optional file)
17827 "Remove current file from the list of files in variable `org-agenda-files'.
17828 These are the files which are being checked for agenda entries.
17829 Optional argument FILE means use this file instead of the current."
17830 (interactive)
17831 (let* ((org-agenda-skip-unavailable-files nil)
17832 (file (or file buffer-file-name
17833 (error "Current buffer does not visit a file")))
17834 (true-file (file-truename file))
17835 (afile (abbreviate-file-name file))
17836 (files (delq nil (mapcar
17837 (lambda (x)
17838 (if (equal true-file
17839 (file-truename x))
17840 nil x))
17841 (org-agenda-files t)))))
17842 (if (not (= (length files) (length (org-agenda-files t))))
17843 (progn
17844 (org-store-new-agenda-file-list files)
17845 (org-install-agenda-files-menu)
17846 (message "Removed file: %s" afile))
17847 (message "File was not in list: %s (not removed)" afile))))
17849 (defun org-file-menu-entry (file)
17850 (vector file (list 'find-file file) t))
17852 (defun org-check-agenda-file (file)
17853 "Make sure FILE exists. If not, ask user what to do."
17854 (when (not (file-exists-p file))
17855 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17856 (abbreviate-file-name file))
17857 (let ((r (downcase (read-char-exclusive))))
17858 (cond
17859 ((equal r ?r)
17860 (org-remove-file file)
17861 (throw 'nextfile t))
17862 (t (error "Abort"))))))
17864 (defun org-get-agenda-file-buffer (file)
17865 "Get a buffer visiting FILE. If the buffer needs to be created, add
17866 it to the list of buffers which might be released later."
17867 (let ((buf (org-find-base-buffer-visiting file)))
17868 (if buf
17869 buf ; just return it
17870 ;; Make a new buffer and remember it
17871 (setq buf (find-file-noselect file))
17872 (if buf (push buf org-agenda-new-buffers))
17873 buf)))
17875 (defun org-release-buffers (blist)
17876 "Release all buffers in list, asking the user for confirmation when needed.
17877 When a buffer is unmodified, it is just killed. When modified, it is saved
17878 \(if the user agrees) and then killed."
17879 (let (buf file)
17880 (while (setq buf (pop blist))
17881 (setq file (buffer-file-name buf))
17882 (when (and (buffer-modified-p buf)
17883 file
17884 (y-or-n-p (format "Save file %s? " file)))
17885 (with-current-buffer buf (save-buffer)))
17886 (kill-buffer buf))))
17888 (defun org-agenda-prepare-buffers (files)
17889 "Create buffers for all agenda files, protect archived trees and comments."
17890 (interactive)
17891 (let ((pa '(:org-archived t))
17892 (pc '(:org-comment t))
17893 (pall '(:org-archived t :org-comment t))
17894 (inhibit-read-only t)
17895 (org-inhibit-startup org-agenda-inhibit-startup)
17896 (rea (concat ":" org-archive-tag ":"))
17897 file re)
17898 (setq org-tag-alist-for-agenda nil
17899 org-tag-groups-alist-for-agenda nil)
17900 (save-excursion
17901 (save-restriction
17902 (while (setq file (pop files))
17903 (catch 'nextfile
17904 (if (bufferp file)
17905 (set-buffer file)
17906 (org-check-agenda-file file)
17907 (set-buffer (org-get-agenda-file-buffer file)))
17908 (widen)
17909 (org-set-regexps-and-options-for-tags)
17910 (org-refresh-category-properties)
17911 (org-refresh-properties org-effort-property 'org-effort)
17912 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17913 (setq org-todo-keywords-for-agenda
17914 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17915 (setq org-done-keywords-for-agenda
17916 (append org-done-keywords-for-agenda org-done-keywords))
17917 (setq org-todo-keyword-alist-for-agenda
17918 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17919 (setq org-drawers-for-agenda
17920 (append org-drawers-for-agenda org-drawers))
17921 (unless (equal org-tag-alist-for-agenda org-tag-alist)
17922 (setq org-tag-alist-for-agenda
17923 (append org-tag-alist-for-agenda org-tag-alist)))
17924 (if org-group-tags
17925 (setq org-tag-groups-alist-for-agenda
17926 (org-uniquify-alist
17927 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
17928 (org-with-silent-modifications
17929 (save-excursion
17930 (remove-text-properties (point-min) (point-max) pall)
17931 (when org-agenda-skip-archived-trees
17932 (goto-char (point-min))
17933 (while (re-search-forward rea nil t)
17934 (if (org-at-heading-p t)
17935 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17936 (goto-char (point-min))
17937 (setq re (format org-heading-keyword-regexp-format
17938 org-comment-string))
17939 (while (re-search-forward re nil t)
17940 (add-text-properties
17941 (match-beginning 0) (org-end-of-subtree t) pc))))))))
17942 (setq org-todo-keywords-for-agenda
17943 (org-uniquify org-todo-keywords-for-agenda))
17944 (setq org-todo-keyword-alist-for-agenda
17945 (org-uniquify org-todo-keyword-alist-for-agenda))))
17948 ;;;; CDLaTeX minor mode
17950 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17951 "Keymap for the minor `org-cdlatex-mode'.")
17953 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17954 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17955 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17956 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17957 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17959 (defvar org-cdlatex-texmathp-advice-is-done nil
17960 "Flag remembering if we have applied the advice to texmathp already.")
17962 (define-minor-mode org-cdlatex-mode
17963 "Toggle the minor `org-cdlatex-mode'.
17964 This mode supports entering LaTeX environment and math in LaTeX fragments
17965 in Org-mode.
17966 \\{org-cdlatex-mode-map}"
17967 nil " OCDL" nil
17968 (when org-cdlatex-mode
17969 (require 'cdlatex)
17970 (run-hooks 'cdlatex-mode-hook)
17971 (cdlatex-compute-tables))
17972 (unless org-cdlatex-texmathp-advice-is-done
17973 (setq org-cdlatex-texmathp-advice-is-done t)
17974 (defadvice texmathp (around org-math-always-on activate)
17975 "Always return t in org-mode buffers.
17976 This is because we want to insert math symbols without dollars even outside
17977 the LaTeX math segments. If Orgmode thinks that point is actually inside
17978 an embedded LaTeX fragment, let texmathp do its job.
17979 \\[org-cdlatex-mode-map]"
17980 (interactive)
17981 (let (p)
17982 (cond
17983 ((not (derived-mode-p 'org-mode)) ad-do-it)
17984 ((eq this-command 'cdlatex-math-symbol)
17985 (setq ad-return-value t
17986 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17988 (let ((p (org-inside-LaTeX-fragment-p)))
17989 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17990 (setq ad-return-value t
17991 texmathp-why '("Org-mode embedded math" . 0))
17992 (if p ad-do-it)))))))))
17994 (defun turn-on-org-cdlatex ()
17995 "Unconditionally turn on `org-cdlatex-mode'."
17996 (org-cdlatex-mode 1))
17998 (defun org-try-cdlatex-tab ()
17999 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18000 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18001 - inside a LaTeX fragment, or
18002 - after the first word in a line, where an abbreviation expansion could
18003 insert a LaTeX environment."
18004 (when org-cdlatex-mode
18005 (cond
18006 ;; Before any word on the line: No expansion possible.
18007 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18008 ;; Just after first word on the line: Expand it. Make sure it
18009 ;; cannot happen on headlines, though.
18010 ((save-excursion
18011 (skip-chars-backward "a-zA-Z0-9*")
18012 (skip-chars-backward " \t")
18013 (and (bolp) (not (org-at-heading-p))))
18014 (cdlatex-tab) t)
18015 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18017 (defun org-cdlatex-underscore-caret (&optional arg)
18018 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18019 Revert to the normal definition outside of these fragments."
18020 (interactive "P")
18021 (if (org-inside-LaTeX-fragment-p)
18022 (call-interactively 'cdlatex-sub-superscript)
18023 (let (org-cdlatex-mode)
18024 (call-interactively (key-binding (vector last-input-event))))))
18026 (defun org-cdlatex-math-modify (&optional arg)
18027 "Execute `cdlatex-math-modify' in LaTeX fragments.
18028 Revert to the normal definition outside of these fragments."
18029 (interactive "P")
18030 (if (org-inside-LaTeX-fragment-p)
18031 (call-interactively 'cdlatex-math-modify)
18032 (let (org-cdlatex-mode)
18033 (call-interactively (key-binding (vector last-input-event))))))
18037 ;;;; LaTeX fragments
18039 (defvar org-latex-regexps
18040 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18041 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18042 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18043 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18044 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18045 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18046 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18047 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18048 "Regular expressions for matching embedded LaTeX.")
18050 (defun org-inside-LaTeX-fragment-p ()
18051 "Test if point is inside a LaTeX fragment.
18052 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18053 sequence appearing also before point.
18054 Even though the matchers for math are configurable, this function assumes
18055 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18056 delimiters are skipped when they have been removed by customization.
18057 The return value is nil, or a cons cell with the delimiter and the
18058 position of this delimiter.
18060 This function does a reasonably good job, but can locally be fooled by
18061 for example currency specifications. For example it will assume being in
18062 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18063 fragments that are properly closed, but during editing, we have to live
18064 with the uncertainty caused by missing closing delimiters. This function
18065 looks only before point, not after."
18066 (catch 'exit
18067 (let ((pos (point))
18068 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18069 (lim (progn
18070 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18071 (point)))
18072 dd-on str (start 0) m re)
18073 (goto-char pos)
18074 (when dodollar
18075 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18076 re (nth 1 (assoc "$" org-latex-regexps)))
18077 (while (string-match re str start)
18078 (cond
18079 ((= (match-end 0) (length str))
18080 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18081 ((= (match-end 0) (- (length str) 5))
18082 (throw 'exit nil))
18083 (t (setq start (match-end 0))))))
18084 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18085 (goto-char pos)
18086 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18087 (and (match-beginning 2) (throw 'exit nil))
18088 ;; count $$
18089 (while (re-search-backward "\\$\\$" lim t)
18090 (setq dd-on (not dd-on)))
18091 (goto-char pos)
18092 (if dd-on (cons "$$" m))))))
18094 (defun org-inside-latex-macro-p ()
18095 "Is point inside a LaTeX macro or its arguments?"
18096 (save-match-data
18097 (org-in-regexp
18098 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18100 (defvar org-latex-fragment-image-overlays nil
18101 "List of overlays carrying the images of latex fragments.")
18102 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18104 (defun org-remove-latex-fragment-image-overlays ()
18105 "Remove all overlays with LaTeX fragment images in current buffer."
18106 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18107 (setq org-latex-fragment-image-overlays nil))
18109 (defun org-preview-latex-fragment (&optional subtree)
18110 "Preview the LaTeX fragment at point, or all locally or globally.
18111 If the cursor is in a LaTeX fragment, create the image and overlay
18112 it over the source code. If there is no fragment at point, display
18113 all fragments in the current text, from one headline to the next. With
18114 prefix SUBTREE, display all fragments in the current subtree. With a
18115 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18116 the cursor is before the first headline,
18117 display all fragments in the buffer.
18118 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18119 (interactive "P")
18120 (unless buffer-file-name
18121 (error "Can't preview LaTeX fragment in a non-file buffer"))
18122 (org-remove-latex-fragment-image-overlays)
18123 (save-excursion
18124 (save-restriction
18125 (let (beg end at msg)
18126 (cond
18127 ((or (equal subtree '(16))
18128 (not (save-excursion
18129 (re-search-backward org-outline-regexp-bol nil t))))
18130 (setq beg (point-min) end (point-max)
18131 msg "Creating images for buffer...%s"))
18132 ((equal subtree '(4))
18133 (org-back-to-heading)
18134 (setq beg (point) end (org-end-of-subtree t)
18135 msg "Creating images for subtree...%s"))
18137 (if (setq at (org-inside-LaTeX-fragment-p))
18138 (goto-char (max (point-min) (- (cdr at) 2)))
18139 (org-back-to-heading))
18140 (setq beg (point) end (progn (outline-next-heading) (point))
18141 msg (if at "Creating image...%s"
18142 "Creating images for entry...%s"))))
18143 (message msg "")
18144 (narrow-to-region beg end)
18145 (goto-char beg)
18146 (org-format-latex
18147 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18148 (file-name-nondirectory
18149 buffer-file-name)))
18150 default-directory 'overlays msg at 'forbuffer
18151 org-latex-create-formula-image-program)
18152 (message msg "done. Use `C-c C-c' to remove images.")))))
18154 (defun org-format-latex (prefix &optional dir overlays msg at
18155 forbuffer processing-type)
18156 "Replace LaTeX fragments with links to an image, and produce images.
18157 Some of the options can be changed using the variable
18158 `org-format-latex-options'."
18159 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18160 (let* ((prefixnodir (file-name-nondirectory prefix))
18161 (absprefix (expand-file-name prefix dir))
18162 (todir (file-name-directory absprefix))
18163 (opt org-format-latex-options)
18164 (optnew org-format-latex-options)
18165 (matchers (plist-get opt :matchers))
18166 (re-list org-latex-regexps)
18167 (cnt 0) txt hash link beg end re e checkdir
18168 string
18169 m n block-type block linkfile movefile ov)
18170 ;; Check the different regular expressions
18171 (while (setq e (pop re-list))
18172 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18173 block (if block-type "\n\n" ""))
18174 (when (member m matchers)
18175 (goto-char (point-min))
18176 (while (re-search-forward re nil t)
18177 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18178 (or (not overlays)
18179 (not (eq (get-char-property (match-beginning n)
18180 'org-overlay-type)
18181 'org-latex-overlay))))
18182 (cond
18183 ((eq processing-type 'verbatim))
18184 ((eq processing-type 'mathjax)
18185 ;; Prepare for MathJax processing.
18186 (setq string (match-string n))
18187 (when (member m '("$" "$1"))
18188 (save-excursion
18189 (delete-region (match-beginning n) (match-end n))
18190 (goto-char (match-beginning n))
18191 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18192 ((or (eq processing-type 'dvipng)
18193 (eq processing-type 'imagemagick))
18194 ;; Process to an image.
18195 (setq txt (match-string n)
18196 beg (match-beginning n) end (match-end n)
18197 cnt (1+ cnt))
18198 (let ((face (face-at-point))
18199 (fg (plist-get opt :foreground))
18200 (bg (plist-get opt :background))
18201 ;; Ensure full list is printed.
18202 print-length print-level)
18203 (when forbuffer
18204 ;; Get the colors from the face at point.
18205 (goto-char beg)
18206 (when (eq fg 'auto)
18207 (setq fg (face-attribute face :foreground nil 'default)))
18208 (when (eq bg 'auto)
18209 (setq bg (face-attribute face :background nil 'default)))
18210 (setq optnew (copy-sequence opt))
18211 (plist-put optnew :foreground fg)
18212 (plist-put optnew :background bg))
18213 (setq hash (sha1 (prin1-to-string
18214 (list org-format-latex-header
18215 org-latex-default-packages-alist
18216 org-latex-packages-alist
18217 org-format-latex-options
18218 forbuffer txt fg bg)))
18219 linkfile (format "%s_%s.png" prefix hash)
18220 movefile (format "%s_%s.png" absprefix hash)))
18221 (setq link (concat block "[[file:" linkfile "]]" block))
18222 (if msg (message msg cnt))
18223 (goto-char beg)
18224 (unless checkdir ; Ensure the directory exists.
18225 (setq checkdir t)
18226 (or (file-directory-p todir) (make-directory todir t)))
18227 (unless (file-exists-p movefile)
18228 (org-create-formula-image
18229 txt movefile optnew forbuffer processing-type))
18230 (if overlays
18231 (progn
18232 (mapc (lambda (o)
18233 (if (eq (overlay-get o 'org-overlay-type)
18234 'org-latex-overlay)
18235 (delete-overlay o)))
18236 (overlays-in beg end))
18237 (setq ov (make-overlay beg end))
18238 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18239 (if (featurep 'xemacs)
18240 (progn
18241 (overlay-put ov 'invisible t)
18242 (overlay-put
18243 ov 'end-glyph
18244 (make-glyph (vector 'png :file movefile))))
18245 (overlay-put
18246 ov 'display
18247 (list 'image :type 'png :file movefile :ascent 'center)))
18248 (push ov org-latex-fragment-image-overlays)
18249 (goto-char end))
18250 (delete-region beg end)
18251 (insert (org-add-props link
18252 (list 'org-latex-src
18253 (replace-regexp-in-string
18254 "\"" "" txt)
18255 'org-latex-src-embed-type
18256 (if block-type 'paragraph 'character))))))
18257 ((eq processing-type 'mathml)
18258 ;; Process to MathML
18259 (unless (save-match-data (org-format-latex-mathml-available-p))
18260 (error "LaTeX to MathML converter not configured"))
18261 (setq txt (match-string n)
18262 beg (match-beginning n) end (match-end n)
18263 cnt (1+ cnt))
18264 (if msg (message msg cnt))
18265 (goto-char beg)
18266 (delete-region beg end)
18267 (insert (org-format-latex-as-mathml
18268 txt block-type prefix dir)))
18270 (error "Unknown conversion type %s for latex fragments"
18271 processing-type)))))))))
18273 (defun org-create-math-formula (latex-frag &optional mathml-file)
18274 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18275 Use `org-latex-to-mathml-convert-command'. If the conversion is
18276 sucessful, return the portion between \"<math...> </math>\"
18277 elements otherwise return nil. When MATHML-FILE is specified,
18278 write the results in to that file. When invoked as an
18279 interactive command, prompt for LATEX-FRAG, with initial value
18280 set to the current active region and echo the results for user
18281 inspection."
18282 (interactive (list (let ((frag (when (org-region-active-p)
18283 (buffer-substring-no-properties
18284 (region-beginning) (region-end)))))
18285 (read-string "LaTeX Fragment: " frag nil frag))))
18286 (unless latex-frag (error "Invalid latex-frag"))
18287 (let* ((tmp-in-file (file-relative-name
18288 (make-temp-name (expand-file-name "ltxmathml-in"))))
18289 (ignore (write-region latex-frag nil tmp-in-file))
18290 (tmp-out-file (file-relative-name
18291 (make-temp-name (expand-file-name "ltxmathml-out"))))
18292 (cmd (format-spec
18293 org-latex-to-mathml-convert-command
18294 `((?j . ,(shell-quote-argument
18295 (expand-file-name org-latex-to-mathml-jar-file)))
18296 (?I . ,(shell-quote-argument tmp-in-file))
18297 (?o . ,(shell-quote-argument tmp-out-file)))))
18298 mathml shell-command-output)
18299 (when (org-called-interactively-p 'any)
18300 (unless (org-format-latex-mathml-available-p)
18301 (error "LaTeX to MathML converter not configured")))
18302 (message "Running %s" cmd)
18303 (setq shell-command-output (shell-command-to-string cmd))
18304 (setq mathml
18305 (when (file-readable-p tmp-out-file)
18306 (with-current-buffer (find-file-noselect tmp-out-file t)
18307 (goto-char (point-min))
18308 (when (re-search-forward
18309 (concat
18310 (regexp-quote
18311 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18312 "\\(.\\|\n\\)*"
18313 (regexp-quote "</math>")) nil t)
18314 (prog1 (match-string 0) (kill-buffer))))))
18315 (cond
18316 (mathml
18317 (setq mathml
18318 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18319 (when mathml-file
18320 (write-region mathml nil mathml-file))
18321 (when (org-called-interactively-p 'any)
18322 (message mathml)))
18323 ((message "LaTeX to MathML conversion failed")
18324 (message shell-command-output)))
18325 (delete-file tmp-in-file)
18326 (when (file-exists-p tmp-out-file)
18327 (delete-file tmp-out-file))
18328 mathml))
18330 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18331 prefix &optional dir)
18332 "Use `org-create-math-formula' but check local cache first."
18333 (let* ((absprefix (expand-file-name prefix dir))
18334 (print-length nil) (print-level nil)
18335 (formula-id (concat
18336 "formula-"
18337 (sha1
18338 (prin1-to-string
18339 (list latex-frag
18340 org-latex-to-mathml-convert-command)))))
18341 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18342 (formula-cache-dir (file-name-directory formula-cache)))
18344 (unless (file-directory-p formula-cache-dir)
18345 (make-directory formula-cache-dir t))
18347 (unless (file-exists-p formula-cache)
18348 (org-create-math-formula latex-frag formula-cache))
18350 (if (file-exists-p formula-cache)
18351 ;; Successful conversion. Return the link to MathML file.
18352 (org-add-props
18353 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18354 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18355 'org-latex-src-embed-type (if latex-frag-type
18356 'paragraph 'character)))
18357 ;; Failed conversion. Return the LaTeX fragment verbatim
18358 latex-frag)))
18360 (defun org-create-formula-image (string tofile options buffer &optional type)
18361 "Create an image from LaTeX source using dvipng or convert.
18362 This function calls either `org-create-formula-image-with-dvipng'
18363 or `org-create-formula-image-with-imagemagick' depending on the
18364 value of `org-latex-create-formula-image-program' or on the value
18365 of the optional TYPE variable.
18367 Note: ultimately these two function should be combined as they
18368 share a good deal of logic."
18369 (org-check-external-command
18370 "latex" "needed to convert LaTeX fragments to images")
18371 (funcall
18372 (case (or type org-latex-create-formula-image-program)
18373 ('dvipng
18374 (org-check-external-command
18375 "dvipng" "needed to convert LaTeX fragments to images")
18376 #'org-create-formula-image-with-dvipng)
18377 ('imagemagick
18378 (org-check-external-command
18379 "convert" "you need to install imagemagick")
18380 #'org-create-formula-image-with-imagemagick)
18381 (t (error
18382 "invalid value of `org-latex-create-formula-image-program'")))
18383 string tofile options buffer))
18385 (declare-function org-export--get-global-options "ox" (&optional backend))
18386 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18387 (defun org-create-formula--latex-header ()
18388 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18389 (org-latex-guess-inputenc
18390 (org-splice-latex-header
18391 org-format-latex-header
18392 org-latex-default-packages-alist
18393 org-latex-packages-alist t
18394 (plist-get
18395 (org-combine-plists
18396 (org-export--get-global-options 'latex)
18397 (org-export--get-inbuffer-options 'latex))
18398 :latex-header))))
18400 ;; This function borrows from Ganesh Swami's latex2png.el
18401 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18402 "This calls dvipng."
18403 (require 'ox-latex)
18404 (let* ((tmpdir (if (featurep 'xemacs)
18405 (temp-directory)
18406 temporary-file-directory))
18407 (texfilebase (make-temp-name
18408 (expand-file-name "orgtex" tmpdir)))
18409 (texfile (concat texfilebase ".tex"))
18410 (dvifile (concat texfilebase ".dvi"))
18411 (pngfile (concat texfilebase ".png"))
18412 (fnh (if (featurep 'xemacs)
18413 (font-height (face-font 'default))
18414 (face-attribute 'default :height nil)))
18415 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18416 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18417 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18418 "Black"))
18419 (bg (or (plist-get options (if buffer :background :html-background))
18420 "Transparent")))
18421 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18422 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18423 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18424 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18425 (let ((latex-header (org-create-formula--latex-header)))
18426 (with-temp-file texfile
18427 (insert latex-header)
18428 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18429 (let ((dir default-directory))
18430 (condition-case nil
18431 (progn
18432 (cd tmpdir)
18433 (call-process "latex" nil nil nil texfile))
18434 (error nil))
18435 (cd dir))
18436 (if (not (file-exists-p dvifile))
18437 (progn (message "Failed to create dvi file from %s" texfile) nil)
18438 (condition-case nil
18439 (if (featurep 'xemacs)
18440 (call-process "dvipng" nil nil nil
18441 "-fg" fg "-bg" bg
18442 "-T" "tight"
18443 "-o" pngfile
18444 dvifile)
18445 (call-process "dvipng" nil nil nil
18446 "-fg" fg "-bg" bg
18447 "-D" dpi
18448 ;;"-x" scale "-y" scale
18449 "-T" "tight"
18450 "-o" pngfile
18451 dvifile))
18452 (error nil))
18453 (if (not (file-exists-p pngfile))
18454 (if org-format-latex-signal-error
18455 (error "Failed to create png file from %s" texfile)
18456 (message "Failed to create png file from %s" texfile)
18457 nil)
18458 ;; Use the requested file name and clean up
18459 (copy-file pngfile tofile 'replace)
18460 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18461 (if (file-exists-p (concat texfilebase e))
18462 (delete-file (concat texfilebase e))))
18463 pngfile))))
18465 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18466 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18467 "This calls convert, which is included into imagemagick."
18468 (require 'ox-latex)
18469 (let* ((tmpdir (if (featurep 'xemacs)
18470 (temp-directory)
18471 temporary-file-directory))
18472 (texfilebase (make-temp-name
18473 (expand-file-name "orgtex" tmpdir)))
18474 (texfile (concat texfilebase ".tex"))
18475 (pdffile (concat texfilebase ".pdf"))
18476 (pngfile (concat texfilebase ".png"))
18477 (fnh (if (featurep 'xemacs)
18478 (font-height (face-font 'default))
18479 (face-attribute 'default :height nil)))
18480 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18481 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18482 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18483 "black"))
18484 (bg (or (plist-get options (if buffer :background :html-background))
18485 "white")))
18486 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18487 (setq fg (org-latex-color-format fg)))
18488 (if (eq bg 'default) (setq bg (org-latex-color :background))
18489 (setq bg (org-latex-color-format
18490 (if (string= bg "Transparent") "white" bg))))
18491 (let ((latex-header (org-create-formula--latex-header)))
18492 (with-temp-file texfile
18493 (insert latex-header)
18494 (insert "\n\\begin{document}\n"
18495 "\\definecolor{fg}{rgb}{" fg "}\n"
18496 "\\definecolor{bg}{rgb}{" bg "}\n"
18497 "\n\\pagecolor{bg}\n"
18498 "\n{\\color{fg}\n"
18499 string
18500 "\n}\n"
18501 "\n\\end{document}\n")))
18502 (org-latex-compile texfile t)
18503 (if (not (file-exists-p pdffile))
18504 (progn (message "Failed to create pdf file from %s" texfile) nil)
18505 (condition-case nil
18506 (if (featurep 'xemacs)
18507 (call-process "convert" nil nil nil
18508 "-density" "96"
18509 "-trim"
18510 "-antialias"
18511 pdffile
18512 "-quality" "100"
18513 ;; "-sharpen" "0x1.0"
18514 pngfile)
18515 (call-process "convert" nil nil nil
18516 "-density" dpi
18517 "-trim"
18518 "-antialias"
18519 pdffile
18520 "-quality" "100"
18521 ;; "-sharpen" "0x1.0"
18522 pngfile))
18523 (error nil))
18524 (if (not (file-exists-p pngfile))
18525 (if org-format-latex-signal-error
18526 (error "Failed to create png file from %s" texfile)
18527 (message "Failed to create png file from %s" texfile)
18528 nil)
18529 ;; Use the requested file name and clean up
18530 (copy-file pngfile tofile 'replace)
18531 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18532 (if (file-exists-p (concat texfilebase e))
18533 (delete-file (concat texfilebase e))))
18534 pngfile))))
18536 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18537 "Fill a LaTeX header template TPL.
18538 In the template, the following place holders will be recognized:
18540 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18541 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18542 [PACKAGES] \\usepackage statements for PKG
18543 [NO-PACKAGES] do not include PKG
18544 [EXTRA] the string EXTRA
18545 [NO-EXTRA] do not include EXTRA
18547 For backward compatibility, if both the positive and the negative place
18548 holder is missing, the positive one (without the \"NO-\") will be
18549 assumed to be present at the end of the template.
18550 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18551 EXTRA is a string.
18552 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18553 (let (rpl (end ""))
18554 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18555 (setq rpl (if (or (match-end 1) (not def-pkg))
18556 "" (org-latex-packages-to-string def-pkg snippets-p t))
18557 tpl (replace-match rpl t t tpl))
18558 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18560 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18561 (setq rpl (if (or (match-end 1) (not pkg))
18562 "" (org-latex-packages-to-string pkg snippets-p t))
18563 tpl (replace-match rpl t t tpl))
18564 (if pkg (setq end
18565 (concat end "\n"
18566 (org-latex-packages-to-string pkg snippets-p)))))
18568 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18569 (setq rpl (if (or (match-end 1) (not extra))
18570 "" (concat extra "\n"))
18571 tpl (replace-match rpl t t tpl))
18572 (if (and extra (string-match "\\S-" extra))
18573 (setq end (concat end "\n" extra))))
18575 (if (string-match "\\S-" end)
18576 (concat tpl "\n" end)
18577 tpl)))
18579 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18580 "Turn an alist of packages into a string with the \\usepackage macros."
18581 (setq pkg (mapconcat (lambda(p)
18582 (cond
18583 ((stringp p) p)
18584 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18585 (format "%% Package %s omitted" (cadr p)))
18586 ((equal "" (car p))
18587 (format "\\usepackage{%s}" (cadr p)))
18589 (format "\\usepackage[%s]{%s}"
18590 (car p) (cadr p)))))
18592 "\n"))
18593 (if newline (concat pkg "\n") pkg))
18595 (defun org-dvipng-color (attr)
18596 "Return a RGB color specification for dvipng."
18597 (apply 'format "rgb %s %s %s"
18598 (mapcar 'org-normalize-color
18599 (if (featurep 'xemacs)
18600 (color-rgb-components
18601 (face-property 'default
18602 (cond ((eq attr :foreground) 'foreground)
18603 ((eq attr :background) 'background))))
18604 (color-values (face-attribute 'default attr nil))))))
18606 (defun org-dvipng-color-format (color-name)
18607 "Convert COLOR-NAME to a RGB color value for dvipng."
18608 (apply 'format "rgb %s %s %s"
18609 (mapcar 'org-normalize-color
18610 (color-values color-name))))
18612 (defun org-latex-color (attr)
18613 "Return a RGB color for the LaTeX color package."
18614 (apply 'format "%s,%s,%s"
18615 (mapcar 'org-normalize-color
18616 (if (featurep 'xemacs)
18617 (color-rgb-components
18618 (face-property 'default
18619 (cond ((eq attr :foreground) 'foreground)
18620 ((eq attr :background) 'background))))
18621 (color-values (face-attribute 'default attr nil))))))
18623 (defun org-latex-color-format (color-name)
18624 "Convert COLOR-NAME to a RGB color value."
18625 (apply 'format "%s,%s,%s"
18626 (mapcar 'org-normalize-color
18627 (color-values color-name))))
18629 (defun org-normalize-color (value)
18630 "Return string to be used as color value for an RGB component."
18631 (format "%g" (/ value 65535.0)))
18635 ;; Image display
18637 (defvar org-inline-image-overlays nil)
18638 (make-variable-buffer-local 'org-inline-image-overlays)
18640 (defun org-toggle-inline-images (&optional include-linked)
18641 "Toggle the display of inline images.
18642 INCLUDE-LINKED is passed to `org-display-inline-images'."
18643 (interactive "P")
18644 (if org-inline-image-overlays
18645 (progn
18646 (org-remove-inline-images)
18647 (message "Inline image display turned off"))
18648 (org-display-inline-images include-linked)
18649 (if (and (org-called-interactively-p)
18650 org-inline-image-overlays)
18651 (message "%d images displayed inline"
18652 (length org-inline-image-overlays))
18653 (message "No images to display inline"))))
18655 (defun org-redisplay-inline-images ()
18656 "Refresh the display of inline images."
18657 (interactive)
18658 (if (not org-inline-image-overlays)
18659 (org-toggle-inline-images)
18660 (org-toggle-inline-images)
18661 (org-toggle-inline-images)))
18663 (defun org-display-inline-images (&optional include-linked refresh beg end)
18664 "Display inline images.
18665 Normally only links without a description part are inlined, because this
18666 is how it will work for export. When INCLUDE-LINKED is set, also links
18667 with a description part will be inlined. This can be nice for a quick
18668 look at those images, but it does not reflect what exported files will look
18669 like.
18670 When REFRESH is set, refresh existing images between BEG and END.
18671 This will create new image displays only if necessary.
18672 BEG and END default to the buffer boundaries."
18673 (interactive "P")
18674 (unless refresh
18675 (org-remove-inline-images)
18676 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18677 (save-excursion
18678 (save-restriction
18679 (widen)
18680 (setq beg (or beg (point-min)) end (or end (point-max)))
18681 (goto-char beg)
18682 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18683 (substring (org-image-file-name-regexp) 0 -2)
18684 "\\)\\]" (if include-linked "" "\\]")))
18685 (case-fold-search t)
18686 old file ov img type attrwidth width)
18687 (while (re-search-forward re end t)
18688 (setq old (get-char-property-and-overlay (match-beginning 1)
18689 'org-image-overlay)
18690 file (expand-file-name
18691 (concat (or (match-string 3) "") (match-string 4))))
18692 (when (image-type-available-p 'imagemagick)
18693 (setq attrwidth (if (or (listp org-image-actual-width)
18694 (null org-image-actual-width))
18695 (save-excursion
18696 (save-match-data
18697 (when (re-search-backward
18698 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18699 (save-excursion
18700 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18701 (string-to-number (match-string 1))))))
18702 width (cond ((eq org-image-actual-width t) nil)
18703 ((null org-image-actual-width) attrwidth)
18704 ((numberp org-image-actual-width)
18705 org-image-actual-width)
18706 ((listp org-image-actual-width)
18707 (or attrwidth (car org-image-actual-width))))
18708 type (if width 'imagemagick)))
18709 (when (file-exists-p file)
18710 (if (and (car-safe old) refresh)
18711 (image-refresh (overlay-get (cdr old) 'display))
18712 (setq img (save-match-data (create-image file type nil :width width)))
18713 (when img
18714 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18715 (overlay-put ov 'display img)
18716 (overlay-put ov 'face 'default)
18717 (overlay-put ov 'org-image-overlay t)
18718 (overlay-put ov 'modification-hooks
18719 (list 'org-display-inline-remove-overlay))
18720 (push ov org-inline-image-overlays)))))))))
18722 (define-obsolete-function-alias
18723 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18725 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18726 "Remove inline-display overlay if a corresponding region is modified."
18727 (let ((inhibit-modification-hooks t))
18728 (when (and ov after)
18729 (delete ov org-inline-image-overlays)
18730 (delete-overlay ov))))
18732 (defun org-remove-inline-images ()
18733 "Remove inline display of images."
18734 (interactive)
18735 (mapc 'delete-overlay org-inline-image-overlays)
18736 (setq org-inline-image-overlays nil))
18738 ;;;; Key bindings
18740 ;; Outline functions from `outline-mode-prefix-map'
18741 ;; that can be remapped in Org:
18742 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18743 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18744 (define-key org-mode-map [remap outline-forward-same-level]
18745 'org-forward-heading-same-level)
18746 (define-key org-mode-map [remap outline-backward-same-level]
18747 'org-backward-heading-same-level)
18748 (define-key org-mode-map [remap show-branches]
18749 'org-kill-note-or-show-branches)
18750 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18751 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18752 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18754 ;; Outline functions from `outline-mode-prefix-map' that can not
18755 ;; be remapped in Org:
18757 ;; - the column "key binding" shows whether the Outline function is still
18758 ;; available in Org mode on the same key that it has been bound to in
18759 ;; Outline mode:
18760 ;; - "overridden": key used for a different functionality in Org mode
18761 ;; - else: key still bound to the same Outline function in Org mode
18763 ;; | Outline function | key binding | Org replacement |
18764 ;; |------------------------------------+-------------+-----------------------|
18765 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18766 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18767 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18768 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18769 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18770 ;; | `show-entry' | overridden | no replacement |
18771 ;; | `show-children' | `C-c C-i' | visibility cycling |
18772 ;; | `show-branches' | `C-c C-k' | still same function |
18773 ;; | `show-subtree' | overridden | visibility cycling |
18774 ;; | `show-all' | overridden | no replacement |
18775 ;; | `hide-subtree' | overridden | visibility cycling |
18776 ;; | `hide-body' | overridden | no replacement |
18777 ;; | `hide-entry' | overridden | visibility cycling |
18778 ;; | `hide-leaves' | overridden | no replacement |
18779 ;; | `hide-sublevels' | overridden | no replacement |
18780 ;; | `hide-other' | overridden | no replacement |
18782 ;; Make `C-c C-x' a prefix key
18783 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18785 ;; TAB key with modifiers
18786 (org-defkey org-mode-map "\C-i" 'org-cycle)
18787 (org-defkey org-mode-map [(tab)] 'org-cycle)
18788 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18789 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18790 ;; The following line is necessary under Suse GNU/Linux
18791 (unless (featurep 'xemacs)
18792 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18793 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18794 (define-key org-mode-map [backtab] 'org-shifttab)
18796 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18797 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18798 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18800 ;; Cursor keys with modifiers
18801 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18802 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18803 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18804 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18806 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18807 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18808 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18809 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18811 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18812 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18813 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18814 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18816 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18817 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18818 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18819 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18821 ;; Babel keys
18822 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18823 (mapc (lambda (pair)
18824 (define-key org-babel-map (car pair) (cdr pair)))
18825 org-babel-key-bindings)
18827 ;;; Extra keys for tty access.
18828 ;; We only set them when really needed because otherwise the
18829 ;; menus don't show the simple keys
18831 (when (or org-use-extra-keys
18832 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18833 (not window-system))
18834 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18835 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18836 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18837 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18838 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18839 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18840 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18841 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18842 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18843 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18844 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18845 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18846 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18847 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18848 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18849 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18850 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18851 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18852 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18853 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18854 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18855 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18856 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18857 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18858 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18859 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18860 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18861 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18863 ;; All the other keys
18865 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18866 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18867 (if (boundp 'narrow-map)
18868 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18869 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18870 (if (boundp 'narrow-map)
18871 (org-defkey narrow-map "b" 'org-narrow-to-block)
18872 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18873 (if (boundp 'narrow-map)
18874 (org-defkey narrow-map "e" 'org-narrow-to-element)
18875 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18876 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18877 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18878 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18879 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18880 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18881 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18882 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18883 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18884 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18885 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18886 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18887 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18888 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18889 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18890 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18891 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18892 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
18893 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18894 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18895 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18896 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18897 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18898 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18899 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18900 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18901 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18902 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18903 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18904 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18905 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18906 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18907 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18908 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18909 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18910 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18911 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18912 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18913 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18914 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18915 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18916 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18917 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18918 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18919 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18920 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18921 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18922 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18923 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18924 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18925 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18926 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18927 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18928 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18929 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18930 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18931 (org-defkey org-mode-map "\C-c^" 'org-sort)
18932 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18933 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18934 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18935 (org-defkey org-mode-map "\C-m" 'org-return)
18936 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18937 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18938 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18939 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18940 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18941 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18942 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18943 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18944 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18945 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18946 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18947 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18948 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18949 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
18950 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18951 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18952 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18953 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18954 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18955 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18956 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18957 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18958 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18960 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18961 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18962 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18964 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18965 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18966 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18967 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18968 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18969 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18970 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18971 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18972 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18973 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18974 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18975 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18976 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18977 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18978 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18979 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18980 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18981 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18982 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18983 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18984 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18985 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18986 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18988 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18989 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18990 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18991 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18992 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18994 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18996 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18998 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18999 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19001 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19004 (when (featurep 'xemacs)
19005 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19008 (defconst org-speed-commands-default
19010 ("Outline Navigation")
19011 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19012 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19013 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19014 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19015 ("F" . org-next-block)
19016 ("B" . org-previous-block)
19017 ("u" . (org-speed-move-safe 'outline-up-heading))
19018 ("j" . org-goto)
19019 ("g" . (org-refile t))
19020 ("Outline Visibility")
19021 ("c" . org-cycle)
19022 ("C" . org-shifttab)
19023 (" " . org-display-outline-path)
19024 ("=" . org-columns)
19025 ("Outline Structure Editing")
19026 ("U" . org-shiftmetaup)
19027 ("D" . org-shiftmetadown)
19028 ("r" . org-metaright)
19029 ("l" . org-metaleft)
19030 ("R" . org-shiftmetaright)
19031 ("L" . org-shiftmetaleft)
19032 ("i" . (progn (forward-char 1) (call-interactively
19033 'org-insert-heading-respect-content)))
19034 ("^" . org-sort)
19035 ("w" . org-refile)
19036 ("a" . org-archive-subtree-default-with-confirmation)
19037 ("@" . org-mark-subtree)
19038 ("#" . org-toggle-comment)
19039 ("Clock Commands")
19040 ("I" . org-clock-in)
19041 ("O" . org-clock-out)
19042 ("Meta Data Editing")
19043 ("t" . org-todo)
19044 ("," . (org-priority))
19045 ("0" . (org-priority ?\ ))
19046 ("1" . (org-priority ?A))
19047 ("2" . (org-priority ?B))
19048 ("3" . (org-priority ?C))
19049 (":" . org-set-tags-command)
19050 ("e" . org-set-effort)
19051 ("E" . org-inc-effort)
19052 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19053 (org-entry-put (point) "APPT_WARNTIME" m)))
19054 ("Agenda Views etc")
19055 ("v" . org-agenda)
19056 ("/" . org-sparse-tree)
19057 ("Misc")
19058 ("o" . org-open-at-point)
19059 ("?" . org-speed-command-help)
19060 ("<" . (org-agenda-set-restriction-lock 'subtree))
19061 (">" . (org-agenda-remove-restriction-lock))
19063 "The default speed commands.")
19065 (defun org-print-speed-command (e)
19066 (if (> (length (car e)) 1)
19067 (progn
19068 (princ "\n")
19069 (princ (car e))
19070 (princ "\n")
19071 (princ (make-string (length (car e)) ?-))
19072 (princ "\n"))
19073 (princ (car e))
19074 (princ " ")
19075 (if (symbolp (cdr e))
19076 (princ (symbol-name (cdr e)))
19077 (prin1 (cdr e)))
19078 (princ "\n")))
19080 (defun org-speed-command-help ()
19081 "Show the available speed commands."
19082 (interactive)
19083 (if (not org-use-speed-commands)
19084 (error "Speed commands are not activated, customize `org-use-speed-commands'")
19085 (with-output-to-temp-buffer "*Help*"
19086 (princ "User-defined Speed commands\n===========================\n")
19087 (mapc 'org-print-speed-command org-speed-commands-user)
19088 (princ "\n")
19089 (princ "Built-in Speed commands\n=======================\n")
19090 (mapc 'org-print-speed-command org-speed-commands-default))
19091 (with-current-buffer "*Help*"
19092 (setq truncate-lines t))))
19094 (defun org-speed-move-safe (cmd)
19095 "Execute CMD, but make sure that the cursor always ends up in a headline.
19096 If not, return to the original position and throw an error."
19097 (interactive)
19098 (let ((pos (point)))
19099 (call-interactively cmd)
19100 (unless (and (bolp) (org-at-heading-p))
19101 (goto-char pos)
19102 (error "Boundary reached while executing %s" cmd))))
19104 (defvar org-self-insert-command-undo-counter 0)
19106 (defvar org-table-auto-blank-field) ; defined in org-table.el
19107 (defvar org-speed-command nil)
19109 (define-obsolete-function-alias
19110 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19112 (defun org-speed-command-activate (keys)
19113 "Hook for activating single-letter speed commands.
19114 `org-speed-commands-default' specifies a minimal command set.
19115 Use `org-speed-commands-user' for further customization."
19116 (when (or (and (bolp) (looking-at org-outline-regexp))
19117 (and (functionp org-use-speed-commands)
19118 (funcall org-use-speed-commands)))
19119 (cdr (assoc keys (append org-speed-commands-user
19120 org-speed-commands-default)))))
19122 (define-obsolete-function-alias
19123 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19125 (defun org-babel-speed-command-activate (keys)
19126 "Hook for activating single-letter code block commands."
19127 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19128 (cdr (assoc keys org-babel-key-bindings))))
19130 (defcustom org-speed-command-hook
19131 '(org-speed-command-default-hook org-babel-speed-command-hook)
19132 "Hook for activating speed commands at strategic locations.
19133 Hook functions are called in sequence until a valid handler is
19134 found.
19136 Each hook takes a single argument, a user-pressed command key
19137 which is also a `self-insert-command' from the global map.
19139 Within the hook, examine the cursor position and the command key
19140 and return nil or a valid handler as appropriate. Handler could
19141 be one of an interactive command, a function, or a form.
19143 Set `org-use-speed-commands' to non-nil value to enable this
19144 hook. The default setting is `org-speed-command-activate'."
19145 :group 'org-structure
19146 :version "24.1"
19147 :type 'hook)
19149 (defun org-self-insert-command (N)
19150 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19151 If the cursor is in a table looking at whitespace, the whitespace is
19152 overwritten, and the table is not marked as requiring realignment."
19153 (interactive "p")
19154 (org-check-before-invisible-edit 'insert)
19155 (cond
19156 ((and org-use-speed-commands
19157 (setq org-speed-command
19158 (run-hook-with-args-until-success
19159 'org-speed-command-hook (this-command-keys))))
19160 (cond
19161 ((commandp org-speed-command)
19162 (setq this-command org-speed-command)
19163 (call-interactively org-speed-command))
19164 ((functionp org-speed-command)
19165 (funcall org-speed-command))
19166 ((and org-speed-command (listp org-speed-command))
19167 (eval org-speed-command))
19168 (t (let (org-use-speed-commands)
19169 (call-interactively 'org-self-insert-command)))))
19170 ((and
19171 (org-table-p)
19172 (progn
19173 ;; check if we blank the field, and if that triggers align
19174 (and (featurep 'org-table) org-table-auto-blank-field
19175 (member last-command
19176 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19177 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19178 ;; got extra space, this field does not determine column width
19179 (let (org-table-may-need-update) (org-table-blank-field))
19180 ;; no extra space, this field may determine column width
19181 (org-table-blank-field)))
19183 (eq N 1)
19184 (looking-at "[^|\n]* |"))
19185 (let (org-table-may-need-update)
19186 (goto-char (1- (match-end 0)))
19187 (backward-delete-char 1)
19188 (goto-char (match-beginning 0))
19189 (self-insert-command N)))
19191 (setq org-table-may-need-update t)
19192 (self-insert-command N)
19193 (org-fix-tags-on-the-fly)
19194 (if org-self-insert-cluster-for-undo
19195 (if (not (eq last-command 'org-self-insert-command))
19196 (setq org-self-insert-command-undo-counter 1)
19197 (if (>= org-self-insert-command-undo-counter 20)
19198 (setq org-self-insert-command-undo-counter 1)
19199 (and (> org-self-insert-command-undo-counter 0)
19200 buffer-undo-list (listp buffer-undo-list)
19201 (not (cadr buffer-undo-list)) ; remove nil entry
19202 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19203 (setq org-self-insert-command-undo-counter
19204 (1+ org-self-insert-command-undo-counter))))))))
19206 (defun org-check-before-invisible-edit (kind)
19207 "Check is editing if kind KIND would be dangerous with invisible text around.
19208 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19209 ;; First, try to get out of here as quickly as possible, to reduce overhead
19210 (if (and org-catch-invisible-edits
19211 (or (not (boundp 'visible-mode)) (not visible-mode))
19212 (or (get-char-property (point) 'invisible)
19213 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19214 ;; OK, we need to take a closer look
19215 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19216 (invisible-before-point (if (bobp) nil (get-char-property
19217 (1- (point)) 'invisible)))
19218 (border-and-ok-direction
19220 ;; Check if we are acting predictably before invisible text
19221 (and invisible-at-point (not invisible-before-point)
19222 (memq kind '(insert delete-backward)))
19223 ;; Check if we are acting predictably after invisible text
19224 ;; This works not well, and I have turned it off. It seems
19225 ;; better to always show and stop after invisible text.
19226 ;; (and (not invisible-at-point) invisible-before-point
19227 ;; (memq kind '(insert delete)))
19229 (when (or (memq invisible-at-point '(outline org-hide-block t))
19230 (memq invisible-before-point '(outline org-hide-block t)))
19231 (if (eq org-catch-invisible-edits 'error)
19232 (error "Editing in invisible areas is prohibited - make visible first"))
19233 (if (and org-custom-properties-overlays
19234 (y-or-n-p "Display invisible properties in this buffer? "))
19235 (org-toggle-custom-properties-visibility)
19236 ;; Make the area visible
19237 (save-excursion
19238 (if invisible-before-point
19239 (goto-char (previous-single-char-property-change
19240 (point) 'invisible)))
19241 (org-cycle))
19242 (cond
19243 ((eq org-catch-invisible-edits 'show)
19244 ;; That's it, we do the edit after showing
19245 (message
19246 "Unfolding invisible region around point before editing")
19247 (sit-for 1))
19248 ((and (eq org-catch-invisible-edits 'smart)
19249 border-and-ok-direction)
19250 (message "Unfolding invisible region around point before editing"))
19252 ;; Don't do the edit, make the user repeat it in full visibility
19253 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19255 (defun org-fix-tags-on-the-fly ()
19256 (when (and (equal (char-after (point-at-bol)) ?*)
19257 (org-at-heading-p))
19258 (org-align-tags-here org-tags-column)))
19260 (defun org-delete-backward-char (N)
19261 "Like `delete-backward-char', insert whitespace at field end in tables.
19262 When deleting backwards, in tables this function will insert whitespace in
19263 front of the next \"|\" separator, to keep the table aligned. The table will
19264 still be marked for re-alignment if the field did fill the entire column,
19265 because, in this case the deletion might narrow the column."
19266 (interactive "p")
19267 (save-match-data
19268 (org-check-before-invisible-edit 'delete-backward)
19269 (if (and (org-table-p)
19270 (eq N 1)
19271 (string-match "|" (buffer-substring (point-at-bol) (point)))
19272 (looking-at ".*?|"))
19273 (let ((pos (point))
19274 (noalign (looking-at "[^|\n\r]* |"))
19275 (c org-table-may-need-update))
19276 (backward-delete-char N)
19277 (if (not overwrite-mode)
19278 (progn
19279 (skip-chars-forward "^|")
19280 (insert " ")
19281 (goto-char (1- pos))))
19282 ;; noalign: if there were two spaces at the end, this field
19283 ;; does not determine the width of the column.
19284 (if noalign (setq org-table-may-need-update c)))
19285 (backward-delete-char N)
19286 (org-fix-tags-on-the-fly))))
19288 (defun org-delete-char (N)
19289 "Like `delete-char', but insert whitespace at field end in tables.
19290 When deleting characters, in tables this function will insert whitespace in
19291 front of the next \"|\" separator, to keep the table aligned. The table will
19292 still be marked for re-alignment if the field did fill the entire column,
19293 because, in this case the deletion might narrow the column."
19294 (interactive "p")
19295 (save-match-data
19296 (org-check-before-invisible-edit 'delete)
19297 (if (and (org-table-p)
19298 (not (bolp))
19299 (not (= (char-after) ?|))
19300 (eq N 1))
19301 (if (looking-at ".*?|")
19302 (let ((pos (point))
19303 (noalign (looking-at "[^|\n\r]* |"))
19304 (c org-table-may-need-update))
19305 (replace-match
19306 (concat (substring (match-string 0) 1 -1) " |") nil t)
19307 (goto-char pos)
19308 ;; noalign: if there were two spaces at the end, this field
19309 ;; does not determine the width of the column.
19310 (if noalign (setq org-table-may-need-update c)))
19311 (delete-char N))
19312 (delete-char N)
19313 (org-fix-tags-on-the-fly))))
19315 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19316 (put 'org-self-insert-command 'delete-selection t)
19317 (put 'orgtbl-self-insert-command 'delete-selection t)
19318 (put 'org-delete-char 'delete-selection 'supersede)
19319 (put 'org-delete-backward-char 'delete-selection 'supersede)
19320 (put 'org-yank 'delete-selection 'yank)
19322 ;; Make `flyspell-mode' delay after some commands
19323 (put 'org-self-insert-command 'flyspell-delayed t)
19324 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19325 (put 'org-delete-char 'flyspell-delayed t)
19326 (put 'org-delete-backward-char 'flyspell-delayed t)
19328 ;; Make pabbrev-mode expand after org-mode commands
19329 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19330 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19332 ;; How to do this: Measure non-white length of current string
19333 ;; If equal to column width, we should realign.
19335 (defun org-remap (map &rest commands)
19336 "In MAP, remap the functions given in COMMANDS.
19337 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19338 (let (new old)
19339 (while commands
19340 (setq old (pop commands) new (pop commands))
19341 (if (fboundp 'command-remapping)
19342 (org-defkey map (vector 'remap old) new)
19343 (substitute-key-definition old new map global-map)))))
19345 (defun org-transpose-words ()
19346 "Transpose words for Org.
19347 This uses the `org-mode-transpose-word-syntax-table' syntax
19348 table, which interprets characters in `org-emphasis-alist' as
19349 word constituants."
19350 (interactive)
19351 (with-syntax-table org-mode-transpose-word-syntax-table
19352 (call-interactively 'transpose-words)))
19353 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19355 (when (eq org-enable-table-editor 'optimized)
19356 ;; If the user wants maximum table support, we need to hijack
19357 ;; some standard editing functions
19358 (org-remap org-mode-map
19359 'self-insert-command 'org-self-insert-command
19360 'delete-char 'org-delete-char
19361 'delete-backward-char 'org-delete-backward-char)
19362 (org-defkey org-mode-map "|" 'org-force-self-insert))
19364 (defvar org-ctrl-c-ctrl-c-hook nil
19365 "Hook for functions attaching themselves to `C-c C-c'.
19367 This can be used to add additional functionality to the C-c C-c
19368 key which executes context-dependent commands. This hook is run
19369 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19370 run after the last test.
19372 Each function will be called with no arguments. The function
19373 must check if the context is appropriate for it to act. If yes,
19374 it should do its thing and then return a non-nil value. If the
19375 context is wrong, just do nothing and return nil.")
19377 (defvar org-ctrl-c-ctrl-c-final-hook nil
19378 "Hook for functions attaching themselves to `C-c C-c'.
19380 This can be used to add additional functionality to the C-c C-c
19381 key which executes context-dependent commands. This hook is run
19382 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19383 before the first test.
19385 Each function will be called with no arguments. The function
19386 must check if the context is appropriate for it to act. If yes,
19387 it should do its thing and then return a non-nil value. If the
19388 context is wrong, just do nothing and return nil.")
19390 (defvar org-tab-first-hook nil
19391 "Hook for functions to attach themselves to TAB.
19392 See `org-ctrl-c-ctrl-c-hook' for more information.
19393 This hook runs as the first action when TAB is pressed, even before
19394 `org-cycle' messes around with the `outline-regexp' to cater for
19395 inline tasks and plain list item folding.
19396 If any function in this hook returns t, any other actions that
19397 would have been caused by TAB (such as table field motion or visibility
19398 cycling) will not occur.")
19400 (defvar org-tab-after-check-for-table-hook nil
19401 "Hook for functions to attach themselves to TAB.
19402 See `org-ctrl-c-ctrl-c-hook' for more information.
19403 This hook runs after it has been established that the cursor is not in a
19404 table, but before checking if the cursor is in a headline or if global cycling
19405 should be done.
19406 If any function in this hook returns t, not other actions like visibility
19407 cycling will be done.")
19409 (defvar org-tab-after-check-for-cycling-hook nil
19410 "Hook for functions to attach themselves to TAB.
19411 See `org-ctrl-c-ctrl-c-hook' for more information.
19412 This hook runs after it has been established that not table field motion and
19413 not visibility should be done because of current context. This is probably
19414 the place where a package like yasnippets can hook in.")
19416 (defvar org-tab-before-tab-emulation-hook nil
19417 "Hook for functions to attach themselves to TAB.
19418 See `org-ctrl-c-ctrl-c-hook' for more information.
19419 This hook runs after every other options for TAB have been exhausted, but
19420 before indentation and \t insertion takes place.")
19422 (defvar org-metaleft-hook nil
19423 "Hook for functions attaching themselves to `M-left'.
19424 See `org-ctrl-c-ctrl-c-hook' for more information.")
19425 (defvar org-metaright-hook nil
19426 "Hook for functions attaching themselves to `M-right'.
19427 See `org-ctrl-c-ctrl-c-hook' for more information.")
19428 (defvar org-metaup-hook nil
19429 "Hook for functions attaching themselves to `M-up'.
19430 See `org-ctrl-c-ctrl-c-hook' for more information.")
19431 (defvar org-metadown-hook nil
19432 "Hook for functions attaching themselves to `M-down'.
19433 See `org-ctrl-c-ctrl-c-hook' for more information.")
19434 (defvar org-shiftmetaleft-hook nil
19435 "Hook for functions attaching themselves to `M-S-left'.
19436 See `org-ctrl-c-ctrl-c-hook' for more information.")
19437 (defvar org-shiftmetaright-hook nil
19438 "Hook for functions attaching themselves to `M-S-right'.
19439 See `org-ctrl-c-ctrl-c-hook' for more information.")
19440 (defvar org-shiftmetaup-hook nil
19441 "Hook for functions attaching themselves to `M-S-up'.
19442 See `org-ctrl-c-ctrl-c-hook' for more information.")
19443 (defvar org-shiftmetadown-hook nil
19444 "Hook for functions attaching themselves to `M-S-down'.
19445 See `org-ctrl-c-ctrl-c-hook' for more information.")
19446 (defvar org-metareturn-hook nil
19447 "Hook for functions attaching themselves to `M-RET'.
19448 See `org-ctrl-c-ctrl-c-hook' for more information.")
19449 (defvar org-shiftup-hook nil
19450 "Hook for functions attaching themselves to `S-up'.
19451 See `org-ctrl-c-ctrl-c-hook' for more information.")
19452 (defvar org-shiftup-final-hook nil
19453 "Hook for functions attaching themselves to `S-up'.
19454 This one runs after all other options except shift-select have been excluded.
19455 See `org-ctrl-c-ctrl-c-hook' for more information.")
19456 (defvar org-shiftdown-hook nil
19457 "Hook for functions attaching themselves to `S-down'.
19458 See `org-ctrl-c-ctrl-c-hook' for more information.")
19459 (defvar org-shiftdown-final-hook nil
19460 "Hook for functions attaching themselves to `S-down'.
19461 This one runs after all other options except shift-select have been excluded.
19462 See `org-ctrl-c-ctrl-c-hook' for more information.")
19463 (defvar org-shiftleft-hook nil
19464 "Hook for functions attaching themselves to `S-left'.
19465 See `org-ctrl-c-ctrl-c-hook' for more information.")
19466 (defvar org-shiftleft-final-hook nil
19467 "Hook for functions attaching themselves to `S-left'.
19468 This one runs after all other options except shift-select have been excluded.
19469 See `org-ctrl-c-ctrl-c-hook' for more information.")
19470 (defvar org-shiftright-hook nil
19471 "Hook for functions attaching themselves to `S-right'.
19472 See `org-ctrl-c-ctrl-c-hook' for more information.")
19473 (defvar org-shiftright-final-hook nil
19474 "Hook for functions attaching themselves to `S-right'.
19475 This one runs after all other options except shift-select have been excluded.
19476 See `org-ctrl-c-ctrl-c-hook' for more information.")
19478 (defun org-modifier-cursor-error ()
19479 "Throw an error, a modified cursor command was applied in wrong context."
19480 (error "This command is active in special context like tables, headlines or items"))
19482 (defun org-shiftselect-error ()
19483 "Throw an error because Shift-Cursor command was applied in wrong context."
19484 (if (and (boundp 'shift-select-mode) shift-select-mode)
19485 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19486 (error "This command works only in special context like headlines or timestamps")))
19488 (defun org-call-for-shift-select (cmd)
19489 (let ((this-command-keys-shift-translated t))
19490 (call-interactively cmd)))
19492 (defun org-shifttab (&optional arg)
19493 "Global visibility cycling or move to previous table field.
19494 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19495 on context.
19496 See the individual commands for more information."
19497 (interactive "P")
19498 (cond
19499 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19500 ((integerp arg)
19501 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19502 (message "Content view to level: %d" arg)
19503 (org-content (prefix-numeric-value arg2))
19504 (setq org-cycle-global-status 'overview)))
19505 (t (call-interactively 'org-global-cycle))))
19507 (defun org-shiftmetaleft ()
19508 "Promote subtree or delete table column.
19509 Calls `org-promote-subtree', `org-outdent-item-tree', or
19510 `org-table-delete-column', depending on context. See the
19511 individual commands for more information."
19512 (interactive)
19513 (cond
19514 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19515 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19516 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19517 ((if (not (org-region-active-p)) (org-at-item-p)
19518 (save-excursion (goto-char (region-beginning))
19519 (org-at-item-p)))
19520 (call-interactively 'org-outdent-item-tree))
19521 (t (org-modifier-cursor-error))))
19523 (defun org-shiftmetaright ()
19524 "Demote subtree or insert table column.
19525 Calls `org-demote-subtree', `org-indent-item-tree', or
19526 `org-table-insert-column', depending on context. See the
19527 individual commands for more information."
19528 (interactive)
19529 (cond
19530 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19531 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19532 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19533 ((if (not (org-region-active-p)) (org-at-item-p)
19534 (save-excursion (goto-char (region-beginning))
19535 (org-at-item-p)))
19536 (call-interactively 'org-indent-item-tree))
19537 (t (org-modifier-cursor-error))))
19539 (defun org-shiftmetaup (&optional arg)
19540 "Move subtree up or kill table row.
19541 Calls `org-move-subtree-up' or `org-table-kill-row' or
19542 `org-move-item-up' or `org-timestamp-up', depending on context.
19543 See the individual commands for more information."
19544 (interactive "P")
19545 (cond
19546 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19547 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19548 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19549 ((org-at-item-p) (call-interactively 'org-move-item-up))
19550 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19551 (call-interactively 'org-timestamp-up)))
19552 (t (call-interactively 'org-drag-line-backward))))
19554 (defun org-shiftmetadown (&optional arg)
19555 "Move subtree down or insert table row.
19556 Calls `org-move-subtree-down' or `org-table-insert-row' or
19557 `org-move-item-down' or `org-timestamp-up', depending on context.
19558 See the individual commands for more information."
19559 (interactive "P")
19560 (cond
19561 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19562 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19563 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19564 ((org-at-item-p) (call-interactively 'org-move-item-down))
19565 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19566 (call-interactively 'org-timestamp-down)))
19567 (t (call-interactively 'org-drag-line-forward))))
19569 (defsubst org-hidden-tree-error ()
19570 (error
19571 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19573 (defun org-metaleft (&optional arg)
19574 "Promote heading or move table column to left.
19575 Calls `org-do-promote' or `org-table-move-column', depending on context.
19576 With no specific context, calls the Emacs default `backward-word'.
19577 See the individual commands for more information."
19578 (interactive "P")
19579 (cond
19580 ((run-hook-with-args-until-success 'org-metaleft-hook))
19581 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19582 ((org-with-limited-levels
19583 (or (org-at-heading-p)
19584 (and (org-region-active-p)
19585 (save-excursion
19586 (goto-char (region-beginning))
19587 (org-at-heading-p)))))
19588 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19589 (call-interactively 'org-do-promote))
19590 ;; At an inline task.
19591 ((org-at-heading-p)
19592 (call-interactively 'org-inlinetask-promote))
19593 ((or (org-at-item-p)
19594 (and (org-region-active-p)
19595 (save-excursion
19596 (goto-char (region-beginning))
19597 (org-at-item-p))))
19598 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19599 (call-interactively 'org-outdent-item))
19600 (t (call-interactively 'backward-word))))
19602 (defun org-metaright (&optional arg)
19603 "Demote a subtree, a list item or move table column to right.
19604 In front of a drawer or a block keyword, indent it correctly.
19605 With no specific context, calls the Emacs default `forward-word'.
19606 See the individual commands for more information."
19607 (interactive "P")
19608 (cond
19609 ((run-hook-with-args-until-success 'org-metaright-hook))
19610 ((org-at-table-p) (call-interactively 'org-table-move-column))
19611 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19612 ((org-at-block-p) (call-interactively 'org-indent-block))
19613 ((org-with-limited-levels
19614 (or (org-at-heading-p)
19615 (and (org-region-active-p)
19616 (save-excursion
19617 (goto-char (region-beginning))
19618 (org-at-heading-p)))))
19619 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19620 (call-interactively 'org-do-demote))
19621 ;; At an inline task.
19622 ((org-at-heading-p)
19623 (call-interactively 'org-inlinetask-demote))
19624 ((or (org-at-item-p)
19625 (and (org-region-active-p)
19626 (save-excursion
19627 (goto-char (region-beginning))
19628 (org-at-item-p))))
19629 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19630 (call-interactively 'org-indent-item))
19631 (t (call-interactively 'forward-word))))
19633 (defun org-check-for-hidden (what)
19634 "Check if there are hidden headlines/items in the current visual line.
19635 WHAT can be either `headlines' or `items'. If the current line is
19636 an outline or item heading and it has a folded subtree below it,
19637 this function returns t, nil otherwise."
19638 (let ((re (cond
19639 ((eq what 'headlines) org-outline-regexp-bol)
19640 ((eq what 'items) (org-item-beginning-re))
19641 (t (error "This should not happen"))))
19642 beg end)
19643 (save-excursion
19644 (catch 'exit
19645 (unless (org-region-active-p)
19646 (setq beg (point-at-bol))
19647 (beginning-of-line 2)
19648 (while (and (not (eobp)) ;; this is like `next-line'
19649 (get-char-property (1- (point)) 'invisible))
19650 (beginning-of-line 2))
19651 (setq end (point))
19652 (goto-char beg)
19653 (goto-char (point-at-eol))
19654 (setq end (max end (point)))
19655 (while (re-search-forward re end t)
19656 (if (get-char-property (match-beginning 0) 'invisible)
19657 (throw 'exit t))))
19658 nil))))
19660 (defun org-metaup (&optional arg)
19661 "Move subtree up or move table row up.
19662 Calls `org-move-subtree-up' or `org-table-move-row' or
19663 `org-move-item-up', depending on context. See the individual commands
19664 for more information."
19665 (interactive "P")
19666 (cond
19667 ((run-hook-with-args-until-success 'org-metaup-hook))
19668 ((org-region-active-p)
19669 (let* ((a (min (region-beginning) (region-end)))
19670 (b (1- (max (region-beginning) (region-end))))
19671 (c (save-excursion (goto-char a)
19672 (move-beginning-of-line 0)))
19673 (d (save-excursion (goto-char a)
19674 (move-end-of-line 0) (point))))
19675 (transpose-regions a b c d)
19676 (goto-char c)))
19677 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19678 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19679 ((org-at-item-p) (call-interactively 'org-move-item-up))
19680 (t (org-drag-element-backward))))
19682 (defun org-metadown (&optional arg)
19683 "Move subtree down or move table row down.
19684 Calls `org-move-subtree-down' or `org-table-move-row' or
19685 `org-move-item-down', depending on context. See the individual
19686 commands for more information."
19687 (interactive "P")
19688 (cond
19689 ((run-hook-with-args-until-success 'org-metadown-hook))
19690 ((org-region-active-p)
19691 (let* ((a (min (region-beginning) (region-end)))
19692 (b (max (region-beginning) (region-end)))
19693 (c (save-excursion (goto-char b)
19694 (move-beginning-of-line 1)))
19695 (d (save-excursion (goto-char b)
19696 (move-end-of-line 1) (1+ (point)))))
19697 (transpose-regions a b c d)
19698 (goto-char d)))
19699 ((org-at-table-p) (call-interactively 'org-table-move-row))
19700 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19701 ((org-at-item-p) (call-interactively 'org-move-item-down))
19702 (t (org-drag-element-forward))))
19704 (defun org-shiftup (&optional arg)
19705 "Increase item in timestamp or increase priority of current headline.
19706 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19707 depending on context. See the individual commands for more information."
19708 (interactive "P")
19709 (cond
19710 ((run-hook-with-args-until-success 'org-shiftup-hook))
19711 ((and org-support-shift-select (org-region-active-p))
19712 (org-call-for-shift-select 'previous-line))
19713 ((org-at-timestamp-p t)
19714 (call-interactively (if org-edit-timestamp-down-means-later
19715 'org-timestamp-down 'org-timestamp-up)))
19716 ((and (not (eq org-support-shift-select 'always))
19717 org-enable-priority-commands
19718 (org-at-heading-p))
19719 (call-interactively 'org-priority-up))
19720 ((and (not org-support-shift-select) (org-at-item-p))
19721 (call-interactively 'org-previous-item))
19722 ((org-clocktable-try-shift 'up arg))
19723 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19724 (org-support-shift-select
19725 (org-call-for-shift-select 'previous-line))
19726 (t (org-shiftselect-error))))
19728 (defun org-shiftdown (&optional arg)
19729 "Decrease item in timestamp or decrease priority of current headline.
19730 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19731 depending on context. See the individual commands for more information."
19732 (interactive "P")
19733 (cond
19734 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19735 ((and org-support-shift-select (org-region-active-p))
19736 (org-call-for-shift-select 'next-line))
19737 ((org-at-timestamp-p t)
19738 (call-interactively (if org-edit-timestamp-down-means-later
19739 'org-timestamp-up 'org-timestamp-down)))
19740 ((and (not (eq org-support-shift-select 'always))
19741 org-enable-priority-commands
19742 (org-at-heading-p))
19743 (call-interactively 'org-priority-down))
19744 ((and (not org-support-shift-select) (org-at-item-p))
19745 (call-interactively 'org-next-item))
19746 ((org-clocktable-try-shift 'down arg))
19747 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19748 (org-support-shift-select
19749 (org-call-for-shift-select 'next-line))
19750 (t (org-shiftselect-error))))
19752 (defun org-shiftright (&optional arg)
19753 "Cycle the thing at point or in the current line, depending on context.
19754 Depending on context, this does one of the following:
19756 - switch a timestamp at point one day into the future
19757 - on a headline, switch to the next TODO keyword.
19758 - on an item, switch entire list to the next bullet type
19759 - on a property line, switch to the next allowed value
19760 - on a clocktable definition line, move time block into the future"
19761 (interactive "P")
19762 (cond
19763 ((run-hook-with-args-until-success 'org-shiftright-hook))
19764 ((and org-support-shift-select (org-region-active-p))
19765 (org-call-for-shift-select 'forward-char))
19766 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19767 ((and (not (eq org-support-shift-select 'always))
19768 (org-at-heading-p))
19769 (let ((org-inhibit-logging
19770 (not org-treat-S-cursor-todo-selection-as-state-change))
19771 (org-inhibit-blocking
19772 (not org-treat-S-cursor-todo-selection-as-state-change)))
19773 (org-call-with-arg 'org-todo 'right)))
19774 ((or (and org-support-shift-select
19775 (not (eq org-support-shift-select 'always))
19776 (org-at-item-bullet-p))
19777 (and (not org-support-shift-select) (org-at-item-p)))
19778 (org-call-with-arg 'org-cycle-list-bullet nil))
19779 ((and (not (eq org-support-shift-select 'always))
19780 (org-at-property-p))
19781 (call-interactively 'org-property-next-allowed-value))
19782 ((org-clocktable-try-shift 'right arg))
19783 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19784 (org-support-shift-select
19785 (org-call-for-shift-select 'forward-char))
19786 (t (org-shiftselect-error))))
19788 (defun org-shiftleft (&optional arg)
19789 "Cycle the thing at point or in the current line, depending on context.
19790 Depending on context, this does one of the following:
19792 - switch a timestamp at point one day into the past
19793 - on a headline, switch to the previous TODO keyword.
19794 - on an item, switch entire list to the previous bullet type
19795 - on a property line, switch to the previous allowed value
19796 - on a clocktable definition line, move time block into the past"
19797 (interactive "P")
19798 (cond
19799 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19800 ((and org-support-shift-select (org-region-active-p))
19801 (org-call-for-shift-select 'backward-char))
19802 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19803 ((and (not (eq org-support-shift-select 'always))
19804 (org-at-heading-p))
19805 (let ((org-inhibit-logging
19806 (not org-treat-S-cursor-todo-selection-as-state-change))
19807 (org-inhibit-blocking
19808 (not org-treat-S-cursor-todo-selection-as-state-change)))
19809 (org-call-with-arg 'org-todo 'left)))
19810 ((or (and org-support-shift-select
19811 (not (eq org-support-shift-select 'always))
19812 (org-at-item-bullet-p))
19813 (and (not org-support-shift-select) (org-at-item-p)))
19814 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19815 ((and (not (eq org-support-shift-select 'always))
19816 (org-at-property-p))
19817 (call-interactively 'org-property-previous-allowed-value))
19818 ((org-clocktable-try-shift 'left arg))
19819 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19820 (org-support-shift-select
19821 (org-call-for-shift-select 'backward-char))
19822 (t (org-shiftselect-error))))
19824 (defun org-shiftcontrolright ()
19825 "Switch to next TODO set."
19826 (interactive)
19827 (cond
19828 ((and org-support-shift-select (org-region-active-p))
19829 (org-call-for-shift-select 'forward-word))
19830 ((and (not (eq org-support-shift-select 'always))
19831 (org-at-heading-p))
19832 (org-call-with-arg 'org-todo 'nextset))
19833 (org-support-shift-select
19834 (org-call-for-shift-select 'forward-word))
19835 (t (org-shiftselect-error))))
19837 (defun org-shiftcontrolleft ()
19838 "Switch to previous TODO set."
19839 (interactive)
19840 (cond
19841 ((and org-support-shift-select (org-region-active-p))
19842 (org-call-for-shift-select 'backward-word))
19843 ((and (not (eq org-support-shift-select 'always))
19844 (org-at-heading-p))
19845 (org-call-with-arg 'org-todo 'previousset))
19846 (org-support-shift-select
19847 (org-call-for-shift-select 'backward-word))
19848 (t (org-shiftselect-error))))
19850 (defun org-shiftcontrolup (&optional n)
19851 "Change timestamps synchronously up in CLOCK log lines.
19852 Optional argument N tells to change by that many units."
19853 (interactive "P")
19854 (cond ((and (not org-support-shift-select)
19855 (org-at-clock-log-p)
19856 (org-at-timestamp-p t))
19857 (org-clock-timestamps-up n))
19858 (t (org-shiftselect-error))))
19860 (defun org-shiftcontroldown (&optional n)
19861 "Change timestamps synchronously down in CLOCK log lines.
19862 Optional argument N tells to change by that many units."
19863 (interactive "P")
19864 (cond ((and (not org-support-shift-select)
19865 (org-at-clock-log-p)
19866 (org-at-timestamp-p t))
19867 (org-clock-timestamps-down n))
19868 (t (org-shiftselect-error))))
19870 (defun org-ctrl-c-ret ()
19871 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19872 (interactive)
19873 (cond
19874 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19875 (t (call-interactively 'org-insert-heading))))
19877 (defun org-find-visible ()
19878 (let ((s (point)))
19879 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19880 (get-char-property s 'invisible)))
19882 (defun org-find-invisible ()
19883 (let ((s (point)))
19884 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19885 (not (get-char-property s 'invisible))))
19888 (defun org-copy-visible (beg end)
19889 "Copy the visible parts of the region."
19890 (interactive "r")
19891 (let (snippets s)
19892 (save-excursion
19893 (save-restriction
19894 (narrow-to-region beg end)
19895 (setq s (goto-char (point-min)))
19896 (while (not (= (point) (point-max)))
19897 (goto-char (org-find-invisible))
19898 (push (buffer-substring s (point)) snippets)
19899 (setq s (goto-char (org-find-visible))))))
19900 (kill-new (apply 'concat (nreverse snippets)))))
19902 (defun org-copy-special ()
19903 "Copy region in table or copy current subtree.
19904 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19905 See the individual commands for more information."
19906 (interactive)
19907 (call-interactively
19908 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19910 (defun org-cut-special ()
19911 "Cut region in table or cut current subtree.
19912 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19913 See the individual commands for more information."
19914 (interactive)
19915 (call-interactively
19916 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19918 (defun org-paste-special (arg)
19919 "Paste rectangular region into table, or past subtree relative to level.
19920 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19921 See the individual commands for more information."
19922 (interactive "P")
19923 (if (org-at-table-p)
19924 (org-table-paste-rectangle)
19925 (org-paste-subtree arg)))
19927 (defsubst org-in-fixed-width-region-p ()
19928 "Is point in a fixed-width region?"
19929 (save-match-data
19930 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19932 (defun org-edit-special (&optional arg)
19933 "Call a special editor for the element at point.
19934 When at a table, call the formula editor with `org-table-edit-formulas'.
19935 When in a source code block, call `org-edit-src-code'.
19936 When in a fixed-width region, call `org-edit-fixed-width-region'.
19937 When at an #+INCLUDE keyword, visit the included file.
19938 On a link, call `ffap' to visit the link at point.
19939 Otherwise, return a user error."
19940 (interactive)
19941 (let ((element (org-element-at-point)))
19942 (assert (not buffer-read-only) nil
19943 "Buffer is read-only: %s" (buffer-name))
19944 (case (org-element-type element)
19945 (src-block
19946 (if (not arg) (org-edit-src-code)
19947 (let* ((info (org-babel-get-src-block-info))
19948 (lang (nth 0 info))
19949 (params (nth 2 info))
19950 (session (cdr (assq :session params))))
19951 (if (not session) (org-edit-src-code)
19952 ;; At a src-block with a session and function called with
19953 ;; an ARG: switch to the buffer related to the inferior
19954 ;; process.
19955 (funcall (intern (concat "org-babel-prep-session:" lang))
19956 session params)))))
19957 (keyword
19958 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
19959 (find-file
19960 (org-remove-double-quotes
19961 (car (org-split-string (org-element-property :value element)))))
19962 (user-error "No special environment to edit here")))
19963 (table
19964 (if (eq (org-element-property :type element) 'table.el)
19965 (org-edit-src-code)
19966 (call-interactively 'org-table-edit-formulas)))
19967 ;; Only Org tables contain `table-row' type elements.
19968 (table-row (call-interactively 'org-table-edit-formulas))
19969 ((example-block export-block) (org-edit-src-code))
19970 (fixed-width (org-edit-fixed-width-region))
19971 (otherwise
19972 ;; No notable element at point. Though, we may be at a link,
19973 ;; which is an object. Thus, scan deeper.
19974 (if (eq (org-element-type (org-element-context element)) 'link)
19975 (call-interactively 'ffap)
19976 (user-error "No special environment to edit here"))))))
19978 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19979 (defun org-ctrl-c-ctrl-c (&optional arg)
19980 "Set tags in headline, or update according to changed information at point.
19982 This command does many different things, depending on context:
19984 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19985 this is what we do.
19987 - If the cursor is on a statistics cookie, update it.
19989 - If the cursor is in a headline, prompt for tags and insert them
19990 into the current line, aligned to `org-tags-column'. When called
19991 with prefix arg, realign all tags in the current buffer.
19993 - If the cursor is in one of the special #+KEYWORD lines, this
19994 triggers scanning the buffer for these lines and updating the
19995 information.
19997 - If the cursor is inside a table, realign the table. This command
19998 works even if the automatic table editor has been turned off.
20000 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20001 the entire table.
20003 - If the cursor is at a footnote reference or definition, jump to
20004 the corresponding definition or references, respectively.
20006 - If the cursor is a the beginning of a dynamic block, update it.
20008 - If the current buffer is a capture buffer, close note and file it.
20010 - If the cursor is on a <<<target>>>, update radio targets and
20011 corresponding links in this buffer.
20013 - If the cursor is on a numbered item in a plain list, renumber the
20014 ordered list.
20016 - If the cursor is on a checkbox, toggle it.
20018 - If the cursor is on a code block, evaluate it. The variable
20019 `org-confirm-babel-evaluate' can be used to control prompting
20020 before code block evaluation, by default every code block
20021 evaluation requires confirmation. Code block evaluation can be
20022 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20023 (interactive "P")
20024 (cond
20025 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20026 org-occur-highlights
20027 org-latex-fragment-image-overlays)
20028 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20029 (org-remove-occur-highlights)
20030 (org-remove-latex-fragment-image-overlays)
20031 (message "Temporary highlights/overlays removed from current buffer"))
20032 ((and (local-variable-p 'org-finish-function (current-buffer))
20033 (fboundp org-finish-function))
20034 (funcall org-finish-function))
20035 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20037 (let* ((context (org-element-context)) (type (org-element-type context)))
20038 ;; Test if point is within a blank line.
20039 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20040 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20041 (user-error "C-c C-c can do nothing useful at this location"))
20042 ;; For convenience: at the first line of a paragraph on the
20043 ;; same line as an item, apply function on that item instead.
20044 (when (eq type 'paragraph)
20045 (let ((parent (org-element-property :parent context)))
20046 (when (and (eq (org-element-type parent) 'item)
20047 (= (point-at-bol) (org-element-property :begin parent)))
20048 (setq context parent type 'item))))
20049 ;; Act according to type of element or object at point.
20050 (case type
20051 (clock (org-clock-update-time-maybe))
20052 (dynamic-block
20053 (save-excursion
20054 (goto-char (org-element-property :post-affiliated context))
20055 (org-update-dblock)))
20056 (footnote-definition
20057 (goto-char (org-element-property :post-affiliated context))
20058 (call-interactively 'org-footnote-action))
20059 (footnote-reference (call-interactively 'org-footnote-action))
20060 ((headline inlinetask)
20061 (save-excursion (goto-char (org-element-property :begin context))
20062 (call-interactively 'org-set-tags)))
20063 (item
20064 ;; At an item: a double C-u set checkbox to "[-]"
20065 ;; unconditionally, whereas a single one will toggle its
20066 ;; presence. Without an universal argument, if the item
20067 ;; has a checkbox, toggle it. Otherwise repair the list.
20068 (let* ((box (org-element-property :checkbox context))
20069 (struct (org-element-property :structure context))
20070 (old-struct (copy-tree struct))
20071 (parents (org-list-parents-alist struct))
20072 (prevs (org-list-prevs-alist struct))
20073 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20074 (org-list-set-checkbox
20075 (org-element-property :begin context) struct
20076 (cond ((equal arg '(16)) "[-]")
20077 ((and (not box) (equal arg '(4))) "[ ]")
20078 ((or (not box) (equal arg '(4))) nil)
20079 ((eq box 'on) "[ ]")
20080 (t "[X]")))
20081 ;; Mimic `org-list-write-struct' but with grabbing
20082 ;; a return value from `org-list-struct-fix-box'.
20083 (org-list-struct-fix-ind struct parents 2)
20084 (org-list-struct-fix-item-end struct)
20085 (org-list-struct-fix-bul struct prevs)
20086 (org-list-struct-fix-ind struct parents)
20087 (let ((block-item
20088 (org-list-struct-fix-box struct parents prevs orderedp)))
20089 (if (and box (equal struct old-struct))
20090 (if (equal arg '(16))
20091 (message "Checkboxes already reset")
20092 (user-error "Cannot toggle this checkbox: %s"
20093 (if (eq box 'on)
20094 "all subitems checked"
20095 "unchecked subitems")))
20096 (org-list-struct-apply-struct struct old-struct)
20097 (org-update-checkbox-count-maybe))
20098 (when block-item
20099 (message "Checkboxes were removed due to empty box at line %d"
20100 (org-current-line block-item))))))
20101 (keyword
20102 (let ((org-inhibit-startup-visibility-stuff t)
20103 (org-startup-align-all-tables nil))
20104 (when (boundp 'org-table-coordinate-overlays)
20105 (mapc 'delete-overlay org-table-coordinate-overlays)
20106 (setq org-table-coordinate-overlays nil))
20107 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20108 (message "Local setup has been refreshed"))
20109 (plain-list
20110 ;; At a plain list, with a double C-u argument, set
20111 ;; checkboxes of each item to "[-]", whereas a single one
20112 ;; will toggle their presence according to the state of the
20113 ;; first item in the list. Without an argument, repair the
20114 ;; list.
20115 (let* ((begin (org-element-property :contents-begin context))
20116 (struct (org-element-property :structure context))
20117 (old-struct (copy-tree struct))
20118 (first-box (save-excursion
20119 (goto-char begin)
20120 (looking-at org-list-full-item-re)
20121 (match-string-no-properties 3)))
20122 (new-box (cond ((equal arg '(16)) "[-]")
20123 ((equal arg '(4)) (unless first-box "[ ]"))
20124 ((equal first-box "[X]") "[ ]")
20125 (t "[X]"))))
20126 (cond
20127 (arg
20128 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20129 (org-list-get-all-items
20130 begin struct (org-list-prevs-alist struct))))
20131 ((and first-box (eq (point) begin))
20132 ;; For convenience, when point is at bol on the first
20133 ;; item of the list and no argument is provided, simply
20134 ;; toggle checkbox of that item, if any.
20135 (org-list-set-checkbox begin struct new-box)))
20136 (org-list-write-struct
20137 struct (org-list-parents-alist struct) old-struct)
20138 (org-update-checkbox-count-maybe)
20139 (save-excursion (goto-char begin) (org-list-send-list 'maybe))))
20140 ((property-drawer node-property)
20141 (call-interactively 'org-property-action))
20142 ((radio-target target)
20143 (call-interactively 'org-update-radio-target-regexp))
20144 (statistics-cookie
20145 (call-interactively 'org-update-statistics-cookies))
20146 ((table table-cell table-row)
20147 ;; At a table, recalculate every field and align it. Also
20148 ;; send the table if necessary. If the table has
20149 ;; a `table.el' type, just give up. At a table row or
20150 ;; cell, maybe recalculate line but always align table.
20151 (if (eq (org-element-property :type context) 'table.el)
20152 (message "Use C-c ' to edit table.el tables")
20153 (let ((org-enable-table-editor t))
20154 (if (or (eq type 'table)
20155 ;; Check if point is at a TBLFM line.
20156 (and (eq type 'table-row)
20157 (= (point) (org-element-property :end context))))
20158 (save-excursion
20159 (goto-char (org-element-property :contents-begin context))
20160 (org-call-with-arg 'org-table-recalculate (or arg t))
20161 (orgtbl-send-table 'maybe))
20162 (org-table-maybe-eval-formula)
20163 (cond (arg (call-interactively 'org-table-recalculate))
20164 ((org-table-maybe-recalculate-line))
20165 (t (org-table-align)))))))
20166 (timestamp (org-timestamp-change 0 'day))
20167 (otherwise
20168 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20169 (user-error
20170 "C-c C-c can do nothing useful at this location")))))))))
20172 (defun org-mode-restart ()
20173 "Restart Org-mode, to scan again for special lines.
20174 Also updates the keyword regular expressions."
20175 (interactive)
20176 (org-mode)
20177 (message "Org-mode restarted"))
20179 (defun org-kill-note-or-show-branches ()
20180 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20181 (interactive)
20182 (if (not org-finish-function)
20183 (progn
20184 (hide-subtree)
20185 (call-interactively 'show-branches))
20186 (let ((org-note-abort t))
20187 (funcall org-finish-function))))
20189 (defun org-return (&optional indent)
20190 "Goto next table row or insert a newline.
20191 Calls `org-table-next-row' or `newline', depending on context.
20192 See the individual commands for more information."
20193 (interactive)
20194 (let (org-ts-what)
20195 (cond
20196 ((or (bobp) (org-in-src-block-p))
20197 (if indent (newline-and-indent) (newline)))
20198 ((org-at-table-p)
20199 (org-table-justify-field-maybe)
20200 (call-interactively 'org-table-next-row))
20201 ;; when `newline-and-indent' is called within a list, make sure
20202 ;; text moved stays inside the item.
20203 ((and (org-in-item-p) indent)
20204 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20205 (progn
20206 (save-match-data (newline))
20207 (org-indent-line-to (length (match-string 0))))
20208 (let ((ind (org-get-indentation)))
20209 (newline)
20210 (if (org-looking-back org-list-end-re)
20211 (org-indent-line)
20212 (org-indent-line-to ind)))))
20213 ((and org-return-follows-link
20214 (org-at-timestamp-p t)
20215 (not (eq org-ts-what 'after)))
20216 (org-follow-timestamp-link))
20217 ((and org-return-follows-link
20218 (let ((tprop (get-text-property (point) 'face)))
20219 (or (eq tprop 'org-link)
20220 (and (listp tprop) (memq 'org-link tprop)))))
20221 (call-interactively 'org-open-at-point))
20222 ((and (org-at-heading-p)
20223 (looking-at
20224 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20225 (org-show-entry)
20226 (end-of-line 1)
20227 (newline))
20228 (t (if indent (newline-and-indent) (newline))))))
20230 (defun org-return-indent ()
20231 "Goto next table row or insert a newline and indent.
20232 Calls `org-table-next-row' or `newline-and-indent', depending on
20233 context. See the individual commands for more information."
20234 (interactive)
20235 (org-return t))
20237 (defun org-ctrl-c-star ()
20238 "Compute table, or change heading status of lines.
20239 Calls `org-table-recalculate' or `org-toggle-heading',
20240 depending on context."
20241 (interactive)
20242 (cond
20243 ((org-at-table-p)
20244 (call-interactively 'org-table-recalculate))
20246 ;; Convert all lines in region to list items
20247 (call-interactively 'org-toggle-heading))))
20249 (defun org-ctrl-c-minus ()
20250 "Insert separator line in table or modify bullet status of line.
20251 Also turns a plain line or a region of lines into list items.
20252 Calls `org-table-insert-hline', `org-toggle-item', or
20253 `org-cycle-list-bullet', depending on context."
20254 (interactive)
20255 (cond
20256 ((org-at-table-p)
20257 (call-interactively 'org-table-insert-hline))
20258 ((org-region-active-p)
20259 (call-interactively 'org-toggle-item))
20260 ((org-in-item-p)
20261 (call-interactively 'org-cycle-list-bullet))
20263 (call-interactively 'org-toggle-item))))
20265 (defun org-toggle-item (arg)
20266 "Convert headings or normal lines to items, items to normal lines.
20267 If there is no active region, only the current line is considered.
20269 If the first non blank line in the region is a headline, convert
20270 all headlines to items, shifting text accordingly.
20272 If it is an item, convert all items to normal lines.
20274 If it is normal text, change region into a list of items.
20275 With a prefix argument ARG, change the region in a single item."
20276 (interactive "P")
20277 (let ((shift-text
20278 (function
20279 ;; Shift text in current section to IND, from point to END.
20280 ;; The function leaves point to END line.
20281 (lambda (ind end)
20282 (let ((min-i 1000) (end (copy-marker end)))
20283 ;; First determine the minimum indentation (MIN-I) of
20284 ;; the text.
20285 (save-excursion
20286 (catch 'exit
20287 (while (< (point) end)
20288 (let ((i (org-get-indentation)))
20289 (cond
20290 ;; Skip blank lines and inline tasks.
20291 ((looking-at "^[ \t]*$"))
20292 ((looking-at org-outline-regexp-bol))
20293 ;; We can't find less than 0 indentation.
20294 ((zerop i) (throw 'exit (setq min-i 0)))
20295 ((< i min-i) (setq min-i i))))
20296 (forward-line))))
20297 ;; Then indent each line so that a line indented to
20298 ;; MIN-I becomes indented to IND. Ignore blank lines
20299 ;; and inline tasks in the process.
20300 (let ((delta (- ind min-i)))
20301 (while (< (point) end)
20302 (unless (or (looking-at "^[ \t]*$")
20303 (looking-at org-outline-regexp-bol))
20304 (org-indent-line-to (+ (org-get-indentation) delta)))
20305 (forward-line)))))))
20306 (skip-blanks
20307 (function
20308 ;; Return beginning of first non-blank line, starting from
20309 ;; line at POS.
20310 (lambda (pos)
20311 (save-excursion
20312 (goto-char pos)
20313 (skip-chars-forward " \r\t\n")
20314 (point-at-bol)))))
20315 beg end)
20316 ;; Determine boundaries of changes.
20317 (if (org-region-active-p)
20318 (setq beg (funcall skip-blanks (region-beginning))
20319 end (copy-marker (region-end)))
20320 (setq beg (funcall skip-blanks (point-at-bol))
20321 end (copy-marker (point-at-eol))))
20322 ;; Depending on the starting line, choose an action on the text
20323 ;; between BEG and END.
20324 (org-with-limited-levels
20325 (save-excursion
20326 (goto-char beg)
20327 (cond
20328 ;; Case 1. Start at an item: de-itemize. Note that it only
20329 ;; happens when a region is active: `org-ctrl-c-minus'
20330 ;; would call `org-cycle-list-bullet' otherwise.
20331 ((org-at-item-p)
20332 (while (< (point) end)
20333 (when (org-at-item-p)
20334 (skip-chars-forward " \t")
20335 (delete-region (point) (match-end 0)))
20336 (forward-line)))
20337 ;; Case 2. Start at an heading: convert to items.
20338 ((org-at-heading-p)
20339 (let* ((bul (org-list-bullet-string "-"))
20340 (bul-len (length bul))
20341 ;; Indentation of the first heading. It should be
20342 ;; relative to the indentation of its parent, if any.
20343 (start-ind (save-excursion
20344 (cond
20345 ((not org-adapt-indentation) 0)
20346 ((not (outline-previous-heading)) 0)
20347 (t (length (match-string 0))))))
20348 ;; Level of first heading. Further headings will be
20349 ;; compared to it to determine hierarchy in the list.
20350 (ref-level (org-reduced-level (org-outline-level))))
20351 (while (< (point) end)
20352 (let* ((level (org-reduced-level (org-outline-level)))
20353 (delta (max 0 (- level ref-level))))
20354 ;; If current headline is less indented than the first
20355 ;; one, set it as reference, in order to preserve
20356 ;; subtrees.
20357 (when (< level ref-level) (setq ref-level level))
20358 (replace-match bul t t)
20359 (org-indent-line-to (+ start-ind (* delta bul-len)))
20360 ;; Ensure all text down to END (or SECTION-END) belongs
20361 ;; to the newly created item.
20362 (let ((section-end (save-excursion
20363 (or (outline-next-heading) (point)))))
20364 (forward-line)
20365 (funcall shift-text
20366 (+ start-ind (* (1+ delta) bul-len))
20367 (min end section-end)))))))
20368 ;; Case 3. Normal line with ARG: make the first line of region
20369 ;; an item, and shift indentation of others lines to
20370 ;; set them as item's body.
20371 (arg (let* ((bul (org-list-bullet-string "-"))
20372 (bul-len (length bul))
20373 (ref-ind (org-get-indentation)))
20374 (skip-chars-forward " \t")
20375 (insert bul)
20376 (forward-line)
20377 (while (< (point) end)
20378 ;; Ensure that lines less indented than first one
20379 ;; still get included in item body.
20380 (funcall shift-text
20381 (+ ref-ind bul-len)
20382 (min end (save-excursion (or (outline-next-heading)
20383 (point)))))
20384 (forward-line))))
20385 ;; Case 4. Normal line without ARG: turn each non-item line
20386 ;; into an item.
20388 (while (< (point) end)
20389 (unless (or (org-at-heading-p) (org-at-item-p))
20390 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20391 (replace-match
20392 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20393 (forward-line))))))))
20395 (defun org-toggle-heading (&optional nstars)
20396 "Convert headings to normal text, or items or text to headings.
20397 If there is no active region, only convert the current line.
20399 With a \\[universal-argument] prefix, convert the whole list at
20400 point into heading.
20402 In a region:
20404 - If the first non blank line is a headline, remove the stars
20405 from all headlines in the region.
20407 - If it is a normal line, turn each and every normal line (i.e.,
20408 not an heading or an item) in the region into headings. If you
20409 want to convert only the first line of this region, use one
20410 universal prefix argument.
20412 - If it is a plain list item, turn all plain list items into headings.
20414 When converting a line into a heading, the number of stars is chosen
20415 such that the lines become children of the current entry. However,
20416 when a numeric prefix argument is given, its value determines the
20417 number of stars to add."
20418 (interactive "P")
20419 (let ((skip-blanks
20420 (function
20421 ;; Return beginning of first non-blank line, starting from
20422 ;; line at POS.
20423 (lambda (pos)
20424 (save-excursion
20425 (goto-char pos)
20426 (while (org-at-comment-p) (forward-line))
20427 (skip-chars-forward " \r\t\n")
20428 (point-at-bol)))))
20429 beg end toggled)
20430 ;; Determine boundaries of changes. If a universal prefix has
20431 ;; been given, put the list in a region. If region ends at a bol,
20432 ;; do not consider the last line to be in the region.
20434 (when (and current-prefix-arg (org-at-item-p))
20435 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20436 (org-mark-element))
20438 (if (org-region-active-p)
20439 (setq beg (funcall skip-blanks (region-beginning))
20440 end (copy-marker (save-excursion
20441 (goto-char (region-end))
20442 (if (bolp) (point) (point-at-eol)))))
20443 (setq beg (funcall skip-blanks (point-at-bol))
20444 end (copy-marker (point-at-eol))))
20445 ;; Ensure inline tasks don't count as headings.
20446 (org-with-limited-levels
20447 (save-excursion
20448 (goto-char beg)
20449 (cond
20450 ;; Case 1. Started at an heading: de-star headings.
20451 ((org-at-heading-p)
20452 (while (< (point) end)
20453 (when (org-at-heading-p t)
20454 (looking-at org-outline-regexp) (replace-match "")
20455 (setq toggled t))
20456 (forward-line)))
20457 ;; Case 2. Started at an item: change items into headlines.
20458 ;; One star will be added by `org-list-to-subtree'.
20459 ((org-at-item-p)
20460 (let* ((stars (make-string
20461 ;; subtract the star that will be added again by
20462 ;; `org-list-to-subtree'
20463 (if (numberp nstars) (1- nstars)
20464 (or (org-current-level) 0))
20465 ?*))
20466 (add-stars
20467 (cond (nstars "") ; stars from prefix only
20468 ((equal stars "") "") ; before first heading
20469 (org-odd-levels-only "*") ; inside heading, odd
20470 (t "")))) ; inside heading, oddeven
20471 (while (< (point) end)
20472 (when (org-at-item-p)
20473 ;; Pay attention to cases when region ends before list.
20474 (let* ((struct (org-list-struct))
20475 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20476 (save-restriction
20477 (narrow-to-region (point) list-end)
20478 (insert
20479 (org-list-to-subtree
20480 (org-list-parse-list t)
20481 '(:istart (concat stars add-stars (funcall get-stars depth))
20482 :icount (concat stars add-stars (funcall get-stars depth)))))))
20483 (setq toggled t))
20484 (forward-line))))
20485 ;; Case 3. Started at normal text: make every line an heading,
20486 ;; skipping headlines and items.
20487 (t (let* ((stars
20488 (make-string
20489 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20490 (add-stars
20491 (cond (nstars "") ; stars from prefix only
20492 ((equal stars "") "*") ; before first heading
20493 (org-odd-levels-only "**") ; inside heading, odd
20494 (t "*"))) ; inside heading, oddeven
20495 (rpl (concat stars add-stars " "))
20496 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20497 (while (< (point) (if (equal nstars '(4)) lend end))
20498 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20499 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20500 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20501 (forward-line)))))))
20502 (unless toggled (message "Cannot toggle heading from here"))))
20504 (defun org-meta-return (&optional arg)
20505 "Insert a new heading or wrap a region in a table.
20506 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20507 See the individual commands for more information."
20508 (interactive "P")
20509 (cond
20510 ((run-hook-with-args-until-success 'org-metareturn-hook))
20511 ((or (org-at-drawer-p) (org-at-property-p))
20512 (newline-and-indent))
20513 ((org-at-table-p)
20514 (call-interactively 'org-table-wrap-region))
20515 (t (call-interactively 'org-insert-heading))))
20517 ;;; Menu entries
20519 (defsubst org-in-subtree-not-table-p ()
20520 "Are we in a subtree and not in a table?"
20521 (and (not (org-before-first-heading-p))
20522 (not (org-at-table-p))))
20524 ;; Define the Org-mode menus
20525 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20526 '("Tbl"
20527 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20528 ["Next Field" org-cycle (org-at-table-p)]
20529 ["Previous Field" org-shifttab (org-at-table-p)]
20530 ["Next Row" org-return (org-at-table-p)]
20531 "--"
20532 ["Blank Field" org-table-blank-field (org-at-table-p)]
20533 ["Edit Field" org-table-edit-field (org-at-table-p)]
20534 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20535 "--"
20536 ("Column"
20537 ["Move Column Left" org-metaleft (org-at-table-p)]
20538 ["Move Column Right" org-metaright (org-at-table-p)]
20539 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20540 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20541 ("Row"
20542 ["Move Row Up" org-metaup (org-at-table-p)]
20543 ["Move Row Down" org-metadown (org-at-table-p)]
20544 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20545 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20546 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20547 "--"
20548 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20549 ("Rectangle"
20550 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20551 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20552 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20553 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20554 "--"
20555 ("Calculate"
20556 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20557 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20558 ["Edit Formulas" org-edit-special (org-at-table-p)]
20559 "--"
20560 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20561 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20562 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20563 "--"
20564 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20565 "--"
20566 ["Sum Column/Rectangle" org-table-sum
20567 (or (org-at-table-p) (org-region-active-p))]
20568 ["Which Column?" org-table-current-column (org-at-table-p)])
20569 ["Debug Formulas"
20570 org-table-toggle-formula-debugger
20571 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20572 ["Show Col/Row Numbers"
20573 org-table-toggle-coordinate-overlays
20574 :style toggle
20575 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20576 "--"
20577 ["Create" org-table-create (and (not (org-at-table-p))
20578 org-enable-table-editor)]
20579 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20580 ["Import from File" org-table-import (not (org-at-table-p))]
20581 ["Export to File" org-table-export (org-at-table-p)]
20582 "--"
20583 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20585 (easy-menu-define org-org-menu org-mode-map "Org menu"
20586 '("Org"
20587 ("Show/Hide"
20588 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20589 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20590 ["Sparse Tree..." org-sparse-tree t]
20591 ["Reveal Context" org-reveal t]
20592 ["Show All" show-all t]
20593 "--"
20594 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20595 "--"
20596 ["New Heading" org-insert-heading t]
20597 ("Navigate Headings"
20598 ["Up" outline-up-heading t]
20599 ["Next" outline-next-visible-heading t]
20600 ["Previous" outline-previous-visible-heading t]
20601 ["Next Same Level" outline-forward-same-level t]
20602 ["Previous Same Level" outline-backward-same-level t]
20603 "--"
20604 ["Jump" org-goto t])
20605 ("Edit Structure"
20606 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20607 "--"
20608 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20609 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20610 "--"
20611 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20612 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20613 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20614 "--"
20615 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20616 "--"
20617 ["Copy visible text" org-copy-visible t]
20618 "--"
20619 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20620 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20621 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20622 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20623 "--"
20624 ["Sort Region/Children" org-sort t]
20625 "--"
20626 ["Convert to odd levels" org-convert-to-odd-levels t]
20627 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20628 ("Editing"
20629 ["Emphasis..." org-emphasize t]
20630 ["Edit Source Example" org-edit-special t]
20631 "--"
20632 ["Footnote new/jump" org-footnote-action t]
20633 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20634 ("Archive"
20635 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20636 "--"
20637 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20638 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20639 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20641 "--"
20642 ("Hyperlinks"
20643 ["Store Link (Global)" org-store-link t]
20644 ["Find existing link to here" org-occur-link-in-agenda-files t]
20645 ["Insert Link" org-insert-link t]
20646 ["Follow Link" org-open-at-point t]
20647 "--"
20648 ["Next link" org-next-link t]
20649 ["Previous link" org-previous-link t]
20650 "--"
20651 ["Descriptive Links"
20652 org-toggle-link-display
20653 :style radio
20654 :selected org-descriptive-links
20656 ["Literal Links"
20657 org-toggle-link-display
20658 :style radio
20659 :selected (not org-descriptive-links)])
20660 "--"
20661 ("TODO Lists"
20662 ["TODO/DONE/-" org-todo t]
20663 ("Select keyword"
20664 ["Next keyword" org-shiftright (org-at-heading-p)]
20665 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20666 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20667 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20668 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20669 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20670 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20671 "--"
20672 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20673 :selected org-enforce-todo-dependencies :style toggle :active t]
20674 "Settings for tree at point"
20675 ["Do Children sequentially" org-toggle-ordered-property :style radio
20676 :selected (org-entry-get nil "ORDERED")
20677 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20678 ["Do Children parallel" org-toggle-ordered-property :style radio
20679 :selected (not (org-entry-get nil "ORDERED"))
20680 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20681 "--"
20682 ["Set Priority" org-priority t]
20683 ["Priority Up" org-shiftup t]
20684 ["Priority Down" org-shiftdown t]
20685 "--"
20686 ["Get news from all feeds" org-feed-update-all t]
20687 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20688 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20689 ("TAGS and Properties"
20690 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20691 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20692 "--"
20693 ["Set property" org-set-property (not (org-before-first-heading-p))]
20694 ["Column view of properties" org-columns t]
20695 ["Insert Column View DBlock" org-insert-columns-dblock t])
20696 ("Dates and Scheduling"
20697 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20698 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20699 ("Change Date"
20700 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20701 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20702 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20703 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20704 ["Compute Time Range" org-evaluate-time-range t]
20705 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20706 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20707 "--"
20708 ["Custom time format" org-toggle-time-stamp-overlays
20709 :style radio :selected org-display-custom-times]
20710 "--"
20711 ["Goto Calendar" org-goto-calendar t]
20712 ["Date from Calendar" org-date-from-calendar t]
20713 "--"
20714 ["Start/Restart Timer" org-timer-start t]
20715 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20716 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20717 ["Insert Timer String" org-timer t]
20718 ["Insert Timer Item" org-timer-item t])
20719 ("Logging work"
20720 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20721 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20722 ["Clock out" org-clock-out t]
20723 ["Clock cancel" org-clock-cancel t]
20724 "--"
20725 ["Mark as default task" org-clock-mark-default-task t]
20726 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20727 ["Goto running clock" org-clock-goto t]
20728 "--"
20729 ["Display times" org-clock-display t]
20730 ["Create clock table" org-clock-report t]
20731 "--"
20732 ["Record DONE time"
20733 (progn (setq org-log-done (not org-log-done))
20734 (message "Switching to %s will %s record a timestamp"
20735 (car org-done-keywords)
20736 (if org-log-done "automatically" "not")))
20737 :style toggle :selected org-log-done])
20738 "--"
20739 ["Agenda Command..." org-agenda t]
20740 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20741 ("File List for Agenda")
20742 ("Special views current file"
20743 ["TODO Tree" org-show-todo-tree t]
20744 ["Check Deadlines" org-check-deadlines t]
20745 ["Timeline" org-timeline t]
20746 ["Tags/Property tree" org-match-sparse-tree t])
20747 "--"
20748 ["Export/Publish..." org-export-dispatch t]
20749 ("LaTeX"
20750 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20751 :selected org-cdlatex-mode]
20752 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20753 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20754 ["Modify math symbol" org-cdlatex-math-modify
20755 (org-inside-LaTeX-fragment-p)]
20756 ["Insert citation" org-reftex-citation t]
20757 "--"
20758 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20759 "--"
20760 ("MobileOrg"
20761 ["Push Files and Views" org-mobile-push t]
20762 ["Get Captured and Flagged" org-mobile-pull t]
20763 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20764 "--"
20765 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20766 "--"
20767 ("Documentation"
20768 ["Show Version" org-version t]
20769 ["Info Documentation" org-info t])
20770 ("Customize"
20771 ["Browse Org Group" org-customize t]
20772 "--"
20773 ["Expand This Menu" org-create-customize-menu
20774 (fboundp 'customize-menu-create)])
20775 ["Send bug report" org-submit-bug-report t]
20776 "--"
20777 ("Refresh/Reload"
20778 ["Refresh setup current buffer" org-mode-restart t]
20779 ["Reload Org (after update)" org-reload t]
20780 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20783 (defun org-info (&optional node)
20784 "Read documentation for Org-mode in the info system.
20785 With optional NODE, go directly to that node."
20786 (interactive)
20787 (info (format "(org)%s" (or node ""))))
20789 ;;;###autoload
20790 (defun org-submit-bug-report ()
20791 "Submit a bug report on Org-mode via mail.
20793 Don't hesitate to report any problems or inaccurate documentation.
20795 If you don't have setup sending mail from (X)Emacs, please copy the
20796 output buffer into your mail program, as it gives us important
20797 information about your Org-mode version and configuration."
20798 (interactive)
20799 (require 'reporter)
20800 (org-load-modules-maybe)
20801 (org-require-autoloaded-modules)
20802 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20803 (reporter-submit-bug-report
20804 "emacs-orgmode@gnu.org"
20805 (org-version nil 'full)
20806 (let (list)
20807 (save-window-excursion
20808 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20809 (delete-other-windows)
20810 (erase-buffer)
20811 (insert "You are about to submit a bug report to the Org-mode mailing list.
20813 We would like to add your full Org-mode and Outline configuration to the
20814 bug report. This greatly simplifies the work of the maintainer and
20815 other experts on the mailing list.
20817 HOWEVER, some variables you have customized may contain private
20818 information. The names of customers, colleagues, or friends, might
20819 appear in the form of file names, tags, todo states, or search strings.
20820 If you answer yes to the prompt, you might want to check and remove
20821 such private information before sending the email.")
20822 (add-text-properties (point-min) (point-max) '(face org-warning))
20823 (when (yes-or-no-p "Include your Org-mode configuration ")
20824 (mapatoms
20825 (lambda (v)
20826 (and (boundp v)
20827 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20828 (or (and (symbol-value v)
20829 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20830 (and
20831 (get v 'custom-type) (get v 'standard-value)
20832 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20833 (push v list)))))
20834 (kill-buffer (get-buffer "*Warn about privacy*"))
20835 list))
20836 nil nil
20837 "Remember to cover the basics, that is, what you expected to happen and
20838 what in fact did happen. You don't know how to make a good report? See
20840 http://orgmode.org/manual/Feedback.html#Feedback
20842 Your bug report will be posted to the Org-mode mailing list.
20843 ------------------------------------------------------------------------")
20844 (save-excursion
20845 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20846 (replace-match "\\1Bug: \\3 [\\2]")))))
20849 (defun org-install-agenda-files-menu ()
20850 (let ((bl (buffer-list)))
20851 (save-excursion
20852 (while bl
20853 (set-buffer (pop bl))
20854 (if (derived-mode-p 'org-mode) (setq bl nil)))
20855 (when (derived-mode-p 'org-mode)
20856 (easy-menu-change
20857 '("Org") "File List for Agenda"
20858 (append
20859 (list
20860 ["Edit File List" (org-edit-agenda-file-list) t]
20861 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20862 ["Remove Current File from List" org-remove-file t]
20863 ["Cycle through agenda files" org-cycle-agenda-files t]
20864 ["Occur in all agenda files" org-occur-in-agenda-files t]
20865 "--")
20866 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20868 ;;;; Documentation
20870 (defun org-require-autoloaded-modules ()
20871 (interactive)
20872 (mapc 'require
20873 '(org-agenda org-archive org-attach org-clock org-colview org-id
20874 org-remember org-table org-timer)))
20876 ;;;###autoload
20877 (defun org-reload (&optional uncompiled)
20878 "Reload all org lisp files.
20879 With prefix arg UNCOMPILED, load the uncompiled versions."
20880 (interactive "P")
20881 (require 'loadhist)
20882 (let* ((org-dir (org-find-library-dir "org"))
20883 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20884 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20885 (remove-re (mapconcat 'identity
20886 (mapcar (lambda (f) (concat "^" f "$"))
20887 (list (if (featurep 'xemacs)
20888 "org-colview"
20889 "org-colview-xemacs")
20890 "org" "org-loaddefs" "org-version"))
20891 "\\|"))
20892 (feats (delete-dups
20893 (mapcar 'file-name-sans-extension
20894 (mapcar 'file-name-nondirectory
20895 (delq nil
20896 (mapcar 'feature-file
20897 features))))))
20898 (lfeat (append
20899 (sort
20900 (setq feats
20901 (delq nil (mapcar
20902 (lambda (f)
20903 (if (and (string-match feature-re f)
20904 (not (string-match remove-re f)))
20905 f nil))
20906 feats)))
20907 'string-lessp)
20908 (list "org-version" "org")))
20909 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20910 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20911 load-uncore load-misses)
20912 (setq load-misses
20913 (delq 't
20914 (mapcar (lambda (f)
20915 (or (org-load-noerror-mustsuffix (concat org-dir f))
20916 (and (string= org-dir contrib-dir)
20917 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20918 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20919 (add-to-list 'load-uncore f 'append)
20922 lfeat)))
20923 (if load-uncore
20924 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20925 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20926 (if load-misses
20927 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20928 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20929 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20931 ;;;###autoload
20932 (defun org-customize ()
20933 "Call the customize function with org as argument."
20934 (interactive)
20935 (org-load-modules-maybe)
20936 (org-require-autoloaded-modules)
20937 (customize-browse 'org))
20939 (defun org-create-customize-menu ()
20940 "Create a full customization menu for Org-mode, insert it into the menu."
20941 (interactive)
20942 (org-load-modules-maybe)
20943 (org-require-autoloaded-modules)
20944 (if (fboundp 'customize-menu-create)
20945 (progn
20946 (easy-menu-change
20947 '("Org") "Customize"
20948 `(["Browse Org group" org-customize t]
20949 "--"
20950 ,(customize-menu-create 'org)
20951 ["Set" Custom-set t]
20952 ["Save" Custom-save t]
20953 ["Reset to Current" Custom-reset-current t]
20954 ["Reset to Saved" Custom-reset-saved t]
20955 ["Reset to Standard Settings" Custom-reset-standard t]))
20956 (message "\"Org\"-menu now contains full customization menu"))
20957 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20959 ;;;; Miscellaneous stuff
20961 ;;; Generally useful functions
20963 (defun org-get-at-bol (property)
20964 "Get text property PROPERTY at beginning of line."
20965 (get-text-property (point-at-bol) property))
20967 (defun org-find-text-property-in-string (prop s)
20968 "Return the first non-nil value of property PROP in string S."
20969 (or (get-text-property 0 prop s)
20970 (get-text-property (or (next-single-property-change 0 prop s) 0)
20971 prop s)))
20973 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20974 "Display the given MESSAGE as a warning."
20975 (if (fboundp 'display-warning)
20976 (display-warning 'org message
20977 (if (featurep 'xemacs) 'warning :warning))
20978 (let ((buf (get-buffer-create "*Org warnings*")))
20979 (with-current-buffer buf
20980 (goto-char (point-max))
20981 (insert "Warning (Org): " message)
20982 (unless (bolp)
20983 (newline)))
20984 (display-buffer buf)
20985 (sit-for 0))))
20987 (defun org-eval (form)
20988 "Eval FORM and return result."
20989 (condition-case error
20990 (eval form)
20991 (error (format "%%![Error: %s]" error))))
20993 (defun org-in-clocktable-p ()
20994 "Check if the cursor is in a clocktable."
20995 (let ((pos (point)) start)
20996 (save-excursion
20997 (end-of-line 1)
20998 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20999 (setq start (match-beginning 0))
21000 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21001 (>= (match-end 0) pos)
21002 start))))
21004 (defun org-in-commented-line ()
21005 "Is point in a line starting with `#'?"
21006 (equal (char-after (point-at-bol)) ?#))
21008 (defun org-in-indented-comment-line ()
21009 "Is point in a line starting with `#' after some white space?"
21010 (save-excursion
21011 (save-match-data
21012 (goto-char (point-at-bol))
21013 (looking-at "[ \t]*#"))))
21015 (defun org-in-verbatim-emphasis ()
21016 (save-match-data
21017 (and (org-in-regexp org-emph-re 2)
21018 (>= (point) (match-beginning 3))
21019 (<= (point) (match-end 4))
21020 (member (match-string 3) '("=" "~")))))
21022 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21023 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21024 (if (and marker (marker-buffer marker)
21025 (buffer-live-p (marker-buffer marker)))
21026 (progn
21027 (org-pop-to-buffer-same-window (marker-buffer marker))
21028 (if (or (> marker (point-max)) (< marker (point-min)))
21029 (widen))
21030 (goto-char marker)
21031 (org-show-context 'org-goto))
21032 (if bookmark
21033 (bookmark-jump bookmark)
21034 (error "Cannot find location"))))
21036 (defun org-quote-csv-field (s)
21037 "Quote field for inclusion in CSV material."
21038 (if (string-match "[\",]" s)
21039 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21042 (defun org-force-self-insert (N)
21043 "Needed to enforce self-insert under remapping."
21044 (interactive "p")
21045 (self-insert-command N))
21047 (defun org-string-width (s)
21048 "Compute width of string, ignoring invisible characters.
21049 This ignores character with invisibility property `org-link', and also
21050 characters with property `org-cwidth', because these will become invisible
21051 upon the next fontification round."
21052 (let (b l)
21053 (when (or (eq t buffer-invisibility-spec)
21054 (assq 'org-link buffer-invisibility-spec))
21055 (while (setq b (text-property-any 0 (length s)
21056 'invisible 'org-link s))
21057 (setq s (concat (substring s 0 b)
21058 (substring s (or (next-single-property-change
21059 b 'invisible s) (length s)))))))
21060 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21061 (setq s (concat (substring s 0 b)
21062 (substring s (or (next-single-property-change
21063 b 'org-cwidth s) (length s))))))
21064 (setq l (string-width s) b -1)
21065 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21066 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21069 (defun org-shorten-string (s maxlength)
21070 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21071 If the string is shorter or has length MAXLENGTH, just return the
21072 original string. If it is longer, the functions finds a space in the
21073 string, breaks this string off at that locations and adds three dots
21074 as ellipsis. Including the ellipsis, the string will not be longer
21075 than MAXLENGTH. If finding a good breaking point in the string does
21076 not work, the string is just chopped off in the middle of a word
21077 if necessary."
21078 (if (<= (length s) maxlength)
21080 (let* ((n (max (- maxlength 4) 1))
21081 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21082 (if (string-match re s)
21083 (concat (match-string 1 s) "...")
21084 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21086 (defun org-get-indentation (&optional line)
21087 "Get the indentation of the current line, interpreting tabs.
21088 When LINE is given, assume it represents a line and compute its indentation."
21089 (if line
21090 (if (string-match "^ *" (org-remove-tabs line))
21091 (match-end 0))
21092 (save-excursion
21093 (beginning-of-line 1)
21094 (skip-chars-forward " \t")
21095 (current-column))))
21097 (defun org-get-string-indentation (s)
21098 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21099 (let ((n -1) (i 0) (w tab-width) c)
21100 (catch 'exit
21101 (while (< (setq n (1+ n)) (length s))
21102 (setq c (aref s n))
21103 (cond ((= c ?\ ) (setq i (1+ i)))
21104 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21105 (t (throw 'exit t)))))
21108 (defun org-remove-tabs (s &optional width)
21109 "Replace tabulators in S with spaces.
21110 Assumes that s is a single line, starting in column 0."
21111 (setq width (or width tab-width))
21112 (while (string-match "\t" s)
21113 (setq s (replace-match
21114 (make-string
21115 (- (* width (/ (+ (match-beginning 0) width) width))
21116 (match-beginning 0)) ?\ )
21117 t t s)))
21120 (defun org-fix-indentation (line ind)
21121 "Fix indentation in LINE.
21122 IND is a cons cell with target and minimum indentation.
21123 If the current indentation in LINE is smaller than the minimum,
21124 leave it alone. If it is larger than ind, set it to the target."
21125 (let* ((l (org-remove-tabs line))
21126 (i (org-get-indentation l))
21127 (i1 (car ind)) (i2 (cdr ind)))
21128 (if (>= i i2) (setq l (substring line i2)))
21129 (if (> i1 0)
21130 (concat (make-string i1 ?\ ) l)
21131 l)))
21133 (defun org-remove-indentation (code &optional n)
21134 "Remove the maximum common indentation from the lines in CODE.
21135 N may optionally be the number of spaces to remove."
21136 (with-temp-buffer
21137 (insert code)
21138 (org-do-remove-indentation n)
21139 (buffer-string)))
21141 (defun org-do-remove-indentation (&optional n)
21142 "Remove the maximum common indentation from the buffer."
21143 (untabify (point-min) (point-max))
21144 (let ((min 10000) re)
21145 (if n
21146 (setq min n)
21147 (goto-char (point-min))
21148 (while (re-search-forward "^ *[^ \n]" nil t)
21149 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21150 (unless (or (= min 0) (= min 10000))
21151 (setq re (format "^ \\{%d\\}" min))
21152 (goto-char (point-min))
21153 (while (re-search-forward re nil t)
21154 (replace-match "")
21155 (end-of-line 1))
21156 min)))
21158 (defun org-fill-template (template alist)
21159 "Find each %key of ALIST in TEMPLATE and replace it."
21160 (let ((case-fold-search nil)
21161 entry key value)
21162 (setq alist (sort (copy-sequence alist)
21163 (lambda (a b) (< (length (car a)) (length (car b))))))
21164 (while (setq entry (pop alist))
21165 (setq template
21166 (replace-regexp-in-string
21167 (concat "%" (regexp-quote (car entry)))
21168 (or (cdr entry) "") template t t)))
21169 template))
21171 (defun org-base-buffer (buffer)
21172 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21173 (if (not buffer)
21174 buffer
21175 (or (buffer-base-buffer buffer)
21176 buffer)))
21178 (defun org-trim (s)
21179 "Remove whitespace at beginning and end of string."
21180 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21181 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21184 (defun org-wrap (string &optional width lines)
21185 "Wrap string to either a number of lines, or a width in characters.
21186 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21187 that costs. If there is a word longer than WIDTH, the text is actually
21188 wrapped to the length of that word.
21189 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21190 many lines, whatever width that takes.
21191 The return value is a list of lines, without newlines at the end."
21192 (let* ((words (org-split-string string "[ \t\n]+"))
21193 (maxword (apply 'max (mapcar 'org-string-width words)))
21194 w ll)
21195 (cond (width
21196 (org-do-wrap words (max maxword width)))
21197 (lines
21198 (setq w maxword)
21199 (setq ll (org-do-wrap words maxword))
21200 (if (<= (length ll) lines)
21202 (setq ll words)
21203 (while (> (length ll) lines)
21204 (setq w (1+ w))
21205 (setq ll (org-do-wrap words w)))
21206 ll))
21207 (t (error "Cannot wrap this")))))
21209 (defun org-do-wrap (words width)
21210 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21211 (let (lines line)
21212 (while words
21213 (setq line (pop words))
21214 (while (and words (< (+ (length line) (length (car words))) width))
21215 (setq line (concat line " " (pop words))))
21216 (setq lines (push line lines)))
21217 (nreverse lines)))
21219 (defun org-split-string (string &optional separators)
21220 "Splits STRING into substrings at SEPARATORS.
21221 No empty strings are returned if there are matches at the beginning
21222 and end of string."
21223 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21224 (start 0)
21225 notfirst
21226 (list nil))
21227 (while (and (string-match rexp string
21228 (if (and notfirst
21229 (= start (match-beginning 0))
21230 (< start (length string)))
21231 (1+ start) start))
21232 (< (match-beginning 0) (length string)))
21233 (setq notfirst t)
21234 (or (eq (match-beginning 0) 0)
21235 (and (eq (match-beginning 0) (match-end 0))
21236 (eq (match-beginning 0) start))
21237 (setq list
21238 (cons (substring string start (match-beginning 0))
21239 list)))
21240 (setq start (match-end 0)))
21241 (or (eq start (length string))
21242 (setq list
21243 (cons (substring string start)
21244 list)))
21245 (nreverse list)))
21247 (defun org-quote-vert (s)
21248 "Replace \"|\" with \"\\vert\"."
21249 (while (string-match "|" s)
21250 (setq s (replace-match "\\vert" t t s)))
21253 (defun org-uuidgen-p (s)
21254 "Is S an ID created by UUIDGEN?"
21255 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21257 (defun org-in-src-block-p (&optional inside)
21258 "Whether point is in a code source block.
21259 When INSIDE is non-nil, don't consider we are within a src block
21260 when point is at #+BEGIN_SRC or #+END_SRC."
21261 (let ((case-fold-search t) ov)
21262 (or (and (setq ov (overlays-at (point)))
21263 (memq 'org-block-background
21264 (overlay-properties (car ov))))
21265 (and (not inside)
21266 (save-match-data
21267 (save-excursion
21268 (beginning-of-line)
21269 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21271 (defun org-context ()
21272 "Return a list of contexts of the current cursor position.
21273 If several contexts apply, all are returned.
21274 Each context entry is a list with a symbol naming the context, and
21275 two positions indicating start and end of the context. Possible
21276 contexts are:
21278 :headline anywhere in a headline
21279 :headline-stars on the leading stars in a headline
21280 :todo-keyword on a TODO keyword (including DONE) in a headline
21281 :tags on the TAGS in a headline
21282 :priority on the priority cookie in a headline
21283 :item on the first line of a plain list item
21284 :item-bullet on the bullet/number of a plain list item
21285 :checkbox on the checkbox in a plain list item
21286 :table in an org-mode table
21287 :table-special on a special filed in a table
21288 :table-table in a table.el table
21289 :clocktable in a clocktable
21290 :src-block in a source block
21291 :link on a hyperlink
21292 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21293 :target on a <<target>>
21294 :radio-target on a <<<radio-target>>>
21295 :latex-fragment on a LaTeX fragment
21296 :latex-preview on a LaTeX fragment with overlaid preview image
21298 This function expects the position to be visible because it uses font-lock
21299 faces as a help to recognize the following contexts: :table-special, :link,
21300 and :keyword."
21301 (let* ((f (get-text-property (point) 'face))
21302 (faces (if (listp f) f (list f)))
21303 (case-fold-search t)
21304 (p (point)) clist o)
21305 ;; First the large context
21306 (cond
21307 ((org-at-heading-p t)
21308 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21309 (when (progn
21310 (beginning-of-line 1)
21311 (looking-at org-todo-line-tags-regexp))
21312 (push (org-point-in-group p 1 :headline-stars) clist)
21313 (push (org-point-in-group p 2 :todo-keyword) clist)
21314 (push (org-point-in-group p 4 :tags) clist))
21315 (goto-char p)
21316 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21317 (if (looking-at "\\[#[A-Z0-9]\\]")
21318 (push (org-point-in-group p 0 :priority) clist)))
21320 ((org-at-item-p)
21321 (push (org-point-in-group p 2 :item-bullet) clist)
21322 (push (list :item (point-at-bol)
21323 (save-excursion (org-end-of-item) (point)))
21324 clist)
21325 (and (org-at-item-checkbox-p)
21326 (push (org-point-in-group p 0 :checkbox) clist)))
21328 ((org-at-table-p)
21329 (push (list :table (org-table-begin) (org-table-end)) clist)
21330 (if (memq 'org-formula faces)
21331 (push (list :table-special
21332 (previous-single-property-change p 'face)
21333 (next-single-property-change p 'face)) clist)))
21334 ((org-at-table-p 'any)
21335 (push (list :table-table) clist)))
21336 (goto-char p)
21338 (let ((case-fold-search t))
21339 ;; New the "medium" contexts: clocktables, source blocks
21340 (cond ((org-in-clocktable-p)
21341 (push (list :clocktable
21342 (and (or (looking-at "#\\+BEGIN: clocktable")
21343 (search-backward "#+BEGIN: clocktable" nil t))
21344 (match-beginning 0))
21345 (and (re-search-forward "#\\+END:?" nil t)
21346 (match-end 0))) clist))
21347 ((org-in-src-block-p)
21348 (push (list :src-block
21349 (and (or (looking-at "#\\+BEGIN_SRC")
21350 (search-backward "#+BEGIN_SRC" nil t))
21351 (match-beginning 0))
21352 (and (search-forward "#+END_SRC" nil t)
21353 (match-beginning 0))) clist))))
21354 (goto-char p)
21356 ;; Now the small context
21357 (cond
21358 ((org-at-timestamp-p)
21359 (push (org-point-in-group p 0 :timestamp) clist))
21360 ((memq 'org-link faces)
21361 (push (list :link
21362 (previous-single-property-change p 'face)
21363 (next-single-property-change p 'face)) clist))
21364 ((memq 'org-special-keyword faces)
21365 (push (list :keyword
21366 (previous-single-property-change p 'face)
21367 (next-single-property-change p 'face)) clist))
21368 ((org-at-target-p)
21369 (push (org-point-in-group p 0 :target) clist)
21370 (goto-char (1- (match-beginning 0)))
21371 (if (looking-at org-radio-target-regexp)
21372 (push (org-point-in-group p 0 :radio-target) clist))
21373 (goto-char p))
21374 ((setq o (car (delq nil
21375 (mapcar
21376 (lambda (x)
21377 (if (memq x org-latex-fragment-image-overlays) x))
21378 (overlays-at (point))))))
21379 (push (list :latex-fragment
21380 (overlay-start o) (overlay-end o)) clist)
21381 (push (list :latex-preview
21382 (overlay-start o) (overlay-end o)) clist))
21383 ((org-inside-LaTeX-fragment-p)
21384 ;; FIXME: positions wrong.
21385 (push (list :latex-fragment (point) (point)) clist)))
21387 (setq clist (nreverse (delq nil clist)))
21388 clist))
21390 ;; FIXME: Compare with at-regexp-p Do we need both?
21391 (defun org-in-regexp (re &optional nlines visually)
21392 "Check if point is inside a match of regexp.
21393 Normally only the current line is checked, but you can include NLINES extra
21394 lines both before and after point into the search.
21395 If VISUALLY is set, require that the cursor is not after the match but
21396 really on, so that the block visually is on the match."
21397 (catch 'exit
21398 (let ((pos (point))
21399 (eol (point-at-eol (+ 1 (or nlines 0))))
21400 (inc (if visually 1 0)))
21401 (save-excursion
21402 (beginning-of-line (- 1 (or nlines 0)))
21403 (while (re-search-forward re eol t)
21404 (if (and (<= (match-beginning 0) pos)
21405 (>= (+ inc (match-end 0)) pos))
21406 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21408 (defun org-at-regexp-p (regexp)
21409 "Is point inside a match of REGEXP in the current line?"
21410 (catch 'exit
21411 (save-excursion
21412 (let ((pos (point)) (end (point-at-eol)))
21413 (beginning-of-line 1)
21414 (while (re-search-forward regexp end t)
21415 (if (and (<= (match-beginning 0) pos)
21416 (>= (match-end 0) pos))
21417 (throw 'exit t)))
21418 nil))))
21420 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21421 "Non-nil when point is between matches of START-RE and END-RE.
21423 Also return a non-nil value when point is on one of the matches.
21425 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21426 buffer positions. Default values are the positions of headlines
21427 surrounding the point.
21429 The functions returns a cons cell whose car (resp. cdr) is the
21430 position before START-RE (resp. after END-RE)."
21431 (save-match-data
21432 (let ((pos (point))
21433 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21434 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21435 beg end)
21436 (save-excursion
21437 ;; Point is on a block when on START-RE or if START-RE can be
21438 ;; found before it...
21439 (and (or (org-at-regexp-p start-re)
21440 (re-search-backward start-re limit-up t))
21441 (setq beg (match-beginning 0))
21442 ;; ... and END-RE after it...
21443 (goto-char (match-end 0))
21444 (re-search-forward end-re limit-down t)
21445 (> (setq end (match-end 0)) pos)
21446 ;; ... without another START-RE in-between.
21447 (goto-char (match-beginning 0))
21448 (not (re-search-backward start-re (1+ beg) t))
21449 ;; Return value.
21450 (cons beg end))))))
21452 (defun org-in-block-p (names)
21453 "Non-nil when point belongs to a block whose name belongs to NAMES.
21455 NAMES is a list of strings containing names of blocks.
21457 Return first block name matched, or nil. Beware that in case of
21458 nested blocks, the returned name may not belong to the closest
21459 block from point."
21460 (save-match-data
21461 (catch 'exit
21462 (let ((case-fold-search t)
21463 (lim-up (save-excursion (outline-previous-heading)))
21464 (lim-down (save-excursion (outline-next-heading))))
21465 (mapc (lambda (name)
21466 (let ((n (regexp-quote name)))
21467 (when (org-between-regexps-p
21468 (concat "^[ \t]*#\\+begin_" n)
21469 (concat "^[ \t]*#\\+end_" n)
21470 lim-up lim-down)
21471 (throw 'exit n))))
21472 names))
21473 nil)))
21475 (defun org-occur-in-agenda-files (regexp &optional nlines)
21476 "Call `multi-occur' with buffers for all agenda files."
21477 (interactive "sOrg-files matching: \np")
21478 (let* ((files (org-agenda-files))
21479 (tnames (mapcar 'file-truename files))
21480 (extra org-agenda-text-search-extra-files)
21482 (when (eq (car extra) 'agenda-archives)
21483 (setq extra (cdr extra))
21484 (setq files (org-add-archive-files files)))
21485 (while (setq f (pop extra))
21486 (unless (member (file-truename f) tnames)
21487 (add-to-list 'files f 'append)
21488 (add-to-list 'tnames (file-truename f) 'append)))
21489 (multi-occur
21490 (mapcar (lambda (x)
21491 (with-current-buffer
21492 (or (get-file-buffer x) (find-file-noselect x))
21493 (widen)
21494 (current-buffer)))
21495 files)
21496 regexp)))
21498 (if (boundp 'occur-mode-find-occurrence-hook)
21499 ;; Emacs 23
21500 (add-hook 'occur-mode-find-occurrence-hook
21501 (lambda ()
21502 (when (derived-mode-p 'org-mode)
21503 (org-reveal))))
21504 ;; Emacs 22
21505 (defadvice occur-mode-goto-occurrence
21506 (after org-occur-reveal activate)
21507 (and (derived-mode-p 'org-mode) (org-reveal)))
21508 (defadvice occur-mode-goto-occurrence-other-window
21509 (after org-occur-reveal activate)
21510 (and (derived-mode-p 'org-mode) (org-reveal)))
21511 (defadvice occur-mode-display-occurrence
21512 (after org-occur-reveal activate)
21513 (when (derived-mode-p 'org-mode)
21514 (let ((pos (occur-mode-find-occurrence)))
21515 (with-current-buffer (marker-buffer pos)
21516 (save-excursion
21517 (goto-char pos)
21518 (org-reveal)))))))
21520 (defun org-occur-link-in-agenda-files ()
21521 "Create a link and search for it in the agendas.
21522 The link is not stored in `org-stored-links', it is just created
21523 for the search purpose."
21524 (interactive)
21525 (let ((link (condition-case nil
21526 (org-store-link nil)
21527 (error "Unable to create a link to here"))))
21528 (org-occur-in-agenda-files (regexp-quote link))))
21530 (defun org-reverse-string (string)
21531 "Return the reverse of STRING."
21532 (apply 'string (reverse (string-to-list string))))
21534 (defun org-uniquify (list)
21535 "Remove duplicate elements from LIST."
21536 (let (res)
21537 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21538 res))
21540 (defun org-uniquify-alist (alist)
21541 "Merge duplicate elements of an alist.
21543 For example, in this alist:
21545 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21546 => '((a 1 3) (b 2))
21548 merge (a 1) and (a 3) into (a 1 3) and return the new alist."
21549 (let (rtn)
21550 (mapc
21551 (lambda (e)
21552 (let (n)
21553 (if (not (assoc (car e) rtn))
21554 (push e rtn)
21555 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21556 (setq rtn (assq-delete-all (car e) rtn))
21557 (push n rtn))))
21558 alist)
21559 rtn))
21561 (defun org-delete-all (elts list)
21562 "Remove all elements in ELTS from LIST."
21563 (while elts
21564 (setq list (delete (pop elts) list)))
21565 list)
21567 (defun org-count (cl-item cl-seq)
21568 "Count the number of occurrences of ITEM in SEQ.
21569 Taken from `count' in cl-seq.el with all keyword arguments removed."
21570 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21571 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21572 (while (< cl-start cl-end)
21573 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21574 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21575 (setq cl-start (1+ cl-start)))
21576 cl-count))
21578 (defun org-remove-if (predicate seq)
21579 "Remove everything from SEQ that fulfills PREDICATE."
21580 (let (res e)
21581 (while seq
21582 (setq e (pop seq))
21583 (if (not (funcall predicate e)) (push e res)))
21584 (nreverse res)))
21586 (defun org-remove-if-not (predicate seq)
21587 "Remove everything from SEQ that does not fulfill PREDICATE."
21588 (let (res e)
21589 (while seq
21590 (setq e (pop seq))
21591 (if (funcall predicate e) (push e res)))
21592 (nreverse res)))
21594 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21595 "Reduce two-argument FUNCTION across SEQ.
21596 Taken from `reduce' in cl-seq.el with all keyword arguments but
21597 \":initial-value\" removed."
21598 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21599 (cadr (memq :initial-value cl-keys)))
21600 (cl-seq (pop cl-seq))
21601 (t (funcall cl-func)))))
21602 (while cl-seq
21603 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21604 cl-accum))
21606 (defun org-back-over-empty-lines ()
21607 "Move backwards over whitespace, to the beginning of the first empty line.
21608 Returns the number of empty lines passed."
21609 (let ((pos (point)))
21610 (if (cdr (assoc 'heading org-blank-before-new-entry))
21611 (skip-chars-backward " \t\n\r")
21612 (unless (eobp)
21613 (forward-line -1)))
21614 (beginning-of-line 2)
21615 (goto-char (min (point) pos))
21616 (count-lines (point) pos)))
21618 (defun org-skip-whitespace ()
21619 (skip-chars-forward " \t\n\r"))
21621 (defun org-point-in-group (point group &optional context)
21622 "Check if POINT is in match-group GROUP.
21623 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21624 match. If the match group does not exist or point is not inside it,
21625 return nil."
21626 (and (match-beginning group)
21627 (>= point (match-beginning group))
21628 (<= point (match-end group))
21629 (if context
21630 (list context (match-beginning group) (match-end group))
21631 t)))
21633 (defun org-switch-to-buffer-other-window (&rest args)
21634 "Switch to buffer in a second window on the current frame.
21635 In particular, do not allow pop-up frames.
21636 Returns the newly created buffer."
21637 (org-no-popups
21638 (apply 'switch-to-buffer-other-window args)))
21640 (defun org-combine-plists (&rest plists)
21641 "Create a single property list from all plists in PLISTS.
21642 The process starts by copying the first list, and then setting properties
21643 from the other lists. Settings in the last list are the most significant
21644 ones and overrule settings in the other lists."
21645 (let ((rtn (copy-sequence (pop plists)))
21646 p v ls)
21647 (while plists
21648 (setq ls (pop plists))
21649 (while ls
21650 (setq p (pop ls) v (pop ls))
21651 (setq rtn (plist-put rtn p v))))
21652 rtn))
21654 (defun org-replace-escapes (string table)
21655 "Replace %-escapes in STRING with values in TABLE.
21656 TABLE is an association list with keys like \"%a\" and string values.
21657 The sequences in STRING may contain normal field width and padding information,
21658 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21659 so values can contain further %-escapes if they are define later in TABLE."
21660 (let ((tbl (copy-alist table))
21661 (case-fold-search nil)
21662 (pchg 0)
21663 e re rpl)
21664 (while (setq e (pop tbl))
21665 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21666 (when (and (cdr e) (string-match re (cdr e)))
21667 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21668 (safe "SREF"))
21669 (add-text-properties 0 3 (list 'sref sref) safe)
21670 (setcdr e (replace-match safe t t (cdr e)))))
21671 (while (string-match re string)
21672 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21673 (cdr e)))
21674 (setq string (replace-match rpl t t string))))
21675 (while (setq pchg (next-property-change pchg string))
21676 (let ((sref (get-text-property pchg 'sref string)))
21677 (when (and sref (string-match "SREF" string pchg))
21678 (setq string (replace-match sref t t string)))))
21679 string))
21681 (defun org-sublist (list start end)
21682 "Return a section of LIST, from START to END.
21683 Counting starts at 1."
21684 (let (rtn (c start))
21685 (setq list (nthcdr (1- start) list))
21686 (while (and list (<= c end))
21687 (push (pop list) rtn)
21688 (setq c (1+ c)))
21689 (nreverse rtn)))
21691 (defun org-find-base-buffer-visiting (file)
21692 "Like `find-buffer-visiting' but always return the base buffer and
21693 not an indirect buffer."
21694 (let ((buf (or (get-file-buffer file)
21695 (find-buffer-visiting file))))
21696 (if buf
21697 (or (buffer-base-buffer buf) buf)
21698 nil)))
21700 (defun org-image-file-name-regexp (&optional extensions)
21701 "Return regexp matching the file names of images.
21702 If EXTENSIONS is given, only match these."
21703 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21704 (image-file-name-regexp)
21705 (let ((image-file-name-extensions
21706 (or extensions
21707 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21708 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21709 (concat "\\."
21710 (regexp-opt (nconc (mapcar 'upcase
21711 image-file-name-extensions)
21712 image-file-name-extensions)
21714 "\\'"))))
21716 (defun org-file-image-p (file &optional extensions)
21717 "Return non-nil if FILE is an image."
21718 (save-match-data
21719 (string-match (org-image-file-name-regexp extensions) file)))
21721 (defun org-get-cursor-date (&optional with-time)
21722 "Return the date at cursor in as a time.
21723 This works in the calendar and in the agenda, anywhere else it just
21724 returns the current time.
21725 If WITH-TIME is non-nil, returns the time of the event at point (in
21726 the agenda) or the current time of the day."
21727 (let (date day defd tp tm hod mod)
21728 (when with-time
21729 (setq tp (get-text-property (point) 'time))
21730 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21731 (setq hod (string-to-number (match-string 1 tp))
21732 mod (string-to-number (match-string 2 tp))))
21733 (or tp (setq hod (nth 2 (decode-time (current-time)))
21734 mod (nth 1 (decode-time (current-time))))))
21735 (cond
21736 ((eq major-mode 'calendar-mode)
21737 (setq date (calendar-cursor-to-date)
21738 defd (encode-time 0 (or mod 0) (or hod 0)
21739 (nth 1 date) (nth 0 date) (nth 2 date))))
21740 ((eq major-mode 'org-agenda-mode)
21741 (setq day (get-text-property (point) 'day))
21742 (if day
21743 (setq date (calendar-gregorian-from-absolute day)
21744 defd (encode-time 0 (or mod 0) (or hod 0)
21745 (nth 1 date) (nth 0 date) (nth 2 date))))))
21746 (or defd (current-time))))
21748 (defun org-mark-subtree (&optional up)
21749 "Mark the current subtree.
21750 This puts point at the start of the current subtree, and mark at
21751 the end. If a numeric prefix UP is given, move up into the
21752 hierarchy of headlines by UP levels before marking the subtree."
21753 (interactive "P")
21754 (org-with-limited-levels
21755 (cond ((org-at-heading-p) (beginning-of-line))
21756 ((org-before-first-heading-p) (error "Not in a subtree"))
21757 (t (outline-previous-visible-heading 1))))
21758 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21759 (if (org-called-interactively-p 'any)
21760 (call-interactively 'org-mark-element)
21761 (org-mark-element)))
21764 ;;; Indentation
21766 (defun org-indent-line ()
21767 "Indent line depending on context."
21768 (interactive)
21769 (let* ((pos (point))
21770 (itemp (org-at-item-p))
21771 (case-fold-search t)
21772 (org-drawer-regexp (or org-drawer-regexp "\000"))
21773 (inline-task-p (and (featurep 'org-inlinetask)
21774 (org-inlinetask-in-task-p)))
21775 (inline-re (and inline-task-p
21776 (org-inlinetask-outline-regexp)))
21777 column)
21778 (if (and orgstruct-is-++ (eq pos (point)))
21779 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21780 (indent-according-to-mode))
21781 (beginning-of-line 1)
21782 (cond
21783 ;; Headings
21784 ((looking-at org-outline-regexp) (setq column 0))
21785 ;; Footnote definition
21786 ((looking-at org-footnote-definition-re) (setq column 0))
21787 ;; Literal examples
21788 ((looking-at "[ \t]*:\\( \\|$\\)")
21789 (setq column (org-get-indentation))) ; do nothing
21790 ;; Lists
21791 ((ignore-errors (goto-char (org-in-item-p)))
21792 (setq column (if itemp
21793 (org-get-indentation)
21794 (org-list-item-body-column (point))))
21795 (goto-char pos))
21796 ;; Drawers
21797 ((and (looking-at "[ \t]*:END:")
21798 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21799 (save-excursion
21800 (goto-char (1- (match-beginning 1)))
21801 (setq column (current-column))))
21802 ;; Special blocks
21803 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21804 (save-excursion
21805 (re-search-backward
21806 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21807 (setq column (org-get-indentation (match-string 0))))
21808 ((and (not (looking-at "[ \t]*#\\+begin_"))
21809 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21810 (save-excursion
21811 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21812 (setq column
21813 (cond ((equal (downcase (match-string 1)) "src")
21814 ;; src blocks: let `org-edit-src-exit' handle them
21815 (org-get-indentation))
21816 ((equal (downcase (match-string 1)) "example")
21817 (max (org-get-indentation)
21818 (org-get-indentation (match-string 0))))
21820 (org-get-indentation (match-string 0))))))
21821 ;; This line has nothing special, look at the previous relevant
21822 ;; line to compute indentation
21824 (beginning-of-line 0)
21825 (while (and (not (bobp))
21826 (not (looking-at org-table-line-regexp))
21827 (not (looking-at org-drawer-regexp))
21828 ;; When point started in an inline task, do not move
21829 ;; above task starting line.
21830 (not (and inline-task-p (looking-at inline-re)))
21831 ;; Skip drawers, blocks, empty lines, verbatim,
21832 ;; comments, tables, footnotes definitions, lists,
21833 ;; inline tasks.
21834 (or (and (looking-at "[ \t]*:END:")
21835 (re-search-backward org-drawer-regexp nil t))
21836 (and (looking-at "[ \t]*#\\+end_")
21837 (re-search-backward "[ \t]*#\\+begin_"nil t))
21838 (looking-at "[ \t]*[\n:#|]")
21839 (looking-at org-footnote-definition-re)
21840 (and (ignore-errors (goto-char (org-in-item-p)))
21841 (goto-char
21842 (org-list-get-top-point (org-list-struct))))
21843 (and (not inline-task-p)
21844 (featurep 'org-inlinetask)
21845 (org-inlinetask-in-task-p)
21846 (or (org-inlinetask-goto-beginning) t))))
21847 (beginning-of-line 0))
21848 (cond
21849 ;; There was an heading above.
21850 ((looking-at "\\*+[ \t]+")
21851 (if (not org-adapt-indentation)
21852 (setq column 0)
21853 (goto-char (match-end 0))
21854 (setq column (current-column))))
21855 ;; A drawer had started and is unfinished
21856 ((looking-at org-drawer-regexp)
21857 (goto-char (1- (match-beginning 1)))
21858 (setq column (current-column)))
21859 ;; Else, nothing noticeable found: get indentation and go on.
21860 (t (setq column (org-get-indentation))))))
21861 ;; Now apply indentation and move cursor accordingly
21862 (goto-char pos)
21863 (if (<= (current-column) (current-indentation))
21864 (org-indent-line-to column)
21865 (save-excursion (org-indent-line-to column)))
21866 ;; Special polishing for properties, see `org-property-format'
21867 (setq column (current-column))
21868 (beginning-of-line 1)
21869 (if (looking-at
21870 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21871 (replace-match (concat (match-string 1)
21872 (format org-property-format
21873 (match-string 2) (match-string 3)))
21874 t t))
21875 (org-move-to-column column))))
21877 (defun org-indent-drawer ()
21878 "Indent the drawer at point."
21879 (interactive)
21880 (let ((p (point))
21881 (e (and (save-excursion (re-search-forward ":END:" nil t))
21882 (match-end 0)))
21883 (folded
21884 (save-excursion
21885 (end-of-line)
21886 (when (overlays-at (point))
21887 (member 'invisible (overlay-properties
21888 (car (overlays-at (point)))))))))
21889 (when folded (org-cycle))
21890 (indent-for-tab-command)
21891 (while (and (move-beginning-of-line 2) (< (point) e))
21892 (indent-for-tab-command))
21893 (goto-char p)
21894 (when folded (org-cycle)))
21895 (message "Drawer at point indented"))
21897 (defun org-indent-block ()
21898 "Indent the block at point."
21899 (interactive)
21900 (let ((p (point))
21901 (case-fold-search t)
21902 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21903 (match-end 0)))
21904 (folded
21905 (save-excursion
21906 (end-of-line)
21907 (when (overlays-at (point))
21908 (member 'invisible (overlay-properties
21909 (car (overlays-at (point)))))))))
21910 (when folded (org-cycle))
21911 (indent-for-tab-command)
21912 (while (and (move-beginning-of-line 2) (< (point) e))
21913 (indent-for-tab-command))
21914 (goto-char p)
21915 (when folded (org-cycle)))
21916 (message "Block at point indented"))
21918 (defun org-indent-region (start end)
21919 "Indent region."
21920 (interactive "r")
21921 (save-excursion
21922 (let ((line-end (org-current-line end)))
21923 (goto-char start)
21924 (while (< (org-current-line) line-end)
21925 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21926 (t (call-interactively 'org-indent-line)))
21927 (move-beginning-of-line 2)))))
21930 ;;; Filling
21932 ;; We use our own fill-paragraph and auto-fill functions.
21934 ;; `org-fill-paragraph' relies on adaptive filling and context
21935 ;; checking. Appropriate `fill-prefix' is computed with
21936 ;; `org-adaptive-fill-function'.
21938 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21939 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21940 ;; `org-adaptive-fill-function' value. Internally,
21941 ;; `org-comment-line-break-function' breaks the line.
21943 ;; `org-setup-filling' installs filling and auto-filling related
21944 ;; variables during `org-mode' initialization.
21946 (defun org-setup-filling ()
21947 (interactive)
21948 ;; Prevent auto-fill from inserting unwanted new items.
21949 (when (boundp 'fill-nobreak-predicate)
21950 (org-set-local
21951 'fill-nobreak-predicate
21952 (org-uniquify
21953 (append fill-nobreak-predicate
21954 '(org-fill-paragraph-separate-nobreak-p
21955 org-fill-line-break-nobreak-p
21956 org-fill-paragraph-with-timestamp-nobreak-p)))))
21957 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21958 (org-set-local 'auto-fill-inhibit-regexp nil)
21959 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21960 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21961 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21963 (defvar org-element-paragraph-separate) ; org-element.el
21964 (defun org-fill-paragraph-separate-nobreak-p ()
21965 "Non-nil when a line break at point would insert a new item."
21966 (looking-at (substring org-element-paragraph-separate 1)))
21968 (defun org-fill-line-break-nobreak-p ()
21969 "Non-nil when a line break at point would create an Org line break."
21970 (save-excursion
21971 (skip-chars-backward "[ \t]")
21972 (skip-chars-backward "\\\\")
21973 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21975 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21976 "Non-nil when a line break at point would insert a new item."
21977 (and (org-at-timestamp-p t)
21978 (not (looking-at org-ts-regexp-both))))
21980 (declare-function message-in-body-p "message" ())
21981 (defvar orgtbl-line-start-regexp) ; From org-table.el
21982 (defun org-adaptive-fill-function ()
21983 "Compute a fill prefix for the current line.
21984 Return fill prefix, as a string, or nil if current line isn't
21985 meant to be filled."
21986 (let (prefix)
21987 (catch 'exit
21988 (when (derived-mode-p 'message-mode)
21989 (save-excursion
21990 (beginning-of-line)
21991 (cond ((or (not (message-in-body-p))
21992 (looking-at orgtbl-line-start-regexp))
21993 (throw 'exit nil))
21994 ((looking-at message-cite-prefix-regexp)
21995 (throw 'exit (match-string-no-properties 0)))
21996 ((looking-at org-outline-regexp)
21997 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21998 (org-with-wide-buffer
21999 (let* ((p (line-beginning-position))
22000 (element (save-excursion (beginning-of-line)
22001 (org-element-at-point)))
22002 (type (org-element-type element))
22003 (post-affiliated (org-element-property :post-affiliated element)))
22004 (unless (and post-affiliated (< p post-affiliated))
22005 (case type
22006 (comment (looking-at "[ \t]*# ?") (match-string 0))
22007 (footnote-definition "")
22008 ((item plain-list)
22009 (make-string (org-list-item-body-column
22010 (or post-affiliated
22011 (org-element-property :begin element)))
22012 ? ))
22013 (paragraph
22014 ;; Fill prefix is usually the same as the current line,
22015 ;; except if the paragraph is at the beginning of an item.
22016 (let ((parent (org-element-property :parent element)))
22017 (cond ((eq (org-element-type parent) 'item)
22018 (make-string (org-list-item-body-column
22019 (org-element-property :begin parent))
22020 ? ))
22021 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22022 (match-string 0))
22023 (t ""))))
22024 (comment-block
22025 ;; Only fill contents if P is within block boundaries.
22026 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22027 (forward-line)
22028 (point)))
22029 (cend (save-excursion
22030 (goto-char (org-element-property :end element))
22031 (skip-chars-backward " \r\t\n")
22032 (line-beginning-position))))
22033 (when (and (>= p cbeg) (< p cend))
22034 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22035 (match-string 0)
22036 "")))))))))))
22038 (declare-function message-goto-body "message" ())
22039 (defvar message-cite-prefix-regexp) ; From message.el
22040 (defun org-fill-paragraph (&optional justify)
22041 "Fill element at point, when applicable.
22043 This function only applies to comment blocks, comments, example
22044 blocks and paragraphs. Also, as a special case, re-align table
22045 when point is at one.
22047 If JUSTIFY is non-nil (interactively, with prefix argument),
22048 justify as well. If `sentence-end-double-space' is non-nil, then
22049 period followed by one space does not end a sentence, so don't
22050 break a line there. The variable `fill-column' controls the
22051 width for filling.
22053 For convenience, when point is at a plain list, an item or
22054 a footnote definition, try to fill the first paragraph within."
22055 (interactive)
22056 (if (and (derived-mode-p 'message-mode)
22057 (or (not (message-in-body-p))
22058 (save-excursion (move-beginning-of-line 1)
22059 (looking-at message-cite-prefix-regexp))))
22060 ;; First ensure filling is correct in message-mode.
22061 (let ((fill-paragraph-function
22062 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22063 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22064 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22065 (paragraph-separate
22066 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22067 (fill-paragraph nil))
22068 (with-syntax-table org-mode-transpose-word-syntax-table
22069 ;; Move to end of line in order to get the first paragraph
22070 ;; within a plain list or a footnote definition.
22071 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22072 ;; First check if point is in a blank line at the beginning of
22073 ;; the buffer. In that case, ignore filling.
22074 (case (org-element-type element)
22075 ;; Use major mode filling function is src blocks.
22076 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22077 ;; Align Org tables, leave table.el tables as-is.
22078 (table-row (org-table-align) t)
22079 (table
22080 (when (eq (org-element-property :type element) 'org)
22081 (org-table-align))
22083 (paragraph
22084 ;; Paragraphs may contain `line-break' type objects.
22085 (let ((beg (max (point-min)
22086 (org-element-property :contents-begin element)))
22087 (end (min (point-max)
22088 (org-element-property :contents-end element))))
22089 ;; Do nothing if point is at an affiliated keyword.
22090 (if (< (line-end-position) beg) t
22091 (when (derived-mode-p 'message-mode)
22092 ;; In `message-mode', do not fill following citation
22093 ;; in current paragraph nor text before message body.
22094 (let ((body-start (save-excursion (message-goto-body))))
22095 (when body-start (setq beg (max body-start beg))))
22096 (when (save-excursion
22097 (re-search-forward
22098 (concat "^" message-cite-prefix-regexp) end t))
22099 (setq end (match-beginning 0))))
22100 ;; Fill paragraph, taking line breaks into account.
22101 ;; For that, slice the paragraph using line breaks as
22102 ;; separators, and fill the parts in reverse order to
22103 ;; avoid messing with markers.
22104 (save-excursion
22105 (goto-char end)
22106 (mapc
22107 (lambda (pos)
22108 (fill-region-as-paragraph pos (point) justify)
22109 (goto-char pos))
22110 ;; Find the list of ending positions for line breaks
22111 ;; in the current paragraph. Add paragraph
22112 ;; beginning to include first slice.
22113 (nreverse
22114 (cons beg
22115 (org-element-map
22116 (org-element--parse-objects
22117 beg end nil (org-element-restriction 'paragraph))
22118 'line-break
22119 (lambda (lb) (org-element-property :end lb)))))))
22120 t)))
22121 ;; Contents of `comment-block' type elements should be
22122 ;; filled as plain text, but only if point is within block
22123 ;; markers.
22124 (comment-block
22125 (let* ((case-fold-search t)
22126 (beg (save-excursion
22127 (goto-char (org-element-property :begin element))
22128 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22129 (forward-line)
22130 (point)))
22131 (end (save-excursion
22132 (goto-char (org-element-property :end element))
22133 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22134 (line-beginning-position))))
22135 (when (and (>= (point) beg) (< (point) end))
22136 (fill-region-as-paragraph
22137 (save-excursion
22138 (end-of-line)
22139 (re-search-backward "^[ \t]*$" beg 'move)
22140 (line-beginning-position))
22141 (save-excursion
22142 (beginning-of-line)
22143 (re-search-forward "^[ \t]*$" end 'move)
22144 (line-beginning-position))
22145 justify)))
22147 ;; Fill comments.
22148 (comment (fill-comment-paragraph justify))
22149 ;; Ignore every other element.
22150 (otherwise t))))))
22152 (defun org-auto-fill-function ()
22153 "Auto-fill function."
22154 ;; Check if auto-filling is meaningful.
22155 (let ((fc (current-fill-column)))
22156 (when (and fc (> (current-column) fc))
22157 (let* ((fill-prefix (org-adaptive-fill-function))
22158 ;; Enforce empty fill prefix, if required. Otherwise, it
22159 ;; will be computed again.
22160 (adaptive-fill-mode (not (equal fill-prefix ""))))
22161 (when fill-prefix (do-auto-fill))))))
22163 (defun org-comment-line-break-function (&optional soft)
22164 "Break line at point and indent, continuing comment if within one.
22165 The inserted newline is marked hard if variable
22166 `use-hard-newlines' is true, unless optional argument SOFT is
22167 non-nil."
22168 (if soft (insert-and-inherit ?\n) (newline 1))
22169 (save-excursion (forward-char -1) (delete-horizontal-space))
22170 (delete-horizontal-space)
22171 (indent-to-left-margin)
22172 (insert-before-markers-and-inherit fill-prefix))
22175 ;;; Comments
22177 ;; Org comments syntax is quite complex. It requires the entire line
22178 ;; to be just a comment. Also, even with the right syntax at the
22179 ;; beginning of line, some some elements (i.e. verse-block or
22180 ;; example-block) don't accept comments. Usual Emacs comment commands
22181 ;; cannot cope with those requirements. Therefore, Org replaces them.
22183 ;; Org still relies on `comment-dwim', but cannot trust
22184 ;; `comment-only-p'. So, `comment-region-function' and
22185 ;; `uncomment-region-function' both point
22186 ;; to`org-comment-or-uncomment-region'. Eventually,
22187 ;; `org-insert-comment' takes care of insertion of comments at the
22188 ;; beginning of line.
22190 ;; `org-setup-comments-handling' install comments related variables
22191 ;; during `org-mode' initialization.
22193 (defun org-setup-comments-handling ()
22194 (interactive)
22195 (org-set-local 'comment-use-syntax nil)
22196 (org-set-local 'comment-start "# ")
22197 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22198 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22199 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22200 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22202 (defun org-insert-comment ()
22203 "Insert an empty comment above current line.
22204 If the line is empty, insert comment at its beginning."
22205 (beginning-of-line)
22206 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22207 (org-indent-line)
22208 (insert "# "))
22210 (defvar comment-empty-lines) ; From newcomment.el.
22211 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22212 "Comment or uncomment each non-blank line in the region.
22213 Uncomment each non-blank line between BEG and END if it only
22214 contains commented lines. Otherwise, comment them."
22215 (save-restriction
22216 ;; Restrict region
22217 (narrow-to-region (save-excursion (goto-char beg)
22218 (skip-chars-forward " \r\t\n" end)
22219 (line-beginning-position))
22220 (save-excursion (goto-char end)
22221 (skip-chars-backward " \r\t\n" beg)
22222 (line-end-position)))
22223 (let ((uncommentp
22224 ;; UNCOMMENTP is non-nil when every non blank line between
22225 ;; BEG and END is a comment.
22226 (save-excursion
22227 (goto-char (point-min))
22228 (while (and (not (eobp))
22229 (let ((element (org-element-at-point)))
22230 (and (eq (org-element-type element) 'comment)
22231 (goto-char (min (point-max)
22232 (org-element-property
22233 :end element)))))))
22234 (eobp))))
22235 (if uncommentp
22236 ;; Only blank lines and comments in region: uncomment it.
22237 (save-excursion
22238 (goto-char (point-min))
22239 (while (not (eobp))
22240 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22241 (replace-match "" nil nil nil 1))
22242 (forward-line)))
22243 ;; Comment each line in region.
22244 (let ((min-indent (point-max)))
22245 ;; First find the minimum indentation across all lines.
22246 (save-excursion
22247 (goto-char (point-min))
22248 (while (and (not (eobp)) (not (zerop min-indent)))
22249 (unless (looking-at "[ \t]*$")
22250 (setq min-indent (min min-indent (current-indentation))))
22251 (forward-line)))
22252 ;; Then loop over all lines.
22253 (save-excursion
22254 (goto-char (point-min))
22255 (while (not (eobp))
22256 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22257 ;; Don't get fooled by invisible text (e.g. link path)
22258 ;; when moving to column MIN-INDENT.
22259 (let ((buffer-invisibility-spec nil))
22260 (org-move-to-column min-indent t))
22261 (insert comment-start))
22262 (forward-line))))))))
22265 ;;; Planning
22267 ;; This section contains tools to operate on timestamp objects, as
22268 ;; returned by, e.g. `org-element-context'.
22270 (defun org-timestamp-has-time-p (timestamp)
22271 "Non-nil when TIMESTAMP has a time specified."
22272 (org-element-property :hour-start timestamp))
22274 (defun org-timestamp-format (timestamp format &optional end utc)
22275 "Format a TIMESTAMP element into a string.
22277 FORMAT is a format specifier to be passed to
22278 `format-time-string'.
22280 When optional argument END is non-nil, use end of date-range or
22281 time-range, if possible.
22283 When optional argument UTC is non-nil, time will be expressed as
22284 Universal Time."
22285 (format-time-string
22286 format
22287 (apply 'encode-time
22288 (cons 0
22289 (mapcar
22290 (lambda (prop) (or (org-element-property prop timestamp) 0))
22291 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22292 '(:minute-start :hour-start :day-start :month-start
22293 :year-start)))))
22294 utc))
22296 (defun org-timestamp-split-range (timestamp &optional end)
22297 "Extract a timestamp object from a date or time range.
22299 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22300 the end of the range. Otherwise, extract its start.
22302 Return a new timestamp object sharing the same parent as
22303 TIMESTAMP."
22304 (let ((type (org-element-property :type timestamp)))
22305 (if (memq type '(active inactive diary)) timestamp
22306 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22307 ;; Set new type.
22308 (org-element-put-property
22309 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22310 ;; Copy start properties over end properties if END is
22311 ;; non-nil. Otherwise, copy end properties over `start' ones.
22312 (let ((p-alist '((:minute-start . :minute-end)
22313 (:hour-start . :hour-end)
22314 (:day-start . :day-end)
22315 (:month-start . :month-end)
22316 (:year-start . :year-end))))
22317 (dolist (p-cell p-alist)
22318 (org-element-put-property
22319 split-ts
22320 (funcall (if end 'car 'cdr) p-cell)
22321 (org-element-property
22322 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22323 ;; Eventually refresh `:raw-value'.
22324 (org-element-put-property split-ts :raw-value nil)
22325 (org-element-put-property
22326 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22328 (defun org-timestamp-translate (timestamp &optional boundary)
22329 "Apply `org-translate-time' on a TIMESTAMP object.
22330 When optional argument BOUNDARY is non-nil, it is either the
22331 symbol `start' or `end'. In this case, only translate the
22332 starting or ending part of TIMESTAMP if it is a date or time
22333 range. Otherwise, translate both parts."
22334 (if (and (not boundary)
22335 (memq (org-element-property :type timestamp)
22336 '(active-range inactive-range)))
22337 (concat
22338 (org-translate-time
22339 (org-element-property :raw-value
22340 (org-timestamp-split-range timestamp)))
22341 "--"
22342 (org-translate-time
22343 (org-element-property :raw-value
22344 (org-timestamp-split-range timestamp t))))
22345 (org-translate-time
22346 (org-element-property
22347 :raw-value
22348 (if (not boundary) timestamp
22349 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22353 ;;; Other stuff.
22355 (defun org-toggle-fixed-width-section (arg)
22356 "Toggle the fixed-width export.
22357 If there is no active region, the QUOTE keyword at the current headline is
22358 inserted or removed. When present, it causes the text between this headline
22359 and the next to be exported as fixed-width text, and unmodified.
22360 If there is an active region, this command adds or removes a colon as the
22361 first character of this line. If the first character of a line is a colon,
22362 this line is also exported in fixed-width font."
22363 (interactive "P")
22364 (let* ((cc 0)
22365 (regionp (org-region-active-p))
22366 (beg (if regionp (region-beginning) (point)))
22367 (end (if regionp (region-end)))
22368 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22369 (case-fold-search nil)
22370 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22371 off)
22372 (if regionp
22373 (save-excursion
22374 (goto-char beg)
22375 (setq cc (current-column))
22376 (beginning-of-line 1)
22377 (setq off (looking-at re))
22378 (while (> nlines 0)
22379 (setq nlines (1- nlines))
22380 (beginning-of-line 1)
22381 (cond
22382 (arg
22383 (org-move-to-column cc t)
22384 (insert ": \n")
22385 (forward-line -1))
22386 ((and off (looking-at re))
22387 (replace-match "" t t nil 1))
22388 ((not off) (org-move-to-column cc t) (insert ": ")))
22389 (forward-line 1)))
22390 (save-excursion
22391 (org-back-to-heading)
22392 (cond
22393 ((looking-at (format org-heading-keyword-regexp-format
22394 org-quote-string))
22395 (goto-char (match-end 1))
22396 (looking-at (concat " +" org-quote-string))
22397 (replace-match "" t t)
22398 (when (eolp) (insert " ")))
22399 ((looking-at org-outline-regexp)
22400 (goto-char (match-end 0))
22401 (insert org-quote-string " ")))))))
22403 (defun org-reftex-citation ()
22404 "Use reftex-citation to insert a citation into the buffer.
22405 This looks for a line like
22407 #+BIBLIOGRAPHY: foo plain option:-d
22409 and derives from it that foo.bib is the bibliography file relevant
22410 for this document. It then installs the necessary environment for RefTeX
22411 to work in this buffer and calls `reftex-citation' to insert a citation
22412 into the buffer.
22414 Export of such citations to both LaTeX and HTML is handled by the contributed
22415 package org-exp-bibtex by Taru Karttunen."
22416 (interactive)
22417 (let ((reftex-docstruct-symbol 'rds)
22418 (reftex-cite-format "\\cite{%l}")
22419 rds bib)
22420 (save-excursion
22421 (save-restriction
22422 (widen)
22423 (let ((case-fold-search t)
22424 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22425 (if (not (save-excursion
22426 (or (re-search-forward re nil t)
22427 (re-search-backward re nil t))))
22428 (error "No bibliography defined in file")
22429 (setq bib (concat (match-string 1) ".bib")
22430 rds (list (list 'bib bib)))))))
22431 (call-interactively 'reftex-citation)))
22433 ;;;; Functions extending outline functionality
22435 (defun org-beginning-of-line (&optional arg)
22436 "Go to the beginning of the current line. If that is invisible, continue
22437 to a visible line beginning. This makes the function of C-a more intuitive.
22438 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22439 first attempt, and only move to after the tags when the cursor is already
22440 beyond the end of the headline."
22441 (interactive "P")
22442 (let ((pos (point))
22443 (special (if (consp org-special-ctrl-a/e)
22444 (car org-special-ctrl-a/e)
22445 org-special-ctrl-a/e))
22446 refpos)
22447 (if (org-bound-and-true-p visual-line-mode)
22448 (beginning-of-visual-line 1)
22449 (beginning-of-line 1))
22450 (if (and arg (fboundp 'move-beginning-of-line))
22451 (call-interactively 'move-beginning-of-line)
22452 (if (bobp)
22454 (backward-char 1)
22455 (if (org-truely-invisible-p)
22456 (while (and (not (bobp)) (org-truely-invisible-p))
22457 (backward-char 1)
22458 (beginning-of-line 1))
22459 (forward-char 1))))
22460 (when special
22461 (cond
22462 ((and (looking-at org-complex-heading-regexp)
22463 (= (char-after (match-end 1)) ?\ ))
22464 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22465 (point-at-eol)))
22466 (goto-char
22467 (if (eq special t)
22468 (cond ((> pos refpos) refpos)
22469 ((= pos (point)) refpos)
22470 (t (point)))
22471 (cond ((> pos (point)) (point))
22472 ((not (eq last-command this-command)) (point))
22473 (t refpos)))))
22474 ((org-at-item-p)
22475 ;; Being at an item and not looking at an the item means point
22476 ;; was previously moved to beginning of a visual line, which
22477 ;; doesn't contain the item. Therefore, do nothing special,
22478 ;; just stay here.
22479 (when (looking-at org-list-full-item-re)
22480 ;; Set special position at first white space character after
22481 ;; bullet, and check-box, if any.
22482 (let ((after-bullet
22483 (let ((box (match-end 3)))
22484 (if (not box) (match-end 1)
22485 (let ((after (char-after box)))
22486 (if (and after (= after ? )) (1+ box) box))))))
22487 ;; Special case: Move point to special position when
22488 ;; currently after it or at beginning of line.
22489 (if (eq special t)
22490 (when (or (> pos after-bullet) (= (point) pos))
22491 (goto-char after-bullet))
22492 ;; Reversed case: Move point to special position when
22493 ;; point was already at beginning of line and command is
22494 ;; repeated.
22495 (when (and (= (point) pos) (eq last-command this-command))
22496 (goto-char after-bullet))))))))
22497 (org-no-warnings
22498 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22500 (defun org-end-of-line (&optional arg)
22501 "Go to the end of the line.
22502 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22503 tags on the first attempt, and only move to after the tags when
22504 the cursor is already beyond the end of the headline."
22505 (interactive "P")
22506 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22507 org-special-ctrl-a/e))
22508 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22509 'end-of-visual-line)
22510 ((fboundp 'move-end-of-line) 'move-end-of-line)
22511 (t 'end-of-line))))
22512 (if (or (not special) arg) (call-interactively move-fun)
22513 (let* ((element (save-excursion (beginning-of-line)
22514 (org-element-at-point)))
22515 (type (org-element-type element)))
22516 (cond
22517 ((memq type '(headline inlinetask))
22518 (let ((pos (point)))
22519 (beginning-of-line 1)
22520 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22521 (if (eq special t)
22522 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22523 (goto-char (match-beginning 1))
22524 (goto-char (match-end 0)))
22525 (if (or (< pos (match-end 0))
22526 (not (eq this-command last-command)))
22527 (goto-char (match-end 0))
22528 (goto-char (match-beginning 1))))
22529 (call-interactively move-fun))))
22530 ((org-element-property :hiddenp element)
22531 ;; If element is hidden, `move-end-of-line' would put point
22532 ;; after it. Use `end-of-line' to stay on current line.
22533 (call-interactively 'end-of-line))
22534 (t (call-interactively move-fun)))))
22535 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22537 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22538 (define-key org-mode-map "\C-e" 'org-end-of-line)
22540 (defun org-backward-sentence (&optional arg)
22541 "Go to beginning of sentence, or beginning of table field.
22542 This will call `backward-sentence' or `org-table-beginning-of-field',
22543 depending on context."
22544 (interactive "P")
22545 (cond
22546 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22547 (t (call-interactively 'backward-sentence))))
22549 (defun org-forward-sentence (&optional arg)
22550 "Go to end of sentence, or end of table field.
22551 This will call `forward-sentence' or `org-table-end-of-field',
22552 depending on context."
22553 (interactive "P")
22554 (cond
22555 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22556 (t (call-interactively 'forward-sentence))))
22558 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22559 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22561 (defun org-kill-line (&optional arg)
22562 "Kill line, to tags or end of line."
22563 (interactive "P")
22564 (cond
22565 ((or (not org-special-ctrl-k)
22566 (bolp)
22567 (not (org-at-heading-p)))
22568 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22569 org-ctrl-k-protect-subtree)
22570 (if (or (eq org-ctrl-k-protect-subtree 'error)
22571 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22572 (error "C-k aborted - would kill hidden subtree")))
22573 (call-interactively
22574 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22575 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22576 (kill-region (point) (match-beginning 1))
22577 (org-set-tags nil t))
22578 (t (kill-region (point) (point-at-eol)))))
22580 (define-key org-mode-map "\C-k" 'org-kill-line)
22582 (defun org-yank (&optional arg)
22583 "Yank. If the kill is a subtree, treat it specially.
22584 This command will look at the current kill and check if is a single
22585 subtree, or a series of subtrees[1]. If it passes the test, and if the
22586 cursor is at the beginning of a line or after the stars of a currently
22587 empty headline, then the yank is handled specially. How exactly depends
22588 on the value of the following variables, both set by default.
22590 org-yank-folded-subtrees
22591 When set, the subtree(s) will be folded after insertion, but only
22592 if doing so would now swallow text after the yanked text.
22594 org-yank-adjusted-subtrees
22595 When set, the subtree will be promoted or demoted in order to
22596 fit into the local outline tree structure, which means that the level
22597 will be adjusted so that it becomes the smaller one of the two
22598 *visible* surrounding headings.
22600 Any prefix to this command will cause `yank' to be called directly with
22601 no special treatment. In particular, a simple \\[universal-argument] prefix \
22602 will just
22603 plainly yank the text as it is.
22605 \[1] The test checks if the first non-white line is a heading
22606 and if there are no other headings with fewer stars."
22607 (interactive "P")
22608 (org-yank-generic 'yank arg))
22610 (defun org-yank-generic (command arg)
22611 "Perform some yank-like command.
22613 This function implements the behavior described in the `org-yank'
22614 documentation. However, it has been generalized to work for any
22615 interactive command with similar behavior."
22617 ;; pretend to be command COMMAND
22618 (setq this-command command)
22620 (if arg
22621 (call-interactively command)
22623 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22624 (and (org-kill-is-subtree-p)
22625 (or (bolp)
22626 (and (looking-at "[ \t]*$")
22627 (string-match
22628 "\\`\\*+\\'"
22629 (buffer-substring (point-at-bol) (point)))))))
22630 swallowp)
22631 (cond
22632 ((and subtreep org-yank-folded-subtrees)
22633 (let ((beg (point))
22634 end)
22635 (if (and subtreep org-yank-adjusted-subtrees)
22636 (org-paste-subtree nil nil 'for-yank)
22637 (call-interactively command))
22639 (setq end (point))
22640 (goto-char beg)
22641 (when (and (bolp) subtreep
22642 (not (setq swallowp
22643 (org-yank-folding-would-swallow-text beg end))))
22644 (org-with-limited-levels
22645 (or (looking-at org-outline-regexp)
22646 (re-search-forward org-outline-regexp-bol end t))
22647 (while (and (< (point) end) (looking-at org-outline-regexp))
22648 (hide-subtree)
22649 (org-cycle-show-empty-lines 'folded)
22650 (condition-case nil
22651 (outline-forward-same-level 1)
22652 (error (goto-char end))))))
22653 (when swallowp
22654 (message
22655 "Inserted text not folded because that would swallow text"))
22657 (goto-char end)
22658 (skip-chars-forward " \t\n\r")
22659 (beginning-of-line 1)
22660 (push-mark beg 'nomsg)))
22661 ((and subtreep org-yank-adjusted-subtrees)
22662 (let ((beg (point-at-bol)))
22663 (org-paste-subtree nil nil 'for-yank)
22664 (push-mark beg 'nomsg)))
22666 (call-interactively command))))))
22668 (defun org-yank-folding-would-swallow-text (beg end)
22669 "Would hide-subtree at BEG swallow any text after END?"
22670 (let (level)
22671 (org-with-limited-levels
22672 (save-excursion
22673 (goto-char beg)
22674 (when (or (looking-at org-outline-regexp)
22675 (re-search-forward org-outline-regexp-bol end t))
22676 (setq level (org-outline-level)))
22677 (goto-char end)
22678 (skip-chars-forward " \t\r\n\v\f")
22679 (if (or (eobp)
22680 (and (bolp) (looking-at org-outline-regexp)
22681 (<= (org-outline-level) level)))
22682 nil ; Nothing would be swallowed
22683 t))))) ; something would swallow
22685 (define-key org-mode-map "\C-y" 'org-yank)
22687 (defun org-truely-invisible-p ()
22688 "Check if point is at a character currently not visible.
22689 This version does not only check the character property, but also
22690 `visible-mode'."
22691 ;; Early versions of noutline don't have `outline-invisible-p'.
22692 (if (org-bound-and-true-p visible-mode)
22694 (outline-invisible-p)))
22696 (defun org-invisible-p2 ()
22697 "Check if point is at a character currently not visible."
22698 (save-excursion
22699 (if (and (eolp) (not (bobp))) (backward-char 1))
22700 ;; Early versions of noutline don't have `outline-invisible-p'.
22701 (outline-invisible-p)))
22703 (defun org-back-to-heading (&optional invisible-ok)
22704 "Call `outline-back-to-heading', but provide a better error message."
22705 (condition-case nil
22706 (outline-back-to-heading invisible-ok)
22707 (error (error "Before first headline at position %d in buffer %s"
22708 (point) (current-buffer)))))
22710 (defun org-before-first-heading-p ()
22711 "Before first heading?"
22712 (save-excursion
22713 (end-of-line)
22714 (null (re-search-backward org-outline-regexp-bol nil t))))
22716 (defun org-at-heading-p (&optional ignored)
22717 (outline-on-heading-p t))
22718 ;; Compatibility alias with Org versions < 7.8.03
22719 (defalias 'org-on-heading-p 'org-at-heading-p)
22721 (defun org-at-comment-p nil
22722 "Is cursor in a line starting with a # character?"
22723 (save-excursion
22724 (beginning-of-line)
22725 (looking-at "^#")))
22727 (defun org-at-drawer-p nil
22728 "Is cursor at a drawer keyword?"
22729 (save-excursion
22730 (move-beginning-of-line 1)
22731 (looking-at org-drawer-regexp)))
22733 (defun org-at-block-p nil
22734 "Is cursor at a block keyword?"
22735 (save-excursion
22736 (move-beginning-of-line 1)
22737 (looking-at org-block-regexp)))
22739 (defun org-point-at-end-of-empty-headline ()
22740 "If point is at the end of an empty headline, return t, else nil.
22741 If the heading only contains a TODO keyword, it is still still considered
22742 empty."
22743 (and (looking-at "[ \t]*$")
22744 (when org-todo-line-regexp
22745 (save-excursion
22746 (beginning-of-line 1)
22747 (let ((case-fold-search nil))
22748 (looking-at org-todo-line-regexp)
22749 (string= (match-string 3) ""))))))
22751 (defun org-at-heading-or-item-p ()
22752 (or (org-at-heading-p) (org-at-item-p)))
22754 (defun org-at-target-p ()
22755 (or (org-in-regexp org-radio-target-regexp)
22756 (org-in-regexp org-target-regexp)))
22757 ;; Compatibility alias with Org versions < 7.8.03
22758 (defalias 'org-on-target-p 'org-at-target-p)
22760 (defun org-up-heading-all (arg)
22761 "Move to the heading line of which the present line is a subheading.
22762 This function considers both visible and invisible heading lines.
22763 With argument, move up ARG levels."
22764 (if (fboundp 'outline-up-heading-all)
22765 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22766 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22768 (defun org-up-heading-safe ()
22769 "Move to the heading line of which the present line is a subheading.
22770 This version will not throw an error. It will return the level of the
22771 headline found, or nil if no higher level is found.
22773 Also, this function will be a lot faster than `outline-up-heading',
22774 because it relies on stars being the outline starters. This can really
22775 make a significant difference in outlines with very many siblings."
22776 (let (start-level re)
22777 (org-back-to-heading t)
22778 (setq start-level (funcall outline-level))
22779 (if (equal start-level 1)
22781 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22782 (if (re-search-backward re nil t)
22783 (funcall outline-level)))))
22785 (defun org-first-sibling-p ()
22786 "Is this heading the first child of its parents?"
22787 (interactive)
22788 (let ((re org-outline-regexp-bol)
22789 level l)
22790 (unless (org-at-heading-p t)
22791 (error "Not at a heading"))
22792 (setq level (funcall outline-level))
22793 (save-excursion
22794 (if (not (re-search-backward re nil t))
22796 (setq l (funcall outline-level))
22797 (< l level)))))
22799 (defun org-goto-sibling (&optional previous)
22800 "Goto the next sibling, even if it is invisible.
22801 When PREVIOUS is set, go to the previous sibling instead. Returns t
22802 when a sibling was found. When none is found, return nil and don't
22803 move point."
22804 (let ((fun (if previous 're-search-backward 're-search-forward))
22805 (pos (point))
22806 (re org-outline-regexp-bol)
22807 level l)
22808 (when (condition-case nil (org-back-to-heading t) (error nil))
22809 (setq level (funcall outline-level))
22810 (catch 'exit
22811 (or previous (forward-char 1))
22812 (while (funcall fun re nil t)
22813 (setq l (funcall outline-level))
22814 (when (< l level) (goto-char pos) (throw 'exit nil))
22815 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22816 (goto-char pos)
22817 nil))))
22819 (defun org-show-siblings ()
22820 "Show all siblings of the current headline."
22821 (save-excursion
22822 (while (org-goto-sibling) (org-flag-heading nil)))
22823 (save-excursion
22824 (while (org-goto-sibling 'previous)
22825 (org-flag-heading nil))))
22827 (defun org-goto-first-child ()
22828 "Goto the first child, even if it is invisible.
22829 Return t when a child was found. Otherwise don't move point and
22830 return nil."
22831 (let (level (pos (point)) (re org-outline-regexp-bol))
22832 (when (condition-case nil (org-back-to-heading t) (error nil))
22833 (setq level (outline-level))
22834 (forward-char 1)
22835 (if (and (re-search-forward re nil t) (> (outline-level) level))
22836 (progn (goto-char (match-beginning 0)) t)
22837 (goto-char pos) nil))))
22839 (defun org-show-hidden-entry ()
22840 "Show an entry where even the heading is hidden."
22841 (save-excursion
22842 (org-show-entry)))
22844 (defun org-flag-heading (flag &optional entry)
22845 "Flag the current heading. FLAG non-nil means make invisible.
22846 When ENTRY is non-nil, show the entire entry."
22847 (save-excursion
22848 (org-back-to-heading t)
22849 ;; Check if we should show the entire entry
22850 (if entry
22851 (progn
22852 (org-show-entry)
22853 (save-excursion
22854 (and (outline-next-heading)
22855 (org-flag-heading nil))))
22856 (outline-flag-region (max (point-min) (1- (point)))
22857 (save-excursion (outline-end-of-heading) (point))
22858 flag))))
22860 (defun org-get-next-sibling ()
22861 "Move to next heading of the same level, and return point.
22862 If there is no such heading, return nil.
22863 This is like outline-next-sibling, but invisible headings are ok."
22864 (let ((level (funcall outline-level)))
22865 (outline-next-heading)
22866 (while (and (not (eobp)) (> (funcall outline-level) level))
22867 (outline-next-heading))
22868 (if (or (eobp) (< (funcall outline-level) level))
22870 (point))))
22872 (defun org-get-last-sibling ()
22873 "Move to previous heading of the same level, and return point.
22874 If there is no such heading, return nil."
22875 (let ((opoint (point))
22876 (level (funcall outline-level)))
22877 (outline-previous-heading)
22878 (when (and (/= (point) opoint) (outline-on-heading-p t))
22879 (while (and (> (funcall outline-level) level)
22880 (not (bobp)))
22881 (outline-previous-heading))
22882 (if (< (funcall outline-level) level)
22884 (point)))))
22886 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22887 "Goto to the end of a subtree."
22888 ;; This contains an exact copy of the original function, but it uses
22889 ;; `org-back-to-heading', to make it work also in invisible
22890 ;; trees. And is uses an invisible-ok argument.
22891 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22892 ;; Furthermore, when used inside Org, finding the end of a large subtree
22893 ;; with many children and grandchildren etc, this can be much faster
22894 ;; than the outline version.
22895 (org-back-to-heading invisible-ok)
22896 (let ((first t)
22897 (level (funcall outline-level)))
22898 (if (and (derived-mode-p 'org-mode) (< level 1000))
22899 ;; A true heading (not a plain list item), in Org-mode
22900 ;; This means we can easily find the end by looking
22901 ;; only for the right number of stars. Using a regexp to do
22902 ;; this is so much faster than using a Lisp loop.
22903 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22904 (forward-char 1)
22905 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22906 ;; something else, do it the slow way
22907 (while (and (not (eobp))
22908 (or first (> (funcall outline-level) level)))
22909 (setq first nil)
22910 (outline-next-heading)))
22911 (unless to-heading
22912 (if (memq (preceding-char) '(?\n ?\^M))
22913 (progn
22914 ;; Go to end of line before heading
22915 (forward-char -1)
22916 (if (memq (preceding-char) '(?\n ?\^M))
22917 ;; leave blank line before heading
22918 (forward-char -1))))))
22919 (point))
22921 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22922 "Use Org version in org-mode, for dramatic speed-up."
22923 (if (derived-mode-p 'org-mode)
22924 (progn
22925 (org-end-of-subtree nil t)
22926 (unless (eobp) (backward-char 1)))
22927 ad-do-it))
22929 (defun org-end-of-meta-data-and-drawers ()
22930 "Jump to the first text after meta data and drawers in the current entry.
22931 This will move over empty lines, lines with planning time stamps,
22932 clocking lines, and drawers."
22933 (org-back-to-heading t)
22934 (let ((end (save-excursion (outline-next-heading) (point)))
22935 (re (concat "\\(" org-drawer-regexp "\\)"
22936 "\\|" "[ \t]*" org-keyword-time-regexp)))
22937 (forward-line 1)
22938 (while (re-search-forward re end t)
22939 (if (not (match-end 1))
22940 ;; empty or planning line
22941 (forward-line 1)
22942 ;; a drawer, find the end
22943 (re-search-forward "^[ \t]*:END:" end 'move)
22944 (forward-line 1)))
22945 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22946 (point)))
22948 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22949 "Move forward to the ARG'th subheading at same level as this one.
22950 Stop at the first and last subheadings of a superior heading.
22951 Normally this only looks at visible headings, but when INVISIBLE-OK is
22952 non-nil it will also look at invisible ones."
22953 (interactive "p")
22954 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22955 (if (and arg (< arg 0))
22956 (goto-char (point-min))
22957 (outline-next-heading))
22958 (org-at-heading-p)
22959 (let ((level (- (match-end 0) (match-beginning 0) 1))
22960 (f (if (and arg (< arg 0))
22961 're-search-backward
22962 're-search-forward))
22963 (count (if arg (abs arg) 1))
22964 (result (point)))
22965 (forward-char (if (and arg (< arg 0)) -1 1))
22966 (while (and (> count 0)
22967 (funcall f org-outline-regexp-bol nil 'move))
22968 (let ((l (- (match-end 0) (match-beginning 0) 1)))
22969 (cond ((< l level) (setq count 0))
22970 ((and (= l level)
22971 (or invisible-ok
22972 (progn
22973 (goto-char (line-beginning-position))
22974 (not (outline-invisible-p)))))
22975 (setq count (1- count))
22976 (when (eq l level)
22977 (setq result (point)))))))
22978 (goto-char result))
22979 (beginning-of-line 1)))
22981 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22982 "Move backward to the ARG'th subheading at same level as this one.
22983 Stop at the first and last subheadings of a superior heading."
22984 (interactive "p")
22985 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
22987 (defun org-next-block (arg &optional backward block-regexp)
22988 "Jump to the next block.
22989 With a prefix argument ARG, jump forward ARG many source blocks.
22990 When BACKWARD is non-nil, jump to the previous block.
22991 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22992 (interactive "p")
22993 (let ((re (or block-regexp org-block-regexp))
22994 (re-search-fn (or (and backward 're-search-backward)
22995 're-search-forward)))
22996 (if (looking-at re) (forward-char 1))
22997 (condition-case nil
22998 (funcall re-search-fn re nil nil arg)
22999 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23000 (goto-char (match-beginning 0)) (org-show-context)))
23002 (defun org-previous-block (arg &optional block-regexp)
23003 "Jump to the previous block.
23004 With a prefix argument ARG, jump backward ARG many source blocks.
23005 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23006 (interactive "p")
23007 (org-next-block arg t block-regexp))
23009 (defun org-forward-element ()
23010 "Move forward by one element.
23011 Move to the next element at the same level, when possible."
23012 (interactive)
23013 (cond ((eobp) (user-error "Cannot move further down"))
23014 ((org-with-limited-levels (org-at-heading-p))
23015 (let ((origin (point)))
23016 (goto-char (org-end-of-subtree nil t))
23017 (unless (org-with-limited-levels (org-at-heading-p))
23018 (goto-char origin)
23019 (user-error "Cannot move further down"))))
23021 (let* ((elem (org-element-at-point))
23022 (end (org-element-property :end elem))
23023 (parent (org-element-property :parent elem)))
23024 (if (and parent (= (org-element-property :contents-end parent) end))
23025 (goto-char (org-element-property :end parent))
23026 (goto-char end))))))
23028 (defun org-backward-element ()
23029 "Move backward by one element.
23030 Move to the previous element at the same level, when possible."
23031 (interactive)
23032 (cond ((bobp) (user-error "Cannot move further up"))
23033 ((org-with-limited-levels (org-at-heading-p))
23034 ;; At a headline, move to the previous one, if any, or stay
23035 ;; here.
23036 (let ((origin (point)))
23037 (org-with-limited-levels (org-backward-heading-same-level 1))
23038 ;; When current headline has no sibling above, move to its
23039 ;; parent.
23040 (when (= (point) origin)
23041 (or (org-with-limited-levels (org-up-heading-safe))
23042 (progn (goto-char origin)
23043 (user-error "Cannot move further up"))))))
23045 (let* ((trail (org-element-at-point 'keep-trail))
23046 (elem (car trail))
23047 (prev-elem (nth 1 trail))
23048 (beg (org-element-property :begin elem)))
23049 (cond
23050 ;; Move to beginning of current element if point isn't
23051 ;; there already.
23052 ((/= (point) beg) (goto-char beg))
23053 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23054 ((org-before-first-heading-p) (goto-char (point-min)))
23055 (t (org-back-to-heading)))))))
23057 (defun org-up-element ()
23058 "Move to upper element."
23059 (interactive)
23060 (if (org-with-limited-levels (org-at-heading-p))
23061 (unless (org-up-heading-safe) (error "No surrounding element"))
23062 (let* ((elem (org-element-at-point))
23063 (parent (org-element-property :parent elem)))
23064 (if parent (goto-char (org-element-property :begin parent))
23065 (if (org-with-limited-levels (org-before-first-heading-p))
23066 (error "No surrounding element")
23067 (org-with-limited-levels (org-back-to-heading)))))))
23069 (defvar org-element-greater-elements)
23070 (defun org-down-element ()
23071 "Move to inner element."
23072 (interactive)
23073 (let ((element (org-element-at-point)))
23074 (cond
23075 ((memq (org-element-type element) '(plain-list table))
23076 (goto-char (org-element-property :contents-begin element))
23077 (forward-char))
23078 ((memq (org-element-type element) org-element-greater-elements)
23079 ;; If contents are hidden, first disclose them.
23080 (when (org-element-property :hiddenp element) (org-cycle))
23081 (goto-char (or (org-element-property :contents-begin element)
23082 (error "No content for this element"))))
23083 (t (error "No inner element")))))
23085 (defun org-drag-element-backward ()
23086 "Move backward element at point."
23087 (interactive)
23088 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23089 (let* ((trail (org-element-at-point 'keep-trail))
23090 (elem (car trail))
23091 (prev-elem (nth 1 trail)))
23092 ;; Error out if no previous element or previous element is
23093 ;; a parent of the current one.
23094 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23095 (error "Cannot drag element backward")
23096 (let ((pos (point)))
23097 (org-element-swap-A-B prev-elem elem)
23098 (goto-char (+ (org-element-property :begin prev-elem)
23099 (- pos (org-element-property :begin elem)))))))))
23101 (defun org-drag-element-forward ()
23102 "Move forward element at point."
23103 (interactive)
23104 (let* ((pos (point))
23105 (elem (org-element-at-point)))
23106 (when (= (point-max) (org-element-property :end elem))
23107 (error "Cannot drag element forward"))
23108 (goto-char (org-element-property :end elem))
23109 (let ((next-elem (org-element-at-point)))
23110 (when (or (org-element-nested-p elem next-elem)
23111 (and (eq (org-element-type next-elem) 'headline)
23112 (not (eq (org-element-type elem) 'headline))))
23113 (goto-char pos)
23114 (error "Cannot drag element forward"))
23115 ;; Compute new position of point: it's shifted by NEXT-ELEM
23116 ;; body's length (without final blanks) and by the length of
23117 ;; blanks between ELEM and NEXT-ELEM.
23118 (let ((size-next (- (save-excursion
23119 (goto-char (org-element-property :end next-elem))
23120 (skip-chars-backward " \r\t\n")
23121 (forward-line)
23122 ;; Small correction if buffer doesn't end
23123 ;; with a newline character.
23124 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23125 (org-element-property :begin next-elem)))
23126 (size-blank (- (org-element-property :end elem)
23127 (save-excursion
23128 (goto-char (org-element-property :end elem))
23129 (skip-chars-backward " \r\t\n")
23130 (forward-line)
23131 (point)))))
23132 (org-element-swap-A-B elem next-elem)
23133 (goto-char (+ pos size-next size-blank))))))
23135 (defun org-drag-line-forward (arg)
23136 "Drag the line at point ARG lines forward."
23137 (interactive "p")
23138 (dotimes (n (abs arg))
23139 (let ((c (current-column)))
23140 (if (< 0 arg)
23141 (progn
23142 (beginning-of-line 2)
23143 (transpose-lines 1)
23144 (beginning-of-line 0))
23145 (transpose-lines 1)
23146 (beginning-of-line -1))
23147 (org-move-to-column c))))
23149 (defun org-drag-line-backward (arg)
23150 "Drag the line at point ARG lines backward."
23151 (interactive "p")
23152 (org-drag-line-forward (- arg)))
23154 (defun org-mark-element ()
23155 "Put point at beginning of this element, mark at end.
23157 Interactively, if this command is repeated or (in Transient Mark
23158 mode) if the mark is active, it marks the next element after the
23159 ones already marked."
23160 (interactive)
23161 (let (deactivate-mark)
23162 (if (and (org-called-interactively-p 'any)
23163 (or (and (eq last-command this-command) (mark t))
23164 (and transient-mark-mode mark-active)))
23165 (set-mark
23166 (save-excursion
23167 (goto-char (mark))
23168 (goto-char (org-element-property :end (org-element-at-point)))))
23169 (let ((element (org-element-at-point)))
23170 (end-of-line)
23171 (push-mark (org-element-property :end element) t t)
23172 (goto-char (org-element-property :begin element))))))
23174 (defun org-narrow-to-element ()
23175 "Narrow buffer to current element."
23176 (interactive)
23177 (let ((elem (org-element-at-point)))
23178 (cond
23179 ((eq (car elem) 'headline)
23180 (narrow-to-region
23181 (org-element-property :begin elem)
23182 (org-element-property :end elem)))
23183 ((memq (car elem) org-element-greater-elements)
23184 (narrow-to-region
23185 (org-element-property :contents-begin elem)
23186 (org-element-property :contents-end elem)))
23188 (narrow-to-region
23189 (org-element-property :begin elem)
23190 (org-element-property :end elem))))))
23192 (defun org-transpose-element ()
23193 "Transpose current and previous elements, keeping blank lines between.
23194 Point is moved after both elements."
23195 (interactive)
23196 (org-skip-whitespace)
23197 (let ((end (org-element-property :end (org-element-at-point))))
23198 (org-drag-element-backward)
23199 (goto-char end)))
23201 (defun org-unindent-buffer ()
23202 "Un-indent the visible part of the buffer.
23203 Relative indentation (between items, inside blocks, etc.) isn't
23204 modified."
23205 (interactive)
23206 (unless (eq major-mode 'org-mode)
23207 (error "Cannot un-indent a buffer not in Org mode"))
23208 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23209 unindent-tree ; For byte-compiler.
23210 (unindent-tree
23211 (function
23212 (lambda (contents)
23213 (mapc
23214 (lambda (element)
23215 (if (memq (org-element-type element) '(headline section))
23216 (funcall unindent-tree (org-element-contents element))
23217 (save-excursion
23218 (save-restriction
23219 (narrow-to-region
23220 (org-element-property :begin element)
23221 (org-element-property :end element))
23222 (org-do-remove-indentation)))))
23223 (reverse contents))))))
23224 (funcall unindent-tree (org-element-contents parse-tree))))
23226 (defun org-show-subtree ()
23227 "Show everything after this heading at deeper levels."
23228 (interactive)
23229 (outline-flag-region
23230 (point)
23231 (save-excursion
23232 (org-end-of-subtree t t))
23233 nil))
23235 (defun org-show-entry ()
23236 "Show the body directly following this heading.
23237 Show the heading too, if it is currently invisible."
23238 (interactive)
23239 (save-excursion
23240 (condition-case nil
23241 (progn
23242 (org-back-to-heading t)
23243 (outline-flag-region
23244 (max (point-min) (1- (point)))
23245 (save-excursion
23246 (if (re-search-forward
23247 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23248 (match-beginning 1)
23249 (point-max)))
23250 nil)
23251 (org-cycle-hide-drawers 'children))
23252 (error nil))))
23254 (defun org-make-options-regexp (kwds &optional extra)
23255 "Make a regular expression for keyword lines."
23256 (concat
23257 "^#\\+\\("
23258 (mapconcat 'regexp-quote kwds "\\|")
23259 (if extra (concat "\\|" extra))
23260 "\\):[ \t]*\\(.*\\)"))
23262 ;; Make isearch reveal the necessary context
23263 (defun org-isearch-end ()
23264 "Reveal context after isearch exits."
23265 (when isearch-success ; only if search was successful
23266 (if (featurep 'xemacs)
23267 ;; Under XEmacs, the hook is run in the correct place,
23268 ;; we directly show the context.
23269 (org-show-context 'isearch)
23270 ;; In Emacs the hook runs *before* restoring the overlays.
23271 ;; So we have to use a one-time post-command-hook to do this.
23272 ;; (Emacs 22 has a special variable, see function `org-mode')
23273 (unless (and (boundp 'isearch-mode-end-hook-quit)
23274 isearch-mode-end-hook-quit)
23275 ;; Only when the isearch was not quitted.
23276 (org-add-hook 'post-command-hook 'org-isearch-post-command
23277 'append 'local)))
23278 (org-fix-ellipsis-at-bol)))
23280 (defun org-isearch-post-command ()
23281 "Remove self from hook, and show context."
23282 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23283 (org-show-context 'isearch))
23286 ;;;; Integration with and fixes for other packages
23288 ;;; Imenu support
23290 (defvar org-imenu-markers nil
23291 "All markers currently used by Imenu.")
23292 (make-variable-buffer-local 'org-imenu-markers)
23294 (defun org-imenu-new-marker (&optional pos)
23295 "Return a new marker for use by Imenu, and remember the marker."
23296 (let ((m (make-marker)))
23297 (move-marker m (or pos (point)))
23298 (push m org-imenu-markers)
23301 (defun org-imenu-get-tree ()
23302 "Produce the index for Imenu."
23303 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23304 (setq org-imenu-markers nil)
23305 (let* ((n org-imenu-depth)
23306 (re (concat "^" (org-get-limited-outline-regexp)))
23307 (subs (make-vector (1+ n) nil))
23308 (last-level 0)
23309 m level head0 head)
23310 (save-excursion
23311 (save-restriction
23312 (widen)
23313 (goto-char (point-max))
23314 (while (re-search-backward re nil t)
23315 (setq level (org-reduced-level (funcall outline-level)))
23316 (when (and (<= level n)
23317 (looking-at org-complex-heading-regexp)
23318 (setq head0 (org-match-string-no-properties 4)))
23319 (setq head (org-link-display-format head0)
23320 m (org-imenu-new-marker))
23321 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23322 (if (>= level last-level)
23323 (push (cons head m) (aref subs level))
23324 (push (cons head (aref subs (1+ level))) (aref subs level))
23325 (loop for i from (1+ level) to n do (aset subs i nil)))
23326 (setq last-level level)))))
23327 (aref subs 1)))
23329 (eval-after-load "imenu"
23330 '(progn
23331 (add-hook 'imenu-after-jump-hook
23332 (lambda ()
23333 (if (derived-mode-p 'org-mode)
23334 (org-show-context 'org-goto))))))
23336 (defun org-link-display-format (link)
23337 "Replace a link with its the description.
23338 If there is no description, use the link target."
23339 (save-match-data
23340 (if (string-match org-bracket-link-analytic-regexp link)
23341 (replace-match (if (match-end 5)
23342 (match-string 5 link)
23343 (concat (match-string 1 link)
23344 (match-string 3 link)))
23345 nil t link)
23346 link)))
23348 (defun org-toggle-link-display ()
23349 "Toggle the literal or descriptive display of links."
23350 (interactive)
23351 (if org-descriptive-links
23352 (progn (org-remove-from-invisibility-spec '(org-link))
23353 (org-restart-font-lock)
23354 (setq org-descriptive-links nil))
23355 (progn (add-to-invisibility-spec '(org-link))
23356 (org-restart-font-lock)
23357 (setq org-descriptive-links t))))
23359 ;; Speedbar support
23361 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23362 "Overlay marking the agenda restriction line in speedbar.")
23363 (overlay-put org-speedbar-restriction-lock-overlay
23364 'face 'org-agenda-restriction-lock)
23365 (overlay-put org-speedbar-restriction-lock-overlay
23366 'help-echo "Agendas are currently limited to this item.")
23367 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23369 (defun org-speedbar-set-agenda-restriction ()
23370 "Restrict future agenda commands to the location at point in speedbar.
23371 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23372 (interactive)
23373 (require 'org-agenda)
23374 (let (p m tp np dir txt)
23375 (cond
23376 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23377 'org-imenu t))
23378 (setq m (get-text-property p 'org-imenu-marker))
23379 (with-current-buffer (marker-buffer m)
23380 (goto-char m)
23381 (org-agenda-set-restriction-lock 'subtree)))
23382 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23383 'speedbar-function 'speedbar-find-file))
23384 (setq tp (previous-single-property-change
23385 (1+ p) 'speedbar-function)
23386 np (next-single-property-change
23387 tp 'speedbar-function)
23388 dir (speedbar-line-directory)
23389 txt (buffer-substring-no-properties (or tp (point-min))
23390 (or np (point-max))))
23391 (with-current-buffer (find-file-noselect
23392 (let ((default-directory dir))
23393 (expand-file-name txt)))
23394 (unless (derived-mode-p 'org-mode)
23395 (error "Cannot restrict to non-Org-mode file"))
23396 (org-agenda-set-restriction-lock 'file)))
23397 (t (error "Don't know how to restrict Org-mode's agenda")))
23398 (move-overlay org-speedbar-restriction-lock-overlay
23399 (point-at-bol) (point-at-eol))
23400 (setq current-prefix-arg nil)
23401 (org-agenda-maybe-redo)))
23403 (eval-after-load "speedbar"
23404 '(progn
23405 (speedbar-add-supported-extension ".org")
23406 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23407 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23408 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23409 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23410 (add-hook 'speedbar-visiting-tag-hook
23411 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23413 ;;; Fixes and Hacks for problems with other packages
23415 ;; Make flyspell not check words in links, to not mess up our keymap
23416 (defvar org-element-affiliated-keywords) ; From org-element.el
23417 (defvar org-element-block-name-alist) ; From org-element.el
23418 (defun org-mode-flyspell-verify ()
23419 "Don't let flyspell put overlays at active buttons, or on
23420 {todo,all-time,additional-option-like}-keywords."
23421 (require 'org-element) ; For `org-element-affiliated-keywords'
23422 (let ((pos (max (1- (point)) (point-min)))
23423 (word (thing-at-point 'word)))
23424 (and (not (get-text-property pos 'keymap))
23425 (not (get-text-property pos 'org-no-flyspell))
23426 (not (member word org-todo-keywords-1))
23427 (not (member word org-all-time-keywords))
23428 (not (member word org-options-keywords))
23429 (not (member word (mapcar 'car org-startup-options)))
23430 (not (member-ignore-case word org-element-affiliated-keywords))
23431 (not (member-ignore-case word (org-get-export-keywords)))
23432 (not (member-ignore-case
23433 word (mapcar 'car org-element-block-name-alist)))
23434 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23436 (defun org-remove-flyspell-overlays-in (beg end)
23437 "Remove flyspell overlays in region."
23438 (and (org-bound-and-true-p flyspell-mode)
23439 (fboundp 'flyspell-delete-region-overlays)
23440 (flyspell-delete-region-overlays beg end))
23441 (add-text-properties beg end '(org-no-flyspell t)))
23443 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23444 (eval-after-load "bookmark"
23445 '(if (boundp 'bookmark-after-jump-hook)
23446 ;; We can use the hook
23447 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23448 ;; Hook not available, use advice
23449 (defadvice bookmark-jump (after org-make-visible activate)
23450 "Make the position visible."
23451 (org-bookmark-jump-unhide))))
23453 ;; Make sure saveplace shows the location if it was hidden
23454 (eval-after-load "saveplace"
23455 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23456 "Make the position visible."
23457 (org-bookmark-jump-unhide)))
23459 ;; Make sure ecb shows the location if it was hidden
23460 (eval-after-load "ecb"
23461 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23462 "Make hierarchy visible when jumping into location from ECB tree buffer."
23463 (if (derived-mode-p 'org-mode)
23464 (org-show-context))))
23466 (defun org-bookmark-jump-unhide ()
23467 "Unhide the current position, to show the bookmark location."
23468 (and (derived-mode-p 'org-mode)
23469 (or (outline-invisible-p)
23470 (save-excursion (goto-char (max (point-min) (1- (point))))
23471 (outline-invisible-p)))
23472 (org-show-context 'bookmark-jump)))
23474 ;; Make session.el ignore our circular variable
23475 (eval-after-load "session"
23476 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23478 ;;;; Experimental code
23480 (defun org-closed-in-range ()
23481 "Sparse tree of items closed in a certain time range.
23482 Still experimental, may disappear in the future."
23483 (interactive)
23484 ;; Get the time interval from the user.
23485 (let* ((time1 (org-float-time
23486 (org-read-date nil 'to-time nil "Starting date: ")))
23487 (time2 (org-float-time
23488 (org-read-date nil 'to-time nil "End date:")))
23489 ;; callback function
23490 (callback (lambda ()
23491 (let ((time
23492 (org-float-time
23493 (apply 'encode-time
23494 (org-parse-time-string
23495 (match-string 1))))))
23496 ;; check if time in interval
23497 (and (>= time time1) (<= time time2))))))
23498 ;; make tree, check each match with the callback
23499 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
23501 ;;;; Finish up
23503 (provide 'org)
23505 (run-hooks 'org-load-hook)
23507 ;;; org.el ends here