org.el (org-link-display-format): Fix docstring
[org-mode.git] / lisp / org.el
blob5f37f4831aa9cf1a17d7f670fdbb3790c7894dc4
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-id-get-create "org-id" (&optional force))
130 (declare-function org-id-find-id-file "org-id" (id))
131 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
132 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
133 (declare-function org-table-align "org-table" ())
134 (declare-function org-table-paste-rectangle "org-table" ())
135 (declare-function org-table-maybe-eval-formula "org-table" ())
136 (declare-function org-table-maybe-recalculate-line "org-table" ())
138 (declare-function org-element--parse-objects "org-element"
139 (beg end acc restriction))
140 (declare-function org-element-at-point "org-element" (&optional keep-trail))
141 (declare-function org-element-contents "org-element" (element))
142 (declare-function org-element-context "org-element" (&optional element))
143 (declare-function org-element-interpret-data "org-element"
144 (data &optional parent))
145 (declare-function org-element-map "org-element"
146 (data types fun &optional info first-match no-recursion))
147 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
148 (declare-function org-element-parse-buffer "org-element"
149 (&optional granularity visible-only))
150 (declare-function org-element-property "org-element" (property element))
151 (declare-function org-element-put-property "org-element"
152 (element property value))
153 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
154 (declare-function org-element--parse-objects "org-element"
155 (beg end acc restriction))
156 (declare-function org-element-parse-buffer "org-element"
157 (&optional granularity visible-only))
158 (declare-function org-element-restriction "org-element" (element))
159 (declare-function org-element-type "org-element" (element))
161 ;; load languages based on value of `org-babel-load-languages'
162 (defvar org-babel-load-languages)
164 ;;;###autoload
165 (defun org-babel-do-load-languages (sym value)
166 "Load the languages defined in `org-babel-load-languages'."
167 (set-default sym value)
168 (mapc (lambda (pair)
169 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
170 (if active
171 (progn
172 (require (intern (concat "ob-" lang))))
173 (progn
174 (funcall 'fmakunbound
175 (intern (concat "org-babel-execute:" lang)))
176 (funcall 'fmakunbound
177 (intern (concat "org-babel-expand-body:" lang)))))))
178 org-babel-load-languages))
180 (defcustom org-babel-load-languages '((emacs-lisp . t))
181 "Languages which can be evaluated in Org-mode buffers.
182 This list can be used to load support for any of the languages
183 below, note that each language will depend on a different set of
184 system executables and/or Emacs modes. When a language is
185 \"loaded\", then code blocks in that language can be evaluated
186 with `org-babel-execute-src-block' bound by default to C-c
187 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
188 be set to remove code block evaluation from the C-c C-c
189 keybinding. By default only Emacs Lisp (which has no
190 requirements) is loaded."
191 :group 'org-babel
192 :set 'org-babel-do-load-languages
193 :version "24.1"
194 :type '(alist :tag "Babel Languages"
195 :key-type
196 (choice
197 (const :tag "Awk" awk)
198 (const :tag "C" C)
199 (const :tag "R" R)
200 (const :tag "Asymptote" asymptote)
201 (const :tag "Calc" calc)
202 (const :tag "Clojure" clojure)
203 (const :tag "CSS" css)
204 (const :tag "Ditaa" ditaa)
205 (const :tag "Dot" dot)
206 (const :tag "Emacs Lisp" emacs-lisp)
207 (const :tag "Fortran" fortran)
208 (const :tag "Gnuplot" gnuplot)
209 (const :tag "Haskell" haskell)
210 (const :tag "IO" io)
211 (const :tag "Java" java)
212 (const :tag "Javascript" js)
213 (const :tag "LaTeX" latex)
214 (const :tag "Ledger" ledger)
215 (const :tag "Lilypond" lilypond)
216 (const :tag "Lisp" lisp)
217 (const :tag "Makefile" makefile)
218 (const :tag "Maxima" maxima)
219 (const :tag "Matlab" matlab)
220 (const :tag "Mscgen" mscgen)
221 (const :tag "Ocaml" ocaml)
222 (const :tag "Octave" octave)
223 (const :tag "Org" org)
224 (const :tag "Perl" perl)
225 (const :tag "Pico Lisp" picolisp)
226 (const :tag "PlantUML" plantuml)
227 (const :tag "Python" python)
228 (const :tag "Ruby" ruby)
229 (const :tag "Sass" sass)
230 (const :tag "Scala" scala)
231 (const :tag "Scheme" scheme)
232 (const :tag "Screen" screen)
233 (const :tag "Shell Script" sh)
234 (const :tag "Shen" shen)
235 (const :tag "Sql" sql)
236 (const :tag "Sqlite" sqlite))
237 :value-type (boolean :tag "Activate" :value t)))
239 ;;;; Customization variables
240 (defcustom org-clone-delete-id nil
241 "Remove ID property of clones of a subtree.
242 When non-nil, clones of a subtree don't inherit the ID property.
243 Otherwise they inherit the ID property with a new unique
244 identifier."
245 :type 'boolean
246 :version "24.1"
247 :group 'org-id)
249 ;;; Version
250 (org-check-version)
252 ;;;###autoload
253 (defun org-version (&optional here full message)
254 "Show the org-mode version in the echo area.
255 With prefix argument HERE, insert it at point.
256 When FULL is non-nil, use a verbose version string.
257 When MESSAGE is non-nil, display a message with the version."
258 (interactive "P")
259 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
260 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
261 (load-suffixes (list ".el"))
262 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
263 (org-trash (or
264 (and (fboundp 'org-release) (fboundp 'org-git-version))
265 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
266 (load-suffixes save-load-suffixes)
267 (org-version (org-release))
268 (git-version (org-git-version))
269 (version (format "Org-mode version %s (%s @ %s)"
270 org-version
271 git-version
272 (if org-install-dir
273 (if (string= org-dir org-install-dir)
274 org-install-dir
275 (concat "mixed installation! " org-install-dir " and " org-dir))
276 "org-loaddefs.el can not be found!")))
277 (_version (if full version org-version)))
278 (if (org-called-interactively-p 'interactive)
279 (if here
280 (insert version)
281 (message version))
282 (if message (message _version))
283 _version)))
285 (defconst org-version (org-version))
287 ;;; Compatibility constants
289 ;;; The custom variables
291 (defgroup org nil
292 "Outline-based notes management and organizer."
293 :tag "Org"
294 :group 'outlines
295 :group 'calendar)
297 (defcustom org-mode-hook nil
298 "Mode hook for Org-mode, run after the mode was turned on."
299 :group 'org
300 :type 'hook)
302 (defcustom org-load-hook nil
303 "Hook that is run after org.el has been loaded."
304 :group 'org
305 :type 'hook)
307 (defcustom org-log-buffer-setup-hook nil
308 "Hook that is run after an Org log buffer is created."
309 :group 'org
310 :version "24.1"
311 :type 'hook)
313 (defvar org-modules) ; defined below
314 (defvar org-modules-loaded nil
315 "Have the modules been loaded already?")
317 (defun org-load-modules-maybe (&optional force)
318 "Load all extensions listed in `org-modules'."
319 (when (or force (not org-modules-loaded))
320 (mapc (lambda (ext)
321 (condition-case nil (require ext)
322 (error (message "Problems while trying to load feature `%s'" ext))))
323 org-modules)
324 (setq org-modules-loaded t)))
326 (defun org-set-modules (var value)
327 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
328 (set var value)
329 (when (featurep 'org)
330 (org-load-modules-maybe 'force)))
332 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
333 "Modules that should always be loaded together with org.el.
335 If a description starts with <C>, the file is not part of Emacs
336 and loading it will require that you have downloaded and properly
337 installed the Org mode distribution.
339 You can also use this system to load external packages (i.e. neither Org
340 core modules, nor modules from the CONTRIB directory). Just add symbols
341 to the end of the list. If the package is called org-xyz.el, then you need
342 to add the symbol `xyz', and the package must have a call to:
344 \(provide 'org-xyz)
346 For export specific modules, see also `org-export-backends'."
347 :group 'org
348 :set 'org-set-modules
349 :version "24.4"
350 :package-version '(Org . "8.0")
351 :type
352 '(set :greedy t
353 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
354 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
355 (const :tag " crypt: Encryption of subtrees" org-crypt)
356 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
357 (const :tag " docview: Links to doc-view buffers" org-docview)
358 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
359 (const :tag " id: Global IDs for identifying entries" org-id)
360 (const :tag " info: Links to Info nodes" org-info)
361 (const :tag " habit: Track your consistency with habits" org-habit)
362 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
363 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
364 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
365 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
366 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
367 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
368 (const :tag " mouse: Additional mouse support" org-mouse)
370 (const :tag "C vm: Links to VM folders/messages" org-vm)
371 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
372 (const :tag "C w3m: Special cut/paste from w3m to Org-mode." org-w3m)
373 (const :tag "C mew: Links to Mew folders/messages" org-mew)
374 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
375 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
376 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
377 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
378 (const :tag "C collector: Collect properties into tables" org-collector)
379 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
380 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
381 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
382 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
383 (const :tag "C eval: Include command output as text" org-eval)
384 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
385 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
386 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
387 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
388 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
390 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
392 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
393 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
394 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
395 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
396 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
397 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
398 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
399 (const :tag "C mtags: Support for muse-like tags" org-mtags)
400 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
401 (const :tag "C registry: A registry for Org-mode links" org-registry)
402 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
403 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
404 (const :tag "C secretary: Team management with org-mode" org-secretary)
405 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
406 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
407 (const :tag "C track: Keep up with Org-mode development" org-track)
408 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
409 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
410 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
412 (defvar org-export-registered-backends) ; From ox.el
413 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
414 (defcustom org-export-backends '(ascii html icalendar latex)
415 "List of export back-ends that should be always available.
417 If a description starts with <C>, the file is not part of Emacs
418 and loading it will require that you have downloaded and properly
419 installed the Org mode distribution.
421 Unlike to `org-modules', libraries in this list will not be
422 loaded along with Org, but only once the export framework is
423 needed.
425 This variable needs to be set before org.el is loaded. If you
426 need to make a change while Emacs is running, use the customize
427 interface or run the following code, where VALUE stands for the
428 new value of the variable, after updating it:
430 \(progn
431 \(setq org-export-registered-backends
432 \(org-remove-if-not
433 \(lambda (backend)
434 \(or (memq backend val)
435 \(catch 'parentp
436 \(mapc
437 \(lambda (b)
438 \(and (org-export-derived-backend-p b (car backend))
439 \(throw 'parentp t)))
440 val)
441 nil)))
442 org-export-registered-backends))
443 \(let ((new-list (mapcar 'car org-export-registered-backends)))
444 \(dolist (backend val)
445 \(cond
446 \((not (load (format \"ox-%s\" backend) t t))
447 \(message \"Problems while trying to load export back-end `%s'\"
448 backend))
449 \((not (memq backend new-list)) (push backend new-list))))
450 \(set-default var new-list)))
452 Adding a back-end to this list will also pull the back-end it
453 depends on, if any."
454 :group 'org
455 :group 'org-export
456 :version "24.4"
457 :package-version '(Org . "8.0")
458 :initialize 'custom-initialize-set
459 :set (lambda (var val)
460 (if (not (featurep 'ox)) (set-default var val)
461 ;; Any back-end not required anymore (not present in VAL and not
462 ;; a parent of any back-end in the new value) is removed from the
463 ;; list of registered back-ends.
464 (setq org-export-registered-backends
465 (org-remove-if-not
466 (lambda (backend)
467 (or (memq backend val)
468 (catch 'parentp
469 (mapc
470 (lambda (b)
471 (and (org-export-derived-backend-p b (car backend))
472 (throw 'parentp t)))
473 val)
474 nil)))
475 org-export-registered-backends))
476 ;; Now build NEW-LIST of both new back-ends and required
477 ;; parents.
478 (let ((new-list (mapcar 'car org-export-registered-backends)))
479 (dolist (backend val)
480 (cond
481 ((not (load (format "ox-%s" backend) t t))
482 (message "Problems while trying to load export back-end `%s'"
483 backend))
484 ((not (memq backend new-list)) (push backend new-list))))
485 ;; Set VAR to that list with fixed dependencies.
486 (set-default var new-list))))
487 :type '(set :greedy t
488 (const :tag " ascii Export buffer to ASCII format" ascii)
489 (const :tag " beamer Export buffer to Beamer presentation" beamer)
490 (const :tag " html Export buffer to HTML format" html)
491 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
492 (const :tag " latex Export buffer to LaTeX format" latex)
493 (const :tag " man Export buffer to MAN format" man)
494 (const :tag " md Export buffer to Markdown format" md)
495 (const :tag " odt Export buffer to ODT format" odt)
496 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
497 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
498 (const :tag "C deck Export buffer to deck.js presentations" deck)
499 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
500 (const :tag "C groff Export buffer to Groff format" groff)
501 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
502 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
503 (const :tag "C s5 Export buffer to s5 presentations" s5)
504 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
506 (eval-after-load 'ox
507 '(mapc
508 (lambda (backend)
509 (condition-case nil (require (intern (format "ox-%s" backend)))
510 (error (message "Problems while trying to load export back-end `%s'"
511 backend))))
512 org-export-backends))
514 (defcustom org-support-shift-select nil
515 "Non-nil means make shift-cursor commands select text when possible.
517 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
518 start selecting a region, or enlarge regions started in this way.
519 In Org-mode, in special contexts, these same keys are used for
520 other purposes, important enough to compete with shift selection.
521 Org tries to balance these needs by supporting `shift-select-mode'
522 outside these special contexts, under control of this variable.
524 The default of this variable is nil, to avoid confusing behavior. Shifted
525 cursor keys will then execute Org commands in the following contexts:
526 - on a headline, changing TODO state (left/right) and priority (up/down)
527 - on a time stamp, changing the time
528 - in a plain list item, changing the bullet type
529 - in a property definition line, switching between allowed values
530 - in the BEGIN line of a clock table (changing the time block).
531 Outside these contexts, the commands will throw an error.
533 When this variable is t and the cursor is not in a special
534 context, Org-mode will support shift-selection for making and
535 enlarging regions. To make this more effective, the bullet
536 cycling will no longer happen anywhere in an item line, but only
537 if the cursor is exactly on the bullet.
539 If you set this variable to the symbol `always', then the keys
540 will not be special in headlines, property lines, and item lines,
541 to make shift selection work there as well. If this is what you
542 want, you can use the following alternative commands: `C-c C-t'
543 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
544 can be used to switch TODO sets, `C-c -' to cycle item bullet
545 types, and properties can be edited by hand or in column view.
547 However, when the cursor is on a timestamp, shift-cursor commands
548 will still edit the time stamp - this is just too good to give up.
550 XEmacs user should have this variable set to nil, because
551 `shift-select-mode' is in Emacs 23 or later only."
552 :group 'org
553 :type '(choice
554 (const :tag "Never" nil)
555 (const :tag "When outside special context" t)
556 (const :tag "Everywhere except timestamps" always)))
558 (defcustom org-loop-over-headlines-in-active-region nil
559 "Shall some commands act upon headlines in the active region?
561 When set to `t', some commands will be performed in all headlines
562 within the active region.
564 When set to `start-level', some commands will be performed in all
565 headlines within the active region, provided that these headlines
566 are of the same level than the first one.
568 When set to a string, those commands will be performed on the
569 matching headlines within the active region. Such string must be
570 a tags/property/todo match as it is used in the agenda tags view.
572 The list of commands is: `org-schedule', `org-deadline',
573 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
574 `org-archive-to-archive-sibling'. The archiving commands skip
575 already archived entries."
576 :type '(choice (const :tag "Don't loop" nil)
577 (const :tag "All headlines in active region" t)
578 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
579 (string :tag "Tags/Property/Todo matcher"))
580 :version "24.1"
581 :group 'org-todo
582 :group 'org-archive)
584 (defgroup org-startup nil
585 "Options concerning startup of Org-mode."
586 :tag "Org Startup"
587 :group 'org)
589 (defcustom org-startup-folded t
590 "Non-nil means entering Org-mode will switch to OVERVIEW.
591 This can also be configured on a per-file basis by adding one of
592 the following lines anywhere in the buffer:
594 #+STARTUP: fold (or `overview', this is equivalent)
595 #+STARTUP: nofold (or `showall', this is equivalent)
596 #+STARTUP: content
597 #+STARTUP: showeverything
599 By default, this option is ignored when Org opens agenda files
600 for the first time. If you want the agenda to honor the startup
601 option, set `org-agenda-inhibit-startup' to nil."
602 :group 'org-startup
603 :type '(choice
604 (const :tag "nofold: show all" nil)
605 (const :tag "fold: overview" t)
606 (const :tag "content: all headlines" content)
607 (const :tag "show everything, even drawers" showeverything)))
609 (defcustom org-startup-truncated t
610 "Non-nil means entering Org-mode will set `truncate-lines'.
611 This is useful since some lines containing links can be very long and
612 uninteresting. Also tables look terrible when wrapped."
613 :group 'org-startup
614 :type 'boolean)
616 (defcustom org-startup-indented nil
617 "Non-nil means turn on `org-indent-mode' on startup.
618 This can also be configured on a per-file basis by adding one of
619 the following lines anywhere in the buffer:
621 #+STARTUP: indent
622 #+STARTUP: noindent"
623 :group 'org-structure
624 :type '(choice
625 (const :tag "Not" nil)
626 (const :tag "Globally (slow on startup in large files)" t)))
628 (defcustom org-use-sub-superscripts t
629 "Non-nil means interpret \"_\" and \"^\" for display.
630 When this option is turned on, you can use TeX-like syntax for sub- and
631 superscripts. Several characters after \"_\" or \"^\" will be
632 considered as a single item - so grouping with {} is normally not
633 needed. For example, the following things will be parsed as single
634 sub- or superscripts.
636 10^24 or 10^tau several digits will be considered 1 item.
637 10^-12 or 10^-tau a leading sign with digits or a word
638 x^2-y^3 will be read as x^2 - y^3, because items are
639 terminated by almost any nonword/nondigit char.
640 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
642 Still, ambiguity is possible - so when in doubt use {} to enclose
643 the sub/superscript. If you set this variable to the symbol
644 `{}', the braces are *required* in order to trigger
645 interpretations as sub/superscript. This can be helpful in
646 documents that need \"_\" frequently in plain text."
647 :group 'org-startup
648 :version "24.1"
649 :type '(choice
650 (const :tag "Always interpret" t)
651 (const :tag "Only with braces" {})
652 (const :tag "Never interpret" nil)))
654 (defcustom org-startup-with-beamer-mode nil
655 "Non-nil means turn on `org-beamer-mode' on startup.
656 This can also be configured on a per-file basis by adding one of
657 the following lines anywhere in the buffer:
659 #+STARTUP: beamer"
660 :group 'org-startup
661 :version "24.1"
662 :type 'boolean)
664 (defcustom org-startup-align-all-tables nil
665 "Non-nil means align all tables when visiting a file.
666 This is useful when the column width in tables is forced with <N> cookies
667 in table fields. Such tables will look correct only after the first re-align.
668 This can also be configured on a per-file basis by adding one of
669 the following lines anywhere in the buffer:
670 #+STARTUP: align
671 #+STARTUP: noalign"
672 :group 'org-startup
673 :type 'boolean)
675 (defcustom org-startup-with-inline-images nil
676 "Non-nil means show inline images when loading a new Org file.
677 This can also be configured on a per-file basis by adding one of
678 the following lines anywhere in the buffer:
679 #+STARTUP: inlineimages
680 #+STARTUP: noinlineimages"
681 :group 'org-startup
682 :version "24.1"
683 :type 'boolean)
685 (defcustom org-startup-with-latex-preview nil
686 "Non-nil means preview LaTeX fragments when loading a new Org file.
688 This can also be configured on a per-file basis by adding one of
689 the followinglines anywhere in the buffer:
690 #+STARTUP: latexpreview
691 #+STARTUP: nolatexpreview"
692 :group 'org-startup
693 :version "24.4"
694 :package-version '(Org . "8.0")
695 :type 'boolean)
697 (defcustom org-insert-mode-line-in-empty-file nil
698 "Non-nil means insert the first line setting Org-mode in empty files.
699 When the function `org-mode' is called interactively in an empty file, this
700 normally means that the file name does not automatically trigger Org-mode.
701 To ensure that the file will always be in Org-mode in the future, a
702 line enforcing Org-mode will be inserted into the buffer, if this option
703 has been set."
704 :group 'org-startup
705 :type 'boolean)
707 (defcustom org-replace-disputed-keys nil
708 "Non-nil means use alternative key bindings for some keys.
709 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
710 These keys are also used by other packages like shift-selection-mode'
711 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
712 If you want to use Org-mode together with one of these other modes,
713 or more generally if you would like to move some Org-mode commands to
714 other keys, set this variable and configure the keys with the variable
715 `org-disputed-keys'.
717 This option is only relevant at load-time of Org-mode, and must be set
718 *before* org.el is loaded. Changing it requires a restart of Emacs to
719 become effective."
720 :group 'org-startup
721 :type 'boolean)
723 (defcustom org-use-extra-keys nil
724 "Non-nil means use extra key sequence definitions for certain commands.
725 This happens automatically if you run XEmacs or if `window-system'
726 is nil. This variable lets you do the same manually. You must
727 set it before loading org.
729 Example: on Carbon Emacs 22 running graphically, with an external
730 keyboard on a Powerbook, the default way of setting M-left might
731 not work for either Alt or ESC. Setting this variable will make
732 it work for ESC."
733 :group 'org-startup
734 :type 'boolean)
736 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
738 (defcustom org-disputed-keys
739 '(([(shift up)] . [(meta p)])
740 ([(shift down)] . [(meta n)])
741 ([(shift left)] . [(meta -)])
742 ([(shift right)] . [(meta +)])
743 ([(control shift right)] . [(meta shift +)])
744 ([(control shift left)] . [(meta shift -)]))
745 "Keys for which Org-mode and other modes compete.
746 This is an alist, cars are the default keys, second element specifies
747 the alternative to use when `org-replace-disputed-keys' is t.
749 Keys can be specified in any syntax supported by `define-key'.
750 The value of this option takes effect only at Org-mode's startup,
751 therefore you'll have to restart Emacs to apply it after changing."
752 :group 'org-startup
753 :type 'alist)
755 (defun org-key (key)
756 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
757 Or return the original if not disputed.
758 Also apply the translations defined in `org-xemacs-key-equivalents'."
759 (when org-replace-disputed-keys
760 (let* ((nkey (key-description key))
761 (x (org-find-if (lambda (x)
762 (equal (key-description (car x)) nkey))
763 org-disputed-keys)))
764 (setq key (if x (cdr x) key))))
765 (when (featurep 'xemacs)
766 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
767 key)
769 (defun org-find-if (predicate seq)
770 (catch 'exit
771 (while seq
772 (if (funcall predicate (car seq))
773 (throw 'exit (car seq))
774 (pop seq)))))
776 (defun org-defkey (keymap key def)
777 "Define a key, possibly translated, as returned by `org-key'."
778 (define-key keymap (org-key key) def))
780 (defcustom org-ellipsis nil
781 "The ellipsis to use in the Org-mode outline.
782 When nil, just use the standard three dots. When a string, use that instead,
783 When a face, use the standard 3 dots, but with the specified face.
784 The change affects only Org-mode (which will then use its own display table).
785 Changing this requires executing `M-x org-mode' in a buffer to become
786 effective."
787 :group 'org-startup
788 :type '(choice (const :tag "Default" nil)
789 (face :tag "Face" :value org-warning)
790 (string :tag "String" :value "...#")))
792 (defvar org-display-table nil
793 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
795 (defgroup org-keywords nil
796 "Keywords in Org-mode."
797 :tag "Org Keywords"
798 :group 'org)
800 (defcustom org-deadline-string "DEADLINE:"
801 "String to mark deadline entries.
802 A deadline is this string, followed by a time stamp. Should be a word,
803 terminated by a colon. You can insert a schedule keyword and
804 a timestamp with \\[org-deadline].
805 Changes become only effective after restarting Emacs."
806 :group 'org-keywords
807 :type 'string)
809 (defcustom org-scheduled-string "SCHEDULED:"
810 "String to mark scheduled TODO entries.
811 A schedule is this string, followed by a time stamp. Should be a word,
812 terminated by a colon. You can insert a schedule keyword and
813 a timestamp with \\[org-schedule].
814 Changes become only effective after restarting Emacs."
815 :group 'org-keywords
816 :type 'string)
818 (defcustom org-closed-string "CLOSED:"
819 "String used as the prefix for timestamps logging closing a TODO entry."
820 :group 'org-keywords
821 :type 'string)
823 (defcustom org-clock-string "CLOCK:"
824 "String used as prefix for timestamps clocking work hours on an item."
825 :group 'org-keywords
826 :type 'string)
828 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
829 org-scheduled-string "\\|"
830 org-deadline-string "\\|"
831 org-closed-string "\\|"
832 org-clock-string "\\)")
833 "Matches a line with planning or clock info.")
835 (defcustom org-comment-string "COMMENT"
836 "Entries starting with this keyword will never be exported.
837 An entry can be toggled between COMMENT and normal with
838 \\[org-toggle-comment].
839 Changes become only effective after restarting Emacs."
840 :group 'org-keywords
841 :type 'string)
843 (defcustom org-quote-string "QUOTE"
844 "Entries starting with this keyword will be exported in fixed-width font.
845 Quoting applies only to the text in the entry following the headline, and does
846 not extend beyond the next headline, even if that is lower level.
847 An entry can be toggled between QUOTE and normal with
848 \\[org-toggle-fixed-width-section]."
849 :group 'org-keywords
850 :type 'string)
852 (defconst org-repeat-re
853 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
854 "Regular expression for specifying repeated events.
855 After a match, group 1 contains the repeat expression.")
857 (defgroup org-structure nil
858 "Options concerning the general structure of Org-mode files."
859 :tag "Org Structure"
860 :group 'org)
862 (defgroup org-reveal-location nil
863 "Options about how to make context of a location visible."
864 :tag "Org Reveal Location"
865 :group 'org-structure)
867 (defconst org-context-choice
868 '(choice
869 (const :tag "Always" t)
870 (const :tag "Never" nil)
871 (repeat :greedy t :tag "Individual contexts"
872 (cons
873 (choice :tag "Context"
874 (const agenda)
875 (const org-goto)
876 (const occur-tree)
877 (const tags-tree)
878 (const link-search)
879 (const mark-goto)
880 (const bookmark-jump)
881 (const isearch)
882 (const default))
883 (boolean))))
884 "Contexts for the reveal options.")
886 (defcustom org-show-hierarchy-above '((default . t))
887 "Non-nil means show full hierarchy when revealing a location.
888 Org-mode often shows locations in an org-mode file which might have
889 been invisible before. When this is set, the hierarchy of headings
890 above the exposed location is shown.
891 Turning this off for example for sparse trees makes them very compact.
892 Instead of t, this can also be an alist specifying this option for different
893 contexts. Valid contexts are
894 agenda when exposing an entry from the agenda
895 org-goto when using the command `org-goto' on key C-c C-j
896 occur-tree when using the command `org-occur' on key C-c /
897 tags-tree when constructing a sparse tree based on tags matches
898 link-search when exposing search matches associated with a link
899 mark-goto when exposing the jump goal of a mark
900 bookmark-jump when exposing a bookmark location
901 isearch when exiting from an incremental search
902 default default for all contexts not set explicitly"
903 :group 'org-reveal-location
904 :type org-context-choice)
906 (defcustom org-show-following-heading '((default . nil))
907 "Non-nil means show following heading when revealing a location.
908 Org-mode often shows locations in an org-mode file which might have
909 been invisible before. When this is set, the heading following the
910 match is shown.
911 Turning this off for example for sparse trees makes them very compact,
912 but makes it harder to edit the location of the match. In such a case,
913 use the command \\[org-reveal] to show more context.
914 Instead of t, this can also be an alist specifying this option for different
915 contexts. See `org-show-hierarchy-above' for valid contexts."
916 :group 'org-reveal-location
917 :type org-context-choice)
919 (defcustom org-show-siblings '((default . nil) (isearch t))
920 "Non-nil means show all sibling heading when revealing a location.
921 Org-mode often shows locations in an org-mode file which might have
922 been invisible before. When this is set, the sibling of the current entry
923 heading are all made visible. If `org-show-hierarchy-above' is t,
924 the same happens on each level of the hierarchy above the current entry.
926 By default this is on for the isearch context, off for all other contexts.
927 Turning this off for example for sparse trees makes them very compact,
928 but makes it harder to edit the location of the match. In such a case,
929 use the command \\[org-reveal] to show more context.
930 Instead of t, this can also be an alist specifying this option for different
931 contexts. See `org-show-hierarchy-above' for valid contexts."
932 :group 'org-reveal-location
933 :type org-context-choice)
935 (defcustom org-show-entry-below '((default . nil))
936 "Non-nil means show the entry below a headline when revealing a location.
937 Org-mode often shows locations in an org-mode file which might have
938 been invisible before. When this is set, the text below the headline that is
939 exposed is also shown.
941 By default this is off for all contexts.
942 Instead of t, this can also be an alist specifying this option for different
943 contexts. See `org-show-hierarchy-above' for valid contexts."
944 :group 'org-reveal-location
945 :type org-context-choice)
947 (defcustom org-indirect-buffer-display 'other-window
948 "How should indirect tree buffers be displayed?
949 This applies to indirect buffers created with the commands
950 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
951 Valid values are:
952 current-window Display in the current window
953 other-window Just display in another window.
954 dedicated-frame Create one new frame, and re-use it each time.
955 new-frame Make a new frame each time. Note that in this case
956 previously-made indirect buffers are kept, and you need to
957 kill these buffers yourself."
958 :group 'org-structure
959 :group 'org-agenda-windows
960 :type '(choice
961 (const :tag "In current window" current-window)
962 (const :tag "In current frame, other window" other-window)
963 (const :tag "Each time a new frame" new-frame)
964 (const :tag "One dedicated frame" dedicated-frame)))
966 (defcustom org-use-speed-commands nil
967 "Non-nil means activate single letter commands at beginning of a headline.
968 This may also be a function to test for appropriate locations where speed
969 commands should be active."
970 :group 'org-structure
971 :type '(choice
972 (const :tag "Never" nil)
973 (const :tag "At beginning of headline stars" t)
974 (function)))
976 (defcustom org-speed-commands-user nil
977 "Alist of additional speed commands.
978 This list will be checked before `org-speed-commands-default'
979 when the variable `org-use-speed-commands' is non-nil
980 and when the cursor is at the beginning of a headline.
981 The car if each entry is a string with a single letter, which must
982 be assigned to `self-insert-command' in the global map.
983 The cdr is either a command to be called interactively, a function
984 to be called, or a form to be evaluated.
985 An entry that is just a list with a single string will be interpreted
986 as a descriptive headline that will be added when listing the speed
987 commands in the Help buffer using the `?' speed command."
988 :group 'org-structure
989 :type '(repeat :value ("k" . ignore)
990 (choice :value ("k" . ignore)
991 (list :tag "Descriptive Headline" (string :tag "Headline"))
992 (cons :tag "Letter and Command"
993 (string :tag "Command letter")
994 (choice
995 (function)
996 (sexp))))))
998 (defgroup org-cycle nil
999 "Options concerning visibility cycling in Org-mode."
1000 :tag "Org Cycle"
1001 :group 'org-structure)
1003 (defcustom org-cycle-skip-children-state-if-no-children t
1004 "Non-nil means skip CHILDREN state in entries that don't have any."
1005 :group 'org-cycle
1006 :type 'boolean)
1008 (defcustom org-cycle-max-level nil
1009 "Maximum level which should still be subject to visibility cycling.
1010 Levels higher than this will, for cycling, be treated as text, not a headline.
1011 When `org-odd-levels-only' is set, a value of N in this variable actually
1012 means 2N-1 stars as the limiting headline.
1013 When nil, cycle all levels.
1014 Note that the limiting level of cycling is also influenced by
1015 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1016 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1017 than its value."
1018 :group 'org-cycle
1019 :type '(choice
1020 (const :tag "No limit" nil)
1021 (integer :tag "Maximum level")))
1023 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1024 "Names of drawers. Drawers are not opened by cycling on the headline above.
1025 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1026 this:
1027 :DRAWERNAME:
1028 .....
1029 :END:
1030 The drawer \"PROPERTIES\" is special for capturing properties through
1031 the property API.
1033 Drawers can be defined on the per-file basis with a line like:
1035 #+DRAWERS: HIDDEN STATE PROPERTIES"
1036 :group 'org-structure
1037 :group 'org-cycle
1038 :type '(repeat (string :tag "Drawer Name")))
1040 (defcustom org-hide-block-startup nil
1041 "Non-nil means entering Org-mode will fold all blocks.
1042 This can also be set in on a per-file basis with
1044 #+STARTUP: hideblocks
1045 #+STARTUP: showblocks"
1046 :group 'org-startup
1047 :group 'org-cycle
1048 :type 'boolean)
1050 (defcustom org-cycle-global-at-bob nil
1051 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1052 This makes it possible to do global cycling without having to use S-TAB or
1053 \\[universal-argument] TAB. For this special case to work, the first line
1054 of the buffer must not be a headline -- it may be empty or some other text.
1055 When used in this way, `org-cycle-hook' is disabled temporarily to make
1056 sure the cursor stays at the beginning of the buffer. When this option is
1057 nil, don't do anything special at the beginning of the buffer."
1058 :group 'org-cycle
1059 :type 'boolean)
1061 (defcustom org-cycle-level-after-item/entry-creation t
1062 "Non-nil means cycle entry level or item indentation in new empty entries.
1064 When the cursor is at the end of an empty headline, i.e., with only stars
1065 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1066 and then all possible ancestor states, before returning to the original state.
1067 This makes data entry extremely fast: M-RET to create a new headline,
1068 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1070 When the cursor is at the end of an empty plain list item, one TAB will
1071 make it a subitem, two or more tabs will back up to make this an item
1072 higher up in the item hierarchy."
1073 :group 'org-cycle
1074 :type 'boolean)
1076 (defcustom org-cycle-emulate-tab t
1077 "Where should `org-cycle' emulate TAB.
1078 nil Never
1079 white Only in completely white lines
1080 whitestart Only at the beginning of lines, before the first non-white char
1081 t Everywhere except in headlines
1082 exc-hl-bol Everywhere except at the start of a headline
1083 If TAB is used in a place where it does not emulate TAB, the current subtree
1084 visibility is cycled."
1085 :group 'org-cycle
1086 :type '(choice (const :tag "Never" nil)
1087 (const :tag "Only in completely white lines" white)
1088 (const :tag "Before first char in a line" whitestart)
1089 (const :tag "Everywhere except in headlines" t)
1090 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
1093 (defcustom org-cycle-separator-lines 2
1094 "Number of empty lines needed to keep an empty line between collapsed trees.
1095 If you leave an empty line between the end of a subtree and the following
1096 headline, this empty line is hidden when the subtree is folded.
1097 Org-mode will leave (exactly) one empty line visible if the number of
1098 empty lines is equal or larger to the number given in this variable.
1099 So the default 2 means at least 2 empty lines after the end of a subtree
1100 are needed to produce free space between a collapsed subtree and the
1101 following headline.
1103 If the number is negative, and the number of empty lines is at least -N,
1104 all empty lines are shown.
1106 Special case: when 0, never leave empty lines in collapsed view."
1107 :group 'org-cycle
1108 :type 'integer)
1109 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1111 (defcustom org-pre-cycle-hook nil
1112 "Hook that is run before visibility cycling is happening.
1113 The function(s) in this hook must accept a single argument which indicates
1114 the new state that will be set right after running this hook. The
1115 argument is a symbol. Before a global state change, it can have the values
1116 `overview', `content', or `all'. Before a local state change, it can have
1117 the values `folded', `children', or `subtree'."
1118 :group 'org-cycle
1119 :type 'hook)
1121 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1122 org-cycle-hide-drawers
1123 org-cycle-hide-inline-tasks
1124 org-cycle-show-empty-lines
1125 org-optimize-window-after-visibility-change)
1126 "Hook that is run after `org-cycle' has changed the buffer visibility.
1127 The function(s) in this hook must accept a single argument which indicates
1128 the new state that was set by the most recent `org-cycle' command. The
1129 argument is a symbol. After a global state change, it can have the values
1130 `overview', `contents', or `all'. After a local state change, it can have
1131 the values `folded', `children', or `subtree'."
1132 :group 'org-cycle
1133 :type 'hook)
1135 (defgroup org-edit-structure nil
1136 "Options concerning structure editing in Org-mode."
1137 :tag "Org Edit Structure"
1138 :group 'org-structure)
1140 (defcustom org-odd-levels-only nil
1141 "Non-nil means skip even levels and only use odd levels for the outline.
1142 This has the effect that two stars are being added/taken away in
1143 promotion/demotion commands. It also influences how levels are
1144 handled by the exporters.
1145 Changing it requires restart of `font-lock-mode' to become effective
1146 for fontification also in regions already fontified.
1147 You may also set this on a per-file basis by adding one of the following
1148 lines to the buffer:
1150 #+STARTUP: odd
1151 #+STARTUP: oddeven"
1152 :group 'org-edit-structure
1153 :group 'org-appearance
1154 :type 'boolean)
1156 (defcustom org-adapt-indentation t
1157 "Non-nil means adapt indentation to outline node level.
1159 When this variable is set, Org assumes that you write outlines by
1160 indenting text in each node to align with the headline (after the stars).
1161 The following issues are influenced by this variable:
1163 - When this is set and the *entire* text in an entry is indented, the
1164 indentation is increased by one space in a demotion command, and
1165 decreased by one in a promotion command. If any line in the entry
1166 body starts with text at column 0, indentation is not changed at all.
1168 - Property drawers and planning information is inserted indented when
1169 this variable s set. When nil, they will not be indented.
1171 - TAB indents a line relative to context. The lines below a headline
1172 will be indented when this variable is set.
1174 Note that this is all about true indentation, by adding and removing
1175 space characters. See also `org-indent.el' which does level-dependent
1176 indentation in a virtual way, i.e. at display time in Emacs."
1177 :group 'org-edit-structure
1178 :type 'boolean)
1180 (defcustom org-special-ctrl-a/e nil
1181 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1183 When t, `C-a' will bring back the cursor to the beginning of the
1184 headline text, i.e. after the stars and after a possible TODO
1185 keyword. In an item, this will be the position after bullet and
1186 check-box, if any. When the cursor is already at that position,
1187 another `C-a' will bring it to the beginning of the line.
1189 `C-e' will jump to the end of the headline, ignoring the presence
1190 of tags in the headline. A second `C-e' will then jump to the
1191 true end of the line, after any tags. This also means that, when
1192 this variable is non-nil, `C-e' also will never jump beyond the
1193 end of the heading of a folded section, i.e. not after the
1194 ellipses.
1196 When set to the symbol `reversed', the first `C-a' or `C-e' works
1197 normally, going to the true line boundary first. Only a directly
1198 following, identical keypress will bring the cursor to the
1199 special positions.
1201 This may also be a cons cell where the behavior for `C-a' and
1202 `C-e' is set separately."
1203 :group 'org-edit-structure
1204 :type '(choice
1205 (const :tag "off" nil)
1206 (const :tag "on: after stars/bullet and before tags first" t)
1207 (const :tag "reversed: true line boundary first" reversed)
1208 (cons :tag "Set C-a and C-e separately"
1209 (choice :tag "Special C-a"
1210 (const :tag "off" nil)
1211 (const :tag "on: after stars/bullet first" t)
1212 (const :tag "reversed: before stars/bullet first" reversed))
1213 (choice :tag "Special C-e"
1214 (const :tag "off" nil)
1215 (const :tag "on: before tags first" t)
1216 (const :tag "reversed: after tags first" reversed)))))
1217 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1219 (defcustom org-special-ctrl-k nil
1220 "Non-nil means `C-k' will behave specially in headlines.
1221 When nil, `C-k' will call the default `kill-line' command.
1222 When t, the following will happen while the cursor is in the headline:
1224 - When the cursor is at the beginning of a headline, kill the entire
1225 line and possible the folded subtree below the line.
1226 - When in the middle of the headline text, kill the headline up to the tags.
1227 - When after the headline text, kill the tags."
1228 :group 'org-edit-structure
1229 :type 'boolean)
1231 (defcustom org-ctrl-k-protect-subtree nil
1232 "Non-nil means, do not delete a hidden subtree with C-k.
1233 When set to the symbol `error', simply throw an error when C-k is
1234 used to kill (part-of) a headline that has hidden text behind it.
1235 Any other non-nil value will result in a query to the user, if it is
1236 OK to kill that hidden subtree. When nil, kill without remorse."
1237 :group 'org-edit-structure
1238 :version "24.1"
1239 :type '(choice
1240 (const :tag "Do not protect hidden subtrees" nil)
1241 (const :tag "Protect hidden subtrees with a security query" t)
1242 (const :tag "Never kill a hidden subtree with C-k" error)))
1244 (defcustom org-catch-invisible-edits nil
1245 "Check if in invisible region before inserting or deleting a character.
1246 Valid values are:
1248 nil Do not check, so just do invisible edits.
1249 error Throw an error and do nothing.
1250 show Make point visible, and do the requested edit.
1251 show-and-error Make point visible, then throw an error and abort the edit.
1252 smart Make point visible, and do insertion/deletion if it is
1253 adjacent to visible text and the change feels predictable.
1254 Never delete a previously invisible character or add in the
1255 middle or right after an invisible region. Basically, this
1256 allows insertion and backward-delete right before ellipses.
1257 FIXME: maybe in this case we should not even show?"
1258 :group 'org-edit-structure
1259 :version "24.1"
1260 :type '(choice
1261 (const :tag "Do not check" nil)
1262 (const :tag "Throw error when trying to edit" error)
1263 (const :tag "Unhide, but do not do the edit" show-and-error)
1264 (const :tag "Show invisible part and do the edit" show)
1265 (const :tag "Be smart and do the right thing" smart)))
1267 (defcustom org-yank-folded-subtrees t
1268 "Non-nil means when yanking subtrees, fold them.
1269 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1270 it starts with a heading and all other headings in it are either children
1271 or siblings, then fold all the subtrees. However, do this only if no
1272 text after the yank would be swallowed into a folded tree by this action."
1273 :group 'org-edit-structure
1274 :type 'boolean)
1276 (defcustom org-yank-adjusted-subtrees nil
1277 "Non-nil means when yanking subtrees, adjust the level.
1278 With this setting, `org-paste-subtree' is used to insert the subtree, see
1279 this function for details."
1280 :group 'org-edit-structure
1281 :type 'boolean)
1283 (defcustom org-M-RET-may-split-line '((default . t))
1284 "Non-nil means M-RET will split the line at the cursor position.
1285 When nil, it will go to the end of the line before making a
1286 new line.
1287 You may also set this option in a different way for different
1288 contexts. Valid contexts are:
1290 headline when creating a new headline
1291 item when creating a new item
1292 table in a table field
1293 default the value to be used for all contexts not explicitly
1294 customized"
1295 :group 'org-structure
1296 :group 'org-table
1297 :type '(choice
1298 (const :tag "Always" t)
1299 (const :tag "Never" nil)
1300 (repeat :greedy t :tag "Individual contexts"
1301 (cons
1302 (choice :tag "Context"
1303 (const headline)
1304 (const item)
1305 (const table)
1306 (const default))
1307 (boolean)))))
1310 (defcustom org-insert-heading-respect-content nil
1311 "Non-nil means insert new headings after the current subtree.
1312 When nil, the new heading is created directly after the current line.
1313 The commands \\[org-insert-heading-respect-content] and
1314 \\[org-insert-todo-heading-respect-content] turn this variable on
1315 for the duration of the command."
1316 :group 'org-structure
1317 :type 'boolean)
1319 (defcustom org-blank-before-new-entry '((heading . auto)
1320 (plain-list-item . auto))
1321 "Should `org-insert-heading' leave a blank line before new heading/item?
1322 The value is an alist, with `heading' and `plain-list-item' as CAR,
1323 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1324 which case Org will look at the surrounding headings/items and try to
1325 make an intelligent decision whether to insert a blank line or not.
1327 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1328 set, the setting here is ignored and no empty line is inserted, to avoid
1329 breaking the list structure."
1330 :group 'org-edit-structure
1331 :type '(list
1332 (cons (const heading)
1333 (choice (const :tag "Never" nil)
1334 (const :tag "Always" t)
1335 (const :tag "Auto" auto)))
1336 (cons (const plain-list-item)
1337 (choice (const :tag "Never" nil)
1338 (const :tag "Always" t)
1339 (const :tag "Auto" auto)))))
1341 (defcustom org-insert-heading-hook nil
1342 "Hook being run after inserting a new heading."
1343 :group 'org-edit-structure
1344 :type 'hook)
1346 (defcustom org-enable-fixed-width-editor t
1347 "Non-nil means lines starting with \":\" are treated as fixed-width.
1348 This currently only means they are never auto-wrapped.
1349 When nil, such lines will be treated like ordinary lines.
1350 See also the QUOTE keyword."
1351 :group 'org-edit-structure
1352 :type 'boolean)
1354 (defcustom org-goto-auto-isearch t
1355 "Non-nil means typing characters in `org-goto' starts incremental search.
1356 When nil, you can use these keybindings to navigate the buffer:
1358 q Quit the org-goto interface
1359 n Go to the next visible heading
1360 p Go to the previous visible heading
1361 f Go one heading forward on same level
1362 b Go one heading backward on same level
1363 u Go one heading up"
1364 :group 'org-edit-structure
1365 :type 'boolean)
1367 (defgroup org-sparse-trees nil
1368 "Options concerning sparse trees in Org-mode."
1369 :tag "Org Sparse Trees"
1370 :group 'org-structure)
1372 (defcustom org-highlight-sparse-tree-matches t
1373 "Non-nil means highlight all matches that define a sparse tree.
1374 The highlights will automatically disappear the next time the buffer is
1375 changed by an edit command."
1376 :group 'org-sparse-trees
1377 :type 'boolean)
1379 (defcustom org-remove-highlights-with-change t
1380 "Non-nil means any change to the buffer will remove temporary highlights.
1381 Such highlights are created by `org-occur' and `org-clock-display'.
1382 When nil, `C-c C-c needs to be used to get rid of the highlights.
1383 The highlights created by `org-preview-latex-fragment' always need
1384 `C-c C-c' to be removed."
1385 :group 'org-sparse-trees
1386 :group 'org-time
1387 :type 'boolean)
1390 (defcustom org-occur-hook '(org-first-headline-recenter)
1391 "Hook that is run after `org-occur' has constructed a sparse tree.
1392 This can be used to recenter the window to show as much of the structure
1393 as possible."
1394 :group 'org-sparse-trees
1395 :type 'hook)
1397 (defgroup org-imenu-and-speedbar nil
1398 "Options concerning imenu and speedbar in Org-mode."
1399 :tag "Org Imenu and Speedbar"
1400 :group 'org-structure)
1402 (defcustom org-imenu-depth 2
1403 "The maximum level for Imenu access to Org-mode headlines.
1404 This also applied for speedbar access."
1405 :group 'org-imenu-and-speedbar
1406 :type 'integer)
1408 (defgroup org-table nil
1409 "Options concerning tables in Org-mode."
1410 :tag "Org Table"
1411 :group 'org)
1413 (defcustom org-enable-table-editor 'optimized
1414 "Non-nil means lines starting with \"|\" are handled by the table editor.
1415 When nil, such lines will be treated like ordinary lines.
1417 When equal to the symbol `optimized', the table editor will be optimized to
1418 do the following:
1419 - Automatic overwrite mode in front of whitespace in table fields.
1420 This makes the structure of the table stay in tact as long as the edited
1421 field does not exceed the column width.
1422 - Minimize the number of realigns. Normally, the table is aligned each time
1423 TAB or RET are pressed to move to another field. With optimization this
1424 happens only if changes to a field might have changed the column width.
1425 Optimization requires replacing the functions `self-insert-command',
1426 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1427 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1428 very good at guessing when a re-align will be necessary, but you can always
1429 force one with \\[org-ctrl-c-ctrl-c].
1431 If you would like to use the optimized version in Org-mode, but the
1432 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1434 This variable can be used to turn on and off the table editor during a session,
1435 but in order to toggle optimization, a restart is required.
1437 See also the variable `org-table-auto-blank-field'."
1438 :group 'org-table
1439 :type '(choice
1440 (const :tag "off" nil)
1441 (const :tag "on" t)
1442 (const :tag "on, optimized" optimized)))
1444 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1445 (version<= emacs-version "24.1"))
1446 "Non-nil means cluster self-insert commands for undo when possible.
1447 If this is set, then, like in the Emacs command loop, 20 consecutive
1448 characters will be undone together.
1449 This is configurable, because there is some impact on typing performance."
1450 :group 'org-table
1451 :type 'boolean)
1453 (defcustom org-table-tab-recognizes-table.el t
1454 "Non-nil means TAB will automatically notice a table.el table.
1455 When it sees such a table, it moves point into it and - if necessary -
1456 calls `table-recognize-table'."
1457 :group 'org-table-editing
1458 :type 'boolean)
1460 (defgroup org-link nil
1461 "Options concerning links in Org-mode."
1462 :tag "Org Link"
1463 :group 'org)
1465 (defvar org-link-abbrev-alist-local nil
1466 "Buffer-local version of `org-link-abbrev-alist', which see.
1467 The value of this is taken from the #+LINK lines.")
1468 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1470 (defcustom org-link-abbrev-alist nil
1471 "Alist of link abbreviations.
1472 The car of each element is a string, to be replaced at the start of a link.
1473 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1474 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1476 [[linkkey:tag][description]]
1478 The 'linkkey' must be a word word, starting with a letter, followed
1479 by letters, numbers, '-' or '_'.
1481 If REPLACE is a string, the tag will simply be appended to create the link.
1482 If the string contains \"%s\", the tag will be inserted there. If the string
1483 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1484 at that point (see the function `url-hexify-string'). If the string contains
1485 the specifier \"%(my-function)\", then the custom function `my-function' will
1486 be invoked: this function takes the tag as its only argument and must return
1487 a string.
1489 REPLACE may also be a function that will be called with the tag as the
1490 only argument to create the link, which should be returned as a string.
1492 See the manual for examples."
1493 :group 'org-link
1494 :type '(repeat
1495 (cons
1496 (string :tag "Protocol")
1497 (choice
1498 (string :tag "Format")
1499 (function)))))
1501 (defcustom org-descriptive-links t
1502 "Non-nil means Org will display descriptive links.
1503 E.g. [[http://orgmode.org][Org website]] will be displayed as
1504 \"Org Website\", hiding the link itself and just displaying its
1505 description. When set to `nil', Org will display the full links
1506 literally.
1508 You can interactively set the value of this variable by calling
1509 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1510 :group 'org-link
1511 :type 'boolean)
1513 (defcustom org-link-file-path-type 'adaptive
1514 "How the path name in file links should be stored.
1515 Valid values are:
1517 relative Relative to the current directory, i.e. the directory of the file
1518 into which the link is being inserted.
1519 absolute Absolute path, if possible with ~ for home directory.
1520 noabbrev Absolute path, no abbreviation of home directory.
1521 adaptive Use relative path for files in the current directory and sub-
1522 directories of it. For other files, use an absolute path."
1523 :group 'org-link
1524 :type '(choice
1525 (const relative)
1526 (const absolute)
1527 (const noabbrev)
1528 (const adaptive)))
1530 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1531 "Types of links that should be activated in Org-mode files.
1532 This is a list of symbols, each leading to the activation of a certain link
1533 type. In principle, it does not hurt to turn on most link types - there may
1534 be a small gain when turning off unused link types. The types are:
1536 bracket The recommended [[link][description]] or [[link]] links with hiding.
1537 angle Links in angular brackets that may contain whitespace like
1538 <bbdb:Carsten Dominik>.
1539 plain Plain links in normal text, no whitespace, like http://google.com.
1540 radio Text that is matched by a radio target, see manual for details.
1541 tag Tag settings in a headline (link to tag search).
1542 date Time stamps (link to calendar).
1543 footnote Footnote labels.
1545 Changing this variable requires a restart of Emacs to become effective."
1546 :group 'org-link
1547 :type '(set :greedy t
1548 (const :tag "Double bracket links" bracket)
1549 (const :tag "Angular bracket links" angle)
1550 (const :tag "Plain text links" plain)
1551 (const :tag "Radio target matches" radio)
1552 (const :tag "Tags" tag)
1553 (const :tag "Timestamps" date)
1554 (const :tag "Footnotes" footnote)))
1556 (defcustom org-make-link-description-function nil
1557 "Function to use for generating link descriptions from links.
1558 When nil, the link location will be used. This function must take
1559 two parameters: the first one is the link, the second one is the
1560 description generated by `org-insert-link'. The function should
1561 return the description to use."
1562 :group 'org-link
1563 :type 'function)
1565 (defgroup org-link-store nil
1566 "Options concerning storing links in Org-mode."
1567 :tag "Org Store Link"
1568 :group 'org-link)
1570 (defcustom org-url-hexify-p t
1571 "When non-nil, hexify URL when creating a link."
1572 :type 'boolean
1573 :version "24.3"
1574 :group 'org-link-store)
1576 (defcustom org-email-link-description-format "Email %c: %.30s"
1577 "Format of the description part of a link to an email or usenet message.
1578 The following %-escapes will be replaced by corresponding information:
1580 %F full \"From\" field
1581 %f name, taken from \"From\" field, address if no name
1582 %T full \"To\" field
1583 %t first name in \"To\" field, address if no name
1584 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1585 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1586 %s subject
1587 %d date
1588 %m message-id.
1590 You may use normal field width specification between the % and the letter.
1591 This is for example useful to limit the length of the subject.
1593 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1594 :group 'org-link-store
1595 :type 'string)
1597 (defcustom org-from-is-user-regexp
1598 (let (r1 r2)
1599 (when (and user-mail-address (not (string= user-mail-address "")))
1600 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1601 (when (and user-full-name (not (string= user-full-name "")))
1602 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1603 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1604 "Regexp matched against the \"From:\" header of an email or usenet message.
1605 It should match if the message is from the user him/herself."
1606 :group 'org-link-store
1607 :type 'regexp)
1609 (defcustom org-context-in-file-links t
1610 "Non-nil means file links from `org-store-link' contain context.
1611 A search string will be added to the file name with :: as separator and
1612 used to find the context when the link is activated by the command
1613 `org-open-at-point'. When this option is t, the entire active region
1614 will be placed in the search string of the file link. If set to a
1615 positive integer, only the first n lines of context will be stored.
1617 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1618 negates this setting for the duration of the command."
1619 :group 'org-link-store
1620 :type '(choice boolean integer))
1622 (defcustom org-keep-stored-link-after-insertion nil
1623 "Non-nil means keep link in list for entire session.
1625 The command `org-store-link' adds a link pointing to the current
1626 location to an internal list. These links accumulate during a session.
1627 The command `org-insert-link' can be used to insert links into any
1628 Org-mode file (offering completion for all stored links). When this
1629 option is nil, every link which has been inserted once using \\[org-insert-link]
1630 will be removed from the list, to make completing the unused links
1631 more efficient."
1632 :group 'org-link-store
1633 :type 'boolean)
1635 (defgroup org-link-follow nil
1636 "Options concerning following links in Org-mode."
1637 :tag "Org Follow Link"
1638 :group 'org-link)
1640 (defcustom org-link-translation-function nil
1641 "Function to translate links with different syntax to Org syntax.
1642 This can be used to translate links created for example by the Planner
1643 or emacs-wiki packages to Org syntax.
1644 The function must accept two parameters, a TYPE containing the link
1645 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1646 which is everything after the link protocol. It should return a cons
1647 with possibly modified values of type and path.
1648 Org contains a function for this, so if you set this variable to
1649 `org-translate-link-from-planner', you should be able follow many
1650 links created by planner."
1651 :group 'org-link-follow
1652 :type 'function)
1654 (defcustom org-follow-link-hook nil
1655 "Hook that is run after a link has been followed."
1656 :group 'org-link-follow
1657 :type 'hook)
1659 (defcustom org-tab-follows-link nil
1660 "Non-nil means on links TAB will follow the link.
1661 Needs to be set before org.el is loaded.
1662 This really should not be used, it does not make sense, and the
1663 implementation is bad."
1664 :group 'org-link-follow
1665 :type 'boolean)
1667 (defcustom org-return-follows-link nil
1668 "Non-nil means on links RET will follow the link.
1669 In tables, the special behavior of RET has precedence."
1670 :group 'org-link-follow
1671 :type 'boolean)
1673 (defcustom org-mouse-1-follows-link
1674 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1675 "Non-nil means mouse-1 on a link will follow the link.
1676 A longer mouse click will still set point. Does not work on XEmacs.
1677 Needs to be set before org.el is loaded."
1678 :group 'org-link-follow
1679 :type 'boolean)
1681 (defcustom org-mark-ring-length 4
1682 "Number of different positions to be recorded in the ring.
1683 Changing this requires a restart of Emacs to work correctly."
1684 :group 'org-link-follow
1685 :type 'integer)
1687 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1688 "Non-nil means internal links in Org files must exactly match a headline.
1689 When nil, the link search tries to match a phrase with all words
1690 in the search text."
1691 :group 'org-link-follow
1692 :version "24.1"
1693 :type '(choice
1694 (const :tag "Use fuzzy text search" nil)
1695 (const :tag "Match only exact headline" t)
1696 (const :tag "Match exact headline or query to create it"
1697 query-to-create)))
1699 (defcustom org-link-frame-setup
1700 '((vm . vm-visit-folder-other-frame)
1701 (vm-imap . vm-visit-imap-folder-other-frame)
1702 (gnus . org-gnus-no-new-news)
1703 (file . find-file-other-window)
1704 (wl . wl-other-frame))
1705 "Setup the frame configuration for following links.
1706 When following a link with Emacs, it may often be useful to display
1707 this link in another window or frame. This variable can be used to
1708 set this up for the different types of links.
1709 For VM, use any of
1710 `vm-visit-folder'
1711 `vm-visit-folder-other-window'
1712 `vm-visit-folder-other-frame'
1713 For Gnus, use any of
1714 `gnus'
1715 `gnus-other-frame'
1716 `org-gnus-no-new-news'
1717 For FILE, use any of
1718 `find-file'
1719 `find-file-other-window'
1720 `find-file-other-frame'
1721 For Wanderlust use any of
1722 `wl'
1723 `wl-other-frame'
1724 For the calendar, use the variable `calendar-setup'.
1725 For BBDB, it is currently only possible to display the matches in
1726 another window."
1727 :group 'org-link-follow
1728 :type '(list
1729 (cons (const vm)
1730 (choice
1731 (const vm-visit-folder)
1732 (const vm-visit-folder-other-window)
1733 (const vm-visit-folder-other-frame)))
1734 (cons (const gnus)
1735 (choice
1736 (const gnus)
1737 (const gnus-other-frame)
1738 (const org-gnus-no-new-news)))
1739 (cons (const file)
1740 (choice
1741 (const find-file)
1742 (const find-file-other-window)
1743 (const find-file-other-frame)))
1744 (cons (const wl)
1745 (choice
1746 (const wl)
1747 (const wl-other-frame)))))
1749 (defcustom org-display-internal-link-with-indirect-buffer nil
1750 "Non-nil means use indirect buffer to display infile links.
1751 Activating internal links (from one location in a file to another location
1752 in the same file) normally just jumps to the location. When the link is
1753 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1754 is displayed in
1755 another window. When this option is set, the other window actually displays
1756 an indirect buffer clone of the current buffer, to avoid any visibility
1757 changes to the current buffer."
1758 :group 'org-link-follow
1759 :type 'boolean)
1761 (defcustom org-open-non-existing-files nil
1762 "Non-nil means `org-open-file' will open non-existing files.
1763 When nil, an error will be generated.
1764 This variable applies only to external applications because they
1765 might choke on non-existing files. If the link is to a file that
1766 will be opened in Emacs, the variable is ignored."
1767 :group 'org-link-follow
1768 :type 'boolean)
1770 (defcustom org-open-directory-means-index-dot-org nil
1771 "Non-nil means a link to a directory really means to index.org.
1772 When nil, following a directory link will run dired or open a finder/explorer
1773 window on that directory."
1774 :group 'org-link-follow
1775 :type 'boolean)
1777 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1778 "Function and arguments to call for following mailto links.
1779 This is a list with the first element being a Lisp function, and the
1780 remaining elements being arguments to the function. In string arguments,
1781 %a will be replaced by the address, and %s will be replaced by the subject
1782 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1783 :group 'org-link-follow
1784 :type '(choice
1785 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1786 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1787 (const :tag "message-mail" (message-mail "%a" "%s"))
1788 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1790 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1791 "Non-nil means ask for confirmation before executing shell links.
1792 Shell links can be dangerous: just think about a link
1794 [[shell:rm -rf ~/*][Google Search]]
1796 This link would show up in your Org-mode document as \"Google Search\",
1797 but really it would remove your entire home directory.
1798 Therefore we advise against setting this variable to nil.
1799 Just change it to `y-or-n-p' if you want to confirm with a
1800 single keystroke rather than having to type \"yes\"."
1801 :group 'org-link-follow
1802 :type '(choice
1803 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1804 (const :tag "with y-or-n (faster)" y-or-n-p)
1805 (const :tag "no confirmation (dangerous)" nil)))
1806 (put 'org-confirm-shell-link-function
1807 'safe-local-variable
1808 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1810 (defcustom org-confirm-shell-link-not-regexp ""
1811 "A regexp to skip confirmation for shell links."
1812 :group 'org-link-follow
1813 :version "24.1"
1814 :type 'regexp)
1816 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1817 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1818 Elisp links can be dangerous: just think about a link
1820 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1822 This link would show up in your Org-mode document as \"Google Search\",
1823 but really it would remove your entire home directory.
1824 Therefore we advise against setting this variable to nil.
1825 Just change it to `y-or-n-p' if you want to confirm with a
1826 single keystroke rather than having to type \"yes\"."
1827 :group 'org-link-follow
1828 :type '(choice
1829 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1830 (const :tag "with y-or-n (faster)" y-or-n-p)
1831 (const :tag "no confirmation (dangerous)" nil)))
1832 (put 'org-confirm-shell-link-function
1833 'safe-local-variable
1834 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1836 (defcustom org-confirm-elisp-link-not-regexp ""
1837 "A regexp to skip confirmation for Elisp links."
1838 :group 'org-link-follow
1839 :version "24.1"
1840 :type 'regexp)
1842 (defconst org-file-apps-defaults-gnu
1843 '((remote . emacs)
1844 (system . mailcap)
1845 (t . mailcap))
1846 "Default file applications on a UNIX or GNU/Linux system.
1847 See `org-file-apps'.")
1849 (defconst org-file-apps-defaults-macosx
1850 '((remote . emacs)
1851 (t . "open %s")
1852 (system . "open %s")
1853 ("ps.gz" . "gv %s")
1854 ("eps.gz" . "gv %s")
1855 ("dvi" . "xdvi %s")
1856 ("fig" . "xfig %s"))
1857 "Default file applications on a MacOS X system.
1858 The system \"open\" is known as a default, but we use X11 applications
1859 for some files for which the OS does not have a good default.
1860 See `org-file-apps'.")
1862 (defconst org-file-apps-defaults-windowsnt
1863 (list
1864 '(remote . emacs)
1865 (cons t
1866 (list (if (featurep 'xemacs)
1867 'mswindows-shell-execute
1868 'w32-shell-execute)
1869 "open" 'file))
1870 (cons 'system
1871 (list (if (featurep 'xemacs)
1872 'mswindows-shell-execute
1873 'w32-shell-execute)
1874 "open" 'file)))
1875 "Default file applications on a Windows NT system.
1876 The system \"open\" is used for most files.
1877 See `org-file-apps'.")
1879 (defcustom org-file-apps
1881 (auto-mode . emacs)
1882 ("\\.mm\\'" . default)
1883 ("\\.x?html?\\'" . default)
1884 ("\\.pdf\\'" . default)
1886 "External applications for opening `file:path' items in a document.
1887 Org-mode uses system defaults for different file types, but
1888 you can use this variable to set the application for a given file
1889 extension. The entries in this list are cons cells where the car identifies
1890 files and the cdr the corresponding command. Possible values for the
1891 file identifier are
1892 \"string\" A string as a file identifier can be interpreted in different
1893 ways, depending on its contents:
1895 - Alphanumeric characters only:
1896 Match links with this file extension.
1897 Example: (\"pdf\" . \"evince %s\")
1898 to open PDFs with evince.
1900 - Regular expression: Match links where the
1901 filename matches the regexp. If you want to
1902 use groups here, use shy groups.
1904 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1905 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1906 to open *.html and *.xhtml with firefox.
1908 - Regular expression which contains (non-shy) groups:
1909 Match links where the whole link, including \"::\", and
1910 anything after that, matches the regexp.
1911 In a custom command string, %1, %2, etc. are replaced with
1912 the parts of the link that were matched by the groups.
1913 For backwards compatibility, if a command string is given
1914 that does not use any of the group matches, this case is
1915 handled identically to the second one (i.e. match against
1916 file name only).
1917 In a custom lisp form, you can access the group matches with
1918 (match-string n link).
1920 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1921 to open [[file:document.pdf::5]] with evince at page 5.
1923 `directory' Matches a directory
1924 `remote' Matches a remote file, accessible through tramp or efs.
1925 Remote files most likely should be visited through Emacs
1926 because external applications cannot handle such paths.
1927 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1928 so all files Emacs knows how to handle. Using this with
1929 command `emacs' will open most files in Emacs. Beware that this
1930 will also open html files inside Emacs, unless you add
1931 (\"html\" . default) to the list as well.
1932 t Default for files not matched by any of the other options.
1933 `system' The system command to open files, like `open' on Windows
1934 and Mac OS X, and mailcap under GNU/Linux. This is the command
1935 that will be selected if you call `C-c C-o' with a double
1936 \\[universal-argument] \\[universal-argument] prefix.
1938 Possible values for the command are:
1939 `emacs' The file will be visited by the current Emacs process.
1940 `default' Use the default application for this file type, which is the
1941 association for t in the list, most likely in the system-specific
1942 part.
1943 This can be used to overrule an unwanted setting in the
1944 system-specific variable.
1945 `system' Use the system command for opening files, like \"open\".
1946 This command is specified by the entry whose car is `system'.
1947 Most likely, the system-specific version of this variable
1948 does define this command, but you can overrule/replace it
1949 here.
1950 string A command to be executed by a shell; %s will be replaced
1951 by the path to the file.
1952 sexp A Lisp form which will be evaluated. The file path will
1953 be available in the Lisp variable `file'.
1954 For more examples, see the system specific constants
1955 `org-file-apps-defaults-macosx'
1956 `org-file-apps-defaults-windowsnt'
1957 `org-file-apps-defaults-gnu'."
1958 :group 'org-link-follow
1959 :type '(repeat
1960 (cons (choice :value ""
1961 (string :tag "Extension")
1962 (const :tag "System command to open files" system)
1963 (const :tag "Default for unrecognized files" t)
1964 (const :tag "Remote file" remote)
1965 (const :tag "Links to a directory" directory)
1966 (const :tag "Any files that have Emacs modes"
1967 auto-mode))
1968 (choice :value ""
1969 (const :tag "Visit with Emacs" emacs)
1970 (const :tag "Use default" default)
1971 (const :tag "Use the system command" system)
1972 (string :tag "Command")
1973 (sexp :tag "Lisp form")))))
1975 (defcustom org-doi-server-url "http://dx.doi.org/"
1976 "The URL of the DOI server."
1977 :type 'string
1978 :version "24.3"
1979 :group 'org-link-follow)
1981 (defgroup org-refile nil
1982 "Options concerning refiling entries in Org-mode."
1983 :tag "Org Refile"
1984 :group 'org)
1986 (defcustom org-directory "~/org"
1987 "Directory with org files.
1988 This is just a default location to look for Org files. There is no need
1989 at all to put your files into this directory. It is only used in the
1990 following situations:
1992 1. When a capture template specifies a target file that is not an
1993 absolute path. The path will then be interpreted relative to
1994 `org-directory'
1995 2. When a capture note is filed away in an interactive way (when exiting the
1996 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1997 with `org-directory' as the default path."
1998 :group 'org-refile
1999 :group 'org-remember
2000 :group 'org-capture
2001 :type 'directory)
2003 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2004 "Default target for storing notes.
2005 Used as a fall back file for org-remember.el and org-capture.el, for
2006 templates that do not specify a target file."
2007 :group 'org-refile
2008 :group 'org-remember
2009 :group 'org-capture
2010 :type '(choice
2011 (const :tag "Default from remember-data-file" nil)
2012 file))
2014 (defcustom org-goto-interface 'outline
2015 "The default interface to be used for `org-goto'.
2016 Allowed values are:
2017 outline The interface shows an outline of the relevant file
2018 and the correct heading is found by moving through
2019 the outline or by searching with incremental search.
2020 outline-path-completion Headlines in the current buffer are offered via
2021 completion. This is the interface also used by
2022 the refile command."
2023 :group 'org-refile
2024 :type '(choice
2025 (const :tag "Outline" outline)
2026 (const :tag "Outline-path-completion" outline-path-completion)))
2028 (defcustom org-goto-max-level 5
2029 "Maximum target level when running `org-goto' with refile interface."
2030 :group 'org-refile
2031 :type 'integer)
2033 (defcustom org-reverse-note-order nil
2034 "Non-nil means store new notes at the beginning of a file or entry.
2035 When nil, new notes will be filed to the end of a file or entry.
2036 This can also be a list with cons cells of regular expressions that
2037 are matched against file names, and values."
2038 :group 'org-remember
2039 :group 'org-capture
2040 :group 'org-refile
2041 :type '(choice
2042 (const :tag "Reverse always" t)
2043 (const :tag "Reverse never" nil)
2044 (repeat :tag "By file name regexp"
2045 (cons regexp boolean))))
2047 (defcustom org-log-refile nil
2048 "Information to record when a task is refiled.
2050 Possible values are:
2052 nil Don't add anything
2053 time Add a time stamp to the task
2054 note Prompt for a note and add it with template `org-log-note-headings'
2056 This option can also be set with on a per-file-basis with
2058 #+STARTUP: nologrefile
2059 #+STARTUP: logrefile
2060 #+STARTUP: lognoterefile
2062 You can have local logging settings for a subtree by setting the LOGGING
2063 property to one or more of these keywords.
2065 When bulk-refiling from the agenda, the value `note' is forbidden and
2066 will temporarily be changed to `time'."
2067 :group 'org-refile
2068 :group 'org-progress
2069 :version "24.1"
2070 :type '(choice
2071 (const :tag "No logging" nil)
2072 (const :tag "Record timestamp" time)
2073 (const :tag "Record timestamp with note." note)))
2075 (defcustom org-refile-targets nil
2076 "Targets for refiling entries with \\[org-refile].
2077 This is a list of cons cells. Each cell contains:
2078 - a specification of the files to be considered, either a list of files,
2079 or a symbol whose function or variable value will be used to retrieve
2080 a file name or a list of file names. If you use `org-agenda-files' for
2081 that, all agenda files will be scanned for targets. Nil means consider
2082 headings in the current buffer.
2083 - A specification of how to find candidate refile targets. This may be
2084 any of:
2085 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2086 This tag has to be present in all target headlines, inheritance will
2087 not be considered.
2088 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2089 todo keyword.
2090 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2091 headlines that are refiling targets.
2092 - a cons cell (:level . N). Any headline of level N is considered a target.
2093 Note that, when `org-odd-levels-only' is set, level corresponds to
2094 order in hierarchy, not to the number of stars.
2095 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2096 Note that, when `org-odd-levels-only' is set, level corresponds to
2097 order in hierarchy, not to the number of stars.
2099 Each element of this list generates a set of possible targets.
2100 The union of these sets is presented (with completion) to
2101 the user by `org-refile'.
2103 You can set the variable `org-refile-target-verify-function' to a function
2104 to verify each headline found by the simple criteria above.
2106 When this variable is nil, all top-level headlines in the current buffer
2107 are used, equivalent to the value `((nil . (:level . 1))'."
2108 :group 'org-refile
2109 :type '(repeat
2110 (cons
2111 (choice :value org-agenda-files
2112 (const :tag "All agenda files" org-agenda-files)
2113 (const :tag "Current buffer" nil)
2114 (function) (variable) (file))
2115 (choice :tag "Identify target headline by"
2116 (cons :tag "Specific tag" (const :value :tag) (string))
2117 (cons :tag "TODO keyword" (const :value :todo) (string))
2118 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2119 (cons :tag "Level number" (const :value :level) (integer))
2120 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2122 (defcustom org-refile-target-verify-function nil
2123 "Function to verify if the headline at point should be a refile target.
2124 The function will be called without arguments, with point at the
2125 beginning of the headline. It should return t and leave point
2126 where it is if the headline is a valid target for refiling.
2128 If the target should not be selected, the function must return nil.
2129 In addition to this, it may move point to a place from where the search
2130 should be continued. For example, the function may decide that the entire
2131 subtree of the current entry should be excluded and move point to the end
2132 of the subtree."
2133 :group 'org-refile
2134 :type 'function)
2136 (defcustom org-refile-use-cache nil
2137 "Non-nil means cache refile targets to speed up the process.
2138 The cache for a particular file will be updated automatically when
2139 the buffer has been killed, or when any of the marker used for flagging
2140 refile targets no longer points at a live buffer.
2141 If you have added new entries to a buffer that might themselves be targets,
2142 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2143 find that easier, `C-u C-u C-u C-c C-w'."
2144 :group 'org-refile
2145 :version "24.1"
2146 :type 'boolean)
2148 (defcustom org-refile-use-outline-path nil
2149 "Non-nil means provide refile targets as paths.
2150 So a level 3 headline will be available as level1/level2/level3.
2152 When the value is `file', also include the file name (without directory)
2153 into the path. In this case, you can also stop the completion after
2154 the file name, to get entries inserted as top level in the file.
2156 When `full-file-path', include the full file path."
2157 :group 'org-refile
2158 :type '(choice
2159 (const :tag "Not" nil)
2160 (const :tag "Yes" t)
2161 (const :tag "Start with file name" file)
2162 (const :tag "Start with full file path" full-file-path)))
2164 (defcustom org-outline-path-complete-in-steps t
2165 "Non-nil means complete the outline path in hierarchical steps.
2166 When Org-mode uses the refile interface to select an outline path
2167 \(see variable `org-refile-use-outline-path'), the completion of
2168 the path can be done is a single go, or if can be done in steps down
2169 the headline hierarchy. Going in steps is probably the best if you
2170 do not use a special completion package like `ido' or `icicles'.
2171 However, when using these packages, going in one step can be very
2172 fast, while still showing the whole path to the entry."
2173 :group 'org-refile
2174 :type 'boolean)
2176 (defcustom org-refile-allow-creating-parent-nodes nil
2177 "Non-nil means allow to create new nodes as refile targets.
2178 New nodes are then created by adding \"/new node name\" to the completion
2179 of an existing node. When the value of this variable is `confirm',
2180 new node creation must be confirmed by the user (recommended)
2181 When nil, the completion must match an existing entry.
2183 Note that, if the new heading is not seen by the criteria
2184 listed in `org-refile-targets', multiple instances of the same
2185 heading would be created by trying again to file under the new
2186 heading."
2187 :group 'org-refile
2188 :type '(choice
2189 (const :tag "Never" nil)
2190 (const :tag "Always" t)
2191 (const :tag "Prompt for confirmation" confirm)))
2193 (defcustom org-refile-active-region-within-subtree nil
2194 "Non-nil means also refile active region within a subtree.
2196 By default `org-refile' doesn't allow refiling regions if they
2197 don't contain a set of subtrees, but it might be convenient to
2198 do so sometimes: in that case, the first line of the region is
2199 converted to a headline before refiling."
2200 :group 'org-refile
2201 :version "24.1"
2202 :type 'boolean)
2204 (defgroup org-todo nil
2205 "Options concerning TODO items in Org-mode."
2206 :tag "Org TODO"
2207 :group 'org)
2209 (defgroup org-progress nil
2210 "Options concerning Progress logging in Org-mode."
2211 :tag "Org Progress"
2212 :group 'org-time)
2214 (defvar org-todo-interpretation-widgets
2215 '((:tag "Sequence (cycling hits every state)" sequence)
2216 (:tag "Type (cycling directly to DONE)" type))
2217 "The available interpretation symbols for customizing `org-todo-keywords'.
2218 Interested libraries should add to this list.")
2220 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2221 "List of TODO entry keyword sequences and their interpretation.
2222 \\<org-mode-map>This is a list of sequences.
2224 Each sequence starts with a symbol, either `sequence' or `type',
2225 indicating if the keywords should be interpreted as a sequence of
2226 action steps, or as different types of TODO items. The first
2227 keywords are states requiring action - these states will select a headline
2228 for inclusion into the global TODO list Org-mode produces. If one of
2229 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2230 signify that no further action is necessary. If \"|\" is not found,
2231 the last keyword is treated as the only DONE state of the sequence.
2233 The command \\[org-todo] cycles an entry through these states, and one
2234 additional state where no keyword is present. For details about this
2235 cycling, see the manual.
2237 TODO keywords and interpretation can also be set on a per-file basis with
2238 the special #+SEQ_TODO and #+TYP_TODO lines.
2240 Each keyword can optionally specify a character for fast state selection
2241 \(in combination with the variable `org-use-fast-todo-selection')
2242 and specifiers for state change logging, using the same syntax that
2243 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2244 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2245 indicates to record a time stamp each time this state is selected.
2247 Each keyword may also specify if a timestamp or a note should be
2248 recorded when entering or leaving the state, by adding additional
2249 characters in the parenthesis after the keyword. This looks like this:
2250 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2251 record only the time of the state change. With X and Y being either
2252 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2253 Y when leaving the state if and only if the *target* state does not
2254 define X. You may omit any of the fast-selection key or X or /Y,
2255 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2257 For backward compatibility, this variable may also be just a list
2258 of keywords. In this case the interpretation (sequence or type) will be
2259 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2260 :group 'org-todo
2261 :group 'org-keywords
2262 :type '(choice
2263 (repeat :tag "Old syntax, just keywords"
2264 (string :tag "Keyword"))
2265 (repeat :tag "New syntax"
2266 (cons
2267 (choice
2268 :tag "Interpretation"
2269 ;;Quick and dirty way to see
2270 ;;`org-todo-interpretations'. This takes the
2271 ;;place of item arguments
2272 :convert-widget
2273 (lambda (widget)
2274 (widget-put widget
2275 :args (mapcar
2276 #'(lambda (x)
2277 (widget-convert
2278 (cons 'const x)))
2279 org-todo-interpretation-widgets))
2280 widget))
2281 (repeat
2282 (string :tag "Keyword"))))))
2284 (defvar org-todo-keywords-1 nil
2285 "All TODO and DONE keywords active in a buffer.")
2286 (make-variable-buffer-local 'org-todo-keywords-1)
2287 (defvar org-todo-keywords-for-agenda nil)
2288 (defvar org-done-keywords-for-agenda nil)
2289 (defvar org-drawers-for-agenda nil)
2290 (defvar org-todo-keyword-alist-for-agenda nil)
2291 (defvar org-tag-alist-for-agenda nil)
2292 (defvar org-agenda-contributing-files nil)
2293 (defvar org-not-done-keywords nil)
2294 (make-variable-buffer-local 'org-not-done-keywords)
2295 (defvar org-done-keywords nil)
2296 (make-variable-buffer-local 'org-done-keywords)
2297 (defvar org-todo-heads nil)
2298 (make-variable-buffer-local 'org-todo-heads)
2299 (defvar org-todo-sets nil)
2300 (make-variable-buffer-local 'org-todo-sets)
2301 (defvar org-todo-log-states nil)
2302 (make-variable-buffer-local 'org-todo-log-states)
2303 (defvar org-todo-kwd-alist nil)
2304 (make-variable-buffer-local 'org-todo-kwd-alist)
2305 (defvar org-todo-key-alist nil)
2306 (make-variable-buffer-local 'org-todo-key-alist)
2307 (defvar org-todo-key-trigger nil)
2308 (make-variable-buffer-local 'org-todo-key-trigger)
2310 (defcustom org-todo-interpretation 'sequence
2311 "Controls how TODO keywords are interpreted.
2312 This variable is in principle obsolete and is only used for
2313 backward compatibility, if the interpretation of todo keywords is
2314 not given already in `org-todo-keywords'. See that variable for
2315 more information."
2316 :group 'org-todo
2317 :group 'org-keywords
2318 :type '(choice (const sequence)
2319 (const type)))
2321 (defcustom org-use-fast-todo-selection t
2322 "Non-nil means use the fast todo selection scheme with C-c C-t.
2323 This variable describes if and under what circumstances the cycling
2324 mechanism for TODO keywords will be replaced by a single-key, direct
2325 selection scheme.
2327 When nil, fast selection is never used.
2329 When the symbol `prefix', it will be used when `org-todo' is called
2330 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2331 `C-u t' in an agenda buffer.
2333 When t, fast selection is used by default. In this case, the prefix
2334 argument forces cycling instead.
2336 In all cases, the special interface is only used if access keys have
2337 actually been assigned by the user, i.e. if keywords in the configuration
2338 are followed by a letter in parenthesis, like TODO(t)."
2339 :group 'org-todo
2340 :type '(choice
2341 (const :tag "Never" nil)
2342 (const :tag "By default" t)
2343 (const :tag "Only with C-u C-c C-t" prefix)))
2345 (defcustom org-provide-todo-statistics t
2346 "Non-nil means update todo statistics after insert and toggle.
2347 ALL-HEADLINES means update todo statistics by including headlines
2348 with no TODO keyword as well, counting them as not done.
2349 A list of TODO keywords means the same, but skip keywords that are
2350 not in this list.
2352 When this is set, todo statistics is updated in the parent of the
2353 current entry each time a todo state is changed."
2354 :group 'org-todo
2355 :type '(choice
2356 (const :tag "Yes, only for TODO entries" t)
2357 (const :tag "Yes, including all entries" 'all-headlines)
2358 (repeat :tag "Yes, for TODOs in this list"
2359 (string :tag "TODO keyword"))
2360 (other :tag "No TODO statistics" nil)))
2362 (defcustom org-hierarchical-todo-statistics t
2363 "Non-nil means TODO statistics covers just direct children.
2364 When nil, all entries in the subtree are considered.
2365 This has only an effect if `org-provide-todo-statistics' is set.
2366 To set this to nil for only a single subtree, use a COOKIE_DATA
2367 property and include the word \"recursive\" into the value."
2368 :group 'org-todo
2369 :type 'boolean)
2371 (defcustom org-after-todo-state-change-hook nil
2372 "Hook which is run after the state of a TODO item was changed.
2373 The new state (a string with a TODO keyword, or nil) is available in the
2374 Lisp variable `org-state'."
2375 :group 'org-todo
2376 :type 'hook)
2378 (defvar org-blocker-hook nil
2379 "Hook for functions that are allowed to block a state change.
2381 Functions in this hook should not modify the buffer.
2382 Each function gets as its single argument a property list,
2383 see `org-trigger-hook' for more information about this list.
2385 If any of the functions in this hook returns nil, the state change
2386 is blocked.")
2388 (defvar org-trigger-hook nil
2389 "Hook for functions that are triggered by a state change.
2391 Each function gets as its single argument a property list with at
2392 least the following elements:
2394 (:type type-of-change :position pos-at-entry-start
2395 :from old-state :to new-state)
2397 Depending on the type, more properties may be present.
2399 This mechanism is currently implemented for:
2401 TODO state changes
2402 ------------------
2403 :type todo-state-change
2404 :from previous state (keyword as a string), or nil, or a symbol
2405 'todo' or 'done', to indicate the general type of state.
2406 :to new state, like in :from")
2408 (defcustom org-enforce-todo-dependencies nil
2409 "Non-nil means undone TODO entries will block switching the parent to DONE.
2410 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2411 be blocked if any prior sibling is not yet done.
2412 Finally, if the parent is blocked because of ordered siblings of its own,
2413 the child will also be blocked."
2414 :set (lambda (var val)
2415 (set var val)
2416 (if val
2417 (add-hook 'org-blocker-hook
2418 'org-block-todo-from-children-or-siblings-or-parent)
2419 (remove-hook 'org-blocker-hook
2420 'org-block-todo-from-children-or-siblings-or-parent)))
2421 :group 'org-todo
2422 :type 'boolean)
2424 (defcustom org-enforce-todo-checkbox-dependencies nil
2425 "Non-nil means unchecked boxes will block switching the parent to DONE.
2426 When this is nil, checkboxes have no influence on switching TODO states.
2427 When non-nil, you first need to check off all check boxes before the TODO
2428 entry can be switched to DONE.
2429 This variable needs to be set before org.el is loaded, and you need to
2430 restart Emacs after a change to make the change effective. The only way
2431 to change is while Emacs is running is through the customize interface."
2432 :set (lambda (var val)
2433 (set var val)
2434 (if val
2435 (add-hook 'org-blocker-hook
2436 'org-block-todo-from-checkboxes)
2437 (remove-hook 'org-blocker-hook
2438 'org-block-todo-from-checkboxes)))
2439 :group 'org-todo
2440 :type 'boolean)
2442 (defcustom org-treat-insert-todo-heading-as-state-change nil
2443 "Non-nil means inserting a TODO heading is treated as state change.
2444 So when the command \\[org-insert-todo-heading] is used, state change
2445 logging will apply if appropriate. When nil, the new TODO item will
2446 be inserted directly, and no logging will take place."
2447 :group 'org-todo
2448 :type 'boolean)
2450 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2451 "Non-nil means switching TODO states with S-cursor counts as state change.
2452 This is the default behavior. However, setting this to nil allows a
2453 convenient way to select a TODO state and bypass any logging associated
2454 with that."
2455 :group 'org-todo
2456 :type 'boolean)
2458 (defcustom org-todo-state-tags-triggers nil
2459 "Tag changes that should be triggered by TODO state changes.
2460 This is a list. Each entry is
2462 (state-change (tag . flag) .......)
2464 State-change can be a string with a state, and empty string to indicate the
2465 state that has no TODO keyword, or it can be one of the symbols `todo'
2466 or `done', meaning any not-done or done state, respectively."
2467 :group 'org-todo
2468 :group 'org-tags
2469 :type '(repeat
2470 (cons (choice :tag "When changing to"
2471 (const :tag "Not-done state" todo)
2472 (const :tag "Done state" done)
2473 (string :tag "State"))
2474 (repeat
2475 (cons :tag "Tag action"
2476 (string :tag "Tag")
2477 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2479 (defcustom org-log-done nil
2480 "Information to record when a task moves to the DONE state.
2482 Possible values are:
2484 nil Don't add anything, just change the keyword
2485 time Add a time stamp to the task
2486 note Prompt for a note and add it with template `org-log-note-headings'
2488 This option can also be set with on a per-file-basis with
2490 #+STARTUP: nologdone
2491 #+STARTUP: logdone
2492 #+STARTUP: lognotedone
2494 You can have local logging settings for a subtree by setting the LOGGING
2495 property to one or more of these keywords."
2496 :group 'org-todo
2497 :group 'org-progress
2498 :type '(choice
2499 (const :tag "No logging" nil)
2500 (const :tag "Record CLOSED timestamp" time)
2501 (const :tag "Record CLOSED timestamp with note." note)))
2503 ;; Normalize old uses of org-log-done.
2504 (cond
2505 ((eq org-log-done t) (setq org-log-done 'time))
2506 ((and (listp org-log-done) (memq 'done org-log-done))
2507 (setq org-log-done 'note)))
2509 (defcustom org-log-reschedule nil
2510 "Information to record when the scheduling date of a tasks is modified.
2512 Possible values are:
2514 nil Don't add anything, just change the date
2515 time Add a time stamp to the task
2516 note Prompt for a note and add it with template `org-log-note-headings'
2518 This option can also be set with on a per-file-basis with
2520 #+STARTUP: nologreschedule
2521 #+STARTUP: logreschedule
2522 #+STARTUP: lognotereschedule"
2523 :group 'org-todo
2524 :group 'org-progress
2525 :type '(choice
2526 (const :tag "No logging" nil)
2527 (const :tag "Record timestamp" time)
2528 (const :tag "Record timestamp with note." note)))
2530 (defcustom org-log-redeadline nil
2531 "Information to record when the deadline date of a tasks is modified.
2533 Possible values are:
2535 nil Don't add anything, just change the date
2536 time Add a time stamp to the task
2537 note Prompt for a note and add it with template `org-log-note-headings'
2539 This option can also be set with on a per-file-basis with
2541 #+STARTUP: nologredeadline
2542 #+STARTUP: logredeadline
2543 #+STARTUP: lognoteredeadline
2545 You can have local logging settings for a subtree by setting the LOGGING
2546 property to one or more of these keywords."
2547 :group 'org-todo
2548 :group 'org-progress
2549 :type '(choice
2550 (const :tag "No logging" nil)
2551 (const :tag "Record timestamp" time)
2552 (const :tag "Record timestamp with note." note)))
2554 (defcustom org-log-note-clock-out nil
2555 "Non-nil means record a note when clocking out of an item.
2556 This can also be configured on a per-file basis by adding one of
2557 the following lines anywhere in the buffer:
2559 #+STARTUP: lognoteclock-out
2560 #+STARTUP: nolognoteclock-out"
2561 :group 'org-todo
2562 :group 'org-progress
2563 :type 'boolean)
2565 (defcustom org-log-done-with-time t
2566 "Non-nil means the CLOSED time stamp will contain date and time.
2567 When nil, only the date will be recorded."
2568 :group 'org-progress
2569 :type 'boolean)
2571 (defcustom org-log-note-headings
2572 '((done . "CLOSING NOTE %t")
2573 (state . "State %-12s from %-12S %t")
2574 (note . "Note taken on %t")
2575 (reschedule . "Rescheduled from %S on %t")
2576 (delschedule . "Not scheduled, was %S on %t")
2577 (redeadline . "New deadline from %S on %t")
2578 (deldeadline . "Removed deadline, was %S on %t")
2579 (refile . "Refiled on %t")
2580 (clock-out . ""))
2581 "Headings for notes added to entries.
2582 The value is an alist, with the car being a symbol indicating the note
2583 context, and the cdr is the heading to be used. The heading may also be the
2584 empty string.
2585 %t in the heading will be replaced by a time stamp.
2586 %T will be an active time stamp instead the default inactive one
2587 %d will be replaced by a short-format time stamp.
2588 %D will be replaced by an active short-format time stamp.
2589 %s will be replaced by the new TODO state, in double quotes.
2590 %S will be replaced by the old TODO state, in double quotes.
2591 %u will be replaced by the user name.
2592 %U will be replaced by the full user name.
2594 In fact, it is not a good idea to change the `state' entry, because
2595 agenda log mode depends on the format of these entries."
2596 :group 'org-todo
2597 :group 'org-progress
2598 :type '(list :greedy t
2599 (cons (const :tag "Heading when closing an item" done) string)
2600 (cons (const :tag
2601 "Heading when changing todo state (todo sequence only)"
2602 state) string)
2603 (cons (const :tag "Heading when just taking a note" note) string)
2604 (cons (const :tag "Heading when clocking out" clock-out) string)
2605 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2606 (cons (const :tag "Heading when rescheduling" reschedule) string)
2607 (cons (const :tag "Heading when changing deadline" redeadline) string)
2608 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2609 (cons (const :tag "Heading when refiling" refile) string)))
2611 (unless (assq 'note org-log-note-headings)
2612 (push '(note . "%t") org-log-note-headings))
2614 (defcustom org-log-into-drawer nil
2615 "Non-nil means insert state change notes and time stamps into a drawer.
2616 When nil, state changes notes will be inserted after the headline and
2617 any scheduling and clock lines, but not inside a drawer.
2619 The value of this variable should be the name of the drawer to use.
2620 LOGBOOK is proposed as the default drawer for this purpose, you can
2621 also set this to a string to define the drawer of your choice.
2623 A value of t is also allowed, representing \"LOGBOOK\".
2625 A value of t or nil can also be set with on a per-file-basis with
2627 #+STARTUP: logdrawer
2628 #+STARTUP: nologdrawer
2630 If this variable is set, `org-log-state-notes-insert-after-drawers'
2631 will be ignored.
2633 You can set the property LOG_INTO_DRAWER to overrule this setting for
2634 a subtree."
2635 :group 'org-todo
2636 :group 'org-progress
2637 :type '(choice
2638 (const :tag "Not into a drawer" nil)
2639 (const :tag "LOGBOOK" t)
2640 (string :tag "Other")))
2642 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2644 (defun org-log-into-drawer ()
2645 "Return the value of `org-log-into-drawer', but let properties overrule.
2646 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2647 used instead of the default value."
2648 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2649 (cond
2650 ((not p) org-log-into-drawer)
2651 ((equal p "nil") nil)
2652 ((equal p "t") "LOGBOOK")
2653 (t p))))
2655 (defcustom org-log-state-notes-insert-after-drawers nil
2656 "Non-nil means insert state change notes after any drawers in entry.
2657 Only the drawers that *immediately* follow the headline and the
2658 deadline/scheduled line are skipped.
2659 When nil, insert notes right after the heading and perhaps the line
2660 with deadline/scheduling if present.
2662 This variable will have no effect if `org-log-into-drawer' is
2663 set."
2664 :group 'org-todo
2665 :group 'org-progress
2666 :type 'boolean)
2668 (defcustom org-log-states-order-reversed t
2669 "Non-nil means the latest state note will be directly after heading.
2670 When nil, the state change notes will be ordered according to time.
2672 This option can also be set with on a per-file-basis with
2674 #+STARTUP: logstatesreversed
2675 #+STARTUP: nologstatesreversed"
2676 :group 'org-todo
2677 :group 'org-progress
2678 :type 'boolean)
2680 (defcustom org-todo-repeat-to-state nil
2681 "The TODO state to which a repeater should return the repeating task.
2682 By default this is the first task in a TODO sequence, or the previous state
2683 in a TODO_TYP set. But you can specify another task here.
2684 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2685 :group 'org-todo
2686 :version "24.1"
2687 :type '(choice (const :tag "Head of sequence" nil)
2688 (string :tag "Specific state")))
2690 (defcustom org-log-repeat 'time
2691 "Non-nil means record moving through the DONE state when triggering repeat.
2692 An auto-repeating task is immediately switched back to TODO when
2693 marked DONE. If you are not logging state changes (by adding \"@\"
2694 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2695 record a closing note, there will be no record of the task moving
2696 through DONE. This variable forces taking a note anyway.
2698 nil Don't force a record
2699 time Record a time stamp
2700 note Prompt for a note and add it with template `org-log-note-headings'
2702 This option can also be set with on a per-file-basis with
2704 #+STARTUP: nologrepeat
2705 #+STARTUP: logrepeat
2706 #+STARTUP: lognoterepeat
2708 You can have local logging settings for a subtree by setting the LOGGING
2709 property to one or more of these keywords."
2710 :group 'org-todo
2711 :group 'org-progress
2712 :type '(choice
2713 (const :tag "Don't force a record" nil)
2714 (const :tag "Force recording the DONE state" time)
2715 (const :tag "Force recording a note with the DONE state" note)))
2718 (defgroup org-priorities nil
2719 "Priorities in Org-mode."
2720 :tag "Org Priorities"
2721 :group 'org-todo)
2723 (defcustom org-enable-priority-commands t
2724 "Non-nil means priority commands are active.
2725 When nil, these commands will be disabled, so that you never accidentally
2726 set a priority."
2727 :group 'org-priorities
2728 :type 'boolean)
2730 (defcustom org-highest-priority ?A
2731 "The highest priority of TODO items. A character like ?A, ?B etc.
2732 Must have a smaller ASCII number than `org-lowest-priority'."
2733 :group 'org-priorities
2734 :type 'character)
2736 (defcustom org-lowest-priority ?C
2737 "The lowest priority of TODO items. A character like ?A, ?B etc.
2738 Must have a larger ASCII number than `org-highest-priority'."
2739 :group 'org-priorities
2740 :type 'character)
2742 (defcustom org-default-priority ?B
2743 "The default priority of TODO items.
2744 This is the priority an item gets if no explicit priority is given.
2745 When starting to cycle on an empty priority the first step in the cycle
2746 depends on `org-priority-start-cycle-with-default'. The resulting first
2747 step priority must not exceed the range from `org-highest-priority' to
2748 `org-lowest-priority' which means that `org-default-priority' has to be
2749 in this range exclusive or inclusive the range boundaries. Else the
2750 first step refuses to set the default and the second will fall back
2751 to (depending on the command used) the highest or lowest priority."
2752 :group 'org-priorities
2753 :type 'character)
2755 (defcustom org-priority-start-cycle-with-default t
2756 "Non-nil means start with default priority when starting to cycle.
2757 When this is nil, the first step in the cycle will be (depending on the
2758 command used) one higher or lower than the default priority.
2759 See also `org-default-priority'."
2760 :group 'org-priorities
2761 :type 'boolean)
2763 (defcustom org-get-priority-function nil
2764 "Function to extract the priority from a string.
2765 The string is normally the headline. If this is nil Org computes the
2766 priority from the priority cookie like [#A] in the headline. It returns
2767 an integer, increasing by 1000 for each priority level.
2768 The user can set a different function here, which should take a string
2769 as an argument and return the numeric priority."
2770 :group 'org-priorities
2771 :version "24.1"
2772 :type 'function)
2774 (defgroup org-time nil
2775 "Options concerning time stamps and deadlines in Org-mode."
2776 :tag "Org Time"
2777 :group 'org)
2779 (defcustom org-insert-labeled-timestamps-at-point nil
2780 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2781 When nil, these labeled time stamps are forces into the second line of an
2782 entry, just after the headline. When scheduling from the global TODO list,
2783 the time stamp will always be forced into the second line."
2784 :group 'org-time
2785 :type 'boolean)
2787 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2788 "Formats for `format-time-string' which are used for time stamps.
2789 It is not recommended to change this constant.")
2791 (defcustom org-time-stamp-rounding-minutes '(0 5)
2792 "Number of minutes to round time stamps to.
2793 These are two values, the first applies when first creating a time stamp.
2794 The second applies when changing it with the commands `S-up' and `S-down'.
2795 When changing the time stamp, this means that it will change in steps
2796 of N minutes, as given by the second value.
2798 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2799 numbers should be factors of 60, so for example 5, 10, 15.
2801 When this is larger than 1, you can still force an exact time stamp by using
2802 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2803 and by using a prefix arg to `S-up/down' to specify the exact number
2804 of minutes to shift."
2805 :group 'org-time
2806 :get #'(lambda (var) ; Make sure both elements are there
2807 (if (integerp (default-value var))
2808 (list (default-value var) 5)
2809 (default-value var)))
2810 :type '(list
2811 (integer :tag "when inserting times")
2812 (integer :tag "when modifying times")))
2814 ;; Normalize old customizations of this variable.
2815 (when (integerp org-time-stamp-rounding-minutes)
2816 (setq org-time-stamp-rounding-minutes
2817 (list org-time-stamp-rounding-minutes
2818 org-time-stamp-rounding-minutes)))
2820 (defcustom org-display-custom-times nil
2821 "Non-nil means overlay custom formats over all time stamps.
2822 The formats are defined through the variable `org-time-stamp-custom-formats'.
2823 To turn this on on a per-file basis, insert anywhere in the file:
2824 #+STARTUP: customtime"
2825 :group 'org-time
2826 :set 'set-default
2827 :type 'sexp)
2828 (make-variable-buffer-local 'org-display-custom-times)
2830 (defcustom org-time-stamp-custom-formats
2831 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2832 "Custom formats for time stamps. See `format-time-string' for the syntax.
2833 These are overlaid over the default ISO format if the variable
2834 `org-display-custom-times' is set. Time like %H:%M should be at the
2835 end of the second format. The custom formats are also honored by export
2836 commands, if custom time display is turned on at the time of export."
2837 :group 'org-time
2838 :type 'sexp)
2840 (defun org-time-stamp-format (&optional long inactive)
2841 "Get the right format for a time string."
2842 (let ((f (if long (cdr org-time-stamp-formats)
2843 (car org-time-stamp-formats))))
2844 (if inactive
2845 (concat "[" (substring f 1 -1) "]")
2846 f)))
2848 (defcustom org-time-clocksum-format
2849 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2850 "The format string used when creating CLOCKSUM lines.
2851 This is also used when Org mode generates a time duration.
2853 The value can be a single format string containing two
2854 %-sequences, which will be filled with the number of hours and
2855 minutes in that order.
2857 Alternatively, the value can be a plist associating any of the
2858 keys :years, :months, :weeks, :days, :hours or :minutes with
2859 format strings. The time duration is formatted using only the
2860 time components that are needed and concatenating the results.
2861 If a time unit in absent, it falls back to the next smallest
2862 unit.
2864 The keys :require-years, :require-months, :require-days,
2865 :require-weeks, :require-hours, :require-minutes are also
2866 meaningful. A non-nil value for these keys indicates that the
2867 corresponding time component should always be included, even if
2868 its value is 0.
2871 For example,
2873 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2874 :require-minutes t)
2876 means durations longer than a day will be expressed in days,
2877 hours and minutes, and durations less than a day will always be
2878 expressed in hours and minutes (even for durations less than an
2879 hour).
2881 The value
2883 \(:days \"%dd\" :minutes \"%dm\")
2885 means durations longer than a day will be expressed in days and
2886 minutes, and durations less than a day will be expressed entirely
2887 in minutes (even for durations longer than an hour)."
2888 :group 'org-time
2889 :group 'org-clock
2890 :version "24.4"
2891 :package-version '(Org . "8.0")
2892 :type '(choice (string :tag "Format string")
2893 (set :tag "Plist"
2894 (group :inline t (const :tag "Years" :years)
2895 (string :tag "Format string"))
2896 (group :inline t
2897 (const :tag "Always show years" :require-years)
2898 (const t))
2899 (group :inline t (const :tag "Months" :months)
2900 (string :tag "Format string"))
2901 (group :inline t
2902 (const :tag "Always show months" :require-months)
2903 (const t))
2904 (group :inline t (const :tag "Weeks" :weeks)
2905 (string :tag "Format string"))
2906 (group :inline t
2907 (const :tag "Always show weeks" :require-weeks)
2908 (const t))
2909 (group :inline t (const :tag "Days" :days)
2910 (string :tag "Format string"))
2911 (group :inline t
2912 (const :tag "Always show days" :require-days)
2913 (const t))
2914 (group :inline t (const :tag "Hours" :hours)
2915 (string :tag "Format string"))
2916 (group :inline t
2917 (const :tag "Always show hours" :require-hours)
2918 (const t))
2919 (group :inline t (const :tag "Minutes" :minutes)
2920 (string :tag "Format string"))
2921 (group :inline t
2922 (const :tag "Always show minutes" :require-minutes)
2923 (const t)))))
2925 (defcustom org-time-clocksum-use-fractional nil
2926 "When non-nil, \\[org-clock-display] uses fractional times.
2927 See `org-time-clocksum-format' for more on time clock formats."
2928 :group 'org-time
2929 :group 'org-clock
2930 :version "24.3"
2931 :type 'boolean)
2933 (defcustom org-time-clocksum-use-effort-durations nil
2934 "When non-nil, \\[org-clock-display] uses effort durations.
2935 E.g. by default, one day is considered to be a 8 hours effort,
2936 so a task that has been clocked for 16 hours will be displayed
2937 as during 2 days in the clock display or in the clocktable.
2939 See `org-effort-durations' on how to set effort durations
2940 and `org-time-clocksum-format' for more on time clock formats."
2941 :group 'org-time
2942 :group 'org-clock
2943 :version "24.4"
2944 :package-version '(Org . "8.0")
2945 :type 'boolean)
2947 (defcustom org-time-clocksum-fractional-format "%.2f"
2948 "The format string used when creating CLOCKSUM lines,
2949 or when Org mode generates a time duration, if
2950 `org-time-clocksum-use-fractional' is enabled.
2952 The value can be a single format string containing one
2953 %-sequence, which will be filled with the number of hours as
2954 a float.
2956 Alternatively, the value can be a plist associating any of the
2957 keys :years, :months, :weeks, :days, :hours or :minutes with
2958 a format string. The time duration is formatted using the
2959 largest time unit which gives a non-zero integer part. If all
2960 specified formats have zero integer part, the smallest time unit
2961 is used."
2962 :group 'org-time
2963 :type '(choice (string :tag "Format string")
2964 (set (group :inline t (const :tag "Years" :years)
2965 (string :tag "Format string"))
2966 (group :inline t (const :tag "Months" :months)
2967 (string :tag "Format string"))
2968 (group :inline t (const :tag "Weeks" :weeks)
2969 (string :tag "Format string"))
2970 (group :inline t (const :tag "Days" :days)
2971 (string :tag "Format string"))
2972 (group :inline t (const :tag "Hours" :hours)
2973 (string :tag "Format string"))
2974 (group :inline t (const :tag "Minutes" :minutes)
2975 (string :tag "Format string")))))
2977 (defcustom org-deadline-warning-days 14
2978 "Number of days before expiration during which a deadline becomes active.
2979 This variable governs the display in sparse trees and in the agenda.
2980 When 0 or negative, it means use this number (the absolute value of it)
2981 even if a deadline has a different individual lead time specified.
2983 Custom commands can set this variable in the options section."
2984 :group 'org-time
2985 :group 'org-agenda-daily/weekly
2986 :type 'integer)
2988 (defcustom org-scheduled-delay-days 0
2989 "Number of days before a scheduled item becomes active.
2990 This variable governs the display in sparse trees and in the agenda.
2991 The default value (i.e. 0) means: don't delay scheduled item.
2992 When negative, it means use this number (the absolute value of it)
2993 even if a scheduled item has a different individual delay time
2994 specified.
2996 Custom commands can set this variable in the options section."
2997 :group 'org-time
2998 :group 'org-agenda-daily/weekly
2999 :version "24.4"
3000 :package-version '(Org . "8.0")
3001 :type 'integer)
3003 (defcustom org-read-date-prefer-future t
3004 "Non-nil means assume future for incomplete date input from user.
3005 This affects the following situations:
3006 1. The user gives a month but not a year.
3007 For example, if it is April and you enter \"feb 2\", this will be read
3008 as Feb 2, *next* year. \"May 5\", however, will be this year.
3009 2. The user gives a day, but no month.
3010 For example, if today is the 15th, and you enter \"3\", Org-mode will
3011 read this as the third of *next* month. However, if you enter \"17\",
3012 it will be considered as *this* month.
3014 If you set this variable to the symbol `time', then also the following
3015 will work:
3017 3. If the user gives a time.
3018 If the time is before now, it will be interpreted as tomorrow.
3020 Currently none of this works for ISO week specifications.
3022 When this option is nil, the current day, month and year will always be
3023 used as defaults.
3025 See also `org-agenda-jump-prefer-future'."
3026 :group 'org-time
3027 :type '(choice
3028 (const :tag "Never" nil)
3029 (const :tag "Check month and day" t)
3030 (const :tag "Check month, day, and time" time)))
3032 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3033 "Should the agenda jump command prefer the future for incomplete dates?
3034 The default is to do the same as configured in `org-read-date-prefer-future'.
3035 But you can also set a deviating value here.
3036 This may t or nil, or the symbol `org-read-date-prefer-future'."
3037 :group 'org-agenda
3038 :group 'org-time
3039 :version "24.1"
3040 :type '(choice
3041 (const :tag "Use org-read-date-prefer-future"
3042 org-read-date-prefer-future)
3043 (const :tag "Never" nil)
3044 (const :tag "Always" t)))
3046 (defcustom org-read-date-force-compatible-dates t
3047 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3049 Depending on the system Emacs is running on, certain dates cannot
3050 be represented with the type used internally to represent time.
3051 Dates between 1970-1-1 and 2038-1-1 can always be represented
3052 correctly. Some systems allow for earlier dates, some for later,
3053 some for both. One way to find out it to insert any date into an
3054 Org buffer, putting the cursor on the year and hitting S-up and
3055 S-down to test the range.
3057 When this variable is set to t, the date/time prompt will not let
3058 you specify dates outside the 1970-2037 range, so it is certain that
3059 these dates will work in whatever version of Emacs you are
3060 running, and also that you can move a file from one Emacs implementation
3061 to another. WHenever Org is forcing the year for you, it will display
3062 a message and beep.
3064 When this variable is nil, Org will check if the date is
3065 representable in the specific Emacs implementation you are using.
3066 If not, it will force a year, usually the current year, and beep
3067 to remind you. Currently this setting is not recommended because
3068 the likelihood that you will open your Org files in an Emacs that
3069 has limited date range is not negligible.
3071 A workaround for this problem is to use diary sexp dates for time
3072 stamps outside of this range."
3073 :group 'org-time
3074 :version "24.1"
3075 :type 'boolean)
3077 (defcustom org-read-date-display-live t
3078 "Non-nil means display current interpretation of date prompt live.
3079 This display will be in an overlay, in the minibuffer."
3080 :group 'org-time
3081 :type 'boolean)
3083 (defcustom org-read-date-popup-calendar t
3084 "Non-nil means pop up a calendar when prompting for a date.
3085 In the calendar, the date can be selected with mouse-1. However, the
3086 minibuffer will also be active, and you can simply enter the date as well.
3087 When nil, only the minibuffer will be available."
3088 :group 'org-time
3089 :type 'boolean)
3090 (org-defvaralias 'org-popup-calendar-for-date-prompt
3091 'org-read-date-popup-calendar)
3093 (make-obsolete-variable
3094 'org-read-date-minibuffer-setup-hook
3095 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3096 (defcustom org-read-date-minibuffer-setup-hook nil
3097 "Hook to be used to set up keys for the date/time interface.
3098 Add key definitions to `minibuffer-local-map', which will be a
3099 temporary copy.
3101 WARNING: This option is obsolete, you should use
3102 `org-read-date-minibuffer-local-map' to set up keys."
3103 :group 'org-time
3104 :type 'hook)
3106 (defcustom org-extend-today-until 0
3107 "The hour when your day really ends. Must be an integer.
3108 This has influence for the following applications:
3109 - When switching the agenda to \"today\". It it is still earlier than
3110 the time given here, the day recognized as TODAY is actually yesterday.
3111 - When a date is read from the user and it is still before the time given
3112 here, the current date and time will be assumed to be yesterday, 23:59.
3113 Also, timestamps inserted in capture templates follow this rule.
3115 IMPORTANT: This is a feature whose implementation is and likely will
3116 remain incomplete. Really, it is only here because past midnight seems to
3117 be the favorite working time of John Wiegley :-)"
3118 :group 'org-time
3119 :type 'integer)
3121 (defcustom org-use-effective-time nil
3122 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3123 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3124 \"effective time\" of any timestamps between midnight and 8am will be
3125 23:59 of the previous day."
3126 :group 'org-time
3127 :version "24.1"
3128 :type 'boolean)
3130 (defcustom org-use-last-clock-out-time-as-effective-time nil
3131 "When non-nil, use the last clock out time for `org-todo'.
3132 Note that this option has precedence over the combined use of
3133 `org-use-effective-time' and `org-extend-today-until'."
3134 :group 'org-time
3135 :version "24.4"
3136 :package-version '(Org . "8.0")
3137 :type 'boolean)
3139 (defcustom org-edit-timestamp-down-means-later nil
3140 "Non-nil means S-down will increase the time in a time stamp.
3141 When nil, S-up will increase."
3142 :group 'org-time
3143 :type 'boolean)
3145 (defcustom org-calendar-follow-timestamp-change t
3146 "Non-nil means make the calendar window follow timestamp changes.
3147 When a timestamp is modified and the calendar window is visible, it will be
3148 moved to the new date."
3149 :group 'org-time
3150 :type 'boolean)
3152 (defgroup org-tags nil
3153 "Options concerning tags in Org-mode."
3154 :tag "Org Tags"
3155 :group 'org)
3157 (defcustom org-tag-alist nil
3158 "List of tags allowed in Org-mode files.
3159 When this list is nil, Org-mode will base TAG input on what is already in the
3160 buffer.
3161 The value of this variable is an alist, the car of each entry must be a
3162 keyword as a string, the cdr may be a character that is used to select
3163 that tag through the fast-tag-selection interface.
3164 See the manual for details."
3165 :group 'org-tags
3166 :type '(repeat
3167 (choice
3168 (cons (string :tag "Tag name")
3169 (character :tag "Access char"))
3170 (list :tag "Start radio group"
3171 (const :startgroup)
3172 (option (string :tag "Group description")))
3173 (list :tag "End radio group"
3174 (const :endgroup)
3175 (option (string :tag "Group description")))
3176 (const :tag "New line" (:newline)))))
3178 (defcustom org-tag-persistent-alist nil
3179 "List of tags that will always appear in all Org-mode files.
3180 This is in addition to any in buffer settings or customizations
3181 of `org-tag-alist'.
3182 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3183 The value of this variable is an alist, the car of each entry must be a
3184 keyword as a string, the cdr may be a character that is used to select
3185 that tag through the fast-tag-selection interface.
3186 See the manual for details.
3187 To disable these tags on a per-file basis, insert anywhere in the file:
3188 #+STARTUP: noptag"
3189 :group 'org-tags
3190 :type '(repeat
3191 (choice
3192 (cons (string :tag "Tag name")
3193 (character :tag "Access char"))
3194 (const :tag "Start radio group" (:startgroup))
3195 (const :tag "End radio group" (:endgroup))
3196 (const :tag "New line" (:newline)))))
3198 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3199 "If non-nil, always offer completion for all tags of all agenda files.
3200 Instead of customizing this variable directly, you might want to
3201 set it locally for capture buffers, because there no list of
3202 tags in that file can be created dynamically (there are none).
3204 (add-hook 'org-capture-mode-hook
3205 (lambda ()
3206 (set (make-local-variable
3207 'org-complete-tags-always-offer-all-agenda-tags)
3208 t)))"
3209 :group 'org-tags
3210 :version "24.1"
3211 :type 'boolean)
3213 (defvar org-file-tags nil
3214 "List of tags that can be inherited by all entries in the file.
3215 The tags will be inherited if the variable `org-use-tag-inheritance'
3216 says they should be.
3217 This variable is populated from #+FILETAGS lines.")
3219 (defcustom org-use-fast-tag-selection 'auto
3220 "Non-nil means use fast tag selection scheme.
3221 This is a special interface to select and deselect tags with single keys.
3222 When nil, fast selection is never used.
3223 When the symbol `auto', fast selection is used if and only if selection
3224 characters for tags have been configured, either through the variable
3225 `org-tag-alist' or through a #+TAGS line in the buffer.
3226 When t, fast selection is always used and selection keys are assigned
3227 automatically if necessary."
3228 :group 'org-tags
3229 :type '(choice
3230 (const :tag "Always" t)
3231 (const :tag "Never" nil)
3232 (const :tag "When selection characters are configured" 'auto)))
3234 (defcustom org-fast-tag-selection-single-key nil
3235 "Non-nil means fast tag selection exits after first change.
3236 When nil, you have to press RET to exit it.
3237 During fast tag selection, you can toggle this flag with `C-c'.
3238 This variable can also have the value `expert'. In this case, the window
3239 displaying the tags menu is not even shown, until you press C-c again."
3240 :group 'org-tags
3241 :type '(choice
3242 (const :tag "No" nil)
3243 (const :tag "Yes" t)
3244 (const :tag "Expert" expert)))
3246 (defvar org-fast-tag-selection-include-todo nil
3247 "Non-nil means fast tags selection interface will also offer TODO states.
3248 This is an undocumented feature, you should not rely on it.")
3250 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3251 "The column to which tags should be indented in a headline.
3252 If this number is positive, it specifies the column. If it is negative,
3253 it means that the tags should be flushright to that column. For example,
3254 -80 works well for a normal 80 character screen.
3255 When 0, place tags directly after headline text, with only one space in
3256 between."
3257 :group 'org-tags
3258 :type 'integer)
3260 (defcustom org-auto-align-tags t
3261 "Non-nil keeps tags aligned when modifying headlines.
3262 Some operations (i.e. demoting) change the length of a headline and
3263 therefore shift the tags around. With this option turned on, after
3264 each such operation the tags are again aligned to `org-tags-column'."
3265 :group 'org-tags
3266 :type 'boolean)
3268 (defcustom org-use-tag-inheritance t
3269 "Non-nil means tags in levels apply also for sublevels.
3270 When nil, only the tags directly given in a specific line apply there.
3271 This may also be a list of tags that should be inherited, or a regexp that
3272 matches tags that should be inherited. Additional control is possible
3273 with the variable `org-tags-exclude-from-inheritance' which gives an
3274 explicit list of tags to be excluded from inheritance, even if the value of
3275 `org-use-tag-inheritance' would select it for inheritance.
3277 If this option is t, a match early-on in a tree can lead to a large
3278 number of matches in the subtree when constructing the agenda or creating
3279 a sparse tree. If you only want to see the first match in a tree during
3280 a search, check out the variable `org-tags-match-list-sublevels'."
3281 :group 'org-tags
3282 :type '(choice
3283 (const :tag "Not" nil)
3284 (const :tag "Always" t)
3285 (repeat :tag "Specific tags" (string :tag "Tag"))
3286 (regexp :tag "Tags matched by regexp")))
3288 (defcustom org-tags-exclude-from-inheritance nil
3289 "List of tags that should never be inherited.
3290 This is a way to exclude a few tags from inheritance. For way to do
3291 the opposite, to actively allow inheritance for selected tags,
3292 see the variable `org-use-tag-inheritance'."
3293 :group 'org-tags
3294 :type '(repeat (string :tag "Tag")))
3296 (defun org-tag-inherit-p (tag)
3297 "Check if TAG is one that should be inherited."
3298 (cond
3299 ((member tag org-tags-exclude-from-inheritance) nil)
3300 ((eq org-use-tag-inheritance t) t)
3301 ((not org-use-tag-inheritance) nil)
3302 ((stringp org-use-tag-inheritance)
3303 (string-match org-use-tag-inheritance tag))
3304 ((listp org-use-tag-inheritance)
3305 (member tag org-use-tag-inheritance))
3306 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3308 (defcustom org-tags-match-list-sublevels t
3309 "Non-nil means list also sublevels of headlines matching a search.
3310 This variable applies to tags/property searches, and also to stuck
3311 projects because this search is based on a tags match as well.
3313 When set to the symbol `indented', sublevels are indented with
3314 leading dots.
3316 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3317 the sublevels of a headline matching a tag search often also match
3318 the same search. Listing all of them can create very long lists.
3319 Setting this variable to nil causes subtrees of a match to be skipped.
3321 This variable is semi-obsolete and probably should always be true. It
3322 is better to limit inheritance to certain tags using the variables
3323 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3324 :group 'org-tags
3325 :type '(choice
3326 (const :tag "No, don't list them" nil)
3327 (const :tag "Yes, do list them" t)
3328 (const :tag "List them, indented with leading dots" indented)))
3330 (defcustom org-tags-sort-function nil
3331 "When set, tags are sorted using this function as a comparator."
3332 :group 'org-tags
3333 :type '(choice
3334 (const :tag "No sorting" nil)
3335 (const :tag "Alphabetical" string<)
3336 (const :tag "Reverse alphabetical" string>)
3337 (function :tag "Custom function" nil)))
3339 (defvar org-tags-history nil
3340 "History of minibuffer reads for tags.")
3341 (defvar org-last-tags-completion-table nil
3342 "The last used completion table for tags.")
3343 (defvar org-after-tags-change-hook nil
3344 "Hook that is run after the tags in a line have changed.")
3346 (defgroup org-properties nil
3347 "Options concerning properties in Org-mode."
3348 :tag "Org Properties"
3349 :group 'org)
3351 (defcustom org-property-format "%-10s %s"
3352 "How property key/value pairs should be formatted by `indent-line'.
3353 When `indent-line' hits a property definition, it will format the line
3354 according to this format, mainly to make sure that the values are
3355 lined-up with respect to each other."
3356 :group 'org-properties
3357 :type 'string)
3359 (defcustom org-properties-postprocess-alist nil
3360 "Alist of properties and functions to adjust inserted values.
3361 Elements of this alist must be of the form
3363 ([string] [function])
3365 where [string] must be a property name and [function] must be a
3366 lambda expression: this lambda expression must take one argument,
3367 the value to adjust, and return the new value as a string.
3369 For example, this element will allow the property \"Remaining\"
3370 to be updated wrt the relation between the \"Effort\" property
3371 and the clock summary:
3373 ((\"Remaining\" (lambda(value)
3374 (let ((clocksum (org-clock-sum-current-item))
3375 (effort (org-duration-string-to-minutes
3376 (org-entry-get (point) \"Effort\"))))
3377 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3378 :group 'org-properties
3379 :version "24.1"
3380 :type '(alist :key-type (string :tag "Property")
3381 :value-type (function :tag "Function")))
3383 (defcustom org-use-property-inheritance nil
3384 "Non-nil means properties apply also for sublevels.
3386 This setting is chiefly used during property searches. Turning it on can
3387 cause significant overhead when doing a search, which is why it is not
3388 on by default.
3390 When nil, only the properties directly given in the current entry count.
3391 When t, every property is inherited. The value may also be a list of
3392 properties that should have inheritance, or a regular expression matching
3393 properties that should be inherited.
3395 However, note that some special properties use inheritance under special
3396 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3397 and the properties ending in \"_ALL\" when they are used as descriptor
3398 for valid values of a property.
3400 Note for programmers:
3401 When querying an entry with `org-entry-get', you can control if inheritance
3402 should be used. By default, `org-entry-get' looks only at the local
3403 properties. You can request inheritance by setting the inherit argument
3404 to t (to force inheritance) or to `selective' (to respect the setting
3405 in this variable)."
3406 :group 'org-properties
3407 :type '(choice
3408 (const :tag "Not" nil)
3409 (const :tag "Always" t)
3410 (repeat :tag "Specific properties" (string :tag "Property"))
3411 (regexp :tag "Properties matched by regexp")))
3413 (defun org-property-inherit-p (property)
3414 "Check if PROPERTY is one that should be inherited."
3415 (cond
3416 ((eq org-use-property-inheritance t) t)
3417 ((not org-use-property-inheritance) nil)
3418 ((stringp org-use-property-inheritance)
3419 (string-match org-use-property-inheritance property))
3420 ((listp org-use-property-inheritance)
3421 (member property org-use-property-inheritance))
3422 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3424 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3425 "The default column format, if no other format has been defined.
3426 This variable can be set on the per-file basis by inserting a line
3428 #+COLUMNS: %25ITEM ....."
3429 :group 'org-properties
3430 :type 'string)
3432 (defcustom org-columns-ellipses ".."
3433 "The ellipses to be used when a field in column view is truncated.
3434 When this is the empty string, as many characters as possible are shown,
3435 but then there will be no visual indication that the field has been truncated.
3436 When this is a string of length N, the last N characters of a truncated
3437 field are replaced by this string. If the column is narrower than the
3438 ellipses string, only part of the ellipses string will be shown."
3439 :group 'org-properties
3440 :type 'string)
3442 (defcustom org-columns-modify-value-for-display-function nil
3443 "Function that modifies values for display in column view.
3444 For example, it can be used to cut out a certain part from a time stamp.
3445 The function must take 2 arguments:
3447 column-title The title of the column (*not* the property name)
3448 value The value that should be modified.
3450 The function should return the value that should be displayed,
3451 or nil if the normal value should be used."
3452 :group 'org-properties
3453 :type 'function)
3455 (defcustom org-effort-property "Effort"
3456 "The property that is being used to keep track of effort estimates.
3457 Effort estimates given in this property need to have the format H:MM."
3458 :group 'org-properties
3459 :group 'org-progress
3460 :type '(string :tag "Property"))
3462 (defconst org-global-properties-fixed
3463 '(("VISIBILITY_ALL" . "folded children content all")
3464 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3465 "List of property/value pairs that can be inherited by any entry.
3467 These are fixed values, for the preset properties. The user variable
3468 that can be used to add to this list is `org-global-properties'.
3470 The entries in this list are cons cells where the car is a property
3471 name and cdr is a string with the value. If the value represents
3472 multiple items like an \"_ALL\" property, separate the items by
3473 spaces.")
3475 (defcustom org-global-properties nil
3476 "List of property/value pairs that can be inherited by any entry.
3478 This list will be combined with the constant `org-global-properties-fixed'.
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.
3483 You can set buffer-local values for the same purpose in the variable
3484 `org-file-properties' this by adding lines like
3486 #+PROPERTY: NAME VALUE"
3487 :group 'org-properties
3488 :type '(repeat
3489 (cons (string :tag "Property")
3490 (string :tag "Value"))))
3492 (defvar org-file-properties nil
3493 "List of property/value pairs that can be inherited by any entry.
3494 Valid for the current buffer.
3495 This variable is populated from #+PROPERTY lines.")
3496 (make-variable-buffer-local 'org-file-properties)
3498 (defgroup org-agenda nil
3499 "Options concerning agenda views in Org-mode."
3500 :tag "Org Agenda"
3501 :group 'org)
3503 (defvar org-category nil
3504 "Variable used by org files to set a category for agenda display.
3505 Such files should use a file variable to set it, for example
3507 # -*- mode: org; org-category: \"ELisp\"
3509 or contain a special line
3511 #+CATEGORY: ELisp
3513 If the file does not specify a category, then file's base name
3514 is used instead.")
3515 (make-variable-buffer-local 'org-category)
3516 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3518 (defcustom org-agenda-files nil
3519 "The files to be used for agenda display.
3520 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3521 \\[org-remove-file]. You can also use customize to edit the list.
3523 If an entry is a directory, all files in that directory that are matched by
3524 `org-agenda-file-regexp' will be part of the file list.
3526 If the value of the variable is not a list but a single file name, then
3527 the list of agenda files is actually stored and maintained in that file, one
3528 agenda file per line. In this file paths can be given relative to
3529 `org-directory'. Tilde expansion and environment variable substitution
3530 are also made."
3531 :group 'org-agenda
3532 :type '(choice
3533 (repeat :tag "List of files and directories" file)
3534 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3536 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3537 "Regular expression to match files for `org-agenda-files'.
3538 If any element in the list in that variable contains a directory instead
3539 of a normal file, all files in that directory that are matched by this
3540 regular expression will be included."
3541 :group 'org-agenda
3542 :type 'regexp)
3544 (defcustom org-agenda-text-search-extra-files nil
3545 "List of extra files to be searched by text search commands.
3546 These files will be search in addition to the agenda files by the
3547 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3548 Note that these files will only be searched for text search commands,
3549 not for the other agenda views like todo lists, tag searches or the weekly
3550 agenda. This variable is intended to list notes and possibly archive files
3551 that should also be searched by these two commands.
3552 In fact, if the first element in the list is the symbol `agenda-archives',
3553 than all archive files of all agenda files will be added to the search
3554 scope."
3555 :group 'org-agenda
3556 :type '(set :greedy t
3557 (const :tag "Agenda Archives" agenda-archives)
3558 (repeat :inline t (file))))
3560 (org-defvaralias 'org-agenda-multi-occur-extra-files
3561 'org-agenda-text-search-extra-files)
3563 (defcustom org-agenda-skip-unavailable-files nil
3564 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3565 A nil value means to remove them, after a query, from the list."
3566 :group 'org-agenda
3567 :type 'boolean)
3569 (defcustom org-calendar-to-agenda-key [?c]
3570 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3571 The command `org-calendar-goto-agenda' will be bound to this key. The
3572 default is the character `c' because then `c' can be used to switch back and
3573 forth between agenda and calendar."
3574 :group 'org-agenda
3575 :type 'sexp)
3577 (defcustom org-calendar-insert-diary-entry-key [?i]
3578 "The key to be installed in `calendar-mode-map' for adding diary entries.
3579 This option is irrelevant until `org-agenda-diary-file' has been configured
3580 to point to an Org-mode file. When that is the case, the command
3581 `org-agenda-diary-entry' will be bound to the key given here, by default
3582 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3583 if you want to continue doing this, you need to change this to a different
3584 key."
3585 :group 'org-agenda
3586 :type 'sexp)
3588 (defcustom org-agenda-diary-file 'diary-file
3589 "File to which to add new entries with the `i' key in agenda and calendar.
3590 When this is the symbol `diary-file', the functionality in the Emacs
3591 calendar will be used to add entries to the `diary-file'. But when this
3592 points to a file, `org-agenda-diary-entry' will be used instead."
3593 :group 'org-agenda
3594 :type '(choice
3595 (const :tag "The standard Emacs diary file" diary-file)
3596 (file :tag "Special Org file diary entries")))
3598 (eval-after-load "calendar"
3599 '(progn
3600 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3601 'org-calendar-goto-agenda)
3602 (add-hook 'calendar-mode-hook
3603 (lambda ()
3604 (unless (eq org-agenda-diary-file 'diary-file)
3605 (define-key calendar-mode-map
3606 org-calendar-insert-diary-entry-key
3607 'org-agenda-diary-entry))))))
3609 (defgroup org-latex nil
3610 "Options for embedding LaTeX code into Org-mode."
3611 :tag "Org LaTeX"
3612 :group 'org)
3614 (defcustom org-format-latex-options
3615 '(:foreground default :background default :scale 1.0
3616 :html-foreground "Black" :html-background "Transparent"
3617 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3618 "Options for creating images from LaTeX fragments.
3619 This is a property list with the following properties:
3620 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3621 `default' means use the foreground of the default face.
3622 `auto' means use the foreground from the text face.
3623 :background the background color, or \"Transparent\".
3624 `default' means use the background of the default face.
3625 `auto' means use the background from the text face.
3626 :scale a scaling factor for the size of the images, to get more pixels
3627 :html-foreground, :html-background, :html-scale
3628 the same numbers for HTML export.
3629 :matchers a list indicating which matchers should be used to
3630 find LaTeX fragments. Valid members of this list are:
3631 \"begin\" find environments
3632 \"$1\" find single characters surrounded by $.$
3633 \"$\" find math expressions surrounded by $...$
3634 \"$$\" find math expressions surrounded by $$....$$
3635 \"\\(\" find math expressions surrounded by \\(...\\)
3636 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3637 :group 'org-latex
3638 :type 'plist)
3640 (defcustom org-format-latex-signal-error t
3641 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3642 When nil, just push out a message."
3643 :group 'org-latex
3644 :version "24.1"
3645 :type 'boolean)
3647 (defcustom org-latex-to-mathml-jar-file nil
3648 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3649 Use this to specify additional executable file say a jar file.
3651 When using MathToWeb as the converter, specify the full-path to
3652 your mathtoweb.jar file."
3653 :group 'org-latex
3654 :version "24.1"
3655 :type '(choice
3656 (const :tag "None" nil)
3657 (file :tag "JAR file" :must-match t)))
3659 (defcustom org-latex-to-mathml-convert-command nil
3660 "Command to convert LaTeX fragments to MathML.
3661 Replace format-specifiers in the command as noted below and use
3662 `shell-command' to convert LaTeX to MathML.
3663 %j: Executable file in fully expanded form as specified by
3664 `org-latex-to-mathml-jar-file'.
3665 %I: Input LaTeX file in fully expanded form
3666 %o: Output MathML file
3667 This command is used by `org-create-math-formula'.
3669 When using MathToWeb as the converter, set this to
3670 \"java -jar %j -unicode -force -df %o %I\"."
3671 :group 'org-latex
3672 :version "24.1"
3673 :type '(choice
3674 (const :tag "None" nil)
3675 (string :tag "\nShell command")))
3677 (defcustom org-latex-create-formula-image-program 'dvipng
3678 "Program to convert LaTeX fragments with.
3680 dvipng Process the LaTeX fragments to dvi file, then convert
3681 dvi files to png files using dvipng.
3682 This will also include processing of non-math environments.
3683 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3684 to convert pdf files to png files"
3685 :group 'org-latex
3686 :version "24.1"
3687 :type '(choice
3688 (const :tag "dvipng" dvipng)
3689 (const :tag "imagemagick" imagemagick)))
3691 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3692 "Path to store latex preview images.
3693 A relative path here creates many directories relative to the
3694 processed org files paths. An absolute path puts all preview
3695 images at the same place."
3696 :group 'org-latex
3697 :version "24.3"
3698 :type 'string)
3700 (defun org-format-latex-mathml-available-p ()
3701 "Return t if `org-latex-to-mathml-convert-command' is usable."
3702 (save-match-data
3703 (when (and (boundp 'org-latex-to-mathml-convert-command)
3704 org-latex-to-mathml-convert-command)
3705 (let ((executable (car (split-string
3706 org-latex-to-mathml-convert-command))))
3707 (when (executable-find executable)
3708 (if (string-match
3709 "%j" org-latex-to-mathml-convert-command)
3710 (file-readable-p org-latex-to-mathml-jar-file)
3711 t))))))
3713 (defcustom org-format-latex-header "\\documentclass{article}
3714 \\usepackage[usenames]{color}
3715 \\usepackage{amsmath}
3716 \\usepackage[mathscr]{eucal}
3717 \\pagestyle{empty} % do not remove
3718 \[PACKAGES]
3719 \[DEFAULT-PACKAGES]
3720 % The settings below are copied from fullpage.sty
3721 \\setlength{\\textwidth}{\\paperwidth}
3722 \\addtolength{\\textwidth}{-3cm}
3723 \\setlength{\\oddsidemargin}{1.5cm}
3724 \\addtolength{\\oddsidemargin}{-2.54cm}
3725 \\setlength{\\evensidemargin}{\\oddsidemargin}
3726 \\setlength{\\textheight}{\\paperheight}
3727 \\addtolength{\\textheight}{-\\headheight}
3728 \\addtolength{\\textheight}{-\\headsep}
3729 \\addtolength{\\textheight}{-\\footskip}
3730 \\addtolength{\\textheight}{-3cm}
3731 \\setlength{\\topmargin}{1.5cm}
3732 \\addtolength{\\topmargin}{-2.54cm}"
3733 "The document header used for processing LaTeX fragments.
3734 It is imperative that this header make sure that no page number
3735 appears on the page. The package defined in the variables
3736 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3737 will either replace the placeholder \"[PACKAGES]\" in this
3738 header, or they will be appended."
3739 :group 'org-latex
3740 :type 'string)
3742 (defun org-set-packages-alist (var val)
3743 "Set the packages alist and make sure it has 3 elements per entry."
3744 (set var (mapcar (lambda (x)
3745 (if (and (consp x) (= (length x) 2))
3746 (list (car x) (nth 1 x) t)
3748 val)))
3750 (defun org-get-packages-alist (var)
3751 "Get the packages alist and make sure it has 3 elements per entry."
3752 (mapcar (lambda (x)
3753 (if (and (consp x) (= (length x) 2))
3754 (list (car x) (nth 1 x) t)
3756 (default-value var)))
3758 (defcustom org-latex-default-packages-alist
3759 '(("AUTO" "inputenc" t)
3760 ("T1" "fontenc" t)
3761 ("" "fixltx2e" nil)
3762 ("" "graphicx" t)
3763 ("" "longtable" nil)
3764 ("" "float" nil)
3765 ("" "wrapfig" nil)
3766 ("" "soul" t)
3767 ("" "textcomp" t)
3768 ("" "marvosym" t)
3769 ("" "wasysym" t)
3770 ("" "latexsym" t)
3771 ("" "amssymb" t)
3772 ("" "hyperref" nil)
3773 "\\tolerance=1000")
3774 "Alist of default packages to be inserted in the header.
3776 Change this only if one of the packages here causes an
3777 incompatibility with another package you are using.
3779 The packages in this list are needed by one part or another of
3780 Org mode to function properly:
3782 - inputenc, fontenc: for basic font and character selection
3783 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3784 symbols used for interpreting the entities in `org-entities'.
3785 You can skip some of these packages if you don't use any of the
3786 symbols in it.
3787 - graphicx: for including images
3788 - float, wrapfig: for figure placement
3789 - longtable: for long tables
3790 - hyperref: for cross references
3792 Therefore you should not modify this variable unless you know
3793 what you are doing. The one reason to change it anyway is that
3794 you might be loading some other package that conflicts with one
3795 of the default packages. Each cell is of the format
3796 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3797 the package also needs to be included when compiling LaTeX
3798 snippets into images for inclusion into non-LaTeX output."
3799 :group 'org-latex
3800 :group 'org-export-latex
3801 :set 'org-set-packages-alist
3802 :get 'org-get-packages-alist
3803 :version "24.1"
3804 :type '(repeat
3805 (choice
3806 (list :tag "options/package pair"
3807 (string :tag "options")
3808 (string :tag "package")
3809 (boolean :tag "Snippet"))
3810 (string :tag "A line of LaTeX"))))
3812 (defcustom org-latex-packages-alist nil
3813 "Alist of packages to be inserted in every LaTeX header.
3815 These will be inserted after `org-latex-default-packages-alist'.
3816 Each cell is of the format:
3818 \(\"options\" \"package\" snippet-flag)
3820 SNIPPET-FLAG, when t, indicates that this package is also needed
3821 when turning LaTeX snippets into images for inclusion into
3822 non-LaTeX output.
3824 Make sure that you only list packages here which:
3826 - you want in every file
3827 - do not conflict with the setup in `org-format-latex-header'.
3828 - do not conflict with the default packages in
3829 `org-latex-default-packages-alist'."
3830 :group 'org-latex
3831 :group 'org-export-latex
3832 :set 'org-set-packages-alist
3833 :get 'org-get-packages-alist
3834 :type '(repeat
3835 (choice
3836 (list :tag "options/package pair"
3837 (string :tag "options")
3838 (string :tag "package")
3839 (boolean :tag "Snippet"))
3840 (string :tag "A line of LaTeX"))))
3842 (defgroup org-appearance nil
3843 "Settings for Org-mode appearance."
3844 :tag "Org Appearance"
3845 :group 'org)
3847 (defcustom org-level-color-stars-only nil
3848 "Non-nil means fontify only the stars in each headline.
3849 When nil, the entire headline is fontified.
3850 Changing it requires restart of `font-lock-mode' to become effective
3851 also in regions already fontified."
3852 :group 'org-appearance
3853 :type 'boolean)
3855 (defcustom org-hide-leading-stars nil
3856 "Non-nil means hide the first N-1 stars in a headline.
3857 This works by using the face `org-hide' for these stars. This
3858 face is white for a light background, and black for a dark
3859 background. You may have to customize the face `org-hide' to
3860 make this work.
3861 Changing it requires restart of `font-lock-mode' to become effective
3862 also in regions already fontified.
3863 You may also set this on a per-file basis by adding one of the following
3864 lines to the buffer:
3866 #+STARTUP: hidestars
3867 #+STARTUP: showstars"
3868 :group 'org-appearance
3869 :type 'boolean)
3871 (defcustom org-hidden-keywords nil
3872 "List of symbols corresponding to keywords to be hidden the org buffer.
3873 For example, a value '(title) for this list will make the document's title
3874 appear in the buffer without the initial #+TITLE: keyword."
3875 :group 'org-appearance
3876 :version "24.1"
3877 :type '(set (const :tag "#+AUTHOR" author)
3878 (const :tag "#+DATE" date)
3879 (const :tag "#+EMAIL" email)
3880 (const :tag "#+TITLE" title)))
3882 (defcustom org-custom-properties nil
3883 "List of properties (as strings) with a special meaning.
3884 The default use of these custom properties is to let the user
3885 hide them with `org-toggle-custom-properties-visibility'."
3886 :group 'org-properties
3887 :group 'org-appearance
3888 :version "24.3"
3889 :type '(repeat (string :tag "Property Name")))
3891 (defcustom org-fontify-done-headline nil
3892 "Non-nil means change the face of a headline if it is marked DONE.
3893 Normally, only the TODO/DONE keyword indicates the state of a headline.
3894 When this is non-nil, the headline after the keyword is set to the
3895 `org-headline-done' as an additional indication."
3896 :group 'org-appearance
3897 :type 'boolean)
3899 (defcustom org-fontify-emphasized-text t
3900 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3901 Changing this variable requires a restart of Emacs to take effect."
3902 :group 'org-appearance
3903 :type 'boolean)
3905 (defcustom org-fontify-whole-heading-line nil
3906 "Non-nil means fontify the whole line for headings.
3907 This is useful when setting a background color for the
3908 org-level-* faces."
3909 :group 'org-appearance
3910 :type 'boolean)
3912 (defcustom org-highlight-latex-and-related nil
3913 "Non-nil means highlight LaTeX related syntax in the buffer.
3914 When non nil, the value should be a list containing any of the
3915 following symbols:
3916 `latex' Highlight LaTeX snippets and environments.
3917 `script' Highlight subscript and superscript.
3918 `entities' Highlight entities."
3919 :group 'org-appearance
3920 :version "24.4"
3921 :package-version '(Org . "8.0")
3922 :type '(choice
3923 (const :tag "No highlighting" nil)
3924 (set :greedy t :tag "Highlight"
3925 (const :tag "LaTeX snippets and environments" latex)
3926 (const :tag "Subscript and superscript" script)
3927 (const :tag "Entities" entities))))
3929 (defcustom org-hide-emphasis-markers nil
3930 "Non-nil mean font-lock should hide the emphasis marker characters."
3931 :group 'org-appearance
3932 :type 'boolean)
3934 (defcustom org-pretty-entities nil
3935 "Non-nil means show entities as UTF8 characters.
3936 When nil, the \\name form remains in the buffer."
3937 :group 'org-appearance
3938 :version "24.1"
3939 :type 'boolean)
3941 (defcustom org-pretty-entities-include-sub-superscripts t
3942 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3943 :group 'org-appearance
3944 :version "24.1"
3945 :type 'boolean)
3947 (defvar org-emph-re nil
3948 "Regular expression for matching emphasis.
3949 After a match, the match groups contain these elements:
3950 0 The match of the full regular expression, including the characters
3951 before and after the proper match
3952 1 The character before the proper match, or empty at beginning of line
3953 2 The proper match, including the leading and trailing markers
3954 3 The leading marker like * or /, indicating the type of highlighting
3955 4 The text between the emphasis markers, not including the markers
3956 5 The character after the match, empty at the end of a line")
3957 (defvar org-verbatim-re nil
3958 "Regular expression for matching verbatim text.")
3959 (defvar org-emphasis-regexp-components) ; defined just below
3960 (defvar org-emphasis-alist) ; defined just below
3961 (defun org-set-emph-re (var val)
3962 "Set variable and compute the emphasis regular expression."
3963 (set var val)
3964 (when (and (boundp 'org-emphasis-alist)
3965 (boundp 'org-emphasis-regexp-components)
3966 org-emphasis-alist org-emphasis-regexp-components)
3967 (let* ((e org-emphasis-regexp-components)
3968 (pre (car e))
3969 (post (nth 1 e))
3970 (border (nth 2 e))
3971 (body (nth 3 e))
3972 (nl (nth 4 e))
3973 (body1 (concat body "*?"))
3974 (markers (mapconcat 'car org-emphasis-alist ""))
3975 (vmarkers (mapconcat
3976 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3977 org-emphasis-alist "")))
3978 ;; make sure special characters appear at the right position in the class
3979 (if (string-match "\\^" markers)
3980 (setq markers (concat (replace-match "" t t markers) "^")))
3981 (if (string-match "-" markers)
3982 (setq markers (concat (replace-match "" t t markers) "-")))
3983 (if (string-match "\\^" vmarkers)
3984 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3985 (if (string-match "-" vmarkers)
3986 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3987 (if (> nl 0)
3988 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3989 (int-to-string nl) "\\}")))
3990 ;; Make the regexp
3991 (setq org-emph-re
3992 (concat "\\([" pre "]\\|^\\)"
3993 "\\("
3994 "\\([" markers "]\\)"
3995 "\\("
3996 "[^" border "]\\|"
3997 "[^" border "]"
3998 body1
3999 "[^" border "]"
4000 "\\)"
4001 "\\3\\)"
4002 "\\([" post "]\\|$\\)"))
4003 (setq org-verbatim-re
4004 (concat "\\([" pre "]\\|^\\)"
4005 "\\("
4006 "\\([" vmarkers "]\\)"
4007 "\\("
4008 "[^" border "]\\|"
4009 "[^" border "]"
4010 body1
4011 "[^" border "]"
4012 "\\)"
4013 "\\3\\)"
4014 "\\([" post "]\\|$\\)")))))
4016 (defcustom org-emphasis-regexp-components
4017 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4018 "Components used to build the regular expression for emphasis.
4019 This is a list with five entries. Terminology: In an emphasis string
4020 like \" *strong word* \", we call the initial space PREMATCH, the final
4021 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4022 and \"trong wor\" is the body. The different components in this variable
4023 specify what is allowed/forbidden in each part:
4025 pre Chars allowed as prematch. Beginning of line will be allowed too.
4026 post Chars allowed as postmatch. End of line will be allowed too.
4027 border The chars *forbidden* as border characters.
4028 body-regexp A regexp like \".\" to match a body character. Don't use
4029 non-shy groups here, and don't allow newline here.
4030 newline The maximum number of newlines allowed in an emphasis exp.
4032 Use customize to modify this, or restart Emacs after changing it."
4033 :group 'org-appearance
4034 :set 'org-set-emph-re
4035 :type '(list
4036 (sexp :tag "Allowed chars in pre ")
4037 (sexp :tag "Allowed chars in post ")
4038 (sexp :tag "Forbidden chars in border ")
4039 (sexp :tag "Regexp for body ")
4040 (integer :tag "number of newlines allowed")
4041 (option (boolean :tag "Please ignore this button"))))
4043 (defcustom org-emphasis-alist
4044 `(("*" bold "<b>" "</b>")
4045 ("/" italic "<i>" "</i>")
4046 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
4047 ("=" org-code "<code>" "</code>" verbatim)
4048 ("~" org-verbatim "<code>" "</code>" verbatim)
4049 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
4050 "<del>" "</del>")
4052 "Special syntax for emphasized text.
4053 Text starting and ending with a special character will be emphasized, for
4054 example *bold*, _underlined_ and /italic/. This variable sets the marker
4055 characters, the face to be used by font-lock for highlighting in Org-mode
4056 Emacs buffers, and the HTML tags to be used for this.
4057 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
4058 Use customize to modify this, or restart Emacs after changing it."
4059 :group 'org-appearance
4060 :set 'org-set-emph-re
4061 :type '(repeat
4062 (list
4063 (string :tag "Marker character")
4064 (choice
4065 (face :tag "Font-lock-face")
4066 (plist :tag "Face property list"))
4067 (string :tag "HTML start tag")
4068 (string :tag "HTML end tag")
4069 (option (const verbatim)))))
4071 (defvar org-protecting-blocks
4072 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4073 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4074 This is needed for font-lock setup.")
4076 ;;; Miscellaneous options
4078 (defgroup org-completion nil
4079 "Completion in Org-mode."
4080 :tag "Org Completion"
4081 :group 'org)
4083 (defcustom org-completion-use-ido nil
4084 "Non-nil means use ido completion wherever possible.
4085 Note that `ido-mode' must be active for this variable to be relevant.
4086 If you decide to turn this variable on, you might well want to turn off
4087 `org-outline-path-complete-in-steps'.
4088 See also `org-completion-use-iswitchb'."
4089 :group 'org-completion
4090 :type 'boolean)
4092 (defcustom org-completion-use-iswitchb nil
4093 "Non-nil means use iswitchb completion wherever possible.
4094 Note that `iswitchb-mode' must be active for this variable to be relevant.
4095 If you decide to turn this variable on, you might well want to turn off
4096 `org-outline-path-complete-in-steps'.
4097 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4098 :group 'org-completion
4099 :type 'boolean)
4101 (defcustom org-completion-fallback-command 'hippie-expand
4102 "The expansion command called by \\[pcomplete] in normal context.
4103 Normal means, no org-mode-specific context."
4104 :group 'org-completion
4105 :type 'function)
4107 ;;; Functions and variables from their packages
4108 ;; Declared here to avoid compiler warnings
4110 ;; XEmacs only
4111 (defvar outline-mode-menu-heading)
4112 (defvar outline-mode-menu-show)
4113 (defvar outline-mode-menu-hide)
4114 (defvar zmacs-regions) ; XEmacs regions
4116 ;; Emacs only
4117 (defvar mark-active)
4119 ;; Various packages
4120 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4121 (declare-function calendar-forward-day "cal-move" (arg))
4122 (declare-function calendar-goto-date "cal-move" (date))
4123 (declare-function calendar-goto-today "cal-move" ())
4124 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4125 (defvar calc-embedded-close-formula)
4126 (defvar calc-embedded-open-formula)
4127 (declare-function cdlatex-tab "ext:cdlatex" ())
4128 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4129 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4130 (defvar font-lock-unfontify-region-function)
4131 (declare-function iswitchb-read-buffer "iswitchb"
4132 (prompt &optional default require-match start matches-set))
4133 (defvar iswitchb-temp-buflist)
4134 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4135 (defvar org-agenda-tags-todo-honor-ignore-options)
4136 (declare-function org-agenda-skip "org-agenda" ())
4137 (declare-function
4138 org-agenda-format-item "org-agenda"
4139 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4140 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4141 (declare-function org-agenda-change-all-lines "org-agenda"
4142 (newhead hdmarker &optional fixface just-this))
4143 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4144 (declare-function org-agenda-maybe-redo "org-agenda" ())
4145 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4146 (beg end))
4147 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4148 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4149 "org-agenda" (&optional end))
4150 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4151 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4152 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4153 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4154 (declare-function org-indent-mode "org-indent" (&optional arg))
4155 (declare-function parse-time-string "parse-time" (string))
4156 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4157 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4158 (defvar remember-data-file)
4159 (defvar texmathp-why)
4160 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4161 (declare-function table--at-cell-p "table" (position &optional object at-column))
4163 (defvar org-latex-regexps)
4165 ;;; Autoload and prepare some org modules
4167 ;; Some table stuff that needs to be defined here, because it is used
4168 ;; by the functions setting up org-mode or checking for table context.
4170 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4171 "Detect an org-type or table-type table.")
4172 (defconst org-table-line-regexp "^[ \t]*|"
4173 "Detect an org-type table line.")
4174 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4175 "Detect an org-type table line.")
4176 (defconst org-table-hline-regexp "^[ \t]*|-"
4177 "Detect an org-type table hline.")
4178 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4179 "Detect a table-type table hline.")
4180 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4181 "Detect the first line outside a table when searching from within it.
4182 This works for both table types.")
4184 ;; Autoload the functions in org-table.el that are needed by functions here.
4186 (eval-and-compile
4187 (org-autoload "org-table"
4188 '(org-table-begin org-table-blank-field org-table-end)))
4190 ;;;###autoload
4191 (defun turn-on-orgtbl ()
4192 "Unconditionally turn on `orgtbl-mode'."
4193 (require 'org-table)
4194 (orgtbl-mode 1))
4196 (defun org-at-table-p (&optional table-type)
4197 "Return t if the cursor is inside an org-type table.
4198 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4199 (if org-enable-table-editor
4200 (save-excursion
4201 (beginning-of-line 1)
4202 (looking-at (if table-type org-table-any-line-regexp
4203 org-table-line-regexp)))
4204 nil))
4205 (defsubst org-table-p () (org-at-table-p))
4207 (defun org-at-table.el-p ()
4208 "Return t if and only if we are at a table.el table."
4209 (and (org-at-table-p 'any)
4210 (save-excursion
4211 (goto-char (org-table-begin 'any))
4212 (looking-at org-table1-hline-regexp))))
4214 (defun org-table-recognize-table.el ()
4215 "If there is a table.el table nearby, recognize it and move into it."
4216 (if org-table-tab-recognizes-table.el
4217 (if (org-at-table.el-p)
4218 (progn
4219 (beginning-of-line 1)
4220 (if (looking-at org-table-dataline-regexp)
4222 (if (looking-at org-table1-hline-regexp)
4223 (progn
4224 (beginning-of-line 2)
4225 (if (looking-at org-table-any-border-regexp)
4226 (beginning-of-line -1)))))
4227 (if (re-search-forward "|" (org-table-end t) t)
4228 (progn
4229 (require 'table)
4230 (if (table--at-cell-p (point))
4232 (message "recognizing table.el table...")
4233 (table-recognize-table)
4234 (message "recognizing table.el table...done")))
4235 (error "This should not happen"))
4237 nil)
4238 nil))
4240 (defun org-at-table-hline-p ()
4241 "Return t if the cursor is inside a hline in a table."
4242 (if org-enable-table-editor
4243 (save-excursion
4244 (beginning-of-line 1)
4245 (looking-at org-table-hline-regexp))
4246 nil))
4248 (defvar org-table-clean-did-remove-column nil)
4249 (defun org-table-map-tables (function &optional quietly)
4250 "Apply FUNCTION to the start of all tables in the buffer."
4251 (save-excursion
4252 (save-restriction
4253 (widen)
4254 (goto-char (point-min))
4255 (while (re-search-forward org-table-any-line-regexp nil t)
4256 (unless quietly
4257 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4258 (beginning-of-line 1)
4259 (when (and (looking-at org-table-line-regexp)
4260 ;; Exclude tables in src/example/verbatim/clocktable blocks
4261 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4262 (save-excursion (funcall function))
4263 (or (looking-at org-table-line-regexp)
4264 (forward-char 1)))
4265 (re-search-forward org-table-any-border-regexp nil 1))))
4266 (unless quietly (message "Mapping tables: done")))
4268 ;; Declare and autoload functions from ox.el and al.
4270 (declare-function org-export-get-environment "ox"
4271 (&optional backend subtreep ext-plist))
4272 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4274 ;; Declare and autoload functions from org-agenda.el
4276 (eval-and-compile
4277 (org-autoload "org-agenda"
4278 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4280 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4281 (declare-function org-clock-update-mode-line "org-clock" ())
4282 (declare-function org-resolve-clocks "org-clock"
4283 (&optional also-non-dangling-p prompt last-valid))
4284 (defvar org-clock-start-time)
4285 (defvar org-clock-marker (make-marker)
4286 "Marker recording the last clock-in.")
4287 (defvar org-clock-hd-marker (make-marker)
4288 "Marker recording the last clock-in, but the headline position.")
4289 (defvar org-clock-heading ""
4290 "The heading of the current clock entry.")
4291 (defun org-clock-is-active ()
4292 "Return non-nil if clock is currently running.
4293 The return value is actually the clock marker."
4294 (marker-buffer org-clock-marker))
4296 (eval-and-compile
4297 (org-autoload "org-clock" '(org-clock-remove-overlays
4298 org-clock-update-time-maybe
4299 org-clocktable-shift)))
4301 (defun org-check-running-clock ()
4302 "Check if the current buffer contains the running clock.
4303 If yes, offer to stop it and to save the buffer with the changes."
4304 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4305 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4306 (buffer-name))))
4307 (org-clock-out)
4308 (when (y-or-n-p "Save changed buffer?")
4309 (save-buffer))))
4311 (defun org-clocktable-try-shift (dir n)
4312 "Check if this line starts a clock table, if yes, shift the time block."
4313 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4314 (org-clocktable-shift dir n)))
4316 ;;;###autoload
4317 (defun org-clock-persistence-insinuate ()
4318 "Set up hooks for clock persistence."
4319 (require 'org-clock)
4320 (add-hook 'org-mode-hook 'org-clock-load)
4321 (add-hook 'kill-emacs-hook 'org-clock-save))
4323 ;; Define the variable already here, to make sure we have it.
4324 (defvar org-indent-mode nil
4325 "Non-nil if Org-Indent mode is enabled.
4326 Use the command `org-indent-mode' to change this variable.")
4328 ;; Autoload archiving code
4329 ;; The stuff that is needed for cycling and tags has to be defined here.
4331 (defgroup org-archive nil
4332 "Options concerning archiving in Org-mode."
4333 :tag "Org Archive"
4334 :group 'org-structure)
4336 (defcustom org-archive-location "%s_archive::"
4337 "The location where subtrees should be archived.
4339 The value of this variable is a string, consisting of two parts,
4340 separated by a double-colon. The first part is a filename and
4341 the second part is a headline.
4343 When the filename is omitted, archiving happens in the same file.
4344 %s in the filename will be replaced by the current file
4345 name (without the directory part). Archiving to a different file
4346 is useful to keep archived entries from contributing to the
4347 Org-mode Agenda.
4349 The archived entries will be filed as subtrees of the specified
4350 headline. When the headline is omitted, the subtrees are simply
4351 filed away at the end of the file, as top-level entries. Also in
4352 the heading you can use %s to represent the file name, this can be
4353 useful when using the same archive for a number of different files.
4355 Here are a few examples:
4356 \"%s_archive::\"
4357 If the current file is Projects.org, archive in file
4358 Projects.org_archive, as top-level trees. This is the default.
4360 \"::* Archived Tasks\"
4361 Archive in the current file, under the top-level headline
4362 \"* Archived Tasks\".
4364 \"~/org/archive.org::\"
4365 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4367 \"~/org/archive.org::* From %s\"
4368 Archive in file ~/org/archive.org (absolute path), under headlines
4369 \"From FILENAME\" where file name is the current file name.
4371 \"~/org/datetree.org::datetree/* Finished Tasks\"
4372 The \"datetree/\" string is special, signifying to archive
4373 items to the datetree. Items are placed in either the CLOSED
4374 date of the item, or the current date if there is no CLOSED date.
4375 The heading will be a subentry to the current date. There doesn't
4376 need to be a heading, but there always needs to be a slash after
4377 datetree. For example, to store archived items directly in the
4378 datetree, use \"~/org/datetree.org::datetree/\".
4380 \"basement::** Finished Tasks\"
4381 Archive in file ./basement (relative path), as level 3 trees
4382 below the level 2 heading \"** Finished Tasks\".
4384 You may set this option on a per-file basis by adding to the buffer a
4385 line like
4387 #+ARCHIVE: basement::** Finished Tasks
4389 You may also define it locally for a subtree by setting an ARCHIVE property
4390 in the entry. If such a property is found in an entry, or anywhere up
4391 the hierarchy, it will be used."
4392 :group 'org-archive
4393 :type 'string)
4395 (defcustom org-archive-tag "ARCHIVE"
4396 "The tag that marks a subtree as archived.
4397 An archived subtree does not open during visibility cycling, and does
4398 not contribute to the agenda listings.
4399 After changing this, font-lock must be restarted in the relevant buffers to
4400 get the proper fontification."
4401 :group 'org-archive
4402 :group 'org-keywords
4403 :type 'string)
4405 (defcustom org-agenda-skip-archived-trees t
4406 "Non-nil means the agenda will skip any items located in archived trees.
4407 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4408 variable is no longer recommended, you should leave it at the value t.
4409 Instead, use the key `v' to cycle the archives-mode in the agenda."
4410 :group 'org-archive
4411 :group 'org-agenda-skip
4412 :type 'boolean)
4414 (defcustom org-columns-skip-archived-trees t
4415 "Non-nil means ignore archived trees when creating column view."
4416 :group 'org-archive
4417 :group 'org-properties
4418 :type 'boolean)
4420 (defcustom org-cycle-open-archived-trees nil
4421 "Non-nil means `org-cycle' will open archived trees.
4422 An archived tree is a tree marked with the tag ARCHIVE.
4423 When nil, archived trees will stay folded. You can still open them with
4424 normal outline commands like `show-all', but not with the cycling commands."
4425 :group 'org-archive
4426 :group 'org-cycle
4427 :type 'boolean)
4429 (defcustom org-sparse-tree-open-archived-trees nil
4430 "Non-nil means sparse tree construction shows matches in archived trees.
4431 When nil, matches in these trees are highlighted, but the trees are kept in
4432 collapsed state."
4433 :group 'org-archive
4434 :group 'org-sparse-trees
4435 :type 'boolean)
4437 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4438 "The default date type when building a sparse tree.
4439 When this is nil, a date is a scheduled or a deadline timestamp.
4440 Otherwise, these types are allowed:
4442 all: all timestamps
4443 active: only active timestamps (<...>)
4444 inactive: only inactive timestamps (<...)
4445 scheduled: only scheduled timestamps
4446 deadline: only deadline timestamps"
4447 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4448 (const :tag "All timestamps" all)
4449 (const :tag "Only active timestamps" active)
4450 (const :tag "Only inactive timestamps" inactive)
4451 (const :tag "Only scheduled timestamps" scheduled)
4452 (const :tag "Only deadline timestamps" deadline))
4453 :version "24.3"
4454 :group 'org-sparse-trees)
4456 (defun org-cycle-hide-archived-subtrees (state)
4457 "Re-hide all archived subtrees after a visibility state change."
4458 (when (and (not org-cycle-open-archived-trees)
4459 (not (memq state '(overview folded))))
4460 (save-excursion
4461 (let* ((globalp (memq state '(contents all)))
4462 (beg (if globalp (point-min) (point)))
4463 (end (if globalp (point-max) (org-end-of-subtree t))))
4464 (org-hide-archived-subtrees beg end)
4465 (goto-char beg)
4466 (if (looking-at (concat ".*:" org-archive-tag ":"))
4467 (message "%s" (substitute-command-keys
4468 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4470 (defun org-force-cycle-archived ()
4471 "Cycle subtree even if it is archived."
4472 (interactive)
4473 (setq this-command 'org-cycle)
4474 (let ((org-cycle-open-archived-trees t))
4475 (call-interactively 'org-cycle)))
4477 (defun org-hide-archived-subtrees (beg end)
4478 "Re-hide all archived subtrees after a visibility state change."
4479 (save-excursion
4480 (let* ((re (concat ":" org-archive-tag ":")))
4481 (goto-char beg)
4482 (while (re-search-forward re end t)
4483 (when (org-at-heading-p)
4484 (org-flag-subtree t)
4485 (org-end-of-subtree t))))))
4487 (declare-function outline-end-of-heading "outline" ())
4488 (declare-function outline-flag-region "outline" (from to flag))
4489 (defun org-flag-subtree (flag)
4490 (save-excursion
4491 (org-back-to-heading t)
4492 (outline-end-of-heading)
4493 (outline-flag-region (point)
4494 (progn (org-end-of-subtree t) (point))
4495 flag)))
4497 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4499 (eval-and-compile
4500 (org-autoload "org-archive"
4501 '(org-add-archive-files)))
4503 ;; Autoload Column View Code
4505 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4506 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4507 (declare-function org-columns-compute "org-colview" (property))
4509 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4510 '(org-columns-number-to-string
4511 org-columns-get-format-and-top-level
4512 org-columns-compute
4513 org-columns-remove-overlays))
4515 ;; Autoload ID code
4517 (declare-function org-id-store-link "org-id")
4518 (declare-function org-id-locations-load "org-id")
4519 (declare-function org-id-locations-save "org-id")
4520 (defvar org-id-track-globally)
4521 (org-autoload "org-id"
4522 '(org-id-new
4523 org-id-copy
4524 org-id-get-with-outline-path-completion
4525 org-id-get-with-outline-drilling))
4527 ;;; Variables for pre-computed regular expressions, all buffer local
4529 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4530 "Matches first line of a hidden block.")
4531 (make-variable-buffer-local 'org-drawer-regexp)
4532 (defvar org-todo-regexp nil
4533 "Matches any of the TODO state keywords.")
4534 (make-variable-buffer-local 'org-todo-regexp)
4535 (defvar org-not-done-regexp nil
4536 "Matches any of the TODO state keywords except the last one.")
4537 (make-variable-buffer-local 'org-not-done-regexp)
4538 (defvar org-not-done-heading-regexp nil
4539 "Matches a TODO headline that is not done.")
4540 (make-variable-buffer-local 'org-not-done-regexp)
4541 (defvar org-todo-line-regexp nil
4542 "Matches a headline and puts TODO state into group 2 if present.")
4543 (make-variable-buffer-local 'org-todo-line-regexp)
4544 (defvar org-complex-heading-regexp nil
4545 "Matches a headline and puts everything into groups:
4546 group 1: the stars
4547 group 2: The todo keyword, maybe
4548 group 3: Priority cookie
4549 group 4: True headline
4550 group 5: Tags")
4551 (make-variable-buffer-local 'org-complex-heading-regexp)
4552 (defvar org-complex-heading-regexp-format nil
4553 "Printf format to make regexp to match an exact headline.
4554 This regexp will match the headline of any node which has the
4555 exact headline text that is put into the format, but may have any
4556 TODO state, priority and tags.")
4557 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4558 (defvar org-todo-line-tags-regexp nil
4559 "Matches a headline and puts TODO state into group 2 if present.
4560 Also put tags into group 4 if tags are present.")
4561 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4562 (defvar org-ds-keyword-length 12
4563 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4564 (make-variable-buffer-local 'org-ds-keyword-length)
4565 (defvar org-deadline-regexp nil
4566 "Matches the DEADLINE keyword.")
4567 (make-variable-buffer-local 'org-deadline-regexp)
4568 (defvar org-deadline-time-regexp nil
4569 "Matches the DEADLINE keyword together with a time stamp.")
4570 (make-variable-buffer-local 'org-deadline-time-regexp)
4571 (defvar org-deadline-time-hour-regexp nil
4572 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4573 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4574 (defvar org-deadline-line-regexp nil
4575 "Matches the DEADLINE keyword and the rest of the line.")
4576 (make-variable-buffer-local 'org-deadline-line-regexp)
4577 (defvar org-scheduled-regexp nil
4578 "Matches the SCHEDULED keyword.")
4579 (make-variable-buffer-local 'org-scheduled-regexp)
4580 (defvar org-scheduled-time-regexp nil
4581 "Matches the SCHEDULED keyword together with a time stamp.")
4582 (make-variable-buffer-local 'org-scheduled-time-regexp)
4583 (defvar org-scheduled-time-hour-regexp nil
4584 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4585 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4586 (defvar org-closed-time-regexp nil
4587 "Matches the CLOSED keyword together with a time stamp.")
4588 (make-variable-buffer-local 'org-closed-time-regexp)
4590 (defvar org-keyword-time-regexp nil
4591 "Matches any of the 4 keywords, together with the time stamp.")
4592 (make-variable-buffer-local 'org-keyword-time-regexp)
4593 (defvar org-keyword-time-not-clock-regexp nil
4594 "Matches any of the 3 keywords, together with the time stamp.")
4595 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4596 (defvar org-maybe-keyword-time-regexp nil
4597 "Matches a timestamp, possibly preceded by a keyword.")
4598 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4599 (defvar org-all-time-keywords nil
4600 "List of time keywords.")
4601 (make-variable-buffer-local 'org-all-time-keywords)
4603 (defconst org-plain-time-of-day-regexp
4604 (concat
4605 "\\(\\<[012]?[0-9]"
4606 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4607 "\\(--?"
4608 "\\(\\<[012]?[0-9]"
4609 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4610 "\\)?")
4611 "Regular expression to match a plain time or time range.
4612 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4613 groups carry important information:
4614 0 the full match
4615 1 the first time, range or not
4616 8 the second time, if it is a range.")
4618 (defconst org-plain-time-extension-regexp
4619 (concat
4620 "\\(\\<[012]?[0-9]"
4621 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4622 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4623 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4624 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4625 groups carry important information:
4626 0 the full match
4627 7 hours of duration
4628 9 minutes of duration")
4630 (defconst org-stamp-time-of-day-regexp
4631 (concat
4632 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4633 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4634 "\\(--?"
4635 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4636 "Regular expression to match a timestamp time or time range.
4637 After a match, the following groups carry important information:
4638 0 the full match
4639 1 date plus weekday, for back referencing to make sure both times are on the same day
4640 2 the first time, range or not
4641 4 the second time, if it is a range.")
4643 (defconst org-startup-options
4644 '(("fold" org-startup-folded t)
4645 ("overview" org-startup-folded t)
4646 ("nofold" org-startup-folded nil)
4647 ("showall" org-startup-folded nil)
4648 ("showeverything" org-startup-folded showeverything)
4649 ("content" org-startup-folded content)
4650 ("indent" org-startup-indented t)
4651 ("noindent" org-startup-indented nil)
4652 ("hidestars" org-hide-leading-stars t)
4653 ("showstars" org-hide-leading-stars nil)
4654 ("odd" org-odd-levels-only t)
4655 ("oddeven" org-odd-levels-only nil)
4656 ("align" org-startup-align-all-tables t)
4657 ("noalign" org-startup-align-all-tables nil)
4658 ("inlineimages" org-startup-with-inline-images t)
4659 ("noinlineimages" org-startup-with-inline-images nil)
4660 ("latexpreview" org-startup-with-latex-preview t)
4661 ("nolatexpreview" org-startup-with-latex-preview nil)
4662 ("customtime" org-display-custom-times t)
4663 ("logdone" org-log-done time)
4664 ("lognotedone" org-log-done note)
4665 ("nologdone" org-log-done nil)
4666 ("lognoteclock-out" org-log-note-clock-out t)
4667 ("nolognoteclock-out" org-log-note-clock-out nil)
4668 ("logrepeat" org-log-repeat state)
4669 ("lognoterepeat" org-log-repeat note)
4670 ("logdrawer" org-log-into-drawer t)
4671 ("nologdrawer" org-log-into-drawer nil)
4672 ("logstatesreversed" org-log-states-order-reversed t)
4673 ("nologstatesreversed" org-log-states-order-reversed nil)
4674 ("nologrepeat" org-log-repeat nil)
4675 ("logreschedule" org-log-reschedule time)
4676 ("lognotereschedule" org-log-reschedule note)
4677 ("nologreschedule" org-log-reschedule nil)
4678 ("logredeadline" org-log-redeadline time)
4679 ("lognoteredeadline" org-log-redeadline note)
4680 ("nologredeadline" org-log-redeadline nil)
4681 ("logrefile" org-log-refile time)
4682 ("lognoterefile" org-log-refile note)
4683 ("nologrefile" org-log-refile nil)
4684 ("fninline" org-footnote-define-inline t)
4685 ("nofninline" org-footnote-define-inline nil)
4686 ("fnlocal" org-footnote-section nil)
4687 ("fnauto" org-footnote-auto-label t)
4688 ("fnprompt" org-footnote-auto-label nil)
4689 ("fnconfirm" org-footnote-auto-label confirm)
4690 ("fnplain" org-footnote-auto-label plain)
4691 ("fnadjust" org-footnote-auto-adjust t)
4692 ("nofnadjust" org-footnote-auto-adjust nil)
4693 ("constcgs" constants-unit-system cgs)
4694 ("constSI" constants-unit-system SI)
4695 ("noptag" org-tag-persistent-alist nil)
4696 ("hideblocks" org-hide-block-startup t)
4697 ("nohideblocks" org-hide-block-startup nil)
4698 ("beamer" org-startup-with-beamer-mode t)
4699 ("entitiespretty" org-pretty-entities t)
4700 ("entitiesplain" org-pretty-entities nil))
4701 "Variable associated with STARTUP options for org-mode.
4702 Each element is a list of three items: the startup options (as written
4703 in the #+STARTUP line), the corresponding variable, and the value to set
4704 this variable to if the option is found. An optional forth element PUSH
4705 means to push this value onto the list in the variable.")
4707 (defun org-update-property-plist (key val props)
4708 "Update PROPS with KEY and VAL."
4709 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4710 (key (if appending (substring key 0 (- (length key) 1)) key))
4711 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4712 (previous (cdr (assoc key props))))
4713 (if appending
4714 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4715 (cons (cons key val) remainder))))
4717 (defconst org-block-regexp
4718 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4719 "Regular expression for hiding blocks.")
4720 (defconst org-heading-keyword-regexp-format
4721 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4722 "Printf format for a regexp matching a headline with some keyword.
4723 This regexp will match the headline of any node which has the
4724 exact keyword that is put into the format. The keyword isn't in
4725 any group by default, but the stars and the body are.")
4726 (defconst org-heading-keyword-maybe-regexp-format
4727 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4728 "Printf format for a regexp matching a headline, possibly with some keyword.
4729 This regexp can match any headline with the specified keyword, or
4730 without a keyword. The keyword isn't in any group by default,
4731 but the stars and the body are.")
4733 (defun org-set-regexps-and-options ()
4734 "Precompute regular expressions for current buffer."
4735 (when (derived-mode-p 'org-mode)
4736 (org-set-local 'org-todo-kwd-alist nil)
4737 (org-set-local 'org-todo-key-alist nil)
4738 (org-set-local 'org-todo-key-trigger nil)
4739 (org-set-local 'org-todo-keywords-1 nil)
4740 (org-set-local 'org-done-keywords nil)
4741 (org-set-local 'org-todo-heads nil)
4742 (org-set-local 'org-todo-sets nil)
4743 (org-set-local 'org-todo-log-states nil)
4744 (org-set-local 'org-file-properties nil)
4745 (org-set-local 'org-file-tags nil)
4746 (let ((re (org-make-options-regexp
4747 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE" "FILETAGS"
4748 "TAGS" "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4749 "SETUPFILE" "OPTIONS")
4750 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4751 (splitre "[ \t]+")
4752 (scripts org-use-sub-superscripts)
4753 kwds kws0 kwsa key log value cat arch tags const links hw dws
4754 tail sep kws1 prio props ftags drawers ext-setup-or-nil setup-contents
4755 (start 0))
4756 (save-excursion
4757 (save-restriction
4758 (widen)
4759 (goto-char (point-min))
4760 (while (or (and ext-setup-or-nil
4761 (string-match re ext-setup-or-nil start)
4762 (setq start (match-end 0)))
4763 (and (setq ext-setup-or-nil nil start 0)
4764 (re-search-forward re nil t)))
4765 (setq key (upcase (match-string 1 ext-setup-or-nil))
4766 value (org-match-string-no-properties 2 ext-setup-or-nil))
4767 (if (stringp value) (setq value (org-trim value)))
4768 (cond
4769 ((equal key "CATEGORY")
4770 (setq cat value))
4771 ((member key '("SEQ_TODO" "TODO"))
4772 (push (cons 'sequence (org-split-string value splitre)) kwds))
4773 ((equal key "TYP_TODO")
4774 (push (cons 'type (org-split-string value splitre)) kwds))
4775 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4776 ;; general TODO-like setup
4777 (push (cons (intern (downcase (match-string 1 key)))
4778 (org-split-string value splitre)) kwds))
4779 ((equal key "TAGS")
4780 (setq tags (append tags (if tags '("\\n") nil)
4781 (org-split-string value splitre))))
4782 ((equal key "COLUMNS")
4783 (org-set-local 'org-columns-default-format value))
4784 ((equal key "LINK")
4785 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4786 (push (cons (match-string 1 value)
4787 (org-trim (match-string 2 value)))
4788 links)))
4789 ((equal key "PRIORITIES")
4790 (setq prio (org-split-string value " +")))
4791 ((equal key "PROPERTY")
4792 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4793 (setq props (org-update-property-plist (match-string 1 value)
4794 (match-string 2 value)
4795 props))))
4796 ((equal key "FILETAGS")
4797 (when (string-match "\\S-" value)
4798 (setq ftags
4799 (append
4800 ftags
4801 (apply 'append
4802 (mapcar (lambda (x) (org-split-string x ":"))
4803 (org-split-string value)))))))
4804 ((equal key "DRAWERS")
4805 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4806 ((equal key "CONSTANTS")
4807 (setq const (append const (org-split-string value splitre))))
4808 ((equal key "STARTUP")
4809 (let ((opts (org-split-string value splitre))
4810 l var val)
4811 (while (setq l (pop opts))
4812 (when (setq l (assoc l org-startup-options))
4813 (setq var (nth 1 l) val (nth 2 l))
4814 (if (not (nth 3 l))
4815 (set (make-local-variable var) val)
4816 (if (not (listp (symbol-value var)))
4817 (set (make-local-variable var) nil))
4818 (set (make-local-variable var) (symbol-value var))
4819 (add-to-list var val))))))
4820 ((equal key "ARCHIVE")
4821 (setq arch value)
4822 (remove-text-properties 0 (length arch)
4823 '(face t fontified t) arch))
4824 ((equal key "OPTIONS")
4825 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4826 (setq scripts (read (match-string 2 value)))))
4827 ((equal key "SETUPFILE")
4828 (setq setup-contents (org-file-contents
4829 (expand-file-name
4830 (org-remove-double-quotes value))
4831 'noerror))
4832 (if (not ext-setup-or-nil)
4833 (setq ext-setup-or-nil setup-contents start 0)
4834 (setq ext-setup-or-nil
4835 (concat (substring ext-setup-or-nil 0 start)
4836 "\n" setup-contents "\n"
4837 (substring ext-setup-or-nil start)))))))
4838 ;; search for property blocks
4839 (goto-char (point-min))
4840 (while (re-search-forward org-block-regexp nil t)
4841 (when (equal "PROPERTY" (upcase (match-string 1)))
4842 (setq value (replace-regexp-in-string
4843 "[\n\r]" " " (match-string 4)))
4844 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4845 (setq props (org-update-property-plist (match-string 1 value)
4846 (match-string 2 value)
4847 props)))))))
4848 (org-set-local 'org-use-sub-superscripts scripts)
4849 (when cat
4850 (org-set-local 'org-category (intern cat))
4851 (push (cons "CATEGORY" cat) props))
4852 (when prio
4853 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4854 (setq prio (mapcar 'string-to-char prio))
4855 (org-set-local 'org-highest-priority (nth 0 prio))
4856 (org-set-local 'org-lowest-priority (nth 1 prio))
4857 (org-set-local 'org-default-priority (nth 2 prio)))
4858 (and props (org-set-local 'org-file-properties (nreverse props)))
4859 (and ftags (org-set-local 'org-file-tags
4860 (mapcar 'org-add-prop-inherited ftags)))
4861 (and drawers (org-set-local 'org-drawers drawers))
4862 (and arch (org-set-local 'org-archive-location arch))
4863 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4864 ;; Process the TODO keywords
4865 (unless kwds
4866 ;; Use the global values as if they had been given locally.
4867 (setq kwds (default-value 'org-todo-keywords))
4868 (if (stringp (car kwds))
4869 (setq kwds (list (cons org-todo-interpretation
4870 (default-value 'org-todo-keywords)))))
4871 (setq kwds (reverse kwds)))
4872 (setq kwds (nreverse kwds))
4873 (let (inter kws kw)
4874 (while (setq kws (pop kwds))
4875 (let ((kws (or
4876 (run-hook-with-args-until-success
4877 'org-todo-setup-filter-hook kws)
4878 kws)))
4879 (setq inter (pop kws) sep (member "|" kws)
4880 kws0 (delete "|" (copy-sequence kws))
4881 kwsa nil
4882 kws1 (mapcar
4883 (lambda (x)
4884 ;; 1 2
4885 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4886 (progn
4887 (setq kw (match-string 1 x)
4888 key (and (match-end 2) (match-string 2 x))
4889 log (org-extract-log-state-settings x))
4890 (push (cons kw (and key (string-to-char key))) kwsa)
4891 (and log (push log org-todo-log-states))
4893 (error "Invalid TODO keyword %s" x)))
4894 kws0)
4895 kwsa (if kwsa (append '((:startgroup))
4896 (nreverse kwsa)
4897 '((:endgroup))))
4898 hw (car kws1)
4899 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4900 tail (list inter hw (car dws) (org-last dws))))
4901 (add-to-list 'org-todo-heads hw 'append)
4902 (push kws1 org-todo-sets)
4903 (setq org-done-keywords (append org-done-keywords dws nil))
4904 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4905 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4906 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4907 (setq org-todo-sets (nreverse org-todo-sets)
4908 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4909 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4910 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4911 ;; Process the constants
4912 (when const
4913 (let (e cst)
4914 (while (setq e (pop const))
4915 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4916 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4917 (setq org-table-formula-constants-local cst)))
4919 ;; Process the tags.
4920 (when tags
4921 (let (e tgs)
4922 (while (setq e (pop tags))
4923 (cond
4924 ((equal e "{") (push '(:startgroup) tgs))
4925 ((equal e "}") (push '(:endgroup) tgs))
4926 ((equal e "\\n") (push '(:newline) tgs))
4927 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4928 (push (cons (match-string 1 e)
4929 (string-to-char (match-string 2 e)))
4930 tgs))
4931 (t (push (list e) tgs))))
4932 (org-set-local 'org-tag-alist nil)
4933 (while (setq e (pop tgs))
4934 (or (and (stringp (car e))
4935 (assoc (car e) org-tag-alist))
4936 (push e org-tag-alist)))))
4938 ;; Compute the regular expressions and other local variables.
4939 ;; Using `org-outline-regexp-bol' would complicate them much,
4940 ;; because of the fixed white space at the end of that string.
4941 (if (not org-done-keywords)
4942 (setq org-done-keywords (and org-todo-keywords-1
4943 (list (org-last org-todo-keywords-1)))))
4944 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4945 (length org-scheduled-string)
4946 (length org-clock-string)
4947 (length org-closed-string)))
4948 org-drawer-regexp
4949 (concat "^[ \t]*:\\("
4950 (mapconcat 'regexp-quote org-drawers "\\|")
4951 "\\):[ \t]*$")
4952 org-not-done-keywords
4953 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4954 org-todo-regexp
4955 (concat "\\("
4956 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4957 "\\)")
4958 org-not-done-regexp
4959 (concat "\\("
4960 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4961 "\\)")
4962 org-not-done-heading-regexp
4963 (format org-heading-keyword-regexp-format org-not-done-regexp)
4964 org-todo-line-regexp
4965 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4966 org-complex-heading-regexp
4967 (concat "^\\(\\*+\\)"
4968 "\\(?: +" org-todo-regexp "\\)?"
4969 "\\(?: +\\(\\[#.\\]\\)\\)?"
4970 "\\(?: +\\(.*?\\)\\)??"
4971 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4972 "[ \t]*$")
4973 org-complex-heading-regexp-format
4974 (concat "^\\(\\*+\\)"
4975 "\\(?: +" org-todo-regexp "\\)?"
4976 "\\(?: +\\(\\[#.\\]\\)\\)?"
4977 "\\(?: +"
4978 ;; Stats cookies can be stuck to body.
4979 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4980 "\\(%s\\)"
4981 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4982 "\\)"
4983 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4984 "[ \t]*$")
4985 org-todo-line-tags-regexp
4986 (concat "^\\(\\*+\\)"
4987 "\\(?: +" org-todo-regexp "\\)?"
4988 "\\(?: +\\(.*?\\)\\)??"
4989 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4990 "[ \t]*$")
4991 org-deadline-regexp (concat "\\<" org-deadline-string)
4992 org-deadline-time-regexp
4993 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4994 org-deadline-time-hour-regexp
4995 (concat "\\<" org-deadline-string
4996 " *<\\(.+[0-9]\\{1,2\\}:[0-9]\\{2\\}[^>]*\\)>")
4997 org-deadline-line-regexp
4998 (concat "\\<\\(" org-deadline-string "\\).*")
4999 org-scheduled-regexp
5000 (concat "\\<" org-scheduled-string)
5001 org-scheduled-time-regexp
5002 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5003 org-scheduled-time-hour-regexp
5004 (concat "\\<" org-scheduled-string
5005 " *<\\(.+[0-9]\\{1,2\\}:[0-9]\\{2\\}[^>]*\\)>")
5006 org-closed-time-regexp
5007 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5008 org-keyword-time-regexp
5009 (concat "\\<\\(" org-scheduled-string
5010 "\\|" org-deadline-string
5011 "\\|" org-closed-string
5012 "\\|" org-clock-string "\\)"
5013 " *[[<]\\([^]>]+\\)[]>]")
5014 org-keyword-time-not-clock-regexp
5015 (concat "\\<\\(" org-scheduled-string
5016 "\\|" org-deadline-string
5017 "\\|" org-closed-string
5018 "\\)"
5019 " *[[<]\\([^]>]+\\)[]>]")
5020 org-maybe-keyword-time-regexp
5021 (concat "\\(\\<\\(" org-scheduled-string
5022 "\\|" org-deadline-string
5023 "\\|" org-closed-string
5024 "\\|" org-clock-string "\\)\\)?"
5025 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5026 org-all-time-keywords
5027 (mapcar (lambda (w) (substring w 0 -1))
5028 (list org-scheduled-string org-deadline-string
5029 org-clock-string org-closed-string)))
5030 (org-compute-latex-and-related-regexp)
5031 (org-set-font-lock-defaults))))
5033 (defun org-file-contents (file &optional noerror)
5034 "Return the contents of FILE, as a string."
5035 (if (or (not file)
5036 (not (file-readable-p file)))
5037 (if noerror
5038 (progn
5039 (message "Cannot read file \"%s\"" file)
5040 (ding) (sit-for 2)
5042 (error "Cannot read file \"%s\"" file))
5043 (with-temp-buffer
5044 (insert-file-contents file)
5045 (buffer-string))))
5047 (defun org-extract-log-state-settings (x)
5048 "Extract the log state setting from a TODO keyword string.
5049 This will extract info from a string like \"WAIT(w@/!)\"."
5050 (let (kw key log1 log2)
5051 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5052 (setq kw (match-string 1 x)
5053 key (and (match-end 2) (match-string 2 x))
5054 log1 (and (match-end 3) (match-string 3 x))
5055 log2 (and (match-end 4) (match-string 4 x)))
5056 (and (or log1 log2)
5057 (list kw
5058 (and log1 (if (equal log1 "!") 'time 'note))
5059 (and log2 (if (equal log2 "!") 'time 'note)))))))
5061 (defun org-remove-keyword-keys (list)
5062 "Remove a pair of parenthesis at the end of each string in LIST."
5063 (mapcar (lambda (x)
5064 (if (string-match "(.*)$" x)
5065 (substring x 0 (match-beginning 0))
5067 list))
5069 (defun org-assign-fast-keys (alist)
5070 "Assign fast keys to a keyword-key alist.
5071 Respect keys that are already there."
5072 (let (new e (alt ?0))
5073 (while (setq e (pop alist))
5074 (if (or (memq (car e) '(:newline :endgroup :startgroup))
5075 (cdr e)) ;; Key already assigned.
5076 (push e new)
5077 (let ((clist (string-to-list (downcase (car e))))
5078 (used (append new alist)))
5079 (when (= (car clist) ?@)
5080 (pop clist))
5081 (while (and clist (rassoc (car clist) used))
5082 (pop clist))
5083 (unless clist
5084 (while (rassoc alt used)
5085 (incf alt)))
5086 (push (cons (car e) (or (car clist) alt)) new))))
5087 (nreverse new)))
5089 ;;; Some variables used in various places
5091 (defvar org-window-configuration nil
5092 "Used in various places to store a window configuration.")
5093 (defvar org-selected-window nil
5094 "Used in various places to store a window configuration.")
5095 (defvar org-finish-function nil
5096 "Function to be called when `C-c C-c' is used.
5097 This is for getting out of special buffers like capture.")
5100 ;; FIXME: Occasionally check by commenting these, to make sure
5101 ;; no other functions uses these, forgetting to let-bind them.
5102 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5103 (defvar org-last-state)
5104 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5106 ;; Defined somewhere in this file, but used before definition.
5107 (defvar org-entities) ;; defined in org-entities.el
5108 (defvar org-struct-menu)
5109 (defvar org-org-menu)
5110 (defvar org-tbl-menu)
5112 ;;;; Define the Org-mode
5114 ;; We use a before-change function to check if a table might need
5115 ;; an update.
5116 (defvar org-table-may-need-update t
5117 "Indicates that a table might need an update.
5118 This variable is set by `org-before-change-function'.
5119 `org-table-align' sets it back to nil.")
5120 (defun org-before-change-function (beg end)
5121 "Every change indicates that a table might need an update."
5122 (setq org-table-may-need-update t))
5123 (defvar org-mode-map)
5124 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5125 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5126 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5127 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5128 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5129 (defvar org-table-buffer-is-an nil)
5131 (defvar bidi-paragraph-direction)
5132 (defvar buffer-face-mode-face)
5134 (require 'outline)
5135 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5136 (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"))
5137 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5139 ;; Other stuff we need.
5140 (require 'time-date)
5141 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5142 (require 'easymenu)
5143 (require 'overlay)
5145 ;; (require 'org-macs) moved higher up in the file before it is first used
5146 (require 'org-entities)
5147 ;; (require 'org-compat) moved higher up in the file before it is first used
5148 (require 'org-faces)
5149 (require 'org-list)
5150 (require 'org-pcomplete)
5151 (require 'org-src)
5152 (require 'org-footnote)
5153 (require 'org-macro)
5155 ;; babel
5156 (require 'ob)
5158 ;;;###autoload
5159 (define-derived-mode org-mode outline-mode "Org"
5160 "Outline-based notes management and organizer, alias
5161 \"Carsten's outline-mode for keeping track of everything.\"
5163 Org-mode develops organizational tasks around a NOTES file which
5164 contains information about projects as plain text. Org-mode is
5165 implemented on top of outline-mode, which is ideal to keep the content
5166 of large files well structured. It supports ToDo items, deadlines and
5167 time stamps, which magically appear in the diary listing of the Emacs
5168 calendar. Tables are easily created with a built-in table editor.
5169 Plain text URL-like links connect to websites, emails (VM), Usenet
5170 messages (Gnus), BBDB entries, and any files related to the project.
5171 For printing and sharing of notes, an Org-mode file (or a part of it)
5172 can be exported as a structured ASCII or HTML file.
5174 The following commands are available:
5176 \\{org-mode-map}"
5178 ;; Get rid of Outline menus, they are not needed
5179 ;; Need to do this here because define-derived-mode sets up
5180 ;; the keymap so late. Still, it is a waste to call this each time
5181 ;; we switch another buffer into org-mode.
5182 (if (featurep 'xemacs)
5183 (when (boundp 'outline-mode-menu-heading)
5184 ;; Assume this is Greg's port, it uses easymenu
5185 (easy-menu-remove outline-mode-menu-heading)
5186 (easy-menu-remove outline-mode-menu-show)
5187 (easy-menu-remove outline-mode-menu-hide))
5188 (define-key org-mode-map [menu-bar headings] 'undefined)
5189 (define-key org-mode-map [menu-bar hide] 'undefined)
5190 (define-key org-mode-map [menu-bar show] 'undefined))
5192 (org-load-modules-maybe)
5193 (easy-menu-add org-org-menu)
5194 (easy-menu-add org-tbl-menu)
5195 (org-install-agenda-files-menu)
5196 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5197 (add-to-invisibility-spec '(org-cwidth))
5198 (add-to-invisibility-spec '(org-hide-block . t))
5199 (when (featurep 'xemacs)
5200 (org-set-local 'line-move-ignore-invisible t))
5201 (org-set-local 'outline-regexp org-outline-regexp)
5202 (org-set-local 'outline-level 'org-outline-level)
5203 (setq bidi-paragraph-direction 'left-to-right)
5204 ;; FIXME Circumvent a bug in outline.el (Emacs <24.4)
5205 (set (make-local-variable 'paragraph-start) "\f\\|[ \t]*$\\|\\*+ ")
5206 (when (and org-ellipsis
5207 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5208 (fboundp 'make-glyph-code))
5209 (unless org-display-table
5210 (setq org-display-table (make-display-table)))
5211 (set-display-table-slot
5212 org-display-table 4
5213 (vconcat (mapcar
5214 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5215 org-ellipsis)))
5216 (if (stringp org-ellipsis) org-ellipsis "..."))))
5217 (setq buffer-display-table org-display-table))
5218 (org-set-regexps-and-options)
5219 (when (and org-tag-faces (not org-tags-special-faces-re))
5220 ;; tag faces set outside customize.... force initialization.
5221 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5222 ;; Calc embedded
5223 (org-set-local 'calc-embedded-open-mode "# ")
5224 ;; Modify a few syntax entries
5225 (modify-syntax-entry ?@ "w")
5226 (modify-syntax-entry ?\" "\"")
5227 (if org-startup-truncated (setq truncate-lines t))
5228 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5229 (org-set-local 'font-lock-unfontify-region-function
5230 'org-unfontify-region)
5231 ;; Activate before-change-function
5232 (org-set-local 'org-table-may-need-update t)
5233 (org-add-hook 'before-change-functions 'org-before-change-function nil
5234 'local)
5235 ;; Check for running clock before killing a buffer
5236 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5237 ;; Initialize macros templates.
5238 (org-macro-initialize-templates)
5239 ;; Initialize radio targets.
5240 (org-update-radio-target-regexp)
5241 ;; Indentation.
5242 (org-set-local 'indent-line-function 'org-indent-line)
5243 (org-set-local 'indent-region-function 'org-indent-region)
5244 ;; Filling and auto-filling.
5245 (org-setup-filling)
5246 ;; Comments.
5247 (org-setup-comments-handling)
5248 ;; Beginning/end of defun
5249 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5250 (org-set-local 'end-of-defun-function 'org-forward-element)
5251 ;; Next error for sparse trees
5252 (org-set-local 'next-error-function 'org-occur-next-match)
5253 ;; Make sure dependence stuff works reliably, even for users who set it
5254 ;; too late :-(
5255 (if org-enforce-todo-dependencies
5256 (add-hook 'org-blocker-hook
5257 'org-block-todo-from-children-or-siblings-or-parent)
5258 (remove-hook 'org-blocker-hook
5259 'org-block-todo-from-children-or-siblings-or-parent))
5260 (if org-enforce-todo-checkbox-dependencies
5261 (add-hook 'org-blocker-hook
5262 'org-block-todo-from-checkboxes)
5263 (remove-hook 'org-blocker-hook
5264 'org-block-todo-from-checkboxes))
5266 ;; Align options lines
5267 (org-set-local
5268 'align-mode-rules-list
5269 '((org-in-buffer-settings
5270 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5271 (modes . '(org-mode)))))
5273 ;; Imenu
5274 (org-set-local 'imenu-create-index-function
5275 'org-imenu-get-tree)
5277 ;; Make isearch reveal context
5278 (if (or (featurep 'xemacs)
5279 (not (boundp 'outline-isearch-open-invisible-function)))
5280 ;; Emacs 21 and XEmacs make use of the hook
5281 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5282 ;; Emacs 22 deals with this through a special variable
5283 (org-set-local 'outline-isearch-open-invisible-function
5284 (lambda (&rest ignore) (org-show-context 'isearch)))
5285 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5287 ;; Setup the pcomplete hooks
5288 (set (make-local-variable 'pcomplete-command-completion-function)
5289 'org-pcomplete-initial)
5290 (set (make-local-variable 'pcomplete-command-name-function)
5291 'org-command-at-point)
5292 (set (make-local-variable 'pcomplete-default-completion-function)
5293 'ignore)
5294 (set (make-local-variable 'pcomplete-parse-arguments-function)
5295 'org-parse-arguments)
5296 (set (make-local-variable 'pcomplete-termination-string) "")
5297 (when (>= emacs-major-version 23)
5298 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5300 ;; If empty file that did not turn on org-mode automatically, make it to.
5301 (if (and org-insert-mode-line-in-empty-file
5302 (org-called-interactively-p 'any)
5303 (= (point-min) (point-max)))
5304 (insert "# -*- mode: org -*-\n\n"))
5305 (unless org-inhibit-startup
5306 (org-unmodified
5307 (and org-startup-with-beamer-mode (org-beamer-mode))
5308 (when org-startup-align-all-tables
5309 (org-table-map-tables 'org-table-align 'quietly))
5310 (when org-startup-with-inline-images
5311 (org-display-inline-images))
5312 (when org-startup-with-latex-preview
5313 (org-preview-latex-fragment))
5314 (unless org-inhibit-startup-visibility-stuff
5315 (org-set-startup-visibility))))
5316 ;; Try to set org-hide correctly
5317 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5319 ;; Update `customize-package-emacs-version-alist'
5320 (add-to-list 'customize-package-emacs-version-alist
5321 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5322 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5323 ("8.0" . "24.4")))
5325 (defvar org-mode-transpose-word-syntax-table
5326 (let ((st (make-syntax-table)))
5327 (mapc (lambda(c) (modify-syntax-entry
5328 (string-to-char (car c)) "w p" st))
5329 org-emphasis-alist)
5330 st))
5332 (when (fboundp 'abbrev-table-put)
5333 (abbrev-table-put org-mode-abbrev-table
5334 :parents (list text-mode-abbrev-table)))
5336 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5338 (defsubst org-fix-ellipsis-at-bol ()
5339 (save-excursion (goto-char (window-start)) (recenter 0)))
5341 (defun org-find-invisible-foreground ()
5342 (let ((candidates (remove
5343 "unspecified-bg"
5344 (nconc
5345 (list (face-background 'default)
5346 (face-background 'org-default))
5347 (mapcar
5348 (lambda (alist)
5349 (when (boundp alist)
5350 (cdr (assoc 'background-color (symbol-value alist)))))
5351 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5352 (list (face-foreground 'org-hide))))))
5353 (car (remove nil candidates))))
5355 (defun org-current-time (&optional rounding-minutes past)
5356 "Current time, possibly rounded to ROUNDING-MINUTES.
5357 When ROUNDING-MINUTES is not an integer, fall back on the car of
5358 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5359 the rounding returns a past time."
5360 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5361 (car org-time-stamp-rounding-minutes)))
5362 (time (decode-time)) res)
5363 (if (< r 1)
5364 (current-time)
5365 (setq res
5366 (apply 'encode-time
5367 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5368 (nthcdr 2 time))))
5369 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5370 (seconds-to-time (- (org-float-time res) (* r 60)))
5371 res))))
5373 (defun org-today ()
5374 "Return today date, considering `org-extend-today-until'."
5375 (time-to-days
5376 (time-subtract (current-time)
5377 (list 0 (* 3600 org-extend-today-until) 0))))
5379 ;;;; Font-Lock stuff, including the activators
5381 (defvar org-mouse-map (make-sparse-keymap))
5382 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5383 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5384 (when org-mouse-1-follows-link
5385 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5386 (when org-tab-follows-link
5387 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5388 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5390 (require 'font-lock)
5392 (defconst org-non-link-chars "]\t\n\r<>")
5393 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5394 "shell" "elisp" "doi" "message"))
5395 (defvar org-link-types-re nil
5396 "Matches a link that has a url-like prefix like \"http:\"")
5397 (defvar org-link-re-with-space nil
5398 "Matches a link with spaces, optional angular brackets around it.")
5399 (defvar org-link-re-with-space2 nil
5400 "Matches a link with spaces, optional angular brackets around it.")
5401 (defvar org-link-re-with-space3 nil
5402 "Matches a link with spaces, only for internal part in bracket links.")
5403 (defvar org-angle-link-re nil
5404 "Matches link with angular brackets, spaces are allowed.")
5405 (defvar org-plain-link-re nil
5406 "Matches plain link, without spaces.")
5407 (defvar org-bracket-link-regexp nil
5408 "Matches a link in double brackets.")
5409 (defvar org-bracket-link-analytic-regexp nil
5410 "Regular expression used to analyze links.
5411 Here is what the match groups contain after a match:
5412 1: http:
5413 2: http
5414 3: path
5415 4: [desc]
5416 5: desc")
5417 (defvar org-bracket-link-analytic-regexp++ nil
5418 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5419 (defvar org-any-link-re nil
5420 "Regular expression matching any link.")
5422 (defconst org-match-sexp-depth 3
5423 "Number of stacked braces for sub/superscript matching.")
5425 (defun org-create-multibrace-regexp (left right n)
5426 "Create a regular expression which will match a balanced sexp.
5427 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5428 as single character strings.
5429 The regexp returned will match the entire expression including the
5430 delimiters. It will also define a single group which contains the
5431 match except for the outermost delimiters. The maximum depth of
5432 stacked delimiters is N. Escaping delimiters is not possible."
5433 (let* ((nothing (concat "[^" left right "]*?"))
5434 (or "\\|")
5435 (re nothing)
5436 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5437 (while (> n 1)
5438 (setq n (1- n)
5439 re (concat re or next)
5440 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5441 (concat left "\\(" re "\\)" right)))
5443 (defvar org-match-substring-regexp
5444 (concat
5445 "\\(\\S-\\)\\([_^]\\)\\("
5446 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5447 "\\|"
5448 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5449 "\\|"
5450 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5451 "The regular expression matching a sub- or superscript.")
5453 (defvar org-match-substring-with-braces-regexp
5454 (concat
5455 "\\(\\S-\\)\\([_^]\\)\\("
5456 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5457 "\\)")
5458 "The regular expression matching a sub- or superscript, forcing braces.")
5460 (defun org-make-link-regexps ()
5461 "Update the link regular expressions.
5462 This should be called after the variable `org-link-types' has changed."
5463 (setq org-link-types-re
5464 (concat
5465 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5466 org-link-re-with-space
5467 (concat
5468 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5469 "\\([^" org-non-link-chars " ]"
5470 "[^" org-non-link-chars "]*"
5471 "[^" org-non-link-chars " ]\\)>?")
5472 org-link-re-with-space2
5473 (concat
5474 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5475 "\\([^" org-non-link-chars " ]"
5476 "[^\t\n\r]*"
5477 "[^" org-non-link-chars " ]\\)>?")
5478 org-link-re-with-space3
5479 (concat
5480 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5481 "\\([^" org-non-link-chars " ]"
5482 "[^\t\n\r]*\\)")
5483 org-angle-link-re
5484 (concat
5485 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5486 "\\([^" org-non-link-chars " ]"
5487 "[^" org-non-link-chars "]*"
5488 "\\)>")
5489 org-plain-link-re
5490 (concat
5491 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5492 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5493 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5494 org-bracket-link-regexp
5495 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5496 org-bracket-link-analytic-regexp
5497 (concat
5498 "\\[\\["
5499 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5500 "\\([^]]+\\)"
5501 "\\]"
5502 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5503 "\\]")
5504 org-bracket-link-analytic-regexp++
5505 (concat
5506 "\\[\\["
5507 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5508 "\\([^]]+\\)"
5509 "\\]"
5510 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5511 "\\]")
5512 org-any-link-re
5513 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5514 org-angle-link-re "\\)\\|\\("
5515 org-plain-link-re "\\)")))
5517 (org-make-link-regexps)
5519 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5520 "Regular expression for fast time stamp matching.")
5521 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5522 "Regular expression for fast time stamp matching.")
5523 (defconst org-ts-regexp0
5524 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5525 "Regular expression matching time strings for analysis.
5526 This one does not require the space after the date, so it can be used
5527 on a string that terminates immediately after the date.")
5528 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5529 "Regular expression matching time strings for analysis.")
5530 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5531 "Regular expression matching time stamps, with groups.")
5532 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5533 "Regular expression matching time stamps (also [..]), with groups.")
5534 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5535 "Regular expression matching a time stamp range.")
5536 (defconst org-tr-regexp-both
5537 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5538 "Regular expression matching a time stamp range.")
5539 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5540 org-ts-regexp "\\)?")
5541 "Regular expression matching a time stamp or time stamp range.")
5542 (defconst org-tsr-regexp-both
5543 (concat org-ts-regexp-both "\\(--?-?"
5544 org-ts-regexp-both "\\)?")
5545 "Regular expression matching a time stamp or time stamp range.
5546 The time stamps may be either active or inactive.")
5548 (defvar org-emph-face nil)
5550 (defun org-do-emphasis-faces (limit)
5551 "Run through the buffer and add overlays to emphasized strings."
5552 (let (rtn a)
5553 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5554 (if (not (= (char-after (match-beginning 3))
5555 (char-after (match-beginning 4))))
5556 (progn
5557 (setq rtn t)
5558 (setq a (assoc (match-string 3) org-emphasis-alist))
5559 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5560 'face
5561 (nth 1 a))
5562 (and (nth 4 a)
5563 (org-remove-flyspell-overlays-in
5564 (match-beginning 0) (match-end 0)))
5565 (add-text-properties (match-beginning 2) (match-end 2)
5566 '(font-lock-multiline t org-emphasis t))
5567 (when org-hide-emphasis-markers
5568 (add-text-properties (match-end 4) (match-beginning 5)
5569 '(invisible org-link))
5570 (add-text-properties (match-beginning 3) (match-end 3)
5571 '(invisible org-link)))))
5572 (backward-char 1))
5573 rtn))
5575 (defun org-emphasize (&optional char)
5576 "Insert or change an emphasis, i.e. a font like bold or italic.
5577 If there is an active region, change that region to a new emphasis.
5578 If there is no region, just insert the marker characters and position
5579 the cursor between them.
5580 CHAR should be either the marker character, or the first character of the
5581 HTML tag associated with that emphasis. If CHAR is a space, the means
5582 to remove the emphasis of the selected region.
5583 If char is not given (for example in an interactive call) it
5584 will be prompted for."
5585 (interactive)
5586 (let ((eal org-emphasis-alist) e det
5587 (erc org-emphasis-regexp-components)
5588 (prompt "")
5589 (string "") beg end move tag c s)
5590 (if (org-region-active-p)
5591 (setq beg (region-beginning) end (region-end)
5592 string (buffer-substring beg end))
5593 (setq move t))
5595 (while (setq e (pop eal))
5596 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5597 c (aref tag 0))
5598 (push (cons c (string-to-char (car e))) det)
5599 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5600 (substring tag 1)))))
5601 (setq det (nreverse det))
5602 (unless char
5603 (message "%s" (concat "Emphasis marker or tag:" prompt))
5604 (setq char (read-char-exclusive)))
5605 (setq char (or (cdr (assoc char det)) char))
5606 (if (equal char ?\ )
5607 (setq s "" move nil)
5608 (unless (assoc (char-to-string char) org-emphasis-alist)
5609 (error "No such emphasis marker: \"%c\"" char))
5610 (setq s (char-to-string char)))
5611 (while (and (> (length string) 1)
5612 (equal (substring string 0 1) (substring string -1))
5613 (assoc (substring string 0 1) org-emphasis-alist))
5614 (setq string (substring string 1 -1)))
5615 (setq string (concat s string s))
5616 (if beg (delete-region beg end))
5617 (unless (or (bolp)
5618 (string-match (concat "[" (nth 0 erc) "\n]")
5619 (char-to-string (char-before (point)))))
5620 (insert " "))
5621 (unless (or (eobp)
5622 (string-match (concat "[" (nth 1 erc) "\n]")
5623 (char-to-string (char-after (point)))))
5624 (insert " ") (backward-char 1))
5625 (insert string)
5626 (and move (backward-char 1))))
5628 (defconst org-nonsticky-props
5629 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5631 (defsubst org-rear-nonsticky-at (pos)
5632 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5634 (defun org-activate-plain-links (limit)
5635 "Run through the buffer and add overlays to links."
5636 (let (f hl)
5637 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5638 (not (org-in-src-block-p)))
5639 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5640 (setq f (get-text-property (match-beginning 0) 'face))
5641 (setq hl (org-match-string-no-properties 0))
5642 (if (or (eq f 'org-tag)
5643 (and (listp f) (memq 'org-tag f)))
5645 (add-text-properties (match-beginning 0) (match-end 0)
5646 (list 'mouse-face 'highlight
5647 'face 'org-link
5648 'htmlize-link `(:uri ,hl)
5649 'keymap org-mouse-map))
5650 (org-rear-nonsticky-at (match-end 0)))
5651 t)))
5653 (defun org-activate-code (limit)
5654 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5655 (progn
5656 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5657 (remove-text-properties (match-beginning 0) (match-end 0)
5658 '(display t invisible t intangible t))
5659 t)))
5661 (defcustom org-src-fontify-natively nil
5662 "When non-nil, fontify code in code blocks."
5663 :type 'boolean
5664 :version "24.1"
5665 :group 'org-appearance
5666 :group 'org-babel)
5668 (defcustom org-allow-promoting-top-level-subtree nil
5669 "When non-nil, allow promoting a top level subtree.
5670 The leading star of the top level headline will be replaced
5671 by a #."
5672 :type 'boolean
5673 :version "24.1"
5674 :group 'org-appearance)
5676 (defun org-fontify-meta-lines-and-blocks (limit)
5677 (condition-case nil
5678 (org-fontify-meta-lines-and-blocks-1 limit)
5679 (error (message "org-mode fontification error"))))
5681 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5682 "Fontify #+ lines and blocks, in the correct ways."
5683 (let ((case-fold-search t))
5684 (if (re-search-forward
5685 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5686 limit t)
5687 (let ((beg (match-beginning 0))
5688 (block-start (match-end 0))
5689 (block-end nil)
5690 (lang (match-string 7))
5691 (beg1 (line-beginning-position 2))
5692 (dc1 (downcase (match-string 2)))
5693 (dc3 (downcase (match-string 3)))
5694 end end1 quoting block-type ovl)
5695 (cond
5696 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5697 ;; a single line of backend-specific content
5698 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5699 (remove-text-properties (match-beginning 0) (match-end 0)
5700 '(display t invisible t intangible t))
5701 (add-text-properties (match-beginning 1) (match-end 3)
5702 '(font-lock-fontified t face org-meta-line))
5703 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5704 '(font-lock-fontified t face org-block))
5705 ; for backend-specific code
5707 ((and (match-end 4) (equal dc3 "+begin"))
5708 ;; Truly a block
5709 (setq block-type (downcase (match-string 5))
5710 quoting (member block-type org-protecting-blocks))
5711 (when (re-search-forward
5712 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5713 nil t) ;; on purpose, we look further than LIMIT
5714 (setq end (min (point-max) (match-end 0))
5715 end1 (min (point-max) (1- (match-beginning 0))))
5716 (setq block-end (match-beginning 0))
5717 (when quoting
5718 (remove-text-properties beg end
5719 '(display t invisible t intangible t)))
5720 (add-text-properties
5721 beg end
5722 '(font-lock-fontified t font-lock-multiline t))
5723 (add-text-properties beg beg1 '(face org-meta-line))
5724 (add-text-properties end1 (min (point-max) (1+ end))
5725 '(face org-meta-line)) ; for end_src
5726 (cond
5727 ((and lang (not (string= lang "")) org-src-fontify-natively)
5728 (org-src-font-lock-fontify-block lang block-start block-end)
5729 ;; remove old background overlays
5730 (mapc (lambda (ov)
5731 (if (eq (overlay-get ov 'face) 'org-block-background)
5732 (delete-overlay ov)))
5733 (overlays-at (/ (+ beg1 block-end) 2)))
5734 ;; add a background overlay
5735 (setq ovl (make-overlay beg1 block-end))
5736 (overlay-put ovl 'face 'org-block-background)
5737 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5738 (quoting
5739 (add-text-properties beg1 (min (point-max) (1+ end1))
5740 '(face org-block))) ; end of source block
5741 ((not org-fontify-quote-and-verse-blocks))
5742 ((string= block-type "quote")
5743 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5744 ((string= block-type "verse")
5745 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5746 (add-text-properties beg beg1 '(face org-block-begin-line))
5747 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5748 '(face org-block-end-line))
5750 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5751 (add-text-properties
5752 beg (match-end 3)
5753 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5754 '(font-lock-fontified t invisible t)
5755 '(font-lock-fontified t face org-document-info-keyword)))
5756 (add-text-properties
5757 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5758 (if (string-equal dc1 "+title:")
5759 '(font-lock-fontified t face org-document-title)
5760 '(font-lock-fontified t face org-document-info))))
5761 ((or (equal dc1 "+results")
5762 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5763 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5764 "+call:" "+header:" "+headers:" "+name:"))
5765 (and (match-end 4) (equal dc3 "+attr")))
5766 (add-text-properties
5767 beg (match-end 0)
5768 '(font-lock-fontified t face org-meta-line))
5770 ((member dc3 '(" " ""))
5771 (add-text-properties
5772 beg (match-end 0)
5773 '(font-lock-fontified t face font-lock-comment-face)))
5774 ((not (member (char-after beg) '(?\ ?\t)))
5775 ;; just any other in-buffer setting, but not indented
5776 (add-text-properties
5777 beg (match-end 0)
5778 '(font-lock-fontified t face org-meta-line))
5780 (t nil))))))
5782 (defun org-activate-angle-links (limit)
5783 "Run through the buffer and add overlays to links."
5784 (if (and (re-search-forward org-angle-link-re limit t)
5785 (not (org-in-src-block-p)))
5786 (progn
5787 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5788 (add-text-properties (match-beginning 0) (match-end 0)
5789 (list 'mouse-face 'highlight
5790 'keymap org-mouse-map))
5791 (org-rear-nonsticky-at (match-end 0))
5792 t)))
5794 (defun org-activate-footnote-links (limit)
5795 "Run through the buffer and add overlays to footnotes."
5796 (let ((fn (org-footnote-next-reference-or-definition limit)))
5797 (when fn
5798 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5799 (org-remove-flyspell-overlays-in beg end)
5800 (add-text-properties beg end
5801 (list 'mouse-face 'highlight
5802 'keymap org-mouse-map
5803 'help-echo
5804 (if (= (point-at-bol) beg)
5805 "Footnote definition"
5806 "Footnote reference")
5807 'font-lock-fontified t
5808 'font-lock-multiline t
5809 'face 'org-footnote))))))
5811 (defun org-activate-bracket-links (limit)
5812 "Run through the buffer and add overlays to bracketed links."
5813 (if (and (re-search-forward org-bracket-link-regexp limit t)
5814 (not (org-in-src-block-p)))
5815 (let* ((hl (org-match-string-no-properties 1))
5816 (help (concat "LINK: " hl))
5817 ;; FIXME: Above we should remove the escapes. But that
5818 ;; requires another match, protecting match data, a lot
5819 ;; of overhead for font-lock.
5820 (ip (org-maybe-intangible
5821 (list 'invisible 'org-link
5822 'keymap org-mouse-map 'mouse-face 'highlight
5823 'font-lock-multiline t 'help-echo help
5824 'htmlize-link `(:uri ,hl))))
5825 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5826 'font-lock-multiline t 'help-echo help
5827 'htmlize-link `(:uri ,hl))))
5828 ;; We need to remove the invisible property here. Table narrowing
5829 ;; may have made some of this invisible.
5830 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5831 (remove-text-properties (match-beginning 0) (match-end 0)
5832 '(invisible nil))
5833 (if (match-end 3)
5834 (progn
5835 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5836 (org-rear-nonsticky-at (match-beginning 3))
5837 (add-text-properties (match-beginning 3) (match-end 3) vp)
5838 (org-rear-nonsticky-at (match-end 3))
5839 (add-text-properties (match-end 3) (match-end 0) ip)
5840 (org-rear-nonsticky-at (match-end 0)))
5841 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5842 (org-rear-nonsticky-at (match-beginning 1))
5843 (add-text-properties (match-beginning 1) (match-end 1) vp)
5844 (org-rear-nonsticky-at (match-end 1))
5845 (add-text-properties (match-end 1) (match-end 0) ip)
5846 (org-rear-nonsticky-at (match-end 0)))
5847 t)))
5849 (defun org-activate-dates (limit)
5850 "Run through the buffer and add overlays to dates."
5851 (if (and (re-search-forward org-tsr-regexp-both limit t)
5852 (not (equal (char-before (match-beginning 0)) 91)))
5853 (progn
5854 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5855 (add-text-properties (match-beginning 0) (match-end 0)
5856 (list 'mouse-face 'highlight
5857 'keymap org-mouse-map))
5858 (org-rear-nonsticky-at (match-end 0))
5859 (when org-display-custom-times
5860 (if (match-end 3)
5861 (org-display-custom-time (match-beginning 3) (match-end 3)))
5862 (org-display-custom-time (match-beginning 1) (match-end 1)))
5863 t)))
5865 (defvar org-target-link-regexp nil
5866 "Regular expression matching radio targets in plain text.")
5867 (make-variable-buffer-local 'org-target-link-regexp)
5868 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5869 "Regular expression matching a link target.")
5870 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5871 "Regular expression matching a radio target.")
5872 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5873 "Regular expression matching any target.")
5875 (defun org-activate-target-links (limit)
5876 "Run through the buffer and add overlays to target matches."
5877 (when org-target-link-regexp
5878 (let ((case-fold-search t))
5879 (if (re-search-forward org-target-link-regexp limit t)
5880 (progn
5881 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5882 (add-text-properties (match-beginning 0) (match-end 0)
5883 (list 'mouse-face 'highlight
5884 'keymap org-mouse-map
5885 'help-echo "Radio target link"
5886 'org-linked-text t))
5887 (org-rear-nonsticky-at (match-end 0))
5888 t)))))
5890 (defun org-update-radio-target-regexp ()
5891 "Find all radio targets in this file and update the regular expression."
5892 (interactive)
5893 (when (memq 'radio org-activate-links)
5894 (setq org-target-link-regexp
5895 (org-make-target-link-regexp (org-all-targets 'radio)))
5896 (org-restart-font-lock)))
5898 (defun org-hide-wide-columns (limit)
5899 (let (s e)
5900 (setq s (text-property-any (point) (or limit (point-max))
5901 'org-cwidth t))
5902 (when s
5903 (setq e (next-single-property-change s 'org-cwidth))
5904 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5905 (goto-char e)
5906 t)))
5908 (defvar org-latex-and-related-regexp nil
5909 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
5910 (defvar org-match-substring-regexp)
5911 (defvar org-match-substring-with-braces-regexp)
5913 (defun org-compute-latex-and-related-regexp ()
5914 "Compute regular expression for LaTeX, entities and sub/superscript.
5915 Result depends on variable `org-highlight-latex-and-related'."
5916 (org-set-local
5917 'org-latex-and-related-regexp
5918 (let* ((re-sub
5919 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
5920 ((eq org-use-sub-superscripts '{})
5921 (list org-match-substring-with-braces-regexp))
5922 (org-use-sub-superscripts (list org-match-substring-regexp))))
5923 (re-latex
5924 (when (memq 'latex org-highlight-latex-and-related)
5925 (let ((matchers (plist-get org-format-latex-options :matchers)))
5926 (delq nil
5927 (mapcar (lambda (x)
5928 (and (member (car x) matchers) (nth 1 x)))
5929 org-latex-regexps)))))
5930 (re-entities
5931 (when (memq 'entities org-highlight-latex-and-related)
5932 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
5933 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
5935 (defun org-do-latex-and-related (limit)
5936 "Highlight LaTeX snippets and environments, entities and sub/superscript.
5937 LIMIT bounds the search for syntax to highlight. Stop at first
5938 highlighted object, if any. Return t if some highlighting was
5939 done, nil otherwise."
5940 (when (org-string-nw-p org-latex-and-related-regexp)
5941 (catch 'found
5942 (while (re-search-forward org-latex-and-related-regexp limit t)
5943 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
5944 'face))
5945 '(org-code org-verbatim underline))
5946 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
5947 '(?_ ?^))
5949 0)))
5950 (font-lock-prepend-text-property
5951 (+ offset (match-beginning 0)) (match-end 0)
5952 'face 'org-latex-and-related)
5953 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
5954 '(font-lock-multiline t)))
5955 (throw 'found t)))
5956 nil)))
5958 (defun org-restart-font-lock ()
5959 "Restart `font-lock-mode', to force refontification."
5960 (when (and (boundp 'font-lock-mode) font-lock-mode)
5961 (font-lock-mode -1)
5962 (font-lock-mode 1)))
5964 (defun org-all-targets (&optional radio)
5965 "Return a list of all targets in this file.
5966 When optional argument RADIO is non-nil, only find radio
5967 targets."
5968 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5969 (save-excursion
5970 (goto-char (point-min))
5971 (while (re-search-forward re nil t)
5972 ;; Make sure point is really within the object.
5973 (backward-char)
5974 (let ((obj (org-element-context)))
5975 (when (memq (org-element-type obj) '(radio-target target))
5976 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5977 rtn)))
5979 (defun org-make-target-link-regexp (targets)
5980 "Make regular expression matching all strings in TARGETS.
5981 The regular expression finds the targets also if there is a line break
5982 between words."
5983 (and targets
5984 (concat
5985 "\\<\\("
5986 (mapconcat
5987 (lambda (x)
5988 (setq x (regexp-quote x))
5989 (while (string-match " +" x)
5990 (setq x (replace-match "\\s-+" t t x)))
5992 targets
5993 "\\|")
5994 "\\)\\>")))
5996 (defun org-activate-tags (limit)
5997 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5998 (progn
5999 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6000 (add-text-properties (match-beginning 1) (match-end 1)
6001 (list 'mouse-face 'highlight
6002 'keymap org-mouse-map))
6003 (org-rear-nonsticky-at (match-end 1))
6004 t)))
6006 (defun org-outline-level ()
6007 "Compute the outline level of the heading at point.
6008 If this is called at a normal headline, the level is the number of stars.
6009 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6010 (save-excursion
6011 (if (not (condition-case nil
6012 (org-back-to-heading t)
6013 (error nil)))
6015 (looking-at org-outline-regexp)
6016 (1- (- (match-end 0) (match-beginning 0))))))
6018 (defvar org-font-lock-keywords nil)
6020 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
6021 "Regular expression matching a property line.")
6023 (defvar org-font-lock-hook nil
6024 "Functions to be called for special font lock stuff.")
6026 (defvar org-font-lock-set-keywords-hook nil
6027 "Functions that can manipulate `org-font-lock-extra-keywords'.
6028 This is called after `org-font-lock-extra-keywords' is defined, but before
6029 it is installed to be used by font lock. This can be useful if something
6030 needs to be inserted at a specific position in the font-lock sequence.")
6032 (defun org-font-lock-hook (limit)
6033 "Run `org-font-lock-hook' within LIMIT."
6034 (run-hook-with-args 'org-font-lock-hook limit))
6036 (defun org-set-font-lock-defaults ()
6037 "Set font lock defaults for the current buffer."
6038 (let* ((em org-fontify-emphasized-text)
6039 (lk org-activate-links)
6040 (org-font-lock-extra-keywords
6041 (list
6042 ;; Call the hook
6043 '(org-font-lock-hook)
6044 ;; Headlines
6045 `(,(if org-fontify-whole-heading-line
6046 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6047 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6048 (1 (org-get-level-face 1))
6049 (2 (org-get-level-face 2))
6050 (3 (org-get-level-face 3)))
6051 ;; Table lines
6052 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6053 (1 'org-table t))
6054 ;; Table internals
6055 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6056 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6057 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6058 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6059 ;; Drawers
6060 (list org-drawer-regexp '(0 'org-special-keyword t))
6061 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6062 ;; Properties
6063 (list org-property-re
6064 '(1 'org-special-keyword t)
6065 '(3 'org-property-value t))
6066 ;; Links
6067 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6068 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6069 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6070 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6071 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6072 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6073 (if (memq 'footnote lk) '(org-activate-footnote-links))
6074 ;; Targets.
6075 (list org-any-target-regexp '(0 'org-target t))
6076 ;; Diary sexps.
6077 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6078 ;; Macro
6079 '("{{{.+}}}" (0 'org-macro t))
6080 '(org-hide-wide-columns (0 nil append))
6081 ;; TODO keyword
6082 (list (format org-heading-keyword-regexp-format
6083 org-todo-regexp)
6084 '(2 (org-get-todo-face 2) t))
6085 ;; DONE
6086 (if org-fontify-done-headline
6087 (list (format org-heading-keyword-regexp-format
6088 (concat
6089 "\\(?:"
6090 (mapconcat 'regexp-quote org-done-keywords "\\|")
6091 "\\)"))
6092 '(2 'org-headline-done t))
6093 nil)
6094 ;; Priorities
6095 '(org-font-lock-add-priority-faces)
6096 ;; Tags
6097 '(org-font-lock-add-tag-faces)
6098 ;; Special keywords
6099 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6100 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6101 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6102 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6103 ;; Emphasis
6104 (if em
6105 (if (featurep 'xemacs)
6106 '(org-do-emphasis-faces (0 nil append))
6107 '(org-do-emphasis-faces)))
6108 ;; Checkboxes
6109 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6110 1 'org-checkbox prepend)
6111 (if (cdr (assq 'checkbox org-list-automatic-rules))
6112 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6113 (0 (org-get-checkbox-statistics-face) t)))
6114 ;; Description list items
6115 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6116 1 'org-list-dt prepend)
6117 ;; ARCHIVEd headings
6118 (list (concat
6119 org-outline-regexp-bol
6120 "\\(.*:" org-archive-tag ":.*\\)")
6121 '(1 'org-archived prepend))
6122 ;; Specials
6123 '(org-do-latex-and-related)
6124 '(org-fontify-entities)
6125 '(org-raise-scripts)
6126 ;; Code
6127 '(org-activate-code (1 'org-code t))
6128 ;; COMMENT
6129 (list (format org-heading-keyword-regexp-format
6130 (concat "\\("
6131 org-comment-string "\\|" org-quote-string
6132 "\\)"))
6133 '(2 'org-special-keyword t))
6134 ;; Blocks and meta lines
6135 '(org-fontify-meta-lines-and-blocks)
6137 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6138 (run-hooks 'org-font-lock-set-keywords-hook)
6139 ;; Now set the full font-lock-keywords
6140 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6141 (org-set-local 'font-lock-defaults
6142 '(org-font-lock-keywords t nil nil backward-paragraph))
6143 (kill-local-variable 'font-lock-keywords) nil))
6145 (defun org-toggle-pretty-entities ()
6146 "Toggle the composition display of entities as UTF8 characters."
6147 (interactive)
6148 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6149 (org-restart-font-lock)
6150 (if org-pretty-entities
6151 (message "Entities are displayed as UTF8 characters")
6152 (save-restriction
6153 (widen)
6154 (org-decompose-region (point-min) (point-max))
6155 (message "Entities are displayed plain"))))
6157 (defvar org-custom-properties-overlays nil
6158 "List of overlays used for custom properties.")
6159 (make-variable-buffer-local 'org-custom-properties-overlays)
6161 (defun org-toggle-custom-properties-visibility ()
6162 "Display or hide properties in `org-custom-properties'."
6163 (interactive)
6164 (if org-custom-properties-overlays
6165 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6166 (setq org-custom-properties-overlays nil))
6167 (unless (not org-custom-properties)
6168 (save-excursion
6169 (save-restriction
6170 (widen)
6171 (goto-char (point-min))
6172 (while (re-search-forward org-property-re nil t)
6173 (mapc (lambda(p)
6174 (when (equal p (substring (match-string 1) 1 -1))
6175 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6176 (overlay-put o 'invisible t)
6177 (overlay-put o 'org-custom-property t)
6178 (push o org-custom-properties-overlays))))
6179 org-custom-properties)))))))
6181 (defun org-fontify-entities (limit)
6182 "Find an entity to fontify."
6183 (let (ee)
6184 (when org-pretty-entities
6185 (catch 'match
6186 (while (re-search-forward
6187 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6188 limit t)
6189 (if (and (not (org-in-indented-comment-line))
6190 (setq ee (org-entity-get (match-string 1)))
6191 (= (length (nth 6 ee)) 1))
6192 (let*
6193 ((end (if (equal (match-string 2) "{}")
6194 (match-end 2)
6195 (match-end 1))))
6196 (add-text-properties
6197 (match-beginning 0) end
6198 (list 'font-lock-fontified t))
6199 (compose-region (match-beginning 0) end
6200 (nth 6 ee) nil)
6201 (backward-char 1)
6202 (throw 'match t))))
6203 nil))))
6205 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6206 "Fontify string S like in Org-mode."
6207 (with-temp-buffer
6208 (insert s)
6209 (let ((org-odd-levels-only odd-levels))
6210 (org-mode)
6211 (font-lock-fontify-buffer)
6212 (buffer-string))))
6214 (defvar org-m nil)
6215 (defvar org-l nil)
6216 (defvar org-f nil)
6217 (defun org-get-level-face (n)
6218 "Get the right face for match N in font-lock matching of headlines."
6219 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6220 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6221 (if org-cycle-level-faces
6222 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6223 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6224 (cond
6225 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6226 ((eq n 2) org-f)
6227 (t (if org-level-color-stars-only nil org-f))))
6230 (defun org-get-todo-face (kwd)
6231 "Get the right face for a TODO keyword KWD.
6232 If KWD is a number, get the corresponding match group."
6233 (if (numberp kwd) (setq kwd (match-string kwd)))
6234 (or (org-face-from-face-or-color
6235 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6236 (and (member kwd org-done-keywords) 'org-done)
6237 'org-todo))
6239 (defun org-face-from-face-or-color (context inherit face-or-color)
6240 "Create a face list that inherits INHERIT, but sets the foreground color.
6241 When FACE-OR-COLOR is not a string, just return it."
6242 (if (stringp face-or-color)
6243 (list :inherit inherit
6244 (cdr (assoc context org-faces-easy-properties))
6245 face-or-color)
6246 face-or-color))
6248 (defun org-font-lock-add-tag-faces (limit)
6249 "Add the special tag faces."
6250 (when (and org-tag-faces org-tags-special-faces-re)
6251 (while (re-search-forward org-tags-special-faces-re limit t)
6252 (add-text-properties (match-beginning 1) (match-end 1)
6253 (list 'face (org-get-tag-face 1)
6254 'font-lock-fontified t))
6255 (backward-char 1))))
6257 (defun org-font-lock-add-priority-faces (limit)
6258 "Add the special priority faces."
6259 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6260 (when (save-match-data (org-at-heading-p))
6261 (add-text-properties
6262 (match-beginning 0) (match-end 0)
6263 (list 'face (or (org-face-from-face-or-color
6264 'priority 'org-priority
6265 (cdr (assoc (char-after (match-beginning 1))
6266 org-priority-faces)))
6267 'org-priority)
6268 'font-lock-fontified t)))))
6270 (defun org-get-tag-face (kwd)
6271 "Get the right face for a TODO keyword KWD.
6272 If KWD is a number, get the corresponding match group."
6273 (if (numberp kwd) (setq kwd (match-string kwd)))
6274 (or (org-face-from-face-or-color
6275 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6276 'org-tag))
6278 (defun org-unfontify-region (beg end &optional maybe_loudly)
6279 "Remove fontification and activation overlays from links."
6280 (font-lock-default-unfontify-region beg end)
6281 (let* ((buffer-undo-list t)
6282 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6283 (inhibit-modification-hooks t)
6284 deactivate-mark buffer-file-name buffer-file-truename)
6285 (org-decompose-region beg end)
6286 (remove-text-properties beg end
6287 '(mouse-face t keymap t org-linked-text t
6288 invisible t intangible t
6289 org-no-flyspell t org-emphasis t))
6290 (org-remove-font-lock-display-properties beg end)))
6292 (defconst org-script-display '(((raise -0.3) (height 0.7))
6293 ((raise 0.3) (height 0.7))
6294 ((raise -0.5))
6295 ((raise 0.5)))
6296 "Display properties for showing superscripts and subscripts.")
6298 (defun org-remove-font-lock-display-properties (beg end)
6299 "Remove specific display properties that have been added by font lock.
6300 The will remove the raise properties that are used to show superscripts
6301 and subscripts."
6302 (let (next prop)
6303 (while (< beg end)
6304 (setq next (next-single-property-change beg 'display nil end)
6305 prop (get-text-property beg 'display))
6306 (if (member prop org-script-display)
6307 (put-text-property beg next 'display nil))
6308 (setq beg next))))
6310 (defun org-raise-scripts (limit)
6311 "Add raise properties to sub/superscripts."
6312 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6313 (if (re-search-forward
6314 (if (eq org-use-sub-superscripts t)
6315 org-match-substring-regexp
6316 org-match-substring-with-braces-regexp)
6317 limit t)
6318 (let* ((pos (point)) table-p comment-p
6319 (mpos (match-beginning 3))
6320 (emph-p (get-text-property mpos 'org-emphasis))
6321 (link-p (get-text-property mpos 'mouse-face))
6322 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6323 (goto-char (point-at-bol))
6324 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6325 comment-p (org-looking-at-p "[ \t]*#"))
6326 (goto-char pos)
6327 ;; FIXME: Should we go back one character here, for a_b^c
6328 ;; (goto-char (1- pos)) ;????????????????????
6329 (if (or comment-p emph-p link-p keyw-p)
6331 (put-text-property (match-beginning 3) (match-end 0)
6332 'display
6333 (if (equal (char-after (match-beginning 2)) ?^)
6334 (nth (if table-p 3 1) org-script-display)
6335 (nth (if table-p 2 0) org-script-display)))
6336 (add-text-properties (match-beginning 2) (match-end 2)
6337 (list 'invisible t
6338 'org-dwidth t 'org-dwidth-n 1))
6339 (if (and (eq (char-after (match-beginning 3)) ?{)
6340 (eq (char-before (match-end 3)) ?}))
6341 (progn
6342 (add-text-properties
6343 (match-beginning 3) (1+ (match-beginning 3))
6344 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6345 (add-text-properties
6346 (1- (match-end 3)) (match-end 3)
6347 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6348 t)))))
6350 ;;;; Visibility cycling, including org-goto and indirect buffer
6352 ;;; Cycling
6354 (defvar org-cycle-global-status nil)
6355 (make-variable-buffer-local 'org-cycle-global-status)
6356 (put 'org-cycle-global-status 'org-state t)
6357 (defvar org-cycle-subtree-status nil)
6358 (make-variable-buffer-local 'org-cycle-subtree-status)
6359 (put 'org-cycle-subtree-status 'org-state t)
6361 (defvar org-inlinetask-min-level)
6363 ;;;###autoload
6364 (defun org-cycle (&optional arg)
6365 "TAB-action and visibility cycling for Org-mode.
6367 This is the command invoked in Org-mode by the TAB key. Its main purpose
6368 is outline visibility cycling, but it also invokes other actions
6369 in special contexts.
6371 - When this function is called with a prefix argument, rotate the entire
6372 buffer through 3 states (global cycling)
6373 1. OVERVIEW: Show only top-level headlines.
6374 2. CONTENTS: Show all headlines of all levels, but no body text.
6375 3. SHOW ALL: Show everything.
6376 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6377 determined by the variable `org-startup-folded', and by any VISIBILITY
6378 properties in the buffer.
6379 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6380 including any drawers.
6382 - When inside a table, re-align the table and move to the next field.
6384 - When point is at the beginning of a headline, rotate the subtree started
6385 by this line through 3 different states (local cycling)
6386 1. FOLDED: Only the main headline is shown.
6387 2. CHILDREN: The main headline and the direct children are shown.
6388 From this state, you can move to one of the children
6389 and zoom in further.
6390 3. SUBTREE: Show the entire subtree, including body text.
6391 If there is no subtree, switch directly from CHILDREN to FOLDED.
6393 - When point is at the beginning of an empty headline and the variable
6394 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6395 of the headline by demoting and promoting it to likely levels. This
6396 speeds up creation document structure by pressing TAB once or several
6397 times right after creating a new headline.
6399 - When there is a numeric prefix, go up to a heading with level ARG, do
6400 a `show-subtree' and return to the previous cursor position. If ARG
6401 is negative, go up that many levels.
6403 - When point is not at the beginning of a headline, execute the global
6404 binding for TAB, which is re-indenting the line. See the option
6405 `org-cycle-emulate-tab' for details.
6407 - Special case: if point is at the beginning of the buffer and there is
6408 no headline in line 1, this function will act as if called with prefix arg
6409 (C-u TAB, same as S-TAB) also when called without prefix arg.
6410 But only if also the variable `org-cycle-global-at-bob' is t."
6411 (interactive "P")
6412 (org-load-modules-maybe)
6413 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6414 (and org-cycle-level-after-item/entry-creation
6415 (or (org-cycle-level)
6416 (org-cycle-item-indentation))))
6417 (let* (message-log-max ; Don't populate the *Messages* buffer
6418 (limit-level
6419 (or org-cycle-max-level
6420 (and (boundp 'org-inlinetask-min-level)
6421 org-inlinetask-min-level
6422 (1- org-inlinetask-min-level))))
6423 (nstars (and limit-level
6424 (if org-odd-levels-only
6425 (and limit-level (1- (* limit-level 2)))
6426 limit-level)))
6427 (org-outline-regexp
6428 (if (not (derived-mode-p 'org-mode))
6429 outline-regexp
6430 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6431 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6432 (not (looking-at org-outline-regexp))))
6433 (org-cycle-hook
6434 (if bob-special
6435 (delq 'org-optimize-window-after-visibility-change
6436 (copy-sequence org-cycle-hook))
6437 org-cycle-hook))
6438 (pos (point)))
6440 (if (or bob-special (equal arg '(4)))
6441 ;; special case: use global cycling
6442 (setq arg t))
6444 (cond
6446 ((equal arg '(16))
6447 (setq last-command 'dummy)
6448 (org-set-startup-visibility)
6449 (message "Startup visibility, plus VISIBILITY properties"))
6451 ((equal arg '(64))
6452 (show-all)
6453 (message "Entire buffer visible, including drawers"))
6455 ;; Table: enter it or move to the next field.
6456 ((org-at-table-p 'any)
6457 (if (org-at-table.el-p)
6458 (message "Use C-c ' to edit table.el tables")
6459 (if arg (org-table-edit-field t)
6460 (org-table-justify-field-maybe)
6461 (call-interactively 'org-table-next-field))))
6463 ((run-hook-with-args-until-success
6464 'org-tab-after-check-for-table-hook))
6466 ;; Global cycling: delegate to `org-cycle-internal-global'.
6467 ((eq arg t) (org-cycle-internal-global))
6469 ;; Drawers: delegate to `org-flag-drawer'.
6470 ((and org-drawers org-drawer-regexp
6471 (save-excursion
6472 (beginning-of-line 1)
6473 (looking-at org-drawer-regexp)))
6474 (org-flag-drawer ; toggle block visibility
6475 (not (get-char-property (match-end 0) 'invisible))))
6477 ;; Show-subtree, ARG levels up from here.
6478 ((integerp arg)
6479 (save-excursion
6480 (org-back-to-heading)
6481 (outline-up-heading (if (< arg 0) (- arg)
6482 (- (funcall outline-level) arg)))
6483 (org-show-subtree)))
6485 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6486 ((and (featurep 'org-inlinetask)
6487 (org-inlinetask-at-task-p)
6488 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6489 (org-inlinetask-toggle-visibility))
6491 ((org-try-cdlatex-tab))
6493 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6494 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6495 (save-excursion (beginning-of-line 1)
6496 (looking-at org-outline-regexp)))
6497 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6498 (org-cycle-internal-local))
6500 ;; From there: TAB emulation and template completion.
6501 (buffer-read-only (org-back-to-heading))
6503 ((run-hook-with-args-until-success
6504 'org-tab-after-check-for-cycling-hook))
6506 ((org-try-structure-completion))
6508 ((run-hook-with-args-until-success
6509 'org-tab-before-tab-emulation-hook))
6511 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6512 (or (not (bolp))
6513 (not (looking-at org-outline-regexp))))
6514 (call-interactively (global-key-binding "\t")))
6516 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6517 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6518 (or (and (eq org-cycle-emulate-tab 'white)
6519 (= (match-end 0) (point-at-eol)))
6520 (and (eq org-cycle-emulate-tab 'whitestart)
6521 (>= (match-end 0) pos))))
6523 (eq org-cycle-emulate-tab t))
6524 (call-interactively (global-key-binding "\t")))
6526 (t (save-excursion
6527 (org-back-to-heading)
6528 (org-cycle)))))))
6530 (defun org-cycle-internal-global ()
6531 "Do the global cycling action."
6532 ;; Hack to avoid display of messages for .org attachments in Gnus
6533 (let (message-log-max ; Don't populate the *Messages* buffer
6534 (ga (string-match "\\*fontification" (buffer-name))))
6535 (cond
6536 ((and (eq last-command this-command)
6537 (eq org-cycle-global-status 'overview))
6538 ;; We just created the overview - now do table of contents
6539 ;; This can be slow in very large buffers, so indicate action
6540 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6541 (unless ga (message "CONTENTS..."))
6542 (org-content)
6543 (unless ga (message "CONTENTS...done"))
6544 (setq org-cycle-global-status 'contents)
6545 (run-hook-with-args 'org-cycle-hook 'contents))
6547 ((and (eq last-command this-command)
6548 (eq org-cycle-global-status 'contents))
6549 ;; We just showed the table of contents - now show everything
6550 (run-hook-with-args 'org-pre-cycle-hook 'all)
6551 (show-all)
6552 (unless ga (message "SHOW ALL"))
6553 (setq org-cycle-global-status 'all)
6554 (run-hook-with-args 'org-cycle-hook 'all))
6557 ;; Default action: go to overview
6558 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6559 (org-overview)
6560 (unless ga (message "OVERVIEW"))
6561 (setq org-cycle-global-status 'overview)
6562 (run-hook-with-args 'org-cycle-hook 'overview)))))
6564 (defun org-cycle-internal-local ()
6565 "Do the local cycling action."
6566 (let (message-log-max ; Don't populate the *Messages* buffer
6567 (goal-column 0) eoh eol eos has-children children-skipped struct)
6568 ;; First, determine end of headline (EOH), end of subtree or item
6569 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6570 (save-excursion
6571 (if (org-at-item-p)
6572 (progn
6573 (beginning-of-line)
6574 (setq struct (org-list-struct))
6575 (setq eoh (point-at-eol))
6576 (setq eos (org-list-get-item-end-before-blank (point) struct))
6577 (setq has-children (org-list-has-child-p (point) struct)))
6578 (org-back-to-heading)
6579 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6580 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6581 (setq has-children
6582 (or (save-excursion
6583 (let ((level (funcall outline-level)))
6584 (outline-next-heading)
6585 (and (org-at-heading-p t)
6586 (> (funcall outline-level) level))))
6587 (save-excursion
6588 (org-list-search-forward (org-item-beginning-re) eos t)))))
6589 ;; Determine end invisible part of buffer (EOL)
6590 (beginning-of-line 2)
6591 ;; XEmacs doesn't have `next-single-char-property-change'
6592 (if (featurep 'xemacs)
6593 (while (and (not (eobp)) ;; this is like `next-line'
6594 (get-char-property (1- (point)) 'invisible))
6595 (beginning-of-line 2))
6596 (while (and (not (eobp)) ;; this is like `next-line'
6597 (get-char-property (1- (point)) 'invisible))
6598 (goto-char (next-single-char-property-change (point) 'invisible))
6599 (and (eolp) (beginning-of-line 2))))
6600 (setq eol (point)))
6601 ;; Find out what to do next and set `this-command'
6602 (cond
6603 ((= eos eoh)
6604 ;; Nothing is hidden behind this heading
6605 (unless (org-before-first-heading-p)
6606 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6607 (message "EMPTY ENTRY")
6608 (setq org-cycle-subtree-status nil)
6609 (save-excursion
6610 (goto-char eos)
6611 (outline-next-heading)
6612 (if (outline-invisible-p) (org-flag-heading nil))))
6613 ((and (or (>= eol eos)
6614 (not (string-match "\\S-" (buffer-substring eol eos))))
6615 (or has-children
6616 (not (setq children-skipped
6617 org-cycle-skip-children-state-if-no-children))))
6618 ;; Entire subtree is hidden in one line: children view
6619 (unless (org-before-first-heading-p)
6620 (run-hook-with-args 'org-pre-cycle-hook 'children))
6621 (if (org-at-item-p)
6622 (org-list-set-item-visibility (point-at-bol) struct 'children)
6623 (org-show-entry)
6624 (org-with-limited-levels (show-children))
6625 ;; FIXME: This slows down the func way too much.
6626 ;; How keep drawers hidden in subtree anyway?
6627 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6628 ;; (org-cycle-hide-drawers 'subtree))
6630 ;; Fold every list in subtree to top-level items.
6631 (when (eq org-cycle-include-plain-lists 'integrate)
6632 (save-excursion
6633 (org-back-to-heading)
6634 (while (org-list-search-forward (org-item-beginning-re) eos t)
6635 (beginning-of-line 1)
6636 (let* ((struct (org-list-struct))
6637 (prevs (org-list-prevs-alist struct))
6638 (end (org-list-get-bottom-point struct)))
6639 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6640 (org-list-get-all-items (point) struct prevs))
6641 (goto-char end))))))
6642 (message "CHILDREN")
6643 (save-excursion
6644 (goto-char eos)
6645 (outline-next-heading)
6646 (if (outline-invisible-p) (org-flag-heading nil)))
6647 (setq org-cycle-subtree-status 'children)
6648 (unless (org-before-first-heading-p)
6649 (run-hook-with-args 'org-cycle-hook 'children)))
6650 ((or children-skipped
6651 (and (eq last-command this-command)
6652 (eq org-cycle-subtree-status 'children)))
6653 ;; We just showed the children, or no children are there,
6654 ;; now show everything.
6655 (unless (org-before-first-heading-p)
6656 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6657 (outline-flag-region eoh eos nil)
6658 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6659 (setq org-cycle-subtree-status 'subtree)
6660 (unless (org-before-first-heading-p)
6661 (run-hook-with-args 'org-cycle-hook 'subtree)))
6663 ;; Default action: hide the subtree.
6664 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6665 (outline-flag-region eoh eos t)
6666 (message "FOLDED")
6667 (setq org-cycle-subtree-status 'folded)
6668 (unless (org-before-first-heading-p)
6669 (run-hook-with-args 'org-cycle-hook 'folded))))))
6671 ;;;###autoload
6672 (defun org-global-cycle (&optional arg)
6673 "Cycle the global visibility. For details see `org-cycle'.
6674 With \\[universal-argument] prefix arg, switch to startup visibility.
6675 With a numeric prefix, show all headlines up to that level."
6676 (interactive "P")
6677 (let ((org-cycle-include-plain-lists
6678 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6679 (cond
6680 ((integerp arg)
6681 (show-all)
6682 (hide-sublevels arg)
6683 (setq org-cycle-global-status 'contents))
6684 ((equal arg '(4))
6685 (org-set-startup-visibility)
6686 (message "Startup visibility, plus VISIBILITY properties."))
6688 (org-cycle '(4))))))
6690 (defun org-set-startup-visibility ()
6691 "Set the visibility required by startup options and properties."
6692 (cond
6693 ((eq org-startup-folded t)
6694 (org-cycle '(4)))
6695 ((eq org-startup-folded 'content)
6696 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6697 (org-cycle '(4)) (org-cycle '(4)))))
6698 (unless (eq org-startup-folded 'showeverything)
6699 (if org-hide-block-startup (org-hide-block-all))
6700 (org-set-visibility-according-to-property 'no-cleanup)
6701 (org-cycle-hide-archived-subtrees 'all)
6702 (org-cycle-hide-drawers 'all)
6703 (org-cycle-show-empty-lines t)))
6705 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6706 "Switch subtree visibilities according to :VISIBILITY: property."
6707 (interactive)
6708 (let (org-show-entry-below state)
6709 (save-excursion
6710 (goto-char (point-min))
6711 (while (re-search-forward
6712 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6713 nil t)
6714 (setq state (match-string 1))
6715 (save-excursion
6716 (org-back-to-heading t)
6717 (hide-subtree)
6718 (org-reveal)
6719 (cond
6720 ((equal state '("fold" "folded"))
6721 (hide-subtree))
6722 ((equal state "children")
6723 (org-show-hidden-entry)
6724 (show-children))
6725 ((equal state "content")
6726 (save-excursion
6727 (save-restriction
6728 (org-narrow-to-subtree)
6729 (org-content))))
6730 ((member state '("all" "showall"))
6731 (show-subtree)))))
6732 (unless no-cleanup
6733 (org-cycle-hide-archived-subtrees 'all)
6734 (org-cycle-hide-drawers 'all)
6735 (org-cycle-show-empty-lines 'all)))))
6737 ;; This function uses outline-regexp instead of the more fundamental
6738 ;; org-outline-regexp so that org-cycle-global works outside of Org
6739 ;; buffers, where outline-regexp is needed.
6740 (defun org-overview ()
6741 "Switch to overview mode, showing only top-level headlines.
6742 Really, this shows all headlines with level equal or greater than the level
6743 of the first headline in the buffer. This is important, because if the
6744 first headline is not level one, then (hide-sublevels 1) gives confusing
6745 results."
6746 (interactive)
6747 (let ((l (org-current-line))
6748 (level (save-excursion
6749 (goto-char (point-min))
6750 (if (re-search-forward (concat "^" outline-regexp) nil t)
6751 (progn
6752 (goto-char (match-beginning 0))
6753 (funcall outline-level))))))
6754 (and level (hide-sublevels level))
6755 (recenter '(4))
6756 (org-goto-line l)))
6758 (defun org-content (&optional arg)
6759 "Show all headlines in the buffer, like a table of contents.
6760 With numerical argument N, show content up to level N."
6761 (interactive "P")
6762 (save-excursion
6763 ;; Visit all headings and show their offspring
6764 (and (integerp arg) (org-overview))
6765 (goto-char (point-max))
6766 (catch 'exit
6767 (while (and (progn (condition-case nil
6768 (outline-previous-visible-heading 1)
6769 (error (goto-char (point-min))))
6771 (looking-at org-outline-regexp))
6772 (if (integerp arg)
6773 (show-children (1- arg))
6774 (show-branches))
6775 (if (bobp) (throw 'exit nil))))))
6778 (defun org-optimize-window-after-visibility-change (state)
6779 "Adjust the window after a change in outline visibility.
6780 This function is the default value of the hook `org-cycle-hook'."
6781 (when (get-buffer-window (current-buffer))
6782 (cond
6783 ((eq state 'content) nil)
6784 ((eq state 'all) nil)
6785 ((eq state 'folded) nil)
6786 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6787 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6789 (defun org-remove-empty-overlays-at (pos)
6790 "Remove outline overlays that do not contain non-white stuff."
6791 (mapc
6792 (lambda (o)
6793 (and (eq 'outline (overlay-get o 'invisible))
6794 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6795 (overlay-end o))))
6796 (delete-overlay o)))
6797 (overlays-at pos)))
6799 (defun org-clean-visibility-after-subtree-move ()
6800 "Fix visibility issues after moving a subtree."
6801 ;; First, find a reasonable region to look at:
6802 ;; Start two siblings above, end three below
6803 (let* ((beg (save-excursion
6804 (and (org-get-last-sibling)
6805 (org-get-last-sibling))
6806 (point)))
6807 (end (save-excursion
6808 (and (org-get-next-sibling)
6809 (org-get-next-sibling)
6810 (org-get-next-sibling))
6811 (if (org-at-heading-p)
6812 (point-at-eol)
6813 (point))))
6814 (level (looking-at "\\*+"))
6815 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6816 (save-excursion
6817 (save-restriction
6818 (narrow-to-region beg end)
6819 (when re
6820 ;; Properly fold already folded siblings
6821 (goto-char (point-min))
6822 (while (re-search-forward re nil t)
6823 (if (and (not (outline-invisible-p))
6824 (save-excursion
6825 (goto-char (point-at-eol)) (outline-invisible-p)))
6826 (hide-entry))))
6827 (org-cycle-show-empty-lines 'overview)
6828 (org-cycle-hide-drawers 'overview)))))
6830 (defun org-cycle-show-empty-lines (state)
6831 "Show empty lines above all visible headlines.
6832 The region to be covered depends on STATE when called through
6833 `org-cycle-hook'. Lisp program can use t for STATE to get the
6834 entire buffer covered. Note that an empty line is only shown if there
6835 are at least `org-cycle-separator-lines' empty lines before the headline."
6836 (when (not (= org-cycle-separator-lines 0))
6837 (save-excursion
6838 (let* ((n (abs org-cycle-separator-lines))
6839 (re (cond
6840 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6841 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6842 (t (let ((ns (number-to-string (- n 2))))
6843 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6844 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6845 beg end b e)
6846 (cond
6847 ((memq state '(overview contents t))
6848 (setq beg (point-min) end (point-max)))
6849 ((memq state '(children folded))
6850 (setq beg (point) end (progn (org-end-of-subtree t t)
6851 (beginning-of-line 2)
6852 (point)))))
6853 (when beg
6854 (goto-char beg)
6855 (while (re-search-forward re end t)
6856 (unless (get-char-property (match-end 1) 'invisible)
6857 (setq e (match-end 1))
6858 (if (< org-cycle-separator-lines 0)
6859 (setq b (save-excursion
6860 (goto-char (match-beginning 0))
6861 (org-back-over-empty-lines)
6862 (if (save-excursion
6863 (goto-char (max (point-min) (1- (point))))
6864 (org-at-heading-p))
6865 (1- (point))
6866 (point))))
6867 (setq b (match-beginning 1)))
6868 (outline-flag-region b e nil)))))))
6869 ;; Never hide empty lines at the end of the file.
6870 (save-excursion
6871 (goto-char (point-max))
6872 (outline-previous-heading)
6873 (outline-end-of-heading)
6874 (if (and (looking-at "[ \t\n]+")
6875 (= (match-end 0) (point-max)))
6876 (outline-flag-region (point) (match-end 0) nil))))
6878 (defun org-show-empty-lines-in-parent ()
6879 "Move to the parent and re-show empty lines before visible headlines."
6880 (save-excursion
6881 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6882 (org-cycle-show-empty-lines context))))
6884 (defun org-files-list ()
6885 "Return `org-agenda-files' list, plus all open org-mode files.
6886 This is useful for operations that need to scan all of a user's
6887 open and agenda-wise Org files."
6888 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6889 (dolist (buf (buffer-list))
6890 (with-current-buffer buf
6891 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6892 (let ((file (expand-file-name (buffer-file-name))))
6893 (unless (member file files)
6894 (push file files))))))
6895 files))
6897 (defsubst org-entry-beginning-position ()
6898 "Return the beginning position of the current entry."
6899 (save-excursion (outline-back-to-heading t) (point)))
6901 (defsubst org-entry-end-position ()
6902 "Return the end position of the current entry."
6903 (save-excursion (outline-next-heading) (point)))
6905 (defun org-cycle-hide-drawers (state)
6906 "Re-hide all drawers after a visibility state change."
6907 (when (and (derived-mode-p 'org-mode)
6908 (not (memq state '(overview folded contents))))
6909 (save-excursion
6910 (let* ((globalp (memq state '(contents all)))
6911 (beg (if globalp (point-min) (point)))
6912 (end (if globalp (point-max)
6913 (if (eq state 'children)
6914 (save-excursion (outline-next-heading) (point))
6915 (org-end-of-subtree t)))))
6916 (goto-char beg)
6917 (while (re-search-forward org-drawer-regexp end t)
6918 (org-flag-drawer t))))))
6920 (defun org-cycle-hide-inline-tasks (state)
6921 "Re-hide inline task when switching to 'contents visibility state."
6922 (when (and (eq state 'contents)
6923 (boundp 'org-inlinetask-min-level)
6924 org-inlinetask-min-level)
6925 (hide-sublevels (1- org-inlinetask-min-level))))
6927 (defun org-flag-drawer (flag)
6928 "When FLAG is non-nil, hide the drawer we are within.
6929 Otherwise make it visible."
6930 (save-excursion
6931 (beginning-of-line 1)
6932 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6933 (let ((b (match-end 0)))
6934 (if (re-search-forward
6935 "^[ \t]*:END:"
6936 (save-excursion (outline-next-heading) (point)) t)
6937 (outline-flag-region b (point-at-eol) flag)
6938 (error ":END: line missing at position %s" b))))))
6940 (defun org-subtree-end-visible-p ()
6941 "Is the end of the current subtree visible?"
6942 (pos-visible-in-window-p
6943 (save-excursion (org-end-of-subtree t) (point))))
6945 (defun org-first-headline-recenter (&optional N)
6946 "Move cursor to the first headline and recenter the headline.
6947 Optional argument N means put the headline into the Nth line of the window."
6948 (goto-char (point-min))
6949 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6950 (beginning-of-line)
6951 (recenter (prefix-numeric-value N))))
6953 ;;; Saving and restoring visibility
6955 (defun org-outline-overlay-data (&optional use-markers)
6956 "Return a list of the locations of all outline overlays.
6957 These are overlays with the `invisible' property value `outline'.
6958 The return value is a list of cons cells, with start and stop
6959 positions for each overlay.
6960 If USE-MARKERS is set, return the positions as markers."
6961 (let (beg end)
6962 (save-excursion
6963 (save-restriction
6964 (widen)
6965 (delq nil
6966 (mapcar (lambda (o)
6967 (when (eq (overlay-get o 'invisible) 'outline)
6968 (setq beg (overlay-start o)
6969 end (overlay-end o))
6970 (and beg end (> end beg)
6971 (if use-markers
6972 (cons (move-marker (make-marker) beg)
6973 (move-marker (make-marker) end))
6974 (cons beg end)))))
6975 (overlays-in (point-min) (point-max))))))))
6977 (defun org-set-outline-overlay-data (data)
6978 "Create visibility overlays for all positions in DATA.
6979 DATA should have been made by `org-outline-overlay-data'."
6980 (let (o)
6981 (save-excursion
6982 (save-restriction
6983 (widen)
6984 (show-all)
6985 (mapc (lambda (c)
6986 (outline-flag-region (car c) (cdr c) t))
6987 data)))))
6989 ;;; Folding of blocks
6991 (defvar org-hide-block-overlays nil
6992 "Overlays hiding blocks.")
6993 (make-variable-buffer-local 'org-hide-block-overlays)
6995 (defun org-block-map (function &optional start end)
6996 "Call FUNCTION at the head of all source blocks in the current buffer.
6997 Optional arguments START and END can be used to limit the range."
6998 (let ((start (or start (point-min)))
6999 (end (or end (point-max))))
7000 (save-excursion
7001 (goto-char start)
7002 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7003 (save-excursion
7004 (save-match-data
7005 (goto-char (match-beginning 0))
7006 (funcall function)))))))
7008 (defun org-hide-block-toggle-all ()
7009 "Toggle the visibility of all blocks in the current buffer."
7010 (org-block-map #'org-hide-block-toggle))
7012 (defun org-hide-block-all ()
7013 "Fold all blocks in the current buffer."
7014 (interactive)
7015 (org-show-block-all)
7016 (org-block-map #'org-hide-block-toggle-maybe))
7018 (defun org-show-block-all ()
7019 "Unfold all blocks in the current buffer."
7020 (interactive)
7021 (mapc 'delete-overlay org-hide-block-overlays)
7022 (setq org-hide-block-overlays nil))
7024 (defun org-hide-block-toggle-maybe ()
7025 "Toggle visibility of block at point."
7026 (interactive)
7027 (let ((case-fold-search t))
7028 (if (save-excursion
7029 (beginning-of-line 1)
7030 (looking-at org-block-regexp))
7031 (progn (org-hide-block-toggle)
7032 t) ;; to signal that we took action
7033 nil))) ;; to signal that we did not
7035 (defun org-hide-block-toggle (&optional force)
7036 "Toggle the visibility of the current block."
7037 (interactive)
7038 (save-excursion
7039 (beginning-of-line)
7040 (if (re-search-forward org-block-regexp nil t)
7041 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7042 (end (match-end 0)) ;; end of entire body
7044 (if (memq t (mapcar (lambda (overlay)
7045 (eq (overlay-get overlay 'invisible)
7046 'org-hide-block))
7047 (overlays-at start)))
7048 (if (or (not force) (eq force 'off))
7049 (mapc (lambda (ov)
7050 (when (member ov org-hide-block-overlays)
7051 (setq org-hide-block-overlays
7052 (delq ov org-hide-block-overlays)))
7053 (when (eq (overlay-get ov 'invisible)
7054 'org-hide-block)
7055 (delete-overlay ov)))
7056 (overlays-at start)))
7057 (setq ov (make-overlay start end))
7058 (overlay-put ov 'invisible 'org-hide-block)
7059 ;; make the block accessible to isearch
7060 (overlay-put
7061 ov 'isearch-open-invisible
7062 (lambda (ov)
7063 (when (member ov org-hide-block-overlays)
7064 (setq org-hide-block-overlays
7065 (delq ov org-hide-block-overlays)))
7066 (when (eq (overlay-get ov 'invisible)
7067 'org-hide-block)
7068 (delete-overlay ov))))
7069 (push ov org-hide-block-overlays)))
7070 (error "Not looking at a source block"))))
7072 ;; org-tab-after-check-for-cycling-hook
7073 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7074 ;; Remove overlays when changing major mode
7075 (add-hook 'org-mode-hook
7076 (lambda () (org-add-hook 'change-major-mode-hook
7077 'org-show-block-all 'append 'local)))
7079 ;;; Org-goto
7081 (defvar org-goto-window-configuration nil)
7082 (defvar org-goto-marker nil)
7083 (defvar org-goto-map)
7084 (defun org-goto-map ()
7085 "Set the keymap `org-goto'."
7086 (setq org-goto-map
7087 (let ((map (make-sparse-keymap)))
7088 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7089 mouse-drag-region universal-argument org-occur))
7090 cmd)
7091 (while (setq cmd (pop cmds))
7092 (substitute-key-definition cmd cmd map global-map)))
7093 (suppress-keymap map)
7094 (org-defkey map "\C-m" 'org-goto-ret)
7095 (org-defkey map [(return)] 'org-goto-ret)
7096 (org-defkey map [(left)] 'org-goto-left)
7097 (org-defkey map [(right)] 'org-goto-right)
7098 (org-defkey map [(control ?g)] 'org-goto-quit)
7099 (org-defkey map "\C-i" 'org-cycle)
7100 (org-defkey map [(tab)] 'org-cycle)
7101 (org-defkey map [(down)] 'outline-next-visible-heading)
7102 (org-defkey map [(up)] 'outline-previous-visible-heading)
7103 (if org-goto-auto-isearch
7104 (if (fboundp 'define-key-after)
7105 (define-key-after map [t] 'org-goto-local-auto-isearch)
7106 nil)
7107 (org-defkey map "q" 'org-goto-quit)
7108 (org-defkey map "n" 'outline-next-visible-heading)
7109 (org-defkey map "p" 'outline-previous-visible-heading)
7110 (org-defkey map "f" 'outline-forward-same-level)
7111 (org-defkey map "b" 'outline-backward-same-level)
7112 (org-defkey map "u" 'outline-up-heading))
7113 (org-defkey map "/" 'org-occur)
7114 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7115 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7116 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7117 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7118 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7119 map)))
7121 (defconst org-goto-help
7122 "Browse buffer copy, to find location or copy text.%s
7123 RET=jump to location C-g=quit and return to previous location
7124 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7126 (defvar org-goto-start-pos) ; dynamically scoped parameter
7128 (defun org-goto (&optional alternative-interface)
7129 "Look up a different location in the current file, keeping current visibility.
7131 When you want look-up or go to a different location in a
7132 document, the fastest way is often to fold the entire buffer and
7133 then dive into the tree. This method has the disadvantage, that
7134 the previous location will be folded, which may not be what you
7135 want.
7137 This command works around this by showing a copy of the current
7138 buffer in an indirect buffer, in overview mode. You can dive
7139 into the tree in that copy, use org-occur and incremental search
7140 to find a location. When pressing RET or `Q', the command
7141 returns to the original buffer in which the visibility is still
7142 unchanged. After RET it will also jump to the location selected
7143 in the indirect buffer and expose the headline hierarchy above.
7145 With a prefix argument, use the alternative interface: e.g. if
7146 `org-goto-interface' is 'outline use 'outline-path-completion."
7147 (interactive "P")
7148 (org-goto-map)
7149 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7150 (org-refile-use-outline-path t)
7151 (org-refile-target-verify-function nil)
7152 (interface
7153 (if (not alternative-interface)
7154 org-goto-interface
7155 (if (eq org-goto-interface 'outline)
7156 'outline-path-completion
7157 'outline)))
7158 (org-goto-start-pos (point))
7159 (selected-point
7160 (if (eq interface 'outline)
7161 (car (org-get-location (current-buffer) org-goto-help))
7162 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7163 (org-refile-check-position pa)
7164 (nth 3 pa)))))
7165 (if selected-point
7166 (progn
7167 (org-mark-ring-push org-goto-start-pos)
7168 (goto-char selected-point)
7169 (if (or (outline-invisible-p) (org-invisible-p2))
7170 (org-show-context 'org-goto)))
7171 (message "Quit"))))
7173 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7174 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7175 (defvar org-goto-local-auto-isearch-map) ; defined below
7177 (defun org-get-location (buf help)
7178 "Let the user select a location in the Org-mode buffer BUF.
7179 This function uses a recursive edit. It returns the selected position
7180 or nil."
7181 (org-no-popups
7182 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7183 (isearch-hide-immediately nil)
7184 (isearch-search-fun-function
7185 (lambda () 'org-goto-local-search-headings))
7186 (org-goto-selected-point org-goto-exit-command))
7187 (save-excursion
7188 (save-window-excursion
7189 (delete-other-windows)
7190 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7191 (org-pop-to-buffer-same-window
7192 (condition-case nil
7193 (make-indirect-buffer (current-buffer) "*org-goto*")
7194 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7195 (with-output-to-temp-buffer "*Org Help*"
7196 (princ (format help (if org-goto-auto-isearch
7197 " Just type for auto-isearch."
7198 " n/p/f/b/u to navigate, q to quit."))))
7199 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7200 (setq buffer-read-only nil)
7201 (let ((org-startup-truncated t)
7202 (org-startup-folded nil)
7203 (org-startup-align-all-tables nil))
7204 (org-mode)
7205 (org-overview))
7206 (setq buffer-read-only t)
7207 (if (and (boundp 'org-goto-start-pos)
7208 (integer-or-marker-p org-goto-start-pos))
7209 (let ((org-show-hierarchy-above t)
7210 (org-show-siblings t)
7211 (org-show-following-heading t))
7212 (goto-char org-goto-start-pos)
7213 (and (outline-invisible-p) (org-show-context)))
7214 (goto-char (point-min)))
7215 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7216 (message "Select location and press RET")
7217 (use-local-map org-goto-map)
7218 (recursive-edit)))
7219 (kill-buffer "*org-goto*")
7220 (cons org-goto-selected-point org-goto-exit-command))))
7222 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7223 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7224 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7225 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7227 (defun org-goto-local-search-headings (string bound noerror)
7228 "Search and make sure that any matches are in headlines."
7229 (catch 'return
7230 (while (if isearch-forward
7231 (search-forward string bound noerror)
7232 (search-backward string bound noerror))
7233 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7234 (and (member :headline context)
7235 (not (member :tags context))))
7236 (throw 'return (point))))))
7238 (defun org-goto-local-auto-isearch ()
7239 "Start isearch."
7240 (interactive)
7241 (goto-char (point-min))
7242 (let ((keys (this-command-keys)))
7243 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7244 (isearch-mode t)
7245 (isearch-process-search-char (string-to-char keys)))))
7247 (defun org-goto-ret (&optional arg)
7248 "Finish `org-goto' by going to the new location."
7249 (interactive "P")
7250 (setq org-goto-selected-point (point)
7251 org-goto-exit-command 'return)
7252 (throw 'exit nil))
7254 (defun org-goto-left ()
7255 "Finish `org-goto' by going to the new location."
7256 (interactive)
7257 (if (org-at-heading-p)
7258 (progn
7259 (beginning-of-line 1)
7260 (setq org-goto-selected-point (point)
7261 org-goto-exit-command 'left)
7262 (throw 'exit nil))
7263 (error "Not on a heading")))
7265 (defun org-goto-right ()
7266 "Finish `org-goto' by going to the new location."
7267 (interactive)
7268 (if (org-at-heading-p)
7269 (progn
7270 (setq org-goto-selected-point (point)
7271 org-goto-exit-command 'right)
7272 (throw 'exit nil))
7273 (error "Not on a heading")))
7275 (defun org-goto-quit ()
7276 "Finish `org-goto' without cursor motion."
7277 (interactive)
7278 (setq org-goto-selected-point nil)
7279 (setq org-goto-exit-command 'quit)
7280 (throw 'exit nil))
7282 ;;; Indirect buffer display of subtrees
7284 (defvar org-indirect-dedicated-frame nil
7285 "This is the frame being used for indirect tree display.")
7286 (defvar org-last-indirect-buffer nil)
7288 (defun org-tree-to-indirect-buffer (&optional arg)
7289 "Create indirect buffer and narrow it to current subtree.
7290 With a numerical prefix ARG, go up to this level and then take that tree.
7291 If ARG is negative, go up that many levels.
7293 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7294 indirect buffer previously made with this command, to avoid proliferation of
7295 indirect buffers. However, when you call the command with a \
7296 \\[universal-argument] prefix, or
7297 when `org-indirect-buffer-display' is `new-frame', the last buffer
7298 is kept so that you can work with several indirect buffers at the same time.
7299 If `org-indirect-buffer-display' is `dedicated-frame', the \
7300 \\[universal-argument] prefix also
7301 requests that a new frame be made for the new buffer, so that the dedicated
7302 frame is not changed."
7303 (interactive "P")
7304 (let ((cbuf (current-buffer))
7305 (cwin (selected-window))
7306 (pos (point))
7307 beg end level heading ibuf)
7308 (save-excursion
7309 (org-back-to-heading t)
7310 (when (numberp arg)
7311 (setq level (org-outline-level))
7312 (if (< arg 0) (setq arg (+ level arg)))
7313 (while (> (setq level (org-outline-level)) arg)
7314 (org-up-heading-safe)))
7315 (setq beg (point)
7316 heading (org-get-heading))
7317 (org-end-of-subtree t t)
7318 (if (org-at-heading-p) (backward-char 1))
7319 (setq end (point)))
7320 (if (and (buffer-live-p org-last-indirect-buffer)
7321 (not (eq org-indirect-buffer-display 'new-frame))
7322 (not arg))
7323 (kill-buffer org-last-indirect-buffer))
7324 (setq ibuf (org-get-indirect-buffer cbuf)
7325 org-last-indirect-buffer ibuf)
7326 (cond
7327 ((or (eq org-indirect-buffer-display 'new-frame)
7328 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7329 (select-frame (make-frame))
7330 (delete-other-windows)
7331 (org-pop-to-buffer-same-window ibuf)
7332 (org-set-frame-title heading))
7333 ((eq org-indirect-buffer-display 'dedicated-frame)
7334 (raise-frame
7335 (select-frame (or (and org-indirect-dedicated-frame
7336 (frame-live-p org-indirect-dedicated-frame)
7337 org-indirect-dedicated-frame)
7338 (setq org-indirect-dedicated-frame (make-frame)))))
7339 (delete-other-windows)
7340 (org-pop-to-buffer-same-window ibuf)
7341 (org-set-frame-title (concat "Indirect: " heading)))
7342 ((eq org-indirect-buffer-display 'current-window)
7343 (org-pop-to-buffer-same-window ibuf))
7344 ((eq org-indirect-buffer-display 'other-window)
7345 (pop-to-buffer ibuf))
7346 (t (error "Invalid value")))
7347 (if (featurep 'xemacs)
7348 (save-excursion (org-mode) (turn-on-font-lock)))
7349 (narrow-to-region beg end)
7350 (show-all)
7351 (goto-char pos)
7352 (run-hook-with-args 'org-cycle-hook 'all)
7353 (and (window-live-p cwin) (select-window cwin))))
7355 (defun org-get-indirect-buffer (&optional buffer)
7356 (setq buffer (or buffer (current-buffer)))
7357 (let ((n 1) (base (buffer-name buffer)) bname)
7358 (while (buffer-live-p
7359 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7360 (setq n (1+ n)))
7361 (condition-case nil
7362 (make-indirect-buffer buffer bname 'clone)
7363 (error (make-indirect-buffer buffer bname)))))
7365 (defun org-set-frame-title (title)
7366 "Set the title of the current frame to the string TITLE."
7367 ;; FIXME: how to name a single frame in XEmacs???
7368 (unless (featurep 'xemacs)
7369 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7371 ;;;; Structure editing
7373 ;;; Inserting headlines
7375 (defun org-previous-line-empty-p (&optional next)
7376 "Is the previous line a blank line?
7377 When NEXT is non-nil, check the next line instead."
7378 (save-excursion
7379 (and (not (bobp))
7380 (or (beginning-of-line (if next 2 0)) t)
7381 (save-match-data
7382 (looking-at "[ \t]*$")))))
7384 (defun org-insert-heading (&optional arg invisible-ok)
7385 "Insert a new heading or item with same depth at point.
7386 If point is in a plain list and ARG is nil, create a new list item.
7387 With one universal prefix argument, insert a heading even in lists.
7388 With two universal prefix arguments, insert the heading at the end
7389 of the parent subtree.
7391 If point is at the beginning of a headline, insert a sibling before
7392 the current headline. If point is not at the beginning, split the line
7393 and create a new headline with the text in the current line after point
7394 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7396 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7397 This is important for non-interactive uses of the command."
7398 (interactive "P")
7399 (cond
7400 ((or (= (buffer-size) 0)
7401 (and (not (save-excursion
7402 (and (ignore-errors (org-back-to-heading invisible-ok))
7403 (org-at-heading-p))))
7404 (or arg (not (org-in-item-p)))))
7405 (insert
7406 (if (org-previous-line-empty-p) "" "\n")
7407 (if (org-in-src-block-p) ",* " "* "))
7408 (run-hooks 'org-insert-heading-hook))
7409 ((or arg (not (org-insert-item
7410 (save-excursion
7411 (beginning-of-line)
7412 (looking-at org-list-full-item-re)
7413 (match-string 3)))))
7414 (let (begn endn)
7415 (when (org-buffer-narrowed-p)
7416 (setq begn (point-min) endn (point-max))
7417 (widen))
7418 (let* ((empty-line-p nil)
7419 (eops (equal arg '(16))) ; insert at end of parent subtree
7420 (org-insert-heading-respect-content
7421 (or (not (null arg)) org-insert-heading-respect-content))
7422 (level nil)
7423 (on-heading (org-at-heading-p))
7424 (head (save-excursion
7425 (condition-case nil
7426 (progn
7427 (org-back-to-heading invisible-ok)
7428 (when (and (not on-heading)
7429 (featurep 'org-inlinetask)
7430 (integerp org-inlinetask-min-level)
7431 (>= (length (match-string 0))
7432 org-inlinetask-min-level))
7433 ;; Find a heading level before the inline task
7434 (while (and (setq level (org-up-heading-safe))
7435 (>= level org-inlinetask-min-level)))
7436 (if (org-at-heading-p)
7437 (org-back-to-heading invisible-ok)
7438 (error "This should not happen")))
7439 (unless (and (save-excursion
7440 (save-match-data
7441 (org-backward-heading-same-level 1 invisible-ok))
7442 (= (point) (match-beginning 0)))
7443 (not (org-previous-line-empty-p t)))
7444 (setq empty-line-p (org-previous-line-empty-p)))
7445 (match-string 0))
7446 (error "* "))))
7447 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7448 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7449 pos hide-previous previous-pos)
7450 (if ;; At the beginning of a heading, open a new line for insertiong
7451 (and (bolp) (org-at-heading-p)
7452 (not eops)
7453 (or (bobp)
7454 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7455 (open-line (if blank 2 1))
7456 (save-excursion
7457 (setq previous-pos (point-at-bol))
7458 (end-of-line)
7459 (setq hide-previous (outline-invisible-p)))
7460 (and org-insert-heading-respect-content
7461 (save-excursion
7462 (while (outline-invisible-p)
7463 (org-show-subtree)
7464 (org-up-heading-safe))))
7465 (let ((split
7466 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7467 (save-excursion
7468 (let ((p (point)))
7469 (goto-char (point-at-bol))
7470 (and (looking-at org-complex-heading-regexp)
7471 (match-beginning 4)
7472 (> p (match-beginning 4)))))))
7473 tags pos)
7474 (cond
7475 ;; Insert a new line, possibly at end of parent subtree
7476 (org-insert-heading-respect-content
7477 (if (not eops)
7478 (progn
7479 (org-end-of-subtree nil t)
7480 (and (looking-at "^\\*") (backward-char 1))
7481 (while (and (not (bobp))
7482 ;; Don't delete spaces in empty headlines
7483 (not (looking-back org-outline-regexp))
7484 (member (char-before) '(?\ ?\t ?\n)))
7485 (backward-delete-char 1)))
7486 (let ((p (point)))
7487 (org-up-heading-safe)
7488 (if (= p (point))
7489 (goto-char (point-max))
7490 (org-end-of-subtree nil t))))
7491 (when (featurep 'org-inlinetask)
7492 (while (and (not (eobp))
7493 (looking-at "\\(\\*+\\)[ \t]+")
7494 (>= (length (match-string 1))
7495 org-inlinetask-min-level))
7496 (org-end-of-subtree nil t)))
7497 (or (bolp) (newline))
7498 (or (org-previous-line-empty-p)
7499 (and blank (newline)))
7500 (if (or empty-line-p eops) (open-line 1)))
7501 ;; Insert a headling containing text after point
7502 ((org-at-heading-p)
7503 (when hide-previous
7504 (show-children)
7505 (org-show-entry))
7506 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7507 (setq tags (and (match-end 2) (match-string 2)))
7508 (and (match-end 1)
7509 (delete-region (match-beginning 1) (match-end 1)))
7510 (setq pos (point-at-bol))
7511 (or split (end-of-line 1))
7512 (delete-horizontal-space)
7513 (if (string-match "\\`\\*+\\'"
7514 (buffer-substring (point-at-bol) (point)))
7515 (insert " "))
7516 (newline (if blank 2 1))
7517 (when tags
7518 (save-excursion
7519 (goto-char pos)
7520 (end-of-line 1)
7521 (insert " " tags)
7522 (org-set-tags nil 'align))))
7524 (or split (end-of-line 1))
7525 (newline (if blank 2 1))))))
7526 (insert head) (just-one-space)
7527 (setq pos (point))
7528 (end-of-line 1)
7529 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7530 (when (and org-insert-heading-respect-content hide-previous)
7531 (save-excursion
7532 (goto-char previous-pos)
7533 (hide-subtree)))
7534 (when (and begn endn)
7535 (narrow-to-region (min (point) begn) (max (point) endn)))
7536 (run-hooks 'org-insert-heading-hook))))))
7538 (defun org-get-heading (&optional no-tags no-todo)
7539 "Return the heading of the current entry, without the stars.
7540 When NO-TAGS is non-nil, don't include tags.
7541 When NO-TODO is non-nil, don't include TODO keywords."
7542 (save-excursion
7543 (org-back-to-heading t)
7544 (cond
7545 ((and no-tags no-todo)
7546 (looking-at org-complex-heading-regexp)
7547 (match-string 4))
7548 (no-tags
7549 (looking-at (concat org-outline-regexp
7550 "\\(.*?\\)"
7551 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7552 (match-string 1))
7553 (no-todo
7554 (looking-at org-todo-line-regexp)
7555 (match-string 3))
7556 (t (looking-at org-heading-regexp)
7557 (match-string 2)))))
7559 (defvar orgstruct-mode) ; defined below
7561 (defun org-heading-components ()
7562 "Return the components of the current heading.
7563 This is a list with the following elements:
7564 - the level as an integer
7565 - the reduced level, different if `org-odd-levels-only' is set.
7566 - the TODO keyword, or nil
7567 - the priority character, like ?A, or nil if no priority is given
7568 - the headline text itself, or the tags string if no headline text
7569 - the tags string, or nil."
7570 (save-excursion
7571 (org-back-to-heading t)
7572 (if (let (case-fold-search)
7573 (looking-at
7574 (if orgstruct-mode
7575 org-heading-regexp
7576 org-complex-heading-regexp)))
7577 (if orgstruct-mode
7578 (list (length (match-string 1))
7579 (org-reduced-level (length (match-string 1)))
7582 (match-string 2)
7583 nil)
7584 (list (length (match-string 1))
7585 (org-reduced-level (length (match-string 1)))
7586 (org-match-string-no-properties 2)
7587 (and (match-end 3) (aref (match-string 3) 2))
7588 (org-match-string-no-properties 4)
7589 (org-match-string-no-properties 5))))))
7591 (defun org-get-entry ()
7592 "Get the entry text, after heading, entire subtree."
7593 (save-excursion
7594 (org-back-to-heading t)
7595 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7597 (defun org-insert-heading-after-current ()
7598 "Insert a new heading with same level as current, after current subtree."
7599 (interactive)
7600 (org-back-to-heading)
7601 (org-insert-heading)
7602 (org-move-subtree-down)
7603 (end-of-line 1))
7605 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7606 "Insert heading with `org-insert-heading-respect-content' set to t."
7607 (interactive "P")
7608 (let ((org-insert-heading-respect-content t))
7609 (org-insert-heading arg invisible-ok)))
7611 (defun org-insert-todo-heading-respect-content (&optional force-state)
7612 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7613 (interactive "P")
7614 (let ((org-insert-heading-respect-content t))
7615 (org-insert-todo-heading force-state t)))
7617 (defun org-insert-todo-heading (arg &optional force-heading)
7618 "Insert a new heading with the same level and TODO state as current heading.
7619 If the heading has no TODO state, or if the state is DONE, use the first
7620 state (TODO by default). Also one prefix arg, force first state. With two
7621 prefix args, force inserting at the end of the parent subtree."
7622 (interactive "P")
7623 (when (or force-heading (not (org-insert-item 'checkbox)))
7624 (org-insert-heading (or (and (equal arg '(16)) '(16))
7625 force-heading))
7626 (save-excursion
7627 (org-back-to-heading)
7628 (outline-previous-heading)
7629 (looking-at org-todo-line-regexp))
7630 (let*
7631 ((new-mark-x
7632 (if (or arg
7633 (not (match-beginning 2))
7634 (member (match-string 2) org-done-keywords))
7635 (car org-todo-keywords-1)
7636 (match-string 2)))
7637 (new-mark
7639 (run-hook-with-args-until-success
7640 'org-todo-get-default-hook new-mark-x nil)
7641 new-mark-x)))
7642 (beginning-of-line 1)
7643 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7644 (if org-treat-insert-todo-heading-as-state-change
7645 (org-todo new-mark)
7646 (insert new-mark " "))))
7647 (when org-provide-todo-statistics
7648 (org-update-parent-todo-statistics))))
7650 (defun org-insert-subheading (arg)
7651 "Insert a new subheading and demote it.
7652 Works for outline headings and for plain lists alike."
7653 (interactive "P")
7654 (org-insert-heading arg)
7655 (cond
7656 ((org-at-heading-p) (org-do-demote))
7657 ((org-at-item-p) (org-indent-item))))
7659 (defun org-insert-todo-subheading (arg)
7660 "Insert a new subheading with TODO keyword or checkbox and demote it.
7661 Works for outline headings and for plain lists alike."
7662 (interactive "P")
7663 (org-insert-todo-heading arg)
7664 (cond
7665 ((org-at-heading-p) (org-do-demote))
7666 ((org-at-item-p) (org-indent-item))))
7668 ;;; Promotion and Demotion
7670 (defvar org-after-demote-entry-hook nil
7671 "Hook run after an entry has been demoted.
7672 The cursor will be at the beginning of the entry.
7673 When a subtree is being demoted, the hook will be called for each node.")
7675 (defvar org-after-promote-entry-hook nil
7676 "Hook run after an entry has been promoted.
7677 The cursor will be at the beginning of the entry.
7678 When a subtree is being promoted, the hook will be called for each node.")
7680 (defun org-promote-subtree ()
7681 "Promote the entire subtree.
7682 See also `org-promote'."
7683 (interactive)
7684 (save-excursion
7685 (org-with-limited-levels (org-map-tree 'org-promote)))
7686 (org-fix-position-after-promote))
7688 (defun org-demote-subtree ()
7689 "Demote the entire subtree. See `org-demote'.
7690 See also `org-promote'."
7691 (interactive)
7692 (save-excursion
7693 (org-with-limited-levels (org-map-tree 'org-demote)))
7694 (org-fix-position-after-promote))
7697 (defun org-do-promote ()
7698 "Promote the current heading higher up the tree.
7699 If the region is active in `transient-mark-mode', promote all headings
7700 in the region."
7701 (interactive)
7702 (save-excursion
7703 (if (org-region-active-p)
7704 (org-map-region 'org-promote (region-beginning) (region-end))
7705 (org-promote)))
7706 (org-fix-position-after-promote))
7708 (defun org-do-demote ()
7709 "Demote the current heading lower down the tree.
7710 If the region is active in `transient-mark-mode', demote all headings
7711 in the region."
7712 (interactive)
7713 (save-excursion
7714 (if (org-region-active-p)
7715 (org-map-region 'org-demote (region-beginning) (region-end))
7716 (org-demote)))
7717 (org-fix-position-after-promote))
7719 (defun org-fix-position-after-promote ()
7720 "Make sure that after pro/demotion cursor position is right."
7721 (let ((pos (point)))
7722 (when (save-excursion
7723 (beginning-of-line 1)
7724 (looking-at org-todo-line-regexp)
7725 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7726 (cond ((eobp) (insert " "))
7727 ((eolp) (insert " "))
7728 ((equal (char-after) ?\ ) (forward-char 1))))))
7730 (defun org-current-level ()
7731 "Return the level of the current entry, or nil if before the first headline.
7732 The level is the number of stars at the beginning of the headline."
7733 (save-excursion
7734 (org-with-limited-levels
7735 (if (ignore-errors (org-back-to-heading t))
7736 (funcall outline-level)))))
7738 (defun org-get-previous-line-level ()
7739 "Return the outline depth of the last headline before the current line.
7740 Returns 0 for the first headline in the buffer, and nil if before the
7741 first headline."
7742 (let ((current-level (org-current-level))
7743 (prev-level (when (> (line-number-at-pos) 1)
7744 (save-excursion
7745 (beginning-of-line 0)
7746 (org-current-level)))))
7747 (cond ((null current-level) nil) ; Before first headline
7748 ((null prev-level) 0) ; At first headline
7749 (prev-level))))
7751 (defun org-reduced-level (l)
7752 "Compute the effective level of a heading.
7753 This takes into account the setting of `org-odd-levels-only'."
7754 (cond
7755 ((zerop l) 0)
7756 (org-odd-levels-only (1+ (floor (/ l 2))))
7757 (t l)))
7759 (defun org-level-increment ()
7760 "Return the number of stars that will be added or removed at a
7761 time to headlines when structure editing, based on the value of
7762 `org-odd-levels-only'."
7763 (if org-odd-levels-only 2 1))
7765 (defun org-get-valid-level (level &optional change)
7766 "Rectify a level change under the influence of `org-odd-levels-only'
7767 LEVEL is a current level, CHANGE is by how much the level should be
7768 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7769 even level numbers will become the next higher odd number."
7770 (if org-odd-levels-only
7771 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7772 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7773 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7774 (max 1 (+ level (or change 0)))))
7776 (if (boundp 'define-obsolete-function-alias)
7777 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7778 (define-obsolete-function-alias 'org-get-legal-level
7779 'org-get-valid-level)
7780 (define-obsolete-function-alias 'org-get-legal-level
7781 'org-get-valid-level "23.1")))
7783 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7784 ;; ̀org-with-limited-levels'
7785 (defun org-promote ()
7786 "Promote the current heading higher up the tree.
7787 If the region is active in `transient-mark-mode', promote all headings
7788 in the region."
7789 (org-back-to-heading t)
7790 (let* ((level (save-match-data (funcall outline-level)))
7791 (after-change-functions (remove 'flyspell-after-change-function
7792 after-change-functions))
7793 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7794 (diff (abs (- level (length up-head) -1))))
7795 (cond ((and (= level 1) org-called-with-limited-levels
7796 org-allow-promoting-top-level-subtree)
7797 (replace-match "# " nil t))
7798 ((= level 1)
7799 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7800 (t (replace-match up-head nil t)))
7801 ;; Fixup tag positioning
7802 (unless (= level 1)
7803 (and org-auto-align-tags (org-set-tags nil t))
7804 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7805 (run-hooks 'org-after-promote-entry-hook)))
7807 (defun org-demote ()
7808 "Demote the current heading lower down the tree.
7809 If the region is active in `transient-mark-mode', demote all headings
7810 in the region."
7811 (org-back-to-heading t)
7812 (let* ((level (save-match-data (funcall outline-level)))
7813 (after-change-functions (remove 'flyspell-after-change-function
7814 after-change-functions))
7815 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7816 (diff (abs (- level (length down-head) -1))))
7817 (replace-match down-head nil t)
7818 ;; Fixup tag positioning
7819 (and org-auto-align-tags (org-set-tags nil t))
7820 (if org-adapt-indentation (org-fixup-indentation diff))
7821 (run-hooks 'org-after-demote-entry-hook)))
7823 (defun org-cycle-level ()
7824 "Cycle the level of an empty headline through possible states.
7825 This goes first to child, then to parent, level, then up the hierarchy.
7826 After top level, it switches back to sibling level."
7827 (interactive)
7828 (let ((org-adapt-indentation nil))
7829 (when (org-point-at-end-of-empty-headline)
7830 (setq this-command 'org-cycle-level) ; Only needed for caching
7831 (let ((cur-level (org-current-level))
7832 (prev-level (org-get-previous-line-level)))
7833 (cond
7834 ;; If first headline in file, promote to top-level.
7835 ((= prev-level 0)
7836 (loop repeat (/ (- cur-level 1) (org-level-increment))
7837 do (org-do-promote)))
7838 ;; If same level as prev, demote one.
7839 ((= prev-level cur-level)
7840 (org-do-demote))
7841 ;; If parent is top-level, promote to top level if not already.
7842 ((= prev-level 1)
7843 (loop repeat (/ (- cur-level 1) (org-level-increment))
7844 do (org-do-promote)))
7845 ;; If top-level, return to prev-level.
7846 ((= cur-level 1)
7847 (loop repeat (/ (- prev-level 1) (org-level-increment))
7848 do (org-do-demote)))
7849 ;; If less than prev-level, promote one.
7850 ((< cur-level prev-level)
7851 (org-do-promote))
7852 ;; If deeper than prev-level, promote until higher than
7853 ;; prev-level.
7854 ((> cur-level prev-level)
7855 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7856 do (org-do-promote))))
7857 t))))
7859 (defun org-map-tree (fun)
7860 "Call FUN for every heading underneath the current one."
7861 (org-back-to-heading)
7862 (let ((level (funcall outline-level)))
7863 (save-excursion
7864 (funcall fun)
7865 (while (and (progn
7866 (outline-next-heading)
7867 (> (funcall outline-level) level))
7868 (not (eobp)))
7869 (funcall fun)))))
7871 (defun org-map-region (fun beg end)
7872 "Call FUN for every heading between BEG and END."
7873 (let ((org-ignore-region t))
7874 (save-excursion
7875 (setq end (copy-marker end))
7876 (goto-char beg)
7877 (if (and (re-search-forward org-outline-regexp-bol nil t)
7878 (< (point) end))
7879 (funcall fun))
7880 (while (and (progn
7881 (outline-next-heading)
7882 (< (point) end))
7883 (not (eobp)))
7884 (funcall fun)))))
7886 (defvar org-property-end-re) ; silence byte-compiler
7887 (defun org-fixup-indentation (diff)
7888 "Change the indentation in the current entry by DIFF.
7889 However, if any line in the current entry has no indentation, or if it
7890 would end up with no indentation after the change, nothing at all is done."
7891 (save-excursion
7892 (let ((end (save-excursion (outline-next-heading)
7893 (point-marker)))
7894 (prohibit (if (> diff 0)
7895 "^\\S-"
7896 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7897 col)
7898 (unless (save-excursion (end-of-line 1)
7899 (re-search-forward prohibit end t))
7900 (while (and (< (point) end)
7901 (re-search-forward "^[ \t]+" end t))
7902 (goto-char (match-end 0))
7903 (setq col (current-column))
7904 (if (< diff 0) (replace-match ""))
7905 (org-indent-to-column (+ diff col))))
7906 (move-marker end nil))))
7908 (defun org-convert-to-odd-levels ()
7909 "Convert an org-mode file with all levels allowed to one with odd levels.
7910 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7911 level 5 etc."
7912 (interactive)
7913 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7914 (let ((outline-level 'org-outline-level)
7915 (org-odd-levels-only nil) n)
7916 (save-excursion
7917 (goto-char (point-min))
7918 (while (re-search-forward "^\\*\\*+ " nil t)
7919 (setq n (- (length (match-string 0)) 2))
7920 (while (>= (setq n (1- n)) 0)
7921 (org-demote))
7922 (end-of-line 1))))))
7924 (defun org-convert-to-oddeven-levels ()
7925 "Convert an org-mode file with only odd levels to one with odd/even levels.
7926 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7927 file contains a section with an even level, conversion would
7928 destroy the structure of the file. An error is signaled in this
7929 case."
7930 (interactive)
7931 (goto-char (point-min))
7932 ;; First check if there are no even levels
7933 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7934 (org-show-context t)
7935 (error "Not all levels are odd in this file. Conversion not possible"))
7936 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7937 (let ((outline-regexp org-outline-regexp)
7938 (outline-level 'org-outline-level)
7939 (org-odd-levels-only nil) n)
7940 (save-excursion
7941 (goto-char (point-min))
7942 (while (re-search-forward "^\\*\\*+ " nil t)
7943 (setq n (/ (1- (length (match-string 0))) 2))
7944 (while (>= (setq n (1- n)) 0)
7945 (org-promote))
7946 (end-of-line 1))))))
7948 (defun org-tr-level (n)
7949 "Make N odd if required."
7950 (if org-odd-levels-only (1+ (/ n 2)) n))
7952 ;;; Vertical tree motion, cutting and pasting of subtrees
7954 (defun org-move-subtree-up (&optional arg)
7955 "Move the current subtree up past ARG headlines of the same level."
7956 (interactive "p")
7957 (org-move-subtree-down (- (prefix-numeric-value arg))))
7959 (defun org-move-subtree-down (&optional arg)
7960 "Move the current subtree down past ARG headlines of the same level."
7961 (interactive "p")
7962 (setq arg (prefix-numeric-value arg))
7963 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7964 'org-get-last-sibling))
7965 (ins-point (make-marker))
7966 (cnt (abs arg))
7967 (col (current-column))
7968 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7969 ;; Select the tree
7970 (org-back-to-heading)
7971 (setq beg0 (point))
7972 (save-excursion
7973 (setq ne-beg (org-back-over-empty-lines))
7974 (setq beg (point)))
7975 (save-match-data
7976 (save-excursion (outline-end-of-heading)
7977 (setq folded (outline-invisible-p)))
7978 (outline-end-of-subtree))
7979 (outline-next-heading)
7980 (setq ne-end (org-back-over-empty-lines))
7981 (setq end (point))
7982 (goto-char beg0)
7983 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7984 ;; include less whitespace
7985 (save-excursion
7986 (goto-char beg)
7987 (forward-line (- ne-beg ne-end))
7988 (setq beg (point))))
7989 ;; Find insertion point, with error handling
7990 (while (> cnt 0)
7991 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7992 (progn (goto-char beg0)
7993 (user-error "Cannot move past superior level or buffer limit")))
7994 (setq cnt (1- cnt)))
7995 (if (> arg 0)
7996 ;; Moving forward - still need to move over subtree
7997 (progn (org-end-of-subtree t t)
7998 (save-excursion
7999 (org-back-over-empty-lines)
8000 (or (bolp) (newline)))))
8001 (setq ne-ins (org-back-over-empty-lines))
8002 (move-marker ins-point (point))
8003 (setq txt (buffer-substring beg end))
8004 (org-save-markers-in-region beg end)
8005 (delete-region beg end)
8006 (org-remove-empty-overlays-at beg)
8007 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8008 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8009 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8010 (let ((bbb (point)))
8011 (insert-before-markers txt)
8012 (org-reinstall-markers-in-region bbb)
8013 (move-marker ins-point bbb))
8014 (or (bolp) (insert "\n"))
8015 (setq ins-end (point))
8016 (goto-char ins-point)
8017 (org-skip-whitespace)
8018 (when (and (< arg 0)
8019 (org-first-sibling-p)
8020 (> ne-ins ne-beg))
8021 ;; Move whitespace back to beginning
8022 (save-excursion
8023 (goto-char ins-end)
8024 (let ((kill-whole-line t))
8025 (kill-line (- ne-ins ne-beg)) (point)))
8026 (insert (make-string (- ne-ins ne-beg) ?\n)))
8027 (move-marker ins-point nil)
8028 (if folded
8029 (hide-subtree)
8030 (org-show-entry)
8031 (show-children)
8032 (org-cycle-hide-drawers 'children))
8033 (org-clean-visibility-after-subtree-move)
8034 ;; move back to the initial column we were at
8035 (move-to-column col)))
8037 (defvar org-subtree-clip ""
8038 "Clipboard for cut and paste of subtrees.
8039 This is actually only a copy of the kill, because we use the normal kill
8040 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8042 (defvar org-subtree-clip-folded nil
8043 "Was the last copied subtree folded?
8044 This is used to fold the tree back after pasting.")
8046 (defun org-cut-subtree (&optional n)
8047 "Cut the current subtree into the clipboard.
8048 With prefix arg N, cut this many sequential subtrees.
8049 This is a short-hand for marking the subtree and then cutting it."
8050 (interactive "p")
8051 (org-copy-subtree n 'cut))
8053 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8054 "Cut the current subtree into the clipboard.
8055 With prefix arg N, cut this many sequential subtrees.
8056 This is a short-hand for marking the subtree and then copying it.
8057 If CUT is non-nil, actually cut the subtree.
8058 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8059 of some markers in the region, even if CUT is non-nil. This is
8060 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8061 (interactive "p")
8062 (let (beg end folded (beg0 (point)))
8063 (if (org-called-interactively-p 'any)
8064 (org-back-to-heading nil) ; take what looks like a subtree
8065 (org-back-to-heading t)) ; take what is really there
8066 (setq beg (point))
8067 (skip-chars-forward " \t\r\n")
8068 (save-match-data
8069 (if nosubtrees
8070 (outline-next-heading)
8071 (save-excursion (outline-end-of-heading)
8072 (setq folded (outline-invisible-p)))
8073 (condition-case nil
8074 (org-forward-heading-same-level (1- n) t)
8075 (error nil))
8076 (org-end-of-subtree t t)))
8077 (setq end (point))
8078 (goto-char beg0)
8079 (when (> end beg)
8080 (setq org-subtree-clip-folded folded)
8081 (when (or cut force-store-markers)
8082 (org-save-markers-in-region beg end))
8083 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8084 (setq org-subtree-clip (current-kill 0))
8085 (message "%s: Subtree(s) with %d characters"
8086 (if cut "Cut" "Copied")
8087 (length org-subtree-clip)))))
8089 (defun org-paste-subtree (&optional level tree for-yank)
8090 "Paste the clipboard as a subtree, with modification of headline level.
8091 The entire subtree is promoted or demoted in order to match a new headline
8092 level.
8094 If the cursor is at the beginning of a headline, the same level as
8095 that headline is used to paste the tree.
8097 If not, the new level is derived from the *visible* headings
8098 before and after the insertion point, and taken to be the inferior headline
8099 level of the two. So if the previous visible heading is level 3 and the
8100 next is level 4 (or vice versa), level 4 will be used for insertion.
8101 This makes sure that the subtree remains an independent subtree and does
8102 not swallow low level entries.
8104 You can also force a different level, either by using a numeric prefix
8105 argument, or by inserting the heading marker by hand. For example, if the
8106 cursor is after \"*****\", then the tree will be shifted to level 5.
8108 If optional TREE is given, use this text instead of the kill ring.
8110 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8111 move back over whitespace before inserting, and move point to the end of
8112 the inserted text when done."
8113 (interactive "P")
8114 (setq tree (or tree (and kill-ring (current-kill 0))))
8115 (unless (org-kill-is-subtree-p tree)
8116 (error "%s"
8117 (substitute-command-keys
8118 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8119 (org-with-limited-levels
8120 (let* ((visp (not (outline-invisible-p)))
8121 (txt tree)
8122 (^re_ "\\(\\*+\\)[ \t]*")
8123 (old-level (if (string-match org-outline-regexp-bol txt)
8124 (- (match-end 0) (match-beginning 0) 1)
8125 -1))
8126 (force-level (cond (level (prefix-numeric-value level))
8127 ((and (looking-at "[ \t]*$")
8128 (string-match
8129 "^\\*+$" (buffer-substring
8130 (point-at-bol) (point))))
8131 (- (match-end 1) (match-beginning 1)))
8132 ((and (bolp)
8133 (looking-at org-outline-regexp))
8134 (- (match-end 0) (point) 1))))
8135 (previous-level (save-excursion
8136 (condition-case nil
8137 (progn
8138 (outline-previous-visible-heading 1)
8139 (if (looking-at ^re_)
8140 (- (match-end 0) (match-beginning 0) 1)
8142 (error 1))))
8143 (next-level (save-excursion
8144 (condition-case nil
8145 (progn
8146 (or (looking-at org-outline-regexp)
8147 (outline-next-visible-heading 1))
8148 (if (looking-at ^re_)
8149 (- (match-end 0) (match-beginning 0) 1)
8151 (error 1))))
8152 (new-level (or force-level (max previous-level next-level)))
8153 (shift (if (or (= old-level -1)
8154 (= new-level -1)
8155 (= old-level new-level))
8157 (- new-level old-level)))
8158 (delta (if (> shift 0) -1 1))
8159 (func (if (> shift 0) 'org-demote 'org-promote))
8160 (org-odd-levels-only nil)
8161 beg end newend)
8162 ;; Remove the forced level indicator
8163 (if force-level
8164 (delete-region (point-at-bol) (point)))
8165 ;; Paste
8166 (beginning-of-line (if (bolp) 1 2))
8167 (setq beg (point))
8168 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8169 (insert-before-markers txt)
8170 (unless (string-match "\n\\'" txt) (insert "\n"))
8171 (setq newend (point))
8172 (org-reinstall-markers-in-region beg)
8173 (setq end (point))
8174 (goto-char beg)
8175 (skip-chars-forward " \t\n\r")
8176 (setq beg (point))
8177 (if (and (outline-invisible-p) visp)
8178 (save-excursion (outline-show-heading)))
8179 ;; Shift if necessary
8180 (unless (= shift 0)
8181 (save-restriction
8182 (narrow-to-region beg end)
8183 (while (not (= shift 0))
8184 (org-map-region func (point-min) (point-max))
8185 (setq shift (+ delta shift)))
8186 (goto-char (point-min))
8187 (setq newend (point-max))))
8188 (when (or (org-called-interactively-p 'interactive) for-yank)
8189 (message "Clipboard pasted as level %d subtree" new-level))
8190 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8191 kill-ring
8192 (eq org-subtree-clip (current-kill 0))
8193 org-subtree-clip-folded)
8194 ;; The tree was folded before it was killed/copied
8195 (hide-subtree))
8196 (and for-yank (goto-char newend)))))
8198 (defun org-kill-is-subtree-p (&optional txt)
8199 "Check if the current kill is an outline subtree, or a set of trees.
8200 Returns nil if kill does not start with a headline, or if the first
8201 headline level is not the largest headline level in the tree.
8202 So this will actually accept several entries of equal levels as well,
8203 which is OK for `org-paste-subtree'.
8204 If optional TXT is given, check this string instead of the current kill."
8205 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8206 (re (org-get-limited-outline-regexp))
8207 (^re (concat "^" re))
8208 (start-level (and kill
8209 (string-match
8210 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8211 kill)
8212 (- (match-end 2) (match-beginning 2) 1)))
8213 (start (1+ (or (match-beginning 2) -1))))
8214 (if (not start-level)
8215 (progn
8216 nil) ;; does not even start with a heading
8217 (catch 'exit
8218 (while (setq start (string-match ^re kill (1+ start)))
8219 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8220 (throw 'exit nil)))
8221 t))))
8223 (defvar org-markers-to-move nil
8224 "Markers that should be moved with a cut-and-paste operation.
8225 Those markers are stored together with their positions relative to
8226 the start of the region.")
8228 (defun org-save-markers-in-region (beg end)
8229 "Check markers in region.
8230 If these markers are between BEG and END, record their position relative
8231 to BEG, so that after moving the block of text, we can put the markers back
8232 into place.
8233 This function gets called just before an entry or tree gets cut from the
8234 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8235 called immediately, to move the markers with the entries."
8236 (setq org-markers-to-move nil)
8237 (when (featurep 'org-clock)
8238 (org-clock-save-markers-for-cut-and-paste beg end))
8239 (when (featurep 'org-agenda)
8240 (org-agenda-save-markers-for-cut-and-paste beg end)))
8242 (defun org-check-and-save-marker (marker beg end)
8243 "Check if MARKER is between BEG and END.
8244 If yes, remember the marker and the distance to BEG."
8245 (when (and (marker-buffer marker)
8246 (equal (marker-buffer marker) (current-buffer)))
8247 (if (and (>= marker beg) (< marker end))
8248 (push (cons marker (- marker beg)) org-markers-to-move))))
8250 (defun org-reinstall-markers-in-region (beg)
8251 "Move all remembered markers to their position relative to BEG."
8252 (mapc (lambda (x)
8253 (move-marker (car x) (+ beg (cdr x))))
8254 org-markers-to-move)
8255 (setq org-markers-to-move nil))
8257 (defun org-narrow-to-subtree ()
8258 "Narrow buffer to the current subtree."
8259 (interactive)
8260 (save-excursion
8261 (save-match-data
8262 (org-with-limited-levels
8263 (narrow-to-region
8264 (progn (org-back-to-heading t) (point))
8265 (progn (org-end-of-subtree t t)
8266 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8267 (point)))))))
8269 (defun org-narrow-to-block ()
8270 "Narrow buffer to the current block."
8271 (interactive)
8272 (let* ((case-fold-search t)
8273 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8274 "^[ \t]*#\\+end_.*")))
8275 (if blockp
8276 (narrow-to-region (car blockp) (cdr blockp))
8277 (error "Not in a block"))))
8279 (eval-when-compile
8280 (defvar org-property-drawer-re))
8282 (defvar org-property-start-re) ;; defined below
8283 (defun org-clone-subtree-with-time-shift (n &optional shift)
8284 "Clone the task (subtree) at point N times.
8285 The clones will be inserted as siblings.
8287 In interactive use, the user will be prompted for the number of
8288 clones to be produced. When called with a universal prefix argument
8289 and if the entry has a timestamp, the user will also be prompted for
8290 a time shift, which may be a repeater as used in time stamps, for
8291 example `+3d'.
8293 When a valid repeater is given and the entry contains any time
8294 stamps, the clones will become a sequence in time, with time
8295 stamps in the subtree shifted for each clone produced. If SHIFT
8296 is nil or the empty string, time stamps will be left alone. The
8297 ID property of the original subtree is removed.
8299 If the original subtree did contain time stamps with a repeater,
8300 the following will happen:
8301 - the repeater will be removed in each clone
8302 - an additional clone will be produced, with the current, unshifted
8303 date(s) in the entry.
8304 - the original entry will be placed *after* all the clones, with
8305 repeater intact.
8306 - the start days in the repeater in the original entry will be shifted
8307 to past the last clone.
8308 In this way you can spell out a number of instances of a repeating task,
8309 and still retain the repeater to cover future instances of the task."
8310 (interactive "nNumber of clones to produce: ")
8311 (let ((shift
8312 (or shift
8313 (if (and (equal current-prefix-arg '(4))
8314 (save-excursion
8315 (re-search-forward org-ts-regexp-both
8316 (save-excursion
8317 (org-end-of-subtree t)
8318 (point)) t)))
8319 (read-from-minibuffer
8320 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8321 ""))) ;; No time shift
8322 (n-no-remove -1)
8323 (drawer-re org-drawer-regexp)
8324 beg end template task idprop
8325 shift-n shift-what doshift nmin nmax)
8326 (if (not (and (integerp n) (> n 0)))
8327 (error "Invalid number of replications %s" n))
8328 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8329 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8330 shift)))
8331 (error "Invalid shift specification %s" shift))
8332 (when doshift
8333 (setq shift-n (string-to-number (match-string 1 shift))
8334 shift-what (cdr (assoc (match-string 2 shift)
8335 '(("d" . day) ("w" . week)
8336 ("m" . month) ("y" . year))))))
8337 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8338 (setq nmin 1 nmax n)
8339 (org-back-to-heading t)
8340 (setq beg (point))
8341 (setq idprop (org-entry-get nil "ID"))
8342 (org-end-of-subtree t t)
8343 (or (bolp) (insert "\n"))
8344 (setq end (point))
8345 (setq template (buffer-substring beg end))
8346 (when (and doshift
8347 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8348 (delete-region beg end)
8349 (setq end beg)
8350 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8351 (goto-char end)
8352 (loop for n from nmin to nmax do
8353 ;; prepare clone
8354 (with-temp-buffer
8355 (insert template)
8356 (org-mode)
8357 (goto-char (point-min))
8358 (org-show-subtree)
8359 (and idprop (if org-clone-delete-id
8360 (org-entry-delete nil "ID")
8361 (org-id-get-create t)))
8362 (unless (= n 0)
8363 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8364 (kill-whole-line))
8365 (goto-char (point-min))
8366 (while (re-search-forward drawer-re nil t)
8367 (mapc (lambda (d)
8368 (org-remove-empty-drawer-at d (point))) org-drawers)))
8369 (goto-char (point-min))
8370 (when doshift
8371 (while (re-search-forward org-ts-regexp-both nil t)
8372 (org-timestamp-change (* n shift-n) shift-what))
8373 (unless (= n n-no-remove)
8374 (goto-char (point-min))
8375 (while (re-search-forward org-ts-regexp nil t)
8376 (save-excursion
8377 (goto-char (match-beginning 0))
8378 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8379 (delete-region (match-beginning 1) (match-end 1)))))))
8380 (setq task (buffer-string)))
8381 (insert task))
8382 (goto-char beg)))
8384 ;;; Outline Sorting
8386 (defun org-sort (with-case)
8387 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8388 Optional argument WITH-CASE means sort case-sensitively."
8389 (interactive "P")
8390 (cond
8391 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8392 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8394 (org-call-with-arg 'org-sort-entries with-case))))
8396 (defun org-sort-remove-invisible (s)
8397 "Remove invisible links from string S."
8398 (remove-text-properties 0 (length s) org-rm-props s)
8399 (while (string-match org-bracket-link-regexp s)
8400 (setq s (replace-match (if (match-end 2)
8401 (match-string 3 s)
8402 (match-string 1 s)) t t s)))
8403 (let ((st (format " %s " s)))
8404 (while (string-match org-emph-re st)
8405 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8406 (setq s (substring st 1 -1)))
8409 (defvar org-priority-regexp) ; defined later in the file
8411 (defvar org-after-sorting-entries-or-items-hook nil
8412 "Hook that is run after a bunch of entries or items have been sorted.
8413 When children are sorted, the cursor is in the parent line when this
8414 hook gets called. When a region or a plain list is sorted, the cursor
8415 will be in the first entry of the sorted region/list.")
8417 (defun org-sort-entries
8418 (&optional with-case sorting-type getkey-func compare-func property)
8419 "Sort entries on a certain level of an outline tree.
8420 If there is an active region, the entries in the region are sorted.
8421 Else, if the cursor is before the first entry, sort the top-level items.
8422 Else, the children of the entry at point are sorted.
8424 Sorting can be alphabetically, numerically, by date/time as given by
8425 a time stamp, by a property, by priority order, or by a custom function.
8427 The command prompts for the sorting type unless it has been given to the
8428 function through the SORTING-TYPE argument, which needs to be a character,
8429 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8430 precise meaning of each character:
8432 n Numerically, by converting the beginning of the entry/item to a number.
8433 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8434 o By order of TODO keywords.
8435 t By date/time, either the first active time stamp in the entry, or, if
8436 none exist, by the first inactive one.
8437 s By the scheduled date/time.
8438 d By deadline date/time.
8439 c By creation time, which is assumed to be the first inactive time stamp
8440 at the beginning of a line.
8441 p By priority according to the cookie.
8442 r By the value of a property.
8444 Capital letters will reverse the sort order.
8446 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8447 called with point at the beginning of the record. It must return either
8448 a string or a number that should serve as the sorting key for that record.
8450 Comparing entries ignores case by default. However, with an optional argument
8451 WITH-CASE, the sorting considers case as well.
8453 Sorting is done against the visible part of the headlines, it ignores hidden
8454 links."
8455 (interactive "P")
8456 (let ((case-func (if with-case 'identity 'downcase))
8457 (cmstr
8458 ;; The clock marker is lost when using `sort-subr', let's
8459 ;; store the clocking string.
8460 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8461 (save-excursion
8462 (goto-char org-clock-marker)
8463 (looking-back "^.*") (match-string-no-properties 0))))
8464 start beg end stars re re2
8465 txt what tmp)
8466 ;; Find beginning and end of region to sort
8467 (cond
8468 ((org-region-active-p)
8469 ;; we will sort the region
8470 (setq end (region-end)
8471 what "region")
8472 (goto-char (region-beginning))
8473 (if (not (org-at-heading-p)) (outline-next-heading))
8474 (setq start (point)))
8475 ((or (org-at-heading-p)
8476 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8477 ;; we will sort the children of the current headline
8478 (org-back-to-heading)
8479 (setq start (point)
8480 end (progn (org-end-of-subtree t t)
8481 (or (bolp) (insert "\n"))
8482 (org-back-over-empty-lines)
8483 (point))
8484 what "children")
8485 (goto-char start)
8486 (show-subtree)
8487 (outline-next-heading))
8489 ;; we will sort the top-level entries in this file
8490 (goto-char (point-min))
8491 (or (org-at-heading-p) (outline-next-heading))
8492 (setq start (point))
8493 (goto-char (point-max))
8494 (beginning-of-line 1)
8495 (when (looking-at ".*?\\S-")
8496 ;; File ends in a non-white line
8497 (end-of-line 1)
8498 (insert "\n"))
8499 (setq end (point-max))
8500 (setq what "top-level")
8501 (goto-char start)
8502 (show-all)))
8504 (setq beg (point))
8505 (if (>= beg end) (error "Nothing to sort"))
8507 (looking-at "\\(\\*+\\)")
8508 (setq stars (match-string 1)
8509 re (concat "^" (regexp-quote stars) " +")
8510 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8511 txt (buffer-substring beg end))
8512 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8513 (if (and (not (equal stars "*")) (string-match re2 txt))
8514 (error "Region to sort contains a level above the first entry"))
8516 (unless sorting-type
8517 (message
8518 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8519 [t]ime [s]cheduled [d]eadline [c]reated
8520 A/N/P/R/O/F/T/S/D/C means reversed:"
8521 what)
8522 (setq sorting-type (read-char-exclusive))
8524 (unless getkey-func
8525 (and (= (downcase sorting-type) ?f)
8526 (setq getkey-func
8527 (org-icompleting-read "Sort using function: "
8528 obarray 'fboundp t nil nil))
8529 (setq getkey-func (intern getkey-func))))
8531 (and (= (downcase sorting-type) ?r)
8532 (not property)
8533 (setq property
8534 (org-icompleting-read "Property: "
8535 (mapcar 'list (org-buffer-property-keys t))
8536 nil t))))
8538 (message "Sorting entries...")
8540 (save-restriction
8541 (narrow-to-region start end)
8542 (let ((dcst (downcase sorting-type))
8543 (case-fold-search nil)
8544 (now (current-time)))
8545 (sort-subr
8546 (/= dcst sorting-type)
8547 ;; This function moves to the beginning character of the "record" to
8548 ;; be sorted.
8549 (lambda nil
8550 (if (re-search-forward re nil t)
8551 (goto-char (match-beginning 0))
8552 (goto-char (point-max))))
8553 ;; This function moves to the last character of the "record" being
8554 ;; sorted.
8555 (lambda nil
8556 (save-match-data
8557 (condition-case nil
8558 (outline-forward-same-level 1)
8559 (error
8560 (goto-char (point-max))))))
8561 ;; This function returns the value that gets sorted against.
8562 (lambda nil
8563 (cond
8564 ((= dcst ?n)
8565 (if (looking-at org-complex-heading-regexp)
8566 (string-to-number (org-sort-remove-invisible (match-string 4)))
8567 nil))
8568 ((= dcst ?a)
8569 (if (looking-at org-complex-heading-regexp)
8570 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8571 nil))
8572 ((= dcst ?t)
8573 (let ((end (save-excursion (outline-next-heading) (point))))
8574 (if (or (re-search-forward org-ts-regexp end t)
8575 (re-search-forward org-ts-regexp-both end t))
8576 (org-time-string-to-seconds (match-string 0))
8577 (org-float-time now))))
8578 ((= dcst ?c)
8579 (let ((end (save-excursion (outline-next-heading) (point))))
8580 (if (re-search-forward
8581 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8582 end t)
8583 (org-time-string-to-seconds (match-string 0))
8584 (org-float-time now))))
8585 ((= dcst ?s)
8586 (let ((end (save-excursion (outline-next-heading) (point))))
8587 (if (re-search-forward org-scheduled-time-regexp end t)
8588 (org-time-string-to-seconds (match-string 1))
8589 (org-float-time now))))
8590 ((= dcst ?d)
8591 (let ((end (save-excursion (outline-next-heading) (point))))
8592 (if (re-search-forward org-deadline-time-regexp end t)
8593 (org-time-string-to-seconds (match-string 1))
8594 (org-float-time now))))
8595 ((= dcst ?p)
8596 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8597 (string-to-char (match-string 2))
8598 org-default-priority))
8599 ((= dcst ?r)
8600 (or (org-entry-get nil property) ""))
8601 ((= dcst ?o)
8602 (if (looking-at org-complex-heading-regexp)
8603 (- 9999 (length (member (match-string 2)
8604 org-todo-keywords-1)))))
8605 ((= dcst ?f)
8606 (if getkey-func
8607 (progn
8608 (setq tmp (funcall getkey-func))
8609 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8610 tmp)
8611 (error "Invalid key function `%s'" getkey-func)))
8612 (t (error "Invalid sorting type `%c'" sorting-type))))
8614 (cond
8615 ((= dcst ?a) 'string<)
8616 ((= dcst ?f) compare-func)
8617 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8618 (run-hooks 'org-after-sorting-entries-or-items-hook)
8619 ;; Reset the clock marker if needed
8620 (when cmstr
8621 (save-excursion
8622 (goto-char start)
8623 (search-forward cmstr nil t)
8624 (move-marker org-clock-marker (point))))
8625 (message "Sorting entries...done")))
8627 (defun org-do-sort (table what &optional with-case sorting-type)
8628 "Sort TABLE of WHAT according to SORTING-TYPE.
8629 The user will be prompted for the SORTING-TYPE if the call to this
8630 function does not specify it. WHAT is only for the prompt, to indicate
8631 what is being sorted. The sorting key will be extracted from
8632 the car of the elements of the table.
8633 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8634 (unless sorting-type
8635 (message
8636 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8637 what)
8638 (setq sorting-type (read-char-exclusive)))
8639 (let ((dcst (downcase sorting-type))
8640 extractfun comparefun)
8641 ;; Define the appropriate functions
8642 (cond
8643 ((= dcst ?n)
8644 (setq extractfun 'string-to-number
8645 comparefun (if (= dcst sorting-type) '< '>)))
8646 ((= dcst ?a)
8647 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8648 (lambda(x) (downcase (org-sort-remove-invisible x))))
8649 comparefun (if (= dcst sorting-type)
8650 'string<
8651 (lambda (a b) (and (not (string< a b))
8652 (not (string= a b)))))))
8653 ((= dcst ?t)
8654 (setq extractfun
8655 (lambda (x)
8656 (if (or (string-match org-ts-regexp x)
8657 (string-match org-ts-regexp-both x))
8658 (org-float-time
8659 (org-time-string-to-time (match-string 0 x)))
8661 comparefun (if (= dcst sorting-type) '< '>)))
8662 (t (error "Invalid sorting type `%c'" sorting-type)))
8664 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8665 table)
8666 (lambda (a b) (funcall comparefun (car a) (car b))))))
8669 ;;; The orgstruct minor mode
8671 ;; Define a minor mode which can be used in other modes in order to
8672 ;; integrate the org-mode structure editing commands.
8674 ;; This is really a hack, because the org-mode structure commands use
8675 ;; keys which normally belong to the major mode. Here is how it
8676 ;; works: The minor mode defines all the keys necessary to operate the
8677 ;; structure commands, but wraps the commands into a function which
8678 ;; tests if the cursor is currently at a headline or a plain list
8679 ;; item. If that is the case, the structure command is used,
8680 ;; temporarily setting many Org-mode variables like regular
8681 ;; expressions for filling etc. However, when any of those keys is
8682 ;; used at a different location, function uses `key-binding' to look
8683 ;; up if the key has an associated command in another currently active
8684 ;; keymap (minor modes, major mode, global), and executes that
8685 ;; command. There might be problems if any of the keys is otherwise
8686 ;; used as a prefix key.
8688 (defcustom orgstruct-heading-prefix-regexp nil
8689 "Regexp that matches the custom prefix of Org headlines in
8690 orgstruct(++)-mode."
8691 :group 'org
8692 :version "24.4"
8693 :package-version '(Org . "8.0")
8694 :type 'string)
8695 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8697 (defcustom orgstruct-setup-hook nil
8698 "Hook run after orgstruct-mode-map is filled."
8699 :group 'org
8700 :version "24.4"
8701 :package-version '(Org . "8.0")
8702 :type 'hook)
8704 (defvar orgstruct-initialized nil)
8706 (defvar org-local-vars nil
8707 "List of local variables, for use by `orgstruct-mode'.")
8709 ;;;###autoload
8710 (define-minor-mode orgstruct-mode
8711 "Toggle the minor mode `orgstruct-mode'.
8712 This mode is for using Org-mode structure commands in other
8713 modes. The following keys behave as if Org-mode were active, if
8714 the cursor is on a headline, or on a plain list item (both as
8715 defined by Org-mode)."
8716 nil " OrgStruct" (make-sparse-keymap)
8717 (funcall (if orgstruct-mode
8718 'add-to-invisibility-spec
8719 'remove-from-invisibility-spec)
8720 '(outline . t))
8721 (when orgstruct-mode
8722 (org-load-modules-maybe)
8723 (unless orgstruct-initialized
8724 (orgstruct-setup)
8725 (setq orgstruct-initialized t))))
8727 ;;;###autoload
8728 (defun turn-on-orgstruct ()
8729 "Unconditionally turn on `orgstruct-mode'."
8730 (orgstruct-mode 1))
8732 (defvar org-fb-vars nil)
8733 (make-variable-buffer-local 'org-fb-vars)
8734 (defun orgstruct++-mode (&optional arg)
8735 "Toggle `orgstruct-mode', the enhanced version of it.
8736 In addition to setting orgstruct-mode, this also exports all
8737 indentation and autofilling variables from org-mode into the
8738 buffer. It will also recognize item context in multiline items."
8739 (interactive "P")
8740 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8741 (if (< arg 1)
8742 (progn (orgstruct-mode -1)
8743 (mapc (lambda(v)
8744 (org-set-local (car v)
8745 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8746 org-fb-vars))
8747 (orgstruct-mode 1)
8748 (setq org-fb-vars nil)
8749 (let (var val)
8750 (mapc
8751 (lambda (x)
8752 (when (string-match
8753 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8754 (symbol-name (car x)))
8755 (setq var (car x) val (nth 1 x))
8756 (push (list var `(quote ,(eval var))) org-fb-vars)
8757 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8758 org-local-vars)
8759 (org-set-local 'orgstruct-is-++ t))))
8761 (defvar orgstruct-is-++ nil
8762 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8763 (make-variable-buffer-local 'orgstruct-is-++)
8765 ;;;###autoload
8766 (defun turn-on-orgstruct++ ()
8767 "Unconditionally turn on `orgstruct++-mode'."
8768 (orgstruct++-mode 1))
8770 (defun orgstruct-error ()
8771 "Error when there is no default binding for a structure key."
8772 (interactive)
8773 (funcall (if (fboundp 'user-error)
8774 'user-error
8775 'error)
8776 "This key has no function outside structure elements"))
8778 (defun orgstruct-setup ()
8779 "Setup orgstruct keymap."
8780 (dolist (cell '((org-demote . t)
8781 (org-metaleft . t)
8782 (org-metaright . t)
8783 (org-promote . t)
8784 (org-shiftmetaleft . t)
8785 (org-shiftmetaright . t)
8786 org-backward-element
8787 org-backward-heading-same-level
8788 org-ctrl-c-ret
8789 org-ctrl-c-minus
8790 org-ctrl-c-star
8791 org-cycle
8792 org-forward-heading-same-level
8793 org-insert-heading
8794 org-insert-heading-respect-content
8795 org-kill-note-or-show-branches
8796 org-mark-subtree
8797 org-meta-return
8798 org-metadown
8799 org-metaup
8800 org-narrow-to-subtree
8801 org-promote-subtree
8802 org-reveal
8803 org-shiftdown
8804 org-shiftleft
8805 org-shiftmetadown
8806 org-shiftmetaup
8807 org-shiftright
8808 org-shifttab
8809 org-shifttab
8810 org-shiftup
8811 org-show-subtree
8812 org-sort
8813 org-up-element
8814 outline-demote
8815 outline-next-visible-heading
8816 outline-previous-visible-heading
8817 outline-promote
8818 outline-up-heading
8819 show-children))
8820 (let ((f (or (car-safe cell) cell))
8821 (disable-when-heading-prefix (cdr-safe cell)))
8822 (when (fboundp f)
8823 (dolist (binding (nconc (where-is-internal f org-mode-map)
8824 (where-is-internal f outline-mode-map)))
8825 ;; TODO use local-function-key-map
8826 (dolist (rep '(("<tab>" . "TAB")
8827 ("<return>" . "RET")
8828 ("<escape>" . "ESC")
8829 ("<delete>" . "DEL")))
8830 (setq binding (read-kbd-macro
8831 (let ((case-fold-search))
8832 (replace-regexp-in-string
8833 (regexp-quote (cdr rep))
8834 (car rep)
8835 (key-description binding))))))
8836 (let ((key (lookup-key orgstruct-mode-map binding)))
8837 (when (or (not key) (numberp key))
8838 (condition-case nil
8839 (org-defkey orgstruct-mode-map
8840 binding
8841 (orgstruct-make-binding f binding disable-when-heading-prefix))
8842 (error nil))))))))
8843 (run-hooks 'orgstruct-setup-hook))
8845 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
8846 "Create a function for binding in the structure minor mode.
8847 FUN is the command to call inside a table. KEY is the key that
8848 should be checked in for a command to execute outside of tables.
8849 Non-nil DISABLE-WHEN-HEADING-PREFIX means to disable the command
8850 if `orgstruct-heading-prefix-regexp' is non-nil."
8851 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8852 (let ((nname name)
8853 (i 0))
8854 (while (fboundp (intern nname))
8855 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8856 (setq name (intern nname)))
8857 (eval
8858 (let ((bindings '((org-heading-regexp
8859 (concat "^"
8860 orgstruct-heading-prefix-regexp
8861 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8862 (org-outline-regexp
8863 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8864 (org-outline-regexp-bol
8865 (concat "^" org-outline-regexp))
8866 (outline-regexp org-outline-regexp)
8867 (outline-heading-end-regexp "\n")
8868 (outline-level 'org-outline-level)
8869 (outline-heading-alist))))
8870 `(defun ,name (arg)
8871 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
8872 "Outside of structure, run the binding of `"
8873 (key-description key) "'."
8874 (when disable-when-heading-prefix
8875 (concat
8876 "\nIf `orgstruct-heading-prefix-regexp' is non-nil, this command will always fall\n"
8877 "back to the default binding due to limitations of Org's implementation of\n"
8878 "`" (symbol-name fun) "'.")))
8879 (interactive "p")
8880 (let* ((disable
8881 ,(when disable-when-heading-prefix
8882 '(and orgstruct-heading-prefix-regexp
8883 (not (string= orgstruct-heading-prefix-regexp "")))))
8884 (fallback
8885 (or disable
8886 (not
8887 (let* ,bindings
8888 (org-context-p 'headline 'item
8889 ,(when (memq fun '(org-insert-heading))
8890 '(when orgstruct-is-++
8891 'item-body))))))))
8892 (if fallback
8893 (let* ((orgstruct-mode)
8894 (binding
8895 (loop with key = ,key
8896 for rep in '(nil
8897 ("<tab>" . "TAB")
8898 ("<return>" . "RET")
8899 ("<escape>" . "ESC")
8900 ("<delete>" . "DEL"))
8902 (when rep
8903 (setq key (read-kbd-macro
8904 (let ((case-fold-search))
8905 (replace-regexp-in-string
8906 (regexp-quote (car rep))
8907 (cdr rep)
8908 (key-description key))))))
8909 thereis (key-binding key))))
8910 (if (keymapp binding)
8911 (set-temporary-overlay-map binding)
8912 (let ((func (or binding
8913 (unless disable
8914 'orgstruct-error))))
8915 (when func
8916 (call-interactively func)))))
8917 (org-run-like-in-org-mode
8918 (lambda ()
8919 (interactive)
8920 (let* ,bindings
8921 (call-interactively ',fun)))))))))
8922 name))
8924 (defun org-contextualize-keys (alist contexts)
8925 "Return valid elements in ALIST depending on CONTEXTS.
8927 `org-agenda-custom-commands' or `org-capture-templates' are the
8928 values used for ALIST, and `org-agenda-custom-commands-contexts'
8929 or `org-capture-templates-contexts' are the associated contexts
8930 definitions."
8931 (let ((contexts
8932 ;; normalize contexts
8933 (mapcar
8934 (lambda(c) (cond ((listp (cadr c))
8935 (list (car c) (car c) (cadr c)))
8936 ((string= "" (cadr c))
8937 (list (car c) (car c) (caddr c)))
8938 (t c))) contexts))
8939 (a alist) c r s)
8940 ;; loop over all commands or templates
8941 (while (setq c (pop a))
8942 (let (vrules repl)
8943 (cond
8944 ((not (assoc (car c) contexts))
8945 (push c r))
8946 ((and (assoc (car c) contexts)
8947 (setq vrules (org-contextualize-validate-key
8948 (car c) contexts)))
8949 (mapc (lambda (vr)
8950 (when (not (equal (car vr) (cadr vr)))
8951 (setq repl vr))) vrules)
8952 (if (not repl) (push c r)
8953 (push (cadr repl) s)
8954 (push
8955 (cons (car c)
8956 (cdr (or (assoc (cadr repl) alist)
8957 (error "Undefined key `%s' as contextual replacement for `%s'"
8958 (cadr repl) (car c)))))
8959 r))))))
8960 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8961 (delq
8963 (delete-dups
8964 (mapcar (lambda (x)
8965 (let ((tpl (car x)))
8966 (when (not (delq
8968 (mapcar (lambda(y)
8969 (equal y tpl)) s))) x)))
8970 (reverse r))))))
8972 (defun org-contextualize-validate-key (key contexts)
8973 "Check CONTEXTS for agenda or capture KEY."
8974 (let (r rr res)
8975 (while (setq r (pop contexts))
8976 (mapc
8977 (lambda (rr)
8978 (when
8979 (and (equal key (car r))
8980 (if (functionp rr) (funcall rr)
8981 (or (and (eq (car rr) 'in-file)
8982 (buffer-file-name)
8983 (string-match (cdr rr) (buffer-file-name)))
8984 (and (eq (car rr) 'in-mode)
8985 (string-match (cdr rr) (symbol-name major-mode)))
8986 (and (eq (car rr) 'in-buffer)
8987 (string-match (cdr rr) (buffer-name)))
8988 (when (and (eq (car rr) 'not-in-file)
8989 (buffer-file-name))
8990 (not (string-match (cdr rr) (buffer-file-name))))
8991 (when (eq (car rr) 'not-in-mode)
8992 (not (string-match (cdr rr) (symbol-name major-mode))))
8993 (when (eq (car rr) 'not-in-buffer)
8994 (not (string-match (cdr rr) (buffer-name)))))))
8995 (push r res)))
8996 (car (last r))))
8997 (delete-dups (delq nil res))))
8999 (defun org-context-p (&rest contexts)
9000 "Check if local context is any of CONTEXTS.
9001 Possible values in the list of contexts are `table', `headline', and `item'."
9002 (let ((pos (point)))
9003 (goto-char (point-at-bol))
9004 (prog1 (or (and (memq 'table contexts)
9005 (looking-at "[ \t]*|"))
9006 (and (memq 'headline contexts)
9007 (looking-at org-outline-regexp))
9008 (and (memq 'item contexts)
9009 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9010 (and (memq 'item-body contexts)
9011 (org-in-item-p)))
9012 (goto-char pos))))
9014 (defun org-get-local-variables ()
9015 "Return a list of all local variables in an Org mode buffer."
9016 (let (varlist)
9017 (with-current-buffer (get-buffer-create "*Org tmp*")
9018 (erase-buffer)
9019 (org-mode)
9020 (setq varlist (buffer-local-variables)))
9021 (kill-buffer "*Org tmp*")
9022 (delq nil
9023 (mapcar
9024 (lambda (x)
9025 (setq x
9026 (if (symbolp x)
9027 (list x)
9028 (list (car x) (cdr x))))
9029 (if (and (not (get (car x) 'org-state))
9030 (string-match
9031 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9032 (symbol-name (car x))))
9033 x nil))
9034 varlist))))
9036 (defun org-clone-local-variables (from-buffer &optional regexp)
9037 "Clone local variables from FROM-BUFFER.
9038 Optional argument REGEXP selects variables to clone."
9039 (mapc
9040 (lambda (pair)
9041 (and (symbolp (car pair))
9042 (or (null regexp)
9043 (string-match regexp (symbol-name (car pair))))
9044 (set (make-local-variable (car pair))
9045 (cdr pair))))
9046 (buffer-local-variables from-buffer)))
9048 ;;;###autoload
9049 (defun org-run-like-in-org-mode (cmd)
9050 "Run a command, pretending that the current buffer is in Org-mode.
9051 This will temporarily bind local variables that are typically bound in
9052 Org-mode to the values they have in Org-mode, and then interactively
9053 call CMD."
9054 (org-load-modules-maybe)
9055 (unless org-local-vars
9056 (setq org-local-vars (org-get-local-variables)))
9057 (let (binds)
9058 (dolist (var org-local-vars)
9059 (when (or (not (boundp (car var)))
9060 (eq (symbol-value (car var))
9061 (default-value (car var))))
9062 (push (list (car var) `(quote ,(cadr var))) binds)))
9063 (eval `(let ,binds
9064 (call-interactively (quote ,cmd))))))
9066 ;;;; Archiving
9068 (defun org-get-category (&optional pos force-refresh)
9069 "Get the category applying to position POS."
9070 (save-match-data
9071 (if force-refresh (org-refresh-category-properties))
9072 (let ((pos (or pos (point))))
9073 (or (get-text-property pos 'org-category)
9074 (progn (org-refresh-category-properties)
9075 (get-text-property pos 'org-category))))))
9077 (defun org-refresh-category-properties ()
9078 "Refresh category text properties in the buffer."
9079 (let ((case-fold-search t)
9080 (inhibit-read-only t)
9081 (def-cat (cond
9082 ((null org-category)
9083 (if buffer-file-name
9084 (file-name-sans-extension
9085 (file-name-nondirectory buffer-file-name))
9086 "???"))
9087 ((symbolp org-category) (symbol-name org-category))
9088 (t org-category)))
9089 beg end cat pos optionp)
9090 (org-with-silent-modifications
9091 (save-excursion
9092 (save-restriction
9093 (widen)
9094 (goto-char (point-min))
9095 (put-text-property (point) (point-max) 'org-category def-cat)
9096 (while (re-search-forward
9097 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9098 (setq pos (match-end 0)
9099 optionp (equal (char-after (match-beginning 0)) ?#)
9100 cat (org-trim (match-string 2)))
9101 (if optionp
9102 (setq beg (point-at-bol) end (point-max))
9103 (org-back-to-heading t)
9104 (setq beg (point) end (org-end-of-subtree t t)))
9105 (put-text-property beg end 'org-category cat)
9106 (put-text-property beg end 'org-category-position beg)
9107 (goto-char pos)))))))
9109 (defun org-refresh-properties (dprop tprop)
9110 "Refresh buffer text properties.
9111 DPROP is the drawer property and TPROP is the corresponding text
9112 property to set."
9113 (let ((case-fold-search t)
9114 (inhibit-read-only t) p)
9115 (org-with-silent-modifications
9116 (save-excursion
9117 (save-restriction
9118 (widen)
9119 (goto-char (point-min))
9120 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9121 (setq p (org-match-string-no-properties 1))
9122 (save-excursion
9123 (org-back-to-heading t)
9124 (put-text-property
9125 (point-at-bol) (point-at-eol) tprop p))))))))
9128 ;;;; Link Stuff
9130 ;;; Link abbreviations
9132 (defun org-link-expand-abbrev (link)
9133 "Apply replacements as defined in `org-link-abbrev-alist'."
9134 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9135 (let* ((key (match-string 1 link))
9136 (as (or (assoc key org-link-abbrev-alist-local)
9137 (assoc key org-link-abbrev-alist)))
9138 (tag (and (match-end 2) (match-string 3 link)))
9139 rpl)
9140 (if (not as)
9141 link
9142 (setq rpl (cdr as))
9143 (cond
9144 ((symbolp rpl) (funcall rpl tag))
9145 ((string-match "%(\\([^)]+\\))" rpl)
9146 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
9147 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9148 ((string-match "%h" rpl)
9149 (replace-match (url-hexify-string (or tag "")) t t rpl))
9150 (t (concat rpl tag)))))
9151 link))
9153 ;;; Storing and inserting links
9155 (defvar org-insert-link-history nil
9156 "Minibuffer history for links inserted with `org-insert-link'.")
9158 (defvar org-stored-links nil
9159 "Contains the links stored with `org-store-link'.")
9161 (defvar org-store-link-plist nil
9162 "Plist with info about the most recently link created with `org-store-link'.")
9164 (defvar org-link-protocols nil
9165 "Link protocols added to Org-mode using `org-add-link-type'.")
9167 (defvar org-store-link-functions nil
9168 "List of functions that are called to create and store a link.
9169 Each function will be called in turn until one returns a non-nil
9170 value. Each function should check if it is responsible for creating
9171 this link (for example by looking at the major mode).
9172 If not, it must exit and return nil.
9173 If yes, it should return a non-nil value after a calling
9174 `org-store-link-props' with a list of properties and values.
9175 Special properties are:
9177 :type The link prefix, like \"http\". This must be given.
9178 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9179 This is obligatory as well.
9180 :description Optional default description for the second pair
9181 of brackets in an Org-mode link. The user can still change
9182 this when inserting this link into an Org-mode buffer.
9184 In addition to these, any additional properties can be specified
9185 and then used in capture templates.")
9187 (defun org-add-link-type (type &optional follow export)
9188 "Add TYPE to the list of `org-link-types'.
9189 Re-compute all regular expressions depending on `org-link-types'
9191 FOLLOW and EXPORT are two functions.
9193 FOLLOW should take the link path as the single argument and do whatever
9194 is necessary to follow the link, for example find a file or display
9195 a mail message.
9197 EXPORT should format the link path for export to one of the export formats.
9198 It should be a function accepting three arguments:
9200 path the path of the link, the text after the prefix (like \"http:\")
9201 desc the description of the link, if any, or a description added by
9202 org-export-normalize-links if there is none
9203 format the export format, a symbol like `html' or `latex' or `ascii'..
9205 The function may use the FORMAT information to return different values
9206 depending on the format. The return value will be put literally into
9207 the exported file. If the return value is nil, this means Org should
9208 do what it normally does with links which do not have EXPORT defined.
9210 Org-mode has a built-in default for exporting links. If you are happy with
9211 this default, there is no need to define an export function for the link
9212 type. For a simple example of an export function, see `org-bbdb.el'."
9213 (add-to-list 'org-link-types type t)
9214 (org-make-link-regexps)
9215 (if (assoc type org-link-protocols)
9216 (setcdr (assoc type org-link-protocols) (list follow export))
9217 (push (list type follow export) org-link-protocols)))
9219 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9220 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9222 ;;;###autoload
9223 (defun org-store-link (arg)
9224 "\\<org-mode-map>Store an org-link to the current location.
9225 This link is added to `org-stored-links' and can later be inserted
9226 into an org-buffer with \\[org-insert-link].
9228 For some link types, a prefix arg is interpreted.
9229 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9230 For file links, arg negates `org-context-in-file-links'.
9232 A double prefix arg force skipping storing functions that are not
9233 part of Org's core."
9234 (interactive "P")
9235 (org-load-modules-maybe)
9236 (setq org-store-link-plist nil) ; reset
9237 (org-with-limited-levels
9238 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
9239 (cond
9240 ((and (not (equal arg '(16)))
9241 (setq sfuns
9242 (delq
9243 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
9244 org-store-link-functions))
9245 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9246 (or (and (cdr sfuns)
9247 (funcall (intern
9248 (completing-read "Which function for creating the link? "
9249 sfunsn t (car sfunsn)))))
9250 (funcall (caar sfuns)))
9251 (setq link (plist-get org-store-link-plist :link)
9252 desc (or (plist-get org-store-link-plist :description) link))))
9253 ((org-src-edit-buffer-p)
9254 (let (label gc)
9255 (while (or (not label)
9256 (save-excursion
9257 (save-restriction
9258 (widen)
9259 (goto-char (point-min))
9260 (re-search-forward
9261 (regexp-quote (format org-coderef-label-format label))
9262 nil t))))
9263 (when label (message "Label exists already") (sit-for 2))
9264 (setq label (read-string "Code line label: " label)))
9265 (end-of-line 1)
9266 (setq link (format org-coderef-label-format label))
9267 (setq gc (- 79 (length link)))
9268 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9269 (insert link)
9270 (setq link (concat "(" label ")") desc nil)))
9272 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9273 ;; We are in the agenda, link to referenced location
9274 (let ((m (or (get-text-property (point) 'org-hd-marker)
9275 (get-text-property (point) 'org-marker))))
9276 (when m
9277 (org-with-point-at m
9278 (setq agenda-link
9279 (if (org-called-interactively-p 'any)
9280 (call-interactively 'org-store-link)
9281 (org-store-link nil)))))))
9283 ((eq major-mode 'calendar-mode)
9284 (let ((cd (calendar-cursor-to-date)))
9285 (setq link
9286 (format-time-string
9287 (car org-time-stamp-formats)
9288 (apply 'encode-time
9289 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9290 nil nil nil))))
9291 (org-store-link-props :type "calendar" :date cd)))
9293 ((eq major-mode 'help-mode)
9294 (setq link (concat "help:" (save-excursion
9295 (goto-char (point-min))
9296 (looking-at "^[^ ]+")
9297 (match-string 0))))
9298 (org-store-link-props :type "help"))
9300 ((eq major-mode 'w3-mode)
9301 (setq cpltxt (if (and (buffer-name)
9302 (not (string-match "Untitled" (buffer-name))))
9303 (buffer-name)
9304 (url-view-url t))
9305 link (url-view-url t))
9306 (org-store-link-props :type "w3" :url (url-view-url t)))
9308 ((setq search (run-hook-with-args-until-success
9309 'org-create-file-search-functions))
9310 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9311 "::" search))
9312 (setq cpltxt (or description link)))
9314 ((eq major-mode 'image-mode)
9315 (setq cpltxt (concat "file:"
9316 (abbreviate-file-name buffer-file-name))
9317 link cpltxt)
9318 (org-store-link-props :type "image" :file buffer-file-name))
9320 ((eq major-mode 'dired-mode)
9321 ;; link to the file in the current line
9322 (let ((file (dired-get-filename nil t)))
9323 (setq file (if file
9324 (abbreviate-file-name
9325 (expand-file-name (dired-get-filename nil t)))
9326 ;; otherwise, no file so use current directory.
9327 default-directory))
9328 (setq cpltxt (concat "file:" file)
9329 link cpltxt)))
9331 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9332 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9333 (cond
9334 ((org-in-regexp "<<\\(.*?\\)>>")
9335 (setq cpltxt
9336 (concat "file:"
9337 (abbreviate-file-name
9338 (buffer-file-name (buffer-base-buffer)))
9339 "::" (match-string 1))
9340 link cpltxt))
9341 ((and (featurep 'org-id)
9342 (or (eq org-id-link-to-org-use-id t)
9343 (and (org-called-interactively-p 'any)
9344 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9345 (and (eq org-id-link-to-org-use-id
9346 'create-if-interactive-and-no-custom-id)
9347 (not custom-id))))
9348 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9349 ;; We can make a link using the ID.
9350 (setq link (condition-case nil
9351 (prog1 (org-id-store-link)
9352 (setq desc (plist-get org-store-link-plist :description)))
9353 (error
9354 ;; probably before first headline, link to file only
9355 (concat "file:"
9356 (abbreviate-file-name
9357 (buffer-file-name (buffer-base-buffer))))))))
9359 ;; Just link to current headline
9360 (setq cpltxt (concat "file:"
9361 (abbreviate-file-name
9362 (buffer-file-name (buffer-base-buffer)))))
9363 ;; Add a context search string
9364 (when (org-xor org-context-in-file-links arg)
9365 (let* ((ee (org-element-at-point))
9366 (et (org-element-type ee))
9367 (ev (plist-get (cadr ee) :value)))
9368 (setq txt (cond
9369 ((org-at-heading-p) nil)
9370 ((eq et 'keyword) ev)
9371 ((org-region-active-p)
9372 (buffer-substring (region-beginning) (region-end)))))
9373 (when (or (null txt) (string-match "\\S-" txt))
9374 (setq cpltxt
9375 (concat cpltxt "::"
9376 (condition-case nil
9377 (org-make-org-heading-search-string txt)
9378 (error "")))
9379 desc (or (and (eq et 'keyword) ev)
9380 (nth 4 (ignore-errors (org-heading-components)))
9381 "NONE")))))
9382 (if (string-match "::\\'" cpltxt)
9383 (setq cpltxt (substring cpltxt 0 -2)))
9384 (setq link cpltxt))))
9386 ((buffer-file-name (buffer-base-buffer))
9387 ;; Just link to this file here.
9388 (setq cpltxt (concat "file:"
9389 (abbreviate-file-name
9390 (buffer-file-name (buffer-base-buffer)))))
9391 ;; Add a context string
9392 (when (org-xor org-context-in-file-links arg)
9393 (setq txt (if (org-region-active-p)
9394 (buffer-substring (region-beginning) (region-end))
9395 (buffer-substring (point-at-bol) (point-at-eol))))
9396 ;; Only use search option if there is some text.
9397 (when (string-match "\\S-" txt)
9398 (setq cpltxt
9399 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9400 desc "NONE")))
9401 (setq link cpltxt))
9403 ((org-called-interactively-p 'interactive)
9404 (user-error "No method for storing a link from this buffer"))
9406 (t (setq link nil)))
9408 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9409 (setq link (or link cpltxt)
9410 desc (or desc cpltxt))
9411 (cond ((equal desc "NONE") (setq desc nil))
9412 ((string-match org-bracket-link-regexp desc)
9413 (setq desc (replace-regexp-in-string
9414 org-bracket-link-regexp
9415 (concat "\\3" (if (equal (length (match-string 0 desc))
9416 (length desc)) "*" "")) desc))))
9418 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9419 (progn
9420 (setq org-stored-links
9421 (cons (list link desc) org-stored-links))
9422 (message "Stored: %s" (or desc link))
9423 (when custom-id
9424 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9425 "::#" custom-id))
9426 (setq org-stored-links
9427 (cons (list link desc) org-stored-links))))
9428 (or agenda-link (and link (org-make-link-string link desc)))))))
9430 (defun org-store-link-props (&rest plist)
9431 "Store link properties, extract names and addresses."
9432 (let (x adr)
9433 (when (setq x (plist-get plist :from))
9434 (setq adr (mail-extract-address-components x))
9435 (setq plist (plist-put plist :fromname (car adr)))
9436 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9437 (when (setq x (plist-get plist :to))
9438 (setq adr (mail-extract-address-components x))
9439 (setq plist (plist-put plist :toname (car adr)))
9440 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9441 (let ((from (plist-get plist :from))
9442 (to (plist-get plist :to)))
9443 (when (and from to org-from-is-user-regexp)
9444 (setq plist
9445 (plist-put plist :fromto
9446 (if (string-match org-from-is-user-regexp from)
9447 (concat "to %t")
9448 (concat "from %f"))))))
9449 (setq org-store-link-plist plist))
9451 (defun org-add-link-props (&rest plist)
9452 "Add these properties to the link property list."
9453 (let (key value)
9454 (while plist
9455 (setq key (pop plist) value (pop plist))
9456 (setq org-store-link-plist
9457 (plist-put org-store-link-plist key value)))))
9459 (defun org-email-link-description (&optional fmt)
9460 "Return the description part of an email link.
9461 This takes information from `org-store-link-plist' and formats it
9462 according to FMT (default from `org-email-link-description-format')."
9463 (setq fmt (or fmt org-email-link-description-format))
9464 (let* ((p org-store-link-plist)
9465 (to (plist-get p :toaddress))
9466 (from (plist-get p :fromaddress))
9467 (table
9468 (list
9469 (cons "%c" (plist-get p :fromto))
9470 (cons "%F" (plist-get p :from))
9471 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9472 (cons "%T" (plist-get p :to))
9473 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9474 (cons "%s" (plist-get p :subject))
9475 (cons "%d" (plist-get p :date))
9476 (cons "%m" (plist-get p :message-id)))))
9477 (when (string-match "%c" fmt)
9478 ;; Check if the user wrote this message
9479 (if (and org-from-is-user-regexp from to
9480 (save-match-data (string-match org-from-is-user-regexp from)))
9481 (setq fmt (replace-match "to %t" t t fmt))
9482 (setq fmt (replace-match "from %f" t t fmt))))
9483 (org-replace-escapes fmt table)))
9485 (defun org-make-org-heading-search-string (&optional string)
9486 "Make search string for the current headline or STRING."
9487 (let ((s (or string
9488 (and (derived-mode-p 'org-mode)
9489 (save-excursion
9490 (org-back-to-heading t)
9491 (org-element-property :raw-value (org-element-at-point))))))
9492 (lines org-context-in-file-links))
9493 (or string (setq s (concat "*" s))) ; Add * for headlines
9494 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9495 (when (and string (integerp lines) (> lines 0))
9496 (let ((slines (org-split-string s "\n")))
9497 (when (< lines (length slines))
9498 (setq s (mapconcat
9499 'identity
9500 (reverse (nthcdr (- (length slines) lines)
9501 (reverse slines))) "\n")))))
9502 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9504 (defun org-make-link-string (link &optional description)
9505 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9506 (unless (string-match "\\S-" link)
9507 (error "Empty link"))
9508 (when (and description
9509 (stringp description)
9510 (not (string-match "\\S-" description)))
9511 (setq description nil))
9512 (when (stringp description)
9513 ;; Remove brackets from the description, they are fatal.
9514 (while (string-match "\\[" description)
9515 (setq description (replace-match "{" t t description)))
9516 (while (string-match "\\]" description)
9517 (setq description (replace-match "}" t t description))))
9518 (when (equal link description)
9519 ;; No description needed, it is identical
9520 (setq description nil))
9521 (when (and (not description)
9522 (not (string-match (org-image-file-name-regexp) link))
9523 (not (equal link (org-link-escape link))))
9524 (setq description (org-extract-attributes link)))
9525 (setq link
9526 (cond ((string-match (org-image-file-name-regexp) link) link)
9527 ((string-match org-link-types-re link)
9528 (concat (match-string 1 link)
9529 (org-link-escape (substring link (match-end 1)))))
9530 (t (org-link-escape link))))
9531 (concat "[[" link "]"
9532 (if description (concat "[" description "]") "")
9533 "]"))
9535 (defconst org-link-escape-chars
9536 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9537 "List of characters that should be escaped in link.
9538 This is the list that is used for internal purposes.")
9540 (defconst org-link-escape-chars-browser
9541 '(?\ )
9542 "List of escapes for characters that are problematic in links.
9543 This is the list that is used before handing over to the browser.")
9545 (defun org-link-escape (text &optional table merge)
9546 "Return percent escaped representation of TEXT.
9547 TEXT is a string with the text to escape.
9548 Optional argument TABLE is a list with characters that should be
9549 escaped. When nil, `org-link-escape-chars' is used.
9550 If optional argument MERGE is set, merge TABLE into
9551 `org-link-escape-chars'."
9552 (cond
9553 ((and table merge)
9554 (mapc (lambda (defchr)
9555 (unless (member defchr table)
9556 (setq table (cons defchr table)))) org-link-escape-chars))
9557 ((null table)
9558 (setq table org-link-escape-chars)))
9559 (mapconcat
9560 (lambda (char)
9561 (if (or (member char table)
9562 (and (or (< char 32) (= char 37) (> char 126))
9563 org-url-hexify-p))
9564 (mapconcat (lambda (sequence-element)
9565 (format "%%%.2X" sequence-element))
9566 (or (encode-coding-char char 'utf-8)
9567 (error "Unable to percent escape character: %s"
9568 (char-to-string char))) "")
9569 (char-to-string char))) text ""))
9571 (defun org-link-unescape (str)
9572 "Unhex hexified Unicode strings as returned from the JavaScript function
9573 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9574 (unless (and (null str) (string= "" str))
9575 (let ((pos 0) (case-fold-search t) unhexed)
9576 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9577 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9578 (setq str (replace-match unhexed t t str))
9579 (setq pos (+ pos (length unhexed))))))
9580 str)
9582 (defun org-link-unescape-compound (hex)
9583 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9584 Note: this function also decodes single byte encodings like
9585 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9586 (save-match-data
9587 (let* ((bytes (cdr (split-string hex "%")))
9588 (ret "")
9589 (eat 0)
9590 (sum 0))
9591 (while bytes
9592 (let* ((val (string-to-number (pop bytes) 16))
9593 (shift-xor
9594 (if (= 0 eat)
9595 (cond
9596 ((>= val 252) (cons 6 252))
9597 ((>= val 248) (cons 5 248))
9598 ((>= val 240) (cons 4 240))
9599 ((>= val 224) (cons 3 224))
9600 ((>= val 192) (cons 2 192))
9601 (t (cons 0 0)))
9602 (cons 6 128))))
9603 (if (>= val 192) (setq eat (car shift-xor)))
9604 (setq val (logxor val (cdr shift-xor)))
9605 (setq sum (+ (lsh sum (car shift-xor)) val))
9606 (if (> eat 0) (setq eat (- eat 1)))
9607 (cond
9608 ((= 0 eat) ;multi byte
9609 (setq ret (concat ret (org-char-to-string sum)))
9610 (setq sum 0))
9611 ((not bytes) ; single byte(s)
9612 (setq ret (org-link-unescape-single-byte-sequence hex))))
9613 )) ;; end (while bytes
9614 ret )))
9616 (defun org-link-unescape-single-byte-sequence (hex)
9617 "Unhexify hex-encoded single byte character sequences."
9618 (mapconcat (lambda (byte)
9619 (char-to-string (string-to-number byte 16)))
9620 (cdr (split-string hex "%")) ""))
9622 (defun org-xor (a b)
9623 "Exclusive or."
9624 (if a (not b) b))
9626 (defun org-fixup-message-id-for-http (s)
9627 "Replace special characters in a message id, so it can be used in an http query."
9628 (when (string-match "%" s)
9629 (setq s (mapconcat (lambda (c)
9630 (if (eq c ?%)
9631 "%25"
9632 (char-to-string c)))
9633 s "")))
9634 (while (string-match "<" s)
9635 (setq s (replace-match "%3C" t t s)))
9636 (while (string-match ">" s)
9637 (setq s (replace-match "%3E" t t s)))
9638 (while (string-match "@" s)
9639 (setq s (replace-match "%40" t t s)))
9642 (defun org-link-prettify (link)
9643 "Return a human-readable representation of LINK.
9644 The car of LINK must be a raw link the cdr of LINK must be either
9645 a link description or nil."
9646 (let ((desc (or (cadr link) "<no description>")))
9647 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9648 "<" (car link) ">")))
9650 ;;;###autoload
9651 (defun org-insert-link-global ()
9652 "Insert a link like Org-mode does.
9653 This command can be called in any mode to insert a link in Org-mode syntax."
9654 (interactive)
9655 (org-load-modules-maybe)
9656 (org-run-like-in-org-mode 'org-insert-link))
9658 (defun org-insert-all-links (&optional keep)
9659 "Insert all links in `org-stored-links'."
9660 (interactive "P")
9661 (let ((links (copy-sequence org-stored-links)) l)
9662 (while (setq l (if keep (pop links) (pop org-stored-links)))
9663 (insert "- ")
9664 (org-insert-link nil (car l) (cadr l))
9665 (insert "\n"))))
9667 (defun org-link-fontify-links-to-this-file ()
9668 "Fontify links to the current file in `org-stored-links'."
9669 (let ((f (buffer-file-name)) a b)
9670 (setq a (mapcar (lambda(l)
9671 (let ((ll (car l)))
9672 (when (and (string-match "^file:\\(.+\\)::" ll)
9673 (equal f (expand-file-name (match-string 1 ll))))
9674 ll)))
9675 org-stored-links))
9676 (when (featurep 'org-id)
9677 (setq b (mapcar (lambda(l)
9678 (let ((ll (car l)))
9679 (when (and (string-match "^id:\\(.+\\)$" ll)
9680 (equal f (expand-file-name
9681 (or (org-id-find-id-file
9682 (match-string 1 ll)) ""))))
9683 ll)))
9684 org-stored-links)))
9685 (mapcar (lambda(l)
9686 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9687 (delq nil (append a b)))))
9689 (defvar org-link-links-in-this-file nil)
9690 (defun org-insert-link (&optional complete-file link-location default-description)
9691 "Insert a link. At the prompt, enter the link.
9693 Completion can be used to insert any of the link protocol prefixes like
9694 http or ftp in use.
9696 The history can be used to select a link previously stored with
9697 `org-store-link'. When the empty string is entered (i.e. if you just
9698 press RET at the prompt), the link defaults to the most recently
9699 stored link. As SPC triggers completion in the minibuffer, you need to
9700 use M-SPC or C-q SPC to force the insertion of a space character.
9702 You will also be prompted for a description, and if one is given, it will
9703 be displayed in the buffer instead of the link.
9705 If there is already a link at point, this command will allow you to edit link
9706 and description parts.
9708 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9709 be selected using completion. The path to the file will be relative to the
9710 current directory if the file is in the current directory or a subdirectory.
9711 Otherwise, the link will be the absolute path as completed in the minibuffer
9712 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9713 option `org-link-file-path-type'.
9715 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9716 the current directory or below.
9718 With three \\[universal-argument] prefixes, negate the meaning of
9719 `org-keep-stored-link-after-insertion'.
9721 If `org-make-link-description-function' is non-nil, this function will be
9722 called with the link target, and the result will be the default
9723 link description.
9725 If the LINK-LOCATION parameter is non-nil, this value will be
9726 used as the link location instead of reading one interactively.
9728 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9729 be used as the default description."
9730 (interactive "P")
9731 (let* ((wcf (current-window-configuration))
9732 (origbuf (current-buffer))
9733 (region (if (org-region-active-p)
9734 (buffer-substring (region-beginning) (region-end))))
9735 (remove (and region (list (region-beginning) (region-end))))
9736 (desc region)
9737 tmphist ; byte-compile incorrectly complains about this
9738 (link link-location)
9739 (abbrevs org-link-abbrev-alist-local)
9740 entry file all-prefixes auto-desc)
9741 (cond
9742 (link-location) ; specified by arg, just use it.
9743 ((org-in-regexp org-bracket-link-regexp 1)
9744 ;; We do have a link at point, and we are going to edit it.
9745 (setq remove (list (match-beginning 0) (match-end 0)))
9746 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9747 (setq link (read-string "Link: "
9748 (org-link-unescape
9749 (org-match-string-no-properties 1)))))
9750 ((or (org-in-regexp org-angle-link-re)
9751 (org-in-regexp org-plain-link-re))
9752 ;; Convert to bracket link
9753 (setq remove (list (match-beginning 0) (match-end 0))
9754 link (read-string "Link: "
9755 (org-remove-angle-brackets (match-string 0)))))
9756 ((member complete-file '((4) (16)))
9757 ;; Completing read for file names.
9758 (setq link (org-file-complete-link complete-file)))
9760 ;; Read link, with completion for stored links.
9761 (org-link-fontify-links-to-this-file)
9762 (org-switch-to-buffer-other-window "*Org Links*")
9763 (with-current-buffer "*Org Links*"
9764 (erase-buffer)
9765 (insert "Insert a link.
9766 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9767 (when org-stored-links
9768 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9769 (insert (mapconcat 'org-link-prettify
9770 (reverse org-stored-links) "\n")))
9771 (goto-char (point-min)))
9772 (let ((cw (selected-window)))
9773 (select-window (get-buffer-window "*Org Links*" 'visible))
9774 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9775 (unless (pos-visible-in-window-p (point-max))
9776 (org-fit-window-to-buffer))
9777 (and (window-live-p cw) (select-window cw)))
9778 ;; Fake a link history, containing the stored links.
9779 (setq tmphist (append (mapcar 'car org-stored-links)
9780 org-insert-link-history))
9781 (setq all-prefixes (append (mapcar 'car abbrevs)
9782 (mapcar 'car org-link-abbrev-alist)
9783 org-link-types))
9784 (unwind-protect
9785 (progn
9786 (setq link
9787 (org-completing-read
9788 "Link: "
9789 (append
9790 (mapcar (lambda (x) (concat x ":"))
9791 all-prefixes)
9792 (mapcar 'car org-stored-links))
9793 nil nil nil
9794 'tmphist
9795 (caar org-stored-links)))
9796 (if (not (string-match "\\S-" link))
9797 (error "No link selected"))
9798 (mapc (lambda(l)
9799 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9800 org-stored-links)
9801 (if (or (member link all-prefixes)
9802 (and (equal ":" (substring link -1))
9803 (member (substring link 0 -1) all-prefixes)
9804 (setq link (substring link 0 -1))))
9805 (setq link (with-current-buffer origbuf
9806 (org-link-try-special-completion link)))))
9807 (set-window-configuration wcf)
9808 (kill-buffer "*Org Links*"))
9809 (setq entry (assoc link org-stored-links))
9810 (or entry (push link org-insert-link-history))
9811 (setq desc (or desc (nth 1 entry)))))
9813 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9814 (not org-keep-stored-link-after-insertion))
9815 (setq org-stored-links (delq (assoc link org-stored-links)
9816 org-stored-links)))
9818 (if (string-match org-plain-link-re link)
9819 ;; URL-like link, normalize the use of angular brackets.
9820 (setq link (org-remove-angle-brackets link)))
9822 ;; Check if we are linking to the current file with a search
9823 ;; option If yes, simplify the link by using only the search
9824 ;; option.
9825 (when (and buffer-file-name
9826 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9827 (let* ((path (match-string 1 link))
9828 (case-fold-search nil)
9829 (search (match-string 2 link)))
9830 (save-match-data
9831 (if (equal (file-truename buffer-file-name) (file-truename path))
9832 ;; We are linking to this same file, with a search option
9833 (setq link search)))))
9835 ;; Check if we can/should use a relative path. If yes, simplify the link
9836 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9837 (let* ((type (match-string 1 link))
9838 (path (match-string 2 link))
9839 (origpath path)
9840 (case-fold-search nil))
9841 (cond
9842 ((or (eq org-link-file-path-type 'absolute)
9843 (equal complete-file '(16)))
9844 (setq path (abbreviate-file-name (expand-file-name path))))
9845 ((eq org-link-file-path-type 'noabbrev)
9846 (setq path (expand-file-name path)))
9847 ((eq org-link-file-path-type 'relative)
9848 (setq path (file-relative-name path)))
9850 (save-match-data
9851 (if (string-match (concat "^" (regexp-quote
9852 (expand-file-name
9853 (file-name-as-directory
9854 default-directory))))
9855 (expand-file-name path))
9856 ;; We are linking a file with relative path name.
9857 (setq path (substring (expand-file-name path)
9858 (match-end 0)))
9859 (setq path (abbreviate-file-name (expand-file-name path)))))))
9860 (setq link (concat type path))
9861 (if (equal desc origpath)
9862 (setq desc path))))
9864 (if org-make-link-description-function
9865 (setq desc
9866 (or (condition-case nil
9867 (funcall org-make-link-description-function link desc)
9868 (error (progn (message "Can't get link description from `%s'"
9869 (symbol-name org-make-link-description-function))
9870 (sit-for 2) nil)))
9871 (read-string "Description: " default-description)))
9872 (if default-description (setq desc default-description)
9873 (setq desc (or (and auto-desc desc)
9874 (read-string "Description: " desc)))))
9876 (unless (string-match "\\S-" desc) (setq desc nil))
9877 (if remove (apply 'delete-region remove))
9878 (insert (org-make-link-string link desc))))
9880 (defun org-link-try-special-completion (type)
9881 "If there is completion support for link type TYPE, offer it."
9882 (let ((fun (intern (concat "org-" type "-complete-link"))))
9883 (if (functionp fun)
9884 (funcall fun)
9885 (read-string "Link (no completion support): " (concat type ":")))))
9887 (defun org-file-complete-link (&optional arg)
9888 "Create a file link using completion."
9889 (let (file link)
9890 (setq file (org-iread-file-name "File: "))
9891 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9892 (pwd1 (file-name-as-directory (abbreviate-file-name
9893 (expand-file-name ".")))))
9894 (cond
9895 ((equal arg '(16))
9896 (setq link (concat
9897 "file:"
9898 (abbreviate-file-name (expand-file-name file)))))
9899 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9900 (setq link (concat "file:" (match-string 1 file))))
9901 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9902 (expand-file-name file))
9903 (setq link (concat
9904 "file:" (match-string 1 (expand-file-name file)))))
9905 (t (setq link (concat "file:" file)))))
9906 link))
9908 (defun org-iread-file-name (&rest args)
9909 "Read-file-name using `ido-mode' speedup if available.
9910 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9911 See `read-file-name' for a description of parameters."
9912 (org-without-partial-completion
9913 (if (and org-completion-use-ido
9914 (fboundp 'ido-read-file-name)
9915 (boundp 'ido-mode) ido-mode
9916 (listp (second args)))
9917 (let ((ido-enter-matching-directory nil))
9918 (apply 'ido-read-file-name args))
9919 (apply 'read-file-name args))))
9921 (defun org-completing-read (&rest args)
9922 "Completing-read with SPACE being a normal character."
9923 (let ((enable-recursive-minibuffers t)
9924 (minibuffer-local-completion-map
9925 (copy-keymap minibuffer-local-completion-map)))
9926 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9927 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9928 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9929 (apply 'org-icompleting-read args)))
9931 (defun org-completing-read-no-i (&rest args)
9932 (let (org-completion-use-ido org-completion-use-iswitchb)
9933 (apply 'org-completing-read args)))
9935 (defun org-iswitchb-completing-read (prompt choices &rest args)
9936 "Use iswitch as a completing-read replacement to choose from choices.
9937 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9938 from."
9939 (let* ((iswitchb-use-virtual-buffers nil)
9940 (iswitchb-make-buflist-hook
9941 (lambda ()
9942 (setq iswitchb-temp-buflist choices))))
9943 (iswitchb-read-buffer prompt)))
9945 (defun org-icompleting-read (&rest args)
9946 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9947 (org-without-partial-completion
9948 (if (and org-completion-use-ido
9949 (fboundp 'ido-completing-read)
9950 (boundp 'ido-mode) ido-mode
9951 (listp (second args)))
9952 (let ((ido-enter-matching-directory nil))
9953 (apply 'ido-completing-read (concat (car args))
9954 (if (consp (car (nth 1 args)))
9955 (mapcar 'car (nth 1 args))
9956 (nth 1 args))
9957 (cddr args)))
9958 (if (and org-completion-use-iswitchb
9959 (boundp 'iswitchb-mode) iswitchb-mode
9960 (listp (second args)))
9961 (apply 'org-iswitchb-completing-read (concat (car args))
9962 (if (consp (car (nth 1 args)))
9963 (mapcar 'car (nth 1 args))
9964 (nth 1 args))
9965 (cddr args))
9966 (apply 'completing-read args)))))
9968 (defun org-extract-attributes (s)
9969 "Extract the attributes cookie from a string and set as text property."
9970 (let (a attr (start 0) key value)
9971 (save-match-data
9972 (when (string-match "{{\\([^}]+\\)}}$" s)
9973 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9974 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9975 (setq key (match-string 1 a) value (match-string 2 a)
9976 start (match-end 0)
9977 attr (plist-put attr (intern key) value))))
9978 (org-add-props s nil 'org-attr attr))
9981 (defun org-extract-attributes-from-string (tag)
9982 (let (key value attr)
9983 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9984 (setq key (match-string 1 tag) value (match-string 2 tag)
9985 tag (replace-match "" t t tag)
9986 attr (plist-put attr (intern key) value)))
9987 (cons tag attr)))
9989 (defun org-attributes-to-string (plist)
9990 "Format a property list into an HTML attribute list."
9991 (let ((s "") key value)
9992 (while plist
9993 (setq key (pop plist) value (pop plist))
9994 (and value
9995 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9998 ;;; Opening/following a link
10000 (defvar org-link-search-failed nil)
10002 (defvar org-open-link-functions nil
10003 "Hook for functions finding a plain text link.
10004 These functions must take a single argument, the link content.
10005 They will be called for links that look like [[link text][description]]
10006 when LINK TEXT does not have a protocol like \"http:\" and does not look
10007 like a filename (e.g. \"./blue.png\").
10009 These functions will be called *before* Org attempts to resolve the
10010 link by doing text searches in the current buffer - so if you want a
10011 link \"[[target]]\" to still find \"<<target>>\", your function should
10012 handle this as a special case.
10014 When the function does handle the link, it must return a non-nil value.
10015 If it decides that it is not responsible for this link, it must return
10016 nil to indicate that that Org-mode can continue with other options
10017 like exact and fuzzy text search.")
10019 (defun org-next-link (&optional search-backward)
10020 "Move forward to the next link.
10021 If the link is in hidden text, expose it."
10022 (interactive "P")
10023 (when (and org-link-search-failed (eq this-command last-command))
10024 (goto-char (point-min))
10025 (message "Link search wrapped back to beginning of buffer"))
10026 (setq org-link-search-failed nil)
10027 (let* ((pos (point))
10028 (ct (org-context))
10029 (a (assoc :link ct))
10030 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10031 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10032 ((looking-at org-any-link-re)
10033 ;; Don't stay stuck at link without an org-link face
10034 (forward-char (if search-backward -1 1))))
10035 (if (funcall srch-fun org-any-link-re nil t)
10036 (progn
10037 (goto-char (match-beginning 0))
10038 (if (outline-invisible-p) (org-show-context)))
10039 (goto-char pos)
10040 (setq org-link-search-failed t)
10041 (message "No further link found"))))
10043 (defun org-previous-link ()
10044 "Move backward to the previous link.
10045 If the link is in hidden text, expose it."
10046 (interactive)
10047 (funcall 'org-next-link t))
10049 (defun org-translate-link (s)
10050 "Translate a link string if a translation function has been defined."
10051 (if (and org-link-translation-function
10052 (fboundp org-link-translation-function)
10053 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10054 (progn
10055 (setq s (funcall org-link-translation-function
10056 (match-string 1 s) (match-string 2 s)))
10057 (concat (car s) ":" (cdr s)))
10060 (defun org-translate-link-from-planner (type path)
10061 "Translate a link from Emacs Planner syntax so that Org can follow it.
10062 This is still an experimental function, your mileage may vary."
10063 (cond
10064 ((member type '("http" "https" "news" "ftp"))
10065 ;; standard Internet links are the same.
10066 nil)
10067 ((and (equal type "irc") (string-match "^//" path))
10068 ;; Planner has two / at the beginning of an irc link, we have 1.
10069 ;; We should have zero, actually....
10070 (setq path (substring path 1)))
10071 ((and (equal type "lisp") (string-match "^/" path))
10072 ;; Planner has a slash, we do not.
10073 (setq type "elisp" path (substring path 1)))
10074 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10075 ;; A typical message link. Planner has the id after the final slash,
10076 ;; we separate it with a hash mark
10077 (setq path (concat (match-string 1 path) "#"
10078 (org-remove-angle-brackets (match-string 2 path)))))
10080 (cons type path))
10082 (defun org-find-file-at-mouse (ev)
10083 "Open file link or URL at mouse."
10084 (interactive "e")
10085 (mouse-set-point ev)
10086 (org-open-at-point 'in-emacs))
10088 (defun org-open-at-mouse (ev)
10089 "Open file link or URL at mouse.
10090 See the docstring of `org-open-file' for details."
10091 (interactive "e")
10092 (mouse-set-point ev)
10093 (if (eq major-mode 'org-agenda-mode)
10094 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10095 (org-open-at-point))
10097 (defvar org-window-config-before-follow-link nil
10098 "The window configuration before following a link.
10099 This is saved in case the need arises to restore it.")
10101 (defvar org-open-link-marker (make-marker)
10102 "Marker pointing to the location where `org-open-at-point; was called.")
10104 ;;;###autoload
10105 (defun org-open-at-point-global ()
10106 "Follow a link like Org-mode does.
10107 This command can be called in any mode to follow a link that has
10108 Org-mode syntax."
10109 (interactive)
10110 (org-run-like-in-org-mode 'org-open-at-point))
10112 ;;;###autoload
10113 (defun org-open-link-from-string (s &optional arg reference-buffer)
10114 "Open a link in the string S, as if it was in Org-mode."
10115 (interactive "sLink: \nP")
10116 (let ((reference-buffer (or reference-buffer (current-buffer))))
10117 (with-temp-buffer
10118 (let ((org-inhibit-startup (not reference-buffer)))
10119 (org-mode)
10120 (insert s)
10121 (goto-char (point-min))
10122 (when reference-buffer
10123 (setq org-link-abbrev-alist-local
10124 (with-current-buffer reference-buffer
10125 org-link-abbrev-alist-local)))
10126 (org-open-at-point arg reference-buffer)))))
10128 (defvar org-open-at-point-functions nil
10129 "Hook that is run when following a link at point.
10131 Functions in this hook must return t if they identify and follow
10132 a link at point. If they don't find anything interesting at point,
10133 they must return nil.")
10135 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10136 (defun org-open-at-point (&optional arg reference-buffer)
10137 "Open link at or after point.
10138 If there is no link at point, this function will search forward up to
10139 the end of the current line.
10140 Normally, files will be opened by an appropriate application. If the
10141 optional prefix argument ARG is non-nil, Emacs will visit the file.
10142 With a double prefix argument, try to open outside of Emacs, in the
10143 application the system uses for this file type."
10144 (interactive "P")
10145 ;; if in a code block, then open the block's results
10146 (unless (call-interactively #'org-babel-open-src-block-result)
10147 (org-load-modules-maybe)
10148 (move-marker org-open-link-marker (point))
10149 (setq org-window-config-before-follow-link (current-window-configuration))
10150 (org-remove-occur-highlights nil nil t)
10151 (cond
10152 ((and (org-at-heading-p)
10153 (not (org-at-timestamp-p t))
10154 (not (org-in-regexp
10155 (concat org-plain-link-re "\\|"
10156 org-bracket-link-regexp "\\|"
10157 org-angle-link-re "\\|"
10158 "[ \t]:[^ \t\n]+:[ \t]*$")))
10159 (not (get-text-property (point) 'org-linked-text)))
10160 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10161 (lk0 (car lkall))
10162 (lk (if (stringp lk0) (list lk0) lk0))
10163 (lkend (cdr lkall)))
10164 (mapcar (lambda(l)
10165 (search-forward l nil lkend)
10166 (goto-char (match-beginning 0))
10167 (org-open-at-point))
10168 lk))
10169 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10170 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10171 ((and (org-at-timestamp-p t)
10172 (not (org-in-regexp org-bracket-link-regexp)))
10173 (org-follow-timestamp-link))
10174 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10175 (not (org-in-regexp org-any-link-re)))
10176 (org-footnote-action))
10178 (let (type path link line search (pos (point)))
10179 (catch 'match
10180 (save-excursion
10181 (skip-chars-forward "^]\n\r")
10182 (when (org-in-regexp org-bracket-link-regexp 1)
10183 (setq link (org-extract-attributes
10184 (org-link-unescape (org-match-string-no-properties 1))))
10185 (while (string-match " *\n *" link)
10186 (setq link (replace-match " " t t link)))
10187 (setq link (org-link-expand-abbrev link))
10188 (cond
10189 ((or (file-name-absolute-p link)
10190 (string-match "^\\.\\.?/" link))
10191 (setq type "file" path link))
10192 ((string-match org-link-re-with-space3 link)
10193 (setq type (match-string 1 link) path (match-string 2 link)))
10194 ((string-match "^help:+\\(.+\\)" link)
10195 (setq type "help" path (match-string 1 link)))
10196 (t (setq type "thisfile" path link)))
10197 (throw 'match t)))
10199 (when (get-text-property (point) 'org-linked-text)
10200 (setq type "thisfile"
10201 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10202 (1+ (point)) (point))
10203 path (buffer-substring
10204 (or (previous-single-property-change pos 'org-linked-text)
10205 (point-min))
10206 (or (next-single-property-change pos 'org-linked-text)
10207 (point-max))))
10208 (throw 'match t))
10210 (save-excursion
10211 (when (or (org-in-regexp org-angle-link-re)
10212 (let ((match (org-in-regexp org-plain-link-re)))
10213 ;; Check a plain link is not within a bracket link
10214 (and match
10215 (save-excursion
10216 (progn
10217 (goto-char (car match))
10218 (not (org-in-regexp org-bracket-link-regexp))))))
10219 (let ((line_ending (save-excursion (end-of-line) (point))))
10220 ;; We are in a line before a plain or bracket link
10221 (or (re-search-forward org-plain-link-re line_ending t)
10222 (re-search-forward org-bracket-link-regexp line_ending t))))
10223 (setq type (match-string 1)
10224 path (org-link-unescape (match-string 2)))
10225 (throw 'match t)))
10226 (save-excursion
10227 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10228 (setq type "tags"
10229 path (match-string 1))
10230 (while (string-match ":" path)
10231 (setq path (replace-match "+" t t path)))
10232 (throw 'match t)))
10233 (when (org-in-regexp "<\\([^><\n]+\\)>")
10234 (setq type "tree-match"
10235 path (match-string 1))
10236 (throw 'match t)))
10237 (unless path
10238 (user-error "No link found"))
10240 ;; switch back to reference buffer
10241 ;; needed when if called in a temporary buffer through
10242 ;; org-open-link-from-string
10243 (with-current-buffer (or reference-buffer (current-buffer))
10245 ;; Remove any trailing spaces in path
10246 (if (string-match " +\\'" path)
10247 (setq path (replace-match "" t t path)))
10248 (if (and org-link-translation-function
10249 (fboundp org-link-translation-function))
10250 ;; Check if we need to translate the link
10251 (let ((tmp (funcall org-link-translation-function type path)))
10252 (setq type (car tmp) path (cdr tmp))))
10254 (cond
10256 ((assoc type org-link-protocols)
10257 (funcall (nth 1 (assoc type org-link-protocols)) path))
10259 ((equal type "help")
10260 (let ((f-or-v (intern path)))
10261 (cond ((fboundp f-or-v)
10262 (describe-function f-or-v))
10263 ((boundp f-or-v)
10264 (describe-variable f-or-v))
10265 (t (error "Not a known function or variable")))))
10267 ((equal type "mailto")
10268 (let ((cmd (car org-link-mailto-program))
10269 (args (cdr org-link-mailto-program)) args1
10270 (address path) (subject "") a)
10271 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10272 (setq address (match-string 1 path)
10273 subject (org-link-escape (match-string 2 path))))
10274 (while args
10275 (cond
10276 ((not (stringp (car args))) (push (pop args) args1))
10277 (t (setq a (pop args))
10278 (if (string-match "%a" a)
10279 (setq a (replace-match address t t a)))
10280 (if (string-match "%s" a)
10281 (setq a (replace-match subject t t a)))
10282 (push a args1))))
10283 (apply cmd (nreverse args1))))
10285 ((member type '("http" "https" "ftp" "news"))
10286 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10287 (org-link-escape
10288 path org-link-escape-chars-browser)
10289 path))))
10291 ((string= type "doi")
10292 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10293 (org-link-escape
10294 path org-link-escape-chars-browser)
10295 path))))
10297 ((member type '("message"))
10298 (browse-url (concat type ":" path)))
10300 ((string= type "tags")
10301 (org-tags-view arg path))
10303 ((string= type "tree-match")
10304 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10306 ((string= type "file")
10307 (if (string-match "::\\([0-9]+\\)\\'" path)
10308 (setq line (string-to-number (match-string 1 path))
10309 path (substring path 0 (match-beginning 0)))
10310 (if (string-match "::\\(.+\\)\\'" path)
10311 (setq search (match-string 1 path)
10312 path (substring path 0 (match-beginning 0)))))
10313 (if (string-match "[*?{]" (file-name-nondirectory path))
10314 (dired path)
10315 (org-open-file path arg line search)))
10317 ((string= type "shell")
10318 (let ((buf (generate-new-buffer "*Org Shell Output"))
10319 (cmd path))
10320 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10321 (string-match org-confirm-shell-link-not-regexp cmd))
10322 (not org-confirm-shell-link-function)
10323 (funcall org-confirm-shell-link-function
10324 (format "Execute \"%s\" in shell? "
10325 (org-add-props cmd nil
10326 'face 'org-warning))))
10327 (progn
10328 (message "Executing %s" cmd)
10329 (shell-command cmd buf)
10330 (if (featurep 'midnight)
10331 (setq clean-buffer-list-kill-buffer-names
10332 (cons buf clean-buffer-list-kill-buffer-names))))
10333 (error "Abort"))))
10335 ((string= type "elisp")
10336 (let ((cmd path))
10337 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10338 (string-match org-confirm-elisp-link-not-regexp cmd))
10339 (not org-confirm-elisp-link-function)
10340 (funcall org-confirm-elisp-link-function
10341 (format "Execute \"%s\" as elisp? "
10342 (org-add-props cmd nil
10343 'face 'org-warning))))
10344 (message "%s => %s" cmd
10345 (if (equal (string-to-char cmd) ?\()
10346 (eval (read cmd))
10347 (call-interactively (read cmd))))
10348 (error "Abort"))))
10350 ((and (string= type "thisfile")
10351 (run-hook-with-args-until-success
10352 'org-open-link-functions path)))
10354 ((string= type "thisfile")
10355 (if arg
10356 (switch-to-buffer-other-window
10357 (org-get-buffer-for-internal-link (current-buffer)))
10358 (org-mark-ring-push))
10359 (let ((cmd `(org-link-search
10360 ,path
10361 ,(cond ((equal arg '(4)) ''occur)
10362 ((equal arg '(16)) ''org-occur))
10363 ,pos)))
10364 (condition-case nil (let ((org-link-search-inhibit-query t))
10365 (eval cmd))
10366 (error (progn (widen) (eval cmd))))))
10368 (t (browse-url-at-point)))))))
10369 (move-marker org-open-link-marker nil)
10370 (run-hook-with-args 'org-follow-link-hook)))
10372 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10373 "Offer links in the current entry and return the selected link.
10374 If there is only one link, return it.
10375 If NTH is an integer, return the NTH link found.
10376 If ZERO is a string, check also this string for a link, and if
10377 there is one, return it."
10378 (with-current-buffer buffer
10379 (save-excursion
10380 (save-restriction
10381 (widen)
10382 (goto-char marker)
10383 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10384 "\\(" org-angle-link-re "\\)\\|"
10385 "\\(" org-plain-link-re "\\)"))
10386 (cnt ?0)
10387 (in-emacs (if (integerp nth) nil nth))
10388 have-zero end links link c)
10389 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10390 (push (match-string 0 zero) links)
10391 (setq cnt (1- cnt) have-zero t))
10392 (save-excursion
10393 (org-back-to-heading t)
10394 (setq end (save-excursion (outline-next-heading) (point)))
10395 (while (re-search-forward re end t)
10396 (push (match-string 0) links))
10397 (setq links (org-uniquify (reverse links))))
10398 (cond
10399 ((null links)
10400 (message "No links"))
10401 ((equal (length links) 1)
10402 (setq link (car links)))
10403 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10404 (setq link (nth (if have-zero nth (1- nth)) links)))
10405 (t ; we have to select a link
10406 (save-excursion
10407 (save-window-excursion
10408 (delete-other-windows)
10409 (with-output-to-temp-buffer "*Select Link*"
10410 (mapc (lambda (l)
10411 (if (not (string-match org-bracket-link-regexp l))
10412 (princ (format "[%c] %s\n" (incf cnt)
10413 (org-remove-angle-brackets l)))
10414 (if (match-end 3)
10415 (princ (format "[%c] %s (%s)\n" (incf cnt)
10416 (match-string 3 l) (match-string 1 l)))
10417 (princ (format "[%c] %s\n" (incf cnt)
10418 (match-string 1 l))))))
10419 links))
10420 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10421 (message "Select link to open, RET to open all:")
10422 (setq c (read-char-exclusive))
10423 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10424 (when (equal c ?q) (error "Abort"))
10425 (if (equal c ?\C-m)
10426 (setq link links)
10427 (setq nth (- c ?0))
10428 (if have-zero (setq nth (1+ nth)))
10429 (unless (and (integerp nth) (>= (length links) nth))
10430 (error "Invalid link selection"))
10431 (setq link (nth (1- nth) links)))))
10432 (cons link end))))))
10434 ;; Add special file links that specify the way of opening
10436 (org-add-link-type "file+sys" 'org-open-file-with-system)
10437 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10438 (defun org-open-file-with-system (path)
10439 "Open file at PATH using the system way of opening it."
10440 (org-open-file path 'system))
10441 (defun org-open-file-with-emacs (path)
10442 "Open file at PATH in Emacs."
10443 (org-open-file path 'emacs))
10446 ;;; File search
10448 (defvar org-create-file-search-functions nil
10449 "List of functions to construct the right search string for a file link.
10450 These functions are called in turn with point at the location to
10451 which the link should point.
10453 A function in the hook should first test if it would like to
10454 handle this file type, for example by checking the `major-mode'
10455 or the file extension. If it decides not to handle this file, it
10456 should just return nil to give other functions a chance. If it
10457 does handle the file, it must return the search string to be used
10458 when following the link. The search string will be part of the
10459 file link, given after a double colon, and `org-open-at-point'
10460 will automatically search for it. If special measures must be
10461 taken to make the search successful, another function should be
10462 added to the companion hook `org-execute-file-search-functions',
10463 which see.
10465 A function in this hook may also use `setq' to set the variable
10466 `description' to provide a suggestion for the descriptive text to
10467 be used for this link when it gets inserted into an Org-mode
10468 buffer with \\[org-insert-link].")
10470 (defvar org-execute-file-search-functions nil
10471 "List of functions to execute a file search triggered by a link.
10473 Functions added to this hook must accept a single argument, the
10474 search string that was part of the file link, the part after the
10475 double colon. The function must first check if it would like to
10476 handle this search, for example by checking the `major-mode' or
10477 the file extension. If it decides not to handle this search, it
10478 should just return nil to give other functions a chance. If it
10479 does handle the search, it must return a non-nil value to keep
10480 other functions from trying.
10482 Each function can access the current prefix argument through the
10483 variable `current-prefix-arg'. Note that a single prefix is used
10484 to force opening a link in Emacs, so it may be good to only use a
10485 numeric or double prefix to guide the search function.
10487 In case this is needed, a function in this hook can also restore
10488 the window configuration before `org-open-at-point' was called using:
10490 (set-window-configuration org-window-config-before-follow-link)")
10492 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10493 (defun org-link-search (s &optional type avoid-pos stealth)
10494 "Search for a link search option.
10495 If S is surrounded by forward slashes, it is interpreted as a
10496 regular expression. In org-mode files, this will create an `org-occur'
10497 sparse tree. In ordinary files, `occur' will be used to list matches.
10498 If the current buffer is in `dired-mode', grep will be used to search
10499 in all files. If AVOID-POS is given, ignore matches near that position.
10501 When optional argument STEALTH is non-nil, do not modify
10502 visibility around point, thus ignoring
10503 `org-show-hierarchy-above', `org-show-following-heading' and
10504 `org-show-siblings' variables."
10505 (let ((case-fold-search t)
10506 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10507 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10508 (append '(("") (" ") ("\t") ("\n"))
10509 org-emphasis-alist)
10510 "\\|") "\\)"))
10511 (pos (point))
10512 (pre nil) (post nil)
10513 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10514 (cond
10515 ;; First check if there are any special search functions
10516 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10517 ;; Now try the builtin stuff
10518 ((and (equal (string-to-char s0) ?#)
10519 (> (length s0) 1)
10520 (save-excursion
10521 (goto-char (point-min))
10522 (and
10523 (re-search-forward
10524 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10525 (setq type 'dedicated
10526 pos (match-beginning 0))))
10527 ;; There is an exact target for this
10528 (goto-char pos)
10529 (org-back-to-heading t)))
10530 ((save-excursion
10531 (goto-char (point-min))
10532 (and
10533 (re-search-forward
10534 (concat "<<" (regexp-quote s0) ">>") nil t)
10535 (setq type 'dedicated
10536 pos (match-beginning 0))))
10537 ;; There is an exact target for this
10538 (goto-char pos))
10539 ((save-excursion
10540 (goto-char (point-min))
10541 (and
10542 (re-search-forward
10543 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10544 (setq type 'dedicated pos (match-beginning 0))))
10545 ;; Found an invisible target.
10546 (goto-char pos))
10547 ((save-excursion
10548 (goto-char (point-min))
10549 (and
10550 (re-search-forward
10551 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10552 (setq type 'dedicated pos (match-beginning 0))))
10553 ;; Found an element with a matching #+name affiliated keyword.
10554 (goto-char pos))
10555 ((and (string-match "^(\\(.*\\))$" s0)
10556 (save-excursion
10557 (goto-char (point-min))
10558 (and
10559 (re-search-forward
10560 (concat "[^[]" (regexp-quote
10561 (format org-coderef-label-format
10562 (match-string 1 s0))))
10563 nil t)
10564 (setq type 'dedicated
10565 pos (1+ (match-beginning 0))))))
10566 ;; There is a coderef target for this
10567 (goto-char pos))
10568 ((string-match "^/\\(.*\\)/$" s)
10569 ;; A regular expression
10570 (cond
10571 ((derived-mode-p 'org-mode)
10572 (org-occur (match-string 1 s)))
10573 (t (org-do-occur (match-string 1 s)))))
10574 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10575 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10576 (goto-char (point-min))
10577 (cond
10578 ((let (case-fold-search)
10579 (re-search-forward (format org-complex-heading-regexp-format
10580 (regexp-quote s))
10581 nil t))
10582 ;; OK, found a match
10583 (setq type 'dedicated)
10584 (goto-char (match-beginning 0)))
10585 ((and (not org-link-search-inhibit-query)
10586 (eq org-link-search-must-match-exact-headline 'query-to-create)
10587 (y-or-n-p "No match - create this as a new heading? "))
10588 (goto-char (point-max))
10589 (or (bolp) (newline))
10590 (insert "* " s "\n")
10591 (beginning-of-line 0))
10593 (goto-char pos)
10594 (error "No match"))))
10596 ;; A normal search string
10597 (when (equal (string-to-char s) ?*)
10598 ;; Anchor on headlines, post may include tags.
10599 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10600 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10601 s (substring s 1)))
10602 (remove-text-properties
10603 0 (length s)
10604 '(face nil mouse-face nil keymap nil fontified nil) s)
10605 ;; Make a series of regular expressions to find a match
10606 (setq words (org-split-string s "[ \n\r\t]+")
10608 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10609 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10610 "\\)" markers)
10611 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10612 re2a (concat "[ \t\r\n]" re2a_)
10613 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10614 re4 (concat "[^a-zA-Z_]" re4_)
10616 re1 (concat pre re2 post)
10617 re3 (concat pre (if pre re4_ re4) post)
10618 re5 (concat pre ".*" re4)
10619 re2 (concat pre re2)
10620 re2a (concat pre (if pre re2a_ re2a))
10621 re4 (concat pre (if pre re4_ re4))
10622 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10623 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10624 re5 "\\)"
10626 (cond
10627 ((eq type 'org-occur) (org-occur reall))
10628 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10629 (t (goto-char (point-min))
10630 (setq type 'fuzzy)
10631 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10632 (org-search-not-self 1 re1 nil t)
10633 (org-search-not-self 1 re2 nil t)
10634 (org-search-not-self 1 re2a nil t)
10635 (org-search-not-self 1 re3 nil t)
10636 (org-search-not-self 1 re4 nil t)
10637 (org-search-not-self 1 re5 nil t)
10639 (goto-char (match-beginning 1))
10640 (goto-char pos)
10641 (error "No match"))))))
10642 (and (derived-mode-p 'org-mode)
10643 (not stealth)
10644 (org-show-context 'link-search))
10645 type))
10647 (defun org-search-not-self (group &rest args)
10648 "Execute `re-search-forward', but only accept matches that do not
10649 enclose the position of `org-open-link-marker'."
10650 (let ((m org-open-link-marker))
10651 (catch 'exit
10652 (while (apply 're-search-forward args)
10653 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10654 (goto-char (match-end group))
10655 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10656 (> (match-beginning 0) (marker-position m))
10657 (< (match-end 0) (marker-position m)))
10658 (save-match-data
10659 (or (not (org-in-regexp
10660 org-bracket-link-analytic-regexp 1))
10661 (not (match-end 4)) ; no description
10662 (and (<= (match-beginning 4) (point))
10663 (>= (match-end 4) (point))))))
10664 (throw 'exit (point))))))))
10666 (defun org-get-buffer-for-internal-link (buffer)
10667 "Return a buffer to be used for displaying the link target of internal links."
10668 (cond
10669 ((not org-display-internal-link-with-indirect-buffer)
10670 buffer)
10671 ((string-match "(Clone)$" (buffer-name buffer))
10672 (message "Buffer is already a clone, not making another one")
10673 ;; we also do not modify visibility in this case
10674 buffer)
10675 (t ; make a new indirect buffer for displaying the link
10676 (let* ((bn (buffer-name buffer))
10677 (ibn (concat bn "(Clone)"))
10678 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10679 (with-current-buffer ib (org-overview))
10680 ib))))
10682 (defun org-do-occur (regexp &optional cleanup)
10683 "Call the Emacs command `occur'.
10684 If CLEANUP is non-nil, remove the printout of the regular expression
10685 in the *Occur* buffer. This is useful if the regex is long and not useful
10686 to read."
10687 (occur regexp)
10688 (when cleanup
10689 (let ((cwin (selected-window)) win beg end)
10690 (when (setq win (get-buffer-window "*Occur*"))
10691 (select-window win))
10692 (goto-char (point-min))
10693 (when (re-search-forward "match[a-z]+" nil t)
10694 (setq beg (match-end 0))
10695 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10696 (setq end (1- (match-beginning 0)))))
10697 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10698 (goto-char (point-min))
10699 (select-window cwin))))
10701 ;;; The mark ring for links jumps
10703 (defvar org-mark-ring nil
10704 "Mark ring for positions before jumps in Org-mode.")
10705 (defvar org-mark-ring-last-goto nil
10706 "Last position in the mark ring used to go back.")
10707 ;; Fill and close the ring
10708 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10709 (loop for i from 1 to org-mark-ring-length do
10710 (push (make-marker) org-mark-ring))
10711 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10712 org-mark-ring)
10714 (defun org-mark-ring-push (&optional pos buffer)
10715 "Put the current position or POS into the mark ring and rotate it."
10716 (interactive)
10717 (setq pos (or pos (point)))
10718 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10719 (move-marker (car org-mark-ring)
10720 (or pos (point))
10721 (or buffer (current-buffer)))
10722 (message "%s"
10723 (substitute-command-keys
10724 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10726 (defun org-mark-ring-goto (&optional n)
10727 "Jump to the previous position in the mark ring.
10728 With prefix arg N, jump back that many stored positions. When
10729 called several times in succession, walk through the entire ring.
10730 Org-mode commands jumping to a different position in the current file,
10731 or to another Org-mode file, automatically push the old position
10732 onto the ring."
10733 (interactive "p")
10734 (let (p m)
10735 (if (eq last-command this-command)
10736 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10737 (setq p org-mark-ring))
10738 (setq org-mark-ring-last-goto p)
10739 (setq m (car p))
10740 (org-pop-to-buffer-same-window (marker-buffer m))
10741 (goto-char m)
10742 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10744 (defun org-remove-angle-brackets (s)
10745 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10746 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10748 (defun org-add-angle-brackets (s)
10749 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10750 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10752 (defun org-remove-double-quotes (s)
10753 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10754 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10757 ;;; Following specific links
10759 (defun org-follow-timestamp-link ()
10760 "Open an agenda view for the time-stamp date/range at point."
10761 (cond
10762 ((org-at-date-range-p t)
10763 (let ((org-agenda-start-on-weekday)
10764 (t1 (match-string 1))
10765 (t2 (match-string 2)) tt1 tt2)
10766 (setq tt1 (time-to-days (org-time-string-to-time t1))
10767 tt2 (time-to-days (org-time-string-to-time t2)))
10768 (let ((org-agenda-buffer-tmp-name
10769 (format "*Org Agenda(a:%s)"
10770 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10771 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10772 ((org-at-timestamp-p t)
10773 (let ((org-agenda-buffer-tmp-name
10774 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10775 (org-agenda-list nil (time-to-days (org-time-string-to-time
10776 (substring (match-string 1) 0 10)))
10777 1)))
10778 (t (error "This should not happen"))))
10781 ;;; Following file links
10782 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10783 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10784 (declare-function mailcap-mime-info
10785 "mailcap" (string &optional request no-decode))
10786 (defvar org-wait nil)
10787 (defun org-open-file (path &optional in-emacs line search)
10788 "Open the file at PATH.
10789 First, this expands any special file name abbreviations. Then the
10790 configuration variable `org-file-apps' is checked if it contains an
10791 entry for this file type, and if yes, the corresponding command is launched.
10793 If no application is found, Emacs simply visits the file.
10795 With optional prefix argument IN-EMACS, Emacs will visit the file.
10796 With a double \\[universal-argument] \\[universal-argument] \
10797 prefix arg, Org tries to avoid opening in Emacs
10798 and to use an external application to visit the file.
10800 Optional LINE specifies a line to go to, optional SEARCH a string
10801 to search for. If LINE or SEARCH is given, the file will be
10802 opened in Emacs, unless an entry from org-file-apps that makes
10803 use of groups in a regexp matches.
10805 If you want to change the way frames are used when following a
10806 link, please customize `org-link-frame-setup'.
10808 If the file does not exist, an error is thrown."
10809 (let* ((file (if (equal path "")
10810 buffer-file-name
10811 (substitute-in-file-name (expand-file-name path))))
10812 (file-apps (append org-file-apps (org-default-apps)))
10813 (apps (org-remove-if
10814 'org-file-apps-entry-match-against-dlink-p file-apps))
10815 (apps-dlink (org-remove-if-not
10816 'org-file-apps-entry-match-against-dlink-p file-apps))
10817 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10818 (dirp (if remp nil (file-directory-p file)))
10819 (file (if (and dirp org-open-directory-means-index-dot-org)
10820 (concat (file-name-as-directory file) "index.org")
10821 file))
10822 (a-m-a-p (assq 'auto-mode apps))
10823 (dfile (downcase file))
10824 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10825 (link (cond ((and (eq line nil)
10826 (eq search nil))
10827 file)
10828 (line
10829 (concat file "::" (number-to-string line)))
10830 (search
10831 (concat file "::" search))))
10832 (dlink (downcase link))
10833 (old-buffer (current-buffer))
10834 (old-pos (point))
10835 (old-mode major-mode)
10836 ext cmd link-match-data)
10837 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10838 (setq ext (match-string 1 dfile))
10839 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10840 (setq ext (match-string 1 dfile))))
10841 (cond
10842 ((member in-emacs '((16) system))
10843 (setq cmd (cdr (assoc 'system apps))))
10844 (in-emacs (setq cmd 'emacs))
10846 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10847 (and dirp (cdr (assoc 'directory apps)))
10848 ; first, try matching against apps-dlink
10849 ; if we get a match here, store the match data for later
10850 (let ((match (assoc-default dlink apps-dlink
10851 'string-match)))
10852 (if match
10853 (progn (setq link-match-data (match-data))
10854 match)
10855 (progn (setq in-emacs (or in-emacs line search))
10856 nil))) ; if we have no match in apps-dlink,
10857 ; always open the file in emacs if line or search
10858 ; is given (for backwards compatibility)
10859 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10860 'string-match)
10861 (cdr (assoc ext apps))
10862 (cdr (assoc t apps))))))
10863 (when (eq cmd 'system)
10864 (setq cmd (cdr (assoc 'system apps))))
10865 (when (eq cmd 'default)
10866 (setq cmd (cdr (assoc t apps))))
10867 (when (eq cmd 'mailcap)
10868 (require 'mailcap)
10869 (mailcap-parse-mailcaps)
10870 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10871 (command (mailcap-mime-info mime-type)))
10872 (if (stringp command)
10873 (setq cmd command)
10874 (setq cmd 'emacs))))
10875 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10876 (not (file-exists-p file))
10877 (not org-open-non-existing-files))
10878 (error "No such file: %s" file))
10879 (cond
10880 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10881 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10882 (while (string-match "['\"]%s['\"]" cmd)
10883 (setq cmd (replace-match "%s" t t cmd)))
10884 (while (string-match "%s" cmd)
10885 (setq cmd (replace-match
10886 (save-match-data
10887 (shell-quote-argument
10888 (convert-standard-filename file)))
10889 t t cmd)))
10891 ;; Replace "%1", "%2" etc. in command with group matches from regex
10892 (save-match-data
10893 (let ((match-index 1)
10894 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10895 (set-match-data link-match-data)
10896 (while (<= match-index number-of-groups)
10897 (let ((regex (concat "%" (number-to-string match-index)))
10898 (replace-with (match-string match-index dlink)))
10899 (while (string-match regex cmd)
10900 (setq cmd (replace-match replace-with t t cmd))))
10901 (setq match-index (+ match-index 1)))))
10903 (save-window-excursion
10904 (message "Running %s...done" cmd)
10905 (start-process-shell-command cmd nil cmd)
10906 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10907 ((or (stringp cmd)
10908 (eq cmd 'emacs))
10909 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10910 (widen)
10911 (if line (org-goto-line line)
10912 (if search (org-link-search search))))
10913 ((consp cmd)
10914 (let ((file (convert-standard-filename file)))
10915 (save-match-data
10916 (set-match-data link-match-data)
10917 (eval cmd))))
10918 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10919 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10920 (or (not (equal old-buffer (current-buffer)))
10921 (not (equal old-pos (point))))
10922 (org-mark-ring-push old-pos old-buffer))))
10924 (defun org-file-apps-entry-match-against-dlink-p (entry)
10925 "This function returns non-nil if `entry' uses a regular
10926 expression which should be matched against the whole link by
10927 org-open-file.
10929 It assumes that is the case when the entry uses a regular
10930 expression which has at least one grouping construct and the
10931 action is either a lisp form or a command string containing
10932 '%1', i.e. using at least one subexpression match as a
10933 parameter."
10934 (let ((selector (car entry))
10935 (action (cdr entry)))
10936 (if (stringp selector)
10937 (and (> (regexp-opt-depth selector) 0)
10938 (or (and (stringp action)
10939 (string-match "%[0-9]" action))
10940 (consp action)))
10941 nil)))
10943 (defun org-default-apps ()
10944 "Return the default applications for this operating system."
10945 (cond
10946 ((eq system-type 'darwin)
10947 org-file-apps-defaults-macosx)
10948 ((eq system-type 'windows-nt)
10949 org-file-apps-defaults-windowsnt)
10950 (t org-file-apps-defaults-gnu)))
10952 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10953 "Convert extensions to regular expressions in the cars of LIST.
10954 Also, weed out any non-string entries, because the return value is used
10955 only for regexp matching.
10956 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10957 point to the symbol `emacs', indicating that the file should
10958 be opened in Emacs."
10959 (append
10960 (delq nil
10961 (mapcar (lambda (x)
10962 (if (not (stringp (car x)))
10964 (if (string-match "\\W" (car x))
10966 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10967 list))
10968 (if add-auto-mode
10969 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10971 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10972 (defun org-file-remote-p (file)
10973 "Test whether FILE specifies a location on a remote system.
10974 Return non-nil if the location is indeed remote.
10976 For example, the filename \"/user@host:/foo\" specifies a location
10977 on the system \"/user@host:\"."
10978 (cond ((fboundp 'file-remote-p)
10979 (file-remote-p file))
10980 ((fboundp 'tramp-handle-file-remote-p)
10981 (tramp-handle-file-remote-p file))
10982 ((and (boundp 'ange-ftp-name-format)
10983 (string-match (car ange-ftp-name-format) file))
10984 t)))
10987 ;;;; Refiling
10989 (defun org-get-org-file ()
10990 "Read a filename, with default directory `org-directory'."
10991 (let ((default (or org-default-notes-file remember-data-file)))
10992 (read-file-name (format "File name [%s]: " default)
10993 (file-name-as-directory org-directory)
10994 default)))
10996 (defun org-notes-order-reversed-p ()
10997 "Check if the current file should receive notes in reversed order."
10998 (cond
10999 ((not org-reverse-note-order) nil)
11000 ((eq t org-reverse-note-order) t)
11001 ((not (listp org-reverse-note-order)) nil)
11002 (t (catch 'exit
11003 (let ((all org-reverse-note-order)
11004 entry)
11005 (while (setq entry (pop all))
11006 (if (string-match (car entry) buffer-file-name)
11007 (throw 'exit (cdr entry))))
11008 nil)))))
11010 (defvar org-refile-target-table nil
11011 "The list of refile targets, created by `org-refile'.")
11013 (defvar org-agenda-new-buffers nil
11014 "Buffers created to visit agenda files.")
11016 (defvar org-refile-cache nil
11017 "Cache for refile targets.")
11019 (defvar org-refile-markers nil
11020 "All the markers used for caching refile locations.")
11022 (defun org-refile-marker (pos)
11023 "Get a new refile marker, but only if caching is in use."
11024 (if (not org-refile-use-cache)
11026 (let ((m (make-marker)))
11027 (move-marker m pos)
11028 (push m org-refile-markers)
11029 m)))
11031 (defun org-refile-cache-clear ()
11032 "Clear the refile cache and disable all the markers."
11033 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11034 (setq org-refile-markers nil)
11035 (setq org-refile-cache nil)
11036 (message "Refile cache has been cleared"))
11038 (defun org-refile-cache-check-set (set)
11039 "Check if all the markers in the cache still have live buffers."
11040 (let (marker)
11041 (catch 'exit
11042 (while (and set (setq marker (nth 3 (pop set))))
11043 ;; if org-refile-use-outline-path is 'file, marker may be nil
11044 (when (and marker (null (marker-buffer marker)))
11045 (message "not found") (sit-for 3)
11046 (throw 'exit nil)))
11047 t)))
11049 (defun org-refile-cache-put (set &rest identifiers)
11050 "Push the refile targets SET into the cache, under IDENTIFIERS."
11051 (let* ((key (sha1 (prin1-to-string identifiers)))
11052 (entry (assoc key org-refile-cache)))
11053 (if entry
11054 (setcdr entry set)
11055 (push (cons key set) org-refile-cache))))
11057 (defun org-refile-cache-get (&rest identifiers)
11058 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11059 (cond
11060 ((not org-refile-cache) nil)
11061 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11063 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11064 org-refile-cache))))
11065 (and set (org-refile-cache-check-set set) set)))))
11067 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11068 "Produce a table with refile targets."
11069 (let ((case-fold-search nil)
11070 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11071 (entries (or org-refile-targets '((nil . (:level . 1)))))
11072 targets tgs txt re files f desc descre fast-path-p level pos0)
11073 (message "Getting targets...")
11074 (with-current-buffer (or default-buffer (current-buffer))
11075 (while (setq entry (pop entries))
11076 (setq files (car entry) desc (cdr entry))
11077 (setq fast-path-p nil)
11078 (cond
11079 ((null files) (setq files (list (current-buffer))))
11080 ((eq files 'org-agenda-files)
11081 (setq files (org-agenda-files 'unrestricted)))
11082 ((and (symbolp files) (fboundp files))
11083 (setq files (funcall files)))
11084 ((and (symbolp files) (boundp files))
11085 (setq files (symbol-value files))))
11086 (if (stringp files) (setq files (list files)))
11087 (cond
11088 ((eq (car desc) :tag)
11089 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11090 ((eq (car desc) :todo)
11091 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11092 ((eq (car desc) :regexp)
11093 (setq descre (cdr desc)))
11094 ((eq (car desc) :level)
11095 (setq descre (concat "^\\*\\{" (number-to-string
11096 (if org-odd-levels-only
11097 (1- (* 2 (cdr desc)))
11098 (cdr desc)))
11099 "\\}[ \t]")))
11100 ((eq (car desc) :maxlevel)
11101 (setq fast-path-p t)
11102 (setq descre (concat "^\\*\\{1," (number-to-string
11103 (if org-odd-levels-only
11104 (1- (* 2 (cdr desc)))
11105 (cdr desc)))
11106 "\\}[ \t]")))
11107 (t (error "Bad refiling target description %s" desc)))
11108 (while (setq f (pop files))
11109 (with-current-buffer
11110 (if (bufferp f) f (org-get-agenda-file-buffer f))
11112 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11113 (progn
11114 (if (bufferp f) (setq f (buffer-file-name
11115 (buffer-base-buffer f))))
11116 (setq f (and f (expand-file-name f)))
11117 (if (eq org-refile-use-outline-path 'file)
11118 (push (list (file-name-nondirectory f) f nil nil) tgs))
11119 (save-excursion
11120 (save-restriction
11121 (widen)
11122 (goto-char (point-min))
11123 (while (re-search-forward descre nil t)
11124 (goto-char (setq pos0 (point-at-bol)))
11125 (catch 'next
11126 (when org-refile-target-verify-function
11127 (save-match-data
11128 (or (funcall org-refile-target-verify-function)
11129 (throw 'next t))))
11130 (when (and (looking-at org-complex-heading-regexp)
11131 (not (member (match-string 4) excluded-entries))
11132 (match-string 4))
11133 (setq level (org-reduced-level
11134 (- (match-end 1) (match-beginning 1)))
11135 txt (org-link-display-format (match-string 4))
11136 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11137 re (format org-complex-heading-regexp-format
11138 (regexp-quote (match-string 4))))
11139 (when org-refile-use-outline-path
11140 (setq txt (mapconcat
11141 'org-protect-slash
11142 (append
11143 (if (eq org-refile-use-outline-path
11144 'file)
11145 (list (file-name-nondirectory
11146 (buffer-file-name
11147 (buffer-base-buffer))))
11148 (if (eq org-refile-use-outline-path
11149 'full-file-path)
11150 (list (buffer-file-name
11151 (buffer-base-buffer)))))
11152 (org-get-outline-path fast-path-p
11153 level txt)
11154 (list txt))
11155 "/")))
11156 (push (list txt f re (org-refile-marker (point)))
11157 tgs)))
11158 (when (= (point) pos0)
11159 ;; verification function has not moved point
11160 (goto-char (point-at-eol))))))))
11161 (when org-refile-use-cache
11162 (org-refile-cache-put tgs (buffer-file-name) descre))
11163 (setq targets (append tgs targets))
11164 ))))
11165 (message "Getting targets...done")
11166 (nreverse targets)))
11168 (defun org-protect-slash (s)
11169 (while (string-match "/" s)
11170 (setq s (replace-match "\\" t t s)))
11173 (defvar org-olpa (make-vector 20 nil))
11175 (defun org-get-outline-path (&optional fastp level heading)
11176 "Return the outline path to the current entry, as a list.
11178 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11179 routine which makes outline path derivations for an entire file,
11180 avoiding backtracing. Refile target collection makes use of that."
11181 (if fastp
11182 (progn
11183 (if (> level 19)
11184 (error "Outline path failure, more than 19 levels"))
11185 (loop for i from level upto 19 do
11186 (aset org-olpa i nil))
11187 (prog1
11188 (delq nil (append org-olpa nil))
11189 (aset org-olpa level heading)))
11190 (let (rtn case-fold-search)
11191 (save-excursion
11192 (save-restriction
11193 (widen)
11194 (while (org-up-heading-safe)
11195 (when (looking-at org-complex-heading-regexp)
11196 (push (org-match-string-no-properties 4) rtn)))
11197 rtn)))))
11199 (defun org-format-outline-path (path &optional width prefix separator)
11200 "Format the outline path PATH for display.
11201 WIDTH is the maximum number of characters that is available.
11202 PREFIX is a prefix to be included in the returned string,
11203 such as the file name.
11204 SEPARATOR is inserted between the different parts of the path,
11205 the default is \"/\"."
11206 (setq width (or width 79))
11207 (if prefix (setq width (- width (length prefix))))
11208 (if (not path)
11209 (or prefix "")
11210 (let* ((nsteps (length path))
11211 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11212 (maxwidth (if (<= total-width width)
11213 10000 ;; everything fits
11214 ;; we need to shorten the level headings
11215 (/ (- width nsteps) nsteps)))
11216 (org-odd-levels-only nil)
11217 (n 0)
11218 (total (1+ (length prefix))))
11219 (setq maxwidth (max maxwidth 10))
11220 (concat prefix
11221 (if prefix (or separator "/"))
11222 (mapconcat
11223 (lambda (h)
11224 (setq n (1+ n))
11225 (if (and (= n nsteps) (< maxwidth 10000))
11226 (setq maxwidth (- total-width total)))
11227 (if (< (length h) maxwidth)
11228 (progn (setq total (+ total (length h) 1)) h)
11229 (setq h (substring h 0 (- maxwidth 2))
11230 total (+ total maxwidth 1))
11231 (if (string-match "[ \t]+\\'" h)
11232 (setq h (substring h 0 (match-beginning 0))))
11233 (setq h (concat h "..")))
11234 (org-add-props h nil 'face
11235 (nth (% (1- n) org-n-level-faces)
11236 org-level-faces))
11238 path (or separator "/"))))))
11240 (defun org-display-outline-path (&optional file current separator just-return-string)
11241 "Display the current outline path in the echo area.
11243 If FILE is non-nil, prepend the output with the file name.
11244 If CURRENT is non-nil, append the current heading to the output.
11245 SEPARATOR is passed through to `org-format-outline-path'. It separates
11246 the different parts of the path and defaults to \"/\".
11247 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11248 (interactive "P")
11249 (let* (case-fold-search
11250 message-log-max ; Don't populate the *Messages* buffer
11251 (bfn (buffer-file-name (buffer-base-buffer)))
11252 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11253 res)
11254 (if current (setq path (append path
11255 (save-excursion
11256 (org-back-to-heading t)
11257 (if (looking-at org-complex-heading-regexp)
11258 (list (match-string 4)))))))
11259 (setq res
11260 (org-format-outline-path
11261 path
11262 (1- (frame-width))
11263 (and file bfn (concat (file-name-nondirectory bfn) separator))
11264 separator))
11265 (if just-return-string
11266 (org-no-properties res)
11267 (message "%s" res))))
11269 (defvar org-refile-history nil
11270 "History for refiling operations.")
11272 (defvar org-after-refile-insert-hook nil
11273 "Hook run after `org-refile' has inserted its stuff at the new location.
11274 Note that this is still *before* the stuff will be removed from
11275 the *old* location.")
11277 (defvar org-capture-last-stored-marker)
11278 (defvar org-refile-keep nil
11279 "Non-nil means `org-refile' will copy instead of refile.")
11281 (defun org-copy ()
11282 "Like `org-refile', but copy."
11283 (interactive)
11284 (let ((org-refile-keep t))
11285 (funcall 'org-refile nil nil nil "Copy")))
11287 (defun org-refile (&optional goto default-buffer rfloc msg)
11288 "Move the entry or entries at point to another heading.
11289 The list of target headings is compiled using the information in
11290 `org-refile-targets', which see.
11292 At the target location, the entry is filed as a subitem of the target
11293 heading. Depending on `org-reverse-note-order', the new subitem will
11294 either be the first or the last subitem.
11296 If there is an active region, all entries in that region will be moved.
11297 However, the region must fulfill the requirement that the first heading
11298 is the first one sets the top-level of the moved text - at most siblings
11299 below it are allowed.
11301 With prefix arg GOTO, the command will only visit the target location
11302 and not actually move anything.
11304 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11305 go to the location where the last refiling operation has put the subtree.
11306 With a prefix argument of `2', refile to the running clock.
11308 RFLOC can be a refile location obtained in a different way.
11310 MSG is a string to replace \"Refile\" in the default prompt with
11311 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11313 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11315 If you are using target caching (see `org-refile-use-cache'),
11316 you have to clear the target cache in order to find new targets.
11317 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11318 prefix argument (`C-u C-u C-u C-c C-w')."
11320 (interactive "P")
11321 (if (member goto '(0 (64)))
11322 (org-refile-cache-clear)
11323 (let* ((actionmsg (or msg "Refile"))
11324 (cbuf (current-buffer))
11325 (regionp (org-region-active-p))
11326 (region-start (and regionp (region-beginning)))
11327 (region-end (and regionp (region-end)))
11328 (region-length (and regionp (- region-end region-start)))
11329 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11330 pos it nbuf file re level reversed)
11331 (setq last-command nil)
11332 (when regionp
11333 (goto-char region-start)
11334 (or (bolp) (goto-char (point-at-bol)))
11335 (setq region-start (point))
11336 (unless (or (org-kill-is-subtree-p
11337 (buffer-substring region-start region-end))
11338 (prog1 org-refile-active-region-within-subtree
11339 (org-toggle-heading)))
11340 (error "The region is not a (sequence of) subtree(s)")))
11341 (if (equal goto '(16))
11342 (org-refile-goto-last-stored)
11343 (when (or
11344 (and (equal goto 2)
11345 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11346 (prog1
11347 (setq it (list (or org-clock-heading "running clock")
11348 (buffer-file-name
11349 (marker-buffer org-clock-hd-marker))
11351 (marker-position org-clock-hd-marker)))
11352 (setq goto nil)))
11353 (setq it (or rfloc
11354 (let (heading-text)
11355 (save-excursion
11356 (unless goto
11357 (org-back-to-heading t)
11358 (setq heading-text
11359 (nth 4 (org-heading-components))))
11361 (org-refile-get-location
11362 (cond (goto "Goto")
11363 (regionp (concat actionmsg " region to"))
11364 (t (concat actionmsg " subtree \""
11365 heading-text "\" to")))
11366 default-buffer
11367 (and (not (equal '(4) goto))
11368 org-refile-allow-creating-parent-nodes)
11369 goto))))))
11370 (setq file (nth 1 it)
11371 re (nth 2 it)
11372 pos (nth 3 it))
11373 (if (and (not goto)
11375 (equal (buffer-file-name) file)
11376 (if regionp
11377 (and (>= pos region-start)
11378 (<= pos region-end))
11379 (and (>= pos (point))
11380 (< pos (save-excursion
11381 (org-end-of-subtree t t))))))
11382 (error "Cannot refile to position inside the tree or region"))
11384 (setq nbuf (or (find-buffer-visiting file)
11385 (find-file-noselect file)))
11386 (if goto
11387 (progn
11388 (org-pop-to-buffer-same-window nbuf)
11389 (goto-char pos)
11390 (org-show-context 'org-goto))
11391 (if regionp
11392 (progn
11393 (org-kill-new (buffer-substring region-start region-end))
11394 (org-save-markers-in-region region-start region-end))
11395 (org-copy-subtree 1 nil t))
11396 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11397 (find-file-noselect file)))
11398 (setq reversed (org-notes-order-reversed-p))
11399 (save-excursion
11400 (save-restriction
11401 (widen)
11402 (if pos
11403 (progn
11404 (goto-char pos)
11405 (looking-at org-outline-regexp)
11406 (setq level (org-get-valid-level (funcall outline-level) 1))
11407 (goto-char
11408 (if reversed
11409 (or (outline-next-heading) (point-max))
11410 (or (save-excursion (org-get-next-sibling))
11411 (org-end-of-subtree t t)
11412 (point-max)))))
11413 (setq level 1)
11414 (if (not reversed)
11415 (goto-char (point-max))
11416 (goto-char (point-min))
11417 (or (outline-next-heading) (goto-char (point-max)))))
11418 (if (not (bolp)) (newline))
11419 (org-paste-subtree level)
11420 (when org-log-refile
11421 (org-add-log-setup 'refile nil nil 'findpos
11422 org-log-refile)
11423 (unless (eq org-log-refile 'note)
11424 (save-excursion (org-add-log-note))))
11425 (and org-auto-align-tags
11426 (let ((org-loop-over-headlines-in-active-region nil))
11427 (org-set-tags nil t)))
11428 (with-demoted-errors
11429 (bookmark-set "org-refile-last-stored"))
11430 ;; If we are refiling for capture, make sure that the
11431 ;; last-capture pointers point here
11432 (when (org-bound-and-true-p org-refile-for-capture)
11433 (with-demoted-errors
11434 (bookmark-set "org-capture-last-stored-marker"))
11435 (move-marker org-capture-last-stored-marker (point)))
11436 (if (fboundp 'deactivate-mark) (deactivate-mark))
11437 (run-hooks 'org-after-refile-insert-hook))))
11438 (unless org-refile-keep
11439 (if regionp
11440 (delete-region (point) (+ (point) region-length))
11441 (org-cut-subtree)))
11442 (when (featurep 'org-inlinetask)
11443 (org-inlinetask-remove-END-maybe))
11444 (setq org-markers-to-move nil)
11445 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11447 (defun org-refile-goto-last-stored ()
11448 "Go to the location where the last refile was stored."
11449 (interactive)
11450 (bookmark-jump "org-refile-last-stored")
11451 (message "This is the location of the last refile"))
11453 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11454 no-exclude)
11455 "Prompt the user for a refile location, using PROMPT.
11456 PROMPT should not be suffixed with a colon and a space, because
11457 this function appends the default value from
11458 `org-refile-history' automatically, if that is not empty.
11459 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11460 this is used for the GOTO interface."
11461 (let ((org-refile-targets org-refile-targets)
11462 (org-refile-use-outline-path org-refile-use-outline-path)
11463 excluded-entries)
11464 (when (and (derived-mode-p 'org-mode)
11465 (not org-refile-use-cache)
11466 (not no-exclude))
11467 (org-map-tree
11468 (lambda()
11469 (setq excluded-entries
11470 (append excluded-entries (list (org-get-heading t t)))))))
11471 (setq org-refile-target-table
11472 (org-refile-get-targets default-buffer excluded-entries)))
11473 (unless org-refile-target-table
11474 (error "No refile targets"))
11475 (let* ((cbuf (current-buffer))
11476 (partial-completion-mode nil)
11477 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11478 (cfunc (if (and org-refile-use-outline-path
11479 org-outline-path-complete-in-steps)
11480 'org-olpath-completing-read
11481 'org-icompleting-read))
11482 (extra (if org-refile-use-outline-path "/" ""))
11483 (cbnex (concat (buffer-name) extra))
11484 (filename (and cfn (expand-file-name cfn)))
11485 (tbl (mapcar
11486 (lambda (x)
11487 (if (and (not (member org-refile-use-outline-path
11488 '(file full-file-path)))
11489 (not (equal filename (nth 1 x))))
11490 (cons (concat (car x) extra " ("
11491 (file-name-nondirectory (nth 1 x)) ")")
11492 (cdr x))
11493 (cons (concat (car x) extra) (cdr x))))
11494 org-refile-target-table))
11495 (completion-ignore-case t)
11496 cdef
11497 (prompt (concat prompt
11498 (or (and (car org-refile-history)
11499 (concat " (default " (car org-refile-history) ")"))
11500 (and (assoc cbnex tbl) (setq cdef cbnex)
11501 (concat " (default " cbnex ")"))) ": "))
11502 pa answ parent-target child parent old-hist)
11503 (setq old-hist org-refile-history)
11504 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11505 nil 'org-refile-history (or cdef (car org-refile-history))))
11506 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11507 (org-refile-check-position pa)
11508 (if pa
11509 (progn
11510 (when (or (not org-refile-history)
11511 (not (eq old-hist org-refile-history))
11512 (not (equal (car pa) (car org-refile-history))))
11513 (setq org-refile-history
11514 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11515 org-refile-history
11516 (cdr org-refile-history))))
11517 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11518 (pop org-refile-history)))
11520 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11521 (progn
11522 (setq parent (match-string 1 answ)
11523 child (match-string 2 answ))
11524 (setq parent-target (or (assoc parent tbl)
11525 (assoc (concat parent "/") tbl)))
11526 (when (and parent-target
11527 (or (eq new-nodes t)
11528 (and (eq new-nodes 'confirm)
11529 (y-or-n-p (format "Create new node \"%s\"? "
11530 child)))))
11531 (org-refile-new-child parent-target child)))
11532 (error "Invalid target location")))))
11534 (declare-function org-string-nw-p "org-macs" (s))
11535 (defun org-refile-check-position (refile-pointer)
11536 "Check if the refile pointer matches the headline to which it points."
11537 (let* ((file (nth 1 refile-pointer))
11538 (re (nth 2 refile-pointer))
11539 (pos (nth 3 refile-pointer))
11540 buffer)
11541 (if (and (not (markerp pos)) (not file))
11542 (error "Please save the buffer to a file before refiling")
11543 (when (org-string-nw-p re)
11544 (setq buffer (if (markerp pos)
11545 (marker-buffer pos)
11546 (or (find-buffer-visiting file)
11547 (find-file-noselect file))))
11548 (with-current-buffer buffer
11549 (save-excursion
11550 (save-restriction
11551 (widen)
11552 (goto-char pos)
11553 (beginning-of-line 1)
11554 (unless (org-looking-at-p re)
11555 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11557 (defun org-refile-new-child (parent-target child)
11558 "Use refile target PARENT-TARGET to add new CHILD below it."
11559 (unless parent-target
11560 (error "Cannot find parent for new node"))
11561 (let ((file (nth 1 parent-target))
11562 (pos (nth 3 parent-target))
11563 level)
11564 (with-current-buffer (or (find-buffer-visiting file)
11565 (find-file-noselect file))
11566 (save-excursion
11567 (save-restriction
11568 (widen)
11569 (if pos
11570 (goto-char pos)
11571 (goto-char (point-max))
11572 (if (not (bolp)) (newline)))
11573 (when (looking-at org-outline-regexp)
11574 (setq level (funcall outline-level))
11575 (org-end-of-subtree t t))
11576 (org-back-over-empty-lines)
11577 (insert "\n" (make-string
11578 (if pos (org-get-valid-level level 1) 1) ?*)
11579 " " child "\n")
11580 (beginning-of-line 0)
11581 (list (concat (car parent-target) "/" child) file "" (point)))))))
11583 (defun org-olpath-completing-read (prompt collection &rest args)
11584 "Read an outline path like a file name."
11585 (let ((thetable collection)
11586 (org-completion-use-ido nil) ; does not work with ido.
11587 (org-completion-use-iswitchb nil)) ; or iswitchb
11588 (apply
11589 'org-icompleting-read prompt
11590 (lambda (string predicate &optional flag)
11591 (let (rtn r f (l (length string)))
11592 (cond
11593 ((eq flag nil)
11594 ;; try completion
11595 (try-completion string thetable))
11596 ((eq flag t)
11597 ;; all-completions
11598 (setq rtn (all-completions string thetable predicate))
11599 (mapcar
11600 (lambda (x)
11601 (setq r (substring x l))
11602 (if (string-match " ([^)]*)$" x)
11603 (setq f (match-string 0 x))
11604 (setq f ""))
11605 (if (string-match "/" r)
11606 (concat string (substring r 0 (match-end 0)) f)
11608 rtn))
11609 ((eq flag 'lambda)
11610 ;; exact match?
11611 (assoc string thetable)))))
11612 args)))
11614 ;;;; Dynamic blocks
11616 (defun org-find-dblock (name)
11617 "Find the first dynamic block with name NAME in the buffer.
11618 If not found, stay at current position and return nil."
11619 (let ((case-fold-search t) pos)
11620 (save-excursion
11621 (goto-char (point-min))
11622 (setq pos (and (re-search-forward
11623 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11624 (match-beginning 0))))
11625 (if pos (goto-char pos))
11626 pos))
11628 (defconst org-dblock-start-re
11629 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11630 "Matches the start line of a dynamic block, with parameters.")
11632 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11633 "Matches the end of a dynamic block.")
11635 (defun org-create-dblock (plist)
11636 "Create a dynamic block section, with parameters taken from PLIST.
11637 PLIST must contain a :name entry which is used as name of the block."
11638 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11639 (end-of-line 1)
11640 (newline))
11641 (let ((col (current-column))
11642 (name (plist-get plist :name)))
11643 (insert "#+BEGIN: " name)
11644 (while plist
11645 (if (eq (car plist) :name)
11646 (setq plist (cddr plist))
11647 (insert " " (prin1-to-string (pop plist)))))
11648 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11649 (beginning-of-line -2)))
11651 (defun org-prepare-dblock ()
11652 "Prepare dynamic block for refresh.
11653 This empties the block, puts the cursor at the insert position and returns
11654 the property list including an extra property :name with the block name."
11655 (unless (looking-at org-dblock-start-re)
11656 (error "Not at a dynamic block"))
11657 (let* ((begdel (1+ (match-end 0)))
11658 (name (org-no-properties (match-string 1)))
11659 (params (append (list :name name)
11660 (read (concat "(" (match-string 3) ")")))))
11661 (save-excursion
11662 (beginning-of-line 1)
11663 (skip-chars-forward " \t")
11664 (setq params (plist-put params :indentation-column (current-column))))
11665 (unless (re-search-forward org-dblock-end-re nil t)
11666 (error "Dynamic block not terminated"))
11667 (setq params
11668 (append params
11669 (list :content (buffer-substring
11670 begdel (match-beginning 0)))))
11671 (delete-region begdel (match-beginning 0))
11672 (goto-char begdel)
11673 (open-line 1)
11674 params))
11676 (defun org-map-dblocks (&optional command)
11677 "Apply COMMAND to all dynamic blocks in the current buffer.
11678 If COMMAND is not given, use `org-update-dblock'."
11679 (let ((cmd (or command 'org-update-dblock)))
11680 (save-excursion
11681 (goto-char (point-min))
11682 (while (re-search-forward org-dblock-start-re nil t)
11683 (goto-char (match-beginning 0))
11684 (save-excursion
11685 (condition-case nil
11686 (funcall cmd)
11687 (error (message "Error during update of dynamic block"))))
11688 (unless (re-search-forward org-dblock-end-re nil t)
11689 (error "Dynamic block not terminated"))))))
11691 (defun org-dblock-update (&optional arg)
11692 "User command for updating dynamic blocks.
11693 Update the dynamic block at point. With prefix ARG, update all dynamic
11694 blocks in the buffer."
11695 (interactive "P")
11696 (if arg
11697 (org-update-all-dblocks)
11698 (or (looking-at org-dblock-start-re)
11699 (org-beginning-of-dblock))
11700 (org-update-dblock)))
11702 (defun org-update-dblock ()
11703 "Update the dynamic block at point.
11704 This means to empty the block, parse for parameters and then call
11705 the correct writing function."
11706 (interactive)
11707 (save-window-excursion
11708 (let* ((pos (point))
11709 (line (org-current-line))
11710 (params (org-prepare-dblock))
11711 (name (plist-get params :name))
11712 (indent (plist-get params :indentation-column))
11713 (cmd (intern (concat "org-dblock-write:" name))))
11714 (message "Updating dynamic block `%s' at line %d..." name line)
11715 (funcall cmd params)
11716 (message "Updating dynamic block `%s' at line %d...done" name line)
11717 (goto-char pos)
11718 (when (and indent (> indent 0))
11719 (setq indent (make-string indent ?\ ))
11720 (save-excursion
11721 (org-beginning-of-dblock)
11722 (forward-line 1)
11723 (while (not (looking-at org-dblock-end-re))
11724 (insert indent)
11725 (beginning-of-line 2))
11726 (when (looking-at org-dblock-end-re)
11727 (and (looking-at "[ \t]+")
11728 (replace-match ""))
11729 (insert indent)))))))
11731 (defun org-beginning-of-dblock ()
11732 "Find the beginning of the dynamic block at point.
11733 Error if there is no such block at point."
11734 (let ((pos (point))
11735 beg)
11736 (end-of-line 1)
11737 (if (and (re-search-backward org-dblock-start-re nil t)
11738 (setq beg (match-beginning 0))
11739 (re-search-forward org-dblock-end-re nil t)
11740 (> (match-end 0) pos))
11741 (goto-char beg)
11742 (goto-char pos)
11743 (error "Not in a dynamic block"))))
11745 (defun org-update-all-dblocks ()
11746 "Update all dynamic blocks in the buffer.
11747 This function can be used in a hook."
11748 (interactive)
11749 (when (derived-mode-p 'org-mode)
11750 (org-map-dblocks 'org-update-dblock)))
11753 ;;;; Completion
11755 (defun org-get-export-keywords ()
11756 "Return a list of all currently understood export keywords.
11757 Export keywords include options, block names, attributes and
11758 keywords relative to each registered export back-end."
11759 (delq nil
11760 (let (keywords)
11761 (mapc
11762 (lambda (back-end)
11763 (let ((props (cdr back-end)))
11764 ;; Back-end name (for keywords, like #+LATEX:)
11765 (push (upcase (symbol-name (car back-end))) keywords)
11766 ;; Back-end options.
11767 (mapc (lambda (option) (push (cadr option) keywords))
11768 (plist-get (cdr back-end) :options-alist))))
11769 (org-bound-and-true-p org-export-registered-backends))
11770 keywords)))
11772 (defconst org-options-keywords
11773 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11774 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11775 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11776 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11777 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:" "INFOJS_OPT:"))
11779 (defcustom org-structure-template-alist
11780 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11781 "<src lang=\"?\">\n\n</src>")
11782 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11783 "<example>\n?\n</example>")
11784 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11785 "<quote>\n?\n</quote>")
11786 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11787 "<verse>\n?\n</verse>")
11788 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11789 "<verbatim>\n?\n</verbatim>")
11790 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11791 "<center>\n?\n</center>")
11792 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11793 "<literal style=\"latex\">\n?\n</literal>")
11794 ("L" "#+LaTeX: "
11795 "<literal style=\"latex\">?</literal>")
11796 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11797 "<literal style=\"html\">\n?\n</literal>")
11798 ("H" "#+HTML: "
11799 "<literal style=\"html\">?</literal>")
11800 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11801 ("A" "#+ASCII: ")
11802 ("i" "#+INDEX: ?"
11803 "#+INDEX: ?")
11804 ("I" "#+INCLUDE: %file ?"
11805 "<include file=%file markup=\"?\">"))
11806 "Structure completion elements.
11807 This is a list of abbreviation keys and values. The value gets inserted
11808 if you type `<' followed by the key and then press the completion key,
11809 usually `M-TAB'. %file will be replaced by a file name after prompting
11810 for the file using completion. The cursor will be placed at the position
11811 of the `?` in the template.
11812 There are two templates for each key, the first uses the original Org syntax,
11813 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11814 the default when the /org-mtags.el/ module has been loaded. See also the
11815 variable `org-mtags-prefer-muse-templates'."
11816 :group 'org-completion
11817 :type '(repeat
11818 (string :tag "Key")
11819 (string :tag "Template")
11820 (string :tag "Muse Template")))
11822 (defun org-try-structure-completion ()
11823 "Try to complete a structure template before point.
11824 This looks for strings like \"<e\" on an otherwise empty line and
11825 expands them."
11826 (let ((l (buffer-substring (point-at-bol) (point)))
11828 (when (and (looking-at "[ \t]*$")
11829 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11830 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11831 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11832 (match-beginning 1)) a)
11833 t)))
11835 (defun org-complete-expand-structure-template (start cell)
11836 "Expand a structure template."
11837 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11838 (rpl (nth (if musep 2 1) cell))
11839 (ind ""))
11840 (delete-region start (point))
11841 (when (string-match "\\`#\\+" rpl)
11842 (cond
11843 ((bolp))
11844 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11845 (setq ind (buffer-substring (point-at-bol) (point))))
11846 (t (newline))))
11847 (setq start (point))
11848 (if (string-match "%file" rpl)
11849 (setq rpl (replace-match
11850 (concat
11851 "\""
11852 (save-match-data
11853 (abbreviate-file-name (read-file-name "Include file: ")))
11854 "\"")
11855 t t rpl)))
11856 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11857 (concat "\n" ind)))
11858 (insert rpl)
11859 (if (re-search-backward "\\?" start t) (delete-char 1))))
11861 ;;;; TODO, DEADLINE, Comments
11863 (defun org-toggle-comment ()
11864 "Change the COMMENT state of an entry."
11865 (interactive)
11866 (save-excursion
11867 (org-back-to-heading)
11868 (let (case-fold-search)
11869 (cond
11870 ((looking-at (format org-heading-keyword-regexp-format
11871 org-comment-string))
11872 (goto-char (match-end 1))
11873 (looking-at (concat " +" org-comment-string))
11874 (replace-match "" t t)
11875 (when (eolp) (insert " ")))
11876 ((looking-at org-outline-regexp)
11877 (goto-char (match-end 0))
11878 (insert org-comment-string " "))))))
11880 (defvar org-last-todo-state-is-todo nil
11881 "This is non-nil when the last TODO state change led to a TODO state.
11882 If the last change removed the TODO tag or switched to DONE, then
11883 this is nil.")
11885 (defvar org-setting-tags nil) ; dynamically skipped
11887 (defvar org-todo-setup-filter-hook nil
11888 "Hook for functions that pre-filter todo specs.
11889 Each function takes a todo spec and returns either nil or the spec
11890 transformed into canonical form." )
11892 (defvar org-todo-get-default-hook nil
11893 "Hook for functions that get a default item for todo.
11894 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11895 nil or a string to be used for the todo mark." )
11897 (defvar org-agenda-headline-snapshot-before-repeat)
11899 (defun org-current-effective-time ()
11900 "Return current time adjusted for `org-extend-today-until' variable."
11901 (let* ((ct (org-current-time))
11902 (dct (decode-time ct))
11903 (ct1
11904 (cond
11905 (org-use-last-clock-out-time-as-effective-time
11906 (or (org-clock-get-last-clock-out-time) ct))
11907 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11908 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11909 (t ct))))
11910 ct1))
11912 (defun org-todo-yesterday (&optional arg)
11913 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11914 (interactive "P")
11915 (if (eq major-mode 'org-agenda-mode)
11916 (apply 'org-agenda-todo-yesterday arg)
11917 (let* ((hour (third (decode-time
11918 (org-current-time))))
11919 (org-extend-today-until (1+ hour)))
11920 (org-todo arg))))
11922 (defvar org-block-entry-blocking ""
11923 "First entry preventing the TODO state change.")
11925 (defun org-todo (&optional arg)
11926 "Change the TODO state of an item.
11927 The state of an item is given by a keyword at the start of the heading,
11928 like
11929 *** TODO Write paper
11930 *** DONE Call mom
11932 The different keywords are specified in the variable `org-todo-keywords'.
11933 By default the available states are \"TODO\" and \"DONE\".
11934 So for this example: when the item starts with TODO, it is changed to DONE.
11935 When it starts with DONE, the DONE is removed. And when neither TODO nor
11936 DONE are present, add TODO at the beginning of the heading.
11938 With \\[universal-argument] prefix arg, use completion to determine the new \
11939 state.
11940 With numeric prefix arg, switch to that state.
11941 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11942 keywords (nextset).
11943 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11944 With a numeric prefix arg of 0, inhibit note taking for the change.
11946 For calling through lisp, arg is also interpreted in the following way:
11947 'none -> empty state
11948 \"\"(empty string) -> switch to empty state
11949 'done -> switch to DONE
11950 'nextset -> switch to the next set of keywords
11951 'previousset -> switch to the previous set of keywords
11952 \"WAITING\" -> switch to the specified keyword, but only if it
11953 really is a member of `org-todo-keywords'."
11954 (interactive "P")
11955 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11956 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11957 'region-start-level 'region))
11958 org-loop-over-headlines-in-active-region)
11959 (org-map-entries
11960 `(org-todo ,arg)
11961 org-loop-over-headlines-in-active-region
11962 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11963 (if (equal arg '(16)) (setq arg 'nextset))
11964 (let ((org-blocker-hook org-blocker-hook)
11965 commentp
11966 case-fold-search)
11967 (when (equal arg '(64))
11968 (setq arg nil org-blocker-hook nil))
11969 (when (and org-blocker-hook
11970 (or org-inhibit-blocking
11971 (org-entry-get nil "NOBLOCKING")))
11972 (setq org-blocker-hook nil))
11973 (save-excursion
11974 (catch 'exit
11975 (org-back-to-heading t)
11976 (when (looking-at (concat "^\\*+ " org-comment-string))
11977 (org-toggle-comment)
11978 (setq commentp t))
11979 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11980 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11981 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11982 (let* ((match-data (match-data))
11983 (startpos (point-at-bol))
11984 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11985 (org-log-done org-log-done)
11986 (org-log-repeat org-log-repeat)
11987 (org-todo-log-states org-todo-log-states)
11988 (org-inhibit-logging
11989 (if (equal arg 0)
11990 (progn (setq arg nil) 'note) org-inhibit-logging))
11991 (this (match-string 1))
11992 (hl-pos (match-beginning 0))
11993 (head (org-get-todo-sequence-head this))
11994 (ass (assoc head org-todo-kwd-alist))
11995 (interpret (nth 1 ass))
11996 (done-word (nth 3 ass))
11997 (final-done-word (nth 4 ass))
11998 (org-last-state (or this ""))
11999 (completion-ignore-case t)
12000 (member (member this org-todo-keywords-1))
12001 (tail (cdr member))
12002 (org-state (cond
12003 ((and org-todo-key-trigger
12004 (or (and (equal arg '(4))
12005 (eq org-use-fast-todo-selection 'prefix))
12006 (and (not arg) org-use-fast-todo-selection
12007 (not (eq org-use-fast-todo-selection
12008 'prefix)))))
12009 ;; Use fast selection
12010 (org-fast-todo-selection))
12011 ((and (equal arg '(4))
12012 (or (not org-use-fast-todo-selection)
12013 (not org-todo-key-trigger)))
12014 ;; Read a state with completion
12015 (org-icompleting-read
12016 "State: " (mapcar (lambda(x) (list x))
12017 org-todo-keywords-1)
12018 nil t))
12019 ((eq arg 'right)
12020 (if this
12021 (if tail (car tail) nil)
12022 (car org-todo-keywords-1)))
12023 ((eq arg 'left)
12024 (if (equal member org-todo-keywords-1)
12026 (if this
12027 (nth (- (length org-todo-keywords-1)
12028 (length tail) 2)
12029 org-todo-keywords-1)
12030 (org-last org-todo-keywords-1))))
12031 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12032 (setq arg nil))) ; hack to fall back to cycling
12033 (arg
12034 ;; user or caller requests a specific state
12035 (cond
12036 ((equal arg "") nil)
12037 ((eq arg 'none) nil)
12038 ((eq arg 'done) (or done-word (car org-done-keywords)))
12039 ((eq arg 'nextset)
12040 (or (car (cdr (member head org-todo-heads)))
12041 (car org-todo-heads)))
12042 ((eq arg 'previousset)
12043 (let ((org-todo-heads (reverse org-todo-heads)))
12044 (or (car (cdr (member head org-todo-heads)))
12045 (car org-todo-heads))))
12046 ((car (member arg org-todo-keywords-1)))
12047 ((stringp arg)
12048 (error "State `%s' not valid in this file" arg))
12049 ((nth (1- (prefix-numeric-value arg))
12050 org-todo-keywords-1))))
12051 ((null member) (or head (car org-todo-keywords-1)))
12052 ((equal this final-done-word) nil) ;; -> make empty
12053 ((null tail) nil) ;; -> first entry
12054 ((memq interpret '(type priority))
12055 (if (eq this-command last-command)
12056 (car tail)
12057 (if (> (length tail) 0)
12058 (or done-word (car org-done-keywords))
12059 nil)))
12061 (car tail))))
12062 (org-state (or
12063 (run-hook-with-args-until-success
12064 'org-todo-get-default-hook org-state org-last-state)
12065 org-state))
12066 (next (if org-state (concat " " org-state " ") " "))
12067 (change-plist (list :type 'todo-state-change :from this :to org-state
12068 :position startpos))
12069 dolog now-done-p)
12070 (when org-blocker-hook
12071 (setq org-last-todo-state-is-todo
12072 (not (member this org-done-keywords)))
12073 (unless (save-excursion
12074 (save-match-data
12075 (org-with-wide-buffer
12076 (run-hook-with-args-until-failure
12077 'org-blocker-hook change-plist))))
12078 (if (org-called-interactively-p 'interactive)
12079 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12080 this org-state org-block-entry-blocking)
12081 ;; fail silently
12082 (message "TODO state change from %s to %s blocked (by \"%s\")"
12083 this org-state org-block-entry-blocking)
12084 (throw 'exit nil))))
12085 (store-match-data match-data)
12086 (replace-match next t t)
12087 (unless (pos-visible-in-window-p hl-pos)
12088 (message "TODO state changed to %s" (org-trim next)))
12089 (unless head
12090 (setq head (org-get-todo-sequence-head org-state)
12091 ass (assoc head org-todo-kwd-alist)
12092 interpret (nth 1 ass)
12093 done-word (nth 3 ass)
12094 final-done-word (nth 4 ass)))
12095 (when (memq arg '(nextset previousset))
12096 (message "Keyword-Set %d/%d: %s"
12097 (- (length org-todo-sets) -1
12098 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12099 (length org-todo-sets)
12100 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12101 (setq org-last-todo-state-is-todo
12102 (not (member org-state org-done-keywords)))
12103 (setq now-done-p (and (member org-state org-done-keywords)
12104 (not (member this org-done-keywords))))
12105 (and logging (org-local-logging logging))
12106 (when (and (or org-todo-log-states org-log-done)
12107 (not (eq org-inhibit-logging t))
12108 (not (memq arg '(nextset previousset))))
12109 ;; we need to look at recording a time and note
12110 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12111 (nth 2 (assoc this org-todo-log-states))))
12112 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12113 (setq dolog 'time))
12114 (when (and org-state
12115 (member org-state org-not-done-keywords)
12116 (not (member this org-not-done-keywords)))
12117 ;; This is now a todo state and was not one before
12118 ;; If there was a CLOSED time stamp, get rid of it.
12119 (org-add-planning-info nil nil 'closed))
12120 (when (and now-done-p org-log-done)
12121 ;; It is now done, and it was not done before
12122 (org-add-planning-info 'closed (org-current-effective-time))
12123 (if (and (not dolog) (eq 'note org-log-done))
12124 (org-add-log-setup 'done org-state this 'findpos 'note)))
12125 (when (and org-state dolog)
12126 ;; This is a non-nil state, and we need to log it
12127 (org-add-log-setup 'state org-state this 'findpos dolog)))
12128 ;; Fixup tag positioning
12129 (org-todo-trigger-tag-changes org-state)
12130 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12131 (when org-provide-todo-statistics
12132 (org-update-parent-todo-statistics))
12133 (run-hooks 'org-after-todo-state-change-hook)
12134 (if (and arg (not (member org-state org-done-keywords)))
12135 (setq head (org-get-todo-sequence-head org-state)))
12136 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12137 ;; Do we need to trigger a repeat?
12138 (when now-done-p
12139 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12140 ;; This is for the agenda, take a snapshot of the headline.
12141 (save-match-data
12142 (setq org-agenda-headline-snapshot-before-repeat
12143 (org-get-heading))))
12144 (org-auto-repeat-maybe org-state))
12145 ;; Fixup cursor location if close to the keyword
12146 (if (and (outline-on-heading-p)
12147 (not (bolp))
12148 (save-excursion (beginning-of-line 1)
12149 (looking-at org-todo-line-regexp))
12150 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12151 (progn
12152 (goto-char (or (match-end 2) (match-end 1)))
12153 (and (looking-at " ") (just-one-space))))
12154 (when org-trigger-hook
12155 (save-excursion
12156 (run-hook-with-args 'org-trigger-hook change-plist)))
12157 (when commentp (org-toggle-comment))))))))
12159 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12160 "Block turning an entry into a TODO, using the hierarchy.
12161 This checks whether the current task should be blocked from state
12162 changes. Such blocking occurs when:
12164 1. The task has children which are not all in a completed state.
12166 2. A task has a parent with the property :ORDERED:, and there
12167 are siblings prior to the current task with incomplete
12168 status.
12170 3. The parent of the task is blocked because it has siblings that should
12171 be done first, or is child of a block grandparent TODO entry."
12173 (if (not org-enforce-todo-dependencies)
12174 t ; if locally turned off don't block
12175 (catch 'dont-block
12176 ;; If this is not a todo state change, or if this entry is already DONE,
12177 ;; do not block
12178 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12179 (member (plist-get change-plist :from)
12180 (cons 'done org-done-keywords))
12181 (member (plist-get change-plist :to)
12182 (cons 'todo org-not-done-keywords))
12183 (not (plist-get change-plist :to)))
12184 (throw 'dont-block t))
12185 ;; If this task has children, and any are undone, it's blocked
12186 (save-excursion
12187 (org-back-to-heading t)
12188 (let ((this-level (funcall outline-level)))
12189 (outline-next-heading)
12190 (let ((child-level (funcall outline-level)))
12191 (while (and (not (eobp))
12192 (> child-level this-level))
12193 ;; this todo has children, check whether they are all
12194 ;; completed
12195 (if (and (not (org-entry-is-done-p))
12196 (org-entry-is-todo-p))
12197 (progn (setq org-block-entry-blocking (org-get-heading))
12198 (throw 'dont-block nil)))
12199 (outline-next-heading)
12200 (setq child-level (funcall outline-level))))))
12201 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12202 ;; any previous siblings are undone, it's blocked
12203 (save-excursion
12204 (org-back-to-heading t)
12205 (let* ((pos (point))
12206 (parent-pos (and (org-up-heading-safe) (point))))
12207 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12208 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12209 (forward-line 1)
12210 (re-search-forward org-not-done-heading-regexp pos t))
12211 (setq org-block-entry-blocking (match-string 0))
12212 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12213 ;; Search further up the hierarchy, to see if an ancestor is blocked
12214 (while t
12215 (goto-char parent-pos)
12216 (if (not (looking-at org-not-done-heading-regexp))
12217 (throw 'dont-block t)) ; do not block, parent is not a TODO
12218 (setq pos (point))
12219 (setq parent-pos (and (org-up-heading-safe) (point)))
12220 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12221 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12222 (forward-line 1)
12223 (re-search-forward org-not-done-heading-regexp pos t)
12224 (setq org-block-entry-blocking (org-get-heading)))
12225 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12227 (defcustom org-track-ordered-property-with-tag nil
12228 "Should the ORDERED property also be shown as a tag?
12229 The ORDERED property decides if an entry should require subtasks to be
12230 completed in sequence. Since a property is not very visible, setting
12231 this option means that toggling the ORDERED property with the command
12232 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12233 not relevant for the behavior, but it makes things more visible.
12235 Note that toggling the tag with tags commands will not change the property
12236 and therefore not influence behavior!
12238 This can be t, meaning the tag ORDERED should be used, It can also be a
12239 string to select a different tag for this task."
12240 :group 'org-todo
12241 :type '(choice
12242 (const :tag "No tracking" nil)
12243 (const :tag "Track with ORDERED tag" t)
12244 (string :tag "Use other tag")))
12246 (defun org-toggle-ordered-property ()
12247 "Toggle the ORDERED property of the current entry.
12248 For better visibility, you can track the value of this property with a tag.
12249 See variable `org-track-ordered-property-with-tag'."
12250 (interactive)
12251 (let* ((t1 org-track-ordered-property-with-tag)
12252 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12253 (save-excursion
12254 (org-back-to-heading)
12255 (if (org-entry-get nil "ORDERED")
12256 (progn
12257 (org-delete-property "ORDERED" "PROPERTIES")
12258 (and tag (org-toggle-tag tag 'off))
12259 (message "Subtasks can be completed in arbitrary order"))
12260 (org-entry-put nil "ORDERED" "t")
12261 (and tag (org-toggle-tag tag 'on))
12262 (message "Subtasks must be completed in sequence")))))
12264 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12265 (defun org-block-todo-from-checkboxes (change-plist)
12266 "Block turning an entry into a TODO, using checkboxes.
12267 This checks whether the current task should be blocked from state
12268 changes because there are unchecked boxes in this entry."
12269 (if (not org-enforce-todo-checkbox-dependencies)
12270 t ; if locally turned off don't block
12271 (catch 'dont-block
12272 ;; If this is not a todo state change, or if this entry is already DONE,
12273 ;; do not block
12274 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12275 (member (plist-get change-plist :from)
12276 (cons 'done org-done-keywords))
12277 (member (plist-get change-plist :to)
12278 (cons 'todo org-not-done-keywords))
12279 (not (plist-get change-plist :to)))
12280 (throw 'dont-block t))
12281 ;; If this task has checkboxes that are not checked, it's blocked
12282 (save-excursion
12283 (org-back-to-heading t)
12284 (let ((beg (point)) end)
12285 (outline-next-heading)
12286 (setq end (point))
12287 (goto-char beg)
12288 (if (org-list-search-forward
12289 (concat (org-item-beginning-re)
12290 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12291 "\\[[- ]\\]")
12292 end t)
12293 (progn
12294 (if (boundp 'org-blocked-by-checkboxes)
12295 (setq org-blocked-by-checkboxes t))
12296 (throw 'dont-block nil)))))
12297 t))) ; do not block
12299 (defun org-entry-blocked-p ()
12300 "Is the current entry blocked?"
12301 (org-with-silent-modifications
12302 (if (org-entry-get nil "NOBLOCKING")
12303 nil ;; Never block this entry
12304 (not (run-hook-with-args-until-failure
12305 'org-blocker-hook
12306 (list :type 'todo-state-change
12307 :position (point)
12308 :from 'todo
12309 :to 'done))))))
12311 (defun org-update-statistics-cookies (all)
12312 "Update the statistics cookie, either from TODO or from checkboxes.
12313 This should be called with the cursor in a line with a statistics cookie."
12314 (interactive "P")
12315 (if all
12316 (progn
12317 (org-update-checkbox-count 'all)
12318 (org-map-entries 'org-update-parent-todo-statistics))
12319 (if (not (org-at-heading-p))
12320 (org-update-checkbox-count)
12321 (let ((pos (point-marker))
12322 end l1 l2)
12323 (ignore-errors (org-back-to-heading t))
12324 (if (not (org-at-heading-p))
12325 (org-update-checkbox-count)
12326 (setq l1 (org-outline-level))
12327 (setq end (save-excursion
12328 (outline-next-heading)
12329 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12330 (point)))
12331 (if (and (save-excursion
12332 (re-search-forward
12333 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12334 (not (save-excursion (re-search-forward
12335 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12336 (org-update-checkbox-count)
12337 (if (and l2 (> l2 l1))
12338 (progn
12339 (goto-char end)
12340 (org-update-parent-todo-statistics))
12341 (goto-char pos)
12342 (beginning-of-line 1)
12343 (while (re-search-forward
12344 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12345 (point-at-eol) t)
12346 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12347 (goto-char pos)
12348 (move-marker pos nil)))))
12350 (defvar org-entry-property-inherited-from) ;; defined below
12351 (defun org-update-parent-todo-statistics ()
12352 "Update any statistics cookie in the parent of the current headline.
12353 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12354 the entire subtree and this will travel up the hierarchy and update
12355 statistics everywhere."
12356 (let* ((prop (save-excursion (org-up-heading-safe)
12357 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12358 (recursive (or (not org-hierarchical-todo-statistics)
12359 (and prop (string-match "\\<recursive\\>" prop))))
12360 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12362 (first t)
12363 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12364 level ltoggle l1 new ndel
12365 (cnt-all 0) (cnt-done 0) is-percent kwd
12366 checkbox-beg ov ovs ove cookie-present)
12367 (catch 'exit
12368 (save-excursion
12369 (beginning-of-line 1)
12370 (setq ltoggle (funcall outline-level))
12371 ;; Three situations are to consider:
12373 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12374 ;; to the top-level ancestor on the headline;
12376 ;; 2. If parent has "recursive" property, repeat up to the
12377 ;; headline setting that property, taking inheritance into
12378 ;; account;
12380 ;; 3. Else, move up to direct parent and proceed only once.
12381 (while (and (setq level (org-up-heading-safe))
12382 (or recursive first)
12383 (>= (point) lim))
12384 (setq first nil cookie-present nil)
12385 (unless (and level
12386 (not (string-match
12387 "\\<checkbox\\>"
12388 (downcase (or (org-entry-get nil "COOKIE_DATA")
12389 "")))))
12390 (throw 'exit nil))
12391 (while (re-search-forward box-re (point-at-eol) t)
12392 (setq cnt-all 0 cnt-done 0 cookie-present t)
12393 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12394 (save-match-data
12395 (unless (outline-next-heading) (throw 'exit nil))
12396 (while (and (looking-at org-complex-heading-regexp)
12397 (> (setq l1 (length (match-string 1))) level))
12398 (setq kwd (and (or recursive (= l1 ltoggle))
12399 (match-string 2)))
12400 (if (or (eq org-provide-todo-statistics 'all-headlines)
12401 (and (listp org-provide-todo-statistics)
12402 (or (member kwd org-provide-todo-statistics)
12403 (member kwd org-done-keywords))))
12404 (setq cnt-all (1+ cnt-all))
12405 (if (eq org-provide-todo-statistics t)
12406 (and kwd (setq cnt-all (1+ cnt-all)))))
12407 (and (member kwd org-done-keywords)
12408 (setq cnt-done (1+ cnt-done)))
12409 (outline-next-heading)))
12410 (setq new
12411 (if is-percent
12412 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12413 (format "[%d/%d]" cnt-done cnt-all))
12414 ndel (- (match-end 0) checkbox-beg))
12415 ;; handle overlays when updating cookie from column view
12416 (when (setq ov (car (overlays-at checkbox-beg)))
12417 (setq ovs (overlay-start ov) ove (overlay-end ov))
12418 (delete-overlay ov))
12419 (goto-char checkbox-beg)
12420 (insert new)
12421 (delete-region (point) (+ (point) ndel))
12422 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12423 (when ov (move-overlay ov ovs ove)))
12424 (when cookie-present
12425 (run-hook-with-args 'org-after-todo-statistics-hook
12426 cnt-done (- cnt-all cnt-done))))))
12427 (run-hooks 'org-todo-statistics-hook)))
12429 (defvar org-after-todo-statistics-hook nil
12430 "Hook that is called after a TODO statistics cookie has been updated.
12431 Each function is called with two arguments: the number of not-done entries
12432 and the number of done entries.
12434 For example, the following function, when added to this hook, will switch
12435 an entry to DONE when all children are done, and back to TODO when new
12436 entries are set to a TODO status. Note that this hook is only called
12437 when there is a statistics cookie in the headline!
12439 (defun org-summary-todo (n-done n-not-done)
12440 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12441 (let (org-log-done org-log-states) ; turn off logging
12442 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12445 (defvar org-todo-statistics-hook nil
12446 "Hook that is run whenever Org thinks TODO statistics should be updated.
12447 This hook runs even if there is no statistics cookie present, in which case
12448 `org-after-todo-statistics-hook' would not run.")
12450 (defun org-todo-trigger-tag-changes (state)
12451 "Apply the changes defined in `org-todo-state-tags-triggers'."
12452 (let ((l org-todo-state-tags-triggers)
12453 changes)
12454 (when (or (not state) (equal state ""))
12455 (setq changes (append changes (cdr (assoc "" l)))))
12456 (when (and (stringp state) (> (length state) 0))
12457 (setq changes (append changes (cdr (assoc state l)))))
12458 (when (member state org-not-done-keywords)
12459 (setq changes (append changes (cdr (assoc 'todo l)))))
12460 (when (member state org-done-keywords)
12461 (setq changes (append changes (cdr (assoc 'done l)))))
12462 (dolist (c changes)
12463 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12465 (defun org-local-logging (value)
12466 "Get logging settings from a property VALUE."
12467 (let* (words w a)
12468 ;; directly set the variables, they are already local.
12469 (setq org-log-done nil
12470 org-log-repeat nil
12471 org-todo-log-states nil)
12472 (setq words (org-split-string value))
12473 (while (setq w (pop words))
12474 (cond
12475 ((setq a (assoc w org-startup-options))
12476 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12477 (set (nth 1 a) (nth 2 a))))
12478 ((setq a (org-extract-log-state-settings w))
12479 (and (member (car a) org-todo-keywords-1)
12480 (push a org-todo-log-states)))))))
12482 (defun org-get-todo-sequence-head (kwd)
12483 "Return the head of the TODO sequence to which KWD belongs.
12484 If KWD is not set, check if there is a text property remembering the
12485 right sequence."
12486 (let (p)
12487 (cond
12488 ((not kwd)
12489 (or (get-text-property (point-at-bol) 'org-todo-head)
12490 (progn
12491 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12492 nil (point-at-eol)))
12493 (get-text-property p 'org-todo-head))))
12494 ((not (member kwd org-todo-keywords-1))
12495 (car org-todo-keywords-1))
12496 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12498 (defun org-fast-todo-selection ()
12499 "Fast TODO keyword selection with single keys.
12500 Returns the new TODO keyword, or nil if no state change should occur."
12501 (let* ((fulltable org-todo-key-alist)
12502 (done-keywords org-done-keywords) ;; needed for the faces.
12503 (maxlen (apply 'max (mapcar
12504 (lambda (x)
12505 (if (stringp (car x)) (string-width (car x)) 0))
12506 fulltable)))
12507 (expert nil)
12508 (fwidth (+ maxlen 3 1 3))
12509 (ncol (/ (- (window-width) 4) fwidth))
12510 tg cnt e c tbl
12511 groups ingroup)
12512 (save-excursion
12513 (save-window-excursion
12514 (if expert
12515 (set-buffer (get-buffer-create " *Org todo*"))
12516 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12517 (erase-buffer)
12518 (org-set-local 'org-done-keywords done-keywords)
12519 (setq tbl fulltable cnt 0)
12520 (while (setq e (pop tbl))
12521 (cond
12522 ((equal e '(:startgroup))
12523 (push '() groups) (setq ingroup t)
12524 (when (not (= cnt 0))
12525 (setq cnt 0)
12526 (insert "\n"))
12527 (insert "{ "))
12528 ((equal e '(:endgroup))
12529 (setq ingroup nil cnt 0)
12530 (insert "}\n"))
12531 ((equal e '(:newline))
12532 (when (not (= cnt 0))
12533 (setq cnt 0)
12534 (insert "\n")
12535 (setq e (car tbl))
12536 (while (equal (car tbl) '(:newline))
12537 (insert "\n")
12538 (setq tbl (cdr tbl)))))
12540 (setq tg (car e) c (cdr e))
12541 (if ingroup (push tg (car groups)))
12542 (setq tg (org-add-props tg nil 'face
12543 (org-get-todo-face tg)))
12544 (if (and (= cnt 0) (not ingroup)) (insert " "))
12545 (insert "[" c "] " tg (make-string
12546 (- fwidth 4 (length tg)) ?\ ))
12547 (when (= (setq cnt (1+ cnt)) ncol)
12548 (insert "\n")
12549 (if ingroup (insert " "))
12550 (setq cnt 0)))))
12551 (insert "\n")
12552 (goto-char (point-min))
12553 (if (not expert) (org-fit-window-to-buffer))
12554 (message "[a-z..]:Set [SPC]:clear")
12555 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12556 (cond
12557 ((or (= c ?\C-g)
12558 (and (= c ?q) (not (rassoc c fulltable))))
12559 (setq quit-flag t))
12560 ((= c ?\ ) nil)
12561 ((setq e (rassoc c fulltable) tg (car e))
12563 (t (setq quit-flag t)))))))
12565 (defun org-entry-is-todo-p ()
12566 (member (org-get-todo-state) org-not-done-keywords))
12568 (defun org-entry-is-done-p ()
12569 (member (org-get-todo-state) org-done-keywords))
12571 (defun org-get-todo-state ()
12572 (save-excursion
12573 (org-back-to-heading t)
12574 (and (looking-at org-todo-line-regexp)
12575 (match-end 2)
12576 (match-string 2))))
12578 (defun org-at-date-range-p (&optional inactive-ok)
12579 "Is the cursor inside a date range?"
12580 (interactive)
12581 (save-excursion
12582 (catch 'exit
12583 (let ((pos (point)))
12584 (skip-chars-backward "^[<\r\n")
12585 (skip-chars-backward "<[")
12586 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12587 (>= (match-end 0) pos)
12588 (throw 'exit t))
12589 (skip-chars-backward "^<[\r\n")
12590 (skip-chars-backward "<[")
12591 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12592 (>= (match-end 0) pos)
12593 (throw 'exit t)))
12594 nil)))
12596 (defun org-get-repeat (&optional tagline)
12597 "Check if there is a deadline/schedule with repeater in this entry."
12598 (save-match-data
12599 (save-excursion
12600 (org-back-to-heading t)
12601 (and (re-search-forward (if tagline
12602 (concat tagline "\\s-*" org-repeat-re)
12603 org-repeat-re)
12604 (org-entry-end-position) t)
12605 (match-string-no-properties 1)))))
12607 (defvar org-last-changed-timestamp)
12608 (defvar org-last-inserted-timestamp)
12609 (defvar org-log-post-message)
12610 (defvar org-log-note-purpose)
12611 (defvar org-log-note-how)
12612 (defvar org-log-note-extra)
12613 (defun org-auto-repeat-maybe (done-word)
12614 "Check if the current headline contains a repeated deadline/schedule.
12615 If yes, set TODO state back to what it was and change the base date
12616 of repeating deadline/scheduled time stamps to new date.
12617 This function is run automatically after each state change to a DONE state."
12618 ;; last-state is dynamically scoped into this function
12619 (let* ((repeat (org-get-repeat))
12620 (aa (assoc org-last-state org-todo-kwd-alist))
12621 (interpret (nth 1 aa))
12622 (head (nth 2 aa))
12623 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12624 (msg "Entry repeats: ")
12625 (org-log-done nil)
12626 (org-todo-log-states nil)
12627 re type n what ts time to-state)
12628 (when repeat
12629 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12630 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12631 org-todo-repeat-to-state))
12632 (unless (and to-state (member to-state org-todo-keywords-1))
12633 (setq to-state (if (eq interpret 'type) org-last-state head)))
12634 (org-todo to-state)
12635 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12636 (org-entry-put nil "LAST_REPEAT" (format-time-string
12637 (org-time-stamp-format t t))))
12638 (when org-log-repeat
12639 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12640 (memq 'org-add-log-note post-command-hook))
12641 ;; OK, we are already setup for some record
12642 (if (eq org-log-repeat 'note)
12643 ;; make sure we take a note, not only a time stamp
12644 (setq org-log-note-how 'note))
12645 ;; Set up for taking a record
12646 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12647 org-last-state
12648 'findpos org-log-repeat)))
12649 (org-back-to-heading t)
12650 (org-add-planning-info nil nil 'closed)
12651 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12652 org-deadline-time-regexp "\\)\\|\\("
12653 org-ts-regexp "\\)"))
12654 (while (re-search-forward
12655 re (save-excursion (outline-next-heading) (point)) t)
12656 (setq type (if (match-end 1) org-scheduled-string
12657 (if (match-end 3) org-deadline-string "Plain:"))
12658 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12659 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12660 (setq n (string-to-number (match-string 2 ts))
12661 what (match-string 3 ts))
12662 (if (equal what "w") (setq n (* n 7) what "d"))
12663 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12664 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12665 ;; Preparation, see if we need to modify the start date for the change
12666 (when (match-end 1)
12667 (setq time (save-match-data (org-time-string-to-time ts)))
12668 (cond
12669 ((equal (match-string 1 ts) ".")
12670 ;; Shift starting date to today
12671 (org-timestamp-change
12672 (- (org-today) (time-to-days time))
12673 'day))
12674 ((equal (match-string 1 ts) "+")
12675 (let ((nshiftmax 10) (nshift 0))
12676 (while (or (= nshift 0)
12677 (<= (time-to-days time)
12678 (time-to-days (current-time))))
12679 (when (= (incf nshift) nshiftmax)
12680 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12681 (error "Abort")))
12682 (org-timestamp-change n (cdr (assoc what whata)))
12683 (org-at-timestamp-p t)
12684 (setq ts (match-string 1))
12685 (setq time (save-match-data (org-time-string-to-time ts)))))
12686 (org-timestamp-change (- n) (cdr (assoc what whata)))
12687 ;; rematch, so that we have everything in place for the real shift
12688 (org-at-timestamp-p t)
12689 (setq ts (match-string 1))
12690 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12691 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12692 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12693 (setq org-log-post-message msg)
12694 (message "%s" msg))))
12696 (defun org-show-todo-tree (arg)
12697 "Make a compact tree which shows all headlines marked with TODO.
12698 The tree will show the lines where the regexp matches, and all higher
12699 headlines above the match.
12700 With a \\[universal-argument] prefix, prompt for a regexp to match.
12701 With a numeric prefix N, construct a sparse tree for the Nth element
12702 of `org-todo-keywords-1'."
12703 (interactive "P")
12704 (let ((case-fold-search nil)
12705 (kwd-re
12706 (cond ((null arg) org-not-done-regexp)
12707 ((equal arg '(4))
12708 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12709 (mapcar 'list org-todo-keywords-1))))
12710 (concat "\\("
12711 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12712 "\\)\\>")))
12713 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12714 (regexp-quote (nth (1- (prefix-numeric-value arg))
12715 org-todo-keywords-1)))
12716 (t (error "Invalid prefix argument: %s" arg)))))
12717 (message "%d TODO entries found"
12718 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12720 (defun org-deadline (arg &optional time)
12721 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12722 With one universal prefix argument, remove any deadline from the item.
12723 With two universal prefix arguments, prompt for a warning delay.
12724 With argument TIME, set the deadline at the corresponding date. TIME
12725 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12726 (interactive "P")
12727 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12728 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12729 'region-start-level 'region))
12730 org-loop-over-headlines-in-active-region)
12731 (org-map-entries
12732 `(org-deadline ',arg ,time)
12733 org-loop-over-headlines-in-active-region
12734 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12735 (let* ((old-date (org-entry-get nil "DEADLINE"))
12736 (old-date-time (if old-date (org-time-string-to-time old-date)))
12737 (repeater (and old-date
12738 (string-match
12739 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12740 old-date)
12741 (match-string 1 old-date))))
12742 (cond
12743 ((equal arg '(4))
12744 (when (and old-date org-log-redeadline)
12745 (org-add-log-setup 'deldeadline nil old-date 'findpos
12746 org-log-redeadline))
12747 (org-remove-timestamp-with-keyword org-deadline-string)
12748 (message "Item no longer has a deadline."))
12749 ((equal arg '(16))
12750 (save-excursion
12751 (if (re-search-forward
12752 org-deadline-time-regexp
12753 (save-excursion (outline-next-heading) (point)) t)
12754 (let* ((rpl0 (match-string 1))
12755 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12756 (replace-match
12757 (concat org-deadline-string
12758 " <" rpl
12759 (format " -%dd"
12760 (abs
12761 (- (time-to-days
12762 (save-match-data
12763 (org-read-date nil t nil "Warn starting from" old-date-time)))
12764 (time-to-days old-date-time))))
12765 ">") t t))
12766 (user-error "No deadline information to update"))))
12768 (org-add-planning-info 'deadline time 'closed)
12769 (when (and old-date org-log-redeadline
12770 (not (equal old-date
12771 (substring org-last-inserted-timestamp 1 -1))))
12772 (org-add-log-setup 'redeadline nil old-date 'findpos
12773 org-log-redeadline))
12774 (when repeater
12775 (save-excursion
12776 (org-back-to-heading t)
12777 (when (re-search-forward (concat org-deadline-string " "
12778 org-last-inserted-timestamp)
12779 (save-excursion
12780 (outline-next-heading) (point)) t)
12781 (goto-char (1- (match-end 0)))
12782 (insert " " repeater)
12783 (setq org-last-inserted-timestamp
12784 (concat (substring org-last-inserted-timestamp 0 -1)
12785 " " repeater
12786 (substring org-last-inserted-timestamp -1))))))
12787 (message "Deadline on %s" org-last-inserted-timestamp))))))
12789 (defun org-schedule (arg &optional time)
12790 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12791 With one universal prefix argument, remove any scheduling date from the item.
12792 With two universal prefix arguments, prompt for a delay cookie.
12793 With argument TIME, scheduled at the corresponding date. TIME can
12794 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12795 (interactive "P")
12796 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12797 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12798 'region-start-level 'region))
12799 org-loop-over-headlines-in-active-region)
12800 (org-map-entries
12801 `(org-schedule ',arg ,time)
12802 org-loop-over-headlines-in-active-region
12803 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12804 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12805 (old-date-time (if old-date (org-time-string-to-time old-date)))
12806 (repeater (and old-date
12807 (string-match
12808 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12809 old-date)
12810 (match-string 1 old-date))))
12811 (cond
12812 ((equal arg '(4))
12813 (progn
12814 (when (and old-date org-log-reschedule)
12815 (org-add-log-setup 'delschedule nil old-date 'findpos
12816 org-log-reschedule))
12817 (org-remove-timestamp-with-keyword org-scheduled-string)
12818 (message "Item is no longer scheduled.")))
12819 ((equal arg '(16))
12820 (save-excursion
12821 (if (re-search-forward
12822 org-scheduled-time-regexp
12823 (save-excursion (outline-next-heading) (point)) t)
12824 (let* ((rpl0 (match-string 1))
12825 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12826 (replace-match
12827 (concat org-scheduled-string
12828 " <" rpl
12829 (format " -%dd"
12830 (abs
12831 (- (time-to-days
12832 (save-match-data
12833 (org-read-date nil t nil "Delay until" old-date-time)))
12834 (time-to-days old-date-time))))
12835 ">") t t))
12836 (user-error "No scheduled information to update"))))
12838 (org-add-planning-info 'scheduled time 'closed)
12839 (when (and old-date org-log-reschedule
12840 (not (equal old-date
12841 (substring org-last-inserted-timestamp 1 -1))))
12842 (org-add-log-setup 'reschedule nil old-date 'findpos
12843 org-log-reschedule))
12844 (when repeater
12845 (save-excursion
12846 (org-back-to-heading t)
12847 (when (re-search-forward (concat org-scheduled-string " "
12848 org-last-inserted-timestamp)
12849 (save-excursion
12850 (outline-next-heading) (point)) t)
12851 (goto-char (1- (match-end 0)))
12852 (insert " " repeater)
12853 (setq org-last-inserted-timestamp
12854 (concat (substring org-last-inserted-timestamp 0 -1)
12855 " " repeater
12856 (substring org-last-inserted-timestamp -1))))))
12857 (message "Scheduled to %s" org-last-inserted-timestamp))))))
12859 (defun org-get-scheduled-time (pom &optional inherit)
12860 "Get the scheduled time as a time tuple, of a format suitable
12861 for calling org-schedule with, or if there is no scheduling,
12862 returns nil."
12863 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12864 (when time
12865 (apply 'encode-time (org-parse-time-string time)))))
12867 (defun org-get-deadline-time (pom &optional inherit)
12868 "Get the deadline as a time tuple, of a format suitable for
12869 calling org-deadline with, or if there is no scheduling, returns
12870 nil."
12871 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12872 (when time
12873 (apply 'encode-time (org-parse-time-string time)))))
12875 (defun org-remove-timestamp-with-keyword (keyword)
12876 "Remove all time stamps with KEYWORD in the current entry."
12877 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12878 beg)
12879 (save-excursion
12880 (org-back-to-heading t)
12881 (setq beg (point))
12882 (outline-next-heading)
12883 (while (re-search-backward re beg t)
12884 (replace-match "")
12885 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12886 (equal (char-before) ?\ ))
12887 (backward-delete-char 1)
12888 (if (string-match "^[ \t]*$" (buffer-substring
12889 (point-at-bol) (point-at-eol)))
12890 (delete-region (point-at-bol)
12891 (min (point-max) (1+ (point-at-eol))))))))))
12893 (defun org-add-planning-info (what &optional time &rest remove)
12894 "Insert new timestamp with keyword in the line directly after the headline.
12895 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12896 If non is given, the user is prompted for a date.
12897 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12898 be removed."
12899 (interactive)
12900 (let (org-time-was-given org-end-time-was-given ts
12901 end default-time default-input)
12903 (catch 'exit
12904 (when (and (memq what '(scheduled deadline))
12905 (or (not time)
12906 (and (stringp time)
12907 (string-match "^[-+]+[0-9]" time))))
12908 ;; Try to get a default date/time from existing timestamp
12909 (save-excursion
12910 (org-back-to-heading t)
12911 (setq end (save-excursion (outline-next-heading) (point)))
12912 (when (re-search-forward (if (eq what 'scheduled)
12913 org-scheduled-time-regexp
12914 org-deadline-time-regexp)
12915 end t)
12916 (setq ts (match-string 1)
12917 default-time
12918 (apply 'encode-time (org-parse-time-string ts))
12919 default-input (and ts (org-get-compact-tod ts))))))
12920 (when what
12921 (setq time
12922 (if (stringp time)
12923 ;; This is a string (relative or absolute), set proper date
12924 (apply 'encode-time
12925 (org-read-date-analyze
12926 time default-time (decode-time default-time)))
12927 ;; If necessary, get the time from the user
12928 (or time (org-read-date nil 'to-time nil nil
12929 default-time default-input)))))
12931 (when (and org-insert-labeled-timestamps-at-point
12932 (member what '(scheduled deadline)))
12933 (insert
12934 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12935 (org-insert-time-stamp time org-time-was-given
12936 nil nil nil (list org-end-time-was-given))
12937 (setq what nil))
12938 (save-excursion
12939 (save-restriction
12940 (let (col list elt ts buffer-invisibility-spec)
12941 (org-back-to-heading t)
12942 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12943 (goto-char (match-end 1))
12944 (setq col (current-column))
12945 (goto-char (match-end 0))
12946 (if (eobp) (insert "\n") (forward-char 1))
12947 (when (and (not what)
12948 (not (looking-at
12949 (concat "[ \t]*"
12950 org-keyword-time-not-clock-regexp))))
12951 ;; Nothing to add, nothing to remove...... :-)
12952 (throw 'exit nil))
12953 (if (and (not (looking-at org-outline-regexp))
12954 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12955 "[^\r\n]*"))
12956 (not (equal (match-string 1) org-clock-string)))
12957 (narrow-to-region (match-beginning 0) (match-end 0))
12958 (insert-before-markers "\n")
12959 (backward-char 1)
12960 (narrow-to-region (point) (point))
12961 (and org-adapt-indentation (org-indent-to-column col)))
12962 ;; Check if we have to remove something.
12963 (setq list (cons what remove))
12964 (while list
12965 (setq elt (pop list))
12966 (when (or (and (eq elt 'scheduled)
12967 (re-search-forward org-scheduled-time-regexp nil t))
12968 (and (eq elt 'deadline)
12969 (re-search-forward org-deadline-time-regexp nil t))
12970 (and (eq elt 'closed)
12971 (re-search-forward org-closed-time-regexp nil t)))
12972 (replace-match "")
12973 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12974 (and (looking-at "[ \t]+") (replace-match ""))
12975 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12976 (when what
12977 (insert
12978 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12979 (cond ((eq what 'scheduled) org-scheduled-string)
12980 ((eq what 'deadline) org-deadline-string)
12981 ((eq what 'closed) org-closed-string))
12982 " ")
12983 (setq ts (org-insert-time-stamp
12984 time
12985 (or org-time-was-given
12986 (and (eq what 'closed) org-log-done-with-time))
12987 (eq what 'closed)
12988 nil nil (list org-end-time-was-given)))
12989 (insert
12990 (if (not (or (bolp) (eq (char-before) ?\ )
12991 (memq (char-after) '(32 10))
12992 (eobp))) " " ""))
12993 (end-of-line 1))
12994 (goto-char (point-min))
12995 (widen)
12996 (if (and (looking-at "[ \t]*\n")
12997 (equal (char-before) ?\n))
12998 (delete-region (1- (point)) (point-at-eol)))
12999 ts))))))
13001 (defvar org-log-note-marker (make-marker))
13002 (defvar org-log-note-purpose nil)
13003 (defvar org-log-note-state nil)
13004 (defvar org-log-note-previous-state nil)
13005 (defvar org-log-note-how nil)
13006 (defvar org-log-note-extra nil)
13007 (defvar org-log-note-window-configuration nil)
13008 (defvar org-log-note-return-to (make-marker))
13009 (defvar org-log-note-effective-time nil
13010 "Remembered current time so that dynamically scoped
13011 `org-extend-today-until' affects tha timestamps in state change
13012 log")
13014 (defvar org-log-post-message nil
13015 "Message to be displayed after a log note has been stored.
13016 The auto-repeater uses this.")
13018 (defun org-add-note ()
13019 "Add a note to the current entry.
13020 This is done in the same way as adding a state change note."
13021 (interactive)
13022 (org-add-log-setup 'note nil nil 'findpos nil))
13024 (defvar org-property-end-re)
13025 (defun org-add-log-setup (&optional purpose state prev-state
13026 findpos how extra)
13027 "Set up the post command hook to take a note.
13028 If this is about to TODO state change, the new state is expected in STATE.
13029 When FINDPOS is non-nil, find the correct position for the note in
13030 the current entry. If not, assume that it can be inserted at point.
13031 HOW is an indicator what kind of note should be created.
13032 EXTRA is additional text that will be inserted into the notes buffer."
13033 (let* ((org-log-into-drawer (org-log-into-drawer))
13034 (drawer (cond ((stringp org-log-into-drawer)
13035 org-log-into-drawer)
13036 (org-log-into-drawer "LOGBOOK"))))
13037 (save-restriction
13038 (save-excursion
13039 (when findpos
13040 (org-back-to-heading t)
13041 (narrow-to-region (point) (save-excursion
13042 (outline-next-heading) (point)))
13043 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13044 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13045 "[^\r\n]*\\)?"))
13046 (goto-char (match-end 0))
13047 (cond
13048 (drawer
13049 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13050 nil t)
13051 (progn
13052 (goto-char (match-end 0))
13053 (or org-log-states-order-reversed
13054 (and (re-search-forward org-property-end-re nil t)
13055 (goto-char (1- (match-beginning 0))))))
13056 (insert "\n:" drawer ":\n:END:")
13057 (beginning-of-line 0)
13058 (org-indent-line)
13059 (beginning-of-line 2)
13060 (org-indent-line)
13061 (end-of-line 0)))
13062 ((and org-log-state-notes-insert-after-drawers
13063 (save-excursion
13064 (forward-line) (looking-at org-drawer-regexp)))
13065 (forward-line)
13066 (while (looking-at org-drawer-regexp)
13067 (goto-char (match-end 0))
13068 (re-search-forward org-property-end-re (point-max) t)
13069 (forward-line))
13070 (forward-line -1)))
13071 (unless org-log-states-order-reversed
13072 (and (= (char-after) ?\n) (forward-char 1))
13073 (org-skip-over-state-notes)
13074 (skip-chars-backward " \t\n\r")))
13075 (move-marker org-log-note-marker (point))
13076 (setq org-log-note-purpose purpose
13077 org-log-note-state state
13078 org-log-note-previous-state prev-state
13079 org-log-note-how how
13080 org-log-note-extra extra
13081 org-log-note-effective-time (org-current-effective-time))
13082 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13084 (defun org-skip-over-state-notes ()
13085 "Skip past the list of State notes in an entry."
13086 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13087 (when (ignore-errors (goto-char (org-in-item-p)))
13088 (let* ((struct (org-list-struct))
13089 (prevs (org-list-prevs-alist struct)))
13090 (while (looking-at "[ \t]*- State")
13091 (goto-char (or (org-list-get-next-item (point) struct prevs)
13092 (org-list-get-item-end (point) struct)))))))
13094 (defun org-add-log-note (&optional purpose)
13095 "Pop up a window for taking a note, and add this note later at point."
13096 (remove-hook 'post-command-hook 'org-add-log-note)
13097 (setq org-log-note-window-configuration (current-window-configuration))
13098 (delete-other-windows)
13099 (move-marker org-log-note-return-to (point))
13100 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13101 (goto-char org-log-note-marker)
13102 (org-switch-to-buffer-other-window "*Org Note*")
13103 (erase-buffer)
13104 (if (memq org-log-note-how '(time state))
13105 (let (current-prefix-arg) (org-store-log-note))
13106 (let ((org-inhibit-startup t)) (org-mode))
13107 (insert (format "# Insert note for %s.
13108 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13109 (cond
13110 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13111 ((eq org-log-note-purpose 'done) "closed todo item")
13112 ((eq org-log-note-purpose 'state)
13113 (format "state change from \"%s\" to \"%s\""
13114 (or org-log-note-previous-state "")
13115 (or org-log-note-state "")))
13116 ((eq org-log-note-purpose 'reschedule)
13117 "rescheduling")
13118 ((eq org-log-note-purpose 'delschedule)
13119 "no longer scheduled")
13120 ((eq org-log-note-purpose 'redeadline)
13121 "changing deadline")
13122 ((eq org-log-note-purpose 'deldeadline)
13123 "removing deadline")
13124 ((eq org-log-note-purpose 'refile)
13125 "refiling")
13126 ((eq org-log-note-purpose 'note)
13127 "this entry")
13128 (t (error "This should not happen")))))
13129 (if org-log-note-extra (insert org-log-note-extra))
13130 (org-set-local 'org-finish-function 'org-store-log-note)
13131 (run-hooks 'org-log-buffer-setup-hook)))
13133 (defvar org-note-abort nil) ; dynamically scoped
13134 (defun org-store-log-note ()
13135 "Finish taking a log note, and insert it to where it belongs."
13136 (let ((txt (buffer-string)))
13137 (kill-buffer (current-buffer))
13138 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13139 lines ind bul)
13140 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13141 (setq txt (replace-match "" t t txt)))
13142 (if (string-match "\\s-+\\'" txt)
13143 (setq txt (replace-match "" t t txt)))
13144 (setq lines (org-split-string txt "\n"))
13145 (when (and note (string-match "\\S-" note))
13146 (setq note
13147 (org-replace-escapes
13148 note
13149 (list (cons "%u" (user-login-name))
13150 (cons "%U" user-full-name)
13151 (cons "%t" (format-time-string
13152 (org-time-stamp-format 'long 'inactive)
13153 org-log-note-effective-time))
13154 (cons "%T" (format-time-string
13155 (org-time-stamp-format 'long nil)
13156 org-log-note-effective-time))
13157 (cons "%d" (format-time-string
13158 (org-time-stamp-format nil 'inactive)
13159 org-log-note-effective-time))
13160 (cons "%D" (format-time-string
13161 (org-time-stamp-format nil nil)
13162 org-log-note-effective-time))
13163 (cons "%s" (if org-log-note-state
13164 (concat "\"" org-log-note-state "\"")
13165 ""))
13166 (cons "%S" (if org-log-note-previous-state
13167 (concat "\"" org-log-note-previous-state "\"")
13168 "\"\"")))))
13169 (if lines (setq note (concat note " \\\\")))
13170 (push note lines))
13171 (when (or current-prefix-arg org-note-abort)
13172 (when org-log-into-drawer
13173 (org-remove-empty-drawer-at
13174 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13175 org-log-note-marker))
13176 (setq lines nil))
13177 (when lines
13178 (with-current-buffer (marker-buffer org-log-note-marker)
13179 (save-excursion
13180 (goto-char org-log-note-marker)
13181 (move-marker org-log-note-marker nil)
13182 (end-of-line 1)
13183 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13184 (setq ind (save-excursion
13185 (if (ignore-errors (goto-char (org-in-item-p)))
13186 (let ((struct (org-list-struct)))
13187 (org-list-get-ind
13188 (org-list-get-top-point struct) struct))
13189 (skip-chars-backward " \r\t\n")
13190 (cond
13191 ((and (org-at-heading-p)
13192 org-adapt-indentation)
13193 (1+ (org-current-level)))
13194 ((org-at-heading-p) 0)
13195 (t (org-get-indentation))))))
13196 (setq bul (org-list-bullet-string "-"))
13197 (org-indent-line-to ind)
13198 (insert bul (pop lines))
13199 (let ((ind-body (+ (length bul) ind)))
13200 (while lines
13201 (insert "\n")
13202 (org-indent-line-to ind-body)
13203 (insert (pop lines))))
13204 (message "Note stored")
13205 (org-back-to-heading t)
13206 (org-cycle-hide-drawers 'children))))))
13207 (set-window-configuration org-log-note-window-configuration)
13208 (with-current-buffer (marker-buffer org-log-note-return-to)
13209 (goto-char org-log-note-return-to))
13210 (move-marker org-log-note-return-to nil)
13211 (and org-log-post-message (message "%s" org-log-post-message)))
13213 (defun org-remove-empty-drawer-at (drawer pos)
13214 "Remove an empty drawer DRAWER at position POS.
13215 POS may also be a marker."
13216 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13217 (save-excursion
13218 (save-restriction
13219 (widen)
13220 (goto-char pos)
13221 (if (org-in-regexp
13222 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13223 (replace-match ""))))))
13225 (defvar org-ts-type nil)
13226 (defun org-sparse-tree (&optional arg type)
13227 "Create a sparse tree, prompt for the details.
13228 This command can create sparse trees. You first need to select the type
13229 of match used to create the tree:
13231 t Show all TODO entries.
13232 T Show entries with a specific TODO keyword.
13233 m Show entries selected by a tags/property match.
13234 p Enter a property name and its value (both with completion on existing
13235 names/values) and show entries with that property.
13236 r Show entries matching a regular expression (`/' can be used as well).
13237 b Show deadlines and scheduled items before a date.
13238 a Show deadlines and scheduled items after a date.
13239 d Show deadlines due within `org-deadline-warning-days'.
13240 D Show deadlines and scheduled items between a date range."
13241 (interactive "P")
13242 (let (ans kwd value ts-type)
13243 (setq type (or type org-sparse-tree-default-date-type))
13244 (setq org-ts-type type)
13245 (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"
13246 (cond ((eq type 'all) "all timestamps")
13247 ((eq type 'scheduled) "only scheduled")
13248 ((eq type 'deadline) "only deadline")
13249 ((eq type 'active) "only active timestamps")
13250 ((eq type 'inactive) "only inactive timestamps")
13251 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13252 (t "scheduled/deadline")))
13253 (setq ans (read-char-exclusive))
13254 (cond
13255 ((equal ans ?c)
13256 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
13257 ((equal ans ?d)
13258 (call-interactively 'org-check-deadlines))
13259 ((equal ans ?b)
13260 (call-interactively 'org-check-before-date))
13261 ((equal ans ?a)
13262 (call-interactively 'org-check-after-date))
13263 ((equal ans ?D)
13264 (call-interactively 'org-check-dates-range))
13265 ((equal ans ?t)
13266 (call-interactively 'org-show-todo-tree))
13267 ((equal ans ?T)
13268 (org-show-todo-tree '(4)))
13269 ((member ans '(?T ?m))
13270 (call-interactively 'org-match-sparse-tree))
13271 ((member ans '(?p ?P))
13272 (setq kwd (org-icompleting-read "Property: "
13273 (mapcar 'list (org-buffer-property-keys))))
13274 (setq value (org-icompleting-read "Value: "
13275 (mapcar 'list (org-property-values kwd))))
13276 (unless (string-match "\\`{.*}\\'" value)
13277 (setq value (concat "\"" value "\"")))
13278 (org-match-sparse-tree arg (concat kwd "=" value)))
13279 ((member ans '(?r ?R ?/))
13280 (call-interactively 'org-occur))
13281 (t (error "No such sparse tree command \"%c\"" ans)))))
13283 (defvar org-occur-highlights nil
13284 "List of overlays used for occur matches.")
13285 (make-variable-buffer-local 'org-occur-highlights)
13286 (defvar org-occur-parameters nil
13287 "Parameters of the active org-occur calls.
13288 This is a list, each call to org-occur pushes as cons cell,
13289 containing the regular expression and the callback, onto the list.
13290 The list can contain several entries if `org-occur' has been called
13291 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13292 will only contain one set of parameters. When the highlights are
13293 removed (for example with `C-c C-c', or with the next edit (depending
13294 on `org-remove-highlights-with-change'), this variable is emptied
13295 as well.")
13296 (make-variable-buffer-local 'org-occur-parameters)
13298 (defun org-occur (regexp &optional keep-previous callback)
13299 "Make a compact tree which shows all matches of REGEXP.
13300 The tree will show the lines where the regexp matches, and all higher
13301 headlines above the match. It will also show the heading after the match,
13302 to make sure editing the matching entry is easy.
13303 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13304 call to `org-occur' will be kept, to allow stacking of calls to this
13305 command.
13306 If CALLBACK is non-nil, it is a function which is called to confirm
13307 that the match should indeed be shown."
13308 (interactive "sRegexp: \nP")
13309 (when (equal regexp "")
13310 (error "Regexp cannot be empty"))
13311 (unless keep-previous
13312 (org-remove-occur-highlights nil nil t))
13313 (push (cons regexp callback) org-occur-parameters)
13314 (let ((cnt 0))
13315 (save-excursion
13316 (goto-char (point-min))
13317 (if (or (not keep-previous) ; do not want to keep
13318 (not org-occur-highlights)) ; no previous matches
13319 ;; hide everything
13320 (org-overview))
13321 (while (re-search-forward regexp nil t)
13322 (when (or (not callback)
13323 (save-match-data (funcall callback)))
13324 (setq cnt (1+ cnt))
13325 (when org-highlight-sparse-tree-matches
13326 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13327 (org-show-context 'occur-tree))))
13328 (when org-remove-highlights-with-change
13329 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13330 nil 'local))
13331 (unless org-sparse-tree-open-archived-trees
13332 (org-hide-archived-subtrees (point-min) (point-max)))
13333 (run-hooks 'org-occur-hook)
13334 (if (org-called-interactively-p 'interactive)
13335 (message "%d match(es) for regexp %s" cnt regexp))
13336 cnt))
13338 (defun org-occur-next-match (&optional n reset)
13339 "Function for `next-error-function' to find sparse tree matches.
13340 N is the number of matches to move, when negative move backwards.
13341 RESET is entirely ignored - this function always goes back to the
13342 starting point when no match is found."
13343 (let* ((limit (if (< n 0) (point-min) (point-max)))
13344 (search-func (if (< n 0)
13345 'previous-single-char-property-change
13346 'next-single-char-property-change))
13347 (n (abs n))
13348 (pos (point))
13350 (catch 'exit
13351 (while (setq p1 (funcall search-func (point) 'org-type))
13352 (when (equal p1 limit)
13353 (goto-char pos)
13354 (error "No more matches"))
13355 (when (equal (get-char-property p1 'org-type) 'org-occur)
13356 (setq n (1- n))
13357 (when (= n 0)
13358 (goto-char p1)
13359 (throw 'exit (point))))
13360 (goto-char p1))
13361 (goto-char p1)
13362 (error "No more matches"))))
13364 (defun org-show-context (&optional key)
13365 "Make sure point and context are visible.
13366 How much context is shown depends upon the variables
13367 `org-show-hierarchy-above', `org-show-following-heading',
13368 `org-show-entry-below' and `org-show-siblings'."
13369 (let ((heading-p (org-at-heading-p t))
13370 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13371 (following-p (org-get-alist-option org-show-following-heading key))
13372 (entry-p (org-get-alist-option org-show-entry-below key))
13373 (siblings-p (org-get-alist-option org-show-siblings key)))
13374 ;; Show heading or entry text
13375 (if (and heading-p (not entry-p))
13376 (org-flag-heading nil) ; only show the heading
13377 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13378 (org-show-hidden-entry))) ; show entire entry
13379 (when following-p
13380 ;; Show next sibling, or heading below text
13381 (save-excursion
13382 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13383 (org-flag-heading nil))))
13384 (when siblings-p (org-show-siblings))
13385 (when hierarchy-p
13386 ;; show all higher headings, possibly with siblings
13387 (save-excursion
13388 (while (and (condition-case nil
13389 (progn (org-up-heading-all 1) t)
13390 (error nil))
13391 (not (bobp)))
13392 (org-flag-heading nil)
13393 (when siblings-p (org-show-siblings)))))
13394 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13396 (defvar org-reveal-start-hook nil
13397 "Hook run before revealing a location.")
13399 (defun org-reveal (&optional siblings)
13400 "Show current entry, hierarchy above it, and the following headline.
13401 This can be used to show a consistent set of context around locations
13402 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13403 not t for the search context.
13405 With optional argument SIBLINGS, on each level of the hierarchy all
13406 siblings are shown. This repairs the tree structure to what it would
13407 look like when opened with hierarchical calls to `org-cycle'.
13408 With double optional argument \\[universal-argument] \\[universal-argument], \
13409 go to the parent and show the
13410 entire tree."
13411 (interactive "P")
13412 (run-hooks 'org-reveal-start-hook)
13413 (let ((org-show-hierarchy-above t)
13414 (org-show-following-heading t)
13415 (org-show-siblings (if siblings t org-show-siblings)))
13416 (org-show-context nil))
13417 (when (equal siblings '(16))
13418 (save-excursion
13419 (when (org-up-heading-safe)
13420 (org-show-subtree)
13421 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13423 (defun org-highlight-new-match (beg end)
13424 "Highlight from BEG to END and mark the highlight is an occur headline."
13425 (let ((ov (make-overlay beg end)))
13426 (overlay-put ov 'face 'secondary-selection)
13427 (overlay-put ov 'org-type 'org-occur)
13428 (push ov org-occur-highlights)))
13430 (defun org-remove-occur-highlights (&optional beg end noremove)
13431 "Remove the occur highlights from the buffer.
13432 BEG and END are ignored. If NOREMOVE is nil, remove this function
13433 from the `before-change-functions' in the current buffer."
13434 (interactive)
13435 (unless org-inhibit-highlight-removal
13436 (mapc 'delete-overlay org-occur-highlights)
13437 (setq org-occur-highlights nil)
13438 (setq org-occur-parameters nil)
13439 (unless noremove
13440 (remove-hook 'before-change-functions
13441 'org-remove-occur-highlights 'local))))
13443 ;;;; Priorities
13445 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13446 "Regular expression matching the priority indicator.")
13448 (defvar org-remove-priority-next-time nil)
13450 (defun org-priority-up ()
13451 "Increase the priority of the current item."
13452 (interactive)
13453 (org-priority 'up))
13455 (defun org-priority-down ()
13456 "Decrease the priority of the current item."
13457 (interactive)
13458 (org-priority 'down))
13460 (defun org-priority (&optional action show)
13461 "Change the priority of an item.
13462 ACTION can be `set', `up', `down', or a character."
13463 (interactive "P")
13464 (if (equal action '(4))
13465 (org-show-priority)
13466 (unless org-enable-priority-commands
13467 (error "Priority commands are disabled"))
13468 (setq action (or action 'set))
13469 (let (current new news have remove)
13470 (save-excursion
13471 (org-back-to-heading t)
13472 (if (looking-at org-priority-regexp)
13473 (setq current (string-to-char (match-string 2))
13474 have t))
13475 (cond
13476 ((eq action 'remove)
13477 (setq remove t new ?\ ))
13478 ((or (eq action 'set)
13479 (if (featurep 'xemacs) (characterp action) (integerp action)))
13480 (if (not (eq action 'set))
13481 (setq new action)
13482 (message "Priority %c-%c, SPC to remove: "
13483 org-highest-priority org-lowest-priority)
13484 (save-match-data
13485 (setq new (read-char-exclusive))))
13486 (if (and (= (upcase org-highest-priority) org-highest-priority)
13487 (= (upcase org-lowest-priority) org-lowest-priority))
13488 (setq new (upcase new)))
13489 (cond ((equal new ?\ ) (setq remove t))
13490 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13491 (error "Priority must be between `%c' and `%c'"
13492 org-highest-priority org-lowest-priority))))
13493 ((eq action 'up)
13494 (setq new (if have
13495 (1- current) ; normal cycling
13496 ;; last priority was empty
13497 (if (eq last-command this-command)
13498 org-lowest-priority ; wrap around empty to lowest
13499 ;; default
13500 (if org-priority-start-cycle-with-default
13501 org-default-priority
13502 (1- org-default-priority))))))
13503 ((eq action 'down)
13504 (setq new (if have
13505 (1+ current) ; normal cycling
13506 ;; last priority was empty
13507 (if (eq last-command this-command)
13508 org-highest-priority ; wrap around empty to highest
13509 ;; default
13510 (if org-priority-start-cycle-with-default
13511 org-default-priority
13512 (1+ org-default-priority))))))
13513 (t (error "Invalid action")))
13514 (if (or (< (upcase new) org-highest-priority)
13515 (> (upcase new) org-lowest-priority))
13516 (if (and (memq action '(up down))
13517 (not have) (not (eq last-command this-command)))
13518 ;; `new' is from default priority
13519 (error
13520 "The default can not be set, see `org-default-priority' why")
13521 ;; normal cycling: `new' is beyond highest/lowest priority
13522 ;; and is wrapped around to the empty priority
13523 (setq remove t)))
13524 (setq news (format "%c" new))
13525 (if have
13526 (if remove
13527 (replace-match "" t t nil 1)
13528 (replace-match news t t nil 2))
13529 (if remove
13530 (error "No priority cookie found in line")
13531 (let ((case-fold-search nil))
13532 (looking-at org-todo-line-regexp))
13533 (if (match-end 2)
13534 (progn
13535 (goto-char (match-end 2))
13536 (insert " [#" news "]"))
13537 (goto-char (match-beginning 3))
13538 (insert "[#" news "] "))))
13539 (org-preserve-lc (org-set-tags nil 'align)))
13540 (if remove
13541 (message "Priority removed")
13542 (message "Priority of current item set to %s" news)))))
13544 (defun org-show-priority ()
13545 "Show the priority of the current item.
13546 This priority is composed of the main priority given with the [#A] cookies,
13547 and by additional input from the age of a schedules or deadline entry."
13548 (interactive)
13549 (let ((pri (if (eq major-mode 'org-agenda-mode)
13550 (org-get-at-bol 'priority)
13551 (save-excursion
13552 (save-match-data
13553 (beginning-of-line)
13554 (and (looking-at org-heading-regexp)
13555 (org-get-priority (match-string 0))))))))
13556 (message "Priority is %d" (if pri pri -1000))))
13558 (defun org-get-priority (s)
13559 "Find priority cookie and return priority."
13560 (save-match-data
13561 (if (functionp org-get-priority-function)
13562 (funcall org-get-priority-function)
13563 (if (not (string-match org-priority-regexp s))
13564 (* 1000 (- org-lowest-priority org-default-priority))
13565 (* 1000 (- org-lowest-priority
13566 (string-to-char (match-string 2 s))))))))
13568 ;;;; Tags
13570 (defvar org-agenda-archives-mode)
13571 (defvar org-map-continue-from nil
13572 "Position from where mapping should continue.
13573 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13575 (defvar org-scanner-tags nil
13576 "The current tag list while the tags scanner is running.")
13577 (defvar org-trust-scanner-tags nil
13578 "Should `org-get-tags-at' use the tags for the scanner.
13579 This is for internal dynamical scoping only.
13580 When this is non-nil, the function `org-get-tags-at' will return the value
13581 of `org-scanner-tags' instead of building the list by itself. This
13582 can lead to large speed-ups when the tags scanner is used in a file with
13583 many entries, and when the list of tags is retrieved, for example to
13584 obtain a list of properties. Building the tags list for each entry in such
13585 a file becomes an N^2 operation - but with this variable set, it scales
13586 as N.")
13588 (defun org-scan-tags (action matcher todo-only &optional start-level)
13589 "Sca headline tags with inheritance and produce output ACTION.
13591 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13592 or `agenda' to produce an entry list for an agenda view. It can also be
13593 a Lisp form or a function that should be called at each matched headline, in
13594 this case the return value is a list of all return values from these calls.
13596 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13597 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13598 only lines with a not-done TODO keyword are included in the output.
13599 This should be the same variable that was scoped into
13600 and set by `org-make-tags-matcher' when it constructed MATCHER.
13602 START-LEVEL can be a string with asterisks, reducing the scope to
13603 headlines matching this string."
13604 (require 'org-agenda)
13605 (let* ((re (concat "^"
13606 (if start-level
13607 ;; Get the correct level to match
13608 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13609 org-outline-regexp)
13610 " *\\(\\<\\("
13611 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13612 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13613 (props (list 'face 'default
13614 'done-face 'org-agenda-done
13615 'undone-face 'default
13616 'mouse-face 'highlight
13617 'org-not-done-regexp org-not-done-regexp
13618 'org-todo-regexp org-todo-regexp
13619 'org-complex-heading-regexp org-complex-heading-regexp
13620 'help-echo
13621 (format "mouse-2 or RET jump to org file %s"
13622 (abbreviate-file-name
13623 (or (buffer-file-name (buffer-base-buffer))
13624 (buffer-name (buffer-base-buffer)))))))
13625 (case-fold-search nil)
13626 (org-map-continue-from nil)
13627 lspos tags tags-list
13628 (tags-alist (list (cons 0 org-file-tags)))
13629 (llast 0) rtn rtn1 level category i txt
13630 todo marker entry priority)
13631 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13632 (setq action (list 'lambda nil action)))
13633 (save-excursion
13634 (goto-char (point-min))
13635 (when (eq action 'sparse-tree)
13636 (org-overview)
13637 (org-remove-occur-highlights))
13638 (while (re-search-forward re nil t)
13639 (setq org-map-continue-from nil)
13640 (catch :skip
13641 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13642 tags (if (match-end 4) (org-match-string-no-properties 4)))
13643 (goto-char (setq lspos (match-beginning 0)))
13644 (setq level (org-reduced-level (org-outline-level))
13645 category (org-get-category))
13646 (setq i llast llast level)
13647 ;; remove tag lists from same and sublevels
13648 (while (>= i level)
13649 (when (setq entry (assoc i tags-alist))
13650 (setq tags-alist (delete entry tags-alist)))
13651 (setq i (1- i)))
13652 ;; add the next tags
13653 (when tags
13654 (setq tags (org-split-string tags ":")
13655 tags-alist
13656 (cons (cons level tags) tags-alist)))
13657 ;; compile tags for current headline
13658 (setq tags-list
13659 (if org-use-tag-inheritance
13660 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13661 tags)
13662 org-scanner-tags tags-list)
13663 (when org-use-tag-inheritance
13664 (setcdr (car tags-alist)
13665 (mapcar (lambda (x)
13666 (setq x (copy-sequence x))
13667 (org-add-prop-inherited x))
13668 (cdar tags-alist))))
13669 (when (and tags org-use-tag-inheritance
13670 (or (not (eq t org-use-tag-inheritance))
13671 org-tags-exclude-from-inheritance))
13672 ;; selective inheritance, remove uninherited ones
13673 (setcdr (car tags-alist)
13674 (org-remove-uninherited-tags (cdar tags-alist))))
13675 (when (and
13677 ;; eval matcher only when the todo condition is OK
13678 (and (or (not todo-only) (member todo org-not-done-keywords))
13679 (let ((case-fold-search t) (org-trust-scanner-tags t))
13680 (eval matcher)))
13682 ;; Call the skipper, but return t if it does not skip,
13683 ;; so that the `and' form continues evaluating
13684 (progn
13685 (unless (eq action 'sparse-tree) (org-agenda-skip))
13688 ;; Check if timestamps are deselecting this entry
13689 (or (not todo-only)
13690 (and (member todo org-not-done-keywords)
13691 (or (not org-agenda-tags-todo-honor-ignore-options)
13692 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13694 ;; select this headline
13695 (cond
13696 ((eq action 'sparse-tree)
13697 (and org-highlight-sparse-tree-matches
13698 (org-get-heading) (match-end 0)
13699 (org-highlight-new-match
13700 (match-beginning 1) (match-end 1)))
13701 (org-show-context 'tags-tree))
13702 ((eq action 'agenda)
13703 (setq txt (org-agenda-format-item
13705 (concat
13706 (if (eq org-tags-match-list-sublevels 'indented)
13707 (make-string (1- level) ?.) "")
13708 (org-get-heading))
13709 level category
13710 tags-list)
13711 priority (org-get-priority txt))
13712 (goto-char lspos)
13713 (setq marker (org-agenda-new-marker))
13714 (org-add-props txt props
13715 'org-marker marker 'org-hd-marker marker 'org-category category
13716 'todo-state todo
13717 'priority priority 'type "tagsmatch")
13718 (push txt rtn))
13719 ((functionp action)
13720 (setq org-map-continue-from nil)
13721 (save-excursion
13722 (setq rtn1 (funcall action))
13723 (push rtn1 rtn)))
13724 (t (error "Invalid action")))
13726 ;; if we are to skip sublevels, jump to end of subtree
13727 (unless org-tags-match-list-sublevels
13728 (org-end-of-subtree t)
13729 (backward-char 1))))
13730 ;; Get the correct position from where to continue
13731 (if org-map-continue-from
13732 (goto-char org-map-continue-from)
13733 (and (= (point) lspos) (end-of-line 1)))))
13734 (when (and (eq action 'sparse-tree)
13735 (not org-sparse-tree-open-archived-trees))
13736 (org-hide-archived-subtrees (point-min) (point-max)))
13737 (nreverse rtn)))
13739 (defun org-remove-uninherited-tags (tags)
13740 "Remove all tags that are not inherited from the list TAGS."
13741 (cond
13742 ((eq org-use-tag-inheritance t)
13743 (if org-tags-exclude-from-inheritance
13744 (org-delete-all org-tags-exclude-from-inheritance tags)
13745 tags))
13746 ((not org-use-tag-inheritance) nil)
13747 ((stringp org-use-tag-inheritance)
13748 (delq nil (mapcar
13749 (lambda (x)
13750 (if (and (string-match org-use-tag-inheritance x)
13751 (not (member x org-tags-exclude-from-inheritance)))
13752 x nil))
13753 tags)))
13754 ((listp org-use-tag-inheritance)
13755 (delq nil (mapcar
13756 (lambda (x)
13757 (if (member x org-use-tag-inheritance) x nil))
13758 tags)))))
13760 (defun org-match-sparse-tree (&optional todo-only match)
13761 "Create a sparse tree according to tags string MATCH.
13762 MATCH can contain positive and negative selection of tags, like
13763 \"+WORK+URGENT-WITHBOSS\".
13764 If optional argument TODO-ONLY is non-nil, only select lines that are
13765 also TODO lines."
13766 (interactive "P")
13767 (org-agenda-prepare-buffers (list (current-buffer)))
13768 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13770 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13772 (defvar org-cached-props nil)
13773 (defun org-cached-entry-get (pom property)
13774 (if (or (eq t org-use-property-inheritance)
13775 (and (stringp org-use-property-inheritance)
13776 (string-match org-use-property-inheritance property))
13777 (and (listp org-use-property-inheritance)
13778 (member property org-use-property-inheritance)))
13779 ;; Caching is not possible, check it directly
13780 (org-entry-get pom property 'inherit)
13781 ;; Get all properties, so that we can do complicated checks easily
13782 (cdr (assoc property (or org-cached-props
13783 (setq org-cached-props
13784 (org-entry-properties pom)))))))
13786 (defun org-global-tags-completion-table (&optional files)
13787 "Return the list of all tags in all agenda buffer/files.
13788 Optional FILES argument is a list of files which can be used
13789 instead of the agenda files."
13790 (save-excursion
13791 (org-uniquify
13792 (delq nil
13793 (apply 'append
13794 (mapcar
13795 (lambda (file)
13796 (set-buffer (find-file-noselect file))
13797 (append (org-get-buffer-tags)
13798 (mapcar (lambda (x) (if (stringp (car-safe x))
13799 (list (car-safe x)) nil))
13800 org-tag-alist)))
13801 (if (and files (car files))
13802 files
13803 (org-agenda-files))))))))
13805 (defun org-make-tags-matcher (match)
13806 "Create the TAGS/TODO matcher form for the selection string MATCH.
13808 The variable `todo-only' is scoped dynamically into this function.
13809 It will be set to t if the matcher restricts matching to TODO entries,
13810 otherwise will not be touched.
13812 Returns a cons of the selection string MATCH and the constructed
13813 lisp form implementing the matcher. The matcher is to be evaluated
13814 at an Org entry, with point on the headline, and returns t if the
13815 entry matches the selection string MATCH. The returned lisp form
13816 references two variables with information about the entry, which
13817 must be bound around the form's evaluation: todo, the TODO keyword
13818 at the entry (or nil of none); and tags-list, the list of all tags
13819 at the entry including inherited ones. Additionally, the category
13820 of the entry (if any) must be specified as the text property
13821 'org-category on the headline.
13823 See also `org-scan-tags'.
13825 (declare (special todo-only))
13826 (unless (boundp 'todo-only)
13827 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13828 (unless match
13829 ;; Get a new match request, with completion
13830 (let ((org-last-tags-completion-table
13831 (org-global-tags-completion-table)))
13832 (setq match (org-completing-read-no-i
13833 "Match: " 'org-tags-completion-function nil nil nil
13834 'org-tags-history))))
13836 ;; Parse the string and create a lisp form
13837 (let ((match0 match)
13838 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13839 minus tag mm
13840 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13841 orterms term orlist re-p str-p level-p level-op time-p
13842 prop-p pn pv po gv rest)
13843 (if (string-match "/+" match)
13844 ;; match contains also a todo-matching request
13845 (progn
13846 (setq tagsmatch (substring match 0 (match-beginning 0))
13847 todomatch (substring match (match-end 0)))
13848 (if (string-match "^!" todomatch)
13849 (setq todo-only t todomatch (substring todomatch 1)))
13850 (if (string-match "^\\s-*$" todomatch)
13851 (setq todomatch nil)))
13852 ;; only matching tags
13853 (setq tagsmatch match todomatch nil))
13855 ;; Make the tags matcher
13856 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13857 (setq tagsmatcher t)
13858 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13859 (while (setq term (pop orterms))
13860 (while (and (equal (substring term -1) "\\") orterms)
13861 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13862 (while (string-match re term)
13863 (setq rest (substring term (match-end 0))
13864 minus (and (match-end 1)
13865 (equal (match-string 1 term) "-"))
13866 tag (save-match-data (replace-regexp-in-string
13867 "\\\\-" "-"
13868 (match-string 2 term)))
13869 re-p (equal (string-to-char tag) ?{)
13870 level-p (match-end 4)
13871 prop-p (match-end 5)
13872 mm (cond
13873 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13874 (level-p
13875 (setq level-op (org-op-to-function (match-string 3 term)))
13876 `(,level-op level ,(string-to-number
13877 (match-string 4 term))))
13878 (prop-p
13879 (setq pn (match-string 5 term)
13880 po (match-string 6 term)
13881 pv (match-string 7 term)
13882 re-p (equal (string-to-char pv) ?{)
13883 str-p (equal (string-to-char pv) ?\")
13884 time-p (save-match-data
13885 (string-match "^\"[[<].*[]>]\"$" pv))
13886 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13887 (if time-p (setq pv (org-matcher-time pv)))
13888 (setq po (org-op-to-function po (if time-p 'time str-p)))
13889 (cond
13890 ((equal pn "CATEGORY")
13891 (setq gv '(get-text-property (point) 'org-category)))
13892 ((equal pn "TODO")
13893 (setq gv 'todo))
13895 (setq gv `(org-cached-entry-get nil ,pn))))
13896 (if re-p
13897 (if (eq po 'org<>)
13898 `(not (string-match ,pv (or ,gv "")))
13899 `(string-match ,pv (or ,gv "")))
13900 (if str-p
13901 `(,po (or ,gv "") ,pv)
13902 `(,po (string-to-number (or ,gv ""))
13903 ,(string-to-number pv) ))))
13904 (t `(member ,tag tags-list)))
13905 mm (if minus (list 'not mm) mm)
13906 term rest)
13907 (push mm tagsmatcher))
13908 (push (if (> (length tagsmatcher) 1)
13909 (cons 'and tagsmatcher)
13910 (car tagsmatcher))
13911 orlist)
13912 (setq tagsmatcher nil))
13913 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13914 (setq tagsmatcher
13915 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13916 ;; Make the todo matcher
13917 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13918 (setq todomatcher t)
13919 (setq orterms (org-split-string todomatch "|") orlist nil)
13920 (while (setq term (pop orterms))
13921 (while (string-match re term)
13922 (setq minus (and (match-end 1)
13923 (equal (match-string 1 term) "-"))
13924 kwd (match-string 2 term)
13925 re-p (equal (string-to-char kwd) ?{)
13926 term (substring term (match-end 0))
13927 mm (if re-p
13928 `(string-match ,(substring kwd 1 -1) todo)
13929 (list 'equal 'todo kwd))
13930 mm (if minus (list 'not mm) mm))
13931 (push mm todomatcher))
13932 (push (if (> (length todomatcher) 1)
13933 (cons 'and todomatcher)
13934 (car todomatcher))
13935 orlist)
13936 (setq todomatcher nil))
13937 (setq todomatcher (if (> (length orlist) 1)
13938 (cons 'or orlist) (car orlist))))
13940 ;; Return the string and lisp forms of the matcher
13941 (setq matcher (if todomatcher
13942 (list 'and tagsmatcher todomatcher)
13943 tagsmatcher))
13944 (when todo-only
13945 (setq matcher (list 'and '(member todo org-not-done-keywords)
13946 matcher)))
13947 (cons match0 matcher)))
13949 (defun org-op-to-function (op &optional stringp)
13950 "Turn an operator into the appropriate function."
13951 (setq op
13952 (cond
13953 ((equal op "<" ) '(< string< org-time<))
13954 ((equal op ">" ) '(> org-string> org-time>))
13955 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13956 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13957 ((member op '("=" "==")) '(= string= org-time=))
13958 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13959 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13961 (defun org<> (a b) (not (= a b)))
13962 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13963 (defun org-string>= (a b) (not (string< a b)))
13964 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13965 (defun org-string<> (a b) (not (string= a b)))
13966 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13967 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13968 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13969 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13970 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13971 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13972 (defun org-2ft (s)
13973 "Convert S to a floating point time.
13974 If S is already a number, just return it. If it is a string, parse
13975 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13976 (cond
13977 ((numberp s) s)
13978 ((stringp s)
13979 (condition-case nil
13980 (float-time (apply 'encode-time (org-parse-time-string s)))
13981 (error 0.)))
13982 (t 0.)))
13984 (defun org-time-today ()
13985 "Time in seconds today at 0:00.
13986 Returns the float number of seconds since the beginning of the
13987 epoch to the beginning of today (00:00)."
13988 (float-time (apply 'encode-time
13989 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13991 (defun org-matcher-time (s)
13992 "Interpret a time comparison value."
13993 (save-match-data
13994 (cond
13995 ((string= s "<now>") (float-time))
13996 ((string= s "<today>") (org-time-today))
13997 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13998 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13999 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14000 (+ (org-time-today)
14001 (* (string-to-number (match-string 1 s))
14002 (cdr (assoc (match-string 2 s)
14003 '(("d" . 86400.0) ("w" . 604800.0)
14004 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14005 (t (org-2ft s)))))
14007 (defun org-match-any-p (re list)
14008 "Does re match any element of list?"
14009 (setq list (mapcar (lambda (x) (string-match re x)) list))
14010 (delq nil list))
14012 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14013 (defvar org-tags-overlay (make-overlay 1 1))
14014 (org-detach-overlay org-tags-overlay)
14016 (defun org-get-local-tags-at (&optional pos)
14017 "Get a list of tags defined in the current headline."
14018 (org-get-tags-at pos 'local))
14020 (defun org-get-local-tags ()
14021 "Get a list of tags defined in the current headline."
14022 (org-get-tags-at nil 'local))
14024 (defun org-get-tags-at (&optional pos local)
14025 "Get a list of all headline tags applicable at POS.
14026 POS defaults to point. If tags are inherited, the list contains
14027 the targets in the same sequence as the headlines appear, i.e.
14028 the tags of the current headline come last.
14029 When LOCAL is non-nil, only return tags from the current headline,
14030 ignore inherited ones."
14031 (interactive)
14032 (if (and org-trust-scanner-tags
14033 (or (not pos) (equal pos (point)))
14034 (not local))
14035 org-scanner-tags
14036 (let (tags ltags lastpos parent)
14037 (save-excursion
14038 (save-restriction
14039 (widen)
14040 (goto-char (or pos (point)))
14041 (save-match-data
14042 (catch 'done
14043 (condition-case nil
14044 (progn
14045 (org-back-to-heading t)
14046 (while (not (equal lastpos (point)))
14047 (setq lastpos (point))
14048 (when (looking-at
14049 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14050 (setq ltags (org-split-string
14051 (org-match-string-no-properties 1) ":"))
14052 (when parent
14053 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14054 (setq tags (append
14055 (if parent
14056 (org-remove-uninherited-tags ltags)
14057 ltags)
14058 tags)))
14059 (or org-use-tag-inheritance (throw 'done t))
14060 (if local (throw 'done t))
14061 (or (org-up-heading-safe) (error nil))
14062 (setq parent t)))
14063 (error nil)))))
14064 (if local
14065 tags
14066 (reverse (delete-dups
14067 (reverse (append
14068 (org-remove-uninherited-tags
14069 org-file-tags) tags)))))))))
14071 (defun org-add-prop-inherited (s)
14072 (add-text-properties 0 (length s) '(inherited t) s)
14075 (defun org-toggle-tag (tag &optional onoff)
14076 "Toggle the tag TAG for the current line.
14077 If ONOFF is `on' or `off', don't toggle but set to this state."
14078 (let (res current)
14079 (save-excursion
14080 (org-back-to-heading t)
14081 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14082 (point-at-eol) t)
14083 (progn
14084 (setq current (match-string 1))
14085 (replace-match ""))
14086 (setq current ""))
14087 (setq current (nreverse (org-split-string current ":")))
14088 (cond
14089 ((eq onoff 'on)
14090 (setq res t)
14091 (or (member tag current) (push tag current)))
14092 ((eq onoff 'off)
14093 (or (not (member tag current)) (setq current (delete tag current))))
14094 (t (if (member tag current)
14095 (setq current (delete tag current))
14096 (setq res t)
14097 (push tag current))))
14098 (end-of-line 1)
14099 (if current
14100 (progn
14101 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14102 (org-set-tags nil t))
14103 (delete-horizontal-space))
14104 (run-hooks 'org-after-tags-change-hook))
14105 res))
14107 (defun org-align-tags-here (to-col)
14108 ;; Assumes that this is a headline
14109 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14110 (beginning-of-line 1)
14111 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14112 (< pos (match-beginning 2)))
14113 (progn
14114 (setq tags-l (- (match-end 2) (match-beginning 2)))
14115 (goto-char (match-beginning 1))
14116 (insert " ")
14117 (delete-region (point) (1+ (match-beginning 2)))
14118 (setq ncol (max (current-column)
14119 (1+ col)
14120 (if (> to-col 0)
14121 to-col
14122 (- (abs to-col) tags-l))))
14123 (setq p (point))
14124 (insert (make-string (- ncol (current-column)) ?\ ))
14125 (setq ncol (current-column))
14126 (when indent-tabs-mode (tabify p (point-at-eol)))
14127 (org-move-to-column (min ncol col) t))
14128 (goto-char pos))))
14130 (defun org-set-tags-command (&optional arg just-align)
14131 "Call the set-tags command for the current entry."
14132 (interactive "P")
14133 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14134 (org-set-tags arg just-align)
14135 (save-excursion
14136 (unless (and (org-region-active-p)
14137 org-loop-over-headlines-in-active-region)
14138 (org-back-to-heading t))
14139 (org-set-tags arg just-align))))
14141 (defun org-set-tags-to (data)
14142 "Set the tags of the current entry to DATA, replacing the current tags.
14143 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14144 If DATA is nil or the empty string, any tags will be removed."
14145 (interactive "sTags: ")
14146 (setq data
14147 (cond
14148 ((eq data nil) "")
14149 ((equal data "") "")
14150 ((stringp data)
14151 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14152 ":"))
14153 ((listp data)
14154 (concat ":" (mapconcat 'identity data ":") ":"))))
14155 (when data
14156 (save-excursion
14157 (org-back-to-heading t)
14158 (when (looking-at org-complex-heading-regexp)
14159 (if (match-end 5)
14160 (progn
14161 (goto-char (match-beginning 5))
14162 (insert data)
14163 (delete-region (point) (point-at-eol))
14164 (org-set-tags nil 'align))
14165 (goto-char (point-at-eol))
14166 (insert " " data)
14167 (org-set-tags nil 'align)))
14168 (beginning-of-line 1)
14169 (if (looking-at ".*?\\([ \t]+\\)$")
14170 (delete-region (match-beginning 1) (match-end 1))))))
14172 (defun org-align-all-tags ()
14173 "Align the tags i all headings."
14174 (interactive)
14175 (save-excursion
14176 (or (ignore-errors (org-back-to-heading t))
14177 (outline-next-heading))
14178 (if (org-at-heading-p)
14179 (org-set-tags t)
14180 (message "No headings"))))
14182 (defvar org-indent-indentation-per-level)
14183 (defun org-set-tags (&optional arg just-align)
14184 "Set the tags for the current headline.
14185 With prefix ARG, realign all tags in headings in the current buffer."
14186 (interactive "P")
14187 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14188 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14189 'region-start-level 'region))
14190 org-loop-over-headlines-in-active-region)
14191 (org-map-entries
14192 ;; We don't use ARG and JUST-ALIGN here these args are not
14193 ;; useful when looping over headlines
14194 `(org-set-tags)
14195 org-loop-over-headlines-in-active-region
14196 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14197 (let* ((re org-outline-regexp-bol)
14198 (current (unless arg (org-get-tags-string)))
14199 (col (current-column))
14200 (org-setting-tags t)
14201 table current-tags inherited-tags ; computed below when needed
14202 tags p0 c0 c1 rpl di tc level)
14203 (if arg
14204 (save-excursion
14205 (goto-char (point-min))
14206 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14207 (while (re-search-forward re nil t)
14208 (org-set-tags nil t)
14209 (end-of-line 1)))
14210 (message "All tags realigned to column %d" org-tags-column))
14211 (if just-align
14212 (setq tags current)
14213 ;; Get a new set of tags from the user
14214 (save-excursion
14215 (setq table (append org-tag-persistent-alist
14216 (or org-tag-alist (org-get-buffer-tags))
14217 (and
14218 org-complete-tags-always-offer-all-agenda-tags
14219 (org-global-tags-completion-table
14220 (org-agenda-files))))
14221 org-last-tags-completion-table table
14222 current-tags (org-split-string current ":")
14223 inherited-tags (nreverse
14224 (nthcdr (length current-tags)
14225 (nreverse (org-get-tags-at))))
14226 tags
14227 (if (or (eq t org-use-fast-tag-selection)
14228 (and org-use-fast-tag-selection
14229 (delq nil (mapcar 'cdr table))))
14230 (org-fast-tag-selection
14231 current-tags inherited-tags table
14232 (if org-fast-tag-selection-include-todo
14233 org-todo-key-alist))
14234 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14235 (org-trim
14236 (org-icompleting-read "Tags: "
14237 'org-tags-completion-function
14238 nil nil current 'org-tags-history))))))
14239 (while (string-match "[-+&]+" tags)
14240 ;; No boolean logic, just a list
14241 (setq tags (replace-match ":" t t tags))))
14243 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14245 (if org-tags-sort-function
14246 (setq tags (mapconcat 'identity
14247 (sort (org-split-string
14248 tags (org-re "[^[:alnum:]_@#%]+"))
14249 org-tags-sort-function) ":")))
14251 (if (string-match "\\`[\t ]*\\'" tags)
14252 (setq tags "")
14253 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14254 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14256 ;; Insert new tags at the correct column
14257 (beginning-of-line 1)
14258 (setq level (or (and (looking-at org-outline-regexp)
14259 (- (match-end 0) (point) 1))
14261 (cond
14262 ((and (equal current "") (equal tags "")))
14263 ((re-search-forward
14264 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14265 (point-at-eol) t)
14266 (if (equal tags "")
14267 (setq rpl "")
14268 (goto-char (match-beginning 0))
14269 (setq c0 (current-column)
14270 ;; compute offset for the case of org-indent-mode active
14271 di (if org-indent-mode
14272 (* (1- org-indent-indentation-per-level) (1- level))
14274 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14275 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14276 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14277 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14278 (replace-match rpl t t)
14279 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14280 tags)
14281 (t (error "Tags alignment failed")))
14282 (org-move-to-column col)
14283 (unless just-align
14284 (run-hooks 'org-after-tags-change-hook))))))
14286 (defun org-change-tag-in-region (beg end tag off)
14287 "Add or remove TAG for each entry in the region.
14288 This works in the agenda, and also in an org-mode buffer."
14289 (interactive
14290 (list (region-beginning) (region-end)
14291 (let ((org-last-tags-completion-table
14292 (if (derived-mode-p 'org-mode)
14293 (org-get-buffer-tags)
14294 (org-global-tags-completion-table))))
14295 (org-icompleting-read
14296 "Tag: " 'org-tags-completion-function nil nil nil
14297 'org-tags-history))
14298 (progn
14299 (message "[s]et or [r]emove? ")
14300 (equal (read-char-exclusive) ?r))))
14301 (if (fboundp 'deactivate-mark) (deactivate-mark))
14302 (let ((agendap (equal major-mode 'org-agenda-mode))
14303 l1 l2 m buf pos newhead (cnt 0))
14304 (goto-char end)
14305 (setq l2 (1- (org-current-line)))
14306 (goto-char beg)
14307 (setq l1 (org-current-line))
14308 (loop for l from l1 to l2 do
14309 (org-goto-line l)
14310 (setq m (get-text-property (point) 'org-hd-marker))
14311 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14312 (and agendap m))
14313 (setq buf (if agendap (marker-buffer m) (current-buffer))
14314 pos (if agendap m (point)))
14315 (with-current-buffer buf
14316 (save-excursion
14317 (save-restriction
14318 (goto-char pos)
14319 (setq cnt (1+ cnt))
14320 (org-toggle-tag tag (if off 'off 'on))
14321 (setq newhead (org-get-heading)))))
14322 (and agendap (org-agenda-change-all-lines newhead m))))
14323 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14325 (defun org-tags-completion-function (string predicate &optional flag)
14326 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14327 (confirm (lambda (x) (stringp (car x)))))
14328 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14329 (setq s1 (match-string 1 string)
14330 s2 (match-string 2 string))
14331 (setq s1 "" s2 string))
14332 (cond
14333 ((eq flag nil)
14334 ;; try completion
14335 (setq rtn (try-completion s2 ctable confirm))
14336 (if (stringp rtn)
14337 (setq rtn
14338 (concat s1 s2 (substring rtn (length s2))
14339 (if (and org-add-colon-after-tag-completion
14340 (assoc rtn ctable))
14341 ":" ""))))
14342 rtn)
14343 ((eq flag t)
14344 ;; all-completions
14345 (all-completions s2 ctable confirm)
14347 ((eq flag 'lambda)
14348 ;; exact match?
14349 (assoc s2 ctable)))
14352 (defun org-fast-tag-insert (kwd tags face &optional end)
14353 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14354 (insert (format "%-12s" (concat kwd ":"))
14355 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14356 (or end "")))
14358 (defun org-fast-tag-show-exit (flag)
14359 (save-excursion
14360 (org-goto-line 3)
14361 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14362 (replace-match ""))
14363 (when flag
14364 (end-of-line 1)
14365 (org-move-to-column (- (window-width) 19) t)
14366 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14368 (defun org-set-current-tags-overlay (current prefix)
14369 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14370 (if (featurep 'xemacs)
14371 (org-overlay-display org-tags-overlay (concat prefix s)
14372 'secondary-selection)
14373 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14374 (org-overlay-display org-tags-overlay (concat prefix s)))))
14376 (defvar org-last-tag-selection-key nil)
14377 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14378 "Fast tag selection with single keys.
14379 CURRENT is the current list of tags in the headline, INHERITED is the
14380 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14381 possibly with grouping information. TODO-TABLE is a similar table with
14382 TODO keywords, should these have keys assigned to them.
14383 If the keys are nil, a-z are automatically assigned.
14384 Returns the new tags string, or nil to not change the current settings."
14385 (let* ((fulltable (append table todo-table))
14386 (maxlen (apply 'max (mapcar
14387 (lambda (x)
14388 (if (stringp (car x)) (string-width (car x)) 0))
14389 fulltable)))
14390 (buf (current-buffer))
14391 (expert (eq org-fast-tag-selection-single-key 'expert))
14392 (buffer-tags nil)
14393 (fwidth (+ maxlen 3 1 3))
14394 (ncol (/ (- (window-width) 4) fwidth))
14395 (i-face 'org-done)
14396 (c-face 'org-todo)
14397 tg cnt e c char c1 c2 ntable tbl rtn
14398 ov-start ov-end ov-prefix
14399 (exit-after-next org-fast-tag-selection-single-key)
14400 (done-keywords org-done-keywords)
14401 groups ingroup)
14402 (save-excursion
14403 (beginning-of-line 1)
14404 (if (looking-at
14405 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14406 (setq ov-start (match-beginning 1)
14407 ov-end (match-end 1)
14408 ov-prefix "")
14409 (setq ov-start (1- (point-at-eol))
14410 ov-end (1+ ov-start))
14411 (skip-chars-forward "^\n\r")
14412 (setq ov-prefix
14413 (concat
14414 (buffer-substring (1- (point)) (point))
14415 (if (> (current-column) org-tags-column)
14417 (make-string (- org-tags-column (current-column)) ?\ ))))))
14418 (move-overlay org-tags-overlay ov-start ov-end)
14419 (save-window-excursion
14420 (if expert
14421 (set-buffer (get-buffer-create " *Org tags*"))
14422 (delete-other-windows)
14423 (split-window-vertically)
14424 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14425 (erase-buffer)
14426 (org-set-local 'org-done-keywords done-keywords)
14427 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14428 (org-fast-tag-insert "Current" current c-face "\n\n")
14429 (org-fast-tag-show-exit exit-after-next)
14430 (org-set-current-tags-overlay current ov-prefix)
14431 (setq tbl fulltable char ?a cnt 0)
14432 (while (setq e (pop tbl))
14433 (cond
14434 ((equal (car e) :startgroup)
14435 (push '() groups) (setq ingroup t)
14436 (when (not (= cnt 0))
14437 (setq cnt 0)
14438 (insert "\n"))
14439 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14440 ((equal (car e) :endgroup)
14441 (setq ingroup nil cnt 0)
14442 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14443 ((equal e '(:newline))
14444 (when (not (= cnt 0))
14445 (setq cnt 0)
14446 (insert "\n")
14447 (setq e (car tbl))
14448 (while (equal (car tbl) '(:newline))
14449 (insert "\n")
14450 (setq tbl (cdr tbl)))))
14452 (setq tg (copy-sequence (car e)) c2 nil)
14453 (if (cdr e)
14454 (setq c (cdr e))
14455 ;; automatically assign a character.
14456 (setq c1 (string-to-char
14457 (downcase (substring
14458 tg (if (= (string-to-char tg) ?@) 1 0)))))
14459 (if (or (rassoc c1 ntable) (rassoc c1 table))
14460 (while (or (rassoc char ntable) (rassoc char table))
14461 (setq char (1+ char)))
14462 (setq c2 c1))
14463 (setq c (or c2 char)))
14464 (if ingroup (push tg (car groups)))
14465 (setq tg (org-add-props tg nil 'face
14466 (cond
14467 ((not (assoc tg table))
14468 (org-get-todo-face tg))
14469 ((member tg current) c-face)
14470 ((member tg inherited) i-face))))
14471 (if (and (= cnt 0) (not ingroup)) (insert " "))
14472 (insert "[" c "] " tg (make-string
14473 (- fwidth 4 (length tg)) ?\ ))
14474 (push (cons tg c) ntable)
14475 (when (= (setq cnt (1+ cnt)) ncol)
14476 (insert "\n")
14477 (if ingroup (insert " "))
14478 (setq cnt 0)))))
14479 (setq ntable (nreverse ntable))
14480 (insert "\n")
14481 (goto-char (point-min))
14482 (if (not expert) (org-fit-window-to-buffer))
14483 (setq rtn
14484 (catch 'exit
14485 (while t
14486 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14487 (if (not groups) "no " "")
14488 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14489 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14490 (setq org-last-tag-selection-key c)
14491 (cond
14492 ((= c ?\r) (throw 'exit t))
14493 ((= c ?!)
14494 (setq groups (not groups))
14495 (goto-char (point-min))
14496 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14497 ((= c ?\C-c)
14498 (if (not expert)
14499 (org-fast-tag-show-exit
14500 (setq exit-after-next (not exit-after-next)))
14501 (setq expert nil)
14502 (delete-other-windows)
14503 (set-window-buffer (split-window-vertically) " *Org tags*")
14504 (org-switch-to-buffer-other-window " *Org tags*")
14505 (org-fit-window-to-buffer)))
14506 ((or (= c ?\C-g)
14507 (and (= c ?q) (not (rassoc c ntable))))
14508 (org-detach-overlay org-tags-overlay)
14509 (setq quit-flag t))
14510 ((= c ?\ )
14511 (setq current nil)
14512 (if exit-after-next (setq exit-after-next 'now)))
14513 ((= c ?\t)
14514 (condition-case nil
14515 (setq tg (org-icompleting-read
14516 "Tag: "
14517 (or buffer-tags
14518 (with-current-buffer buf
14519 (org-get-buffer-tags)))))
14520 (quit (setq tg "")))
14521 (when (string-match "\\S-" tg)
14522 (add-to-list 'buffer-tags (list tg))
14523 (if (member tg current)
14524 (setq current (delete tg current))
14525 (push tg current)))
14526 (if exit-after-next (setq exit-after-next 'now)))
14527 ((setq e (rassoc c todo-table) tg (car e))
14528 (with-current-buffer buf
14529 (save-excursion (org-todo tg)))
14530 (if exit-after-next (setq exit-after-next 'now)))
14531 ((setq e (rassoc c ntable) tg (car e))
14532 (if (member tg current)
14533 (setq current (delete tg current))
14534 (loop for g in groups do
14535 (if (member tg g)
14536 (mapc (lambda (x)
14537 (setq current (delete x current)))
14538 g)))
14539 (push tg current))
14540 (if exit-after-next (setq exit-after-next 'now))))
14542 ;; Create a sorted list
14543 (setq current
14544 (sort current
14545 (lambda (a b)
14546 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14547 (if (eq exit-after-next 'now) (throw 'exit t))
14548 (goto-char (point-min))
14549 (beginning-of-line 2)
14550 (delete-region (point) (point-at-eol))
14551 (org-fast-tag-insert "Current" current c-face)
14552 (org-set-current-tags-overlay current ov-prefix)
14553 (while (re-search-forward
14554 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14555 (setq tg (match-string 1))
14556 (add-text-properties
14557 (match-beginning 1) (match-end 1)
14558 (list 'face
14559 (cond
14560 ((member tg current) c-face)
14561 ((member tg inherited) i-face)
14562 (t (get-text-property (match-beginning 1) 'face))))))
14563 (goto-char (point-min)))))
14564 (org-detach-overlay org-tags-overlay)
14565 (if rtn
14566 (mapconcat 'identity current ":")
14567 nil))))
14569 (defun org-get-tags-string ()
14570 "Get the TAGS string in the current headline."
14571 (unless (org-at-heading-p t)
14572 (error "Not on a heading"))
14573 (save-excursion
14574 (beginning-of-line 1)
14575 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14576 (org-match-string-no-properties 1)
14577 "")))
14579 (defun org-get-tags ()
14580 "Get the list of tags specified in the current headline."
14581 (org-split-string (org-get-tags-string) ":"))
14583 (defun org-get-buffer-tags ()
14584 "Get a table of all tags used in the buffer, for completion."
14585 (let (tags)
14586 (save-excursion
14587 (goto-char (point-min))
14588 (while (re-search-forward
14589 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14590 (when (equal (char-after (point-at-bol 0)) ?*)
14591 (mapc (lambda (x) (add-to-list 'tags x))
14592 (org-split-string (org-match-string-no-properties 1) ":")))))
14593 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14594 (mapcar 'list tags)))
14596 ;;;; The mapping API
14598 (defun org-map-entries (func &optional match scope &rest skip)
14599 "Call FUNC at each headline selected by MATCH in SCOPE.
14601 FUNC is a function or a lisp form. The function will be called without
14602 arguments, with the cursor positioned at the beginning of the headline.
14603 The return values of all calls to the function will be collected and
14604 returned as a list.
14606 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14607 does not need to preserve point. After evaluation, the cursor will be
14608 moved to the end of the line (presumably of the headline of the
14609 processed entry) and search continues from there. Under some
14610 circumstances, this may not produce the wanted results. For example,
14611 if you have removed (e.g. archived) the current (sub)tree it could
14612 mean that the next entry will be skipped entirely. In such cases, you
14613 can specify the position from where search should continue by making
14614 FUNC set the variable `org-map-continue-from' to the desired buffer
14615 position.
14617 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14618 Only headlines that are matched by this query will be considered during
14619 the iteration. When MATCH is nil or t, all headlines will be
14620 visited by the iteration.
14622 SCOPE determines the scope of this command. It can be any of:
14624 nil The current buffer, respecting the restriction if any
14625 tree The subtree started with the entry at point
14626 region The entries within the active region, if any
14627 region-start-level
14628 The entries within the active region, but only those at
14629 the same level than the first one.
14630 file The current buffer, without restriction
14631 file-with-archives
14632 The current buffer, and any archives associated with it
14633 agenda All agenda files
14634 agenda-with-archives
14635 All agenda files with any archive files associated with them
14636 \(file1 file2 ...)
14637 If this is a list, all files in the list will be scanned
14639 The remaining args are treated as settings for the skipping facilities of
14640 the scanner. The following items can be given here:
14642 archive skip trees with the archive tag
14643 comment skip trees with the COMMENT keyword
14644 function or Emacs Lisp form:
14645 will be used as value for `org-agenda-skip-function', so
14646 whenever the function returns a position, FUNC will not be
14647 called for that entry and search will continue from the
14648 position returned
14650 If your function needs to retrieve the tags including inherited tags
14651 at the *current* entry, you can use the value of the variable
14652 `org-scanner-tags' which will be much faster than getting the value
14653 with `org-get-tags-at'. If your function gets properties with
14654 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14655 to t around the call to `org-entry-properties' to get the same speedup.
14656 Note that if your function moves around to retrieve tags and properties at
14657 a *different* entry, you cannot use these techniques."
14658 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14659 (not (org-region-active-p)))
14660 (let* ((org-agenda-archives-mode nil) ; just to make sure
14661 (org-agenda-skip-archived-trees (memq 'archive skip))
14662 (org-agenda-skip-comment-trees (memq 'comment skip))
14663 (org-agenda-skip-function
14664 (car (org-delete-all '(comment archive) skip)))
14665 (org-tags-match-list-sublevels t)
14666 (start-level (eq scope 'region-start-level))
14667 matcher file res
14668 org-todo-keywords-for-agenda
14669 org-done-keywords-for-agenda
14670 org-todo-keyword-alist-for-agenda
14671 org-drawers-for-agenda
14672 org-tag-alist-for-agenda
14673 todo-only)
14675 (cond
14676 ((eq match t) (setq matcher t))
14677 ((eq match nil) (setq matcher t))
14678 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14680 (save-window-excursion
14681 (save-restriction
14682 (cond ((eq scope 'tree)
14683 (org-back-to-heading t)
14684 (org-narrow-to-subtree)
14685 (setq scope nil))
14686 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14687 (org-region-active-p))
14688 ;; If needed, set start-level to a string like "2"
14689 (when start-level
14690 (save-excursion
14691 (goto-char (region-beginning))
14692 (unless (org-at-heading-p) (outline-next-heading))
14693 (setq start-level (org-current-level))))
14694 (narrow-to-region (region-beginning)
14695 (save-excursion
14696 (goto-char (region-end))
14697 (unless (and (bolp) (org-at-heading-p))
14698 (outline-next-heading))
14699 (point)))
14700 (setq scope nil)))
14702 (if (not scope)
14703 (progn
14704 (org-agenda-prepare-buffers
14705 (list (buffer-file-name (current-buffer))))
14706 (setq res (org-scan-tags func matcher todo-only start-level)))
14707 ;; Get the right scope
14708 (cond
14709 ((and scope (listp scope) (symbolp (car scope)))
14710 (setq scope (eval scope)))
14711 ((eq scope 'agenda)
14712 (setq scope (org-agenda-files t)))
14713 ((eq scope 'agenda-with-archives)
14714 (setq scope (org-agenda-files t))
14715 (setq scope (org-add-archive-files scope)))
14716 ((eq scope 'file)
14717 (setq scope (list (buffer-file-name))))
14718 ((eq scope 'file-with-archives)
14719 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14720 (org-agenda-prepare-buffers scope)
14721 (while (setq file (pop scope))
14722 (with-current-buffer (org-find-base-buffer-visiting file)
14723 (save-excursion
14724 (save-restriction
14725 (widen)
14726 (goto-char (point-min))
14727 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14728 res)))
14730 ;;;; Properties
14732 ;;; Setting and retrieving properties
14734 (defconst org-special-properties
14735 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14736 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14737 "The special properties valid in Org-mode.
14739 These are properties that are not defined in the property drawer,
14740 but in some other way.")
14742 (defconst org-default-properties
14743 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14744 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14745 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14746 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14747 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14748 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14749 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14750 "Some properties that are used by Org-mode for various purposes.
14751 Being in this list makes sure that they are offered for completion.")
14753 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14754 "Regular expression matching the first line of a property drawer.")
14756 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14757 "Regular expression matching the last line of a property drawer.")
14759 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14760 "Regular expression matching the first line of a property drawer.")
14762 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14763 "Regular expression matching the first line of a property drawer.")
14765 (defconst org-property-drawer-re
14766 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14767 org-property-end-re "\\)\n?")
14768 "Matches an entire property drawer.")
14770 (defconst org-clock-drawer-re
14771 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14772 org-property-end-re "\\)\n?")
14773 "Matches an entire clock drawer.")
14775 (defsubst org-re-property (property)
14776 "Return a regexp matching a PROPERTY line.
14777 Match group 1 will be set to the value."
14778 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14780 (defsubst org-re-property-keyword (property)
14781 "Return a regexp matching a PROPERTY line, possibly with no
14782 value for the property."
14783 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14785 (defun org-property-action ()
14786 "Do an action on properties."
14787 (interactive)
14788 (let (c)
14789 (org-at-property-p)
14790 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14791 (setq c (read-char-exclusive))
14792 (cond
14793 ((equal c ?s)
14794 (call-interactively 'org-set-property))
14795 ((equal c ?d)
14796 (call-interactively 'org-delete-property))
14797 ((equal c ?D)
14798 (call-interactively 'org-delete-property-globally))
14799 ((equal c ?c)
14800 (call-interactively 'org-compute-property-at-point))
14801 (t (error "No such property action %c" c)))))
14803 (defun org-inc-effort ()
14804 "Increment the value of the effort property in the current entry."
14805 (interactive)
14806 (org-set-effort nil t))
14808 (defvar org-clock-effort) ;; Defined in org-clock.el
14809 (defvar org-clock-current-task) ;; Defined in org-clock.el
14810 (defun org-set-effort (&optional value increment)
14811 "Set the effort property of the current entry.
14812 With numerical prefix arg, use the nth allowed value, 0 stands for the
14813 10th allowed value.
14815 When INCREMENT is non-nil, set the property to the next allowed value."
14816 (interactive "P")
14817 (if (equal value 0) (setq value 10))
14818 (let* ((completion-ignore-case t)
14819 (prop org-effort-property)
14820 (cur (org-entry-get nil prop))
14821 (allowed (org-property-get-allowed-values nil prop 'table))
14822 (existing (mapcar 'list (org-property-values prop)))
14823 (heading (nth 4 (org-heading-components)))
14825 (val (cond
14826 ((stringp value) value)
14827 ((and allowed (integerp value))
14828 (or (car (nth (1- value) allowed))
14829 (car (org-last allowed))))
14830 ((and allowed increment)
14831 (or (caadr (member (list cur) allowed))
14832 (error "Allowed effort values are not set")))
14833 (allowed
14834 (message "Select 1-9,0, [RET%s]: %s"
14835 (if cur (concat "=" cur) "")
14836 (mapconcat 'car allowed " "))
14837 (setq rpl (read-char-exclusive))
14838 (if (equal rpl ?\r)
14840 (setq rpl (- rpl ?0))
14841 (if (equal rpl 0) (setq rpl 10))
14842 (if (and (> rpl 0) (<= rpl (length allowed)))
14843 (car (nth (1- rpl) allowed))
14844 (org-completing-read "Effort: " allowed nil))))
14846 (let (org-completion-use-ido org-completion-use-iswitchb)
14847 (org-completing-read
14848 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14849 (concat "[" cur "]") "")
14850 ": ")
14851 existing nil nil "" nil cur))))))
14852 (unless (equal (org-entry-get nil prop) val)
14853 (org-entry-put nil prop val))
14854 (save-excursion
14855 (org-back-to-heading t)
14856 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14857 (when (string= heading org-clock-current-task)
14858 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
14859 (org-clock-update-mode-line))
14860 (message "%s is now %s" prop val)))
14862 (defun org-at-property-p ()
14863 "Is cursor inside a property drawer?"
14864 (save-excursion
14865 (beginning-of-line 1)
14866 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14867 (save-match-data ;; Used by calling procedures
14868 (let ((p (point))
14869 (range (unless (org-before-first-heading-p)
14870 (org-get-property-block))))
14871 (and range (<= (car range) p) (< p (cdr range))))))))
14873 (defun org-get-property-block (&optional beg end force)
14874 "Return the (beg . end) range of the body of the property drawer.
14875 BEG and END are the beginning and end of the current subtree, or of
14876 the part before the first headline. If they are not given, they will
14877 be found. If the drawer does not exist and FORCE is non-nil, create
14878 the drawer."
14879 (catch 'exit
14880 (save-excursion
14881 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14882 (progn (org-back-to-heading t) (point))))
14883 (end (or end (and (not (outline-next-heading)) (point-max))
14884 (point))))
14885 (goto-char beg)
14886 (if (re-search-forward org-property-start-re end t)
14887 (setq beg (1+ (match-end 0)))
14888 (if force
14889 (save-excursion
14890 (org-insert-property-drawer)
14891 (setq end (progn (outline-next-heading) (point))))
14892 (throw 'exit nil))
14893 (goto-char beg)
14894 (if (re-search-forward org-property-start-re end t)
14895 (setq beg (1+ (match-end 0)))))
14896 (if (re-search-forward org-property-end-re end t)
14897 (setq end (match-beginning 0))
14898 (or force (throw 'exit nil))
14899 (goto-char beg)
14900 (setq end beg)
14901 (org-indent-line)
14902 (insert ":END:\n"))
14903 (cons beg end)))))
14905 (defun org-entry-properties (&optional pom which specific)
14906 "Get all properties of the entry at point-or-marker POM.
14907 This includes the TODO keyword, the tags, time strings for deadline,
14908 scheduled, and clocking, and any additional properties defined in the
14909 entry. The return value is an alist, keys may occur multiple times
14910 if the property key was used several times.
14911 POM may also be nil, in which case the current entry is used.
14912 If WHICH is nil or `all', get all properties. If WHICH is
14913 `special' or `standard', only get that subclass. If WHICH
14914 is a string only get exactly this property. SPECIFIC can be a string, the
14915 specific property we are interested in. Specifying it can speed
14916 things up because then unnecessary parsing is avoided."
14917 (setq which (or which 'all))
14918 (org-with-point-at pom
14919 (let ((clockstr (substring org-clock-string 0 -1))
14920 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14921 (case-fold-search nil)
14922 beg end range props sum-props key key1 value string clocksum clocksumt)
14923 (save-excursion
14924 (when (condition-case nil
14925 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14926 (error nil))
14927 (setq beg (point))
14928 (setq sum-props (get-text-property (point) 'org-summaries))
14929 (setq clocksum (get-text-property (point) :org-clock-minutes)
14930 clocksumt (get-text-property (point) :org-clock-minutes-today))
14931 (outline-next-heading)
14932 (setq end (point))
14933 (when (memq which '(all special))
14934 ;; Get the special properties, like TODO and tags
14935 (goto-char beg)
14936 (when (and (or (not specific) (string= specific "TODO"))
14937 (looking-at org-todo-line-regexp) (match-end 2))
14938 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14939 (when (and (or (not specific) (string= specific "PRIORITY"))
14940 (looking-at org-priority-regexp))
14941 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14942 (when (or (not specific) (string= specific "FILE"))
14943 (push (cons "FILE" buffer-file-name) props))
14944 (when (and (or (not specific) (string= specific "TAGS"))
14945 (setq value (org-get-tags-string))
14946 (string-match "\\S-" value))
14947 (push (cons "TAGS" value) props))
14948 (when (and (or (not specific) (string= specific "ALLTAGS"))
14949 (setq value (org-get-tags-at)))
14950 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14951 ":"))
14952 props))
14953 (when (or (not specific) (string= specific "BLOCKED"))
14954 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14955 (when (or (not specific)
14956 (member specific
14957 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14958 "TIMESTAMP" "TIMESTAMP_IA")))
14959 (catch 'match
14960 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14961 (setq key (if (match-end 1)
14962 (substring (org-match-string-no-properties 1)
14963 0 -1))
14964 string (if (equal key clockstr)
14965 (org-trim
14966 (buffer-substring-no-properties
14967 (match-beginning 3) (goto-char
14968 (point-at-eol))))
14969 (substring (org-match-string-no-properties 3)
14970 1 -1)))
14971 ;; Get the correct property name from the key. This is
14972 ;; necessary if the user has configured time keywords.
14973 (setq key1 (concat key ":"))
14974 (cond
14975 ((not key)
14976 (setq key
14977 (if (= (char-after (match-beginning 3)) ?\[)
14978 "TIMESTAMP_IA" "TIMESTAMP")))
14979 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14980 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14981 ((equal key1 org-closed-string) (setq key "CLOSED"))
14982 ((equal key1 org-clock-string) (setq key "CLOCK")))
14983 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14984 (progn
14985 (push (cons key string) props)
14986 ;; no need to search further if match is found
14987 (throw 'match t))
14988 (when (or (equal key "CLOCK") (not (assoc key props)))
14989 (push (cons key string) props)))))))
14991 (when (memq which '(all standard))
14992 ;; Get the standard properties, like :PROP: ...
14993 (setq range (org-get-property-block beg end))
14994 (when range
14995 (goto-char (car range))
14996 (while (re-search-forward
14997 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14998 (cdr range) t)
14999 (setq key (org-match-string-no-properties 1)
15000 value (org-trim (or (org-match-string-no-properties 2) "")))
15001 (unless (member key excluded)
15002 (push (cons key (or value "")) props)))))
15003 (if clocksum
15004 (push (cons "CLOCKSUM"
15005 (org-columns-number-to-string (/ (float clocksum) 60.)
15006 'add_times))
15007 props))
15008 (if clocksumt
15009 (push (cons "CLOCKSUM_T"
15010 (org-columns-number-to-string (/ (float clocksumt) 60.)
15011 'add_times))
15012 props))
15013 (unless (assoc "CATEGORY" props)
15014 (push (cons "CATEGORY" (org-get-category)) props))
15015 (append sum-props (nreverse props)))))))
15017 (defun org-entry-get (pom property &optional inherit literal-nil)
15018 "Get value of PROPERTY for entry or content at point-or-marker POM.
15019 If INHERIT is non-nil and the entry does not have the property,
15020 then also check higher levels of the hierarchy.
15021 If INHERIT is the symbol `selective', use inheritance only if the setting
15022 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15023 If the property is present but empty, the return value is the empty string.
15024 If the property is not present at all, nil is returned.
15026 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15027 do not interpret it as the list atom nil. This is used for inheritance
15028 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15029 (org-with-point-at pom
15030 (if (and inherit (if (eq inherit 'selective)
15031 (org-property-inherit-p property)
15033 (org-entry-get-with-inheritance property literal-nil)
15034 (if (member property org-special-properties)
15035 ;; We need a special property. Use `org-entry-properties' to
15036 ;; retrieve it, but specify the wanted property
15037 (cdr (assoc property (org-entry-properties nil 'special property)))
15038 (let ((range (org-get-property-block)))
15039 (when (and range (not (eq (car range) (cdr range))))
15040 (let* ((props (list (or (assoc property org-file-properties)
15041 (assoc property org-global-properties)
15042 (assoc property org-global-properties-fixed))))
15043 (ap (lambda (key)
15044 (when (re-search-forward
15045 (org-re-property key) (cdr range) t)
15046 (setq props
15047 (org-update-property-plist
15049 (if (match-end 1)
15050 (org-match-string-no-properties 1) "")
15051 props)))))
15052 val)
15053 (goto-char (car range))
15054 (funcall ap property)
15055 (goto-char (car range))
15056 (while (funcall ap (concat property "+")))
15057 (setq val (cdr (assoc property props)))
15058 (when val (if literal-nil val (org-not-nil val))))))))))
15060 (defun org-property-or-variable-value (var &optional inherit)
15061 "Check if there is a property fixing the value of VAR.
15062 If yes, return this value. If not, return the current value of the variable."
15063 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15064 (if (and prop (stringp prop) (string-match "\\S-" prop))
15065 (read prop)
15066 (symbol-value var))))
15068 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15069 "Delete the property PROPERTY from entry at point-or-marker POM.
15070 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15071 an empty drawer to delete."
15072 (org-with-point-at pom
15073 (if (member property org-special-properties)
15074 nil ; cannot delete these properties.
15075 (let ((range (org-get-property-block)))
15076 (if (and range
15077 (goto-char (car range))
15078 (re-search-forward
15079 (org-re-property property)
15080 (cdr range) t))
15081 (progn
15082 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15083 (and delete-empty-drawer
15084 (org-remove-empty-drawer-at
15085 delete-empty-drawer (car range)))
15087 nil)))))
15089 ;; Multi-values properties are properties that contain multiple values
15090 ;; These values are assumed to be single words, separated by whitespace.
15091 (defun org-entry-add-to-multivalued-property (pom property value)
15092 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15093 (let* ((old (org-entry-get pom property))
15094 (values (and old (org-split-string old "[ \t]"))))
15095 (setq value (org-entry-protect-space value))
15096 (unless (member value values)
15097 (setq values (cons value values))
15098 (org-entry-put pom property
15099 (mapconcat 'identity values " ")))))
15101 (defun org-entry-remove-from-multivalued-property (pom property value)
15102 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15103 (let* ((old (org-entry-get pom property))
15104 (values (and old (org-split-string old "[ \t]"))))
15105 (setq value (org-entry-protect-space value))
15106 (when (member value values)
15107 (setq values (delete value values))
15108 (org-entry-put pom property
15109 (mapconcat 'identity values " ")))))
15111 (defun org-entry-member-in-multivalued-property (pom property value)
15112 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15113 (let* ((old (org-entry-get pom property))
15114 (values (and old (org-split-string old "[ \t]"))))
15115 (setq value (org-entry-protect-space value))
15116 (member value values)))
15118 (defun org-entry-get-multivalued-property (pom property)
15119 "Return a list of values in a multivalued property."
15120 (let* ((value (org-entry-get pom property))
15121 (values (and value (org-split-string value "[ \t]"))))
15122 (mapcar 'org-entry-restore-space values)))
15124 (defun org-entry-put-multivalued-property (pom property &rest values)
15125 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15126 VALUES should be a list of strings. Spaces will be protected."
15127 (org-entry-put pom property
15128 (mapconcat 'org-entry-protect-space values " "))
15129 (let* ((value (org-entry-get pom property))
15130 (values (and value (org-split-string value "[ \t]"))))
15131 (mapcar 'org-entry-restore-space values)))
15133 (defun org-entry-protect-space (s)
15134 "Protect spaces and newline in string S."
15135 (while (string-match " " s)
15136 (setq s (replace-match "%20" t t s)))
15137 (while (string-match "\n" s)
15138 (setq s (replace-match "%0A" t t s)))
15141 (defun org-entry-restore-space (s)
15142 "Restore spaces and newline in string S."
15143 (while (string-match "%20" s)
15144 (setq s (replace-match " " t t s)))
15145 (while (string-match "%0A" s)
15146 (setq s (replace-match "\n" t t s)))
15149 (defvar org-entry-property-inherited-from (make-marker)
15150 "Marker pointing to the entry from where a property was inherited.
15151 Each call to `org-entry-get-with-inheritance' will set this marker to the
15152 location of the entry where the inheritance search matched. If there was
15153 no match, the marker will point nowhere.
15154 Note that also `org-entry-get' calls this function, if the INHERIT flag
15155 is set.")
15157 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15158 "Get PROPERTY of entry or content at point, search higher levels if needed.
15159 The search will stop at the first ancestor which has the property defined.
15160 If the value found is \"nil\", return nil to show that the property
15161 should be considered as undefined (this is the meaning of nil here).
15162 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15163 (move-marker org-entry-property-inherited-from nil)
15164 (let (tmp)
15165 (save-excursion
15166 (save-restriction
15167 (widen)
15168 (catch 'ex
15169 (while t
15170 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15171 (or (ignore-errors (org-back-to-heading t))
15172 (goto-char (point-min)))
15173 (move-marker org-entry-property-inherited-from (point))
15174 (throw 'ex tmp))
15175 (or (ignore-errors (org-up-heading-safe))
15176 (throw 'ex nil))))))
15177 (setq tmp (or tmp
15178 (cdr (assoc property org-file-properties))
15179 (cdr (assoc property org-global-properties))
15180 (cdr (assoc property org-global-properties-fixed))))
15181 (if literal-nil tmp (org-not-nil tmp))))
15183 (defvar org-property-changed-functions nil
15184 "Hook called when the value of a property has changed.
15185 Each hook function should accept two arguments, the name of the property
15186 and the new value.")
15188 (defun org-entry-put (pom property value)
15189 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15190 (org-with-point-at pom
15191 (org-back-to-heading t)
15192 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15193 range)
15194 (cond
15195 ((equal property "TODO")
15196 (when (and (stringp value) (string-match "\\S-" value)
15197 (not (member value org-todo-keywords-1)))
15198 (error "\"%s\" is not a valid TODO state" value))
15199 (if (or (not value)
15200 (not (string-match "\\S-" value)))
15201 (setq value 'none))
15202 (org-todo value)
15203 (org-set-tags nil 'align))
15204 ((equal property "PRIORITY")
15205 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15206 (string-to-char value) ?\ ))
15207 (org-set-tags nil 'align))
15208 ((equal property "CLOCKSUM")
15209 (if (not (re-search-forward
15210 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15211 (error "Cannot find a clock log")
15212 (goto-char (- (match-end 1) 2))
15213 (cond
15214 ((eq value 'earlier) (org-timestamp-down))
15215 ((eq value 'later) (org-timestamp-up)))
15216 (org-clock-sum-current-item)))
15217 ((equal property "SCHEDULED")
15218 (if (re-search-forward org-scheduled-time-regexp end t)
15219 (cond
15220 ((eq value 'earlier) (org-timestamp-change -1 'day))
15221 ((eq value 'later) (org-timestamp-change 1 'day))
15222 (t (call-interactively 'org-schedule)))
15223 (call-interactively 'org-schedule)))
15224 ((equal property "DEADLINE")
15225 (if (re-search-forward org-deadline-time-regexp end t)
15226 (cond
15227 ((eq value 'earlier) (org-timestamp-change -1 'day))
15228 ((eq value 'later) (org-timestamp-change 1 'day))
15229 (t (call-interactively 'org-deadline)))
15230 (call-interactively 'org-deadline)))
15231 ((member property org-special-properties)
15232 (error "The %s property can not yet be set with `org-entry-put'"
15233 property))
15234 (t ; a non-special property
15235 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15236 (setq range (org-get-property-block beg end 'force))
15237 (goto-char (car range))
15238 (if (re-search-forward
15239 (org-re-property-keyword property) (cdr range) t)
15240 (progn
15241 (delete-region (match-beginning 0) (match-end 0))
15242 (goto-char (match-beginning 0)))
15243 (goto-char (cdr range))
15244 (insert "\n")
15245 (backward-char 1)
15246 (org-indent-line))
15247 (insert ":" property ":")
15248 (and value (insert " " value))
15249 (org-indent-line)))))
15250 (run-hook-with-args 'org-property-changed-functions property value)))
15252 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15253 "Get all property keys in the current buffer.
15254 With INCLUDE-SPECIALS, also list the special properties that reflect things
15255 like tags and TODO state.
15256 With INCLUDE-DEFAULTS, also include properties that has special meaning
15257 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15258 and others.
15259 With INCLUDE-COLUMNS, also include property names given in COLUMN
15260 formats in the current buffer."
15261 (let (rtn range cfmt s p)
15262 (save-excursion
15263 (save-restriction
15264 (widen)
15265 (goto-char (point-min))
15266 (while (re-search-forward org-property-start-re nil t)
15267 (setq range (org-get-property-block))
15268 (goto-char (car range))
15269 (while (re-search-forward
15270 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15271 (cdr range) t)
15272 (add-to-list 'rtn (org-match-string-no-properties 1)))
15273 (outline-next-heading))))
15275 (when include-specials
15276 (setq rtn (append org-special-properties rtn)))
15278 (when include-defaults
15279 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15280 (add-to-list 'rtn org-effort-property))
15282 (when include-columns
15283 (save-excursion
15284 (save-restriction
15285 (widen)
15286 (goto-char (point-min))
15287 (while (re-search-forward
15288 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15289 nil t)
15290 (setq cfmt (match-string 2) s 0)
15291 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15292 cfmt s)
15293 (setq s (match-end 0)
15294 p (match-string 1 cfmt))
15295 (unless (or (equal p "ITEM")
15296 (member p org-special-properties))
15297 (add-to-list 'rtn (match-string 1 cfmt))))))))
15299 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15301 (defun org-property-values (key)
15302 "Return a list of all values of property KEY in the current buffer."
15303 (save-excursion
15304 (save-restriction
15305 (widen)
15306 (goto-char (point-min))
15307 (let ((re (org-re-property key))
15308 values)
15309 (while (re-search-forward re nil t)
15310 (add-to-list 'values (org-trim (match-string 1))))
15311 (delete "" values)))))
15313 (defun org-insert-property-drawer ()
15314 "Insert a property drawer into the current entry."
15315 (org-back-to-heading t)
15316 (looking-at org-outline-regexp)
15317 (let ((indent (if org-adapt-indentation
15318 (- (match-end 0) (match-beginning 0))
15320 (beg (point))
15321 (re (concat "^[ \t]*" org-keyword-time-regexp))
15322 end hiddenp)
15323 (outline-next-heading)
15324 (setq end (point))
15325 (goto-char beg)
15326 (while (re-search-forward re end t))
15327 (setq hiddenp (outline-invisible-p))
15328 (end-of-line 1)
15329 (and (equal (char-after) ?\n) (forward-char 1))
15330 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15331 (if (member (match-string 1) '("CLOCK:" ":END:"))
15332 ;; just skip this line
15333 (beginning-of-line 2)
15334 ;; Drawer start, find the end
15335 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15336 (beginning-of-line 1)))
15337 (org-skip-over-state-notes)
15338 (skip-chars-backward " \t\n\r")
15339 (if (eq (char-before) ?*) (forward-char 1))
15340 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15341 (beginning-of-line 0)
15342 (org-indent-to-column indent)
15343 (beginning-of-line 2)
15344 (org-indent-to-column indent)
15345 (beginning-of-line 0)
15346 (if hiddenp
15347 (save-excursion
15348 (org-back-to-heading t)
15349 (hide-entry))
15350 (org-flag-drawer t))))
15352 (defun org-insert-drawer (&optional arg drawer)
15353 "Insert a drawer at point.
15355 Optional argument DRAWER, when non-nil, is a string representing
15356 drawer's name. Otherwise, the user is prompted for a name.
15358 If a region is active, insert the drawer around that region
15359 instead.
15361 Point is left between drawer's boundaries."
15362 (interactive "P")
15363 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15364 "LOGBOOK"))
15365 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15366 ;; internally by Org. They are meant to be inserted
15367 ;; automatically.
15368 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15369 ;; Remove system drawers from list. Note: For some reason,
15370 ;; `org-completing-read' ignores the predicate while
15371 ;; `completing-read' handles it fine.
15372 (drawer (if arg "PROPERTIES"
15373 (or drawer
15374 (completing-read
15375 "Drawer: " org-drawers
15376 (lambda (d) (not (member d system-drawers))))))))
15377 (cond
15378 ;; With C-u, fall back on `org-insert-property-drawer'
15379 (arg (org-insert-property-drawer))
15380 ;; With an active region, insert a drawer at point.
15381 ((not (org-region-active-p))
15382 (progn
15383 (unless (bolp) (insert "\n"))
15384 (insert (format ":%s:\n\n:END:\n" drawer))
15385 (forward-line -2)))
15386 ;; Otherwise, insert the drawer at point
15388 (let ((rbeg (region-beginning))
15389 (rend (copy-marker (region-end))))
15390 (unwind-protect
15391 (progn
15392 (goto-char rbeg)
15393 (beginning-of-line)
15394 (when (save-excursion
15395 (re-search-forward org-outline-regexp-bol rend t))
15396 (error "Drawers cannot contain headlines"))
15397 ;; Position point at the beginning of the first
15398 ;; non-blank line in region. Insert drawer's opening
15399 ;; there, then indent it.
15400 (org-skip-whitespace)
15401 (beginning-of-line)
15402 (insert ":" drawer ":\n")
15403 (forward-line -1)
15404 (indent-for-tab-command)
15405 ;; Move point to the beginning of the first blank line
15406 ;; after the last non-blank line in region. Insert
15407 ;; drawer's closing, then indent it.
15408 (goto-char rend)
15409 (skip-chars-backward " \r\t\n")
15410 (insert "\n:END:")
15411 (deactivate-mark t)
15412 (indent-for-tab-command)
15413 (unless (eolp) (insert "\n")))
15414 ;; Clear marker, whatever the outcome of insertion is.
15415 (set-marker rend nil)))))))
15417 (defvar org-property-set-functions-alist nil
15418 "Property set function alist.
15419 Each entry should have the following format:
15421 (PROPERTY . READ-FUNCTION)
15423 The read function will be called with the same argument as
15424 `org-completing-read'.")
15426 (defun org-set-property-function (property)
15427 "Get the function that should be used to set PROPERTY.
15428 This is computed according to `org-property-set-functions-alist'."
15429 (or (cdr (assoc property org-property-set-functions-alist))
15430 'org-completing-read))
15432 (defun org-read-property-value (property)
15433 "Read PROPERTY value from user."
15434 (let* ((completion-ignore-case t)
15435 (allowed (org-property-get-allowed-values nil property 'table))
15436 (cur (org-entry-get nil property))
15437 (prompt (concat property " value"
15438 (if (and cur (string-match "\\S-" cur))
15439 (concat " [" cur "]") "") ": "))
15440 (set-function (org-set-property-function property))
15441 (val (if allowed
15442 (funcall set-function prompt allowed nil
15443 (not (get-text-property 0 'org-unrestricted
15444 (caar allowed))))
15445 (let (org-completion-use-ido org-completion-use-iswitchb)
15446 (funcall set-function prompt
15447 (mapcar 'list (org-property-values property))
15448 nil nil "" nil cur)))))
15449 (if (equal val "")
15451 val)))
15453 (defvar org-last-set-property nil)
15454 (defvar org-last-set-property-value nil)
15455 (defun org-read-property-name ()
15456 "Read a property name."
15457 (let* ((completion-ignore-case t)
15458 (keys (org-buffer-property-keys nil t t))
15459 (default-prop (or (save-excursion
15460 (save-match-data
15461 (beginning-of-line)
15462 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15463 (null (string= (match-string 1) "END"))
15464 (match-string 1))))
15465 org-last-set-property))
15466 (property (org-icompleting-read
15467 (concat "Property"
15468 (if default-prop (concat " [" default-prop "]") "")
15469 ": ")
15470 (mapcar 'list keys)
15471 nil nil nil nil
15472 default-prop)))
15473 (if (member property keys)
15474 property
15475 (or (cdr (assoc (downcase property)
15476 (mapcar (lambda (x) (cons (downcase x) x))
15477 keys)))
15478 property))))
15480 (defun org-set-property-and-value (use-last)
15481 "Allow to set [PROPERTY]: [value] direction from prompt.
15482 When use-default, don't even ask, just use the last
15483 \"[PROPERTY]: [value]\" string from the history."
15484 (interactive "P")
15485 (let* ((completion-ignore-case t)
15486 (pv (or (and use-last org-last-set-property-value)
15487 (org-completing-read
15488 "Enter a \"[Property]: [value]\" pair: "
15489 nil nil nil nil nil
15490 org-last-set-property-value)))
15491 prop val)
15492 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15493 (setq prop (match-string 1 pv)
15494 val (match-string 2 pv))
15495 (org-set-property prop val))))
15497 (defun org-set-property (property value)
15498 "In the current entry, set PROPERTY to VALUE.
15499 When called interactively, this will prompt for a property name, offering
15500 completion on existing and default properties. And then it will prompt
15501 for a value, offering completion either on allowed values (via an inherited
15502 xxx_ALL property) or on existing values in other instances of this property
15503 in the current file."
15504 (interactive (list nil nil))
15505 (let* ((property (or property (org-read-property-name)))
15506 (value (or value (org-read-property-value property)))
15507 (fn (cdr (assoc property org-properties-postprocess-alist))))
15508 (setq org-last-set-property property)
15509 (setq org-last-set-property-value (concat property ": " value))
15510 ;; Possibly postprocess the inserted value:
15511 (when fn (setq value (funcall fn value)))
15512 (unless (equal (org-entry-get nil property) value)
15513 (org-entry-put nil property value))))
15515 (defun org-delete-property (property &optional delete-empty-drawer)
15516 "In the current entry, delete PROPERTY.
15517 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15518 an empty drawer to delete."
15519 (interactive
15520 (let* ((completion-ignore-case t)
15521 (prop (org-icompleting-read "Property: "
15522 (org-entry-properties nil 'standard))))
15523 (list prop)))
15524 (message "Property %s %s" property
15525 (if (org-entry-delete nil property delete-empty-drawer)
15526 "deleted"
15527 "was not present in the entry")))
15529 (defun org-delete-property-globally (property)
15530 "Remove PROPERTY globally, from all entries."
15531 (interactive
15532 (let* ((completion-ignore-case t)
15533 (prop (org-icompleting-read
15534 "Globally remove property: "
15535 (mapcar 'list (org-buffer-property-keys)))))
15536 (list prop)))
15537 (save-excursion
15538 (save-restriction
15539 (widen)
15540 (goto-char (point-min))
15541 (let ((cnt 0))
15542 (while (re-search-forward
15543 (org-re-property property)
15544 nil t)
15545 (setq cnt (1+ cnt))
15546 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15547 (message "Property \"%s\" removed from %d entries" property cnt)))))
15549 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15551 (defun org-compute-property-at-point ()
15552 "Compute the property at point.
15553 This looks for an enclosing column format, extracts the operator and
15554 then applies it to the property in the column format's scope."
15555 (interactive)
15556 (unless (org-at-property-p)
15557 (error "Not at a property"))
15558 (let ((prop (org-match-string-no-properties 2)))
15559 (org-columns-get-format-and-top-level)
15560 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15561 (error "No operator defined for property %s" prop))
15562 (org-columns-compute prop)))
15564 (defvar org-property-allowed-value-functions nil
15565 "Hook for functions supplying allowed values for a specific property.
15566 The functions must take a single argument, the name of the property, and
15567 return a flat list of allowed values. If \":ETC\" is one of
15568 the values, this means that these values are intended as defaults for
15569 completion, but that other values should be allowed too.
15570 The functions must return nil if they are not responsible for this
15571 property.")
15573 (defun org-property-get-allowed-values (pom property &optional table)
15574 "Get allowed values for the property PROPERTY.
15575 When TABLE is non-nil, return an alist that can directly be used for
15576 completion."
15577 (let (vals)
15578 (cond
15579 ((equal property "TODO")
15580 (setq vals (org-with-point-at pom
15581 (append org-todo-keywords-1 '("")))))
15582 ((equal property "PRIORITY")
15583 (let ((n org-lowest-priority))
15584 (while (>= n org-highest-priority)
15585 (push (char-to-string n) vals)
15586 (setq n (1- n)))))
15587 ((member property org-special-properties))
15588 ((setq vals (run-hook-with-args-until-success
15589 'org-property-allowed-value-functions property)))
15591 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15592 (when (and vals (string-match "\\S-" vals))
15593 (setq vals (car (read-from-string (concat "(" vals ")"))))
15594 (setq vals (mapcar (lambda (x)
15595 (cond ((stringp x) x)
15596 ((numberp x) (number-to-string x))
15597 ((symbolp x) (symbol-name x))
15598 (t "???")))
15599 vals)))))
15600 (when (member ":ETC" vals)
15601 (setq vals (remove ":ETC" vals))
15602 (org-add-props (car vals) '(org-unrestricted t)))
15603 (if table (mapcar 'list vals) vals)))
15605 (defun org-property-previous-allowed-value (&optional previous)
15606 "Switch to the next allowed value for this property."
15607 (interactive)
15608 (org-property-next-allowed-value t))
15610 (defun org-property-next-allowed-value (&optional previous)
15611 "Switch to the next allowed value for this property."
15612 (interactive)
15613 (unless (org-at-property-p)
15614 (error "Not at a property"))
15615 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15616 (key (match-string 2))
15617 (value (match-string 3))
15618 (allowed (or (org-property-get-allowed-values (point) key)
15619 (and (member value '("[ ]" "[-]" "[X]"))
15620 '("[ ]" "[X]"))))
15621 (heading (save-match-data (nth 4 (org-heading-components))))
15622 nval)
15623 (unless allowed
15624 (error "Allowed values for this property have not been defined"))
15625 (if previous (setq allowed (reverse allowed)))
15626 (if (member value allowed)
15627 (setq nval (car (cdr (member value allowed)))))
15628 (setq nval (or nval (car allowed)))
15629 (if (equal nval value)
15630 (error "Only one allowed value for this property"))
15631 (org-at-property-p)
15632 (replace-match (concat " :" key ": " nval) t t)
15633 (org-indent-line)
15634 (beginning-of-line 1)
15635 (skip-chars-forward " \t")
15636 (when (equal prop org-effort-property)
15637 (save-excursion
15638 (org-back-to-heading t)
15639 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15640 (when (string= org-clock-current-task heading)
15641 (setq org-clock-effort nval)
15642 (org-clock-update-mode-line)))
15643 (run-hook-with-args 'org-property-changed-functions key nval)))
15645 (defun org-find-olp (path &optional this-buffer)
15646 "Return a marker pointing to the entry at outline path OLP.
15647 If anything goes wrong, throw an error.
15648 You can wrap this call to catch the error like this:
15650 (condition-case msg
15651 (org-mobile-locate-entry (match-string 4))
15652 (error (nth 1 msg)))
15654 The return value will then be either a string with the error message,
15655 or a marker if everything is OK.
15657 If THIS-BUFFER is set, the outline path does not contain a file,
15658 only headings."
15659 (let* ((file (if this-buffer buffer-file-name (pop path)))
15660 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15661 (level 1)
15662 (lmin 1)
15663 (lmax 1)
15664 limit re end found pos heading cnt flevel)
15665 (unless buffer (error "File not found :%s" file))
15666 (with-current-buffer buffer
15667 (save-excursion
15668 (save-restriction
15669 (widen)
15670 (setq limit (point-max))
15671 (goto-char (point-min))
15672 (while (setq heading (pop path))
15673 (setq re (format org-complex-heading-regexp-format
15674 (regexp-quote heading)))
15675 (setq cnt 0 pos (point))
15676 (while (re-search-forward re end t)
15677 (setq level (- (match-end 1) (match-beginning 1)))
15678 (if (and (>= level lmin) (<= level lmax))
15679 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15680 (when (= cnt 0) (error "Heading not found on level %d: %s"
15681 lmax heading))
15682 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15683 lmax heading))
15684 (goto-char found)
15685 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15686 (setq end (save-excursion (org-end-of-subtree t t))))
15687 (when (org-at-heading-p)
15688 (point-marker)))))))
15690 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15691 "Find node HEADING in BUFFER.
15692 Return a marker to the heading if it was found, or nil if not.
15693 If POS-ONLY is set, return just the position instead of a marker.
15695 The heading text must match exact, but it may have a TODO keyword,
15696 a priority cookie and tags in the standard locations."
15697 (with-current-buffer (or buffer (current-buffer))
15698 (save-excursion
15699 (save-restriction
15700 (widen)
15701 (goto-char (point-min))
15702 (let (case-fold-search)
15703 (if (re-search-forward
15704 (format org-complex-heading-regexp-format
15705 (regexp-quote heading)) nil t)
15706 (if pos-only
15707 (match-beginning 0)
15708 (move-marker (make-marker) (match-beginning 0)))))))))
15710 (defun org-find-exact-heading-in-directory (heading &optional dir)
15711 "Find Org node headline HEADING in all .org files in directory DIR.
15712 When the target headline is found, return a marker to this location."
15713 (let ((files (directory-files (or dir default-directory)
15714 nil "\\`[^.#].*\\.org\\'"))
15715 file visiting m buffer)
15716 (catch 'found
15717 (while (setq file (pop files))
15718 (message "trying %s" file)
15719 (setq visiting (org-find-base-buffer-visiting file))
15720 (setq buffer (or visiting (find-file-noselect file)))
15721 (setq m (org-find-exact-headline-in-buffer
15722 heading buffer))
15723 (when (and (not m) (not visiting)) (kill-buffer buffer))
15724 (and m (throw 'found m))))))
15726 (defun org-find-entry-with-id (ident)
15727 "Locate the entry that contains the ID property with exact value IDENT.
15728 IDENT can be a string, a symbol or a number, this function will search for
15729 the string representation of it.
15730 Return the position where this entry starts, or nil if there is no such entry."
15731 (interactive "sID: ")
15732 (let ((id (cond
15733 ((stringp ident) ident)
15734 ((symbol-name ident) (symbol-name ident))
15735 ((numberp ident) (number-to-string ident))
15736 (t (error "IDENT %s must be a string, symbol or number" ident))))
15737 (case-fold-search nil))
15738 (save-excursion
15739 (save-restriction
15740 (widen)
15741 (goto-char (point-min))
15742 (when (re-search-forward
15743 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15744 nil t)
15745 (org-back-to-heading t)
15746 (point))))))
15748 ;;;; Timestamps
15750 (defvar org-last-changed-timestamp nil)
15751 (defvar org-last-inserted-timestamp nil
15752 "The last time stamp inserted with `org-insert-time-stamp'.")
15753 (defvar org-time-was-given) ; dynamically scoped parameter
15754 (defvar org-end-time-was-given) ; dynamically scoped parameter
15755 (defvar org-ts-what) ; dynamically scoped parameter
15757 (defun org-time-stamp (arg &optional inactive)
15758 "Prompt for a date/time and insert a time stamp.
15759 If the user specifies a time like HH:MM or if this command is
15760 called with at least one prefix argument, the time stamp contains
15761 the date and the time. Otherwise, only the date is be included.
15763 All parts of a date not specified by the user is filled in from
15764 the current date/time. So if you just press return without
15765 typing anything, the time stamp will represent the current
15766 date/time.
15768 If there is already a timestamp at the cursor, it will be
15769 modified.
15771 With two universal prefix arguments, insert an active timestamp
15772 with the current time without prompting the user."
15773 (interactive "P")
15774 (let* ((ts nil)
15775 (default-time
15776 ;; Default time is either today, or, when entering a range,
15777 ;; the range start.
15778 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15779 (save-excursion
15780 (re-search-backward
15781 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15782 (- (point) 20) t)))
15783 (apply 'encode-time (org-parse-time-string (match-string 1)))
15784 (current-time)))
15785 (default-input (and ts (org-get-compact-tod ts)))
15786 (repeater (save-excursion
15787 (save-match-data
15788 (beginning-of-line)
15789 (when (re-search-forward
15790 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15791 (save-excursion (progn (end-of-line) (point))) t)
15792 (match-string 0)))))
15793 org-time-was-given org-end-time-was-given time)
15794 (cond
15795 ((and (org-at-timestamp-p t)
15796 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15797 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15798 (insert "--")
15799 (setq time (let ((this-command this-command))
15800 (org-read-date arg 'totime nil nil
15801 default-time default-input inactive)))
15802 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15803 ((org-at-timestamp-p t)
15804 (setq time (let ((this-command this-command))
15805 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15806 (when (org-at-timestamp-p t) ; just to get the match data
15807 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15808 (replace-match "")
15809 (setq org-last-changed-timestamp
15810 (org-insert-time-stamp
15811 time (or org-time-was-given arg)
15812 inactive nil nil (list org-end-time-was-given)))
15813 (when repeater (goto-char (1- (point))) (insert " " repeater)
15814 (setq org-last-changed-timestamp
15815 (concat (substring org-last-inserted-timestamp 0 -1)
15816 " " repeater ">"))))
15817 (message "Timestamp updated"))
15818 ((equal arg '(16))
15819 (org-insert-time-stamp (current-time) t))
15821 (setq time (let ((this-command this-command))
15822 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15823 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15824 nil nil (list org-end-time-was-given))))))
15826 ;; FIXME: can we use this for something else, like computing time differences?
15827 (defun org-get-compact-tod (s)
15828 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15829 (let* ((t1 (match-string 1 s))
15830 (h1 (string-to-number (match-string 2 s)))
15831 (m1 (string-to-number (match-string 3 s)))
15832 (t2 (and (match-end 4) (match-string 5 s)))
15833 (h2 (and t2 (string-to-number (match-string 6 s))))
15834 (m2 (and t2 (string-to-number (match-string 7 s))))
15835 dh dm)
15836 (if (not t2)
15838 (setq dh (- h2 h1) dm (- m2 m1))
15839 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15840 (concat t1 "+" (number-to-string dh)
15841 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15843 (defun org-time-stamp-inactive (&optional arg)
15844 "Insert an inactive time stamp.
15845 An inactive time stamp is enclosed in square brackets instead of angle
15846 brackets. It is inactive in the sense that it does not trigger agenda entries,
15847 does not link to the calendar and cannot be changed with the S-cursor keys.
15848 So these are more for recording a certain time/date."
15849 (interactive "P")
15850 (org-time-stamp arg 'inactive))
15852 (defvar org-date-ovl (make-overlay 1 1))
15853 (overlay-put org-date-ovl 'face 'org-date-selected)
15854 (org-detach-overlay org-date-ovl)
15856 (defvar org-ans1) ; dynamically scoped parameter
15857 (defvar org-ans2) ; dynamically scoped parameter
15859 (defvar org-plain-time-of-day-regexp) ; defined below
15861 (defvar org-overriding-default-time nil) ; dynamically scoped
15862 (defvar org-read-date-overlay nil)
15863 (defvar org-dcst nil) ; dynamically scoped
15864 (defvar org-read-date-history nil)
15865 (defvar org-read-date-final-answer nil)
15866 (defvar org-read-date-analyze-futurep nil)
15867 (defvar org-read-date-analyze-forced-year nil)
15868 (defvar org-read-date-inactive)
15870 (defvar org-read-date-minibuffer-local-map
15871 (let ((map (make-sparse-keymap)))
15872 (set-keymap-parent map minibuffer-local-map)
15873 (org-defkey map (kbd ".")
15874 (lambda () (interactive)
15875 (org-eval-in-calendar '(calendar-goto-today))))
15876 (org-defkey map [(meta shift left)]
15877 (lambda () (interactive)
15878 (org-eval-in-calendar '(calendar-backward-month 1))))
15879 (org-defkey map [(meta shift right)]
15880 (lambda () (interactive)
15881 (org-eval-in-calendar '(calendar-forward-month 1))))
15882 (org-defkey map [(meta shift up)]
15883 (lambda () (interactive)
15884 (org-eval-in-calendar '(calendar-backward-year 1))))
15885 (org-defkey map [(meta shift down)]
15886 (lambda () (interactive)
15887 (org-eval-in-calendar '(calendar-forward-year 1))))
15888 (org-defkey map [?\e (shift left)]
15889 (lambda () (interactive)
15890 (org-eval-in-calendar '(calendar-backward-month 1))))
15891 (org-defkey map [?\e (shift right)]
15892 (lambda () (interactive)
15893 (org-eval-in-calendar '(calendar-forward-month 1))))
15894 (org-defkey map [?\e (shift up)]
15895 (lambda () (interactive)
15896 (org-eval-in-calendar '(calendar-backward-year 1))))
15897 (org-defkey map [?\e (shift down)]
15898 (lambda () (interactive)
15899 (org-eval-in-calendar '(calendar-forward-year 1))))
15900 (org-defkey map [(shift up)]
15901 (lambda () (interactive)
15902 (org-eval-in-calendar '(calendar-backward-week 1))))
15903 (org-defkey map [(shift down)]
15904 (lambda () (interactive)
15905 (org-eval-in-calendar '(calendar-forward-week 1))))
15906 (org-defkey map [(shift left)]
15907 (lambda () (interactive)
15908 (org-eval-in-calendar '(calendar-backward-day 1))))
15909 (org-defkey map [(shift right)]
15910 (lambda () (interactive)
15911 (org-eval-in-calendar '(calendar-forward-day 1))))
15912 (org-defkey map "!"
15913 (lambda () (interactive)
15914 (org-eval-in-calendar '(diary-view-entries))
15915 (message "")))
15916 (org-defkey map ">"
15917 (lambda () (interactive)
15918 (org-eval-in-calendar '(scroll-calendar-left 1))))
15919 (org-defkey map "<"
15920 (lambda () (interactive)
15921 (org-eval-in-calendar '(scroll-calendar-right 1))))
15922 (org-defkey map "\C-v"
15923 (lambda () (interactive)
15924 (org-eval-in-calendar
15925 '(calendar-scroll-left-three-months 1))))
15926 (org-defkey map "\M-v"
15927 (lambda () (interactive)
15928 (org-eval-in-calendar
15929 '(calendar-scroll-right-three-months 1))))
15930 map)
15931 "Keymap for minibuffer commands when using `org-read-date'.")
15933 (defun org-read-date (&optional org-with-time to-time from-string prompt
15934 default-time default-input inactive)
15935 "Read a date, possibly a time, and make things smooth for the user.
15936 The prompt will suggest to enter an ISO date, but you can also enter anything
15937 which will at least partially be understood by `parse-time-string'.
15938 Unrecognized parts of the date will default to the current day, month, year,
15939 hour and minute. If this command is called to replace a timestamp at point,
15940 or to enter the second timestamp of a range, the default time is taken
15941 from the existing stamp. Furthermore, the command prefers the future,
15942 so if you are giving a date where the year is not given, and the day-month
15943 combination is already past in the current year, it will assume you
15944 mean next year. For details, see the manual. A few examples:
15946 3-2-5 --> 2003-02-05
15947 feb 15 --> currentyear-02-15
15948 2/15 --> currentyear-02-15
15949 sep 12 9 --> 2009-09-12
15950 12:45 --> today 12:45
15951 22 sept 0:34 --> currentyear-09-22 0:34
15952 12 --> currentyear-currentmonth-12
15953 Fri --> nearest Friday (today or later)
15954 etc.
15956 Furthermore you can specify a relative date by giving, as the *first* thing
15957 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15958 change in days weeks, months, years.
15959 With a single plus or minus, the date is relative to today. With a double
15960 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15961 +4d --> four days from today
15962 +4 --> same as above
15963 +2w --> two weeks from today
15964 ++5 --> five days from default date
15966 The function understands only English month and weekday abbreviations.
15968 While prompting, a calendar is popped up - you can also select the
15969 date with the mouse (button 1). The calendar shows a period of three
15970 months. To scroll it to other months, use the keys `>' and `<'.
15971 If you don't like the calendar, turn it off with
15972 \(setq org-read-date-popup-calendar nil)
15974 With optional argument TO-TIME, the date will immediately be converted
15975 to an internal time.
15976 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15977 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15978 still enter a time, and this function will inform the calling routine
15979 about this change. The calling routine may then choose to change the
15980 format used to insert the time stamp into the buffer to include the time.
15981 With optional argument FROM-STRING, read from this string instead from
15982 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15983 the time/date that is used for everything that is not specified by the
15984 user."
15985 (require 'parse-time)
15986 (let* ((org-time-stamp-rounding-minutes
15987 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15988 (org-dcst org-display-custom-times)
15989 (ct (org-current-time))
15990 (org-def (or org-overriding-default-time default-time ct))
15991 (org-defdecode (decode-time org-def))
15992 (dummy (progn
15993 (when (< (nth 2 org-defdecode) org-extend-today-until)
15994 (setcar (nthcdr 2 org-defdecode) -1)
15995 (setcar (nthcdr 1 org-defdecode) 59)
15996 (setq org-def (apply 'encode-time org-defdecode)
15997 org-defdecode (decode-time org-def)))))
15998 (mouse-autoselect-window nil) ; Don't let the mouse jump
15999 (calendar-frame-setup nil)
16000 (calendar-setup nil)
16001 (calendar-move-hook nil)
16002 (calendar-view-diary-initially-flag nil)
16003 (calendar-view-holidays-initially-flag nil)
16004 (timestr (format-time-string
16005 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16006 (prompt (concat (if prompt (concat prompt " ") "")
16007 (format "Date+time [%s]: " timestr)))
16008 ans (org-ans0 "") org-ans1 org-ans2 final)
16010 (cond
16011 (from-string (setq ans from-string))
16012 (org-read-date-popup-calendar
16013 (save-excursion
16014 (save-window-excursion
16015 (calendar)
16016 (org-eval-in-calendar '(setq cursor-type nil) t)
16017 (unwind-protect
16018 (progn
16019 (calendar-forward-day (- (time-to-days org-def)
16020 (calendar-absolute-from-gregorian
16021 (calendar-current-date))))
16022 (org-eval-in-calendar nil t)
16023 (let* ((old-map (current-local-map))
16024 (map (copy-keymap calendar-mode-map))
16025 (minibuffer-local-map
16026 (copy-keymap org-read-date-minibuffer-local-map)))
16027 (org-defkey map (kbd "RET") 'org-calendar-select)
16028 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16029 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16030 (unwind-protect
16031 (progn
16032 (use-local-map map)
16033 (setq org-read-date-inactive inactive)
16034 (add-hook 'post-command-hook 'org-read-date-display)
16035 (setq org-ans0 (read-string prompt default-input
16036 'org-read-date-history nil))
16037 ;; org-ans0: from prompt
16038 ;; org-ans1: from mouse click
16039 ;; org-ans2: from calendar motion
16040 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16041 (remove-hook 'post-command-hook 'org-read-date-display)
16042 (use-local-map old-map)
16043 (when org-read-date-overlay
16044 (delete-overlay org-read-date-overlay)
16045 (setq org-read-date-overlay nil)))))
16046 (bury-buffer "*Calendar*")))))
16048 (t ; Naked prompt only
16049 (unwind-protect
16050 (setq ans (read-string prompt default-input
16051 'org-read-date-history timestr))
16052 (when org-read-date-overlay
16053 (delete-overlay org-read-date-overlay)
16054 (setq org-read-date-overlay nil)))))
16056 (setq final (org-read-date-analyze ans org-def org-defdecode))
16058 (when org-read-date-analyze-forced-year
16059 (message "Year was forced into %s"
16060 (if org-read-date-force-compatible-dates
16061 "compatible range (1970-2037)"
16062 "range representable on this machine"))
16063 (ding))
16065 ;; One round trip to get rid of 34th of August and stuff like that....
16066 (setq final (decode-time (apply 'encode-time final)))
16068 (setq org-read-date-final-answer ans)
16070 (if to-time
16071 (apply 'encode-time final)
16072 (if (and (boundp 'org-time-was-given) org-time-was-given)
16073 (format "%04d-%02d-%02d %02d:%02d"
16074 (nth 5 final) (nth 4 final) (nth 3 final)
16075 (nth 2 final) (nth 1 final))
16076 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16078 (defvar org-def)
16079 (defvar org-defdecode)
16080 (defvar org-with-time)
16081 (defun org-read-date-display ()
16082 "Display the current date prompt interpretation in the minibuffer."
16083 (when org-read-date-display-live
16084 (when org-read-date-overlay
16085 (delete-overlay org-read-date-overlay))
16086 (when (minibufferp (current-buffer))
16087 (save-excursion
16088 (end-of-line 1)
16089 (while (not (equal (buffer-substring
16090 (max (point-min) (- (point) 4)) (point))
16091 " "))
16092 (insert " ")))
16093 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16094 " " (or org-ans1 org-ans2)))
16095 (org-end-time-was-given nil)
16096 (f (org-read-date-analyze ans org-def org-defdecode))
16097 (fmts (if org-dcst
16098 org-time-stamp-custom-formats
16099 org-time-stamp-formats))
16100 (fmt (if (or org-with-time
16101 (and (boundp 'org-time-was-given) org-time-was-given))
16102 (cdr fmts)
16103 (car fmts)))
16104 (txt (format-time-string fmt (apply 'encode-time f)))
16105 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16106 (txt (concat "=> " txt)))
16107 (when (and org-end-time-was-given
16108 (string-match org-plain-time-of-day-regexp txt))
16109 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16110 org-end-time-was-given
16111 (substring txt (match-end 0)))))
16112 (when org-read-date-analyze-futurep
16113 (setq txt (concat txt " (=>F)")))
16114 (setq org-read-date-overlay
16115 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16116 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16118 (defun org-read-date-analyze (ans org-def org-defdecode)
16119 "Analyze the combined answer of the date prompt."
16120 ;; FIXME: cleanup and comment
16121 (let ((nowdecode (decode-time (current-time)))
16122 delta deltan deltaw deltadef year month day
16123 hour minute second wday pm h2 m2 tl wday1
16124 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16125 (setq org-read-date-analyze-futurep nil
16126 org-read-date-analyze-forced-year nil)
16127 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16128 (setq ans "+0"))
16130 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16131 (setq ans (replace-match "" t t ans)
16132 deltan (car delta)
16133 deltaw (nth 1 delta)
16134 deltadef (nth 2 delta)))
16136 ;; Check if there is an iso week date in there. If yes, store the
16137 ;; info and postpone interpreting it until the rest of the parsing
16138 ;; is done.
16139 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16140 (setq iso-year (if (match-end 1)
16141 (org-small-year-to-year
16142 (string-to-number (match-string 1 ans))))
16143 iso-weekday (if (match-end 3)
16144 (string-to-number (match-string 3 ans)))
16145 iso-week (string-to-number (match-string 2 ans)))
16146 (setq ans (replace-match "" t t ans)))
16148 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16149 (when (string-match
16150 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16151 (setq year (if (match-end 2)
16152 (string-to-number (match-string 2 ans))
16153 (progn (setq kill-year t)
16154 (string-to-number (format-time-string "%Y"))))
16155 month (string-to-number (match-string 3 ans))
16156 day (string-to-number (match-string 4 ans)))
16157 (if (< year 100) (setq year (+ 2000 year)))
16158 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16159 t nil ans)))
16161 ;; Help matching dotted european dates
16162 (when (string-match
16163 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16164 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16165 (setq kill-year t)
16166 (string-to-number (format-time-string "%Y")))
16167 day (string-to-number (match-string 1 ans))
16168 month (string-to-number (match-string 2 ans))
16169 ans (replace-match (format "%04d-%02d-%02d" year month day)
16170 t nil ans)))
16172 ;; Help matching american dates, like 5/30 or 5/30/7
16173 (when (string-match
16174 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16175 (setq year (if (match-end 4)
16176 (string-to-number (match-string 4 ans))
16177 (progn (setq kill-year t)
16178 (string-to-number (format-time-string "%Y"))))
16179 month (string-to-number (match-string 1 ans))
16180 day (string-to-number (match-string 2 ans)))
16181 (if (< year 100) (setq year (+ 2000 year)))
16182 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16183 t nil ans)))
16184 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16185 ;; If there is a time with am/pm, and *no* time without it, we convert
16186 ;; so that matching will be successful.
16187 (loop for i from 1 to 2 do ; twice, for end time as well
16188 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16189 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16190 (setq hour (string-to-number (match-string 1 ans))
16191 minute (if (match-end 3)
16192 (string-to-number (match-string 3 ans))
16194 pm (equal ?p
16195 (string-to-char (downcase (match-string 4 ans)))))
16196 (if (and (= hour 12) (not pm))
16197 (setq hour 0)
16198 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16199 (setq ans (replace-match (format "%02d:%02d" hour minute)
16200 t t ans))))
16202 ;; Check if a time range is given as a duration
16203 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16204 (setq hour (string-to-number (match-string 1 ans))
16205 h2 (+ hour (string-to-number (match-string 3 ans)))
16206 minute (string-to-number (match-string 2 ans))
16207 m2 (+ minute (if (match-end 5) (string-to-number
16208 (match-string 5 ans))0)))
16209 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16210 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16211 t t ans)))
16213 ;; Check if there is a time range
16214 (when (boundp 'org-end-time-was-given)
16215 (setq org-time-was-given nil)
16216 (when (and (string-match org-plain-time-of-day-regexp ans)
16217 (match-end 8))
16218 (setq org-end-time-was-given (match-string 8 ans))
16219 (setq ans (concat (substring ans 0 (match-beginning 7))
16220 (substring ans (match-end 7))))))
16222 (setq tl (parse-time-string ans)
16223 day (or (nth 3 tl) (nth 3 org-defdecode))
16224 month (or (nth 4 tl)
16225 (if (and org-read-date-prefer-future
16226 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16227 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16228 (nth 4 org-defdecode)))
16229 year (or (and (not kill-year) (nth 5 tl))
16230 (if (and org-read-date-prefer-future
16231 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16232 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16233 (nth 5 org-defdecode)))
16234 hour (or (nth 2 tl) (nth 2 org-defdecode))
16235 minute (or (nth 1 tl) (nth 1 org-defdecode))
16236 second (or (nth 0 tl) 0)
16237 wday (nth 6 tl))
16239 (when (and (eq org-read-date-prefer-future 'time)
16240 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16241 (equal day (nth 3 nowdecode))
16242 (equal month (nth 4 nowdecode))
16243 (equal year (nth 5 nowdecode))
16244 (nth 2 tl)
16245 (or (< (nth 2 tl) (nth 2 nowdecode))
16246 (and (= (nth 2 tl) (nth 2 nowdecode))
16247 (nth 1 tl)
16248 (< (nth 1 tl) (nth 1 nowdecode)))))
16249 (setq day (1+ day)
16250 futurep t))
16252 ;; Special date definitions below
16253 (cond
16254 (iso-week
16255 ;; There was an iso week
16256 (require 'cal-iso)
16257 (setq futurep nil)
16258 (setq year (or iso-year year)
16259 day (or iso-weekday wday 1)
16260 wday nil ; to make sure that the trigger below does not match
16261 iso-date (calendar-gregorian-from-absolute
16262 (calendar-absolute-from-iso
16263 (list iso-week day year))))
16264 ; FIXME: Should we also push ISO weeks into the future?
16265 ; (when (and org-read-date-prefer-future
16266 ; (not iso-year)
16267 ; (< (calendar-absolute-from-gregorian iso-date)
16268 ; (time-to-days (current-time))))
16269 ; (setq year (1+ year)
16270 ; iso-date (calendar-gregorian-from-absolute
16271 ; (calendar-absolute-from-iso
16272 ; (list iso-week day year)))))
16273 (setq month (car iso-date)
16274 year (nth 2 iso-date)
16275 day (nth 1 iso-date)))
16276 (deltan
16277 (setq futurep nil)
16278 (unless deltadef
16279 (let ((now (decode-time (current-time))))
16280 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16281 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16282 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16283 ((equal deltaw "m") (setq month (+ month deltan)))
16284 ((equal deltaw "y") (setq year (+ year deltan)))))
16285 ((and wday (not (nth 3 tl)))
16286 ;; Weekday was given, but no day, so pick that day in the week
16287 ;; on or after the derived date.
16288 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16289 (unless (equal wday wday1)
16290 (setq day (+ day (% (- wday wday1 -7) 7))))))
16291 (if (and (boundp 'org-time-was-given)
16292 (nth 2 tl))
16293 (setq org-time-was-given t))
16294 (if (< year 100) (setq year (+ 2000 year)))
16295 ;; Check of the date is representable
16296 (if org-read-date-force-compatible-dates
16297 (progn
16298 (if (< year 1970)
16299 (setq year 1970 org-read-date-analyze-forced-year t))
16300 (if (> year 2037)
16301 (setq year 2037 org-read-date-analyze-forced-year t)))
16302 (condition-case nil
16303 (ignore (encode-time second minute hour day month year))
16304 (error
16305 (setq year (nth 5 org-defdecode))
16306 (setq org-read-date-analyze-forced-year t))))
16307 (setq org-read-date-analyze-futurep futurep)
16308 (list second minute hour day month year)))
16310 (defvar parse-time-weekdays)
16311 (defun org-read-date-get-relative (s today default)
16312 "Check string S for special relative date string.
16313 TODAY and DEFAULT are internal times, for today and for a default.
16314 Return shift list (N what def-flag)
16315 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16316 N is the number of WHATs to shift.
16317 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16318 the DEFAULT date rather than TODAY."
16319 (require 'parse-time)
16320 (when (and
16321 (string-match
16322 (concat
16323 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16324 "\\([0-9]+\\)?"
16325 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16326 "\\([ \t]\\|$\\)") s)
16327 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16328 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16329 (string-to-char (substring (match-string 1 s) -1))
16330 ?+))
16331 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16332 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16333 (what (if (match-end 3) (match-string 3 s) "d"))
16334 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16335 (date (if rel default today))
16336 (wday (nth 6 (decode-time date)))
16337 delta)
16338 (if wday1
16339 (progn
16340 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16341 (if (= dir ?-) (setq delta (- delta 7)))
16342 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16343 (list delta "d" rel))
16344 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16346 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16347 "Turn a user-specified date into the internal representation.
16348 The internal representation needed by the calendar is (month day year).
16349 This is a wrapper to handle the brain-dead convention in calendar that
16350 user function argument order change dependent on argument order."
16351 (if (boundp 'calendar-date-style)
16352 (cond
16353 ((eq calendar-date-style 'american)
16354 (list arg1 arg2 arg3))
16355 ((eq calendar-date-style 'european)
16356 (list arg2 arg1 arg3))
16357 ((eq calendar-date-style 'iso)
16358 (list arg2 arg3 arg1)))
16359 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16360 (if (org-bound-and-true-p european-calendar-style)
16361 (list arg2 arg1 arg3)
16362 (list arg1 arg2 arg3)))))
16364 (defun org-eval-in-calendar (form &optional keepdate)
16365 "Eval FORM in the calendar window and return to current window.
16366 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16367 otherwise stick to the current value of `org-ans2'."
16368 (let ((sf (selected-frame))
16369 (sw (selected-window)))
16370 (select-window (get-buffer-window "*Calendar*" t))
16371 (eval form)
16372 (when (and (not keepdate) (calendar-cursor-to-date))
16373 (let* ((date (calendar-cursor-to-date))
16374 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16375 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16376 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16377 (select-window sw)
16378 (org-select-frame-set-input-focus sf)))
16380 (defun org-calendar-select ()
16381 "Return to `org-read-date' with the date currently selected.
16382 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16383 (interactive)
16384 (when (calendar-cursor-to-date)
16385 (let* ((date (calendar-cursor-to-date))
16386 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16387 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16388 (if (active-minibuffer-window) (exit-minibuffer))))
16390 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16391 "Insert a date stamp for the date given by the internal TIME.
16392 WITH-HM means use the stamp format that includes the time of the day.
16393 INACTIVE means use square brackets instead of angular ones, so that the
16394 stamp will not contribute to the agenda.
16395 PRE and POST are optional strings to be inserted before and after the
16396 stamp.
16397 The command returns the inserted time stamp."
16398 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16399 stamp)
16400 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16401 (insert-before-markers (or pre ""))
16402 (when (listp extra)
16403 (setq extra (car extra))
16404 (if (and (stringp extra)
16405 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16406 (setq extra (format "-%02d:%02d"
16407 (string-to-number (match-string 1 extra))
16408 (string-to-number (match-string 2 extra))))
16409 (setq extra nil)))
16410 (when extra
16411 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16412 (insert-before-markers (setq stamp (format-time-string fmt time)))
16413 (insert-before-markers (or post ""))
16414 (setq org-last-inserted-timestamp stamp)))
16416 (defun org-toggle-time-stamp-overlays ()
16417 "Toggle the use of custom time stamp formats."
16418 (interactive)
16419 (setq org-display-custom-times (not org-display-custom-times))
16420 (unless org-display-custom-times
16421 (let ((p (point-min)) (bmp (buffer-modified-p)))
16422 (while (setq p (next-single-property-change p 'display))
16423 (if (and (get-text-property p 'display)
16424 (eq (get-text-property p 'face) 'org-date))
16425 (remove-text-properties
16426 p (setq p (next-single-property-change p 'display))
16427 '(display t))))
16428 (set-buffer-modified-p bmp)))
16429 (if (featurep 'xemacs)
16430 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16431 (org-restart-font-lock)
16432 (setq org-table-may-need-update t)
16433 (if org-display-custom-times
16434 (message "Time stamps are overlaid with custom format")
16435 (message "Time stamp overlays removed")))
16437 (defun org-display-custom-time (beg end)
16438 "Overlay modified time stamp format over timestamp between BEG and END."
16439 (let* ((ts (buffer-substring beg end))
16440 t1 w1 with-hm tf time str w2 (off 0))
16441 (save-match-data
16442 (setq t1 (org-parse-time-string ts t))
16443 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16444 (setq off (- (match-end 0) (match-beginning 0)))))
16445 (setq end (- end off))
16446 (setq w1 (- end beg)
16447 with-hm (and (nth 1 t1) (nth 2 t1))
16448 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16449 time (org-fix-decoded-time t1)
16450 str (org-add-props
16451 (format-time-string
16452 (substring tf 1 -1) (apply 'encode-time time))
16453 nil 'mouse-face 'highlight)
16454 w2 (length str))
16455 (if (not (= w2 w1))
16456 (add-text-properties (1+ beg) (+ 2 beg)
16457 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16458 (if (featurep 'xemacs)
16459 (progn
16460 (put-text-property beg end 'invisible t)
16461 (put-text-property beg end 'end-glyph (make-glyph str)))
16462 (put-text-property beg end 'display str))))
16464 (defun org-translate-time (string)
16465 "Translate all timestamps in STRING to custom format.
16466 But do this only if the variable `org-display-custom-times' is set."
16467 (when org-display-custom-times
16468 (save-match-data
16469 (let* ((start 0)
16470 (re org-ts-regexp-both)
16471 t1 with-hm inactive tf time str beg end)
16472 (while (setq start (string-match re string start))
16473 (setq beg (match-beginning 0)
16474 end (match-end 0)
16475 t1 (save-match-data
16476 (org-parse-time-string (substring string beg end) t))
16477 with-hm (and (nth 1 t1) (nth 2 t1))
16478 inactive (equal (substring string beg (1+ beg)) "[")
16479 tf (funcall (if with-hm 'cdr 'car)
16480 org-time-stamp-custom-formats)
16481 time (org-fix-decoded-time t1)
16482 str (format-time-string
16483 (concat
16484 (if inactive "[" "<") (substring tf 1 -1)
16485 (if inactive "]" ">"))
16486 (apply 'encode-time time))
16487 string (replace-match str t t string)
16488 start (+ start (length str)))))))
16489 string)
16491 (defun org-fix-decoded-time (time)
16492 "Set 0 instead of nil for the first 6 elements of time.
16493 Don't touch the rest."
16494 (let ((n 0))
16495 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16497 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16499 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16500 "Difference between TIMESTAMP-STRING and now in days.
16501 If SECONDS is non-nil, return the difference in seconds."
16502 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16503 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16504 (funcall fdiff (current-time)))))
16506 (defun org-deadline-close (timestamp-string &optional ndays)
16507 "Is the time in TIMESTAMP-STRING close to the current date?"
16508 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16509 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16510 (not (org-entry-is-done-p))))
16512 (defun org-get-wdays (ts &optional delay zero-delay)
16513 "Get the deadline lead time appropriate for timestring TS.
16514 When DELAY is non-nil, get the delay time for scheduled items
16515 instead of the deadline lead time. When ZERO-DELAY is non-nil
16516 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16517 don't try to find the delay cookie in the scheduled timestamp."
16518 (let ((tv (if delay org-scheduled-delay-days
16519 org-deadline-warning-days)))
16520 (cond
16521 ((or (and delay (< tv 0))
16522 (and delay zero-delay (<= tv 0))
16523 (and (not delay) (<= tv 0)))
16524 ;; Enforce this value no matter what
16525 (- tv))
16526 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16527 ;; lead time is specified.
16528 (floor (* (string-to-number (match-string 1 ts))
16529 (cdr (assoc (match-string 2 ts)
16530 '(("d" . 1) ("w" . 7)
16531 ("m" . 30.4) ("y" . 365.25)
16532 ("h" . 0.041667)))))))
16533 ;; go for the default.
16534 (t tv))))
16536 (defun org-calendar-select-mouse (ev)
16537 "Return to `org-read-date' with the date currently selected.
16538 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16539 (interactive "e")
16540 (mouse-set-point ev)
16541 (when (calendar-cursor-to-date)
16542 (let* ((date (calendar-cursor-to-date))
16543 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16544 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16545 (if (active-minibuffer-window) (exit-minibuffer))))
16547 (defun org-check-deadlines (ndays)
16548 "Check if there are any deadlines due or past due.
16549 A deadline is considered due if it happens within `org-deadline-warning-days'
16550 days from today's date. If the deadline appears in an entry marked DONE,
16551 it is not shown. The prefix arg NDAYS can be used to test that many
16552 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16553 (interactive "P")
16554 (let* ((org-warn-days
16555 (cond
16556 ((equal ndays '(4)) 100000)
16557 (ndays (prefix-numeric-value ndays))
16558 (t (abs org-deadline-warning-days))))
16559 (case-fold-search nil)
16560 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16561 (callback
16562 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16564 (message "%d deadlines past-due or due within %d days"
16565 (org-occur regexp nil callback)
16566 org-warn-days)))
16568 (defsubst org-re-timestamp (type)
16569 "Return a regexp for timestamp TYPE.
16570 Allowed values for TYPE are:
16572 all: all timestamps
16573 active: only active timestamps (<...>)
16574 inactive: only inactive timestamps ([...])
16575 scheduled: only scheduled timestamps
16576 deadline: only deadline timestamps
16578 When TYPE is nil, fall back on returning a regexp that matches
16579 both scheduled and deadline timestamps."
16580 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16581 ((eq type 'active) org-ts-regexp)
16582 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16583 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16584 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16585 ((eq type 'scheduled-or-deadline)
16586 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16588 (defun org-check-before-date (date)
16589 "Check if there are deadlines or scheduled entries before DATE."
16590 (interactive (list (org-read-date)))
16591 (let ((case-fold-search nil)
16592 (regexp (org-re-timestamp org-ts-type))
16593 (callback
16594 (lambda () (time-less-p
16595 (org-time-string-to-time (match-string 1))
16596 (org-time-string-to-time date)))))
16597 (message "%d entries before %s"
16598 (org-occur regexp nil callback) date)))
16600 (defun org-check-after-date (date)
16601 "Check if there are deadlines or scheduled entries after DATE."
16602 (interactive (list (org-read-date)))
16603 (let ((case-fold-search nil)
16604 (regexp (org-re-timestamp org-ts-type))
16605 (callback
16606 (lambda () (not
16607 (time-less-p
16608 (org-time-string-to-time (match-string 1))
16609 (org-time-string-to-time date))))))
16610 (message "%d entries after %s"
16611 (org-occur regexp nil callback) date)))
16613 (defun org-check-dates-range (start-date end-date)
16614 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16615 (interactive (list (org-read-date nil nil nil "Range starts")
16616 (org-read-date nil nil nil "Range end")))
16617 (let ((case-fold-search nil)
16618 (regexp (org-re-timestamp org-ts-type))
16619 (callback
16620 (lambda ()
16621 (let ((match (match-string 1)))
16622 (and
16623 (not (time-less-p
16624 (org-time-string-to-time match)
16625 (org-time-string-to-time start-date)))
16626 (time-less-p
16627 (org-time-string-to-time match)
16628 (org-time-string-to-time end-date)))))))
16629 (message "%d entries between %s and %s"
16630 (org-occur regexp nil callback) start-date end-date)))
16632 (defun org-evaluate-time-range (&optional to-buffer)
16633 "Evaluate a time range by computing the difference between start and end.
16634 Normally the result is just printed in the echo area, but with prefix arg
16635 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16636 If the time range is actually in a table, the result is inserted into the
16637 next column.
16638 For time difference computation, a year is assumed to be exactly 365
16639 days in order to avoid rounding problems."
16640 (interactive "P")
16642 (org-clock-update-time-maybe)
16643 (save-excursion
16644 (unless (org-at-date-range-p t)
16645 (goto-char (point-at-bol))
16646 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16647 (if (not (org-at-date-range-p t))
16648 (error "Not at a time-stamp range, and none found in current line")))
16649 (let* ((ts1 (match-string 1))
16650 (ts2 (match-string 2))
16651 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16652 (match-end (match-end 0))
16653 (time1 (org-time-string-to-time ts1))
16654 (time2 (org-time-string-to-time ts2))
16655 (t1 (org-float-time time1))
16656 (t2 (org-float-time time2))
16657 (diff (abs (- t2 t1)))
16658 (negative (< (- t2 t1) 0))
16659 ;; (ys (floor (* 365 24 60 60)))
16660 (ds (* 24 60 60))
16661 (hs (* 60 60))
16662 (fy "%dy %dd %02d:%02d")
16663 (fy1 "%dy %dd")
16664 (fd "%dd %02d:%02d")
16665 (fd1 "%dd")
16666 (fh "%02d:%02d")
16667 y d h m align)
16668 (if havetime
16669 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16671 d (floor (/ diff ds)) diff (mod diff ds)
16672 h (floor (/ diff hs)) diff (mod diff hs)
16673 m (floor (/ diff 60)))
16674 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16676 d (floor (+ (/ diff ds) 0.5))
16677 h 0 m 0))
16678 (if (not to-buffer)
16679 (message "%s" (org-make-tdiff-string y d h m))
16680 (if (org-at-table-p)
16681 (progn
16682 (goto-char match-end)
16683 (setq align t)
16684 (and (looking-at " *|") (goto-char (match-end 0))))
16685 (goto-char match-end))
16686 (if (looking-at
16687 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16688 (replace-match ""))
16689 (if negative (insert " -"))
16690 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16691 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16692 (insert " " (format fh h m))))
16693 (if align (org-table-align))
16694 (message "Time difference inserted")))))
16696 (defun org-make-tdiff-string (y d h m)
16697 (let ((fmt "")
16698 (l nil))
16699 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16700 l (push y l)))
16701 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16702 l (push d l)))
16703 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16704 l (push h l)))
16705 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16706 l (push m l)))
16707 (apply 'format fmt (nreverse l))))
16709 (defun org-time-string-to-time (s &optional buffer pos)
16710 "Convert a timestamp string into internal time."
16711 (condition-case errdata
16712 (apply 'encode-time (org-parse-time-string s))
16713 (error (error "Bad timestamp `%s'%s\nError was: %s"
16714 s (if (not (and buffer pos))
16716 (format " at %d in buffer `%s'" pos buffer))
16717 (cdr errdata)))))
16719 (defun org-time-string-to-seconds (s)
16720 "Convert a timestamp string to a number of seconds."
16721 (org-float-time (org-time-string-to-time s)))
16723 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16724 "Convert a time stamp to an absolute day number.
16725 If there is a specifier for a cyclic time stamp, get the closest
16726 date to DAYNR.
16727 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16728 The variable `date' is bound by the calendar when this is called."
16729 (cond
16730 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16731 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16732 daynr
16733 (+ daynr 1000)))
16734 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16735 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16736 (time-to-days (current-time))) (match-string 0 s)
16737 prefer show-all))
16738 (t (time-to-days
16739 (condition-case errdata
16740 (apply 'encode-time (org-parse-time-string s))
16741 (error (error "Bad timestamp `%s'%s\nError was: %s"
16742 s (if (not (and buffer pos))
16744 (format " at %d in buffer `%s'" pos buffer))
16745 (cdr errdata))))))))
16747 (defun org-days-to-iso-week (days)
16748 "Return the iso week number."
16749 (require 'cal-iso)
16750 (car (calendar-iso-from-absolute days)))
16752 (defun org-small-year-to-year (year)
16753 "Convert 2-digit years into 4-digit years.
16754 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16755 The year 2000 cannot be abbreviated. Any year larger than 99
16756 is returned unchanged."
16757 (if (< year 38)
16758 (setq year (+ 2000 year))
16759 (if (< year 100)
16760 (setq year (+ 1900 year))))
16761 year)
16763 (defun org-time-from-absolute (d)
16764 "Return the time corresponding to date D.
16765 D may be an absolute day number, or a calendar-type list (month day year)."
16766 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16767 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16769 (defun org-calendar-holiday ()
16770 "List of holidays, for Diary display in Org-mode."
16771 (require 'holidays)
16772 (let ((hl (funcall
16773 (if (fboundp 'calendar-check-holidays)
16774 'calendar-check-holidays 'check-calendar-holidays) date)))
16775 (if hl (mapconcat 'identity hl "; "))))
16777 (defun org-diary-sexp-entry (sexp entry date)
16778 "Process a SEXP diary ENTRY for DATE."
16779 (require 'diary-lib)
16780 (let ((result (if calendar-debug-sexp
16781 (let ((stack-trace-on-error t))
16782 (eval (car (read-from-string sexp))))
16783 (condition-case nil
16784 (eval (car (read-from-string sexp)))
16785 (error
16786 (beep)
16787 (message "Bad sexp at line %d in %s: %s"
16788 (org-current-line)
16789 (buffer-file-name) sexp)
16790 (sleep-for 2))))))
16791 (cond ((stringp result) (split-string result "; "))
16792 ((and (consp result)
16793 (not (consp (cdr result)))
16794 (stringp (cdr result))) (cdr result))
16795 ((and (consp result)
16796 (stringp (car result))) result)
16797 (result entry))))
16799 (defun org-diary-to-ical-string (frombuf)
16800 "Get iCalendar entries from diary entries in buffer FROMBUF.
16801 This uses the icalendar.el library."
16802 (let* ((tmpdir (if (featurep 'xemacs)
16803 (temp-directory)
16804 temporary-file-directory))
16805 (tmpfile (make-temp-name
16806 (expand-file-name "orgics" tmpdir)))
16807 buf rtn b e)
16808 (with-current-buffer frombuf
16809 (icalendar-export-region (point-min) (point-max) tmpfile)
16810 (setq buf (find-buffer-visiting tmpfile))
16811 (set-buffer buf)
16812 (goto-char (point-min))
16813 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16814 (setq b (match-beginning 0)))
16815 (goto-char (point-max))
16816 (if (re-search-backward "^END:VEVENT" nil t)
16817 (setq e (match-end 0)))
16818 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16819 (kill-buffer buf)
16820 (delete-file tmpfile)
16821 rtn))
16823 (defun org-closest-date (start current change prefer show-all)
16824 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16825 When PREFER is `past', return a date that is either CURRENT or past.
16826 When PREFER is `future', return a date that is either CURRENT or future.
16827 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16828 ;; Make the proper lists from the dates
16829 (catch 'exit
16830 (let ((a1 '(("h" . hour)
16831 ("d" . day)
16832 ("w" . week)
16833 ("m" . month)
16834 ("y" . year)))
16835 (shour (nth 2 (org-parse-time-string start)))
16836 dn dw sday cday n1 n2 n0
16837 d m y y1 y2 date1 date2 nmonths nm ny m2)
16839 (setq start (org-date-to-gregorian start)
16840 current (org-date-to-gregorian
16841 (if show-all
16842 current
16843 (time-to-days (current-time))))
16844 sday (calendar-absolute-from-gregorian start)
16845 cday (calendar-absolute-from-gregorian current))
16847 (if (<= cday sday) (throw 'exit sday))
16849 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16850 (setq dn (string-to-number (match-string 1 change))
16851 dw (cdr (assoc (match-string 2 change) a1)))
16852 (error "Invalid change specifier: %s" change))
16853 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16854 (cond
16855 ((eq dw 'hour)
16856 (let ((missing-hours
16857 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16858 dn)))
16859 (setq n1 (if (zerop missing-hours) cday
16860 (- cday (1+ (floor (/ missing-hours 24)))))
16861 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16862 ((eq dw 'day)
16863 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16864 n2 (+ n1 dn)))
16865 ((eq dw 'year)
16866 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16867 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16868 (setq date1 (list m d y1)
16869 n1 (calendar-absolute-from-gregorian date1)
16870 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16871 n2 (calendar-absolute-from-gregorian date2)))
16872 ((eq dw 'month)
16873 ;; approx number of month between the two dates
16874 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16875 ;; How often does dn fit in there?
16876 (setq d (nth 1 start) m (car start) y (nth 2 start)
16877 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16878 m (+ m nm)
16879 ny (floor (/ m 12))
16880 y (+ y ny)
16881 m (- m (* ny 12)))
16882 (while (> m 12) (setq m (- m 12) y (1+ y)))
16883 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16884 (setq m2 (+ m dn) y2 y)
16885 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16886 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16887 (while (<= n2 cday)
16888 (setq n1 n2 m m2 y y2)
16889 (setq m2 (+ m dn) y2 y)
16890 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16891 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16892 ;; Make sure n1 is the earlier date
16893 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16894 (if show-all
16895 (cond
16896 ((eq prefer 'past) (if (= cday n2) n2 n1))
16897 ((eq prefer 'future) (if (= cday n1) n1 n2))
16898 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16899 (cond
16900 ((eq prefer 'past) (if (= cday n2) n2 n1))
16901 ((eq prefer 'future) (if (= cday n1) n1 n2))
16902 (t (if (= cday n1) n1 n2)))))))
16904 (defun org-date-to-gregorian (date)
16905 "Turn any specification of DATE into a Gregorian date for the calendar."
16906 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16907 ((and (listp date) (= (length date) 3)) date)
16908 ((stringp date)
16909 (setq date (org-parse-time-string date))
16910 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16911 ((listp date)
16912 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16914 (defun org-parse-time-string (s &optional nodefault)
16915 "Parse the standard Org-mode time string.
16916 This should be a lot faster than the normal `parse-time-string'.
16917 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16918 hour and minute fields will be nil if not given."
16919 (cond ((string-match org-ts-regexp0 s)
16920 (list 0
16921 (if (or (match-beginning 8) (not nodefault))
16922 (string-to-number (or (match-string 8 s) "0")))
16923 (if (or (match-beginning 7) (not nodefault))
16924 (string-to-number (or (match-string 7 s) "0")))
16925 (string-to-number (match-string 4 s))
16926 (string-to-number (match-string 3 s))
16927 (string-to-number (match-string 2 s))
16928 nil nil nil))
16929 ((string-match "^<[^>]+>$" s)
16930 (decode-time (seconds-to-time (org-matcher-time s))))
16931 (t (error "Not a standard Org-mode time string: %s" s))))
16933 (defun org-timestamp-up (&optional arg)
16934 "Increase the date item at the cursor by one.
16935 If the cursor is on the year, change the year. If it is on the month,
16936 the day or the time, change that.
16937 With prefix ARG, change by that many units."
16938 (interactive "p")
16939 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16941 (defun org-timestamp-down (&optional arg)
16942 "Decrease the date item at the cursor by one.
16943 If the cursor is on the year, change the year. If it is on the month,
16944 the day or the time, change that.
16945 With prefix ARG, change by that many units."
16946 (interactive "p")
16947 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16949 (defun org-timestamp-up-day (&optional arg)
16950 "Increase the date in the time stamp by one day.
16951 With prefix ARG, change that many days."
16952 (interactive "p")
16953 (if (and (not (org-at-timestamp-p t))
16954 (org-at-heading-p))
16955 (org-todo 'up)
16956 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16958 (defun org-timestamp-down-day (&optional arg)
16959 "Decrease the date in the time stamp by one day.
16960 With prefix ARG, change that many days."
16961 (interactive "p")
16962 (if (and (not (org-at-timestamp-p t))
16963 (org-at-heading-p))
16964 (org-todo 'down)
16965 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16967 (defun org-at-timestamp-p (&optional inactive-ok)
16968 "Determine if the cursor is in or at a timestamp."
16969 (interactive)
16970 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16971 (pos (point))
16972 (ans (or (looking-at tsr)
16973 (save-excursion
16974 (skip-chars-backward "^[<\n\r\t")
16975 (if (> (point) (point-min)) (backward-char 1))
16976 (and (looking-at tsr)
16977 (> (- (match-end 0) pos) -1))))))
16978 (and ans
16979 (boundp 'org-ts-what)
16980 (setq org-ts-what
16981 (cond
16982 ((= pos (match-beginning 0)) 'bracket)
16983 ;; Point is considered to be "on the bracket" whether
16984 ;; it's really on it or right after it.
16985 ((= pos (1- (match-end 0))) 'bracket)
16986 ((= pos (match-end 0)) 'after)
16987 ((org-pos-in-match-range pos 2) 'year)
16988 ((org-pos-in-match-range pos 3) 'month)
16989 ((org-pos-in-match-range pos 7) 'hour)
16990 ((org-pos-in-match-range pos 8) 'minute)
16991 ((or (org-pos-in-match-range pos 4)
16992 (org-pos-in-match-range pos 5)) 'day)
16993 ((and (> pos (or (match-end 8) (match-end 5)))
16994 (< pos (match-end 0)))
16995 (- pos (or (match-end 8) (match-end 5))))
16996 (t 'day))))
16997 ans))
16999 (defun org-toggle-timestamp-type ()
17000 "Toggle the type (<active> or [inactive]) of a time stamp."
17001 (interactive)
17002 (when (org-at-timestamp-p t)
17003 (let ((beg (match-beginning 0)) (end (match-end 0))
17004 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17005 (save-excursion
17006 (goto-char beg)
17007 (while (re-search-forward "[][<>]" end t)
17008 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17009 t t)))
17010 (message "Timestamp is now %sactive"
17011 (if (equal (char-after beg) ?<) "" "in")))))
17013 (defun org-at-clock-log-p nil
17014 "Is the cursor on the clock log line?"
17015 (save-excursion
17016 (move-beginning-of-line 1)
17017 (looking-at "^[ \t]*CLOCK:")))
17019 (defvar org-clock-history) ; defined in org-clock.el
17020 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17021 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17022 "Change the date in the time stamp at point.
17023 The date will be changed by N times WHAT. WHAT can be `day', `month',
17024 `year', `minute', `second'. If WHAT is not given, the cursor position
17025 in the timestamp determines what will be changed.
17026 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17027 (let ((origin (point)) origin-cat
17028 with-hm inactive
17029 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17030 org-ts-what
17031 extra rem
17032 ts time time0 fixnext clrgx)
17033 (if (not (org-at-timestamp-p t))
17034 (error "Not at a timestamp"))
17035 (if (and (not what) (eq org-ts-what 'bracket))
17036 (org-toggle-timestamp-type)
17037 ;; Point isn't on brackets. Remember the part of the time-stamp
17038 ;; the point was in. Indeed, size of time-stamps may change,
17039 ;; but point must be kept in the same category nonetheless.
17040 (setq origin-cat org-ts-what)
17041 (if (and (not what) (not (eq org-ts-what 'day))
17042 org-display-custom-times
17043 (get-text-property (point) 'display)
17044 (not (get-text-property (1- (point)) 'display)))
17045 (setq org-ts-what 'day))
17046 (setq org-ts-what (or what org-ts-what)
17047 inactive (= (char-after (match-beginning 0)) ?\[)
17048 ts (match-string 0))
17049 (replace-match "")
17050 (when (string-match
17051 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17053 (setq extra (match-string 1 ts))
17054 (if suppress-tmp-delay
17055 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17056 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17057 (setq with-hm t))
17058 (setq time0 (org-parse-time-string ts))
17059 (when (and updown
17060 (eq org-ts-what 'minute)
17061 (not current-prefix-arg))
17062 ;; This looks like s-up and s-down. Change by one rounding step.
17063 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17064 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17065 (setcar (cdr time0) (+ (nth 1 time0)
17066 (if (> n 0) (- rem) (- dm rem))))))
17067 (setq time
17068 (encode-time (or (car time0) 0)
17069 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17070 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17071 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17072 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17073 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17074 (nthcdr 6 time0)))
17075 (when (and (member org-ts-what '(hour minute))
17076 extra
17077 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17078 (setq extra (org-modify-ts-extra
17079 extra
17080 (if (eq org-ts-what 'hour) 2 5)
17081 n dm)))
17082 (when (integerp org-ts-what)
17083 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17084 (if (eq what 'calendar)
17085 (let ((cal-date (org-get-date-from-calendar)))
17086 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17087 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17088 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17089 (setcar time0 (or (car time0) 0))
17090 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17091 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17092 (setq time (apply 'encode-time time0))))
17093 ;; Insert the new time-stamp, and ensure point stays in the same
17094 ;; category as before (i.e. not after the last position in that
17095 ;; category).
17096 (let ((pos (point)))
17097 ;; Stay before inserted string. `save-excursion' is of no use.
17098 (setq org-last-changed-timestamp
17099 (org-insert-time-stamp time with-hm inactive nil nil extra))
17100 (goto-char pos))
17101 (save-match-data
17102 (looking-at org-ts-regexp3)
17103 (goto-char (cond
17104 ;; `day' category ends before `hour' if any, or at
17105 ;; the end of the day name.
17106 ((eq origin-cat 'day)
17107 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17108 ((eq origin-cat 'hour) (min (match-end 7) origin))
17109 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17110 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17111 ;; `year' and `month' have both fixed size: point
17112 ;; couldn't have moved into another part.
17113 (t origin))))
17114 ;; Update clock if on a CLOCK line.
17115 (org-clock-update-time-maybe)
17116 ;; Maybe adjust the closest clock in `org-clock-history'
17117 (when org-clock-adjust-closest
17118 (if (not (and (org-at-clock-log-p)
17119 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
17120 org-clock-history))))))
17121 (message "No clock to adjust")
17122 (cond ((save-excursion ; fix previous clock?
17123 (re-search-backward org-ts-regexp0 nil t)
17124 (org-looking-back (concat org-clock-string " \\[")))
17125 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17126 ((save-excursion ; fix next clock?
17127 (re-search-backward org-ts-regexp0 nil t)
17128 (looking-at (concat org-ts-regexp0 "\\] =>")))
17129 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17130 (save-window-excursion
17131 ;; Find closest clock to point, adjust the previous/next one in history
17132 (let* ((p (save-excursion (org-back-to-heading t)))
17133 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17134 (clfixnth
17135 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17136 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17137 (if (not clfixpos)
17138 (message "No clock to adjust")
17139 (save-excursion
17140 (org-goto-marker-or-bmk clfixpos)
17141 (org-show-subtree)
17142 (when (re-search-forward clrgx nil t)
17143 (goto-char (match-beginning 1))
17144 (let (org-clock-adjust-closest)
17145 (org-timestamp-change n org-ts-what updown))
17146 (message "Clock adjusted in %s for heading: %s"
17147 (file-name-nondirectory (buffer-file-name))
17148 (org-get-heading t t)))))))))
17149 ;; Try to recenter the calendar window, if any.
17150 (if (and org-calendar-follow-timestamp-change
17151 (get-buffer-window "*Calendar*" t)
17152 (memq org-ts-what '(day month year)))
17153 (org-recenter-calendar (time-to-days time))))))
17155 (defun org-modify-ts-extra (s pos n dm)
17156 "Change the different parts of the lead-time and repeat fields in timestamp."
17157 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17158 ng h m new rem)
17159 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17160 (cond
17161 ((or (org-pos-in-match-range pos 2)
17162 (org-pos-in-match-range pos 3))
17163 (setq m (string-to-number (match-string 3 s))
17164 h (string-to-number (match-string 2 s)))
17165 (if (org-pos-in-match-range pos 2)
17166 (setq h (+ h n))
17167 (setq n (* dm (org-no-warnings (signum n))))
17168 (when (not (= 0 (setq rem (% m dm))))
17169 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17170 (setq m (+ m n)))
17171 (if (< m 0) (setq m (+ m 60) h (1- h)))
17172 (if (> m 59) (setq m (- m 60) h (1+ h)))
17173 (setq h (min 24 (max 0 h)))
17174 (setq ng 1 new (format "-%02d:%02d" h m)))
17175 ((org-pos-in-match-range pos 6)
17176 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17177 ((org-pos-in-match-range pos 5)
17178 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17180 ((org-pos-in-match-range pos 9)
17181 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17182 ((org-pos-in-match-range pos 8)
17183 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17185 (when ng
17186 (setq s (concat
17187 (substring s 0 (match-beginning ng))
17189 (substring s (match-end ng))))))
17192 (defun org-recenter-calendar (date)
17193 "If the calendar is visible, recenter it to DATE."
17194 (let ((cwin (get-buffer-window "*Calendar*" t)))
17195 (when cwin
17196 (let ((calendar-move-hook nil))
17197 (with-selected-window cwin
17198 (calendar-goto-date (if (listp date) date
17199 (calendar-gregorian-from-absolute date))))))))
17201 (defun org-goto-calendar (&optional arg)
17202 "Go to the Emacs calendar at the current date.
17203 If there is a time stamp in the current line, go to that date.
17204 A prefix ARG can be used to force the current date."
17205 (interactive "P")
17206 (let ((tsr org-ts-regexp) diff
17207 (calendar-move-hook nil)
17208 (calendar-view-holidays-initially-flag nil)
17209 (calendar-view-diary-initially-flag nil))
17210 (if (or (org-at-timestamp-p)
17211 (save-excursion
17212 (beginning-of-line 1)
17213 (looking-at (concat ".*" tsr))))
17214 (let ((d1 (time-to-days (current-time)))
17215 (d2 (time-to-days
17216 (org-time-string-to-time (match-string 1)))))
17217 (setq diff (- d2 d1))))
17218 (calendar)
17219 (calendar-goto-today)
17220 (if (and diff (not arg)) (calendar-forward-day diff))))
17222 (defun org-get-date-from-calendar ()
17223 "Return a list (month day year) of date at point in calendar."
17224 (with-current-buffer "*Calendar*"
17225 (save-match-data
17226 (calendar-cursor-to-date))))
17228 (defun org-date-from-calendar ()
17229 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17230 If there is already a time stamp at the cursor position, update it."
17231 (interactive)
17232 (if (org-at-timestamp-p t)
17233 (org-timestamp-change 0 'calendar)
17234 (let ((cal-date (org-get-date-from-calendar)))
17235 (org-insert-time-stamp
17236 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17238 (defcustom org-effort-durations
17239 `(("h" . 60)
17240 ("d" . ,(* 60 8))
17241 ("w" . ,(* 60 8 5))
17242 ("m" . ,(* 60 8 5 4))
17243 ("y" . ,(* 60 8 5 40)))
17244 "Conversion factor to minutes for an effort modifier.
17246 Each entry has the form (MODIFIER . MINUTES).
17248 In an effort string, a number followed by MODIFIER is multiplied
17249 by the specified number of MINUTES to obtain an effort in
17250 minutes.
17252 For example, if the value of this variable is ((\"hours\" . 60)), then an
17253 effort string \"2hours\" is equivalent to 120 minutes."
17254 :group 'org-agenda
17255 :version "24.1"
17256 :type '(alist :key-type (string :tag "Modifier")
17257 :value-type (number :tag "Minutes")))
17259 (defun org-minutes-to-clocksum-string (m)
17260 "Format number of minutes as a clocksum string.
17261 The format is determined by `org-time-clocksum-format',
17262 `org-time-clocksum-use-fractional' and
17263 `org-time-clocksum-fractional-format' and
17264 `org-time-clocksum-use-effort-durations'."
17265 (let ((clocksum "") h d w mo y fmt n)
17266 (setq h (if org-time-clocksum-use-effort-durations
17267 (cdr (assoc "h" org-effort-durations)) 60)
17268 d (if org-time-clocksum-use-effort-durations
17269 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17270 w (if org-time-clocksum-use-effort-durations
17271 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17272 mo (if org-time-clocksum-use-effort-durations
17273 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17274 y (if org-time-clocksum-use-effort-durations
17275 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17276 ;; fractional format
17277 (if org-time-clocksum-use-fractional
17278 (cond
17279 ;; single format string
17280 ((stringp org-time-clocksum-fractional-format)
17281 (format org-time-clocksum-fractional-format (/ m (float h))))
17282 ;; choice of fractional formats for different time units
17283 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17284 (> (/ (truncate m) (* y d h)) 0))
17285 (format fmt (/ m (* y d (float h)))))
17286 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17287 (> (/ (truncate m) (* mo d h)) 0))
17288 (format fmt (/ m (* mo d (float h)))))
17289 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17290 (> (/ (truncate m) (* w d h)) 0))
17291 (format fmt (/ m (* w d (float h)))))
17292 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17293 (> (/ (truncate m) (* d h)) 0))
17294 (format fmt (/ m (* d (float h)))))
17295 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17296 (> (/ (truncate m) h) 0))
17297 (format fmt (/ m (float h))))
17298 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17299 (format fmt m))
17300 ;; fall back to smallest time unit with a format
17301 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17302 (format fmt (/ m (float h))))
17303 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17304 (format fmt (/ m (* d (float h)))))
17305 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17306 (format fmt (/ m (* w d (float h)))))
17307 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17308 (format fmt (/ m (* mo d (float h)))))
17309 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17310 (format fmt (/ m (* y d (float h))))))
17311 ;; standard (non-fractional) format, with single format string
17312 (if (stringp org-time-clocksum-format)
17313 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17314 ;; separate formats components
17315 (and (setq fmt (plist-get org-time-clocksum-format :years))
17316 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17317 (plist-get org-time-clocksum-format :require-years))
17318 (setq clocksum (concat clocksum (format fmt n))
17319 m (- m (* n y d h))))
17320 (and (setq fmt (plist-get org-time-clocksum-format :months))
17321 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17322 (plist-get org-time-clocksum-format :require-months))
17323 (setq clocksum (concat clocksum (format fmt n))
17324 m (- m (* n mo d h))))
17325 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17326 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17327 (plist-get org-time-clocksum-format :require-weeks))
17328 (setq clocksum (concat clocksum (format fmt n))
17329 m (- m (* n w d h))))
17330 (and (setq fmt (plist-get org-time-clocksum-format :days))
17331 (or (> (setq n (/ (truncate m) (* d h))) 0)
17332 (plist-get org-time-clocksum-format :require-days))
17333 (setq clocksum (concat clocksum (format fmt n))
17334 m (- m (* n d h))))
17335 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17336 (or (> (setq n (/ (truncate m) h)) 0)
17337 (plist-get org-time-clocksum-format :require-hours))
17338 (setq clocksum (concat clocksum (format fmt n))
17339 m (- m (* n h))))
17340 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17341 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17342 (setq clocksum (concat clocksum (format fmt m))))
17343 ;; return formatted time duration
17344 clocksum))))
17346 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17347 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17348 "Org mode version 8.0")
17350 (defun org-hours-to-clocksum-string (n)
17351 (org-minutes-to-clocksum-string (* n 60)))
17353 (defun org-hh:mm-string-to-minutes (s)
17354 "Convert a string H:MM to a number of minutes.
17355 If the string is just a number, interpret it as minutes.
17356 In fact, the first hh:mm or number in the string will be taken,
17357 there can be extra stuff in the string.
17358 If no number is found, the return value is 0."
17359 (cond
17360 ((integerp s) s)
17361 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17362 (+ (* (string-to-number (match-string 1 s)) 60)
17363 (string-to-number (match-string 2 s))))
17364 ((string-match "\\([0-9]+\\)" s)
17365 (string-to-number (match-string 1 s)))
17366 (t 0)))
17368 (defcustom org-image-actual-width t
17369 "Should we use the actual width of images when inlining them?
17371 When set to `t', always use the image width.
17373 When set to a number, use imagemagick (when available) to set
17374 the image's width to this value.
17376 When set to a number in a list, try to get the width from the
17377 #+ATTR.* keyword if it matches a width specification like
17378 width=\"[0-9]+\", and fall back on that number if none is found.
17380 When set to nil, try to get the width from an #+ATTR.* keyword
17381 and fall back on the original width if none is found.
17383 This requires Emacs >= 24.1, build with imagemagick support."
17384 :group 'org-appearance
17385 :version "24.4"
17386 :package-version '(Org . "8.0")
17387 :type '(choice
17388 (const :tag "Use the image width" t)
17389 (integer :tag "Use a number of pixels")
17390 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17391 (const :tag "Use #+ATTR* or don't resize" nil)))
17393 (defcustom org-agenda-inhibit-startup nil
17394 "Inhibit startup when preparing agenda buffers.
17395 When this variable is `t' (the default), the initialization of
17396 the Org agenda buffers is inhibited: e.g. the visibility state
17397 is not set, the tables are not re-aligned, etc."
17398 :type 'boolean
17399 :version "24.3"
17400 :group 'org-agenda)
17402 (defun org-duration-string-to-minutes (s &optional output-to-string)
17403 "Convert a duration string S to minutes.
17405 A bare number is interpreted as minutes, modifiers can be set by
17406 customizing `org-effort-durations' (which see).
17408 Entries containing a colon are interpreted as H:MM by
17409 `org-hh:mm-string-to-minutes'."
17410 (let ((result 0)
17411 (re (concat "\\([0-9.]+\\) *\\("
17412 (regexp-opt (mapcar 'car org-effort-durations))
17413 "\\)")))
17414 (while (string-match re s)
17415 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17416 (string-to-number (match-string 1 s))))
17417 (setq s (replace-match "" nil t s)))
17418 (setq result (floor result))
17419 (incf result (org-hh:mm-string-to-minutes s))
17420 (if output-to-string (number-to-string result) result)))
17422 ;;;; Files
17424 (defun org-save-all-org-buffers ()
17425 "Save all Org-mode buffers without user confirmation."
17426 (interactive)
17427 (message "Saving all Org-mode buffers...")
17428 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17429 (when (featurep 'org-id) (org-id-locations-save))
17430 (message "Saving all Org-mode buffers... done"))
17432 (defun org-revert-all-org-buffers ()
17433 "Revert all Org-mode buffers.
17434 Prompt for confirmation when there are unsaved changes.
17435 Be sure you know what you are doing before letting this function
17436 overwrite your changes.
17438 This function is useful in a setup where one tracks org files
17439 with a version control system, to revert on one machine after pulling
17440 changes from another. I believe the procedure must be like this:
17442 1. M-x org-save-all-org-buffers
17443 2. Pull changes from the other machine, resolve conflicts
17444 3. M-x org-revert-all-org-buffers"
17445 (interactive)
17446 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17447 (error "Abort"))
17448 (save-excursion
17449 (save-window-excursion
17450 (mapc
17451 (lambda (b)
17452 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17453 (with-current-buffer b buffer-file-name))
17454 (org-pop-to-buffer-same-window b)
17455 (revert-buffer t 'no-confirm)))
17456 (buffer-list))
17457 (when (and (featurep 'org-id) org-id-track-globally)
17458 (org-id-locations-load)))))
17460 ;;;; Agenda files
17462 ;;;###autoload
17463 (defun org-switchb (&optional arg)
17464 "Switch between Org buffers.
17465 With one prefix argument, restrict available buffers to files.
17466 With two prefix arguments, restrict available buffers to agenda files.
17468 Defaults to `iswitchb' for buffer name completion.
17469 Set `org-completion-use-ido' to make it use ido instead."
17470 (interactive "P")
17471 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17472 ((equal arg '(16)) (org-buffer-list 'agenda))
17473 (t (org-buffer-list))))
17474 (org-completion-use-iswitchb org-completion-use-iswitchb)
17475 (org-completion-use-ido org-completion-use-ido))
17476 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17477 (setq org-completion-use-iswitchb t))
17478 (org-pop-to-buffer-same-window
17479 (org-icompleting-read "Org buffer: "
17480 (mapcar 'list (mapcar 'buffer-name blist))
17481 nil t))))
17483 ;;; Define some older names previously used for this functionality
17484 ;;;###autoload
17485 (defalias 'org-ido-switchb 'org-switchb)
17486 ;;;###autoload
17487 (defalias 'org-iswitchb 'org-switchb)
17489 (defun org-buffer-list (&optional predicate exclude-tmp)
17490 "Return a list of Org buffers.
17491 PREDICATE can be `export', `files' or `agenda'.
17493 export restrict the list to Export buffers.
17494 files restrict the list to buffers visiting Org files.
17495 agenda restrict the list to buffers visiting agenda files.
17497 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17498 (let* ((bfn nil)
17499 (agenda-files (and (eq predicate 'agenda)
17500 (mapcar 'file-truename (org-agenda-files t))))
17501 (filter
17502 (cond
17503 ((eq predicate 'files)
17504 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17505 ((eq predicate 'export)
17506 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17507 ((eq predicate 'agenda)
17508 (lambda (b)
17509 (with-current-buffer b
17510 (and (derived-mode-p 'org-mode)
17511 (setq bfn (buffer-file-name b))
17512 (member (file-truename bfn) agenda-files)))))
17513 (t (lambda (b) (with-current-buffer b
17514 (or (derived-mode-p 'org-mode)
17515 (string-match "\*Org .*Export"
17516 (buffer-name b)))))))))
17517 (delq nil
17518 (mapcar
17519 (lambda(b)
17520 (if (and (funcall filter b)
17521 (or (not exclude-tmp)
17522 (not (string-match "tmp" (buffer-name b)))))
17524 nil))
17525 (buffer-list)))))
17527 (defun org-agenda-files (&optional unrestricted archives)
17528 "Get the list of agenda files.
17529 Optional UNRESTRICTED means return the full list even if a restriction
17530 is currently in place.
17531 When ARCHIVES is t, include all archive files that are really being
17532 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17533 `org-agenda-archives-mode' is t."
17534 (let ((files
17535 (cond
17536 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17537 ((stringp org-agenda-files) (org-read-agenda-file-list))
17538 ((listp org-agenda-files) org-agenda-files)
17539 (t (error "Invalid value of `org-agenda-files'")))))
17540 (setq files (apply 'append
17541 (mapcar (lambda (f)
17542 (if (file-directory-p f)
17543 (directory-files
17544 f t org-agenda-file-regexp)
17545 (list f)))
17546 files)))
17547 (when org-agenda-skip-unavailable-files
17548 (setq files (delq nil
17549 (mapcar (function
17550 (lambda (file)
17551 (and (file-readable-p file) file)))
17552 files))))
17553 (when (or (eq archives t)
17554 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17555 (setq files (org-add-archive-files files)))
17556 files))
17558 (defun org-agenda-file-p (&optional file)
17559 "Return non-nil, if FILE is an agenda file.
17560 If FILE is omitted, use the file associated with the current
17561 buffer."
17562 (member (or file (buffer-file-name))
17563 (org-agenda-files t)))
17565 (defun org-edit-agenda-file-list ()
17566 "Edit the list of agenda files.
17567 Depending on setup, this either uses customize to edit the variable
17568 `org-agenda-files', or it visits the file that is holding the list. In the
17569 latter case, the buffer is set up in a way that saving it automatically kills
17570 the buffer and restores the previous window configuration."
17571 (interactive)
17572 (if (stringp org-agenda-files)
17573 (let ((cw (current-window-configuration)))
17574 (find-file org-agenda-files)
17575 (org-set-local 'org-window-configuration cw)
17576 (org-add-hook 'after-save-hook
17577 (lambda ()
17578 (set-window-configuration
17579 (prog1 org-window-configuration
17580 (kill-buffer (current-buffer))))
17581 (org-install-agenda-files-menu)
17582 (message "New agenda file list installed"))
17583 nil 'local)
17584 (message "%s" (substitute-command-keys
17585 "Edit list and finish with \\[save-buffer]")))
17586 (customize-variable 'org-agenda-files)))
17588 (defun org-store-new-agenda-file-list (list)
17589 "Set new value for the agenda file list and save it correctly."
17590 (if (stringp org-agenda-files)
17591 (let ((fe (org-read-agenda-file-list t)) b u)
17592 (while (setq b (find-buffer-visiting org-agenda-files))
17593 (kill-buffer b))
17594 (with-temp-file org-agenda-files
17595 (insert
17596 (mapconcat
17597 (lambda (f) ;; Keep un-expanded entries.
17598 (if (setq u (assoc f fe))
17599 (cdr u)
17601 list "\n")
17602 "\n")))
17603 (let ((org-mode-hook nil) (org-inhibit-startup t)
17604 (org-insert-mode-line-in-empty-file nil))
17605 (setq org-agenda-files list)
17606 (customize-save-variable 'org-agenda-files org-agenda-files))))
17608 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17609 "Read the list of agenda files from a file.
17610 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17611 filenames, used by `org-store-new-agenda-file-list' to write back
17612 un-expanded file names."
17613 (when (file-directory-p org-agenda-files)
17614 (error "`org-agenda-files' cannot be a single directory"))
17615 (when (stringp org-agenda-files)
17616 (with-temp-buffer
17617 (insert-file-contents org-agenda-files)
17618 (mapcar
17619 (lambda (f)
17620 (let ((e (expand-file-name (substitute-in-file-name f)
17621 org-directory)))
17622 (if pair-with-expansion
17623 (cons e f)
17624 e)))
17625 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17627 ;;;###autoload
17628 (defun org-cycle-agenda-files ()
17629 "Cycle through the files in `org-agenda-files'.
17630 If the current buffer visits an agenda file, find the next one in the list.
17631 If the current buffer does not, find the first agenda file."
17632 (interactive)
17633 (let* ((fs (org-agenda-files t))
17634 (files (append fs (list (car fs))))
17635 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17636 file)
17637 (unless files (error "No agenda files"))
17638 (catch 'exit
17639 (while (setq file (pop files))
17640 (if (equal (file-truename file) tcf)
17641 (when (car files)
17642 (find-file (car files))
17643 (throw 'exit t))))
17644 (find-file (car fs)))
17645 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17647 (defun org-agenda-file-to-front (&optional to-end)
17648 "Move/add the current file to the top of the agenda file list.
17649 If the file is not present in the list, it is added to the front. If it is
17650 present, it is moved there. With optional argument TO-END, add/move to the
17651 end of the list."
17652 (interactive "P")
17653 (let ((org-agenda-skip-unavailable-files nil)
17654 (file-alist (mapcar (lambda (x)
17655 (cons (file-truename x) x))
17656 (org-agenda-files t)))
17657 (ctf (file-truename
17658 (or buffer-file-name
17659 (error "Please save the current buffer to a file"))))
17660 x had)
17661 (setq x (assoc ctf file-alist) had x)
17663 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17664 (if to-end
17665 (setq file-alist (append (delq x file-alist) (list x)))
17666 (setq file-alist (cons x (delq x file-alist))))
17667 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17668 (org-install-agenda-files-menu)
17669 (message "File %s to %s of agenda file list"
17670 (if had "moved" "added") (if to-end "end" "front"))))
17672 (defun org-remove-file (&optional file)
17673 "Remove current file from the list of files in variable `org-agenda-files'.
17674 These are the files which are being checked for agenda entries.
17675 Optional argument FILE means use this file instead of the current."
17676 (interactive)
17677 (let* ((org-agenda-skip-unavailable-files nil)
17678 (file (or file buffer-file-name
17679 (error "Current buffer does not visit a file")))
17680 (true-file (file-truename file))
17681 (afile (abbreviate-file-name file))
17682 (files (delq nil (mapcar
17683 (lambda (x)
17684 (if (equal true-file
17685 (file-truename x))
17686 nil x))
17687 (org-agenda-files t)))))
17688 (if (not (= (length files) (length (org-agenda-files t))))
17689 (progn
17690 (org-store-new-agenda-file-list files)
17691 (org-install-agenda-files-menu)
17692 (message "Removed file: %s" afile))
17693 (message "File was not in list: %s (not removed)" afile))))
17695 (defun org-file-menu-entry (file)
17696 (vector file (list 'find-file file) t))
17698 (defun org-check-agenda-file (file)
17699 "Make sure FILE exists. If not, ask user what to do."
17700 (when (not (file-exists-p file))
17701 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17702 (abbreviate-file-name file))
17703 (let ((r (downcase (read-char-exclusive))))
17704 (cond
17705 ((equal r ?r)
17706 (org-remove-file file)
17707 (throw 'nextfile t))
17708 (t (error "Abort"))))))
17710 (defun org-get-agenda-file-buffer (file)
17711 "Get a buffer visiting FILE. If the buffer needs to be created, add
17712 it to the list of buffers which might be released later."
17713 (let ((buf (org-find-base-buffer-visiting file)))
17714 (if buf
17715 buf ; just return it
17716 ;; Make a new buffer and remember it
17717 (setq buf (find-file-noselect file))
17718 (if buf (push buf org-agenda-new-buffers))
17719 buf)))
17721 (defun org-release-buffers (blist)
17722 "Release all buffers in list, asking the user for confirmation when needed.
17723 When a buffer is unmodified, it is just killed. When modified, it is saved
17724 \(if the user agrees) and then killed."
17725 (let (buf file)
17726 (while (setq buf (pop blist))
17727 (setq file (buffer-file-name buf))
17728 (when (and (buffer-modified-p buf)
17729 file
17730 (y-or-n-p (format "Save file %s? " file)))
17731 (with-current-buffer buf (save-buffer)))
17732 (kill-buffer buf))))
17734 (defun org-agenda-prepare-buffers (files)
17735 "Create buffers for all agenda files, protect archived trees and comments."
17736 (interactive)
17737 (let ((pa '(:org-archived t))
17738 (pc '(:org-comment t))
17739 (pall '(:org-archived t :org-comment t))
17740 (inhibit-read-only t)
17741 (org-inhibit-startup org-agenda-inhibit-startup)
17742 (rea (concat ":" org-archive-tag ":"))
17743 file re)
17744 (save-excursion
17745 (save-restriction
17746 (while (setq file (pop files))
17747 (catch 'nextfile
17748 (if (bufferp file)
17749 (set-buffer file)
17750 (org-check-agenda-file file)
17751 (set-buffer (org-get-agenda-file-buffer file)))
17752 (widen)
17753 (org-refresh-category-properties)
17754 (org-refresh-properties org-effort-property 'org-effort)
17755 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17756 (setq org-todo-keywords-for-agenda
17757 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17758 (setq org-done-keywords-for-agenda
17759 (append org-done-keywords-for-agenda org-done-keywords))
17760 (setq org-todo-keyword-alist-for-agenda
17761 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17762 (setq org-drawers-for-agenda
17763 (append org-drawers-for-agenda org-drawers))
17764 (setq org-tag-alist-for-agenda
17765 (append org-tag-alist-for-agenda org-tag-alist))
17766 (org-with-silent-modifications
17767 (save-excursion
17768 (remove-text-properties (point-min) (point-max) pall)
17769 (when org-agenda-skip-archived-trees
17770 (goto-char (point-min))
17771 (while (re-search-forward rea nil t)
17772 (if (org-at-heading-p t)
17773 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17774 (goto-char (point-min))
17775 (setq re (format org-heading-keyword-regexp-format
17776 org-comment-string))
17777 (while (re-search-forward re nil t)
17778 (add-text-properties
17779 (match-beginning 0) (org-end-of-subtree t) pc))))))))
17780 (setq org-todo-keywords-for-agenda
17781 (org-uniquify org-todo-keywords-for-agenda))
17782 (setq org-todo-keyword-alist-for-agenda
17783 (org-uniquify org-todo-keyword-alist-for-agenda)
17784 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17787 ;;;; CDLaTeX minor mode
17789 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17790 "Keymap for the minor `org-cdlatex-mode'.")
17792 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17793 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17794 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17795 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17796 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17798 (defvar org-cdlatex-texmathp-advice-is-done nil
17799 "Flag remembering if we have applied the advice to texmathp already.")
17801 (define-minor-mode org-cdlatex-mode
17802 "Toggle the minor `org-cdlatex-mode'.
17803 This mode supports entering LaTeX environment and math in LaTeX fragments
17804 in Org-mode.
17805 \\{org-cdlatex-mode-map}"
17806 nil " OCDL" nil
17807 (when org-cdlatex-mode
17808 (require 'cdlatex)
17809 (run-hooks 'cdlatex-mode-hook)
17810 (cdlatex-compute-tables))
17811 (unless org-cdlatex-texmathp-advice-is-done
17812 (setq org-cdlatex-texmathp-advice-is-done t)
17813 (defadvice texmathp (around org-math-always-on activate)
17814 "Always return t in org-mode buffers.
17815 This is because we want to insert math symbols without dollars even outside
17816 the LaTeX math segments. If Orgmode thinks that point is actually inside
17817 an embedded LaTeX fragment, let texmathp do its job.
17818 \\[org-cdlatex-mode-map]"
17819 (interactive)
17820 (let (p)
17821 (cond
17822 ((not (derived-mode-p 'org-mode)) ad-do-it)
17823 ((eq this-command 'cdlatex-math-symbol)
17824 (setq ad-return-value t
17825 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17827 (let ((p (org-inside-LaTeX-fragment-p)))
17828 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17829 (setq ad-return-value t
17830 texmathp-why '("Org-mode embedded math" . 0))
17831 (if p ad-do-it)))))))))
17833 (defun turn-on-org-cdlatex ()
17834 "Unconditionally turn on `org-cdlatex-mode'."
17835 (org-cdlatex-mode 1))
17837 (defun org-try-cdlatex-tab ()
17838 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17839 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17840 - inside a LaTeX fragment, or
17841 - after the first word in a line, where an abbreviation expansion could
17842 insert a LaTeX environment."
17843 (when org-cdlatex-mode
17844 (cond
17845 ;; Before any word on the line: No expansion possible.
17846 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17847 ;; Just after first word on the line: Expand it. Make sure it
17848 ;; cannot happen on headlines, though.
17849 ((save-excursion
17850 (skip-chars-backward "a-zA-Z0-9*")
17851 (skip-chars-backward " \t")
17852 (and (bolp) (not (org-at-heading-p))))
17853 (cdlatex-tab) t)
17854 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17856 (defun org-cdlatex-underscore-caret (&optional arg)
17857 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17858 Revert to the normal definition outside of these fragments."
17859 (interactive "P")
17860 (if (org-inside-LaTeX-fragment-p)
17861 (call-interactively 'cdlatex-sub-superscript)
17862 (let (org-cdlatex-mode)
17863 (call-interactively (key-binding (vector last-input-event))))))
17865 (defun org-cdlatex-math-modify (&optional arg)
17866 "Execute `cdlatex-math-modify' in LaTeX fragments.
17867 Revert to the normal definition outside of these fragments."
17868 (interactive "P")
17869 (if (org-inside-LaTeX-fragment-p)
17870 (call-interactively 'cdlatex-math-modify)
17871 (let (org-cdlatex-mode)
17872 (call-interactively (key-binding (vector last-input-event))))))
17876 ;;;; LaTeX fragments
17878 (defvar org-latex-regexps
17879 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17880 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17881 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17882 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17883 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17884 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17885 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17886 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17887 "Regular expressions for matching embedded LaTeX.")
17889 (defun org-inside-LaTeX-fragment-p ()
17890 "Test if point is inside a LaTeX fragment.
17891 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17892 sequence appearing also before point.
17893 Even though the matchers for math are configurable, this function assumes
17894 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17895 delimiters are skipped when they have been removed by customization.
17896 The return value is nil, or a cons cell with the delimiter and the
17897 position of this delimiter.
17899 This function does a reasonably good job, but can locally be fooled by
17900 for example currency specifications. For example it will assume being in
17901 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17902 fragments that are properly closed, but during editing, we have to live
17903 with the uncertainty caused by missing closing delimiters. This function
17904 looks only before point, not after."
17905 (catch 'exit
17906 (let ((pos (point))
17907 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17908 (lim (progn
17909 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17910 (point)))
17911 dd-on str (start 0) m re)
17912 (goto-char pos)
17913 (when dodollar
17914 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17915 re (nth 1 (assoc "$" org-latex-regexps)))
17916 (while (string-match re str start)
17917 (cond
17918 ((= (match-end 0) (length str))
17919 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17920 ((= (match-end 0) (- (length str) 5))
17921 (throw 'exit nil))
17922 (t (setq start (match-end 0))))))
17923 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17924 (goto-char pos)
17925 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17926 (and (match-beginning 2) (throw 'exit nil))
17927 ;; count $$
17928 (while (re-search-backward "\\$\\$" lim t)
17929 (setq dd-on (not dd-on)))
17930 (goto-char pos)
17931 (if dd-on (cons "$$" m))))))
17933 (defun org-inside-latex-macro-p ()
17934 "Is point inside a LaTeX macro or its arguments?"
17935 (save-match-data
17936 (org-in-regexp
17937 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17939 (defvar org-latex-fragment-image-overlays nil
17940 "List of overlays carrying the images of latex fragments.")
17941 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17943 (defun org-remove-latex-fragment-image-overlays ()
17944 "Remove all overlays with LaTeX fragment images in current buffer."
17945 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17946 (setq org-latex-fragment-image-overlays nil))
17948 (defun org-preview-latex-fragment (&optional subtree)
17949 "Preview the LaTeX fragment at point, or all locally or globally.
17950 If the cursor is in a LaTeX fragment, create the image and overlay
17951 it over the source code. If there is no fragment at point, display
17952 all fragments in the current text, from one headline to the next. With
17953 prefix SUBTREE, display all fragments in the current subtree. With a
17954 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17955 the cursor is before the first headline,
17956 display all fragments in the buffer.
17957 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17958 (interactive "P")
17959 (unless buffer-file-name
17960 (error "Can't preview LaTeX fragment in a non-file buffer"))
17961 (org-remove-latex-fragment-image-overlays)
17962 (save-excursion
17963 (save-restriction
17964 (let (beg end at msg)
17965 (cond
17966 ((or (equal subtree '(16))
17967 (not (save-excursion
17968 (re-search-backward org-outline-regexp-bol nil t))))
17969 (setq beg (point-min) end (point-max)
17970 msg "Creating images for buffer...%s"))
17971 ((equal subtree '(4))
17972 (org-back-to-heading)
17973 (setq beg (point) end (org-end-of-subtree t)
17974 msg "Creating images for subtree...%s"))
17976 (if (setq at (org-inside-LaTeX-fragment-p))
17977 (goto-char (max (point-min) (- (cdr at) 2)))
17978 (org-back-to-heading))
17979 (setq beg (point) end (progn (outline-next-heading) (point))
17980 msg (if at "Creating image...%s"
17981 "Creating images for entry...%s"))))
17982 (message msg "")
17983 (narrow-to-region beg end)
17984 (goto-char beg)
17985 (org-format-latex
17986 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17987 (file-name-nondirectory
17988 buffer-file-name)))
17989 default-directory 'overlays msg at 'forbuffer
17990 org-latex-create-formula-image-program)
17991 (message msg "done. Use `C-c C-c' to remove images.")))))
17993 (defun org-format-latex (prefix &optional dir overlays msg at
17994 forbuffer processing-type)
17995 "Replace LaTeX fragments with links to an image, and produce images.
17996 Some of the options can be changed using the variable
17997 `org-format-latex-options'."
17998 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17999 (let* ((prefixnodir (file-name-nondirectory prefix))
18000 (absprefix (expand-file-name prefix dir))
18001 (todir (file-name-directory absprefix))
18002 (opt org-format-latex-options)
18003 (optnew org-format-latex-options)
18004 (matchers (plist-get opt :matchers))
18005 (re-list org-latex-regexps)
18006 (cnt 0) txt hash link beg end re e checkdir
18007 string
18008 m n block-type block linkfile movefile ov)
18009 ;; Check the different regular expressions
18010 (while (setq e (pop re-list))
18011 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18012 block (if block-type "\n\n" ""))
18013 (when (member m matchers)
18014 (goto-char (point-min))
18015 (while (re-search-forward re nil t)
18016 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18017 (or (not overlays)
18018 (not (eq (get-char-property (match-beginning n)
18019 'org-overlay-type)
18020 'org-latex-overlay))))
18021 (cond
18022 ((eq processing-type 'verbatim))
18023 ((eq processing-type 'mathjax)
18024 ;; Prepare for MathJax processing.
18025 (setq string (match-string n))
18026 (when (member m '("$" "$1"))
18027 (save-excursion
18028 (delete-region (match-beginning n) (match-end n))
18029 (goto-char (match-beginning n))
18030 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18031 ((or (eq processing-type 'dvipng)
18032 (eq processing-type 'imagemagick))
18033 ;; Process to an image.
18034 (setq txt (match-string n)
18035 beg (match-beginning n) end (match-end n)
18036 cnt (1+ cnt))
18037 (let ((face (face-at-point))
18038 (fg (plist-get opt :foreground))
18039 (bg (plist-get opt :background))
18040 ;; Ensure full list is printed.
18041 print-length print-level)
18042 (when forbuffer
18043 ;; Get the colors from the face at point.
18044 (goto-char beg)
18045 (when (eq fg 'auto)
18046 (setq fg (face-attribute face :foreground nil 'default)))
18047 (when (eq bg 'auto)
18048 (setq bg (face-attribute face :background nil 'default)))
18049 (setq optnew (copy-sequence opt))
18050 (plist-put optnew :foreground fg)
18051 (plist-put optnew :background bg))
18052 (setq hash (sha1 (prin1-to-string
18053 (list org-format-latex-header
18054 org-latex-default-packages-alist
18055 org-latex-packages-alist
18056 org-format-latex-options
18057 forbuffer txt fg bg)))
18058 linkfile (format "%s_%s.png" prefix hash)
18059 movefile (format "%s_%s.png" absprefix hash)))
18060 (setq link (concat block "[[file:" linkfile "]]" block))
18061 (if msg (message msg cnt))
18062 (goto-char beg)
18063 (unless checkdir ; Ensure the directory exists.
18064 (setq checkdir t)
18065 (or (file-directory-p todir) (make-directory todir t)))
18066 (unless (file-exists-p movefile)
18067 (org-create-formula-image
18068 txt movefile optnew forbuffer processing-type))
18069 (if overlays
18070 (progn
18071 (mapc (lambda (o)
18072 (if (eq (overlay-get o 'org-overlay-type)
18073 'org-latex-overlay)
18074 (delete-overlay o)))
18075 (overlays-in beg end))
18076 (setq ov (make-overlay beg end))
18077 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18078 (if (featurep 'xemacs)
18079 (progn
18080 (overlay-put ov 'invisible t)
18081 (overlay-put
18082 ov 'end-glyph
18083 (make-glyph (vector 'png :file movefile))))
18084 (overlay-put
18085 ov 'display
18086 (list 'image :type 'png :file movefile :ascent 'center)))
18087 (push ov org-latex-fragment-image-overlays)
18088 (goto-char end))
18089 (delete-region beg end)
18090 (insert (org-add-props link
18091 (list 'org-latex-src
18092 (replace-regexp-in-string
18093 "\"" "" txt)
18094 'org-latex-src-embed-type
18095 (if block-type 'paragraph 'character))))))
18096 ((eq processing-type 'mathml)
18097 ;; Process to MathML
18098 (unless (save-match-data (org-format-latex-mathml-available-p))
18099 (error "LaTeX to MathML converter not configured"))
18100 (setq txt (match-string n)
18101 beg (match-beginning n) end (match-end n)
18102 cnt (1+ cnt))
18103 (if msg (message msg cnt))
18104 (goto-char beg)
18105 (delete-region beg end)
18106 (insert (org-format-latex-as-mathml
18107 txt block-type prefix dir)))
18109 (error "Unknown conversion type %s for latex fragments"
18110 processing-type)))))))))
18112 (defun org-create-math-formula (latex-frag &optional mathml-file)
18113 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18114 Use `org-latex-to-mathml-convert-command'. If the conversion is
18115 sucessful, return the portion between \"<math...> </math>\"
18116 elements otherwise return nil. When MATHML-FILE is specified,
18117 write the results in to that file. When invoked as an
18118 interactive command, prompt for LATEX-FRAG, with initial value
18119 set to the current active region and echo the results for user
18120 inspection."
18121 (interactive (list (let ((frag (when (org-region-active-p)
18122 (buffer-substring-no-properties
18123 (region-beginning) (region-end)))))
18124 (read-string "LaTeX Fragment: " frag nil frag))))
18125 (unless latex-frag (error "Invalid latex-frag"))
18126 (let* ((tmp-in-file (file-relative-name
18127 (make-temp-name (expand-file-name "ltxmathml-in"))))
18128 (ignore (write-region latex-frag nil tmp-in-file))
18129 (tmp-out-file (file-relative-name
18130 (make-temp-name (expand-file-name "ltxmathml-out"))))
18131 (cmd (format-spec
18132 org-latex-to-mathml-convert-command
18133 `((?j . ,(shell-quote-argument
18134 (expand-file-name org-latex-to-mathml-jar-file)))
18135 (?I . ,(shell-quote-argument tmp-in-file))
18136 (?o . ,(shell-quote-argument tmp-out-file)))))
18137 mathml shell-command-output)
18138 (when (org-called-interactively-p 'any)
18139 (unless (org-format-latex-mathml-available-p)
18140 (error "LaTeX to MathML converter not configured")))
18141 (message "Running %s" cmd)
18142 (setq shell-command-output (shell-command-to-string cmd))
18143 (setq mathml
18144 (when (file-readable-p tmp-out-file)
18145 (with-current-buffer (find-file-noselect tmp-out-file t)
18146 (goto-char (point-min))
18147 (when (re-search-forward
18148 (concat
18149 (regexp-quote
18150 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18151 "\\(.\\|\n\\)*"
18152 (regexp-quote "</math>")) nil t)
18153 (prog1 (match-string 0) (kill-buffer))))))
18154 (cond
18155 (mathml
18156 (setq mathml
18157 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18158 (when mathml-file
18159 (write-region mathml nil mathml-file))
18160 (when (org-called-interactively-p 'any)
18161 (message mathml)))
18162 ((message "LaTeX to MathML conversion failed")
18163 (message shell-command-output)))
18164 (delete-file tmp-in-file)
18165 (when (file-exists-p tmp-out-file)
18166 (delete-file tmp-out-file))
18167 mathml))
18169 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18170 prefix &optional dir)
18171 "Use `org-create-math-formula' but check local cache first."
18172 (let* ((absprefix (expand-file-name prefix dir))
18173 (print-length nil) (print-level nil)
18174 (formula-id (concat
18175 "formula-"
18176 (sha1
18177 (prin1-to-string
18178 (list latex-frag
18179 org-latex-to-mathml-convert-command)))))
18180 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18181 (formula-cache-dir (file-name-directory formula-cache)))
18183 (unless (file-directory-p formula-cache-dir)
18184 (make-directory formula-cache-dir t))
18186 (unless (file-exists-p formula-cache)
18187 (org-create-math-formula latex-frag formula-cache))
18189 (if (file-exists-p formula-cache)
18190 ;; Successful conversion. Return the link to MathML file.
18191 (org-add-props
18192 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18193 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18194 'org-latex-src-embed-type (if latex-frag-type
18195 'paragraph 'character)))
18196 ;; Failed conversion. Return the LaTeX fragment verbatim
18197 latex-frag)))
18199 (defun org-create-formula-image (string tofile options buffer &optional type)
18200 "Create an image from LaTeX source using dvipng or convert.
18201 This function calls either `org-create-formula-image-with-dvipng'
18202 or `org-create-formula-image-with-imagemagick' depending on the
18203 value of `org-latex-create-formula-image-program' or on the value
18204 of the optional TYPE variable.
18206 Note: ultimately these two function should be combined as they
18207 share a good deal of logic."
18208 (org-check-external-command
18209 "latex" "needed to convert LaTeX fragments to images")
18210 (funcall
18211 (case (or type org-latex-create-formula-image-program)
18212 ('dvipng
18213 (org-check-external-command
18214 "dvipng" "needed to convert LaTeX fragments to images")
18215 #'org-create-formula-image-with-dvipng)
18216 ('imagemagick
18217 (org-check-external-command
18218 "convert" "you need to install imagemagick")
18219 #'org-create-formula-image-with-imagemagick)
18220 (t (error
18221 "invalid value of `org-latex-create-formula-image-program'")))
18222 string tofile options buffer))
18224 (declare-function org-export--get-global-options "ox" (&optional backend))
18225 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18226 (defun org-create-formula--latex-header ()
18227 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18228 (org-latex-guess-inputenc
18229 (org-splice-latex-header
18230 org-format-latex-header
18231 org-latex-default-packages-alist
18232 org-latex-packages-alist t
18233 (plist-get
18234 (org-combine-plists
18235 (org-export--get-global-options 'latex)
18236 (org-export--get-inbuffer-options 'latex))
18237 :latex-header))))
18239 ;; This function borrows from Ganesh Swami's latex2png.el
18240 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18241 "This calls dvipng."
18242 (require 'ox-latex)
18243 (let* ((tmpdir (if (featurep 'xemacs)
18244 (temp-directory)
18245 temporary-file-directory))
18246 (texfilebase (make-temp-name
18247 (expand-file-name "orgtex" tmpdir)))
18248 (texfile (concat texfilebase ".tex"))
18249 (dvifile (concat texfilebase ".dvi"))
18250 (pngfile (concat texfilebase ".png"))
18251 (fnh (if (featurep 'xemacs)
18252 (font-height (face-font 'default))
18253 (face-attribute 'default :height nil)))
18254 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18255 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18256 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18257 "Black"))
18258 (bg (or (plist-get options (if buffer :background :html-background))
18259 "Transparent")))
18260 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18261 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18262 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18263 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18264 (let ((latex-header (org-create-formula--latex-header)))
18265 (with-temp-file texfile
18266 (insert latex-header)
18267 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18268 (let ((dir default-directory))
18269 (condition-case nil
18270 (progn
18271 (cd tmpdir)
18272 (call-process "latex" nil nil nil texfile))
18273 (error nil))
18274 (cd dir))
18275 (if (not (file-exists-p dvifile))
18276 (progn (message "Failed to create dvi file from %s" texfile) nil)
18277 (condition-case nil
18278 (if (featurep 'xemacs)
18279 (call-process "dvipng" nil nil nil
18280 "-fg" fg "-bg" bg
18281 "-T" "tight"
18282 "-o" pngfile
18283 dvifile)
18284 (call-process "dvipng" nil nil nil
18285 "-fg" fg "-bg" bg
18286 "-D" dpi
18287 ;;"-x" scale "-y" scale
18288 "-T" "tight"
18289 "-o" pngfile
18290 dvifile))
18291 (error nil))
18292 (if (not (file-exists-p pngfile))
18293 (if org-format-latex-signal-error
18294 (error "Failed to create png file from %s" texfile)
18295 (message "Failed to create png file from %s" texfile)
18296 nil)
18297 ;; Use the requested file name and clean up
18298 (copy-file pngfile tofile 'replace)
18299 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18300 (if (file-exists-p (concat texfilebase e))
18301 (delete-file (concat texfilebase e))))
18302 pngfile))))
18304 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18305 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18306 "This calls convert, which is included into imagemagick."
18307 (require 'ox-latex)
18308 (let* ((tmpdir (if (featurep 'xemacs)
18309 (temp-directory)
18310 temporary-file-directory))
18311 (texfilebase (make-temp-name
18312 (expand-file-name "orgtex" tmpdir)))
18313 (texfile (concat texfilebase ".tex"))
18314 (pdffile (concat texfilebase ".pdf"))
18315 (pngfile (concat texfilebase ".png"))
18316 (fnh (if (featurep 'xemacs)
18317 (font-height (face-font 'default))
18318 (face-attribute 'default :height nil)))
18319 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18320 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18321 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18322 "black"))
18323 (bg (or (plist-get options (if buffer :background :html-background))
18324 "white")))
18325 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18326 (setq fg (org-latex-color-format fg)))
18327 (if (eq bg 'default) (setq bg (org-latex-color :background))
18328 (setq bg (org-latex-color-format
18329 (if (string= bg "Transparent") "white" bg))))
18330 (let ((latex-header (org-create-formula--latex-header)))
18331 (with-temp-file texfile
18332 (insert latex-header)
18333 (insert "\n\\begin{document}\n"
18334 "\\definecolor{fg}{rgb}{" fg "}\n"
18335 "\\definecolor{bg}{rgb}{" bg "}\n"
18336 "\n\\pagecolor{bg}\n"
18337 "\n{\\color{fg}\n"
18338 string
18339 "\n}\n"
18340 "\n\\end{document}\n")))
18341 (org-latex-compile texfile t)
18342 (if (not (file-exists-p pdffile))
18343 (progn (message "Failed to create pdf file from %s" texfile) nil)
18344 (condition-case nil
18345 (if (featurep 'xemacs)
18346 (call-process "convert" nil nil nil
18347 "-density" "96"
18348 "-trim"
18349 "-antialias"
18350 pdffile
18351 "-quality" "100"
18352 ;; "-sharpen" "0x1.0"
18353 pngfile)
18354 (call-process "convert" nil nil nil
18355 "-density" dpi
18356 "-trim"
18357 "-antialias"
18358 pdffile
18359 "-quality" "100"
18360 ;; "-sharpen" "0x1.0"
18361 pngfile))
18362 (error nil))
18363 (if (not (file-exists-p pngfile))
18364 (if org-format-latex-signal-error
18365 (error "Failed to create png file from %s" texfile)
18366 (message "Failed to create png file from %s" texfile)
18367 nil)
18368 ;; Use the requested file name and clean up
18369 (copy-file pngfile tofile 'replace)
18370 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18371 (if (file-exists-p (concat texfilebase e))
18372 (delete-file (concat texfilebase e))))
18373 pngfile))))
18375 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18376 "Fill a LaTeX header template TPL.
18377 In the template, the following place holders will be recognized:
18379 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18380 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18381 [PACKAGES] \\usepackage statements for PKG
18382 [NO-PACKAGES] do not include PKG
18383 [EXTRA] the string EXTRA
18384 [NO-EXTRA] do not include EXTRA
18386 For backward compatibility, if both the positive and the negative place
18387 holder is missing, the positive one (without the \"NO-\") will be
18388 assumed to be present at the end of the template.
18389 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18390 EXTRA is a string.
18391 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18392 (let (rpl (end ""))
18393 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18394 (setq rpl (if (or (match-end 1) (not def-pkg))
18395 "" (org-latex-packages-to-string def-pkg snippets-p t))
18396 tpl (replace-match rpl t t tpl))
18397 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18399 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18400 (setq rpl (if (or (match-end 1) (not pkg))
18401 "" (org-latex-packages-to-string pkg snippets-p t))
18402 tpl (replace-match rpl t t tpl))
18403 (if pkg (setq end
18404 (concat end "\n"
18405 (org-latex-packages-to-string pkg snippets-p)))))
18407 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18408 (setq rpl (if (or (match-end 1) (not extra))
18409 "" (concat extra "\n"))
18410 tpl (replace-match rpl t t tpl))
18411 (if (and extra (string-match "\\S-" extra))
18412 (setq end (concat end "\n" extra))))
18414 (if (string-match "\\S-" end)
18415 (concat tpl "\n" end)
18416 tpl)))
18418 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18419 "Turn an alist of packages into a string with the \\usepackage macros."
18420 (setq pkg (mapconcat (lambda(p)
18421 (cond
18422 ((stringp p) p)
18423 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18424 (format "%% Package %s omitted" (cadr p)))
18425 ((equal "" (car p))
18426 (format "\\usepackage{%s}" (cadr p)))
18428 (format "\\usepackage[%s]{%s}"
18429 (car p) (cadr p)))))
18431 "\n"))
18432 (if newline (concat pkg "\n") pkg))
18434 (defun org-dvipng-color (attr)
18435 "Return a RGB color specification for dvipng."
18436 (apply 'format "rgb %s %s %s"
18437 (mapcar 'org-normalize-color
18438 (if (featurep 'xemacs)
18439 (color-rgb-components
18440 (face-property 'default
18441 (cond ((eq attr :foreground) 'foreground)
18442 ((eq attr :background) 'background))))
18443 (color-values (face-attribute 'default attr nil))))))
18445 (defun org-dvipng-color-format (color-name)
18446 "Convert COLOR-NAME to a RGB color value for dvipng."
18447 (apply 'format "rgb %s %s %s"
18448 (mapcar 'org-normalize-color
18449 (color-values color-name))))
18451 (defun org-latex-color (attr)
18452 "Return a RGB color for the LaTeX color package."
18453 (apply 'format "%s,%s,%s"
18454 (mapcar 'org-normalize-color
18455 (if (featurep 'xemacs)
18456 (color-rgb-components
18457 (face-property 'default
18458 (cond ((eq attr :foreground) 'foreground)
18459 ((eq attr :background) 'background))))
18460 (color-values (face-attribute 'default attr nil))))))
18462 (defun org-latex-color-format (color-name)
18463 "Convert COLOR-NAME to a RGB color value."
18464 (apply 'format "%s,%s,%s"
18465 (mapcar 'org-normalize-color
18466 (color-values color-name))))
18468 (defun org-normalize-color (value)
18469 "Return string to be used as color value for an RGB component."
18470 (format "%g" (/ value 65535.0)))
18474 ;; Image display
18476 (defvar org-inline-image-overlays nil)
18477 (make-variable-buffer-local 'org-inline-image-overlays)
18479 (defun org-toggle-inline-images (&optional include-linked)
18480 "Toggle the display of inline images.
18481 INCLUDE-LINKED is passed to `org-display-inline-images'."
18482 (interactive "P")
18483 (if org-inline-image-overlays
18484 (progn
18485 (org-remove-inline-images)
18486 (message "Inline image display turned off"))
18487 (org-display-inline-images include-linked)
18488 (if (and (org-called-interactively-p)
18489 org-inline-image-overlays)
18490 (message "%d images displayed inline"
18491 (length org-inline-image-overlays))
18492 (message "No images to display inline"))))
18494 (defun org-redisplay-inline-images ()
18495 "Refresh the display of inline images."
18496 (interactive)
18497 (if (not org-inline-image-overlays)
18498 (org-toggle-inline-images)
18499 (org-toggle-inline-images)
18500 (org-toggle-inline-images)))
18502 (defun org-display-inline-images (&optional include-linked refresh beg end)
18503 "Display inline images.
18504 Normally only links without a description part are inlined, because this
18505 is how it will work for export. When INCLUDE-LINKED is set, also links
18506 with a description part will be inlined. This can be nice for a quick
18507 look at those images, but it does not reflect what exported files will look
18508 like.
18509 When REFRESH is set, refresh existing images between BEG and END.
18510 This will create new image displays only if necessary.
18511 BEG and END default to the buffer boundaries."
18512 (interactive "P")
18513 (unless refresh
18514 (org-remove-inline-images)
18515 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18516 (save-excursion
18517 (save-restriction
18518 (widen)
18519 (setq beg (or beg (point-min)) end (or end (point-max)))
18520 (goto-char beg)
18521 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18522 (substring (org-image-file-name-regexp) 0 -2)
18523 "\\)\\]" (if include-linked "" "\\]")))
18524 old file ov img type attrwidth width)
18525 (while (re-search-forward re end t)
18526 (setq old (get-char-property-and-overlay (match-beginning 1)
18527 'org-image-overlay)
18528 file (expand-file-name
18529 (concat (or (match-string 3) "") (match-string 4))))
18530 (when (image-type-available-p 'imagemagick)
18531 (setq attrwidth (if (or (listp org-image-actual-width)
18532 (null org-image-actual-width))
18533 (save-excursion
18534 (save-match-data
18535 (when (re-search-backward
18536 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18537 (save-excursion
18538 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18539 (string-to-number (match-string 1))))))
18540 width (cond ((eq org-image-actual-width t) nil)
18541 ((null org-image-actual-width) attrwidth)
18542 ((numberp org-image-actual-width)
18543 org-image-actual-width)
18544 ((listp org-image-actual-width)
18545 (or attrwidth (car org-image-actual-width))))
18546 type (if width 'imagemagick)))
18547 (when (file-exists-p file)
18548 (if (and (car-safe old) refresh)
18549 (image-refresh (overlay-get (cdr old) 'display))
18550 (setq img (save-match-data (create-image file type nil :width width)))
18551 (when img
18552 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18553 (overlay-put ov 'display img)
18554 (overlay-put ov 'face 'default)
18555 (overlay-put ov 'org-image-overlay t)
18556 (overlay-put ov 'modification-hooks
18557 (list 'org-display-inline-remove-overlay))
18558 (push ov org-inline-image-overlays)))))))))
18560 (define-obsolete-function-alias
18561 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18563 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18564 "Remove inline-display overlay if a corresponding region is modified."
18565 (let ((inhibit-modification-hooks t))
18566 (when (and ov after)
18567 (delete ov org-inline-image-overlays)
18568 (delete-overlay ov))))
18570 (defun org-remove-inline-images ()
18571 "Remove inline display of images."
18572 (interactive)
18573 (mapc 'delete-overlay org-inline-image-overlays)
18574 (setq org-inline-image-overlays nil))
18576 ;;;; Key bindings
18578 ;; Outline functions from `outline-mode-prefix-map'
18579 ;; that can be remapped in Org:
18580 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18581 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18582 (define-key org-mode-map [remap outline-forward-same-level]
18583 'org-forward-heading-same-level)
18584 (define-key org-mode-map [remap outline-backward-same-level]
18585 'org-backward-heading-same-level)
18586 (define-key org-mode-map [remap show-branches]
18587 'org-kill-note-or-show-branches)
18588 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18589 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18590 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18592 ;; Outline functions from `outline-mode-prefix-map' that can not
18593 ;; be remapped in Org:
18595 ;; - the column "key binding" shows whether the Outline function is still
18596 ;; available in Org mode on the same key that it has been bound to in
18597 ;; Outline mode:
18598 ;; - "overridden": key used for a different functionality in Org mode
18599 ;; - else: key still bound to the same Outline function in Org mode
18601 ;; | Outline function | key binding | Org replacement |
18602 ;; |------------------------------------+-------------+-----------------------|
18603 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18604 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18605 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18606 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18607 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18608 ;; | `show-entry' | overridden | no replacement |
18609 ;; | `show-children' | `C-c C-i' | visibility cycling |
18610 ;; | `show-branches' | `C-c C-k' | still same function |
18611 ;; | `show-subtree' | overridden | visibility cycling |
18612 ;; | `show-all' | overridden | no replacement |
18613 ;; | `hide-subtree' | overridden | visibility cycling |
18614 ;; | `hide-body' | overridden | no replacement |
18615 ;; | `hide-entry' | overridden | visibility cycling |
18616 ;; | `hide-leaves' | overridden | no replacement |
18617 ;; | `hide-sublevels' | overridden | no replacement |
18618 ;; | `hide-other' | overridden | no replacement |
18620 ;; Make `C-c C-x' a prefix key
18621 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18623 ;; TAB key with modifiers
18624 (org-defkey org-mode-map "\C-i" 'org-cycle)
18625 (org-defkey org-mode-map [(tab)] 'org-cycle)
18626 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18627 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18628 ;; The following line is necessary under Suse GNU/Linux
18629 (unless (featurep 'xemacs)
18630 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18631 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18632 (define-key org-mode-map [backtab] 'org-shifttab)
18634 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18635 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18636 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18638 ;; Cursor keys with modifiers
18639 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18640 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18641 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18642 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18644 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18645 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18646 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18647 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18649 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18650 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18651 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18652 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18654 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18655 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18656 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18657 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18659 ;; Babel keys
18660 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18661 (mapc (lambda (pair)
18662 (define-key org-babel-map (car pair) (cdr pair)))
18663 org-babel-key-bindings)
18665 ;;; Extra keys for tty access.
18666 ;; We only set them when really needed because otherwise the
18667 ;; menus don't show the simple keys
18669 (when (or org-use-extra-keys
18670 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18671 (not window-system))
18672 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18673 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18674 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18675 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18676 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18677 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18678 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18679 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18680 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18681 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18682 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18683 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18684 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18685 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18686 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18687 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18688 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18689 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18690 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18691 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18692 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18693 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18694 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18695 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18696 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18697 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18698 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18699 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18701 ;; All the other keys
18703 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18704 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18705 (if (boundp 'narrow-map)
18706 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18707 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18708 (if (boundp 'narrow-map)
18709 (org-defkey narrow-map "b" 'org-narrow-to-block)
18710 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18711 (if (boundp 'narrow-map)
18712 (org-defkey narrow-map "e" 'org-narrow-to-element)
18713 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18714 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18715 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18716 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18717 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18718 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18719 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18720 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18721 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18722 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18723 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18724 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18725 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18726 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18727 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18728 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18729 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18730 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18731 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18732 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18733 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18734 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18735 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18736 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18737 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18738 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18739 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18740 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18741 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18742 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18743 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18744 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18745 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18746 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18747 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18748 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18749 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18750 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18751 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18752 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18753 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18754 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18755 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18756 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18757 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18758 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18759 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18760 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18761 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18762 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18763 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18764 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18765 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18766 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18767 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18768 (org-defkey org-mode-map "\C-c^" 'org-sort)
18769 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18770 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18771 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18772 (org-defkey org-mode-map "\C-m" 'org-return)
18773 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18774 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18775 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18776 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18777 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18778 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18779 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18780 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18781 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18782 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18783 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18784 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18785 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18786 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
18787 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18788 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18789 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18790 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18791 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18792 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18793 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18794 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18795 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18797 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18798 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18799 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18801 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18802 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18803 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18804 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18805 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18806 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18807 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18808 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18809 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18810 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18811 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18812 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18813 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18814 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18815 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18816 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18817 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18818 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18819 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18820 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18821 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18822 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18823 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18825 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18826 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18827 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18828 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18829 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18831 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18833 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18835 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18836 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18838 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18841 (when (featurep 'xemacs)
18842 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18845 (defconst org-speed-commands-default
18847 ("Outline Navigation")
18848 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18849 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18850 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18851 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18852 ("F" . org-next-block)
18853 ("B" . org-previous-block)
18854 ("u" . (org-speed-move-safe 'outline-up-heading))
18855 ("j" . org-goto)
18856 ("g" . (org-refile t))
18857 ("Outline Visibility")
18858 ("c" . org-cycle)
18859 ("C" . org-shifttab)
18860 (" " . org-display-outline-path)
18861 ("=" . org-columns)
18862 ("Outline Structure Editing")
18863 ("U" . org-shiftmetaup)
18864 ("D" . org-shiftmetadown)
18865 ("r" . org-metaright)
18866 ("l" . org-metaleft)
18867 ("R" . org-shiftmetaright)
18868 ("L" . org-shiftmetaleft)
18869 ("i" . (progn (forward-char 1) (call-interactively
18870 'org-insert-heading-respect-content)))
18871 ("^" . org-sort)
18872 ("w" . org-refile)
18873 ("a" . org-archive-subtree-default-with-confirmation)
18874 ("@" . org-mark-subtree)
18875 ("#" . org-toggle-comment)
18876 ("Clock Commands")
18877 ("I" . org-clock-in)
18878 ("O" . org-clock-out)
18879 ("Meta Data Editing")
18880 ("t" . org-todo)
18881 ("," . (org-priority))
18882 ("0" . (org-priority ?\ ))
18883 ("1" . (org-priority ?A))
18884 ("2" . (org-priority ?B))
18885 ("3" . (org-priority ?C))
18886 (":" . org-set-tags-command)
18887 ("e" . org-set-effort)
18888 ("E" . org-inc-effort)
18889 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18890 (org-entry-put (point) "APPT_WARNTIME" m)))
18891 ("Agenda Views etc")
18892 ("v" . org-agenda)
18893 ("/" . org-sparse-tree)
18894 ("Misc")
18895 ("o" . org-open-at-point)
18896 ("?" . org-speed-command-help)
18897 ("<" . (org-agenda-set-restriction-lock 'subtree))
18898 (">" . (org-agenda-remove-restriction-lock))
18900 "The default speed commands.")
18902 (defun org-print-speed-command (e)
18903 (if (> (length (car e)) 1)
18904 (progn
18905 (princ "\n")
18906 (princ (car e))
18907 (princ "\n")
18908 (princ (make-string (length (car e)) ?-))
18909 (princ "\n"))
18910 (princ (car e))
18911 (princ " ")
18912 (if (symbolp (cdr e))
18913 (princ (symbol-name (cdr e)))
18914 (prin1 (cdr e)))
18915 (princ "\n")))
18917 (defun org-speed-command-help ()
18918 "Show the available speed commands."
18919 (interactive)
18920 (if (not org-use-speed-commands)
18921 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18922 (with-output-to-temp-buffer "*Help*"
18923 (princ "User-defined Speed commands\n===========================\n")
18924 (mapc 'org-print-speed-command org-speed-commands-user)
18925 (princ "\n")
18926 (princ "Built-in Speed commands\n=======================\n")
18927 (mapc 'org-print-speed-command org-speed-commands-default))
18928 (with-current-buffer "*Help*"
18929 (setq truncate-lines t))))
18931 (defun org-speed-move-safe (cmd)
18932 "Execute CMD, but make sure that the cursor always ends up in a headline.
18933 If not, return to the original position and throw an error."
18934 (interactive)
18935 (let ((pos (point)))
18936 (call-interactively cmd)
18937 (unless (and (bolp) (org-at-heading-p))
18938 (goto-char pos)
18939 (error "Boundary reached while executing %s" cmd))))
18941 (defvar org-self-insert-command-undo-counter 0)
18943 (defvar org-table-auto-blank-field) ; defined in org-table.el
18944 (defvar org-speed-command nil)
18946 (define-obsolete-function-alias
18947 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18949 (defun org-speed-command-activate (keys)
18950 "Hook for activating single-letter speed commands.
18951 `org-speed-commands-default' specifies a minimal command set.
18952 Use `org-speed-commands-user' for further customization."
18953 (when (or (and (bolp) (looking-at org-outline-regexp))
18954 (and (functionp org-use-speed-commands)
18955 (funcall org-use-speed-commands)))
18956 (cdr (assoc keys (append org-speed-commands-user
18957 org-speed-commands-default)))))
18959 (define-obsolete-function-alias
18960 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18962 (defun org-babel-speed-command-activate (keys)
18963 "Hook for activating single-letter code block commands."
18964 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18965 (cdr (assoc keys org-babel-key-bindings))))
18967 (defcustom org-speed-command-hook
18968 '(org-speed-command-default-hook org-babel-speed-command-hook)
18969 "Hook for activating speed commands at strategic locations.
18970 Hook functions are called in sequence until a valid handler is
18971 found.
18973 Each hook takes a single argument, a user-pressed command key
18974 which is also a `self-insert-command' from the global map.
18976 Within the hook, examine the cursor position and the command key
18977 and return nil or a valid handler as appropriate. Handler could
18978 be one of an interactive command, a function, or a form.
18980 Set `org-use-speed-commands' to non-nil value to enable this
18981 hook. The default setting is `org-speed-command-activate'."
18982 :group 'org-structure
18983 :version "24.1"
18984 :type 'hook)
18986 (defun org-self-insert-command (N)
18987 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18988 If the cursor is in a table looking at whitespace, the whitespace is
18989 overwritten, and the table is not marked as requiring realignment."
18990 (interactive "p")
18991 (org-check-before-invisible-edit 'insert)
18992 (cond
18993 ((and org-use-speed-commands
18994 (setq org-speed-command
18995 (run-hook-with-args-until-success
18996 'org-speed-command-hook (this-command-keys))))
18997 (cond
18998 ((commandp org-speed-command)
18999 (setq this-command org-speed-command)
19000 (call-interactively org-speed-command))
19001 ((functionp org-speed-command)
19002 (funcall org-speed-command))
19003 ((and org-speed-command (listp org-speed-command))
19004 (eval org-speed-command))
19005 (t (let (org-use-speed-commands)
19006 (call-interactively 'org-self-insert-command)))))
19007 ((and
19008 (org-table-p)
19009 (progn
19010 ;; check if we blank the field, and if that triggers align
19011 (and (featurep 'org-table) org-table-auto-blank-field
19012 (member last-command
19013 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19014 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19015 ;; got extra space, this field does not determine column width
19016 (let (org-table-may-need-update) (org-table-blank-field))
19017 ;; no extra space, this field may determine column width
19018 (org-table-blank-field)))
19020 (eq N 1)
19021 (looking-at "[^|\n]* |"))
19022 (let (org-table-may-need-update)
19023 (goto-char (1- (match-end 0)))
19024 (backward-delete-char 1)
19025 (goto-char (match-beginning 0))
19026 (self-insert-command N)))
19028 (setq org-table-may-need-update t)
19029 (self-insert-command N)
19030 (org-fix-tags-on-the-fly)
19031 (if org-self-insert-cluster-for-undo
19032 (if (not (eq last-command 'org-self-insert-command))
19033 (setq org-self-insert-command-undo-counter 1)
19034 (if (>= org-self-insert-command-undo-counter 20)
19035 (setq org-self-insert-command-undo-counter 1)
19036 (and (> org-self-insert-command-undo-counter 0)
19037 buffer-undo-list (listp buffer-undo-list)
19038 (not (cadr buffer-undo-list)) ; remove nil entry
19039 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19040 (setq org-self-insert-command-undo-counter
19041 (1+ org-self-insert-command-undo-counter))))))))
19043 (defun org-check-before-invisible-edit (kind)
19044 "Check is editing if kind KIND would be dangerous with invisible text around.
19045 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19046 ;; First, try to get out of here as quickly as possible, to reduce overhead
19047 (if (and org-catch-invisible-edits
19048 (or (not (boundp 'visible-mode)) (not visible-mode))
19049 (or (get-char-property (point) 'invisible)
19050 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19051 ;; OK, we need to take a closer look
19052 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19053 (invisible-before-point (if (bobp) nil (get-char-property
19054 (1- (point)) 'invisible)))
19055 (border-and-ok-direction
19057 ;; Check if we are acting predictably before invisible text
19058 (and invisible-at-point (not invisible-before-point)
19059 (memq kind '(insert delete-backward)))
19060 ;; Check if we are acting predictably after invisible text
19061 ;; This works not well, and I have turned it off. It seems
19062 ;; better to always show and stop after invisible text.
19063 ;; (and (not invisible-at-point) invisible-before-point
19064 ;; (memq kind '(insert delete)))
19066 (when (or (memq invisible-at-point '(outline org-hide-block t))
19067 (memq invisible-before-point '(outline org-hide-block t)))
19068 (if (eq org-catch-invisible-edits 'error)
19069 (error "Editing in invisible areas is prohibited - make visible first"))
19070 (if (and org-custom-properties-overlays
19071 (y-or-n-p "Display invisible properties in this buffer? "))
19072 (org-toggle-custom-properties-visibility)
19073 ;; Make the area visible
19074 (save-excursion
19075 (if invisible-before-point
19076 (goto-char (previous-single-char-property-change
19077 (point) 'invisible)))
19078 (org-cycle))
19079 (cond
19080 ((eq org-catch-invisible-edits 'show)
19081 ;; That's it, we do the edit after showing
19082 (message
19083 "Unfolding invisible region around point before editing")
19084 (sit-for 1))
19085 ((and (eq org-catch-invisible-edits 'smart)
19086 border-and-ok-direction)
19087 (message "Unfolding invisible region around point before editing"))
19089 ;; Don't do the edit, make the user repeat it in full visibility
19090 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19092 (defun org-fix-tags-on-the-fly ()
19093 (when (and (equal (char-after (point-at-bol)) ?*)
19094 (org-at-heading-p))
19095 (org-align-tags-here org-tags-column)))
19097 (defun org-delete-backward-char (N)
19098 "Like `delete-backward-char', insert whitespace at field end in tables.
19099 When deleting backwards, in tables this function will insert whitespace in
19100 front of the next \"|\" separator, to keep the table aligned. The table will
19101 still be marked for re-alignment if the field did fill the entire column,
19102 because, in this case the deletion might narrow the column."
19103 (interactive "p")
19104 (save-match-data
19105 (org-check-before-invisible-edit 'delete-backward)
19106 (if (and (org-table-p)
19107 (eq N 1)
19108 (string-match "|" (buffer-substring (point-at-bol) (point)))
19109 (looking-at ".*?|"))
19110 (let ((pos (point))
19111 (noalign (looking-at "[^|\n\r]* |"))
19112 (c org-table-may-need-update))
19113 (backward-delete-char N)
19114 (if (not overwrite-mode)
19115 (progn
19116 (skip-chars-forward "^|")
19117 (insert " ")
19118 (goto-char (1- pos))))
19119 ;; noalign: if there were two spaces at the end, this field
19120 ;; does not determine the width of the column.
19121 (if noalign (setq org-table-may-need-update c)))
19122 (backward-delete-char N)
19123 (org-fix-tags-on-the-fly))))
19125 (defun org-delete-char (N)
19126 "Like `delete-char', but insert whitespace at field end in tables.
19127 When deleting characters, in tables this function will insert whitespace in
19128 front of the next \"|\" separator, to keep the table aligned. The table will
19129 still be marked for re-alignment if the field did fill the entire column,
19130 because, in this case the deletion might narrow the column."
19131 (interactive "p")
19132 (save-match-data
19133 (org-check-before-invisible-edit 'delete)
19134 (if (and (org-table-p)
19135 (not (bolp))
19136 (not (= (char-after) ?|))
19137 (eq N 1))
19138 (if (looking-at ".*?|")
19139 (let ((pos (point))
19140 (noalign (looking-at "[^|\n\r]* |"))
19141 (c org-table-may-need-update))
19142 (replace-match
19143 (concat (substring (match-string 0) 1 -1) " |") nil t)
19144 (goto-char pos)
19145 ;; noalign: if there were two spaces at the end, this field
19146 ;; does not determine the width of the column.
19147 (if noalign (setq org-table-may-need-update c)))
19148 (delete-char N))
19149 (delete-char N)
19150 (org-fix-tags-on-the-fly))))
19152 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19153 (put 'org-self-insert-command 'delete-selection t)
19154 (put 'orgtbl-self-insert-command 'delete-selection t)
19155 (put 'org-delete-char 'delete-selection 'supersede)
19156 (put 'org-delete-backward-char 'delete-selection 'supersede)
19157 (put 'org-yank 'delete-selection 'yank)
19159 ;; Make `flyspell-mode' delay after some commands
19160 (put 'org-self-insert-command 'flyspell-delayed t)
19161 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19162 (put 'org-delete-char 'flyspell-delayed t)
19163 (put 'org-delete-backward-char 'flyspell-delayed t)
19165 ;; Make pabbrev-mode expand after org-mode commands
19166 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19167 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19169 ;; How to do this: Measure non-white length of current string
19170 ;; If equal to column width, we should realign.
19172 (defun org-remap (map &rest commands)
19173 "In MAP, remap the functions given in COMMANDS.
19174 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19175 (let (new old)
19176 (while commands
19177 (setq old (pop commands) new (pop commands))
19178 (if (fboundp 'command-remapping)
19179 (org-defkey map (vector 'remap old) new)
19180 (substitute-key-definition old new map global-map)))))
19182 (defun org-transpose-words ()
19183 "Transpose words for Org.
19184 This uses the `org-mode-transpose-word-syntax-table' syntax
19185 table, which interprets characters in `org-emphasis-alist' as
19186 word constituants."
19187 (interactive)
19188 (with-syntax-table org-mode-transpose-word-syntax-table
19189 (call-interactively 'transpose-words)))
19190 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19192 (when (eq org-enable-table-editor 'optimized)
19193 ;; If the user wants maximum table support, we need to hijack
19194 ;; some standard editing functions
19195 (org-remap org-mode-map
19196 'self-insert-command 'org-self-insert-command
19197 'delete-char 'org-delete-char
19198 'delete-backward-char 'org-delete-backward-char)
19199 (org-defkey org-mode-map "|" 'org-force-self-insert))
19201 (defvar org-ctrl-c-ctrl-c-hook nil
19202 "Hook for functions attaching themselves to `C-c C-c'.
19204 This can be used to add additional functionality to the C-c C-c
19205 key which executes context-dependent commands. This hook is run
19206 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19207 run after the last test.
19209 Each function will be called with no arguments. The function
19210 must check if the context is appropriate for it to act. If yes,
19211 it should do its thing and then return a non-nil value. If the
19212 context is wrong, just do nothing and return nil.")
19214 (defvar org-ctrl-c-ctrl-c-final-hook nil
19215 "Hook for functions attaching themselves to `C-c C-c'.
19217 This can be used to add additional functionality to the C-c C-c
19218 key which executes context-dependent commands. This hook is run
19219 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19220 before the first test.
19222 Each function will be called with no arguments. The function
19223 must check if the context is appropriate for it to act. If yes,
19224 it should do its thing and then return a non-nil value. If the
19225 context is wrong, just do nothing and return nil.")
19227 (defvar org-tab-first-hook nil
19228 "Hook for functions to attach themselves to TAB.
19229 See `org-ctrl-c-ctrl-c-hook' for more information.
19230 This hook runs as the first action when TAB is pressed, even before
19231 `org-cycle' messes around with the `outline-regexp' to cater for
19232 inline tasks and plain list item folding.
19233 If any function in this hook returns t, any other actions that
19234 would have been caused by TAB (such as table field motion or visibility
19235 cycling) will not occur.")
19237 (defvar org-tab-after-check-for-table-hook nil
19238 "Hook for functions to attach themselves to TAB.
19239 See `org-ctrl-c-ctrl-c-hook' for more information.
19240 This hook runs after it has been established that the cursor is not in a
19241 table, but before checking if the cursor is in a headline or if global cycling
19242 should be done.
19243 If any function in this hook returns t, not other actions like visibility
19244 cycling will be done.")
19246 (defvar org-tab-after-check-for-cycling-hook nil
19247 "Hook for functions to attach themselves to TAB.
19248 See `org-ctrl-c-ctrl-c-hook' for more information.
19249 This hook runs after it has been established that not table field motion and
19250 not visibility should be done because of current context. This is probably
19251 the place where a package like yasnippets can hook in.")
19253 (defvar org-tab-before-tab-emulation-hook nil
19254 "Hook for functions to attach themselves to TAB.
19255 See `org-ctrl-c-ctrl-c-hook' for more information.
19256 This hook runs after every other options for TAB have been exhausted, but
19257 before indentation and \t insertion takes place.")
19259 (defvar org-metaleft-hook nil
19260 "Hook for functions attaching themselves to `M-left'.
19261 See `org-ctrl-c-ctrl-c-hook' for more information.")
19262 (defvar org-metaright-hook nil
19263 "Hook for functions attaching themselves to `M-right'.
19264 See `org-ctrl-c-ctrl-c-hook' for more information.")
19265 (defvar org-metaup-hook nil
19266 "Hook for functions attaching themselves to `M-up'.
19267 See `org-ctrl-c-ctrl-c-hook' for more information.")
19268 (defvar org-metadown-hook nil
19269 "Hook for functions attaching themselves to `M-down'.
19270 See `org-ctrl-c-ctrl-c-hook' for more information.")
19271 (defvar org-shiftmetaleft-hook nil
19272 "Hook for functions attaching themselves to `M-S-left'.
19273 See `org-ctrl-c-ctrl-c-hook' for more information.")
19274 (defvar org-shiftmetaright-hook nil
19275 "Hook for functions attaching themselves to `M-S-right'.
19276 See `org-ctrl-c-ctrl-c-hook' for more information.")
19277 (defvar org-shiftmetaup-hook nil
19278 "Hook for functions attaching themselves to `M-S-up'.
19279 See `org-ctrl-c-ctrl-c-hook' for more information.")
19280 (defvar org-shiftmetadown-hook nil
19281 "Hook for functions attaching themselves to `M-S-down'.
19282 See `org-ctrl-c-ctrl-c-hook' for more information.")
19283 (defvar org-metareturn-hook nil
19284 "Hook for functions attaching themselves to `M-RET'.
19285 See `org-ctrl-c-ctrl-c-hook' for more information.")
19286 (defvar org-shiftup-hook nil
19287 "Hook for functions attaching themselves to `S-up'.
19288 See `org-ctrl-c-ctrl-c-hook' for more information.")
19289 (defvar org-shiftup-final-hook nil
19290 "Hook for functions attaching themselves to `S-up'.
19291 This one runs after all other options except shift-select have been excluded.
19292 See `org-ctrl-c-ctrl-c-hook' for more information.")
19293 (defvar org-shiftdown-hook nil
19294 "Hook for functions attaching themselves to `S-down'.
19295 See `org-ctrl-c-ctrl-c-hook' for more information.")
19296 (defvar org-shiftdown-final-hook nil
19297 "Hook for functions attaching themselves to `S-down'.
19298 This one runs after all other options except shift-select have been excluded.
19299 See `org-ctrl-c-ctrl-c-hook' for more information.")
19300 (defvar org-shiftleft-hook nil
19301 "Hook for functions attaching themselves to `S-left'.
19302 See `org-ctrl-c-ctrl-c-hook' for more information.")
19303 (defvar org-shiftleft-final-hook nil
19304 "Hook for functions attaching themselves to `S-left'.
19305 This one runs after all other options except shift-select have been excluded.
19306 See `org-ctrl-c-ctrl-c-hook' for more information.")
19307 (defvar org-shiftright-hook nil
19308 "Hook for functions attaching themselves to `S-right'.
19309 See `org-ctrl-c-ctrl-c-hook' for more information.")
19310 (defvar org-shiftright-final-hook nil
19311 "Hook for functions attaching themselves to `S-right'.
19312 This one runs after all other options except shift-select have been excluded.
19313 See `org-ctrl-c-ctrl-c-hook' for more information.")
19315 (defun org-modifier-cursor-error ()
19316 "Throw an error, a modified cursor command was applied in wrong context."
19317 (error "This command is active in special context like tables, headlines or items"))
19319 (defun org-shiftselect-error ()
19320 "Throw an error because Shift-Cursor command was applied in wrong context."
19321 (if (and (boundp 'shift-select-mode) shift-select-mode)
19322 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19323 (error "This command works only in special context like headlines or timestamps")))
19325 (defun org-call-for-shift-select (cmd)
19326 (let ((this-command-keys-shift-translated t))
19327 (call-interactively cmd)))
19329 (defun org-shifttab (&optional arg)
19330 "Global visibility cycling or move to previous table field.
19331 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19332 on context.
19333 See the individual commands for more information."
19334 (interactive "P")
19335 (cond
19336 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19337 ((integerp arg)
19338 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19339 (message "Content view to level: %d" arg)
19340 (org-content (prefix-numeric-value arg2))
19341 (setq org-cycle-global-status 'overview)))
19342 (t (call-interactively 'org-global-cycle))))
19344 (defun org-shiftmetaleft ()
19345 "Promote subtree or delete table column.
19346 Calls `org-promote-subtree', `org-outdent-item-tree', or
19347 `org-table-delete-column', depending on context. See the
19348 individual commands for more information."
19349 (interactive)
19350 (cond
19351 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19352 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19353 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19354 ((if (not (org-region-active-p)) (org-at-item-p)
19355 (save-excursion (goto-char (region-beginning))
19356 (org-at-item-p)))
19357 (call-interactively 'org-outdent-item-tree))
19358 (t (org-modifier-cursor-error))))
19360 (defun org-shiftmetaright ()
19361 "Demote subtree or insert table column.
19362 Calls `org-demote-subtree', `org-indent-item-tree', or
19363 `org-table-insert-column', depending on context. See the
19364 individual commands for more information."
19365 (interactive)
19366 (cond
19367 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19368 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19369 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19370 ((if (not (org-region-active-p)) (org-at-item-p)
19371 (save-excursion (goto-char (region-beginning))
19372 (org-at-item-p)))
19373 (call-interactively 'org-indent-item-tree))
19374 (t (org-modifier-cursor-error))))
19376 (defun org-shiftmetaup (&optional arg)
19377 "Move subtree up or kill table row.
19378 Calls `org-move-subtree-up' or `org-table-kill-row' or
19379 `org-move-item-up' or `org-timestamp-up', depending on context.
19380 See the individual commands for more information."
19381 (interactive "P")
19382 (cond
19383 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19384 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19385 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19386 ((org-at-item-p) (call-interactively 'org-move-item-up))
19387 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19388 (call-interactively 'org-timestamp-up)))
19389 (t (call-interactively 'org-drag-line-backward))))
19391 (defun org-shiftmetadown (&optional arg)
19392 "Move subtree down or insert table row.
19393 Calls `org-move-subtree-down' or `org-table-insert-row' or
19394 `org-move-item-down' or `org-timestamp-up', depending on context.
19395 See the individual commands for more information."
19396 (interactive "P")
19397 (cond
19398 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19399 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19400 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19401 ((org-at-item-p) (call-interactively 'org-move-item-down))
19402 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19403 (call-interactively 'org-timestamp-down)))
19404 (t (call-interactively 'org-drag-line-forward))))
19406 (defsubst org-hidden-tree-error ()
19407 (error
19408 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19410 (defun org-metaleft (&optional arg)
19411 "Promote heading or move table column to left.
19412 Calls `org-do-promote' or `org-table-move-column', depending on context.
19413 With no specific context, calls the Emacs default `backward-word'.
19414 See the individual commands for more information."
19415 (interactive "P")
19416 (cond
19417 ((run-hook-with-args-until-success 'org-metaleft-hook))
19418 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19419 ((org-with-limited-levels
19420 (or (org-at-heading-p)
19421 (and (org-region-active-p)
19422 (save-excursion
19423 (goto-char (region-beginning))
19424 (org-at-heading-p)))))
19425 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19426 (call-interactively 'org-do-promote))
19427 ;; At an inline task.
19428 ((org-at-heading-p)
19429 (call-interactively 'org-inlinetask-promote))
19430 ((or (org-at-item-p)
19431 (and (org-region-active-p)
19432 (save-excursion
19433 (goto-char (region-beginning))
19434 (org-at-item-p))))
19435 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19436 (call-interactively 'org-outdent-item))
19437 (t (call-interactively 'backward-word))))
19439 (defun org-metaright (&optional arg)
19440 "Demote a subtree, a list item or move table column to right.
19441 In front of a drawer or a block keyword, indent it correctly.
19442 With no specific context, calls the Emacs default `forward-word'.
19443 See the individual commands for more information."
19444 (interactive "P")
19445 (cond
19446 ((run-hook-with-args-until-success 'org-metaright-hook))
19447 ((org-at-table-p) (call-interactively 'org-table-move-column))
19448 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19449 ((org-at-block-p) (call-interactively 'org-indent-block))
19450 ((org-with-limited-levels
19451 (or (org-at-heading-p)
19452 (and (org-region-active-p)
19453 (save-excursion
19454 (goto-char (region-beginning))
19455 (org-at-heading-p)))))
19456 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19457 (call-interactively 'org-do-demote))
19458 ;; At an inline task.
19459 ((org-at-heading-p)
19460 (call-interactively 'org-inlinetask-demote))
19461 ((or (org-at-item-p)
19462 (and (org-region-active-p)
19463 (save-excursion
19464 (goto-char (region-beginning))
19465 (org-at-item-p))))
19466 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19467 (call-interactively 'org-indent-item))
19468 (t (call-interactively 'forward-word))))
19470 (defun org-check-for-hidden (what)
19471 "Check if there are hidden headlines/items in the current visual line.
19472 WHAT can be either `headlines' or `items'. If the current line is
19473 an outline or item heading and it has a folded subtree below it,
19474 this function returns t, nil otherwise."
19475 (let ((re (cond
19476 ((eq what 'headlines) org-outline-regexp-bol)
19477 ((eq what 'items) (org-item-beginning-re))
19478 (t (error "This should not happen"))))
19479 beg end)
19480 (save-excursion
19481 (catch 'exit
19482 (unless (org-region-active-p)
19483 (setq beg (point-at-bol))
19484 (beginning-of-line 2)
19485 (while (and (not (eobp)) ;; this is like `next-line'
19486 (get-char-property (1- (point)) 'invisible))
19487 (beginning-of-line 2))
19488 (setq end (point))
19489 (goto-char beg)
19490 (goto-char (point-at-eol))
19491 (setq end (max end (point)))
19492 (while (re-search-forward re end t)
19493 (if (get-char-property (match-beginning 0) 'invisible)
19494 (throw 'exit t))))
19495 nil))))
19497 (defun org-metaup (&optional arg)
19498 "Move subtree up or move table row up.
19499 Calls `org-move-subtree-up' or `org-table-move-row' or
19500 `org-move-item-up', depending on context. See the individual commands
19501 for more information."
19502 (interactive "P")
19503 (cond
19504 ((run-hook-with-args-until-success 'org-metaup-hook))
19505 ((org-region-active-p)
19506 (let* ((a (min (region-beginning) (region-end)))
19507 (b (1- (max (region-beginning) (region-end))))
19508 (c (save-excursion (goto-char a)
19509 (move-beginning-of-line 0)))
19510 (d (save-excursion (goto-char a)
19511 (move-end-of-line 0) (point))))
19512 (transpose-regions a b c d)
19513 (goto-char c)))
19514 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19515 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19516 ((org-at-item-p) (call-interactively 'org-move-item-up))
19517 (t (org-drag-element-backward))))
19519 (defun org-metadown (&optional arg)
19520 "Move subtree down or move table row down.
19521 Calls `org-move-subtree-down' or `org-table-move-row' or
19522 `org-move-item-down', depending on context. See the individual
19523 commands for more information."
19524 (interactive "P")
19525 (cond
19526 ((run-hook-with-args-until-success 'org-metadown-hook))
19527 ((org-region-active-p)
19528 (let* ((a (min (region-beginning) (region-end)))
19529 (b (max (region-beginning) (region-end)))
19530 (c (save-excursion (goto-char b)
19531 (move-beginning-of-line 1)))
19532 (d (save-excursion (goto-char b)
19533 (move-end-of-line 1) (1+ (point)))))
19534 (transpose-regions a b c d)
19535 (goto-char d)))
19536 ((org-at-table-p) (call-interactively 'org-table-move-row))
19537 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19538 ((org-at-item-p) (call-interactively 'org-move-item-down))
19539 (t (org-drag-element-forward))))
19541 (defun org-shiftup (&optional arg)
19542 "Increase item in timestamp or increase priority of current headline.
19543 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19544 depending on context. See the individual commands for more information."
19545 (interactive "P")
19546 (cond
19547 ((run-hook-with-args-until-success 'org-shiftup-hook))
19548 ((and org-support-shift-select (org-region-active-p))
19549 (org-call-for-shift-select 'previous-line))
19550 ((org-at-timestamp-p t)
19551 (call-interactively (if org-edit-timestamp-down-means-later
19552 'org-timestamp-down 'org-timestamp-up)))
19553 ((and (not (eq org-support-shift-select 'always))
19554 org-enable-priority-commands
19555 (org-at-heading-p))
19556 (call-interactively 'org-priority-up))
19557 ((and (not org-support-shift-select) (org-at-item-p))
19558 (call-interactively 'org-previous-item))
19559 ((org-clocktable-try-shift 'up arg))
19560 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19561 (org-support-shift-select
19562 (org-call-for-shift-select 'previous-line))
19563 (t (org-shiftselect-error))))
19565 (defun org-shiftdown (&optional arg)
19566 "Decrease item in timestamp or decrease priority of current headline.
19567 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19568 depending on context. See the individual commands for more information."
19569 (interactive "P")
19570 (cond
19571 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19572 ((and org-support-shift-select (org-region-active-p))
19573 (org-call-for-shift-select 'next-line))
19574 ((org-at-timestamp-p t)
19575 (call-interactively (if org-edit-timestamp-down-means-later
19576 'org-timestamp-up 'org-timestamp-down)))
19577 ((and (not (eq org-support-shift-select 'always))
19578 org-enable-priority-commands
19579 (org-at-heading-p))
19580 (call-interactively 'org-priority-down))
19581 ((and (not org-support-shift-select) (org-at-item-p))
19582 (call-interactively 'org-next-item))
19583 ((org-clocktable-try-shift 'down arg))
19584 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19585 (org-support-shift-select
19586 (org-call-for-shift-select 'next-line))
19587 (t (org-shiftselect-error))))
19589 (defun org-shiftright (&optional arg)
19590 "Cycle the thing at point or in the current line, depending on context.
19591 Depending on context, this does one of the following:
19593 - switch a timestamp at point one day into the future
19594 - on a headline, switch to the next TODO keyword.
19595 - on an item, switch entire list to the next bullet type
19596 - on a property line, switch to the next allowed value
19597 - on a clocktable definition line, move time block into the future"
19598 (interactive "P")
19599 (cond
19600 ((run-hook-with-args-until-success 'org-shiftright-hook))
19601 ((and org-support-shift-select (org-region-active-p))
19602 (org-call-for-shift-select 'forward-char))
19603 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19604 ((and (not (eq org-support-shift-select 'always))
19605 (org-at-heading-p))
19606 (let ((org-inhibit-logging
19607 (not org-treat-S-cursor-todo-selection-as-state-change))
19608 (org-inhibit-blocking
19609 (not org-treat-S-cursor-todo-selection-as-state-change)))
19610 (org-call-with-arg 'org-todo 'right)))
19611 ((or (and org-support-shift-select
19612 (not (eq org-support-shift-select 'always))
19613 (org-at-item-bullet-p))
19614 (and (not org-support-shift-select) (org-at-item-p)))
19615 (org-call-with-arg 'org-cycle-list-bullet nil))
19616 ((and (not (eq org-support-shift-select 'always))
19617 (org-at-property-p))
19618 (call-interactively 'org-property-next-allowed-value))
19619 ((org-clocktable-try-shift 'right arg))
19620 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19621 (org-support-shift-select
19622 (org-call-for-shift-select 'forward-char))
19623 (t (org-shiftselect-error))))
19625 (defun org-shiftleft (&optional arg)
19626 "Cycle the thing at point or in the current line, depending on context.
19627 Depending on context, this does one of the following:
19629 - switch a timestamp at point one day into the past
19630 - on a headline, switch to the previous TODO keyword.
19631 - on an item, switch entire list to the previous bullet type
19632 - on a property line, switch to the previous allowed value
19633 - on a clocktable definition line, move time block into the past"
19634 (interactive "P")
19635 (cond
19636 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19637 ((and org-support-shift-select (org-region-active-p))
19638 (org-call-for-shift-select 'backward-char))
19639 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19640 ((and (not (eq org-support-shift-select 'always))
19641 (org-at-heading-p))
19642 (let ((org-inhibit-logging
19643 (not org-treat-S-cursor-todo-selection-as-state-change))
19644 (org-inhibit-blocking
19645 (not org-treat-S-cursor-todo-selection-as-state-change)))
19646 (org-call-with-arg 'org-todo 'left)))
19647 ((or (and org-support-shift-select
19648 (not (eq org-support-shift-select 'always))
19649 (org-at-item-bullet-p))
19650 (and (not org-support-shift-select) (org-at-item-p)))
19651 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19652 ((and (not (eq org-support-shift-select 'always))
19653 (org-at-property-p))
19654 (call-interactively 'org-property-previous-allowed-value))
19655 ((org-clocktable-try-shift 'left arg))
19656 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19657 (org-support-shift-select
19658 (org-call-for-shift-select 'backward-char))
19659 (t (org-shiftselect-error))))
19661 (defun org-shiftcontrolright ()
19662 "Switch to next TODO set."
19663 (interactive)
19664 (cond
19665 ((and org-support-shift-select (org-region-active-p))
19666 (org-call-for-shift-select 'forward-word))
19667 ((and (not (eq org-support-shift-select 'always))
19668 (org-at-heading-p))
19669 (org-call-with-arg 'org-todo 'nextset))
19670 (org-support-shift-select
19671 (org-call-for-shift-select 'forward-word))
19672 (t (org-shiftselect-error))))
19674 (defun org-shiftcontrolleft ()
19675 "Switch to previous TODO set."
19676 (interactive)
19677 (cond
19678 ((and org-support-shift-select (org-region-active-p))
19679 (org-call-for-shift-select 'backward-word))
19680 ((and (not (eq org-support-shift-select 'always))
19681 (org-at-heading-p))
19682 (org-call-with-arg 'org-todo 'previousset))
19683 (org-support-shift-select
19684 (org-call-for-shift-select 'backward-word))
19685 (t (org-shiftselect-error))))
19687 (defun org-shiftcontrolup (&optional n)
19688 "Change timestamps synchronously up in CLOCK log lines.
19689 Optional argument N tells to change by that many units."
19690 (interactive "P")
19691 (cond ((and (not org-support-shift-select)
19692 (org-at-clock-log-p)
19693 (org-at-timestamp-p t))
19694 (org-clock-timestamps-up n))
19695 (t (org-shiftselect-error))))
19697 (defun org-shiftcontroldown (&optional n)
19698 "Change timestamps synchronously down in CLOCK log lines.
19699 Optional argument N tells to change by that many units."
19700 (interactive "P")
19701 (cond ((and (not org-support-shift-select)
19702 (org-at-clock-log-p)
19703 (org-at-timestamp-p t))
19704 (org-clock-timestamps-down n))
19705 (t (org-shiftselect-error))))
19707 (defun org-ctrl-c-ret ()
19708 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19709 (interactive)
19710 (cond
19711 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19712 (t (call-interactively 'org-insert-heading))))
19714 (defun org-find-visible ()
19715 (let ((s (point)))
19716 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19717 (get-char-property s 'invisible)))
19719 (defun org-find-invisible ()
19720 (let ((s (point)))
19721 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19722 (not (get-char-property s 'invisible))))
19725 (defun org-copy-visible (beg end)
19726 "Copy the visible parts of the region."
19727 (interactive "r")
19728 (let (snippets s)
19729 (save-excursion
19730 (save-restriction
19731 (narrow-to-region beg end)
19732 (setq s (goto-char (point-min)))
19733 (while (not (= (point) (point-max)))
19734 (goto-char (org-find-invisible))
19735 (push (buffer-substring s (point)) snippets)
19736 (setq s (goto-char (org-find-visible))))))
19737 (kill-new (apply 'concat (nreverse snippets)))))
19739 (defun org-copy-special ()
19740 "Copy region in table or copy current subtree.
19741 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19742 See the individual commands for more information."
19743 (interactive)
19744 (call-interactively
19745 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19747 (defun org-cut-special ()
19748 "Cut region in table or cut current subtree.
19749 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19750 See the individual commands for more information."
19751 (interactive)
19752 (call-interactively
19753 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19755 (defun org-paste-special (arg)
19756 "Paste rectangular region into table, or past subtree relative to level.
19757 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19758 See the individual commands for more information."
19759 (interactive "P")
19760 (if (org-at-table-p)
19761 (org-table-paste-rectangle)
19762 (org-paste-subtree arg)))
19764 (defsubst org-in-fixed-width-region-p ()
19765 "Is point in a fixed-width region?"
19766 (save-match-data
19767 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19769 (defun org-edit-special (&optional arg)
19770 "Call a special editor for the element at point.
19771 When at a table, call the formula editor with `org-table-edit-formulas'.
19772 When in a source code block, call `org-edit-src-code'.
19773 When in a fixed-width region, call `org-edit-fixed-width-region'.
19774 When at an #+INCLUDE keyword, visit the included file.
19775 On a link, call `ffap' to visit the link at point.
19776 Otherwise, return a user error."
19777 (interactive)
19778 (let ((element (org-element-at-point)))
19779 (assert (not buffer-read-only) nil
19780 "Buffer is read-only: %s" (buffer-name))
19781 (case (org-element-type element)
19782 (src-block
19783 (if (not arg) (org-edit-src-code)
19784 (let* ((info (org-babel-get-src-block-info))
19785 (lang (nth 0 info))
19786 (params (nth 2 info))
19787 (session (cdr (assq :session params))))
19788 (if (not session) (org-edit-src-code)
19789 ;; At a src-block with a session and function called with
19790 ;; an ARG: switch to the buffer related to the inferior
19791 ;; process.
19792 (funcall (intern (concat "org-babel-prep-session:" lang))
19793 session params)))))
19794 (keyword
19795 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
19796 (find-file
19797 (org-remove-double-quotes
19798 (car (org-split-string (org-element-property :value element)))))
19799 (user-error "No special environment to edit here")))
19800 (table
19801 (if (eq (org-element-property :type element) 'table.el)
19802 (org-edit-src-code)
19803 (call-interactively 'org-table-edit-formulas)))
19804 ;; Only Org tables contain `table-row' type elements.
19805 (table-row (call-interactively 'org-table-edit-formulas))
19806 ((example-block export-block) (org-edit-src-code))
19807 (fixed-width (org-edit-fixed-width-region))
19808 (otherwise
19809 ;; No notable element at point. Though, we may be at a link,
19810 ;; which is an object. Thus, scan deeper.
19811 (if (eq (org-element-type (org-element-context element)) 'link)
19812 (call-interactively 'ffap)
19813 (user-error "No special environment to edit here"))))))
19815 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19816 (defun org-ctrl-c-ctrl-c (&optional arg)
19817 "Set tags in headline, or update according to changed information at point.
19819 This command does many different things, depending on context:
19821 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19822 this is what we do.
19824 - If the cursor is on a statistics cookie, update it.
19826 - If the cursor is in a headline, prompt for tags and insert them
19827 into the current line, aligned to `org-tags-column'. When called
19828 with prefix arg, realign all tags in the current buffer.
19830 - If the cursor is in one of the special #+KEYWORD lines, this
19831 triggers scanning the buffer for these lines and updating the
19832 information.
19834 - If the cursor is inside a table, realign the table. This command
19835 works even if the automatic table editor has been turned off.
19837 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19838 the entire table.
19840 - If the cursor is at a footnote reference or definition, jump to
19841 the corresponding definition or references, respectively.
19843 - If the cursor is a the beginning of a dynamic block, update it.
19845 - If the current buffer is a capture buffer, close note and file it.
19847 - If the cursor is on a <<<target>>>, update radio targets and
19848 corresponding links in this buffer.
19850 - If the cursor is on a numbered item in a plain list, renumber the
19851 ordered list.
19853 - If the cursor is on a checkbox, toggle it.
19855 - If the cursor is on a code block, evaluate it. The variable
19856 `org-confirm-babel-evaluate' can be used to control prompting
19857 before code block evaluation, by default every code block
19858 evaluation requires confirmation. Code block evaluation can be
19859 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19860 (interactive "P")
19861 (cond
19862 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19863 org-occur-highlights
19864 org-latex-fragment-image-overlays)
19865 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19866 (org-remove-occur-highlights)
19867 (org-remove-latex-fragment-image-overlays)
19868 (message "Temporary highlights/overlays removed from current buffer"))
19869 ((and (local-variable-p 'org-finish-function (current-buffer))
19870 (fboundp org-finish-function))
19871 (funcall org-finish-function))
19872 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19874 (let* ((context (org-element-context)) (type (org-element-type context)))
19875 ;; Test if point is within a blank line.
19876 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
19877 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19878 (user-error "C-c C-c can do nothing useful at this location"))
19879 ;; For convenience: at the first line of a paragraph on the
19880 ;; same line as an item, apply function on that item instead.
19881 (when (eq type 'paragraph)
19882 (let ((parent (org-element-property :parent context)))
19883 (when (and (eq (org-element-type parent) 'item)
19884 (= (point-at-bol) (org-element-property :begin parent)))
19885 (setq context parent type 'item))))
19886 ;; Act according to type of element or object at point.
19887 (case type
19888 (clock (org-clock-update-time-maybe))
19889 (dynamic-block
19890 (save-excursion
19891 (goto-char (org-element-property :post-affiliated context))
19892 (org-update-dblock)))
19893 (footnote-definition
19894 (goto-char (org-element-property :post-affiliated context))
19895 (call-interactively 'org-footnote-action))
19896 (footnote-reference (call-interactively 'org-footnote-action))
19897 ((headline inlinetask)
19898 (save-excursion (goto-char (org-element-property :begin context))
19899 (call-interactively 'org-set-tags)))
19900 (item
19901 ;; At an item: a double C-u set checkbox to "[-]"
19902 ;; unconditionally, whereas a single one will toggle its
19903 ;; presence. Without an universal argument, if the item
19904 ;; has a checkbox, toggle it. Otherwise repair the list.
19905 (let* ((box (org-element-property :checkbox context))
19906 (struct (org-element-property :structure context))
19907 (old-struct (copy-tree struct))
19908 (parents (org-list-parents-alist struct))
19909 (prevs (org-list-prevs-alist struct))
19910 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
19911 (org-list-set-checkbox
19912 (org-element-property :begin context) struct
19913 (cond ((equal arg '(16)) "[-]")
19914 ((and (not box) (equal arg '(4))) "[ ]")
19915 ((or (not box) (equal arg '(4))) nil)
19916 ((eq box 'on) "[ ]")
19917 (t "[X]")))
19918 ;; Mimic `org-list-write-struct' but with grabbing
19919 ;; a return value from `org-list-struct-fix-box'.
19920 (org-list-struct-fix-ind struct parents 2)
19921 (org-list-struct-fix-item-end struct)
19922 (org-list-struct-fix-bul struct prevs)
19923 (org-list-struct-fix-ind struct parents)
19924 (let ((block-item
19925 (org-list-struct-fix-box struct parents prevs orderedp)))
19926 (if (and box (equal struct old-struct))
19927 (if (equal arg '(16))
19928 (message "Checkboxes already reset")
19929 (user-error "Cannot toggle this checkbox: %s"
19930 (if (eq box 'on)
19931 "all subitems checked"
19932 "unchecked subitems")))
19933 (org-list-struct-apply-struct struct old-struct)
19934 (org-update-checkbox-count-maybe))
19935 (when block-item
19936 (message "Checkboxes were removed due to empty box at line %d"
19937 (org-current-line block-item))))))
19938 (keyword
19939 (let ((org-inhibit-startup-visibility-stuff t)
19940 (org-startup-align-all-tables nil))
19941 (when (boundp 'org-table-coordinate-overlays)
19942 (mapc 'delete-overlay org-table-coordinate-overlays)
19943 (setq org-table-coordinate-overlays nil))
19944 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19945 (message "Local setup has been refreshed"))
19946 (plain-list
19947 ;; At a plain list, with a double C-u argument, set
19948 ;; checkboxes of each item to "[-]", whereas a single one
19949 ;; will toggle their presence according to the state of the
19950 ;; first item in the list. Without an argument, repair the
19951 ;; list.
19952 (let* ((begin (org-element-property :contents-begin context))
19953 (struct (org-element-property :structure context))
19954 (old-struct (copy-tree struct))
19955 (first-box (save-excursion
19956 (goto-char begin)
19957 (looking-at org-list-full-item-re)
19958 (match-string-no-properties 3)))
19959 (new-box (cond ((equal arg '(16)) "[-]")
19960 ((equal arg '(4)) (unless first-box "[ ]"))
19961 ((equal first-box "[X]") "[ ]")
19962 (t "[X]"))))
19963 (cond
19964 (arg
19965 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
19966 (org-list-get-all-items
19967 begin struct (org-list-prevs-alist struct))))
19968 ((and first-box (eq (point) begin))
19969 ;; For convenience, when point is at bol on the first
19970 ;; item of the list and no argument is provided, simply
19971 ;; toggle checkbox of that item, if any.
19972 (org-list-set-checkbox begin struct new-box)))
19973 (org-list-write-struct
19974 struct (org-list-parents-alist struct) old-struct)
19975 (org-update-checkbox-count-maybe)
19976 (save-excursion (goto-char begin) (org-list-send-list 'maybe))))
19977 ((property-drawer node-property)
19978 (call-interactively 'org-property-action))
19979 ((radio-target target)
19980 (call-interactively 'org-update-radio-target-regexp))
19981 (statistics-cookie
19982 (call-interactively 'org-update-statistics-cookies))
19983 ((table table-cell table-row)
19984 ;; At a table, recalculate every field and align it. Also
19985 ;; send the table if necessary. If the table has
19986 ;; a `table.el' type, just give up. At a table row or
19987 ;; cell, maybe recalculate line but always align table.
19988 (if (eq (org-element-property :type context) 'table.el)
19989 (message "Use C-c ' to edit table.el tables")
19990 (let ((org-enable-table-editor t))
19991 (if (or (eq type 'table)
19992 ;; Check if point is at a TBLFM line.
19993 (and (eq type 'table-row)
19994 (= (point) (org-element-property :end context))))
19995 (save-excursion
19996 (goto-char (org-element-property :contents-begin context))
19997 (org-call-with-arg 'org-table-recalculate (or arg t))
19998 (orgtbl-send-table 'maybe))
19999 (org-table-maybe-eval-formula)
20000 (cond (arg (call-interactively 'org-table-recalculate))
20001 ((org-table-maybe-recalculate-line))
20002 (t (org-table-align)))))))
20003 (timestamp (org-timestamp-change 0 'day))
20004 (otherwise
20005 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20006 (user-error
20007 "C-c C-c can do nothing useful at this location")))))))))
20009 (defun org-mode-restart ()
20010 "Restart Org-mode, to scan again for special lines.
20011 Also updates the keyword regular expressions."
20012 (interactive)
20013 (org-mode)
20014 (message "Org-mode restarted"))
20016 (defun org-kill-note-or-show-branches ()
20017 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20018 (interactive)
20019 (if (not org-finish-function)
20020 (progn
20021 (hide-subtree)
20022 (call-interactively 'show-branches))
20023 (let ((org-note-abort t))
20024 (funcall org-finish-function))))
20026 (defun org-return (&optional indent)
20027 "Goto next table row or insert a newline.
20028 Calls `org-table-next-row' or `newline', depending on context.
20029 See the individual commands for more information."
20030 (interactive)
20031 (let (org-ts-what)
20032 (cond
20033 ((or (bobp) (org-in-src-block-p))
20034 (if indent (newline-and-indent) (newline)))
20035 ((org-at-table-p)
20036 (org-table-justify-field-maybe)
20037 (call-interactively 'org-table-next-row))
20038 ;; when `newline-and-indent' is called within a list, make sure
20039 ;; text moved stays inside the item.
20040 ((and (org-in-item-p) indent)
20041 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20042 (progn
20043 (save-match-data (newline))
20044 (org-indent-line-to (length (match-string 0))))
20045 (let ((ind (org-get-indentation)))
20046 (newline)
20047 (if (org-looking-back org-list-end-re)
20048 (org-indent-line)
20049 (org-indent-line-to ind)))))
20050 ((and org-return-follows-link
20051 (org-at-timestamp-p t)
20052 (not (eq org-ts-what 'after)))
20053 (org-follow-timestamp-link))
20054 ((and org-return-follows-link
20055 (let ((tprop (get-text-property (point) 'face)))
20056 (or (eq tprop 'org-link)
20057 (and (listp tprop) (memq 'org-link tprop)))))
20058 (call-interactively 'org-open-at-point))
20059 ((and (org-at-heading-p)
20060 (looking-at
20061 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20062 (org-show-entry)
20063 (end-of-line 1)
20064 (newline))
20065 (t (if indent (newline-and-indent) (newline))))))
20067 (defun org-return-indent ()
20068 "Goto next table row or insert a newline and indent.
20069 Calls `org-table-next-row' or `newline-and-indent', depending on
20070 context. See the individual commands for more information."
20071 (interactive)
20072 (org-return t))
20074 (defun org-ctrl-c-star ()
20075 "Compute table, or change heading status of lines.
20076 Calls `org-table-recalculate' or `org-toggle-heading',
20077 depending on context."
20078 (interactive)
20079 (cond
20080 ((org-at-table-p)
20081 (call-interactively 'org-table-recalculate))
20083 ;; Convert all lines in region to list items
20084 (call-interactively 'org-toggle-heading))))
20086 (defun org-ctrl-c-minus ()
20087 "Insert separator line in table or modify bullet status of line.
20088 Also turns a plain line or a region of lines into list items.
20089 Calls `org-table-insert-hline', `org-toggle-item', or
20090 `org-cycle-list-bullet', depending on context."
20091 (interactive)
20092 (cond
20093 ((org-at-table-p)
20094 (call-interactively 'org-table-insert-hline))
20095 ((org-region-active-p)
20096 (call-interactively 'org-toggle-item))
20097 ((org-in-item-p)
20098 (call-interactively 'org-cycle-list-bullet))
20100 (call-interactively 'org-toggle-item))))
20102 (defun org-toggle-item (arg)
20103 "Convert headings or normal lines to items, items to normal lines.
20104 If there is no active region, only the current line is considered.
20106 If the first non blank line in the region is a headline, convert
20107 all headlines to items, shifting text accordingly.
20109 If it is an item, convert all items to normal lines.
20111 If it is normal text, change region into a list of items.
20112 With a prefix argument ARG, change the region in a single item."
20113 (interactive "P")
20114 (let ((shift-text
20115 (function
20116 ;; Shift text in current section to IND, from point to END.
20117 ;; The function leaves point to END line.
20118 (lambda (ind end)
20119 (let ((min-i 1000) (end (copy-marker end)))
20120 ;; First determine the minimum indentation (MIN-I) of
20121 ;; the text.
20122 (save-excursion
20123 (catch 'exit
20124 (while (< (point) end)
20125 (let ((i (org-get-indentation)))
20126 (cond
20127 ;; Skip blank lines and inline tasks.
20128 ((looking-at "^[ \t]*$"))
20129 ((looking-at org-outline-regexp-bol))
20130 ;; We can't find less than 0 indentation.
20131 ((zerop i) (throw 'exit (setq min-i 0)))
20132 ((< i min-i) (setq min-i i))))
20133 (forward-line))))
20134 ;; Then indent each line so that a line indented to
20135 ;; MIN-I becomes indented to IND. Ignore blank lines
20136 ;; and inline tasks in the process.
20137 (let ((delta (- ind min-i)))
20138 (while (< (point) end)
20139 (unless (or (looking-at "^[ \t]*$")
20140 (looking-at org-outline-regexp-bol))
20141 (org-indent-line-to (+ (org-get-indentation) delta)))
20142 (forward-line)))))))
20143 (skip-blanks
20144 (function
20145 ;; Return beginning of first non-blank line, starting from
20146 ;; line at POS.
20147 (lambda (pos)
20148 (save-excursion
20149 (goto-char pos)
20150 (skip-chars-forward " \r\t\n")
20151 (point-at-bol)))))
20152 beg end)
20153 ;; Determine boundaries of changes.
20154 (if (org-region-active-p)
20155 (setq beg (funcall skip-blanks (region-beginning))
20156 end (copy-marker (region-end)))
20157 (setq beg (funcall skip-blanks (point-at-bol))
20158 end (copy-marker (point-at-eol))))
20159 ;; Depending on the starting line, choose an action on the text
20160 ;; between BEG and END.
20161 (org-with-limited-levels
20162 (save-excursion
20163 (goto-char beg)
20164 (cond
20165 ;; Case 1. Start at an item: de-itemize. Note that it only
20166 ;; happens when a region is active: `org-ctrl-c-minus'
20167 ;; would call `org-cycle-list-bullet' otherwise.
20168 ((org-at-item-p)
20169 (while (< (point) end)
20170 (when (org-at-item-p)
20171 (skip-chars-forward " \t")
20172 (delete-region (point) (match-end 0)))
20173 (forward-line)))
20174 ;; Case 2. Start at an heading: convert to items.
20175 ((org-at-heading-p)
20176 (let* ((bul (org-list-bullet-string "-"))
20177 (bul-len (length bul))
20178 ;; Indentation of the first heading. It should be
20179 ;; relative to the indentation of its parent, if any.
20180 (start-ind (save-excursion
20181 (cond
20182 ((not org-adapt-indentation) 0)
20183 ((not (outline-previous-heading)) 0)
20184 (t (length (match-string 0))))))
20185 ;; Level of first heading. Further headings will be
20186 ;; compared to it to determine hierarchy in the list.
20187 (ref-level (org-reduced-level (org-outline-level))))
20188 (while (< (point) end)
20189 (let* ((level (org-reduced-level (org-outline-level)))
20190 (delta (max 0 (- level ref-level))))
20191 ;; If current headline is less indented than the first
20192 ;; one, set it as reference, in order to preserve
20193 ;; subtrees.
20194 (when (< level ref-level) (setq ref-level level))
20195 (replace-match bul t t)
20196 (org-indent-line-to (+ start-ind (* delta bul-len)))
20197 ;; Ensure all text down to END (or SECTION-END) belongs
20198 ;; to the newly created item.
20199 (let ((section-end (save-excursion
20200 (or (outline-next-heading) (point)))))
20201 (forward-line)
20202 (funcall shift-text
20203 (+ start-ind (* (1+ delta) bul-len))
20204 (min end section-end)))))))
20205 ;; Case 3. Normal line with ARG: make the first line of region
20206 ;; an item, and shift indentation of others lines to
20207 ;; set them as item's body.
20208 (arg (let* ((bul (org-list-bullet-string "-"))
20209 (bul-len (length bul))
20210 (ref-ind (org-get-indentation)))
20211 (skip-chars-forward " \t")
20212 (insert bul)
20213 (forward-line)
20214 (while (< (point) end)
20215 ;; Ensure that lines less indented than first one
20216 ;; still get included in item body.
20217 (funcall shift-text
20218 (+ ref-ind bul-len)
20219 (min end (save-excursion (or (outline-next-heading)
20220 (point)))))
20221 (forward-line))))
20222 ;; Case 4. Normal line without ARG: turn each non-item line
20223 ;; into an item.
20225 (while (< (point) end)
20226 (unless (or (org-at-heading-p) (org-at-item-p))
20227 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20228 (replace-match
20229 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20230 (forward-line))))))))
20232 (defun org-toggle-heading (&optional nstars)
20233 "Convert headings to normal text, or items or text to headings.
20234 If there is no active region, only convert the current line.
20236 With a \\[universal-argument] prefix, convert the whole list at
20237 point into heading.
20239 In a region:
20241 - If the first non blank line is a headline, remove the stars
20242 from all headlines in the region.
20244 - If it is a normal line, turn each and every normal line (i.e.,
20245 not an heading or an item) in the region into headings. If you
20246 want to convert only the first line of this region, use one
20247 universal prefix argument.
20249 - If it is a plain list item, turn all plain list items into headings.
20251 When converting a line into a heading, the number of stars is chosen
20252 such that the lines become children of the current entry. However,
20253 when a numeric prefix argument is given, its value determines the
20254 number of stars to add."
20255 (interactive "P")
20256 (let ((skip-blanks
20257 (function
20258 ;; Return beginning of first non-blank line, starting from
20259 ;; line at POS.
20260 (lambda (pos)
20261 (save-excursion
20262 (goto-char pos)
20263 (while (org-at-comment-p) (forward-line))
20264 (skip-chars-forward " \r\t\n")
20265 (point-at-bol)))))
20266 beg end toggled)
20267 ;; Determine boundaries of changes. If a universal prefix has
20268 ;; been given, put the list in a region. If region ends at a bol,
20269 ;; do not consider the last line to be in the region.
20271 (when (and current-prefix-arg (org-at-item-p))
20272 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20273 (org-mark-element))
20275 (if (org-region-active-p)
20276 (setq beg (funcall skip-blanks (region-beginning))
20277 end (copy-marker (save-excursion
20278 (goto-char (region-end))
20279 (if (bolp) (point) (point-at-eol)))))
20280 (setq beg (funcall skip-blanks (point-at-bol))
20281 end (copy-marker (point-at-eol))))
20282 ;; Ensure inline tasks don't count as headings.
20283 (org-with-limited-levels
20284 (save-excursion
20285 (goto-char beg)
20286 (cond
20287 ;; Case 1. Started at an heading: de-star headings.
20288 ((org-at-heading-p)
20289 (while (< (point) end)
20290 (when (org-at-heading-p t)
20291 (looking-at org-outline-regexp) (replace-match "")
20292 (setq toggled t))
20293 (forward-line)))
20294 ;; Case 2. Started at an item: change items into headlines.
20295 ;; One star will be added by `org-list-to-subtree'.
20296 ((org-at-item-p)
20297 (let* ((stars (make-string
20298 ;; subtract the star that will be added again by
20299 ;; `org-list-to-subtree'
20300 (if (numberp nstars) (1- nstars)
20301 (or (org-current-level) 0))
20302 ?*))
20303 (add-stars
20304 (cond (nstars "") ; stars from prefix only
20305 ((equal stars "") "") ; before first heading
20306 (org-odd-levels-only "*") ; inside heading, odd
20307 (t "")))) ; inside heading, oddeven
20308 (while (< (point) end)
20309 (when (org-at-item-p)
20310 ;; Pay attention to cases when region ends before list.
20311 (let* ((struct (org-list-struct))
20312 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20313 (save-restriction
20314 (narrow-to-region (point) list-end)
20315 (insert
20316 (org-list-to-subtree
20317 (org-list-parse-list t)
20318 '(:istart (concat stars add-stars (funcall get-stars depth))
20319 :icount (concat stars add-stars (funcall get-stars depth)))))))
20320 (setq toggled t))
20321 (forward-line))))
20322 ;; Case 3. Started at normal text: make every line an heading,
20323 ;; skipping headlines and items.
20324 (t (let* ((stars
20325 (make-string
20326 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20327 (add-stars
20328 (cond (nstars "") ; stars from prefix only
20329 ((equal stars "") "*") ; before first heading
20330 (org-odd-levels-only "**") ; inside heading, odd
20331 (t "*"))) ; inside heading, oddeven
20332 (rpl (concat stars add-stars " "))
20333 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20334 (while (< (point) (if (equal nstars '(4)) lend end))
20335 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20336 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20337 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20338 (forward-line)))))))
20339 (unless toggled (message "Cannot toggle heading from here"))))
20341 (defun org-meta-return (&optional arg)
20342 "Insert a new heading or wrap a region in a table.
20343 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20344 See the individual commands for more information."
20345 (interactive "P")
20346 (cond
20347 ((run-hook-with-args-until-success 'org-metareturn-hook))
20348 ((or (org-at-drawer-p) (org-at-property-p))
20349 (newline-and-indent))
20350 ((org-at-table-p)
20351 (call-interactively 'org-table-wrap-region))
20352 (t (call-interactively 'org-insert-heading))))
20354 ;;; Menu entries
20356 (defsubst org-in-subtree-not-table-p ()
20357 "Are we in a subtree and not in a table?"
20358 (and (not (org-before-first-heading-p))
20359 (not (org-at-table-p))))
20361 ;; Define the Org-mode menus
20362 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20363 '("Tbl"
20364 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20365 ["Next Field" org-cycle (org-at-table-p)]
20366 ["Previous Field" org-shifttab (org-at-table-p)]
20367 ["Next Row" org-return (org-at-table-p)]
20368 "--"
20369 ["Blank Field" org-table-blank-field (org-at-table-p)]
20370 ["Edit Field" org-table-edit-field (org-at-table-p)]
20371 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20372 "--"
20373 ("Column"
20374 ["Move Column Left" org-metaleft (org-at-table-p)]
20375 ["Move Column Right" org-metaright (org-at-table-p)]
20376 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20377 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20378 ("Row"
20379 ["Move Row Up" org-metaup (org-at-table-p)]
20380 ["Move Row Down" org-metadown (org-at-table-p)]
20381 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20382 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20383 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20384 "--"
20385 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20386 ("Rectangle"
20387 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20388 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20389 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20390 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20391 "--"
20392 ("Calculate"
20393 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20394 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20395 ["Edit Formulas" org-edit-special (org-at-table-p)]
20396 "--"
20397 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20398 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20399 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20400 "--"
20401 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20402 "--"
20403 ["Sum Column/Rectangle" org-table-sum
20404 (or (org-at-table-p) (org-region-active-p))]
20405 ["Which Column?" org-table-current-column (org-at-table-p)])
20406 ["Debug Formulas"
20407 org-table-toggle-formula-debugger
20408 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20409 ["Show Col/Row Numbers"
20410 org-table-toggle-coordinate-overlays
20411 :style toggle
20412 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20413 "--"
20414 ["Create" org-table-create (and (not (org-at-table-p))
20415 org-enable-table-editor)]
20416 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20417 ["Import from File" org-table-import (not (org-at-table-p))]
20418 ["Export to File" org-table-export (org-at-table-p)]
20419 "--"
20420 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20422 (easy-menu-define org-org-menu org-mode-map "Org menu"
20423 '("Org"
20424 ("Show/Hide"
20425 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20426 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20427 ["Sparse Tree..." org-sparse-tree t]
20428 ["Reveal Context" org-reveal t]
20429 ["Show All" show-all t]
20430 "--"
20431 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20432 "--"
20433 ["New Heading" org-insert-heading t]
20434 ("Navigate Headings"
20435 ["Up" outline-up-heading t]
20436 ["Next" outline-next-visible-heading t]
20437 ["Previous" outline-previous-visible-heading t]
20438 ["Next Same Level" outline-forward-same-level t]
20439 ["Previous Same Level" outline-backward-same-level t]
20440 "--"
20441 ["Jump" org-goto t])
20442 ("Edit Structure"
20443 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20444 "--"
20445 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20446 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20447 "--"
20448 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20449 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20450 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20451 "--"
20452 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20453 "--"
20454 ["Copy visible text" org-copy-visible t]
20455 "--"
20456 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20457 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20458 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20459 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20460 "--"
20461 ["Sort Region/Children" org-sort t]
20462 "--"
20463 ["Convert to odd levels" org-convert-to-odd-levels t]
20464 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20465 ("Editing"
20466 ["Emphasis..." org-emphasize t]
20467 ["Edit Source Example" org-edit-special t]
20468 "--"
20469 ["Footnote new/jump" org-footnote-action t]
20470 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20471 ("Archive"
20472 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20473 "--"
20474 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20475 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20476 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20478 "--"
20479 ("Hyperlinks"
20480 ["Store Link (Global)" org-store-link t]
20481 ["Find existing link to here" org-occur-link-in-agenda-files t]
20482 ["Insert Link" org-insert-link t]
20483 ["Follow Link" org-open-at-point t]
20484 "--"
20485 ["Next link" org-next-link t]
20486 ["Previous link" org-previous-link t]
20487 "--"
20488 ["Descriptive Links"
20489 org-toggle-link-display
20490 :style radio
20491 :selected org-descriptive-links
20493 ["Literal Links"
20494 org-toggle-link-display
20495 :style radio
20496 :selected (not org-descriptive-links)])
20497 "--"
20498 ("TODO Lists"
20499 ["TODO/DONE/-" org-todo t]
20500 ("Select keyword"
20501 ["Next keyword" org-shiftright (org-at-heading-p)]
20502 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20503 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20504 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20505 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20506 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20507 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20508 "--"
20509 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20510 :selected org-enforce-todo-dependencies :style toggle :active t]
20511 "Settings for tree at point"
20512 ["Do Children sequentially" org-toggle-ordered-property :style radio
20513 :selected (org-entry-get nil "ORDERED")
20514 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20515 ["Do Children parallel" org-toggle-ordered-property :style radio
20516 :selected (not (org-entry-get nil "ORDERED"))
20517 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20518 "--"
20519 ["Set Priority" org-priority t]
20520 ["Priority Up" org-shiftup t]
20521 ["Priority Down" org-shiftdown t]
20522 "--"
20523 ["Get news from all feeds" org-feed-update-all t]
20524 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20525 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20526 ("TAGS and Properties"
20527 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20528 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20529 "--"
20530 ["Set property" org-set-property (not (org-before-first-heading-p))]
20531 ["Column view of properties" org-columns t]
20532 ["Insert Column View DBlock" org-insert-columns-dblock t])
20533 ("Dates and Scheduling"
20534 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20535 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20536 ("Change Date"
20537 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20538 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20539 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20540 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20541 ["Compute Time Range" org-evaluate-time-range t]
20542 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20543 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20544 "--"
20545 ["Custom time format" org-toggle-time-stamp-overlays
20546 :style radio :selected org-display-custom-times]
20547 "--"
20548 ["Goto Calendar" org-goto-calendar t]
20549 ["Date from Calendar" org-date-from-calendar t]
20550 "--"
20551 ["Start/Restart Timer" org-timer-start t]
20552 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20553 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20554 ["Insert Timer String" org-timer t]
20555 ["Insert Timer Item" org-timer-item t])
20556 ("Logging work"
20557 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20558 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20559 ["Clock out" org-clock-out t]
20560 ["Clock cancel" org-clock-cancel t]
20561 "--"
20562 ["Mark as default task" org-clock-mark-default-task t]
20563 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20564 ["Goto running clock" org-clock-goto t]
20565 "--"
20566 ["Display times" org-clock-display t]
20567 ["Create clock table" org-clock-report t]
20568 "--"
20569 ["Record DONE time"
20570 (progn (setq org-log-done (not org-log-done))
20571 (message "Switching to %s will %s record a timestamp"
20572 (car org-done-keywords)
20573 (if org-log-done "automatically" "not")))
20574 :style toggle :selected org-log-done])
20575 "--"
20576 ["Agenda Command..." org-agenda t]
20577 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20578 ("File List for Agenda")
20579 ("Special views current file"
20580 ["TODO Tree" org-show-todo-tree t]
20581 ["Check Deadlines" org-check-deadlines t]
20582 ["Timeline" org-timeline t]
20583 ["Tags/Property tree" org-match-sparse-tree t])
20584 "--"
20585 ["Export/Publish..." org-export-dispatch t]
20586 ("LaTeX"
20587 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20588 :selected org-cdlatex-mode]
20589 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20590 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20591 ["Modify math symbol" org-cdlatex-math-modify
20592 (org-inside-LaTeX-fragment-p)]
20593 ["Insert citation" org-reftex-citation t]
20594 "--"
20595 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20596 "--"
20597 ("MobileOrg"
20598 ["Push Files and Views" org-mobile-push t]
20599 ["Get Captured and Flagged" org-mobile-pull t]
20600 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20601 "--"
20602 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20603 "--"
20604 ("Documentation"
20605 ["Show Version" org-version t]
20606 ["Info Documentation" org-info t])
20607 ("Customize"
20608 ["Browse Org Group" org-customize t]
20609 "--"
20610 ["Expand This Menu" org-create-customize-menu
20611 (fboundp 'customize-menu-create)])
20612 ["Send bug report" org-submit-bug-report t]
20613 "--"
20614 ("Refresh/Reload"
20615 ["Refresh setup current buffer" org-mode-restart t]
20616 ["Reload Org (after update)" org-reload t]
20617 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20620 (defun org-info (&optional node)
20621 "Read documentation for Org-mode in the info system.
20622 With optional NODE, go directly to that node."
20623 (interactive)
20624 (info (format "(org)%s" (or node ""))))
20626 ;;;###autoload
20627 (defun org-submit-bug-report ()
20628 "Submit a bug report on Org-mode via mail.
20630 Don't hesitate to report any problems or inaccurate documentation.
20632 If you don't have setup sending mail from (X)Emacs, please copy the
20633 output buffer into your mail program, as it gives us important
20634 information about your Org-mode version and configuration."
20635 (interactive)
20636 (require 'reporter)
20637 (org-load-modules-maybe)
20638 (org-require-autoloaded-modules)
20639 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20640 (reporter-submit-bug-report
20641 "emacs-orgmode@gnu.org"
20642 (org-version nil 'full)
20643 (let (list)
20644 (save-window-excursion
20645 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20646 (delete-other-windows)
20647 (erase-buffer)
20648 (insert "You are about to submit a bug report to the Org-mode mailing list.
20650 We would like to add your full Org-mode and Outline configuration to the
20651 bug report. This greatly simplifies the work of the maintainer and
20652 other experts on the mailing list.
20654 HOWEVER, some variables you have customized may contain private
20655 information. The names of customers, colleagues, or friends, might
20656 appear in the form of file names, tags, todo states, or search strings.
20657 If you answer yes to the prompt, you might want to check and remove
20658 such private information before sending the email.")
20659 (add-text-properties (point-min) (point-max) '(face org-warning))
20660 (when (yes-or-no-p "Include your Org-mode configuration ")
20661 (mapatoms
20662 (lambda (v)
20663 (and (boundp v)
20664 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20665 (or (and (symbol-value v)
20666 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20667 (and
20668 (get v 'custom-type) (get v 'standard-value)
20669 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20670 (push v list)))))
20671 (kill-buffer (get-buffer "*Warn about privacy*"))
20672 list))
20673 nil nil
20674 "Remember to cover the basics, that is, what you expected to happen and
20675 what in fact did happen. You don't know how to make a good report? See
20677 http://orgmode.org/manual/Feedback.html#Feedback
20679 Your bug report will be posted to the Org-mode mailing list.
20680 ------------------------------------------------------------------------")
20681 (save-excursion
20682 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20683 (replace-match "\\1Bug: \\3 [\\2]")))))
20686 (defun org-install-agenda-files-menu ()
20687 (let ((bl (buffer-list)))
20688 (save-excursion
20689 (while bl
20690 (set-buffer (pop bl))
20691 (if (derived-mode-p 'org-mode) (setq bl nil)))
20692 (when (derived-mode-p 'org-mode)
20693 (easy-menu-change
20694 '("Org") "File List for Agenda"
20695 (append
20696 (list
20697 ["Edit File List" (org-edit-agenda-file-list) t]
20698 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20699 ["Remove Current File from List" org-remove-file t]
20700 ["Cycle through agenda files" org-cycle-agenda-files t]
20701 ["Occur in all agenda files" org-occur-in-agenda-files t]
20702 "--")
20703 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20705 ;;;; Documentation
20707 (defun org-require-autoloaded-modules ()
20708 (interactive)
20709 (mapc 'require
20710 '(org-agenda org-archive org-attach org-clock org-colview org-id
20711 org-remember org-table org-timer)))
20713 ;;;###autoload
20714 (defun org-reload (&optional uncompiled)
20715 "Reload all org lisp files.
20716 With prefix arg UNCOMPILED, load the uncompiled versions."
20717 (interactive "P")
20718 (require 'loadhist)
20719 (let* ((org-dir (org-find-library-dir "org"))
20720 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20721 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20722 (remove-re (mapconcat 'identity
20723 (mapcar (lambda (f) (concat "^" f "$"))
20724 (list (if (featurep 'xemacs)
20725 "org-colview"
20726 "org-colview-xemacs")
20727 "org" "org-loaddefs" "org-version"))
20728 "\\|"))
20729 (feats (delete-dups
20730 (mapcar 'file-name-sans-extension
20731 (mapcar 'file-name-nondirectory
20732 (delq nil
20733 (mapcar 'feature-file
20734 features))))))
20735 (lfeat (append
20736 (sort
20737 (setq feats
20738 (delq nil (mapcar
20739 (lambda (f)
20740 (if (and (string-match feature-re f)
20741 (not (string-match remove-re f)))
20742 f nil))
20743 feats)))
20744 'string-lessp)
20745 (list "org-version" "org")))
20746 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20747 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20748 load-uncore load-misses)
20749 (setq load-misses
20750 (delq 't
20751 (mapcar (lambda (f)
20752 (or (org-load-noerror-mustsuffix (concat org-dir f))
20753 (and (string= org-dir contrib-dir)
20754 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20755 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20756 (add-to-list 'load-uncore f 'append)
20759 lfeat)))
20760 (if load-uncore
20761 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20762 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20763 (if load-misses
20764 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20765 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20766 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20768 ;;;###autoload
20769 (defun org-customize ()
20770 "Call the customize function with org as argument."
20771 (interactive)
20772 (org-load-modules-maybe)
20773 (org-require-autoloaded-modules)
20774 (customize-browse 'org))
20776 (defun org-create-customize-menu ()
20777 "Create a full customization menu for Org-mode, insert it into the menu."
20778 (interactive)
20779 (org-load-modules-maybe)
20780 (org-require-autoloaded-modules)
20781 (if (fboundp 'customize-menu-create)
20782 (progn
20783 (easy-menu-change
20784 '("Org") "Customize"
20785 `(["Browse Org group" org-customize t]
20786 "--"
20787 ,(customize-menu-create 'org)
20788 ["Set" Custom-set t]
20789 ["Save" Custom-save t]
20790 ["Reset to Current" Custom-reset-current t]
20791 ["Reset to Saved" Custom-reset-saved t]
20792 ["Reset to Standard Settings" Custom-reset-standard t]))
20793 (message "\"Org\"-menu now contains full customization menu"))
20794 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20796 ;;;; Miscellaneous stuff
20798 ;;; Generally useful functions
20800 (defun org-get-at-bol (property)
20801 "Get text property PROPERTY at beginning of line."
20802 (get-text-property (point-at-bol) property))
20804 (defun org-find-text-property-in-string (prop s)
20805 "Return the first non-nil value of property PROP in string S."
20806 (or (get-text-property 0 prop s)
20807 (get-text-property (or (next-single-property-change 0 prop s) 0)
20808 prop s)))
20810 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20811 "Display the given MESSAGE as a warning."
20812 (if (fboundp 'display-warning)
20813 (display-warning 'org message
20814 (if (featurep 'xemacs) 'warning :warning))
20815 (let ((buf (get-buffer-create "*Org warnings*")))
20816 (with-current-buffer buf
20817 (goto-char (point-max))
20818 (insert "Warning (Org): " message)
20819 (unless (bolp)
20820 (newline)))
20821 (display-buffer buf)
20822 (sit-for 0))))
20824 (defun org-eval (form)
20825 "Eval FORM and return result."
20826 (condition-case error
20827 (eval form)
20828 (error (format "%%![Error: %s]" error))))
20830 (defun org-in-clocktable-p ()
20831 "Check if the cursor is in a clocktable."
20832 (let ((pos (point)) start)
20833 (save-excursion
20834 (end-of-line 1)
20835 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20836 (setq start (match-beginning 0))
20837 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20838 (>= (match-end 0) pos)
20839 start))))
20841 (defun org-in-commented-line ()
20842 "Is point in a line starting with `#'?"
20843 (equal (char-after (point-at-bol)) ?#))
20845 (defun org-in-indented-comment-line ()
20846 "Is point in a line starting with `#' after some white space?"
20847 (save-excursion
20848 (save-match-data
20849 (goto-char (point-at-bol))
20850 (looking-at "[ \t]*#"))))
20852 (defun org-in-verbatim-emphasis ()
20853 (save-match-data
20854 (and (org-in-regexp org-emph-re 2)
20855 (>= (point) (match-beginning 3))
20856 (<= (point) (match-end 4))
20857 (member (match-string 3) '("=" "~")))))
20859 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20860 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20861 (if (and marker (marker-buffer marker)
20862 (buffer-live-p (marker-buffer marker)))
20863 (progn
20864 (org-pop-to-buffer-same-window (marker-buffer marker))
20865 (if (or (> marker (point-max)) (< marker (point-min)))
20866 (widen))
20867 (goto-char marker)
20868 (org-show-context 'org-goto))
20869 (if bookmark
20870 (bookmark-jump bookmark)
20871 (error "Cannot find location"))))
20873 (defun org-quote-csv-field (s)
20874 "Quote field for inclusion in CSV material."
20875 (if (string-match "[\",]" s)
20876 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20879 (defun org-force-self-insert (N)
20880 "Needed to enforce self-insert under remapping."
20881 (interactive "p")
20882 (self-insert-command N))
20884 (defun org-string-width (s)
20885 "Compute width of string, ignoring invisible characters.
20886 This ignores character with invisibility property `org-link', and also
20887 characters with property `org-cwidth', because these will become invisible
20888 upon the next fontification round."
20889 (let (b l)
20890 (when (or (eq t buffer-invisibility-spec)
20891 (assq 'org-link buffer-invisibility-spec))
20892 (while (setq b (text-property-any 0 (length s)
20893 'invisible 'org-link s))
20894 (setq s (concat (substring s 0 b)
20895 (substring s (or (next-single-property-change
20896 b 'invisible s) (length s)))))))
20897 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20898 (setq s (concat (substring s 0 b)
20899 (substring s (or (next-single-property-change
20900 b 'org-cwidth s) (length s))))))
20901 (setq l (string-width s) b -1)
20902 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20903 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20906 (defun org-shorten-string (s maxlength)
20907 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20908 If the string is shorter or has length MAXLENGTH, just return the
20909 original string. If it is longer, the functions finds a space in the
20910 string, breaks this string off at that locations and adds three dots
20911 as ellipsis. Including the ellipsis, the string will not be longer
20912 than MAXLENGTH. If finding a good breaking point in the string does
20913 not work, the string is just chopped off in the middle of a word
20914 if necessary."
20915 (if (<= (length s) maxlength)
20917 (let* ((n (max (- maxlength 4) 1))
20918 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20919 (if (string-match re s)
20920 (concat (match-string 1 s) "...")
20921 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20923 (defun org-get-indentation (&optional line)
20924 "Get the indentation of the current line, interpreting tabs.
20925 When LINE is given, assume it represents a line and compute its indentation."
20926 (if line
20927 (if (string-match "^ *" (org-remove-tabs line))
20928 (match-end 0))
20929 (save-excursion
20930 (beginning-of-line 1)
20931 (skip-chars-forward " \t")
20932 (current-column))))
20934 (defun org-get-string-indentation (s)
20935 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20936 (let ((n -1) (i 0) (w tab-width) c)
20937 (catch 'exit
20938 (while (< (setq n (1+ n)) (length s))
20939 (setq c (aref s n))
20940 (cond ((= c ?\ ) (setq i (1+ i)))
20941 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20942 (t (throw 'exit t)))))
20945 (defun org-remove-tabs (s &optional width)
20946 "Replace tabulators in S with spaces.
20947 Assumes that s is a single line, starting in column 0."
20948 (setq width (or width tab-width))
20949 (while (string-match "\t" s)
20950 (setq s (replace-match
20951 (make-string
20952 (- (* width (/ (+ (match-beginning 0) width) width))
20953 (match-beginning 0)) ?\ )
20954 t t s)))
20957 (defun org-fix-indentation (line ind)
20958 "Fix indentation in LINE.
20959 IND is a cons cell with target and minimum indentation.
20960 If the current indentation in LINE is smaller than the minimum,
20961 leave it alone. If it is larger than ind, set it to the target."
20962 (let* ((l (org-remove-tabs line))
20963 (i (org-get-indentation l))
20964 (i1 (car ind)) (i2 (cdr ind)))
20965 (if (>= i i2) (setq l (substring line i2)))
20966 (if (> i1 0)
20967 (concat (make-string i1 ?\ ) l)
20968 l)))
20970 (defun org-remove-indentation (code &optional n)
20971 "Remove the maximum common indentation from the lines in CODE.
20972 N may optionally be the number of spaces to remove."
20973 (with-temp-buffer
20974 (insert code)
20975 (org-do-remove-indentation n)
20976 (buffer-string)))
20978 (defun org-do-remove-indentation (&optional n)
20979 "Remove the maximum common indentation from the buffer."
20980 (untabify (point-min) (point-max))
20981 (let ((min 10000) re)
20982 (if n
20983 (setq min n)
20984 (goto-char (point-min))
20985 (while (re-search-forward "^ *[^ \n]" nil t)
20986 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20987 (unless (or (= min 0) (= min 10000))
20988 (setq re (format "^ \\{%d\\}" min))
20989 (goto-char (point-min))
20990 (while (re-search-forward re nil t)
20991 (replace-match "")
20992 (end-of-line 1))
20993 min)))
20995 (defun org-fill-template (template alist)
20996 "Find each %key of ALIST in TEMPLATE and replace it."
20997 (let ((case-fold-search nil)
20998 entry key value)
20999 (setq alist (sort (copy-sequence alist)
21000 (lambda (a b) (< (length (car a)) (length (car b))))))
21001 (while (setq entry (pop alist))
21002 (setq template
21003 (replace-regexp-in-string
21004 (concat "%" (regexp-quote (car entry)))
21005 (or (cdr entry) "") template t t)))
21006 template))
21008 (defun org-base-buffer (buffer)
21009 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21010 (if (not buffer)
21011 buffer
21012 (or (buffer-base-buffer buffer)
21013 buffer)))
21015 (defun org-trim (s)
21016 "Remove whitespace at beginning and end of string."
21017 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21018 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21021 (defun org-wrap (string &optional width lines)
21022 "Wrap string to either a number of lines, or a width in characters.
21023 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21024 that costs. If there is a word longer than WIDTH, the text is actually
21025 wrapped to the length of that word.
21026 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21027 many lines, whatever width that takes.
21028 The return value is a list of lines, without newlines at the end."
21029 (let* ((words (org-split-string string "[ \t\n]+"))
21030 (maxword (apply 'max (mapcar 'org-string-width words)))
21031 w ll)
21032 (cond (width
21033 (org-do-wrap words (max maxword width)))
21034 (lines
21035 (setq w maxword)
21036 (setq ll (org-do-wrap words maxword))
21037 (if (<= (length ll) lines)
21039 (setq ll words)
21040 (while (> (length ll) lines)
21041 (setq w (1+ w))
21042 (setq ll (org-do-wrap words w)))
21043 ll))
21044 (t (error "Cannot wrap this")))))
21046 (defun org-do-wrap (words width)
21047 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21048 (let (lines line)
21049 (while words
21050 (setq line (pop words))
21051 (while (and words (< (+ (length line) (length (car words))) width))
21052 (setq line (concat line " " (pop words))))
21053 (setq lines (push line lines)))
21054 (nreverse lines)))
21056 (defun org-split-string (string &optional separators)
21057 "Splits STRING into substrings at SEPARATORS.
21058 No empty strings are returned if there are matches at the beginning
21059 and end of string."
21060 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21061 (start 0)
21062 notfirst
21063 (list nil))
21064 (while (and (string-match rexp string
21065 (if (and notfirst
21066 (= start (match-beginning 0))
21067 (< start (length string)))
21068 (1+ start) start))
21069 (< (match-beginning 0) (length string)))
21070 (setq notfirst t)
21071 (or (eq (match-beginning 0) 0)
21072 (and (eq (match-beginning 0) (match-end 0))
21073 (eq (match-beginning 0) start))
21074 (setq list
21075 (cons (substring string start (match-beginning 0))
21076 list)))
21077 (setq start (match-end 0)))
21078 (or (eq start (length string))
21079 (setq list
21080 (cons (substring string start)
21081 list)))
21082 (nreverse list)))
21084 (defun org-quote-vert (s)
21085 "Replace \"|\" with \"\\vert\"."
21086 (while (string-match "|" s)
21087 (setq s (replace-match "\\vert" t t s)))
21090 (defun org-uuidgen-p (s)
21091 "Is S an ID created by UUIDGEN?"
21092 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21094 (defun org-in-src-block-p (&optional inside)
21095 "Whether point is in a code source block.
21096 When INSIDE is non-nil, don't consider we are within a src block
21097 when point is at #+BEGIN_SRC or #+END_SRC."
21098 (let ((case-fold-search t) ov)
21099 (or (and (setq ov (overlays-at (point)))
21100 (memq 'org-block-background
21101 (overlay-properties (car ov))))
21102 (and (not inside)
21103 (save-match-data
21104 (save-excursion
21105 (beginning-of-line)
21106 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21108 (defun org-context ()
21109 "Return a list of contexts of the current cursor position.
21110 If several contexts apply, all are returned.
21111 Each context entry is a list with a symbol naming the context, and
21112 two positions indicating start and end of the context. Possible
21113 contexts are:
21115 :headline anywhere in a headline
21116 :headline-stars on the leading stars in a headline
21117 :todo-keyword on a TODO keyword (including DONE) in a headline
21118 :tags on the TAGS in a headline
21119 :priority on the priority cookie in a headline
21120 :item on the first line of a plain list item
21121 :item-bullet on the bullet/number of a plain list item
21122 :checkbox on the checkbox in a plain list item
21123 :table in an org-mode table
21124 :table-special on a special filed in a table
21125 :table-table in a table.el table
21126 :clocktable in a clocktable
21127 :src-block in a source block
21128 :link on a hyperlink
21129 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21130 :target on a <<target>>
21131 :radio-target on a <<<radio-target>>>
21132 :latex-fragment on a LaTeX fragment
21133 :latex-preview on a LaTeX fragment with overlaid preview image
21135 This function expects the position to be visible because it uses font-lock
21136 faces as a help to recognize the following contexts: :table-special, :link,
21137 and :keyword."
21138 (let* ((f (get-text-property (point) 'face))
21139 (faces (if (listp f) f (list f)))
21140 (case-fold-search t)
21141 (p (point)) clist o)
21142 ;; First the large context
21143 (cond
21144 ((org-at-heading-p t)
21145 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21146 (when (progn
21147 (beginning-of-line 1)
21148 (looking-at org-todo-line-tags-regexp))
21149 (push (org-point-in-group p 1 :headline-stars) clist)
21150 (push (org-point-in-group p 2 :todo-keyword) clist)
21151 (push (org-point-in-group p 4 :tags) clist))
21152 (goto-char p)
21153 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21154 (if (looking-at "\\[#[A-Z0-9]\\]")
21155 (push (org-point-in-group p 0 :priority) clist)))
21157 ((org-at-item-p)
21158 (push (org-point-in-group p 2 :item-bullet) clist)
21159 (push (list :item (point-at-bol)
21160 (save-excursion (org-end-of-item) (point)))
21161 clist)
21162 (and (org-at-item-checkbox-p)
21163 (push (org-point-in-group p 0 :checkbox) clist)))
21165 ((org-at-table-p)
21166 (push (list :table (org-table-begin) (org-table-end)) clist)
21167 (if (memq 'org-formula faces)
21168 (push (list :table-special
21169 (previous-single-property-change p 'face)
21170 (next-single-property-change p 'face)) clist)))
21171 ((org-at-table-p 'any)
21172 (push (list :table-table) clist)))
21173 (goto-char p)
21175 (let ((case-fold-search t))
21176 ;; New the "medium" contexts: clocktables, source blocks
21177 (cond ((org-in-clocktable-p)
21178 (push (list :clocktable
21179 (and (or (looking-at "#\\+BEGIN: clocktable")
21180 (search-backward "#+BEGIN: clocktable" nil t))
21181 (match-beginning 0))
21182 (and (re-search-forward "#\\+END:?" nil t)
21183 (match-end 0))) clist))
21184 ((org-in-src-block-p)
21185 (push (list :src-block
21186 (and (or (looking-at "#\\+BEGIN_SRC")
21187 (search-backward "#+BEGIN_SRC" nil t))
21188 (match-beginning 0))
21189 (and (search-forward "#+END_SRC" nil t)
21190 (match-beginning 0))) clist))))
21191 (goto-char p)
21193 ;; Now the small context
21194 (cond
21195 ((org-at-timestamp-p)
21196 (push (org-point-in-group p 0 :timestamp) clist))
21197 ((memq 'org-link faces)
21198 (push (list :link
21199 (previous-single-property-change p 'face)
21200 (next-single-property-change p 'face)) clist))
21201 ((memq 'org-special-keyword faces)
21202 (push (list :keyword
21203 (previous-single-property-change p 'face)
21204 (next-single-property-change p 'face)) clist))
21205 ((org-at-target-p)
21206 (push (org-point-in-group p 0 :target) clist)
21207 (goto-char (1- (match-beginning 0)))
21208 (if (looking-at org-radio-target-regexp)
21209 (push (org-point-in-group p 0 :radio-target) clist))
21210 (goto-char p))
21211 ((setq o (car (delq nil
21212 (mapcar
21213 (lambda (x)
21214 (if (memq x org-latex-fragment-image-overlays) x))
21215 (overlays-at (point))))))
21216 (push (list :latex-fragment
21217 (overlay-start o) (overlay-end o)) clist)
21218 (push (list :latex-preview
21219 (overlay-start o) (overlay-end o)) clist))
21220 ((org-inside-LaTeX-fragment-p)
21221 ;; FIXME: positions wrong.
21222 (push (list :latex-fragment (point) (point)) clist)))
21224 (setq clist (nreverse (delq nil clist)))
21225 clist))
21227 ;; FIXME: Compare with at-regexp-p Do we need both?
21228 (defun org-in-regexp (re &optional nlines visually)
21229 "Check if point is inside a match of regexp.
21230 Normally only the current line is checked, but you can include NLINES extra
21231 lines both before and after point into the search.
21232 If VISUALLY is set, require that the cursor is not after the match but
21233 really on, so that the block visually is on the match."
21234 (catch 'exit
21235 (let ((pos (point))
21236 (eol (point-at-eol (+ 1 (or nlines 0))))
21237 (inc (if visually 1 0)))
21238 (save-excursion
21239 (beginning-of-line (- 1 (or nlines 0)))
21240 (while (re-search-forward re eol t)
21241 (if (and (<= (match-beginning 0) pos)
21242 (>= (+ inc (match-end 0)) pos))
21243 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21245 (defun org-at-regexp-p (regexp)
21246 "Is point inside a match of REGEXP in the current line?"
21247 (catch 'exit
21248 (save-excursion
21249 (let ((pos (point)) (end (point-at-eol)))
21250 (beginning-of-line 1)
21251 (while (re-search-forward regexp end t)
21252 (if (and (<= (match-beginning 0) pos)
21253 (>= (match-end 0) pos))
21254 (throw 'exit t)))
21255 nil))))
21257 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21258 "Non-nil when point is between matches of START-RE and END-RE.
21260 Also return a non-nil value when point is on one of the matches.
21262 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21263 buffer positions. Default values are the positions of headlines
21264 surrounding the point.
21266 The functions returns a cons cell whose car (resp. cdr) is the
21267 position before START-RE (resp. after END-RE)."
21268 (save-match-data
21269 (let ((pos (point))
21270 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21271 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21272 beg end)
21273 (save-excursion
21274 ;; Point is on a block when on START-RE or if START-RE can be
21275 ;; found before it...
21276 (and (or (org-at-regexp-p start-re)
21277 (re-search-backward start-re limit-up t))
21278 (setq beg (match-beginning 0))
21279 ;; ... and END-RE after it...
21280 (goto-char (match-end 0))
21281 (re-search-forward end-re limit-down t)
21282 (> (setq end (match-end 0)) pos)
21283 ;; ... without another START-RE in-between.
21284 (goto-char (match-beginning 0))
21285 (not (re-search-backward start-re (1+ beg) t))
21286 ;; Return value.
21287 (cons beg end))))))
21289 (defun org-in-block-p (names)
21290 "Non-nil when point belongs to a block whose name belongs to NAMES.
21292 NAMES is a list of strings containing names of blocks.
21294 Return first block name matched, or nil. Beware that in case of
21295 nested blocks, the returned name may not belong to the closest
21296 block from point."
21297 (save-match-data
21298 (catch 'exit
21299 (let ((case-fold-search t)
21300 (lim-up (save-excursion (outline-previous-heading)))
21301 (lim-down (save-excursion (outline-next-heading))))
21302 (mapc (lambda (name)
21303 (let ((n (regexp-quote name)))
21304 (when (org-between-regexps-p
21305 (concat "^[ \t]*#\\+begin_" n)
21306 (concat "^[ \t]*#\\+end_" n)
21307 lim-up lim-down)
21308 (throw 'exit n))))
21309 names))
21310 nil)))
21312 (defun org-occur-in-agenda-files (regexp &optional nlines)
21313 "Call `multi-occur' with buffers for all agenda files."
21314 (interactive "sOrg-files matching: \np")
21315 (let* ((files (org-agenda-files))
21316 (tnames (mapcar 'file-truename files))
21317 (extra org-agenda-text-search-extra-files)
21319 (when (eq (car extra) 'agenda-archives)
21320 (setq extra (cdr extra))
21321 (setq files (org-add-archive-files files)))
21322 (while (setq f (pop extra))
21323 (unless (member (file-truename f) tnames)
21324 (add-to-list 'files f 'append)
21325 (add-to-list 'tnames (file-truename f) 'append)))
21326 (multi-occur
21327 (mapcar (lambda (x)
21328 (with-current-buffer
21329 (or (get-file-buffer x) (find-file-noselect x))
21330 (widen)
21331 (current-buffer)))
21332 files)
21333 regexp)))
21335 (if (boundp 'occur-mode-find-occurrence-hook)
21336 ;; Emacs 23
21337 (add-hook 'occur-mode-find-occurrence-hook
21338 (lambda ()
21339 (when (derived-mode-p 'org-mode)
21340 (org-reveal))))
21341 ;; Emacs 22
21342 (defadvice occur-mode-goto-occurrence
21343 (after org-occur-reveal activate)
21344 (and (derived-mode-p 'org-mode) (org-reveal)))
21345 (defadvice occur-mode-goto-occurrence-other-window
21346 (after org-occur-reveal activate)
21347 (and (derived-mode-p 'org-mode) (org-reveal)))
21348 (defadvice occur-mode-display-occurrence
21349 (after org-occur-reveal activate)
21350 (when (derived-mode-p 'org-mode)
21351 (let ((pos (occur-mode-find-occurrence)))
21352 (with-current-buffer (marker-buffer pos)
21353 (save-excursion
21354 (goto-char pos)
21355 (org-reveal)))))))
21357 (defun org-occur-link-in-agenda-files ()
21358 "Create a link and search for it in the agendas.
21359 The link is not stored in `org-stored-links', it is just created
21360 for the search purpose."
21361 (interactive)
21362 (let ((link (condition-case nil
21363 (org-store-link nil)
21364 (error "Unable to create a link to here"))))
21365 (org-occur-in-agenda-files (regexp-quote link))))
21367 (defun org-reverse-string (string)
21368 "Return the reverse of STRING."
21369 (apply 'string (reverse (string-to-list string))))
21371 (defun org-uniquify (list)
21372 "Remove duplicate elements from LIST."
21373 (let (res)
21374 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21375 res))
21377 (defun org-delete-all (elts list)
21378 "Remove all elements in ELTS from LIST."
21379 (while elts
21380 (setq list (delete (pop elts) list)))
21381 list)
21383 (defun org-count (cl-item cl-seq)
21384 "Count the number of occurrences of ITEM in SEQ.
21385 Taken from `count' in cl-seq.el with all keyword arguments removed."
21386 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21387 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21388 (while (< cl-start cl-end)
21389 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21390 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21391 (setq cl-start (1+ cl-start)))
21392 cl-count))
21394 (defun org-remove-if (predicate seq)
21395 "Remove everything from SEQ that fulfills PREDICATE."
21396 (let (res e)
21397 (while seq
21398 (setq e (pop seq))
21399 (if (not (funcall predicate e)) (push e res)))
21400 (nreverse res)))
21402 (defun org-remove-if-not (predicate seq)
21403 "Remove everything from SEQ that does not fulfill PREDICATE."
21404 (let (res e)
21405 (while seq
21406 (setq e (pop seq))
21407 (if (funcall predicate e) (push e res)))
21408 (nreverse res)))
21410 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21411 "Reduce two-argument FUNCTION across SEQ.
21412 Taken from `reduce' in cl-seq.el with all keyword arguments but
21413 \":initial-value\" removed."
21414 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21415 (cadr (memq :initial-value cl-keys)))
21416 (cl-seq (pop cl-seq))
21417 (t (funcall cl-func)))))
21418 (while cl-seq
21419 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21420 cl-accum))
21422 (defun org-back-over-empty-lines ()
21423 "Move backwards over whitespace, to the beginning of the first empty line.
21424 Returns the number of empty lines passed."
21425 (let ((pos (point)))
21426 (if (cdr (assoc 'heading org-blank-before-new-entry))
21427 (skip-chars-backward " \t\n\r")
21428 (unless (eobp)
21429 (forward-line -1)))
21430 (beginning-of-line 2)
21431 (goto-char (min (point) pos))
21432 (count-lines (point) pos)))
21434 (defun org-skip-whitespace ()
21435 (skip-chars-forward " \t\n\r"))
21437 (defun org-point-in-group (point group &optional context)
21438 "Check if POINT is in match-group GROUP.
21439 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21440 match. If the match group does not exist or point is not inside it,
21441 return nil."
21442 (and (match-beginning group)
21443 (>= point (match-beginning group))
21444 (<= point (match-end group))
21445 (if context
21446 (list context (match-beginning group) (match-end group))
21447 t)))
21449 (defun org-switch-to-buffer-other-window (&rest args)
21450 "Switch to buffer in a second window on the current frame.
21451 In particular, do not allow pop-up frames.
21452 Returns the newly created buffer."
21453 (org-no-popups
21454 (apply 'switch-to-buffer-other-window args)))
21456 (defun org-combine-plists (&rest plists)
21457 "Create a single property list from all plists in PLISTS.
21458 The process starts by copying the first list, and then setting properties
21459 from the other lists. Settings in the last list are the most significant
21460 ones and overrule settings in the other lists."
21461 (let ((rtn (copy-sequence (pop plists)))
21462 p v ls)
21463 (while plists
21464 (setq ls (pop plists))
21465 (while ls
21466 (setq p (pop ls) v (pop ls))
21467 (setq rtn (plist-put rtn p v))))
21468 rtn))
21470 (defun org-replace-escapes (string table)
21471 "Replace %-escapes in STRING with values in TABLE.
21472 TABLE is an association list with keys like \"%a\" and string values.
21473 The sequences in STRING may contain normal field width and padding information,
21474 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21475 so values can contain further %-escapes if they are define later in TABLE."
21476 (let ((tbl (copy-alist table))
21477 (case-fold-search nil)
21478 (pchg 0)
21479 e re rpl)
21480 (while (setq e (pop tbl))
21481 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21482 (when (and (cdr e) (string-match re (cdr e)))
21483 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21484 (safe "SREF"))
21485 (add-text-properties 0 3 (list 'sref sref) safe)
21486 (setcdr e (replace-match safe t t (cdr e)))))
21487 (while (string-match re string)
21488 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21489 (cdr e)))
21490 (setq string (replace-match rpl t t string))))
21491 (while (setq pchg (next-property-change pchg string))
21492 (let ((sref (get-text-property pchg 'sref string)))
21493 (when (and sref (string-match "SREF" string pchg))
21494 (setq string (replace-match sref t t string)))))
21495 string))
21497 (defun org-sublist (list start end)
21498 "Return a section of LIST, from START to END.
21499 Counting starts at 1."
21500 (let (rtn (c start))
21501 (setq list (nthcdr (1- start) list))
21502 (while (and list (<= c end))
21503 (push (pop list) rtn)
21504 (setq c (1+ c)))
21505 (nreverse rtn)))
21507 (defun org-find-base-buffer-visiting (file)
21508 "Like `find-buffer-visiting' but always return the base buffer and
21509 not an indirect buffer."
21510 (let ((buf (or (get-file-buffer file)
21511 (find-buffer-visiting file))))
21512 (if buf
21513 (or (buffer-base-buffer buf) buf)
21514 nil)))
21516 (defun org-image-file-name-regexp (&optional extensions)
21517 "Return regexp matching the file names of images.
21518 If EXTENSIONS is given, only match these."
21519 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21520 (image-file-name-regexp)
21521 (let ((image-file-name-extensions
21522 (or extensions
21523 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21524 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21525 (concat "\\."
21526 (regexp-opt (nconc (mapcar 'upcase
21527 image-file-name-extensions)
21528 image-file-name-extensions)
21530 "\\'"))))
21532 (defun org-file-image-p (file &optional extensions)
21533 "Return non-nil if FILE is an image."
21534 (save-match-data
21535 (string-match (org-image-file-name-regexp extensions) file)))
21537 (defun org-get-cursor-date (&optional with-time)
21538 "Return the date at cursor in as a time.
21539 This works in the calendar and in the agenda, anywhere else it just
21540 returns the current time.
21541 If WITH-TIME is non-nil, returns the time of the event at point (in
21542 the agenda) or the current time of the day."
21543 (let (date day defd tp tm hod mod)
21544 (when with-time
21545 (setq tp (get-text-property (point) 'time))
21546 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21547 (setq hod (string-to-number (match-string 1 tp))
21548 mod (string-to-number (match-string 2 tp))))
21549 (or tp (setq hod (nth 2 (decode-time (current-time)))
21550 mod (nth 1 (decode-time (current-time))))))
21551 (cond
21552 ((eq major-mode 'calendar-mode)
21553 (setq date (calendar-cursor-to-date)
21554 defd (encode-time 0 (or mod 0) (or hod 0)
21555 (nth 1 date) (nth 0 date) (nth 2 date))))
21556 ((eq major-mode 'org-agenda-mode)
21557 (setq day (get-text-property (point) 'day))
21558 (if day
21559 (setq date (calendar-gregorian-from-absolute day)
21560 defd (encode-time 0 (or mod 0) (or hod 0)
21561 (nth 1 date) (nth 0 date) (nth 2 date))))))
21562 (or defd (current-time))))
21564 (defun org-mark-subtree (&optional up)
21565 "Mark the current subtree.
21566 This puts point at the start of the current subtree, and mark at
21567 the end. If a numeric prefix UP is given, move up into the
21568 hierarchy of headlines by UP levels before marking the subtree."
21569 (interactive "P")
21570 (org-with-limited-levels
21571 (cond ((org-at-heading-p) (beginning-of-line))
21572 ((org-before-first-heading-p) (error "Not in a subtree"))
21573 (t (outline-previous-visible-heading 1))))
21574 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21575 (if (org-called-interactively-p 'any)
21576 (call-interactively 'org-mark-element)
21577 (org-mark-element)))
21580 ;;; Indentation
21582 (defun org-indent-line ()
21583 "Indent line depending on context."
21584 (interactive)
21585 (let* ((pos (point))
21586 (itemp (org-at-item-p))
21587 (case-fold-search t)
21588 (org-drawer-regexp (or org-drawer-regexp "\000"))
21589 (inline-task-p (and (featurep 'org-inlinetask)
21590 (org-inlinetask-in-task-p)))
21591 (inline-re (and inline-task-p
21592 (org-inlinetask-outline-regexp)))
21593 column)
21594 (if (and orgstruct-is-++ (eq pos (point)))
21595 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21596 (indent-according-to-mode))
21597 (beginning-of-line 1)
21598 (cond
21599 ;; Headings
21600 ((looking-at org-outline-regexp) (setq column 0))
21601 ;; Footnote definition
21602 ((looking-at org-footnote-definition-re) (setq column 0))
21603 ;; Literal examples
21604 ((looking-at "[ \t]*:\\( \\|$\\)")
21605 (setq column (org-get-indentation))) ; do nothing
21606 ;; Lists
21607 ((ignore-errors (goto-char (org-in-item-p)))
21608 (setq column (if itemp
21609 (org-get-indentation)
21610 (org-list-item-body-column (point))))
21611 (goto-char pos))
21612 ;; Drawers
21613 ((and (looking-at "[ \t]*:END:")
21614 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21615 (save-excursion
21616 (goto-char (1- (match-beginning 1)))
21617 (setq column (current-column))))
21618 ;; Special blocks
21619 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21620 (save-excursion
21621 (re-search-backward
21622 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21623 (setq column (org-get-indentation (match-string 0))))
21624 ((and (not (looking-at "[ \t]*#\\+begin_"))
21625 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21626 (save-excursion
21627 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21628 (setq column
21629 (cond ((equal (downcase (match-string 1)) "src")
21630 ;; src blocks: let `org-edit-src-exit' handle them
21631 (org-get-indentation))
21632 ((equal (downcase (match-string 1)) "example")
21633 (max (org-get-indentation)
21634 (org-get-indentation (match-string 0))))
21636 (org-get-indentation (match-string 0))))))
21637 ;; This line has nothing special, look at the previous relevant
21638 ;; line to compute indentation
21640 (beginning-of-line 0)
21641 (while (and (not (bobp))
21642 (not (looking-at org-table-line-regexp))
21643 (not (looking-at org-drawer-regexp))
21644 ;; When point started in an inline task, do not move
21645 ;; above task starting line.
21646 (not (and inline-task-p (looking-at inline-re)))
21647 ;; Skip drawers, blocks, empty lines, verbatim,
21648 ;; comments, tables, footnotes definitions, lists,
21649 ;; inline tasks.
21650 (or (and (looking-at "[ \t]*:END:")
21651 (re-search-backward org-drawer-regexp nil t))
21652 (and (looking-at "[ \t]*#\\+end_")
21653 (re-search-backward "[ \t]*#\\+begin_"nil t))
21654 (looking-at "[ \t]*[\n:#|]")
21655 (looking-at org-footnote-definition-re)
21656 (and (ignore-errors (goto-char (org-in-item-p)))
21657 (goto-char
21658 (org-list-get-top-point (org-list-struct))))
21659 (and (not inline-task-p)
21660 (featurep 'org-inlinetask)
21661 (org-inlinetask-in-task-p)
21662 (or (org-inlinetask-goto-beginning) t))))
21663 (beginning-of-line 0))
21664 (cond
21665 ;; There was an heading above.
21666 ((looking-at "\\*+[ \t]+")
21667 (if (not org-adapt-indentation)
21668 (setq column 0)
21669 (goto-char (match-end 0))
21670 (setq column (current-column))))
21671 ;; A drawer had started and is unfinished
21672 ((looking-at org-drawer-regexp)
21673 (goto-char (1- (match-beginning 1)))
21674 (setq column (current-column)))
21675 ;; Else, nothing noticeable found: get indentation and go on.
21676 (t (setq column (org-get-indentation))))))
21677 ;; Now apply indentation and move cursor accordingly
21678 (goto-char pos)
21679 (if (<= (current-column) (current-indentation))
21680 (org-indent-line-to column)
21681 (save-excursion (org-indent-line-to column)))
21682 ;; Special polishing for properties, see `org-property-format'
21683 (setq column (current-column))
21684 (beginning-of-line 1)
21685 (if (looking-at
21686 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21687 (replace-match (concat (match-string 1)
21688 (format org-property-format
21689 (match-string 2) (match-string 3)))
21690 t t))
21691 (org-move-to-column column))))
21693 (defun org-indent-drawer ()
21694 "Indent the drawer at point."
21695 (interactive)
21696 (let ((p (point))
21697 (e (and (save-excursion (re-search-forward ":END:" nil t))
21698 (match-end 0)))
21699 (folded
21700 (save-excursion
21701 (end-of-line)
21702 (when (overlays-at (point))
21703 (member 'invisible (overlay-properties
21704 (car (overlays-at (point)))))))))
21705 (when folded (org-cycle))
21706 (indent-for-tab-command)
21707 (while (and (move-beginning-of-line 2) (< (point) e))
21708 (indent-for-tab-command))
21709 (goto-char p)
21710 (when folded (org-cycle)))
21711 (message "Drawer at point indented"))
21713 (defun org-indent-block ()
21714 "Indent the block at point."
21715 (interactive)
21716 (let ((p (point))
21717 (case-fold-search t)
21718 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21719 (match-end 0)))
21720 (folded
21721 (save-excursion
21722 (end-of-line)
21723 (when (overlays-at (point))
21724 (member 'invisible (overlay-properties
21725 (car (overlays-at (point)))))))))
21726 (when folded (org-cycle))
21727 (indent-for-tab-command)
21728 (while (and (move-beginning-of-line 2) (< (point) e))
21729 (indent-for-tab-command))
21730 (goto-char p)
21731 (when folded (org-cycle)))
21732 (message "Block at point indented"))
21734 (defun org-indent-region (start end)
21735 "Indent region."
21736 (interactive "r")
21737 (save-excursion
21738 (let ((line-end (org-current-line end)))
21739 (goto-char start)
21740 (while (< (org-current-line) line-end)
21741 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21742 (t (call-interactively 'org-indent-line)))
21743 (move-beginning-of-line 2)))))
21746 ;;; Filling
21748 ;; We use our own fill-paragraph and auto-fill functions.
21750 ;; `org-fill-paragraph' relies on adaptive filling and context
21751 ;; checking. Appropriate `fill-prefix' is computed with
21752 ;; `org-adaptive-fill-function'.
21754 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21755 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21756 ;; `org-adaptive-fill-function' value. Internally,
21757 ;; `org-comment-line-break-function' breaks the line.
21759 ;; `org-setup-filling' installs filling and auto-filling related
21760 ;; variables during `org-mode' initialization.
21762 (defun org-setup-filling ()
21763 (interactive)
21764 ;; Prevent auto-fill from inserting unwanted new items.
21765 (when (boundp 'fill-nobreak-predicate)
21766 (org-set-local
21767 'fill-nobreak-predicate
21768 (org-uniquify
21769 (append fill-nobreak-predicate
21770 '(org-fill-paragraph-separate-nobreak-p
21771 org-fill-line-break-nobreak-p
21772 org-fill-paragraph-with-timestamp-nobreak-p)))))
21773 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21774 (org-set-local 'auto-fill-inhibit-regexp nil)
21775 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21776 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21777 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21779 (defvar org-element-paragraph-separate) ; org-element.el
21780 (defun org-fill-paragraph-separate-nobreak-p ()
21781 "Non-nil when a line break at point would insert a new item."
21782 (looking-at (substring org-element-paragraph-separate 1)))
21784 (defun org-fill-line-break-nobreak-p ()
21785 "Non-nil when a line break at point would create an Org line break."
21786 (save-excursion
21787 (skip-chars-backward "[ \t]")
21788 (skip-chars-backward "\\\\")
21789 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21791 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21792 "Non-nil when a line break at point would insert a new item."
21793 (and (org-at-timestamp-p t)
21794 (not (looking-at org-ts-regexp-both))))
21796 (declare-function message-in-body-p "message" ())
21797 (defvar orgtbl-line-start-regexp) ; From org-table.el
21798 (defun org-adaptive-fill-function ()
21799 "Compute a fill prefix for the current line.
21800 Return fill prefix, as a string, or nil if current line isn't
21801 meant to be filled."
21802 (let (prefix)
21803 (catch 'exit
21804 (when (derived-mode-p 'message-mode)
21805 (save-excursion
21806 (beginning-of-line)
21807 (cond ((or (not (message-in-body-p))
21808 (looking-at orgtbl-line-start-regexp))
21809 (throw 'exit nil))
21810 ((looking-at message-cite-prefix-regexp)
21811 (throw 'exit (match-string-no-properties 0)))
21812 ((looking-at org-outline-regexp)
21813 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21814 (org-with-wide-buffer
21815 (let* ((p (line-beginning-position))
21816 (element (save-excursion (beginning-of-line)
21817 (org-element-at-point)))
21818 (type (org-element-type element))
21819 (post-affiliated (org-element-property :post-affiliated element)))
21820 (unless (and post-affiliated (< p post-affiliated))
21821 (case type
21822 (comment (looking-at "[ \t]*# ?") (match-string 0))
21823 (footnote-definition "")
21824 ((item plain-list)
21825 (make-string (org-list-item-body-column
21826 (or post-affiliated
21827 (org-element-property :begin element)))
21828 ? ))
21829 (paragraph
21830 ;; Fill prefix is usually the same as the current line,
21831 ;; except if the paragraph is at the beginning of an item.
21832 (let ((parent (org-element-property :parent element)))
21833 (cond ((eq (org-element-type parent) 'item)
21834 (make-string (org-list-item-body-column
21835 (org-element-property :begin parent))
21836 ? ))
21837 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21838 (match-string 0))
21839 (t ""))))
21840 (comment-block
21841 ;; Only fill contents if P is within block boundaries.
21842 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21843 (forward-line)
21844 (point)))
21845 (cend (save-excursion
21846 (goto-char (org-element-property :end element))
21847 (skip-chars-backward " \r\t\n")
21848 (line-beginning-position))))
21849 (when (and (>= p cbeg) (< p cend))
21850 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21851 (match-string 0)
21852 "")))))))))))
21854 (declare-function message-goto-body "message" ())
21855 (defvar message-cite-prefix-regexp) ; From message.el
21856 (defun org-fill-paragraph (&optional justify)
21857 "Fill element at point, when applicable.
21859 This function only applies to comment blocks, comments, example
21860 blocks and paragraphs. Also, as a special case, re-align table
21861 when point is at one.
21863 If JUSTIFY is non-nil (interactively, with prefix argument),
21864 justify as well. If `sentence-end-double-space' is non-nil, then
21865 period followed by one space does not end a sentence, so don't
21866 break a line there. The variable `fill-column' controls the
21867 width for filling.
21869 For convenience, when point is at a plain list, an item or
21870 a footnote definition, try to fill the first paragraph within."
21871 (interactive)
21872 (if (and (derived-mode-p 'message-mode)
21873 (or (not (message-in-body-p))
21874 (save-excursion (move-beginning-of-line 1)
21875 (looking-at message-cite-prefix-regexp))))
21876 ;; First ensure filling is correct in message-mode.
21877 (let ((fill-paragraph-function
21878 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21879 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21880 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21881 (paragraph-separate
21882 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21883 (fill-paragraph nil))
21884 (with-syntax-table org-mode-transpose-word-syntax-table
21885 ;; Move to end of line in order to get the first paragraph
21886 ;; within a plain list or a footnote definition.
21887 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
21888 ;; First check if point is in a blank line at the beginning of
21889 ;; the buffer. In that case, ignore filling.
21890 (case (org-element-type element)
21891 ;; Use major mode filling function is src blocks.
21892 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21893 ;; Align Org tables, leave table.el tables as-is.
21894 (table-row (org-table-align) t)
21895 (table
21896 (when (eq (org-element-property :type element) 'org)
21897 (org-table-align))
21899 (paragraph
21900 ;; Paragraphs may contain `line-break' type objects.
21901 (let ((beg (max (point-min)
21902 (org-element-property :contents-begin element)))
21903 (end (min (point-max)
21904 (org-element-property :contents-end element))))
21905 ;; Do nothing if point is at an affiliated keyword.
21906 (if (< (line-end-position) beg) t
21907 (when (derived-mode-p 'message-mode)
21908 ;; In `message-mode', do not fill following citation
21909 ;; in current paragraph nor text before message body.
21910 (let ((body-start (save-excursion (message-goto-body))))
21911 (when body-start (setq beg (max body-start beg))))
21912 (when (save-excursion
21913 (re-search-forward
21914 (concat "^" message-cite-prefix-regexp) end t))
21915 (setq end (match-beginning 0))))
21916 ;; Fill paragraph, taking line breaks into account.
21917 ;; For that, slice the paragraph using line breaks as
21918 ;; separators, and fill the parts in reverse order to
21919 ;; avoid messing with markers.
21920 (save-excursion
21921 (goto-char end)
21922 (mapc
21923 (lambda (pos)
21924 (fill-region-as-paragraph pos (point) justify)
21925 (goto-char pos))
21926 ;; Find the list of ending positions for line breaks
21927 ;; in the current paragraph. Add paragraph
21928 ;; beginning to include first slice.
21929 (nreverse
21930 (cons beg
21931 (org-element-map
21932 (org-element--parse-objects
21933 beg end nil (org-element-restriction 'paragraph))
21934 'line-break
21935 (lambda (lb) (org-element-property :end lb)))))))
21936 t)))
21937 ;; Contents of `comment-block' type elements should be
21938 ;; filled as plain text, but only if point is within block
21939 ;; markers.
21940 (comment-block
21941 (let* ((case-fold-search t)
21942 (beg (save-excursion
21943 (goto-char (org-element-property :begin element))
21944 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21945 (forward-line)
21946 (point)))
21947 (end (save-excursion
21948 (goto-char (org-element-property :end element))
21949 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21950 (line-beginning-position))))
21951 (when (and (>= (point) beg) (< (point) end))
21952 (fill-region-as-paragraph
21953 (save-excursion
21954 (end-of-line)
21955 (re-search-backward "^[ \t]*$" beg 'move)
21956 (line-beginning-position))
21957 (save-excursion
21958 (beginning-of-line)
21959 (re-search-forward "^[ \t]*$" end 'move)
21960 (line-beginning-position))
21961 justify)))
21963 ;; Fill comments.
21964 (comment (fill-comment-paragraph justify))
21965 ;; Ignore every other element.
21966 (otherwise t))))))
21968 (defun org-auto-fill-function ()
21969 "Auto-fill function."
21970 ;; Check if auto-filling is meaningful.
21971 (let ((fc (current-fill-column)))
21972 (when (and fc (> (current-column) fc))
21973 (let* ((fill-prefix (org-adaptive-fill-function))
21974 ;; Enforce empty fill prefix, if required. Otherwise, it
21975 ;; will be computed again.
21976 (adaptive-fill-mode (not (equal fill-prefix ""))))
21977 (when fill-prefix (do-auto-fill))))))
21979 (defun org-comment-line-break-function (&optional soft)
21980 "Break line at point and indent, continuing comment if within one.
21981 The inserted newline is marked hard if variable
21982 `use-hard-newlines' is true, unless optional argument SOFT is
21983 non-nil."
21984 (if soft (insert-and-inherit ?\n) (newline 1))
21985 (save-excursion (forward-char -1) (delete-horizontal-space))
21986 (delete-horizontal-space)
21987 (indent-to-left-margin)
21988 (insert-before-markers-and-inherit fill-prefix))
21991 ;;; Comments
21993 ;; Org comments syntax is quite complex. It requires the entire line
21994 ;; to be just a comment. Also, even with the right syntax at the
21995 ;; beginning of line, some some elements (i.e. verse-block or
21996 ;; example-block) don't accept comments. Usual Emacs comment commands
21997 ;; cannot cope with those requirements. Therefore, Org replaces them.
21999 ;; Org still relies on `comment-dwim', but cannot trust
22000 ;; `comment-only-p'. So, `comment-region-function' and
22001 ;; `uncomment-region-function' both point
22002 ;; to`org-comment-or-uncomment-region'. Eventually,
22003 ;; `org-insert-comment' takes care of insertion of comments at the
22004 ;; beginning of line.
22006 ;; `org-setup-comments-handling' install comments related variables
22007 ;; during `org-mode' initialization.
22009 (defun org-setup-comments-handling ()
22010 (interactive)
22011 (org-set-local 'comment-use-syntax nil)
22012 (org-set-local 'comment-start "# ")
22013 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22014 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22015 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22016 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22018 (defun org-insert-comment ()
22019 "Insert an empty comment above current line.
22020 If the line is empty, insert comment at its beginning."
22021 (beginning-of-line)
22022 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22023 (org-indent-line)
22024 (insert "# "))
22026 (defvar comment-empty-lines) ; From newcomment.el.
22027 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22028 "Comment or uncomment each non-blank line in the region.
22029 Uncomment each non-blank line between BEG and END if it only
22030 contains commented lines. Otherwise, comment them."
22031 (save-restriction
22032 ;; Restrict region
22033 (narrow-to-region (save-excursion (goto-char beg)
22034 (skip-chars-forward " \r\t\n" end)
22035 (line-beginning-position))
22036 (save-excursion (goto-char end)
22037 (skip-chars-backward " \r\t\n" beg)
22038 (line-end-position)))
22039 (let ((uncommentp
22040 ;; UNCOMMENTP is non-nil when every non blank line between
22041 ;; BEG and END is a comment.
22042 (save-excursion
22043 (goto-char (point-min))
22044 (while (and (not (eobp))
22045 (let ((element (org-element-at-point)))
22046 (and (eq (org-element-type element) 'comment)
22047 (goto-char (min (point-max)
22048 (org-element-property
22049 :end element)))))))
22050 (eobp))))
22051 (if uncommentp
22052 ;; Only blank lines and comments in region: uncomment it.
22053 (save-excursion
22054 (goto-char (point-min))
22055 (while (not (eobp))
22056 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22057 (replace-match "" nil nil nil 1))
22058 (forward-line)))
22059 ;; Comment each line in region.
22060 (let ((min-indent (point-max)))
22061 ;; First find the minimum indentation across all lines.
22062 (save-excursion
22063 (goto-char (point-min))
22064 (while (and (not (eobp)) (not (zerop min-indent)))
22065 (unless (looking-at "[ \t]*$")
22066 (setq min-indent (min min-indent (current-indentation))))
22067 (forward-line)))
22068 ;; Then loop over all lines.
22069 (save-excursion
22070 (goto-char (point-min))
22071 (while (not (eobp))
22072 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22073 ;; Don't get fooled by invisible text (e.g. link path)
22074 ;; when moving to column MIN-INDENT.
22075 (let ((buffer-invisibility-spec nil))
22076 (org-move-to-column min-indent t))
22077 (insert comment-start))
22078 (forward-line))))))))
22081 ;;; Planning
22083 ;; This section contains tools to operate on timestamp objects, as
22084 ;; returned by, e.g. `org-element-context'.
22086 (defun org-timestamp-has-time-p (timestamp)
22087 "Non-nil when TIMESTAMP has a time specified."
22088 (org-element-property :hour-start timestamp))
22090 (defun org-timestamp-format (timestamp format &optional end utc)
22091 "Format a TIMESTAMP element into a string.
22093 FORMAT is a format specifier to be passed to
22094 `format-time-string'.
22096 When optional argument END is non-nil, use end of date-range or
22097 time-range, if possible.
22099 When optional argument UTC is non-nil, time will be expressed as
22100 Universal Time."
22101 (format-time-string
22102 format
22103 (apply 'encode-time
22104 (cons 0
22105 (mapcar
22106 (lambda (prop) (or (org-element-property prop timestamp) 0))
22107 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22108 '(:minute-start :hour-start :day-start :month-start
22109 :year-start)))))
22110 utc))
22112 (defun org-timestamp-split-range (timestamp &optional end)
22113 "Extract a timestamp object from a date or time range.
22115 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22116 the end of the range. Otherwise, extract its start.
22118 Return a new timestamp object sharing the same parent as
22119 TIMESTAMP."
22120 (let ((type (org-element-property :type timestamp)))
22121 (if (memq type '(active inactive diary)) timestamp
22122 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22123 ;; Set new type.
22124 (org-element-put-property
22125 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22126 ;; Copy start properties over end properties if END is
22127 ;; non-nil. Otherwise, copy end properties over `start' ones.
22128 (let ((p-alist '((:minute-start . :minute-end)
22129 (:hour-start . :hour-end)
22130 (:day-start . :day-end)
22131 (:month-start . :month-end)
22132 (:year-start . :year-end))))
22133 (dolist (p-cell p-alist)
22134 (org-element-put-property
22135 split-ts
22136 (funcall (if end 'car 'cdr) p-cell)
22137 (org-element-property
22138 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22139 ;; Eventually refresh `:raw-value'.
22140 (org-element-put-property split-ts :raw-value nil)
22141 (org-element-put-property
22142 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22144 (defun org-timestamp-translate (timestamp &optional boundary)
22145 "Apply `org-translate-time' on a TIMESTAMP object.
22146 When optional argument BOUNDARY is non-nil, it is either the
22147 symbol `start' or `end'. In this case, only translate the
22148 starting or ending part of TIMESTAMP if it is a date or time
22149 range. Otherwise, translate both parts."
22150 (if (and (not boundary)
22151 (memq (org-element-property :type timestamp)
22152 '(active-range inactive-range)))
22153 (concat
22154 (org-translate-time
22155 (org-element-property :raw-value
22156 (org-timestamp-split-range timestamp)))
22157 "--"
22158 (org-translate-time
22159 (org-element-property :raw-value
22160 (org-timestamp-split-range timestamp t))))
22161 (org-translate-time
22162 (org-element-property
22163 :raw-value
22164 (if (not boundary) timestamp
22165 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22169 ;;; Other stuff.
22171 (defun org-toggle-fixed-width-section (arg)
22172 "Toggle the fixed-width export.
22173 If there is no active region, the QUOTE keyword at the current headline is
22174 inserted or removed. When present, it causes the text between this headline
22175 and the next to be exported as fixed-width text, and unmodified.
22176 If there is an active region, this command adds or removes a colon as the
22177 first character of this line. If the first character of a line is a colon,
22178 this line is also exported in fixed-width font."
22179 (interactive "P")
22180 (let* ((cc 0)
22181 (regionp (org-region-active-p))
22182 (beg (if regionp (region-beginning) (point)))
22183 (end (if regionp (region-end)))
22184 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22185 (case-fold-search nil)
22186 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22187 off)
22188 (if regionp
22189 (save-excursion
22190 (goto-char beg)
22191 (setq cc (current-column))
22192 (beginning-of-line 1)
22193 (setq off (looking-at re))
22194 (while (> nlines 0)
22195 (setq nlines (1- nlines))
22196 (beginning-of-line 1)
22197 (cond
22198 (arg
22199 (org-move-to-column cc t)
22200 (insert ": \n")
22201 (forward-line -1))
22202 ((and off (looking-at re))
22203 (replace-match "" t t nil 1))
22204 ((not off) (org-move-to-column cc t) (insert ": ")))
22205 (forward-line 1)))
22206 (save-excursion
22207 (org-back-to-heading)
22208 (cond
22209 ((looking-at (format org-heading-keyword-regexp-format
22210 org-quote-string))
22211 (goto-char (match-end 1))
22212 (looking-at (concat " +" org-quote-string))
22213 (replace-match "" t t)
22214 (when (eolp) (insert " ")))
22215 ((looking-at org-outline-regexp)
22216 (goto-char (match-end 0))
22217 (insert org-quote-string " ")))))))
22219 (defun org-reftex-citation ()
22220 "Use reftex-citation to insert a citation into the buffer.
22221 This looks for a line like
22223 #+BIBLIOGRAPHY: foo plain option:-d
22225 and derives from it that foo.bib is the bibliography file relevant
22226 for this document. It then installs the necessary environment for RefTeX
22227 to work in this buffer and calls `reftex-citation' to insert a citation
22228 into the buffer.
22230 Export of such citations to both LaTeX and HTML is handled by the contributed
22231 package org-exp-bibtex by Taru Karttunen."
22232 (interactive)
22233 (let ((reftex-docstruct-symbol 'rds)
22234 (reftex-cite-format "\\cite{%l}")
22235 rds bib)
22236 (save-excursion
22237 (save-restriction
22238 (widen)
22239 (let ((case-fold-search t)
22240 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22241 (if (not (save-excursion
22242 (or (re-search-forward re nil t)
22243 (re-search-backward re nil t))))
22244 (error "No bibliography defined in file")
22245 (setq bib (concat (match-string 1) ".bib")
22246 rds (list (list 'bib bib)))))))
22247 (call-interactively 'reftex-citation)))
22249 ;;;; Functions extending outline functionality
22251 (defun org-beginning-of-line (&optional arg)
22252 "Go to the beginning of the current line. If that is invisible, continue
22253 to a visible line beginning. This makes the function of C-a more intuitive.
22254 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22255 first attempt, and only move to after the tags when the cursor is already
22256 beyond the end of the headline."
22257 (interactive "P")
22258 (let ((pos (point))
22259 (special (if (consp org-special-ctrl-a/e)
22260 (car org-special-ctrl-a/e)
22261 org-special-ctrl-a/e))
22262 refpos)
22263 (if (org-bound-and-true-p visual-line-mode)
22264 (beginning-of-visual-line 1)
22265 (beginning-of-line 1))
22266 (if (and arg (fboundp 'move-beginning-of-line))
22267 (call-interactively 'move-beginning-of-line)
22268 (if (bobp)
22270 (backward-char 1)
22271 (if (org-truely-invisible-p)
22272 (while (and (not (bobp)) (org-truely-invisible-p))
22273 (backward-char 1)
22274 (beginning-of-line 1))
22275 (forward-char 1))))
22276 (when special
22277 (cond
22278 ((and (looking-at org-complex-heading-regexp)
22279 (= (char-after (match-end 1)) ?\ ))
22280 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22281 (point-at-eol)))
22282 (goto-char
22283 (if (eq special t)
22284 (cond ((> pos refpos) refpos)
22285 ((= pos (point)) refpos)
22286 (t (point)))
22287 (cond ((> pos (point)) (point))
22288 ((not (eq last-command this-command)) (point))
22289 (t refpos)))))
22290 ((org-at-item-p)
22291 ;; Being at an item and not looking at an the item means point
22292 ;; was previously moved to beginning of a visual line, which
22293 ;; doesn't contain the item. Therefore, do nothing special,
22294 ;; just stay here.
22295 (when (looking-at org-list-full-item-re)
22296 ;; Set special position at first white space character after
22297 ;; bullet, and check-box, if any.
22298 (let ((after-bullet
22299 (let ((box (match-end 3)))
22300 (if (not box) (match-end 1)
22301 (let ((after (char-after box)))
22302 (if (and after (= after ? )) (1+ box) box))))))
22303 ;; Special case: Move point to special position when
22304 ;; currently after it or at beginning of line.
22305 (if (eq special t)
22306 (when (or (> pos after-bullet) (= (point) pos))
22307 (goto-char after-bullet))
22308 ;; Reversed case: Move point to special position when
22309 ;; point was already at beginning of line and command is
22310 ;; repeated.
22311 (when (and (= (point) pos) (eq last-command this-command))
22312 (goto-char after-bullet))))))))
22313 (org-no-warnings
22314 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22316 (defun org-end-of-line (&optional arg)
22317 "Go to the end of the line.
22318 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22319 tags on the first attempt, and only move to after the tags when
22320 the cursor is already beyond the end of the headline."
22321 (interactive "P")
22322 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22323 org-special-ctrl-a/e))
22324 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22325 'end-of-visual-line)
22326 ((fboundp 'move-end-of-line) 'move-end-of-line)
22327 (t 'end-of-line))))
22328 (if (or (not special) arg) (call-interactively move-fun)
22329 (let* ((element (save-excursion (beginning-of-line)
22330 (org-element-at-point)))
22331 (type (org-element-type element)))
22332 (cond
22333 ((memq type '(headline inlinetask))
22334 (let ((pos (point)))
22335 (beginning-of-line 1)
22336 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22337 (if (eq special t)
22338 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22339 (goto-char (match-beginning 1))
22340 (goto-char (match-end 0)))
22341 (if (or (< pos (match-end 0))
22342 (not (eq this-command last-command)))
22343 (goto-char (match-end 0))
22344 (goto-char (match-beginning 1))))
22345 (call-interactively move-fun))))
22346 ((org-element-property :hiddenp element)
22347 ;; If element is hidden, `move-end-of-line' would put point
22348 ;; after it. Use `end-of-line' to stay on current line.
22349 (call-interactively 'end-of-line))
22350 (t (call-interactively move-fun)))))
22351 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22353 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22354 (define-key org-mode-map "\C-e" 'org-end-of-line)
22356 (defun org-backward-sentence (&optional arg)
22357 "Go to beginning of sentence, or beginning of table field.
22358 This will call `backward-sentence' or `org-table-beginning-of-field',
22359 depending on context."
22360 (interactive "P")
22361 (cond
22362 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22363 (t (call-interactively 'backward-sentence))))
22365 (defun org-forward-sentence (&optional arg)
22366 "Go to end of sentence, or end of table field.
22367 This will call `forward-sentence' or `org-table-end-of-field',
22368 depending on context."
22369 (interactive "P")
22370 (cond
22371 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22372 (t (call-interactively 'forward-sentence))))
22374 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22375 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22377 (defun org-kill-line (&optional arg)
22378 "Kill line, to tags or end of line."
22379 (interactive "P")
22380 (cond
22381 ((or (not org-special-ctrl-k)
22382 (bolp)
22383 (not (org-at-heading-p)))
22384 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22385 org-ctrl-k-protect-subtree)
22386 (if (or (eq org-ctrl-k-protect-subtree 'error)
22387 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22388 (error "C-k aborted - would kill hidden subtree")))
22389 (call-interactively
22390 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22391 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22392 (kill-region (point) (match-beginning 1))
22393 (org-set-tags nil t))
22394 (t (kill-region (point) (point-at-eol)))))
22396 (define-key org-mode-map "\C-k" 'org-kill-line)
22398 (defun org-yank (&optional arg)
22399 "Yank. If the kill is a subtree, treat it specially.
22400 This command will look at the current kill and check if is a single
22401 subtree, or a series of subtrees[1]. If it passes the test, and if the
22402 cursor is at the beginning of a line or after the stars of a currently
22403 empty headline, then the yank is handled specially. How exactly depends
22404 on the value of the following variables, both set by default.
22406 org-yank-folded-subtrees
22407 When set, the subtree(s) will be folded after insertion, but only
22408 if doing so would now swallow text after the yanked text.
22410 org-yank-adjusted-subtrees
22411 When set, the subtree will be promoted or demoted in order to
22412 fit into the local outline tree structure, which means that the level
22413 will be adjusted so that it becomes the smaller one of the two
22414 *visible* surrounding headings.
22416 Any prefix to this command will cause `yank' to be called directly with
22417 no special treatment. In particular, a simple \\[universal-argument] prefix \
22418 will just
22419 plainly yank the text as it is.
22421 \[1] The test checks if the first non-white line is a heading
22422 and if there are no other headings with fewer stars."
22423 (interactive "P")
22424 (org-yank-generic 'yank arg))
22426 (defun org-yank-generic (command arg)
22427 "Perform some yank-like command.
22429 This function implements the behavior described in the `org-yank'
22430 documentation. However, it has been generalized to work for any
22431 interactive command with similar behavior."
22433 ;; pretend to be command COMMAND
22434 (setq this-command command)
22436 (if arg
22437 (call-interactively command)
22439 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22440 (and (org-kill-is-subtree-p)
22441 (or (bolp)
22442 (and (looking-at "[ \t]*$")
22443 (string-match
22444 "\\`\\*+\\'"
22445 (buffer-substring (point-at-bol) (point)))))))
22446 swallowp)
22447 (cond
22448 ((and subtreep org-yank-folded-subtrees)
22449 (let ((beg (point))
22450 end)
22451 (if (and subtreep org-yank-adjusted-subtrees)
22452 (org-paste-subtree nil nil 'for-yank)
22453 (call-interactively command))
22455 (setq end (point))
22456 (goto-char beg)
22457 (when (and (bolp) subtreep
22458 (not (setq swallowp
22459 (org-yank-folding-would-swallow-text beg end))))
22460 (org-with-limited-levels
22461 (or (looking-at org-outline-regexp)
22462 (re-search-forward org-outline-regexp-bol end t))
22463 (while (and (< (point) end) (looking-at org-outline-regexp))
22464 (hide-subtree)
22465 (org-cycle-show-empty-lines 'folded)
22466 (condition-case nil
22467 (outline-forward-same-level 1)
22468 (error (goto-char end))))))
22469 (when swallowp
22470 (message
22471 "Inserted text not folded because that would swallow text"))
22473 (goto-char end)
22474 (skip-chars-forward " \t\n\r")
22475 (beginning-of-line 1)
22476 (push-mark beg 'nomsg)))
22477 ((and subtreep org-yank-adjusted-subtrees)
22478 (let ((beg (point-at-bol)))
22479 (org-paste-subtree nil nil 'for-yank)
22480 (push-mark beg 'nomsg)))
22482 (call-interactively command))))))
22484 (defun org-yank-folding-would-swallow-text (beg end)
22485 "Would hide-subtree at BEG swallow any text after END?"
22486 (let (level)
22487 (org-with-limited-levels
22488 (save-excursion
22489 (goto-char beg)
22490 (when (or (looking-at org-outline-regexp)
22491 (re-search-forward org-outline-regexp-bol end t))
22492 (setq level (org-outline-level)))
22493 (goto-char end)
22494 (skip-chars-forward " \t\r\n\v\f")
22495 (if (or (eobp)
22496 (and (bolp) (looking-at org-outline-regexp)
22497 (<= (org-outline-level) level)))
22498 nil ; Nothing would be swallowed
22499 t))))) ; something would swallow
22501 (define-key org-mode-map "\C-y" 'org-yank)
22503 (defun org-truely-invisible-p ()
22504 "Check if point is at a character currently not visible.
22505 This version does not only check the character property, but also
22506 `visible-mode'."
22507 ;; Early versions of noutline don't have `outline-invisible-p'.
22508 (if (org-bound-and-true-p visible-mode)
22510 (outline-invisible-p)))
22512 (defun org-invisible-p2 ()
22513 "Check if point is at a character currently not visible."
22514 (save-excursion
22515 (if (and (eolp) (not (bobp))) (backward-char 1))
22516 ;; Early versions of noutline don't have `outline-invisible-p'.
22517 (outline-invisible-p)))
22519 (defun org-back-to-heading (&optional invisible-ok)
22520 "Call `outline-back-to-heading', but provide a better error message."
22521 (condition-case nil
22522 (outline-back-to-heading invisible-ok)
22523 (error (error "Before first headline at position %d in buffer %s"
22524 (point) (current-buffer)))))
22526 (defun org-before-first-heading-p ()
22527 "Before first heading?"
22528 (save-excursion
22529 (end-of-line)
22530 (null (re-search-backward org-outline-regexp-bol nil t))))
22532 (defun org-at-heading-p (&optional ignored)
22533 (outline-on-heading-p t))
22534 ;; Compatibility alias with Org versions < 7.8.03
22535 (defalias 'org-on-heading-p 'org-at-heading-p)
22537 (defun org-at-comment-p nil
22538 "Is cursor in a line starting with a # character?"
22539 (save-excursion
22540 (beginning-of-line)
22541 (looking-at "^#")))
22543 (defun org-at-drawer-p nil
22544 "Is cursor at a drawer keyword?"
22545 (save-excursion
22546 (move-beginning-of-line 1)
22547 (looking-at org-drawer-regexp)))
22549 (defun org-at-block-p nil
22550 "Is cursor at a block keyword?"
22551 (save-excursion
22552 (move-beginning-of-line 1)
22553 (looking-at org-block-regexp)))
22555 (defun org-point-at-end-of-empty-headline ()
22556 "If point is at the end of an empty headline, return t, else nil.
22557 If the heading only contains a TODO keyword, it is still still considered
22558 empty."
22559 (and (looking-at "[ \t]*$")
22560 (when org-todo-line-regexp
22561 (save-excursion
22562 (beginning-of-line 1)
22563 (let ((case-fold-search nil))
22564 (looking-at org-todo-line-regexp)
22565 (string= (match-string 3) ""))))))
22567 (defun org-at-heading-or-item-p ()
22568 (or (org-at-heading-p) (org-at-item-p)))
22570 (defun org-at-target-p ()
22571 (or (org-in-regexp org-radio-target-regexp)
22572 (org-in-regexp org-target-regexp)))
22573 ;; Compatibility alias with Org versions < 7.8.03
22574 (defalias 'org-on-target-p 'org-at-target-p)
22576 (defun org-up-heading-all (arg)
22577 "Move to the heading line of which the present line is a subheading.
22578 This function considers both visible and invisible heading lines.
22579 With argument, move up ARG levels."
22580 (if (fboundp 'outline-up-heading-all)
22581 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22582 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22584 (defun org-up-heading-safe ()
22585 "Move to the heading line of which the present line is a subheading.
22586 This version will not throw an error. It will return the level of the
22587 headline found, or nil if no higher level is found.
22589 Also, this function will be a lot faster than `outline-up-heading',
22590 because it relies on stars being the outline starters. This can really
22591 make a significant difference in outlines with very many siblings."
22592 (let (start-level re)
22593 (org-back-to-heading t)
22594 (setq start-level (funcall outline-level))
22595 (if (equal start-level 1)
22597 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22598 (if (re-search-backward re nil t)
22599 (funcall outline-level)))))
22601 (defun org-first-sibling-p ()
22602 "Is this heading the first child of its parents?"
22603 (interactive)
22604 (let ((re org-outline-regexp-bol)
22605 level l)
22606 (unless (org-at-heading-p t)
22607 (error "Not at a heading"))
22608 (setq level (funcall outline-level))
22609 (save-excursion
22610 (if (not (re-search-backward re nil t))
22612 (setq l (funcall outline-level))
22613 (< l level)))))
22615 (defun org-goto-sibling (&optional previous)
22616 "Goto the next sibling, even if it is invisible.
22617 When PREVIOUS is set, go to the previous sibling instead. Returns t
22618 when a sibling was found. When none is found, return nil and don't
22619 move point."
22620 (let ((fun (if previous 're-search-backward 're-search-forward))
22621 (pos (point))
22622 (re org-outline-regexp-bol)
22623 level l)
22624 (when (condition-case nil (org-back-to-heading t) (error nil))
22625 (setq level (funcall outline-level))
22626 (catch 'exit
22627 (or previous (forward-char 1))
22628 (while (funcall fun re nil t)
22629 (setq l (funcall outline-level))
22630 (when (< l level) (goto-char pos) (throw 'exit nil))
22631 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22632 (goto-char pos)
22633 nil))))
22635 (defun org-show-siblings ()
22636 "Show all siblings of the current headline."
22637 (save-excursion
22638 (while (org-goto-sibling) (org-flag-heading nil)))
22639 (save-excursion
22640 (while (org-goto-sibling 'previous)
22641 (org-flag-heading nil))))
22643 (defun org-goto-first-child ()
22644 "Goto the first child, even if it is invisible.
22645 Return t when a child was found. Otherwise don't move point and
22646 return nil."
22647 (let (level (pos (point)) (re org-outline-regexp-bol))
22648 (when (condition-case nil (org-back-to-heading t) (error nil))
22649 (setq level (outline-level))
22650 (forward-char 1)
22651 (if (and (re-search-forward re nil t) (> (outline-level) level))
22652 (progn (goto-char (match-beginning 0)) t)
22653 (goto-char pos) nil))))
22655 (defun org-show-hidden-entry ()
22656 "Show an entry where even the heading is hidden."
22657 (save-excursion
22658 (org-show-entry)))
22660 (defun org-flag-heading (flag &optional entry)
22661 "Flag the current heading. FLAG non-nil means make invisible.
22662 When ENTRY is non-nil, show the entire entry."
22663 (save-excursion
22664 (org-back-to-heading t)
22665 ;; Check if we should show the entire entry
22666 (if entry
22667 (progn
22668 (org-show-entry)
22669 (save-excursion
22670 (and (outline-next-heading)
22671 (org-flag-heading nil))))
22672 (outline-flag-region (max (point-min) (1- (point)))
22673 (save-excursion (outline-end-of-heading) (point))
22674 flag))))
22676 (defun org-get-next-sibling ()
22677 "Move to next heading of the same level, and return point.
22678 If there is no such heading, return nil.
22679 This is like outline-next-sibling, but invisible headings are ok."
22680 (let ((level (funcall outline-level)))
22681 (outline-next-heading)
22682 (while (and (not (eobp)) (> (funcall outline-level) level))
22683 (outline-next-heading))
22684 (if (or (eobp) (< (funcall outline-level) level))
22686 (point))))
22688 (defun org-get-last-sibling ()
22689 "Move to previous heading of the same level, and return point.
22690 If there is no such heading, return nil."
22691 (let ((opoint (point))
22692 (level (funcall outline-level)))
22693 (outline-previous-heading)
22694 (when (and (/= (point) opoint) (outline-on-heading-p t))
22695 (while (and (> (funcall outline-level) level)
22696 (not (bobp)))
22697 (outline-previous-heading))
22698 (if (< (funcall outline-level) level)
22700 (point)))))
22702 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22703 "Goto to the end of a subtree."
22704 ;; This contains an exact copy of the original function, but it uses
22705 ;; `org-back-to-heading', to make it work also in invisible
22706 ;; trees. And is uses an invisible-ok argument.
22707 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22708 ;; Furthermore, when used inside Org, finding the end of a large subtree
22709 ;; with many children and grandchildren etc, this can be much faster
22710 ;; than the outline version.
22711 (org-back-to-heading invisible-ok)
22712 (let ((first t)
22713 (level (funcall outline-level)))
22714 (if (and (derived-mode-p 'org-mode) (< level 1000))
22715 ;; A true heading (not a plain list item), in Org-mode
22716 ;; This means we can easily find the end by looking
22717 ;; only for the right number of stars. Using a regexp to do
22718 ;; this is so much faster than using a Lisp loop.
22719 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22720 (forward-char 1)
22721 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22722 ;; something else, do it the slow way
22723 (while (and (not (eobp))
22724 (or first (> (funcall outline-level) level)))
22725 (setq first nil)
22726 (outline-next-heading)))
22727 (unless to-heading
22728 (if (memq (preceding-char) '(?\n ?\^M))
22729 (progn
22730 ;; Go to end of line before heading
22731 (forward-char -1)
22732 (if (memq (preceding-char) '(?\n ?\^M))
22733 ;; leave blank line before heading
22734 (forward-char -1))))))
22735 (point))
22737 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22738 "Use Org version in org-mode, for dramatic speed-up."
22739 (if (derived-mode-p 'org-mode)
22740 (progn
22741 (org-end-of-subtree nil t)
22742 (unless (eobp) (backward-char 1)))
22743 ad-do-it))
22745 (defun org-end-of-meta-data-and-drawers ()
22746 "Jump to the first text after meta data and drawers in the current entry.
22747 This will move over empty lines, lines with planning time stamps,
22748 clocking lines, and drawers."
22749 (org-back-to-heading t)
22750 (let ((end (save-excursion (outline-next-heading) (point)))
22751 (re (concat "\\(" org-drawer-regexp "\\)"
22752 "\\|" "[ \t]*" org-keyword-time-regexp)))
22753 (forward-line 1)
22754 (while (re-search-forward re end t)
22755 (if (not (match-end 1))
22756 ;; empty or planning line
22757 (forward-line 1)
22758 ;; a drawer, find the end
22759 (re-search-forward "^[ \t]*:END:" end 'move)
22760 (forward-line 1)))
22761 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22762 (point)))
22764 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22765 "Move forward to the ARG'th subheading at same level as this one.
22766 Stop at the first and last subheadings of a superior heading.
22767 Normally this only looks at visible headings, but when INVISIBLE-OK is
22768 non-nil it will also look at invisible ones."
22769 (interactive "p")
22770 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22771 (if (and arg (< arg 0))
22772 (goto-char (point-min))
22773 (outline-next-heading))
22774 (org-at-heading-p)
22775 (let ((level (- (match-end 0) (match-beginning 0) 1))
22776 (f (if (and arg (< arg 0))
22777 're-search-backward
22778 're-search-forward))
22779 (count (if arg (abs arg) 1))
22780 (result (point)))
22781 (forward-char (if (and arg (< arg 0)) -1 1))
22782 (while (and (> count 0)
22783 (funcall f org-outline-regexp-bol nil 'move))
22784 (let ((l (- (match-end 0) (match-beginning 0) 1)))
22785 (cond ((< l level) (setq count 0))
22786 ((and (= l level)
22787 (or invisible-ok
22788 (progn
22789 (goto-char (line-beginning-position))
22790 (not (outline-invisible-p)))))
22791 (setq count (1- count))
22792 (when (eq l level)
22793 (setq result (point)))))))
22794 (goto-char result))
22795 (beginning-of-line 1)))
22797 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22798 "Move backward to the ARG'th subheading at same level as this one.
22799 Stop at the first and last subheadings of a superior heading."
22800 (interactive "p")
22801 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
22803 (defun org-next-block (arg &optional backward block-regexp)
22804 "Jump to the next block.
22805 With a prefix argument ARG, jump forward ARG many source blocks.
22806 When BACKWARD is non-nil, jump to the previous block.
22807 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22808 (interactive "p")
22809 (let ((re (or block-regexp org-block-regexp))
22810 (re-search-fn (or (and backward 're-search-backward)
22811 're-search-forward)))
22812 (if (looking-at re) (forward-char 1))
22813 (condition-case nil
22814 (funcall re-search-fn re nil nil arg)
22815 (error (error "No %s code blocks" (if backward "previous" "further" ))))
22816 (goto-char (match-beginning 0)) (org-show-context)))
22818 (defun org-previous-block (arg &optional block-regexp)
22819 "Jump to the previous block.
22820 With a prefix argument ARG, jump backward ARG many source blocks.
22821 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22822 (interactive "p")
22823 (org-next-block arg t block-regexp))
22825 (defun org-forward-element ()
22826 "Move forward by one element.
22827 Move to the next element at the same level, when possible."
22828 (interactive)
22829 (cond ((eobp) (user-error "Cannot move further down"))
22830 ((org-with-limited-levels (org-at-heading-p))
22831 (let ((origin (point)))
22832 (goto-char (org-end-of-subtree nil t))
22833 (unless (org-with-limited-levels (org-at-heading-p))
22834 (goto-char origin)
22835 (user-error "Cannot move further down"))))
22837 (let* ((elem (org-element-at-point))
22838 (end (org-element-property :end elem))
22839 (parent (org-element-property :parent elem)))
22840 (if (and parent (= (org-element-property :contents-end parent) end))
22841 (goto-char (org-element-property :end parent))
22842 (goto-char end))))))
22844 (defun org-backward-element ()
22845 "Move backward by one element.
22846 Move to the previous element at the same level, when possible."
22847 (interactive)
22848 (cond ((bobp) (user-error "Cannot move further up"))
22849 ((org-with-limited-levels (org-at-heading-p))
22850 ;; At a headline, move to the previous one, if any, or stay
22851 ;; here.
22852 (let ((origin (point)))
22853 (org-with-limited-levels (org-backward-heading-same-level 1))
22854 ;; When current headline has no sibling above, move to its
22855 ;; parent.
22856 (when (= (point) origin)
22857 (or (org-with-limited-levels (org-up-heading-safe))
22858 (progn (goto-char origin)
22859 (user-error "Cannot move further up"))))))
22861 (let* ((trail (org-element-at-point 'keep-trail))
22862 (elem (car trail))
22863 (prev-elem (nth 1 trail))
22864 (beg (org-element-property :begin elem)))
22865 (cond
22866 ;; Move to beginning of current element if point isn't
22867 ;; there already.
22868 ((/= (point) beg) (goto-char beg))
22869 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22870 ((org-before-first-heading-p) (goto-char (point-min)))
22871 (t (org-back-to-heading)))))))
22873 (defun org-up-element ()
22874 "Move to upper element."
22875 (interactive)
22876 (if (org-with-limited-levels (org-at-heading-p))
22877 (unless (org-up-heading-safe) (error "No surrounding element"))
22878 (let* ((elem (org-element-at-point))
22879 (parent (org-element-property :parent elem)))
22880 (if parent (goto-char (org-element-property :begin parent))
22881 (if (org-with-limited-levels (org-before-first-heading-p))
22882 (error "No surrounding element")
22883 (org-with-limited-levels (org-back-to-heading)))))))
22885 (defvar org-element-greater-elements)
22886 (defun org-down-element ()
22887 "Move to inner element."
22888 (interactive)
22889 (let ((element (org-element-at-point)))
22890 (cond
22891 ((memq (org-element-type element) '(plain-list table))
22892 (goto-char (org-element-property :contents-begin element))
22893 (forward-char))
22894 ((memq (org-element-type element) org-element-greater-elements)
22895 ;; If contents are hidden, first disclose them.
22896 (when (org-element-property :hiddenp element) (org-cycle))
22897 (goto-char (or (org-element-property :contents-begin element)
22898 (error "No content for this element"))))
22899 (t (error "No inner element")))))
22901 (defun org-drag-element-backward ()
22902 "Move backward element at point."
22903 (interactive)
22904 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22905 (let* ((trail (org-element-at-point 'keep-trail))
22906 (elem (car trail))
22907 (prev-elem (nth 1 trail)))
22908 ;; Error out if no previous element or previous element is
22909 ;; a parent of the current one.
22910 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22911 (error "Cannot drag element backward")
22912 (let ((pos (point)))
22913 (org-element-swap-A-B prev-elem elem)
22914 (goto-char (+ (org-element-property :begin prev-elem)
22915 (- pos (org-element-property :begin elem)))))))))
22917 (defun org-drag-element-forward ()
22918 "Move forward element at point."
22919 (interactive)
22920 (let* ((pos (point))
22921 (elem (org-element-at-point)))
22922 (when (= (point-max) (org-element-property :end elem))
22923 (error "Cannot drag element forward"))
22924 (goto-char (org-element-property :end elem))
22925 (let ((next-elem (org-element-at-point)))
22926 (when (or (org-element-nested-p elem next-elem)
22927 (and (eq (org-element-type next-elem) 'headline)
22928 (not (eq (org-element-type elem) 'headline))))
22929 (goto-char pos)
22930 (error "Cannot drag element forward"))
22931 ;; Compute new position of point: it's shifted by NEXT-ELEM
22932 ;; body's length (without final blanks) and by the length of
22933 ;; blanks between ELEM and NEXT-ELEM.
22934 (let ((size-next (- (save-excursion
22935 (goto-char (org-element-property :end next-elem))
22936 (skip-chars-backward " \r\t\n")
22937 (forward-line)
22938 ;; Small correction if buffer doesn't end
22939 ;; with a newline character.
22940 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22941 (org-element-property :begin next-elem)))
22942 (size-blank (- (org-element-property :end elem)
22943 (save-excursion
22944 (goto-char (org-element-property :end elem))
22945 (skip-chars-backward " \r\t\n")
22946 (forward-line)
22947 (point)))))
22948 (org-element-swap-A-B elem next-elem)
22949 (goto-char (+ pos size-next size-blank))))))
22951 (defun org-drag-line-forward (arg)
22952 "Drag the line at point ARG lines forward."
22953 (interactive "p")
22954 (dotimes (n (abs arg))
22955 (let ((c (current-column)))
22956 (if (< 0 arg)
22957 (progn
22958 (beginning-of-line 2)
22959 (transpose-lines 1)
22960 (beginning-of-line 0))
22961 (transpose-lines 1)
22962 (beginning-of-line -1))
22963 (org-move-to-column c))))
22965 (defun org-drag-line-backward (arg)
22966 "Drag the line at point ARG lines backward."
22967 (interactive "p")
22968 (org-drag-line-forward (- arg)))
22970 (defun org-mark-element ()
22971 "Put point at beginning of this element, mark at end.
22973 Interactively, if this command is repeated or (in Transient Mark
22974 mode) if the mark is active, it marks the next element after the
22975 ones already marked."
22976 (interactive)
22977 (let (deactivate-mark)
22978 (if (and (org-called-interactively-p 'any)
22979 (or (and (eq last-command this-command) (mark t))
22980 (and transient-mark-mode mark-active)))
22981 (set-mark
22982 (save-excursion
22983 (goto-char (mark))
22984 (goto-char (org-element-property :end (org-element-at-point)))))
22985 (let ((element (org-element-at-point)))
22986 (end-of-line)
22987 (push-mark (org-element-property :end element) t t)
22988 (goto-char (org-element-property :begin element))))))
22990 (defun org-narrow-to-element ()
22991 "Narrow buffer to current element."
22992 (interactive)
22993 (let ((elem (org-element-at-point)))
22994 (cond
22995 ((eq (car elem) 'headline)
22996 (narrow-to-region
22997 (org-element-property :begin elem)
22998 (org-element-property :end elem)))
22999 ((memq (car elem) org-element-greater-elements)
23000 (narrow-to-region
23001 (org-element-property :contents-begin elem)
23002 (org-element-property :contents-end elem)))
23004 (narrow-to-region
23005 (org-element-property :begin elem)
23006 (org-element-property :end elem))))))
23008 (defun org-transpose-element ()
23009 "Transpose current and previous elements, keeping blank lines between.
23010 Point is moved after both elements."
23011 (interactive)
23012 (org-skip-whitespace)
23013 (let ((end (org-element-property :end (org-element-at-point))))
23014 (org-drag-element-backward)
23015 (goto-char end)))
23017 (defun org-unindent-buffer ()
23018 "Un-indent the visible part of the buffer.
23019 Relative indentation (between items, inside blocks, etc.) isn't
23020 modified."
23021 (interactive)
23022 (unless (eq major-mode 'org-mode)
23023 (error "Cannot un-indent a buffer not in Org mode"))
23024 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23025 unindent-tree ; For byte-compiler.
23026 (unindent-tree
23027 (function
23028 (lambda (contents)
23029 (mapc
23030 (lambda (element)
23031 (if (memq (org-element-type element) '(headline section))
23032 (funcall unindent-tree (org-element-contents element))
23033 (save-excursion
23034 (save-restriction
23035 (narrow-to-region
23036 (org-element-property :begin element)
23037 (org-element-property :end element))
23038 (org-do-remove-indentation)))))
23039 (reverse contents))))))
23040 (funcall unindent-tree (org-element-contents parse-tree))))
23042 (defun org-show-subtree ()
23043 "Show everything after this heading at deeper levels."
23044 (interactive)
23045 (outline-flag-region
23046 (point)
23047 (save-excursion
23048 (org-end-of-subtree t t))
23049 nil))
23051 (defun org-show-entry ()
23052 "Show the body directly following this heading.
23053 Show the heading too, if it is currently invisible."
23054 (interactive)
23055 (save-excursion
23056 (condition-case nil
23057 (progn
23058 (org-back-to-heading t)
23059 (outline-flag-region
23060 (max (point-min) (1- (point)))
23061 (save-excursion
23062 (if (re-search-forward
23063 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23064 (match-beginning 1)
23065 (point-max)))
23066 nil)
23067 (org-cycle-hide-drawers 'children))
23068 (error nil))))
23070 (defun org-make-options-regexp (kwds &optional extra)
23071 "Make a regular expression for keyword lines."
23072 (concat
23073 "^#\\+\\("
23074 (mapconcat 'regexp-quote kwds "\\|")
23075 (if extra (concat "\\|" extra))
23076 "\\):[ \t]*\\(.*\\)"))
23078 ;; Make isearch reveal the necessary context
23079 (defun org-isearch-end ()
23080 "Reveal context after isearch exits."
23081 (when isearch-success ; only if search was successful
23082 (if (featurep 'xemacs)
23083 ;; Under XEmacs, the hook is run in the correct place,
23084 ;; we directly show the context.
23085 (org-show-context 'isearch)
23086 ;; In Emacs the hook runs *before* restoring the overlays.
23087 ;; So we have to use a one-time post-command-hook to do this.
23088 ;; (Emacs 22 has a special variable, see function `org-mode')
23089 (unless (and (boundp 'isearch-mode-end-hook-quit)
23090 isearch-mode-end-hook-quit)
23091 ;; Only when the isearch was not quitted.
23092 (org-add-hook 'post-command-hook 'org-isearch-post-command
23093 'append 'local)))
23094 (org-fix-ellipsis-at-bol)))
23096 (defun org-isearch-post-command ()
23097 "Remove self from hook, and show context."
23098 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23099 (org-show-context 'isearch))
23102 ;;;; Integration with and fixes for other packages
23104 ;;; Imenu support
23106 (defvar org-imenu-markers nil
23107 "All markers currently used by Imenu.")
23108 (make-variable-buffer-local 'org-imenu-markers)
23110 (defun org-imenu-new-marker (&optional pos)
23111 "Return a new marker for use by Imenu, and remember the marker."
23112 (let ((m (make-marker)))
23113 (move-marker m (or pos (point)))
23114 (push m org-imenu-markers)
23117 (defun org-imenu-get-tree ()
23118 "Produce the index for Imenu."
23119 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23120 (setq org-imenu-markers nil)
23121 (let* ((n org-imenu-depth)
23122 (re (concat "^" (org-get-limited-outline-regexp)))
23123 (subs (make-vector (1+ n) nil))
23124 (last-level 0)
23125 m level head0 head)
23126 (save-excursion
23127 (save-restriction
23128 (widen)
23129 (goto-char (point-max))
23130 (while (re-search-backward re nil t)
23131 (setq level (org-reduced-level (funcall outline-level)))
23132 (when (and (<= level n)
23133 (looking-at org-complex-heading-regexp)
23134 (setq head0 (org-match-string-no-properties 4)))
23135 (setq head (org-link-display-format head0)
23136 m (org-imenu-new-marker))
23137 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23138 (if (>= level last-level)
23139 (push (cons head m) (aref subs level))
23140 (push (cons head (aref subs (1+ level))) (aref subs level))
23141 (loop for i from (1+ level) to n do (aset subs i nil)))
23142 (setq last-level level)))))
23143 (aref subs 1)))
23145 (eval-after-load "imenu"
23146 '(progn
23147 (add-hook 'imenu-after-jump-hook
23148 (lambda ()
23149 (if (derived-mode-p 'org-mode)
23150 (org-show-context 'org-goto))))))
23152 (defun org-link-display-format (link)
23153 "Replace a link with its the description.
23154 If there is no description, use the link target."
23155 (save-match-data
23156 (if (string-match org-bracket-link-analytic-regexp link)
23157 (replace-match (if (match-end 5)
23158 (match-string 5 link)
23159 (concat (match-string 1 link)
23160 (match-string 3 link)))
23161 nil t link)
23162 link)))
23164 (defun org-toggle-link-display ()
23165 "Toggle the literal or descriptive display of links."
23166 (interactive)
23167 (if org-descriptive-links
23168 (progn (org-remove-from-invisibility-spec '(org-link))
23169 (org-restart-font-lock)
23170 (setq org-descriptive-links nil))
23171 (progn (add-to-invisibility-spec '(org-link))
23172 (org-restart-font-lock)
23173 (setq org-descriptive-links t))))
23175 ;; Speedbar support
23177 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23178 "Overlay marking the agenda restriction line in speedbar.")
23179 (overlay-put org-speedbar-restriction-lock-overlay
23180 'face 'org-agenda-restriction-lock)
23181 (overlay-put org-speedbar-restriction-lock-overlay
23182 'help-echo "Agendas are currently limited to this item.")
23183 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23185 (defun org-speedbar-set-agenda-restriction ()
23186 "Restrict future agenda commands to the location at point in speedbar.
23187 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23188 (interactive)
23189 (require 'org-agenda)
23190 (let (p m tp np dir txt)
23191 (cond
23192 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23193 'org-imenu t))
23194 (setq m (get-text-property p 'org-imenu-marker))
23195 (with-current-buffer (marker-buffer m)
23196 (goto-char m)
23197 (org-agenda-set-restriction-lock 'subtree)))
23198 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23199 'speedbar-function 'speedbar-find-file))
23200 (setq tp (previous-single-property-change
23201 (1+ p) 'speedbar-function)
23202 np (next-single-property-change
23203 tp 'speedbar-function)
23204 dir (speedbar-line-directory)
23205 txt (buffer-substring-no-properties (or tp (point-min))
23206 (or np (point-max))))
23207 (with-current-buffer (find-file-noselect
23208 (let ((default-directory dir))
23209 (expand-file-name txt)))
23210 (unless (derived-mode-p 'org-mode)
23211 (error "Cannot restrict to non-Org-mode file"))
23212 (org-agenda-set-restriction-lock 'file)))
23213 (t (error "Don't know how to restrict Org-mode's agenda")))
23214 (move-overlay org-speedbar-restriction-lock-overlay
23215 (point-at-bol) (point-at-eol))
23216 (setq current-prefix-arg nil)
23217 (org-agenda-maybe-redo)))
23219 (eval-after-load "speedbar"
23220 '(progn
23221 (speedbar-add-supported-extension ".org")
23222 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23223 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23224 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23225 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23226 (add-hook 'speedbar-visiting-tag-hook
23227 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23229 ;;; Fixes and Hacks for problems with other packages
23231 ;; Make flyspell not check words in links, to not mess up our keymap
23232 (defvar org-element-affiliated-keywords) ; From org-element.el
23233 (defvar org-element-block-name-alist) ; From org-element.el
23234 (defun org-mode-flyspell-verify ()
23235 "Don't let flyspell put overlays at active buttons, or on
23236 {todo,all-time,additional-option-like}-keywords."
23237 (let ((pos (max (1- (point)) (point-min)))
23238 (word (thing-at-point 'word)))
23239 (and (not (get-text-property pos 'keymap))
23240 (not (get-text-property pos 'org-no-flyspell))
23241 (not (member word org-todo-keywords-1))
23242 (not (member word org-all-time-keywords))
23243 (not (member word org-options-keywords))
23244 (not (member word (mapcar 'car org-startup-options)))
23245 (not (member-ignore-case word org-element-affiliated-keywords))
23246 (not (member-ignore-case word (org-get-export-keywords)))
23247 (not (member-ignore-case
23248 word (mapcar 'car org-element-block-name-alist)))
23249 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23251 (defun org-remove-flyspell-overlays-in (beg end)
23252 "Remove flyspell overlays in region."
23253 (and (org-bound-and-true-p flyspell-mode)
23254 (fboundp 'flyspell-delete-region-overlays)
23255 (flyspell-delete-region-overlays beg end))
23256 (add-text-properties beg end '(org-no-flyspell t)))
23258 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23259 (eval-after-load "bookmark"
23260 '(if (boundp 'bookmark-after-jump-hook)
23261 ;; We can use the hook
23262 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23263 ;; Hook not available, use advice
23264 (defadvice bookmark-jump (after org-make-visible activate)
23265 "Make the position visible."
23266 (org-bookmark-jump-unhide))))
23268 ;; Make sure saveplace shows the location if it was hidden
23269 (eval-after-load "saveplace"
23270 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23271 "Make the position visible."
23272 (org-bookmark-jump-unhide)))
23274 ;; Make sure ecb shows the location if it was hidden
23275 (eval-after-load "ecb"
23276 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23277 "Make hierarchy visible when jumping into location from ECB tree buffer."
23278 (if (derived-mode-p 'org-mode)
23279 (org-show-context))))
23281 (defun org-bookmark-jump-unhide ()
23282 "Unhide the current position, to show the bookmark location."
23283 (and (derived-mode-p 'org-mode)
23284 (or (outline-invisible-p)
23285 (save-excursion (goto-char (max (point-min) (1- (point))))
23286 (outline-invisible-p)))
23287 (org-show-context 'bookmark-jump)))
23289 ;; Make session.el ignore our circular variable
23290 (eval-after-load "session"
23291 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23293 ;;;; Experimental code
23295 (defun org-closed-in-range ()
23296 "Sparse tree of items closed in a certain time range.
23297 Still experimental, may disappear in the future."
23298 (interactive)
23299 ;; Get the time interval from the user.
23300 (let* ((time1 (org-float-time
23301 (org-read-date nil 'to-time nil "Starting date: ")))
23302 (time2 (org-float-time
23303 (org-read-date nil 'to-time nil "End date:")))
23304 ;; callback function
23305 (callback (lambda ()
23306 (let ((time
23307 (org-float-time
23308 (apply 'encode-time
23309 (org-parse-time-string
23310 (match-string 1))))))
23311 ;; check if time in interval
23312 (and (>= time time1) (<= time time2))))))
23313 ;; make tree, check each match with the callback
23314 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
23316 ;;;; Finish up
23318 (provide 'org)
23320 (run-hooks 'org-load-hook)
23322 ;;; org.el ends here