org.el (org-minutes-to-clocksum-string): Round fractions of minutes
[org-mode/org-tableheadings.git] / lisp / org.el
blob7d633ad2b44519c0c67140bd0058487fe827a4d2
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2013 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 (load "org-loaddefs.el" t t t)
83 (require 'org-macs)
84 (require 'org-compat)
86 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
87 ;; some places -- e.g. see the macro `org-with-limited-levels'.
89 ;; In Org buffers, the value of `outline-regexp' is that of
90 ;; `org-outline-regexp'. The only function still directly relying on
91 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
92 ;; job when `orgstruct-mode' is active.
93 (defvar org-outline-regexp "\\*+ "
94 "Regexp to match Org headlines.")
96 (defvar org-outline-regexp-bol "^\\*+ "
97 "Regexp to match Org headlines.
98 This is similar to `org-outline-regexp' but additionally makes
99 sure that we are at the beginning of the line.")
101 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
102 "Matches a headline, putting stars and text into groups.
103 Stars are put in group 1 and the trimmed body in group 2.")
105 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
106 (unless (boundp 'calendar-view-holidays-initially-flag)
107 (org-defvaralias 'calendar-view-holidays-initially-flag
108 'view-calendar-holidays-initially))
109 (unless (boundp 'calendar-view-diary-initially-flag)
110 (org-defvaralias 'calendar-view-diary-initially-flag
111 'view-diary-entries-initially))
112 (unless (boundp 'diary-fancy-buffer)
113 (org-defvaralias 'diary-fancy-buffer 'fancy-diary-buffer))
115 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
116 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
117 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
118 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
119 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
120 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
121 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
122 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
124 (declare-function orgtbl-mode "org-table" (&optional arg))
125 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
126 (declare-function org-beamer-mode "ox-beamer" ())
127 (declare-function org-table-edit-field "org-table" (arg))
128 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
129 (declare-function org-table-set-constants "org-table" ())
130 (declare-function org-id-get-create "org-id" (&optional force))
131 (declare-function org-id-find-id-file "org-id" (id))
132 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
133 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
134 (declare-function org-agenda-redo "org-agenda" (&optional all))
135 (declare-function org-table-align "org-table" ())
136 (declare-function org-table-paste-rectangle "org-table" ())
137 (declare-function org-table-maybe-eval-formula "org-table" ())
138 (declare-function org-table-maybe-recalculate-line "org-table" ())
140 (declare-function org-element--parse-objects "org-element"
141 (beg end acc restriction))
142 (declare-function org-element-at-point "org-element" (&optional keep-trail))
143 (declare-function org-element-contents "org-element" (element))
144 (declare-function org-element-context "org-element" (&optional element))
145 (declare-function org-element-interpret-data "org-element"
146 (data &optional parent))
147 (declare-function org-element-map "org-element"
148 (data types fun &optional info first-match no-recursion))
149 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
150 (declare-function org-element-parse-buffer "org-element"
151 (&optional granularity visible-only))
152 (declare-function org-element-property "org-element" (property element))
153 (declare-function org-element-put-property "org-element"
154 (element property value))
155 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
156 (declare-function org-element--parse-objects "org-element"
157 (beg end acc restriction))
158 (declare-function org-element-parse-buffer "org-element"
159 (&optional granularity visible-only))
160 (declare-function org-element-restriction "org-element" (element))
161 (declare-function org-element-type "org-element" (element))
163 ;; load languages based on value of `org-babel-load-languages'
164 (defvar org-babel-load-languages)
166 ;;;###autoload
167 (defun org-babel-do-load-languages (sym value)
168 "Load the languages defined in `org-babel-load-languages'."
169 (set-default sym value)
170 (mapc (lambda (pair)
171 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
172 (if active
173 (progn
174 (require (intern (concat "ob-" lang))))
175 (progn
176 (funcall 'fmakunbound
177 (intern (concat "org-babel-execute:" lang)))
178 (funcall 'fmakunbound
179 (intern (concat "org-babel-expand-body:" lang)))))))
180 org-babel-load-languages))
182 ;;;###autoload
183 (defun org-babel-load-file (file &optional compile)
184 "Load Emacs Lisp source code blocks in the Org-mode FILE.
185 This function exports the source code using `org-babel-tangle'
186 and then loads the resulting file using `load-file'. With prefix
187 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
188 file to byte-code before it is loaded."
189 (interactive "fFile to load: \nP")
190 (require 'ob-core)
191 (let* ((age (lambda (file)
192 (float-time
193 (time-subtract (current-time)
194 (nth 5 (or (file-attributes (file-truename file))
195 (file-attributes file)))))))
196 (base-name (file-name-sans-extension file))
197 (exported-file (concat base-name ".el")))
198 ;; tangle if the org-mode file is newer than the elisp file
199 (unless (and (file-exists-p exported-file)
200 (> (funcall age file) (funcall age exported-file)))
201 (org-babel-tangle-file file exported-file "emacs-lisp"))
202 (message "%s %s"
203 (if compile
204 (progn (byte-compile-file exported-file 'load)
205 "Compiled and loaded")
206 (progn (load-file exported-file) "Loaded"))
207 exported-file)))
209 (defcustom org-babel-load-languages '((emacs-lisp . t))
210 "Languages which can be evaluated in Org-mode buffers.
211 This list can be used to load support for any of the languages
212 below, note that each language will depend on a different set of
213 system executables and/or Emacs modes. When a language is
214 \"loaded\", then code blocks in that language can be evaluated
215 with `org-babel-execute-src-block' bound by default to C-c
216 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
217 be set to remove code block evaluation from the C-c C-c
218 keybinding. By default only Emacs Lisp (which has no
219 requirements) is loaded."
220 :group 'org-babel
221 :set 'org-babel-do-load-languages
222 :version "24.1"
223 :type '(alist :tag "Babel Languages"
224 :key-type
225 (choice
226 (const :tag "Awk" awk)
227 (const :tag "C" C)
228 (const :tag "R" R)
229 (const :tag "Asymptote" asymptote)
230 (const :tag "Calc" calc)
231 (const :tag "Clojure" clojure)
232 (const :tag "CSS" css)
233 (const :tag "Ditaa" ditaa)
234 (const :tag "Dot" dot)
235 (const :tag "Emacs Lisp" emacs-lisp)
236 (const :tag "Fortran" fortran)
237 (const :tag "Gnuplot" gnuplot)
238 (const :tag "Haskell" haskell)
239 (const :tag "IO" io)
240 (const :tag "Java" java)
241 (const :tag "Javascript" js)
242 (const :tag "LaTeX" latex)
243 (const :tag "Ledger" ledger)
244 (const :tag "Lilypond" lilypond)
245 (const :tag "Lisp" lisp)
246 (const :tag "Makefile" makefile)
247 (const :tag "Maxima" maxima)
248 (const :tag "Matlab" matlab)
249 (const :tag "Mscgen" mscgen)
250 (const :tag "Ocaml" ocaml)
251 (const :tag "Octave" octave)
252 (const :tag "Org" org)
253 (const :tag "Perl" perl)
254 (const :tag "Pico Lisp" picolisp)
255 (const :tag "PlantUML" plantuml)
256 (const :tag "Python" python)
257 (const :tag "Ruby" ruby)
258 (const :tag "Sass" sass)
259 (const :tag "Scala" scala)
260 (const :tag "Scheme" scheme)
261 (const :tag "Screen" screen)
262 (const :tag "Shell Script" sh)
263 (const :tag "Shen" shen)
264 (const :tag "Sql" sql)
265 (const :tag "Sqlite" sqlite))
266 :value-type (boolean :tag "Activate" :value t)))
268 ;;;; Customization variables
269 (defcustom org-clone-delete-id nil
270 "Remove ID property of clones of a subtree.
271 When non-nil, clones of a subtree don't inherit the ID property.
272 Otherwise they inherit the ID property with a new unique
273 identifier."
274 :type 'boolean
275 :version "24.1"
276 :group 'org-id)
278 ;;; Version
279 (org-check-version)
281 ;;;###autoload
282 (defun org-version (&optional here full message)
283 "Show the org-mode version in the echo area.
284 With prefix argument HERE, insert it at point.
285 When FULL is non-nil, use a verbose version string.
286 When MESSAGE is non-nil, display a message with the version."
287 (interactive "P")
288 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
289 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
290 (load-suffixes (list ".el"))
291 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
292 (org-trash (or
293 (and (fboundp 'org-release) (fboundp 'org-git-version))
294 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
295 (load-suffixes save-load-suffixes)
296 (org-version (org-release))
297 (git-version (org-git-version))
298 (version (format "Org-mode version %s (%s @ %s)"
299 org-version
300 git-version
301 (if org-install-dir
302 (if (string= org-dir org-install-dir)
303 org-install-dir
304 (concat "mixed installation! " org-install-dir " and " org-dir))
305 "org-loaddefs.el can not be found!")))
306 (_version (if full version org-version)))
307 (if (org-called-interactively-p 'interactive)
308 (if here
309 (insert version)
310 (message version))
311 (if message (message _version))
312 _version)))
314 (defconst org-version (org-version))
316 ;;; Compatibility constants
318 ;;; The custom variables
320 (defgroup org nil
321 "Outline-based notes management and organizer."
322 :tag "Org"
323 :group 'outlines
324 :group 'calendar)
326 (defcustom org-mode-hook nil
327 "Mode hook for Org-mode, run after the mode was turned on."
328 :group 'org
329 :type 'hook)
331 (defcustom org-load-hook nil
332 "Hook that is run after org.el has been loaded."
333 :group 'org
334 :type 'hook)
336 (defcustom org-log-buffer-setup-hook nil
337 "Hook that is run after an Org log buffer is created."
338 :group 'org
339 :version "24.1"
340 :type 'hook)
342 (defvar org-modules) ; defined below
343 (defvar org-modules-loaded nil
344 "Have the modules been loaded already?")
346 (defun org-load-modules-maybe (&optional force)
347 "Load all extensions listed in `org-modules'."
348 (when (or force (not org-modules-loaded))
349 (mapc (lambda (ext)
350 (condition-case nil (require ext)
351 (error (message "Problems while trying to load feature `%s'" ext))))
352 org-modules)
353 (setq org-modules-loaded t)))
355 (defun org-set-modules (var value)
356 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
357 (set var value)
358 (when (featurep 'org)
359 (org-load-modules-maybe 'force)))
361 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
362 "Modules that should always be loaded together with org.el.
364 If a description starts with <C>, the file is not part of Emacs
365 and loading it will require that you have downloaded and properly
366 installed the Org mode distribution.
368 You can also use this system to load external packages (i.e. neither Org
369 core modules, nor modules from the CONTRIB directory). Just add symbols
370 to the end of the list. If the package is called org-xyz.el, then you need
371 to add the symbol `xyz', and the package must have a call to:
373 \(provide 'org-xyz)
375 For export specific modules, see also `org-export-backends'."
376 :group 'org
377 :set 'org-set-modules
378 :version "24.4"
379 :package-version '(Org . "8.0")
380 :type
381 '(set :greedy t
382 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
383 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
384 (const :tag " crypt: Encryption of subtrees" org-crypt)
385 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
386 (const :tag " docview: Links to doc-view buffers" org-docview)
387 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
388 (const :tag " habit: Track your consistency with habits" org-habit)
389 (const :tag " id: Global IDs for identifying entries" org-id)
390 (const :tag " info: Links to Info nodes" org-info)
391 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
392 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
393 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
394 (const :tag " mouse: Additional mouse support" org-mouse)
395 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
396 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
397 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
399 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
400 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
401 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
402 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
403 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
404 (const :tag "C collector: Collect properties into tables" org-collector)
405 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
406 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
407 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
408 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
409 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
410 (const :tag "C eval: Include command output as text" org-eval)
411 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
412 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
413 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
414 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
415 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
416 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
417 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
418 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
419 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
420 (const :tag "C mac-message: Links to messages in Apple Mail" org-mac-message)
421 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
422 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
423 (const :tag "C mew: Links to Mew folders/messages" org-mew)
424 (const :tag "C mtags: Support for muse-like tags" org-mtags)
425 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
426 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
427 (const :tag "C registry: A registry for Org-mode links" org-registry)
428 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
429 (const :tag "C secretary: Team management with org-mode" org-secretary)
430 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
431 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
432 (const :tag "C track: Keep up with Org-mode development" org-track)
433 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
434 (const :tag "C vm: Links to VM folders/messages" org-vm)
435 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
436 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
437 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
439 (defvar org-export-registered-backends) ; From ox.el
440 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
441 (defcustom org-export-backends '(ascii html icalendar latex)
442 "List of export back-ends that should be always available.
444 If a description starts with <C>, the file is not part of Emacs
445 and loading it will require that you have downloaded and properly
446 installed the Org mode distribution.
448 Unlike to `org-modules', libraries in this list will not be
449 loaded along with Org, but only once the export framework is
450 needed.
452 This variable needs to be set before org.el is loaded. If you
453 need to make a change while Emacs is running, use the customize
454 interface or run the following code, where VALUE stands for the
455 new value of the variable, after updating it:
457 \(progn
458 \(setq org-export-registered-backends
459 \(org-remove-if-not
460 \(lambda (backend)
461 \(or (memq backend val)
462 \(catch 'parentp
463 \(mapc
464 \(lambda (b)
465 \(and (org-export-derived-backend-p b (car backend))
466 \(throw 'parentp t)))
467 val)
468 nil)))
469 org-export-registered-backends))
470 \(let ((new-list (mapcar 'car org-export-registered-backends)))
471 \(dolist (backend val)
472 \(cond
473 \((not (load (format \"ox-%s\" backend) t t))
474 \(message \"Problems while trying to load export back-end `%s'\"
475 backend))
476 \((not (memq backend new-list)) (push backend new-list))))
477 \(set-default var new-list)))
479 Adding a back-end to this list will also pull the back-end it
480 depends on, if any."
481 :group 'org
482 :group 'org-export
483 :version "24.4"
484 :package-version '(Org . "8.0")
485 :initialize 'custom-initialize-set
486 :set (lambda (var val)
487 (if (not (featurep 'ox)) (set-default var val)
488 ;; Any back-end not required anymore (not present in VAL and not
489 ;; a parent of any back-end in the new value) is removed from the
490 ;; list of registered back-ends.
491 (setq org-export-registered-backends
492 (org-remove-if-not
493 (lambda (backend)
494 (or (memq backend val)
495 (catch 'parentp
496 (mapc
497 (lambda (b)
498 (and (org-export-derived-backend-p b (car backend))
499 (throw 'parentp t)))
500 val)
501 nil)))
502 org-export-registered-backends))
503 ;; Now build NEW-LIST of both new back-ends and required
504 ;; parents.
505 (let ((new-list (mapcar 'car org-export-registered-backends)))
506 (dolist (backend val)
507 (cond
508 ((not (load (format "ox-%s" backend) t t))
509 (message "Problems while trying to load export back-end `%s'"
510 backend))
511 ((not (memq backend new-list)) (push backend new-list))))
512 ;; Set VAR to that list with fixed dependencies.
513 (set-default var new-list))))
514 :type '(set :greedy t
515 (const :tag " ascii Export buffer to ASCII format" ascii)
516 (const :tag " beamer Export buffer to Beamer presentation" beamer)
517 (const :tag " html Export buffer to HTML format" html)
518 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
519 (const :tag " latex Export buffer to LaTeX format" latex)
520 (const :tag " man Export buffer to MAN format" man)
521 (const :tag " md Export buffer to Markdown format" md)
522 (const :tag " odt Export buffer to ODT format" odt)
523 (const :tag " org Export buffer to Org format" org)
524 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
525 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
526 (const :tag "C deck Export buffer to deck.js presentations" deck)
527 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
528 (const :tag "C groff Export buffer to Groff format" groff)
529 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
530 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
531 (const :tag "C s5 Export buffer to s5 presentations" s5)
532 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
534 (eval-after-load 'ox
535 '(mapc
536 (lambda (backend)
537 (condition-case nil (require (intern (format "ox-%s" backend)))
538 (error (message "Problems while trying to load export back-end `%s'"
539 backend))))
540 org-export-backends))
542 (defcustom org-support-shift-select nil
543 "Non-nil means make shift-cursor commands select text when possible.
545 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
546 start selecting a region, or enlarge regions started in this way.
547 In Org-mode, in special contexts, these same keys are used for
548 other purposes, important enough to compete with shift selection.
549 Org tries to balance these needs by supporting `shift-select-mode'
550 outside these special contexts, under control of this variable.
552 The default of this variable is nil, to avoid confusing behavior. Shifted
553 cursor keys will then execute Org commands in the following contexts:
554 - on a headline, changing TODO state (left/right) and priority (up/down)
555 - on a time stamp, changing the time
556 - in a plain list item, changing the bullet type
557 - in a property definition line, switching between allowed values
558 - in the BEGIN line of a clock table (changing the time block).
559 Outside these contexts, the commands will throw an error.
561 When this variable is t and the cursor is not in a special
562 context, Org-mode will support shift-selection for making and
563 enlarging regions. To make this more effective, the bullet
564 cycling will no longer happen anywhere in an item line, but only
565 if the cursor is exactly on the bullet.
567 If you set this variable to the symbol `always', then the keys
568 will not be special in headlines, property lines, and item lines,
569 to make shift selection work there as well. If this is what you
570 want, you can use the following alternative commands: `C-c C-t'
571 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
572 can be used to switch TODO sets, `C-c -' to cycle item bullet
573 types, and properties can be edited by hand or in column view.
575 However, when the cursor is on a timestamp, shift-cursor commands
576 will still edit the time stamp - this is just too good to give up.
578 XEmacs user should have this variable set to nil, because
579 `shift-select-mode' is in Emacs 23 or later only."
580 :group 'org
581 :type '(choice
582 (const :tag "Never" nil)
583 (const :tag "When outside special context" t)
584 (const :tag "Everywhere except timestamps" always)))
586 (defcustom org-loop-over-headlines-in-active-region nil
587 "Shall some commands act upon headlines in the active region?
589 When set to `t', some commands will be performed in all headlines
590 within the active region.
592 When set to `start-level', some commands will be performed in all
593 headlines within the active region, provided that these headlines
594 are of the same level than the first one.
596 When set to a string, those commands will be performed on the
597 matching headlines within the active region. Such string must be
598 a tags/property/todo match as it is used in the agenda tags view.
600 The list of commands is: `org-schedule', `org-deadline',
601 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
602 `org-archive-to-archive-sibling'. The archiving commands skip
603 already archived entries."
604 :type '(choice (const :tag "Don't loop" nil)
605 (const :tag "All headlines in active region" t)
606 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
607 (string :tag "Tags/Property/Todo matcher"))
608 :version "24.1"
609 :group 'org-todo
610 :group 'org-archive)
612 (defgroup org-startup nil
613 "Options concerning startup of Org-mode."
614 :tag "Org Startup"
615 :group 'org)
617 (defcustom org-startup-folded t
618 "Non-nil means entering Org-mode will switch to OVERVIEW.
619 This can also be configured on a per-file basis by adding one of
620 the following lines anywhere in the buffer:
622 #+STARTUP: fold (or `overview', this is equivalent)
623 #+STARTUP: nofold (or `showall', this is equivalent)
624 #+STARTUP: content
625 #+STARTUP: showeverything
627 By default, this option is ignored when Org opens agenda files
628 for the first time. If you want the agenda to honor the startup
629 option, set `org-agenda-inhibit-startup' to nil."
630 :group 'org-startup
631 :type '(choice
632 (const :tag "nofold: show all" nil)
633 (const :tag "fold: overview" t)
634 (const :tag "content: all headlines" content)
635 (const :tag "show everything, even drawers" showeverything)))
637 (defcustom org-startup-truncated t
638 "Non-nil means entering Org-mode will set `truncate-lines'.
639 This is useful since some lines containing links can be very long and
640 uninteresting. Also tables look terrible when wrapped."
641 :group 'org-startup
642 :type 'boolean)
644 (defcustom org-startup-indented nil
645 "Non-nil means turn on `org-indent-mode' on startup.
646 This can also be configured on a per-file basis by adding one of
647 the following lines anywhere in the buffer:
649 #+STARTUP: indent
650 #+STARTUP: noindent"
651 :group 'org-structure
652 :type '(choice
653 (const :tag "Not" nil)
654 (const :tag "Globally (slow on startup in large files)" t)))
656 (defcustom org-use-sub-superscripts t
657 "Non-nil means interpret \"_\" and \"^\" for display.
658 When this option is turned on, you can use TeX-like syntax for sub- and
659 superscripts. Several characters after \"_\" or \"^\" will be
660 considered as a single item - so grouping with {} is normally not
661 needed. For example, the following things will be parsed as single
662 sub- or superscripts.
664 10^24 or 10^tau several digits will be considered 1 item.
665 10^-12 or 10^-tau a leading sign with digits or a word
666 x^2-y^3 will be read as x^2 - y^3, because items are
667 terminated by almost any nonword/nondigit char.
668 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
670 Still, ambiguity is possible - so when in doubt use {} to enclose
671 the sub/superscript. If you set this variable to the symbol
672 `{}', the braces are *required* in order to trigger
673 interpretations as sub/superscript. This can be helpful in
674 documents that need \"_\" frequently in plain text."
675 :group 'org-startup
676 :version "24.1"
677 :type '(choice
678 (const :tag "Always interpret" t)
679 (const :tag "Only with braces" {})
680 (const :tag "Never interpret" nil)))
682 (defcustom org-startup-with-beamer-mode nil
683 "Non-nil means turn on `org-beamer-mode' on startup.
684 This can also be configured on a per-file basis by adding one of
685 the following lines anywhere in the buffer:
687 #+STARTUP: beamer"
688 :group 'org-startup
689 :version "24.1"
690 :type 'boolean)
692 (defcustom org-startup-align-all-tables nil
693 "Non-nil means align all tables when visiting a file.
694 This is useful when the column width in tables is forced with <N> cookies
695 in table fields. Such tables will look correct only after the first re-align.
696 This can also be configured on a per-file basis by adding one of
697 the following lines anywhere in the buffer:
698 #+STARTUP: align
699 #+STARTUP: noalign"
700 :group 'org-startup
701 :type 'boolean)
703 (defcustom org-startup-with-inline-images nil
704 "Non-nil means show inline images when loading a new Org file.
705 This can also be configured on a per-file basis by adding one of
706 the following lines anywhere in the buffer:
707 #+STARTUP: inlineimages
708 #+STARTUP: noinlineimages"
709 :group 'org-startup
710 :version "24.1"
711 :type 'boolean)
713 (defcustom org-startup-with-latex-preview nil
714 "Non-nil means preview LaTeX fragments when loading a new Org file.
716 This can also be configured on a per-file basis by adding one of
717 the followinglines anywhere in the buffer:
718 #+STARTUP: latexpreview
719 #+STARTUP: nolatexpreview"
720 :group 'org-startup
721 :version "24.4"
722 :package-version '(Org . "8.0")
723 :type 'boolean)
725 (defcustom org-insert-mode-line-in-empty-file nil
726 "Non-nil means insert the first line setting Org-mode in empty files.
727 When the function `org-mode' is called interactively in an empty file, this
728 normally means that the file name does not automatically trigger Org-mode.
729 To ensure that the file will always be in Org-mode in the future, a
730 line enforcing Org-mode will be inserted into the buffer, if this option
731 has been set."
732 :group 'org-startup
733 :type 'boolean)
735 (defcustom org-replace-disputed-keys nil
736 "Non-nil means use alternative key bindings for some keys.
737 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
738 These keys are also used by other packages like shift-selection-mode'
739 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
740 If you want to use Org-mode together with one of these other modes,
741 or more generally if you would like to move some Org-mode commands to
742 other keys, set this variable and configure the keys with the variable
743 `org-disputed-keys'.
745 This option is only relevant at load-time of Org-mode, and must be set
746 *before* org.el is loaded. Changing it requires a restart of Emacs to
747 become effective."
748 :group 'org-startup
749 :type 'boolean)
751 (defcustom org-use-extra-keys nil
752 "Non-nil means use extra key sequence definitions for certain commands.
753 This happens automatically if you run XEmacs or if `window-system'
754 is nil. This variable lets you do the same manually. You must
755 set it before loading org.
757 Example: on Carbon Emacs 22 running graphically, with an external
758 keyboard on a Powerbook, the default way of setting M-left might
759 not work for either Alt or ESC. Setting this variable will make
760 it work for ESC."
761 :group 'org-startup
762 :type 'boolean)
764 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
766 (defcustom org-disputed-keys
767 '(([(shift up)] . [(meta p)])
768 ([(shift down)] . [(meta n)])
769 ([(shift left)] . [(meta -)])
770 ([(shift right)] . [(meta +)])
771 ([(control shift right)] . [(meta shift +)])
772 ([(control shift left)] . [(meta shift -)]))
773 "Keys for which Org-mode and other modes compete.
774 This is an alist, cars are the default keys, second element specifies
775 the alternative to use when `org-replace-disputed-keys' is t.
777 Keys can be specified in any syntax supported by `define-key'.
778 The value of this option takes effect only at Org-mode's startup,
779 therefore you'll have to restart Emacs to apply it after changing."
780 :group 'org-startup
781 :type 'alist)
783 (defun org-key (key)
784 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
785 Or return the original if not disputed.
786 Also apply the translations defined in `org-xemacs-key-equivalents'."
787 (when org-replace-disputed-keys
788 (let* ((nkey (key-description key))
789 (x (org-find-if (lambda (x)
790 (equal (key-description (car x)) nkey))
791 org-disputed-keys)))
792 (setq key (if x (cdr x) key))))
793 (when (featurep 'xemacs)
794 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
795 key)
797 (defun org-find-if (predicate seq)
798 (catch 'exit
799 (while seq
800 (if (funcall predicate (car seq))
801 (throw 'exit (car seq))
802 (pop seq)))))
804 (defun org-defkey (keymap key def)
805 "Define a key, possibly translated, as returned by `org-key'."
806 (define-key keymap (org-key key) def))
808 (defcustom org-ellipsis nil
809 "The ellipsis to use in the Org-mode outline.
810 When nil, just use the standard three dots. When a string, use that instead,
811 When a face, use the standard 3 dots, but with the specified face.
812 The change affects only Org-mode (which will then use its own display table).
813 Changing this requires executing `M-x org-mode' in a buffer to become
814 effective."
815 :group 'org-startup
816 :type '(choice (const :tag "Default" nil)
817 (face :tag "Face" :value org-warning)
818 (string :tag "String" :value "...#")))
820 (defvar org-display-table nil
821 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
823 (defgroup org-keywords nil
824 "Keywords in Org-mode."
825 :tag "Org Keywords"
826 :group 'org)
828 (defcustom org-deadline-string "DEADLINE:"
829 "String to mark deadline entries.
830 A deadline is this string, followed by a time stamp. Should be a word,
831 terminated by a colon. You can insert a schedule keyword and
832 a timestamp with \\[org-deadline].
833 Changes become only effective after restarting Emacs."
834 :group 'org-keywords
835 :type 'string)
837 (defcustom org-scheduled-string "SCHEDULED:"
838 "String to mark scheduled TODO entries.
839 A schedule is this string, followed by a time stamp. Should be a word,
840 terminated by a colon. You can insert a schedule keyword and
841 a timestamp with \\[org-schedule].
842 Changes become only effective after restarting Emacs."
843 :group 'org-keywords
844 :type 'string)
846 (defcustom org-closed-string "CLOSED:"
847 "String used as the prefix for timestamps logging closing a TODO entry."
848 :group 'org-keywords
849 :type 'string)
851 (defcustom org-clock-string "CLOCK:"
852 "String used as prefix for timestamps clocking work hours on an item."
853 :group 'org-keywords
854 :type 'string)
856 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
857 org-scheduled-string "\\|"
858 org-deadline-string "\\|"
859 org-closed-string "\\|"
860 org-clock-string "\\)")
861 "Matches a line with planning or clock info.")
863 (defcustom org-comment-string "COMMENT"
864 "Entries starting with this keyword will never be exported.
865 An entry can be toggled between COMMENT and normal with
866 \\[org-toggle-comment].
867 Changes become only effective after restarting Emacs."
868 :group 'org-keywords
869 :type 'string)
871 (defcustom org-quote-string "QUOTE"
872 "Entries starting with this keyword will be exported in fixed-width font.
873 Quoting applies only to the text in the entry following the headline, and does
874 not extend beyond the next headline, even if that is lower level.
875 An entry can be toggled between QUOTE and normal with
876 \\[org-toggle-fixed-width-section]."
877 :group 'org-keywords
878 :type 'string)
880 (defconst org-repeat-re
881 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
882 "Regular expression for specifying repeated events.
883 After a match, group 1 contains the repeat expression.")
885 (defgroup org-structure nil
886 "Options concerning the general structure of Org-mode files."
887 :tag "Org Structure"
888 :group 'org)
890 (defgroup org-reveal-location nil
891 "Options about how to make context of a location visible."
892 :tag "Org Reveal Location"
893 :group 'org-structure)
895 (defconst org-context-choice
896 '(choice
897 (const :tag "Always" t)
898 (const :tag "Never" nil)
899 (repeat :greedy t :tag "Individual contexts"
900 (cons
901 (choice :tag "Context"
902 (const agenda)
903 (const org-goto)
904 (const occur-tree)
905 (const tags-tree)
906 (const link-search)
907 (const mark-goto)
908 (const bookmark-jump)
909 (const isearch)
910 (const default))
911 (boolean))))
912 "Contexts for the reveal options.")
914 (defcustom org-show-hierarchy-above '((default . t))
915 "Non-nil means show full hierarchy when revealing a location.
916 Org-mode often shows locations in an org-mode file which might have
917 been invisible before. When this is set, the hierarchy of headings
918 above the exposed location is shown.
919 Turning this off for example for sparse trees makes them very compact.
920 Instead of t, this can also be an alist specifying this option for different
921 contexts. Valid contexts are
922 agenda when exposing an entry from the agenda
923 org-goto when using the command `org-goto' on key C-c C-j
924 occur-tree when using the command `org-occur' on key C-c /
925 tags-tree when constructing a sparse tree based on tags matches
926 link-search when exposing search matches associated with a link
927 mark-goto when exposing the jump goal of a mark
928 bookmark-jump when exposing a bookmark location
929 isearch when exiting from an incremental search
930 default default for all contexts not set explicitly"
931 :group 'org-reveal-location
932 :type org-context-choice)
934 (defcustom org-show-following-heading '((default . nil))
935 "Non-nil means show following heading when revealing a location.
936 Org-mode often shows locations in an org-mode file which might have
937 been invisible before. When this is set, the heading following the
938 match is shown.
939 Turning this off for example for sparse trees makes them very compact,
940 but makes it harder to edit the location of the match. In such a case,
941 use the command \\[org-reveal] to show more context.
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-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
948 "Non-nil means show all sibling heading when revealing a location.
949 Org-mode often shows locations in an org-mode file which might have
950 been invisible before. When this is set, the sibling of the current entry
951 heading are all made visible. If `org-show-hierarchy-above' is t,
952 the same happens on each level of the hierarchy above the current entry.
954 By default this is on for the isearch context, off for all other contexts.
955 Turning this off for example for sparse trees makes them very compact,
956 but makes it harder to edit the location of the match. In such a case,
957 use the command \\[org-reveal] to show more context.
958 Instead of t, this can also be an alist specifying this option for different
959 contexts. See `org-show-hierarchy-above' for valid contexts."
960 :group 'org-reveal-location
961 :type org-context-choice
962 :version "24.4"
963 :package-version '(Org . "8.0"))
965 (defcustom org-show-entry-below '((default . nil))
966 "Non-nil means show the entry below a headline when revealing a location.
967 Org-mode often shows locations in an org-mode file which might have
968 been invisible before. When this is set, the text below the headline that is
969 exposed is also shown.
971 By default this is off for all contexts.
972 Instead of t, this can also be an alist specifying this option for different
973 contexts. See `org-show-hierarchy-above' for valid contexts."
974 :group 'org-reveal-location
975 :type org-context-choice)
977 (defcustom org-indirect-buffer-display 'other-window
978 "How should indirect tree buffers be displayed?
979 This applies to indirect buffers created with the commands
980 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
981 Valid values are:
982 current-window Display in the current window
983 other-window Just display in another window.
984 dedicated-frame Create one new frame, and re-use it each time.
985 new-frame Make a new frame each time. Note that in this case
986 previously-made indirect buffers are kept, and you need to
987 kill these buffers yourself."
988 :group 'org-structure
989 :group 'org-agenda-windows
990 :type '(choice
991 (const :tag "In current window" current-window)
992 (const :tag "In current frame, other window" other-window)
993 (const :tag "Each time a new frame" new-frame)
994 (const :tag "One dedicated frame" dedicated-frame)))
996 (defcustom org-use-speed-commands nil
997 "Non-nil means activate single letter commands at beginning of a headline.
998 This may also be a function to test for appropriate locations where speed
999 commands should be active."
1000 :group 'org-structure
1001 :type '(choice
1002 (const :tag "Never" nil)
1003 (const :tag "At beginning of headline stars" t)
1004 (function)))
1006 (defcustom org-speed-commands-user nil
1007 "Alist of additional speed commands.
1008 This list will be checked before `org-speed-commands-default'
1009 when the variable `org-use-speed-commands' is non-nil
1010 and when the cursor is at the beginning of a headline.
1011 The car if each entry is a string with a single letter, which must
1012 be assigned to `self-insert-command' in the global map.
1013 The cdr is either a command to be called interactively, a function
1014 to be called, or a form to be evaluated.
1015 An entry that is just a list with a single string will be interpreted
1016 as a descriptive headline that will be added when listing the speed
1017 commands in the Help buffer using the `?' speed command."
1018 :group 'org-structure
1019 :type '(repeat :value ("k" . ignore)
1020 (choice :value ("k" . ignore)
1021 (list :tag "Descriptive Headline" (string :tag "Headline"))
1022 (cons :tag "Letter and Command"
1023 (string :tag "Command letter")
1024 (choice
1025 (function)
1026 (sexp))))))
1028 (defgroup org-cycle nil
1029 "Options concerning visibility cycling in Org-mode."
1030 :tag "Org Cycle"
1031 :group 'org-structure)
1033 (defcustom org-cycle-skip-children-state-if-no-children t
1034 "Non-nil means skip CHILDREN state in entries that don't have any."
1035 :group 'org-cycle
1036 :type 'boolean)
1038 (defcustom org-cycle-max-level nil
1039 "Maximum level which should still be subject to visibility cycling.
1040 Levels higher than this will, for cycling, be treated as text, not a headline.
1041 When `org-odd-levels-only' is set, a value of N in this variable actually
1042 means 2N-1 stars as the limiting headline.
1043 When nil, cycle all levels.
1044 Note that the limiting level of cycling is also influenced by
1045 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1046 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1047 than its value."
1048 :group 'org-cycle
1049 :type '(choice
1050 (const :tag "No limit" nil)
1051 (integer :tag "Maximum level")))
1053 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1054 "Names of drawers. Drawers are not opened by cycling on the headline above.
1055 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1056 this:
1057 :DRAWERNAME:
1058 .....
1059 :END:
1060 The drawer \"PROPERTIES\" is special for capturing properties through
1061 the property API.
1063 Drawers can be defined on the per-file basis with a line like:
1065 #+DRAWERS: HIDDEN STATE PROPERTIES"
1066 :group 'org-structure
1067 :group 'org-cycle
1068 :type '(repeat (string :tag "Drawer Name")))
1070 (defcustom org-hide-block-startup nil
1071 "Non-nil means entering Org-mode will fold all blocks.
1072 This can also be set in on a per-file basis with
1074 #+STARTUP: hideblocks
1075 #+STARTUP: showblocks"
1076 :group 'org-startup
1077 :group 'org-cycle
1078 :type 'boolean)
1080 (defcustom org-cycle-global-at-bob nil
1081 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1082 This makes it possible to do global cycling without having to use S-TAB or
1083 \\[universal-argument] TAB. For this special case to work, the first line
1084 of the buffer must not be a headline -- it may be empty or some other text.
1085 When used in this way, `org-cycle-hook' is disabled temporarily to make
1086 sure the cursor stays at the beginning of the buffer. When this option is
1087 nil, don't do anything special at the beginning of the buffer."
1088 :group 'org-cycle
1089 :type 'boolean)
1091 (defcustom org-cycle-level-after-item/entry-creation t
1092 "Non-nil means cycle entry level or item indentation in new empty entries.
1094 When the cursor is at the end of an empty headline, i.e., with only stars
1095 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1096 and then all possible ancestor states, before returning to the original state.
1097 This makes data entry extremely fast: M-RET to create a new headline,
1098 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1100 When the cursor is at the end of an empty plain list item, one TAB will
1101 make it a subitem, two or more tabs will back up to make this an item
1102 higher up in the item hierarchy."
1103 :group 'org-cycle
1104 :type 'boolean)
1106 (defcustom org-cycle-emulate-tab t
1107 "Where should `org-cycle' emulate TAB.
1108 nil Never
1109 white Only in completely white lines
1110 whitestart Only at the beginning of lines, before the first non-white char
1111 t Everywhere except in headlines
1112 exc-hl-bol Everywhere except at the start of a headline
1113 If TAB is used in a place where it does not emulate TAB, the current subtree
1114 visibility is cycled."
1115 :group 'org-cycle
1116 :type '(choice (const :tag "Never" nil)
1117 (const :tag "Only in completely white lines" white)
1118 (const :tag "Before first char in a line" whitestart)
1119 (const :tag "Everywhere except in headlines" t)
1120 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
1123 (defcustom org-cycle-separator-lines 2
1124 "Number of empty lines needed to keep an empty line between collapsed trees.
1125 If you leave an empty line between the end of a subtree and the following
1126 headline, this empty line is hidden when the subtree is folded.
1127 Org-mode will leave (exactly) one empty line visible if the number of
1128 empty lines is equal or larger to the number given in this variable.
1129 So the default 2 means at least 2 empty lines after the end of a subtree
1130 are needed to produce free space between a collapsed subtree and the
1131 following headline.
1133 If the number is negative, and the number of empty lines is at least -N,
1134 all empty lines are shown.
1136 Special case: when 0, never leave empty lines in collapsed view."
1137 :group 'org-cycle
1138 :type 'integer)
1139 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1141 (defcustom org-pre-cycle-hook nil
1142 "Hook that is run before visibility cycling is happening.
1143 The function(s) in this hook must accept a single argument which indicates
1144 the new state that will be set right after running this hook. The
1145 argument is a symbol. Before a global state change, it can have the values
1146 `overview', `content', or `all'. Before a local state change, it can have
1147 the values `folded', `children', or `subtree'."
1148 :group 'org-cycle
1149 :type 'hook)
1151 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1152 org-cycle-hide-drawers
1153 org-cycle-hide-inline-tasks
1154 org-cycle-show-empty-lines
1155 org-optimize-window-after-visibility-change)
1156 "Hook that is run after `org-cycle' has changed the buffer visibility.
1157 The function(s) in this hook must accept a single argument which indicates
1158 the new state that was set by the most recent `org-cycle' command. The
1159 argument is a symbol. After a global state change, it can have the values
1160 `overview', `contents', or `all'. After a local state change, it can have
1161 the values `folded', `children', or `subtree'."
1162 :group 'org-cycle
1163 :type 'hook)
1165 (defgroup org-edit-structure nil
1166 "Options concerning structure editing in Org-mode."
1167 :tag "Org Edit Structure"
1168 :group 'org-structure)
1170 (defcustom org-odd-levels-only nil
1171 "Non-nil means skip even levels and only use odd levels for the outline.
1172 This has the effect that two stars are being added/taken away in
1173 promotion/demotion commands. It also influences how levels are
1174 handled by the exporters.
1175 Changing it requires restart of `font-lock-mode' to become effective
1176 for fontification also in regions already fontified.
1177 You may also set this on a per-file basis by adding one of the following
1178 lines to the buffer:
1180 #+STARTUP: odd
1181 #+STARTUP: oddeven"
1182 :group 'org-edit-structure
1183 :group 'org-appearance
1184 :type 'boolean)
1186 (defcustom org-adapt-indentation t
1187 "Non-nil means adapt indentation to outline node level.
1189 When this variable is set, Org assumes that you write outlines by
1190 indenting text in each node to align with the headline (after the stars).
1191 The following issues are influenced by this variable:
1193 - When this is set and the *entire* text in an entry is indented, the
1194 indentation is increased by one space in a demotion command, and
1195 decreased by one in a promotion command. If any line in the entry
1196 body starts with text at column 0, indentation is not changed at all.
1198 - Property drawers and planning information is inserted indented when
1199 this variable s set. When nil, they will not be indented.
1201 - TAB indents a line relative to context. The lines below a headline
1202 will be indented when this variable is set.
1204 Note that this is all about true indentation, by adding and removing
1205 space characters. See also `org-indent.el' which does level-dependent
1206 indentation in a virtual way, i.e. at display time in Emacs."
1207 :group 'org-edit-structure
1208 :type 'boolean)
1210 (defcustom org-special-ctrl-a/e nil
1211 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1213 When t, `C-a' will bring back the cursor to the beginning of the
1214 headline text, i.e. after the stars and after a possible TODO
1215 keyword. In an item, this will be the position after bullet and
1216 check-box, if any. When the cursor is already at that position,
1217 another `C-a' will bring it to the beginning of the line.
1219 `C-e' will jump to the end of the headline, ignoring the presence
1220 of tags in the headline. A second `C-e' will then jump to the
1221 true end of the line, after any tags. This also means that, when
1222 this variable is non-nil, `C-e' also will never jump beyond the
1223 end of the heading of a folded section, i.e. not after the
1224 ellipses.
1226 When set to the symbol `reversed', the first `C-a' or `C-e' works
1227 normally, going to the true line boundary first. Only a directly
1228 following, identical keypress will bring the cursor to the
1229 special positions.
1231 This may also be a cons cell where the behavior for `C-a' and
1232 `C-e' is set separately."
1233 :group 'org-edit-structure
1234 :type '(choice
1235 (const :tag "off" nil)
1236 (const :tag "on: after stars/bullet and before tags first" t)
1237 (const :tag "reversed: true line boundary first" reversed)
1238 (cons :tag "Set C-a and C-e separately"
1239 (choice :tag "Special C-a"
1240 (const :tag "off" nil)
1241 (const :tag "on: after stars/bullet first" t)
1242 (const :tag "reversed: before stars/bullet first" reversed))
1243 (choice :tag "Special C-e"
1244 (const :tag "off" nil)
1245 (const :tag "on: before tags first" t)
1246 (const :tag "reversed: after tags first" reversed)))))
1247 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1249 (defcustom org-special-ctrl-k nil
1250 "Non-nil means `C-k' will behave specially in headlines.
1251 When nil, `C-k' will call the default `kill-line' command.
1252 When t, the following will happen while the cursor is in the headline:
1254 - When the cursor is at the beginning of a headline, kill the entire
1255 line and possible the folded subtree below the line.
1256 - When in the middle of the headline text, kill the headline up to the tags.
1257 - When after the headline text, kill the tags."
1258 :group 'org-edit-structure
1259 :type 'boolean)
1261 (defcustom org-ctrl-k-protect-subtree nil
1262 "Non-nil means, do not delete a hidden subtree with C-k.
1263 When set to the symbol `error', simply throw an error when C-k is
1264 used to kill (part-of) a headline that has hidden text behind it.
1265 Any other non-nil value will result in a query to the user, if it is
1266 OK to kill that hidden subtree. When nil, kill without remorse."
1267 :group 'org-edit-structure
1268 :version "24.1"
1269 :type '(choice
1270 (const :tag "Do not protect hidden subtrees" nil)
1271 (const :tag "Protect hidden subtrees with a security query" t)
1272 (const :tag "Never kill a hidden subtree with C-k" error)))
1274 (defcustom org-catch-invisible-edits nil
1275 "Check if in invisible region before inserting or deleting a character.
1276 Valid values are:
1278 nil Do not check, so just do invisible edits.
1279 error Throw an error and do nothing.
1280 show Make point visible, and do the requested edit.
1281 show-and-error Make point visible, then throw an error and abort the edit.
1282 smart Make point visible, and do insertion/deletion if it is
1283 adjacent to visible text and the change feels predictable.
1284 Never delete a previously invisible character or add in the
1285 middle or right after an invisible region. Basically, this
1286 allows insertion and backward-delete right before ellipses.
1287 FIXME: maybe in this case we should not even show?"
1288 :group 'org-edit-structure
1289 :version "24.1"
1290 :type '(choice
1291 (const :tag "Do not check" nil)
1292 (const :tag "Throw error when trying to edit" error)
1293 (const :tag "Unhide, but do not do the edit" show-and-error)
1294 (const :tag "Show invisible part and do the edit" show)
1295 (const :tag "Be smart and do the right thing" smart)))
1297 (defcustom org-yank-folded-subtrees t
1298 "Non-nil means when yanking subtrees, fold them.
1299 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1300 it starts with a heading and all other headings in it are either children
1301 or siblings, then fold all the subtrees. However, do this only if no
1302 text after the yank would be swallowed into a folded tree by this action."
1303 :group 'org-edit-structure
1304 :type 'boolean)
1306 (defcustom org-yank-adjusted-subtrees nil
1307 "Non-nil means when yanking subtrees, adjust the level.
1308 With this setting, `org-paste-subtree' is used to insert the subtree, see
1309 this function for details."
1310 :group 'org-edit-structure
1311 :type 'boolean)
1313 (defcustom org-M-RET-may-split-line '((default . t))
1314 "Non-nil means M-RET will split the line at the cursor position.
1315 When nil, it will go to the end of the line before making a
1316 new line.
1317 You may also set this option in a different way for different
1318 contexts. Valid contexts are:
1320 headline when creating a new headline
1321 item when creating a new item
1322 table in a table field
1323 default the value to be used for all contexts not explicitly
1324 customized"
1325 :group 'org-structure
1326 :group 'org-table
1327 :type '(choice
1328 (const :tag "Always" t)
1329 (const :tag "Never" nil)
1330 (repeat :greedy t :tag "Individual contexts"
1331 (cons
1332 (choice :tag "Context"
1333 (const headline)
1334 (const item)
1335 (const table)
1336 (const default))
1337 (boolean)))))
1340 (defcustom org-insert-heading-respect-content nil
1341 "Non-nil means insert new headings after the current subtree.
1342 When nil, the new heading is created directly after the current line.
1343 The commands \\[org-insert-heading-respect-content] and
1344 \\[org-insert-todo-heading-respect-content] turn this variable on
1345 for the duration of the command."
1346 :group 'org-structure
1347 :type 'boolean)
1349 (defcustom org-blank-before-new-entry '((heading . auto)
1350 (plain-list-item . auto))
1351 "Should `org-insert-heading' leave a blank line before new heading/item?
1352 The value is an alist, with `heading' and `plain-list-item' as CAR,
1353 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1354 which case Org will look at the surrounding headings/items and try to
1355 make an intelligent decision whether to insert a blank line or not.
1357 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1358 the setting here is ignored and no empty line is inserted to avoid breaking
1359 the list structure."
1360 :group 'org-edit-structure
1361 :type '(list
1362 (cons (const heading)
1363 (choice (const :tag "Never" nil)
1364 (const :tag "Always" t)
1365 (const :tag "Auto" auto)))
1366 (cons (const plain-list-item)
1367 (choice (const :tag "Never" nil)
1368 (const :tag "Always" t)
1369 (const :tag "Auto" auto)))))
1371 (defcustom org-insert-heading-hook nil
1372 "Hook being run after inserting a new heading."
1373 :group 'org-edit-structure
1374 :type 'hook)
1376 (defcustom org-enable-fixed-width-editor t
1377 "Non-nil means lines starting with \":\" are treated as fixed-width.
1378 This currently only means they are never auto-wrapped.
1379 When nil, such lines will be treated like ordinary lines.
1380 See also the QUOTE keyword."
1381 :group 'org-edit-structure
1382 :type 'boolean)
1384 (defcustom org-goto-auto-isearch t
1385 "Non-nil means typing characters in `org-goto' starts incremental search.
1386 When nil, you can use these keybindings to navigate the buffer:
1388 q Quit the org-goto interface
1389 n Go to the next visible heading
1390 p Go to the previous visible heading
1391 f Go one heading forward on same level
1392 b Go one heading backward on same level
1393 u Go one heading up"
1394 :group 'org-edit-structure
1395 :type 'boolean)
1397 (defgroup org-sparse-trees nil
1398 "Options concerning sparse trees in Org-mode."
1399 :tag "Org Sparse Trees"
1400 :group 'org-structure)
1402 (defcustom org-highlight-sparse-tree-matches t
1403 "Non-nil means highlight all matches that define a sparse tree.
1404 The highlights will automatically disappear the next time the buffer is
1405 changed by an edit command."
1406 :group 'org-sparse-trees
1407 :type 'boolean)
1409 (defcustom org-remove-highlights-with-change t
1410 "Non-nil means any change to the buffer will remove temporary highlights.
1411 Such highlights are created by `org-occur' and `org-clock-display'.
1412 When nil, `C-c C-c needs to be used to get rid of the highlights.
1413 The highlights created by `org-preview-latex-fragment' always need
1414 `C-c C-c' to be removed."
1415 :group 'org-sparse-trees
1416 :group 'org-time
1417 :type 'boolean)
1420 (defcustom org-occur-hook '(org-first-headline-recenter)
1421 "Hook that is run after `org-occur' has constructed a sparse tree.
1422 This can be used to recenter the window to show as much of the structure
1423 as possible."
1424 :group 'org-sparse-trees
1425 :type 'hook)
1427 (defgroup org-imenu-and-speedbar nil
1428 "Options concerning imenu and speedbar in Org-mode."
1429 :tag "Org Imenu and Speedbar"
1430 :group 'org-structure)
1432 (defcustom org-imenu-depth 2
1433 "The maximum level for Imenu access to Org-mode headlines.
1434 This also applied for speedbar access."
1435 :group 'org-imenu-and-speedbar
1436 :type 'integer)
1438 (defgroup org-table nil
1439 "Options concerning tables in Org-mode."
1440 :tag "Org Table"
1441 :group 'org)
1443 (defcustom org-enable-table-editor 'optimized
1444 "Non-nil means lines starting with \"|\" are handled by the table editor.
1445 When nil, such lines will be treated like ordinary lines.
1447 When equal to the symbol `optimized', the table editor will be optimized to
1448 do the following:
1449 - Automatic overwrite mode in front of whitespace in table fields.
1450 This makes the structure of the table stay in tact as long as the edited
1451 field does not exceed the column width.
1452 - Minimize the number of realigns. Normally, the table is aligned each time
1453 TAB or RET are pressed to move to another field. With optimization this
1454 happens only if changes to a field might have changed the column width.
1455 Optimization requires replacing the functions `self-insert-command',
1456 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1457 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1458 very good at guessing when a re-align will be necessary, but you can always
1459 force one with \\[org-ctrl-c-ctrl-c].
1461 If you would like to use the optimized version in Org-mode, but the
1462 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1464 This variable can be used to turn on and off the table editor during a session,
1465 but in order to toggle optimization, a restart is required.
1467 See also the variable `org-table-auto-blank-field'."
1468 :group 'org-table
1469 :type '(choice
1470 (const :tag "off" nil)
1471 (const :tag "on" t)
1472 (const :tag "on, optimized" optimized)))
1474 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1475 (version<= emacs-version "24.1"))
1476 "Non-nil means cluster self-insert commands for undo when possible.
1477 If this is set, then, like in the Emacs command loop, 20 consecutive
1478 characters will be undone together.
1479 This is configurable, because there is some impact on typing performance."
1480 :group 'org-table
1481 :type 'boolean)
1483 (defcustom org-table-tab-recognizes-table.el t
1484 "Non-nil means TAB will automatically notice a table.el table.
1485 When it sees such a table, it moves point into it and - if necessary -
1486 calls `table-recognize-table'."
1487 :group 'org-table-editing
1488 :type 'boolean)
1490 (defgroup org-link nil
1491 "Options concerning links in Org-mode."
1492 :tag "Org Link"
1493 :group 'org)
1495 (defvar org-link-abbrev-alist-local nil
1496 "Buffer-local version of `org-link-abbrev-alist', which see.
1497 The value of this is taken from the #+LINK lines.")
1498 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1500 (defcustom org-link-abbrev-alist nil
1501 "Alist of link abbreviations.
1502 The car of each element is a string, to be replaced at the start of a link.
1503 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1504 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1506 [[linkkey:tag][description]]
1508 The 'linkkey' must be a word word, starting with a letter, followed
1509 by letters, numbers, '-' or '_'.
1511 If REPLACE is a string, the tag will simply be appended to create the link.
1512 If the string contains \"%s\", the tag will be inserted there. If the string
1513 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1514 at that point (see the function `url-hexify-string'). If the string contains
1515 the specifier \"%(my-function)\", then the custom function `my-function' will
1516 be invoked: this function takes the tag as its only argument and must return
1517 a string.
1519 REPLACE may also be a function that will be called with the tag as the
1520 only argument to create the link, which should be returned as a string.
1522 See the manual for examples."
1523 :group 'org-link
1524 :type '(repeat
1525 (cons
1526 (string :tag "Protocol")
1527 (choice
1528 (string :tag "Format")
1529 (function)))))
1531 (defcustom org-descriptive-links t
1532 "Non-nil means Org will display descriptive links.
1533 E.g. [[http://orgmode.org][Org website]] will be displayed as
1534 \"Org Website\", hiding the link itself and just displaying its
1535 description. When set to `nil', Org will display the full links
1536 literally.
1538 You can interactively set the value of this variable by calling
1539 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1540 :group 'org-link
1541 :type 'boolean)
1543 (defcustom org-link-file-path-type 'adaptive
1544 "How the path name in file links should be stored.
1545 Valid values are:
1547 relative Relative to the current directory, i.e. the directory of the file
1548 into which the link is being inserted.
1549 absolute Absolute path, if possible with ~ for home directory.
1550 noabbrev Absolute path, no abbreviation of home directory.
1551 adaptive Use relative path for files in the current directory and sub-
1552 directories of it. For other files, use an absolute path."
1553 :group 'org-link
1554 :type '(choice
1555 (const relative)
1556 (const absolute)
1557 (const noabbrev)
1558 (const adaptive)))
1560 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1561 "Types of links that should be activated in Org-mode files.
1562 This is a list of symbols, each leading to the activation of a certain link
1563 type. In principle, it does not hurt to turn on most link types - there may
1564 be a small gain when turning off unused link types. The types are:
1566 bracket The recommended [[link][description]] or [[link]] links with hiding.
1567 angle Links in angular brackets that may contain whitespace like
1568 <bbdb:Carsten Dominik>.
1569 plain Plain links in normal text, no whitespace, like http://google.com.
1570 radio Text that is matched by a radio target, see manual for details.
1571 tag Tag settings in a headline (link to tag search).
1572 date Time stamps (link to calendar).
1573 footnote Footnote labels.
1575 Changing this variable requires a restart of Emacs to become effective."
1576 :group 'org-link
1577 :type '(set :greedy t
1578 (const :tag "Double bracket links" bracket)
1579 (const :tag "Angular bracket links" angle)
1580 (const :tag "Plain text links" plain)
1581 (const :tag "Radio target matches" radio)
1582 (const :tag "Tags" tag)
1583 (const :tag "Timestamps" date)
1584 (const :tag "Footnotes" footnote)))
1586 (defcustom org-make-link-description-function nil
1587 "Function to use for generating link descriptions from links.
1588 When nil, the link location will be used. This function must take
1589 two parameters: the first one is the link, the second one is the
1590 description generated by `org-insert-link'. The function should
1591 return the description to use."
1592 :group 'org-link
1593 :type 'function)
1595 (defgroup org-link-store nil
1596 "Options concerning storing links in Org-mode."
1597 :tag "Org Store Link"
1598 :group 'org-link)
1600 (defcustom org-url-hexify-p t
1601 "When non-nil, hexify URL when creating a link."
1602 :type 'boolean
1603 :version "24.3"
1604 :group 'org-link-store)
1606 (defcustom org-email-link-description-format "Email %c: %.30s"
1607 "Format of the description part of a link to an email or usenet message.
1608 The following %-escapes will be replaced by corresponding information:
1610 %F full \"From\" field
1611 %f name, taken from \"From\" field, address if no name
1612 %T full \"To\" field
1613 %t first name in \"To\" field, address if no name
1614 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1615 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1616 %s subject
1617 %d date
1618 %m message-id.
1620 You may use normal field width specification between the % and the letter.
1621 This is for example useful to limit the length of the subject.
1623 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1624 :group 'org-link-store
1625 :type 'string)
1627 (defcustom org-from-is-user-regexp
1628 (let (r1 r2)
1629 (when (and user-mail-address (not (string= user-mail-address "")))
1630 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1631 (when (and user-full-name (not (string= user-full-name "")))
1632 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1633 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1634 "Regexp matched against the \"From:\" header of an email or usenet message.
1635 It should match if the message is from the user him/herself."
1636 :group 'org-link-store
1637 :type 'regexp)
1639 (defcustom org-context-in-file-links t
1640 "Non-nil means file links from `org-store-link' contain context.
1641 A search string will be added to the file name with :: as separator and
1642 used to find the context when the link is activated by the command
1643 `org-open-at-point'. When this option is t, the entire active region
1644 will be placed in the search string of the file link. If set to a
1645 positive integer, only the first n lines of context will be stored.
1647 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1648 negates this setting for the duration of the command."
1649 :group 'org-link-store
1650 :type '(choice boolean integer))
1652 (defcustom org-keep-stored-link-after-insertion nil
1653 "Non-nil means keep link in list for entire session.
1655 The command `org-store-link' adds a link pointing to the current
1656 location to an internal list. These links accumulate during a session.
1657 The command `org-insert-link' can be used to insert links into any
1658 Org-mode file (offering completion for all stored links). When this
1659 option is nil, every link which has been inserted once using \\[org-insert-link]
1660 will be removed from the list, to make completing the unused links
1661 more efficient."
1662 :group 'org-link-store
1663 :type 'boolean)
1665 (defgroup org-link-follow nil
1666 "Options concerning following links in Org-mode."
1667 :tag "Org Follow Link"
1668 :group 'org-link)
1670 (defcustom org-link-translation-function nil
1671 "Function to translate links with different syntax to Org syntax.
1672 This can be used to translate links created for example by the Planner
1673 or emacs-wiki packages to Org syntax.
1674 The function must accept two parameters, a TYPE containing the link
1675 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1676 which is everything after the link protocol. It should return a cons
1677 with possibly modified values of type and path.
1678 Org contains a function for this, so if you set this variable to
1679 `org-translate-link-from-planner', you should be able follow many
1680 links created by planner."
1681 :group 'org-link-follow
1682 :type 'function)
1684 (defcustom org-follow-link-hook nil
1685 "Hook that is run after a link has been followed."
1686 :group 'org-link-follow
1687 :type 'hook)
1689 (defcustom org-tab-follows-link nil
1690 "Non-nil means on links TAB will follow the link.
1691 Needs to be set before org.el is loaded.
1692 This really should not be used, it does not make sense, and the
1693 implementation is bad."
1694 :group 'org-link-follow
1695 :type 'boolean)
1697 (defcustom org-return-follows-link nil
1698 "Non-nil means on links RET will follow the link.
1699 In tables, the special behavior of RET has precedence."
1700 :group 'org-link-follow
1701 :type 'boolean)
1703 (defcustom org-mouse-1-follows-link
1704 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1705 "Non-nil means mouse-1 on a link will follow the link.
1706 A longer mouse click will still set point. Does not work on XEmacs.
1707 Needs to be set before org.el is loaded."
1708 :group 'org-link-follow
1709 :type 'boolean)
1711 (defcustom org-mark-ring-length 4
1712 "Number of different positions to be recorded in the ring.
1713 Changing this requires a restart of Emacs to work correctly."
1714 :group 'org-link-follow
1715 :type 'integer)
1717 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1718 "Non-nil means internal links in Org files must exactly match a headline.
1719 When nil, the link search tries to match a phrase with all words
1720 in the search text."
1721 :group 'org-link-follow
1722 :version "24.1"
1723 :type '(choice
1724 (const :tag "Use fuzzy text search" nil)
1725 (const :tag "Match only exact headline" t)
1726 (const :tag "Match exact headline or query to create it"
1727 query-to-create)))
1729 (defcustom org-link-frame-setup
1730 '((vm . vm-visit-folder-other-frame)
1731 (vm-imap . vm-visit-imap-folder-other-frame)
1732 (gnus . org-gnus-no-new-news)
1733 (file . find-file-other-window)
1734 (wl . wl-other-frame))
1735 "Setup the frame configuration for following links.
1736 When following a link with Emacs, it may often be useful to display
1737 this link in another window or frame. This variable can be used to
1738 set this up for the different types of links.
1739 For VM, use any of
1740 `vm-visit-folder'
1741 `vm-visit-folder-other-window'
1742 `vm-visit-folder-other-frame'
1743 For Gnus, use any of
1744 `gnus'
1745 `gnus-other-frame'
1746 `org-gnus-no-new-news'
1747 For FILE, use any of
1748 `find-file'
1749 `find-file-other-window'
1750 `find-file-other-frame'
1751 For Wanderlust use any of
1752 `wl'
1753 `wl-other-frame'
1754 For the calendar, use the variable `calendar-setup'.
1755 For BBDB, it is currently only possible to display the matches in
1756 another window."
1757 :group 'org-link-follow
1758 :type '(list
1759 (cons (const vm)
1760 (choice
1761 (const vm-visit-folder)
1762 (const vm-visit-folder-other-window)
1763 (const vm-visit-folder-other-frame)))
1764 (cons (const gnus)
1765 (choice
1766 (const gnus)
1767 (const gnus-other-frame)
1768 (const org-gnus-no-new-news)))
1769 (cons (const file)
1770 (choice
1771 (const find-file)
1772 (const find-file-other-window)
1773 (const find-file-other-frame)))
1774 (cons (const wl)
1775 (choice
1776 (const wl)
1777 (const wl-other-frame)))))
1779 (defcustom org-display-internal-link-with-indirect-buffer nil
1780 "Non-nil means use indirect buffer to display infile links.
1781 Activating internal links (from one location in a file to another location
1782 in the same file) normally just jumps to the location. When the link is
1783 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1784 is displayed in
1785 another window. When this option is set, the other window actually displays
1786 an indirect buffer clone of the current buffer, to avoid any visibility
1787 changes to the current buffer."
1788 :group 'org-link-follow
1789 :type 'boolean)
1791 (defcustom org-open-non-existing-files nil
1792 "Non-nil means `org-open-file' will open non-existing files.
1793 When nil, an error will be generated.
1794 This variable applies only to external applications because they
1795 might choke on non-existing files. If the link is to a file that
1796 will be opened in Emacs, the variable is ignored."
1797 :group 'org-link-follow
1798 :type 'boolean)
1800 (defcustom org-open-directory-means-index-dot-org nil
1801 "Non-nil means a link to a directory really means to index.org.
1802 When nil, following a directory link will run dired or open a finder/explorer
1803 window on that directory."
1804 :group 'org-link-follow
1805 :type 'boolean)
1807 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1808 "Function and arguments to call for following mailto links.
1809 This is a list with the first element being a Lisp function, and the
1810 remaining elements being arguments to the function. In string arguments,
1811 %a will be replaced by the address, and %s will be replaced by the subject
1812 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1813 :group 'org-link-follow
1814 :type '(choice
1815 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1816 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1817 (const :tag "message-mail" (message-mail "%a" "%s"))
1818 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1820 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1821 "Non-nil means ask for confirmation before executing shell links.
1822 Shell links can be dangerous: just think about a link
1824 [[shell:rm -rf ~/*][Google Search]]
1826 This link would show up in your Org-mode document as \"Google Search\",
1827 but really it would remove your entire home directory.
1828 Therefore we advise against setting this variable to nil.
1829 Just change it to `y-or-n-p' if you want to confirm with a
1830 single keystroke rather than having to type \"yes\"."
1831 :group 'org-link-follow
1832 :type '(choice
1833 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1834 (const :tag "with y-or-n (faster)" y-or-n-p)
1835 (const :tag "no confirmation (dangerous)" nil)))
1836 (put 'org-confirm-shell-link-function
1837 'safe-local-variable
1838 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1840 (defcustom org-confirm-shell-link-not-regexp ""
1841 "A regexp to skip confirmation for shell links."
1842 :group 'org-link-follow
1843 :version "24.1"
1844 :type 'regexp)
1846 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1847 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1848 Elisp links can be dangerous: just think about a link
1850 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1852 This link would show up in your Org-mode document as \"Google Search\",
1853 but really it would remove your entire home directory.
1854 Therefore we advise against setting this variable to nil.
1855 Just change it to `y-or-n-p' if you want to confirm with a
1856 single keystroke rather than having to type \"yes\"."
1857 :group 'org-link-follow
1858 :type '(choice
1859 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1860 (const :tag "with y-or-n (faster)" y-or-n-p)
1861 (const :tag "no confirmation (dangerous)" nil)))
1862 (put 'org-confirm-shell-link-function
1863 'safe-local-variable
1864 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1866 (defcustom org-confirm-elisp-link-not-regexp ""
1867 "A regexp to skip confirmation for Elisp links."
1868 :group 'org-link-follow
1869 :version "24.1"
1870 :type 'regexp)
1872 (defconst org-file-apps-defaults-gnu
1873 '((remote . emacs)
1874 (system . mailcap)
1875 (t . mailcap))
1876 "Default file applications on a UNIX or GNU/Linux system.
1877 See `org-file-apps'.")
1879 (defconst org-file-apps-defaults-macosx
1880 '((remote . emacs)
1881 (t . "open %s")
1882 (system . "open %s")
1883 ("ps.gz" . "gv %s")
1884 ("eps.gz" . "gv %s")
1885 ("dvi" . "xdvi %s")
1886 ("fig" . "xfig %s"))
1887 "Default file applications on a MacOS X system.
1888 The system \"open\" is known as a default, but we use X11 applications
1889 for some files for which the OS does not have a good default.
1890 See `org-file-apps'.")
1892 (defconst org-file-apps-defaults-windowsnt
1893 (list
1894 '(remote . emacs)
1895 (cons t
1896 (list (if (featurep 'xemacs)
1897 'mswindows-shell-execute
1898 'w32-shell-execute)
1899 "open" 'file))
1900 (cons 'system
1901 (list (if (featurep 'xemacs)
1902 'mswindows-shell-execute
1903 'w32-shell-execute)
1904 "open" 'file)))
1905 "Default file applications on a Windows NT system.
1906 The system \"open\" is used for most files.
1907 See `org-file-apps'.")
1909 (defcustom org-file-apps
1911 (auto-mode . emacs)
1912 ("\\.mm\\'" . default)
1913 ("\\.x?html?\\'" . default)
1914 ("\\.pdf\\'" . default)
1916 "External applications for opening `file:path' items in a document.
1917 Org-mode uses system defaults for different file types, but
1918 you can use this variable to set the application for a given file
1919 extension. The entries in this list are cons cells where the car identifies
1920 files and the cdr the corresponding command. Possible values for the
1921 file identifier are
1922 \"string\" A string as a file identifier can be interpreted in different
1923 ways, depending on its contents:
1925 - Alphanumeric characters only:
1926 Match links with this file extension.
1927 Example: (\"pdf\" . \"evince %s\")
1928 to open PDFs with evince.
1930 - Regular expression: Match links where the
1931 filename matches the regexp. If you want to
1932 use groups here, use shy groups.
1934 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1935 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1936 to open *.html and *.xhtml with firefox.
1938 - Regular expression which contains (non-shy) groups:
1939 Match links where the whole link, including \"::\", and
1940 anything after that, matches the regexp.
1941 In a custom command string, %1, %2, etc. are replaced with
1942 the parts of the link that were matched by the groups.
1943 For backwards compatibility, if a command string is given
1944 that does not use any of the group matches, this case is
1945 handled identically to the second one (i.e. match against
1946 file name only).
1947 In a custom lisp form, you can access the group matches with
1948 (match-string n link).
1950 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1951 to open [[file:document.pdf::5]] with evince at page 5.
1953 `directory' Matches a directory
1954 `remote' Matches a remote file, accessible through tramp or efs.
1955 Remote files most likely should be visited through Emacs
1956 because external applications cannot handle such paths.
1957 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1958 so all files Emacs knows how to handle. Using this with
1959 command `emacs' will open most files in Emacs. Beware that this
1960 will also open html files inside Emacs, unless you add
1961 (\"html\" . default) to the list as well.
1962 t Default for files not matched by any of the other options.
1963 `system' The system command to open files, like `open' on Windows
1964 and Mac OS X, and mailcap under GNU/Linux. This is the command
1965 that will be selected if you call `C-c C-o' with a double
1966 \\[universal-argument] \\[universal-argument] prefix.
1968 Possible values for the command are:
1969 `emacs' The file will be visited by the current Emacs process.
1970 `default' Use the default application for this file type, which is the
1971 association for t in the list, most likely in the system-specific
1972 part.
1973 This can be used to overrule an unwanted setting in the
1974 system-specific variable.
1975 `system' Use the system command for opening files, like \"open\".
1976 This command is specified by the entry whose car is `system'.
1977 Most likely, the system-specific version of this variable
1978 does define this command, but you can overrule/replace it
1979 here.
1980 string A command to be executed by a shell; %s will be replaced
1981 by the path to the file.
1982 sexp A Lisp form which will be evaluated. The file path will
1983 be available in the Lisp variable `file'.
1984 For more examples, see the system specific constants
1985 `org-file-apps-defaults-macosx'
1986 `org-file-apps-defaults-windowsnt'
1987 `org-file-apps-defaults-gnu'."
1988 :group 'org-link-follow
1989 :type '(repeat
1990 (cons (choice :value ""
1991 (string :tag "Extension")
1992 (const :tag "System command to open files" system)
1993 (const :tag "Default for unrecognized files" t)
1994 (const :tag "Remote file" remote)
1995 (const :tag "Links to a directory" directory)
1996 (const :tag "Any files that have Emacs modes"
1997 auto-mode))
1998 (choice :value ""
1999 (const :tag "Visit with Emacs" emacs)
2000 (const :tag "Use default" default)
2001 (const :tag "Use the system command" system)
2002 (string :tag "Command")
2003 (sexp :tag "Lisp form")))))
2005 (defcustom org-doi-server-url "http://dx.doi.org/"
2006 "The URL of the DOI server."
2007 :type 'string
2008 :version "24.3"
2009 :group 'org-link-follow)
2011 (defgroup org-refile nil
2012 "Options concerning refiling entries in Org-mode."
2013 :tag "Org Refile"
2014 :group 'org)
2016 (defcustom org-directory "~/org"
2017 "Directory with org files.
2018 This is just a default location to look for Org files. There is no need
2019 at all to put your files into this directory. It is only used in the
2020 following situations:
2022 1. When a capture template specifies a target file that is not an
2023 absolute path. The path will then be interpreted relative to
2024 `org-directory'
2025 2. When a capture note is filed away in an interactive way (when exiting the
2026 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2027 with `org-directory' as the default path."
2028 :group 'org-refile
2029 :group 'org-remember
2030 :group 'org-capture
2031 :type 'directory)
2033 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2034 "Default target for storing notes.
2035 Used as a fall back file for org-remember.el and org-capture.el, for
2036 templates that do not specify a target file."
2037 :group 'org-refile
2038 :group 'org-remember
2039 :group 'org-capture
2040 :type '(choice
2041 (const :tag "Default from remember-data-file" nil)
2042 file))
2044 (defcustom org-goto-interface 'outline
2045 "The default interface to be used for `org-goto'.
2046 Allowed values are:
2047 outline The interface shows an outline of the relevant file
2048 and the correct heading is found by moving through
2049 the outline or by searching with incremental search.
2050 outline-path-completion Headlines in the current buffer are offered via
2051 completion. This is the interface also used by
2052 the refile command."
2053 :group 'org-refile
2054 :type '(choice
2055 (const :tag "Outline" outline)
2056 (const :tag "Outline-path-completion" outline-path-completion)))
2058 (defcustom org-goto-max-level 5
2059 "Maximum target level when running `org-goto' with refile interface."
2060 :group 'org-refile
2061 :type 'integer)
2063 (defcustom org-reverse-note-order nil
2064 "Non-nil means store new notes at the beginning of a file or entry.
2065 When nil, new notes will be filed to the end of a file or entry.
2066 This can also be a list with cons cells of regular expressions that
2067 are matched against file names, and values."
2068 :group 'org-remember
2069 :group 'org-capture
2070 :group 'org-refile
2071 :type '(choice
2072 (const :tag "Reverse always" t)
2073 (const :tag "Reverse never" nil)
2074 (repeat :tag "By file name regexp"
2075 (cons regexp boolean))))
2077 (defcustom org-log-refile nil
2078 "Information to record when a task is refiled.
2080 Possible values are:
2082 nil Don't add anything
2083 time Add a time stamp to the task
2084 note Prompt for a note and add it with template `org-log-note-headings'
2086 This option can also be set with on a per-file-basis with
2088 #+STARTUP: nologrefile
2089 #+STARTUP: logrefile
2090 #+STARTUP: lognoterefile
2092 You can have local logging settings for a subtree by setting the LOGGING
2093 property to one or more of these keywords.
2095 When bulk-refiling from the agenda, the value `note' is forbidden and
2096 will temporarily be changed to `time'."
2097 :group 'org-refile
2098 :group 'org-progress
2099 :version "24.1"
2100 :type '(choice
2101 (const :tag "No logging" nil)
2102 (const :tag "Record timestamp" time)
2103 (const :tag "Record timestamp with note." note)))
2105 (defcustom org-refile-targets nil
2106 "Targets for refiling entries with \\[org-refile].
2107 This is a list of cons cells. Each cell contains:
2108 - a specification of the files to be considered, either a list of files,
2109 or a symbol whose function or variable value will be used to retrieve
2110 a file name or a list of file names. If you use `org-agenda-files' for
2111 that, all agenda files will be scanned for targets. Nil means consider
2112 headings in the current buffer.
2113 - A specification of how to find candidate refile targets. This may be
2114 any of:
2115 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2116 This tag has to be present in all target headlines, inheritance will
2117 not be considered.
2118 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2119 todo keyword.
2120 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2121 headlines that are refiling targets.
2122 - a cons cell (:level . N). Any headline of level N is considered a target.
2123 Note that, when `org-odd-levels-only' is set, level corresponds to
2124 order in hierarchy, not to the number of stars.
2125 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2126 Note that, when `org-odd-levels-only' is set, level corresponds to
2127 order in hierarchy, not to the number of stars.
2129 Each element of this list generates a set of possible targets.
2130 The union of these sets is presented (with completion) to
2131 the user by `org-refile'.
2133 You can set the variable `org-refile-target-verify-function' to a function
2134 to verify each headline found by the simple criteria above.
2136 When this variable is nil, all top-level headlines in the current buffer
2137 are used, equivalent to the value `((nil . (:level . 1))'."
2138 :group 'org-refile
2139 :type '(repeat
2140 (cons
2141 (choice :value org-agenda-files
2142 (const :tag "All agenda files" org-agenda-files)
2143 (const :tag "Current buffer" nil)
2144 (function) (variable) (file))
2145 (choice :tag "Identify target headline by"
2146 (cons :tag "Specific tag" (const :value :tag) (string))
2147 (cons :tag "TODO keyword" (const :value :todo) (string))
2148 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2149 (cons :tag "Level number" (const :value :level) (integer))
2150 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2152 (defcustom org-refile-target-verify-function nil
2153 "Function to verify if the headline at point should be a refile target.
2154 The function will be called without arguments, with point at the
2155 beginning of the headline. It should return t and leave point
2156 where it is if the headline is a valid target for refiling.
2158 If the target should not be selected, the function must return nil.
2159 In addition to this, it may move point to a place from where the search
2160 should be continued. For example, the function may decide that the entire
2161 subtree of the current entry should be excluded and move point to the end
2162 of the subtree."
2163 :group 'org-refile
2164 :type 'function)
2166 (defcustom org-refile-use-cache nil
2167 "Non-nil means cache refile targets to speed up the process.
2168 The cache for a particular file will be updated automatically when
2169 the buffer has been killed, or when any of the marker used for flagging
2170 refile targets no longer points at a live buffer.
2171 If you have added new entries to a buffer that might themselves be targets,
2172 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2173 find that easier, `C-u C-u C-u C-c C-w'."
2174 :group 'org-refile
2175 :version "24.1"
2176 :type 'boolean)
2178 (defcustom org-refile-use-outline-path nil
2179 "Non-nil means provide refile targets as paths.
2180 So a level 3 headline will be available as level1/level2/level3.
2182 When the value is `file', also include the file name (without directory)
2183 into the path. In this case, you can also stop the completion after
2184 the file name, to get entries inserted as top level in the file.
2186 When `full-file-path', include the full file path."
2187 :group 'org-refile
2188 :type '(choice
2189 (const :tag "Not" nil)
2190 (const :tag "Yes" t)
2191 (const :tag "Start with file name" file)
2192 (const :tag "Start with full file path" full-file-path)))
2194 (defcustom org-outline-path-complete-in-steps t
2195 "Non-nil means complete the outline path in hierarchical steps.
2196 When Org-mode uses the refile interface to select an outline path
2197 \(see variable `org-refile-use-outline-path'), the completion of
2198 the path can be done is a single go, or if can be done in steps down
2199 the headline hierarchy. Going in steps is probably the best if you
2200 do not use a special completion package like `ido' or `icicles'.
2201 However, when using these packages, going in one step can be very
2202 fast, while still showing the whole path to the entry."
2203 :group 'org-refile
2204 :type 'boolean)
2206 (defcustom org-refile-allow-creating-parent-nodes nil
2207 "Non-nil means allow to create new nodes as refile targets.
2208 New nodes are then created by adding \"/new node name\" to the completion
2209 of an existing node. When the value of this variable is `confirm',
2210 new node creation must be confirmed by the user (recommended)
2211 When nil, the completion must match an existing entry.
2213 Note that, if the new heading is not seen by the criteria
2214 listed in `org-refile-targets', multiple instances of the same
2215 heading would be created by trying again to file under the new
2216 heading."
2217 :group 'org-refile
2218 :type '(choice
2219 (const :tag "Never" nil)
2220 (const :tag "Always" t)
2221 (const :tag "Prompt for confirmation" confirm)))
2223 (defcustom org-refile-active-region-within-subtree nil
2224 "Non-nil means also refile active region within a subtree.
2226 By default `org-refile' doesn't allow refiling regions if they
2227 don't contain a set of subtrees, but it might be convenient to
2228 do so sometimes: in that case, the first line of the region is
2229 converted to a headline before refiling."
2230 :group 'org-refile
2231 :version "24.1"
2232 :type 'boolean)
2234 (defgroup org-todo nil
2235 "Options concerning TODO items in Org-mode."
2236 :tag "Org TODO"
2237 :group 'org)
2239 (defgroup org-progress nil
2240 "Options concerning Progress logging in Org-mode."
2241 :tag "Org Progress"
2242 :group 'org-time)
2244 (defvar org-todo-interpretation-widgets
2245 '((:tag "Sequence (cycling hits every state)" sequence)
2246 (:tag "Type (cycling directly to DONE)" type))
2247 "The available interpretation symbols for customizing `org-todo-keywords'.
2248 Interested libraries should add to this list.")
2250 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2251 "List of TODO entry keyword sequences and their interpretation.
2252 \\<org-mode-map>This is a list of sequences.
2254 Each sequence starts with a symbol, either `sequence' or `type',
2255 indicating if the keywords should be interpreted as a sequence of
2256 action steps, or as different types of TODO items. The first
2257 keywords are states requiring action - these states will select a headline
2258 for inclusion into the global TODO list Org-mode produces. If one of
2259 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2260 signify that no further action is necessary. If \"|\" is not found,
2261 the last keyword is treated as the only DONE state of the sequence.
2263 The command \\[org-todo] cycles an entry through these states, and one
2264 additional state where no keyword is present. For details about this
2265 cycling, see the manual.
2267 TODO keywords and interpretation can also be set on a per-file basis with
2268 the special #+SEQ_TODO and #+TYP_TODO lines.
2270 Each keyword can optionally specify a character for fast state selection
2271 \(in combination with the variable `org-use-fast-todo-selection')
2272 and specifiers for state change logging, using the same syntax that
2273 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2274 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2275 indicates to record a time stamp each time this state is selected.
2277 Each keyword may also specify if a timestamp or a note should be
2278 recorded when entering or leaving the state, by adding additional
2279 characters in the parenthesis after the keyword. This looks like this:
2280 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2281 record only the time of the state change. With X and Y being either
2282 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2283 Y when leaving the state if and only if the *target* state does not
2284 define X. You may omit any of the fast-selection key or X or /Y,
2285 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2287 For backward compatibility, this variable may also be just a list
2288 of keywords. In this case the interpretation (sequence or type) will be
2289 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2290 :group 'org-todo
2291 :group 'org-keywords
2292 :type '(choice
2293 (repeat :tag "Old syntax, just keywords"
2294 (string :tag "Keyword"))
2295 (repeat :tag "New syntax"
2296 (cons
2297 (choice
2298 :tag "Interpretation"
2299 ;;Quick and dirty way to see
2300 ;;`org-todo-interpretations'. This takes the
2301 ;;place of item arguments
2302 :convert-widget
2303 (lambda (widget)
2304 (widget-put widget
2305 :args (mapcar
2306 #'(lambda (x)
2307 (widget-convert
2308 (cons 'const x)))
2309 org-todo-interpretation-widgets))
2310 widget))
2311 (repeat
2312 (string :tag "Keyword"))))))
2314 (defvar org-todo-keywords-1 nil
2315 "All TODO and DONE keywords active in a buffer.")
2316 (make-variable-buffer-local 'org-todo-keywords-1)
2317 (defvar org-todo-keywords-for-agenda nil)
2318 (defvar org-done-keywords-for-agenda nil)
2319 (defvar org-drawers-for-agenda nil)
2320 (defvar org-todo-keyword-alist-for-agenda nil)
2321 (defvar org-tag-alist-for-agenda nil
2322 "Alist of all tags from all agenda files.")
2323 (defvar org-tag-groups-alist-for-agenda nil
2324 "Alist of all groups tags from all current agenda files.")
2325 (defvar org-tag-groups-alist nil)
2326 (make-variable-buffer-local 'org-tag-groups-alist)
2327 (defvar org-agenda-contributing-files nil)
2328 (defvar org-not-done-keywords nil)
2329 (make-variable-buffer-local 'org-not-done-keywords)
2330 (defvar org-done-keywords nil)
2331 (make-variable-buffer-local 'org-done-keywords)
2332 (defvar org-todo-heads nil)
2333 (make-variable-buffer-local 'org-todo-heads)
2334 (defvar org-todo-sets nil)
2335 (make-variable-buffer-local 'org-todo-sets)
2336 (defvar org-todo-log-states nil)
2337 (make-variable-buffer-local 'org-todo-log-states)
2338 (defvar org-todo-kwd-alist nil)
2339 (make-variable-buffer-local 'org-todo-kwd-alist)
2340 (defvar org-todo-key-alist nil)
2341 (make-variable-buffer-local 'org-todo-key-alist)
2342 (defvar org-todo-key-trigger nil)
2343 (make-variable-buffer-local 'org-todo-key-trigger)
2345 (defcustom org-todo-interpretation 'sequence
2346 "Controls how TODO keywords are interpreted.
2347 This variable is in principle obsolete and is only used for
2348 backward compatibility, if the interpretation of todo keywords is
2349 not given already in `org-todo-keywords'. See that variable for
2350 more information."
2351 :group 'org-todo
2352 :group 'org-keywords
2353 :type '(choice (const sequence)
2354 (const type)))
2356 (defcustom org-use-fast-todo-selection t
2357 "Non-nil means use the fast todo selection scheme with C-c C-t.
2358 This variable describes if and under what circumstances the cycling
2359 mechanism for TODO keywords will be replaced by a single-key, direct
2360 selection scheme.
2362 When nil, fast selection is never used.
2364 When the symbol `prefix', it will be used when `org-todo' is called
2365 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2366 `C-u t' in an agenda buffer.
2368 When t, fast selection is used by default. In this case, the prefix
2369 argument forces cycling instead.
2371 In all cases, the special interface is only used if access keys have
2372 actually been assigned by the user, i.e. if keywords in the configuration
2373 are followed by a letter in parenthesis, like TODO(t)."
2374 :group 'org-todo
2375 :type '(choice
2376 (const :tag "Never" nil)
2377 (const :tag "By default" t)
2378 (const :tag "Only with C-u C-c C-t" prefix)))
2380 (defcustom org-provide-todo-statistics t
2381 "Non-nil means update todo statistics after insert and toggle.
2382 ALL-HEADLINES means update todo statistics by including headlines
2383 with no TODO keyword as well, counting them as not done.
2384 A list of TODO keywords means the same, but skip keywords that are
2385 not in this list.
2387 When this is set, todo statistics is updated in the parent of the
2388 current entry each time a todo state is changed."
2389 :group 'org-todo
2390 :type '(choice
2391 (const :tag "Yes, only for TODO entries" t)
2392 (const :tag "Yes, including all entries" 'all-headlines)
2393 (repeat :tag "Yes, for TODOs in this list"
2394 (string :tag "TODO keyword"))
2395 (other :tag "No TODO statistics" nil)))
2397 (defcustom org-hierarchical-todo-statistics t
2398 "Non-nil means TODO statistics covers just direct children.
2399 When nil, all entries in the subtree are considered.
2400 This has only an effect if `org-provide-todo-statistics' is set.
2401 To set this to nil for only a single subtree, use a COOKIE_DATA
2402 property and include the word \"recursive\" into the value."
2403 :group 'org-todo
2404 :type 'boolean)
2406 (defcustom org-after-todo-state-change-hook nil
2407 "Hook which is run after the state of a TODO item was changed.
2408 The new state (a string with a TODO keyword, or nil) is available in the
2409 Lisp variable `org-state'."
2410 :group 'org-todo
2411 :type 'hook)
2413 (defvar org-blocker-hook nil
2414 "Hook for functions that are allowed to block a state change.
2416 Functions in this hook should not modify the buffer.
2417 Each function gets as its single argument a property list,
2418 see `org-trigger-hook' for more information about this list.
2420 If any of the functions in this hook returns nil, the state change
2421 is blocked.")
2423 (defvar org-trigger-hook nil
2424 "Hook for functions that are triggered by a state change.
2426 Each function gets as its single argument a property list with at
2427 least the following elements:
2429 (:type type-of-change :position pos-at-entry-start
2430 :from old-state :to new-state)
2432 Depending on the type, more properties may be present.
2434 This mechanism is currently implemented for:
2436 TODO state changes
2437 ------------------
2438 :type todo-state-change
2439 :from previous state (keyword as a string), or nil, or a symbol
2440 'todo' or 'done', to indicate the general type of state.
2441 :to new state, like in :from")
2443 (defcustom org-enforce-todo-dependencies nil
2444 "Non-nil means undone TODO entries will block switching the parent to DONE.
2445 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2446 be blocked if any prior sibling is not yet done.
2447 Finally, if the parent is blocked because of ordered siblings of its own,
2448 the child will also be blocked."
2449 :set (lambda (var val)
2450 (set var val)
2451 (if val
2452 (add-hook 'org-blocker-hook
2453 'org-block-todo-from-children-or-siblings-or-parent)
2454 (remove-hook 'org-blocker-hook
2455 'org-block-todo-from-children-or-siblings-or-parent)))
2456 :group 'org-todo
2457 :type 'boolean)
2459 (defcustom org-enforce-todo-checkbox-dependencies nil
2460 "Non-nil means unchecked boxes will block switching the parent to DONE.
2461 When this is nil, checkboxes have no influence on switching TODO states.
2462 When non-nil, you first need to check off all check boxes before the TODO
2463 entry can be switched to DONE.
2464 This variable needs to be set before org.el is loaded, and you need to
2465 restart Emacs after a change to make the change effective. The only way
2466 to change is while Emacs is running is through the customize interface."
2467 :set (lambda (var val)
2468 (set var val)
2469 (if val
2470 (add-hook 'org-blocker-hook
2471 'org-block-todo-from-checkboxes)
2472 (remove-hook 'org-blocker-hook
2473 'org-block-todo-from-checkboxes)))
2474 :group 'org-todo
2475 :type 'boolean)
2477 (defcustom org-treat-insert-todo-heading-as-state-change nil
2478 "Non-nil means inserting a TODO heading is treated as state change.
2479 So when the command \\[org-insert-todo-heading] is used, state change
2480 logging will apply if appropriate. When nil, the new TODO item will
2481 be inserted directly, and no logging will take place."
2482 :group 'org-todo
2483 :type 'boolean)
2485 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2486 "Non-nil means switching TODO states with S-cursor counts as state change.
2487 This is the default behavior. However, setting this to nil allows a
2488 convenient way to select a TODO state and bypass any logging associated
2489 with that."
2490 :group 'org-todo
2491 :type 'boolean)
2493 (defcustom org-todo-state-tags-triggers nil
2494 "Tag changes that should be triggered by TODO state changes.
2495 This is a list. Each entry is
2497 (state-change (tag . flag) .......)
2499 State-change can be a string with a state, and empty string to indicate the
2500 state that has no TODO keyword, or it can be one of the symbols `todo'
2501 or `done', meaning any not-done or done state, respectively."
2502 :group 'org-todo
2503 :group 'org-tags
2504 :type '(repeat
2505 (cons (choice :tag "When changing to"
2506 (const :tag "Not-done state" todo)
2507 (const :tag "Done state" done)
2508 (string :tag "State"))
2509 (repeat
2510 (cons :tag "Tag action"
2511 (string :tag "Tag")
2512 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2514 (defcustom org-log-done nil
2515 "Information to record when a task moves to the DONE state.
2517 Possible values are:
2519 nil Don't add anything, just change the keyword
2520 time Add a time stamp to the task
2521 note Prompt for a note and add it with template `org-log-note-headings'
2523 This option can also be set with on a per-file-basis with
2525 #+STARTUP: nologdone
2526 #+STARTUP: logdone
2527 #+STARTUP: lognotedone
2529 You can have local logging settings for a subtree by setting the LOGGING
2530 property to one or more of these keywords."
2531 :group 'org-todo
2532 :group 'org-progress
2533 :type '(choice
2534 (const :tag "No logging" nil)
2535 (const :tag "Record CLOSED timestamp" time)
2536 (const :tag "Record CLOSED timestamp with note." note)))
2538 ;; Normalize old uses of org-log-done.
2539 (cond
2540 ((eq org-log-done t) (setq org-log-done 'time))
2541 ((and (listp org-log-done) (memq 'done org-log-done))
2542 (setq org-log-done 'note)))
2544 (defcustom org-log-reschedule nil
2545 "Information to record when the scheduling date of a tasks is modified.
2547 Possible values are:
2549 nil Don't add anything, just change the date
2550 time Add a time stamp to the task
2551 note Prompt for a note and add it with template `org-log-note-headings'
2553 This option can also be set with on a per-file-basis with
2555 #+STARTUP: nologreschedule
2556 #+STARTUP: logreschedule
2557 #+STARTUP: lognotereschedule"
2558 :group 'org-todo
2559 :group 'org-progress
2560 :type '(choice
2561 (const :tag "No logging" nil)
2562 (const :tag "Record timestamp" time)
2563 (const :tag "Record timestamp with note." note)))
2565 (defcustom org-log-redeadline nil
2566 "Information to record when the deadline date of a tasks is modified.
2568 Possible values are:
2570 nil Don't add anything, just change the date
2571 time Add a time stamp to the task
2572 note Prompt for a note and add it with template `org-log-note-headings'
2574 This option can also be set with on a per-file-basis with
2576 #+STARTUP: nologredeadline
2577 #+STARTUP: logredeadline
2578 #+STARTUP: lognoteredeadline
2580 You can have local logging settings for a subtree by setting the LOGGING
2581 property to one or more of these keywords."
2582 :group 'org-todo
2583 :group 'org-progress
2584 :type '(choice
2585 (const :tag "No logging" nil)
2586 (const :tag "Record timestamp" time)
2587 (const :tag "Record timestamp with note." note)))
2589 (defcustom org-log-note-clock-out nil
2590 "Non-nil means record a note when clocking out of an item.
2591 This can also be configured on a per-file basis by adding one of
2592 the following lines anywhere in the buffer:
2594 #+STARTUP: lognoteclock-out
2595 #+STARTUP: nolognoteclock-out"
2596 :group 'org-todo
2597 :group 'org-progress
2598 :type 'boolean)
2600 (defcustom org-log-done-with-time t
2601 "Non-nil means the CLOSED time stamp will contain date and time.
2602 When nil, only the date will be recorded."
2603 :group 'org-progress
2604 :type 'boolean)
2606 (defcustom org-log-note-headings
2607 '((done . "CLOSING NOTE %t")
2608 (state . "State %-12s from %-12S %t")
2609 (note . "Note taken on %t")
2610 (reschedule . "Rescheduled from %S on %t")
2611 (delschedule . "Not scheduled, was %S on %t")
2612 (redeadline . "New deadline from %S on %t")
2613 (deldeadline . "Removed deadline, was %S on %t")
2614 (refile . "Refiled on %t")
2615 (clock-out . ""))
2616 "Headings for notes added to entries.
2617 The value is an alist, with the car being a symbol indicating the note
2618 context, and the cdr is the heading to be used. The heading may also be the
2619 empty string.
2620 %t in the heading will be replaced by a time stamp.
2621 %T will be an active time stamp instead the default inactive one
2622 %d will be replaced by a short-format time stamp.
2623 %D will be replaced by an active short-format time stamp.
2624 %s will be replaced by the new TODO state, in double quotes.
2625 %S will be replaced by the old TODO state, in double quotes.
2626 %u will be replaced by the user name.
2627 %U will be replaced by the full user name.
2629 In fact, it is not a good idea to change the `state' entry, because
2630 agenda log mode depends on the format of these entries."
2631 :group 'org-todo
2632 :group 'org-progress
2633 :type '(list :greedy t
2634 (cons (const :tag "Heading when closing an item" done) string)
2635 (cons (const :tag
2636 "Heading when changing todo state (todo sequence only)"
2637 state) string)
2638 (cons (const :tag "Heading when just taking a note" note) string)
2639 (cons (const :tag "Heading when clocking out" clock-out) string)
2640 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2641 (cons (const :tag "Heading when rescheduling" reschedule) string)
2642 (cons (const :tag "Heading when changing deadline" redeadline) string)
2643 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2644 (cons (const :tag "Heading when refiling" refile) string)))
2646 (unless (assq 'note org-log-note-headings)
2647 (push '(note . "%t") org-log-note-headings))
2649 (defcustom org-log-into-drawer nil
2650 "Non-nil means insert state change notes and time stamps into a drawer.
2651 When nil, state changes notes will be inserted after the headline and
2652 any scheduling and clock lines, but not inside a drawer.
2654 The value of this variable should be the name of the drawer to use.
2655 LOGBOOK is proposed as the default drawer for this purpose, you can
2656 also set this to a string to define the drawer of your choice.
2658 A value of t is also allowed, representing \"LOGBOOK\".
2660 A value of t or nil can also be set with on a per-file-basis with
2662 #+STARTUP: logdrawer
2663 #+STARTUP: nologdrawer
2665 If this variable is set, `org-log-state-notes-insert-after-drawers'
2666 will be ignored.
2668 You can set the property LOG_INTO_DRAWER to overrule this setting for
2669 a subtree."
2670 :group 'org-todo
2671 :group 'org-progress
2672 :type '(choice
2673 (const :tag "Not into a drawer" nil)
2674 (const :tag "LOGBOOK" t)
2675 (string :tag "Other")))
2677 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2679 (defun org-log-into-drawer ()
2680 "Return the value of `org-log-into-drawer', but let properties overrule.
2681 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2682 used instead of the default value."
2683 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2684 (cond
2685 ((not p) org-log-into-drawer)
2686 ((equal p "nil") nil)
2687 ((equal p "t") "LOGBOOK")
2688 (t p))))
2690 (defcustom org-log-state-notes-insert-after-drawers nil
2691 "Non-nil means insert state change notes after any drawers in entry.
2692 Only the drawers that *immediately* follow the headline and the
2693 deadline/scheduled line are skipped.
2694 When nil, insert notes right after the heading and perhaps the line
2695 with deadline/scheduling if present.
2697 This variable will have no effect if `org-log-into-drawer' is
2698 set."
2699 :group 'org-todo
2700 :group 'org-progress
2701 :type 'boolean)
2703 (defcustom org-log-states-order-reversed t
2704 "Non-nil means the latest state note will be directly after heading.
2705 When nil, the state change notes will be ordered according to time.
2707 This option can also be set with on a per-file-basis with
2709 #+STARTUP: logstatesreversed
2710 #+STARTUP: nologstatesreversed"
2711 :group 'org-todo
2712 :group 'org-progress
2713 :type 'boolean)
2715 (defcustom org-todo-repeat-to-state nil
2716 "The TODO state to which a repeater should return the repeating task.
2717 By default this is the first task in a TODO sequence, or the previous state
2718 in a TODO_TYP set. But you can specify another task here.
2719 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2720 :group 'org-todo
2721 :version "24.1"
2722 :type '(choice (const :tag "Head of sequence" nil)
2723 (string :tag "Specific state")))
2725 (defcustom org-log-repeat 'time
2726 "Non-nil means record moving through the DONE state when triggering repeat.
2727 An auto-repeating task is immediately switched back to TODO when
2728 marked DONE. If you are not logging state changes (by adding \"@\"
2729 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2730 record a closing note, there will be no record of the task moving
2731 through DONE. This variable forces taking a note anyway.
2733 nil Don't force a record
2734 time Record a time stamp
2735 note Prompt for a note and add it with template `org-log-note-headings'
2737 This option can also be set with on a per-file-basis with
2739 #+STARTUP: nologrepeat
2740 #+STARTUP: logrepeat
2741 #+STARTUP: lognoterepeat
2743 You can have local logging settings for a subtree by setting the LOGGING
2744 property to one or more of these keywords."
2745 :group 'org-todo
2746 :group 'org-progress
2747 :type '(choice
2748 (const :tag "Don't force a record" nil)
2749 (const :tag "Force recording the DONE state" time)
2750 (const :tag "Force recording a note with the DONE state" note)))
2753 (defgroup org-priorities nil
2754 "Priorities in Org-mode."
2755 :tag "Org Priorities"
2756 :group 'org-todo)
2758 (defcustom org-enable-priority-commands t
2759 "Non-nil means priority commands are active.
2760 When nil, these commands will be disabled, so that you never accidentally
2761 set a priority."
2762 :group 'org-priorities
2763 :type 'boolean)
2765 (defcustom org-highest-priority ?A
2766 "The highest priority of TODO items. A character like ?A, ?B etc.
2767 Must have a smaller ASCII number than `org-lowest-priority'."
2768 :group 'org-priorities
2769 :type 'character)
2771 (defcustom org-lowest-priority ?C
2772 "The lowest priority of TODO items. A character like ?A, ?B etc.
2773 Must have a larger ASCII number than `org-highest-priority'."
2774 :group 'org-priorities
2775 :type 'character)
2777 (defcustom org-default-priority ?B
2778 "The default priority of TODO items.
2779 This is the priority an item gets if no explicit priority is given.
2780 When starting to cycle on an empty priority the first step in the cycle
2781 depends on `org-priority-start-cycle-with-default'. The resulting first
2782 step priority must not exceed the range from `org-highest-priority' to
2783 `org-lowest-priority' which means that `org-default-priority' has to be
2784 in this range exclusive or inclusive the range boundaries. Else the
2785 first step refuses to set the default and the second will fall back
2786 to (depending on the command used) the highest or lowest priority."
2787 :group 'org-priorities
2788 :type 'character)
2790 (defcustom org-priority-start-cycle-with-default t
2791 "Non-nil means start with default priority when starting to cycle.
2792 When this is nil, the first step in the cycle will be (depending on the
2793 command used) one higher or lower than the default priority.
2794 See also `org-default-priority'."
2795 :group 'org-priorities
2796 :type 'boolean)
2798 (defcustom org-get-priority-function nil
2799 "Function to extract the priority from a string.
2800 The string is normally the headline. If this is nil Org computes the
2801 priority from the priority cookie like [#A] in the headline. It returns
2802 an integer, increasing by 1000 for each priority level.
2803 The user can set a different function here, which should take a string
2804 as an argument and return the numeric priority."
2805 :group 'org-priorities
2806 :version "24.1"
2807 :type 'function)
2809 (defgroup org-time nil
2810 "Options concerning time stamps and deadlines in Org-mode."
2811 :tag "Org Time"
2812 :group 'org)
2814 (defcustom org-insert-labeled-timestamps-at-point nil
2815 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2816 When nil, these labeled time stamps are forces into the second line of an
2817 entry, just after the headline. When scheduling from the global TODO list,
2818 the time stamp will always be forced into the second line."
2819 :group 'org-time
2820 :type 'boolean)
2822 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2823 "Formats for `format-time-string' which are used for time stamps.
2824 It is not recommended to change this constant.")
2826 (defcustom org-time-stamp-rounding-minutes '(0 5)
2827 "Number of minutes to round time stamps to.
2828 These are two values, the first applies when first creating a time stamp.
2829 The second applies when changing it with the commands `S-up' and `S-down'.
2830 When changing the time stamp, this means that it will change in steps
2831 of N minutes, as given by the second value.
2833 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2834 numbers should be factors of 60, so for example 5, 10, 15.
2836 When this is larger than 1, you can still force an exact time stamp by using
2837 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2838 and by using a prefix arg to `S-up/down' to specify the exact number
2839 of minutes to shift."
2840 :group 'org-time
2841 :get #'(lambda (var) ; Make sure both elements are there
2842 (if (integerp (default-value var))
2843 (list (default-value var) 5)
2844 (default-value var)))
2845 :type '(list
2846 (integer :tag "when inserting times")
2847 (integer :tag "when modifying times")))
2849 ;; Normalize old customizations of this variable.
2850 (when (integerp org-time-stamp-rounding-minutes)
2851 (setq org-time-stamp-rounding-minutes
2852 (list org-time-stamp-rounding-minutes
2853 org-time-stamp-rounding-minutes)))
2855 (defcustom org-display-custom-times nil
2856 "Non-nil means overlay custom formats over all time stamps.
2857 The formats are defined through the variable `org-time-stamp-custom-formats'.
2858 To turn this on on a per-file basis, insert anywhere in the file:
2859 #+STARTUP: customtime"
2860 :group 'org-time
2861 :set 'set-default
2862 :type 'sexp)
2863 (make-variable-buffer-local 'org-display-custom-times)
2865 (defcustom org-time-stamp-custom-formats
2866 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2867 "Custom formats for time stamps. See `format-time-string' for the syntax.
2868 These are overlaid over the default ISO format if the variable
2869 `org-display-custom-times' is set. Time like %H:%M should be at the
2870 end of the second format. The custom formats are also honored by export
2871 commands, if custom time display is turned on at the time of export."
2872 :group 'org-time
2873 :type 'sexp)
2875 (defun org-time-stamp-format (&optional long inactive)
2876 "Get the right format for a time string."
2877 (let ((f (if long (cdr org-time-stamp-formats)
2878 (car org-time-stamp-formats))))
2879 (if inactive
2880 (concat "[" (substring f 1 -1) "]")
2881 f)))
2883 (defcustom org-time-clocksum-format
2884 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2885 "The format string used when creating CLOCKSUM lines.
2886 This is also used when Org mode generates a time duration.
2888 The value can be a single format string containing two
2889 %-sequences, which will be filled with the number of hours and
2890 minutes in that order.
2892 Alternatively, the value can be a plist associating any of the
2893 keys :years, :months, :weeks, :days, :hours or :minutes with
2894 format strings. The time duration is formatted using only the
2895 time components that are needed and concatenating the results.
2896 If a time unit in absent, it falls back to the next smallest
2897 unit.
2899 The keys :require-years, :require-months, :require-days,
2900 :require-weeks, :require-hours, :require-minutes are also
2901 meaningful. A non-nil value for these keys indicates that the
2902 corresponding time component should always be included, even if
2903 its value is 0.
2906 For example,
2908 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2909 :require-minutes t)
2911 means durations longer than a day will be expressed in days,
2912 hours and minutes, and durations less than a day will always be
2913 expressed in hours and minutes (even for durations less than an
2914 hour).
2916 The value
2918 \(:days \"%dd\" :minutes \"%dm\")
2920 means durations longer than a day will be expressed in days and
2921 minutes, and durations less than a day will be expressed entirely
2922 in minutes (even for durations longer than an hour)."
2923 :group 'org-time
2924 :group 'org-clock
2925 :version "24.4"
2926 :package-version '(Org . "8.0")
2927 :type '(choice (string :tag "Format string")
2928 (set :tag "Plist"
2929 (group :inline t (const :tag "Years" :years)
2930 (string :tag "Format string"))
2931 (group :inline t
2932 (const :tag "Always show years" :require-years)
2933 (const t))
2934 (group :inline t (const :tag "Months" :months)
2935 (string :tag "Format string"))
2936 (group :inline t
2937 (const :tag "Always show months" :require-months)
2938 (const t))
2939 (group :inline t (const :tag "Weeks" :weeks)
2940 (string :tag "Format string"))
2941 (group :inline t
2942 (const :tag "Always show weeks" :require-weeks)
2943 (const t))
2944 (group :inline t (const :tag "Days" :days)
2945 (string :tag "Format string"))
2946 (group :inline t
2947 (const :tag "Always show days" :require-days)
2948 (const t))
2949 (group :inline t (const :tag "Hours" :hours)
2950 (string :tag "Format string"))
2951 (group :inline t
2952 (const :tag "Always show hours" :require-hours)
2953 (const t))
2954 (group :inline t (const :tag "Minutes" :minutes)
2955 (string :tag "Format string"))
2956 (group :inline t
2957 (const :tag "Always show minutes" :require-minutes)
2958 (const t)))))
2960 (defcustom org-time-clocksum-use-fractional nil
2961 "When non-nil, \\[org-clock-display] uses fractional times.
2962 See `org-time-clocksum-format' for more on time clock formats."
2963 :group 'org-time
2964 :group 'org-clock
2965 :version "24.3"
2966 :type 'boolean)
2968 (defcustom org-time-clocksum-use-effort-durations nil
2969 "When non-nil, \\[org-clock-display] uses effort durations.
2970 E.g. by default, one day is considered to be a 8 hours effort,
2971 so a task that has been clocked for 16 hours will be displayed
2972 as during 2 days in the clock display or in the clocktable.
2974 See `org-effort-durations' on how to set effort durations
2975 and `org-time-clocksum-format' for more on time clock formats."
2976 :group 'org-time
2977 :group 'org-clock
2978 :version "24.4"
2979 :package-version '(Org . "8.0")
2980 :type 'boolean)
2982 (defcustom org-time-clocksum-fractional-format "%.2f"
2983 "The format string used when creating CLOCKSUM lines,
2984 or when Org mode generates a time duration, if
2985 `org-time-clocksum-use-fractional' is enabled.
2987 The value can be a single format string containing one
2988 %-sequence, which will be filled with the number of hours as
2989 a float.
2991 Alternatively, the value can be a plist associating any of the
2992 keys :years, :months, :weeks, :days, :hours or :minutes with
2993 a format string. The time duration is formatted using the
2994 largest time unit which gives a non-zero integer part. If all
2995 specified formats have zero integer part, the smallest time unit
2996 is used."
2997 :group 'org-time
2998 :type '(choice (string :tag "Format string")
2999 (set (group :inline t (const :tag "Years" :years)
3000 (string :tag "Format string"))
3001 (group :inline t (const :tag "Months" :months)
3002 (string :tag "Format string"))
3003 (group :inline t (const :tag "Weeks" :weeks)
3004 (string :tag "Format string"))
3005 (group :inline t (const :tag "Days" :days)
3006 (string :tag "Format string"))
3007 (group :inline t (const :tag "Hours" :hours)
3008 (string :tag "Format string"))
3009 (group :inline t (const :tag "Minutes" :minutes)
3010 (string :tag "Format string")))))
3012 (defcustom org-deadline-warning-days 14
3013 "Number of days before expiration during which a deadline becomes active.
3014 This variable governs the display in sparse trees and in the agenda.
3015 When 0 or negative, it means use this number (the absolute value of it)
3016 even if a deadline has a different individual lead time specified.
3018 Custom commands can set this variable in the options section."
3019 :group 'org-time
3020 :group 'org-agenda-daily/weekly
3021 :type 'integer)
3023 (defcustom org-scheduled-delay-days 0
3024 "Number of days before a scheduled item becomes active.
3025 This variable governs the display in sparse trees and in the agenda.
3026 The default value (i.e. 0) means: don't delay scheduled item.
3027 When negative, it means use this number (the absolute value of it)
3028 even if a scheduled item has a different individual delay time
3029 specified.
3031 Custom commands can set this variable in the options section."
3032 :group 'org-time
3033 :group 'org-agenda-daily/weekly
3034 :version "24.4"
3035 :package-version '(Org . "8.0")
3036 :type 'integer)
3038 (defcustom org-read-date-prefer-future t
3039 "Non-nil means assume future for incomplete date input from user.
3040 This affects the following situations:
3041 1. The user gives a month but not a year.
3042 For example, if it is April and you enter \"feb 2\", this will be read
3043 as Feb 2, *next* year. \"May 5\", however, will be this year.
3044 2. The user gives a day, but no month.
3045 For example, if today is the 15th, and you enter \"3\", Org-mode will
3046 read this as the third of *next* month. However, if you enter \"17\",
3047 it will be considered as *this* month.
3049 If you set this variable to the symbol `time', then also the following
3050 will work:
3052 3. If the user gives a time.
3053 If the time is before now, it will be interpreted as tomorrow.
3055 Currently none of this works for ISO week specifications.
3057 When this option is nil, the current day, month and year will always be
3058 used as defaults.
3060 See also `org-agenda-jump-prefer-future'."
3061 :group 'org-time
3062 :type '(choice
3063 (const :tag "Never" nil)
3064 (const :tag "Check month and day" t)
3065 (const :tag "Check month, day, and time" time)))
3067 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3068 "Should the agenda jump command prefer the future for incomplete dates?
3069 The default is to do the same as configured in `org-read-date-prefer-future'.
3070 But you can also set a deviating value here.
3071 This may t or nil, or the symbol `org-read-date-prefer-future'."
3072 :group 'org-agenda
3073 :group 'org-time
3074 :version "24.1"
3075 :type '(choice
3076 (const :tag "Use org-read-date-prefer-future"
3077 org-read-date-prefer-future)
3078 (const :tag "Never" nil)
3079 (const :tag "Always" t)))
3081 (defcustom org-read-date-force-compatible-dates t
3082 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3084 Depending on the system Emacs is running on, certain dates cannot
3085 be represented with the type used internally to represent time.
3086 Dates between 1970-1-1 and 2038-1-1 can always be represented
3087 correctly. Some systems allow for earlier dates, some for later,
3088 some for both. One way to find out it to insert any date into an
3089 Org buffer, putting the cursor on the year and hitting S-up and
3090 S-down to test the range.
3092 When this variable is set to t, the date/time prompt will not let
3093 you specify dates outside the 1970-2037 range, so it is certain that
3094 these dates will work in whatever version of Emacs you are
3095 running, and also that you can move a file from one Emacs implementation
3096 to another. WHenever Org is forcing the year for you, it will display
3097 a message and beep.
3099 When this variable is nil, Org will check if the date is
3100 representable in the specific Emacs implementation you are using.
3101 If not, it will force a year, usually the current year, and beep
3102 to remind you. Currently this setting is not recommended because
3103 the likelihood that you will open your Org files in an Emacs that
3104 has limited date range is not negligible.
3106 A workaround for this problem is to use diary sexp dates for time
3107 stamps outside of this range."
3108 :group 'org-time
3109 :version "24.1"
3110 :type 'boolean)
3112 (defcustom org-read-date-display-live t
3113 "Non-nil means display current interpretation of date prompt live.
3114 This display will be in an overlay, in the minibuffer."
3115 :group 'org-time
3116 :type 'boolean)
3118 (defcustom org-read-date-popup-calendar t
3119 "Non-nil means pop up a calendar when prompting for a date.
3120 In the calendar, the date can be selected with mouse-1. However, the
3121 minibuffer will also be active, and you can simply enter the date as well.
3122 When nil, only the minibuffer will be available."
3123 :group 'org-time
3124 :type 'boolean)
3125 (org-defvaralias 'org-popup-calendar-for-date-prompt
3126 'org-read-date-popup-calendar)
3128 (make-obsolete-variable
3129 'org-read-date-minibuffer-setup-hook
3130 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3131 (defcustom org-read-date-minibuffer-setup-hook nil
3132 "Hook to be used to set up keys for the date/time interface.
3133 Add key definitions to `minibuffer-local-map', which will be a
3134 temporary copy.
3136 WARNING: This option is obsolete, you should use
3137 `org-read-date-minibuffer-local-map' to set up keys."
3138 :group 'org-time
3139 :type 'hook)
3141 (defcustom org-extend-today-until 0
3142 "The hour when your day really ends. Must be an integer.
3143 This has influence for the following applications:
3144 - When switching the agenda to \"today\". It it is still earlier than
3145 the time given here, the day recognized as TODAY is actually yesterday.
3146 - When a date is read from the user and it is still before the time given
3147 here, the current date and time will be assumed to be yesterday, 23:59.
3148 Also, timestamps inserted in capture templates follow this rule.
3150 IMPORTANT: This is a feature whose implementation is and likely will
3151 remain incomplete. Really, it is only here because past midnight seems to
3152 be the favorite working time of John Wiegley :-)"
3153 :group 'org-time
3154 :type 'integer)
3156 (defcustom org-use-effective-time nil
3157 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3158 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3159 \"effective time\" of any timestamps between midnight and 8am will be
3160 23:59 of the previous day."
3161 :group 'org-time
3162 :version "24.1"
3163 :type 'boolean)
3165 (defcustom org-use-last-clock-out-time-as-effective-time nil
3166 "When non-nil, use the last clock out time for `org-todo'.
3167 Note that this option has precedence over the combined use of
3168 `org-use-effective-time' and `org-extend-today-until'."
3169 :group 'org-time
3170 :version "24.4"
3171 :package-version '(Org . "8.0")
3172 :type 'boolean)
3174 (defcustom org-edit-timestamp-down-means-later nil
3175 "Non-nil means S-down will increase the time in a time stamp.
3176 When nil, S-up will increase."
3177 :group 'org-time
3178 :type 'boolean)
3180 (defcustom org-calendar-follow-timestamp-change t
3181 "Non-nil means make the calendar window follow timestamp changes.
3182 When a timestamp is modified and the calendar window is visible, it will be
3183 moved to the new date."
3184 :group 'org-time
3185 :type 'boolean)
3187 (defgroup org-tags nil
3188 "Options concerning tags in Org-mode."
3189 :tag "Org Tags"
3190 :group 'org)
3192 (defcustom org-tag-alist nil
3193 "List of tags allowed in Org-mode files.
3194 When this list is nil, Org-mode will base TAG input on what is already in the
3195 buffer.
3196 The value of this variable is an alist, the car of each entry must be a
3197 keyword as a string, the cdr may be a character that is used to select
3198 that tag through the fast-tag-selection interface.
3199 See the manual for details."
3200 :group 'org-tags
3201 :type '(repeat
3202 (choice
3203 (cons (string :tag "Tag name")
3204 (character :tag "Access char"))
3205 (list :tag "Start radio group"
3206 (const :startgroup)
3207 (option (string :tag "Group description")))
3208 (list :tag "Group tags delimiter"
3209 (const :grouptags))
3210 (list :tag "End radio group"
3211 (const :endgroup)
3212 (option (string :tag "Group description")))
3213 (const :tag "New line" (:newline)))))
3215 (defcustom org-tag-persistent-alist nil
3216 "List of tags that will always appear in all Org-mode files.
3217 This is in addition to any in buffer settings or customizations
3218 of `org-tag-alist'.
3219 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3220 The value of this variable is an alist, the car of each entry must be a
3221 keyword as a string, the cdr may be a character that is used to select
3222 that tag through the fast-tag-selection interface.
3223 See the manual for details.
3224 To disable these tags on a per-file basis, insert anywhere in the file:
3225 #+STARTUP: noptag"
3226 :group 'org-tags
3227 :type '(repeat
3228 (choice
3229 (cons (string :tag "Tag name")
3230 (character :tag "Access char"))
3231 (const :tag "Start radio group" (:startgroup))
3232 (const :tag "Group tags delimiter" (:grouptags))
3233 (const :tag "End radio group" (:endgroup))
3234 (const :tag "New line" (:newline)))))
3236 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3237 "If non-nil, always offer completion for all tags of all agenda files.
3238 Instead of customizing this variable directly, you might want to
3239 set it locally for capture buffers, because there no list of
3240 tags in that file can be created dynamically (there are none).
3242 (add-hook 'org-capture-mode-hook
3243 (lambda ()
3244 (set (make-local-variable
3245 'org-complete-tags-always-offer-all-agenda-tags)
3246 t)))"
3247 :group 'org-tags
3248 :version "24.1"
3249 :type 'boolean)
3251 (defvar org-file-tags nil
3252 "List of tags that can be inherited by all entries in the file.
3253 The tags will be inherited if the variable `org-use-tag-inheritance'
3254 says they should be.
3255 This variable is populated from #+FILETAGS lines.")
3257 (defcustom org-use-fast-tag-selection 'auto
3258 "Non-nil means use fast tag selection scheme.
3259 This is a special interface to select and deselect tags with single keys.
3260 When nil, fast selection is never used.
3261 When the symbol `auto', fast selection is used if and only if selection
3262 characters for tags have been configured, either through the variable
3263 `org-tag-alist' or through a #+TAGS line in the buffer.
3264 When t, fast selection is always used and selection keys are assigned
3265 automatically if necessary."
3266 :group 'org-tags
3267 :type '(choice
3268 (const :tag "Always" t)
3269 (const :tag "Never" nil)
3270 (const :tag "When selection characters are configured" 'auto)))
3272 (defcustom org-fast-tag-selection-single-key nil
3273 "Non-nil means fast tag selection exits after first change.
3274 When nil, you have to press RET to exit it.
3275 During fast tag selection, you can toggle this flag with `C-c'.
3276 This variable can also have the value `expert'. In this case, the window
3277 displaying the tags menu is not even shown, until you press C-c again."
3278 :group 'org-tags
3279 :type '(choice
3280 (const :tag "No" nil)
3281 (const :tag "Yes" t)
3282 (const :tag "Expert" expert)))
3284 (defvar org-fast-tag-selection-include-todo nil
3285 "Non-nil means fast tags selection interface will also offer TODO states.
3286 This is an undocumented feature, you should not rely on it.")
3288 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3289 "The column to which tags should be indented in a headline.
3290 If this number is positive, it specifies the column. If it is negative,
3291 it means that the tags should be flushright to that column. For example,
3292 -80 works well for a normal 80 character screen.
3293 When 0, place tags directly after headline text, with only one space in
3294 between."
3295 :group 'org-tags
3296 :type 'integer)
3298 (defcustom org-auto-align-tags t
3299 "Non-nil keeps tags aligned when modifying headlines.
3300 Some operations (i.e. demoting) change the length of a headline and
3301 therefore shift the tags around. With this option turned on, after
3302 each such operation the tags are again aligned to `org-tags-column'."
3303 :group 'org-tags
3304 :type 'boolean)
3306 (defcustom org-use-tag-inheritance t
3307 "Non-nil means tags in levels apply also for sublevels.
3308 When nil, only the tags directly given in a specific line apply there.
3309 This may also be a list of tags that should be inherited, or a regexp that
3310 matches tags that should be inherited. Additional control is possible
3311 with the variable `org-tags-exclude-from-inheritance' which gives an
3312 explicit list of tags to be excluded from inheritance, even if the value of
3313 `org-use-tag-inheritance' would select it for inheritance.
3315 If this option is t, a match early-on in a tree can lead to a large
3316 number of matches in the subtree when constructing the agenda or creating
3317 a sparse tree. If you only want to see the first match in a tree during
3318 a search, check out the variable `org-tags-match-list-sublevels'."
3319 :group 'org-tags
3320 :type '(choice
3321 (const :tag "Not" nil)
3322 (const :tag "Always" t)
3323 (repeat :tag "Specific tags" (string :tag "Tag"))
3324 (regexp :tag "Tags matched by regexp")))
3326 (defcustom org-tags-exclude-from-inheritance nil
3327 "List of tags that should never be inherited.
3328 This is a way to exclude a few tags from inheritance. For way to do
3329 the opposite, to actively allow inheritance for selected tags,
3330 see the variable `org-use-tag-inheritance'."
3331 :group 'org-tags
3332 :type '(repeat (string :tag "Tag")))
3334 (defun org-tag-inherit-p (tag)
3335 "Check if TAG is one that should be inherited."
3336 (cond
3337 ((member tag org-tags-exclude-from-inheritance) nil)
3338 ((eq org-use-tag-inheritance t) t)
3339 ((not org-use-tag-inheritance) nil)
3340 ((stringp org-use-tag-inheritance)
3341 (string-match org-use-tag-inheritance tag))
3342 ((listp org-use-tag-inheritance)
3343 (member tag org-use-tag-inheritance))
3344 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3346 (defcustom org-tags-match-list-sublevels t
3347 "Non-nil means list also sublevels of headlines matching a search.
3348 This variable applies to tags/property searches, and also to stuck
3349 projects because this search is based on a tags match as well.
3351 When set to the symbol `indented', sublevels are indented with
3352 leading dots.
3354 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3355 the sublevels of a headline matching a tag search often also match
3356 the same search. Listing all of them can create very long lists.
3357 Setting this variable to nil causes subtrees of a match to be skipped.
3359 This variable is semi-obsolete and probably should always be true. It
3360 is better to limit inheritance to certain tags using the variables
3361 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3362 :group 'org-tags
3363 :type '(choice
3364 (const :tag "No, don't list them" nil)
3365 (const :tag "Yes, do list them" t)
3366 (const :tag "List them, indented with leading dots" indented)))
3368 (defcustom org-tags-sort-function nil
3369 "When set, tags are sorted using this function as a comparator."
3370 :group 'org-tags
3371 :type '(choice
3372 (const :tag "No sorting" nil)
3373 (const :tag "Alphabetical" string<)
3374 (const :tag "Reverse alphabetical" string>)
3375 (function :tag "Custom function" nil)))
3377 (defvar org-tags-history nil
3378 "History of minibuffer reads for tags.")
3379 (defvar org-last-tags-completion-table nil
3380 "The last used completion table for tags.")
3381 (defvar org-after-tags-change-hook nil
3382 "Hook that is run after the tags in a line have changed.")
3384 (defgroup org-properties nil
3385 "Options concerning properties in Org-mode."
3386 :tag "Org Properties"
3387 :group 'org)
3389 (defcustom org-property-format "%-10s %s"
3390 "How property key/value pairs should be formatted by `indent-line'.
3391 When `indent-line' hits a property definition, it will format the line
3392 according to this format, mainly to make sure that the values are
3393 lined-up with respect to each other."
3394 :group 'org-properties
3395 :type 'string)
3397 (defcustom org-properties-postprocess-alist nil
3398 "Alist of properties and functions to adjust inserted values.
3399 Elements of this alist must be of the form
3401 ([string] [function])
3403 where [string] must be a property name and [function] must be a
3404 lambda expression: this lambda expression must take one argument,
3405 the value to adjust, and return the new value as a string.
3407 For example, this element will allow the property \"Remaining\"
3408 to be updated wrt the relation between the \"Effort\" property
3409 and the clock summary:
3411 ((\"Remaining\" (lambda(value)
3412 (let ((clocksum (org-clock-sum-current-item))
3413 (effort (org-duration-string-to-minutes
3414 (org-entry-get (point) \"Effort\"))))
3415 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3416 :group 'org-properties
3417 :version "24.1"
3418 :type '(alist :key-type (string :tag "Property")
3419 :value-type (function :tag "Function")))
3421 (defcustom org-use-property-inheritance nil
3422 "Non-nil means properties apply also for sublevels.
3424 This setting is chiefly used during property searches. Turning it on can
3425 cause significant overhead when doing a search, which is why it is not
3426 on by default.
3428 When nil, only the properties directly given in the current entry count.
3429 When t, every property is inherited. The value may also be a list of
3430 properties that should have inheritance, or a regular expression matching
3431 properties that should be inherited.
3433 However, note that some special properties use inheritance under special
3434 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3435 and the properties ending in \"_ALL\" when they are used as descriptor
3436 for valid values of a property.
3438 Note for programmers:
3439 When querying an entry with `org-entry-get', you can control if inheritance
3440 should be used. By default, `org-entry-get' looks only at the local
3441 properties. You can request inheritance by setting the inherit argument
3442 to t (to force inheritance) or to `selective' (to respect the setting
3443 in this variable)."
3444 :group 'org-properties
3445 :type '(choice
3446 (const :tag "Not" nil)
3447 (const :tag "Always" t)
3448 (repeat :tag "Specific properties" (string :tag "Property"))
3449 (regexp :tag "Properties matched by regexp")))
3451 (defun org-property-inherit-p (property)
3452 "Check if PROPERTY is one that should be inherited."
3453 (cond
3454 ((eq org-use-property-inheritance t) t)
3455 ((not org-use-property-inheritance) nil)
3456 ((stringp org-use-property-inheritance)
3457 (string-match org-use-property-inheritance property))
3458 ((listp org-use-property-inheritance)
3459 (member property org-use-property-inheritance))
3460 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3462 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3463 "The default column format, if no other format has been defined.
3464 This variable can be set on the per-file basis by inserting a line
3466 #+COLUMNS: %25ITEM ....."
3467 :group 'org-properties
3468 :type 'string)
3470 (defcustom org-columns-ellipses ".."
3471 "The ellipses to be used when a field in column view is truncated.
3472 When this is the empty string, as many characters as possible are shown,
3473 but then there will be no visual indication that the field has been truncated.
3474 When this is a string of length N, the last N characters of a truncated
3475 field are replaced by this string. If the column is narrower than the
3476 ellipses string, only part of the ellipses string will be shown."
3477 :group 'org-properties
3478 :type 'string)
3480 (defcustom org-columns-modify-value-for-display-function nil
3481 "Function that modifies values for display in column view.
3482 For example, it can be used to cut out a certain part from a time stamp.
3483 The function must take 2 arguments:
3485 column-title The title of the column (*not* the property name)
3486 value The value that should be modified.
3488 The function should return the value that should be displayed,
3489 or nil if the normal value should be used."
3490 :group 'org-properties
3491 :type 'function)
3493 (defcustom org-effort-property "Effort"
3494 "The property that is being used to keep track of effort estimates.
3495 Effort estimates given in this property need to have the format H:MM."
3496 :group 'org-properties
3497 :group 'org-progress
3498 :type '(string :tag "Property"))
3500 (defconst org-global-properties-fixed
3501 '(("VISIBILITY_ALL" . "folded children content all")
3502 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3503 "List of property/value pairs that can be inherited by any entry.
3505 These are fixed values, for the preset properties. The user variable
3506 that can be used to add to this list is `org-global-properties'.
3508 The entries in this list are cons cells where the car is a property
3509 name and cdr is a string with the value. If the value represents
3510 multiple items like an \"_ALL\" property, separate the items by
3511 spaces.")
3513 (defcustom org-global-properties nil
3514 "List of property/value pairs that can be inherited by any entry.
3516 This list will be combined with the constant `org-global-properties-fixed'.
3518 The entries in this list are cons cells where the car is a property
3519 name and cdr is a string with the value.
3521 You can set buffer-local values for the same purpose in the variable
3522 `org-file-properties' this by adding lines like
3524 #+PROPERTY: NAME VALUE"
3525 :group 'org-properties
3526 :type '(repeat
3527 (cons (string :tag "Property")
3528 (string :tag "Value"))))
3530 (defvar org-file-properties nil
3531 "List of property/value pairs that can be inherited by any entry.
3532 Valid for the current buffer.
3533 This variable is populated from #+PROPERTY lines.")
3534 (make-variable-buffer-local 'org-file-properties)
3536 (defgroup org-agenda nil
3537 "Options concerning agenda views in Org-mode."
3538 :tag "Org Agenda"
3539 :group 'org)
3541 (defvar org-category nil
3542 "Variable used by org files to set a category for agenda display.
3543 Such files should use a file variable to set it, for example
3545 # -*- mode: org; org-category: \"ELisp\"
3547 or contain a special line
3549 #+CATEGORY: ELisp
3551 If the file does not specify a category, then file's base name
3552 is used instead.")
3553 (make-variable-buffer-local 'org-category)
3554 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3556 (defcustom org-agenda-files nil
3557 "The files to be used for agenda display.
3558 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3559 \\[org-remove-file]. You can also use customize to edit the list.
3561 If an entry is a directory, all files in that directory that are matched by
3562 `org-agenda-file-regexp' will be part of the file list.
3564 If the value of the variable is not a list but a single file name, then
3565 the list of agenda files is actually stored and maintained in that file, one
3566 agenda file per line. In this file paths can be given relative to
3567 `org-directory'. Tilde expansion and environment variable substitution
3568 are also made."
3569 :group 'org-agenda
3570 :type '(choice
3571 (repeat :tag "List of files and directories" file)
3572 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3574 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3575 "Regular expression to match files for `org-agenda-files'.
3576 If any element in the list in that variable contains a directory instead
3577 of a normal file, all files in that directory that are matched by this
3578 regular expression will be included."
3579 :group 'org-agenda
3580 :type 'regexp)
3582 (defcustom org-agenda-text-search-extra-files nil
3583 "List of extra files to be searched by text search commands.
3584 These files will be search in addition to the agenda files by the
3585 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3586 Note that these files will only be searched for text search commands,
3587 not for the other agenda views like todo lists, tag searches or the weekly
3588 agenda. This variable is intended to list notes and possibly archive files
3589 that should also be searched by these two commands.
3590 In fact, if the first element in the list is the symbol `agenda-archives',
3591 than all archive files of all agenda files will be added to the search
3592 scope."
3593 :group 'org-agenda
3594 :type '(set :greedy t
3595 (const :tag "Agenda Archives" agenda-archives)
3596 (repeat :inline t (file))))
3598 (org-defvaralias 'org-agenda-multi-occur-extra-files
3599 'org-agenda-text-search-extra-files)
3601 (defcustom org-agenda-skip-unavailable-files nil
3602 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3603 A nil value means to remove them, after a query, from the list."
3604 :group 'org-agenda
3605 :type 'boolean)
3607 (defcustom org-calendar-to-agenda-key [?c]
3608 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3609 The command `org-calendar-goto-agenda' will be bound to this key. The
3610 default is the character `c' because then `c' can be used to switch back and
3611 forth between agenda and calendar."
3612 :group 'org-agenda
3613 :type 'sexp)
3615 (defcustom org-calendar-insert-diary-entry-key [?i]
3616 "The key to be installed in `calendar-mode-map' for adding diary entries.
3617 This option is irrelevant until `org-agenda-diary-file' has been configured
3618 to point to an Org-mode file. When that is the case, the command
3619 `org-agenda-diary-entry' will be bound to the key given here, by default
3620 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3621 if you want to continue doing this, you need to change this to a different
3622 key."
3623 :group 'org-agenda
3624 :type 'sexp)
3626 (defcustom org-agenda-diary-file 'diary-file
3627 "File to which to add new entries with the `i' key in agenda and calendar.
3628 When this is the symbol `diary-file', the functionality in the Emacs
3629 calendar will be used to add entries to the `diary-file'. But when this
3630 points to a file, `org-agenda-diary-entry' will be used instead."
3631 :group 'org-agenda
3632 :type '(choice
3633 (const :tag "The standard Emacs diary file" diary-file)
3634 (file :tag "Special Org file diary entries")))
3636 (eval-after-load "calendar"
3637 '(progn
3638 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3639 'org-calendar-goto-agenda)
3640 (add-hook 'calendar-mode-hook
3641 (lambda ()
3642 (unless (eq org-agenda-diary-file 'diary-file)
3643 (define-key calendar-mode-map
3644 org-calendar-insert-diary-entry-key
3645 'org-agenda-diary-entry))))))
3647 (defgroup org-latex nil
3648 "Options for embedding LaTeX code into Org-mode."
3649 :tag "Org LaTeX"
3650 :group 'org)
3652 (defcustom org-format-latex-options
3653 '(:foreground default :background default :scale 1.0
3654 :html-foreground "Black" :html-background "Transparent"
3655 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3656 "Options for creating images from LaTeX fragments.
3657 This is a property list with the following properties:
3658 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3659 `default' means use the foreground of the default face.
3660 `auto' means use the foreground from the text face.
3661 :background the background color, or \"Transparent\".
3662 `default' means use the background of the default face.
3663 `auto' means use the background from the text face.
3664 :scale a scaling factor for the size of the images, to get more pixels
3665 :html-foreground, :html-background, :html-scale
3666 the same numbers for HTML export.
3667 :matchers a list indicating which matchers should be used to
3668 find LaTeX fragments. Valid members of this list are:
3669 \"begin\" find environments
3670 \"$1\" find single characters surrounded by $.$
3671 \"$\" find math expressions surrounded by $...$
3672 \"$$\" find math expressions surrounded by $$....$$
3673 \"\\(\" find math expressions surrounded by \\(...\\)
3674 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3675 :group 'org-latex
3676 :type 'plist)
3678 (defcustom org-format-latex-signal-error t
3679 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3680 When nil, just push out a message."
3681 :group 'org-latex
3682 :version "24.1"
3683 :type 'boolean)
3685 (defcustom org-latex-to-mathml-jar-file nil
3686 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3687 Use this to specify additional executable file say a jar file.
3689 When using MathToWeb as the converter, specify the full-path to
3690 your mathtoweb.jar file."
3691 :group 'org-latex
3692 :version "24.1"
3693 :type '(choice
3694 (const :tag "None" nil)
3695 (file :tag "JAR file" :must-match t)))
3697 (defcustom org-latex-to-mathml-convert-command nil
3698 "Command to convert LaTeX fragments to MathML.
3699 Replace format-specifiers in the command as noted below and use
3700 `shell-command' to convert LaTeX to MathML.
3701 %j: Executable file in fully expanded form as specified by
3702 `org-latex-to-mathml-jar-file'.
3703 %I: Input LaTeX file in fully expanded form
3704 %o: Output MathML file
3705 This command is used by `org-create-math-formula'.
3707 When using MathToWeb as the converter, set this to
3708 \"java -jar %j -unicode -force -df %o %I\"."
3709 :group 'org-latex
3710 :version "24.1"
3711 :type '(choice
3712 (const :tag "None" nil)
3713 (string :tag "\nShell command")))
3715 (defcustom org-latex-create-formula-image-program 'dvipng
3716 "Program to convert LaTeX fragments with.
3718 dvipng Process the LaTeX fragments to dvi file, then convert
3719 dvi files to png files using dvipng.
3720 This will also include processing of non-math environments.
3721 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3722 to convert pdf files to png files"
3723 :group 'org-latex
3724 :version "24.1"
3725 :type '(choice
3726 (const :tag "dvipng" dvipng)
3727 (const :tag "imagemagick" imagemagick)))
3729 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3730 "Path to store latex preview images.
3731 A relative path here creates many directories relative to the
3732 processed org files paths. An absolute path puts all preview
3733 images at the same place."
3734 :group 'org-latex
3735 :version "24.3"
3736 :type 'string)
3738 (defun org-format-latex-mathml-available-p ()
3739 "Return t if `org-latex-to-mathml-convert-command' is usable."
3740 (save-match-data
3741 (when (and (boundp 'org-latex-to-mathml-convert-command)
3742 org-latex-to-mathml-convert-command)
3743 (let ((executable (car (split-string
3744 org-latex-to-mathml-convert-command))))
3745 (when (executable-find executable)
3746 (if (string-match
3747 "%j" org-latex-to-mathml-convert-command)
3748 (file-readable-p org-latex-to-mathml-jar-file)
3749 t))))))
3751 (defcustom org-format-latex-header "\\documentclass{article}
3752 \\usepackage[usenames]{color}
3753 \\usepackage{amsmath}
3754 \\usepackage[mathscr]{eucal}
3755 \\pagestyle{empty} % do not remove
3756 \[PACKAGES]
3757 \[DEFAULT-PACKAGES]
3758 % The settings below are copied from fullpage.sty
3759 \\setlength{\\textwidth}{\\paperwidth}
3760 \\addtolength{\\textwidth}{-3cm}
3761 \\setlength{\\oddsidemargin}{1.5cm}
3762 \\addtolength{\\oddsidemargin}{-2.54cm}
3763 \\setlength{\\evensidemargin}{\\oddsidemargin}
3764 \\setlength{\\textheight}{\\paperheight}
3765 \\addtolength{\\textheight}{-\\headheight}
3766 \\addtolength{\\textheight}{-\\headsep}
3767 \\addtolength{\\textheight}{-\\footskip}
3768 \\addtolength{\\textheight}{-3cm}
3769 \\setlength{\\topmargin}{1.5cm}
3770 \\addtolength{\\topmargin}{-2.54cm}"
3771 "The document header used for processing LaTeX fragments.
3772 It is imperative that this header make sure that no page number
3773 appears on the page. The package defined in the variables
3774 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3775 will either replace the placeholder \"[PACKAGES]\" in this
3776 header, or they will be appended."
3777 :group 'org-latex
3778 :type 'string)
3780 (defun org-set-packages-alist (var val)
3781 "Set the packages alist and make sure it has 3 elements per entry."
3782 (set var (mapcar (lambda (x)
3783 (if (and (consp x) (= (length x) 2))
3784 (list (car x) (nth 1 x) t)
3786 val)))
3788 (defun org-get-packages-alist (var)
3789 "Get the packages alist and make sure it has 3 elements per entry."
3790 (mapcar (lambda (x)
3791 (if (and (consp x) (= (length x) 2))
3792 (list (car x) (nth 1 x) t)
3794 (default-value var)))
3796 (defcustom org-latex-default-packages-alist
3797 '(("AUTO" "inputenc" t)
3798 ("T1" "fontenc" t)
3799 ("" "fixltx2e" nil)
3800 ("" "graphicx" t)
3801 ("" "longtable" nil)
3802 ("" "float" nil)
3803 ("" "wrapfig" nil)
3804 ("" "soul" t)
3805 ("" "textcomp" t)
3806 ("" "marvosym" t)
3807 ("" "wasysym" t)
3808 ("" "latexsym" t)
3809 ("" "amssymb" t)
3810 ("" "hyperref" nil)
3811 "\\tolerance=1000")
3812 "Alist of default packages to be inserted in the header.
3814 Change this only if one of the packages here causes an
3815 incompatibility with another package you are using.
3817 The packages in this list are needed by one part or another of
3818 Org mode to function properly:
3820 - inputenc, fontenc: for basic font and character selection
3821 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3822 symbols used for interpreting the entities in `org-entities'.
3823 You can skip some of these packages if you don't use any of the
3824 symbols in it.
3825 - graphicx: for including images
3826 - float, wrapfig: for figure placement
3827 - longtable: for long tables
3828 - hyperref: for cross references
3830 Therefore you should not modify this variable unless you know
3831 what you are doing. The one reason to change it anyway is that
3832 you might be loading some other package that conflicts with one
3833 of the default packages. Each cell is of the format
3834 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3835 the package also needs to be included when compiling LaTeX
3836 snippets into images for inclusion into non-LaTeX output."
3837 :group 'org-latex
3838 :group 'org-export-latex
3839 :set 'org-set-packages-alist
3840 :get 'org-get-packages-alist
3841 :version "24.1"
3842 :type '(repeat
3843 (choice
3844 (list :tag "options/package pair"
3845 (string :tag "options")
3846 (string :tag "package")
3847 (boolean :tag "Snippet"))
3848 (string :tag "A line of LaTeX"))))
3850 (defcustom org-latex-packages-alist nil
3851 "Alist of packages to be inserted in every LaTeX header.
3853 These will be inserted after `org-latex-default-packages-alist'.
3854 Each cell is of the format:
3856 \(\"options\" \"package\" snippet-flag)
3858 SNIPPET-FLAG, when t, indicates that this package is also needed
3859 when turning LaTeX snippets into images for inclusion into
3860 non-LaTeX output.
3862 Make sure that you only list packages here which:
3864 - you want in every file
3865 - do not conflict with the setup in `org-format-latex-header'.
3866 - do not conflict with the default packages in
3867 `org-latex-default-packages-alist'."
3868 :group 'org-latex
3869 :group 'org-export-latex
3870 :set 'org-set-packages-alist
3871 :get 'org-get-packages-alist
3872 :type '(repeat
3873 (choice
3874 (list :tag "options/package pair"
3875 (string :tag "options")
3876 (string :tag "package")
3877 (boolean :tag "Snippet"))
3878 (string :tag "A line of LaTeX"))))
3880 (defgroup org-appearance nil
3881 "Settings for Org-mode appearance."
3882 :tag "Org Appearance"
3883 :group 'org)
3885 (defcustom org-level-color-stars-only nil
3886 "Non-nil means fontify only the stars in each headline.
3887 When nil, the entire headline is fontified.
3888 Changing it requires restart of `font-lock-mode' to become effective
3889 also in regions already fontified."
3890 :group 'org-appearance
3891 :type 'boolean)
3893 (defcustom org-hide-leading-stars nil
3894 "Non-nil means hide the first N-1 stars in a headline.
3895 This works by using the face `org-hide' for these stars. This
3896 face is white for a light background, and black for a dark
3897 background. You may have to customize the face `org-hide' to
3898 make this work.
3899 Changing it requires restart of `font-lock-mode' to become effective
3900 also in regions already fontified.
3901 You may also set this on a per-file basis by adding one of the following
3902 lines to the buffer:
3904 #+STARTUP: hidestars
3905 #+STARTUP: showstars"
3906 :group 'org-appearance
3907 :type 'boolean)
3909 (defcustom org-hidden-keywords nil
3910 "List of symbols corresponding to keywords to be hidden the org buffer.
3911 For example, a value '(title) for this list will make the document's title
3912 appear in the buffer without the initial #+TITLE: keyword."
3913 :group 'org-appearance
3914 :version "24.1"
3915 :type '(set (const :tag "#+AUTHOR" author)
3916 (const :tag "#+DATE" date)
3917 (const :tag "#+EMAIL" email)
3918 (const :tag "#+TITLE" title)))
3920 (defcustom org-custom-properties nil
3921 "List of properties (as strings) with a special meaning.
3922 The default use of these custom properties is to let the user
3923 hide them with `org-toggle-custom-properties-visibility'."
3924 :group 'org-properties
3925 :group 'org-appearance
3926 :version "24.3"
3927 :type '(repeat (string :tag "Property Name")))
3929 (defcustom org-fontify-done-headline nil
3930 "Non-nil means change the face of a headline if it is marked DONE.
3931 Normally, only the TODO/DONE keyword indicates the state of a headline.
3932 When this is non-nil, the headline after the keyword is set to the
3933 `org-headline-done' as an additional indication."
3934 :group 'org-appearance
3935 :type 'boolean)
3937 (defcustom org-fontify-emphasized-text t
3938 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3939 Changing this variable requires a restart of Emacs to take effect."
3940 :group 'org-appearance
3941 :type 'boolean)
3943 (defcustom org-fontify-whole-heading-line nil
3944 "Non-nil means fontify the whole line for headings.
3945 This is useful when setting a background color for the
3946 org-level-* faces."
3947 :group 'org-appearance
3948 :type 'boolean)
3950 (defcustom org-highlight-latex-and-related nil
3951 "Non-nil means highlight LaTeX related syntax in the buffer.
3952 When non nil, the value should be a list containing any of the
3953 following symbols:
3954 `latex' Highlight LaTeX snippets and environments.
3955 `script' Highlight subscript and superscript.
3956 `entities' Highlight entities."
3957 :group 'org-appearance
3958 :version "24.4"
3959 :package-version '(Org . "8.0")
3960 :type '(choice
3961 (const :tag "No highlighting" nil)
3962 (set :greedy t :tag "Highlight"
3963 (const :tag "LaTeX snippets and environments" latex)
3964 (const :tag "Subscript and superscript" script)
3965 (const :tag "Entities" entities))))
3967 (defcustom org-hide-emphasis-markers nil
3968 "Non-nil mean font-lock should hide the emphasis marker characters."
3969 :group 'org-appearance
3970 :type 'boolean)
3972 (defcustom org-pretty-entities nil
3973 "Non-nil means show entities as UTF8 characters.
3974 When nil, the \\name form remains in the buffer."
3975 :group 'org-appearance
3976 :version "24.1"
3977 :type 'boolean)
3979 (defcustom org-pretty-entities-include-sub-superscripts t
3980 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3981 :group 'org-appearance
3982 :version "24.1"
3983 :type 'boolean)
3985 (defvar org-emph-re nil
3986 "Regular expression for matching emphasis.
3987 After a match, the match groups contain these elements:
3988 0 The match of the full regular expression, including the characters
3989 before and after the proper match
3990 1 The character before the proper match, or empty at beginning of line
3991 2 The proper match, including the leading and trailing markers
3992 3 The leading marker like * or /, indicating the type of highlighting
3993 4 The text between the emphasis markers, not including the markers
3994 5 The character after the match, empty at the end of a line")
3995 (defvar org-verbatim-re nil
3996 "Regular expression for matching verbatim text.")
3997 (defvar org-emphasis-regexp-components) ; defined just below
3998 (defvar org-emphasis-alist) ; defined just below
3999 (defun org-set-emph-re (var val)
4000 "Set variable and compute the emphasis regular expression."
4001 (set var val)
4002 (when (and (boundp 'org-emphasis-alist)
4003 (boundp 'org-emphasis-regexp-components)
4004 org-emphasis-alist org-emphasis-regexp-components)
4005 (let* ((e org-emphasis-regexp-components)
4006 (pre (car e))
4007 (post (nth 1 e))
4008 (border (nth 2 e))
4009 (body (nth 3 e))
4010 (nl (nth 4 e))
4011 (body1 (concat body "*?"))
4012 (markers (mapconcat 'car org-emphasis-alist ""))
4013 (vmarkers (mapconcat
4014 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
4015 org-emphasis-alist "")))
4016 ;; make sure special characters appear at the right position in the class
4017 (if (string-match "\\^" markers)
4018 (setq markers (concat (replace-match "" t t markers) "^")))
4019 (if (string-match "-" markers)
4020 (setq markers (concat (replace-match "" t t markers) "-")))
4021 (if (string-match "\\^" vmarkers)
4022 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4023 (if (string-match "-" vmarkers)
4024 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4025 (if (> nl 0)
4026 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4027 (int-to-string nl) "\\}")))
4028 ;; Make the regexp
4029 (setq org-emph-re
4030 (concat "\\([" pre "]\\|^\\)"
4031 "\\("
4032 "\\([" markers "]\\)"
4033 "\\("
4034 "[^" border "]\\|"
4035 "[^" border "]"
4036 body1
4037 "[^" border "]"
4038 "\\)"
4039 "\\3\\)"
4040 "\\([" post "]\\|$\\)"))
4041 (setq org-verbatim-re
4042 (concat "\\([" pre "]\\|^\\)"
4043 "\\("
4044 "\\([" vmarkers "]\\)"
4045 "\\("
4046 "[^" border "]\\|"
4047 "[^" border "]"
4048 body1
4049 "[^" border "]"
4050 "\\)"
4051 "\\3\\)"
4052 "\\([" post "]\\|$\\)")))))
4054 (defcustom org-emphasis-regexp-components
4055 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4056 "Components used to build the regular expression for emphasis.
4057 This is a list with five entries. Terminology: In an emphasis string
4058 like \" *strong word* \", we call the initial space PREMATCH, the final
4059 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4060 and \"trong wor\" is the body. The different components in this variable
4061 specify what is allowed/forbidden in each part:
4063 pre Chars allowed as prematch. Beginning of line will be allowed too.
4064 post Chars allowed as postmatch. End of line will be allowed too.
4065 border The chars *forbidden* as border characters.
4066 body-regexp A regexp like \".\" to match a body character. Don't use
4067 non-shy groups here, and don't allow newline here.
4068 newline The maximum number of newlines allowed in an emphasis exp.
4070 Use customize to modify this, or restart Emacs after changing it."
4071 :group 'org-appearance
4072 :set 'org-set-emph-re
4073 :type '(list
4074 (sexp :tag "Allowed chars in pre ")
4075 (sexp :tag "Allowed chars in post ")
4076 (sexp :tag "Forbidden chars in border ")
4077 (sexp :tag "Regexp for body ")
4078 (integer :tag "number of newlines allowed")
4079 (option (boolean :tag "Please ignore this button"))))
4081 (defcustom org-emphasis-alist
4082 `(("*" bold "<b>" "</b>")
4083 ("/" italic "<i>" "</i>")
4084 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
4085 ("=" org-code "<code>" "</code>" verbatim)
4086 ("~" org-verbatim "<code>" "</code>" verbatim)
4087 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
4088 "<del>" "</del>")
4090 "Special syntax for emphasized text.
4091 Text starting and ending with a special character will be emphasized, for
4092 example *bold*, _underlined_ and /italic/. This variable sets the marker
4093 characters, the face to be used by font-lock for highlighting in Org-mode
4094 Emacs buffers, and the HTML tags to be used for this.
4095 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
4096 Use customize to modify this, or restart Emacs after changing it."
4097 :group 'org-appearance
4098 :set 'org-set-emph-re
4099 :type '(repeat
4100 (list
4101 (string :tag "Marker character")
4102 (choice
4103 (face :tag "Font-lock-face")
4104 (plist :tag "Face property list"))
4105 (string :tag "HTML start tag")
4106 (string :tag "HTML end tag")
4107 (option (const verbatim)))))
4109 (defvar org-protecting-blocks
4110 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4111 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4112 This is needed for font-lock setup.")
4114 ;;; Miscellaneous options
4116 (defgroup org-completion nil
4117 "Completion in Org-mode."
4118 :tag "Org Completion"
4119 :group 'org)
4121 (defcustom org-completion-use-ido nil
4122 "Non-nil means use ido completion wherever possible.
4123 Note that `ido-mode' must be active for this variable to be relevant.
4124 If you decide to turn this variable on, you might well want to turn off
4125 `org-outline-path-complete-in-steps'.
4126 See also `org-completion-use-iswitchb'."
4127 :group 'org-completion
4128 :type 'boolean)
4130 (defcustom org-completion-use-iswitchb nil
4131 "Non-nil means use iswitchb completion wherever possible.
4132 Note that `iswitchb-mode' must be active for this variable to be relevant.
4133 If you decide to turn this variable on, you might well want to turn off
4134 `org-outline-path-complete-in-steps'.
4135 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4136 :group 'org-completion
4137 :type 'boolean)
4139 (defcustom org-completion-fallback-command 'hippie-expand
4140 "The expansion command called by \\[pcomplete] in normal context.
4141 Normal means, no org-mode-specific context."
4142 :group 'org-completion
4143 :type 'function)
4145 ;;; Functions and variables from their packages
4146 ;; Declared here to avoid compiler warnings
4148 ;; XEmacs only
4149 (defvar outline-mode-menu-heading)
4150 (defvar outline-mode-menu-show)
4151 (defvar outline-mode-menu-hide)
4152 (defvar zmacs-regions) ; XEmacs regions
4154 ;; Emacs only
4155 (defvar mark-active)
4157 ;; Various packages
4158 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4159 (declare-function calendar-forward-day "cal-move" (arg))
4160 (declare-function calendar-goto-date "cal-move" (date))
4161 (declare-function calendar-goto-today "cal-move" ())
4162 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4163 (defvar calc-embedded-close-formula)
4164 (defvar calc-embedded-open-formula)
4165 (declare-function cdlatex-tab "ext:cdlatex" ())
4166 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4167 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4168 (defvar font-lock-unfontify-region-function)
4169 (declare-function iswitchb-read-buffer "iswitchb"
4170 (prompt &optional default require-match start matches-set))
4171 (defvar iswitchb-temp-buflist)
4172 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4173 (defvar org-agenda-tags-todo-honor-ignore-options)
4174 (declare-function org-agenda-skip "org-agenda" ())
4175 (declare-function
4176 org-agenda-format-item "org-agenda"
4177 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4178 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4179 (declare-function org-agenda-change-all-lines "org-agenda"
4180 (newhead hdmarker &optional fixface just-this))
4181 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4182 (declare-function org-agenda-maybe-redo "org-agenda" ())
4183 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4184 (beg end))
4185 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4186 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4187 "org-agenda" (&optional end))
4188 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4189 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4190 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4191 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4192 (declare-function org-indent-mode "org-indent" (&optional arg))
4193 (declare-function parse-time-string "parse-time" (string))
4194 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4195 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4196 (defvar remember-data-file)
4197 (defvar texmathp-why)
4198 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4199 (declare-function table--at-cell-p "table" (position &optional object at-column))
4201 (defvar org-latex-regexps)
4203 ;;; Autoload and prepare some org modules
4205 ;; Some table stuff that needs to be defined here, because it is used
4206 ;; by the functions setting up org-mode or checking for table context.
4208 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4209 "Detect an org-type or table-type table.")
4210 (defconst org-table-line-regexp "^[ \t]*|"
4211 "Detect an org-type table line.")
4212 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4213 "Detect an org-type table line.")
4214 (defconst org-table-hline-regexp "^[ \t]*|-"
4215 "Detect an org-type table hline.")
4216 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4217 "Detect a table-type table hline.")
4218 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4219 "Detect the first line outside a table when searching from within it.
4220 This works for both table types.")
4222 ;; Autoload the functions in org-table.el that are needed by functions here.
4224 (eval-and-compile
4225 (org-autoload "org-table"
4226 '(org-table-begin org-table-blank-field org-table-end)))
4228 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
4229 "Detect a #+TBLFM line.")
4231 ;;;###autoload
4232 (defun turn-on-orgtbl ()
4233 "Unconditionally turn on `orgtbl-mode'."
4234 (require 'org-table)
4235 (orgtbl-mode 1))
4237 (defun org-at-table-p (&optional table-type)
4238 "Return t if the cursor is inside an org-type table.
4239 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4240 (if org-enable-table-editor
4241 (save-excursion
4242 (beginning-of-line 1)
4243 (looking-at (if table-type org-table-any-line-regexp
4244 org-table-line-regexp)))
4245 nil))
4246 (defsubst org-table-p () (org-at-table-p))
4248 (defun org-at-table.el-p ()
4249 "Return t if and only if we are at a table.el table."
4250 (and (org-at-table-p 'any)
4251 (save-excursion
4252 (goto-char (org-table-begin 'any))
4253 (looking-at org-table1-hline-regexp))))
4255 (defun org-table-recognize-table.el ()
4256 "If there is a table.el table nearby, recognize it and move into it."
4257 (if org-table-tab-recognizes-table.el
4258 (if (org-at-table.el-p)
4259 (progn
4260 (beginning-of-line 1)
4261 (if (looking-at org-table-dataline-regexp)
4263 (if (looking-at org-table1-hline-regexp)
4264 (progn
4265 (beginning-of-line 2)
4266 (if (looking-at org-table-any-border-regexp)
4267 (beginning-of-line -1)))))
4268 (if (re-search-forward "|" (org-table-end t) t)
4269 (progn
4270 (require 'table)
4271 (if (table--at-cell-p (point))
4273 (message "recognizing table.el table...")
4274 (table-recognize-table)
4275 (message "recognizing table.el table...done")))
4276 (error "This should not happen"))
4278 nil)
4279 nil))
4281 (defun org-at-table-hline-p ()
4282 "Return t if the cursor is inside a hline in a table."
4283 (if org-enable-table-editor
4284 (save-excursion
4285 (beginning-of-line 1)
4286 (looking-at org-table-hline-regexp))
4287 nil))
4289 (defvar org-table-clean-did-remove-column nil)
4290 (defun org-table-map-tables (function &optional quietly)
4291 "Apply FUNCTION to the start of all tables in the buffer."
4292 (save-excursion
4293 (save-restriction
4294 (widen)
4295 (goto-char (point-min))
4296 (while (re-search-forward org-table-any-line-regexp nil t)
4297 (unless quietly
4298 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4299 (beginning-of-line 1)
4300 (when (and (looking-at org-table-line-regexp)
4301 ;; Exclude tables in src/example/verbatim/clocktable blocks
4302 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4303 (save-excursion (funcall function))
4304 (or (looking-at org-table-line-regexp)
4305 (forward-char 1)))
4306 (re-search-forward org-table-any-border-regexp nil 1))))
4307 (unless quietly (message "Mapping tables: done")))
4309 ;; Declare and autoload functions from ox.el and al.
4311 (declare-function org-export-get-environment "ox"
4312 (&optional backend subtreep ext-plist))
4313 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4315 ;; Declare and autoload functions from org-agenda.el
4317 (eval-and-compile
4318 (org-autoload "org-agenda"
4319 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4321 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4322 (declare-function org-clock-update-mode-line "org-clock" ())
4323 (declare-function org-resolve-clocks "org-clock"
4324 (&optional also-non-dangling-p prompt last-valid))
4326 (defun org-at-TBLFM-p (&optional pos)
4327 "Return t when point (or POS) is in #+TBLFM line."
4328 (save-excursion
4329 (let ((pos pos)))
4330 (goto-char (or pos (point)))
4331 (beginning-of-line 1)
4332 (looking-at org-TBLFM-regexp)))
4334 (defvar org-clock-start-time)
4335 (defvar org-clock-marker (make-marker)
4336 "Marker recording the last clock-in.")
4337 (defvar org-clock-hd-marker (make-marker)
4338 "Marker recording the last clock-in, but the headline position.")
4339 (defvar org-clock-heading ""
4340 "The heading of the current clock entry.")
4341 (defun org-clock-is-active ()
4342 "Return non-nil if clock is currently running.
4343 The return value is actually the clock marker."
4344 (marker-buffer org-clock-marker))
4346 (eval-and-compile
4347 (org-autoload "org-clock" '(org-clock-remove-overlays
4348 org-clock-update-time-maybe
4349 org-clocktable-shift)))
4351 (defun org-check-running-clock ()
4352 "Check if the current buffer contains the running clock.
4353 If yes, offer to stop it and to save the buffer with the changes."
4354 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4355 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4356 (buffer-name))))
4357 (org-clock-out)
4358 (when (y-or-n-p "Save changed buffer?")
4359 (save-buffer))))
4361 (defun org-clocktable-try-shift (dir n)
4362 "Check if this line starts a clock table, if yes, shift the time block."
4363 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4364 (org-clocktable-shift dir n)))
4366 ;;;###autoload
4367 (defun org-clock-persistence-insinuate ()
4368 "Set up hooks for clock persistence."
4369 (require 'org-clock)
4370 (add-hook 'org-mode-hook 'org-clock-load)
4371 (add-hook 'kill-emacs-hook 'org-clock-save))
4373 ;; Define the variable already here, to make sure we have it.
4374 (defvar org-indent-mode nil
4375 "Non-nil if Org-Indent mode is enabled.
4376 Use the command `org-indent-mode' to change this variable.")
4378 ;; Autoload archiving code
4379 ;; The stuff that is needed for cycling and tags has to be defined here.
4381 (defgroup org-archive nil
4382 "Options concerning archiving in Org-mode."
4383 :tag "Org Archive"
4384 :group 'org-structure)
4386 (defcustom org-archive-location "%s_archive::"
4387 "The location where subtrees should be archived.
4389 The value of this variable is a string, consisting of two parts,
4390 separated by a double-colon. The first part is a filename and
4391 the second part is a headline.
4393 When the filename is omitted, archiving happens in the same file.
4394 %s in the filename will be replaced by the current file
4395 name (without the directory part). Archiving to a different file
4396 is useful to keep archived entries from contributing to the
4397 Org-mode Agenda.
4399 The archived entries will be filed as subtrees of the specified
4400 headline. When the headline is omitted, the subtrees are simply
4401 filed away at the end of the file, as top-level entries. Also in
4402 the heading you can use %s to represent the file name, this can be
4403 useful when using the same archive for a number of different files.
4405 Here are a few examples:
4406 \"%s_archive::\"
4407 If the current file is Projects.org, archive in file
4408 Projects.org_archive, as top-level trees. This is the default.
4410 \"::* Archived Tasks\"
4411 Archive in the current file, under the top-level headline
4412 \"* Archived Tasks\".
4414 \"~/org/archive.org::\"
4415 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4417 \"~/org/archive.org::* From %s\"
4418 Archive in file ~/org/archive.org (absolute path), under headlines
4419 \"From FILENAME\" where file name is the current file name.
4421 \"~/org/datetree.org::datetree/* Finished Tasks\"
4422 The \"datetree/\" string is special, signifying to archive
4423 items to the datetree. Items are placed in either the CLOSED
4424 date of the item, or the current date if there is no CLOSED date.
4425 The heading will be a subentry to the current date. There doesn't
4426 need to be a heading, but there always needs to be a slash after
4427 datetree. For example, to store archived items directly in the
4428 datetree, use \"~/org/datetree.org::datetree/\".
4430 \"basement::** Finished Tasks\"
4431 Archive in file ./basement (relative path), as level 3 trees
4432 below the level 2 heading \"** Finished Tasks\".
4434 You may set this option on a per-file basis by adding to the buffer a
4435 line like
4437 #+ARCHIVE: basement::** Finished Tasks
4439 You may also define it locally for a subtree by setting an ARCHIVE property
4440 in the entry. If such a property is found in an entry, or anywhere up
4441 the hierarchy, it will be used."
4442 :group 'org-archive
4443 :type 'string)
4445 (defcustom org-archive-tag "ARCHIVE"
4446 "The tag that marks a subtree as archived.
4447 An archived subtree does not open during visibility cycling, and does
4448 not contribute to the agenda listings.
4449 After changing this, font-lock must be restarted in the relevant buffers to
4450 get the proper fontification."
4451 :group 'org-archive
4452 :group 'org-keywords
4453 :type 'string)
4455 (defcustom org-agenda-skip-archived-trees t
4456 "Non-nil means the agenda will skip any items located in archived trees.
4457 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4458 variable is no longer recommended, you should leave it at the value t.
4459 Instead, use the key `v' to cycle the archives-mode in the agenda."
4460 :group 'org-archive
4461 :group 'org-agenda-skip
4462 :type 'boolean)
4464 (defcustom org-columns-skip-archived-trees t
4465 "Non-nil means ignore archived trees when creating column view."
4466 :group 'org-archive
4467 :group 'org-properties
4468 :type 'boolean)
4470 (defcustom org-cycle-open-archived-trees nil
4471 "Non-nil means `org-cycle' will open archived trees.
4472 An archived tree is a tree marked with the tag ARCHIVE.
4473 When nil, archived trees will stay folded. You can still open them with
4474 normal outline commands like `show-all', but not with the cycling commands."
4475 :group 'org-archive
4476 :group 'org-cycle
4477 :type 'boolean)
4479 (defcustom org-sparse-tree-open-archived-trees nil
4480 "Non-nil means sparse tree construction shows matches in archived trees.
4481 When nil, matches in these trees are highlighted, but the trees are kept in
4482 collapsed state."
4483 :group 'org-archive
4484 :group 'org-sparse-trees
4485 :type 'boolean)
4487 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4488 "The default date type when building a sparse tree.
4489 When this is nil, a date is a scheduled or a deadline timestamp.
4490 Otherwise, these types are allowed:
4492 all: all timestamps
4493 active: only active timestamps (<...>)
4494 inactive: only inactive timestamps (<...)
4495 scheduled: only scheduled timestamps
4496 deadline: only deadline timestamps"
4497 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4498 (const :tag "All timestamps" all)
4499 (const :tag "Only active timestamps" active)
4500 (const :tag "Only inactive timestamps" inactive)
4501 (const :tag "Only scheduled timestamps" scheduled)
4502 (const :tag "Only deadline timestamps" deadline)
4503 (const :tag "Only closed timestamps" closed))
4504 :version "24.3"
4505 :group 'org-sparse-trees)
4507 (defun org-cycle-hide-archived-subtrees (state)
4508 "Re-hide all archived subtrees after a visibility state change."
4509 (when (and (not org-cycle-open-archived-trees)
4510 (not (memq state '(overview folded))))
4511 (save-excursion
4512 (let* ((globalp (memq state '(contents all)))
4513 (beg (if globalp (point-min) (point)))
4514 (end (if globalp (point-max) (org-end-of-subtree t))))
4515 (org-hide-archived-subtrees beg end)
4516 (goto-char beg)
4517 (if (looking-at (concat ".*:" org-archive-tag ":"))
4518 (message "%s" (substitute-command-keys
4519 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4521 (defun org-force-cycle-archived ()
4522 "Cycle subtree even if it is archived."
4523 (interactive)
4524 (setq this-command 'org-cycle)
4525 (let ((org-cycle-open-archived-trees t))
4526 (call-interactively 'org-cycle)))
4528 (defun org-hide-archived-subtrees (beg end)
4529 "Re-hide all archived subtrees after a visibility state change."
4530 (save-excursion
4531 (let* ((re (concat ":" org-archive-tag ":")))
4532 (goto-char beg)
4533 (while (re-search-forward re end t)
4534 (when (org-at-heading-p)
4535 (org-flag-subtree t)
4536 (org-end-of-subtree t))))))
4538 (declare-function outline-end-of-heading "outline" ())
4539 (declare-function outline-flag-region "outline" (from to flag))
4540 (defun org-flag-subtree (flag)
4541 (save-excursion
4542 (org-back-to-heading t)
4543 (outline-end-of-heading)
4544 (outline-flag-region (point)
4545 (progn (org-end-of-subtree t) (point))
4546 flag)))
4548 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4550 (eval-and-compile
4551 (org-autoload "org-archive"
4552 '(org-add-archive-files)))
4554 ;; Autoload Column View Code
4556 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4557 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4558 (declare-function org-columns-compute "org-colview" (property))
4560 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4561 '(org-columns-number-to-string
4562 org-columns-get-format-and-top-level
4563 org-columns-compute
4564 org-columns-remove-overlays))
4566 ;; Autoload ID code
4568 (declare-function org-id-store-link "org-id")
4569 (declare-function org-id-locations-load "org-id")
4570 (declare-function org-id-locations-save "org-id")
4571 (defvar org-id-track-globally)
4572 (org-autoload "org-id"
4573 '(org-id-new
4574 org-id-copy
4575 org-id-get-with-outline-path-completion
4576 org-id-get-with-outline-drilling))
4578 ;;; Variables for pre-computed regular expressions, all buffer local
4580 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4581 "Matches first line of a hidden block.")
4582 (make-variable-buffer-local 'org-drawer-regexp)
4583 (defvar org-todo-regexp nil
4584 "Matches any of the TODO state keywords.")
4585 (make-variable-buffer-local 'org-todo-regexp)
4586 (defvar org-not-done-regexp nil
4587 "Matches any of the TODO state keywords except the last one.")
4588 (make-variable-buffer-local 'org-not-done-regexp)
4589 (defvar org-not-done-heading-regexp nil
4590 "Matches a TODO headline that is not done.")
4591 (make-variable-buffer-local 'org-not-done-regexp)
4592 (defvar org-todo-line-regexp nil
4593 "Matches a headline and puts TODO state into group 2 if present.")
4594 (make-variable-buffer-local 'org-todo-line-regexp)
4595 (defvar org-complex-heading-regexp nil
4596 "Matches a headline and puts everything into groups:
4597 group 1: the stars
4598 group 2: The todo keyword, maybe
4599 group 3: Priority cookie
4600 group 4: True headline
4601 group 5: Tags")
4602 (make-variable-buffer-local 'org-complex-heading-regexp)
4603 (defvar org-complex-heading-regexp-format nil
4604 "Printf format to make regexp to match an exact headline.
4605 This regexp will match the headline of any node which has the
4606 exact headline text that is put into the format, but may have any
4607 TODO state, priority and tags.")
4608 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4609 (defvar org-todo-line-tags-regexp nil
4610 "Matches a headline and puts TODO state into group 2 if present.
4611 Also put tags into group 4 if tags are present.")
4612 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4613 (defvar org-ds-keyword-length 12
4614 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4615 (make-variable-buffer-local 'org-ds-keyword-length)
4616 (defvar org-deadline-regexp nil
4617 "Matches the DEADLINE keyword.")
4618 (make-variable-buffer-local 'org-deadline-regexp)
4619 (defvar org-deadline-time-regexp nil
4620 "Matches the DEADLINE keyword together with a time stamp.")
4621 (make-variable-buffer-local 'org-deadline-time-regexp)
4622 (defvar org-deadline-time-hour-regexp nil
4623 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4624 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4625 (defvar org-deadline-line-regexp nil
4626 "Matches the DEADLINE keyword and the rest of the line.")
4627 (make-variable-buffer-local 'org-deadline-line-regexp)
4628 (defvar org-scheduled-regexp nil
4629 "Matches the SCHEDULED keyword.")
4630 (make-variable-buffer-local 'org-scheduled-regexp)
4631 (defvar org-scheduled-time-regexp nil
4632 "Matches the SCHEDULED keyword together with a time stamp.")
4633 (make-variable-buffer-local 'org-scheduled-time-regexp)
4634 (defvar org-scheduled-time-hour-regexp nil
4635 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4636 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4637 (defvar org-closed-time-regexp nil
4638 "Matches the CLOSED keyword together with a time stamp.")
4639 (make-variable-buffer-local 'org-closed-time-regexp)
4641 (defvar org-keyword-time-regexp nil
4642 "Matches any of the 4 keywords, together with the time stamp.")
4643 (make-variable-buffer-local 'org-keyword-time-regexp)
4644 (defvar org-keyword-time-not-clock-regexp nil
4645 "Matches any of the 3 keywords, together with the time stamp.")
4646 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4647 (defvar org-maybe-keyword-time-regexp nil
4648 "Matches a timestamp, possibly preceded by a keyword.")
4649 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4650 (defvar org-all-time-keywords nil
4651 "List of time keywords.")
4652 (make-variable-buffer-local 'org-all-time-keywords)
4654 (defconst org-plain-time-of-day-regexp
4655 (concat
4656 "\\(\\<[012]?[0-9]"
4657 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4658 "\\(--?"
4659 "\\(\\<[012]?[0-9]"
4660 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4661 "\\)?")
4662 "Regular expression to match a plain time or time range.
4663 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4664 groups carry important information:
4665 0 the full match
4666 1 the first time, range or not
4667 8 the second time, if it is a range.")
4669 (defconst org-plain-time-extension-regexp
4670 (concat
4671 "\\(\\<[012]?[0-9]"
4672 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4673 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4674 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4675 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4676 groups carry important information:
4677 0 the full match
4678 7 hours of duration
4679 9 minutes of duration")
4681 (defconst org-stamp-time-of-day-regexp
4682 (concat
4683 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4684 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4685 "\\(--?"
4686 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4687 "Regular expression to match a timestamp time or time range.
4688 After a match, the following groups carry important information:
4689 0 the full match
4690 1 date plus weekday, for back referencing to make sure both times are on the same day
4691 2 the first time, range or not
4692 4 the second time, if it is a range.")
4694 (defconst org-startup-options
4695 '(("fold" org-startup-folded t)
4696 ("overview" org-startup-folded t)
4697 ("nofold" org-startup-folded nil)
4698 ("showall" org-startup-folded nil)
4699 ("showeverything" org-startup-folded showeverything)
4700 ("content" org-startup-folded content)
4701 ("indent" org-startup-indented t)
4702 ("noindent" org-startup-indented nil)
4703 ("hidestars" org-hide-leading-stars t)
4704 ("showstars" org-hide-leading-stars nil)
4705 ("odd" org-odd-levels-only t)
4706 ("oddeven" org-odd-levels-only nil)
4707 ("align" org-startup-align-all-tables t)
4708 ("noalign" org-startup-align-all-tables nil)
4709 ("inlineimages" org-startup-with-inline-images t)
4710 ("noinlineimages" org-startup-with-inline-images nil)
4711 ("latexpreview" org-startup-with-latex-preview t)
4712 ("nolatexpreview" org-startup-with-latex-preview nil)
4713 ("customtime" org-display-custom-times t)
4714 ("logdone" org-log-done time)
4715 ("lognotedone" org-log-done note)
4716 ("nologdone" org-log-done nil)
4717 ("lognoteclock-out" org-log-note-clock-out t)
4718 ("nolognoteclock-out" org-log-note-clock-out nil)
4719 ("logrepeat" org-log-repeat state)
4720 ("lognoterepeat" org-log-repeat note)
4721 ("logdrawer" org-log-into-drawer t)
4722 ("nologdrawer" org-log-into-drawer nil)
4723 ("logstatesreversed" org-log-states-order-reversed t)
4724 ("nologstatesreversed" org-log-states-order-reversed nil)
4725 ("nologrepeat" org-log-repeat nil)
4726 ("logreschedule" org-log-reschedule time)
4727 ("lognotereschedule" org-log-reschedule note)
4728 ("nologreschedule" org-log-reschedule nil)
4729 ("logredeadline" org-log-redeadline time)
4730 ("lognoteredeadline" org-log-redeadline note)
4731 ("nologredeadline" org-log-redeadline nil)
4732 ("logrefile" org-log-refile time)
4733 ("lognoterefile" org-log-refile note)
4734 ("nologrefile" org-log-refile nil)
4735 ("fninline" org-footnote-define-inline t)
4736 ("nofninline" org-footnote-define-inline nil)
4737 ("fnlocal" org-footnote-section nil)
4738 ("fnauto" org-footnote-auto-label t)
4739 ("fnprompt" org-footnote-auto-label nil)
4740 ("fnconfirm" org-footnote-auto-label confirm)
4741 ("fnplain" org-footnote-auto-label plain)
4742 ("fnadjust" org-footnote-auto-adjust t)
4743 ("nofnadjust" org-footnote-auto-adjust nil)
4744 ("constcgs" constants-unit-system cgs)
4745 ("constSI" constants-unit-system SI)
4746 ("noptag" org-tag-persistent-alist nil)
4747 ("hideblocks" org-hide-block-startup t)
4748 ("nohideblocks" org-hide-block-startup nil)
4749 ("beamer" org-startup-with-beamer-mode t)
4750 ("entitiespretty" org-pretty-entities t)
4751 ("entitiesplain" org-pretty-entities nil))
4752 "Variable associated with STARTUP options for org-mode.
4753 Each element is a list of three items: the startup options (as written
4754 in the #+STARTUP line), the corresponding variable, and the value to set
4755 this variable to if the option is found. An optional forth element PUSH
4756 means to push this value onto the list in the variable.")
4758 (defun org-update-property-plist (key val props)
4759 "Update PROPS with KEY and VAL."
4760 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4761 (key (if appending (substring key 0 (- (length key) 1)) key))
4762 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4763 (previous (cdr (assoc key props))))
4764 (if appending
4765 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4766 (cons (cons key val) remainder))))
4768 (defconst org-block-regexp
4769 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4770 "Regular expression for hiding blocks.")
4771 (defconst org-heading-keyword-regexp-format
4772 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4773 "Printf format for a regexp matching a headline with some keyword.
4774 This regexp will match the headline of any node which has the
4775 exact keyword that is put into the format. The keyword isn't in
4776 any group by default, but the stars and the body are.")
4777 (defconst org-heading-keyword-maybe-regexp-format
4778 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4779 "Printf format for a regexp matching a headline, possibly with some keyword.
4780 This regexp can match any headline with the specified keyword, or
4781 without a keyword. The keyword isn't in any group by default,
4782 but the stars and the body are.")
4784 (defcustom org-group-tags t
4785 "When non-nil (the default), use group tags.
4786 This can be turned on/off through `org-toggle-tags-groups'."
4787 :group 'org-tags
4788 :group 'org-startup
4789 :type 'boolean)
4791 (defun org-toggle-tags-groups ()
4792 "Toggle support for group tags.
4793 Support for group tags is controlled by the option
4794 `org-group-tags', which is non-nil by default."
4795 (interactive)
4796 (setq org-group-tags (not org-group-tags))
4797 (cond ((and (derived-mode-p 'org-agenda-mode)
4798 org-group-tags)
4799 (org-agenda-redo))
4800 ((derived-mode-p 'org-mode)
4801 (let ((org-inhibit-startup t)) (org-mode))))
4802 (message "Groups tags support has been turned %s"
4803 (if org-group-tags "on" "off")))
4805 (defun org-set-regexps-and-options-for-tags ()
4806 "Precompute regular expressions used for tags in the current buffer."
4807 (when (derived-mode-p 'org-mode)
4808 (org-set-local 'org-file-tags nil)
4809 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4810 (splitre "[ \t]+")
4811 (start 0)
4812 tags ftags key value)
4813 (save-excursion
4814 (save-restriction
4815 (widen)
4816 (goto-char (point-min))
4817 (while (re-search-forward re nil t)
4818 (setq key (upcase (org-match-string-no-properties 1))
4819 value (org-match-string-no-properties 2))
4820 (if (stringp value) (setq value (org-trim value)))
4821 (cond
4822 ((equal key "TAGS")
4823 (setq tags (append tags (if tags '("\\n") nil)
4824 (org-split-string value splitre))))
4825 ((equal key "FILETAGS")
4826 (when (string-match "\\S-" value)
4827 (setq ftags
4828 (append
4829 ftags
4830 (apply 'append
4831 (mapcar (lambda (x) (org-split-string x ":"))
4832 (org-split-string value)))))))))))
4833 ;; Process the file tags.
4834 (and ftags (org-set-local 'org-file-tags
4835 (mapcar 'org-add-prop-inherited ftags)))
4836 (org-set-local 'org-tag-groups-alist nil)
4837 ;; Process the tags.
4838 ;; FIXME
4839 (when tags
4840 (let (e tgs g)
4841 (while (setq e (pop tags))
4842 (cond
4843 ((equal e "{")
4844 (progn (push '(:startgroup) tgs)
4845 (when (equal (nth 1 tags) ":")
4846 (push (list (replace-regexp-in-string
4847 "(.+)$" "" (nth 0 tags)))
4848 org-tag-groups-alist)
4849 (setq g 0))))
4850 ((equal e ":") (push '(:grouptags) tgs))
4851 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4852 ((equal e "\\n") (push '(:newline) tgs))
4853 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4854 (push (cons (match-string 1 e)
4855 (string-to-char (match-string 2 e))) tgs)
4856 (if (and g (> g 0))
4857 (setcar org-tag-groups-alist
4858 (append (car org-tag-groups-alist)
4859 (list (match-string 1 e)))))
4860 (if g (setq g (1+ g))))
4861 (t (push (list e) tgs)
4862 (if (and g (> g 0))
4863 (setcar org-tag-groups-alist
4864 (append (car org-tag-groups-alist) (list e))))
4865 (if g (setq g (1+ g))))))
4866 (org-set-local 'org-tag-alist nil)
4867 (while (setq e (pop tgs))
4868 (or (and (stringp (car e))
4869 (assoc (car e) org-tag-alist))
4870 (push e org-tag-alist))))))))
4872 (defun org-set-regexps-and-options ()
4873 "Precompute regular expressions used in the current buffer."
4874 (when (derived-mode-p 'org-mode)
4875 (org-set-local 'org-todo-kwd-alist nil)
4876 (org-set-local 'org-todo-key-alist nil)
4877 (org-set-local 'org-todo-key-trigger nil)
4878 (org-set-local 'org-todo-keywords-1 nil)
4879 (org-set-local 'org-done-keywords nil)
4880 (org-set-local 'org-todo-heads nil)
4881 (org-set-local 'org-todo-sets nil)
4882 (org-set-local 'org-todo-log-states nil)
4883 (org-set-local 'org-file-properties nil)
4884 (let ((re (org-make-options-regexp
4885 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4886 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4887 "SETUPFILE" "OPTIONS")
4888 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4889 (splitre "[ \t]+")
4890 (scripts org-use-sub-superscripts)
4891 kwds kws0 kwsa key log value cat arch const links hw dws
4892 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4893 (start 0))
4894 (save-excursion
4895 (save-restriction
4896 (widen)
4897 (goto-char (point-min))
4898 (while (or (and ext-setup-or-nil
4899 (let (ret)
4900 (with-temp-buffer
4901 (insert ext-setup-or-nil)
4902 (let ((major-mode 'org-mode))
4903 (org-set-regexps-and-options-for-tags)
4904 (setq ret (list org-file-tags org-tag-alist
4905 org-tag-groups-alist))))
4906 (setq org-file-tags (nth 0 ret)
4907 org-tag-alist (nth 1 ret)
4908 org-tag-groups-alist (nth 2 ret))))
4909 (and ext-setup-or-nil
4910 (string-match re ext-setup-or-nil start)
4911 (setq start (match-end 0)))
4912 (and (setq ext-setup-or-nil nil start 0)
4913 (re-search-forward re nil t)))
4914 (setq key (upcase (match-string 1 ext-setup-or-nil))
4915 value (org-match-string-no-properties 2 ext-setup-or-nil))
4916 (if (stringp value) (setq value (org-trim value)))
4917 (cond
4918 ((equal key "CATEGORY")
4919 (setq cat value))
4920 ((member key '("SEQ_TODO" "TODO"))
4921 (push (cons 'sequence (org-split-string value splitre)) kwds))
4922 ((equal key "TYP_TODO")
4923 (push (cons 'type (org-split-string value splitre)) kwds))
4924 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4925 ;; general TODO-like setup
4926 (push (cons (intern (downcase (match-string 1 key)))
4927 (org-split-string value splitre)) kwds))
4928 ((equal key "COLUMNS")
4929 (org-set-local 'org-columns-default-format value))
4930 ((equal key "LINK")
4931 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4932 (push (cons (match-string 1 value)
4933 (org-trim (match-string 2 value)))
4934 links)))
4935 ((equal key "PRIORITIES")
4936 (setq prio (org-split-string value " +")))
4937 ((equal key "PROPERTY")
4938 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4939 (setq props (org-update-property-plist (match-string 1 value)
4940 (match-string 2 value)
4941 props))))
4942 ((equal key "DRAWERS")
4943 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4944 ((equal key "CONSTANTS")
4945 (org-table-set-constants))
4946 ((equal key "STARTUP")
4947 (let ((opts (org-split-string value splitre))
4948 l var val)
4949 (while (setq l (pop opts))
4950 (when (setq l (assoc l org-startup-options))
4951 (setq var (nth 1 l) val (nth 2 l))
4952 (if (not (nth 3 l))
4953 (set (make-local-variable var) val)
4954 (if (not (listp (symbol-value var)))
4955 (set (make-local-variable var) nil))
4956 (set (make-local-variable var) (symbol-value var))
4957 (add-to-list var val))))))
4958 ((equal key "ARCHIVE")
4959 (setq arch value)
4960 (remove-text-properties 0 (length arch)
4961 '(face t fontified t) arch))
4962 ((equal key "OPTIONS")
4963 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4964 (setq scripts (read (match-string 2 value)))))
4965 ((and (equal key "SETUPFILE")
4966 ;; Prevent checking in Gnus messages
4967 (not buffer-read-only))
4968 (setq setup-contents (org-file-contents
4969 (expand-file-name
4970 (org-remove-double-quotes value))
4971 'noerror))
4972 (if (not ext-setup-or-nil)
4973 (setq ext-setup-or-nil setup-contents start 0)
4974 (setq ext-setup-or-nil
4975 (concat (substring ext-setup-or-nil 0 start)
4976 "\n" setup-contents "\n"
4977 (substring ext-setup-or-nil start)))))))
4978 ;; search for property blocks
4979 (goto-char (point-min))
4980 (while (re-search-forward org-block-regexp nil t)
4981 (when (equal "PROPERTY" (upcase (match-string 1)))
4982 (setq value (replace-regexp-in-string
4983 "[\n\r]" " " (match-string 4)))
4984 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4985 (setq props (org-update-property-plist (match-string 1 value)
4986 (match-string 2 value)
4987 props)))))))
4988 (org-set-local 'org-use-sub-superscripts scripts)
4989 (when cat
4990 (org-set-local 'org-category (intern cat))
4991 (push (cons "CATEGORY" cat) props))
4992 (when prio
4993 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4994 (setq prio (mapcar 'string-to-char prio))
4995 (org-set-local 'org-highest-priority (nth 0 prio))
4996 (org-set-local 'org-lowest-priority (nth 1 prio))
4997 (org-set-local 'org-default-priority (nth 2 prio)))
4998 (and props (org-set-local 'org-file-properties (nreverse props)))
4999 (and drawers (org-set-local 'org-drawers drawers))
5000 (and arch (org-set-local 'org-archive-location arch))
5001 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5002 ;; Process the TODO keywords
5003 (unless kwds
5004 ;; Use the global values as if they had been given locally.
5005 (setq kwds (default-value 'org-todo-keywords))
5006 (if (stringp (car kwds))
5007 (setq kwds (list (cons org-todo-interpretation
5008 (default-value 'org-todo-keywords)))))
5009 (setq kwds (reverse kwds)))
5010 (setq kwds (nreverse kwds))
5011 (let (inter kws kw)
5012 (while (setq kws (pop kwds))
5013 (let ((kws (or
5014 (run-hook-with-args-until-success
5015 'org-todo-setup-filter-hook kws)
5016 kws)))
5017 (setq inter (pop kws) sep (member "|" kws)
5018 kws0 (delete "|" (copy-sequence kws))
5019 kwsa nil
5020 kws1 (mapcar
5021 (lambda (x)
5022 ;; 1 2
5023 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5024 (progn
5025 (setq kw (match-string 1 x)
5026 key (and (match-end 2) (match-string 2 x))
5027 log (org-extract-log-state-settings x))
5028 (push (cons kw (and key (string-to-char key))) kwsa)
5029 (and log (push log org-todo-log-states))
5031 (error "Invalid TODO keyword %s" x)))
5032 kws0)
5033 kwsa (if kwsa (append '((:startgroup))
5034 (nreverse kwsa)
5035 '((:endgroup))))
5036 hw (car kws1)
5037 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5038 tail (list inter hw (car dws) (org-last dws))))
5039 (add-to-list 'org-todo-heads hw 'append)
5040 (push kws1 org-todo-sets)
5041 (setq org-done-keywords (append org-done-keywords dws nil))
5042 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5043 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5044 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5045 (setq org-todo-sets (nreverse org-todo-sets)
5046 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5047 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5048 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5049 ;; Compute the regular expressions and other local variables.
5050 ;; Using `org-outline-regexp-bol' would complicate them much,
5051 ;; because of the fixed white space at the end of that string.
5052 (if (not org-done-keywords)
5053 (setq org-done-keywords (and org-todo-keywords-1
5054 (list (org-last org-todo-keywords-1)))))
5055 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5056 (length org-scheduled-string)
5057 (length org-clock-string)
5058 (length org-closed-string)))
5059 org-drawer-regexp
5060 (concat "^[ \t]*:\\("
5061 (mapconcat 'regexp-quote org-drawers "\\|")
5062 "\\):[ \t]*$")
5063 org-not-done-keywords
5064 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5065 org-todo-regexp
5066 (concat "\\("
5067 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5068 "\\)")
5069 org-not-done-regexp
5070 (concat "\\("
5071 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5072 "\\)")
5073 org-not-done-heading-regexp
5074 (format org-heading-keyword-regexp-format org-not-done-regexp)
5075 org-todo-line-regexp
5076 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5077 org-complex-heading-regexp
5078 (concat "^\\(\\*+\\)"
5079 "\\(?: +" org-todo-regexp "\\)?"
5080 "\\(?: +\\(\\[#.\\]\\)\\)?"
5081 "\\(?: +\\(.*?\\)\\)??"
5082 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5083 "[ \t]*$")
5084 org-complex-heading-regexp-format
5085 (concat "^\\(\\*+\\)"
5086 "\\(?: +" org-todo-regexp "\\)?"
5087 "\\(?: +\\(\\[#.\\]\\)\\)?"
5088 "\\(?: +"
5089 ;; Stats cookies can be stuck to body.
5090 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5091 "\\(%s\\)"
5092 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5093 "\\)"
5094 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5095 "[ \t]*$")
5096 org-todo-line-tags-regexp
5097 (concat "^\\(\\*+\\)"
5098 "\\(?: +" org-todo-regexp "\\)?"
5099 "\\(?: +\\(.*?\\)\\)??"
5100 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5101 "[ \t]*$")
5102 org-deadline-regexp (concat "\\<" org-deadline-string)
5103 org-deadline-time-regexp
5104 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5105 org-deadline-time-hour-regexp
5106 (concat "\\<" org-deadline-string
5107 " *<\\(.+[0-9]\\{1,2\\}:[0-9]\\{2\\}[^>]*\\)>")
5108 org-deadline-line-regexp
5109 (concat "\\<\\(" org-deadline-string "\\).*")
5110 org-scheduled-regexp
5111 (concat "\\<" org-scheduled-string)
5112 org-scheduled-time-regexp
5113 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5114 org-scheduled-time-hour-regexp
5115 (concat "\\<" org-scheduled-string
5116 " *<\\(.+[0-9]\\{1,2\\}:[0-9]\\{2\\}[^>]*\\)>")
5117 org-closed-time-regexp
5118 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5119 org-keyword-time-regexp
5120 (concat "\\<\\(" org-scheduled-string
5121 "\\|" org-deadline-string
5122 "\\|" org-closed-string
5123 "\\|" org-clock-string "\\)"
5124 " *[[<]\\([^]>]+\\)[]>]")
5125 org-keyword-time-not-clock-regexp
5126 (concat "\\<\\(" org-scheduled-string
5127 "\\|" org-deadline-string
5128 "\\|" org-closed-string
5129 "\\)"
5130 " *[[<]\\([^]>]+\\)[]>]")
5131 org-maybe-keyword-time-regexp
5132 (concat "\\(\\<\\(" org-scheduled-string
5133 "\\|" org-deadline-string
5134 "\\|" org-closed-string
5135 "\\|" org-clock-string "\\)\\)?"
5136 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5137 org-all-time-keywords
5138 (mapcar (lambda (w) (substring w 0 -1))
5139 (list org-scheduled-string org-deadline-string
5140 org-clock-string org-closed-string)))
5141 (org-compute-latex-and-related-regexp)
5142 (org-set-font-lock-defaults))))
5144 (defun org-file-contents (file &optional noerror)
5145 "Return the contents of FILE, as a string."
5146 (if (or (not file)
5147 (not (file-readable-p file)))
5148 (if noerror
5149 (message "Cannot read file \"%s\"" file)
5150 (error "Cannot read file \"%s\"" file))
5151 (with-temp-buffer
5152 (insert-file-contents file)
5153 (buffer-string))))
5155 (defun org-extract-log-state-settings (x)
5156 "Extract the log state setting from a TODO keyword string.
5157 This will extract info from a string like \"WAIT(w@/!)\"."
5158 (let (kw key log1 log2)
5159 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5160 (setq kw (match-string 1 x)
5161 key (and (match-end 2) (match-string 2 x))
5162 log1 (and (match-end 3) (match-string 3 x))
5163 log2 (and (match-end 4) (match-string 4 x)))
5164 (and (or log1 log2)
5165 (list kw
5166 (and log1 (if (equal log1 "!") 'time 'note))
5167 (and log2 (if (equal log2 "!") 'time 'note)))))))
5169 (defun org-remove-keyword-keys (list)
5170 "Remove a pair of parenthesis at the end of each string in LIST."
5171 (mapcar (lambda (x)
5172 (if (string-match "(.*)$" x)
5173 (substring x 0 (match-beginning 0))
5175 list))
5177 (defun org-assign-fast-keys (alist)
5178 "Assign fast keys to a keyword-key alist.
5179 Respect keys that are already there."
5180 (let (new e (alt ?0))
5181 (while (setq e (pop alist))
5182 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5183 (cdr e)) ;; Key already assigned.
5184 (push e new)
5185 (let ((clist (string-to-list (downcase (car e))))
5186 (used (append new alist)))
5187 (when (= (car clist) ?@)
5188 (pop clist))
5189 (while (and clist (rassoc (car clist) used))
5190 (pop clist))
5191 (unless clist
5192 (while (rassoc alt used)
5193 (incf alt)))
5194 (push (cons (car e) (or (car clist) alt)) new))))
5195 (nreverse new)))
5197 ;;; Some variables used in various places
5199 (defvar org-window-configuration nil
5200 "Used in various places to store a window configuration.")
5201 (defvar org-selected-window nil
5202 "Used in various places to store a window configuration.")
5203 (defvar org-finish-function nil
5204 "Function to be called when `C-c C-c' is used.
5205 This is for getting out of special buffers like capture.")
5208 ;; FIXME: Occasionally check by commenting these, to make sure
5209 ;; no other functions uses these, forgetting to let-bind them.
5210 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5211 (defvar org-last-state)
5212 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5214 ;; Defined somewhere in this file, but used before definition.
5215 (defvar org-entities) ;; defined in org-entities.el
5216 (defvar org-struct-menu)
5217 (defvar org-org-menu)
5218 (defvar org-tbl-menu)
5220 ;;;; Define the Org-mode
5222 ;; We use a before-change function to check if a table might need
5223 ;; an update.
5224 (defvar org-table-may-need-update t
5225 "Indicates that a table might need an update.
5226 This variable is set by `org-before-change-function'.
5227 `org-table-align' sets it back to nil.")
5228 (defun org-before-change-function (beg end)
5229 "Every change indicates that a table might need an update."
5230 (setq org-table-may-need-update t))
5231 (defvar org-mode-map)
5232 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5233 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5234 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5235 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5236 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5237 (defvar org-table-buffer-is-an nil)
5239 (defvar bidi-paragraph-direction)
5240 (defvar buffer-face-mode-face)
5242 (require 'outline)
5243 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5244 (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"))
5245 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5247 ;; Other stuff we need.
5248 (require 'time-date)
5249 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5250 (require 'easymenu)
5251 (require 'overlay)
5253 ;; (require 'org-macs) moved higher up in the file before it is first used
5254 (require 'org-entities)
5255 ;; (require 'org-compat) moved higher up in the file before it is first used
5256 (require 'org-faces)
5257 (require 'org-list)
5258 (require 'org-pcomplete)
5259 (require 'org-src)
5260 (require 'org-footnote)
5261 (require 'org-macro)
5263 ;; babel
5264 (require 'ob)
5266 ;;;###autoload
5267 (define-derived-mode org-mode outline-mode "Org"
5268 "Outline-based notes management and organizer, alias
5269 \"Carsten's outline-mode for keeping track of everything.\"
5271 Org-mode develops organizational tasks around a NOTES file which
5272 contains information about projects as plain text. Org-mode is
5273 implemented on top of outline-mode, which is ideal to keep the content
5274 of large files well structured. It supports ToDo items, deadlines and
5275 time stamps, which magically appear in the diary listing of the Emacs
5276 calendar. Tables are easily created with a built-in table editor.
5277 Plain text URL-like links connect to websites, emails (VM), Usenet
5278 messages (Gnus), BBDB entries, and any files related to the project.
5279 For printing and sharing of notes, an Org-mode file (or a part of it)
5280 can be exported as a structured ASCII or HTML file.
5282 The following commands are available:
5284 \\{org-mode-map}"
5286 ;; Get rid of Outline menus, they are not needed
5287 ;; Need to do this here because define-derived-mode sets up
5288 ;; the keymap so late. Still, it is a waste to call this each time
5289 ;; we switch another buffer into org-mode.
5290 (if (featurep 'xemacs)
5291 (when (boundp 'outline-mode-menu-heading)
5292 ;; Assume this is Greg's port, it uses easymenu
5293 (easy-menu-remove outline-mode-menu-heading)
5294 (easy-menu-remove outline-mode-menu-show)
5295 (easy-menu-remove outline-mode-menu-hide))
5296 (define-key org-mode-map [menu-bar headings] 'undefined)
5297 (define-key org-mode-map [menu-bar hide] 'undefined)
5298 (define-key org-mode-map [menu-bar show] 'undefined))
5300 (org-load-modules-maybe)
5301 (easy-menu-add org-org-menu)
5302 (easy-menu-add org-tbl-menu)
5303 (org-install-agenda-files-menu)
5304 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5305 (add-to-invisibility-spec '(org-cwidth))
5306 (add-to-invisibility-spec '(org-hide-block . t))
5307 (when (featurep 'xemacs)
5308 (org-set-local 'line-move-ignore-invisible t))
5309 (org-set-local 'outline-regexp org-outline-regexp)
5310 (org-set-local 'outline-level 'org-outline-level)
5311 (setq bidi-paragraph-direction 'left-to-right)
5312 ;; FIXME Circumvent a bug in outline.el (Emacs <24.4)
5313 (set (make-local-variable 'paragraph-start) "\f\\|[ \t]*$\\|\\*+ ")
5314 (when (and org-ellipsis
5315 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5316 (fboundp 'make-glyph-code))
5317 (unless org-display-table
5318 (setq org-display-table (make-display-table)))
5319 (set-display-table-slot
5320 org-display-table 4
5321 (vconcat (mapcar
5322 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5323 org-ellipsis)))
5324 (if (stringp org-ellipsis) org-ellipsis "..."))))
5325 (setq buffer-display-table org-display-table))
5326 (org-set-regexps-and-options-for-tags)
5327 (org-set-regexps-and-options)
5328 (when (and org-tag-faces (not org-tags-special-faces-re))
5329 ;; tag faces set outside customize.... force initialization.
5330 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5331 ;; Calc embedded
5332 (org-set-local 'calc-embedded-open-mode "# ")
5333 ;; Modify a few syntax entries
5334 (modify-syntax-entry ?@ "w")
5335 (modify-syntax-entry ?\" "\"")
5336 (if org-startup-truncated (setq truncate-lines t))
5337 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5338 (org-set-local 'font-lock-unfontify-region-function
5339 'org-unfontify-region)
5340 ;; Activate before-change-function
5341 (org-set-local 'org-table-may-need-update t)
5342 (org-add-hook 'before-change-functions 'org-before-change-function nil
5343 'local)
5344 ;; Check for running clock before killing a buffer
5345 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5346 ;; Initialize macros templates.
5347 (org-macro-initialize-templates)
5348 ;; Initialize radio targets.
5349 (org-update-radio-target-regexp)
5350 ;; Indentation.
5351 (org-set-local 'indent-line-function 'org-indent-line)
5352 (org-set-local 'indent-region-function 'org-indent-region)
5353 ;; Filling and auto-filling.
5354 (org-setup-filling)
5355 ;; Comments.
5356 (org-setup-comments-handling)
5357 ;; Beginning/end of defun
5358 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5359 (org-set-local 'end-of-defun-function 'org-forward-element)
5360 ;; Next error for sparse trees
5361 (org-set-local 'next-error-function 'org-occur-next-match)
5362 ;; Make sure dependence stuff works reliably, even for users who set it
5363 ;; too late :-(
5364 (if org-enforce-todo-dependencies
5365 (add-hook 'org-blocker-hook
5366 'org-block-todo-from-children-or-siblings-or-parent)
5367 (remove-hook 'org-blocker-hook
5368 'org-block-todo-from-children-or-siblings-or-parent))
5369 (if org-enforce-todo-checkbox-dependencies
5370 (add-hook 'org-blocker-hook
5371 'org-block-todo-from-checkboxes)
5372 (remove-hook 'org-blocker-hook
5373 'org-block-todo-from-checkboxes))
5375 ;; Align options lines
5376 (org-set-local
5377 'align-mode-rules-list
5378 '((org-in-buffer-settings
5379 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5380 (modes . '(org-mode)))))
5382 ;; Imenu
5383 (org-set-local 'imenu-create-index-function
5384 'org-imenu-get-tree)
5386 ;; Make isearch reveal context
5387 (if (or (featurep 'xemacs)
5388 (not (boundp 'outline-isearch-open-invisible-function)))
5389 ;; Emacs 21 and XEmacs make use of the hook
5390 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5391 ;; Emacs 22 deals with this through a special variable
5392 (org-set-local 'outline-isearch-open-invisible-function
5393 (lambda (&rest ignore) (org-show-context 'isearch)))
5394 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5396 ;; Setup the pcomplete hooks
5397 (set (make-local-variable 'pcomplete-command-completion-function)
5398 'org-pcomplete-initial)
5399 (set (make-local-variable 'pcomplete-command-name-function)
5400 'org-command-at-point)
5401 (set (make-local-variable 'pcomplete-default-completion-function)
5402 'ignore)
5403 (set (make-local-variable 'pcomplete-parse-arguments-function)
5404 'org-parse-arguments)
5405 (set (make-local-variable 'pcomplete-termination-string) "")
5406 (when (>= emacs-major-version 23)
5407 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5409 ;; If empty file that did not turn on org-mode automatically, make it to.
5410 (if (and org-insert-mode-line-in-empty-file
5411 (org-called-interactively-p 'any)
5412 (= (point-min) (point-max)))
5413 (insert "# -*- mode: org -*-\n\n"))
5414 (unless org-inhibit-startup
5415 (org-unmodified
5416 (and org-startup-with-beamer-mode (org-beamer-mode))
5417 (when org-startup-align-all-tables
5418 (org-table-map-tables 'org-table-align 'quietly))
5419 (when org-startup-with-inline-images
5420 (org-display-inline-images))
5421 (when org-startup-with-latex-preview
5422 (org-preview-latex-fragment))
5423 (unless org-inhibit-startup-visibility-stuff
5424 (org-set-startup-visibility))))
5425 ;; Try to set org-hide correctly
5426 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5428 ;; Update `customize-package-emacs-version-alist'
5429 (add-to-list 'customize-package-emacs-version-alist
5430 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5431 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5432 ("8.0" . "24.4")))
5434 (defvar org-mode-transpose-word-syntax-table
5435 (let ((st (make-syntax-table)))
5436 (mapc (lambda(c) (modify-syntax-entry
5437 (string-to-char (car c)) "w p" st))
5438 org-emphasis-alist)
5439 st))
5441 (when (fboundp 'abbrev-table-put)
5442 (abbrev-table-put org-mode-abbrev-table
5443 :parents (list text-mode-abbrev-table)))
5445 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5447 (defsubst org-fix-ellipsis-at-bol ()
5448 (save-excursion (goto-char (window-start)) (recenter 0)))
5450 (defun org-find-invisible-foreground ()
5451 (let ((candidates (remove
5452 "unspecified-bg"
5453 (nconc
5454 (list (face-background 'default)
5455 (face-background 'org-default))
5456 (mapcar
5457 (lambda (alist)
5458 (when (boundp alist)
5459 (cdr (assoc 'background-color (symbol-value alist)))))
5460 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5461 (list (face-foreground 'org-hide))))))
5462 (car (remove nil candidates))))
5464 (defun org-current-time (&optional rounding-minutes past)
5465 "Current time, possibly rounded to ROUNDING-MINUTES.
5466 When ROUNDING-MINUTES is not an integer, fall back on the car of
5467 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5468 the rounding returns a past time."
5469 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5470 (car org-time-stamp-rounding-minutes)))
5471 (time (decode-time)) res)
5472 (if (< r 1)
5473 (current-time)
5474 (setq res
5475 (apply 'encode-time
5476 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5477 (nthcdr 2 time))))
5478 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5479 (seconds-to-time (- (org-float-time res) (* r 60)))
5480 res))))
5482 (defun org-today ()
5483 "Return today date, considering `org-extend-today-until'."
5484 (time-to-days
5485 (time-subtract (current-time)
5486 (list 0 (* 3600 org-extend-today-until) 0))))
5488 ;;;; Font-Lock stuff, including the activators
5490 (defvar org-mouse-map (make-sparse-keymap))
5491 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5492 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5493 (when org-mouse-1-follows-link
5494 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5495 (when org-tab-follows-link
5496 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5497 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5499 (require 'font-lock)
5501 (defconst org-non-link-chars "]\t\n\r<>")
5502 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5503 "shell" "elisp" "doi" "message"))
5504 (defvar org-link-types-re nil
5505 "Matches a link that has a url-like prefix like \"http:\"")
5506 (defvar org-link-re-with-space nil
5507 "Matches a link with spaces, optional angular brackets around it.")
5508 (defvar org-link-re-with-space2 nil
5509 "Matches a link with spaces, optional angular brackets around it.")
5510 (defvar org-link-re-with-space3 nil
5511 "Matches a link with spaces, only for internal part in bracket links.")
5512 (defvar org-angle-link-re nil
5513 "Matches link with angular brackets, spaces are allowed.")
5514 (defvar org-plain-link-re nil
5515 "Matches plain link, without spaces.")
5516 (defvar org-bracket-link-regexp nil
5517 "Matches a link in double brackets.")
5518 (defvar org-bracket-link-analytic-regexp nil
5519 "Regular expression used to analyze links.
5520 Here is what the match groups contain after a match:
5521 1: http:
5522 2: http
5523 3: path
5524 4: [desc]
5525 5: desc")
5526 (defvar org-bracket-link-analytic-regexp++ nil
5527 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5528 (defvar org-any-link-re nil
5529 "Regular expression matching any link.")
5531 (defconst org-match-sexp-depth 3
5532 "Number of stacked braces for sub/superscript matching.")
5534 (defun org-create-multibrace-regexp (left right n)
5535 "Create a regular expression which will match a balanced sexp.
5536 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5537 as single character strings.
5538 The regexp returned will match the entire expression including the
5539 delimiters. It will also define a single group which contains the
5540 match except for the outermost delimiters. The maximum depth of
5541 stacked delimiters is N. Escaping delimiters is not possible."
5542 (let* ((nothing (concat "[^" left right "]*?"))
5543 (or "\\|")
5544 (re nothing)
5545 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5546 (while (> n 1)
5547 (setq n (1- n)
5548 re (concat re or next)
5549 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5550 (concat left "\\(" re "\\)" right)))
5552 (defvar org-match-substring-regexp
5553 (concat
5554 "\\(\\S-\\)\\([_^]\\)\\("
5555 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5556 "\\|"
5557 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5558 "\\|"
5559 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5560 "The regular expression matching a sub- or superscript.")
5562 (defvar org-match-substring-with-braces-regexp
5563 (concat
5564 "\\(\\S-\\)\\([_^]\\)\\("
5565 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5566 "\\)")
5567 "The regular expression matching a sub- or superscript, forcing braces.")
5569 (defun org-make-link-regexps ()
5570 "Update the link regular expressions.
5571 This should be called after the variable `org-link-types' has changed."
5572 (setq org-link-types-re
5573 (concat
5574 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5575 org-link-re-with-space
5576 (concat
5577 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5578 "\\([^" org-non-link-chars " ]"
5579 "[^" org-non-link-chars "]*"
5580 "[^" org-non-link-chars " ]\\)>?")
5581 org-link-re-with-space2
5582 (concat
5583 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5584 "\\([^" org-non-link-chars " ]"
5585 "[^\t\n\r]*"
5586 "[^" org-non-link-chars " ]\\)>?")
5587 org-link-re-with-space3
5588 (concat
5589 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5590 "\\([^" org-non-link-chars " ]"
5591 "[^\t\n\r]*\\)")
5592 org-angle-link-re
5593 (concat
5594 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5595 "\\([^" org-non-link-chars " ]"
5596 "[^" org-non-link-chars "]*"
5597 "\\)>")
5598 org-plain-link-re
5599 (concat
5600 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5601 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5602 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5603 org-bracket-link-regexp
5604 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5605 org-bracket-link-analytic-regexp
5606 (concat
5607 "\\[\\["
5608 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5609 "\\([^]]+\\)"
5610 "\\]"
5611 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5612 "\\]")
5613 org-bracket-link-analytic-regexp++
5614 (concat
5615 "\\[\\["
5616 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5617 "\\([^]]+\\)"
5618 "\\]"
5619 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5620 "\\]")
5621 org-any-link-re
5622 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5623 org-angle-link-re "\\)\\|\\("
5624 org-plain-link-re "\\)")))
5626 (org-make-link-regexps)
5628 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5629 "Regular expression for fast time stamp matching.")
5630 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5631 "Regular expression for fast time stamp matching.")
5632 (defconst org-ts-regexp0
5633 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5634 "Regular expression matching time strings for analysis.
5635 This one does not require the space after the date, so it can be used
5636 on a string that terminates immediately after the date.")
5637 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5638 "Regular expression matching time strings for analysis.")
5639 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5640 "Regular expression matching time stamps, with groups.")
5641 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5642 "Regular expression matching time stamps (also [..]), with groups.")
5643 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5644 "Regular expression matching a time stamp range.")
5645 (defconst org-tr-regexp-both
5646 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5647 "Regular expression matching a time stamp range.")
5648 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5649 org-ts-regexp "\\)?")
5650 "Regular expression matching a time stamp or time stamp range.")
5651 (defconst org-tsr-regexp-both
5652 (concat org-ts-regexp-both "\\(--?-?"
5653 org-ts-regexp-both "\\)?")
5654 "Regular expression matching a time stamp or time stamp range.
5655 The time stamps may be either active or inactive.")
5657 (defvar org-emph-face nil)
5659 (defun org-do-emphasis-faces (limit)
5660 "Run through the buffer and add overlays to emphasized strings."
5661 (let (rtn a)
5662 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5663 (if (not (= (char-after (match-beginning 3))
5664 (char-after (match-beginning 4))))
5665 (progn
5666 (setq rtn t)
5667 (setq a (assoc (match-string 3) org-emphasis-alist))
5668 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5669 'face
5670 (nth 1 a))
5671 (and (nth 4 a)
5672 (org-remove-flyspell-overlays-in
5673 (match-beginning 0) (match-end 0)))
5674 (add-text-properties (match-beginning 2) (match-end 2)
5675 '(font-lock-multiline t org-emphasis t))
5676 (when org-hide-emphasis-markers
5677 (add-text-properties (match-end 4) (match-beginning 5)
5678 '(invisible org-link))
5679 (add-text-properties (match-beginning 3) (match-end 3)
5680 '(invisible org-link)))))
5681 (backward-char 1))
5682 rtn))
5684 (defun org-emphasize (&optional char)
5685 "Insert or change an emphasis, i.e. a font like bold or italic.
5686 If there is an active region, change that region to a new emphasis.
5687 If there is no region, just insert the marker characters and position
5688 the cursor between them.
5689 CHAR should be either the marker character, or the first character of the
5690 HTML tag associated with that emphasis. If CHAR is a space, the means
5691 to remove the emphasis of the selected region.
5692 If char is not given (for example in an interactive call) it
5693 will be prompted for."
5694 (interactive)
5695 (let ((eal org-emphasis-alist) e det
5696 (erc org-emphasis-regexp-components)
5697 (prompt "")
5698 (string "") beg end move tag c s)
5699 (if (org-region-active-p)
5700 (setq beg (region-beginning) end (region-end)
5701 string (buffer-substring beg end))
5702 (setq move t))
5704 (while (setq e (pop eal))
5705 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5706 c (aref tag 0))
5707 (push (cons c (string-to-char (car e))) det)
5708 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5709 (substring tag 1)))))
5710 (setq det (nreverse det))
5711 (unless char
5712 (message "%s" (concat "Emphasis marker or tag:" prompt))
5713 (setq char (read-char-exclusive)))
5714 (setq char (or (cdr (assoc char det)) char))
5715 (if (equal char ?\ )
5716 (setq s "" move nil)
5717 (unless (assoc (char-to-string char) org-emphasis-alist)
5718 (error "No such emphasis marker: \"%c\"" char))
5719 (setq s (char-to-string char)))
5720 (while (and (> (length string) 1)
5721 (equal (substring string 0 1) (substring string -1))
5722 (assoc (substring string 0 1) org-emphasis-alist))
5723 (setq string (substring string 1 -1)))
5724 (setq string (concat s string s))
5725 (if beg (delete-region beg end))
5726 (unless (or (bolp)
5727 (string-match (concat "[" (nth 0 erc) "\n]")
5728 (char-to-string (char-before (point)))))
5729 (insert " "))
5730 (unless (or (eobp)
5731 (string-match (concat "[" (nth 1 erc) "\n]")
5732 (char-to-string (char-after (point)))))
5733 (insert " ") (backward-char 1))
5734 (insert string)
5735 (and move (backward-char 1))))
5737 (defconst org-nonsticky-props
5738 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5740 (defsubst org-rear-nonsticky-at (pos)
5741 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5743 (defun org-activate-plain-links (limit)
5744 "Run through the buffer and add overlays to links."
5745 (let (f hl)
5746 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5747 (not (org-in-src-block-p)))
5748 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5749 (setq f (get-text-property (match-beginning 0) 'face))
5750 (setq hl (org-match-string-no-properties 0))
5751 (if (or (eq f 'org-tag)
5752 (and (listp f) (memq 'org-tag f)))
5754 (add-text-properties (match-beginning 0) (match-end 0)
5755 (list 'mouse-face 'highlight
5756 'face 'org-link
5757 'htmlize-link `(:uri ,hl)
5758 'keymap org-mouse-map))
5759 (org-rear-nonsticky-at (match-end 0)))
5760 t)))
5762 (defun org-activate-code (limit)
5763 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5764 (progn
5765 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5766 (remove-text-properties (match-beginning 0) (match-end 0)
5767 '(display t invisible t intangible t))
5768 t)))
5770 (defcustom org-src-fontify-natively nil
5771 "When non-nil, fontify code in code blocks."
5772 :type 'boolean
5773 :version "24.1"
5774 :group 'org-appearance
5775 :group 'org-babel)
5777 (defcustom org-allow-promoting-top-level-subtree nil
5778 "When non-nil, allow promoting a top level subtree.
5779 The leading star of the top level headline will be replaced
5780 by a #."
5781 :type 'boolean
5782 :version "24.1"
5783 :group 'org-appearance)
5785 (defun org-fontify-meta-lines-and-blocks (limit)
5786 (condition-case nil
5787 (org-fontify-meta-lines-and-blocks-1 limit)
5788 (error (message "org-mode fontification error"))))
5790 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5791 "Fontify #+ lines and blocks."
5792 (let ((case-fold-search t))
5793 (if (re-search-forward
5794 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5795 limit t)
5796 (let ((beg (match-beginning 0))
5797 (block-start (match-end 0))
5798 (block-end nil)
5799 (lang (match-string 7))
5800 (beg1 (line-beginning-position 2))
5801 (dc1 (downcase (match-string 2)))
5802 (dc3 (downcase (match-string 3)))
5803 end end1 quoting block-type ovl)
5804 (cond
5805 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5806 ;; a single line of backend-specific content
5807 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5808 (remove-text-properties (match-beginning 0) (match-end 0)
5809 '(display t invisible t intangible t))
5810 (add-text-properties (match-beginning 1) (match-end 3)
5811 '(font-lock-fontified t face org-meta-line))
5812 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5813 '(font-lock-fontified t face org-block))
5814 ; for backend-specific code
5816 ((and (match-end 4) (equal dc3 "+begin"))
5817 ;; Truly a block
5818 (setq block-type (downcase (match-string 5))
5819 quoting (member block-type org-protecting-blocks))
5820 (when (re-search-forward
5821 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5822 nil t) ;; on purpose, we look further than LIMIT
5823 (setq end (min (point-max) (match-end 0))
5824 end1 (min (point-max) (1- (match-beginning 0))))
5825 (setq block-end (match-beginning 0))
5826 (when quoting
5827 (remove-text-properties beg end
5828 '(display t invisible t intangible t)))
5829 (add-text-properties
5830 beg end
5831 '(font-lock-fontified t font-lock-multiline t))
5832 (add-text-properties beg beg1 '(face org-meta-line))
5833 (add-text-properties end1 (min (point-max) (1+ end))
5834 '(face org-meta-line)) ; for end_src
5835 (cond
5836 ((and lang (not (string= lang "")) org-src-fontify-natively)
5837 (org-src-font-lock-fontify-block lang block-start block-end)
5838 ;; remove old background overlays
5839 (mapc (lambda (ov)
5840 (if (eq (overlay-get ov 'face) 'org-block-background)
5841 (delete-overlay ov)))
5842 (overlays-at (/ (+ beg1 block-end) 2)))
5843 ;; add a background overlay
5844 (setq ovl (make-overlay beg1 block-end))
5845 (overlay-put ovl 'face 'org-block-background)
5846 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5847 (quoting
5848 (add-text-properties beg1 (min (point-max) (1+ end1))
5849 '(face org-block))) ; end of source block
5850 ((not org-fontify-quote-and-verse-blocks))
5851 ((string= block-type "quote")
5852 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5853 ((string= block-type "verse")
5854 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5855 (add-text-properties beg beg1 '(face org-block-begin-line))
5856 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5857 '(face org-block-end-line))
5859 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5860 (add-text-properties
5861 beg (match-end 3)
5862 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5863 '(font-lock-fontified t invisible t)
5864 '(font-lock-fontified t face org-document-info-keyword)))
5865 (add-text-properties
5866 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5867 (if (string-equal dc1 "+title:")
5868 '(font-lock-fontified t face org-document-title)
5869 '(font-lock-fontified t face org-document-info))))
5870 ((or (equal dc1 "+results")
5871 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5872 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5873 "+call:" "+header:" "+headers:" "+name:"))
5874 (and (match-end 4) (equal dc3 "+attr")))
5875 (add-text-properties
5876 beg (match-end 0)
5877 '(font-lock-fontified t face org-meta-line))
5879 ((member dc3 '(" " ""))
5880 (add-text-properties
5881 beg (match-end 0)
5882 '(font-lock-fontified t face font-lock-comment-face)))
5883 ((not (member (char-after beg) '(?\ ?\t)))
5884 ;; just any other in-buffer setting, but not indented
5885 (add-text-properties
5886 beg (match-end 0)
5887 '(font-lock-fontified t face org-meta-line))
5889 (t nil))))))
5891 (defun org-activate-angle-links (limit)
5892 "Run through the buffer and add overlays to links."
5893 (if (and (re-search-forward org-angle-link-re limit t)
5894 (not (org-in-src-block-p)))
5895 (progn
5896 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5897 (add-text-properties (match-beginning 0) (match-end 0)
5898 (list 'mouse-face 'highlight
5899 'keymap org-mouse-map))
5900 (org-rear-nonsticky-at (match-end 0))
5901 t)))
5903 (defun org-activate-footnote-links (limit)
5904 "Run through the buffer and add overlays to footnotes."
5905 (let ((fn (org-footnote-next-reference-or-definition limit)))
5906 (when fn
5907 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5908 (org-remove-flyspell-overlays-in beg end)
5909 (add-text-properties beg end
5910 (list 'mouse-face 'highlight
5911 'keymap org-mouse-map
5912 'help-echo
5913 (if (= (point-at-bol) beg)
5914 "Footnote definition"
5915 "Footnote reference")
5916 'font-lock-fontified t
5917 'font-lock-multiline t
5918 'face 'org-footnote))))))
5920 (defun org-activate-bracket-links (limit)
5921 "Run through the buffer and add overlays to bracketed links."
5922 (if (and (re-search-forward org-bracket-link-regexp limit t)
5923 (not (org-in-src-block-p)))
5924 (let* ((hl (org-match-string-no-properties 1))
5925 (help (concat "LINK: " hl))
5926 ;; FIXME: Above we should remove the escapes. But that
5927 ;; requires another match, protecting match data, a lot
5928 ;; of overhead for font-lock.
5929 (ip (org-maybe-intangible
5930 (list 'invisible 'org-link
5931 'keymap org-mouse-map 'mouse-face 'highlight
5932 'font-lock-multiline t 'help-echo help
5933 'htmlize-link `(:uri ,hl))))
5934 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5935 'font-lock-multiline t 'help-echo help
5936 'htmlize-link `(:uri ,hl))))
5937 ;; We need to remove the invisible property here. Table narrowing
5938 ;; may have made some of this invisible.
5939 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5940 (remove-text-properties (match-beginning 0) (match-end 0)
5941 '(invisible nil))
5942 (if (match-end 3)
5943 (progn
5944 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5945 (org-rear-nonsticky-at (match-beginning 3))
5946 (add-text-properties (match-beginning 3) (match-end 3) vp)
5947 (org-rear-nonsticky-at (match-end 3))
5948 (add-text-properties (match-end 3) (match-end 0) ip)
5949 (org-rear-nonsticky-at (match-end 0)))
5950 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5951 (org-rear-nonsticky-at (match-beginning 1))
5952 (add-text-properties (match-beginning 1) (match-end 1) vp)
5953 (org-rear-nonsticky-at (match-end 1))
5954 (add-text-properties (match-end 1) (match-end 0) ip)
5955 (org-rear-nonsticky-at (match-end 0)))
5956 t)))
5958 (defun org-activate-dates (limit)
5959 "Run through the buffer and add overlays to dates."
5960 (if (and (re-search-forward org-tsr-regexp-both limit t)
5961 (not (equal (char-before (match-beginning 0)) 91)))
5962 (progn
5963 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5964 (add-text-properties (match-beginning 0) (match-end 0)
5965 (list 'mouse-face 'highlight
5966 'keymap org-mouse-map))
5967 (org-rear-nonsticky-at (match-end 0))
5968 (when org-display-custom-times
5969 (if (match-end 3)
5970 (org-display-custom-time (match-beginning 3) (match-end 3)))
5971 (org-display-custom-time (match-beginning 1) (match-end 1)))
5972 t)))
5974 (defvar org-target-link-regexp nil
5975 "Regular expression matching radio targets in plain text.")
5976 (make-variable-buffer-local 'org-target-link-regexp)
5977 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5978 "Regular expression matching a link target.")
5979 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5980 "Regular expression matching a radio target.")
5981 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5982 "Regular expression matching any target.")
5984 (defun org-activate-target-links (limit)
5985 "Run through the buffer and add overlays to target matches."
5986 (when org-target-link-regexp
5987 (let ((case-fold-search t))
5988 (if (re-search-forward org-target-link-regexp limit t)
5989 (progn
5990 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5991 (add-text-properties (match-beginning 0) (match-end 0)
5992 (list 'mouse-face 'highlight
5993 'keymap org-mouse-map
5994 'help-echo "Radio target link"
5995 'org-linked-text t))
5996 (org-rear-nonsticky-at (match-end 0))
5997 t)))))
5999 (defun org-update-radio-target-regexp ()
6000 "Find all radio targets in this file and update the regular expression."
6001 (interactive)
6002 (when (memq 'radio org-activate-links)
6003 (setq org-target-link-regexp
6004 (org-make-target-link-regexp (org-all-targets 'radio)))
6005 (org-restart-font-lock)))
6007 (defun org-hide-wide-columns (limit)
6008 (let (s e)
6009 (setq s (text-property-any (point) (or limit (point-max))
6010 'org-cwidth t))
6011 (when s
6012 (setq e (next-single-property-change s 'org-cwidth))
6013 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6014 (goto-char e)
6015 t)))
6017 (defvar org-latex-and-related-regexp nil
6018 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6019 (defvar org-match-substring-regexp)
6020 (defvar org-match-substring-with-braces-regexp)
6022 (defun org-compute-latex-and-related-regexp ()
6023 "Compute regular expression for LaTeX, entities and sub/superscript.
6024 Result depends on variable `org-highlight-latex-and-related'."
6025 (org-set-local
6026 'org-latex-and-related-regexp
6027 (let* ((re-sub
6028 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6029 ((eq org-use-sub-superscripts '{})
6030 (list org-match-substring-with-braces-regexp))
6031 (org-use-sub-superscripts (list org-match-substring-regexp))))
6032 (re-latex
6033 (when (memq 'latex org-highlight-latex-and-related)
6034 (let ((matchers (plist-get org-format-latex-options :matchers)))
6035 (delq nil
6036 (mapcar (lambda (x)
6037 (and (member (car x) matchers) (nth 1 x)))
6038 org-latex-regexps)))))
6039 (re-entities
6040 (when (memq 'entities org-highlight-latex-and-related)
6041 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6042 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6044 (defun org-do-latex-and-related (limit)
6045 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6046 LIMIT bounds the search for syntax to highlight. Stop at first
6047 highlighted object, if any. Return t if some highlighting was
6048 done, nil otherwise."
6049 (when (org-string-nw-p org-latex-and-related-regexp)
6050 (catch 'found
6051 (while (re-search-forward org-latex-and-related-regexp limit t)
6052 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6053 'face))
6054 '(org-code org-verbatim underline))
6055 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6056 '(?_ ?^))
6058 0)))
6059 (font-lock-prepend-text-property
6060 (+ offset (match-beginning 0)) (match-end 0)
6061 'face 'org-latex-and-related)
6062 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6063 '(font-lock-multiline t)))
6064 (throw 'found t)))
6065 nil)))
6067 (defun org-restart-font-lock ()
6068 "Restart `font-lock-mode', to force refontification."
6069 (when (and (boundp 'font-lock-mode) font-lock-mode)
6070 (font-lock-mode -1)
6071 (font-lock-mode 1)))
6073 (defun org-all-targets (&optional radio)
6074 "Return a list of all targets in this file.
6075 When optional argument RADIO is non-nil, only find radio
6076 targets."
6077 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6078 (save-excursion
6079 (goto-char (point-min))
6080 (while (re-search-forward re nil t)
6081 ;; Make sure point is really within the object.
6082 (backward-char)
6083 (let ((obj (org-element-context)))
6084 (when (memq (org-element-type obj) '(radio-target target))
6085 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6086 rtn)))
6088 (defun org-make-target-link-regexp (targets)
6089 "Make regular expression matching all strings in TARGETS.
6090 The regular expression finds the targets also if there is a line break
6091 between words."
6092 (and targets
6093 (concat
6094 "\\<\\("
6095 (mapconcat
6096 (lambda (x)
6097 (setq x (regexp-quote x))
6098 (while (string-match " +" x)
6099 (setq x (replace-match "\\s-+" t t x)))
6101 targets
6102 "\\|")
6103 "\\)\\>")))
6105 (defun org-activate-tags (limit)
6106 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6107 (progn
6108 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6109 (add-text-properties (match-beginning 1) (match-end 1)
6110 (list 'mouse-face 'highlight
6111 'keymap org-mouse-map))
6112 (org-rear-nonsticky-at (match-end 1))
6113 t)))
6115 (defun org-outline-level ()
6116 "Compute the outline level of the heading at point.
6117 If this is called at a normal headline, the level is the number of stars.
6118 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6119 (save-excursion
6120 (if (not (condition-case nil
6121 (org-back-to-heading t)
6122 (error nil)))
6124 (looking-at org-outline-regexp)
6125 (1- (- (match-end 0) (match-beginning 0))))))
6127 (defvar org-font-lock-keywords nil)
6129 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
6130 "Regular expression matching a property line.")
6132 (defvar org-font-lock-hook nil
6133 "Functions to be called for special font lock stuff.")
6135 (defvar org-font-lock-set-keywords-hook nil
6136 "Functions that can manipulate `org-font-lock-extra-keywords'.
6137 This is called after `org-font-lock-extra-keywords' is defined, but before
6138 it is installed to be used by font lock. This can be useful if something
6139 needs to be inserted at a specific position in the font-lock sequence.")
6141 (defun org-font-lock-hook (limit)
6142 "Run `org-font-lock-hook' within LIMIT."
6143 (run-hook-with-args 'org-font-lock-hook limit))
6145 (defun org-set-font-lock-defaults ()
6146 "Set font lock defaults for the current buffer."
6147 (let* ((em org-fontify-emphasized-text)
6148 (lk org-activate-links)
6149 (org-font-lock-extra-keywords
6150 (list
6151 ;; Call the hook
6152 '(org-font-lock-hook)
6153 ;; Headlines
6154 `(,(if org-fontify-whole-heading-line
6155 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6156 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6157 (1 (org-get-level-face 1))
6158 (2 (org-get-level-face 2))
6159 (3 (org-get-level-face 3)))
6160 ;; Table lines
6161 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6162 (1 'org-table t))
6163 ;; Table internals
6164 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6165 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6166 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6167 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6168 ;; Drawers
6169 (list org-drawer-regexp '(0 'org-special-keyword t))
6170 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6171 ;; Properties
6172 (list org-property-re
6173 '(1 'org-special-keyword t)
6174 '(3 'org-property-value t))
6175 ;; Links
6176 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6177 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6178 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6179 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6180 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6181 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6182 (if (memq 'footnote lk) '(org-activate-footnote-links))
6183 ;; Targets.
6184 (list org-any-target-regexp '(0 'org-target t))
6185 ;; Diary sexps.
6186 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6187 ;; Macro
6188 '("{{{.+}}}" (0 'org-macro t))
6189 '(org-hide-wide-columns (0 nil append))
6190 ;; TODO keyword
6191 (list (format org-heading-keyword-regexp-format
6192 org-todo-regexp)
6193 '(2 (org-get-todo-face 2) t))
6194 ;; DONE
6195 (if org-fontify-done-headline
6196 (list (format org-heading-keyword-regexp-format
6197 (concat
6198 "\\(?:"
6199 (mapconcat 'regexp-quote org-done-keywords "\\|")
6200 "\\)"))
6201 '(2 'org-headline-done t))
6202 nil)
6203 ;; Priorities
6204 '(org-font-lock-add-priority-faces)
6205 ;; Tags
6206 '(org-font-lock-add-tag-faces)
6207 ;; Tags groups
6208 (if (and org-group-tags org-tag-groups-alist)
6209 (list (concat org-outline-regexp-bol ".+\\(:"
6210 (regexp-opt (mapcar 'car org-tag-groups-alist))
6211 ":\\).*$")
6212 '(1 'org-tag-group prepend)))
6213 ;; Special keywords
6214 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6215 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6216 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6217 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6218 ;; Emphasis
6219 (if em
6220 (if (featurep 'xemacs)
6221 '(org-do-emphasis-faces (0 nil append))
6222 '(org-do-emphasis-faces)))
6223 ;; Checkboxes
6224 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6225 1 'org-checkbox prepend)
6226 (if (cdr (assq 'checkbox org-list-automatic-rules))
6227 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6228 (0 (org-get-checkbox-statistics-face) t)))
6229 ;; Description list items
6230 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6231 1 'org-list-dt prepend)
6232 ;; ARCHIVEd headings
6233 (list (concat
6234 org-outline-regexp-bol
6235 "\\(.*:" org-archive-tag ":.*\\)")
6236 '(1 'org-archived prepend))
6237 ;; Specials
6238 '(org-do-latex-and-related)
6239 '(org-fontify-entities)
6240 '(org-raise-scripts)
6241 ;; Code
6242 '(org-activate-code (1 'org-code t))
6243 ;; COMMENT
6244 (list (format org-heading-keyword-regexp-format
6245 (concat "\\("
6246 org-comment-string "\\|" org-quote-string
6247 "\\)"))
6248 '(2 'org-special-keyword t))
6249 ;; Blocks and meta lines
6250 '(org-fontify-meta-lines-and-blocks)
6252 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6253 (run-hooks 'org-font-lock-set-keywords-hook)
6254 ;; Now set the full font-lock-keywords
6255 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6256 (org-set-local 'font-lock-defaults
6257 '(org-font-lock-keywords t nil nil backward-paragraph))
6258 (kill-local-variable 'font-lock-keywords) nil))
6260 (defun org-toggle-pretty-entities ()
6261 "Toggle the composition display of entities as UTF8 characters."
6262 (interactive)
6263 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6264 (org-restart-font-lock)
6265 (if org-pretty-entities
6266 (message "Entities are now displayed as UTF8 characters")
6267 (save-restriction
6268 (widen)
6269 (org-decompose-region (point-min) (point-max))
6270 (message "Entities are now displayed as plain text"))))
6272 (defvar org-custom-properties-overlays nil
6273 "List of overlays used for custom properties.")
6274 (make-variable-buffer-local 'org-custom-properties-overlays)
6276 (defun org-toggle-custom-properties-visibility ()
6277 "Display or hide properties in `org-custom-properties'."
6278 (interactive)
6279 (if org-custom-properties-overlays
6280 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6281 (setq org-custom-properties-overlays nil))
6282 (unless (not org-custom-properties)
6283 (save-excursion
6284 (save-restriction
6285 (widen)
6286 (goto-char (point-min))
6287 (while (re-search-forward org-property-re nil t)
6288 (mapc (lambda(p)
6289 (when (equal p (substring (match-string 1) 1 -1))
6290 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6291 (overlay-put o 'invisible t)
6292 (overlay-put o 'org-custom-property t)
6293 (push o org-custom-properties-overlays))))
6294 org-custom-properties)))))))
6296 (defun org-fontify-entities (limit)
6297 "Find an entity to fontify."
6298 (let (ee)
6299 (when org-pretty-entities
6300 (catch 'match
6301 (while (re-search-forward
6302 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6303 limit t)
6304 (if (and (not (org-in-indented-comment-line))
6305 (setq ee (org-entity-get (match-string 1)))
6306 (= (length (nth 6 ee)) 1))
6307 (let*
6308 ((end (if (equal (match-string 2) "{}")
6309 (match-end 2)
6310 (match-end 1))))
6311 (add-text-properties
6312 (match-beginning 0) end
6313 (list 'font-lock-fontified t))
6314 (compose-region (match-beginning 0) end
6315 (nth 6 ee) nil)
6316 (backward-char 1)
6317 (throw 'match t))))
6318 nil))))
6320 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6321 "Fontify string S like in Org-mode."
6322 (with-temp-buffer
6323 (insert s)
6324 (let ((org-odd-levels-only odd-levels))
6325 (org-mode)
6326 (font-lock-fontify-buffer)
6327 (buffer-string))))
6329 (defvar org-m nil)
6330 (defvar org-l nil)
6331 (defvar org-f nil)
6332 (defun org-get-level-face (n)
6333 "Get the right face for match N in font-lock matching of headlines."
6334 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6335 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6336 (if org-cycle-level-faces
6337 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6338 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6339 (cond
6340 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6341 ((eq n 2) org-f)
6342 (t (if org-level-color-stars-only nil org-f))))
6345 (defun org-get-todo-face (kwd)
6346 "Get the right face for a TODO keyword KWD.
6347 If KWD is a number, get the corresponding match group."
6348 (if (numberp kwd) (setq kwd (match-string kwd)))
6349 (or (org-face-from-face-or-color
6350 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6351 (and (member kwd org-done-keywords) 'org-done)
6352 'org-todo))
6354 (defun org-face-from-face-or-color (context inherit face-or-color)
6355 "Create a face list that inherits INHERIT, but sets the foreground color.
6356 When FACE-OR-COLOR is not a string, just return it."
6357 (if (stringp face-or-color)
6358 (list :inherit inherit
6359 (cdr (assoc context org-faces-easy-properties))
6360 face-or-color)
6361 face-or-color))
6363 (defun org-font-lock-add-tag-faces (limit)
6364 "Add the special tag faces."
6365 (when (and org-tag-faces org-tags-special-faces-re)
6366 (while (re-search-forward org-tags-special-faces-re limit t)
6367 (add-text-properties (match-beginning 1) (match-end 1)
6368 (list 'face (org-get-tag-face 1)
6369 'font-lock-fontified t))
6370 (backward-char 1))))
6372 (defun org-font-lock-add-priority-faces (limit)
6373 "Add the special priority faces."
6374 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6375 (when (save-match-data (org-at-heading-p))
6376 (add-text-properties
6377 (match-beginning 0) (match-end 0)
6378 (list 'face (or (org-face-from-face-or-color
6379 'priority 'org-priority
6380 (cdr (assoc (char-after (match-beginning 1))
6381 org-priority-faces)))
6382 'org-priority)
6383 'font-lock-fontified t)))))
6385 (defun org-get-tag-face (kwd)
6386 "Get the right face for a TODO keyword KWD.
6387 If KWD is a number, get the corresponding match group."
6388 (if (numberp kwd) (setq kwd (match-string kwd)))
6389 (or (org-face-from-face-or-color
6390 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6391 'org-tag))
6393 (defun org-unfontify-region (beg end &optional maybe_loudly)
6394 "Remove fontification and activation overlays from links."
6395 (font-lock-default-unfontify-region beg end)
6396 (let* ((buffer-undo-list t)
6397 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6398 (inhibit-modification-hooks t)
6399 deactivate-mark buffer-file-name buffer-file-truename)
6400 (org-decompose-region beg end)
6401 (remove-text-properties beg end
6402 '(mouse-face t keymap t org-linked-text t
6403 invisible t intangible t
6404 org-no-flyspell t org-emphasis t))
6405 (org-remove-font-lock-display-properties beg end)))
6407 (defconst org-script-display '(((raise -0.3) (height 0.7))
6408 ((raise 0.3) (height 0.7))
6409 ((raise -0.5))
6410 ((raise 0.5)))
6411 "Display properties for showing superscripts and subscripts.")
6413 (defun org-remove-font-lock-display-properties (beg end)
6414 "Remove specific display properties that have been added by font lock.
6415 The will remove the raise properties that are used to show superscripts
6416 and subscripts."
6417 (let (next prop)
6418 (while (< beg end)
6419 (setq next (next-single-property-change beg 'display nil end)
6420 prop (get-text-property beg 'display))
6421 (if (member prop org-script-display)
6422 (put-text-property beg next 'display nil))
6423 (setq beg next))))
6425 (defun org-raise-scripts (limit)
6426 "Add raise properties to sub/superscripts."
6427 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6428 (if (re-search-forward
6429 (if (eq org-use-sub-superscripts t)
6430 org-match-substring-regexp
6431 org-match-substring-with-braces-regexp)
6432 limit t)
6433 (let* ((pos (point)) table-p comment-p
6434 (mpos (match-beginning 3))
6435 (emph-p (get-text-property mpos 'org-emphasis))
6436 (link-p (get-text-property mpos 'mouse-face))
6437 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6438 (goto-char (point-at-bol))
6439 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6440 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6441 (goto-char pos)
6442 ;; Handle a_b^c
6443 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6444 (if (or comment-p emph-p link-p keyw-p)
6446 (put-text-property (match-beginning 3) (match-end 0)
6447 'display
6448 (if (equal (char-after (match-beginning 2)) ?^)
6449 (nth (if table-p 3 1) org-script-display)
6450 (nth (if table-p 2 0) org-script-display)))
6451 (add-text-properties (match-beginning 2) (match-end 2)
6452 (list 'invisible t
6453 'org-dwidth t 'org-dwidth-n 1))
6454 (if (and (eq (char-after (match-beginning 3)) ?{)
6455 (eq (char-before (match-end 3)) ?}))
6456 (progn
6457 (add-text-properties
6458 (match-beginning 3) (1+ (match-beginning 3))
6459 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6460 (add-text-properties
6461 (1- (match-end 3)) (match-end 3)
6462 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6463 t)))))
6465 ;;;; Visibility cycling, including org-goto and indirect buffer
6467 ;;; Cycling
6469 (defvar org-cycle-global-status nil)
6470 (make-variable-buffer-local 'org-cycle-global-status)
6471 (put 'org-cycle-global-status 'org-state t)
6472 (defvar org-cycle-subtree-status nil)
6473 (make-variable-buffer-local 'org-cycle-subtree-status)
6474 (put 'org-cycle-subtree-status 'org-state t)
6476 (defvar org-inlinetask-min-level)
6478 ;;;###autoload
6479 (defun org-cycle (&optional arg)
6480 "TAB-action and visibility cycling for Org-mode.
6482 This is the command invoked in Org-mode by the TAB key. Its main purpose
6483 is outline visibility cycling, but it also invokes other actions
6484 in special contexts.
6486 - When this function is called with a prefix argument, rotate the entire
6487 buffer through 3 states (global cycling)
6488 1. OVERVIEW: Show only top-level headlines.
6489 2. CONTENTS: Show all headlines of all levels, but no body text.
6490 3. SHOW ALL: Show everything.
6491 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6492 determined by the variable `org-startup-folded', and by any VISIBILITY
6493 properties in the buffer.
6494 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6495 including any drawers.
6497 - When inside a table, re-align the table and move to the next field.
6499 - When point is at the beginning of a headline, rotate the subtree started
6500 by this line through 3 different states (local cycling)
6501 1. FOLDED: Only the main headline is shown.
6502 2. CHILDREN: The main headline and the direct children are shown.
6503 From this state, you can move to one of the children
6504 and zoom in further.
6505 3. SUBTREE: Show the entire subtree, including body text.
6506 If there is no subtree, switch directly from CHILDREN to FOLDED.
6508 - When point is at the beginning of an empty headline and the variable
6509 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6510 of the headline by demoting and promoting it to likely levels. This
6511 speeds up creation document structure by pressing TAB once or several
6512 times right after creating a new headline.
6514 - When there is a numeric prefix, go up to a heading with level ARG, do
6515 a `show-subtree' and return to the previous cursor position. If ARG
6516 is negative, go up that many levels.
6518 - When point is not at the beginning of a headline, execute the global
6519 binding for TAB, which is re-indenting the line. See the option
6520 `org-cycle-emulate-tab' for details.
6522 - Special case: if point is at the beginning of the buffer and there is
6523 no headline in line 1, this function will act as if called with prefix arg
6524 (C-u TAB, same as S-TAB) also when called without prefix arg.
6525 But only if also the variable `org-cycle-global-at-bob' is t."
6526 (interactive "P")
6527 (org-load-modules-maybe)
6528 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6529 (and org-cycle-level-after-item/entry-creation
6530 (or (org-cycle-level)
6531 (org-cycle-item-indentation))))
6532 (let* (message-log-max ; Don't populate the *Messages* buffer
6533 (limit-level
6534 (or org-cycle-max-level
6535 (and (boundp 'org-inlinetask-min-level)
6536 org-inlinetask-min-level
6537 (1- org-inlinetask-min-level))))
6538 (nstars (and limit-level
6539 (if org-odd-levels-only
6540 (and limit-level (1- (* limit-level 2)))
6541 limit-level)))
6542 (org-outline-regexp
6543 (if (not (derived-mode-p 'org-mode))
6544 outline-regexp
6545 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6546 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6547 (not (looking-at org-outline-regexp))))
6548 (org-cycle-hook
6549 (if bob-special
6550 (delq 'org-optimize-window-after-visibility-change
6551 (copy-sequence org-cycle-hook))
6552 org-cycle-hook))
6553 (pos (point)))
6555 (if (or bob-special (equal arg '(4)))
6556 ;; special case: use global cycling
6557 (setq arg t))
6559 (cond
6561 ((equal arg '(16))
6562 (setq last-command 'dummy)
6563 (org-set-startup-visibility)
6564 (message "Startup visibility, plus VISIBILITY properties"))
6566 ((equal arg '(64))
6567 (show-all)
6568 (message "Entire buffer visible, including drawers"))
6570 ;; Table: enter it or move to the next field.
6571 ((org-at-table-p 'any)
6572 (if (org-at-table.el-p)
6573 (message "Use C-c ' to edit table.el tables")
6574 (if arg (org-table-edit-field t)
6575 (org-table-justify-field-maybe)
6576 (call-interactively 'org-table-next-field))))
6578 ((run-hook-with-args-until-success
6579 'org-tab-after-check-for-table-hook))
6581 ;; Global cycling: delegate to `org-cycle-internal-global'.
6582 ((eq arg t) (org-cycle-internal-global))
6584 ;; Drawers: delegate to `org-flag-drawer'.
6585 ((and org-drawers org-drawer-regexp
6586 (save-excursion
6587 (beginning-of-line 1)
6588 (looking-at org-drawer-regexp)))
6589 (org-flag-drawer ; toggle block visibility
6590 (not (get-char-property (match-end 0) 'invisible))))
6592 ;; Show-subtree, ARG levels up from here.
6593 ((integerp arg)
6594 (save-excursion
6595 (org-back-to-heading)
6596 (outline-up-heading (if (< arg 0) (- arg)
6597 (- (funcall outline-level) arg)))
6598 (org-show-subtree)))
6600 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6601 ((and (featurep 'org-inlinetask)
6602 (org-inlinetask-at-task-p)
6603 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6604 (org-inlinetask-toggle-visibility))
6606 ((org-try-cdlatex-tab))
6608 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6609 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6610 (save-excursion (beginning-of-line 1)
6611 (looking-at org-outline-regexp)))
6612 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6613 (org-cycle-internal-local))
6615 ;; From there: TAB emulation and template completion.
6616 (buffer-read-only (org-back-to-heading))
6618 ((run-hook-with-args-until-success
6619 'org-tab-after-check-for-cycling-hook))
6621 ((org-try-structure-completion))
6623 ((run-hook-with-args-until-success
6624 'org-tab-before-tab-emulation-hook))
6626 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6627 (or (not (bolp))
6628 (not (looking-at org-outline-regexp))))
6629 (call-interactively (global-key-binding "\t")))
6631 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6632 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6633 (or (and (eq org-cycle-emulate-tab 'white)
6634 (= (match-end 0) (point-at-eol)))
6635 (and (eq org-cycle-emulate-tab 'whitestart)
6636 (>= (match-end 0) pos))))
6638 (eq org-cycle-emulate-tab t))
6639 (call-interactively (global-key-binding "\t")))
6641 (t (save-excursion
6642 (org-back-to-heading)
6643 (org-cycle)))))))
6645 (defun org-cycle-internal-global ()
6646 "Do the global cycling action."
6647 ;; Hack to avoid display of messages for .org attachments in Gnus
6648 (let (message-log-max ; Don't populate the *Messages* buffer
6649 (ga (string-match "\\*fontification" (buffer-name))))
6650 (cond
6651 ((and (eq last-command this-command)
6652 (eq org-cycle-global-status 'overview))
6653 ;; We just created the overview - now do table of contents
6654 ;; This can be slow in very large buffers, so indicate action
6655 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6656 (unless ga (message "CONTENTS..."))
6657 (org-content)
6658 (unless ga (message "CONTENTS...done"))
6659 (setq org-cycle-global-status 'contents)
6660 (run-hook-with-args 'org-cycle-hook 'contents))
6662 ((and (eq last-command this-command)
6663 (eq org-cycle-global-status 'contents))
6664 ;; We just showed the table of contents - now show everything
6665 (run-hook-with-args 'org-pre-cycle-hook 'all)
6666 (show-all)
6667 (unless ga (message "SHOW ALL"))
6668 (setq org-cycle-global-status 'all)
6669 (run-hook-with-args 'org-cycle-hook 'all))
6672 ;; Default action: go to overview
6673 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6674 (org-overview)
6675 (unless ga (message "OVERVIEW"))
6676 (setq org-cycle-global-status 'overview)
6677 (run-hook-with-args 'org-cycle-hook 'overview)))))
6679 (defun org-cycle-internal-local ()
6680 "Do the local cycling action."
6681 (let (message-log-max ; Don't populate the *Messages* buffer
6682 (goal-column 0) eoh eol eos has-children children-skipped struct)
6683 ;; First, determine end of headline (EOH), end of subtree or item
6684 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6685 (save-excursion
6686 (if (org-at-item-p)
6687 (progn
6688 (beginning-of-line)
6689 (setq struct (org-list-struct))
6690 (setq eoh (point-at-eol))
6691 (setq eos (org-list-get-item-end-before-blank (point) struct))
6692 (setq has-children (org-list-has-child-p (point) struct)))
6693 (org-back-to-heading)
6694 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6695 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6696 (setq has-children
6697 (or (save-excursion
6698 (let ((level (funcall outline-level)))
6699 (outline-next-heading)
6700 (and (org-at-heading-p t)
6701 (> (funcall outline-level) level))))
6702 (save-excursion
6703 (org-list-search-forward (org-item-beginning-re) eos t)))))
6704 ;; Determine end invisible part of buffer (EOL)
6705 (beginning-of-line 2)
6706 ;; XEmacs doesn't have `next-single-char-property-change'
6707 (if (featurep 'xemacs)
6708 (while (and (not (eobp)) ;; this is like `next-line'
6709 (get-char-property (1- (point)) 'invisible))
6710 (beginning-of-line 2))
6711 (while (and (not (eobp)) ;; this is like `next-line'
6712 (get-char-property (1- (point)) 'invisible))
6713 (goto-char (next-single-char-property-change (point) 'invisible))
6714 (and (eolp) (beginning-of-line 2))))
6715 (setq eol (point)))
6716 ;; Find out what to do next and set `this-command'
6717 (cond
6718 ((= eos eoh)
6719 ;; Nothing is hidden behind this heading
6720 (unless (org-before-first-heading-p)
6721 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6722 (message "EMPTY ENTRY")
6723 (setq org-cycle-subtree-status nil)
6724 (save-excursion
6725 (goto-char eos)
6726 (outline-next-heading)
6727 (if (outline-invisible-p) (org-flag-heading nil))))
6728 ((and (or (>= eol eos)
6729 (not (string-match "\\S-" (buffer-substring eol eos))))
6730 (or has-children
6731 (not (setq children-skipped
6732 org-cycle-skip-children-state-if-no-children))))
6733 ;; Entire subtree is hidden in one line: children view
6734 (unless (org-before-first-heading-p)
6735 (run-hook-with-args 'org-pre-cycle-hook 'children))
6736 (if (org-at-item-p)
6737 (org-list-set-item-visibility (point-at-bol) struct 'children)
6738 (org-show-entry)
6739 (org-with-limited-levels (show-children))
6740 ;; FIXME: This slows down the func way too much.
6741 ;; How keep drawers hidden in subtree anyway?
6742 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6743 ;; (org-cycle-hide-drawers 'subtree))
6745 ;; Fold every list in subtree to top-level items.
6746 (when (eq org-cycle-include-plain-lists 'integrate)
6747 (save-excursion
6748 (org-back-to-heading)
6749 (while (org-list-search-forward (org-item-beginning-re) eos t)
6750 (beginning-of-line 1)
6751 (let* ((struct (org-list-struct))
6752 (prevs (org-list-prevs-alist struct))
6753 (end (org-list-get-bottom-point struct)))
6754 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6755 (org-list-get-all-items (point) struct prevs))
6756 (goto-char (if (< end eos) end eos)))))))
6757 (message "CHILDREN")
6758 (save-excursion
6759 (goto-char eos)
6760 (outline-next-heading)
6761 (if (outline-invisible-p) (org-flag-heading nil)))
6762 (setq org-cycle-subtree-status 'children)
6763 (unless (org-before-first-heading-p)
6764 (run-hook-with-args 'org-cycle-hook 'children)))
6765 ((or children-skipped
6766 (and (eq last-command this-command)
6767 (eq org-cycle-subtree-status 'children)))
6768 ;; We just showed the children, or no children are there,
6769 ;; now show everything.
6770 (unless (org-before-first-heading-p)
6771 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6772 (outline-flag-region eoh eos nil)
6773 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6774 (setq org-cycle-subtree-status 'subtree)
6775 (unless (org-before-first-heading-p)
6776 (run-hook-with-args 'org-cycle-hook 'subtree)))
6778 ;; Default action: hide the subtree.
6779 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6780 (outline-flag-region eoh eos t)
6781 (message "FOLDED")
6782 (setq org-cycle-subtree-status 'folded)
6783 (unless (org-before-first-heading-p)
6784 (run-hook-with-args 'org-cycle-hook 'folded))))))
6786 ;;;###autoload
6787 (defun org-global-cycle (&optional arg)
6788 "Cycle the global visibility. For details see `org-cycle'.
6789 With \\[universal-argument] prefix arg, switch to startup visibility.
6790 With a numeric prefix, show all headlines up to that level."
6791 (interactive "P")
6792 (let ((org-cycle-include-plain-lists
6793 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6794 (cond
6795 ((integerp arg)
6796 (show-all)
6797 (hide-sublevels arg)
6798 (setq org-cycle-global-status 'contents))
6799 ((equal arg '(4))
6800 (org-set-startup-visibility)
6801 (message "Startup visibility, plus VISIBILITY properties."))
6803 (org-cycle '(4))))))
6805 (defun org-set-startup-visibility ()
6806 "Set the visibility required by startup options and properties."
6807 (cond
6808 ((eq org-startup-folded t)
6809 (org-cycle '(4)))
6810 ((eq org-startup-folded 'content)
6811 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6812 (org-cycle '(4)) (org-cycle '(4)))))
6813 (unless (eq org-startup-folded 'showeverything)
6814 (if org-hide-block-startup (org-hide-block-all))
6815 (org-set-visibility-according-to-property 'no-cleanup)
6816 (org-cycle-hide-archived-subtrees 'all)
6817 (org-cycle-hide-drawers 'all)
6818 (org-cycle-show-empty-lines t)))
6820 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6821 "Switch subtree visibilities according to :VISIBILITY: property."
6822 (interactive)
6823 (let (org-show-entry-below state)
6824 (save-excursion
6825 (goto-char (point-min))
6826 (while (re-search-forward
6827 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6828 nil t)
6829 (setq state (match-string 1))
6830 (save-excursion
6831 (org-back-to-heading t)
6832 (hide-subtree)
6833 (org-reveal)
6834 (cond
6835 ((equal state '("fold" "folded"))
6836 (hide-subtree))
6837 ((equal state "children")
6838 (org-show-hidden-entry)
6839 (show-children))
6840 ((equal state "content")
6841 (save-excursion
6842 (save-restriction
6843 (org-narrow-to-subtree)
6844 (org-content))))
6845 ((member state '("all" "showall"))
6846 (show-subtree)))))
6847 (unless no-cleanup
6848 (org-cycle-hide-archived-subtrees 'all)
6849 (org-cycle-hide-drawers 'all)
6850 (org-cycle-show-empty-lines 'all)))))
6852 ;; This function uses outline-regexp instead of the more fundamental
6853 ;; org-outline-regexp so that org-cycle-global works outside of Org
6854 ;; buffers, where outline-regexp is needed.
6855 (defun org-overview ()
6856 "Switch to overview mode, showing only top-level headlines.
6857 Really, this shows all headlines with level equal or greater than the level
6858 of the first headline in the buffer. This is important, because if the
6859 first headline is not level one, then (hide-sublevels 1) gives confusing
6860 results."
6861 (interactive)
6862 (let ((l (org-current-line))
6863 (level (save-excursion
6864 (goto-char (point-min))
6865 (if (re-search-forward (concat "^" outline-regexp) nil t)
6866 (progn
6867 (goto-char (match-beginning 0))
6868 (funcall outline-level))))))
6869 (and level (hide-sublevels level))
6870 (recenter '(4))
6871 (org-goto-line l)))
6873 (defun org-content (&optional arg)
6874 "Show all headlines in the buffer, like a table of contents.
6875 With numerical argument N, show content up to level N."
6876 (interactive "P")
6877 (save-excursion
6878 ;; Visit all headings and show their offspring
6879 (and (integerp arg) (org-overview))
6880 (goto-char (point-max))
6881 (catch 'exit
6882 (while (and (progn (condition-case nil
6883 (outline-previous-visible-heading 1)
6884 (error (goto-char (point-min))))
6886 (looking-at org-outline-regexp))
6887 (if (integerp arg)
6888 (show-children (1- arg))
6889 (show-branches))
6890 (if (bobp) (throw 'exit nil))))))
6893 (defun org-optimize-window-after-visibility-change (state)
6894 "Adjust the window after a change in outline visibility.
6895 This function is the default value of the hook `org-cycle-hook'."
6896 (when (get-buffer-window (current-buffer))
6897 (cond
6898 ((eq state 'content) nil)
6899 ((eq state 'all) nil)
6900 ((eq state 'folded) nil)
6901 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6902 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6904 (defun org-remove-empty-overlays-at (pos)
6905 "Remove outline overlays that do not contain non-white stuff."
6906 (mapc
6907 (lambda (o)
6908 (and (eq 'outline (overlay-get o 'invisible))
6909 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6910 (overlay-end o))))
6911 (delete-overlay o)))
6912 (overlays-at pos)))
6914 (defun org-clean-visibility-after-subtree-move ()
6915 "Fix visibility issues after moving a subtree."
6916 ;; First, find a reasonable region to look at:
6917 ;; Start two siblings above, end three below
6918 (let* ((beg (save-excursion
6919 (and (org-get-last-sibling)
6920 (org-get-last-sibling))
6921 (point)))
6922 (end (save-excursion
6923 (and (org-get-next-sibling)
6924 (org-get-next-sibling)
6925 (org-get-next-sibling))
6926 (if (org-at-heading-p)
6927 (point-at-eol)
6928 (point))))
6929 (level (looking-at "\\*+"))
6930 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6931 (save-excursion
6932 (save-restriction
6933 (narrow-to-region beg end)
6934 (when re
6935 ;; Properly fold already folded siblings
6936 (goto-char (point-min))
6937 (while (re-search-forward re nil t)
6938 (if (and (not (outline-invisible-p))
6939 (save-excursion
6940 (goto-char (point-at-eol)) (outline-invisible-p)))
6941 (hide-entry))))
6942 (org-cycle-show-empty-lines 'overview)
6943 (org-cycle-hide-drawers 'overview)))))
6945 (defun org-cycle-show-empty-lines (state)
6946 "Show empty lines above all visible headlines.
6947 The region to be covered depends on STATE when called through
6948 `org-cycle-hook'. Lisp program can use t for STATE to get the
6949 entire buffer covered. Note that an empty line is only shown if there
6950 are at least `org-cycle-separator-lines' empty lines before the headline."
6951 (when (not (= org-cycle-separator-lines 0))
6952 (save-excursion
6953 (let* ((n (abs org-cycle-separator-lines))
6954 (re (cond
6955 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6956 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6957 (t (let ((ns (number-to-string (- n 2))))
6958 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6959 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6960 beg end b e)
6961 (cond
6962 ((memq state '(overview contents t))
6963 (setq beg (point-min) end (point-max)))
6964 ((memq state '(children folded))
6965 (setq beg (point) end (progn (org-end-of-subtree t t)
6966 (beginning-of-line 2)
6967 (point)))))
6968 (when beg
6969 (goto-char beg)
6970 (while (re-search-forward re end t)
6971 (unless (get-char-property (match-end 1) 'invisible)
6972 (setq e (match-end 1))
6973 (if (< org-cycle-separator-lines 0)
6974 (setq b (save-excursion
6975 (goto-char (match-beginning 0))
6976 (org-back-over-empty-lines)
6977 (if (save-excursion
6978 (goto-char (max (point-min) (1- (point))))
6979 (org-at-heading-p))
6980 (1- (point))
6981 (point))))
6982 (setq b (match-beginning 1)))
6983 (outline-flag-region b e nil)))))))
6984 ;; Never hide empty lines at the end of the file.
6985 (save-excursion
6986 (goto-char (point-max))
6987 (outline-previous-heading)
6988 (outline-end-of-heading)
6989 (if (and (looking-at "[ \t\n]+")
6990 (= (match-end 0) (point-max)))
6991 (outline-flag-region (point) (match-end 0) nil))))
6993 (defun org-show-empty-lines-in-parent ()
6994 "Move to the parent and re-show empty lines before visible headlines."
6995 (save-excursion
6996 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6997 (org-cycle-show-empty-lines context))))
6999 (defun org-files-list ()
7000 "Return `org-agenda-files' list, plus all open org-mode files.
7001 This is useful for operations that need to scan all of a user's
7002 open and agenda-wise Org files."
7003 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7004 (dolist (buf (buffer-list))
7005 (with-current-buffer buf
7006 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7007 (let ((file (expand-file-name (buffer-file-name))))
7008 (unless (member file files)
7009 (push file files))))))
7010 files))
7012 (defsubst org-entry-beginning-position ()
7013 "Return the beginning position of the current entry."
7014 (save-excursion (outline-back-to-heading t) (point)))
7016 (defsubst org-entry-end-position ()
7017 "Return the end position of the current entry."
7018 (save-excursion (outline-next-heading) (point)))
7020 (defun org-cycle-hide-drawers (state)
7021 "Re-hide all drawers after a visibility state change."
7022 (when (and (derived-mode-p 'org-mode)
7023 (not (memq state '(overview folded contents))))
7024 (save-excursion
7025 (let* ((globalp (memq state '(contents all)))
7026 (beg (if globalp (point-min) (point)))
7027 (end (if globalp (point-max)
7028 (if (eq state 'children)
7029 (save-excursion (outline-next-heading) (point))
7030 (org-end-of-subtree t)))))
7031 (goto-char beg)
7032 (while (re-search-forward org-drawer-regexp end t)
7033 (org-flag-drawer t))))))
7035 (defun org-cycle-hide-inline-tasks (state)
7036 "Re-hide inline task when switching to 'contents visibility state."
7037 (when (and (eq state 'contents)
7038 (boundp 'org-inlinetask-min-level)
7039 org-inlinetask-min-level)
7040 (hide-sublevels (1- org-inlinetask-min-level))))
7042 (defun org-flag-drawer (flag)
7043 "When FLAG is non-nil, hide the drawer we are within.
7044 Otherwise make it visible."
7045 (save-excursion
7046 (beginning-of-line 1)
7047 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7048 (let ((b (match-end 0)))
7049 (if (re-search-forward
7050 "^[ \t]*:END:"
7051 (save-excursion (outline-next-heading) (point)) t)
7052 (outline-flag-region b (point-at-eol) flag)
7053 (error ":END: line missing at position %s" b))))))
7055 (defun org-subtree-end-visible-p ()
7056 "Is the end of the current subtree visible?"
7057 (pos-visible-in-window-p
7058 (save-excursion (org-end-of-subtree t) (point))))
7060 (defun org-first-headline-recenter (&optional N)
7061 "Move cursor to the first headline and recenter the headline.
7062 Optional argument N means put the headline into the Nth line of the window."
7063 (goto-char (point-min))
7064 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7065 (beginning-of-line)
7066 (recenter (prefix-numeric-value N))))
7068 ;;; Saving and restoring visibility
7070 (defun org-outline-overlay-data (&optional use-markers)
7071 "Return a list of the locations of all outline overlays.
7072 These are overlays with the `invisible' property value `outline'.
7073 The return value is a list of cons cells, with start and stop
7074 positions for each overlay.
7075 If USE-MARKERS is set, return the positions as markers."
7076 (let (beg end)
7077 (save-excursion
7078 (save-restriction
7079 (widen)
7080 (delq nil
7081 (mapcar (lambda (o)
7082 (when (eq (overlay-get o 'invisible) 'outline)
7083 (setq beg (overlay-start o)
7084 end (overlay-end o))
7085 (and beg end (> end beg)
7086 (if use-markers
7087 (cons (move-marker (make-marker) beg)
7088 (move-marker (make-marker) end))
7089 (cons beg end)))))
7090 (overlays-in (point-min) (point-max))))))))
7092 (defun org-set-outline-overlay-data (data)
7093 "Create visibility overlays for all positions in DATA.
7094 DATA should have been made by `org-outline-overlay-data'."
7095 (let (o)
7096 (save-excursion
7097 (save-restriction
7098 (widen)
7099 (show-all)
7100 (mapc (lambda (c)
7101 (outline-flag-region (car c) (cdr c) t))
7102 data)))))
7104 ;;; Folding of blocks
7106 (defvar org-hide-block-overlays nil
7107 "Overlays hiding blocks.")
7108 (make-variable-buffer-local 'org-hide-block-overlays)
7110 (defun org-block-map (function &optional start end)
7111 "Call FUNCTION at the head of all source blocks in the current buffer.
7112 Optional arguments START and END can be used to limit the range."
7113 (let ((start (or start (point-min)))
7114 (end (or end (point-max))))
7115 (save-excursion
7116 (goto-char start)
7117 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7118 (save-excursion
7119 (save-match-data
7120 (goto-char (match-beginning 0))
7121 (funcall function)))))))
7123 (defun org-hide-block-toggle-all ()
7124 "Toggle the visibility of all blocks in the current buffer."
7125 (org-block-map #'org-hide-block-toggle))
7127 (defun org-hide-block-all ()
7128 "Fold all blocks in the current buffer."
7129 (interactive)
7130 (org-show-block-all)
7131 (org-block-map #'org-hide-block-toggle-maybe))
7133 (defun org-show-block-all ()
7134 "Unfold all blocks in the current buffer."
7135 (interactive)
7136 (mapc 'delete-overlay org-hide-block-overlays)
7137 (setq org-hide-block-overlays nil))
7139 (defun org-hide-block-toggle-maybe ()
7140 "Toggle visibility of block at point."
7141 (interactive)
7142 (let ((case-fold-search t))
7143 (if (save-excursion
7144 (beginning-of-line 1)
7145 (looking-at org-block-regexp))
7146 (progn (org-hide-block-toggle)
7147 t) ;; to signal that we took action
7148 nil))) ;; to signal that we did not
7150 (defun org-hide-block-toggle (&optional force)
7151 "Toggle the visibility of the current block."
7152 (interactive)
7153 (save-excursion
7154 (beginning-of-line)
7155 (if (re-search-forward org-block-regexp nil t)
7156 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7157 (end (match-end 0)) ;; end of entire body
7159 (if (memq t (mapcar (lambda (overlay)
7160 (eq (overlay-get overlay 'invisible)
7161 'org-hide-block))
7162 (overlays-at start)))
7163 (if (or (not force) (eq force 'off))
7164 (mapc (lambda (ov)
7165 (when (member ov org-hide-block-overlays)
7166 (setq org-hide-block-overlays
7167 (delq ov org-hide-block-overlays)))
7168 (when (eq (overlay-get ov 'invisible)
7169 'org-hide-block)
7170 (delete-overlay ov)))
7171 (overlays-at start)))
7172 (setq ov (make-overlay start end))
7173 (overlay-put ov 'invisible 'org-hide-block)
7174 ;; make the block accessible to isearch
7175 (overlay-put
7176 ov 'isearch-open-invisible
7177 (lambda (ov)
7178 (when (member ov org-hide-block-overlays)
7179 (setq org-hide-block-overlays
7180 (delq ov org-hide-block-overlays)))
7181 (when (eq (overlay-get ov 'invisible)
7182 'org-hide-block)
7183 (delete-overlay ov))))
7184 (push ov org-hide-block-overlays)))
7185 (error "Not looking at a source block"))))
7187 ;; org-tab-after-check-for-cycling-hook
7188 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7189 ;; Remove overlays when changing major mode
7190 (add-hook 'org-mode-hook
7191 (lambda () (org-add-hook 'change-major-mode-hook
7192 'org-show-block-all 'append 'local)))
7194 ;;; Org-goto
7196 (defvar org-goto-window-configuration nil)
7197 (defvar org-goto-marker nil)
7198 (defvar org-goto-map)
7199 (defun org-goto-map ()
7200 "Set the keymap `org-goto'."
7201 (setq org-goto-map
7202 (let ((map (make-sparse-keymap)))
7203 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7204 mouse-drag-region universal-argument org-occur))
7205 cmd)
7206 (while (setq cmd (pop cmds))
7207 (substitute-key-definition cmd cmd map global-map)))
7208 (suppress-keymap map)
7209 (org-defkey map "\C-m" 'org-goto-ret)
7210 (org-defkey map [(return)] 'org-goto-ret)
7211 (org-defkey map [(left)] 'org-goto-left)
7212 (org-defkey map [(right)] 'org-goto-right)
7213 (org-defkey map [(control ?g)] 'org-goto-quit)
7214 (org-defkey map "\C-i" 'org-cycle)
7215 (org-defkey map [(tab)] 'org-cycle)
7216 (org-defkey map [(down)] 'outline-next-visible-heading)
7217 (org-defkey map [(up)] 'outline-previous-visible-heading)
7218 (if org-goto-auto-isearch
7219 (if (fboundp 'define-key-after)
7220 (define-key-after map [t] 'org-goto-local-auto-isearch)
7221 nil)
7222 (org-defkey map "q" 'org-goto-quit)
7223 (org-defkey map "n" 'outline-next-visible-heading)
7224 (org-defkey map "p" 'outline-previous-visible-heading)
7225 (org-defkey map "f" 'outline-forward-same-level)
7226 (org-defkey map "b" 'outline-backward-same-level)
7227 (org-defkey map "u" 'outline-up-heading))
7228 (org-defkey map "/" 'org-occur)
7229 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7230 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7231 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7232 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7233 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7234 map)))
7236 (defconst org-goto-help
7237 "Browse buffer copy, to find location or copy text.%s
7238 RET=jump to location C-g=quit and return to previous location
7239 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7241 (defvar org-goto-start-pos) ; dynamically scoped parameter
7243 (defun org-goto (&optional alternative-interface)
7244 "Look up a different location in the current file, keeping current visibility.
7246 When you want look-up or go to a different location in a
7247 document, the fastest way is often to fold the entire buffer and
7248 then dive into the tree. This method has the disadvantage, that
7249 the previous location will be folded, which may not be what you
7250 want.
7252 This command works around this by showing a copy of the current
7253 buffer in an indirect buffer, in overview mode. You can dive
7254 into the tree in that copy, use org-occur and incremental search
7255 to find a location. When pressing RET or `Q', the command
7256 returns to the original buffer in which the visibility is still
7257 unchanged. After RET it will also jump to the location selected
7258 in the indirect buffer and expose the headline hierarchy above.
7260 With a prefix argument, use the alternative interface: e.g. if
7261 `org-goto-interface' is 'outline use 'outline-path-completion."
7262 (interactive "P")
7263 (org-goto-map)
7264 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7265 (org-refile-use-outline-path t)
7266 (org-refile-target-verify-function nil)
7267 (interface
7268 (if (not alternative-interface)
7269 org-goto-interface
7270 (if (eq org-goto-interface 'outline)
7271 'outline-path-completion
7272 'outline)))
7273 (org-goto-start-pos (point))
7274 (selected-point
7275 (if (eq interface 'outline)
7276 (car (org-get-location (current-buffer) org-goto-help))
7277 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7278 (org-refile-check-position pa)
7279 (nth 3 pa)))))
7280 (if selected-point
7281 (progn
7282 (org-mark-ring-push org-goto-start-pos)
7283 (goto-char selected-point)
7284 (if (or (outline-invisible-p) (org-invisible-p2))
7285 (org-show-context 'org-goto)))
7286 (message "Quit"))))
7288 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7289 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7290 (defvar org-goto-local-auto-isearch-map) ; defined below
7292 (defun org-get-location (buf help)
7293 "Let the user select a location in the Org-mode buffer BUF.
7294 This function uses a recursive edit. It returns the selected position
7295 or nil."
7296 (org-no-popups
7297 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7298 (isearch-hide-immediately nil)
7299 (isearch-search-fun-function
7300 (lambda () 'org-goto-local-search-headings))
7301 (org-goto-selected-point org-goto-exit-command))
7302 (save-excursion
7303 (save-window-excursion
7304 (delete-other-windows)
7305 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7306 (org-pop-to-buffer-same-window
7307 (condition-case nil
7308 (make-indirect-buffer (current-buffer) "*org-goto*")
7309 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7310 (with-output-to-temp-buffer "*Org Help*"
7311 (princ (format help (if org-goto-auto-isearch
7312 " Just type for auto-isearch."
7313 " n/p/f/b/u to navigate, q to quit."))))
7314 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7315 (setq buffer-read-only nil)
7316 (let ((org-startup-truncated t)
7317 (org-startup-folded nil)
7318 (org-startup-align-all-tables nil))
7319 (org-mode)
7320 (org-overview))
7321 (setq buffer-read-only t)
7322 (if (and (boundp 'org-goto-start-pos)
7323 (integer-or-marker-p org-goto-start-pos))
7324 (let ((org-show-hierarchy-above t)
7325 (org-show-siblings t)
7326 (org-show-following-heading t))
7327 (goto-char org-goto-start-pos)
7328 (and (outline-invisible-p) (org-show-context)))
7329 (goto-char (point-min)))
7330 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7331 (message "Select location and press RET")
7332 (use-local-map org-goto-map)
7333 (recursive-edit)))
7334 (kill-buffer "*org-goto*")
7335 (cons org-goto-selected-point org-goto-exit-command))))
7337 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7338 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7339 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7340 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7342 (defun org-goto-local-search-headings (string bound noerror)
7343 "Search and make sure that any matches are in headlines."
7344 (catch 'return
7345 (while (if isearch-forward
7346 (search-forward string bound noerror)
7347 (search-backward string bound noerror))
7348 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7349 (and (member :headline context)
7350 (not (member :tags context))))
7351 (throw 'return (point))))))
7353 (defun org-goto-local-auto-isearch ()
7354 "Start isearch."
7355 (interactive)
7356 (goto-char (point-min))
7357 (let ((keys (this-command-keys)))
7358 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7359 (isearch-mode t)
7360 (isearch-process-search-char (string-to-char keys)))))
7362 (defun org-goto-ret (&optional arg)
7363 "Finish `org-goto' by going to the new location."
7364 (interactive "P")
7365 (setq org-goto-selected-point (point)
7366 org-goto-exit-command 'return)
7367 (throw 'exit nil))
7369 (defun org-goto-left ()
7370 "Finish `org-goto' by going to the new location."
7371 (interactive)
7372 (if (org-at-heading-p)
7373 (progn
7374 (beginning-of-line 1)
7375 (setq org-goto-selected-point (point)
7376 org-goto-exit-command 'left)
7377 (throw 'exit nil))
7378 (error "Not on a heading")))
7380 (defun org-goto-right ()
7381 "Finish `org-goto' by going to the new location."
7382 (interactive)
7383 (if (org-at-heading-p)
7384 (progn
7385 (setq org-goto-selected-point (point)
7386 org-goto-exit-command 'right)
7387 (throw 'exit nil))
7388 (error "Not on a heading")))
7390 (defun org-goto-quit ()
7391 "Finish `org-goto' without cursor motion."
7392 (interactive)
7393 (setq org-goto-selected-point nil)
7394 (setq org-goto-exit-command 'quit)
7395 (throw 'exit nil))
7397 ;;; Indirect buffer display of subtrees
7399 (defvar org-indirect-dedicated-frame nil
7400 "This is the frame being used for indirect tree display.")
7401 (defvar org-last-indirect-buffer nil)
7403 (defun org-tree-to-indirect-buffer (&optional arg)
7404 "Create indirect buffer and narrow it to current subtree.
7405 With a numerical prefix ARG, go up to this level and then take that tree.
7406 If ARG is negative, go up that many levels.
7408 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7409 indirect buffer previously made with this command, to avoid proliferation of
7410 indirect buffers. However, when you call the command with a \
7411 \\[universal-argument] prefix, or
7412 when `org-indirect-buffer-display' is `new-frame', the last buffer
7413 is kept so that you can work with several indirect buffers at the same time.
7414 If `org-indirect-buffer-display' is `dedicated-frame', the \
7415 \\[universal-argument] prefix also
7416 requests that a new frame be made for the new buffer, so that the dedicated
7417 frame is not changed."
7418 (interactive "P")
7419 (let ((cbuf (current-buffer))
7420 (cwin (selected-window))
7421 (pos (point))
7422 beg end level heading ibuf)
7423 (save-excursion
7424 (org-back-to-heading t)
7425 (when (numberp arg)
7426 (setq level (org-outline-level))
7427 (if (< arg 0) (setq arg (+ level arg)))
7428 (while (> (setq level (org-outline-level)) arg)
7429 (org-up-heading-safe)))
7430 (setq beg (point)
7431 heading (org-get-heading))
7432 (org-end-of-subtree t t)
7433 (if (org-at-heading-p) (backward-char 1))
7434 (setq end (point)))
7435 (if (and (buffer-live-p org-last-indirect-buffer)
7436 (not (eq org-indirect-buffer-display 'new-frame))
7437 (not arg))
7438 (kill-buffer org-last-indirect-buffer))
7439 (setq ibuf (org-get-indirect-buffer cbuf)
7440 org-last-indirect-buffer ibuf)
7441 (cond
7442 ((or (eq org-indirect-buffer-display 'new-frame)
7443 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7444 (select-frame (make-frame))
7445 (delete-other-windows)
7446 (org-pop-to-buffer-same-window ibuf)
7447 (org-set-frame-title heading))
7448 ((eq org-indirect-buffer-display 'dedicated-frame)
7449 (raise-frame
7450 (select-frame (or (and org-indirect-dedicated-frame
7451 (frame-live-p org-indirect-dedicated-frame)
7452 org-indirect-dedicated-frame)
7453 (setq org-indirect-dedicated-frame (make-frame)))))
7454 (delete-other-windows)
7455 (org-pop-to-buffer-same-window ibuf)
7456 (org-set-frame-title (concat "Indirect: " heading)))
7457 ((eq org-indirect-buffer-display 'current-window)
7458 (org-pop-to-buffer-same-window ibuf))
7459 ((eq org-indirect-buffer-display 'other-window)
7460 (pop-to-buffer ibuf))
7461 (t (error "Invalid value")))
7462 (if (featurep 'xemacs)
7463 (save-excursion (org-mode) (turn-on-font-lock)))
7464 (narrow-to-region beg end)
7465 (show-all)
7466 (goto-char pos)
7467 (run-hook-with-args 'org-cycle-hook 'all)
7468 (and (window-live-p cwin) (select-window cwin))))
7470 (defun org-get-indirect-buffer (&optional buffer)
7471 (setq buffer (or buffer (current-buffer)))
7472 (let ((n 1) (base (buffer-name buffer)) bname)
7473 (while (buffer-live-p
7474 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7475 (setq n (1+ n)))
7476 (condition-case nil
7477 (make-indirect-buffer buffer bname 'clone)
7478 (error (make-indirect-buffer buffer bname)))))
7480 (defun org-set-frame-title (title)
7481 "Set the title of the current frame to the string TITLE."
7482 ;; FIXME: how to name a single frame in XEmacs???
7483 (unless (featurep 'xemacs)
7484 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7486 ;;;; Structure editing
7488 ;;; Inserting headlines
7490 (defun org-previous-line-empty-p (&optional next)
7491 "Is the previous line a blank line?
7492 When NEXT is non-nil, check the next line instead."
7493 (save-excursion
7494 (and (not (bobp))
7495 (or (beginning-of-line (if next 2 0)) t)
7496 (save-match-data
7497 (looking-at "[ \t]*$")))))
7499 (defun org-insert-heading (&optional arg invisible-ok)
7500 "Insert a new heading or item with same depth at point.
7501 If point is in a plain list and ARG is nil, create a new list item.
7502 With one universal prefix argument, insert a heading even in lists.
7503 With two universal prefix arguments, insert the heading at the end
7504 of the parent subtree.
7506 If point is at the beginning of a headline, insert a sibling before
7507 the current headline. If point is not at the beginning, split the line
7508 and create a new headline with the text in the current line after point
7509 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7511 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7512 This is important for non-interactive uses of the command."
7513 (interactive "P")
7514 (cond
7515 ((or (= (buffer-size) 0)
7516 (and (not (save-excursion
7517 (and (ignore-errors (org-back-to-heading invisible-ok))
7518 (org-at-heading-p))))
7519 (or arg (not (org-in-item-p)))))
7520 (insert
7521 (if (org-previous-line-empty-p) "" "\n")
7522 (if (org-in-src-block-p) ",* " "* "))
7523 (run-hooks 'org-insert-heading-hook))
7524 ((or arg (not (org-insert-item
7525 (save-excursion
7526 (beginning-of-line)
7527 (looking-at org-list-full-item-re)
7528 (match-string 3)))))
7529 (let (begn endn)
7530 (when (org-buffer-narrowed-p)
7531 (setq begn (point-min) endn (point-max))
7532 (widen))
7533 (let* ((empty-line-p nil)
7534 (eops (equal arg '(16))) ; insert at end of parent subtree
7535 (org-insert-heading-respect-content
7536 (or (not (null arg)) org-insert-heading-respect-content))
7537 (level nil)
7538 (on-heading (org-at-heading-p))
7539 (head (save-excursion
7540 (condition-case nil
7541 (progn
7542 (org-back-to-heading invisible-ok)
7543 (when (and (not on-heading)
7544 (featurep 'org-inlinetask)
7545 (integerp org-inlinetask-min-level)
7546 (>= (length (match-string 0))
7547 org-inlinetask-min-level))
7548 ;; Find a heading level before the inline task
7549 (while (and (setq level (org-up-heading-safe))
7550 (>= level org-inlinetask-min-level)))
7551 (if (org-at-heading-p)
7552 (org-back-to-heading invisible-ok)
7553 (error "This should not happen")))
7554 (unless (and (save-excursion
7555 (save-match-data
7556 (org-backward-heading-same-level 1 invisible-ok))
7557 (= (point) (match-beginning 0)))
7558 (not (org-previous-line-empty-p t)))
7559 (setq empty-line-p (org-previous-line-empty-p)))
7560 (match-string 0))
7561 (error "* "))))
7562 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7563 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7564 pos hide-previous previous-pos)
7565 (if ;; At the beginning of a heading, open a new line for insertiong
7566 (and (bolp) (org-at-heading-p)
7567 (not eops)
7568 (or (bobp)
7569 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7570 (open-line (if blank 2 1))
7571 (save-excursion
7572 (setq previous-pos (point-at-bol))
7573 (end-of-line)
7574 (setq hide-previous (outline-invisible-p)))
7575 (and org-insert-heading-respect-content
7576 (save-excursion
7577 (while (outline-invisible-p)
7578 (org-show-subtree)
7579 (org-up-heading-safe))))
7580 (let ((split
7581 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7582 (save-excursion
7583 (let ((p (point)))
7584 (goto-char (point-at-bol))
7585 (and (looking-at org-complex-heading-regexp)
7586 (match-beginning 4)
7587 (> p (match-beginning 4)))))))
7588 tags pos)
7589 (cond
7590 ;; Insert a new line, possibly at end of parent subtree
7591 (org-insert-heading-respect-content
7592 (if (not eops)
7593 (progn
7594 (org-end-of-subtree nil t)
7595 (and (looking-at "^\\*") (backward-char 1))
7596 (while (and (not (bobp))
7597 ;; Don't delete spaces in empty headlines
7598 (not (looking-back org-outline-regexp))
7599 (member (char-before) '(?\ ?\t ?\n)))
7600 (backward-delete-char 1)))
7601 (let ((p (point)))
7602 (org-up-heading-safe)
7603 (if (= p (point))
7604 (goto-char (point-max))
7605 (org-end-of-subtree nil t))))
7606 (when (featurep 'org-inlinetask)
7607 (while (and (not (eobp))
7608 (looking-at "\\(\\*+\\)[ \t]+")
7609 (>= (length (match-string 1))
7610 org-inlinetask-min-level))
7611 (org-end-of-subtree nil t)))
7612 (or (bolp) (newline))
7613 (or (org-previous-line-empty-p)
7614 (and blank (newline)))
7615 (if (or empty-line-p eops) (open-line 1)))
7616 ;; Insert a headling containing text after point
7617 ((org-at-heading-p)
7618 (when hide-previous
7619 (show-children)
7620 (org-show-entry))
7621 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7622 (setq tags (and (match-end 2) (match-string 2)))
7623 (and (match-end 1)
7624 (delete-region (match-beginning 1) (match-end 1)))
7625 (setq pos (point-at-bol))
7626 (or split (end-of-line 1))
7627 (delete-horizontal-space)
7628 (if (string-match "\\`\\*+\\'"
7629 (buffer-substring (point-at-bol) (point)))
7630 (insert " "))
7631 (newline (if blank 2 1))
7632 (when tags
7633 (save-excursion
7634 (goto-char pos)
7635 (end-of-line 1)
7636 (insert " " tags)
7637 (org-set-tags nil 'align))))
7639 (or split (end-of-line 1))
7640 (newline (if blank 2 1))))))
7641 (insert head) (just-one-space)
7642 (setq pos (point))
7643 (end-of-line 1)
7644 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7645 (when (and org-insert-heading-respect-content hide-previous)
7646 (save-excursion
7647 (goto-char previous-pos)
7648 (hide-subtree)))
7649 (when (and begn endn)
7650 (narrow-to-region (min (point) begn) (max (point) endn)))
7651 (run-hooks 'org-insert-heading-hook))))))
7653 (defun org-get-heading (&optional no-tags no-todo)
7654 "Return the heading of the current entry, without the stars.
7655 When NO-TAGS is non-nil, don't include tags.
7656 When NO-TODO is non-nil, don't include TODO keywords."
7657 (save-excursion
7658 (org-back-to-heading t)
7659 (cond
7660 ((and no-tags no-todo)
7661 (looking-at org-complex-heading-regexp)
7662 (match-string 4))
7663 (no-tags
7664 (looking-at (concat org-outline-regexp
7665 "\\(.*?\\)"
7666 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7667 (match-string 1))
7668 (no-todo
7669 (looking-at org-todo-line-regexp)
7670 (match-string 3))
7671 (t (looking-at org-heading-regexp)
7672 (match-string 2)))))
7674 (defvar orgstruct-mode) ; defined below
7676 (defun org-heading-components ()
7677 "Return the components of the current heading.
7678 This is a list with the following elements:
7679 - the level as an integer
7680 - the reduced level, different if `org-odd-levels-only' is set.
7681 - the TODO keyword, or nil
7682 - the priority character, like ?A, or nil if no priority is given
7683 - the headline text itself, or the tags string if no headline text
7684 - the tags string, or nil."
7685 (save-excursion
7686 (org-back-to-heading t)
7687 (if (let (case-fold-search)
7688 (looking-at
7689 (if orgstruct-mode
7690 org-heading-regexp
7691 org-complex-heading-regexp)))
7692 (if orgstruct-mode
7693 (list (length (match-string 1))
7694 (org-reduced-level (length (match-string 1)))
7697 (match-string 2)
7698 nil)
7699 (list (length (match-string 1))
7700 (org-reduced-level (length (match-string 1)))
7701 (org-match-string-no-properties 2)
7702 (and (match-end 3) (aref (match-string 3) 2))
7703 (org-match-string-no-properties 4)
7704 (org-match-string-no-properties 5))))))
7706 (defun org-get-entry ()
7707 "Get the entry text, after heading, entire subtree."
7708 (save-excursion
7709 (org-back-to-heading t)
7710 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7712 (defun org-insert-heading-after-current ()
7713 "Insert a new heading with same level as current, after current subtree."
7714 (interactive)
7715 (org-back-to-heading)
7716 (org-insert-heading)
7717 (org-move-subtree-down)
7718 (end-of-line 1))
7720 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7721 "Insert heading with `org-insert-heading-respect-content' set to t."
7722 (interactive "P")
7723 (let ((org-insert-heading-respect-content t))
7724 (org-insert-heading arg invisible-ok)))
7726 (defun org-insert-todo-heading-respect-content (&optional force-state)
7727 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7728 (interactive "P")
7729 (let ((org-insert-heading-respect-content t))
7730 (org-insert-todo-heading force-state t)))
7732 (defun org-insert-todo-heading (arg &optional force-heading)
7733 "Insert a new heading with the same level and TODO state as current heading.
7734 If the heading has no TODO state, or if the state is DONE, use the first
7735 state (TODO by default). Also one prefix arg, force first state. With two
7736 prefix args, force inserting at the end of the parent subtree."
7737 (interactive "P")
7738 (when (or force-heading (not (org-insert-item 'checkbox)))
7739 (org-insert-heading (or (and (equal arg '(16)) '(16))
7740 force-heading))
7741 (save-excursion
7742 (org-back-to-heading)
7743 (outline-previous-heading)
7744 (looking-at org-todo-line-regexp))
7745 (let*
7746 ((new-mark-x
7747 (if (or arg
7748 (not (match-beginning 2))
7749 (member (match-string 2) org-done-keywords))
7750 (car org-todo-keywords-1)
7751 (match-string 2)))
7752 (new-mark
7754 (run-hook-with-args-until-success
7755 'org-todo-get-default-hook new-mark-x nil)
7756 new-mark-x)))
7757 (beginning-of-line 1)
7758 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7759 (if org-treat-insert-todo-heading-as-state-change
7760 (org-todo new-mark)
7761 (insert new-mark " "))))
7762 (when org-provide-todo-statistics
7763 (org-update-parent-todo-statistics))))
7765 (defun org-insert-subheading (arg)
7766 "Insert a new subheading and demote it.
7767 Works for outline headings and for plain lists alike."
7768 (interactive "P")
7769 (org-insert-heading arg)
7770 (cond
7771 ((org-at-heading-p) (org-do-demote))
7772 ((org-at-item-p) (org-indent-item))))
7774 (defun org-insert-todo-subheading (arg)
7775 "Insert a new subheading with TODO keyword or checkbox and demote it.
7776 Works for outline headings and for plain lists alike."
7777 (interactive "P")
7778 (org-insert-todo-heading arg)
7779 (cond
7780 ((org-at-heading-p) (org-do-demote))
7781 ((org-at-item-p) (org-indent-item))))
7783 ;;; Promotion and Demotion
7785 (defvar org-after-demote-entry-hook nil
7786 "Hook run after an entry has been demoted.
7787 The cursor will be at the beginning of the entry.
7788 When a subtree is being demoted, the hook will be called for each node.")
7790 (defvar org-after-promote-entry-hook nil
7791 "Hook run after an entry has been promoted.
7792 The cursor will be at the beginning of the entry.
7793 When a subtree is being promoted, the hook will be called for each node.")
7795 (defun org-promote-subtree ()
7796 "Promote the entire subtree.
7797 See also `org-promote'."
7798 (interactive)
7799 (save-excursion
7800 (org-with-limited-levels (org-map-tree 'org-promote)))
7801 (org-fix-position-after-promote))
7803 (defun org-demote-subtree ()
7804 "Demote the entire subtree. See `org-demote'.
7805 See also `org-promote'."
7806 (interactive)
7807 (save-excursion
7808 (org-with-limited-levels (org-map-tree 'org-demote)))
7809 (org-fix-position-after-promote))
7812 (defun org-do-promote ()
7813 "Promote the current heading higher up the tree.
7814 If the region is active in `transient-mark-mode', promote all headings
7815 in the region."
7816 (interactive)
7817 (save-excursion
7818 (if (org-region-active-p)
7819 (org-map-region 'org-promote (region-beginning) (region-end))
7820 (org-promote)))
7821 (org-fix-position-after-promote))
7823 (defun org-do-demote ()
7824 "Demote the current heading lower down the tree.
7825 If the region is active in `transient-mark-mode', demote all headings
7826 in the region."
7827 (interactive)
7828 (save-excursion
7829 (if (org-region-active-p)
7830 (org-map-region 'org-demote (region-beginning) (region-end))
7831 (org-demote)))
7832 (org-fix-position-after-promote))
7834 (defun org-fix-position-after-promote ()
7835 "Make sure that after pro/demotion cursor position is right."
7836 (let ((pos (point)))
7837 (when (save-excursion
7838 (beginning-of-line 1)
7839 (looking-at org-todo-line-regexp)
7840 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7841 (cond ((eobp) (insert " "))
7842 ((eolp) (insert " "))
7843 ((equal (char-after) ?\ ) (forward-char 1))))))
7845 (defun org-current-level ()
7846 "Return the level of the current entry, or nil if before the first headline.
7847 The level is the number of stars at the beginning of the headline."
7848 (save-excursion
7849 (org-with-limited-levels
7850 (if (ignore-errors (org-back-to-heading t))
7851 (funcall outline-level)))))
7853 (defun org-get-previous-line-level ()
7854 "Return the outline depth of the last headline before the current line.
7855 Returns 0 for the first headline in the buffer, and nil if before the
7856 first headline."
7857 (let ((current-level (org-current-level))
7858 (prev-level (when (> (line-number-at-pos) 1)
7859 (save-excursion
7860 (beginning-of-line 0)
7861 (org-current-level)))))
7862 (cond ((null current-level) nil) ; Before first headline
7863 ((null prev-level) 0) ; At first headline
7864 (prev-level))))
7866 (defun org-reduced-level (l)
7867 "Compute the effective level of a heading.
7868 This takes into account the setting of `org-odd-levels-only'."
7869 (cond
7870 ((zerop l) 0)
7871 (org-odd-levels-only (1+ (floor (/ l 2))))
7872 (t l)))
7874 (defun org-level-increment ()
7875 "Return the number of stars that will be added or removed at a
7876 time to headlines when structure editing, based on the value of
7877 `org-odd-levels-only'."
7878 (if org-odd-levels-only 2 1))
7880 (defun org-get-valid-level (level &optional change)
7881 "Rectify a level change under the influence of `org-odd-levels-only'
7882 LEVEL is a current level, CHANGE is by how much the level should be
7883 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7884 even level numbers will become the next higher odd number."
7885 (if org-odd-levels-only
7886 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7887 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7888 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7889 (max 1 (+ level (or change 0)))))
7891 (if (boundp 'define-obsolete-function-alias)
7892 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7893 (define-obsolete-function-alias 'org-get-legal-level
7894 'org-get-valid-level)
7895 (define-obsolete-function-alias 'org-get-legal-level
7896 'org-get-valid-level "23.1")))
7898 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7899 ;; ̀org-with-limited-levels'
7900 (defun org-promote ()
7901 "Promote the current heading higher up the tree.
7902 If the region is active in `transient-mark-mode', promote all headings
7903 in the region."
7904 (org-back-to-heading t)
7905 (let* ((level (save-match-data (funcall outline-level)))
7906 (after-change-functions (remove 'flyspell-after-change-function
7907 after-change-functions))
7908 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7909 (diff (abs (- level (length up-head) -1))))
7910 (cond ((and (= level 1) org-called-with-limited-levels
7911 org-allow-promoting-top-level-subtree)
7912 (replace-match "# " nil t))
7913 ((= level 1)
7914 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7915 (t (replace-match up-head nil t)))
7916 ;; Fixup tag positioning
7917 (unless (= level 1)
7918 (and org-auto-align-tags (org-set-tags nil t))
7919 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7920 (run-hooks 'org-after-promote-entry-hook)))
7922 (defun org-demote ()
7923 "Demote the current heading lower down the tree.
7924 If the region is active in `transient-mark-mode', demote all headings
7925 in the region."
7926 (org-back-to-heading t)
7927 (let* ((level (save-match-data (funcall outline-level)))
7928 (after-change-functions (remove 'flyspell-after-change-function
7929 after-change-functions))
7930 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7931 (diff (abs (- level (length down-head) -1))))
7932 (replace-match down-head nil t)
7933 ;; Fixup tag positioning
7934 (and org-auto-align-tags (org-set-tags nil t))
7935 (if org-adapt-indentation (org-fixup-indentation diff))
7936 (run-hooks 'org-after-demote-entry-hook)))
7938 (defun org-cycle-level ()
7939 "Cycle the level of an empty headline through possible states.
7940 This goes first to child, then to parent, level, then up the hierarchy.
7941 After top level, it switches back to sibling level."
7942 (interactive)
7943 (let ((org-adapt-indentation nil))
7944 (when (org-point-at-end-of-empty-headline)
7945 (setq this-command 'org-cycle-level) ; Only needed for caching
7946 (let ((cur-level (org-current-level))
7947 (prev-level (org-get-previous-line-level)))
7948 (cond
7949 ;; If first headline in file, promote to top-level.
7950 ((= prev-level 0)
7951 (loop repeat (/ (- cur-level 1) (org-level-increment))
7952 do (org-do-promote)))
7953 ;; If same level as prev, demote one.
7954 ((= prev-level cur-level)
7955 (org-do-demote))
7956 ;; If parent is top-level, promote to top level if not already.
7957 ((= prev-level 1)
7958 (loop repeat (/ (- cur-level 1) (org-level-increment))
7959 do (org-do-promote)))
7960 ;; If top-level, return to prev-level.
7961 ((= cur-level 1)
7962 (loop repeat (/ (- prev-level 1) (org-level-increment))
7963 do (org-do-demote)))
7964 ;; If less than prev-level, promote one.
7965 ((< cur-level prev-level)
7966 (org-do-promote))
7967 ;; If deeper than prev-level, promote until higher than
7968 ;; prev-level.
7969 ((> cur-level prev-level)
7970 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7971 do (org-do-promote))))
7972 t))))
7974 (defun org-map-tree (fun)
7975 "Call FUN for every heading underneath the current one."
7976 (org-back-to-heading)
7977 (let ((level (funcall outline-level)))
7978 (save-excursion
7979 (funcall fun)
7980 (while (and (progn
7981 (outline-next-heading)
7982 (> (funcall outline-level) level))
7983 (not (eobp)))
7984 (funcall fun)))))
7986 (defun org-map-region (fun beg end)
7987 "Call FUN for every heading between BEG and END."
7988 (let ((org-ignore-region t))
7989 (save-excursion
7990 (setq end (copy-marker end))
7991 (goto-char beg)
7992 (if (and (re-search-forward org-outline-regexp-bol nil t)
7993 (< (point) end))
7994 (funcall fun))
7995 (while (and (progn
7996 (outline-next-heading)
7997 (< (point) end))
7998 (not (eobp)))
7999 (funcall fun)))))
8001 (defvar org-property-end-re) ; silence byte-compiler
8002 (defun org-fixup-indentation (diff)
8003 "Change the indentation in the current entry by DIFF.
8004 However, if any line in the current entry has no indentation, or if it
8005 would end up with no indentation after the change, nothing at all is done."
8006 (save-excursion
8007 (let ((end (save-excursion (outline-next-heading)
8008 (point-marker)))
8009 (prohibit (if (> diff 0)
8010 "^\\S-"
8011 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8012 col)
8013 (unless (save-excursion (end-of-line 1)
8014 (re-search-forward prohibit end t))
8015 (while (and (< (point) end)
8016 (re-search-forward "^[ \t]+" end t))
8017 (goto-char (match-end 0))
8018 (setq col (current-column))
8019 (if (< diff 0) (replace-match ""))
8020 (org-indent-to-column (+ diff col))))
8021 (move-marker end nil))))
8023 (defun org-convert-to-odd-levels ()
8024 "Convert an org-mode file with all levels allowed to one with odd levels.
8025 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8026 level 5 etc."
8027 (interactive)
8028 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8029 (let ((outline-level 'org-outline-level)
8030 (org-odd-levels-only nil) n)
8031 (save-excursion
8032 (goto-char (point-min))
8033 (while (re-search-forward "^\\*\\*+ " nil t)
8034 (setq n (- (length (match-string 0)) 2))
8035 (while (>= (setq n (1- n)) 0)
8036 (org-demote))
8037 (end-of-line 1))))))
8039 (defun org-convert-to-oddeven-levels ()
8040 "Convert an org-mode file with only odd levels to one with odd/even levels.
8041 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8042 file contains a section with an even level, conversion would
8043 destroy the structure of the file. An error is signaled in this
8044 case."
8045 (interactive)
8046 (goto-char (point-min))
8047 ;; First check if there are no even levels
8048 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8049 (org-show-context t)
8050 (error "Not all levels are odd in this file. Conversion not possible"))
8051 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8052 (let ((outline-regexp org-outline-regexp)
8053 (outline-level 'org-outline-level)
8054 (org-odd-levels-only nil) n)
8055 (save-excursion
8056 (goto-char (point-min))
8057 (while (re-search-forward "^\\*\\*+ " nil t)
8058 (setq n (/ (1- (length (match-string 0))) 2))
8059 (while (>= (setq n (1- n)) 0)
8060 (org-promote))
8061 (end-of-line 1))))))
8063 (defun org-tr-level (n)
8064 "Make N odd if required."
8065 (if org-odd-levels-only (1+ (/ n 2)) n))
8067 ;;; Vertical tree motion, cutting and pasting of subtrees
8069 (defun org-move-subtree-up (&optional arg)
8070 "Move the current subtree up past ARG headlines of the same level."
8071 (interactive "p")
8072 (org-move-subtree-down (- (prefix-numeric-value arg))))
8074 (defun org-move-subtree-down (&optional arg)
8075 "Move the current subtree down past ARG headlines of the same level."
8076 (interactive "p")
8077 (setq arg (prefix-numeric-value arg))
8078 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8079 'org-get-last-sibling))
8080 (ins-point (make-marker))
8081 (cnt (abs arg))
8082 (col (current-column))
8083 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8084 ;; Select the tree
8085 (org-back-to-heading)
8086 (setq beg0 (point))
8087 (save-excursion
8088 (setq ne-beg (org-back-over-empty-lines))
8089 (setq beg (point)))
8090 (save-match-data
8091 (save-excursion (outline-end-of-heading)
8092 (setq folded (outline-invisible-p)))
8093 (outline-end-of-subtree))
8094 (outline-next-heading)
8095 (setq ne-end (org-back-over-empty-lines))
8096 (setq end (point))
8097 (goto-char beg0)
8098 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8099 ;; include less whitespace
8100 (save-excursion
8101 (goto-char beg)
8102 (forward-line (- ne-beg ne-end))
8103 (setq beg (point))))
8104 ;; Find insertion point, with error handling
8105 (while (> cnt 0)
8106 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8107 (progn (goto-char beg0)
8108 (user-error "Cannot move past superior level or buffer limit")))
8109 (setq cnt (1- cnt)))
8110 (if (> arg 0)
8111 ;; Moving forward - still need to move over subtree
8112 (progn (org-end-of-subtree t t)
8113 (save-excursion
8114 (org-back-over-empty-lines)
8115 (or (bolp) (newline)))))
8116 (setq ne-ins (org-back-over-empty-lines))
8117 (move-marker ins-point (point))
8118 (setq txt (buffer-substring beg end))
8119 (org-save-markers-in-region beg end)
8120 (delete-region beg end)
8121 (org-remove-empty-overlays-at beg)
8122 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8123 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8124 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8125 (let ((bbb (point)))
8126 (insert-before-markers txt)
8127 (org-reinstall-markers-in-region bbb)
8128 (move-marker ins-point bbb))
8129 (or (bolp) (insert "\n"))
8130 (setq ins-end (point))
8131 (goto-char ins-point)
8132 (org-skip-whitespace)
8133 (when (and (< arg 0)
8134 (org-first-sibling-p)
8135 (> ne-ins ne-beg))
8136 ;; Move whitespace back to beginning
8137 (save-excursion
8138 (goto-char ins-end)
8139 (let ((kill-whole-line t))
8140 (kill-line (- ne-ins ne-beg)) (point)))
8141 (insert (make-string (- ne-ins ne-beg) ?\n)))
8142 (move-marker ins-point nil)
8143 (if folded
8144 (hide-subtree)
8145 (org-show-entry)
8146 (show-children)
8147 (org-cycle-hide-drawers 'children))
8148 (org-clean-visibility-after-subtree-move)
8149 ;; move back to the initial column we were at
8150 (move-to-column col)))
8152 (defvar org-subtree-clip ""
8153 "Clipboard for cut and paste of subtrees.
8154 This is actually only a copy of the kill, because we use the normal kill
8155 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8157 (defvar org-subtree-clip-folded nil
8158 "Was the last copied subtree folded?
8159 This is used to fold the tree back after pasting.")
8161 (defun org-cut-subtree (&optional n)
8162 "Cut the current subtree into the clipboard.
8163 With prefix arg N, cut this many sequential subtrees.
8164 This is a short-hand for marking the subtree and then cutting it."
8165 (interactive "p")
8166 (org-copy-subtree n 'cut))
8168 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8169 "Cut the current subtree into the clipboard.
8170 With prefix arg N, cut this many sequential subtrees.
8171 This is a short-hand for marking the subtree and then copying it.
8172 If CUT is non-nil, actually cut the subtree.
8173 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8174 of some markers in the region, even if CUT is non-nil. This is
8175 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8176 (interactive "p")
8177 (let (beg end folded (beg0 (point)))
8178 (if (org-called-interactively-p 'any)
8179 (org-back-to-heading nil) ; take what looks like a subtree
8180 (org-back-to-heading t)) ; take what is really there
8181 (setq beg (point))
8182 (skip-chars-forward " \t\r\n")
8183 (save-match-data
8184 (if nosubtrees
8185 (outline-next-heading)
8186 (save-excursion (outline-end-of-heading)
8187 (setq folded (outline-invisible-p)))
8188 (condition-case nil
8189 (org-forward-heading-same-level (1- n) t)
8190 (error nil))
8191 (org-end-of-subtree t t)))
8192 (setq end (point))
8193 (goto-char beg0)
8194 (when (> end beg)
8195 (setq org-subtree-clip-folded folded)
8196 (when (or cut force-store-markers)
8197 (org-save-markers-in-region beg end))
8198 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8199 (setq org-subtree-clip (current-kill 0))
8200 (message "%s: Subtree(s) with %d characters"
8201 (if cut "Cut" "Copied")
8202 (length org-subtree-clip)))))
8204 (defun org-paste-subtree (&optional level tree for-yank)
8205 "Paste the clipboard as a subtree, with modification of headline level.
8206 The entire subtree is promoted or demoted in order to match a new headline
8207 level.
8209 If the cursor is at the beginning of a headline, the same level as
8210 that headline is used to paste the tree.
8212 If not, the new level is derived from the *visible* headings
8213 before and after the insertion point, and taken to be the inferior headline
8214 level of the two. So if the previous visible heading is level 3 and the
8215 next is level 4 (or vice versa), level 4 will be used for insertion.
8216 This makes sure that the subtree remains an independent subtree and does
8217 not swallow low level entries.
8219 You can also force a different level, either by using a numeric prefix
8220 argument, or by inserting the heading marker by hand. For example, if the
8221 cursor is after \"*****\", then the tree will be shifted to level 5.
8223 If optional TREE is given, use this text instead of the kill ring.
8225 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8226 move back over whitespace before inserting, and move point to the end of
8227 the inserted text when done."
8228 (interactive "P")
8229 (setq tree (or tree (and kill-ring (current-kill 0))))
8230 (unless (org-kill-is-subtree-p tree)
8231 (error "%s"
8232 (substitute-command-keys
8233 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8234 (org-with-limited-levels
8235 (let* ((visp (not (outline-invisible-p)))
8236 (txt tree)
8237 (^re_ "\\(\\*+\\)[ \t]*")
8238 (old-level (if (string-match org-outline-regexp-bol txt)
8239 (- (match-end 0) (match-beginning 0) 1)
8240 -1))
8241 (force-level (cond (level (prefix-numeric-value level))
8242 ((and (looking-at "[ \t]*$")
8243 (string-match
8244 "^\\*+$" (buffer-substring
8245 (point-at-bol) (point))))
8246 (- (match-end 1) (match-beginning 1)))
8247 ((and (bolp)
8248 (looking-at org-outline-regexp))
8249 (- (match-end 0) (point) 1))))
8250 (previous-level (save-excursion
8251 (condition-case nil
8252 (progn
8253 (outline-previous-visible-heading 1)
8254 (if (looking-at ^re_)
8255 (- (match-end 0) (match-beginning 0) 1)
8257 (error 1))))
8258 (next-level (save-excursion
8259 (condition-case nil
8260 (progn
8261 (or (looking-at org-outline-regexp)
8262 (outline-next-visible-heading 1))
8263 (if (looking-at ^re_)
8264 (- (match-end 0) (match-beginning 0) 1)
8266 (error 1))))
8267 (new-level (or force-level (max previous-level next-level)))
8268 (shift (if (or (= old-level -1)
8269 (= new-level -1)
8270 (= old-level new-level))
8272 (- new-level old-level)))
8273 (delta (if (> shift 0) -1 1))
8274 (func (if (> shift 0) 'org-demote 'org-promote))
8275 (org-odd-levels-only nil)
8276 beg end newend)
8277 ;; Remove the forced level indicator
8278 (if force-level
8279 (delete-region (point-at-bol) (point)))
8280 ;; Paste
8281 (beginning-of-line (if (bolp) 1 2))
8282 (setq beg (point))
8283 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8284 (insert-before-markers txt)
8285 (unless (string-match "\n\\'" txt) (insert "\n"))
8286 (setq newend (point))
8287 (org-reinstall-markers-in-region beg)
8288 (setq end (point))
8289 (goto-char beg)
8290 (skip-chars-forward " \t\n\r")
8291 (setq beg (point))
8292 (if (and (outline-invisible-p) visp)
8293 (save-excursion (outline-show-heading)))
8294 ;; Shift if necessary
8295 (unless (= shift 0)
8296 (save-restriction
8297 (narrow-to-region beg end)
8298 (while (not (= shift 0))
8299 (org-map-region func (point-min) (point-max))
8300 (setq shift (+ delta shift)))
8301 (goto-char (point-min))
8302 (setq newend (point-max))))
8303 (when (or (org-called-interactively-p 'interactive) for-yank)
8304 (message "Clipboard pasted as level %d subtree" new-level))
8305 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8306 kill-ring
8307 (eq org-subtree-clip (current-kill 0))
8308 org-subtree-clip-folded)
8309 ;; The tree was folded before it was killed/copied
8310 (hide-subtree))
8311 (and for-yank (goto-char newend)))))
8313 (defun org-kill-is-subtree-p (&optional txt)
8314 "Check if the current kill is an outline subtree, or a set of trees.
8315 Returns nil if kill does not start with a headline, or if the first
8316 headline level is not the largest headline level in the tree.
8317 So this will actually accept several entries of equal levels as well,
8318 which is OK for `org-paste-subtree'.
8319 If optional TXT is given, check this string instead of the current kill."
8320 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8321 (re (org-get-limited-outline-regexp))
8322 (^re (concat "^" re))
8323 (start-level (and kill
8324 (string-match
8325 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8326 kill)
8327 (- (match-end 2) (match-beginning 2) 1)))
8328 (start (1+ (or (match-beginning 2) -1))))
8329 (if (not start-level)
8330 (progn
8331 nil) ;; does not even start with a heading
8332 (catch 'exit
8333 (while (setq start (string-match ^re kill (1+ start)))
8334 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8335 (throw 'exit nil)))
8336 t))))
8338 (defvar org-markers-to-move nil
8339 "Markers that should be moved with a cut-and-paste operation.
8340 Those markers are stored together with their positions relative to
8341 the start of the region.")
8343 (defun org-save-markers-in-region (beg end)
8344 "Check markers in region.
8345 If these markers are between BEG and END, record their position relative
8346 to BEG, so that after moving the block of text, we can put the markers back
8347 into place.
8348 This function gets called just before an entry or tree gets cut from the
8349 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8350 called immediately, to move the markers with the entries."
8351 (setq org-markers-to-move nil)
8352 (when (featurep 'org-clock)
8353 (org-clock-save-markers-for-cut-and-paste beg end))
8354 (when (featurep 'org-agenda)
8355 (org-agenda-save-markers-for-cut-and-paste beg end)))
8357 (defun org-check-and-save-marker (marker beg end)
8358 "Check if MARKER is between BEG and END.
8359 If yes, remember the marker and the distance to BEG."
8360 (when (and (marker-buffer marker)
8361 (equal (marker-buffer marker) (current-buffer)))
8362 (if (and (>= marker beg) (< marker end))
8363 (push (cons marker (- marker beg)) org-markers-to-move))))
8365 (defun org-reinstall-markers-in-region (beg)
8366 "Move all remembered markers to their position relative to BEG."
8367 (mapc (lambda (x)
8368 (move-marker (car x) (+ beg (cdr x))))
8369 org-markers-to-move)
8370 (setq org-markers-to-move nil))
8372 (defun org-narrow-to-subtree ()
8373 "Narrow buffer to the current subtree."
8374 (interactive)
8375 (save-excursion
8376 (save-match-data
8377 (org-with-limited-levels
8378 (narrow-to-region
8379 (progn (org-back-to-heading t) (point))
8380 (progn (org-end-of-subtree t t)
8381 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8382 (point)))))))
8384 (defun org-narrow-to-block ()
8385 "Narrow buffer to the current block."
8386 (interactive)
8387 (let* ((case-fold-search t)
8388 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8389 "^[ \t]*#\\+end_.*")))
8390 (if blockp
8391 (narrow-to-region (car blockp) (cdr blockp))
8392 (error "Not in a block"))))
8394 (eval-when-compile
8395 (defvar org-property-drawer-re))
8397 (defvar org-property-start-re) ;; defined below
8398 (defun org-clone-subtree-with-time-shift (n &optional shift)
8399 "Clone the task (subtree) at point N times.
8400 The clones will be inserted as siblings.
8402 In interactive use, the user will be prompted for the number of
8403 clones to be produced. When called with a universal prefix argument
8404 and if the entry has a timestamp, the user will also be prompted for
8405 a time shift, which may be a repeater as used in time stamps, for
8406 example `+3d'.
8408 When a valid repeater is given and the entry contains any time
8409 stamps, the clones will become a sequence in time, with time
8410 stamps in the subtree shifted for each clone produced. If SHIFT
8411 is nil or the empty string, time stamps will be left alone. The
8412 ID property of the original subtree is removed.
8414 If the original subtree did contain time stamps with a repeater,
8415 the following will happen:
8416 - the repeater will be removed in each clone
8417 - an additional clone will be produced, with the current, unshifted
8418 date(s) in the entry.
8419 - the original entry will be placed *after* all the clones, with
8420 repeater intact.
8421 - the start days in the repeater in the original entry will be shifted
8422 to past the last clone.
8423 In this way you can spell out a number of instances of a repeating task,
8424 and still retain the repeater to cover future instances of the task."
8425 (interactive "nNumber of clones to produce: ")
8426 (let ((shift
8427 (or shift
8428 (if (and (equal current-prefix-arg '(4))
8429 (save-excursion
8430 (re-search-forward org-ts-regexp-both
8431 (save-excursion
8432 (org-end-of-subtree t)
8433 (point)) t)))
8434 (read-from-minibuffer
8435 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8436 ""))) ;; No time shift
8437 (n-no-remove -1)
8438 (drawer-re org-drawer-regexp)
8439 beg end template task idprop
8440 shift-n shift-what doshift nmin nmax)
8441 (if (not (and (integerp n) (> n 0)))
8442 (error "Invalid number of replications %s" n))
8443 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8444 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8445 shift)))
8446 (error "Invalid shift specification %s" shift))
8447 (when doshift
8448 (setq shift-n (string-to-number (match-string 1 shift))
8449 shift-what (cdr (assoc (match-string 2 shift)
8450 '(("d" . day) ("w" . week)
8451 ("m" . month) ("y" . year))))))
8452 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8453 (setq nmin 1 nmax n)
8454 (org-back-to-heading t)
8455 (setq beg (point))
8456 (setq idprop (org-entry-get nil "ID"))
8457 (org-end-of-subtree t t)
8458 (or (bolp) (insert "\n"))
8459 (setq end (point))
8460 (setq template (buffer-substring beg end))
8461 (when (and doshift
8462 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8463 (delete-region beg end)
8464 (setq end beg)
8465 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8466 (goto-char end)
8467 (loop for n from nmin to nmax do
8468 ;; prepare clone
8469 (with-temp-buffer
8470 (insert template)
8471 (org-mode)
8472 (goto-char (point-min))
8473 (org-show-subtree)
8474 (and idprop (if org-clone-delete-id
8475 (org-entry-delete nil "ID")
8476 (org-id-get-create t)))
8477 (unless (= n 0)
8478 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8479 (kill-whole-line))
8480 (goto-char (point-min))
8481 (while (re-search-forward drawer-re nil t)
8482 (mapc (lambda (d)
8483 (org-remove-empty-drawer-at d (point))) org-drawers)))
8484 (goto-char (point-min))
8485 (when doshift
8486 (while (re-search-forward org-ts-regexp-both nil t)
8487 (org-timestamp-change (* n shift-n) shift-what))
8488 (unless (= n n-no-remove)
8489 (goto-char (point-min))
8490 (while (re-search-forward org-ts-regexp nil t)
8491 (save-excursion
8492 (goto-char (match-beginning 0))
8493 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8494 (delete-region (match-beginning 1) (match-end 1)))))))
8495 (setq task (buffer-string)))
8496 (insert task))
8497 (goto-char beg)))
8499 ;;; Outline Sorting
8501 (defun org-sort (with-case)
8502 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8503 Optional argument WITH-CASE means sort case-sensitively."
8504 (interactive "P")
8505 (cond
8506 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8507 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8509 (org-call-with-arg 'org-sort-entries with-case))))
8511 (defun org-sort-remove-invisible (s)
8512 "Remove invisible links from string S."
8513 (remove-text-properties 0 (length s) org-rm-props s)
8514 (while (string-match org-bracket-link-regexp s)
8515 (setq s (replace-match (if (match-end 2)
8516 (match-string 3 s)
8517 (match-string 1 s)) t t s)))
8518 (let ((st (format " %s " s)))
8519 (while (string-match org-emph-re st)
8520 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8521 (setq s (substring st 1 -1)))
8524 (defvar org-priority-regexp) ; defined later in the file
8526 (defvar org-after-sorting-entries-or-items-hook nil
8527 "Hook that is run after a bunch of entries or items have been sorted.
8528 When children are sorted, the cursor is in the parent line when this
8529 hook gets called. When a region or a plain list is sorted, the cursor
8530 will be in the first entry of the sorted region/list.")
8532 (defun org-sort-entries
8533 (&optional with-case sorting-type getkey-func compare-func property)
8534 "Sort entries on a certain level of an outline tree.
8535 If there is an active region, the entries in the region are sorted.
8536 Else, if the cursor is before the first entry, sort the top-level items.
8537 Else, the children of the entry at point are sorted.
8539 Sorting can be alphabetically, numerically, by date/time as given by
8540 a time stamp, by a property, by priority order, or by a custom function.
8542 The command prompts for the sorting type unless it has been given to the
8543 function through the SORTING-TYPE argument, which needs to be a character,
8544 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8545 precise meaning of each character:
8547 n Numerically, by converting the beginning of the entry/item to a number.
8548 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8549 o By order of TODO keywords.
8550 t By date/time, either the first active time stamp in the entry, or, if
8551 none exist, by the first inactive one.
8552 s By the scheduled date/time.
8553 d By deadline date/time.
8554 c By creation time, which is assumed to be the first inactive time stamp
8555 at the beginning of a line.
8556 p By priority according to the cookie.
8557 r By the value of a property.
8559 Capital letters will reverse the sort order.
8561 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8562 called with point at the beginning of the record. It must return either
8563 a string or a number that should serve as the sorting key for that record.
8565 Comparing entries ignores case by default. However, with an optional argument
8566 WITH-CASE, the sorting considers case as well.
8568 Sorting is done against the visible part of the headlines, it ignores hidden
8569 links."
8570 (interactive "P")
8571 (let ((case-func (if with-case 'identity 'downcase))
8572 (cmstr
8573 ;; The clock marker is lost when using `sort-subr', let's
8574 ;; store the clocking string.
8575 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8576 (save-excursion
8577 (goto-char org-clock-marker)
8578 (looking-back "^.*") (match-string-no-properties 0))))
8579 start beg end stars re re2
8580 txt what tmp)
8581 ;; Find beginning and end of region to sort
8582 (cond
8583 ((org-region-active-p)
8584 ;; we will sort the region
8585 (setq end (region-end)
8586 what "region")
8587 (goto-char (region-beginning))
8588 (if (not (org-at-heading-p)) (outline-next-heading))
8589 (setq start (point)))
8590 ((or (org-at-heading-p)
8591 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8592 ;; we will sort the children of the current headline
8593 (org-back-to-heading)
8594 (setq start (point)
8595 end (progn (org-end-of-subtree t t)
8596 (or (bolp) (insert "\n"))
8597 (org-back-over-empty-lines)
8598 (point))
8599 what "children")
8600 (goto-char start)
8601 (show-subtree)
8602 (outline-next-heading))
8604 ;; we will sort the top-level entries in this file
8605 (goto-char (point-min))
8606 (or (org-at-heading-p) (outline-next-heading))
8607 (setq start (point))
8608 (goto-char (point-max))
8609 (beginning-of-line 1)
8610 (when (looking-at ".*?\\S-")
8611 ;; File ends in a non-white line
8612 (end-of-line 1)
8613 (insert "\n"))
8614 (setq end (point-max))
8615 (setq what "top-level")
8616 (goto-char start)
8617 (show-all)))
8619 (setq beg (point))
8620 (if (>= beg end) (error "Nothing to sort"))
8622 (looking-at "\\(\\*+\\)")
8623 (setq stars (match-string 1)
8624 re (concat "^" (regexp-quote stars) " +")
8625 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8626 txt (buffer-substring beg end))
8627 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8628 (if (and (not (equal stars "*")) (string-match re2 txt))
8629 (error "Region to sort contains a level above the first entry"))
8631 (unless sorting-type
8632 (message
8633 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8634 [t]ime [s]cheduled [d]eadline [c]reated
8635 A/N/P/R/O/F/T/S/D/C means reversed:"
8636 what)
8637 (setq sorting-type (read-char-exclusive))
8639 (unless getkey-func
8640 (and (= (downcase sorting-type) ?f)
8641 (setq getkey-func
8642 (org-icompleting-read "Sort using function: "
8643 obarray 'fboundp t nil nil))
8644 (setq getkey-func (intern getkey-func))))
8646 (and (= (downcase sorting-type) ?r)
8647 (not property)
8648 (setq property
8649 (org-icompleting-read "Property: "
8650 (mapcar 'list (org-buffer-property-keys t))
8651 nil t))))
8653 (message "Sorting entries...")
8655 (save-restriction
8656 (narrow-to-region start end)
8657 (let ((dcst (downcase sorting-type))
8658 (case-fold-search nil)
8659 (now (current-time)))
8660 (sort-subr
8661 (/= dcst sorting-type)
8662 ;; This function moves to the beginning character of the "record" to
8663 ;; be sorted.
8664 (lambda nil
8665 (if (re-search-forward re nil t)
8666 (goto-char (match-beginning 0))
8667 (goto-char (point-max))))
8668 ;; This function moves to the last character of the "record" being
8669 ;; sorted.
8670 (lambda nil
8671 (save-match-data
8672 (condition-case nil
8673 (outline-forward-same-level 1)
8674 (error
8675 (goto-char (point-max))))))
8676 ;; This function returns the value that gets sorted against.
8677 (lambda nil
8678 (cond
8679 ((= dcst ?n)
8680 (if (looking-at org-complex-heading-regexp)
8681 (string-to-number (org-sort-remove-invisible (match-string 4)))
8682 nil))
8683 ((= dcst ?a)
8684 (if (looking-at org-complex-heading-regexp)
8685 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8686 nil))
8687 ((= dcst ?t)
8688 (let ((end (save-excursion (outline-next-heading) (point))))
8689 (if (or (re-search-forward org-ts-regexp end t)
8690 (re-search-forward org-ts-regexp-both end t))
8691 (org-time-string-to-seconds (match-string 0))
8692 (org-float-time now))))
8693 ((= dcst ?c)
8694 (let ((end (save-excursion (outline-next-heading) (point))))
8695 (if (re-search-forward
8696 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8697 end t)
8698 (org-time-string-to-seconds (match-string 0))
8699 (org-float-time now))))
8700 ((= dcst ?s)
8701 (let ((end (save-excursion (outline-next-heading) (point))))
8702 (if (re-search-forward org-scheduled-time-regexp end t)
8703 (org-time-string-to-seconds (match-string 1))
8704 (org-float-time now))))
8705 ((= dcst ?d)
8706 (let ((end (save-excursion (outline-next-heading) (point))))
8707 (if (re-search-forward org-deadline-time-regexp end t)
8708 (org-time-string-to-seconds (match-string 1))
8709 (org-float-time now))))
8710 ((= dcst ?p)
8711 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8712 (string-to-char (match-string 2))
8713 org-default-priority))
8714 ((= dcst ?r)
8715 (or (org-entry-get nil property) ""))
8716 ((= dcst ?o)
8717 (if (looking-at org-complex-heading-regexp)
8718 (- 9999 (length (member (match-string 2)
8719 org-todo-keywords-1)))))
8720 ((= dcst ?f)
8721 (if getkey-func
8722 (progn
8723 (setq tmp (funcall getkey-func))
8724 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8725 tmp)
8726 (error "Invalid key function `%s'" getkey-func)))
8727 (t (error "Invalid sorting type `%c'" sorting-type))))
8729 (cond
8730 ((= dcst ?a) 'string<)
8731 ((= dcst ?f) compare-func)
8732 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8733 (run-hooks 'org-after-sorting-entries-or-items-hook)
8734 ;; Reset the clock marker if needed
8735 (when cmstr
8736 (save-excursion
8737 (goto-char start)
8738 (search-forward cmstr nil t)
8739 (move-marker org-clock-marker (point))))
8740 (message "Sorting entries...done")))
8742 (defun org-do-sort (table what &optional with-case sorting-type)
8743 "Sort TABLE of WHAT according to SORTING-TYPE.
8744 The user will be prompted for the SORTING-TYPE if the call to this
8745 function does not specify it. WHAT is only for the prompt, to indicate
8746 what is being sorted. The sorting key will be extracted from
8747 the car of the elements of the table.
8748 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8749 (unless sorting-type
8750 (message
8751 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8752 what)
8753 (setq sorting-type (read-char-exclusive)))
8754 (let ((dcst (downcase sorting-type))
8755 extractfun comparefun)
8756 ;; Define the appropriate functions
8757 (cond
8758 ((= dcst ?n)
8759 (setq extractfun 'string-to-number
8760 comparefun (if (= dcst sorting-type) '< '>)))
8761 ((= dcst ?a)
8762 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8763 (lambda(x) (downcase (org-sort-remove-invisible x))))
8764 comparefun (if (= dcst sorting-type)
8765 'string<
8766 (lambda (a b) (and (not (string< a b))
8767 (not (string= a b)))))))
8768 ((= dcst ?t)
8769 (setq extractfun
8770 (lambda (x)
8771 (if (or (string-match org-ts-regexp x)
8772 (string-match org-ts-regexp-both x))
8773 (org-float-time
8774 (org-time-string-to-time (match-string 0 x)))
8776 comparefun (if (= dcst sorting-type) '< '>)))
8777 (t (error "Invalid sorting type `%c'" sorting-type)))
8779 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8780 table)
8781 (lambda (a b) (funcall comparefun (car a) (car b))))))
8784 ;;; The orgstruct minor mode
8786 ;; Define a minor mode which can be used in other modes in order to
8787 ;; integrate the org-mode structure editing commands.
8789 ;; This is really a hack, because the org-mode structure commands use
8790 ;; keys which normally belong to the major mode. Here is how it
8791 ;; works: The minor mode defines all the keys necessary to operate the
8792 ;; structure commands, but wraps the commands into a function which
8793 ;; tests if the cursor is currently at a headline or a plain list
8794 ;; item. If that is the case, the structure command is used,
8795 ;; temporarily setting many Org-mode variables like regular
8796 ;; expressions for filling etc. However, when any of those keys is
8797 ;; used at a different location, function uses `key-binding' to look
8798 ;; up if the key has an associated command in another currently active
8799 ;; keymap (minor modes, major mode, global), and executes that
8800 ;; command. There might be problems if any of the keys is otherwise
8801 ;; used as a prefix key.
8803 (defcustom orgstruct-heading-prefix-regexp nil
8804 "Regexp that matches the custom prefix of Org headlines in
8805 orgstruct(++)-mode."
8806 :group 'org
8807 :version "24.4"
8808 :package-version '(Org . "8.0")
8809 :type 'string)
8810 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8812 (defcustom orgstruct-setup-hook nil
8813 "Hook run after orgstruct-mode-map is filled."
8814 :group 'org
8815 :version "24.4"
8816 :package-version '(Org . "8.0")
8817 :type 'hook)
8819 (defvar orgstruct-initialized nil)
8821 (defvar org-local-vars nil
8822 "List of local variables, for use by `orgstruct-mode'.")
8824 ;;;###autoload
8825 (define-minor-mode orgstruct-mode
8826 "Toggle the minor mode `orgstruct-mode'.
8827 This mode is for using Org-mode structure commands in other
8828 modes. The following keys behave as if Org-mode were active, if
8829 the cursor is on a headline, or on a plain list item (both as
8830 defined by Org-mode)."
8831 nil " OrgStruct" (make-sparse-keymap)
8832 (funcall (if orgstruct-mode
8833 'add-to-invisibility-spec
8834 'remove-from-invisibility-spec)
8835 '(outline . t))
8836 (when orgstruct-mode
8837 (org-load-modules-maybe)
8838 (unless orgstruct-initialized
8839 (orgstruct-setup)
8840 (setq orgstruct-initialized t))))
8842 ;;;###autoload
8843 (defun turn-on-orgstruct ()
8844 "Unconditionally turn on `orgstruct-mode'."
8845 (orgstruct-mode 1))
8847 (defvar org-fb-vars nil)
8848 (make-variable-buffer-local 'org-fb-vars)
8849 (defun orgstruct++-mode (&optional arg)
8850 "Toggle `orgstruct-mode', the enhanced version of it.
8851 In addition to setting orgstruct-mode, this also exports all
8852 indentation and autofilling variables from org-mode into the
8853 buffer. It will also recognize item context in multiline items."
8854 (interactive "P")
8855 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8856 (if (< arg 1)
8857 (progn (orgstruct-mode -1)
8858 (mapc (lambda(v)
8859 (org-set-local (car v)
8860 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8861 org-fb-vars))
8862 (orgstruct-mode 1)
8863 (setq org-fb-vars nil)
8864 (let (var val)
8865 (mapc
8866 (lambda (x)
8867 (when (string-match
8868 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8869 (symbol-name (car x)))
8870 (setq var (car x) val (nth 1 x))
8871 (push (list var `(quote ,(eval var))) org-fb-vars)
8872 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8873 org-local-vars)
8874 (org-set-local 'orgstruct-is-++ t))))
8876 (defvar orgstruct-is-++ nil
8877 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8878 (make-variable-buffer-local 'orgstruct-is-++)
8880 ;;;###autoload
8881 (defun turn-on-orgstruct++ ()
8882 "Unconditionally turn on `orgstruct++-mode'."
8883 (orgstruct++-mode 1))
8885 (defun orgstruct-error ()
8886 "Error when there is no default binding for a structure key."
8887 (interactive)
8888 (funcall (if (fboundp 'user-error)
8889 'user-error
8890 'error)
8891 "This key has no function outside structure elements"))
8893 (defun orgstruct-setup ()
8894 "Setup orgstruct keymap."
8895 (dolist (cell '((org-demote . t)
8896 (org-metaleft . t)
8897 (org-metaright . t)
8898 (org-promote . t)
8899 (org-shiftmetaleft . t)
8900 (org-shiftmetaright . t)
8901 org-backward-element
8902 org-backward-heading-same-level
8903 org-ctrl-c-ret
8904 org-ctrl-c-minus
8905 org-ctrl-c-star
8906 org-cycle
8907 org-forward-heading-same-level
8908 org-insert-heading
8909 org-insert-heading-respect-content
8910 org-kill-note-or-show-branches
8911 org-mark-subtree
8912 org-meta-return
8913 org-metadown
8914 org-metaup
8915 org-narrow-to-subtree
8916 org-promote-subtree
8917 org-reveal
8918 org-shiftdown
8919 org-shiftleft
8920 org-shiftmetadown
8921 org-shiftmetaup
8922 org-shiftright
8923 org-shifttab
8924 org-shifttab
8925 org-shiftup
8926 org-show-subtree
8927 org-sort
8928 org-up-element
8929 outline-demote
8930 outline-next-visible-heading
8931 outline-previous-visible-heading
8932 outline-promote
8933 outline-up-heading
8934 show-children))
8935 (let ((f (or (car-safe cell) cell))
8936 (disable-when-heading-prefix (cdr-safe cell)))
8937 (when (fboundp f)
8938 (dolist (binding (nconc (where-is-internal f org-mode-map)
8939 (where-is-internal f outline-mode-map)))
8940 ;; TODO use local-function-key-map
8941 (dolist (rep '(("<tab>" . "TAB")
8942 ("<return>" . "RET")
8943 ("<escape>" . "ESC")
8944 ("<delete>" . "DEL")))
8945 (setq binding (read-kbd-macro
8946 (let ((case-fold-search))
8947 (replace-regexp-in-string
8948 (regexp-quote (cdr rep))
8949 (car rep)
8950 (key-description binding))))))
8951 (let ((key (lookup-key orgstruct-mode-map binding)))
8952 (when (or (not key) (numberp key))
8953 (condition-case nil
8954 (org-defkey orgstruct-mode-map
8955 binding
8956 (orgstruct-make-binding f binding disable-when-heading-prefix))
8957 (error nil))))))))
8958 (run-hooks 'orgstruct-setup-hook))
8960 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
8961 "Create a function for binding in the structure minor mode.
8962 FUN is the command to call inside a table. KEY is the key that
8963 should be checked in for a command to execute outside of tables.
8964 Non-nil DISABLE-WHEN-HEADING-PREFIX means to disable the command
8965 if `orgstruct-heading-prefix-regexp' is non-nil."
8966 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8967 (let ((nname name)
8968 (i 0))
8969 (while (fboundp (intern nname))
8970 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8971 (setq name (intern nname)))
8972 (eval
8973 (let ((bindings '((org-heading-regexp
8974 (concat "^"
8975 orgstruct-heading-prefix-regexp
8976 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8977 (org-outline-regexp
8978 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8979 (org-outline-regexp-bol
8980 (concat "^" org-outline-regexp))
8981 (outline-regexp org-outline-regexp)
8982 (outline-heading-end-regexp "\n")
8983 (outline-level 'org-outline-level)
8984 (outline-heading-alist))))
8985 `(defun ,name (arg)
8986 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
8987 "Outside of structure, run the binding of `"
8988 (key-description key) "'."
8989 (when disable-when-heading-prefix
8990 (concat
8991 "\nIf `orgstruct-heading-prefix-regexp' is non-nil, this command will always fall\n"
8992 "back to the default binding due to limitations of Org's implementation of\n"
8993 "`" (symbol-name fun) "'.")))
8994 (interactive "p")
8995 (let* ((disable
8996 ,(when disable-when-heading-prefix
8997 '(and orgstruct-heading-prefix-regexp
8998 (not (string= orgstruct-heading-prefix-regexp "")))))
8999 (fallback
9000 (or disable
9001 (not
9002 (let* ,bindings
9003 (org-context-p 'headline 'item
9004 ,(when (memq fun '(org-insert-heading))
9005 '(when orgstruct-is-++
9006 'item-body))))))))
9007 (if fallback
9008 (let* ((orgstruct-mode)
9009 (binding
9010 (loop with key = ,key
9011 for rep in
9012 '(nil
9013 ("<\\([^>]*\\)tab>" . "\\1TAB")
9014 ("<\\([^>]*\\)return>" . "\\1RET")
9015 ("<\\([^>]*\\)escape>" . "\\1ESC")
9016 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9018 (when rep
9019 (setq key (read-kbd-macro
9020 (let ((case-fold-search))
9021 (replace-regexp-in-string
9022 (car rep)
9023 (cdr rep)
9024 (key-description key))))))
9025 thereis (key-binding key))))
9026 (if (keymapp binding)
9027 (set-temporary-overlay-map binding)
9028 (let ((func (or binding
9029 (unless disable
9030 'orgstruct-error))))
9031 (when func
9032 (call-interactively func)))))
9033 (org-run-like-in-org-mode
9034 (lambda ()
9035 (interactive)
9036 (let* ,bindings
9037 (call-interactively ',fun)))))))))
9038 name))
9040 (defun org-contextualize-keys (alist contexts)
9041 "Return valid elements in ALIST depending on CONTEXTS.
9043 `org-agenda-custom-commands' or `org-capture-templates' are the
9044 values used for ALIST, and `org-agenda-custom-commands-contexts'
9045 or `org-capture-templates-contexts' are the associated contexts
9046 definitions."
9047 (let ((contexts
9048 ;; normalize contexts
9049 (mapcar
9050 (lambda(c) (cond ((listp (cadr c))
9051 (list (car c) (car c) (cadr c)))
9052 ((string= "" (cadr c))
9053 (list (car c) (car c) (caddr c)))
9054 (t c))) contexts))
9055 (a alist) c r s)
9056 ;; loop over all commands or templates
9057 (while (setq c (pop a))
9058 (let (vrules repl)
9059 (cond
9060 ((not (assoc (car c) contexts))
9061 (push c r))
9062 ((and (assoc (car c) contexts)
9063 (setq vrules (org-contextualize-validate-key
9064 (car c) contexts)))
9065 (mapc (lambda (vr)
9066 (when (not (equal (car vr) (cadr vr)))
9067 (setq repl vr))) vrules)
9068 (if (not repl) (push c r)
9069 (push (cadr repl) s)
9070 (push
9071 (cons (car c)
9072 (cdr (or (assoc (cadr repl) alist)
9073 (error "Undefined key `%s' as contextual replacement for `%s'"
9074 (cadr repl) (car c)))))
9075 r))))))
9076 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9077 (delq
9079 (delete-dups
9080 (mapcar (lambda (x)
9081 (let ((tpl (car x)))
9082 (when (not (delq
9084 (mapcar (lambda(y)
9085 (equal y tpl)) s))) x)))
9086 (reverse r))))))
9088 (defun org-contextualize-validate-key (key contexts)
9089 "Check CONTEXTS for agenda or capture KEY."
9090 (let (r rr res)
9091 (while (setq r (pop contexts))
9092 (mapc
9093 (lambda (rr)
9094 (when
9095 (and (equal key (car r))
9096 (if (functionp rr) (funcall rr)
9097 (or (and (eq (car rr) 'in-file)
9098 (buffer-file-name)
9099 (string-match (cdr rr) (buffer-file-name)))
9100 (and (eq (car rr) 'in-mode)
9101 (string-match (cdr rr) (symbol-name major-mode)))
9102 (and (eq (car rr) 'in-buffer)
9103 (string-match (cdr rr) (buffer-name)))
9104 (when (and (eq (car rr) 'not-in-file)
9105 (buffer-file-name))
9106 (not (string-match (cdr rr) (buffer-file-name))))
9107 (when (eq (car rr) 'not-in-mode)
9108 (not (string-match (cdr rr) (symbol-name major-mode))))
9109 (when (eq (car rr) 'not-in-buffer)
9110 (not (string-match (cdr rr) (buffer-name)))))))
9111 (push r res)))
9112 (car (last r))))
9113 (delete-dups (delq nil res))))
9115 (defun org-context-p (&rest contexts)
9116 "Check if local context is any of CONTEXTS.
9117 Possible values in the list of contexts are `table', `headline', and `item'."
9118 (let ((pos (point)))
9119 (goto-char (point-at-bol))
9120 (prog1 (or (and (memq 'table contexts)
9121 (looking-at "[ \t]*|"))
9122 (and (memq 'headline contexts)
9123 (looking-at org-outline-regexp))
9124 (and (memq 'item contexts)
9125 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9126 (and (memq 'item-body contexts)
9127 (org-in-item-p)))
9128 (goto-char pos))))
9130 (defun org-get-local-variables ()
9131 "Return a list of all local variables in an Org mode buffer."
9132 (let (varlist)
9133 (with-current-buffer (get-buffer-create "*Org tmp*")
9134 (erase-buffer)
9135 (org-mode)
9136 (setq varlist (buffer-local-variables)))
9137 (kill-buffer "*Org tmp*")
9138 (delq nil
9139 (mapcar
9140 (lambda (x)
9141 (setq x
9142 (if (symbolp x)
9143 (list x)
9144 (list (car x) (cdr x))))
9145 (if (and (not (get (car x) 'org-state))
9146 (string-match
9147 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9148 (symbol-name (car x))))
9149 x nil))
9150 varlist))))
9152 (defun org-clone-local-variables (from-buffer &optional regexp)
9153 "Clone local variables from FROM-BUFFER.
9154 Optional argument REGEXP selects variables to clone."
9155 (mapc
9156 (lambda (pair)
9157 (and (symbolp (car pair))
9158 (or (null regexp)
9159 (string-match regexp (symbol-name (car pair))))
9160 (set (make-local-variable (car pair))
9161 (cdr pair))))
9162 (buffer-local-variables from-buffer)))
9164 ;;;###autoload
9165 (defun org-run-like-in-org-mode (cmd)
9166 "Run a command, pretending that the current buffer is in Org-mode.
9167 This will temporarily bind local variables that are typically bound in
9168 Org-mode to the values they have in Org-mode, and then interactively
9169 call CMD."
9170 (org-load-modules-maybe)
9171 (unless org-local-vars
9172 (setq org-local-vars (org-get-local-variables)))
9173 (let (binds)
9174 (dolist (var org-local-vars)
9175 (when (or (not (boundp (car var)))
9176 (eq (symbol-value (car var))
9177 (default-value (car var))))
9178 (push (list (car var) `(quote ,(cadr var))) binds)))
9179 (eval `(let ,binds
9180 (call-interactively (quote ,cmd))))))
9182 ;;;; Archiving
9184 (defun org-get-category (&optional pos force-refresh)
9185 "Get the category applying to position POS."
9186 (save-match-data
9187 (if force-refresh (org-refresh-category-properties))
9188 (let ((pos (or pos (point))))
9189 (or (get-text-property pos 'org-category)
9190 (progn (org-refresh-category-properties)
9191 (get-text-property pos 'org-category))))))
9193 (defun org-refresh-category-properties ()
9194 "Refresh category text properties in the buffer."
9195 (let ((case-fold-search t)
9196 (inhibit-read-only t)
9197 (def-cat (cond
9198 ((null org-category)
9199 (if buffer-file-name
9200 (file-name-sans-extension
9201 (file-name-nondirectory buffer-file-name))
9202 "???"))
9203 ((symbolp org-category) (symbol-name org-category))
9204 (t org-category)))
9205 beg end cat pos optionp)
9206 (org-with-silent-modifications
9207 (save-excursion
9208 (save-restriction
9209 (widen)
9210 (goto-char (point-min))
9211 (put-text-property (point) (point-max) 'org-category def-cat)
9212 (while (re-search-forward
9213 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9214 (setq pos (match-end 0)
9215 optionp (equal (char-after (match-beginning 0)) ?#)
9216 cat (org-trim (match-string 2)))
9217 (if optionp
9218 (setq beg (point-at-bol) end (point-max))
9219 (org-back-to-heading t)
9220 (setq beg (point) end (org-end-of-subtree t t)))
9221 (put-text-property beg end 'org-category cat)
9222 (put-text-property beg end 'org-category-position beg)
9223 (goto-char pos)))))))
9225 (defun org-refresh-properties (dprop tprop)
9226 "Refresh buffer text properties.
9227 DPROP is the drawer property and TPROP is the corresponding text
9228 property to set."
9229 (let ((case-fold-search t)
9230 (inhibit-read-only t) p)
9231 (org-with-silent-modifications
9232 (save-excursion
9233 (save-restriction
9234 (widen)
9235 (goto-char (point-min))
9236 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9237 (setq p (org-match-string-no-properties 1))
9238 (save-excursion
9239 (org-back-to-heading t)
9240 (put-text-property
9241 (point-at-bol) (point-at-eol) tprop p))))))))
9244 ;;;; Link Stuff
9246 ;;; Link abbreviations
9248 (defun org-link-expand-abbrev (link)
9249 "Apply replacements as defined in `org-link-abbrev-alist'."
9250 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9251 (let* ((key (match-string 1 link))
9252 (as (or (assoc key org-link-abbrev-alist-local)
9253 (assoc key org-link-abbrev-alist)))
9254 (tag (and (match-end 2) (match-string 3 link)))
9255 rpl)
9256 (if (not as)
9257 link
9258 (setq rpl (cdr as))
9259 (cond
9260 ((symbolp rpl) (funcall rpl tag))
9261 ((string-match "%(\\([^)]+\\))" rpl)
9262 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
9263 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9264 ((string-match "%h" rpl)
9265 (replace-match (url-hexify-string (or tag "")) t t rpl))
9266 (t (concat rpl tag)))))
9267 link))
9269 ;;; Storing and inserting links
9271 (defvar org-insert-link-history nil
9272 "Minibuffer history for links inserted with `org-insert-link'.")
9274 (defvar org-stored-links nil
9275 "Contains the links stored with `org-store-link'.")
9277 (defvar org-store-link-plist nil
9278 "Plist with info about the most recently link created with `org-store-link'.")
9280 (defvar org-link-protocols nil
9281 "Link protocols added to Org-mode using `org-add-link-type'.")
9283 (defvar org-store-link-functions nil
9284 "List of functions that are called to create and store a link.
9285 Each function will be called in turn until one returns a non-nil
9286 value. Each function should check if it is responsible for creating
9287 this link (for example by looking at the major mode).
9288 If not, it must exit and return nil.
9289 If yes, it should return a non-nil value after a calling
9290 `org-store-link-props' with a list of properties and values.
9291 Special properties are:
9293 :type The link prefix, like \"http\". This must be given.
9294 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9295 This is obligatory as well.
9296 :description Optional default description for the second pair
9297 of brackets in an Org-mode link. The user can still change
9298 this when inserting this link into an Org-mode buffer.
9300 In addition to these, any additional properties can be specified
9301 and then used in capture templates.")
9303 (defun org-add-link-type (type &optional follow export)
9304 "Add TYPE to the list of `org-link-types'.
9305 Re-compute all regular expressions depending on `org-link-types'
9307 FOLLOW and EXPORT are two functions.
9309 FOLLOW should take the link path as the single argument and do whatever
9310 is necessary to follow the link, for example find a file or display
9311 a mail message.
9313 EXPORT should format the link path for export to one of the export formats.
9314 It should be a function accepting three arguments:
9316 path the path of the link, the text after the prefix (like \"http:\")
9317 desc the description of the link, if any, or a description added by
9318 org-export-normalize-links if there is none
9319 format the export format, a symbol like `html' or `latex' or `ascii'..
9321 The function may use the FORMAT information to return different values
9322 depending on the format. The return value will be put literally into
9323 the exported file. If the return value is nil, this means Org should
9324 do what it normally does with links which do not have EXPORT defined.
9326 Org-mode has a built-in default for exporting links. If you are happy with
9327 this default, there is no need to define an export function for the link
9328 type. For a simple example of an export function, see `org-bbdb.el'."
9329 (add-to-list 'org-link-types type t)
9330 (org-make-link-regexps)
9331 (if (assoc type org-link-protocols)
9332 (setcdr (assoc type org-link-protocols) (list follow export))
9333 (push (list type follow export) org-link-protocols)))
9335 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9336 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9338 ;;;###autoload
9339 (defun org-store-link (arg)
9340 "\\<org-mode-map>Store an org-link to the current location.
9341 This link is added to `org-stored-links' and can later be inserted
9342 into an org-buffer with \\[org-insert-link].
9344 For some link types, a prefix arg is interpreted.
9345 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9346 For file links, arg negates `org-context-in-file-links'.
9348 A double prefix arg force skipping storing functions that are not
9349 part of Org's core.
9351 A triple prefix arg force storing a link for each line in the
9352 active region."
9353 (interactive "P")
9354 (org-load-modules-maybe)
9355 (if (and (equal arg '(64)) (org-region-active-p))
9356 (save-excursion
9357 (let ((end (region-end)))
9358 (goto-char (region-beginning))
9359 (set-mark (point))
9360 (while (< (point-at-eol) end)
9361 (move-end-of-line 1) (activate-mark)
9362 (let (current-prefix-arg)
9363 (call-interactively 'org-store-link))
9364 (move-beginning-of-line 2)
9365 (set-mark (point)))))
9366 (org-with-limited-levels
9367 (setq org-store-link-plist nil)
9368 (let (link cpltxt desc description search
9369 txt custom-id agenda-link sfuns sfunsn)
9370 (cond
9372 ;; Store a link using an external link type
9373 ((and (not (equal arg '(16)))
9374 (setq sfuns
9375 (delq
9376 nil (mapcar (lambda (f)
9377 (let (fs) (if (funcall f) (push f fs))))
9378 org-store-link-functions))
9379 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9380 (or (and (cdr sfuns)
9381 (funcall (intern
9382 (completing-read
9383 "Which function for creating the link? "
9384 sfunsn t (car sfunsn)))))
9385 (funcall (caar sfuns)))
9386 (setq link (plist-get org-store-link-plist :link)
9387 desc (or (plist-get org-store-link-plist
9388 :description) link))))
9390 ;; Store a link from a source code buffer
9391 ((org-src-edit-buffer-p)
9392 (let (label gc)
9393 (while (or (not label)
9394 (save-excursion
9395 (save-restriction
9396 (widen)
9397 (goto-char (point-min))
9398 (re-search-forward
9399 (regexp-quote (format org-coderef-label-format label))
9400 nil t))))
9401 (when label (message "Label exists already") (sit-for 2))
9402 (setq label (read-string "Code line label: " label)))
9403 (end-of-line 1)
9404 (setq link (format org-coderef-label-format label))
9405 (setq gc (- 79 (length link)))
9406 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9407 (insert link)
9408 (setq link (concat "(" label ")") desc nil)))
9410 ;; We are in the agenda, link to referenced location
9411 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9412 (let ((m (or (get-text-property (point) 'org-hd-marker)
9413 (get-text-property (point) 'org-marker))))
9414 (when m
9415 (org-with-point-at m
9416 (setq agenda-link
9417 (if (org-called-interactively-p 'any)
9418 (call-interactively 'org-store-link)
9419 (org-store-link nil)))))))
9421 ((eq major-mode 'calendar-mode)
9422 (let ((cd (calendar-cursor-to-date)))
9423 (setq link
9424 (format-time-string
9425 (car org-time-stamp-formats)
9426 (apply 'encode-time
9427 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9428 nil nil nil))))
9429 (org-store-link-props :type "calendar" :date cd)))
9431 ((eq major-mode 'help-mode)
9432 (setq link (concat "help:" (save-excursion
9433 (goto-char (point-min))
9434 (looking-at "^[^ ]+")
9435 (match-string 0))))
9436 (org-store-link-props :type "help"))
9438 ((eq major-mode 'w3-mode)
9439 (setq cpltxt (if (and (buffer-name)
9440 (not (string-match "Untitled" (buffer-name))))
9441 (buffer-name)
9442 (url-view-url t))
9443 link (url-view-url t))
9444 (org-store-link-props :type "w3" :url (url-view-url t)))
9446 ((eq major-mode 'image-mode)
9447 (setq cpltxt (concat "file:"
9448 (abbreviate-file-name buffer-file-name))
9449 link cpltxt)
9450 (org-store-link-props :type "image" :file buffer-file-name))
9452 ;; In dired, store a link to the file of the current line
9453 ((eq major-mode 'dired-mode)
9454 (let ((file (dired-get-filename nil t)))
9455 (setq file (if file
9456 (abbreviate-file-name
9457 (expand-file-name (dired-get-filename nil t)))
9458 ;; otherwise, no file so use current directory.
9459 default-directory))
9460 (setq cpltxt (concat "file:" file)
9461 link cpltxt)))
9463 ((setq search (run-hook-with-args-until-success
9464 'org-create-file-search-functions))
9465 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9466 "::" search))
9467 (setq cpltxt (or description link)))
9469 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9470 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9471 (cond
9472 ;; Store a link using the radio target at point
9473 ((org-in-regexp "<<\\(.*?\\)>>")
9474 (setq cpltxt
9475 (concat "file:"
9476 (abbreviate-file-name
9477 (buffer-file-name (buffer-base-buffer)))
9478 "::" (match-string 1))
9479 link cpltxt))
9480 ((and (featurep 'org-id)
9481 (or (eq org-id-link-to-org-use-id t)
9482 (and (org-called-interactively-p 'any)
9483 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9484 (and (eq org-id-link-to-org-use-id
9485 'create-if-interactive-and-no-custom-id)
9486 (not custom-id))))
9487 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9488 ;; Store a link using the ID at point
9489 (setq link (condition-case nil
9490 (prog1 (org-id-store-link)
9491 (setq desc (plist-get org-store-link-plist
9492 :description)))
9493 (error
9494 ;; Probably before first headline, link only to file
9495 (concat "file:"
9496 (abbreviate-file-name
9497 (buffer-file-name (buffer-base-buffer))))))))
9499 ;; Just link to current headline
9500 (setq cpltxt (concat "file:"
9501 (abbreviate-file-name
9502 (buffer-file-name (buffer-base-buffer)))))
9503 ;; Add a context search string
9504 (when (org-xor org-context-in-file-links arg)
9505 (let* ((ee (org-element-at-point))
9506 (et (org-element-type ee))
9507 (ev (plist-get (cadr ee) :value))
9508 (ek (plist-get (cadr ee) :key))
9509 (eok (and (stringp ek) (string-match "name" ek))))
9510 (setq txt (cond
9511 ((org-at-heading-p) nil)
9512 ((and (eq et 'keyword) eok) ev)
9513 ((org-region-active-p)
9514 (buffer-substring (region-beginning) (region-end)))))
9515 (when (or (null txt) (string-match "\\S-" txt))
9516 (setq cpltxt
9517 (concat cpltxt "::"
9518 (condition-case nil
9519 (org-make-org-heading-search-string txt)
9520 (error "")))
9521 desc (or (and (eq et 'keyword) eok ev)
9522 (nth 4 (ignore-errors (org-heading-components)))
9523 "NONE")))))
9524 (if (string-match "::\\'" cpltxt)
9525 (setq cpltxt (substring cpltxt 0 -2)))
9526 (setq link cpltxt))))
9528 ((buffer-file-name (buffer-base-buffer))
9529 ;; Just link to this file here.
9530 (setq cpltxt (concat "file:"
9531 (abbreviate-file-name
9532 (buffer-file-name (buffer-base-buffer)))))
9533 ;; Add a context string.
9534 (when (org-xor org-context-in-file-links arg)
9535 (setq txt (if (org-region-active-p)
9536 (buffer-substring (region-beginning) (region-end))
9537 (buffer-substring (point-at-bol) (point-at-eol))))
9538 ;; Only use search option if there is some text.
9539 (when (string-match "\\S-" txt)
9540 (setq cpltxt
9541 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9542 desc "NONE")))
9543 (setq link cpltxt))
9545 ((org-called-interactively-p 'interactive)
9546 (user-error "No method for storing a link from this buffer"))
9548 (t (setq link nil)))
9550 ;; We're done setting link and desc, clean up
9551 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9552 (setq link (or link cpltxt)
9553 desc (or desc cpltxt))
9554 (cond ((equal desc "NONE") (setq desc nil))
9555 ((string-match org-bracket-link-regexp desc)
9556 (setq desc
9557 (replace-regexp-in-string
9558 org-bracket-link-regexp
9559 (concat "\\3" (if (equal (length (match-string 0 desc))
9560 (length desc)) "*" "")) desc))))
9562 ;; Return the link
9563 (if (not (and (or (org-called-interactively-p 'any)
9564 executing-kbd-macro) link))
9565 (or agenda-link (and link (org-make-link-string link desc)))
9566 (push (list link desc) org-stored-links)
9567 (message "Stored: %s" (or desc link))
9568 (when custom-id
9569 (setq link (concat "file:" (abbreviate-file-name
9570 (buffer-file-name)) "::#" custom-id))
9571 (push (list link desc) org-stored-links)))))))
9573 (defun org-store-link-props (&rest plist)
9574 "Store link properties, extract names and addresses."
9575 (let (x adr)
9576 (when (setq x (plist-get plist :from))
9577 (setq adr (mail-extract-address-components x))
9578 (setq plist (plist-put plist :fromname (car adr)))
9579 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9580 (when (setq x (plist-get plist :to))
9581 (setq adr (mail-extract-address-components x))
9582 (setq plist (plist-put plist :toname (car adr)))
9583 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9584 (let ((from (plist-get plist :from))
9585 (to (plist-get plist :to)))
9586 (when (and from to org-from-is-user-regexp)
9587 (setq plist
9588 (plist-put plist :fromto
9589 (if (string-match org-from-is-user-regexp from)
9590 (concat "to %t")
9591 (concat "from %f"))))))
9592 (setq org-store-link-plist plist))
9594 (defun org-add-link-props (&rest plist)
9595 "Add these properties to the link property list."
9596 (let (key value)
9597 (while plist
9598 (setq key (pop plist) value (pop plist))
9599 (setq org-store-link-plist
9600 (plist-put org-store-link-plist key value)))))
9602 (defun org-email-link-description (&optional fmt)
9603 "Return the description part of an email link.
9604 This takes information from `org-store-link-plist' and formats it
9605 according to FMT (default from `org-email-link-description-format')."
9606 (setq fmt (or fmt org-email-link-description-format))
9607 (let* ((p org-store-link-plist)
9608 (to (plist-get p :toaddress))
9609 (from (plist-get p :fromaddress))
9610 (table
9611 (list
9612 (cons "%c" (plist-get p :fromto))
9613 (cons "%F" (plist-get p :from))
9614 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9615 (cons "%T" (plist-get p :to))
9616 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9617 (cons "%s" (plist-get p :subject))
9618 (cons "%d" (plist-get p :date))
9619 (cons "%m" (plist-get p :message-id)))))
9620 (when (string-match "%c" fmt)
9621 ;; Check if the user wrote this message
9622 (if (and org-from-is-user-regexp from to
9623 (save-match-data (string-match org-from-is-user-regexp from)))
9624 (setq fmt (replace-match "to %t" t t fmt))
9625 (setq fmt (replace-match "from %f" t t fmt))))
9626 (org-replace-escapes fmt table)))
9628 (defun org-make-org-heading-search-string (&optional string)
9629 "Make search string for the current headline or STRING."
9630 (let ((s (or string
9631 (and (derived-mode-p 'org-mode)
9632 (save-excursion
9633 (org-back-to-heading t)
9634 (org-element-property :raw-value (org-element-at-point))))))
9635 (lines org-context-in-file-links))
9636 (or string (setq s (concat "*" s))) ; Add * for headlines
9637 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9638 (when (and string (integerp lines) (> lines 0))
9639 (let ((slines (org-split-string s "\n")))
9640 (when (< lines (length slines))
9641 (setq s (mapconcat
9642 'identity
9643 (reverse (nthcdr (- (length slines) lines)
9644 (reverse slines))) "\n")))))
9645 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9647 (defun org-make-link-string (link &optional description)
9648 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9649 (unless (string-match "\\S-" link)
9650 (error "Empty link"))
9651 (when (and description
9652 (stringp description)
9653 (not (string-match "\\S-" description)))
9654 (setq description nil))
9655 (when (stringp description)
9656 ;; Remove brackets from the description, they are fatal.
9657 (while (string-match "\\[" description)
9658 (setq description (replace-match "{" t t description)))
9659 (while (string-match "\\]" description)
9660 (setq description (replace-match "}" t t description))))
9661 (when (equal link description)
9662 ;; No description needed, it is identical
9663 (setq description nil))
9664 (when (and (not description)
9665 (not (string-match (org-image-file-name-regexp) link))
9666 (not (equal link (org-link-escape link))))
9667 (setq description (org-extract-attributes link)))
9668 (setq link
9669 (cond ((string-match (org-image-file-name-regexp) link) link)
9670 ((string-match org-link-types-re link)
9671 (concat (match-string 1 link)
9672 (org-link-escape (substring link (match-end 1)))))
9673 (t (org-link-escape link))))
9674 (concat "[[" link "]"
9675 (if description (concat "[" description "]") "")
9676 "]"))
9678 (defconst org-link-escape-chars
9679 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9680 "List of characters that should be escaped in link.
9681 This is the list that is used for internal purposes.")
9683 (defconst org-link-escape-chars-browser
9684 '(?\ )
9685 "List of escapes for characters that are problematic in links.
9686 This is the list that is used before handing over to the browser.")
9688 (defun org-link-escape (text &optional table merge)
9689 "Return percent escaped representation of TEXT.
9690 TEXT is a string with the text to escape.
9691 Optional argument TABLE is a list with characters that should be
9692 escaped. When nil, `org-link-escape-chars' is used.
9693 If optional argument MERGE is set, merge TABLE into
9694 `org-link-escape-chars'."
9695 (cond
9696 ((and table merge)
9697 (mapc (lambda (defchr)
9698 (unless (member defchr table)
9699 (setq table (cons defchr table)))) org-link-escape-chars))
9700 ((null table)
9701 (setq table org-link-escape-chars)))
9702 (mapconcat
9703 (lambda (char)
9704 (if (or (member char table)
9705 (and (or (< char 32) (= char 37) (> char 126))
9706 org-url-hexify-p))
9707 (mapconcat (lambda (sequence-element)
9708 (format "%%%.2X" sequence-element))
9709 (or (encode-coding-char char 'utf-8)
9710 (error "Unable to percent escape character: %s"
9711 (char-to-string char))) "")
9712 (char-to-string char))) text ""))
9714 (defun org-link-unescape (str)
9715 "Unhex hexified Unicode strings as returned from the JavaScript function
9716 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9717 (unless (and (null str) (string= "" str))
9718 (let ((pos 0) (case-fold-search t) unhexed)
9719 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9720 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9721 (setq str (replace-match unhexed t t str))
9722 (setq pos (+ pos (length unhexed))))))
9723 str)
9725 (defun org-link-unescape-compound (hex)
9726 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9727 Note: this function also decodes single byte encodings like
9728 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9729 (save-match-data
9730 (let* ((bytes (cdr (split-string hex "%")))
9731 (ret "")
9732 (eat 0)
9733 (sum 0))
9734 (while bytes
9735 (let* ((val (string-to-number (pop bytes) 16))
9736 (shift-xor
9737 (if (= 0 eat)
9738 (cond
9739 ((>= val 252) (cons 6 252))
9740 ((>= val 248) (cons 5 248))
9741 ((>= val 240) (cons 4 240))
9742 ((>= val 224) (cons 3 224))
9743 ((>= val 192) (cons 2 192))
9744 (t (cons 0 0)))
9745 (cons 6 128))))
9746 (if (>= val 192) (setq eat (car shift-xor)))
9747 (setq val (logxor val (cdr shift-xor)))
9748 (setq sum (+ (lsh sum (car shift-xor)) val))
9749 (if (> eat 0) (setq eat (- eat 1)))
9750 (cond
9751 ((= 0 eat) ;multi byte
9752 (setq ret (concat ret (org-char-to-string sum)))
9753 (setq sum 0))
9754 ((not bytes) ; single byte(s)
9755 (setq ret (org-link-unescape-single-byte-sequence hex))))
9756 )) ;; end (while bytes
9757 ret )))
9759 (defun org-link-unescape-single-byte-sequence (hex)
9760 "Unhexify hex-encoded single byte character sequences."
9761 (mapconcat (lambda (byte)
9762 (char-to-string (string-to-number byte 16)))
9763 (cdr (split-string hex "%")) ""))
9765 (defun org-xor (a b)
9766 "Exclusive or."
9767 (if a (not b) b))
9769 (defun org-fixup-message-id-for-http (s)
9770 "Replace special characters in a message id, so it can be used in an http query."
9771 (when (string-match "%" s)
9772 (setq s (mapconcat (lambda (c)
9773 (if (eq c ?%)
9774 "%25"
9775 (char-to-string c)))
9776 s "")))
9777 (while (string-match "<" s)
9778 (setq s (replace-match "%3C" t t s)))
9779 (while (string-match ">" s)
9780 (setq s (replace-match "%3E" t t s)))
9781 (while (string-match "@" s)
9782 (setq s (replace-match "%40" t t s)))
9785 (defun org-link-prettify (link)
9786 "Return a human-readable representation of LINK.
9787 The car of LINK must be a raw link the cdr of LINK must be either
9788 a link description or nil."
9789 (let ((desc (or (cadr link) "<no description>")))
9790 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9791 "<" (car link) ">")))
9793 ;;;###autoload
9794 (defun org-insert-link-global ()
9795 "Insert a link like Org-mode does.
9796 This command can be called in any mode to insert a link in Org-mode syntax."
9797 (interactive)
9798 (org-load-modules-maybe)
9799 (org-run-like-in-org-mode 'org-insert-link))
9801 (defun org-insert-all-links (&optional keep)
9802 "Insert all links in `org-stored-links'."
9803 (interactive "P")
9804 (let ((links (copy-sequence org-stored-links)) l)
9805 (while (setq l (if keep (pop links) (pop org-stored-links)))
9806 (insert "- ")
9807 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9808 (insert "\n"))))
9810 (defun org-link-fontify-links-to-this-file ()
9811 "Fontify links to the current file in `org-stored-links'."
9812 (let ((f (buffer-file-name)) a b)
9813 (setq a (mapcar (lambda(l)
9814 (let ((ll (car l)))
9815 (when (and (string-match "^file:\\(.+\\)::" ll)
9816 (equal f (expand-file-name (match-string 1 ll))))
9817 ll)))
9818 org-stored-links))
9819 (when (featurep 'org-id)
9820 (setq b (mapcar (lambda(l)
9821 (let ((ll (car l)))
9822 (when (and (string-match "^id:\\(.+\\)$" ll)
9823 (equal f (expand-file-name
9824 (or (org-id-find-id-file
9825 (match-string 1 ll)) ""))))
9826 ll)))
9827 org-stored-links)))
9828 (mapcar (lambda(l)
9829 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9830 (delq nil (append a b)))))
9832 (defvar org-link-links-in-this-file nil)
9833 (defun org-insert-link (&optional complete-file link-location default-description)
9834 "Insert a link. At the prompt, enter the link.
9836 Completion can be used to insert any of the link protocol prefixes like
9837 http or ftp in use.
9839 The history can be used to select a link previously stored with
9840 `org-store-link'. When the empty string is entered (i.e. if you just
9841 press RET at the prompt), the link defaults to the most recently
9842 stored link. As SPC triggers completion in the minibuffer, you need to
9843 use M-SPC or C-q SPC to force the insertion of a space character.
9845 You will also be prompted for a description, and if one is given, it will
9846 be displayed in the buffer instead of the link.
9848 If there is already a link at point, this command will allow you to edit link
9849 and description parts.
9851 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9852 be selected using completion. The path to the file will be relative to the
9853 current directory if the file is in the current directory or a subdirectory.
9854 Otherwise, the link will be the absolute path as completed in the minibuffer
9855 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9856 option `org-link-file-path-type'.
9858 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9859 the current directory or below.
9861 With three \\[universal-argument] prefixes, negate the meaning of
9862 `org-keep-stored-link-after-insertion'.
9864 If `org-make-link-description-function' is non-nil, this function will be
9865 called with the link target, and the result will be the default
9866 link description.
9868 If the LINK-LOCATION parameter is non-nil, this value will be
9869 used as the link location instead of reading one interactively.
9871 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9872 be used as the default description."
9873 (interactive "P")
9874 (let* ((wcf (current-window-configuration))
9875 (origbuf (current-buffer))
9876 (region (if (org-region-active-p)
9877 (buffer-substring (region-beginning) (region-end))))
9878 (remove (and region (list (region-beginning) (region-end))))
9879 (desc region)
9880 tmphist ; byte-compile incorrectly complains about this
9881 (link link-location)
9882 (abbrevs org-link-abbrev-alist-local)
9883 entry file all-prefixes auto-desc)
9884 (cond
9885 (link-location) ; specified by arg, just use it.
9886 ((org-in-regexp org-bracket-link-regexp 1)
9887 ;; We do have a link at point, and we are going to edit it.
9888 (setq remove (list (match-beginning 0) (match-end 0)))
9889 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9890 (setq link (read-string "Link: "
9891 (org-link-unescape
9892 (org-match-string-no-properties 1)))))
9893 ((or (org-in-regexp org-angle-link-re)
9894 (org-in-regexp org-plain-link-re))
9895 ;; Convert to bracket link
9896 (setq remove (list (match-beginning 0) (match-end 0))
9897 link (read-string "Link: "
9898 (org-remove-angle-brackets (match-string 0)))))
9899 ((member complete-file '((4) (16)))
9900 ;; Completing read for file names.
9901 (setq link (org-file-complete-link complete-file)))
9903 ;; Read link, with completion for stored links.
9904 (org-link-fontify-links-to-this-file)
9905 (org-switch-to-buffer-other-window "*Org Links*")
9906 (with-current-buffer "*Org Links*"
9907 (erase-buffer)
9908 (insert "Insert a link.
9909 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9910 (when org-stored-links
9911 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9912 (insert (mapconcat 'org-link-prettify
9913 (reverse org-stored-links) "\n")))
9914 (goto-char (point-min)))
9915 (let ((cw (selected-window)))
9916 (select-window (get-buffer-window "*Org Links*" 'visible))
9917 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9918 (unless (pos-visible-in-window-p (point-max))
9919 (org-fit-window-to-buffer))
9920 (and (window-live-p cw) (select-window cw)))
9921 ;; Fake a link history, containing the stored links.
9922 (setq tmphist (append (mapcar 'car org-stored-links)
9923 org-insert-link-history))
9924 (setq all-prefixes (append (mapcar 'car abbrevs)
9925 (mapcar 'car org-link-abbrev-alist)
9926 org-link-types))
9927 (unwind-protect
9928 (progn
9929 (setq link
9930 (org-completing-read
9931 "Link: "
9932 (append
9933 (mapcar (lambda (x) (concat x ":"))
9934 all-prefixes)
9935 (mapcar 'car org-stored-links))
9936 nil nil nil
9937 'tmphist
9938 (caar org-stored-links)))
9939 (if (not (string-match "\\S-" link))
9940 (error "No link selected"))
9941 (mapc (lambda(l)
9942 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9943 org-stored-links)
9944 (if (or (member link all-prefixes)
9945 (and (equal ":" (substring link -1))
9946 (member (substring link 0 -1) all-prefixes)
9947 (setq link (substring link 0 -1))))
9948 (setq link (with-current-buffer origbuf
9949 (org-link-try-special-completion link)))))
9950 (set-window-configuration wcf)
9951 (kill-buffer "*Org Links*"))
9952 (setq entry (assoc link org-stored-links))
9953 (or entry (push link org-insert-link-history))
9954 (setq desc (or desc (nth 1 entry)))))
9956 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9957 (not org-keep-stored-link-after-insertion))
9958 (setq org-stored-links (delq (assoc link org-stored-links)
9959 org-stored-links)))
9961 (if (string-match org-plain-link-re link)
9962 ;; URL-like link, normalize the use of angular brackets.
9963 (setq link (org-remove-angle-brackets link)))
9965 ;; Check if we are linking to the current file with a search
9966 ;; option If yes, simplify the link by using only the search
9967 ;; option.
9968 (when (and buffer-file-name
9969 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9970 (let* ((path (match-string 1 link))
9971 (case-fold-search nil)
9972 (search (match-string 2 link)))
9973 (save-match-data
9974 (if (equal (file-truename buffer-file-name) (file-truename path))
9975 ;; We are linking to this same file, with a search option
9976 (setq link search)))))
9978 ;; Check if we can/should use a relative path. If yes, simplify the link
9979 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9980 (let* ((type (match-string 1 link))
9981 (path (match-string 2 link))
9982 (origpath path)
9983 (case-fold-search nil))
9984 (cond
9985 ((or (eq org-link-file-path-type 'absolute)
9986 (equal complete-file '(16)))
9987 (setq path (abbreviate-file-name (expand-file-name path))))
9988 ((eq org-link-file-path-type 'noabbrev)
9989 (setq path (expand-file-name path)))
9990 ((eq org-link-file-path-type 'relative)
9991 (setq path (file-relative-name path)))
9993 (save-match-data
9994 (if (string-match (concat "^" (regexp-quote
9995 (expand-file-name
9996 (file-name-as-directory
9997 default-directory))))
9998 (expand-file-name path))
9999 ;; We are linking a file with relative path name.
10000 (setq path (substring (expand-file-name path)
10001 (match-end 0)))
10002 (setq path (abbreviate-file-name (expand-file-name path)))))))
10003 (setq link (concat type path))
10004 (if (equal desc origpath)
10005 (setq desc path))))
10007 (if org-make-link-description-function
10008 (setq desc
10009 (or (condition-case nil
10010 (funcall org-make-link-description-function link desc)
10011 (error (progn (message "Can't get link description from `%s'"
10012 (symbol-name org-make-link-description-function))
10013 (sit-for 2) nil)))
10014 (read-string "Description: " default-description)))
10015 (if default-description (setq desc default-description)
10016 (setq desc (or (and auto-desc desc)
10017 (read-string "Description: " desc)))))
10019 (unless (string-match "\\S-" desc) (setq desc nil))
10020 (if remove (apply 'delete-region remove))
10021 (insert (org-make-link-string link desc))))
10023 (defun org-link-try-special-completion (type)
10024 "If there is completion support for link type TYPE, offer it."
10025 (let ((fun (intern (concat "org-" type "-complete-link"))))
10026 (if (functionp fun)
10027 (funcall fun)
10028 (read-string "Link (no completion support): " (concat type ":")))))
10030 (defun org-file-complete-link (&optional arg)
10031 "Create a file link using completion."
10032 (let (file link)
10033 (setq file (org-iread-file-name "File: "))
10034 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10035 (pwd1 (file-name-as-directory (abbreviate-file-name
10036 (expand-file-name ".")))))
10037 (cond
10038 ((equal arg '(16))
10039 (setq link (concat
10040 "file:"
10041 (abbreviate-file-name (expand-file-name file)))))
10042 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10043 (setq link (concat "file:" (match-string 1 file))))
10044 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10045 (expand-file-name file))
10046 (setq link (concat
10047 "file:" (match-string 1 (expand-file-name file)))))
10048 (t (setq link (concat "file:" file)))))
10049 link))
10051 (defun org-iread-file-name (&rest args)
10052 "Read-file-name using `ido-mode' speedup if available.
10053 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10054 See `read-file-name' for a description of parameters."
10055 (org-without-partial-completion
10056 (if (and org-completion-use-ido
10057 (fboundp 'ido-read-file-name)
10058 (boundp 'ido-mode) ido-mode
10059 (listp (second args)))
10060 (let ((ido-enter-matching-directory nil))
10061 (apply 'ido-read-file-name args))
10062 (apply 'read-file-name args))))
10064 (defun org-completing-read (&rest args)
10065 "Completing-read with SPACE being a normal character."
10066 (let ((enable-recursive-minibuffers t)
10067 (minibuffer-local-completion-map
10068 (copy-keymap minibuffer-local-completion-map)))
10069 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10070 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10071 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10072 (apply 'org-icompleting-read args)))
10074 (defun org-completing-read-no-i (&rest args)
10075 (let (org-completion-use-ido org-completion-use-iswitchb)
10076 (apply 'org-completing-read args)))
10078 (defun org-iswitchb-completing-read (prompt choices &rest args)
10079 "Use iswitch as a completing-read replacement to choose from choices.
10080 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10081 from."
10082 (let* ((iswitchb-use-virtual-buffers nil)
10083 (iswitchb-make-buflist-hook
10084 (lambda ()
10085 (setq iswitchb-temp-buflist choices))))
10086 (iswitchb-read-buffer prompt)))
10088 (defun org-icompleting-read (&rest args)
10089 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10090 (org-without-partial-completion
10091 (if (and org-completion-use-ido
10092 (fboundp 'ido-completing-read)
10093 (boundp 'ido-mode) ido-mode
10094 (listp (second args)))
10095 (let ((ido-enter-matching-directory nil))
10096 (apply 'ido-completing-read (concat (car args))
10097 (if (consp (car (nth 1 args)))
10098 (mapcar 'car (nth 1 args))
10099 (nth 1 args))
10100 (cddr args)))
10101 (if (and org-completion-use-iswitchb
10102 (boundp 'iswitchb-mode) iswitchb-mode
10103 (listp (second args)))
10104 (apply 'org-iswitchb-completing-read (concat (car args))
10105 (if (consp (car (nth 1 args)))
10106 (mapcar 'car (nth 1 args))
10107 (nth 1 args))
10108 (cddr args))
10109 (apply 'completing-read args)))))
10111 (defun org-extract-attributes (s)
10112 "Extract the attributes cookie from a string and set as text property."
10113 (let (a attr (start 0) key value)
10114 (save-match-data
10115 (when (string-match "{{\\([^}]+\\)}}$" s)
10116 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10117 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10118 (setq key (match-string 1 a) value (match-string 2 a)
10119 start (match-end 0)
10120 attr (plist-put attr (intern key) value))))
10121 (org-add-props s nil 'org-attr attr))
10124 (defun org-extract-attributes-from-string (tag)
10125 (let (key value attr)
10126 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
10127 (setq key (match-string 1 tag) value (match-string 2 tag)
10128 tag (replace-match "" t t tag)
10129 attr (plist-put attr (intern key) value)))
10130 (cons tag attr)))
10132 (defun org-attributes-to-string (plist)
10133 "Format a property list into an HTML attribute list."
10134 (let ((s "") key value)
10135 (while plist
10136 (setq key (pop plist) value (pop plist))
10137 (and value
10138 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
10141 ;;; Opening/following a link
10143 (defvar org-link-search-failed nil)
10145 (defvar org-open-link-functions nil
10146 "Hook for functions finding a plain text link.
10147 These functions must take a single argument, the link content.
10148 They will be called for links that look like [[link text][description]]
10149 when LINK TEXT does not have a protocol like \"http:\" and does not look
10150 like a filename (e.g. \"./blue.png\").
10152 These functions will be called *before* Org attempts to resolve the
10153 link by doing text searches in the current buffer - so if you want a
10154 link \"[[target]]\" to still find \"<<target>>\", your function should
10155 handle this as a special case.
10157 When the function does handle the link, it must return a non-nil value.
10158 If it decides that it is not responsible for this link, it must return
10159 nil to indicate that that Org-mode can continue with other options
10160 like exact and fuzzy text search.")
10162 (defun org-next-link (&optional search-backward)
10163 "Move forward to the next link.
10164 If the link is in hidden text, expose it."
10165 (interactive "P")
10166 (when (and org-link-search-failed (eq this-command last-command))
10167 (goto-char (point-min))
10168 (message "Link search wrapped back to beginning of buffer"))
10169 (setq org-link-search-failed nil)
10170 (let* ((pos (point))
10171 (ct (org-context))
10172 (a (assoc :link ct))
10173 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10174 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10175 ((looking-at org-any-link-re)
10176 ;; Don't stay stuck at link without an org-link face
10177 (forward-char (if search-backward -1 1))))
10178 (if (funcall srch-fun org-any-link-re nil t)
10179 (progn
10180 (goto-char (match-beginning 0))
10181 (if (outline-invisible-p) (org-show-context)))
10182 (goto-char pos)
10183 (setq org-link-search-failed t)
10184 (message "No further link found"))))
10186 (defun org-previous-link ()
10187 "Move backward to the previous link.
10188 If the link is in hidden text, expose it."
10189 (interactive)
10190 (funcall 'org-next-link t))
10192 (defun org-translate-link (s)
10193 "Translate a link string if a translation function has been defined."
10194 (if (and org-link-translation-function
10195 (fboundp org-link-translation-function)
10196 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10197 (progn
10198 (setq s (funcall org-link-translation-function
10199 (match-string 1 s) (match-string 2 s)))
10200 (concat (car s) ":" (cdr s)))
10203 (defun org-translate-link-from-planner (type path)
10204 "Translate a link from Emacs Planner syntax so that Org can follow it.
10205 This is still an experimental function, your mileage may vary."
10206 (cond
10207 ((member type '("http" "https" "news" "ftp"))
10208 ;; standard Internet links are the same.
10209 nil)
10210 ((and (equal type "irc") (string-match "^//" path))
10211 ;; Planner has two / at the beginning of an irc link, we have 1.
10212 ;; We should have zero, actually....
10213 (setq path (substring path 1)))
10214 ((and (equal type "lisp") (string-match "^/" path))
10215 ;; Planner has a slash, we do not.
10216 (setq type "elisp" path (substring path 1)))
10217 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10218 ;; A typical message link. Planner has the id after the final slash,
10219 ;; we separate it with a hash mark
10220 (setq path (concat (match-string 1 path) "#"
10221 (org-remove-angle-brackets (match-string 2 path)))))
10223 (cons type path))
10225 (defun org-find-file-at-mouse (ev)
10226 "Open file link or URL at mouse."
10227 (interactive "e")
10228 (mouse-set-point ev)
10229 (org-open-at-point 'in-emacs))
10231 (defun org-open-at-mouse (ev)
10232 "Open file link or URL at mouse.
10233 See the docstring of `org-open-file' for details."
10234 (interactive "e")
10235 (mouse-set-point ev)
10236 (if (eq major-mode 'org-agenda-mode)
10237 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10238 (org-open-at-point))
10240 (defvar org-window-config-before-follow-link nil
10241 "The window configuration before following a link.
10242 This is saved in case the need arises to restore it.")
10244 (defvar org-open-link-marker (make-marker)
10245 "Marker pointing to the location where `org-open-at-point; was called.")
10247 ;;;###autoload
10248 (defun org-open-at-point-global ()
10249 "Follow a link like Org-mode does.
10250 This command can be called in any mode to follow a link that has
10251 Org-mode syntax."
10252 (interactive)
10253 (org-run-like-in-org-mode 'org-open-at-point))
10255 ;;;###autoload
10256 (defun org-open-link-from-string (s &optional arg reference-buffer)
10257 "Open a link in the string S, as if it was in Org-mode."
10258 (interactive "sLink: \nP")
10259 (let ((reference-buffer (or reference-buffer (current-buffer))))
10260 (with-temp-buffer
10261 (let ((org-inhibit-startup (not reference-buffer)))
10262 (org-mode)
10263 (insert s)
10264 (goto-char (point-min))
10265 (when reference-buffer
10266 (setq org-link-abbrev-alist-local
10267 (with-current-buffer reference-buffer
10268 org-link-abbrev-alist-local)))
10269 (org-open-at-point arg reference-buffer)))))
10271 (defvar org-open-at-point-functions nil
10272 "Hook that is run when following a link at point.
10274 Functions in this hook must return t if they identify and follow
10275 a link at point. If they don't find anything interesting at point,
10276 they must return nil.")
10278 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10279 (defun org-open-at-point (&optional arg reference-buffer)
10280 "Open link at or after point.
10281 If there is no link at point, this function will search forward up to
10282 the end of the current line.
10283 Normally, files will be opened by an appropriate application. If the
10284 optional prefix argument ARG is non-nil, Emacs will visit the file.
10285 With a double prefix argument, try to open outside of Emacs, in the
10286 application the system uses for this file type."
10287 (interactive "P")
10288 ;; if in a code block, then open the block's results
10289 (unless (call-interactively #'org-babel-open-src-block-result)
10290 (org-load-modules-maybe)
10291 (move-marker org-open-link-marker (point))
10292 (setq org-window-config-before-follow-link (current-window-configuration))
10293 (org-remove-occur-highlights nil nil t)
10294 (cond
10295 ((and (org-at-heading-p)
10296 (not (org-at-timestamp-p t))
10297 (not (org-in-regexp
10298 (concat org-plain-link-re "\\|"
10299 org-bracket-link-regexp "\\|"
10300 org-angle-link-re "\\|"
10301 "[ \t]:[^ \t\n]+:[ \t]*$")))
10302 (not (get-text-property (point) 'org-linked-text)))
10303 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10304 (lk0 (car lkall))
10305 (lk (if (stringp lk0) (list lk0) lk0))
10306 (lkend (cdr lkall)))
10307 (mapcar (lambda(l)
10308 (search-forward l nil lkend)
10309 (goto-char (match-beginning 0))
10310 (org-open-at-point))
10311 lk))
10312 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10313 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10314 ((and (org-at-timestamp-p t)
10315 (not (org-in-regexp org-bracket-link-regexp)))
10316 (org-follow-timestamp-link))
10317 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10318 (not (org-in-regexp org-any-link-re)))
10319 (org-footnote-action))
10321 (let (type path link line search (pos (point)))
10322 (catch 'match
10323 (save-excursion
10324 (skip-chars-forward "^]\n\r")
10325 (when (org-in-regexp org-bracket-link-regexp 1)
10326 (setq link (org-extract-attributes
10327 (org-link-unescape (org-match-string-no-properties 1))))
10328 (while (string-match " *\n *" link)
10329 (setq link (replace-match " " t t link)))
10330 (setq link (org-link-expand-abbrev link))
10331 (cond
10332 ((or (file-name-absolute-p link)
10333 (string-match "^\\.\\.?/" link))
10334 (setq type "file" path link))
10335 ((string-match org-link-re-with-space3 link)
10336 (setq type (match-string 1 link) path (match-string 2 link)))
10337 ((string-match "^help:+\\(.+\\)" link)
10338 (setq type "help" path (match-string 1 link)))
10339 (t (setq type "thisfile" path link)))
10340 (throw 'match t)))
10342 (when (get-text-property (point) 'org-linked-text)
10343 (setq type "thisfile"
10344 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10345 (1+ (point)) (point))
10346 path (buffer-substring
10347 (or (previous-single-property-change pos 'org-linked-text)
10348 (point-min))
10349 (or (next-single-property-change pos 'org-linked-text)
10350 (point-max))))
10351 (throw 'match t))
10353 (save-excursion
10354 (when (or (org-in-regexp org-angle-link-re)
10355 (let ((match (org-in-regexp org-plain-link-re)))
10356 ;; Check a plain link is not within a bracket link
10357 (and match
10358 (save-excursion
10359 (progn
10360 (goto-char (car match))
10361 (not (org-in-regexp org-bracket-link-regexp))))))
10362 (let ((line_ending (save-excursion (end-of-line) (point))))
10363 ;; We are in a line before a plain or bracket link
10364 (or (re-search-forward org-plain-link-re line_ending t)
10365 (re-search-forward org-bracket-link-regexp line_ending t))))
10366 (setq type (match-string 1)
10367 path (org-link-unescape (match-string 2)))
10368 (throw 'match t)))
10369 (save-excursion
10370 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10371 (setq type "tags"
10372 path (match-string 1))
10373 (while (string-match ":" path)
10374 (setq path (replace-match "+" t t path)))
10375 (throw 'match t)))
10376 (when (org-in-regexp "<\\([^><\n]+\\)>")
10377 (setq type "tree-match"
10378 path (match-string 1))
10379 (throw 'match t)))
10380 (unless path
10381 (user-error "No link found"))
10383 ;; switch back to reference buffer
10384 ;; needed when if called in a temporary buffer through
10385 ;; org-open-link-from-string
10386 (with-current-buffer (or reference-buffer (current-buffer))
10388 ;; Remove any trailing spaces in path
10389 (if (string-match " +\\'" path)
10390 (setq path (replace-match "" t t path)))
10391 (if (and org-link-translation-function
10392 (fboundp org-link-translation-function))
10393 ;; Check if we need to translate the link
10394 (let ((tmp (funcall org-link-translation-function type path)))
10395 (setq type (car tmp) path (cdr tmp))))
10397 (cond
10399 ((assoc type org-link-protocols)
10400 (funcall (nth 1 (assoc type org-link-protocols)) path))
10402 ((equal type "help")
10403 (let ((f-or-v (intern path)))
10404 (cond ((fboundp f-or-v)
10405 (describe-function f-or-v))
10406 ((boundp f-or-v)
10407 (describe-variable f-or-v))
10408 (t (error "Not a known function or variable")))))
10410 ((equal type "mailto")
10411 (let ((cmd (car org-link-mailto-program))
10412 (args (cdr org-link-mailto-program)) args1
10413 (address path) (subject "") a)
10414 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10415 (setq address (match-string 1 path)
10416 subject (org-link-escape (match-string 2 path))))
10417 (while args
10418 (cond
10419 ((not (stringp (car args))) (push (pop args) args1))
10420 (t (setq a (pop args))
10421 (if (string-match "%a" a)
10422 (setq a (replace-match address t t a)))
10423 (if (string-match "%s" a)
10424 (setq a (replace-match subject t t a)))
10425 (push a args1))))
10426 (apply cmd (nreverse args1))))
10428 ((member type '("http" "https" "ftp" "news"))
10429 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10430 (org-link-escape
10431 path org-link-escape-chars-browser)
10432 path))))
10434 ((string= type "doi")
10435 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10436 (org-link-escape
10437 path org-link-escape-chars-browser)
10438 path))))
10440 ((member type '("message"))
10441 (browse-url (concat type ":" path)))
10443 ((string= type "tags")
10444 (org-tags-view arg path))
10446 ((string= type "tree-match")
10447 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10449 ((string= type "file")
10450 (if (string-match "::\\([0-9]+\\)\\'" path)
10451 (setq line (string-to-number (match-string 1 path))
10452 path (substring path 0 (match-beginning 0)))
10453 (if (string-match "::\\(.+\\)\\'" path)
10454 (setq search (match-string 1 path)
10455 path (substring path 0 (match-beginning 0)))))
10456 (if (string-match "[*?{]" (file-name-nondirectory path))
10457 (dired path)
10458 (org-open-file path arg line search)))
10460 ((string= type "shell")
10461 (let ((buf (generate-new-buffer "*Org Shell Output"))
10462 (cmd path))
10463 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10464 (string-match org-confirm-shell-link-not-regexp cmd))
10465 (not org-confirm-shell-link-function)
10466 (funcall org-confirm-shell-link-function
10467 (format "Execute \"%s\" in shell? "
10468 (org-add-props cmd nil
10469 'face 'org-warning))))
10470 (progn
10471 (message "Executing %s" cmd)
10472 (shell-command cmd buf)
10473 (if (featurep 'midnight)
10474 (setq clean-buffer-list-kill-buffer-names
10475 (cons buf clean-buffer-list-kill-buffer-names))))
10476 (error "Abort"))))
10478 ((string= type "elisp")
10479 (let ((cmd path))
10480 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10481 (string-match org-confirm-elisp-link-not-regexp cmd))
10482 (not org-confirm-elisp-link-function)
10483 (funcall org-confirm-elisp-link-function
10484 (format "Execute \"%s\" as elisp? "
10485 (org-add-props cmd nil
10486 'face 'org-warning))))
10487 (message "%s => %s" cmd
10488 (if (equal (string-to-char cmd) ?\()
10489 (eval (read cmd))
10490 (call-interactively (read cmd))))
10491 (error "Abort"))))
10493 ((and (string= type "thisfile")
10494 (run-hook-with-args-until-success
10495 'org-open-link-functions path)))
10497 ((string= type "thisfile")
10498 (if arg
10499 (switch-to-buffer-other-window
10500 (org-get-buffer-for-internal-link (current-buffer)))
10501 (org-mark-ring-push))
10502 (let ((cmd `(org-link-search
10503 ,path
10504 ,(cond ((equal arg '(4)) ''occur)
10505 ((equal arg '(16)) ''org-occur))
10506 ,pos)))
10507 (condition-case nil (let ((org-link-search-inhibit-query t))
10508 (eval cmd))
10509 (error (progn (widen) (eval cmd))))))
10511 (t (browse-url-at-point)))))))
10512 (move-marker org-open-link-marker nil)
10513 (run-hook-with-args 'org-follow-link-hook)))
10515 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10516 "Offer links in the current entry and return the selected link.
10517 If there is only one link, return it.
10518 If NTH is an integer, return the NTH link found.
10519 If ZERO is a string, check also this string for a link, and if
10520 there is one, return it."
10521 (with-current-buffer buffer
10522 (save-excursion
10523 (save-restriction
10524 (widen)
10525 (goto-char marker)
10526 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10527 "\\(" org-angle-link-re "\\)\\|"
10528 "\\(" org-plain-link-re "\\)"))
10529 (cnt ?0)
10530 (in-emacs (if (integerp nth) nil nth))
10531 have-zero end links link c)
10532 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10533 (push (match-string 0 zero) links)
10534 (setq cnt (1- cnt) have-zero t))
10535 (save-excursion
10536 (org-back-to-heading t)
10537 (setq end (save-excursion (outline-next-heading) (point)))
10538 (while (re-search-forward re end t)
10539 (push (match-string 0) links))
10540 (setq links (org-uniquify (reverse links))))
10541 (cond
10542 ((null links)
10543 (message "No links"))
10544 ((equal (length links) 1)
10545 (setq link (car links)))
10546 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10547 (setq link (nth (if have-zero nth (1- nth)) links)))
10548 (t ; we have to select a link
10549 (save-excursion
10550 (save-window-excursion
10551 (delete-other-windows)
10552 (with-output-to-temp-buffer "*Select Link*"
10553 (mapc (lambda (l)
10554 (if (not (string-match org-bracket-link-regexp l))
10555 (princ (format "[%c] %s\n" (incf cnt)
10556 (org-remove-angle-brackets l)))
10557 (if (match-end 3)
10558 (princ (format "[%c] %s (%s)\n" (incf cnt)
10559 (match-string 3 l) (match-string 1 l)))
10560 (princ (format "[%c] %s\n" (incf cnt)
10561 (match-string 1 l))))))
10562 links))
10563 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10564 (message "Select link to open, RET to open all:")
10565 (setq c (read-char-exclusive))
10566 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10567 (when (equal c ?q) (error "Abort"))
10568 (if (equal c ?\C-m)
10569 (setq link links)
10570 (setq nth (- c ?0))
10571 (if have-zero (setq nth (1+ nth)))
10572 (unless (and (integerp nth) (>= (length links) nth))
10573 (error "Invalid link selection"))
10574 (setq link (nth (1- nth) links)))))
10575 (cons link end))))))
10577 ;; Add special file links that specify the way of opening
10579 (org-add-link-type "file+sys" 'org-open-file-with-system)
10580 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10581 (defun org-open-file-with-system (path)
10582 "Open file at PATH using the system way of opening it."
10583 (org-open-file path 'system))
10584 (defun org-open-file-with-emacs (path)
10585 "Open file at PATH in Emacs."
10586 (org-open-file path 'emacs))
10589 ;;; File search
10591 (defvar org-create-file-search-functions nil
10592 "List of functions to construct the right search string for a file link.
10593 These functions are called in turn with point at the location to
10594 which the link should point.
10596 A function in the hook should first test if it would like to
10597 handle this file type, for example by checking the `major-mode'
10598 or the file extension. If it decides not to handle this file, it
10599 should just return nil to give other functions a chance. If it
10600 does handle the file, it must return the search string to be used
10601 when following the link. The search string will be part of the
10602 file link, given after a double colon, and `org-open-at-point'
10603 will automatically search for it. If special measures must be
10604 taken to make the search successful, another function should be
10605 added to the companion hook `org-execute-file-search-functions',
10606 which see.
10608 A function in this hook may also use `setq' to set the variable
10609 `description' to provide a suggestion for the descriptive text to
10610 be used for this link when it gets inserted into an Org-mode
10611 buffer with \\[org-insert-link].")
10613 (defvar org-execute-file-search-functions nil
10614 "List of functions to execute a file search triggered by a link.
10616 Functions added to this hook must accept a single argument, the
10617 search string that was part of the file link, the part after the
10618 double colon. The function must first check if it would like to
10619 handle this search, for example by checking the `major-mode' or
10620 the file extension. If it decides not to handle this search, it
10621 should just return nil to give other functions a chance. If it
10622 does handle the search, it must return a non-nil value to keep
10623 other functions from trying.
10625 Each function can access the current prefix argument through the
10626 variable `current-prefix-arg'. Note that a single prefix is used
10627 to force opening a link in Emacs, so it may be good to only use a
10628 numeric or double prefix to guide the search function.
10630 In case this is needed, a function in this hook can also restore
10631 the window configuration before `org-open-at-point' was called using:
10633 (set-window-configuration org-window-config-before-follow-link)")
10635 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10636 (defun org-link-search (s &optional type avoid-pos stealth)
10637 "Search for a link search option.
10638 If S is surrounded by forward slashes, it is interpreted as a
10639 regular expression. In org-mode files, this will create an `org-occur'
10640 sparse tree. In ordinary files, `occur' will be used to list matches.
10641 If the current buffer is in `dired-mode', grep will be used to search
10642 in all files. If AVOID-POS is given, ignore matches near that position.
10644 When optional argument STEALTH is non-nil, do not modify
10645 visibility around point, thus ignoring
10646 `org-show-hierarchy-above', `org-show-following-heading' and
10647 `org-show-siblings' variables."
10648 (let ((case-fold-search t)
10649 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10650 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10651 (append '(("") (" ") ("\t") ("\n"))
10652 org-emphasis-alist)
10653 "\\|") "\\)"))
10654 (pos (point))
10655 (pre nil) (post nil)
10656 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10657 (cond
10658 ;; First check if there are any special search functions
10659 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10660 ;; Now try the builtin stuff
10661 ((and (equal (string-to-char s0) ?#)
10662 (> (length s0) 1)
10663 (save-excursion
10664 (goto-char (point-min))
10665 (and
10666 (re-search-forward
10667 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10668 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10669 (setq type 'dedicated
10670 pos (match-beginning 0))))
10671 ;; There is an exact target for this
10672 (goto-char pos)
10673 (org-back-to-heading t)))
10674 ((save-excursion
10675 (goto-char (point-min))
10676 (and
10677 (re-search-forward
10678 (concat "<<" (regexp-quote s0) ">>") nil t)
10679 (setq type 'dedicated
10680 pos (match-beginning 0))))
10681 ;; There is an exact target for this
10682 (goto-char pos))
10683 ((save-excursion
10684 (goto-char (point-min))
10685 (and
10686 (re-search-forward
10687 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10688 (setq type 'dedicated pos (match-beginning 0))))
10689 ;; Found an element with a matching #+name affiliated keyword.
10690 (goto-char pos))
10691 ((and (string-match "^(\\(.*\\))$" s0)
10692 (save-excursion
10693 (goto-char (point-min))
10694 (and
10695 (re-search-forward
10696 (concat "[^[]" (regexp-quote
10697 (format org-coderef-label-format
10698 (match-string 1 s0))))
10699 nil t)
10700 (setq type 'dedicated
10701 pos (1+ (match-beginning 0))))))
10702 ;; There is a coderef target for this
10703 (goto-char pos))
10704 ((string-match "^/\\(.*\\)/$" s)
10705 ;; A regular expression
10706 (cond
10707 ((derived-mode-p 'org-mode)
10708 (org-occur (match-string 1 s)))
10709 (t (org-do-occur (match-string 1 s)))))
10710 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10711 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10712 (goto-char (point-min))
10713 (cond
10714 ((let (case-fold-search)
10715 (re-search-forward (format org-complex-heading-regexp-format
10716 (regexp-quote s))
10717 nil t))
10718 ;; OK, found a match
10719 (setq type 'dedicated)
10720 (goto-char (match-beginning 0)))
10721 ((and (not org-link-search-inhibit-query)
10722 (eq org-link-search-must-match-exact-headline 'query-to-create)
10723 (y-or-n-p "No match - create this as a new heading? "))
10724 (goto-char (point-max))
10725 (or (bolp) (newline))
10726 (insert "* " s "\n")
10727 (beginning-of-line 0))
10729 (goto-char pos)
10730 (error "No match"))))
10732 ;; A normal search string
10733 (when (equal (string-to-char s) ?*)
10734 ;; Anchor on headlines, post may include tags.
10735 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10736 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10737 s (substring s 1)))
10738 (remove-text-properties
10739 0 (length s)
10740 '(face nil mouse-face nil keymap nil fontified nil) s)
10741 ;; Make a series of regular expressions to find a match
10742 (setq words (org-split-string s "[ \n\r\t]+")
10744 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10745 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10746 "\\)" markers)
10747 re2a_ (concat "\\(" (mapconcat 'downcase words
10748 "[ \t\r\n]+") "\\)[ \t\r\n]")
10749 re2a (concat "[ \t\r\n]" re2a_)
10750 re4_ (concat "\\(" (mapconcat 'downcase words
10751 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10752 re4 (concat "[^a-zA-Z_]" re4_)
10754 re1 (concat pre re2 post)
10755 re3 (concat pre (if pre re4_ re4) post)
10756 re5 (concat pre ".*" re4)
10757 re2 (concat pre re2)
10758 re2a (concat pre (if pre re2a_ re2a))
10759 re4 (concat pre (if pre re4_ re4))
10760 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10761 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10762 re5 "\\)"
10764 (cond
10765 ((eq type 'org-occur) (org-occur reall))
10766 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10767 (t (goto-char (point-min))
10768 (setq type 'fuzzy)
10769 (if (or (and (org-search-not-self 1 re0 nil t)
10770 (setq type 'dedicated))
10771 (org-search-not-self 1 re1 nil t)
10772 (org-search-not-self 1 re2 nil t)
10773 (org-search-not-self 1 re2a nil t)
10774 (org-search-not-self 1 re3 nil t)
10775 (org-search-not-self 1 re4 nil t)
10776 (org-search-not-self 1 re5 nil t))
10777 (goto-char (match-beginning 1))
10778 (goto-char pos)
10779 (error "No match"))))))
10780 (and (derived-mode-p 'org-mode)
10781 (not stealth)
10782 (org-show-context 'link-search))
10783 type))
10785 (defun org-search-not-self (group &rest args)
10786 "Execute `re-search-forward', but only accept matches that do not
10787 enclose the position of `org-open-link-marker'."
10788 (let ((m org-open-link-marker))
10789 (catch 'exit
10790 (while (apply 're-search-forward args)
10791 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10792 (goto-char (match-end group))
10793 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10794 (> (match-beginning 0) (marker-position m))
10795 (< (match-end 0) (marker-position m)))
10796 (save-match-data
10797 (or (not (org-in-regexp
10798 org-bracket-link-analytic-regexp 1))
10799 (not (match-end 4)) ; no description
10800 (and (<= (match-beginning 4) (point))
10801 (>= (match-end 4) (point))))))
10802 (throw 'exit (point))))))))
10804 (defun org-get-buffer-for-internal-link (buffer)
10805 "Return a buffer to be used for displaying the link target of internal links."
10806 (cond
10807 ((not org-display-internal-link-with-indirect-buffer)
10808 buffer)
10809 ((string-match "(Clone)$" (buffer-name buffer))
10810 (message "Buffer is already a clone, not making another one")
10811 ;; we also do not modify visibility in this case
10812 buffer)
10813 (t ; make a new indirect buffer for displaying the link
10814 (let* ((bn (buffer-name buffer))
10815 (ibn (concat bn "(Clone)"))
10816 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10817 (with-current-buffer ib (org-overview))
10818 ib))))
10820 (defun org-do-occur (regexp &optional cleanup)
10821 "Call the Emacs command `occur'.
10822 If CLEANUP is non-nil, remove the printout of the regular expression
10823 in the *Occur* buffer. This is useful if the regex is long and not useful
10824 to read."
10825 (occur regexp)
10826 (when cleanup
10827 (let ((cwin (selected-window)) win beg end)
10828 (when (setq win (get-buffer-window "*Occur*"))
10829 (select-window win))
10830 (goto-char (point-min))
10831 (when (re-search-forward "match[a-z]+" nil t)
10832 (setq beg (match-end 0))
10833 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10834 (setq end (1- (match-beginning 0)))))
10835 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10836 (goto-char (point-min))
10837 (select-window cwin))))
10839 ;;; The mark ring for links jumps
10841 (defvar org-mark-ring nil
10842 "Mark ring for positions before jumps in Org-mode.")
10843 (defvar org-mark-ring-last-goto nil
10844 "Last position in the mark ring used to go back.")
10845 ;; Fill and close the ring
10846 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10847 (loop for i from 1 to org-mark-ring-length do
10848 (push (make-marker) org-mark-ring))
10849 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10850 org-mark-ring)
10852 (defun org-mark-ring-push (&optional pos buffer)
10853 "Put the current position or POS into the mark ring and rotate it."
10854 (interactive)
10855 (setq pos (or pos (point)))
10856 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10857 (move-marker (car org-mark-ring)
10858 (or pos (point))
10859 (or buffer (current-buffer)))
10860 (message "%s"
10861 (substitute-command-keys
10862 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10864 (defun org-mark-ring-goto (&optional n)
10865 "Jump to the previous position in the mark ring.
10866 With prefix arg N, jump back that many stored positions. When
10867 called several times in succession, walk through the entire ring.
10868 Org-mode commands jumping to a different position in the current file,
10869 or to another Org-mode file, automatically push the old position
10870 onto the ring."
10871 (interactive "p")
10872 (let (p m)
10873 (if (eq last-command this-command)
10874 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10875 (setq p org-mark-ring))
10876 (setq org-mark-ring-last-goto p)
10877 (setq m (car p))
10878 (org-pop-to-buffer-same-window (marker-buffer m))
10879 (goto-char m)
10880 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10882 (defun org-remove-angle-brackets (s)
10883 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10884 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10886 (defun org-add-angle-brackets (s)
10887 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10888 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10890 (defun org-remove-double-quotes (s)
10891 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10892 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10895 ;;; Following specific links
10897 (defun org-follow-timestamp-link ()
10898 "Open an agenda view for the time-stamp date/range at point."
10899 (cond
10900 ((org-at-date-range-p t)
10901 (let ((org-agenda-start-on-weekday)
10902 (t1 (match-string 1))
10903 (t2 (match-string 2)) tt1 tt2)
10904 (setq tt1 (time-to-days (org-time-string-to-time t1))
10905 tt2 (time-to-days (org-time-string-to-time t2)))
10906 (let ((org-agenda-buffer-tmp-name
10907 (format "*Org Agenda(a:%s)"
10908 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10909 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10910 ((org-at-timestamp-p t)
10911 (let ((org-agenda-buffer-tmp-name
10912 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10913 (org-agenda-list nil (time-to-days (org-time-string-to-time
10914 (substring (match-string 1) 0 10)))
10915 1)))
10916 (t (error "This should not happen"))))
10919 ;;; Following file links
10920 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10921 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10922 (declare-function mailcap-mime-info
10923 "mailcap" (string &optional request no-decode))
10924 (defvar org-wait nil)
10925 (defun org-open-file (path &optional in-emacs line search)
10926 "Open the file at PATH.
10927 First, this expands any special file name abbreviations. Then the
10928 configuration variable `org-file-apps' is checked if it contains an
10929 entry for this file type, and if yes, the corresponding command is launched.
10931 If no application is found, Emacs simply visits the file.
10933 With optional prefix argument IN-EMACS, Emacs will visit the file.
10934 With a double \\[universal-argument] \\[universal-argument] \
10935 prefix arg, Org tries to avoid opening in Emacs
10936 and to use an external application to visit the file.
10938 Optional LINE specifies a line to go to, optional SEARCH a string
10939 to search for. If LINE or SEARCH is given, the file will be
10940 opened in Emacs, unless an entry from org-file-apps that makes
10941 use of groups in a regexp matches.
10943 If you want to change the way frames are used when following a
10944 link, please customize `org-link-frame-setup'.
10946 If the file does not exist, an error is thrown."
10947 (let* ((file (if (equal path "")
10948 buffer-file-name
10949 (substitute-in-file-name (expand-file-name path))))
10950 (file-apps (append org-file-apps (org-default-apps)))
10951 (apps (org-remove-if
10952 'org-file-apps-entry-match-against-dlink-p file-apps))
10953 (apps-dlink (org-remove-if-not
10954 'org-file-apps-entry-match-against-dlink-p file-apps))
10955 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10956 (dirp (if remp nil (file-directory-p file)))
10957 (file (if (and dirp org-open-directory-means-index-dot-org)
10958 (concat (file-name-as-directory file) "index.org")
10959 file))
10960 (a-m-a-p (assq 'auto-mode apps))
10961 (dfile (downcase file))
10962 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10963 (link (cond ((and (eq line nil)
10964 (eq search nil))
10965 file)
10966 (line
10967 (concat file "::" (number-to-string line)))
10968 (search
10969 (concat file "::" search))))
10970 (dlink (downcase link))
10971 (old-buffer (current-buffer))
10972 (old-pos (point))
10973 (old-mode major-mode)
10974 ext cmd link-match-data)
10975 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10976 (setq ext (match-string 1 dfile))
10977 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10978 (setq ext (match-string 1 dfile))))
10979 (cond
10980 ((member in-emacs '((16) system))
10981 (setq cmd (cdr (assoc 'system apps))))
10982 (in-emacs (setq cmd 'emacs))
10984 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10985 (and dirp (cdr (assoc 'directory apps)))
10986 ; first, try matching against apps-dlink
10987 ; if we get a match here, store the match data for later
10988 (let ((match (assoc-default dlink apps-dlink
10989 'string-match)))
10990 (if match
10991 (progn (setq link-match-data (match-data))
10992 match)
10993 (progn (setq in-emacs (or in-emacs line search))
10994 nil))) ; if we have no match in apps-dlink,
10995 ; always open the file in emacs if line or search
10996 ; is given (for backwards compatibility)
10997 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10998 'string-match)
10999 (cdr (assoc ext apps))
11000 (cdr (assoc t apps))))))
11001 (when (eq cmd 'system)
11002 (setq cmd (cdr (assoc 'system apps))))
11003 (when (eq cmd 'default)
11004 (setq cmd (cdr (assoc t apps))))
11005 (when (eq cmd 'mailcap)
11006 (require 'mailcap)
11007 (mailcap-parse-mailcaps)
11008 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11009 (command (mailcap-mime-info mime-type)))
11010 (if (stringp command)
11011 (setq cmd command)
11012 (setq cmd 'emacs))))
11013 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11014 (not (file-exists-p file))
11015 (not org-open-non-existing-files))
11016 (error "No such file: %s" file))
11017 (cond
11018 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11019 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11020 (while (string-match "['\"]%s['\"]" cmd)
11021 (setq cmd (replace-match "%s" t t cmd)))
11022 (while (string-match "%s" cmd)
11023 (setq cmd (replace-match
11024 (save-match-data
11025 (shell-quote-argument
11026 (convert-standard-filename file)))
11027 t t cmd)))
11029 ;; Replace "%1", "%2" etc. in command with group matches from regex
11030 (save-match-data
11031 (let ((match-index 1)
11032 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11033 (set-match-data link-match-data)
11034 (while (<= match-index number-of-groups)
11035 (let ((regex (concat "%" (number-to-string match-index)))
11036 (replace-with (match-string match-index dlink)))
11037 (while (string-match regex cmd)
11038 (setq cmd (replace-match replace-with t t cmd))))
11039 (setq match-index (+ match-index 1)))))
11041 (save-window-excursion
11042 (message "Running %s...done" cmd)
11043 (start-process-shell-command cmd nil cmd)
11044 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11045 ((or (stringp cmd)
11046 (eq cmd 'emacs))
11047 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11048 (widen)
11049 (if line (org-goto-line line)
11050 (if search (org-link-search search))))
11051 ((consp cmd)
11052 (let ((file (convert-standard-filename file)))
11053 (save-match-data
11054 (set-match-data link-match-data)
11055 (eval cmd))))
11056 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11057 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11058 (or (not (equal old-buffer (current-buffer)))
11059 (not (equal old-pos (point))))
11060 (org-mark-ring-push old-pos old-buffer))))
11062 (defun org-file-apps-entry-match-against-dlink-p (entry)
11063 "This function returns non-nil if `entry' uses a regular
11064 expression which should be matched against the whole link by
11065 org-open-file.
11067 It assumes that is the case when the entry uses a regular
11068 expression which has at least one grouping construct and the
11069 action is either a lisp form or a command string containing
11070 '%1', i.e. using at least one subexpression match as a
11071 parameter."
11072 (let ((selector (car entry))
11073 (action (cdr entry)))
11074 (if (stringp selector)
11075 (and (> (regexp-opt-depth selector) 0)
11076 (or (and (stringp action)
11077 (string-match "%[0-9]" action))
11078 (consp action)))
11079 nil)))
11081 (defun org-default-apps ()
11082 "Return the default applications for this operating system."
11083 (cond
11084 ((eq system-type 'darwin)
11085 org-file-apps-defaults-macosx)
11086 ((eq system-type 'windows-nt)
11087 org-file-apps-defaults-windowsnt)
11088 (t org-file-apps-defaults-gnu)))
11090 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11091 "Convert extensions to regular expressions in the cars of LIST.
11092 Also, weed out any non-string entries, because the return value is used
11093 only for regexp matching.
11094 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11095 point to the symbol `emacs', indicating that the file should
11096 be opened in Emacs."
11097 (append
11098 (delq nil
11099 (mapcar (lambda (x)
11100 (if (not (stringp (car x)))
11102 (if (string-match "\\W" (car x))
11104 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11105 list))
11106 (if add-auto-mode
11107 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11109 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11110 (defun org-file-remote-p (file)
11111 "Test whether FILE specifies a location on a remote system.
11112 Return non-nil if the location is indeed remote.
11114 For example, the filename \"/user@host:/foo\" specifies a location
11115 on the system \"/user@host:\"."
11116 (cond ((fboundp 'file-remote-p)
11117 (file-remote-p file))
11118 ((fboundp 'tramp-handle-file-remote-p)
11119 (tramp-handle-file-remote-p file))
11120 ((and (boundp 'ange-ftp-name-format)
11121 (string-match (car ange-ftp-name-format) file))
11122 t)))
11125 ;;;; Refiling
11127 (defun org-get-org-file ()
11128 "Read a filename, with default directory `org-directory'."
11129 (let ((default (or org-default-notes-file remember-data-file)))
11130 (read-file-name (format "File name [%s]: " default)
11131 (file-name-as-directory org-directory)
11132 default)))
11134 (defun org-notes-order-reversed-p ()
11135 "Check if the current file should receive notes in reversed order."
11136 (cond
11137 ((not org-reverse-note-order) nil)
11138 ((eq t org-reverse-note-order) t)
11139 ((not (listp org-reverse-note-order)) nil)
11140 (t (catch 'exit
11141 (let ((all org-reverse-note-order)
11142 entry)
11143 (while (setq entry (pop all))
11144 (if (string-match (car entry) buffer-file-name)
11145 (throw 'exit (cdr entry))))
11146 nil)))))
11148 (defvar org-refile-target-table nil
11149 "The list of refile targets, created by `org-refile'.")
11151 (defvar org-agenda-new-buffers nil
11152 "Buffers created to visit agenda files.")
11154 (defvar org-refile-cache nil
11155 "Cache for refile targets.")
11157 (defvar org-refile-markers nil
11158 "All the markers used for caching refile locations.")
11160 (defun org-refile-marker (pos)
11161 "Get a new refile marker, but only if caching is in use."
11162 (if (not org-refile-use-cache)
11164 (let ((m (make-marker)))
11165 (move-marker m pos)
11166 (push m org-refile-markers)
11167 m)))
11169 (defun org-refile-cache-clear ()
11170 "Clear the refile cache and disable all the markers."
11171 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11172 (setq org-refile-markers nil)
11173 (setq org-refile-cache nil)
11174 (message "Refile cache has been cleared"))
11176 (defun org-refile-cache-check-set (set)
11177 "Check if all the markers in the cache still have live buffers."
11178 (let (marker)
11179 (catch 'exit
11180 (while (and set (setq marker (nth 3 (pop set))))
11181 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11182 (when (and marker (null (marker-buffer marker)))
11183 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11184 (sit-for 3)
11185 (throw 'exit nil)))
11186 t)))
11188 (defun org-refile-cache-put (set &rest identifiers)
11189 "Push the refile targets SET into the cache, under IDENTIFIERS."
11190 (let* ((key (sha1 (prin1-to-string identifiers)))
11191 (entry (assoc key org-refile-cache)))
11192 (if entry
11193 (setcdr entry set)
11194 (push (cons key set) org-refile-cache))))
11196 (defun org-refile-cache-get (&rest identifiers)
11197 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11198 (cond
11199 ((not org-refile-cache) nil)
11200 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11202 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11203 org-refile-cache))))
11204 (and set (org-refile-cache-check-set set) set)))))
11206 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11207 "Produce a table with refile targets."
11208 (let ((case-fold-search nil)
11209 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11210 (entries (or org-refile-targets '((nil . (:level . 1)))))
11211 targets tgs txt re files f desc descre fast-path-p level pos0)
11212 (message "Getting targets...")
11213 (with-current-buffer (or default-buffer (current-buffer))
11214 (while (setq entry (pop entries))
11215 (setq files (car entry) desc (cdr entry))
11216 (setq fast-path-p nil)
11217 (cond
11218 ((null files) (setq files (list (current-buffer))))
11219 ((eq files 'org-agenda-files)
11220 (setq files (org-agenda-files 'unrestricted)))
11221 ((and (symbolp files) (fboundp files))
11222 (setq files (funcall files)))
11223 ((and (symbolp files) (boundp files))
11224 (setq files (symbol-value files))))
11225 (if (stringp files) (setq files (list files)))
11226 (cond
11227 ((eq (car desc) :tag)
11228 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11229 ((eq (car desc) :todo)
11230 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11231 ((eq (car desc) :regexp)
11232 (setq descre (cdr desc)))
11233 ((eq (car desc) :level)
11234 (setq descre (concat "^\\*\\{" (number-to-string
11235 (if org-odd-levels-only
11236 (1- (* 2 (cdr desc)))
11237 (cdr desc)))
11238 "\\}[ \t]")))
11239 ((eq (car desc) :maxlevel)
11240 (setq fast-path-p t)
11241 (setq descre (concat "^\\*\\{1," (number-to-string
11242 (if org-odd-levels-only
11243 (1- (* 2 (cdr desc)))
11244 (cdr desc)))
11245 "\\}[ \t]")))
11246 (t (error "Bad refiling target description %s" desc)))
11247 (while (setq f (pop files))
11248 (with-current-buffer
11249 (if (bufferp f) f (org-get-agenda-file-buffer f))
11251 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11252 (progn
11253 (if (bufferp f) (setq f (buffer-file-name
11254 (buffer-base-buffer f))))
11255 (setq f (and f (expand-file-name f)))
11256 (if (eq org-refile-use-outline-path 'file)
11257 (push (list (file-name-nondirectory f) f nil nil) tgs))
11258 (save-excursion
11259 (save-restriction
11260 (widen)
11261 (goto-char (point-min))
11262 (while (re-search-forward descre nil t)
11263 (goto-char (setq pos0 (point-at-bol)))
11264 (catch 'next
11265 (when org-refile-target-verify-function
11266 (save-match-data
11267 (or (funcall org-refile-target-verify-function)
11268 (throw 'next t))))
11269 (when (and (looking-at org-complex-heading-regexp)
11270 (not (member (match-string 4) excluded-entries))
11271 (match-string 4))
11272 (setq level (org-reduced-level
11273 (- (match-end 1) (match-beginning 1)))
11274 txt (org-link-display-format (match-string 4))
11275 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11276 re (format org-complex-heading-regexp-format
11277 (regexp-quote (match-string 4))))
11278 (when org-refile-use-outline-path
11279 (setq txt (mapconcat
11280 'org-protect-slash
11281 (append
11282 (if (eq org-refile-use-outline-path
11283 'file)
11284 (list (file-name-nondirectory
11285 (buffer-file-name
11286 (buffer-base-buffer))))
11287 (if (eq org-refile-use-outline-path
11288 'full-file-path)
11289 (list (buffer-file-name
11290 (buffer-base-buffer)))))
11291 (org-get-outline-path fast-path-p
11292 level txt)
11293 (list txt))
11294 "/")))
11295 (push (list txt f re (org-refile-marker (point)))
11296 tgs)))
11297 (when (= (point) pos0)
11298 ;; verification function has not moved point
11299 (goto-char (point-at-eol))))))))
11300 (when org-refile-use-cache
11301 (org-refile-cache-put tgs (buffer-file-name) descre))
11302 (setq targets (append tgs targets))
11303 ))))
11304 (message "Getting targets...done")
11305 (nreverse targets)))
11307 (defun org-protect-slash (s)
11308 (while (string-match "/" s)
11309 (setq s (replace-match "\\" t t s)))
11312 (defvar org-olpa (make-vector 20 nil))
11314 (defun org-get-outline-path (&optional fastp level heading)
11315 "Return the outline path to the current entry, as a list.
11317 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11318 routine which makes outline path derivations for an entire file,
11319 avoiding backtracing. Refile target collection makes use of that."
11320 (if fastp
11321 (progn
11322 (if (> level 19)
11323 (error "Outline path failure, more than 19 levels"))
11324 (loop for i from level upto 19 do
11325 (aset org-olpa i nil))
11326 (prog1
11327 (delq nil (append org-olpa nil))
11328 (aset org-olpa level heading)))
11329 (let (rtn case-fold-search)
11330 (save-excursion
11331 (save-restriction
11332 (widen)
11333 (while (org-up-heading-safe)
11334 (when (looking-at org-complex-heading-regexp)
11335 (push (org-match-string-no-properties 4) rtn)))
11336 rtn)))))
11338 (defun org-format-outline-path (path &optional width prefix separator)
11339 "Format the outline path PATH for display.
11340 WIDTH is the maximum number of characters that is available.
11341 PREFIX is a prefix to be included in the returned string,
11342 such as the file name.
11343 SEPARATOR is inserted between the different parts of the path,
11344 the default is \"/\"."
11345 (setq width (or width 79))
11346 (if prefix (setq width (- width (length prefix))))
11347 (if (not path)
11348 (or prefix "")
11349 (let* ((nsteps (length path))
11350 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11351 (maxwidth (if (<= total-width width)
11352 10000 ;; everything fits
11353 ;; we need to shorten the level headings
11354 (/ (- width nsteps) nsteps)))
11355 (org-odd-levels-only nil)
11356 (n 0)
11357 (total (1+ (length prefix))))
11358 (setq maxwidth (max maxwidth 10))
11359 (concat prefix
11360 (if prefix (or separator "/"))
11361 (mapconcat
11362 (lambda (h)
11363 (setq n (1+ n))
11364 (if (and (= n nsteps) (< maxwidth 10000))
11365 (setq maxwidth (- total-width total)))
11366 (if (< (length h) maxwidth)
11367 (progn (setq total (+ total (length h) 1)) h)
11368 (setq h (substring h 0 (- maxwidth 2))
11369 total (+ total maxwidth 1))
11370 (if (string-match "[ \t]+\\'" h)
11371 (setq h (substring h 0 (match-beginning 0))))
11372 (setq h (concat h "..")))
11373 (org-add-props h nil 'face
11374 (nth (% (1- n) org-n-level-faces)
11375 org-level-faces))
11377 path (or separator "/"))))))
11379 (defun org-display-outline-path (&optional file current separator just-return-string)
11380 "Display the current outline path in the echo area.
11382 If FILE is non-nil, prepend the output with the file name.
11383 If CURRENT is non-nil, append the current heading to the output.
11384 SEPARATOR is passed through to `org-format-outline-path'. It separates
11385 the different parts of the path and defaults to \"/\".
11386 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11387 (interactive "P")
11388 (let* (case-fold-search
11389 message-log-max ; Don't populate the *Messages* buffer
11390 (bfn (buffer-file-name (buffer-base-buffer)))
11391 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11392 res)
11393 (if current (setq path (append path
11394 (save-excursion
11395 (org-back-to-heading t)
11396 (if (looking-at org-complex-heading-regexp)
11397 (list (match-string 4)))))))
11398 (setq res
11399 (org-format-outline-path
11400 path
11401 (1- (frame-width))
11402 (and file bfn (concat (file-name-nondirectory bfn) separator))
11403 separator))
11404 (if just-return-string
11405 (org-no-properties res)
11406 (message "%s" res))))
11408 (defvar org-refile-history nil
11409 "History for refiling operations.")
11411 (defvar org-after-refile-insert-hook nil
11412 "Hook run after `org-refile' has inserted its stuff at the new location.
11413 Note that this is still *before* the stuff will be removed from
11414 the *old* location.")
11416 (defvar org-capture-last-stored-marker)
11417 (defvar org-refile-keep nil
11418 "Non-nil means `org-refile' will copy instead of refile.")
11420 (defun org-copy ()
11421 "Like `org-refile', but copy."
11422 (interactive)
11423 (let ((org-refile-keep t))
11424 (funcall 'org-refile nil nil nil "Copy")))
11426 (defun org-refile (&optional goto default-buffer rfloc msg)
11427 "Move the entry or entries at point to another heading.
11428 The list of target headings is compiled using the information in
11429 `org-refile-targets', which see.
11431 At the target location, the entry is filed as a subitem of the target
11432 heading. Depending on `org-reverse-note-order', the new subitem will
11433 either be the first or the last subitem.
11435 If there is an active region, all entries in that region will be moved.
11436 However, the region must fulfill the requirement that the first heading
11437 is the first one sets the top-level of the moved text - at most siblings
11438 below it are allowed.
11440 With prefix arg GOTO, the command will only visit the target location
11441 and not actually move anything.
11443 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11444 go to the location where the last refiling operation has put the subtree.
11445 With a prefix argument of `2', refile to the running clock.
11447 RFLOC can be a refile location obtained in a different way.
11449 MSG is a string to replace \"Refile\" in the default prompt with
11450 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11452 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11454 If you are using target caching (see `org-refile-use-cache'),
11455 you have to clear the target cache in order to find new targets.
11456 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11457 prefix argument (`C-u C-u C-u C-c C-w')."
11459 (interactive "P")
11460 (if (member goto '(0 (64)))
11461 (org-refile-cache-clear)
11462 (let* ((actionmsg (or msg "Refile"))
11463 (cbuf (current-buffer))
11464 (regionp (org-region-active-p))
11465 (region-start (and regionp (region-beginning)))
11466 (region-end (and regionp (region-end)))
11467 (region-length (and regionp (- region-end region-start)))
11468 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11469 pos it nbuf file re level reversed)
11470 (setq last-command nil)
11471 (when regionp
11472 (goto-char region-start)
11473 (or (bolp) (goto-char (point-at-bol)))
11474 (setq region-start (point))
11475 (unless (or (org-kill-is-subtree-p
11476 (buffer-substring region-start region-end))
11477 (prog1 org-refile-active-region-within-subtree
11478 (org-toggle-heading)))
11479 (error "The region is not a (sequence of) subtree(s)")))
11480 (if (equal goto '(16))
11481 (org-refile-goto-last-stored)
11482 (when (or
11483 (and (equal goto 2)
11484 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11485 (prog1
11486 (setq it (list (or org-clock-heading "running clock")
11487 (buffer-file-name
11488 (marker-buffer org-clock-hd-marker))
11490 (marker-position org-clock-hd-marker)))
11491 (setq goto nil)))
11492 (setq it (or rfloc
11493 (let (heading-text)
11494 (save-excursion
11495 (unless goto
11496 (org-back-to-heading t)
11497 (setq heading-text
11498 (nth 4 (org-heading-components))))
11500 (org-refile-get-location
11501 (cond (goto "Goto")
11502 (regionp (concat actionmsg " region to"))
11503 (t (concat actionmsg " subtree \""
11504 heading-text "\" to")))
11505 default-buffer
11506 (and (not (equal '(4) goto))
11507 org-refile-allow-creating-parent-nodes)
11508 goto))))))
11509 (setq file (nth 1 it)
11510 re (nth 2 it)
11511 pos (nth 3 it))
11512 (if (and (not goto)
11514 (equal (buffer-file-name) file)
11515 (if regionp
11516 (and (>= pos region-start)
11517 (<= pos region-end))
11518 (and (>= pos (point))
11519 (< pos (save-excursion
11520 (org-end-of-subtree t t))))))
11521 (error "Cannot refile to position inside the tree or region"))
11523 (setq nbuf (or (find-buffer-visiting file)
11524 (find-file-noselect file)))
11525 (if goto
11526 (progn
11527 (org-pop-to-buffer-same-window nbuf)
11528 (goto-char pos)
11529 (org-show-context 'org-goto))
11530 (if regionp
11531 (progn
11532 (org-kill-new (buffer-substring region-start region-end))
11533 (org-save-markers-in-region region-start region-end))
11534 (org-copy-subtree 1 nil t))
11535 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11536 (find-file-noselect file)))
11537 (setq reversed (org-notes-order-reversed-p))
11538 (save-excursion
11539 (save-restriction
11540 (widen)
11541 (if pos
11542 (progn
11543 (goto-char pos)
11544 (looking-at org-outline-regexp)
11545 (setq level (org-get-valid-level (funcall outline-level) 1))
11546 (goto-char
11547 (if reversed
11548 (or (outline-next-heading) (point-max))
11549 (or (save-excursion (org-get-next-sibling))
11550 (org-end-of-subtree t t)
11551 (point-max)))))
11552 (setq level 1)
11553 (if (not reversed)
11554 (goto-char (point-max))
11555 (goto-char (point-min))
11556 (or (outline-next-heading) (goto-char (point-max)))))
11557 (if (not (bolp)) (newline))
11558 (org-paste-subtree level)
11559 (when org-log-refile
11560 (org-add-log-setup 'refile nil nil 'findpos
11561 org-log-refile)
11562 (unless (eq org-log-refile 'note)
11563 (save-excursion (org-add-log-note))))
11564 (and org-auto-align-tags
11565 (let ((org-loop-over-headlines-in-active-region nil))
11566 (org-set-tags nil t)))
11567 (with-demoted-errors
11568 (bookmark-set "org-refile-last-stored"))
11569 ;; If we are refiling for capture, make sure that the
11570 ;; last-capture pointers point here
11571 (when (org-bound-and-true-p org-refile-for-capture)
11572 (with-demoted-errors
11573 (bookmark-set "org-capture-last-stored-marker"))
11574 (move-marker org-capture-last-stored-marker (point)))
11575 (if (fboundp 'deactivate-mark) (deactivate-mark))
11576 (run-hooks 'org-after-refile-insert-hook))))
11577 (unless org-refile-keep
11578 (if regionp
11579 (delete-region (point) (+ (point) region-length))
11580 (org-cut-subtree)))
11581 (when (featurep 'org-inlinetask)
11582 (org-inlinetask-remove-END-maybe))
11583 (setq org-markers-to-move nil)
11584 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11586 (defun org-refile-goto-last-stored ()
11587 "Go to the location where the last refile was stored."
11588 (interactive)
11589 (bookmark-jump "org-refile-last-stored")
11590 (message "This is the location of the last refile"))
11592 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11593 no-exclude)
11594 "Prompt the user for a refile location, using PROMPT.
11595 PROMPT should not be suffixed with a colon and a space, because
11596 this function appends the default value from
11597 `org-refile-history' automatically, if that is not empty.
11598 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11599 this is used for the GOTO interface."
11600 (let ((org-refile-targets org-refile-targets)
11601 (org-refile-use-outline-path org-refile-use-outline-path)
11602 excluded-entries)
11603 (when (and (derived-mode-p 'org-mode)
11604 (not org-refile-use-cache)
11605 (not no-exclude))
11606 (org-map-tree
11607 (lambda()
11608 (setq excluded-entries
11609 (append excluded-entries (list (org-get-heading t t)))))))
11610 (setq org-refile-target-table
11611 (org-refile-get-targets default-buffer excluded-entries)))
11612 (unless org-refile-target-table
11613 (error "No refile targets"))
11614 (let* ((cbuf (current-buffer))
11615 (partial-completion-mode nil)
11616 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11617 (cfunc (if (and org-refile-use-outline-path
11618 org-outline-path-complete-in-steps)
11619 'org-olpath-completing-read
11620 'org-icompleting-read))
11621 (extra (if org-refile-use-outline-path "/" ""))
11622 (cbnex (concat (buffer-name) extra))
11623 (filename (and cfn (expand-file-name cfn)))
11624 (tbl (mapcar
11625 (lambda (x)
11626 (if (and (not (member org-refile-use-outline-path
11627 '(file full-file-path)))
11628 (not (equal filename (nth 1 x))))
11629 (cons (concat (car x) extra " ("
11630 (file-name-nondirectory (nth 1 x)) ")")
11631 (cdr x))
11632 (cons (concat (car x) extra) (cdr x))))
11633 org-refile-target-table))
11634 (completion-ignore-case t)
11635 cdef
11636 (prompt (concat prompt
11637 (or (and (car org-refile-history)
11638 (concat " (default " (car org-refile-history) ")"))
11639 (and (assoc cbnex tbl) (setq cdef cbnex)
11640 (concat " (default " cbnex ")"))) ": "))
11641 pa answ parent-target child parent old-hist)
11642 (setq old-hist org-refile-history)
11643 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11644 nil 'org-refile-history (or cdef (car org-refile-history))))
11645 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11646 (org-refile-check-position pa)
11647 (if pa
11648 (progn
11649 (when (or (not org-refile-history)
11650 (not (eq old-hist org-refile-history))
11651 (not (equal (car pa) (car org-refile-history))))
11652 (setq org-refile-history
11653 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11654 org-refile-history
11655 (cdr org-refile-history))))
11656 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11657 (pop org-refile-history)))
11659 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11660 (progn
11661 (setq parent (match-string 1 answ)
11662 child (match-string 2 answ))
11663 (setq parent-target (or (assoc parent tbl)
11664 (assoc (concat parent "/") tbl)))
11665 (when (and parent-target
11666 (or (eq new-nodes t)
11667 (and (eq new-nodes 'confirm)
11668 (y-or-n-p (format "Create new node \"%s\"? "
11669 child)))))
11670 (org-refile-new-child parent-target child)))
11671 (error "Invalid target location")))))
11673 (declare-function org-string-nw-p "org-macs" (s))
11674 (defun org-refile-check-position (refile-pointer)
11675 "Check if the refile pointer matches the headline to which it points."
11676 (let* ((file (nth 1 refile-pointer))
11677 (re (nth 2 refile-pointer))
11678 (pos (nth 3 refile-pointer))
11679 buffer)
11680 (if (and (not (markerp pos)) (not file))
11681 (error "Please save the buffer to a file before refiling")
11682 (when (org-string-nw-p re)
11683 (setq buffer (if (markerp pos)
11684 (marker-buffer pos)
11685 (or (find-buffer-visiting file)
11686 (find-file-noselect file))))
11687 (with-current-buffer buffer
11688 (save-excursion
11689 (save-restriction
11690 (widen)
11691 (goto-char pos)
11692 (beginning-of-line 1)
11693 (unless (org-looking-at-p re)
11694 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11696 (defun org-refile-new-child (parent-target child)
11697 "Use refile target PARENT-TARGET to add new CHILD below it."
11698 (unless parent-target
11699 (error "Cannot find parent for new node"))
11700 (let ((file (nth 1 parent-target))
11701 (pos (nth 3 parent-target))
11702 level)
11703 (with-current-buffer (or (find-buffer-visiting file)
11704 (find-file-noselect file))
11705 (save-excursion
11706 (save-restriction
11707 (widen)
11708 (if pos
11709 (goto-char pos)
11710 (goto-char (point-max))
11711 (if (not (bolp)) (newline)))
11712 (when (looking-at org-outline-regexp)
11713 (setq level (funcall outline-level))
11714 (org-end-of-subtree t t))
11715 (org-back-over-empty-lines)
11716 (insert "\n" (make-string
11717 (if pos (org-get-valid-level level 1) 1) ?*)
11718 " " child "\n")
11719 (beginning-of-line 0)
11720 (list (concat (car parent-target) "/" child) file "" (point)))))))
11722 (defun org-olpath-completing-read (prompt collection &rest args)
11723 "Read an outline path like a file name."
11724 (let ((thetable collection)
11725 (org-completion-use-ido nil) ; does not work with ido.
11726 (org-completion-use-iswitchb nil)) ; or iswitchb
11727 (apply
11728 'org-icompleting-read prompt
11729 (lambda (string predicate &optional flag)
11730 (let (rtn r f (l (length string)))
11731 (cond
11732 ((eq flag nil)
11733 ;; try completion
11734 (try-completion string thetable))
11735 ((eq flag t)
11736 ;; all-completions
11737 (setq rtn (all-completions string thetable predicate))
11738 (mapcar
11739 (lambda (x)
11740 (setq r (substring x l))
11741 (if (string-match " ([^)]*)$" x)
11742 (setq f (match-string 0 x))
11743 (setq f ""))
11744 (if (string-match "/" r)
11745 (concat string (substring r 0 (match-end 0)) f)
11747 rtn))
11748 ((eq flag 'lambda)
11749 ;; exact match?
11750 (assoc string thetable)))))
11751 args)))
11753 ;;;; Dynamic blocks
11755 (defun org-find-dblock (name)
11756 "Find the first dynamic block with name NAME in the buffer.
11757 If not found, stay at current position and return nil."
11758 (let ((case-fold-search t) pos)
11759 (save-excursion
11760 (goto-char (point-min))
11761 (setq pos (and (re-search-forward
11762 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11763 (match-beginning 0))))
11764 (if pos (goto-char pos))
11765 pos))
11767 (defconst org-dblock-start-re
11768 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11769 "Matches the start line of a dynamic block, with parameters.")
11771 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11772 "Matches the end of a dynamic block.")
11774 (defun org-create-dblock (plist)
11775 "Create a dynamic block section, with parameters taken from PLIST.
11776 PLIST must contain a :name entry which is used as name of the block."
11777 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11778 (end-of-line 1)
11779 (newline))
11780 (let ((col (current-column))
11781 (name (plist-get plist :name)))
11782 (insert "#+BEGIN: " name)
11783 (while plist
11784 (if (eq (car plist) :name)
11785 (setq plist (cddr plist))
11786 (insert " " (prin1-to-string (pop plist)))))
11787 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11788 (beginning-of-line -2)))
11790 (defun org-prepare-dblock ()
11791 "Prepare dynamic block for refresh.
11792 This empties the block, puts the cursor at the insert position and returns
11793 the property list including an extra property :name with the block name."
11794 (unless (looking-at org-dblock-start-re)
11795 (error "Not at a dynamic block"))
11796 (let* ((begdel (1+ (match-end 0)))
11797 (name (org-no-properties (match-string 1)))
11798 (params (append (list :name name)
11799 (read (concat "(" (match-string 3) ")")))))
11800 (save-excursion
11801 (beginning-of-line 1)
11802 (skip-chars-forward " \t")
11803 (setq params (plist-put params :indentation-column (current-column))))
11804 (unless (re-search-forward org-dblock-end-re nil t)
11805 (error "Dynamic block not terminated"))
11806 (setq params
11807 (append params
11808 (list :content (buffer-substring
11809 begdel (match-beginning 0)))))
11810 (delete-region begdel (match-beginning 0))
11811 (goto-char begdel)
11812 (open-line 1)
11813 params))
11815 (defun org-map-dblocks (&optional command)
11816 "Apply COMMAND to all dynamic blocks in the current buffer.
11817 If COMMAND is not given, use `org-update-dblock'."
11818 (let ((cmd (or command 'org-update-dblock)))
11819 (save-excursion
11820 (goto-char (point-min))
11821 (while (re-search-forward org-dblock-start-re nil t)
11822 (goto-char (match-beginning 0))
11823 (save-excursion
11824 (condition-case nil
11825 (funcall cmd)
11826 (error (message "Error during update of dynamic block"))))
11827 (unless (re-search-forward org-dblock-end-re nil t)
11828 (error "Dynamic block not terminated"))))))
11830 (defun org-dblock-update (&optional arg)
11831 "User command for updating dynamic blocks.
11832 Update the dynamic block at point. With prefix ARG, update all dynamic
11833 blocks in the buffer."
11834 (interactive "P")
11835 (if arg
11836 (org-update-all-dblocks)
11837 (or (looking-at org-dblock-start-re)
11838 (org-beginning-of-dblock))
11839 (org-update-dblock)))
11841 (defun org-update-dblock ()
11842 "Update the dynamic block at point.
11843 This means to empty the block, parse for parameters and then call
11844 the correct writing function."
11845 (interactive)
11846 (save-window-excursion
11847 (let* ((pos (point))
11848 (line (org-current-line))
11849 (params (org-prepare-dblock))
11850 (name (plist-get params :name))
11851 (indent (plist-get params :indentation-column))
11852 (cmd (intern (concat "org-dblock-write:" name))))
11853 (message "Updating dynamic block `%s' at line %d..." name line)
11854 (funcall cmd params)
11855 (message "Updating dynamic block `%s' at line %d...done" name line)
11856 (goto-char pos)
11857 (when (and indent (> indent 0))
11858 (setq indent (make-string indent ?\ ))
11859 (save-excursion
11860 (org-beginning-of-dblock)
11861 (forward-line 1)
11862 (while (not (looking-at org-dblock-end-re))
11863 (insert indent)
11864 (beginning-of-line 2))
11865 (when (looking-at org-dblock-end-re)
11866 (and (looking-at "[ \t]+")
11867 (replace-match ""))
11868 (insert indent)))))))
11870 (defun org-beginning-of-dblock ()
11871 "Find the beginning of the dynamic block at point.
11872 Error if there is no such block at point."
11873 (let ((pos (point))
11874 beg)
11875 (end-of-line 1)
11876 (if (and (re-search-backward org-dblock-start-re nil t)
11877 (setq beg (match-beginning 0))
11878 (re-search-forward org-dblock-end-re nil t)
11879 (> (match-end 0) pos))
11880 (goto-char beg)
11881 (goto-char pos)
11882 (error "Not in a dynamic block"))))
11884 (defun org-update-all-dblocks ()
11885 "Update all dynamic blocks in the buffer.
11886 This function can be used in a hook."
11887 (interactive)
11888 (when (derived-mode-p 'org-mode)
11889 (org-map-dblocks 'org-update-dblock)))
11892 ;;;; Completion
11894 (defun org-get-export-keywords ()
11895 "Return a list of all currently understood export keywords.
11896 Export keywords include options, block names, attributes and
11897 keywords relative to each registered export back-end."
11898 (delq nil
11899 (let (keywords)
11900 (mapc
11901 (lambda (back-end)
11902 (let ((props (cdr back-end)))
11903 ;; Back-end name (for keywords, like #+LATEX:)
11904 (push (upcase (symbol-name (car back-end))) keywords)
11905 ;; Back-end options.
11906 (mapc (lambda (option) (push (cadr option) keywords))
11907 (plist-get (cdr back-end) :options-alist))))
11908 (org-bound-and-true-p org-export-registered-backends))
11909 keywords)))
11911 (defconst org-options-keywords
11912 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11913 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11914 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11915 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11916 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11918 (defcustom org-structure-template-alist
11919 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11920 "<src lang=\"?\">\n\n</src>")
11921 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11922 "<example>\n?\n</example>")
11923 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11924 "<quote>\n?\n</quote>")
11925 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11926 "<verse>\n?\n</verse>")
11927 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11928 "<verbatim>\n?\n</verbatim>")
11929 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11930 "<center>\n?\n</center>")
11931 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11932 "<literal style=\"latex\">\n?\n</literal>")
11933 ("L" "#+LaTeX: "
11934 "<literal style=\"latex\">?</literal>")
11935 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11936 "<literal style=\"html\">\n?\n</literal>")
11937 ("H" "#+HTML: "
11938 "<literal style=\"html\">?</literal>")
11939 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11940 ("A" "#+ASCII: ")
11941 ("i" "#+INDEX: ?"
11942 "#+INDEX: ?")
11943 ("I" "#+INCLUDE: %file ?"
11944 "<include file=%file markup=\"?\">"))
11945 "Structure completion elements.
11946 This is a list of abbreviation keys and values. The value gets inserted
11947 if you type `<' followed by the key and then press the completion key,
11948 usually `M-TAB'. %file will be replaced by a file name after prompting
11949 for the file using completion. The cursor will be placed at the position
11950 of the `?` in the template.
11951 There are two templates for each key, the first uses the original Org syntax,
11952 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11953 the default when the /org-mtags.el/ module has been loaded. See also the
11954 variable `org-mtags-prefer-muse-templates'."
11955 :group 'org-completion
11956 :type '(repeat
11957 (string :tag "Key")
11958 (string :tag "Template")
11959 (string :tag "Muse Template")))
11961 (defun org-try-structure-completion ()
11962 "Try to complete a structure template before point.
11963 This looks for strings like \"<e\" on an otherwise empty line and
11964 expands them."
11965 (let ((l (buffer-substring (point-at-bol) (point)))
11967 (when (and (looking-at "[ \t]*$")
11968 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11969 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11970 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11971 (match-beginning 1)) a)
11972 t)))
11974 (defun org-complete-expand-structure-template (start cell)
11975 "Expand a structure template."
11976 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11977 (rpl (nth (if musep 2 1) cell))
11978 (ind ""))
11979 (delete-region start (point))
11980 (when (string-match "\\`#\\+" rpl)
11981 (cond
11982 ((bolp))
11983 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11984 (setq ind (buffer-substring (point-at-bol) (point))))
11985 (t (newline))))
11986 (setq start (point))
11987 (if (string-match "%file" rpl)
11988 (setq rpl (replace-match
11989 (concat
11990 "\""
11991 (save-match-data
11992 (abbreviate-file-name (read-file-name "Include file: ")))
11993 "\"")
11994 t t rpl)))
11995 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11996 (concat "\n" ind)))
11997 (insert rpl)
11998 (if (re-search-backward "\\?" start t) (delete-char 1))))
12000 ;;;; TODO, DEADLINE, Comments
12002 (defun org-toggle-comment ()
12003 "Change the COMMENT state of an entry."
12004 (interactive)
12005 (save-excursion
12006 (org-back-to-heading)
12007 (let (case-fold-search)
12008 (cond
12009 ((looking-at (format org-heading-keyword-regexp-format
12010 org-comment-string))
12011 (goto-char (match-end 1))
12012 (looking-at (concat " +" org-comment-string))
12013 (replace-match "" t t)
12014 (when (eolp) (insert " ")))
12015 ((looking-at org-outline-regexp)
12016 (goto-char (match-end 0))
12017 (insert org-comment-string " "))))))
12019 (defvar org-last-todo-state-is-todo nil
12020 "This is non-nil when the last TODO state change led to a TODO state.
12021 If the last change removed the TODO tag or switched to DONE, then
12022 this is nil.")
12024 (defvar org-setting-tags nil) ; dynamically skipped
12026 (defvar org-todo-setup-filter-hook nil
12027 "Hook for functions that pre-filter todo specs.
12028 Each function takes a todo spec and returns either nil or the spec
12029 transformed into canonical form." )
12031 (defvar org-todo-get-default-hook nil
12032 "Hook for functions that get a default item for todo.
12033 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12034 nil or a string to be used for the todo mark." )
12036 (defvar org-agenda-headline-snapshot-before-repeat)
12038 (defun org-current-effective-time ()
12039 "Return current time adjusted for `org-extend-today-until' variable."
12040 (let* ((ct (org-current-time))
12041 (dct (decode-time ct))
12042 (ct1
12043 (cond
12044 (org-use-last-clock-out-time-as-effective-time
12045 (or (org-clock-get-last-clock-out-time) ct))
12046 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12047 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12048 (t ct))))
12049 ct1))
12051 (defun org-todo-yesterday (&optional arg)
12052 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12053 (interactive "P")
12054 (if (eq major-mode 'org-agenda-mode)
12055 (apply 'org-agenda-todo-yesterday arg)
12056 (let* ((hour (third (decode-time
12057 (org-current-time))))
12058 (org-extend-today-until (1+ hour)))
12059 (org-todo arg))))
12061 (defvar org-block-entry-blocking ""
12062 "First entry preventing the TODO state change.")
12064 (defun org-todo (&optional arg)
12065 "Change the TODO state of an item.
12066 The state of an item is given by a keyword at the start of the heading,
12067 like
12068 *** TODO Write paper
12069 *** DONE Call mom
12071 The different keywords are specified in the variable `org-todo-keywords'.
12072 By default the available states are \"TODO\" and \"DONE\".
12073 So for this example: when the item starts with TODO, it is changed to DONE.
12074 When it starts with DONE, the DONE is removed. And when neither TODO nor
12075 DONE are present, add TODO at the beginning of the heading.
12077 With \\[universal-argument] prefix arg, use completion to determine the new \
12078 state.
12079 With numeric prefix arg, switch to that state.
12080 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12081 keywords (nextset).
12082 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12083 With a numeric prefix arg of 0, inhibit note taking for the change.
12085 For calling through lisp, arg is also interpreted in the following way:
12086 'none -> empty state
12087 \"\"(empty string) -> switch to empty state
12088 'done -> switch to DONE
12089 'nextset -> switch to the next set of keywords
12090 'previousset -> switch to the previous set of keywords
12091 \"WAITING\" -> switch to the specified keyword, but only if it
12092 really is a member of `org-todo-keywords'."
12093 (interactive "P")
12094 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12095 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12096 'region-start-level 'region))
12097 org-loop-over-headlines-in-active-region)
12098 (org-map-entries
12099 `(org-todo ,arg)
12100 org-loop-over-headlines-in-active-region
12101 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12102 (if (equal arg '(16)) (setq arg 'nextset))
12103 (let ((org-blocker-hook org-blocker-hook)
12104 commentp
12105 case-fold-search)
12106 (when (equal arg '(64))
12107 (setq arg nil org-blocker-hook nil))
12108 (when (and org-blocker-hook
12109 (or org-inhibit-blocking
12110 (org-entry-get nil "NOBLOCKING")))
12111 (setq org-blocker-hook nil))
12112 (save-excursion
12113 (catch 'exit
12114 (org-back-to-heading t)
12115 (when (looking-at (concat "^\\*+ " org-comment-string))
12116 (org-toggle-comment)
12117 (setq commentp t))
12118 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12119 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12120 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12121 (let* ((match-data (match-data))
12122 (startpos (point-at-bol))
12123 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12124 (org-log-done org-log-done)
12125 (org-log-repeat org-log-repeat)
12126 (org-todo-log-states org-todo-log-states)
12127 (org-inhibit-logging
12128 (if (equal arg 0)
12129 (progn (setq arg nil) 'note) org-inhibit-logging))
12130 (this (match-string 1))
12131 (hl-pos (match-beginning 0))
12132 (head (org-get-todo-sequence-head this))
12133 (ass (assoc head org-todo-kwd-alist))
12134 (interpret (nth 1 ass))
12135 (done-word (nth 3 ass))
12136 (final-done-word (nth 4 ass))
12137 (org-last-state (or this ""))
12138 (completion-ignore-case t)
12139 (member (member this org-todo-keywords-1))
12140 (tail (cdr member))
12141 (org-state (cond
12142 ((and org-todo-key-trigger
12143 (or (and (equal arg '(4))
12144 (eq org-use-fast-todo-selection 'prefix))
12145 (and (not arg) org-use-fast-todo-selection
12146 (not (eq org-use-fast-todo-selection
12147 'prefix)))))
12148 ;; Use fast selection
12149 (org-fast-todo-selection))
12150 ((and (equal arg '(4))
12151 (or (not org-use-fast-todo-selection)
12152 (not org-todo-key-trigger)))
12153 ;; Read a state with completion
12154 (org-icompleting-read
12155 "State: " (mapcar 'list org-todo-keywords-1)
12156 nil t))
12157 ((eq arg 'right)
12158 (if this
12159 (if tail (car tail) nil)
12160 (car org-todo-keywords-1)))
12161 ((eq arg 'left)
12162 (if (equal member org-todo-keywords-1)
12164 (if this
12165 (nth (- (length org-todo-keywords-1)
12166 (length tail) 2)
12167 org-todo-keywords-1)
12168 (org-last org-todo-keywords-1))))
12169 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12170 (setq arg nil))) ; hack to fall back to cycling
12171 (arg
12172 ;; user or caller requests a specific state
12173 (cond
12174 ((equal arg "") nil)
12175 ((eq arg 'none) nil)
12176 ((eq arg 'done) (or done-word (car org-done-keywords)))
12177 ((eq arg 'nextset)
12178 (or (car (cdr (member head org-todo-heads)))
12179 (car org-todo-heads)))
12180 ((eq arg 'previousset)
12181 (let ((org-todo-heads (reverse org-todo-heads)))
12182 (or (car (cdr (member head org-todo-heads)))
12183 (car org-todo-heads))))
12184 ((car (member arg org-todo-keywords-1)))
12185 ((stringp arg)
12186 (error "State `%s' not valid in this file" arg))
12187 ((nth (1- (prefix-numeric-value arg))
12188 org-todo-keywords-1))))
12189 ((null member) (or head (car org-todo-keywords-1)))
12190 ((equal this final-done-word) nil) ;; -> make empty
12191 ((null tail) nil) ;; -> first entry
12192 ((memq interpret '(type priority))
12193 (if (eq this-command last-command)
12194 (car tail)
12195 (if (> (length tail) 0)
12196 (or done-word (car org-done-keywords))
12197 nil)))
12199 (car tail))))
12200 (org-state (or
12201 (run-hook-with-args-until-success
12202 'org-todo-get-default-hook org-state org-last-state)
12203 org-state))
12204 (next (if org-state (concat " " org-state " ") " "))
12205 (change-plist (list :type 'todo-state-change :from this :to org-state
12206 :position startpos))
12207 dolog now-done-p)
12208 (when org-blocker-hook
12209 (setq org-last-todo-state-is-todo
12210 (not (member this org-done-keywords)))
12211 (unless (save-excursion
12212 (save-match-data
12213 (org-with-wide-buffer
12214 (run-hook-with-args-until-failure
12215 'org-blocker-hook change-plist))))
12216 (if (org-called-interactively-p 'interactive)
12217 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12218 this org-state org-block-entry-blocking)
12219 ;; fail silently
12220 (message "TODO state change from %s to %s blocked (by \"%s\")"
12221 this org-state org-block-entry-blocking)
12222 (throw 'exit nil))))
12223 (store-match-data match-data)
12224 (replace-match next t t)
12225 (unless (pos-visible-in-window-p hl-pos)
12226 (message "TODO state changed to %s" (org-trim next)))
12227 (unless head
12228 (setq head (org-get-todo-sequence-head org-state)
12229 ass (assoc head org-todo-kwd-alist)
12230 interpret (nth 1 ass)
12231 done-word (nth 3 ass)
12232 final-done-word (nth 4 ass)))
12233 (when (memq arg '(nextset previousset))
12234 (message "Keyword-Set %d/%d: %s"
12235 (- (length org-todo-sets) -1
12236 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12237 (length org-todo-sets)
12238 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12239 (setq org-last-todo-state-is-todo
12240 (not (member org-state org-done-keywords)))
12241 (setq now-done-p (and (member org-state org-done-keywords)
12242 (not (member this org-done-keywords))))
12243 (and logging (org-local-logging logging))
12244 (when (and (or org-todo-log-states org-log-done)
12245 (not (eq org-inhibit-logging t))
12246 (not (memq arg '(nextset previousset))))
12247 ;; we need to look at recording a time and note
12248 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12249 (nth 2 (assoc this org-todo-log-states))))
12250 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12251 (setq dolog 'time))
12252 (when (and org-state
12253 (member org-state org-not-done-keywords)
12254 (not (member this org-not-done-keywords)))
12255 ;; This is now a todo state and was not one before
12256 ;; If there was a CLOSED time stamp, get rid of it.
12257 (org-add-planning-info nil nil 'closed))
12258 (when (and now-done-p org-log-done)
12259 ;; It is now done, and it was not done before
12260 (org-add-planning-info 'closed (org-current-effective-time))
12261 (if (and (not dolog) (eq 'note org-log-done))
12262 (org-add-log-setup 'done org-state this 'findpos 'note)))
12263 (when (and org-state dolog)
12264 ;; This is a non-nil state, and we need to log it
12265 (org-add-log-setup 'state org-state this 'findpos dolog)))
12266 ;; Fixup tag positioning
12267 (org-todo-trigger-tag-changes org-state)
12268 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12269 (when org-provide-todo-statistics
12270 (org-update-parent-todo-statistics))
12271 (run-hooks 'org-after-todo-state-change-hook)
12272 (if (and arg (not (member org-state org-done-keywords)))
12273 (setq head (org-get-todo-sequence-head org-state)))
12274 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12275 ;; Do we need to trigger a repeat?
12276 (when now-done-p
12277 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12278 ;; This is for the agenda, take a snapshot of the headline.
12279 (save-match-data
12280 (setq org-agenda-headline-snapshot-before-repeat
12281 (org-get-heading))))
12282 (org-auto-repeat-maybe org-state))
12283 ;; Fixup cursor location if close to the keyword
12284 (if (and (outline-on-heading-p)
12285 (not (bolp))
12286 (save-excursion (beginning-of-line 1)
12287 (looking-at org-todo-line-regexp))
12288 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12289 (progn
12290 (goto-char (or (match-end 2) (match-end 1)))
12291 (and (looking-at " ") (just-one-space))))
12292 (when org-trigger-hook
12293 (save-excursion
12294 (run-hook-with-args 'org-trigger-hook change-plist)))
12295 (when commentp (org-toggle-comment))))))))
12297 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12298 "Block turning an entry into a TODO, using the hierarchy.
12299 This checks whether the current task should be blocked from state
12300 changes. Such blocking occurs when:
12302 1. The task has children which are not all in a completed state.
12304 2. A task has a parent with the property :ORDERED:, and there
12305 are siblings prior to the current task with incomplete
12306 status.
12308 3. The parent of the task is blocked because it has siblings that should
12309 be done first, or is child of a block grandparent TODO entry."
12311 (if (not org-enforce-todo-dependencies)
12312 t ; if locally turned off don't block
12313 (catch 'dont-block
12314 ;; If this is not a todo state change, or if this entry is already DONE,
12315 ;; do not block
12316 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12317 (member (plist-get change-plist :from)
12318 (cons 'done org-done-keywords))
12319 (member (plist-get change-plist :to)
12320 (cons 'todo org-not-done-keywords))
12321 (not (plist-get change-plist :to)))
12322 (throw 'dont-block t))
12323 ;; If this task has children, and any are undone, it's blocked
12324 (save-excursion
12325 (org-back-to-heading t)
12326 (let ((this-level (funcall outline-level)))
12327 (outline-next-heading)
12328 (let ((child-level (funcall outline-level)))
12329 (while (and (not (eobp))
12330 (> child-level this-level))
12331 ;; this todo has children, check whether they are all
12332 ;; completed
12333 (if (and (not (org-entry-is-done-p))
12334 (org-entry-is-todo-p))
12335 (progn (setq org-block-entry-blocking (org-get-heading))
12336 (throw 'dont-block nil)))
12337 (outline-next-heading)
12338 (setq child-level (funcall outline-level))))))
12339 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12340 ;; any previous siblings are undone, it's blocked
12341 (save-excursion
12342 (org-back-to-heading t)
12343 (let* ((pos (point))
12344 (parent-pos (and (org-up-heading-safe) (point))))
12345 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12346 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12347 (forward-line 1)
12348 (re-search-forward org-not-done-heading-regexp pos t))
12349 (setq org-block-entry-blocking (match-string 0))
12350 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12351 ;; Search further up the hierarchy, to see if an ancestor is blocked
12352 (while t
12353 (goto-char parent-pos)
12354 (if (not (looking-at org-not-done-heading-regexp))
12355 (throw 'dont-block t)) ; do not block, parent is not a TODO
12356 (setq pos (point))
12357 (setq parent-pos (and (org-up-heading-safe) (point)))
12358 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12359 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12360 (forward-line 1)
12361 (re-search-forward org-not-done-heading-regexp pos t)
12362 (setq org-block-entry-blocking (org-get-heading)))
12363 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12365 (defcustom org-track-ordered-property-with-tag nil
12366 "Should the ORDERED property also be shown as a tag?
12367 The ORDERED property decides if an entry should require subtasks to be
12368 completed in sequence. Since a property is not very visible, setting
12369 this option means that toggling the ORDERED property with the command
12370 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12371 not relevant for the behavior, but it makes things more visible.
12373 Note that toggling the tag with tags commands will not change the property
12374 and therefore not influence behavior!
12376 This can be t, meaning the tag ORDERED should be used, It can also be a
12377 string to select a different tag for this task."
12378 :group 'org-todo
12379 :type '(choice
12380 (const :tag "No tracking" nil)
12381 (const :tag "Track with ORDERED tag" t)
12382 (string :tag "Use other tag")))
12384 (defun org-toggle-ordered-property ()
12385 "Toggle the ORDERED property of the current entry.
12386 For better visibility, you can track the value of this property with a tag.
12387 See variable `org-track-ordered-property-with-tag'."
12388 (interactive)
12389 (let* ((t1 org-track-ordered-property-with-tag)
12390 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12391 (save-excursion
12392 (org-back-to-heading)
12393 (if (org-entry-get nil "ORDERED")
12394 (progn
12395 (org-delete-property "ORDERED" "PROPERTIES")
12396 (and tag (org-toggle-tag tag 'off))
12397 (message "Subtasks can be completed in arbitrary order"))
12398 (org-entry-put nil "ORDERED" "t")
12399 (and tag (org-toggle-tag tag 'on))
12400 (message "Subtasks must be completed in sequence")))))
12402 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12403 (defun org-block-todo-from-checkboxes (change-plist)
12404 "Block turning an entry into a TODO, using checkboxes.
12405 This checks whether the current task should be blocked from state
12406 changes because there are unchecked boxes in this entry."
12407 (if (not org-enforce-todo-checkbox-dependencies)
12408 t ; if locally turned off don't block
12409 (catch 'dont-block
12410 ;; If this is not a todo state change, or if this entry is already DONE,
12411 ;; do not block
12412 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12413 (member (plist-get change-plist :from)
12414 (cons 'done org-done-keywords))
12415 (member (plist-get change-plist :to)
12416 (cons 'todo org-not-done-keywords))
12417 (not (plist-get change-plist :to)))
12418 (throw 'dont-block t))
12419 ;; If this task has checkboxes that are not checked, it's blocked
12420 (save-excursion
12421 (org-back-to-heading t)
12422 (let ((beg (point)) end)
12423 (outline-next-heading)
12424 (setq end (point))
12425 (goto-char beg)
12426 (if (org-list-search-forward
12427 (concat (org-item-beginning-re)
12428 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12429 "\\[[- ]\\]")
12430 end t)
12431 (progn
12432 (if (boundp 'org-blocked-by-checkboxes)
12433 (setq org-blocked-by-checkboxes t))
12434 (throw 'dont-block nil)))))
12435 t))) ; do not block
12437 (defun org-entry-blocked-p ()
12438 "Is the current entry blocked?"
12439 (org-with-silent-modifications
12440 (if (org-entry-get nil "NOBLOCKING")
12441 nil ;; Never block this entry
12442 (not (run-hook-with-args-until-failure
12443 'org-blocker-hook
12444 (list :type 'todo-state-change
12445 :position (point)
12446 :from 'todo
12447 :to 'done))))))
12449 (defun org-update-statistics-cookies (all)
12450 "Update the statistics cookie, either from TODO or from checkboxes.
12451 This should be called with the cursor in a line with a statistics cookie."
12452 (interactive "P")
12453 (if all
12454 (progn
12455 (org-update-checkbox-count 'all)
12456 (org-map-entries 'org-update-parent-todo-statistics))
12457 (if (not (org-at-heading-p))
12458 (org-update-checkbox-count)
12459 (let ((pos (point-marker))
12460 end l1 l2)
12461 (ignore-errors (org-back-to-heading t))
12462 (if (not (org-at-heading-p))
12463 (org-update-checkbox-count)
12464 (setq l1 (org-outline-level))
12465 (setq end (save-excursion
12466 (outline-next-heading)
12467 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12468 (point)))
12469 (if (and (save-excursion
12470 (re-search-forward
12471 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12472 (not (save-excursion (re-search-forward
12473 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12474 (org-update-checkbox-count)
12475 (if (and l2 (> l2 l1))
12476 (progn
12477 (goto-char end)
12478 (org-update-parent-todo-statistics))
12479 (goto-char pos)
12480 (beginning-of-line 1)
12481 (while (re-search-forward
12482 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12483 (point-at-eol) t)
12484 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12485 (goto-char pos)
12486 (move-marker pos nil)))))
12488 (defvar org-entry-property-inherited-from) ;; defined below
12489 (defun org-update-parent-todo-statistics ()
12490 "Update any statistics cookie in the parent of the current headline.
12491 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12492 the entire subtree and this will travel up the hierarchy and update
12493 statistics everywhere."
12494 (let* ((prop (save-excursion (org-up-heading-safe)
12495 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12496 (recursive (or (not org-hierarchical-todo-statistics)
12497 (and prop (string-match "\\<recursive\\>" prop))))
12498 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12500 (first t)
12501 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12502 level ltoggle l1 new ndel
12503 (cnt-all 0) (cnt-done 0) is-percent kwd
12504 checkbox-beg ov ovs ove cookie-present)
12505 (catch 'exit
12506 (save-excursion
12507 (beginning-of-line 1)
12508 (setq ltoggle (funcall outline-level))
12509 ;; Three situations are to consider:
12511 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12512 ;; to the top-level ancestor on the headline;
12514 ;; 2. If parent has "recursive" property, repeat up to the
12515 ;; headline setting that property, taking inheritance into
12516 ;; account;
12518 ;; 3. Else, move up to direct parent and proceed only once.
12519 (while (and (setq level (org-up-heading-safe))
12520 (or recursive first)
12521 (>= (point) lim))
12522 (setq first nil cookie-present nil)
12523 (unless (and level
12524 (not (string-match
12525 "\\<checkbox\\>"
12526 (downcase (or (org-entry-get nil "COOKIE_DATA")
12527 "")))))
12528 (throw 'exit nil))
12529 (while (re-search-forward box-re (point-at-eol) t)
12530 (setq cnt-all 0 cnt-done 0 cookie-present t)
12531 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12532 (save-match-data
12533 (unless (outline-next-heading) (throw 'exit nil))
12534 (while (and (looking-at org-complex-heading-regexp)
12535 (> (setq l1 (length (match-string 1))) level))
12536 (setq kwd (and (or recursive (= l1 ltoggle))
12537 (match-string 2)))
12538 (if (or (eq org-provide-todo-statistics 'all-headlines)
12539 (and (listp org-provide-todo-statistics)
12540 (or (member kwd org-provide-todo-statistics)
12541 (member kwd org-done-keywords))))
12542 (setq cnt-all (1+ cnt-all))
12543 (if (eq org-provide-todo-statistics t)
12544 (and kwd (setq cnt-all (1+ cnt-all)))))
12545 (and (member kwd org-done-keywords)
12546 (setq cnt-done (1+ cnt-done)))
12547 (outline-next-heading)))
12548 (setq new
12549 (if is-percent
12550 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12551 (format "[%d/%d]" cnt-done cnt-all))
12552 ndel (- (match-end 0) checkbox-beg))
12553 ;; handle overlays when updating cookie from column view
12554 (when (setq ov (car (overlays-at checkbox-beg)))
12555 (setq ovs (overlay-start ov) ove (overlay-end ov))
12556 (delete-overlay ov))
12557 (goto-char checkbox-beg)
12558 (insert new)
12559 (delete-region (point) (+ (point) ndel))
12560 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12561 (when ov (move-overlay ov ovs ove)))
12562 (when cookie-present
12563 (run-hook-with-args 'org-after-todo-statistics-hook
12564 cnt-done (- cnt-all cnt-done))))))
12565 (run-hooks 'org-todo-statistics-hook)))
12567 (defvar org-after-todo-statistics-hook nil
12568 "Hook that is called after a TODO statistics cookie has been updated.
12569 Each function is called with two arguments: the number of not-done entries
12570 and the number of done entries.
12572 For example, the following function, when added to this hook, will switch
12573 an entry to DONE when all children are done, and back to TODO when new
12574 entries are set to a TODO status. Note that this hook is only called
12575 when there is a statistics cookie in the headline!
12577 (defun org-summary-todo (n-done n-not-done)
12578 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12579 (let (org-log-done org-log-states) ; turn off logging
12580 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12583 (defvar org-todo-statistics-hook nil
12584 "Hook that is run whenever Org thinks TODO statistics should be updated.
12585 This hook runs even if there is no statistics cookie present, in which case
12586 `org-after-todo-statistics-hook' would not run.")
12588 (defun org-todo-trigger-tag-changes (state)
12589 "Apply the changes defined in `org-todo-state-tags-triggers'."
12590 (let ((l org-todo-state-tags-triggers)
12591 changes)
12592 (when (or (not state) (equal state ""))
12593 (setq changes (append changes (cdr (assoc "" l)))))
12594 (when (and (stringp state) (> (length state) 0))
12595 (setq changes (append changes (cdr (assoc state l)))))
12596 (when (member state org-not-done-keywords)
12597 (setq changes (append changes (cdr (assoc 'todo l)))))
12598 (when (member state org-done-keywords)
12599 (setq changes (append changes (cdr (assoc 'done l)))))
12600 (dolist (c changes)
12601 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12603 (defun org-local-logging (value)
12604 "Get logging settings from a property VALUE."
12605 (let* (words w a)
12606 ;; directly set the variables, they are already local.
12607 (setq org-log-done nil
12608 org-log-repeat nil
12609 org-todo-log-states nil)
12610 (setq words (org-split-string value))
12611 (while (setq w (pop words))
12612 (cond
12613 ((setq a (assoc w org-startup-options))
12614 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12615 (set (nth 1 a) (nth 2 a))))
12616 ((setq a (org-extract-log-state-settings w))
12617 (and (member (car a) org-todo-keywords-1)
12618 (push a org-todo-log-states)))))))
12620 (defun org-get-todo-sequence-head (kwd)
12621 "Return the head of the TODO sequence to which KWD belongs.
12622 If KWD is not set, check if there is a text property remembering the
12623 right sequence."
12624 (let (p)
12625 (cond
12626 ((not kwd)
12627 (or (get-text-property (point-at-bol) 'org-todo-head)
12628 (progn
12629 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12630 nil (point-at-eol)))
12631 (get-text-property p 'org-todo-head))))
12632 ((not (member kwd org-todo-keywords-1))
12633 (car org-todo-keywords-1))
12634 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12636 (defun org-fast-todo-selection ()
12637 "Fast TODO keyword selection with single keys.
12638 Returns the new TODO keyword, or nil if no state change should occur."
12639 (let* ((fulltable org-todo-key-alist)
12640 (done-keywords org-done-keywords) ;; needed for the faces.
12641 (maxlen (apply 'max (mapcar
12642 (lambda (x)
12643 (if (stringp (car x)) (string-width (car x)) 0))
12644 fulltable)))
12645 (expert nil)
12646 (fwidth (+ maxlen 3 1 3))
12647 (ncol (/ (- (window-width) 4) fwidth))
12648 tg cnt e c tbl
12649 groups ingroup)
12650 (save-excursion
12651 (save-window-excursion
12652 (if expert
12653 (set-buffer (get-buffer-create " *Org todo*"))
12654 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12655 (erase-buffer)
12656 (org-set-local 'org-done-keywords done-keywords)
12657 (setq tbl fulltable cnt 0)
12658 (while (setq e (pop tbl))
12659 (cond
12660 ((equal e '(:startgroup))
12661 (push '() groups) (setq ingroup t)
12662 (when (not (= cnt 0))
12663 (setq cnt 0)
12664 (insert "\n"))
12665 (insert "{ "))
12666 ((equal e '(:endgroup))
12667 (setq ingroup nil cnt 0)
12668 (insert "}\n"))
12669 ((equal e '(:newline))
12670 (when (not (= cnt 0))
12671 (setq cnt 0)
12672 (insert "\n")
12673 (setq e (car tbl))
12674 (while (equal (car tbl) '(:newline))
12675 (insert "\n")
12676 (setq tbl (cdr tbl)))))
12678 (setq tg (car e) c (cdr e))
12679 (if ingroup (push tg (car groups)))
12680 (setq tg (org-add-props tg nil 'face
12681 (org-get-todo-face tg)))
12682 (if (and (= cnt 0) (not ingroup)) (insert " "))
12683 (insert "[" c "] " tg (make-string
12684 (- fwidth 4 (length tg)) ?\ ))
12685 (when (= (setq cnt (1+ cnt)) ncol)
12686 (insert "\n")
12687 (if ingroup (insert " "))
12688 (setq cnt 0)))))
12689 (insert "\n")
12690 (goto-char (point-min))
12691 (if (not expert) (org-fit-window-to-buffer))
12692 (message "[a-z..]:Set [SPC]:clear")
12693 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12694 (cond
12695 ((or (= c ?\C-g)
12696 (and (= c ?q) (not (rassoc c fulltable))))
12697 (setq quit-flag t))
12698 ((= c ?\ ) nil)
12699 ((setq e (rassoc c fulltable) tg (car e))
12701 (t (setq quit-flag t)))))))
12703 (defun org-entry-is-todo-p ()
12704 (member (org-get-todo-state) org-not-done-keywords))
12706 (defun org-entry-is-done-p ()
12707 (member (org-get-todo-state) org-done-keywords))
12709 (defun org-get-todo-state ()
12710 "Return the TODO keyword of the current subtree."
12711 (save-excursion
12712 (org-back-to-heading t)
12713 (and (looking-at org-todo-line-regexp)
12714 (match-end 2)
12715 (match-string 2))))
12717 (defun org-at-date-range-p (&optional inactive-ok)
12718 "Is the cursor inside a date range?"
12719 (interactive)
12720 (save-excursion
12721 (catch 'exit
12722 (let ((pos (point)))
12723 (skip-chars-backward "^[<\r\n")
12724 (skip-chars-backward "<[")
12725 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12726 (>= (match-end 0) pos)
12727 (throw 'exit t))
12728 (skip-chars-backward "^<[\r\n")
12729 (skip-chars-backward "<[")
12730 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12731 (>= (match-end 0) pos)
12732 (throw 'exit t)))
12733 nil)))
12735 (defun org-get-repeat (&optional tagline)
12736 "Check if there is a deadline/schedule with repeater in this entry."
12737 (save-match-data
12738 (save-excursion
12739 (org-back-to-heading t)
12740 (and (re-search-forward (if tagline
12741 (concat tagline "\\s-*" org-repeat-re)
12742 org-repeat-re)
12743 (org-entry-end-position) t)
12744 (match-string-no-properties 1)))))
12746 (defvar org-last-changed-timestamp)
12747 (defvar org-last-inserted-timestamp)
12748 (defvar org-log-post-message)
12749 (defvar org-log-note-purpose)
12750 (defvar org-log-note-how)
12751 (defvar org-log-note-extra)
12752 (defun org-auto-repeat-maybe (done-word)
12753 "Check if the current headline contains a repeated deadline/schedule.
12754 If yes, set TODO state back to what it was and change the base date
12755 of repeating deadline/scheduled time stamps to new date.
12756 This function is run automatically after each state change to a DONE state."
12757 ;; last-state is dynamically scoped into this function
12758 (let* ((repeat (org-get-repeat))
12759 (aa (assoc org-last-state org-todo-kwd-alist))
12760 (interpret (nth 1 aa))
12761 (head (nth 2 aa))
12762 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12763 (msg "Entry repeats: ")
12764 (org-log-done nil)
12765 (org-todo-log-states nil)
12766 re type n what ts time to-state)
12767 (when repeat
12768 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12769 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12770 org-todo-repeat-to-state))
12771 (unless (and to-state (member to-state org-todo-keywords-1))
12772 (setq to-state (if (eq interpret 'type) org-last-state head)))
12773 (org-todo to-state)
12774 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12775 (org-entry-put nil "LAST_REPEAT" (format-time-string
12776 (org-time-stamp-format t t))))
12777 (when org-log-repeat
12778 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12779 (memq 'org-add-log-note post-command-hook))
12780 ;; OK, we are already setup for some record
12781 (if (eq org-log-repeat 'note)
12782 ;; make sure we take a note, not only a time stamp
12783 (setq org-log-note-how 'note))
12784 ;; Set up for taking a record
12785 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12786 org-last-state
12787 'findpos org-log-repeat)))
12788 (org-back-to-heading t)
12789 (org-add-planning-info nil nil 'closed)
12790 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12791 org-deadline-time-regexp "\\)\\|\\("
12792 org-ts-regexp "\\)"))
12793 (while (re-search-forward
12794 re (save-excursion (outline-next-heading) (point)) t)
12795 (setq type (if (match-end 1) org-scheduled-string
12796 (if (match-end 3) org-deadline-string "Plain:"))
12797 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12798 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12799 (setq n (string-to-number (match-string 2 ts))
12800 what (match-string 3 ts))
12801 (if (equal what "w") (setq n (* n 7) what "d"))
12802 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12803 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12804 ;; Preparation, see if we need to modify the start date for the change
12805 (when (match-end 1)
12806 (setq time (save-match-data (org-time-string-to-time ts)))
12807 (cond
12808 ((equal (match-string 1 ts) ".")
12809 ;; Shift starting date to today
12810 (org-timestamp-change
12811 (- (org-today) (time-to-days time))
12812 'day))
12813 ((equal (match-string 1 ts) "+")
12814 (let ((nshiftmax 10) (nshift 0))
12815 (while (or (= nshift 0)
12816 (<= (time-to-days time)
12817 (time-to-days (current-time))))
12818 (when (= (incf nshift) nshiftmax)
12819 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12820 (error "Abort")))
12821 (org-timestamp-change n (cdr (assoc what whata)))
12822 (org-at-timestamp-p t)
12823 (setq ts (match-string 1))
12824 (setq time (save-match-data (org-time-string-to-time ts)))))
12825 (org-timestamp-change (- n) (cdr (assoc what whata)))
12826 ;; rematch, so that we have everything in place for the real shift
12827 (org-at-timestamp-p t)
12828 (setq ts (match-string 1))
12829 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12830 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12831 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12832 (setq org-log-post-message msg)
12833 (message "%s" msg))))
12835 (defun org-show-todo-tree (arg)
12836 "Make a compact tree which shows all headlines marked with TODO.
12837 The tree will show the lines where the regexp matches, and all higher
12838 headlines above the match.
12839 With a \\[universal-argument] prefix, prompt for a regexp to match.
12840 With a numeric prefix N, construct a sparse tree for the Nth element
12841 of `org-todo-keywords-1'."
12842 (interactive "P")
12843 (let ((case-fold-search nil)
12844 (kwd-re
12845 (cond ((null arg) org-not-done-regexp)
12846 ((equal arg '(4))
12847 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12848 (mapcar 'list org-todo-keywords-1))))
12849 (concat "\\("
12850 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12851 "\\)\\>")))
12852 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12853 (regexp-quote (nth (1- (prefix-numeric-value arg))
12854 org-todo-keywords-1)))
12855 (t (error "Invalid prefix argument: %s" arg)))))
12856 (message "%d TODO entries found"
12857 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12859 (defun org-deadline (arg &optional time)
12860 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12861 With one universal prefix argument, remove any deadline from the item.
12862 With two universal prefix arguments, prompt for a warning delay.
12863 With argument TIME, set the deadline at the corresponding date. TIME
12864 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12865 (interactive "P")
12866 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12867 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12868 'region-start-level 'region))
12869 org-loop-over-headlines-in-active-region)
12870 (org-map-entries
12871 `(org-deadline ',arg ,time)
12872 org-loop-over-headlines-in-active-region
12873 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12874 (let* ((old-date (org-entry-get nil "DEADLINE"))
12875 (old-date-time (if old-date (org-time-string-to-time old-date)))
12876 (repeater (and old-date
12877 (string-match
12878 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12879 old-date)
12880 (match-string 1 old-date))))
12881 (cond
12882 ((equal arg '(4))
12883 (when (and old-date org-log-redeadline)
12884 (org-add-log-setup 'deldeadline nil old-date 'findpos
12885 org-log-redeadline))
12886 (org-remove-timestamp-with-keyword org-deadline-string)
12887 (message "Item no longer has a deadline."))
12888 ((equal arg '(16))
12889 (save-excursion
12890 (if (re-search-forward
12891 org-deadline-time-regexp
12892 (save-excursion (outline-next-heading) (point)) t)
12893 (let* ((rpl0 (match-string 1))
12894 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12895 (replace-match
12896 (concat org-deadline-string
12897 " <" rpl
12898 (format " -%dd"
12899 (abs
12900 (- (time-to-days
12901 (save-match-data
12902 (org-read-date nil t nil "Warn starting from" old-date-time)))
12903 (time-to-days old-date-time))))
12904 ">") t t))
12905 (user-error "No deadline information to update"))))
12907 (org-add-planning-info 'deadline time 'closed)
12908 (when (and old-date org-log-redeadline
12909 (not (equal old-date
12910 (substring org-last-inserted-timestamp 1 -1))))
12911 (org-add-log-setup 'redeadline nil old-date 'findpos
12912 org-log-redeadline))
12913 (when repeater
12914 (save-excursion
12915 (org-back-to-heading t)
12916 (when (re-search-forward (concat org-deadline-string " "
12917 org-last-inserted-timestamp)
12918 (save-excursion
12919 (outline-next-heading) (point)) t)
12920 (goto-char (1- (match-end 0)))
12921 (insert " " repeater)
12922 (setq org-last-inserted-timestamp
12923 (concat (substring org-last-inserted-timestamp 0 -1)
12924 " " repeater
12925 (substring org-last-inserted-timestamp -1))))))
12926 (message "Deadline on %s" org-last-inserted-timestamp))))))
12928 (defun org-schedule (arg &optional time)
12929 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12930 With one universal prefix argument, remove any scheduling date from the item.
12931 With two universal prefix arguments, prompt for a delay cookie.
12932 With argument TIME, scheduled at the corresponding date. TIME can
12933 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12934 (interactive "P")
12935 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12936 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12937 'region-start-level 'region))
12938 org-loop-over-headlines-in-active-region)
12939 (org-map-entries
12940 `(org-schedule ',arg ,time)
12941 org-loop-over-headlines-in-active-region
12942 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12943 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12944 (old-date-time (if old-date (org-time-string-to-time old-date)))
12945 (repeater (and old-date
12946 (string-match
12947 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12948 old-date)
12949 (match-string 1 old-date))))
12950 (cond
12951 ((equal arg '(4))
12952 (progn
12953 (when (and old-date org-log-reschedule)
12954 (org-add-log-setup 'delschedule nil old-date 'findpos
12955 org-log-reschedule))
12956 (org-remove-timestamp-with-keyword org-scheduled-string)
12957 (message "Item is no longer scheduled.")))
12958 ((equal arg '(16))
12959 (save-excursion
12960 (if (re-search-forward
12961 org-scheduled-time-regexp
12962 (save-excursion (outline-next-heading) (point)) t)
12963 (let* ((rpl0 (match-string 1))
12964 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12965 (replace-match
12966 (concat org-scheduled-string
12967 " <" rpl
12968 (format " -%dd"
12969 (abs
12970 (- (time-to-days
12971 (save-match-data
12972 (org-read-date nil t nil "Delay until" old-date-time)))
12973 (time-to-days old-date-time))))
12974 ">") t t))
12975 (user-error "No scheduled information to update"))))
12977 (org-add-planning-info 'scheduled time 'closed)
12978 (when (and old-date org-log-reschedule
12979 (not (equal old-date
12980 (substring org-last-inserted-timestamp 1 -1))))
12981 (org-add-log-setup 'reschedule nil old-date 'findpos
12982 org-log-reschedule))
12983 (when repeater
12984 (save-excursion
12985 (org-back-to-heading t)
12986 (when (re-search-forward (concat org-scheduled-string " "
12987 org-last-inserted-timestamp)
12988 (save-excursion
12989 (outline-next-heading) (point)) t)
12990 (goto-char (1- (match-end 0)))
12991 (insert " " repeater)
12992 (setq org-last-inserted-timestamp
12993 (concat (substring org-last-inserted-timestamp 0 -1)
12994 " " repeater
12995 (substring org-last-inserted-timestamp -1))))))
12996 (message "Scheduled to %s" org-last-inserted-timestamp))))))
12998 (defun org-get-scheduled-time (pom &optional inherit)
12999 "Get the scheduled time as a time tuple, of a format suitable
13000 for calling org-schedule with, or if there is no scheduling,
13001 returns nil."
13002 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13003 (when time
13004 (apply 'encode-time (org-parse-time-string time)))))
13006 (defun org-get-deadline-time (pom &optional inherit)
13007 "Get the deadline as a time tuple, of a format suitable for
13008 calling org-deadline with, or if there is no scheduling, returns
13009 nil."
13010 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13011 (when time
13012 (apply 'encode-time (org-parse-time-string time)))))
13014 (defun org-remove-timestamp-with-keyword (keyword)
13015 "Remove all time stamps with KEYWORD in the current entry."
13016 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13017 beg)
13018 (save-excursion
13019 (org-back-to-heading t)
13020 (setq beg (point))
13021 (outline-next-heading)
13022 (while (re-search-backward re beg t)
13023 (replace-match "")
13024 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13025 (equal (char-before) ?\ ))
13026 (backward-delete-char 1)
13027 (if (string-match "^[ \t]*$" (buffer-substring
13028 (point-at-bol) (point-at-eol)))
13029 (delete-region (point-at-bol)
13030 (min (point-max) (1+ (point-at-eol))))))))))
13032 (defun org-add-planning-info (what &optional time &rest remove)
13033 "Insert new timestamp with keyword in the line directly after the headline.
13034 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13035 If non is given, the user is prompted for a date.
13036 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13037 be removed."
13038 (interactive)
13039 (let (org-time-was-given org-end-time-was-given ts
13040 end default-time default-input)
13042 (catch 'exit
13043 (when (and (memq what '(scheduled deadline))
13044 (or (not time)
13045 (and (stringp time)
13046 (string-match "^[-+]+[0-9]" time))))
13047 ;; Try to get a default date/time from existing timestamp
13048 (save-excursion
13049 (org-back-to-heading t)
13050 (setq end (save-excursion (outline-next-heading) (point)))
13051 (when (re-search-forward (if (eq what 'scheduled)
13052 org-scheduled-time-regexp
13053 org-deadline-time-regexp)
13054 end t)
13055 (setq ts (match-string 1)
13056 default-time
13057 (apply 'encode-time (org-parse-time-string ts))
13058 default-input (and ts (org-get-compact-tod ts))))))
13059 (when what
13060 (setq time
13061 (if (stringp time)
13062 ;; This is a string (relative or absolute), set proper date
13063 (apply 'encode-time
13064 (org-read-date-analyze
13065 time default-time (decode-time default-time)))
13066 ;; If necessary, get the time from the user
13067 (or time (org-read-date nil 'to-time nil nil
13068 default-time default-input)))))
13070 (when (and org-insert-labeled-timestamps-at-point
13071 (member what '(scheduled deadline)))
13072 (insert
13073 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13074 (org-insert-time-stamp time org-time-was-given
13075 nil nil nil (list org-end-time-was-given))
13076 (setq what nil))
13077 (save-excursion
13078 (save-restriction
13079 (let (col list elt ts buffer-invisibility-spec)
13080 (org-back-to-heading t)
13081 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13082 (goto-char (match-end 1))
13083 (setq col (current-column))
13084 (goto-char (match-end 0))
13085 (if (eobp) (insert "\n") (forward-char 1))
13086 (when (and (not what)
13087 (not (looking-at
13088 (concat "[ \t]*"
13089 org-keyword-time-not-clock-regexp))))
13090 ;; Nothing to add, nothing to remove...... :-)
13091 (throw 'exit nil))
13092 (if (and (not (looking-at org-outline-regexp))
13093 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13094 "[^\r\n]*"))
13095 (not (equal (match-string 1) org-clock-string)))
13096 (narrow-to-region (match-beginning 0) (match-end 0))
13097 (insert-before-markers "\n")
13098 (backward-char 1)
13099 (narrow-to-region (point) (point))
13100 (and org-adapt-indentation (org-indent-to-column col)))
13101 ;; Check if we have to remove something.
13102 (setq list (cons what remove))
13103 (while list
13104 (setq elt (pop list))
13105 (when (or (and (eq elt 'scheduled)
13106 (re-search-forward org-scheduled-time-regexp nil t))
13107 (and (eq elt 'deadline)
13108 (re-search-forward org-deadline-time-regexp nil t))
13109 (and (eq elt 'closed)
13110 (re-search-forward org-closed-time-regexp nil t)))
13111 (replace-match "")
13112 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13113 (and (looking-at "[ \t]+") (replace-match ""))
13114 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13115 (when what
13116 (insert
13117 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13118 (cond ((eq what 'scheduled) org-scheduled-string)
13119 ((eq what 'deadline) org-deadline-string)
13120 ((eq what 'closed) org-closed-string))
13121 " ")
13122 (setq ts (org-insert-time-stamp
13123 time
13124 (or org-time-was-given
13125 (and (eq what 'closed) org-log-done-with-time))
13126 (eq what 'closed)
13127 nil nil (list org-end-time-was-given)))
13128 (insert
13129 (if (not (or (bolp) (eq (char-before) ?\ )
13130 (memq (char-after) '(32 10))
13131 (eobp))) " " ""))
13132 (end-of-line 1))
13133 (goto-char (point-min))
13134 (widen)
13135 (if (and (looking-at "[ \t]*\n")
13136 (equal (char-before) ?\n))
13137 (delete-region (1- (point)) (point-at-eol)))
13138 ts))))))
13140 (defvar org-log-note-marker (make-marker))
13141 (defvar org-log-note-purpose nil)
13142 (defvar org-log-note-state nil)
13143 (defvar org-log-note-previous-state nil)
13144 (defvar org-log-note-how nil)
13145 (defvar org-log-note-extra nil)
13146 (defvar org-log-note-window-configuration nil)
13147 (defvar org-log-note-return-to (make-marker))
13148 (defvar org-log-note-effective-time nil
13149 "Remembered current time so that dynamically scoped
13150 `org-extend-today-until' affects tha timestamps in state change
13151 log")
13153 (defvar org-log-post-message nil
13154 "Message to be displayed after a log note has been stored.
13155 The auto-repeater uses this.")
13157 (defun org-add-note ()
13158 "Add a note to the current entry.
13159 This is done in the same way as adding a state change note."
13160 (interactive)
13161 (org-add-log-setup 'note nil nil 'findpos nil))
13163 (defvar org-property-end-re)
13164 (defun org-add-log-setup (&optional purpose state prev-state
13165 findpos how extra)
13166 "Set up the post command hook to take a note.
13167 If this is about to TODO state change, the new state is expected in STATE.
13168 When FINDPOS is non-nil, find the correct position for the note in
13169 the current entry. If not, assume that it can be inserted at point.
13170 HOW is an indicator what kind of note should be created.
13171 EXTRA is additional text that will be inserted into the notes buffer."
13172 (let* ((org-log-into-drawer (org-log-into-drawer))
13173 (drawer (cond ((stringp org-log-into-drawer)
13174 org-log-into-drawer)
13175 (org-log-into-drawer "LOGBOOK"))))
13176 (save-restriction
13177 (save-excursion
13178 (when findpos
13179 (org-back-to-heading t)
13180 (narrow-to-region (point) (save-excursion
13181 (outline-next-heading) (point)))
13182 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13183 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13184 "[^\r\n]*\\)?"))
13185 (goto-char (match-end 0))
13186 (cond
13187 (drawer
13188 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13189 nil t)
13190 (progn
13191 (goto-char (match-end 0))
13192 (or org-log-states-order-reversed
13193 (and (re-search-forward org-property-end-re nil t)
13194 (goto-char (1- (match-beginning 0))))))
13195 (insert "\n:" drawer ":\n:END:")
13196 (beginning-of-line 0)
13197 (org-indent-line)
13198 (beginning-of-line 2)
13199 (org-indent-line)
13200 (end-of-line 0)))
13201 ((and org-log-state-notes-insert-after-drawers
13202 (save-excursion
13203 (forward-line) (looking-at org-drawer-regexp)))
13204 (forward-line)
13205 (while (looking-at org-drawer-regexp)
13206 (goto-char (match-end 0))
13207 (re-search-forward org-property-end-re (point-max) t)
13208 (forward-line))
13209 (forward-line -1)))
13210 (unless org-log-states-order-reversed
13211 (and (= (char-after) ?\n) (forward-char 1))
13212 (org-skip-over-state-notes)
13213 (skip-chars-backward " \t\n\r")))
13214 (move-marker org-log-note-marker (point))
13215 (setq org-log-note-purpose purpose
13216 org-log-note-state state
13217 org-log-note-previous-state prev-state
13218 org-log-note-how how
13219 org-log-note-extra extra
13220 org-log-note-effective-time (org-current-effective-time))
13221 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13223 (defun org-skip-over-state-notes ()
13224 "Skip past the list of State notes in an entry."
13225 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13226 (when (ignore-errors (goto-char (org-in-item-p)))
13227 (let* ((struct (org-list-struct))
13228 (prevs (org-list-prevs-alist struct)))
13229 (while (looking-at "[ \t]*- State")
13230 (goto-char (or (org-list-get-next-item (point) struct prevs)
13231 (org-list-get-item-end (point) struct)))))))
13233 (defun org-add-log-note (&optional purpose)
13234 "Pop up a window for taking a note, and add this note later at point."
13235 (remove-hook 'post-command-hook 'org-add-log-note)
13236 (setq org-log-note-window-configuration (current-window-configuration))
13237 (delete-other-windows)
13238 (move-marker org-log-note-return-to (point))
13239 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13240 (goto-char org-log-note-marker)
13241 (org-switch-to-buffer-other-window "*Org Note*")
13242 (erase-buffer)
13243 (if (memq org-log-note-how '(time state))
13244 (let (current-prefix-arg) (org-store-log-note))
13245 (let ((org-inhibit-startup t)) (org-mode))
13246 (insert (format "# Insert note for %s.
13247 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13248 (cond
13249 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13250 ((eq org-log-note-purpose 'done) "closed todo item")
13251 ((eq org-log-note-purpose 'state)
13252 (format "state change from \"%s\" to \"%s\""
13253 (or org-log-note-previous-state "")
13254 (or org-log-note-state "")))
13255 ((eq org-log-note-purpose 'reschedule)
13256 "rescheduling")
13257 ((eq org-log-note-purpose 'delschedule)
13258 "no longer scheduled")
13259 ((eq org-log-note-purpose 'redeadline)
13260 "changing deadline")
13261 ((eq org-log-note-purpose 'deldeadline)
13262 "removing deadline")
13263 ((eq org-log-note-purpose 'refile)
13264 "refiling")
13265 ((eq org-log-note-purpose 'note)
13266 "this entry")
13267 (t (error "This should not happen")))))
13268 (if org-log-note-extra (insert org-log-note-extra))
13269 (org-set-local 'org-finish-function 'org-store-log-note)
13270 (run-hooks 'org-log-buffer-setup-hook)))
13272 (defvar org-note-abort nil) ; dynamically scoped
13273 (defun org-store-log-note ()
13274 "Finish taking a log note, and insert it to where it belongs."
13275 (let ((txt (buffer-string)))
13276 (kill-buffer (current-buffer))
13277 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13278 lines ind bul)
13279 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13280 (setq txt (replace-match "" t t txt)))
13281 (if (string-match "\\s-+\\'" txt)
13282 (setq txt (replace-match "" t t txt)))
13283 (setq lines (org-split-string txt "\n"))
13284 (when (and note (string-match "\\S-" note))
13285 (setq note
13286 (org-replace-escapes
13287 note
13288 (list (cons "%u" (user-login-name))
13289 (cons "%U" user-full-name)
13290 (cons "%t" (format-time-string
13291 (org-time-stamp-format 'long 'inactive)
13292 org-log-note-effective-time))
13293 (cons "%T" (format-time-string
13294 (org-time-stamp-format 'long nil)
13295 org-log-note-effective-time))
13296 (cons "%d" (format-time-string
13297 (org-time-stamp-format nil 'inactive)
13298 org-log-note-effective-time))
13299 (cons "%D" (format-time-string
13300 (org-time-stamp-format nil nil)
13301 org-log-note-effective-time))
13302 (cons "%s" (if org-log-note-state
13303 (concat "\"" org-log-note-state "\"")
13304 ""))
13305 (cons "%S" (if org-log-note-previous-state
13306 (concat "\"" org-log-note-previous-state "\"")
13307 "\"\"")))))
13308 (if lines (setq note (concat note " \\\\")))
13309 (push note lines))
13310 (when (or current-prefix-arg org-note-abort)
13311 (when org-log-into-drawer
13312 (org-remove-empty-drawer-at
13313 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13314 org-log-note-marker))
13315 (setq lines nil))
13316 (when lines
13317 (with-current-buffer (marker-buffer org-log-note-marker)
13318 (save-excursion
13319 (goto-char org-log-note-marker)
13320 (move-marker org-log-note-marker nil)
13321 (end-of-line 1)
13322 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13323 (setq ind (save-excursion
13324 (if (ignore-errors (goto-char (org-in-item-p)))
13325 (let ((struct (org-list-struct)))
13326 (org-list-get-ind
13327 (org-list-get-top-point struct) struct))
13328 (skip-chars-backward " \r\t\n")
13329 (cond
13330 ((and (org-at-heading-p)
13331 org-adapt-indentation)
13332 (1+ (org-current-level)))
13333 ((org-at-heading-p) 0)
13334 (t (org-get-indentation))))))
13335 (setq bul (org-list-bullet-string "-"))
13336 (org-indent-line-to ind)
13337 (insert bul (pop lines))
13338 (let ((ind-body (+ (length bul) ind)))
13339 (while lines
13340 (insert "\n")
13341 (org-indent-line-to ind-body)
13342 (insert (pop lines))))
13343 (message "Note stored")
13344 (org-back-to-heading t)
13345 (org-cycle-hide-drawers 'children))))))
13346 (set-window-configuration org-log-note-window-configuration)
13347 (with-current-buffer (marker-buffer org-log-note-return-to)
13348 (goto-char org-log-note-return-to))
13349 (move-marker org-log-note-return-to nil)
13350 (and org-log-post-message (message "%s" org-log-post-message)))
13352 (defun org-remove-empty-drawer-at (drawer pos)
13353 "Remove an empty drawer DRAWER at position POS.
13354 POS may also be a marker."
13355 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13356 (save-excursion
13357 (save-restriction
13358 (widen)
13359 (goto-char pos)
13360 (if (org-in-regexp
13361 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13362 (replace-match ""))))))
13364 (defvar org-ts-type nil)
13365 (defun org-sparse-tree (&optional arg type)
13366 "Create a sparse tree, prompt for the details.
13367 This command can create sparse trees. You first need to select the type
13368 of match used to create the tree:
13370 t Show all TODO entries.
13371 T Show entries with a specific TODO keyword.
13372 m Show entries selected by a tags/property match.
13373 p Enter a property name and its value (both with completion on existing
13374 names/values) and show entries with that property.
13375 r Show entries matching a regular expression (`/' can be used as well).
13376 b Show deadlines and scheduled items before a date.
13377 a Show deadlines and scheduled items after a date.
13378 d Show deadlines due within `org-deadline-warning-days'.
13379 D Show deadlines and scheduled items between a date range."
13380 (interactive "P")
13381 (let (ans kwd value ts-type)
13382 (setq type (or type org-sparse-tree-default-date-type))
13383 (setq org-ts-type type)
13384 (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"
13385 (cond ((eq type 'all) "all timestamps")
13386 ((eq type 'scheduled) "only scheduled")
13387 ((eq type 'deadline) "only deadline")
13388 ((eq type 'active) "only active timestamps")
13389 ((eq type 'inactive) "only inactive timestamps")
13390 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13391 ((eq type 'closed) "with a closed time-stamp")
13392 (t "scheduled/deadline")))
13393 (setq ans (read-char-exclusive))
13394 (cond
13395 ((equal ans ?c)
13396 (org-sparse-tree
13397 arg (cadr (member type '(scheduled-or-deadline
13398 all scheduled deadline active inactive closed)))))
13399 ((equal ans ?d)
13400 (call-interactively 'org-check-deadlines))
13401 ((equal ans ?b)
13402 (call-interactively 'org-check-before-date))
13403 ((equal ans ?a)
13404 (call-interactively 'org-check-after-date))
13405 ((equal ans ?D)
13406 (call-interactively 'org-check-dates-range))
13407 ((equal ans ?t)
13408 (call-interactively 'org-show-todo-tree))
13409 ((equal ans ?T)
13410 (org-show-todo-tree '(4)))
13411 ((member ans '(?T ?m))
13412 (call-interactively 'org-match-sparse-tree))
13413 ((member ans '(?p ?P))
13414 (setq kwd (org-icompleting-read "Property: "
13415 (mapcar 'list (org-buffer-property-keys))))
13416 (setq value (org-icompleting-read "Value: "
13417 (mapcar 'list (org-property-values kwd))))
13418 (unless (string-match "\\`{.*}\\'" value)
13419 (setq value (concat "\"" value "\"")))
13420 (org-match-sparse-tree arg (concat kwd "=" value)))
13421 ((member ans '(?r ?R ?/))
13422 (call-interactively 'org-occur))
13423 (t (error "No such sparse tree command \"%c\"" ans)))))
13425 (defvar org-occur-highlights nil
13426 "List of overlays used for occur matches.")
13427 (make-variable-buffer-local 'org-occur-highlights)
13428 (defvar org-occur-parameters nil
13429 "Parameters of the active org-occur calls.
13430 This is a list, each call to org-occur pushes as cons cell,
13431 containing the regular expression and the callback, onto the list.
13432 The list can contain several entries if `org-occur' has been called
13433 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13434 will only contain one set of parameters. When the highlights are
13435 removed (for example with `C-c C-c', or with the next edit (depending
13436 on `org-remove-highlights-with-change'), this variable is emptied
13437 as well.")
13438 (make-variable-buffer-local 'org-occur-parameters)
13440 (defun org-occur (regexp &optional keep-previous callback)
13441 "Make a compact tree which shows all matches of REGEXP.
13442 The tree will show the lines where the regexp matches, and all higher
13443 headlines above the match. It will also show the heading after the match,
13444 to make sure editing the matching entry is easy.
13445 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13446 call to `org-occur' will be kept, to allow stacking of calls to this
13447 command.
13448 If CALLBACK is non-nil, it is a function which is called to confirm
13449 that the match should indeed be shown."
13450 (interactive "sRegexp: \nP")
13451 (when (equal regexp "")
13452 (error "Regexp cannot be empty"))
13453 (unless keep-previous
13454 (org-remove-occur-highlights nil nil t))
13455 (push (cons regexp callback) org-occur-parameters)
13456 (let ((cnt 0))
13457 (save-excursion
13458 (goto-char (point-min))
13459 (if (or (not keep-previous) ; do not want to keep
13460 (not org-occur-highlights)) ; no previous matches
13461 ;; hide everything
13462 (org-overview))
13463 (while (re-search-forward regexp nil t)
13464 (when (or (not callback)
13465 (save-match-data (funcall callback)))
13466 (setq cnt (1+ cnt))
13467 (when org-highlight-sparse-tree-matches
13468 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13469 (org-show-context 'occur-tree))))
13470 (when org-remove-highlights-with-change
13471 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13472 nil 'local))
13473 (unless org-sparse-tree-open-archived-trees
13474 (org-hide-archived-subtrees (point-min) (point-max)))
13475 (run-hooks 'org-occur-hook)
13476 (if (org-called-interactively-p 'interactive)
13477 (message "%d match(es) for regexp %s" cnt regexp))
13478 cnt))
13480 (defun org-occur-next-match (&optional n reset)
13481 "Function for `next-error-function' to find sparse tree matches.
13482 N is the number of matches to move, when negative move backwards.
13483 RESET is entirely ignored - this function always goes back to the
13484 starting point when no match is found."
13485 (let* ((limit (if (< n 0) (point-min) (point-max)))
13486 (search-func (if (< n 0)
13487 'previous-single-char-property-change
13488 'next-single-char-property-change))
13489 (n (abs n))
13490 (pos (point))
13492 (catch 'exit
13493 (while (setq p1 (funcall search-func (point) 'org-type))
13494 (when (equal p1 limit)
13495 (goto-char pos)
13496 (error "No more matches"))
13497 (when (equal (get-char-property p1 'org-type) 'org-occur)
13498 (setq n (1- n))
13499 (when (= n 0)
13500 (goto-char p1)
13501 (throw 'exit (point))))
13502 (goto-char p1))
13503 (goto-char p1)
13504 (error "No more matches"))))
13506 (defun org-show-context (&optional key)
13507 "Make sure point and context are visible.
13508 How much context is shown depends upon the variables
13509 `org-show-hierarchy-above', `org-show-following-heading',
13510 `org-show-entry-below' and `org-show-siblings'."
13511 (let ((heading-p (org-at-heading-p t))
13512 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13513 (following-p (org-get-alist-option org-show-following-heading key))
13514 (entry-p (org-get-alist-option org-show-entry-below key))
13515 (siblings-p (org-get-alist-option org-show-siblings key)))
13516 ;; Show heading or entry text
13517 (if (and heading-p (not entry-p))
13518 (org-flag-heading nil) ; only show the heading
13519 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13520 (org-show-hidden-entry))) ; show entire entry
13521 (when following-p
13522 ;; Show next sibling, or heading below text
13523 (save-excursion
13524 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13525 (org-flag-heading nil))))
13526 (when siblings-p (org-show-siblings))
13527 (when hierarchy-p
13528 ;; show all higher headings, possibly with siblings
13529 (save-excursion
13530 (while (and (condition-case nil
13531 (progn (org-up-heading-all 1) t)
13532 (error nil))
13533 (not (bobp)))
13534 (org-flag-heading nil)
13535 (when siblings-p (org-show-siblings)))))
13536 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13538 (defvar org-reveal-start-hook nil
13539 "Hook run before revealing a location.")
13541 (defun org-reveal (&optional siblings)
13542 "Show current entry, hierarchy above it, and the following headline.
13543 This can be used to show a consistent set of context around locations
13544 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13545 not t for the search context.
13547 With optional argument SIBLINGS, on each level of the hierarchy all
13548 siblings are shown. This repairs the tree structure to what it would
13549 look like when opened with hierarchical calls to `org-cycle'.
13550 With double optional argument \\[universal-argument] \\[universal-argument], \
13551 go to the parent and show the
13552 entire tree."
13553 (interactive "P")
13554 (run-hooks 'org-reveal-start-hook)
13555 (let ((org-show-hierarchy-above t)
13556 (org-show-following-heading t)
13557 (org-show-siblings (if siblings t org-show-siblings)))
13558 (org-show-context nil))
13559 (when (equal siblings '(16))
13560 (save-excursion
13561 (when (org-up-heading-safe)
13562 (org-show-subtree)
13563 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13565 (defun org-highlight-new-match (beg end)
13566 "Highlight from BEG to END and mark the highlight is an occur headline."
13567 (let ((ov (make-overlay beg end)))
13568 (overlay-put ov 'face 'secondary-selection)
13569 (overlay-put ov 'org-type 'org-occur)
13570 (push ov org-occur-highlights)))
13572 (defun org-remove-occur-highlights (&optional beg end noremove)
13573 "Remove the occur highlights from the buffer.
13574 BEG and END are ignored. If NOREMOVE is nil, remove this function
13575 from the `before-change-functions' in the current buffer."
13576 (interactive)
13577 (unless org-inhibit-highlight-removal
13578 (mapc 'delete-overlay org-occur-highlights)
13579 (setq org-occur-highlights nil)
13580 (setq org-occur-parameters nil)
13581 (unless noremove
13582 (remove-hook 'before-change-functions
13583 'org-remove-occur-highlights 'local))))
13585 ;;;; Priorities
13587 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13588 "Regular expression matching the priority indicator.")
13590 (defvar org-remove-priority-next-time nil)
13592 (defun org-priority-up ()
13593 "Increase the priority of the current item."
13594 (interactive)
13595 (org-priority 'up))
13597 (defun org-priority-down ()
13598 "Decrease the priority of the current item."
13599 (interactive)
13600 (org-priority 'down))
13602 (defun org-priority (&optional action show)
13603 "Change the priority of an item.
13604 ACTION can be `set', `up', `down', or a character."
13605 (interactive "P")
13606 (if (equal action '(4))
13607 (org-show-priority)
13608 (unless org-enable-priority-commands
13609 (error "Priority commands are disabled"))
13610 (setq action (or action 'set))
13611 (let (current new news have remove)
13612 (save-excursion
13613 (org-back-to-heading t)
13614 (if (looking-at org-priority-regexp)
13615 (setq current (string-to-char (match-string 2))
13616 have t))
13617 (cond
13618 ((eq action 'remove)
13619 (setq remove t new ?\ ))
13620 ((or (eq action 'set)
13621 (if (featurep 'xemacs) (characterp action) (integerp action)))
13622 (if (not (eq action 'set))
13623 (setq new action)
13624 (message "Priority %c-%c, SPC to remove: "
13625 org-highest-priority org-lowest-priority)
13626 (save-match-data
13627 (setq new (read-char-exclusive))))
13628 (if (and (= (upcase org-highest-priority) org-highest-priority)
13629 (= (upcase org-lowest-priority) org-lowest-priority))
13630 (setq new (upcase new)))
13631 (cond ((equal new ?\ ) (setq remove t))
13632 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13633 (error "Priority must be between `%c' and `%c'"
13634 org-highest-priority org-lowest-priority))))
13635 ((eq action 'up)
13636 (setq new (if have
13637 (1- current) ; normal cycling
13638 ;; last priority was empty
13639 (if (eq last-command this-command)
13640 org-lowest-priority ; wrap around empty to lowest
13641 ;; default
13642 (if org-priority-start-cycle-with-default
13643 org-default-priority
13644 (1- org-default-priority))))))
13645 ((eq action 'down)
13646 (setq new (if have
13647 (1+ current) ; normal cycling
13648 ;; last priority was empty
13649 (if (eq last-command this-command)
13650 org-highest-priority ; wrap around empty to highest
13651 ;; default
13652 (if org-priority-start-cycle-with-default
13653 org-default-priority
13654 (1+ org-default-priority))))))
13655 (t (error "Invalid action")))
13656 (if (or (< (upcase new) org-highest-priority)
13657 (> (upcase new) org-lowest-priority))
13658 (if (and (memq action '(up down))
13659 (not have) (not (eq last-command this-command)))
13660 ;; `new' is from default priority
13661 (error
13662 "The default can not be set, see `org-default-priority' why")
13663 ;; normal cycling: `new' is beyond highest/lowest priority
13664 ;; and is wrapped around to the empty priority
13665 (setq remove t)))
13666 (setq news (format "%c" new))
13667 (if have
13668 (if remove
13669 (replace-match "" t t nil 1)
13670 (replace-match news t t nil 2))
13671 (if remove
13672 (error "No priority cookie found in line")
13673 (let ((case-fold-search nil))
13674 (looking-at org-todo-line-regexp))
13675 (if (match-end 2)
13676 (progn
13677 (goto-char (match-end 2))
13678 (insert " [#" news "]"))
13679 (goto-char (match-beginning 3))
13680 (insert "[#" news "] "))))
13681 (org-preserve-lc (org-set-tags nil 'align)))
13682 (if remove
13683 (message "Priority removed")
13684 (message "Priority of current item set to %s" news)))))
13686 (defun org-show-priority ()
13687 "Show the priority of the current item.
13688 This priority is composed of the main priority given with the [#A] cookies,
13689 and by additional input from the age of a schedules or deadline entry."
13690 (interactive)
13691 (let ((pri (if (eq major-mode 'org-agenda-mode)
13692 (org-get-at-bol 'priority)
13693 (save-excursion
13694 (save-match-data
13695 (beginning-of-line)
13696 (and (looking-at org-heading-regexp)
13697 (org-get-priority (match-string 0))))))))
13698 (message "Priority is %d" (if pri pri -1000))))
13700 (defun org-get-priority (s)
13701 "Find priority cookie and return priority."
13702 (save-match-data
13703 (if (functionp org-get-priority-function)
13704 (funcall org-get-priority-function)
13705 (if (not (string-match org-priority-regexp s))
13706 (* 1000 (- org-lowest-priority org-default-priority))
13707 (* 1000 (- org-lowest-priority
13708 (string-to-char (match-string 2 s))))))))
13710 ;;;; Tags
13712 (defvar org-agenda-archives-mode)
13713 (defvar org-map-continue-from nil
13714 "Position from where mapping should continue.
13715 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13717 (defvar org-scanner-tags nil
13718 "The current tag list while the tags scanner is running.")
13719 (defvar org-trust-scanner-tags nil
13720 "Should `org-get-tags-at' use the tags for the scanner.
13721 This is for internal dynamical scoping only.
13722 When this is non-nil, the function `org-get-tags-at' will return the value
13723 of `org-scanner-tags' instead of building the list by itself. This
13724 can lead to large speed-ups when the tags scanner is used in a file with
13725 many entries, and when the list of tags is retrieved, for example to
13726 obtain a list of properties. Building the tags list for each entry in such
13727 a file becomes an N^2 operation - but with this variable set, it scales
13728 as N.")
13730 (defun org-scan-tags (action matcher todo-only &optional start-level)
13731 "Sca headline tags with inheritance and produce output ACTION.
13733 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13734 or `agenda' to produce an entry list for an agenda view. It can also be
13735 a Lisp form or a function that should be called at each matched headline, in
13736 this case the return value is a list of all return values from these calls.
13738 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13739 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13740 only lines with a not-done TODO keyword are included in the output.
13741 This should be the same variable that was scoped into
13742 and set by `org-make-tags-matcher' when it constructed MATCHER.
13744 START-LEVEL can be a string with asterisks, reducing the scope to
13745 headlines matching this string."
13746 (require 'org-agenda)
13747 (let* ((re (concat "^"
13748 (if start-level
13749 ;; Get the correct level to match
13750 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13751 org-outline-regexp)
13752 " *\\(\\<\\("
13753 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13754 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13755 (props (list 'face 'default
13756 'done-face 'org-agenda-done
13757 'undone-face 'default
13758 'mouse-face 'highlight
13759 'org-not-done-regexp org-not-done-regexp
13760 'org-todo-regexp org-todo-regexp
13761 'org-complex-heading-regexp org-complex-heading-regexp
13762 'help-echo
13763 (format "mouse-2 or RET jump to org file %s"
13764 (abbreviate-file-name
13765 (or (buffer-file-name (buffer-base-buffer))
13766 (buffer-name (buffer-base-buffer)))))))
13767 (case-fold-search nil)
13768 (org-map-continue-from nil)
13769 lspos tags tags-list
13770 (tags-alist (list (cons 0 org-file-tags)))
13771 (llast 0) rtn rtn1 level category i txt
13772 todo marker entry priority)
13773 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13774 (setq action (list 'lambda nil action)))
13775 (save-excursion
13776 (goto-char (point-min))
13777 (when (eq action 'sparse-tree)
13778 (org-overview)
13779 (org-remove-occur-highlights))
13780 (while (re-search-forward re nil t)
13781 (setq org-map-continue-from nil)
13782 (catch :skip
13783 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13784 tags (if (match-end 4) (org-match-string-no-properties 4)))
13785 (goto-char (setq lspos (match-beginning 0)))
13786 (setq level (org-reduced-level (org-outline-level))
13787 category (org-get-category))
13788 (setq i llast llast level)
13789 ;; remove tag lists from same and sublevels
13790 (while (>= i level)
13791 (when (setq entry (assoc i tags-alist))
13792 (setq tags-alist (delete entry tags-alist)))
13793 (setq i (1- i)))
13794 ;; add the next tags
13795 (when tags
13796 (setq tags (org-split-string tags ":")
13797 tags-alist
13798 (cons (cons level tags) tags-alist)))
13799 ;; compile tags for current headline
13800 (setq tags-list
13801 (if org-use-tag-inheritance
13802 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13803 tags)
13804 org-scanner-tags tags-list)
13805 (when org-use-tag-inheritance
13806 (setcdr (car tags-alist)
13807 (mapcar (lambda (x)
13808 (setq x (copy-sequence x))
13809 (org-add-prop-inherited x))
13810 (cdar tags-alist))))
13811 (when (and tags org-use-tag-inheritance
13812 (or (not (eq t org-use-tag-inheritance))
13813 org-tags-exclude-from-inheritance))
13814 ;; selective inheritance, remove uninherited ones
13815 (setcdr (car tags-alist)
13816 (org-remove-uninherited-tags (cdar tags-alist))))
13817 (when (and
13819 ;; eval matcher only when the todo condition is OK
13820 (and (or (not todo-only) (member todo org-not-done-keywords))
13821 (let ((case-fold-search t) (org-trust-scanner-tags t))
13822 (eval matcher)))
13824 ;; Call the skipper, but return t if it does not skip,
13825 ;; so that the `and' form continues evaluating
13826 (progn
13827 (unless (eq action 'sparse-tree) (org-agenda-skip))
13830 ;; Check if timestamps are deselecting this entry
13831 (or (not todo-only)
13832 (and (member todo org-not-done-keywords)
13833 (or (not org-agenda-tags-todo-honor-ignore-options)
13834 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13836 ;; select this headline
13837 (cond
13838 ((eq action 'sparse-tree)
13839 (and org-highlight-sparse-tree-matches
13840 (org-get-heading) (match-end 0)
13841 (org-highlight-new-match
13842 (match-beginning 1) (match-end 1)))
13843 (org-show-context 'tags-tree))
13844 ((eq action 'agenda)
13845 (setq txt (org-agenda-format-item
13847 (concat
13848 (if (eq org-tags-match-list-sublevels 'indented)
13849 (make-string (1- level) ?.) "")
13850 (org-get-heading))
13851 level category
13852 tags-list)
13853 priority (org-get-priority txt))
13854 (goto-char lspos)
13855 (setq marker (org-agenda-new-marker))
13856 (org-add-props txt props
13857 'org-marker marker 'org-hd-marker marker 'org-category category
13858 'todo-state todo
13859 'priority priority 'type "tagsmatch")
13860 (push txt rtn))
13861 ((functionp action)
13862 (setq org-map-continue-from nil)
13863 (save-excursion
13864 (setq rtn1 (funcall action))
13865 (push rtn1 rtn)))
13866 (t (error "Invalid action")))
13868 ;; if we are to skip sublevels, jump to end of subtree
13869 (unless org-tags-match-list-sublevels
13870 (org-end-of-subtree t)
13871 (backward-char 1))))
13872 ;; Get the correct position from where to continue
13873 (if org-map-continue-from
13874 (goto-char org-map-continue-from)
13875 (and (= (point) lspos) (end-of-line 1)))))
13876 (when (and (eq action 'sparse-tree)
13877 (not org-sparse-tree-open-archived-trees))
13878 (org-hide-archived-subtrees (point-min) (point-max)))
13879 (nreverse rtn)))
13881 (defun org-remove-uninherited-tags (tags)
13882 "Remove all tags that are not inherited from the list TAGS."
13883 (cond
13884 ((eq org-use-tag-inheritance t)
13885 (if org-tags-exclude-from-inheritance
13886 (org-delete-all org-tags-exclude-from-inheritance tags)
13887 tags))
13888 ((not org-use-tag-inheritance) nil)
13889 ((stringp org-use-tag-inheritance)
13890 (delq nil (mapcar
13891 (lambda (x)
13892 (if (and (string-match org-use-tag-inheritance x)
13893 (not (member x org-tags-exclude-from-inheritance)))
13894 x nil))
13895 tags)))
13896 ((listp org-use-tag-inheritance)
13897 (delq nil (mapcar
13898 (lambda (x)
13899 (if (member x org-use-tag-inheritance) x nil))
13900 tags)))))
13902 (defun org-match-sparse-tree (&optional todo-only match)
13903 "Create a sparse tree according to tags string MATCH.
13904 MATCH can contain positive and negative selection of tags, like
13905 \"+WORK+URGENT-WITHBOSS\".
13906 If optional argument TODO-ONLY is non-nil, only select lines that are
13907 also TODO lines."
13908 (interactive "P")
13909 (org-agenda-prepare-buffers (list (current-buffer)))
13910 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13912 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13914 (defvar org-cached-props nil)
13915 (defun org-cached-entry-get (pom property)
13916 (if (or (eq t org-use-property-inheritance)
13917 (and (stringp org-use-property-inheritance)
13918 (string-match org-use-property-inheritance property))
13919 (and (listp org-use-property-inheritance)
13920 (member property org-use-property-inheritance)))
13921 ;; Caching is not possible, check it directly
13922 (org-entry-get pom property 'inherit)
13923 ;; Get all properties, so that we can do complicated checks easily
13924 (cdr (assoc property (or org-cached-props
13925 (setq org-cached-props
13926 (org-entry-properties pom)))))))
13928 (defun org-global-tags-completion-table (&optional files)
13929 "Return the list of all tags in all agenda buffer/files.
13930 Optional FILES argument is a list of files which can be used
13931 instead of the agenda files."
13932 (save-excursion
13933 (org-uniquify
13934 (delq nil
13935 (apply 'append
13936 (mapcar
13937 (lambda (file)
13938 (set-buffer (find-file-noselect file))
13939 (append (org-get-buffer-tags)
13940 (mapcar (lambda (x) (if (stringp (car-safe x))
13941 (list (car-safe x)) nil))
13942 org-tag-alist)))
13943 (if (and files (car files))
13944 files
13945 (org-agenda-files))))))))
13947 (defun org-make-tags-matcher (match)
13948 "Create the TAGS/TODO matcher form for the selection string MATCH.
13950 The variable `todo-only' is scoped dynamically into this function.
13951 It will be set to t if the matcher restricts matching to TODO entries,
13952 otherwise will not be touched.
13954 Returns a cons of the selection string MATCH and the constructed
13955 lisp form implementing the matcher. The matcher is to be evaluated
13956 at an Org entry, with point on the headline, and returns t if the
13957 entry matches the selection string MATCH. The returned lisp form
13958 references two variables with information about the entry, which
13959 must be bound around the form's evaluation: todo, the TODO keyword
13960 at the entry (or nil of none); and tags-list, the list of all tags
13961 at the entry including inherited ones. Additionally, the category
13962 of the entry (if any) must be specified as the text property
13963 'org-category on the headline.
13965 See also `org-scan-tags'.
13967 (declare (special todo-only))
13968 (unless (boundp 'todo-only)
13969 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
13970 (unless match
13971 ;; Get a new match request, with completion
13972 (let ((org-last-tags-completion-table
13973 (org-global-tags-completion-table)))
13974 (setq match (org-completing-read-no-i
13975 "Match: " 'org-tags-completion-function nil nil nil
13976 'org-tags-history))))
13978 ;; Parse the string and create a lisp form
13979 (let ((match0 match)
13980 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13981 minus tag mm
13982 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13983 orterms term orlist re-p str-p level-p level-op time-p
13984 prop-p pn pv po gv rest)
13985 ;; Expand group tags
13986 (setq match (org-tags-expand match))
13987 (if (string-match "/+" match)
13988 ;; match contains also a todo-matching request
13989 (progn
13990 (setq tagsmatch (substring match 0 (match-beginning 0))
13991 todomatch (substring match (match-end 0)))
13992 (if (string-match "^!" todomatch)
13993 (setq todo-only t todomatch (substring todomatch 1)))
13994 (if (string-match "^\\s-*$" todomatch)
13995 (setq todomatch nil)))
13996 ;; only matching tags
13997 (setq tagsmatch match todomatch nil))
13999 ;; Make the tags matcher
14000 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14001 (setq tagsmatcher t)
14002 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14003 (while (setq term (pop orterms))
14004 (while (and (equal (substring term -1) "\\") orterms)
14005 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14006 (while (string-match re term)
14007 (setq rest (substring term (match-end 0))
14008 minus (and (match-end 1)
14009 (equal (match-string 1 term) "-"))
14010 tag (save-match-data (replace-regexp-in-string
14011 "\\\\-" "-"
14012 (match-string 2 term)))
14013 re-p (equal (string-to-char tag) ?{)
14014 level-p (match-end 4)
14015 prop-p (match-end 5)
14016 mm (cond
14017 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14018 (level-p
14019 (setq level-op (org-op-to-function (match-string 3 term)))
14020 `(,level-op level ,(string-to-number
14021 (match-string 4 term))))
14022 (prop-p
14023 (setq pn (match-string 5 term)
14024 po (match-string 6 term)
14025 pv (match-string 7 term)
14026 re-p (equal (string-to-char pv) ?{)
14027 str-p (equal (string-to-char pv) ?\")
14028 time-p (save-match-data
14029 (string-match "^\"[[<].*[]>]\"$" pv))
14030 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14031 (if time-p (setq pv (org-matcher-time pv)))
14032 (setq po (org-op-to-function po (if time-p 'time str-p)))
14033 (cond
14034 ((equal pn "CATEGORY")
14035 (setq gv '(get-text-property (point) 'org-category)))
14036 ((equal pn "TODO")
14037 (setq gv 'todo))
14039 (setq gv `(org-cached-entry-get nil ,pn))))
14040 (if re-p
14041 (if (eq po 'org<>)
14042 `(not (string-match ,pv (or ,gv "")))
14043 `(string-match ,pv (or ,gv "")))
14044 (if str-p
14045 `(,po (or ,gv "") ,pv)
14046 `(,po (string-to-number (or ,gv ""))
14047 ,(string-to-number pv) ))))
14048 (t `(member ,tag tags-list)))
14049 mm (if minus (list 'not mm) mm)
14050 term rest)
14051 (push mm tagsmatcher))
14052 (push (if (> (length tagsmatcher) 1)
14053 (cons 'and tagsmatcher)
14054 (car tagsmatcher))
14055 orlist)
14056 (setq tagsmatcher nil))
14057 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14058 (setq tagsmatcher
14059 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14060 ;; Make the todo matcher
14061 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14062 (setq todomatcher t)
14063 (setq orterms (org-split-string todomatch "|") orlist nil)
14064 (while (setq term (pop orterms))
14065 (while (string-match re term)
14066 (setq minus (and (match-end 1)
14067 (equal (match-string 1 term) "-"))
14068 kwd (match-string 2 term)
14069 re-p (equal (string-to-char kwd) ?{)
14070 term (substring term (match-end 0))
14071 mm (if re-p
14072 `(string-match ,(substring kwd 1 -1) todo)
14073 (list 'equal 'todo kwd))
14074 mm (if minus (list 'not mm) mm))
14075 (push mm todomatcher))
14076 (push (if (> (length todomatcher) 1)
14077 (cons 'and todomatcher)
14078 (car todomatcher))
14079 orlist)
14080 (setq todomatcher nil))
14081 (setq todomatcher (if (> (length orlist) 1)
14082 (cons 'or orlist) (car orlist))))
14084 ;; Return the string and lisp forms of the matcher
14085 (setq matcher (if todomatcher
14086 (list 'and tagsmatcher todomatcher)
14087 tagsmatcher))
14088 (when todo-only
14089 (setq matcher (list 'and '(member todo org-not-done-keywords)
14090 matcher)))
14091 (cons match0 matcher)))
14093 (defun org-tags-expand (match &optional single-as-list downcased)
14094 "Expand group tags in MATCH.
14096 This replaces every group tag in MATCH with a regexp tag search.
14097 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14098 will be replaced like this:
14100 Work => {\(?:Work\|Lab\|Conf\}
14101 +Work => +{\(?:Work\|Lab\|Conf\}
14102 -Work => -{\(?:Work\|Lab\|Conf\}
14104 Replacing by a regexp preserves the structure of the match.
14105 E.g., this expansion
14107 Work|Home => {\(?:Work\|Lab\|Conf\}|Home
14109 will match anything tagged with \"Lab\" and \"Home\", or tagged
14110 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14112 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14113 assumed to be a single group tag, and the function will return
14114 the list of tags in this group.
14116 When DOWNCASE is non-nil, expand downcased TAGS."
14117 (if org-group-tags
14118 (let* ((case-fold-search t)
14119 (stable org-mode-syntax-table)
14120 (tal (or org-tag-groups-alist-for-agenda
14121 org-tag-groups-alist))
14122 (tal (if downcased (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14123 (tml (mapcar 'car tal))
14124 (rtnmatch match) rpl)
14125 ;; @ and _ are allowed as word-components in tags
14126 (modify-syntax-entry ?@ "w" stable)
14127 (modify-syntax-entry ?_ "w" stable)
14128 (while (and tml (string-match
14129 (concat "\\(?1:[+-]?\\)\\(?2:\\<" (regexp-opt tml) "\\>\\)")
14130 rtnmatch))
14131 (let* ((dir (match-string 1 rtnmatch))
14132 (tag (match-string 2 rtnmatch))
14133 (tag (if downcased (downcase tag) tag)))
14134 (setq tml (delete tag tml))
14135 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14136 (setq rtnmatch
14137 (replace-match
14138 (concat dir "{" (regexp-opt rpl) "}") t t rtnmatch))))
14139 (if single-as-list
14140 (or (reverse rpl) (list rtnmatch))
14141 rtnmatch))
14142 (if single-as-list (list (if downcased (downcase match) match))
14143 match)))
14145 (defun org-op-to-function (op &optional stringp)
14146 "Turn an operator into the appropriate function."
14147 (setq op
14148 (cond
14149 ((equal op "<" ) '(< string< org-time<))
14150 ((equal op ">" ) '(> org-string> org-time>))
14151 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14152 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14153 ((member op '("=" "==")) '(= string= org-time=))
14154 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14155 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14157 (defun org<> (a b) (not (= a b)))
14158 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14159 (defun org-string>= (a b) (not (string< a b)))
14160 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14161 (defun org-string<> (a b) (not (string= a b)))
14162 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14163 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14164 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14165 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14166 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14167 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14168 (defun org-2ft (s)
14169 "Convert S to a floating point time.
14170 If S is already a number, just return it. If it is a string, parse
14171 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14172 (cond
14173 ((numberp s) s)
14174 ((stringp s)
14175 (condition-case nil
14176 (float-time (apply 'encode-time (org-parse-time-string s)))
14177 (error 0.)))
14178 (t 0.)))
14180 (defun org-time-today ()
14181 "Time in seconds today at 0:00.
14182 Returns the float number of seconds since the beginning of the
14183 epoch to the beginning of today (00:00)."
14184 (float-time (apply 'encode-time
14185 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14187 (defun org-matcher-time (s)
14188 "Interpret a time comparison value."
14189 (save-match-data
14190 (cond
14191 ((string= s "<now>") (float-time))
14192 ((string= s "<today>") (org-time-today))
14193 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14194 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14195 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14196 (+ (org-time-today)
14197 (* (string-to-number (match-string 1 s))
14198 (cdr (assoc (match-string 2 s)
14199 '(("d" . 86400.0) ("w" . 604800.0)
14200 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14201 (t (org-2ft s)))))
14203 (defun org-match-any-p (re list)
14204 "Does re match any element of list?"
14205 (setq list (mapcar (lambda (x) (string-match re x)) list))
14206 (delq nil list))
14208 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14209 (defvar org-tags-overlay (make-overlay 1 1))
14210 (org-detach-overlay org-tags-overlay)
14212 (defun org-get-local-tags-at (&optional pos)
14213 "Get a list of tags defined in the current headline."
14214 (org-get-tags-at pos 'local))
14216 (defun org-get-local-tags ()
14217 "Get a list of tags defined in the current headline."
14218 (org-get-tags-at nil 'local))
14220 (defun org-get-tags-at (&optional pos local)
14221 "Get a list of all headline tags applicable at POS.
14222 POS defaults to point. If tags are inherited, the list contains
14223 the targets in the same sequence as the headlines appear, i.e.
14224 the tags of the current headline come last.
14225 When LOCAL is non-nil, only return tags from the current headline,
14226 ignore inherited ones."
14227 (interactive)
14228 (if (and org-trust-scanner-tags
14229 (or (not pos) (equal pos (point)))
14230 (not local))
14231 org-scanner-tags
14232 (let (tags ltags lastpos parent)
14233 (save-excursion
14234 (save-restriction
14235 (widen)
14236 (goto-char (or pos (point)))
14237 (save-match-data
14238 (catch 'done
14239 (condition-case nil
14240 (progn
14241 (org-back-to-heading t)
14242 (while (not (equal lastpos (point)))
14243 (setq lastpos (point))
14244 (when (looking-at
14245 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14246 (setq ltags (org-split-string
14247 (org-match-string-no-properties 1) ":"))
14248 (when parent
14249 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14250 (setq tags (append
14251 (if parent
14252 (org-remove-uninherited-tags ltags)
14253 ltags)
14254 tags)))
14255 (or org-use-tag-inheritance (throw 'done t))
14256 (if local (throw 'done t))
14257 (or (org-up-heading-safe) (error nil))
14258 (setq parent t)))
14259 (error nil)))))
14260 (if local
14261 tags
14262 (reverse (delete-dups
14263 (reverse (append
14264 (org-remove-uninherited-tags
14265 org-file-tags) tags)))))))))
14267 (defun org-add-prop-inherited (s)
14268 (add-text-properties 0 (length s) '(inherited t) s)
14271 (defun org-toggle-tag (tag &optional onoff)
14272 "Toggle the tag TAG for the current line.
14273 If ONOFF is `on' or `off', don't toggle but set to this state."
14274 (let (res current)
14275 (save-excursion
14276 (org-back-to-heading t)
14277 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14278 (point-at-eol) t)
14279 (progn
14280 (setq current (match-string 1))
14281 (replace-match ""))
14282 (setq current ""))
14283 (setq current (nreverse (org-split-string current ":")))
14284 (cond
14285 ((eq onoff 'on)
14286 (setq res t)
14287 (or (member tag current) (push tag current)))
14288 ((eq onoff 'off)
14289 (or (not (member tag current)) (setq current (delete tag current))))
14290 (t (if (member tag current)
14291 (setq current (delete tag current))
14292 (setq res t)
14293 (push tag current))))
14294 (end-of-line 1)
14295 (if current
14296 (progn
14297 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14298 (org-set-tags nil t))
14299 (delete-horizontal-space))
14300 (run-hooks 'org-after-tags-change-hook))
14301 res))
14303 (defun org-align-tags-here (to-col)
14304 ;; Assumes that this is a headline
14305 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14306 (beginning-of-line 1)
14307 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14308 (< pos (match-beginning 2)))
14309 (progn
14310 (setq tags-l (- (match-end 2) (match-beginning 2)))
14311 (goto-char (match-beginning 1))
14312 (insert " ")
14313 (delete-region (point) (1+ (match-beginning 2)))
14314 (setq ncol (max (current-column)
14315 (1+ col)
14316 (if (> to-col 0)
14317 to-col
14318 (- (abs to-col) tags-l))))
14319 (setq p (point))
14320 (insert (make-string (- ncol (current-column)) ?\ ))
14321 (setq ncol (current-column))
14322 (when indent-tabs-mode (tabify p (point-at-eol)))
14323 (org-move-to-column (min ncol col) t))
14324 (goto-char pos))))
14326 (defun org-set-tags-command (&optional arg just-align)
14327 "Call the set-tags command for the current entry."
14328 (interactive "P")
14329 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14330 (org-set-tags arg just-align)
14331 (save-excursion
14332 (unless (and (org-region-active-p)
14333 org-loop-over-headlines-in-active-region)
14334 (org-back-to-heading t))
14335 (org-set-tags arg just-align))))
14337 (defun org-set-tags-to (data)
14338 "Set the tags of the current entry to DATA, replacing the current tags.
14339 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14340 If DATA is nil or the empty string, any tags will be removed."
14341 (interactive "sTags: ")
14342 (setq data
14343 (cond
14344 ((eq data nil) "")
14345 ((equal data "") "")
14346 ((stringp data)
14347 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14348 ":"))
14349 ((listp data)
14350 (concat ":" (mapconcat 'identity data ":") ":"))))
14351 (when data
14352 (save-excursion
14353 (org-back-to-heading t)
14354 (when (looking-at org-complex-heading-regexp)
14355 (if (match-end 5)
14356 (progn
14357 (goto-char (match-beginning 5))
14358 (insert data)
14359 (delete-region (point) (point-at-eol))
14360 (org-set-tags nil 'align))
14361 (goto-char (point-at-eol))
14362 (insert " " data)
14363 (org-set-tags nil 'align)))
14364 (beginning-of-line 1)
14365 (if (looking-at ".*?\\([ \t]+\\)$")
14366 (delete-region (match-beginning 1) (match-end 1))))))
14368 (defun org-align-all-tags ()
14369 "Align the tags i all headings."
14370 (interactive)
14371 (save-excursion
14372 (or (ignore-errors (org-back-to-heading t))
14373 (outline-next-heading))
14374 (if (org-at-heading-p)
14375 (org-set-tags t)
14376 (message "No headings"))))
14378 (defvar org-indent-indentation-per-level)
14379 (defun org-set-tags (&optional arg just-align)
14380 "Set the tags for the current headline.
14381 With prefix ARG, realign all tags in headings in the current buffer."
14382 (interactive "P")
14383 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14384 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14385 'region-start-level 'region))
14386 org-loop-over-headlines-in-active-region)
14387 (org-map-entries
14388 ;; We don't use ARG and JUST-ALIGN here these args are not
14389 ;; useful when looping over headlines
14390 `(org-set-tags)
14391 org-loop-over-headlines-in-active-region
14392 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14393 (let* ((re org-outline-regexp-bol)
14394 (current (unless arg (org-get-tags-string)))
14395 (col (current-column))
14396 (org-setting-tags t)
14397 table current-tags inherited-tags ; computed below when needed
14398 tags p0 c0 c1 rpl di tc level)
14399 (if arg
14400 (save-excursion
14401 (goto-char (point-min))
14402 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14403 (while (re-search-forward re nil t)
14404 (org-set-tags nil t)
14405 (end-of-line 1)))
14406 (message "All tags realigned to column %d" org-tags-column))
14407 (if just-align
14408 (setq tags current)
14409 ;; Get a new set of tags from the user
14410 (save-excursion
14411 (setq table (append org-tag-persistent-alist
14412 (or org-tag-alist (org-get-buffer-tags))
14413 (and
14414 org-complete-tags-always-offer-all-agenda-tags
14415 (org-global-tags-completion-table
14416 (org-agenda-files))))
14417 org-last-tags-completion-table table
14418 current-tags (org-split-string current ":")
14419 inherited-tags (nreverse
14420 (nthcdr (length current-tags)
14421 (nreverse (org-get-tags-at))))
14422 tags
14423 (if (or (eq t org-use-fast-tag-selection)
14424 (and org-use-fast-tag-selection
14425 (delq nil (mapcar 'cdr table))))
14426 (org-fast-tag-selection
14427 current-tags inherited-tags table
14428 (if org-fast-tag-selection-include-todo
14429 org-todo-key-alist))
14430 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14431 (org-trim
14432 (org-icompleting-read "Tags: "
14433 'org-tags-completion-function
14434 nil nil current 'org-tags-history))))))
14435 (while (string-match "[-+&]+" tags)
14436 ;; No boolean logic, just a list
14437 (setq tags (replace-match ":" t t tags))))
14439 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14441 (if org-tags-sort-function
14442 (setq tags (mapconcat 'identity
14443 (sort (org-split-string
14444 tags (org-re "[^[:alnum:]_@#%]+"))
14445 org-tags-sort-function) ":")))
14447 (if (string-match "\\`[\t ]*\\'" tags)
14448 (setq tags "")
14449 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14450 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14452 ;; Insert new tags at the correct column
14453 (beginning-of-line 1)
14454 (setq level (or (and (looking-at org-outline-regexp)
14455 (- (match-end 0) (point) 1))
14457 (cond
14458 ((and (equal current "") (equal tags "")))
14459 ((re-search-forward
14460 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14461 (point-at-eol) t)
14462 (if (equal tags "")
14463 (setq rpl "")
14464 (goto-char (match-beginning 0))
14465 (setq c0 (current-column)
14466 ;; compute offset for the case of org-indent-mode active
14467 di (if org-indent-mode
14468 (* (1- org-indent-indentation-per-level) (1- level))
14470 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14471 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14472 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14473 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14474 (replace-match rpl t t)
14475 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14476 tags)
14477 (t (error "Tags alignment failed")))
14478 (org-move-to-column col)
14479 (unless just-align
14480 (run-hooks 'org-after-tags-change-hook))))))
14482 (defun org-change-tag-in-region (beg end tag off)
14483 "Add or remove TAG for each entry in the region.
14484 This works in the agenda, and also in an org-mode buffer."
14485 (interactive
14486 (list (region-beginning) (region-end)
14487 (let ((org-last-tags-completion-table
14488 (if (derived-mode-p 'org-mode)
14489 (org-get-buffer-tags)
14490 (org-global-tags-completion-table))))
14491 (org-icompleting-read
14492 "Tag: " 'org-tags-completion-function nil nil nil
14493 'org-tags-history))
14494 (progn
14495 (message "[s]et or [r]emove? ")
14496 (equal (read-char-exclusive) ?r))))
14497 (if (fboundp 'deactivate-mark) (deactivate-mark))
14498 (let ((agendap (equal major-mode 'org-agenda-mode))
14499 l1 l2 m buf pos newhead (cnt 0))
14500 (goto-char end)
14501 (setq l2 (1- (org-current-line)))
14502 (goto-char beg)
14503 (setq l1 (org-current-line))
14504 (loop for l from l1 to l2 do
14505 (org-goto-line l)
14506 (setq m (get-text-property (point) 'org-hd-marker))
14507 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14508 (and agendap m))
14509 (setq buf (if agendap (marker-buffer m) (current-buffer))
14510 pos (if agendap m (point)))
14511 (with-current-buffer buf
14512 (save-excursion
14513 (save-restriction
14514 (goto-char pos)
14515 (setq cnt (1+ cnt))
14516 (org-toggle-tag tag (if off 'off 'on))
14517 (setq newhead (org-get-heading)))))
14518 (and agendap (org-agenda-change-all-lines newhead m))))
14519 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14521 (defun org-tags-completion-function (string predicate &optional flag)
14522 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14523 (confirm (lambda (x) (stringp (car x)))))
14524 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14525 (setq s1 (match-string 1 string)
14526 s2 (match-string 2 string))
14527 (setq s1 "" s2 string))
14528 (cond
14529 ((eq flag nil)
14530 ;; try completion
14531 (setq rtn (try-completion s2 ctable confirm))
14532 (if (stringp rtn)
14533 (setq rtn
14534 (concat s1 s2 (substring rtn (length s2))
14535 (if (and org-add-colon-after-tag-completion
14536 (assoc rtn ctable))
14537 ":" ""))))
14538 rtn)
14539 ((eq flag t)
14540 ;; all-completions
14541 (all-completions s2 ctable confirm))
14542 ((eq flag 'lambda)
14543 ;; exact match?
14544 (assoc s2 ctable)))))
14546 (defun org-fast-tag-insert (kwd tags face &optional end)
14547 "Insert KDW, and the TAGS, the latter with face FACE.
14548 Also insert END."
14549 (insert (format "%-12s" (concat kwd ":"))
14550 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14551 (or end "")))
14553 (defun org-fast-tag-show-exit (flag)
14554 (save-excursion
14555 (org-goto-line 3)
14556 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14557 (replace-match ""))
14558 (when flag
14559 (end-of-line 1)
14560 (org-move-to-column (- (window-width) 19) t)
14561 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14563 (defun org-set-current-tags-overlay (current prefix)
14564 "Add an overlay to CURRENT tag with PREFIX."
14565 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14566 (if (featurep 'xemacs)
14567 (org-overlay-display org-tags-overlay (concat prefix s)
14568 'secondary-selection)
14569 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14570 (org-overlay-display org-tags-overlay (concat prefix s)))))
14572 (defvar org-last-tag-selection-key nil)
14573 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14574 "Fast tag selection with single keys.
14575 CURRENT is the current list of tags in the headline, INHERITED is the
14576 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14577 possibly with grouping information. TODO-TABLE is a similar table with
14578 TODO keywords, should these have keys assigned to them.
14579 If the keys are nil, a-z are automatically assigned.
14580 Returns the new tags string, or nil to not change the current settings."
14581 (let* ((fulltable (append table todo-table))
14582 (maxlen (apply 'max (mapcar
14583 (lambda (x)
14584 (if (stringp (car x)) (string-width (car x)) 0))
14585 fulltable)))
14586 (buf (current-buffer))
14587 (expert (eq org-fast-tag-selection-single-key 'expert))
14588 (buffer-tags nil)
14589 (fwidth (+ maxlen 3 1 3))
14590 (ncol (/ (- (window-width) 4) fwidth))
14591 (i-face 'org-done)
14592 (c-face 'org-todo)
14593 tg cnt e c char c1 c2 ntable tbl rtn
14594 ov-start ov-end ov-prefix
14595 (exit-after-next org-fast-tag-selection-single-key)
14596 (done-keywords org-done-keywords)
14597 groups ingroup)
14598 (save-excursion
14599 (beginning-of-line 1)
14600 (if (looking-at
14601 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14602 (setq ov-start (match-beginning 1)
14603 ov-end (match-end 1)
14604 ov-prefix "")
14605 (setq ov-start (1- (point-at-eol))
14606 ov-end (1+ ov-start))
14607 (skip-chars-forward "^\n\r")
14608 (setq ov-prefix
14609 (concat
14610 (buffer-substring (1- (point)) (point))
14611 (if (> (current-column) org-tags-column)
14613 (make-string (- org-tags-column (current-column)) ?\ ))))))
14614 (move-overlay org-tags-overlay ov-start ov-end)
14615 (save-window-excursion
14616 (if expert
14617 (set-buffer (get-buffer-create " *Org tags*"))
14618 (delete-other-windows)
14619 (split-window-vertically)
14620 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14621 (erase-buffer)
14622 (org-set-local 'org-done-keywords done-keywords)
14623 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14624 (org-fast-tag-insert "Current" current c-face "\n\n")
14625 (org-fast-tag-show-exit exit-after-next)
14626 (org-set-current-tags-overlay current ov-prefix)
14627 (setq tbl fulltable char ?a cnt 0)
14628 (while (setq e (pop tbl))
14629 (cond
14630 ((equal (car e) :startgroup)
14631 (push '() groups) (setq ingroup t)
14632 (when (not (= cnt 0))
14633 (setq cnt 0)
14634 (insert "\n"))
14635 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14636 ((equal (car e) :endgroup)
14637 (setq ingroup nil cnt 0)
14638 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14639 ((equal e '(:newline))
14640 (when (not (= cnt 0))
14641 (setq cnt 0)
14642 (insert "\n")
14643 (setq e (car tbl))
14644 (while (equal (car tbl) '(:newline))
14645 (insert "\n")
14646 (setq tbl (cdr tbl)))))
14647 ((equal e '(:grouptags)) nil)
14649 (setq tg (copy-sequence (car e)) c2 nil)
14650 (if (cdr e)
14651 (setq c (cdr e))
14652 ;; automatically assign a character.
14653 (setq c1 (string-to-char
14654 (downcase (substring
14655 tg (if (= (string-to-char tg) ?@) 1 0)))))
14656 (if (or (rassoc c1 ntable) (rassoc c1 table))
14657 (while (or (rassoc char ntable) (rassoc char table))
14658 (setq char (1+ char)))
14659 (setq c2 c1))
14660 (setq c (or c2 char)))
14661 (if ingroup (push tg (car groups)))
14662 (setq tg (org-add-props tg nil 'face
14663 (cond
14664 ((not (assoc tg table))
14665 (org-get-todo-face tg))
14666 ((member tg current) c-face)
14667 ((member tg inherited) i-face))))
14668 (if (equal (caar tbl) :grouptags)
14669 (org-add-props tg nil 'face 'org-tag-group))
14670 (if (and (= cnt 0) (not ingroup)) (insert " "))
14671 (insert "[" c "] " tg (make-string
14672 (- fwidth 4 (length tg)) ?\ ))
14673 (push (cons tg c) ntable)
14674 (when (= (setq cnt (1+ cnt)) ncol)
14675 (insert "\n")
14676 (if ingroup (insert " "))
14677 (setq cnt 0)))))
14678 (setq ntable (nreverse ntable))
14679 (insert "\n")
14680 (goto-char (point-min))
14681 (if (not expert) (org-fit-window-to-buffer))
14682 (setq rtn
14683 (catch 'exit
14684 (while t
14685 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14686 (if (not groups) "no " "")
14687 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14688 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14689 (setq org-last-tag-selection-key c)
14690 (cond
14691 ((= c ?\r) (throw 'exit t))
14692 ((= c ?!)
14693 (setq groups (not groups))
14694 (goto-char (point-min))
14695 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14696 ((= c ?\C-c)
14697 (if (not expert)
14698 (org-fast-tag-show-exit
14699 (setq exit-after-next (not exit-after-next)))
14700 (setq expert nil)
14701 (delete-other-windows)
14702 (set-window-buffer (split-window-vertically) " *Org tags*")
14703 (org-switch-to-buffer-other-window " *Org tags*")
14704 (org-fit-window-to-buffer)))
14705 ((or (= c ?\C-g)
14706 (and (= c ?q) (not (rassoc c ntable))))
14707 (org-detach-overlay org-tags-overlay)
14708 (setq quit-flag t))
14709 ((= c ?\ )
14710 (setq current nil)
14711 (if exit-after-next (setq exit-after-next 'now)))
14712 ((= c ?\t)
14713 (condition-case nil
14714 (setq tg (org-icompleting-read
14715 "Tag: "
14716 (or buffer-tags
14717 (with-current-buffer buf
14718 (org-get-buffer-tags)))))
14719 (quit (setq tg "")))
14720 (when (string-match "\\S-" tg)
14721 (add-to-list 'buffer-tags (list tg))
14722 (if (member tg current)
14723 (setq current (delete tg current))
14724 (push tg current)))
14725 (if exit-after-next (setq exit-after-next 'now)))
14726 ((setq e (rassoc c todo-table) tg (car e))
14727 (with-current-buffer buf
14728 (save-excursion (org-todo tg)))
14729 (if exit-after-next (setq exit-after-next 'now)))
14730 ((setq e (rassoc c ntable) tg (car e))
14731 (if (member tg current)
14732 (setq current (delete tg current))
14733 (loop for g in groups do
14734 (if (member tg g)
14735 (mapc (lambda (x)
14736 (setq current (delete x current)))
14737 g)))
14738 (push tg current))
14739 (if exit-after-next (setq exit-after-next 'now))))
14741 ;; Create a sorted list
14742 (setq current
14743 (sort current
14744 (lambda (a b)
14745 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14746 (if (eq exit-after-next 'now) (throw 'exit t))
14747 (goto-char (point-min))
14748 (beginning-of-line 2)
14749 (delete-region (point) (point-at-eol))
14750 (org-fast-tag-insert "Current" current c-face)
14751 (org-set-current-tags-overlay current ov-prefix)
14752 (while (re-search-forward
14753 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14754 (setq tg (match-string 1))
14755 (add-text-properties
14756 (match-beginning 1) (match-end 1)
14757 (list 'face
14758 (cond
14759 ((member tg current) c-face)
14760 ((member tg inherited) i-face)
14761 (t (get-text-property (match-beginning 1) 'face))))))
14762 (goto-char (point-min)))))
14763 (org-detach-overlay org-tags-overlay)
14764 (if rtn
14765 (mapconcat 'identity current ":")
14766 nil))))
14768 (defun org-get-tags-string ()
14769 "Get the TAGS string in the current headline."
14770 (unless (org-at-heading-p t)
14771 (error "Not on a heading"))
14772 (save-excursion
14773 (beginning-of-line 1)
14774 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14775 (org-match-string-no-properties 1)
14776 "")))
14778 (defun org-get-tags ()
14779 "Get the list of tags specified in the current headline."
14780 (org-split-string (org-get-tags-string) ":"))
14782 (defun org-get-buffer-tags ()
14783 "Get a table of all tags used in the buffer, for completion."
14784 (let (tags)
14785 (save-excursion
14786 (goto-char (point-min))
14787 (while (re-search-forward
14788 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14789 (when (equal (char-after (point-at-bol 0)) ?*)
14790 (mapc (lambda (x) (add-to-list 'tags x))
14791 (org-split-string (org-match-string-no-properties 1) ":")))))
14792 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14793 (mapcar 'list tags)))
14795 ;;;; The mapping API
14797 (defun org-map-entries (func &optional match scope &rest skip)
14798 "Call FUNC at each headline selected by MATCH in SCOPE.
14800 FUNC is a function or a lisp form. The function will be called without
14801 arguments, with the cursor positioned at the beginning of the headline.
14802 The return values of all calls to the function will be collected and
14803 returned as a list.
14805 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14806 does not need to preserve point. After evaluation, the cursor will be
14807 moved to the end of the line (presumably of the headline of the
14808 processed entry) and search continues from there. Under some
14809 circumstances, this may not produce the wanted results. For example,
14810 if you have removed (e.g. archived) the current (sub)tree it could
14811 mean that the next entry will be skipped entirely. In such cases, you
14812 can specify the position from where search should continue by making
14813 FUNC set the variable `org-map-continue-from' to the desired buffer
14814 position.
14816 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14817 Only headlines that are matched by this query will be considered during
14818 the iteration. When MATCH is nil or t, all headlines will be
14819 visited by the iteration.
14821 SCOPE determines the scope of this command. It can be any of:
14823 nil The current buffer, respecting the restriction if any
14824 tree The subtree started with the entry at point
14825 region The entries within the active region, if any
14826 region-start-level
14827 The entries within the active region, but only those at
14828 the same level than the first one.
14829 file The current buffer, without restriction
14830 file-with-archives
14831 The current buffer, and any archives associated with it
14832 agenda All agenda files
14833 agenda-with-archives
14834 All agenda files with any archive files associated with them
14835 \(file1 file2 ...)
14836 If this is a list, all files in the list will be scanned
14838 The remaining args are treated as settings for the skipping facilities of
14839 the scanner. The following items can be given here:
14841 archive skip trees with the archive tag
14842 comment skip trees with the COMMENT keyword
14843 function or Emacs Lisp form:
14844 will be used as value for `org-agenda-skip-function', so
14845 whenever the function returns a position, FUNC will not be
14846 called for that entry and search will continue from the
14847 position returned
14849 If your function needs to retrieve the tags including inherited tags
14850 at the *current* entry, you can use the value of the variable
14851 `org-scanner-tags' which will be much faster than getting the value
14852 with `org-get-tags-at'. If your function gets properties with
14853 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14854 to t around the call to `org-entry-properties' to get the same speedup.
14855 Note that if your function moves around to retrieve tags and properties at
14856 a *different* entry, you cannot use these techniques."
14857 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14858 (not (org-region-active-p)))
14859 (let* ((org-agenda-archives-mode nil) ; just to make sure
14860 (org-agenda-skip-archived-trees (memq 'archive skip))
14861 (org-agenda-skip-comment-trees (memq 'comment skip))
14862 (org-agenda-skip-function
14863 (car (org-delete-all '(comment archive) skip)))
14864 (org-tags-match-list-sublevels t)
14865 (start-level (eq scope 'region-start-level))
14866 matcher file res
14867 org-todo-keywords-for-agenda
14868 org-done-keywords-for-agenda
14869 org-todo-keyword-alist-for-agenda
14870 org-drawers-for-agenda
14871 org-tag-alist-for-agenda
14872 todo-only)
14874 (cond
14875 ((eq match t) (setq matcher t))
14876 ((eq match nil) (setq matcher t))
14877 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14879 (save-window-excursion
14880 (save-restriction
14881 (cond ((eq scope 'tree)
14882 (org-back-to-heading t)
14883 (org-narrow-to-subtree)
14884 (setq scope nil))
14885 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14886 (org-region-active-p))
14887 ;; If needed, set start-level to a string like "2"
14888 (when start-level
14889 (save-excursion
14890 (goto-char (region-beginning))
14891 (unless (org-at-heading-p) (outline-next-heading))
14892 (setq start-level (org-current-level))))
14893 (narrow-to-region (region-beginning)
14894 (save-excursion
14895 (goto-char (region-end))
14896 (unless (and (bolp) (org-at-heading-p))
14897 (outline-next-heading))
14898 (point)))
14899 (setq scope nil)))
14901 (if (not scope)
14902 (progn
14903 (org-agenda-prepare-buffers
14904 (list (buffer-file-name (current-buffer))))
14905 (setq res (org-scan-tags func matcher todo-only start-level)))
14906 ;; Get the right scope
14907 (cond
14908 ((and scope (listp scope) (symbolp (car scope)))
14909 (setq scope (eval scope)))
14910 ((eq scope 'agenda)
14911 (setq scope (org-agenda-files t)))
14912 ((eq scope 'agenda-with-archives)
14913 (setq scope (org-agenda-files t))
14914 (setq scope (org-add-archive-files scope)))
14915 ((eq scope 'file)
14916 (setq scope (list (buffer-file-name))))
14917 ((eq scope 'file-with-archives)
14918 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14919 (org-agenda-prepare-buffers scope)
14920 (while (setq file (pop scope))
14921 (with-current-buffer (org-find-base-buffer-visiting file)
14922 (save-excursion
14923 (save-restriction
14924 (widen)
14925 (goto-char (point-min))
14926 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14927 res)))
14929 ;;;; Properties
14931 ;;; Setting and retrieving properties
14933 (defconst org-special-properties
14934 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14935 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14936 "The special properties valid in Org-mode.
14938 These are properties that are not defined in the property drawer,
14939 but in some other way.")
14941 (defconst org-default-properties
14942 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14943 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14944 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14945 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14946 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14947 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14948 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14949 "Some properties that are used by Org-mode for various purposes.
14950 Being in this list makes sure that they are offered for completion.")
14952 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14953 "Regular expression matching the first line of a property drawer.")
14955 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14956 "Regular expression matching the last line of a property drawer.")
14958 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14959 "Regular expression matching the first line of a property drawer.")
14961 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14962 "Regular expression matching the first line of a property drawer.")
14964 (defconst org-property-drawer-re
14965 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14966 org-property-end-re "\\)\n?")
14967 "Matches an entire property drawer.")
14969 (defconst org-clock-drawer-re
14970 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14971 org-property-end-re "\\)\n?")
14972 "Matches an entire clock drawer.")
14974 (defsubst org-re-property (property)
14975 "Return a regexp matching a PROPERTY line.
14976 Match group 1 will be set to the value."
14977 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14979 (defsubst org-re-property-keyword (property)
14980 "Return a regexp matching a PROPERTY line, possibly with no
14981 value for the property."
14982 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14984 (defun org-property-action ()
14985 "Do an action on properties."
14986 (interactive)
14987 (let (c)
14988 (org-at-property-p)
14989 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14990 (setq c (read-char-exclusive))
14991 (cond
14992 ((equal c ?s)
14993 (call-interactively 'org-set-property))
14994 ((equal c ?d)
14995 (call-interactively 'org-delete-property))
14996 ((equal c ?D)
14997 (call-interactively 'org-delete-property-globally))
14998 ((equal c ?c)
14999 (call-interactively 'org-compute-property-at-point))
15000 (t (error "No such property action %c" c)))))
15002 (defun org-inc-effort ()
15003 "Increment the value of the effort property in the current entry."
15004 (interactive)
15005 (org-set-effort nil t))
15007 (defvar org-clock-effort) ;; Defined in org-clock.el
15008 (defvar org-clock-current-task) ;; Defined in org-clock.el
15009 (defun org-set-effort (&optional value increment)
15010 "Set the effort property of the current entry.
15011 With numerical prefix arg, use the nth allowed value, 0 stands for the
15012 10th allowed value.
15014 When INCREMENT is non-nil, set the property to the next allowed value."
15015 (interactive "P")
15016 (if (equal value 0) (setq value 10))
15017 (let* ((completion-ignore-case t)
15018 (prop org-effort-property)
15019 (cur (org-entry-get nil prop))
15020 (allowed (org-property-get-allowed-values nil prop 'table))
15021 (existing (mapcar 'list (org-property-values prop)))
15022 (heading (nth 4 (org-heading-components)))
15024 (val (cond
15025 ((stringp value) value)
15026 ((and allowed (integerp value))
15027 (or (car (nth (1- value) allowed))
15028 (car (org-last allowed))))
15029 ((and allowed increment)
15030 (or (caadr (member (list cur) allowed))
15031 (error "Allowed effort values are not set")))
15032 (allowed
15033 (message "Select 1-9,0, [RET%s]: %s"
15034 (if cur (concat "=" cur) "")
15035 (mapconcat 'car allowed " "))
15036 (setq rpl (read-char-exclusive))
15037 (if (equal rpl ?\r)
15039 (setq rpl (- rpl ?0))
15040 (if (equal rpl 0) (setq rpl 10))
15041 (if (and (> rpl 0) (<= rpl (length allowed)))
15042 (car (nth (1- rpl) allowed))
15043 (org-completing-read "Effort: " allowed nil))))
15045 (let (org-completion-use-ido org-completion-use-iswitchb)
15046 (org-completing-read
15047 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15048 (concat "[" cur "]") "")
15049 ": ")
15050 existing nil nil "" nil cur))))))
15051 (unless (equal (org-entry-get nil prop) val)
15052 (org-entry-put nil prop val))
15053 (save-excursion
15054 (org-back-to-heading t)
15055 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15056 (when (string= heading org-clock-current-task)
15057 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15058 (org-clock-update-mode-line))
15059 (message "%s is now %s" prop val)))
15061 (defun org-at-property-p ()
15062 "Is cursor inside a property drawer?"
15063 (save-excursion
15064 (beginning-of-line 1)
15065 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
15066 (save-match-data ;; Used by calling procedures
15067 (let ((p (point))
15068 (range (unless (org-before-first-heading-p)
15069 (org-get-property-block))))
15070 (and range (<= (car range) p) (< p (cdr range))))))))
15072 (defun org-get-property-block (&optional beg end force)
15073 "Return the (beg . end) range of the body of the property drawer.
15074 BEG and END are the beginning and end of the current subtree, or of
15075 the part before the first headline. If they are not given, they will
15076 be found. If the drawer does not exist and FORCE is non-nil, create
15077 the drawer."
15078 (catch 'exit
15079 (save-excursion
15080 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15081 (progn (org-back-to-heading t) (point))))
15082 (end (or end (and (not (outline-next-heading)) (point-max))
15083 (point))))
15084 (goto-char beg)
15085 (if (re-search-forward org-property-start-re end t)
15086 (setq beg (1+ (match-end 0)))
15087 (if force
15088 (save-excursion
15089 (org-insert-property-drawer)
15090 (setq end (progn (outline-next-heading) (point))))
15091 (throw 'exit nil))
15092 (goto-char beg)
15093 (if (re-search-forward org-property-start-re end t)
15094 (setq beg (1+ (match-end 0)))))
15095 (if (re-search-forward org-property-end-re end t)
15096 (setq end (match-beginning 0))
15097 (or force (throw 'exit nil))
15098 (goto-char beg)
15099 (setq end beg)
15100 (org-indent-line)
15101 (insert ":END:\n"))
15102 (cons beg end)))))
15104 (defun org-entry-properties (&optional pom which specific)
15105 "Get all properties of the entry at point-or-marker POM.
15106 This includes the TODO keyword, the tags, time strings for deadline,
15107 scheduled, and clocking, and any additional properties defined in the
15108 entry. The return value is an alist, keys may occur multiple times
15109 if the property key was used several times.
15110 POM may also be nil, in which case the current entry is used.
15111 If WHICH is nil or `all', get all properties. If WHICH is
15112 `special' or `standard', only get that subclass. If WHICH
15113 is a string only get exactly this property. SPECIFIC can be a string, the
15114 specific property we are interested in. Specifying it can speed
15115 things up because then unnecessary parsing is avoided."
15116 (setq which (or which 'all))
15117 (org-with-point-at pom
15118 (let ((clockstr (substring org-clock-string 0 -1))
15119 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15120 (case-fold-search nil)
15121 beg end range props sum-props key key1 value string clocksum clocksumt)
15122 (save-excursion
15123 (when (condition-case nil
15124 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
15125 (error nil))
15126 (setq beg (point))
15127 (setq sum-props (get-text-property (point) 'org-summaries))
15128 (setq clocksum (get-text-property (point) :org-clock-minutes)
15129 clocksumt (get-text-property (point) :org-clock-minutes-today))
15130 (outline-next-heading)
15131 (setq end (point))
15132 (when (memq which '(all special))
15133 ;; Get the special properties, like TODO and tags
15134 (goto-char beg)
15135 (when (and (or (not specific) (string= specific "TODO"))
15136 (looking-at org-todo-line-regexp) (match-end 2))
15137 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15138 (when (and (or (not specific) (string= specific "PRIORITY"))
15139 (looking-at org-priority-regexp))
15140 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15141 (when (or (not specific) (string= specific "FILE"))
15142 (push (cons "FILE" buffer-file-name) props))
15143 (when (and (or (not specific) (string= specific "TAGS"))
15144 (setq value (org-get-tags-string))
15145 (string-match "\\S-" value))
15146 (push (cons "TAGS" value) props))
15147 (when (and (or (not specific) (string= specific "ALLTAGS"))
15148 (setq value (org-get-tags-at)))
15149 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15150 ":"))
15151 props))
15152 (when (or (not specific) (string= specific "BLOCKED"))
15153 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15154 (when (or (not specific)
15155 (member specific
15156 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15157 "TIMESTAMP" "TIMESTAMP_IA")))
15158 (catch 'match
15159 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15160 (setq key (if (match-end 1)
15161 (substring (org-match-string-no-properties 1)
15162 0 -1))
15163 string (if (equal key clockstr)
15164 (org-trim
15165 (buffer-substring-no-properties
15166 (match-beginning 3) (goto-char
15167 (point-at-eol))))
15168 (substring (org-match-string-no-properties 3)
15169 1 -1)))
15170 ;; Get the correct property name from the key. This is
15171 ;; necessary if the user has configured time keywords.
15172 (setq key1 (concat key ":"))
15173 (cond
15174 ((not key)
15175 (setq key
15176 (if (= (char-after (match-beginning 3)) ?\[)
15177 "TIMESTAMP_IA" "TIMESTAMP")))
15178 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15179 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15180 ((equal key1 org-closed-string) (setq key "CLOSED"))
15181 ((equal key1 org-clock-string) (setq key "CLOCK")))
15182 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15183 (progn
15184 (push (cons key string) props)
15185 ;; no need to search further if match is found
15186 (throw 'match t))
15187 (when (or (equal key "CLOCK") (not (assoc key props)))
15188 (push (cons key string) props)))))))
15190 (when (memq which '(all standard))
15191 ;; Get the standard properties, like :PROP: ...
15192 (setq range (org-get-property-block beg end))
15193 (when range
15194 (goto-char (car range))
15195 (while (re-search-forward
15196 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15197 (cdr range) t)
15198 (setq key (org-match-string-no-properties 1)
15199 value (org-trim (or (org-match-string-no-properties 2) "")))
15200 (unless (member key excluded)
15201 (push (cons key (or value "")) props)))))
15202 (if clocksum
15203 (push (cons "CLOCKSUM"
15204 (org-columns-number-to-string (/ (float clocksum) 60.)
15205 'add_times))
15206 props))
15207 (if clocksumt
15208 (push (cons "CLOCKSUM_T"
15209 (org-columns-number-to-string (/ (float clocksumt) 60.)
15210 'add_times))
15211 props))
15212 (unless (assoc "CATEGORY" props)
15213 (push (cons "CATEGORY" (org-get-category)) props))
15214 (append sum-props (nreverse props)))))))
15216 (defun org-entry-get (pom property &optional inherit literal-nil)
15217 "Get value of PROPERTY for entry or content at point-or-marker POM.
15218 If INHERIT is non-nil and the entry does not have the property,
15219 then also check higher levels of the hierarchy.
15220 If INHERIT is the symbol `selective', use inheritance only if the setting
15221 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15222 If the property is present but empty, the return value is the empty string.
15223 If the property is not present at all, nil is returned.
15225 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15226 do not interpret it as the list atom nil. This is used for inheritance
15227 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15228 (org-with-point-at pom
15229 (if (and inherit (if (eq inherit 'selective)
15230 (org-property-inherit-p property)
15232 (org-entry-get-with-inheritance property literal-nil)
15233 (if (member property org-special-properties)
15234 ;; We need a special property. Use `org-entry-properties' to
15235 ;; retrieve it, but specify the wanted property
15236 (cdr (assoc property (org-entry-properties nil 'special property)))
15237 (let ((range (org-get-property-block)))
15238 (when (and range (not (eq (car range) (cdr range))))
15239 (let* ((props (list (or (assoc property org-file-properties)
15240 (assoc property org-global-properties)
15241 (assoc property org-global-properties-fixed))))
15242 (ap (lambda (key)
15243 (when (re-search-forward
15244 (org-re-property key) (cdr range) t)
15245 (setq props
15246 (org-update-property-plist
15248 (if (match-end 1)
15249 (org-match-string-no-properties 1) "")
15250 props)))))
15251 val)
15252 (goto-char (car range))
15253 (funcall ap property)
15254 (goto-char (car range))
15255 (while (funcall ap (concat property "+")))
15256 (setq val (cdr (assoc property props)))
15257 (when val (if literal-nil val (org-not-nil val))))))))))
15259 (defun org-property-or-variable-value (var &optional inherit)
15260 "Check if there is a property fixing the value of VAR.
15261 If yes, return this value. If not, return the current value of the variable."
15262 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15263 (if (and prop (stringp prop) (string-match "\\S-" prop))
15264 (read prop)
15265 (symbol-value var))))
15267 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15268 "Delete the property PROPERTY from entry at point-or-marker POM.
15269 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15270 an empty drawer to delete."
15271 (org-with-point-at pom
15272 (if (member property org-special-properties)
15273 nil ; cannot delete these properties.
15274 (let ((range (org-get-property-block)))
15275 (if (and range
15276 (goto-char (car range))
15277 (re-search-forward
15278 (org-re-property property)
15279 (cdr range) t))
15280 (progn
15281 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15282 (and delete-empty-drawer
15283 (org-remove-empty-drawer-at
15284 delete-empty-drawer (car range)))
15286 nil)))))
15288 ;; Multi-values properties are properties that contain multiple values
15289 ;; These values are assumed to be single words, separated by whitespace.
15290 (defun org-entry-add-to-multivalued-property (pom property value)
15291 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15292 (let* ((old (org-entry-get pom property))
15293 (values (and old (org-split-string old "[ \t]"))))
15294 (setq value (org-entry-protect-space value))
15295 (unless (member value values)
15296 (setq values (append values (list value)))
15297 (org-entry-put pom property
15298 (mapconcat 'identity values " ")))))
15300 (defun org-entry-remove-from-multivalued-property (pom property value)
15301 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15302 (let* ((old (org-entry-get pom property))
15303 (values (and old (org-split-string old "[ \t]"))))
15304 (setq value (org-entry-protect-space value))
15305 (when (member value values)
15306 (setq values (delete value values))
15307 (org-entry-put pom property
15308 (mapconcat 'identity values " ")))))
15310 (defun org-entry-member-in-multivalued-property (pom property value)
15311 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15312 (let* ((old (org-entry-get pom property))
15313 (values (and old (org-split-string old "[ \t]"))))
15314 (setq value (org-entry-protect-space value))
15315 (member value values)))
15317 (defun org-entry-get-multivalued-property (pom property)
15318 "Return a list of values in a multivalued property."
15319 (let* ((value (org-entry-get pom property))
15320 (values (and value (org-split-string value "[ \t]"))))
15321 (mapcar 'org-entry-restore-space values)))
15323 (defun org-entry-put-multivalued-property (pom property &rest values)
15324 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15325 VALUES should be a list of strings. Spaces will be protected."
15326 (org-entry-put pom property
15327 (mapconcat 'org-entry-protect-space values " "))
15328 (let* ((value (org-entry-get pom property))
15329 (values (and value (org-split-string value "[ \t]"))))
15330 (mapcar 'org-entry-restore-space values)))
15332 (defun org-entry-protect-space (s)
15333 "Protect spaces and newline in string S."
15334 (while (string-match " " s)
15335 (setq s (replace-match "%20" t t s)))
15336 (while (string-match "\n" s)
15337 (setq s (replace-match "%0A" t t s)))
15340 (defun org-entry-restore-space (s)
15341 "Restore spaces and newline in string S."
15342 (while (string-match "%20" s)
15343 (setq s (replace-match " " t t s)))
15344 (while (string-match "%0A" s)
15345 (setq s (replace-match "\n" t t s)))
15348 (defvar org-entry-property-inherited-from (make-marker)
15349 "Marker pointing to the entry from where a property was inherited.
15350 Each call to `org-entry-get-with-inheritance' will set this marker to the
15351 location of the entry where the inheritance search matched. If there was
15352 no match, the marker will point nowhere.
15353 Note that also `org-entry-get' calls this function, if the INHERIT flag
15354 is set.")
15356 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15357 "Get PROPERTY of entry or content at point, search higher levels if needed.
15358 The search will stop at the first ancestor which has the property defined.
15359 If the value found is \"nil\", return nil to show that the property
15360 should be considered as undefined (this is the meaning of nil here).
15361 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15362 (move-marker org-entry-property-inherited-from nil)
15363 (let (tmp)
15364 (save-excursion
15365 (save-restriction
15366 (widen)
15367 (catch 'ex
15368 (while t
15369 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15370 (or (ignore-errors (org-back-to-heading t))
15371 (goto-char (point-min)))
15372 (move-marker org-entry-property-inherited-from (point))
15373 (throw 'ex tmp))
15374 (or (ignore-errors (org-up-heading-safe))
15375 (throw 'ex nil))))))
15376 (setq tmp (or tmp
15377 (cdr (assoc property org-file-properties))
15378 (cdr (assoc property org-global-properties))
15379 (cdr (assoc property org-global-properties-fixed))))
15380 (if literal-nil tmp (org-not-nil tmp))))
15382 (defvar org-property-changed-functions nil
15383 "Hook called when the value of a property has changed.
15384 Each hook function should accept two arguments, the name of the property
15385 and the new value.")
15387 (defun org-entry-put (pom property value)
15388 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15389 (org-with-point-at pom
15390 (org-back-to-heading t)
15391 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15392 range)
15393 (cond
15394 ((equal property "TODO")
15395 (when (and (stringp value) (string-match "\\S-" value)
15396 (not (member value org-todo-keywords-1)))
15397 (error "\"%s\" is not a valid TODO state" value))
15398 (if (or (not value)
15399 (not (string-match "\\S-" value)))
15400 (setq value 'none))
15401 (org-todo value)
15402 (org-set-tags nil 'align))
15403 ((equal property "PRIORITY")
15404 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15405 (string-to-char value) ?\ ))
15406 (org-set-tags nil 'align))
15407 ((equal property "CLOCKSUM")
15408 (if (not (re-search-forward
15409 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15410 (error "Cannot find a clock log")
15411 (goto-char (- (match-end 1) 2))
15412 (cond
15413 ((eq value 'earlier) (org-timestamp-down))
15414 ((eq value 'later) (org-timestamp-up)))
15415 (org-clock-sum-current-item)))
15416 ((equal property "SCHEDULED")
15417 (if (re-search-forward org-scheduled-time-regexp end t)
15418 (cond
15419 ((eq value 'earlier) (org-timestamp-change -1 'day))
15420 ((eq value 'later) (org-timestamp-change 1 'day))
15421 (t (call-interactively 'org-schedule)))
15422 (call-interactively 'org-schedule)))
15423 ((equal property "DEADLINE")
15424 (if (re-search-forward org-deadline-time-regexp end t)
15425 (cond
15426 ((eq value 'earlier) (org-timestamp-change -1 'day))
15427 ((eq value 'later) (org-timestamp-change 1 'day))
15428 (t (call-interactively 'org-deadline)))
15429 (call-interactively 'org-deadline)))
15430 ((member property org-special-properties)
15431 (error "The %s property can not yet be set with `org-entry-put'"
15432 property))
15433 (t ; a non-special property
15434 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15435 (setq range (org-get-property-block beg end 'force))
15436 (goto-char (car range))
15437 (if (re-search-forward
15438 (org-re-property-keyword property) (cdr range) t)
15439 (progn
15440 (delete-region (match-beginning 0) (match-end 0))
15441 (goto-char (match-beginning 0)))
15442 (goto-char (cdr range))
15443 (insert "\n")
15444 (backward-char 1)
15445 (org-indent-line))
15446 (insert ":" property ":")
15447 (and value (insert " " value))
15448 (org-indent-line)))))
15449 (run-hook-with-args 'org-property-changed-functions property value)))
15451 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15452 "Get all property keys in the current buffer.
15453 With INCLUDE-SPECIALS, also list the special properties that reflect things
15454 like tags and TODO state.
15455 With INCLUDE-DEFAULTS, also include properties that has special meaning
15456 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15457 and others.
15458 With INCLUDE-COLUMNS, also include property names given in COLUMN
15459 formats in the current buffer."
15460 (let (rtn range cfmt s p)
15461 (save-excursion
15462 (save-restriction
15463 (widen)
15464 (goto-char (point-min))
15465 (while (re-search-forward org-property-start-re nil t)
15466 (setq range (org-get-property-block))
15467 (goto-char (car range))
15468 (while (re-search-forward
15469 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15470 (cdr range) t)
15471 (add-to-list 'rtn (org-match-string-no-properties 1)))
15472 (outline-next-heading))))
15474 (when include-specials
15475 (setq rtn (append org-special-properties rtn)))
15477 (when include-defaults
15478 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15479 (add-to-list 'rtn org-effort-property))
15481 (when include-columns
15482 (save-excursion
15483 (save-restriction
15484 (widen)
15485 (goto-char (point-min))
15486 (while (re-search-forward
15487 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15488 nil t)
15489 (setq cfmt (match-string 2) s 0)
15490 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15491 cfmt s)
15492 (setq s (match-end 0)
15493 p (match-string 1 cfmt))
15494 (unless (or (equal p "ITEM")
15495 (member p org-special-properties))
15496 (add-to-list 'rtn (match-string 1 cfmt))))))))
15498 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15500 (defun org-property-values (key)
15501 "Return a list of all values of property KEY in the current buffer."
15502 (save-excursion
15503 (save-restriction
15504 (widen)
15505 (goto-char (point-min))
15506 (let ((re (org-re-property key))
15507 values)
15508 (while (re-search-forward re nil t)
15509 (add-to-list 'values (org-trim (match-string 1))))
15510 (delete "" values)))))
15512 (defun org-insert-property-drawer ()
15513 "Insert a property drawer into the current entry."
15514 (org-back-to-heading t)
15515 (looking-at org-outline-regexp)
15516 (let ((indent (if org-adapt-indentation
15517 (- (match-end 0) (match-beginning 0))
15519 (beg (point))
15520 (re (concat "^[ \t]*" org-keyword-time-regexp))
15521 end hiddenp)
15522 (outline-next-heading)
15523 (setq end (point))
15524 (goto-char beg)
15525 (while (re-search-forward re end t))
15526 (setq hiddenp (outline-invisible-p))
15527 (end-of-line 1)
15528 (and (equal (char-after) ?\n) (forward-char 1))
15529 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15530 (if (member (match-string 1) '("CLOCK:" ":END:"))
15531 ;; just skip this line
15532 (beginning-of-line 2)
15533 ;; Drawer start, find the end
15534 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15535 (beginning-of-line 1)))
15536 (org-skip-over-state-notes)
15537 (skip-chars-backward " \t\n\r")
15538 (if (eq (char-before) ?*) (forward-char 1))
15539 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15540 (beginning-of-line 0)
15541 (org-indent-to-column indent)
15542 (beginning-of-line 2)
15543 (org-indent-to-column indent)
15544 (beginning-of-line 0)
15545 (if hiddenp
15546 (save-excursion
15547 (org-back-to-heading t)
15548 (hide-entry))
15549 (org-flag-drawer t))))
15551 (defun org-insert-drawer (&optional arg drawer)
15552 "Insert a drawer at point.
15554 Optional argument DRAWER, when non-nil, is a string representing
15555 drawer's name. Otherwise, the user is prompted for a name.
15557 If a region is active, insert the drawer around that region
15558 instead.
15560 Point is left between drawer's boundaries."
15561 (interactive "P")
15562 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15563 "LOGBOOK"))
15564 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15565 ;; internally by Org. They are meant to be inserted
15566 ;; automatically.
15567 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15568 ;; Remove system drawers from list. Note: For some reason,
15569 ;; `org-completing-read' ignores the predicate while
15570 ;; `completing-read' handles it fine.
15571 (drawer (if arg "PROPERTIES"
15572 (or drawer
15573 (completing-read
15574 "Drawer: " org-drawers
15575 (lambda (d) (not (member d system-drawers))))))))
15576 (cond
15577 ;; With C-u, fall back on `org-insert-property-drawer'
15578 (arg (org-insert-property-drawer))
15579 ;; With an active region, insert a drawer at point.
15580 ((not (org-region-active-p))
15581 (progn
15582 (unless (bolp) (insert "\n"))
15583 (insert (format ":%s:\n\n:END:\n" drawer))
15584 (forward-line -2)))
15585 ;; Otherwise, insert the drawer at point
15587 (let ((rbeg (region-beginning))
15588 (rend (copy-marker (region-end))))
15589 (unwind-protect
15590 (progn
15591 (goto-char rbeg)
15592 (beginning-of-line)
15593 (when (save-excursion
15594 (re-search-forward org-outline-regexp-bol rend t))
15595 (error "Drawers cannot contain headlines"))
15596 ;; Position point at the beginning of the first
15597 ;; non-blank line in region. Insert drawer's opening
15598 ;; there, then indent it.
15599 (org-skip-whitespace)
15600 (beginning-of-line)
15601 (insert ":" drawer ":\n")
15602 (forward-line -1)
15603 (indent-for-tab-command)
15604 ;; Move point to the beginning of the first blank line
15605 ;; after the last non-blank line in region. Insert
15606 ;; drawer's closing, then indent it.
15607 (goto-char rend)
15608 (skip-chars-backward " \r\t\n")
15609 (insert "\n:END:")
15610 (deactivate-mark t)
15611 (indent-for-tab-command)
15612 (unless (eolp) (insert "\n")))
15613 ;; Clear marker, whatever the outcome of insertion is.
15614 (set-marker rend nil)))))))
15616 (defvar org-property-set-functions-alist nil
15617 "Property set function alist.
15618 Each entry should have the following format:
15620 (PROPERTY . READ-FUNCTION)
15622 The read function will be called with the same argument as
15623 `org-completing-read'.")
15625 (defun org-set-property-function (property)
15626 "Get the function that should be used to set PROPERTY.
15627 This is computed according to `org-property-set-functions-alist'."
15628 (or (cdr (assoc property org-property-set-functions-alist))
15629 'org-completing-read))
15631 (defun org-read-property-value (property)
15632 "Read PROPERTY value from user."
15633 (let* ((completion-ignore-case t)
15634 (allowed (org-property-get-allowed-values nil property 'table))
15635 (cur (org-entry-get nil property))
15636 (prompt (concat property " value"
15637 (if (and cur (string-match "\\S-" cur))
15638 (concat " [" cur "]") "") ": "))
15639 (set-function (org-set-property-function property))
15640 (val (if allowed
15641 (funcall set-function prompt allowed nil
15642 (not (get-text-property 0 'org-unrestricted
15643 (caar allowed))))
15644 (let (org-completion-use-ido org-completion-use-iswitchb)
15645 (funcall set-function prompt
15646 (mapcar 'list (org-property-values property))
15647 nil nil "" nil cur)))))
15648 (if (equal val "")
15650 val)))
15652 (defvar org-last-set-property nil)
15653 (defvar org-last-set-property-value nil)
15654 (defun org-read-property-name ()
15655 "Read a property name."
15656 (let* ((completion-ignore-case t)
15657 (keys (org-buffer-property-keys nil t t))
15658 (default-prop (or (save-excursion
15659 (save-match-data
15660 (beginning-of-line)
15661 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15662 (null (string= (match-string 1) "END"))
15663 (match-string 1))))
15664 org-last-set-property))
15665 (property (org-icompleting-read
15666 (concat "Property"
15667 (if default-prop (concat " [" default-prop "]") "")
15668 ": ")
15669 (mapcar 'list keys)
15670 nil nil nil nil
15671 default-prop)))
15672 (if (member property keys)
15673 property
15674 (or (cdr (assoc (downcase property)
15675 (mapcar (lambda (x) (cons (downcase x) x))
15676 keys)))
15677 property))))
15679 (defun org-set-property-and-value (use-last)
15680 "Allow to set [PROPERTY]: [value] direction from prompt.
15681 When use-default, don't even ask, just use the last
15682 \"[PROPERTY]: [value]\" string from the history."
15683 (interactive "P")
15684 (let* ((completion-ignore-case t)
15685 (pv (or (and use-last org-last-set-property-value)
15686 (org-completing-read
15687 "Enter a \"[Property]: [value]\" pair: "
15688 nil nil nil nil nil
15689 org-last-set-property-value)))
15690 prop val)
15691 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15692 (setq prop (match-string 1 pv)
15693 val (match-string 2 pv))
15694 (org-set-property prop val))))
15696 (defun org-set-property (property value)
15697 "In the current entry, set PROPERTY to VALUE.
15698 When called interactively, this will prompt for a property name, offering
15699 completion on existing and default properties. And then it will prompt
15700 for a value, offering completion either on allowed values (via an inherited
15701 xxx_ALL property) or on existing values in other instances of this property
15702 in the current file."
15703 (interactive (list nil nil))
15704 (let* ((property (or property (org-read-property-name)))
15705 (value (or value (org-read-property-value property)))
15706 (fn (cdr (assoc property org-properties-postprocess-alist))))
15707 (setq org-last-set-property property)
15708 (setq org-last-set-property-value (concat property ": " value))
15709 ;; Possibly postprocess the inserted value:
15710 (when fn (setq value (funcall fn value)))
15711 (unless (equal (org-entry-get nil property) value)
15712 (org-entry-put nil property value))))
15714 (defun org-delete-property (property &optional delete-empty-drawer)
15715 "In the current entry, delete PROPERTY.
15716 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15717 an empty drawer to delete."
15718 (interactive
15719 (let* ((completion-ignore-case t)
15720 (prop (org-icompleting-read "Property: "
15721 (org-entry-properties nil 'standard))))
15722 (list prop)))
15723 (message "Property %s %s" property
15724 (if (org-entry-delete nil property delete-empty-drawer)
15725 "deleted"
15726 "was not present in the entry")))
15728 (defun org-delete-property-globally (property)
15729 "Remove PROPERTY globally, from all entries."
15730 (interactive
15731 (let* ((completion-ignore-case t)
15732 (prop (org-icompleting-read
15733 "Globally remove property: "
15734 (mapcar 'list (org-buffer-property-keys)))))
15735 (list prop)))
15736 (save-excursion
15737 (save-restriction
15738 (widen)
15739 (goto-char (point-min))
15740 (let ((cnt 0))
15741 (while (re-search-forward
15742 (org-re-property property)
15743 nil t)
15744 (setq cnt (1+ cnt))
15745 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15746 (message "Property \"%s\" removed from %d entries" property cnt)))))
15748 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15750 (defun org-compute-property-at-point ()
15751 "Compute the property at point.
15752 This looks for an enclosing column format, extracts the operator and
15753 then applies it to the property in the column format's scope."
15754 (interactive)
15755 (unless (org-at-property-p)
15756 (error "Not at a property"))
15757 (let ((prop (org-match-string-no-properties 2)))
15758 (org-columns-get-format-and-top-level)
15759 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15760 (error "No operator defined for property %s" prop))
15761 (org-columns-compute prop)))
15763 (defvar org-property-allowed-value-functions nil
15764 "Hook for functions supplying allowed values for a specific property.
15765 The functions must take a single argument, the name of the property, and
15766 return a flat list of allowed values. If \":ETC\" is one of
15767 the values, this means that these values are intended as defaults for
15768 completion, but that other values should be allowed too.
15769 The functions must return nil if they are not responsible for this
15770 property.")
15772 (defun org-property-get-allowed-values (pom property &optional table)
15773 "Get allowed values for the property PROPERTY.
15774 When TABLE is non-nil, return an alist that can directly be used for
15775 completion."
15776 (let (vals)
15777 (cond
15778 ((equal property "TODO")
15779 (setq vals (org-with-point-at pom
15780 (append org-todo-keywords-1 '("")))))
15781 ((equal property "PRIORITY")
15782 (let ((n org-lowest-priority))
15783 (while (>= n org-highest-priority)
15784 (push (char-to-string n) vals)
15785 (setq n (1- n)))))
15786 ((member property org-special-properties))
15787 ((setq vals (run-hook-with-args-until-success
15788 'org-property-allowed-value-functions property)))
15790 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15791 (when (and vals (string-match "\\S-" vals))
15792 (setq vals (car (read-from-string (concat "(" vals ")"))))
15793 (setq vals (mapcar (lambda (x)
15794 (cond ((stringp x) x)
15795 ((numberp x) (number-to-string x))
15796 ((symbolp x) (symbol-name x))
15797 (t "???")))
15798 vals)))))
15799 (when (member ":ETC" vals)
15800 (setq vals (remove ":ETC" vals))
15801 (org-add-props (car vals) '(org-unrestricted t)))
15802 (if table (mapcar 'list vals) vals)))
15804 (defun org-property-previous-allowed-value (&optional previous)
15805 "Switch to the next allowed value for this property."
15806 (interactive)
15807 (org-property-next-allowed-value t))
15809 (defun org-property-next-allowed-value (&optional previous)
15810 "Switch to the next allowed value for this property."
15811 (interactive)
15812 (unless (org-at-property-p)
15813 (error "Not at a property"))
15814 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15815 (key (match-string 2))
15816 (value (match-string 3))
15817 (allowed (or (org-property-get-allowed-values (point) key)
15818 (and (member value '("[ ]" "[-]" "[X]"))
15819 '("[ ]" "[X]"))))
15820 (heading (save-match-data (nth 4 (org-heading-components))))
15821 nval)
15822 (unless allowed
15823 (error "Allowed values for this property have not been defined"))
15824 (if previous (setq allowed (reverse allowed)))
15825 (if (member value allowed)
15826 (setq nval (car (cdr (member value allowed)))))
15827 (setq nval (or nval (car allowed)))
15828 (if (equal nval value)
15829 (error "Only one allowed value for this property"))
15830 (org-at-property-p)
15831 (replace-match (concat " :" key ": " nval) t t)
15832 (org-indent-line)
15833 (beginning-of-line 1)
15834 (skip-chars-forward " \t")
15835 (when (equal prop org-effort-property)
15836 (save-excursion
15837 (org-back-to-heading t)
15838 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15839 (when (string= org-clock-current-task heading)
15840 (setq org-clock-effort nval)
15841 (org-clock-update-mode-line)))
15842 (run-hook-with-args 'org-property-changed-functions key nval)))
15844 (defun org-find-olp (path &optional this-buffer)
15845 "Return a marker pointing to the entry at outline path OLP.
15846 If anything goes wrong, throw an error.
15847 You can wrap this call to catch the error like this:
15849 (condition-case msg
15850 (org-mobile-locate-entry (match-string 4))
15851 (error (nth 1 msg)))
15853 The return value will then be either a string with the error message,
15854 or a marker if everything is OK.
15856 If THIS-BUFFER is set, the outline path does not contain a file,
15857 only headings."
15858 (let* ((file (if this-buffer buffer-file-name (pop path)))
15859 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15860 (level 1)
15861 (lmin 1)
15862 (lmax 1)
15863 limit re end found pos heading cnt flevel)
15864 (unless buffer (error "File not found :%s" file))
15865 (with-current-buffer buffer
15866 (save-excursion
15867 (save-restriction
15868 (widen)
15869 (setq limit (point-max))
15870 (goto-char (point-min))
15871 (while (setq heading (pop path))
15872 (setq re (format org-complex-heading-regexp-format
15873 (regexp-quote heading)))
15874 (setq cnt 0 pos (point))
15875 (while (re-search-forward re end t)
15876 (setq level (- (match-end 1) (match-beginning 1)))
15877 (if (and (>= level lmin) (<= level lmax))
15878 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15879 (when (= cnt 0) (error "Heading not found on level %d: %s"
15880 lmax heading))
15881 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15882 lmax heading))
15883 (goto-char found)
15884 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15885 (setq end (save-excursion (org-end-of-subtree t t))))
15886 (when (org-at-heading-p)
15887 (point-marker)))))))
15889 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15890 "Find node HEADING in BUFFER.
15891 Return a marker to the heading if it was found, or nil if not.
15892 If POS-ONLY is set, return just the position instead of a marker.
15894 The heading text must match exact, but it may have a TODO keyword,
15895 a priority cookie and tags in the standard locations."
15896 (with-current-buffer (or buffer (current-buffer))
15897 (save-excursion
15898 (save-restriction
15899 (widen)
15900 (goto-char (point-min))
15901 (let (case-fold-search)
15902 (if (re-search-forward
15903 (format org-complex-heading-regexp-format
15904 (regexp-quote heading)) nil t)
15905 (if pos-only
15906 (match-beginning 0)
15907 (move-marker (make-marker) (match-beginning 0)))))))))
15909 (defun org-find-exact-heading-in-directory (heading &optional dir)
15910 "Find Org node headline HEADING in all .org files in directory DIR.
15911 When the target headline is found, return a marker to this location."
15912 (let ((files (directory-files (or dir default-directory)
15913 nil "\\`[^.#].*\\.org\\'"))
15914 file visiting m buffer)
15915 (catch 'found
15916 (while (setq file (pop files))
15917 (message "trying %s" file)
15918 (setq visiting (org-find-base-buffer-visiting file))
15919 (setq buffer (or visiting (find-file-noselect file)))
15920 (setq m (org-find-exact-headline-in-buffer
15921 heading buffer))
15922 (when (and (not m) (not visiting)) (kill-buffer buffer))
15923 (and m (throw 'found m))))))
15925 (defun org-find-entry-with-id (ident)
15926 "Locate the entry that contains the ID property with exact value IDENT.
15927 IDENT can be a string, a symbol or a number, this function will search for
15928 the string representation of it.
15929 Return the position where this entry starts, or nil if there is no such entry."
15930 (interactive "sID: ")
15931 (let ((id (cond
15932 ((stringp ident) ident)
15933 ((symbol-name ident) (symbol-name ident))
15934 ((numberp ident) (number-to-string ident))
15935 (t (error "IDENT %s must be a string, symbol or number" ident))))
15936 (case-fold-search nil))
15937 (save-excursion
15938 (save-restriction
15939 (widen)
15940 (goto-char (point-min))
15941 (when (re-search-forward
15942 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15943 nil t)
15944 (org-back-to-heading t)
15945 (point))))))
15947 ;;;; Timestamps
15949 (defvar org-last-changed-timestamp nil)
15950 (defvar org-last-inserted-timestamp nil
15951 "The last time stamp inserted with `org-insert-time-stamp'.")
15952 (defvar org-time-was-given) ; dynamically scoped parameter
15953 (defvar org-end-time-was-given) ; dynamically scoped parameter
15954 (defvar org-ts-what) ; dynamically scoped parameter
15956 (defun org-time-stamp (arg &optional inactive)
15957 "Prompt for a date/time and insert a time stamp.
15958 If the user specifies a time like HH:MM or if this command is
15959 called with at least one prefix argument, the time stamp contains
15960 the date and the time. Otherwise, only the date is be included.
15962 All parts of a date not specified by the user is filled in from
15963 the current date/time. So if you just press return without
15964 typing anything, the time stamp will represent the current
15965 date/time.
15967 If there is already a timestamp at the cursor, it will be
15968 modified.
15970 With two universal prefix arguments, insert an active timestamp
15971 with the current time without prompting the user."
15972 (interactive "P")
15973 (let* ((ts nil)
15974 (default-time
15975 ;; Default time is either today, or, when entering a range,
15976 ;; the range start.
15977 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15978 (save-excursion
15979 (re-search-backward
15980 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15981 (- (point) 20) t)))
15982 (apply 'encode-time (org-parse-time-string (match-string 1)))
15983 (current-time)))
15984 (default-input (and ts (org-get-compact-tod ts)))
15985 (repeater (save-excursion
15986 (save-match-data
15987 (beginning-of-line)
15988 (when (re-search-forward
15989 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15990 (save-excursion (progn (end-of-line) (point))) t)
15991 (match-string 0)))))
15992 org-time-was-given org-end-time-was-given time)
15993 (cond
15994 ((and (org-at-timestamp-p t)
15995 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15996 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15997 (insert "--")
15998 (setq time (let ((this-command this-command))
15999 (org-read-date arg 'totime nil nil
16000 default-time default-input inactive)))
16001 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16002 ((org-at-timestamp-p t)
16003 (setq time (let ((this-command this-command))
16004 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16005 (when (org-at-timestamp-p t) ; just to get the match data
16006 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16007 (replace-match "")
16008 (setq org-last-changed-timestamp
16009 (org-insert-time-stamp
16010 time (or org-time-was-given arg)
16011 inactive nil nil (list org-end-time-was-given)))
16012 (when repeater (goto-char (1- (point))) (insert " " repeater)
16013 (setq org-last-changed-timestamp
16014 (concat (substring org-last-inserted-timestamp 0 -1)
16015 " " repeater ">"))))
16016 (message "Timestamp updated"))
16017 ((equal arg '(16))
16018 (org-insert-time-stamp (current-time) t))
16020 (setq time (let ((this-command this-command))
16021 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16022 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16023 nil nil (list org-end-time-was-given))))))
16025 ;; FIXME: can we use this for something else, like computing time differences?
16026 (defun org-get-compact-tod (s)
16027 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16028 (let* ((t1 (match-string 1 s))
16029 (h1 (string-to-number (match-string 2 s)))
16030 (m1 (string-to-number (match-string 3 s)))
16031 (t2 (and (match-end 4) (match-string 5 s)))
16032 (h2 (and t2 (string-to-number (match-string 6 s))))
16033 (m2 (and t2 (string-to-number (match-string 7 s))))
16034 dh dm)
16035 (if (not t2)
16037 (setq dh (- h2 h1) dm (- m2 m1))
16038 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16039 (concat t1 "+" (number-to-string dh)
16040 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
16042 (defun org-time-stamp-inactive (&optional arg)
16043 "Insert an inactive time stamp.
16044 An inactive time stamp is enclosed in square brackets instead of angle
16045 brackets. It is inactive in the sense that it does not trigger agenda entries,
16046 does not link to the calendar and cannot be changed with the S-cursor keys.
16047 So these are more for recording a certain time/date."
16048 (interactive "P")
16049 (org-time-stamp arg 'inactive))
16051 (defvar org-date-ovl (make-overlay 1 1))
16052 (overlay-put org-date-ovl 'face 'org-date-selected)
16053 (org-detach-overlay org-date-ovl)
16055 (defvar org-ans1) ; dynamically scoped parameter
16056 (defvar org-ans2) ; dynamically scoped parameter
16058 (defvar org-plain-time-of-day-regexp) ; defined below
16060 (defvar org-overriding-default-time nil) ; dynamically scoped
16061 (defvar org-read-date-overlay nil)
16062 (defvar org-dcst nil) ; dynamically scoped
16063 (defvar org-read-date-history nil)
16064 (defvar org-read-date-final-answer nil)
16065 (defvar org-read-date-analyze-futurep nil)
16066 (defvar org-read-date-analyze-forced-year nil)
16067 (defvar org-read-date-inactive)
16069 (defvar org-read-date-minibuffer-local-map
16070 (let ((map (make-sparse-keymap)))
16071 (set-keymap-parent map minibuffer-local-map)
16072 (org-defkey map (kbd ".")
16073 (lambda () (interactive)
16074 (org-eval-in-calendar '(calendar-goto-today))))
16075 (org-defkey map [(meta shift left)]
16076 (lambda () (interactive)
16077 (org-eval-in-calendar '(calendar-backward-month 1))))
16078 (org-defkey map [(meta shift right)]
16079 (lambda () (interactive)
16080 (org-eval-in-calendar '(calendar-forward-month 1))))
16081 (org-defkey map [(meta shift up)]
16082 (lambda () (interactive)
16083 (org-eval-in-calendar '(calendar-backward-year 1))))
16084 (org-defkey map [(meta shift down)]
16085 (lambda () (interactive)
16086 (org-eval-in-calendar '(calendar-forward-year 1))))
16087 (org-defkey map [?\e (shift left)]
16088 (lambda () (interactive)
16089 (org-eval-in-calendar '(calendar-backward-month 1))))
16090 (org-defkey map [?\e (shift right)]
16091 (lambda () (interactive)
16092 (org-eval-in-calendar '(calendar-forward-month 1))))
16093 (org-defkey map [?\e (shift up)]
16094 (lambda () (interactive)
16095 (org-eval-in-calendar '(calendar-backward-year 1))))
16096 (org-defkey map [?\e (shift down)]
16097 (lambda () (interactive)
16098 (org-eval-in-calendar '(calendar-forward-year 1))))
16099 (org-defkey map [(shift up)]
16100 (lambda () (interactive)
16101 (org-eval-in-calendar '(calendar-backward-week 1))))
16102 (org-defkey map [(shift down)]
16103 (lambda () (interactive)
16104 (org-eval-in-calendar '(calendar-forward-week 1))))
16105 (org-defkey map [(shift left)]
16106 (lambda () (interactive)
16107 (org-eval-in-calendar '(calendar-backward-day 1))))
16108 (org-defkey map [(shift right)]
16109 (lambda () (interactive)
16110 (org-eval-in-calendar '(calendar-forward-day 1))))
16111 (org-defkey map "!"
16112 (lambda () (interactive)
16113 (org-eval-in-calendar '(diary-view-entries))
16114 (message "")))
16115 (org-defkey map ">"
16116 (lambda () (interactive)
16117 (org-eval-in-calendar '(scroll-calendar-left 1))))
16118 (org-defkey map "<"
16119 (lambda () (interactive)
16120 (org-eval-in-calendar '(scroll-calendar-right 1))))
16121 (org-defkey map "\C-v"
16122 (lambda () (interactive)
16123 (org-eval-in-calendar
16124 '(calendar-scroll-left-three-months 1))))
16125 (org-defkey map "\M-v"
16126 (lambda () (interactive)
16127 (org-eval-in-calendar
16128 '(calendar-scroll-right-three-months 1))))
16129 map)
16130 "Keymap for minibuffer commands when using `org-read-date'.")
16132 (defun org-read-date (&optional org-with-time to-time from-string prompt
16133 default-time default-input inactive)
16134 "Read a date, possibly a time, and make things smooth for the user.
16135 The prompt will suggest to enter an ISO date, but you can also enter anything
16136 which will at least partially be understood by `parse-time-string'.
16137 Unrecognized parts of the date will default to the current day, month, year,
16138 hour and minute. If this command is called to replace a timestamp at point,
16139 or to enter the second timestamp of a range, the default time is taken
16140 from the existing stamp. Furthermore, the command prefers the future,
16141 so if you are giving a date where the year is not given, and the day-month
16142 combination is already past in the current year, it will assume you
16143 mean next year. For details, see the manual. A few examples:
16145 3-2-5 --> 2003-02-05
16146 feb 15 --> currentyear-02-15
16147 2/15 --> currentyear-02-15
16148 sep 12 9 --> 2009-09-12
16149 12:45 --> today 12:45
16150 22 sept 0:34 --> currentyear-09-22 0:34
16151 12 --> currentyear-currentmonth-12
16152 Fri --> nearest Friday (today or later)
16153 etc.
16155 Furthermore you can specify a relative date by giving, as the *first* thing
16156 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16157 change in days weeks, months, years.
16158 With a single plus or minus, the date is relative to today. With a double
16159 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16160 +4d --> four days from today
16161 +4 --> same as above
16162 +2w --> two weeks from today
16163 ++5 --> five days from default date
16165 The function understands only English month and weekday abbreviations.
16167 While prompting, a calendar is popped up - you can also select the
16168 date with the mouse (button 1). The calendar shows a period of three
16169 months. To scroll it to other months, use the keys `>' and `<'.
16170 If you don't like the calendar, turn it off with
16171 \(setq org-read-date-popup-calendar nil)
16173 With optional argument TO-TIME, the date will immediately be converted
16174 to an internal time.
16175 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16176 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16177 still enter a time, and this function will inform the calling routine
16178 about this change. The calling routine may then choose to change the
16179 format used to insert the time stamp into the buffer to include the time.
16180 With optional argument FROM-STRING, read from this string instead from
16181 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16182 the time/date that is used for everything that is not specified by the
16183 user."
16184 (require 'parse-time)
16185 (let* ((org-time-stamp-rounding-minutes
16186 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16187 (org-dcst org-display-custom-times)
16188 (ct (org-current-time))
16189 (org-def (or org-overriding-default-time default-time ct))
16190 (org-defdecode (decode-time org-def))
16191 (dummy (progn
16192 (when (< (nth 2 org-defdecode) org-extend-today-until)
16193 (setcar (nthcdr 2 org-defdecode) -1)
16194 (setcar (nthcdr 1 org-defdecode) 59)
16195 (setq org-def (apply 'encode-time org-defdecode)
16196 org-defdecode (decode-time org-def)))))
16197 (mouse-autoselect-window nil) ; Don't let the mouse jump
16198 (calendar-frame-setup nil)
16199 (calendar-setup nil)
16200 (calendar-move-hook nil)
16201 (calendar-view-diary-initially-flag nil)
16202 (calendar-view-holidays-initially-flag nil)
16203 (timestr (format-time-string
16204 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16205 (prompt (concat (if prompt (concat prompt " ") "")
16206 (format "Date+time [%s]: " timestr)))
16207 ans (org-ans0 "") org-ans1 org-ans2 final)
16209 (cond
16210 (from-string (setq ans from-string))
16211 (org-read-date-popup-calendar
16212 (save-excursion
16213 (save-window-excursion
16214 (calendar)
16215 (org-eval-in-calendar '(setq cursor-type nil) t)
16216 (unwind-protect
16217 (progn
16218 (calendar-forward-day (- (time-to-days org-def)
16219 (calendar-absolute-from-gregorian
16220 (calendar-current-date))))
16221 (org-eval-in-calendar nil t)
16222 (let* ((old-map (current-local-map))
16223 (map (copy-keymap calendar-mode-map))
16224 (minibuffer-local-map
16225 (copy-keymap org-read-date-minibuffer-local-map)))
16226 (org-defkey map (kbd "RET") 'org-calendar-select)
16227 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16228 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16229 (unwind-protect
16230 (progn
16231 (use-local-map map)
16232 (setq org-read-date-inactive inactive)
16233 (add-hook 'post-command-hook 'org-read-date-display)
16234 (setq org-ans0 (read-string prompt default-input
16235 'org-read-date-history nil))
16236 ;; org-ans0: from prompt
16237 ;; org-ans1: from mouse click
16238 ;; org-ans2: from calendar motion
16239 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16240 (remove-hook 'post-command-hook 'org-read-date-display)
16241 (use-local-map old-map)
16242 (when org-read-date-overlay
16243 (delete-overlay org-read-date-overlay)
16244 (setq org-read-date-overlay nil)))))
16245 (bury-buffer "*Calendar*")))))
16247 (t ; Naked prompt only
16248 (unwind-protect
16249 (setq ans (read-string prompt default-input
16250 'org-read-date-history timestr))
16251 (when org-read-date-overlay
16252 (delete-overlay org-read-date-overlay)
16253 (setq org-read-date-overlay nil)))))
16255 (setq final (org-read-date-analyze ans org-def org-defdecode))
16257 (when org-read-date-analyze-forced-year
16258 (message "Year was forced into %s"
16259 (if org-read-date-force-compatible-dates
16260 "compatible range (1970-2037)"
16261 "range representable on this machine"))
16262 (ding))
16264 ;; One round trip to get rid of 34th of August and stuff like that....
16265 (setq final (decode-time (apply 'encode-time final)))
16267 (setq org-read-date-final-answer ans)
16269 (if to-time
16270 (apply 'encode-time final)
16271 (if (and (boundp 'org-time-was-given) org-time-was-given)
16272 (format "%04d-%02d-%02d %02d:%02d"
16273 (nth 5 final) (nth 4 final) (nth 3 final)
16274 (nth 2 final) (nth 1 final))
16275 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16277 (defvar org-def)
16278 (defvar org-defdecode)
16279 (defvar org-with-time)
16280 (defun org-read-date-display ()
16281 "Display the current date prompt interpretation in the minibuffer."
16282 (when org-read-date-display-live
16283 (when org-read-date-overlay
16284 (delete-overlay org-read-date-overlay))
16285 (when (minibufferp (current-buffer))
16286 (save-excursion
16287 (end-of-line 1)
16288 (while (not (equal (buffer-substring
16289 (max (point-min) (- (point) 4)) (point))
16290 " "))
16291 (insert " ")))
16292 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16293 " " (or org-ans1 org-ans2)))
16294 (org-end-time-was-given nil)
16295 (f (org-read-date-analyze ans org-def org-defdecode))
16296 (fmts (if org-dcst
16297 org-time-stamp-custom-formats
16298 org-time-stamp-formats))
16299 (fmt (if (or org-with-time
16300 (and (boundp 'org-time-was-given) org-time-was-given))
16301 (cdr fmts)
16302 (car fmts)))
16303 (txt (format-time-string fmt (apply 'encode-time f)))
16304 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16305 (txt (concat "=> " txt)))
16306 (when (and org-end-time-was-given
16307 (string-match org-plain-time-of-day-regexp txt))
16308 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16309 org-end-time-was-given
16310 (substring txt (match-end 0)))))
16311 (when org-read-date-analyze-futurep
16312 (setq txt (concat txt " (=>F)")))
16313 (setq org-read-date-overlay
16314 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16315 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16317 (defun org-read-date-analyze (ans org-def org-defdecode)
16318 "Analyze the combined answer of the date prompt."
16319 ;; FIXME: cleanup and comment
16320 (let ((nowdecode (decode-time (current-time)))
16321 delta deltan deltaw deltadef year month day
16322 hour minute second wday pm h2 m2 tl wday1
16323 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16324 (setq org-read-date-analyze-futurep nil
16325 org-read-date-analyze-forced-year nil)
16326 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16327 (setq ans "+0"))
16329 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16330 (setq ans (replace-match "" t t ans)
16331 deltan (car delta)
16332 deltaw (nth 1 delta)
16333 deltadef (nth 2 delta)))
16335 ;; Check if there is an iso week date in there. If yes, store the
16336 ;; info and postpone interpreting it until the rest of the parsing
16337 ;; is done.
16338 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16339 (setq iso-year (if (match-end 1)
16340 (org-small-year-to-year
16341 (string-to-number (match-string 1 ans))))
16342 iso-weekday (if (match-end 3)
16343 (string-to-number (match-string 3 ans)))
16344 iso-week (string-to-number (match-string 2 ans)))
16345 (setq ans (replace-match "" t t ans)))
16347 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16348 (when (string-match
16349 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16350 (setq year (if (match-end 2)
16351 (string-to-number (match-string 2 ans))
16352 (progn (setq kill-year t)
16353 (string-to-number (format-time-string "%Y"))))
16354 month (string-to-number (match-string 3 ans))
16355 day (string-to-number (match-string 4 ans)))
16356 (if (< year 100) (setq year (+ 2000 year)))
16357 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16358 t nil ans)))
16360 ;; Help matching dotted european dates
16361 (when (string-match
16362 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16363 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16364 (setq kill-year t)
16365 (string-to-number (format-time-string "%Y")))
16366 day (string-to-number (match-string 1 ans))
16367 month (string-to-number (match-string 2 ans))
16368 ans (replace-match (format "%04d-%02d-%02d" year month day)
16369 t nil ans)))
16371 ;; Help matching american dates, like 5/30 or 5/30/7
16372 (when (string-match
16373 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16374 (setq year (if (match-end 4)
16375 (string-to-number (match-string 4 ans))
16376 (progn (setq kill-year t)
16377 (string-to-number (format-time-string "%Y"))))
16378 month (string-to-number (match-string 1 ans))
16379 day (string-to-number (match-string 2 ans)))
16380 (if (< year 100) (setq year (+ 2000 year)))
16381 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16382 t nil ans)))
16383 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16384 ;; If there is a time with am/pm, and *no* time without it, we convert
16385 ;; so that matching will be successful.
16386 (loop for i from 1 to 2 do ; twice, for end time as well
16387 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16388 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16389 (setq hour (string-to-number (match-string 1 ans))
16390 minute (if (match-end 3)
16391 (string-to-number (match-string 3 ans))
16393 pm (equal ?p
16394 (string-to-char (downcase (match-string 4 ans)))))
16395 (if (and (= hour 12) (not pm))
16396 (setq hour 0)
16397 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16398 (setq ans (replace-match (format "%02d:%02d" hour minute)
16399 t t ans))))
16401 ;; Check if a time range is given as a duration
16402 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16403 (setq hour (string-to-number (match-string 1 ans))
16404 h2 (+ hour (string-to-number (match-string 3 ans)))
16405 minute (string-to-number (match-string 2 ans))
16406 m2 (+ minute (if (match-end 5) (string-to-number
16407 (match-string 5 ans))0)))
16408 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16409 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16410 t t ans)))
16412 ;; Check if there is a time range
16413 (when (boundp 'org-end-time-was-given)
16414 (setq org-time-was-given nil)
16415 (when (and (string-match org-plain-time-of-day-regexp ans)
16416 (match-end 8))
16417 (setq org-end-time-was-given (match-string 8 ans))
16418 (setq ans (concat (substring ans 0 (match-beginning 7))
16419 (substring ans (match-end 7))))))
16421 (setq tl (parse-time-string ans)
16422 day (or (nth 3 tl) (nth 3 org-defdecode))
16423 month (or (nth 4 tl)
16424 (if (and org-read-date-prefer-future
16425 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16426 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16427 (nth 4 org-defdecode)))
16428 year (or (and (not kill-year) (nth 5 tl))
16429 (if (and org-read-date-prefer-future
16430 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16431 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16432 (nth 5 org-defdecode)))
16433 hour (or (nth 2 tl) (nth 2 org-defdecode))
16434 minute (or (nth 1 tl) (nth 1 org-defdecode))
16435 second (or (nth 0 tl) 0)
16436 wday (nth 6 tl))
16438 (when (and (eq org-read-date-prefer-future 'time)
16439 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16440 (equal day (nth 3 nowdecode))
16441 (equal month (nth 4 nowdecode))
16442 (equal year (nth 5 nowdecode))
16443 (nth 2 tl)
16444 (or (< (nth 2 tl) (nth 2 nowdecode))
16445 (and (= (nth 2 tl) (nth 2 nowdecode))
16446 (nth 1 tl)
16447 (< (nth 1 tl) (nth 1 nowdecode)))))
16448 (setq day (1+ day)
16449 futurep t))
16451 ;; Special date definitions below
16452 (cond
16453 (iso-week
16454 ;; There was an iso week
16455 (require 'cal-iso)
16456 (setq futurep nil)
16457 (setq year (or iso-year year)
16458 day (or iso-weekday wday 1)
16459 wday nil ; to make sure that the trigger below does not match
16460 iso-date (calendar-gregorian-from-absolute
16461 (calendar-absolute-from-iso
16462 (list iso-week day year))))
16463 ; FIXME: Should we also push ISO weeks into the future?
16464 ; (when (and org-read-date-prefer-future
16465 ; (not iso-year)
16466 ; (< (calendar-absolute-from-gregorian iso-date)
16467 ; (time-to-days (current-time))))
16468 ; (setq year (1+ year)
16469 ; iso-date (calendar-gregorian-from-absolute
16470 ; (calendar-absolute-from-iso
16471 ; (list iso-week day year)))))
16472 (setq month (car iso-date)
16473 year (nth 2 iso-date)
16474 day (nth 1 iso-date)))
16475 (deltan
16476 (setq futurep nil)
16477 (unless deltadef
16478 (let ((now (decode-time (current-time))))
16479 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16480 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16481 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16482 ((equal deltaw "m") (setq month (+ month deltan)))
16483 ((equal deltaw "y") (setq year (+ year deltan)))))
16484 ((and wday (not (nth 3 tl)))
16485 ;; Weekday was given, but no day, so pick that day in the week
16486 ;; on or after the derived date.
16487 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16488 (unless (equal wday wday1)
16489 (setq day (+ day (% (- wday wday1 -7) 7))))))
16490 (if (and (boundp 'org-time-was-given)
16491 (nth 2 tl))
16492 (setq org-time-was-given t))
16493 (if (< year 100) (setq year (+ 2000 year)))
16494 ;; Check of the date is representable
16495 (if org-read-date-force-compatible-dates
16496 (progn
16497 (if (< year 1970)
16498 (setq year 1970 org-read-date-analyze-forced-year t))
16499 (if (> year 2037)
16500 (setq year 2037 org-read-date-analyze-forced-year t)))
16501 (condition-case nil
16502 (ignore (encode-time second minute hour day month year))
16503 (error
16504 (setq year (nth 5 org-defdecode))
16505 (setq org-read-date-analyze-forced-year t))))
16506 (setq org-read-date-analyze-futurep futurep)
16507 (list second minute hour day month year)))
16509 (defvar parse-time-weekdays)
16510 (defun org-read-date-get-relative (s today default)
16511 "Check string S for special relative date string.
16512 TODAY and DEFAULT are internal times, for today and for a default.
16513 Return shift list (N what def-flag)
16514 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16515 N is the number of WHATs to shift.
16516 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16517 the DEFAULT date rather than TODAY."
16518 (require 'parse-time)
16519 (when (and
16520 (string-match
16521 (concat
16522 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16523 "\\([0-9]+\\)?"
16524 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16525 "\\([ \t]\\|$\\)") s)
16526 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16527 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16528 (string-to-char (substring (match-string 1 s) -1))
16529 ?+))
16530 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16531 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16532 (what (if (match-end 3) (match-string 3 s) "d"))
16533 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16534 (date (if rel default today))
16535 (wday (nth 6 (decode-time date)))
16536 delta)
16537 (if wday1
16538 (progn
16539 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16540 (if (= dir ?-) (setq delta (- delta 7)))
16541 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16542 (list delta "d" rel))
16543 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16545 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16546 "Turn a user-specified date into the internal representation.
16547 The internal representation needed by the calendar is (month day year).
16548 This is a wrapper to handle the brain-dead convention in calendar that
16549 user function argument order change dependent on argument order."
16550 (if (boundp 'calendar-date-style)
16551 (cond
16552 ((eq calendar-date-style 'american)
16553 (list arg1 arg2 arg3))
16554 ((eq calendar-date-style 'european)
16555 (list arg2 arg1 arg3))
16556 ((eq calendar-date-style 'iso)
16557 (list arg2 arg3 arg1)))
16558 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16559 (if (org-bound-and-true-p european-calendar-style)
16560 (list arg2 arg1 arg3)
16561 (list arg1 arg2 arg3)))))
16563 (defun org-eval-in-calendar (form &optional keepdate)
16564 "Eval FORM in the calendar window and return to current window.
16565 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16566 otherwise stick to the current value of `org-ans2'."
16567 (let ((sf (selected-frame))
16568 (sw (selected-window)))
16569 (select-window (get-buffer-window "*Calendar*" t))
16570 (eval form)
16571 (when (and (not keepdate) (calendar-cursor-to-date))
16572 (let* ((date (calendar-cursor-to-date))
16573 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16574 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16575 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16576 (select-window sw)
16577 (org-select-frame-set-input-focus sf)))
16579 (defun org-calendar-select ()
16580 "Return to `org-read-date' with the date currently selected.
16581 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16582 (interactive)
16583 (when (calendar-cursor-to-date)
16584 (let* ((date (calendar-cursor-to-date))
16585 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16586 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16587 (if (active-minibuffer-window) (exit-minibuffer))))
16589 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16590 "Insert a date stamp for the date given by the internal TIME.
16591 WITH-HM means use the stamp format that includes the time of the day.
16592 INACTIVE means use square brackets instead of angular ones, so that the
16593 stamp will not contribute to the agenda.
16594 PRE and POST are optional strings to be inserted before and after the
16595 stamp.
16596 The command returns the inserted time stamp."
16597 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16598 stamp)
16599 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16600 (insert-before-markers (or pre ""))
16601 (when (listp extra)
16602 (setq extra (car extra))
16603 (if (and (stringp extra)
16604 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16605 (setq extra (format "-%02d:%02d"
16606 (string-to-number (match-string 1 extra))
16607 (string-to-number (match-string 2 extra))))
16608 (setq extra nil)))
16609 (when extra
16610 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16611 (insert-before-markers (setq stamp (format-time-string fmt time)))
16612 (insert-before-markers (or post ""))
16613 (setq org-last-inserted-timestamp stamp)))
16615 (defun org-toggle-time-stamp-overlays ()
16616 "Toggle the use of custom time stamp formats."
16617 (interactive)
16618 (setq org-display-custom-times (not org-display-custom-times))
16619 (unless org-display-custom-times
16620 (let ((p (point-min)) (bmp (buffer-modified-p)))
16621 (while (setq p (next-single-property-change p 'display))
16622 (if (and (get-text-property p 'display)
16623 (eq (get-text-property p 'face) 'org-date))
16624 (remove-text-properties
16625 p (setq p (next-single-property-change p 'display))
16626 '(display t))))
16627 (set-buffer-modified-p bmp)))
16628 (if (featurep 'xemacs)
16629 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16630 (org-restart-font-lock)
16631 (setq org-table-may-need-update t)
16632 (if org-display-custom-times
16633 (message "Time stamps are overlaid with custom format")
16634 (message "Time stamp overlays removed")))
16636 (defun org-display-custom-time (beg end)
16637 "Overlay modified time stamp format over timestamp between BEG and END."
16638 (let* ((ts (buffer-substring beg end))
16639 t1 w1 with-hm tf time str w2 (off 0))
16640 (save-match-data
16641 (setq t1 (org-parse-time-string ts t))
16642 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16643 (setq off (- (match-end 0) (match-beginning 0)))))
16644 (setq end (- end off))
16645 (setq w1 (- end beg)
16646 with-hm (and (nth 1 t1) (nth 2 t1))
16647 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16648 time (org-fix-decoded-time t1)
16649 str (org-add-props
16650 (format-time-string
16651 (substring tf 1 -1) (apply 'encode-time time))
16652 nil 'mouse-face 'highlight)
16653 w2 (length str))
16654 (if (not (= w2 w1))
16655 (add-text-properties (1+ beg) (+ 2 beg)
16656 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16657 (if (featurep 'xemacs)
16658 (progn
16659 (put-text-property beg end 'invisible t)
16660 (put-text-property beg end 'end-glyph (make-glyph str)))
16661 (put-text-property beg end 'display str))))
16663 (defun org-translate-time (string)
16664 "Translate all timestamps in STRING to custom format.
16665 But do this only if the variable `org-display-custom-times' is set."
16666 (when org-display-custom-times
16667 (save-match-data
16668 (let* ((start 0)
16669 (re org-ts-regexp-both)
16670 t1 with-hm inactive tf time str beg end)
16671 (while (setq start (string-match re string start))
16672 (setq beg (match-beginning 0)
16673 end (match-end 0)
16674 t1 (save-match-data
16675 (org-parse-time-string (substring string beg end) t))
16676 with-hm (and (nth 1 t1) (nth 2 t1))
16677 inactive (equal (substring string beg (1+ beg)) "[")
16678 tf (funcall (if with-hm 'cdr 'car)
16679 org-time-stamp-custom-formats)
16680 time (org-fix-decoded-time t1)
16681 str (format-time-string
16682 (concat
16683 (if inactive "[" "<") (substring tf 1 -1)
16684 (if inactive "]" ">"))
16685 (apply 'encode-time time))
16686 string (replace-match str t t string)
16687 start (+ start (length str)))))))
16688 string)
16690 (defun org-fix-decoded-time (time)
16691 "Set 0 instead of nil for the first 6 elements of time.
16692 Don't touch the rest."
16693 (let ((n 0))
16694 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16696 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16698 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16699 "Difference between TIMESTAMP-STRING and now in days.
16700 If SECONDS is non-nil, return the difference in seconds."
16701 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16702 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16703 (funcall fdiff (current-time)))))
16705 (defun org-deadline-close (timestamp-string &optional ndays)
16706 "Is the time in TIMESTAMP-STRING close to the current date?"
16707 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16708 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16709 (not (org-entry-is-done-p))))
16711 (defun org-get-wdays (ts &optional delay zero-delay)
16712 "Get the deadline lead time appropriate for timestring TS.
16713 When DELAY is non-nil, get the delay time for scheduled items
16714 instead of the deadline lead time. When ZERO-DELAY is non-nil
16715 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16716 don't try to find the delay cookie in the scheduled timestamp."
16717 (let ((tv (if delay org-scheduled-delay-days
16718 org-deadline-warning-days)))
16719 (cond
16720 ((or (and delay (< tv 0))
16721 (and delay zero-delay (<= tv 0))
16722 (and (not delay) (<= tv 0)))
16723 ;; Enforce this value no matter what
16724 (- tv))
16725 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16726 ;; lead time is specified.
16727 (floor (* (string-to-number (match-string 1 ts))
16728 (cdr (assoc (match-string 2 ts)
16729 '(("d" . 1) ("w" . 7)
16730 ("m" . 30.4) ("y" . 365.25)
16731 ("h" . 0.041667)))))))
16732 ;; go for the default.
16733 (t tv))))
16735 (defun org-calendar-select-mouse (ev)
16736 "Return to `org-read-date' with the date currently selected.
16737 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16738 (interactive "e")
16739 (mouse-set-point ev)
16740 (when (calendar-cursor-to-date)
16741 (let* ((date (calendar-cursor-to-date))
16742 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16743 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16744 (if (active-minibuffer-window) (exit-minibuffer))))
16746 (defun org-check-deadlines (ndays)
16747 "Check if there are any deadlines due or past due.
16748 A deadline is considered due if it happens within `org-deadline-warning-days'
16749 days from today's date. If the deadline appears in an entry marked DONE,
16750 it is not shown. The prefix arg NDAYS can be used to test that many
16751 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16752 (interactive "P")
16753 (let* ((org-warn-days
16754 (cond
16755 ((equal ndays '(4)) 100000)
16756 (ndays (prefix-numeric-value ndays))
16757 (t (abs org-deadline-warning-days))))
16758 (case-fold-search nil)
16759 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16760 (callback
16761 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16763 (message "%d deadlines past-due or due within %d days"
16764 (org-occur regexp nil callback)
16765 org-warn-days)))
16767 (defsubst org-re-timestamp (type)
16768 "Return a regexp for timestamp TYPE.
16769 Allowed values for TYPE are:
16771 all: all timestamps
16772 active: only active timestamps (<...>)
16773 inactive: only inactive timestamps ([...])
16774 scheduled: only scheduled timestamps
16775 deadline: only deadline timestamps
16776 closed: only closed time-stamps
16778 When TYPE is nil, fall back on returning a regexp that matches
16779 both scheduled and deadline timestamps."
16780 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16781 ((eq type 'active) org-ts-regexp)
16782 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16783 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16784 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16785 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16786 ((eq type 'scheduled-or-deadline)
16787 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16789 (defun org-check-before-date (date)
16790 "Check if there are deadlines or scheduled entries before DATE."
16791 (interactive (list (org-read-date)))
16792 (let ((case-fold-search nil)
16793 (regexp (org-re-timestamp org-ts-type))
16794 (callback
16795 (lambda () (time-less-p
16796 (org-time-string-to-time (match-string 1))
16797 (org-time-string-to-time date)))))
16798 (message "%d entries before %s"
16799 (org-occur regexp nil callback) date)))
16801 (defun org-check-after-date (date)
16802 "Check if there are deadlines or scheduled entries after DATE."
16803 (interactive (list (org-read-date)))
16804 (let ((case-fold-search nil)
16805 (regexp (org-re-timestamp org-ts-type))
16806 (callback
16807 (lambda () (not
16808 (time-less-p
16809 (org-time-string-to-time (match-string 1))
16810 (org-time-string-to-time date))))))
16811 (message "%d entries after %s"
16812 (org-occur regexp nil callback) date)))
16814 (defun org-check-dates-range (start-date end-date)
16815 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16816 (interactive (list (org-read-date nil nil nil "Range starts")
16817 (org-read-date nil nil nil "Range end")))
16818 (let ((case-fold-search nil)
16819 (regexp (org-re-timestamp org-ts-type))
16820 (callback
16821 (lambda ()
16822 (let ((match (match-string 1)))
16823 (and
16824 (not (time-less-p
16825 (org-time-string-to-time match)
16826 (org-time-string-to-time start-date)))
16827 (time-less-p
16828 (org-time-string-to-time match)
16829 (org-time-string-to-time end-date)))))))
16830 (message "%d entries between %s and %s"
16831 (org-occur regexp nil callback) start-date end-date)))
16833 (defun org-evaluate-time-range (&optional to-buffer)
16834 "Evaluate a time range by computing the difference between start and end.
16835 Normally the result is just printed in the echo area, but with prefix arg
16836 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16837 If the time range is actually in a table, the result is inserted into the
16838 next column.
16839 For time difference computation, a year is assumed to be exactly 365
16840 days in order to avoid rounding problems."
16841 (interactive "P")
16843 (org-clock-update-time-maybe)
16844 (save-excursion
16845 (unless (org-at-date-range-p t)
16846 (goto-char (point-at-bol))
16847 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16848 (if (not (org-at-date-range-p t))
16849 (error "Not at a time-stamp range, and none found in current line")))
16850 (let* ((ts1 (match-string 1))
16851 (ts2 (match-string 2))
16852 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16853 (match-end (match-end 0))
16854 (time1 (org-time-string-to-time ts1))
16855 (time2 (org-time-string-to-time ts2))
16856 (t1 (org-float-time time1))
16857 (t2 (org-float-time time2))
16858 (diff (abs (- t2 t1)))
16859 (negative (< (- t2 t1) 0))
16860 ;; (ys (floor (* 365 24 60 60)))
16861 (ds (* 24 60 60))
16862 (hs (* 60 60))
16863 (fy "%dy %dd %02d:%02d")
16864 (fy1 "%dy %dd")
16865 (fd "%dd %02d:%02d")
16866 (fd1 "%dd")
16867 (fh "%02d:%02d")
16868 y d h m align)
16869 (if havetime
16870 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16872 d (floor (/ diff ds)) diff (mod diff ds)
16873 h (floor (/ diff hs)) diff (mod diff hs)
16874 m (floor (/ diff 60)))
16875 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16877 d (floor (+ (/ diff ds) 0.5))
16878 h 0 m 0))
16879 (if (not to-buffer)
16880 (message "%s" (org-make-tdiff-string y d h m))
16881 (if (org-at-table-p)
16882 (progn
16883 (goto-char match-end)
16884 (setq align t)
16885 (and (looking-at " *|") (goto-char (match-end 0))))
16886 (goto-char match-end))
16887 (if (looking-at
16888 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16889 (replace-match ""))
16890 (if negative (insert " -"))
16891 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16892 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16893 (insert " " (format fh h m))))
16894 (if align (org-table-align))
16895 (message "Time difference inserted")))))
16897 (defun org-make-tdiff-string (y d h m)
16898 (let ((fmt "")
16899 (l nil))
16900 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16901 l (push y l)))
16902 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16903 l (push d l)))
16904 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16905 l (push h l)))
16906 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16907 l (push m l)))
16908 (apply 'format fmt (nreverse l))))
16910 (defun org-time-string-to-time (s &optional buffer pos)
16911 "Convert a timestamp string into internal time."
16912 (condition-case errdata
16913 (apply 'encode-time (org-parse-time-string s))
16914 (error (error "Bad timestamp `%s'%s\nError was: %s"
16915 s (if (not (and buffer pos))
16917 (format " at %d in buffer `%s'" pos buffer))
16918 (cdr errdata)))))
16920 (defun org-time-string-to-seconds (s)
16921 "Convert a timestamp string to a number of seconds."
16922 (org-float-time (org-time-string-to-time s)))
16924 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16925 "Convert a time stamp to an absolute day number.
16926 If there is a specifier for a cyclic time stamp, get the closest
16927 date to DAYNR.
16928 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16929 The variable `date' is bound by the calendar when this is called."
16930 (cond
16931 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16932 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16933 daynr
16934 (+ daynr 1000)))
16935 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16936 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16937 (time-to-days (current-time))) (match-string 0 s)
16938 prefer show-all))
16939 (t (time-to-days
16940 (condition-case errdata
16941 (apply 'encode-time (org-parse-time-string s))
16942 (error (error "Bad timestamp `%s'%s\nError was: %s"
16943 s (if (not (and buffer pos))
16945 (format " at %d in buffer `%s'" pos buffer))
16946 (cdr errdata))))))))
16948 (defun org-days-to-iso-week (days)
16949 "Return the iso week number."
16950 (require 'cal-iso)
16951 (car (calendar-iso-from-absolute days)))
16953 (defun org-small-year-to-year (year)
16954 "Convert 2-digit years into 4-digit years.
16955 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16956 The year 2000 cannot be abbreviated. Any year larger than 99
16957 is returned unchanged."
16958 (if (< year 38)
16959 (setq year (+ 2000 year))
16960 (if (< year 100)
16961 (setq year (+ 1900 year))))
16962 year)
16964 (defun org-time-from-absolute (d)
16965 "Return the time corresponding to date D.
16966 D may be an absolute day number, or a calendar-type list (month day year)."
16967 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16968 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16970 (defun org-calendar-holiday ()
16971 "List of holidays, for Diary display in Org-mode."
16972 (require 'holidays)
16973 (let ((hl (funcall
16974 (if (fboundp 'calendar-check-holidays)
16975 'calendar-check-holidays 'check-calendar-holidays) date)))
16976 (if hl (mapconcat 'identity hl "; "))))
16978 (defun org-diary-sexp-entry (sexp entry date)
16979 "Process a SEXP diary ENTRY for DATE."
16980 (require 'diary-lib)
16981 (let ((result (if calendar-debug-sexp
16982 (let ((stack-trace-on-error t))
16983 (eval (car (read-from-string sexp))))
16984 (condition-case nil
16985 (eval (car (read-from-string sexp)))
16986 (error
16987 (beep)
16988 (message "Bad sexp at line %d in %s: %s"
16989 (org-current-line)
16990 (buffer-file-name) sexp)
16991 (sleep-for 2))))))
16992 (cond ((stringp result) (split-string result "; "))
16993 ((and (consp result)
16994 (not (consp (cdr result)))
16995 (stringp (cdr result))) (cdr result))
16996 ((and (consp result)
16997 (stringp (car result))) result)
16998 (result entry))))
17000 (defun org-diary-to-ical-string (frombuf)
17001 "Get iCalendar entries from diary entries in buffer FROMBUF.
17002 This uses the icalendar.el library."
17003 (let* ((tmpdir (if (featurep 'xemacs)
17004 (temp-directory)
17005 temporary-file-directory))
17006 (tmpfile (make-temp-name
17007 (expand-file-name "orgics" tmpdir)))
17008 buf rtn b e)
17009 (with-current-buffer frombuf
17010 (icalendar-export-region (point-min) (point-max) tmpfile)
17011 (setq buf (find-buffer-visiting tmpfile))
17012 (set-buffer buf)
17013 (goto-char (point-min))
17014 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17015 (setq b (match-beginning 0)))
17016 (goto-char (point-max))
17017 (if (re-search-backward "^END:VEVENT" nil t)
17018 (setq e (match-end 0)))
17019 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17020 (kill-buffer buf)
17021 (delete-file tmpfile)
17022 rtn))
17024 (defun org-closest-date (start current change prefer show-all)
17025 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17026 When PREFER is `past', return a date that is either CURRENT or past.
17027 When PREFER is `future', return a date that is either CURRENT or future.
17028 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17029 ;; Make the proper lists from the dates
17030 (catch 'exit
17031 (let ((a1 '(("h" . hour)
17032 ("d" . day)
17033 ("w" . week)
17034 ("m" . month)
17035 ("y" . year)))
17036 (shour (nth 2 (org-parse-time-string start)))
17037 dn dw sday cday n1 n2 n0
17038 d m y y1 y2 date1 date2 nmonths nm ny m2)
17040 (setq start (org-date-to-gregorian start)
17041 current (org-date-to-gregorian
17042 (if show-all
17043 current
17044 (time-to-days (current-time))))
17045 sday (calendar-absolute-from-gregorian start)
17046 cday (calendar-absolute-from-gregorian current))
17048 (if (<= cday sday) (throw 'exit sday))
17050 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17051 (setq dn (string-to-number (match-string 1 change))
17052 dw (cdr (assoc (match-string 2 change) a1)))
17053 (error "Invalid change specifier: %s" change))
17054 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17055 (cond
17056 ((eq dw 'hour)
17057 (let ((missing-hours
17058 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17059 dn)))
17060 (setq n1 (if (zerop missing-hours) cday
17061 (- cday (1+ (floor (/ missing-hours 24)))))
17062 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17063 ((eq dw 'day)
17064 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17065 n2 (+ n1 dn)))
17066 ((eq dw 'year)
17067 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17068 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17069 (setq date1 (list m d y1)
17070 n1 (calendar-absolute-from-gregorian date1)
17071 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17072 n2 (calendar-absolute-from-gregorian date2)))
17073 ((eq dw 'month)
17074 ;; approx number of month between the two dates
17075 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17076 ;; How often does dn fit in there?
17077 (setq d (nth 1 start) m (car start) y (nth 2 start)
17078 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17079 m (+ m nm)
17080 ny (floor (/ m 12))
17081 y (+ y ny)
17082 m (- m (* ny 12)))
17083 (while (> m 12) (setq m (- m 12) y (1+ y)))
17084 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17085 (setq m2 (+ m dn) y2 y)
17086 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17087 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17088 (while (<= n2 cday)
17089 (setq n1 n2 m m2 y y2)
17090 (setq m2 (+ m dn) y2 y)
17091 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17092 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17093 ;; Make sure n1 is the earlier date
17094 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17095 (if show-all
17096 (cond
17097 ((eq prefer 'past) (if (= cday n2) n2 n1))
17098 ((eq prefer 'future) (if (= cday n1) n1 n2))
17099 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17100 (cond
17101 ((eq prefer 'past) (if (= cday n2) n2 n1))
17102 ((eq prefer 'future) (if (= cday n1) n1 n2))
17103 (t (if (= cday n1) n1 n2)))))))
17105 (defun org-date-to-gregorian (date)
17106 "Turn any specification of DATE into a Gregorian date for the calendar."
17107 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17108 ((and (listp date) (= (length date) 3)) date)
17109 ((stringp date)
17110 (setq date (org-parse-time-string date))
17111 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17112 ((listp date)
17113 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17115 (defun org-parse-time-string (s &optional nodefault)
17116 "Parse the standard Org-mode time string.
17117 This should be a lot faster than the normal `parse-time-string'.
17118 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17119 hour and minute fields will be nil if not given."
17120 (cond ((string-match org-ts-regexp0 s)
17121 (list 0
17122 (if (or (match-beginning 8) (not nodefault))
17123 (string-to-number (or (match-string 8 s) "0")))
17124 (if (or (match-beginning 7) (not nodefault))
17125 (string-to-number (or (match-string 7 s) "0")))
17126 (string-to-number (match-string 4 s))
17127 (string-to-number (match-string 3 s))
17128 (string-to-number (match-string 2 s))
17129 nil nil nil))
17130 ((string-match "^<[^>]+>$" s)
17131 (decode-time (seconds-to-time (org-matcher-time s))))
17132 (t (error "Not a standard Org-mode time string: %s" s))))
17134 (defun org-timestamp-up (&optional arg)
17135 "Increase the date item at the cursor by one.
17136 If the cursor is on the year, change the year. If it is on the month,
17137 the day or the time, change that.
17138 With prefix ARG, change by that many units."
17139 (interactive "p")
17140 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17142 (defun org-timestamp-down (&optional arg)
17143 "Decrease the date item at the cursor by one.
17144 If the cursor is on the year, change the year. If it is on the month,
17145 the day or the time, change that.
17146 With prefix ARG, change by that many units."
17147 (interactive "p")
17148 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17150 (defun org-timestamp-up-day (&optional arg)
17151 "Increase the date in the time stamp by one day.
17152 With prefix ARG, change that many days."
17153 (interactive "p")
17154 (if (and (not (org-at-timestamp-p t))
17155 (org-at-heading-p))
17156 (org-todo 'up)
17157 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17159 (defun org-timestamp-down-day (&optional arg)
17160 "Decrease the date in the time stamp by one day.
17161 With prefix ARG, change that many days."
17162 (interactive "p")
17163 (if (and (not (org-at-timestamp-p t))
17164 (org-at-heading-p))
17165 (org-todo 'down)
17166 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17168 (defun org-at-timestamp-p (&optional inactive-ok)
17169 "Determine if the cursor is in or at a timestamp."
17170 (interactive)
17171 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17172 (pos (point))
17173 (ans (or (looking-at tsr)
17174 (save-excursion
17175 (skip-chars-backward "^[<\n\r\t")
17176 (if (> (point) (point-min)) (backward-char 1))
17177 (and (looking-at tsr)
17178 (> (- (match-end 0) pos) -1))))))
17179 (and ans
17180 (boundp 'org-ts-what)
17181 (setq org-ts-what
17182 (cond
17183 ((= pos (match-beginning 0)) 'bracket)
17184 ;; Point is considered to be "on the bracket" whether
17185 ;; it's really on it or right after it.
17186 ((= pos (1- (match-end 0))) 'bracket)
17187 ((= pos (match-end 0)) 'after)
17188 ((org-pos-in-match-range pos 2) 'year)
17189 ((org-pos-in-match-range pos 3) 'month)
17190 ((org-pos-in-match-range pos 7) 'hour)
17191 ((org-pos-in-match-range pos 8) 'minute)
17192 ((or (org-pos-in-match-range pos 4)
17193 (org-pos-in-match-range pos 5)) 'day)
17194 ((and (> pos (or (match-end 8) (match-end 5)))
17195 (< pos (match-end 0)))
17196 (- pos (or (match-end 8) (match-end 5))))
17197 (t 'day))))
17198 ans))
17200 (defun org-toggle-timestamp-type ()
17201 "Toggle the type (<active> or [inactive]) of a time stamp."
17202 (interactive)
17203 (when (org-at-timestamp-p t)
17204 (let ((beg (match-beginning 0)) (end (match-end 0))
17205 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17206 (save-excursion
17207 (goto-char beg)
17208 (while (re-search-forward "[][<>]" end t)
17209 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17210 t t)))
17211 (message "Timestamp is now %sactive"
17212 (if (equal (char-after beg) ?<) "" "in")))))
17214 (defun org-at-clock-log-p nil
17215 "Is the cursor on the clock log line?"
17216 (save-excursion
17217 (move-beginning-of-line 1)
17218 (looking-at "^[ \t]*CLOCK:")))
17220 (defvar org-clock-history) ; defined in org-clock.el
17221 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17222 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17223 "Change the date in the time stamp at point.
17224 The date will be changed by N times WHAT. WHAT can be `day', `month',
17225 `year', `minute', `second'. If WHAT is not given, the cursor position
17226 in the timestamp determines what will be changed.
17227 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17228 (let ((origin (point)) origin-cat
17229 with-hm inactive
17230 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17231 org-ts-what
17232 extra rem
17233 ts time time0 fixnext clrgx)
17234 (if (not (org-at-timestamp-p t))
17235 (error "Not at a timestamp"))
17236 (if (and (not what) (eq org-ts-what 'bracket))
17237 (org-toggle-timestamp-type)
17238 ;; Point isn't on brackets. Remember the part of the time-stamp
17239 ;; the point was in. Indeed, size of time-stamps may change,
17240 ;; but point must be kept in the same category nonetheless.
17241 (setq origin-cat org-ts-what)
17242 (if (and (not what) (not (eq org-ts-what 'day))
17243 org-display-custom-times
17244 (get-text-property (point) 'display)
17245 (not (get-text-property (1- (point)) 'display)))
17246 (setq org-ts-what 'day))
17247 (setq org-ts-what (or what org-ts-what)
17248 inactive (= (char-after (match-beginning 0)) ?\[)
17249 ts (match-string 0))
17250 (replace-match "")
17251 (when (string-match
17252 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17254 (setq extra (match-string 1 ts))
17255 (if suppress-tmp-delay
17256 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17257 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17258 (setq with-hm t))
17259 (setq time0 (org-parse-time-string ts))
17260 (when (and updown
17261 (eq org-ts-what 'minute)
17262 (not current-prefix-arg))
17263 ;; This looks like s-up and s-down. Change by one rounding step.
17264 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17265 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17266 (setcar (cdr time0) (+ (nth 1 time0)
17267 (if (> n 0) (- rem) (- dm rem))))))
17268 (setq time
17269 (encode-time (or (car time0) 0)
17270 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17271 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17272 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17273 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17274 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17275 (nthcdr 6 time0)))
17276 (when (and (member org-ts-what '(hour minute))
17277 extra
17278 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17279 (setq extra (org-modify-ts-extra
17280 extra
17281 (if (eq org-ts-what 'hour) 2 5)
17282 n dm)))
17283 (when (integerp org-ts-what)
17284 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17285 (if (eq what 'calendar)
17286 (let ((cal-date (org-get-date-from-calendar)))
17287 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17288 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17289 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17290 (setcar time0 (or (car time0) 0))
17291 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17292 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17293 (setq time (apply 'encode-time time0))))
17294 ;; Insert the new time-stamp, and ensure point stays in the same
17295 ;; category as before (i.e. not after the last position in that
17296 ;; category).
17297 (let ((pos (point)))
17298 ;; Stay before inserted string. `save-excursion' is of no use.
17299 (setq org-last-changed-timestamp
17300 (org-insert-time-stamp time with-hm inactive nil nil extra))
17301 (goto-char pos))
17302 (save-match-data
17303 (looking-at org-ts-regexp3)
17304 (goto-char (cond
17305 ;; `day' category ends before `hour' if any, or at
17306 ;; the end of the day name.
17307 ((eq origin-cat 'day)
17308 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17309 ((eq origin-cat 'hour) (min (match-end 7) origin))
17310 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17311 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17312 ;; `year' and `month' have both fixed size: point
17313 ;; couldn't have moved into another part.
17314 (t origin))))
17315 ;; Update clock if on a CLOCK line.
17316 (org-clock-update-time-maybe)
17317 ;; Maybe adjust the closest clock in `org-clock-history'
17318 (when org-clock-adjust-closest
17319 (if (not (and (org-at-clock-log-p)
17320 (< 1 (length (delq nil (mapcar 'marker-position
17321 org-clock-history))))))
17322 (message "No clock to adjust")
17323 (cond ((save-excursion ; fix previous clock?
17324 (re-search-backward org-ts-regexp0 nil t)
17325 (org-looking-back (concat org-clock-string " \\[")))
17326 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17327 ((save-excursion ; fix next clock?
17328 (re-search-backward org-ts-regexp0 nil t)
17329 (looking-at (concat org-ts-regexp0 "\\] =>")))
17330 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17331 (save-window-excursion
17332 ;; Find closest clock to point, adjust the previous/next one in history
17333 (let* ((p (save-excursion (org-back-to-heading t)))
17334 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17335 (clfixnth
17336 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17337 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17338 (if (not clfixpos)
17339 (message "No clock to adjust")
17340 (save-excursion
17341 (org-goto-marker-or-bmk clfixpos)
17342 (org-show-subtree)
17343 (when (re-search-forward clrgx nil t)
17344 (goto-char (match-beginning 1))
17345 (let (org-clock-adjust-closest)
17346 (org-timestamp-change n org-ts-what updown))
17347 (message "Clock adjusted in %s for heading: %s"
17348 (file-name-nondirectory (buffer-file-name))
17349 (org-get-heading t t)))))))))
17350 ;; Try to recenter the calendar window, if any.
17351 (if (and org-calendar-follow-timestamp-change
17352 (get-buffer-window "*Calendar*" t)
17353 (memq org-ts-what '(day month year)))
17354 (org-recenter-calendar (time-to-days time))))))
17356 (defun org-modify-ts-extra (s pos n dm)
17357 "Change the different parts of the lead-time and repeat fields in timestamp."
17358 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17359 ng h m new rem)
17360 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17361 (cond
17362 ((or (org-pos-in-match-range pos 2)
17363 (org-pos-in-match-range pos 3))
17364 (setq m (string-to-number (match-string 3 s))
17365 h (string-to-number (match-string 2 s)))
17366 (if (org-pos-in-match-range pos 2)
17367 (setq h (+ h n))
17368 (setq n (* dm (org-no-warnings (signum n))))
17369 (when (not (= 0 (setq rem (% m dm))))
17370 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17371 (setq m (+ m n)))
17372 (if (< m 0) (setq m (+ m 60) h (1- h)))
17373 (if (> m 59) (setq m (- m 60) h (1+ h)))
17374 (setq h (min 24 (max 0 h)))
17375 (setq ng 1 new (format "-%02d:%02d" h m)))
17376 ((org-pos-in-match-range pos 6)
17377 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17378 ((org-pos-in-match-range pos 5)
17379 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17381 ((org-pos-in-match-range pos 9)
17382 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17383 ((org-pos-in-match-range pos 8)
17384 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17386 (when ng
17387 (setq s (concat
17388 (substring s 0 (match-beginning ng))
17390 (substring s (match-end ng))))))
17393 (defun org-recenter-calendar (date)
17394 "If the calendar is visible, recenter it to DATE."
17395 (let ((cwin (get-buffer-window "*Calendar*" t)))
17396 (when cwin
17397 (let ((calendar-move-hook nil))
17398 (with-selected-window cwin
17399 (calendar-goto-date (if (listp date) date
17400 (calendar-gregorian-from-absolute date))))))))
17402 (defun org-goto-calendar (&optional arg)
17403 "Go to the Emacs calendar at the current date.
17404 If there is a time stamp in the current line, go to that date.
17405 A prefix ARG can be used to force the current date."
17406 (interactive "P")
17407 (let ((tsr org-ts-regexp) diff
17408 (calendar-move-hook nil)
17409 (calendar-view-holidays-initially-flag nil)
17410 (calendar-view-diary-initially-flag nil))
17411 (if (or (org-at-timestamp-p)
17412 (save-excursion
17413 (beginning-of-line 1)
17414 (looking-at (concat ".*" tsr))))
17415 (let ((d1 (time-to-days (current-time)))
17416 (d2 (time-to-days
17417 (org-time-string-to-time (match-string 1)))))
17418 (setq diff (- d2 d1))))
17419 (calendar)
17420 (calendar-goto-today)
17421 (if (and diff (not arg)) (calendar-forward-day diff))))
17423 (defun org-get-date-from-calendar ()
17424 "Return a list (month day year) of date at point in calendar."
17425 (with-current-buffer "*Calendar*"
17426 (save-match-data
17427 (calendar-cursor-to-date))))
17429 (defun org-date-from-calendar ()
17430 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17431 If there is already a time stamp at the cursor position, update it."
17432 (interactive)
17433 (if (org-at-timestamp-p t)
17434 (org-timestamp-change 0 'calendar)
17435 (let ((cal-date (org-get-date-from-calendar)))
17436 (org-insert-time-stamp
17437 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17439 (defcustom org-effort-durations
17440 `(("h" . 60)
17441 ("d" . ,(* 60 8))
17442 ("w" . ,(* 60 8 5))
17443 ("m" . ,(* 60 8 5 4))
17444 ("y" . ,(* 60 8 5 40)))
17445 "Conversion factor to minutes for an effort modifier.
17447 Each entry has the form (MODIFIER . MINUTES).
17449 In an effort string, a number followed by MODIFIER is multiplied
17450 by the specified number of MINUTES to obtain an effort in
17451 minutes.
17453 For example, if the value of this variable is ((\"hours\" . 60)), then an
17454 effort string \"2hours\" is equivalent to 120 minutes."
17455 :group 'org-agenda
17456 :version "24.1"
17457 :type '(alist :key-type (string :tag "Modifier")
17458 :value-type (number :tag "Minutes")))
17460 (defun org-minutes-to-clocksum-string (m)
17461 "Format number of minutes as a clocksum string.
17462 The format is determined by `org-time-clocksum-format',
17463 `org-time-clocksum-use-fractional' and
17464 `org-time-clocksum-fractional-format' and
17465 `org-time-clocksum-use-effort-durations'."
17466 (let ((clocksum "")
17467 (m (round m)) ; Don't allow fractions of minutes
17468 h d w mo y fmt n)
17469 (setq h (if org-time-clocksum-use-effort-durations
17470 (cdr (assoc "h" org-effort-durations)) 60)
17471 d (if org-time-clocksum-use-effort-durations
17472 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17473 w (if org-time-clocksum-use-effort-durations
17474 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17475 mo (if org-time-clocksum-use-effort-durations
17476 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17477 y (if org-time-clocksum-use-effort-durations
17478 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17479 ;; fractional format
17480 (if org-time-clocksum-use-fractional
17481 (cond
17482 ;; single format string
17483 ((stringp org-time-clocksum-fractional-format)
17484 (format org-time-clocksum-fractional-format (/ m (float h))))
17485 ;; choice of fractional formats for different time units
17486 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17487 (> (/ (truncate m) (* y d h)) 0))
17488 (format fmt (/ m (* y d (float h)))))
17489 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17490 (> (/ (truncate m) (* mo d h)) 0))
17491 (format fmt (/ m (* mo d (float h)))))
17492 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17493 (> (/ (truncate m) (* w d h)) 0))
17494 (format fmt (/ m (* w d (float h)))))
17495 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17496 (> (/ (truncate m) (* d h)) 0))
17497 (format fmt (/ m (* d (float h)))))
17498 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17499 (> (/ (truncate m) h) 0))
17500 (format fmt (/ m (float h))))
17501 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17502 (format fmt m))
17503 ;; fall back to smallest time unit with a format
17504 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17505 (format fmt (/ m (float h))))
17506 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17507 (format fmt (/ m (* d (float h)))))
17508 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17509 (format fmt (/ m (* w d (float h)))))
17510 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17511 (format fmt (/ m (* mo d (float h)))))
17512 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17513 (format fmt (/ m (* y d (float h))))))
17514 ;; standard (non-fractional) format, with single format string
17515 (if (stringp org-time-clocksum-format)
17516 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17517 ;; separate formats components
17518 (and (setq fmt (plist-get org-time-clocksum-format :years))
17519 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17520 (plist-get org-time-clocksum-format :require-years))
17521 (setq clocksum (concat clocksum (format fmt n))
17522 m (- m (* n y d h))))
17523 (and (setq fmt (plist-get org-time-clocksum-format :months))
17524 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17525 (plist-get org-time-clocksum-format :require-months))
17526 (setq clocksum (concat clocksum (format fmt n))
17527 m (- m (* n mo d h))))
17528 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17529 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17530 (plist-get org-time-clocksum-format :require-weeks))
17531 (setq clocksum (concat clocksum (format fmt n))
17532 m (- m (* n w d h))))
17533 (and (setq fmt (plist-get org-time-clocksum-format :days))
17534 (or (> (setq n (/ (truncate m) (* d h))) 0)
17535 (plist-get org-time-clocksum-format :require-days))
17536 (setq clocksum (concat clocksum (format fmt n))
17537 m (- m (* n d h))))
17538 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17539 (or (> (setq n (/ (truncate m) h)) 0)
17540 (plist-get org-time-clocksum-format :require-hours))
17541 (setq clocksum (concat clocksum (format fmt n))
17542 m (- m (* n h))))
17543 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17544 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17545 (setq clocksum (concat clocksum (format fmt m))))
17546 ;; return formatted time duration
17547 clocksum))))
17549 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17550 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17551 "Org mode version 8.0")
17553 (defun org-hours-to-clocksum-string (n)
17554 (org-minutes-to-clocksum-string (* n 60)))
17556 (defun org-hh:mm-string-to-minutes (s)
17557 "Convert a string H:MM to a number of minutes.
17558 If the string is just a number, interpret it as minutes.
17559 In fact, the first hh:mm or number in the string will be taken,
17560 there can be extra stuff in the string.
17561 If no number is found, the return value is 0."
17562 (cond
17563 ((integerp s) s)
17564 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17565 (+ (* (string-to-number (match-string 1 s)) 60)
17566 (string-to-number (match-string 2 s))))
17567 ((string-match "\\([0-9]+\\)" s)
17568 (string-to-number (match-string 1 s)))
17569 (t 0)))
17571 (defcustom org-image-actual-width t
17572 "Should we use the actual width of images when inlining them?
17574 When set to `t', always use the image width.
17576 When set to a number, use imagemagick (when available) to set
17577 the image's width to this value.
17579 When set to a number in a list, try to get the width from any
17580 #+ATTR.* keyword if it matches a width specification like
17582 #+ATTR_HTML: :width 300px
17584 and fall back on that number if none is found.
17586 When set to nil, try to get the width from an #+ATTR.* keyword
17587 and fall back on the original width if none is found.
17589 This requires Emacs >= 24.1, build with imagemagick support."
17590 :group 'org-appearance
17591 :version "24.4"
17592 :package-version '(Org . "8.0")
17593 :type '(choice
17594 (const :tag "Use the image width" t)
17595 (integer :tag "Use a number of pixels")
17596 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17597 (const :tag "Use #+ATTR* or don't resize" nil)))
17599 (defcustom org-agenda-inhibit-startup nil
17600 "Inhibit startup when preparing agenda buffers.
17601 When this variable is `t' (the default), the initialization of
17602 the Org agenda buffers is inhibited: e.g. the visibility state
17603 is not set, the tables are not re-aligned, etc."
17604 :type 'boolean
17605 :version "24.3"
17606 :group 'org-agenda)
17608 (defun org-duration-string-to-minutes (s &optional output-to-string)
17609 "Convert a duration string S to minutes.
17611 A bare number is interpreted as minutes, modifiers can be set by
17612 customizing `org-effort-durations' (which see).
17614 Entries containing a colon are interpreted as H:MM by
17615 `org-hh:mm-string-to-minutes'."
17616 (let ((result 0)
17617 (re (concat "\\([0-9.]+\\) *\\("
17618 (regexp-opt (mapcar 'car org-effort-durations))
17619 "\\)")))
17620 (while (string-match re s)
17621 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17622 (string-to-number (match-string 1 s))))
17623 (setq s (replace-match "" nil t s)))
17624 (setq result (floor result))
17625 (incf result (org-hh:mm-string-to-minutes s))
17626 (if output-to-string (number-to-string result) result)))
17628 ;;;; Files
17630 (defun org-save-all-org-buffers ()
17631 "Save all Org-mode buffers without user confirmation."
17632 (interactive)
17633 (message "Saving all Org-mode buffers...")
17634 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17635 (when (featurep 'org-id) (org-id-locations-save))
17636 (message "Saving all Org-mode buffers... done"))
17638 (defun org-revert-all-org-buffers ()
17639 "Revert all Org-mode buffers.
17640 Prompt for confirmation when there are unsaved changes.
17641 Be sure you know what you are doing before letting this function
17642 overwrite your changes.
17644 This function is useful in a setup where one tracks org files
17645 with a version control system, to revert on one machine after pulling
17646 changes from another. I believe the procedure must be like this:
17648 1. M-x org-save-all-org-buffers
17649 2. Pull changes from the other machine, resolve conflicts
17650 3. M-x org-revert-all-org-buffers"
17651 (interactive)
17652 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17653 (error "Abort"))
17654 (save-excursion
17655 (save-window-excursion
17656 (mapc
17657 (lambda (b)
17658 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17659 (with-current-buffer b buffer-file-name))
17660 (org-pop-to-buffer-same-window b)
17661 (revert-buffer t 'no-confirm)))
17662 (buffer-list))
17663 (when (and (featurep 'org-id) org-id-track-globally)
17664 (org-id-locations-load)))))
17666 ;;;; Agenda files
17668 ;;;###autoload
17669 (defun org-switchb (&optional arg)
17670 "Switch between Org buffers.
17671 With one prefix argument, restrict available buffers to files.
17672 With two prefix arguments, restrict available buffers to agenda files.
17674 Defaults to `iswitchb' for buffer name completion.
17675 Set `org-completion-use-ido' to make it use ido instead."
17676 (interactive "P")
17677 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17678 ((equal arg '(16)) (org-buffer-list 'agenda))
17679 (t (org-buffer-list))))
17680 (org-completion-use-iswitchb org-completion-use-iswitchb)
17681 (org-completion-use-ido org-completion-use-ido))
17682 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17683 (setq org-completion-use-iswitchb t))
17684 (org-pop-to-buffer-same-window
17685 (org-icompleting-read "Org buffer: "
17686 (mapcar 'list (mapcar 'buffer-name blist))
17687 nil t))))
17689 ;;; Define some older names previously used for this functionality
17690 ;;;###autoload
17691 (defalias 'org-ido-switchb 'org-switchb)
17692 ;;;###autoload
17693 (defalias 'org-iswitchb 'org-switchb)
17695 (defun org-buffer-list (&optional predicate exclude-tmp)
17696 "Return a list of Org buffers.
17697 PREDICATE can be `export', `files' or `agenda'.
17699 export restrict the list to Export buffers.
17700 files restrict the list to buffers visiting Org files.
17701 agenda restrict the list to buffers visiting agenda files.
17703 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17704 (let* ((bfn nil)
17705 (agenda-files (and (eq predicate 'agenda)
17706 (mapcar 'file-truename (org-agenda-files t))))
17707 (filter
17708 (cond
17709 ((eq predicate 'files)
17710 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17711 ((eq predicate 'export)
17712 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17713 ((eq predicate 'agenda)
17714 (lambda (b)
17715 (with-current-buffer b
17716 (and (derived-mode-p 'org-mode)
17717 (setq bfn (buffer-file-name b))
17718 (member (file-truename bfn) agenda-files)))))
17719 (t (lambda (b) (with-current-buffer b
17720 (or (derived-mode-p 'org-mode)
17721 (string-match "\*Org .*Export"
17722 (buffer-name b)))))))))
17723 (delq nil
17724 (mapcar
17725 (lambda(b)
17726 (if (and (funcall filter b)
17727 (or (not exclude-tmp)
17728 (not (string-match "tmp" (buffer-name b)))))
17730 nil))
17731 (buffer-list)))))
17733 (defun org-agenda-files (&optional unrestricted archives)
17734 "Get the list of agenda files.
17735 Optional UNRESTRICTED means return the full list even if a restriction
17736 is currently in place.
17737 When ARCHIVES is t, include all archive files that are really being
17738 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17739 `org-agenda-archives-mode' is t."
17740 (let ((files
17741 (cond
17742 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17743 ((stringp org-agenda-files) (org-read-agenda-file-list))
17744 ((listp org-agenda-files) org-agenda-files)
17745 (t (error "Invalid value of `org-agenda-files'")))))
17746 (setq files (apply 'append
17747 (mapcar (lambda (f)
17748 (if (file-directory-p f)
17749 (directory-files
17750 f t org-agenda-file-regexp)
17751 (list f)))
17752 files)))
17753 (when org-agenda-skip-unavailable-files
17754 (setq files (delq nil
17755 (mapcar (function
17756 (lambda (file)
17757 (and (file-readable-p file) file)))
17758 files))))
17759 (when (or (eq archives t)
17760 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17761 (setq files (org-add-archive-files files)))
17762 files))
17764 (defun org-agenda-file-p (&optional file)
17765 "Return non-nil, if FILE is an agenda file.
17766 If FILE is omitted, use the file associated with the current
17767 buffer."
17768 (member (or file (buffer-file-name))
17769 (org-agenda-files t)))
17771 (defun org-edit-agenda-file-list ()
17772 "Edit the list of agenda files.
17773 Depending on setup, this either uses customize to edit the variable
17774 `org-agenda-files', or it visits the file that is holding the list. In the
17775 latter case, the buffer is set up in a way that saving it automatically kills
17776 the buffer and restores the previous window configuration."
17777 (interactive)
17778 (if (stringp org-agenda-files)
17779 (let ((cw (current-window-configuration)))
17780 (find-file org-agenda-files)
17781 (org-set-local 'org-window-configuration cw)
17782 (org-add-hook 'after-save-hook
17783 (lambda ()
17784 (set-window-configuration
17785 (prog1 org-window-configuration
17786 (kill-buffer (current-buffer))))
17787 (org-install-agenda-files-menu)
17788 (message "New agenda file list installed"))
17789 nil 'local)
17790 (message "%s" (substitute-command-keys
17791 "Edit list and finish with \\[save-buffer]")))
17792 (customize-variable 'org-agenda-files)))
17794 (defun org-store-new-agenda-file-list (list)
17795 "Set new value for the agenda file list and save it correctly."
17796 (if (stringp org-agenda-files)
17797 (let ((fe (org-read-agenda-file-list t)) b u)
17798 (while (setq b (find-buffer-visiting org-agenda-files))
17799 (kill-buffer b))
17800 (with-temp-file org-agenda-files
17801 (insert
17802 (mapconcat
17803 (lambda (f) ;; Keep un-expanded entries.
17804 (if (setq u (assoc f fe))
17805 (cdr u)
17807 list "\n")
17808 "\n")))
17809 (let ((org-mode-hook nil) (org-inhibit-startup t)
17810 (org-insert-mode-line-in-empty-file nil))
17811 (setq org-agenda-files list)
17812 (customize-save-variable 'org-agenda-files org-agenda-files))))
17814 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17815 "Read the list of agenda files from a file.
17816 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17817 filenames, used by `org-store-new-agenda-file-list' to write back
17818 un-expanded file names."
17819 (when (file-directory-p org-agenda-files)
17820 (error "`org-agenda-files' cannot be a single directory"))
17821 (when (stringp org-agenda-files)
17822 (with-temp-buffer
17823 (insert-file-contents org-agenda-files)
17824 (mapcar
17825 (lambda (f)
17826 (let ((e (expand-file-name (substitute-in-file-name f)
17827 org-directory)))
17828 (if pair-with-expansion
17829 (cons e f)
17830 e)))
17831 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17833 ;;;###autoload
17834 (defun org-cycle-agenda-files ()
17835 "Cycle through the files in `org-agenda-files'.
17836 If the current buffer visits an agenda file, find the next one in the list.
17837 If the current buffer does not, find the first agenda file."
17838 (interactive)
17839 (let* ((fs (org-agenda-files t))
17840 (files (append fs (list (car fs))))
17841 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17842 file)
17843 (unless files (error "No agenda files"))
17844 (catch 'exit
17845 (while (setq file (pop files))
17846 (if (equal (file-truename file) tcf)
17847 (when (car files)
17848 (find-file (car files))
17849 (throw 'exit t))))
17850 (find-file (car fs)))
17851 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17853 (defun org-agenda-file-to-front (&optional to-end)
17854 "Move/add the current file to the top of the agenda file list.
17855 If the file is not present in the list, it is added to the front. If it is
17856 present, it is moved there. With optional argument TO-END, add/move to the
17857 end of the list."
17858 (interactive "P")
17859 (let ((org-agenda-skip-unavailable-files nil)
17860 (file-alist (mapcar (lambda (x)
17861 (cons (file-truename x) x))
17862 (org-agenda-files t)))
17863 (ctf (file-truename
17864 (or buffer-file-name
17865 (error "Please save the current buffer to a file"))))
17866 x had)
17867 (setq x (assoc ctf file-alist) had x)
17869 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17870 (if to-end
17871 (setq file-alist (append (delq x file-alist) (list x)))
17872 (setq file-alist (cons x (delq x file-alist))))
17873 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17874 (org-install-agenda-files-menu)
17875 (message "File %s to %s of agenda file list"
17876 (if had "moved" "added") (if to-end "end" "front"))))
17878 (defun org-remove-file (&optional file)
17879 "Remove current file from the list of files in variable `org-agenda-files'.
17880 These are the files which are being checked for agenda entries.
17881 Optional argument FILE means use this file instead of the current."
17882 (interactive)
17883 (let* ((org-agenda-skip-unavailable-files nil)
17884 (file (or file buffer-file-name
17885 (error "Current buffer does not visit a file")))
17886 (true-file (file-truename file))
17887 (afile (abbreviate-file-name file))
17888 (files (delq nil (mapcar
17889 (lambda (x)
17890 (if (equal true-file
17891 (file-truename x))
17892 nil x))
17893 (org-agenda-files t)))))
17894 (if (not (= (length files) (length (org-agenda-files t))))
17895 (progn
17896 (org-store-new-agenda-file-list files)
17897 (org-install-agenda-files-menu)
17898 (message "Removed file: %s" afile))
17899 (message "File was not in list: %s (not removed)" afile))))
17901 (defun org-file-menu-entry (file)
17902 (vector file (list 'find-file file) t))
17904 (defun org-check-agenda-file (file)
17905 "Make sure FILE exists. If not, ask user what to do."
17906 (when (not (file-exists-p file))
17907 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17908 (abbreviate-file-name file))
17909 (let ((r (downcase (read-char-exclusive))))
17910 (cond
17911 ((equal r ?r)
17912 (org-remove-file file)
17913 (throw 'nextfile t))
17914 (t (error "Abort"))))))
17916 (defun org-get-agenda-file-buffer (file)
17917 "Get a buffer visiting FILE. If the buffer needs to be created, add
17918 it to the list of buffers which might be released later."
17919 (let ((buf (org-find-base-buffer-visiting file)))
17920 (if buf
17921 buf ; just return it
17922 ;; Make a new buffer and remember it
17923 (setq buf (find-file-noselect file))
17924 (if buf (push buf org-agenda-new-buffers))
17925 buf)))
17927 (defun org-release-buffers (blist)
17928 "Release all buffers in list, asking the user for confirmation when needed.
17929 When a buffer is unmodified, it is just killed. When modified, it is saved
17930 \(if the user agrees) and then killed."
17931 (let (buf file)
17932 (while (setq buf (pop blist))
17933 (setq file (buffer-file-name buf))
17934 (when (and (buffer-modified-p buf)
17935 file
17936 (y-or-n-p (format "Save file %s? " file)))
17937 (with-current-buffer buf (save-buffer)))
17938 (kill-buffer buf))))
17940 (defun org-agenda-prepare-buffers (files)
17941 "Create buffers for all agenda files, protect archived trees and comments."
17942 (interactive)
17943 (let ((pa '(:org-archived t))
17944 (pc '(:org-comment t))
17945 (pall '(:org-archived t :org-comment t))
17946 (inhibit-read-only t)
17947 (org-inhibit-startup org-agenda-inhibit-startup)
17948 (rea (concat ":" org-archive-tag ":"))
17949 file re)
17950 (setq org-tag-alist-for-agenda nil
17951 org-tag-groups-alist-for-agenda nil)
17952 (save-excursion
17953 (save-restriction
17954 (while (setq file (pop files))
17955 (catch 'nextfile
17956 (if (bufferp file)
17957 (set-buffer file)
17958 (org-check-agenda-file file)
17959 (set-buffer (org-get-agenda-file-buffer file)))
17960 (widen)
17961 (org-set-regexps-and-options-for-tags)
17962 (org-refresh-category-properties)
17963 (org-refresh-properties org-effort-property 'org-effort)
17964 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17965 (setq org-todo-keywords-for-agenda
17966 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17967 (setq org-done-keywords-for-agenda
17968 (append org-done-keywords-for-agenda org-done-keywords))
17969 (setq org-todo-keyword-alist-for-agenda
17970 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17971 (setq org-drawers-for-agenda
17972 (append org-drawers-for-agenda org-drawers))
17973 (unless (equal org-tag-alist-for-agenda org-tag-alist)
17974 (setq org-tag-alist-for-agenda
17975 (append org-tag-alist-for-agenda org-tag-alist)))
17976 (if org-group-tags
17977 (setq org-tag-groups-alist-for-agenda
17978 (org-uniquify-alist
17979 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
17980 (org-with-silent-modifications
17981 (save-excursion
17982 (remove-text-properties (point-min) (point-max) pall)
17983 (when org-agenda-skip-archived-trees
17984 (goto-char (point-min))
17985 (while (re-search-forward rea nil t)
17986 (if (org-at-heading-p t)
17987 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17988 (goto-char (point-min))
17989 (setq re (format org-heading-keyword-regexp-format
17990 org-comment-string))
17991 (while (re-search-forward re nil t)
17992 (add-text-properties
17993 (match-beginning 0) (org-end-of-subtree t) pc))))))))
17994 (setq org-todo-keywords-for-agenda
17995 (org-uniquify org-todo-keywords-for-agenda))
17996 (setq org-todo-keyword-alist-for-agenda
17997 (org-uniquify org-todo-keyword-alist-for-agenda))))
18000 ;;;; CDLaTeX minor mode
18002 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18003 "Keymap for the minor `org-cdlatex-mode'.")
18005 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18006 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18007 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18008 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18009 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18011 (defvar org-cdlatex-texmathp-advice-is-done nil
18012 "Flag remembering if we have applied the advice to texmathp already.")
18014 (define-minor-mode org-cdlatex-mode
18015 "Toggle the minor `org-cdlatex-mode'.
18016 This mode supports entering LaTeX environment and math in LaTeX fragments
18017 in Org-mode.
18018 \\{org-cdlatex-mode-map}"
18019 nil " OCDL" nil
18020 (when org-cdlatex-mode
18021 (require 'cdlatex)
18022 (run-hooks 'cdlatex-mode-hook)
18023 (cdlatex-compute-tables))
18024 (unless org-cdlatex-texmathp-advice-is-done
18025 (setq org-cdlatex-texmathp-advice-is-done t)
18026 (defadvice texmathp (around org-math-always-on activate)
18027 "Always return t in org-mode buffers.
18028 This is because we want to insert math symbols without dollars even outside
18029 the LaTeX math segments. If Orgmode thinks that point is actually inside
18030 an embedded LaTeX fragment, let texmathp do its job.
18031 \\[org-cdlatex-mode-map]"
18032 (interactive)
18033 (let (p)
18034 (cond
18035 ((not (derived-mode-p 'org-mode)) ad-do-it)
18036 ((eq this-command 'cdlatex-math-symbol)
18037 (setq ad-return-value t
18038 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18040 (let ((p (org-inside-LaTeX-fragment-p)))
18041 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18042 (setq ad-return-value t
18043 texmathp-why '("Org-mode embedded math" . 0))
18044 (if p ad-do-it)))))))))
18046 (defun turn-on-org-cdlatex ()
18047 "Unconditionally turn on `org-cdlatex-mode'."
18048 (org-cdlatex-mode 1))
18050 (defun org-try-cdlatex-tab ()
18051 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18052 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18053 - inside a LaTeX fragment, or
18054 - after the first word in a line, where an abbreviation expansion could
18055 insert a LaTeX environment."
18056 (when org-cdlatex-mode
18057 (cond
18058 ;; Before any word on the line: No expansion possible.
18059 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18060 ;; Just after first word on the line: Expand it. Make sure it
18061 ;; cannot happen on headlines, though.
18062 ((save-excursion
18063 (skip-chars-backward "a-zA-Z0-9*")
18064 (skip-chars-backward " \t")
18065 (and (bolp) (not (org-at-heading-p))))
18066 (cdlatex-tab) t)
18067 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18069 (defun org-cdlatex-underscore-caret (&optional arg)
18070 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18071 Revert to the normal definition outside of these fragments."
18072 (interactive "P")
18073 (if (org-inside-LaTeX-fragment-p)
18074 (call-interactively 'cdlatex-sub-superscript)
18075 (let (org-cdlatex-mode)
18076 (call-interactively (key-binding (vector last-input-event))))))
18078 (defun org-cdlatex-math-modify (&optional arg)
18079 "Execute `cdlatex-math-modify' in LaTeX fragments.
18080 Revert to the normal definition outside of these fragments."
18081 (interactive "P")
18082 (if (org-inside-LaTeX-fragment-p)
18083 (call-interactively 'cdlatex-math-modify)
18084 (let (org-cdlatex-mode)
18085 (call-interactively (key-binding (vector last-input-event))))))
18089 ;;;; LaTeX fragments
18091 (defvar org-latex-regexps
18092 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18093 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18094 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18095 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18096 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18097 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18098 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18099 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18100 "Regular expressions for matching embedded LaTeX.")
18102 (defun org-inside-LaTeX-fragment-p ()
18103 "Test if point is inside a LaTeX fragment.
18104 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18105 sequence appearing also before point.
18106 Even though the matchers for math are configurable, this function assumes
18107 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18108 delimiters are skipped when they have been removed by customization.
18109 The return value is nil, or a cons cell with the delimiter and the
18110 position of this delimiter.
18112 This function does a reasonably good job, but can locally be fooled by
18113 for example currency specifications. For example it will assume being in
18114 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18115 fragments that are properly closed, but during editing, we have to live
18116 with the uncertainty caused by missing closing delimiters. This function
18117 looks only before point, not after."
18118 (catch 'exit
18119 (let ((pos (point))
18120 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18121 (lim (progn
18122 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18123 (point)))
18124 dd-on str (start 0) m re)
18125 (goto-char pos)
18126 (when dodollar
18127 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18128 re (nth 1 (assoc "$" org-latex-regexps)))
18129 (while (string-match re str start)
18130 (cond
18131 ((= (match-end 0) (length str))
18132 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18133 ((= (match-end 0) (- (length str) 5))
18134 (throw 'exit nil))
18135 (t (setq start (match-end 0))))))
18136 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18137 (goto-char pos)
18138 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18139 (and (match-beginning 2) (throw 'exit nil))
18140 ;; count $$
18141 (while (re-search-backward "\\$\\$" lim t)
18142 (setq dd-on (not dd-on)))
18143 (goto-char pos)
18144 (if dd-on (cons "$$" m))))))
18146 (defun org-inside-latex-macro-p ()
18147 "Is point inside a LaTeX macro or its arguments?"
18148 (save-match-data
18149 (org-in-regexp
18150 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18152 (defvar org-latex-fragment-image-overlays nil
18153 "List of overlays carrying the images of latex fragments.")
18154 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18156 (defun org-remove-latex-fragment-image-overlays ()
18157 "Remove all overlays with LaTeX fragment images in current buffer."
18158 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18159 (setq org-latex-fragment-image-overlays nil))
18161 (defun org-preview-latex-fragment (&optional subtree)
18162 "Preview the LaTeX fragment at point, or all locally or globally.
18163 If the cursor is in a LaTeX fragment, create the image and overlay
18164 it over the source code. If there is no fragment at point, display
18165 all fragments in the current text, from one headline to the next. With
18166 prefix SUBTREE, display all fragments in the current subtree. With a
18167 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18168 the cursor is before the first headline,
18169 display all fragments in the buffer.
18170 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18171 (interactive "P")
18172 (unless buffer-file-name
18173 (error "Can't preview LaTeX fragment in a non-file buffer"))
18174 (org-remove-latex-fragment-image-overlays)
18175 (save-excursion
18176 (save-restriction
18177 (let (beg end at msg)
18178 (cond
18179 ((or (equal subtree '(16))
18180 (not (save-excursion
18181 (re-search-backward org-outline-regexp-bol nil t))))
18182 (setq beg (point-min) end (point-max)
18183 msg "Creating images for buffer...%s"))
18184 ((equal subtree '(4))
18185 (org-back-to-heading)
18186 (setq beg (point) end (org-end-of-subtree t)
18187 msg "Creating images for subtree...%s"))
18189 (if (setq at (org-inside-LaTeX-fragment-p))
18190 (goto-char (max (point-min) (- (cdr at) 2)))
18191 (org-back-to-heading))
18192 (setq beg (point) end (progn (outline-next-heading) (point))
18193 msg (if at "Creating image...%s"
18194 "Creating images for entry...%s"))))
18195 (message msg "")
18196 (narrow-to-region beg end)
18197 (goto-char beg)
18198 (org-format-latex
18199 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18200 (file-name-nondirectory
18201 buffer-file-name)))
18202 default-directory 'overlays msg at 'forbuffer
18203 org-latex-create-formula-image-program)
18204 (message msg "done. Use `C-c C-c' to remove images.")))))
18206 (defun org-format-latex (prefix &optional dir overlays msg at
18207 forbuffer processing-type)
18208 "Replace LaTeX fragments with links to an image, and produce images.
18209 Some of the options can be changed using the variable
18210 `org-format-latex-options'."
18211 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18212 (let* ((prefixnodir (file-name-nondirectory prefix))
18213 (absprefix (expand-file-name prefix dir))
18214 (todir (file-name-directory absprefix))
18215 (opt org-format-latex-options)
18216 (optnew org-format-latex-options)
18217 (matchers (plist-get opt :matchers))
18218 (re-list org-latex-regexps)
18219 (cnt 0) txt hash link beg end re e checkdir
18220 string
18221 m n block-type block linkfile movefile ov)
18222 ;; Check the different regular expressions
18223 (while (setq e (pop re-list))
18224 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18225 block (if block-type "\n\n" ""))
18226 (when (member m matchers)
18227 (goto-char (point-min))
18228 (while (re-search-forward re nil t)
18229 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18230 (or (not overlays)
18231 (not (eq (get-char-property (match-beginning n)
18232 'org-overlay-type)
18233 'org-latex-overlay))))
18234 (cond
18235 ((eq processing-type 'verbatim))
18236 ((eq processing-type 'mathjax)
18237 ;; Prepare for MathJax processing.
18238 (setq string (match-string n))
18239 (when (member m '("$" "$1"))
18240 (save-excursion
18241 (delete-region (match-beginning n) (match-end n))
18242 (goto-char (match-beginning n))
18243 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18244 ((or (eq processing-type 'dvipng)
18245 (eq processing-type 'imagemagick))
18246 ;; Process to an image.
18247 (setq txt (match-string n)
18248 beg (match-beginning n) end (match-end n)
18249 cnt (1+ cnt))
18250 (let ((face (face-at-point))
18251 (fg (plist-get opt :foreground))
18252 (bg (plist-get opt :background))
18253 ;; Ensure full list is printed.
18254 print-length print-level)
18255 (when forbuffer
18256 ;; Get the colors from the face at point.
18257 (goto-char beg)
18258 (when (eq fg 'auto)
18259 (setq fg (face-attribute face :foreground nil 'default)))
18260 (when (eq bg 'auto)
18261 (setq bg (face-attribute face :background nil 'default)))
18262 (setq optnew (copy-sequence opt))
18263 (plist-put optnew :foreground fg)
18264 (plist-put optnew :background bg))
18265 (setq hash (sha1 (prin1-to-string
18266 (list org-format-latex-header
18267 org-latex-default-packages-alist
18268 org-latex-packages-alist
18269 org-format-latex-options
18270 forbuffer txt fg bg)))
18271 linkfile (format "%s_%s.png" prefix hash)
18272 movefile (format "%s_%s.png" absprefix hash)))
18273 (setq link (concat block "[[file:" linkfile "]]" block))
18274 (if msg (message msg cnt))
18275 (goto-char beg)
18276 (unless checkdir ; Ensure the directory exists.
18277 (setq checkdir t)
18278 (or (file-directory-p todir) (make-directory todir t)))
18279 (unless (file-exists-p movefile)
18280 (org-create-formula-image
18281 txt movefile optnew forbuffer processing-type))
18282 (if overlays
18283 (progn
18284 (mapc (lambda (o)
18285 (if (eq (overlay-get o 'org-overlay-type)
18286 'org-latex-overlay)
18287 (delete-overlay o)))
18288 (overlays-in beg end))
18289 (setq ov (make-overlay beg end))
18290 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18291 (if (featurep 'xemacs)
18292 (progn
18293 (overlay-put ov 'invisible t)
18294 (overlay-put
18295 ov 'end-glyph
18296 (make-glyph (vector 'png :file movefile))))
18297 (overlay-put
18298 ov 'display
18299 (list 'image :type 'png :file movefile :ascent 'center)))
18300 (push ov org-latex-fragment-image-overlays)
18301 (goto-char end))
18302 (delete-region beg end)
18303 (insert (org-add-props link
18304 (list 'org-latex-src
18305 (replace-regexp-in-string
18306 "\"" "" txt)
18307 'org-latex-src-embed-type
18308 (if block-type 'paragraph 'character))))))
18309 ((eq processing-type 'mathml)
18310 ;; Process to MathML
18311 (unless (save-match-data (org-format-latex-mathml-available-p))
18312 (error "LaTeX to MathML converter not configured"))
18313 (setq txt (match-string n)
18314 beg (match-beginning n) end (match-end n)
18315 cnt (1+ cnt))
18316 (if msg (message msg cnt))
18317 (goto-char beg)
18318 (delete-region beg end)
18319 (insert (org-format-latex-as-mathml
18320 txt block-type prefix dir)))
18322 (error "Unknown conversion type %s for latex fragments"
18323 processing-type)))))))))
18325 (defun org-create-math-formula (latex-frag &optional mathml-file)
18326 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18327 Use `org-latex-to-mathml-convert-command'. If the conversion is
18328 sucessful, return the portion between \"<math...> </math>\"
18329 elements otherwise return nil. When MATHML-FILE is specified,
18330 write the results in to that file. When invoked as an
18331 interactive command, prompt for LATEX-FRAG, with initial value
18332 set to the current active region and echo the results for user
18333 inspection."
18334 (interactive (list (let ((frag (when (org-region-active-p)
18335 (buffer-substring-no-properties
18336 (region-beginning) (region-end)))))
18337 (read-string "LaTeX Fragment: " frag nil frag))))
18338 (unless latex-frag (error "Invalid latex-frag"))
18339 (let* ((tmp-in-file (file-relative-name
18340 (make-temp-name (expand-file-name "ltxmathml-in"))))
18341 (ignore (write-region latex-frag nil tmp-in-file))
18342 (tmp-out-file (file-relative-name
18343 (make-temp-name (expand-file-name "ltxmathml-out"))))
18344 (cmd (format-spec
18345 org-latex-to-mathml-convert-command
18346 `((?j . ,(shell-quote-argument
18347 (expand-file-name org-latex-to-mathml-jar-file)))
18348 (?I . ,(shell-quote-argument tmp-in-file))
18349 (?o . ,(shell-quote-argument tmp-out-file)))))
18350 mathml shell-command-output)
18351 (when (org-called-interactively-p 'any)
18352 (unless (org-format-latex-mathml-available-p)
18353 (error "LaTeX to MathML converter not configured")))
18354 (message "Running %s" cmd)
18355 (setq shell-command-output (shell-command-to-string cmd))
18356 (setq mathml
18357 (when (file-readable-p tmp-out-file)
18358 (with-current-buffer (find-file-noselect tmp-out-file t)
18359 (goto-char (point-min))
18360 (when (re-search-forward
18361 (concat
18362 (regexp-quote
18363 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18364 "\\(.\\|\n\\)*"
18365 (regexp-quote "</math>")) nil t)
18366 (prog1 (match-string 0) (kill-buffer))))))
18367 (cond
18368 (mathml
18369 (setq mathml
18370 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18371 (when mathml-file
18372 (write-region mathml nil mathml-file))
18373 (when (org-called-interactively-p 'any)
18374 (message mathml)))
18375 ((message "LaTeX to MathML conversion failed")
18376 (message shell-command-output)))
18377 (delete-file tmp-in-file)
18378 (when (file-exists-p tmp-out-file)
18379 (delete-file tmp-out-file))
18380 mathml))
18382 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18383 prefix &optional dir)
18384 "Use `org-create-math-formula' but check local cache first."
18385 (let* ((absprefix (expand-file-name prefix dir))
18386 (print-length nil) (print-level nil)
18387 (formula-id (concat
18388 "formula-"
18389 (sha1
18390 (prin1-to-string
18391 (list latex-frag
18392 org-latex-to-mathml-convert-command)))))
18393 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18394 (formula-cache-dir (file-name-directory formula-cache)))
18396 (unless (file-directory-p formula-cache-dir)
18397 (make-directory formula-cache-dir t))
18399 (unless (file-exists-p formula-cache)
18400 (org-create-math-formula latex-frag formula-cache))
18402 (if (file-exists-p formula-cache)
18403 ;; Successful conversion. Return the link to MathML file.
18404 (org-add-props
18405 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18406 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18407 'org-latex-src-embed-type (if latex-frag-type
18408 'paragraph 'character)))
18409 ;; Failed conversion. Return the LaTeX fragment verbatim
18410 latex-frag)))
18412 (defun org-create-formula-image (string tofile options buffer &optional type)
18413 "Create an image from LaTeX source using dvipng or convert.
18414 This function calls either `org-create-formula-image-with-dvipng'
18415 or `org-create-formula-image-with-imagemagick' depending on the
18416 value of `org-latex-create-formula-image-program' or on the value
18417 of the optional TYPE variable.
18419 Note: ultimately these two function should be combined as they
18420 share a good deal of logic."
18421 (org-check-external-command
18422 "latex" "needed to convert LaTeX fragments to images")
18423 (funcall
18424 (case (or type org-latex-create-formula-image-program)
18425 ('dvipng
18426 (org-check-external-command
18427 "dvipng" "needed to convert LaTeX fragments to images")
18428 #'org-create-formula-image-with-dvipng)
18429 ('imagemagick
18430 (org-check-external-command
18431 "convert" "you need to install imagemagick")
18432 #'org-create-formula-image-with-imagemagick)
18433 (t (error
18434 "invalid value of `org-latex-create-formula-image-program'")))
18435 string tofile options buffer))
18437 (declare-function org-export--get-global-options "ox" (&optional backend))
18438 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18439 (defun org-create-formula--latex-header ()
18440 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18441 (org-latex-guess-inputenc
18442 (org-splice-latex-header
18443 org-format-latex-header
18444 org-latex-default-packages-alist
18445 org-latex-packages-alist t
18446 (plist-get
18447 (org-combine-plists
18448 (org-export--get-global-options 'latex)
18449 (org-export--get-inbuffer-options 'latex))
18450 :latex-header))))
18452 ;; This function borrows from Ganesh Swami's latex2png.el
18453 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18454 "This calls dvipng."
18455 (require 'ox-latex)
18456 (let* ((tmpdir (if (featurep 'xemacs)
18457 (temp-directory)
18458 temporary-file-directory))
18459 (texfilebase (make-temp-name
18460 (expand-file-name "orgtex" tmpdir)))
18461 (texfile (concat texfilebase ".tex"))
18462 (dvifile (concat texfilebase ".dvi"))
18463 (pngfile (concat texfilebase ".png"))
18464 (fnh (if (featurep 'xemacs)
18465 (font-height (face-font 'default))
18466 (face-attribute 'default :height nil)))
18467 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18468 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18469 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18470 "Black"))
18471 (bg (or (plist-get options (if buffer :background :html-background))
18472 "Transparent")))
18473 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18474 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18475 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18476 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18477 (let ((latex-header (org-create-formula--latex-header)))
18478 (with-temp-file texfile
18479 (insert latex-header)
18480 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18481 (let ((dir default-directory))
18482 (condition-case nil
18483 (progn
18484 (cd tmpdir)
18485 (call-process "latex" nil nil nil texfile))
18486 (error nil))
18487 (cd dir))
18488 (if (not (file-exists-p dvifile))
18489 (progn (message "Failed to create dvi file from %s" texfile) nil)
18490 (condition-case nil
18491 (if (featurep 'xemacs)
18492 (call-process "dvipng" nil nil nil
18493 "-fg" fg "-bg" bg
18494 "-T" "tight"
18495 "-o" pngfile
18496 dvifile)
18497 (call-process "dvipng" nil nil nil
18498 "-fg" fg "-bg" bg
18499 "-D" dpi
18500 ;;"-x" scale "-y" scale
18501 "-T" "tight"
18502 "-o" pngfile
18503 dvifile))
18504 (error nil))
18505 (if (not (file-exists-p pngfile))
18506 (if org-format-latex-signal-error
18507 (error "Failed to create png file from %s" texfile)
18508 (message "Failed to create png file from %s" texfile)
18509 nil)
18510 ;; Use the requested file name and clean up
18511 (copy-file pngfile tofile 'replace)
18512 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18513 (if (file-exists-p (concat texfilebase e))
18514 (delete-file (concat texfilebase e))))
18515 pngfile))))
18517 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18518 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18519 "This calls convert, which is included into imagemagick."
18520 (require 'ox-latex)
18521 (let* ((tmpdir (if (featurep 'xemacs)
18522 (temp-directory)
18523 temporary-file-directory))
18524 (texfilebase (make-temp-name
18525 (expand-file-name "orgtex" tmpdir)))
18526 (texfile (concat texfilebase ".tex"))
18527 (pdffile (concat texfilebase ".pdf"))
18528 (pngfile (concat texfilebase ".png"))
18529 (fnh (if (featurep 'xemacs)
18530 (font-height (face-font 'default))
18531 (face-attribute 'default :height nil)))
18532 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18533 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18534 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18535 "black"))
18536 (bg (or (plist-get options (if buffer :background :html-background))
18537 "white")))
18538 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18539 (setq fg (org-latex-color-format fg)))
18540 (if (eq bg 'default) (setq bg (org-latex-color :background))
18541 (setq bg (org-latex-color-format
18542 (if (string= bg "Transparent") "white" bg))))
18543 (let ((latex-header (org-create-formula--latex-header)))
18544 (with-temp-file texfile
18545 (insert latex-header)
18546 (insert "\n\\begin{document}\n"
18547 "\\definecolor{fg}{rgb}{" fg "}\n"
18548 "\\definecolor{bg}{rgb}{" bg "}\n"
18549 "\n\\pagecolor{bg}\n"
18550 "\n{\\color{fg}\n"
18551 string
18552 "\n}\n"
18553 "\n\\end{document}\n")))
18554 (org-latex-compile texfile t)
18555 (if (not (file-exists-p pdffile))
18556 (progn (message "Failed to create pdf file from %s" texfile) nil)
18557 (condition-case nil
18558 (if (featurep 'xemacs)
18559 (call-process "convert" nil nil nil
18560 "-density" "96"
18561 "-trim"
18562 "-antialias"
18563 pdffile
18564 "-quality" "100"
18565 ;; "-sharpen" "0x1.0"
18566 pngfile)
18567 (call-process "convert" nil nil nil
18568 "-density" dpi
18569 "-trim"
18570 "-antialias"
18571 pdffile
18572 "-quality" "100"
18573 ;; "-sharpen" "0x1.0"
18574 pngfile))
18575 (error nil))
18576 (if (not (file-exists-p pngfile))
18577 (if org-format-latex-signal-error
18578 (error "Failed to create png file from %s" texfile)
18579 (message "Failed to create png file from %s" texfile)
18580 nil)
18581 ;; Use the requested file name and clean up
18582 (copy-file pngfile tofile 'replace)
18583 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18584 (if (file-exists-p (concat texfilebase e))
18585 (delete-file (concat texfilebase e))))
18586 pngfile))))
18588 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18589 "Fill a LaTeX header template TPL.
18590 In the template, the following place holders will be recognized:
18592 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18593 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18594 [PACKAGES] \\usepackage statements for PKG
18595 [NO-PACKAGES] do not include PKG
18596 [EXTRA] the string EXTRA
18597 [NO-EXTRA] do not include EXTRA
18599 For backward compatibility, if both the positive and the negative place
18600 holder is missing, the positive one (without the \"NO-\") will be
18601 assumed to be present at the end of the template.
18602 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18603 EXTRA is a string.
18604 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18605 (let (rpl (end ""))
18606 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18607 (setq rpl (if (or (match-end 1) (not def-pkg))
18608 "" (org-latex-packages-to-string def-pkg snippets-p t))
18609 tpl (replace-match rpl t t tpl))
18610 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18612 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18613 (setq rpl (if (or (match-end 1) (not pkg))
18614 "" (org-latex-packages-to-string pkg snippets-p t))
18615 tpl (replace-match rpl t t tpl))
18616 (if pkg (setq end
18617 (concat end "\n"
18618 (org-latex-packages-to-string pkg snippets-p)))))
18620 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18621 (setq rpl (if (or (match-end 1) (not extra))
18622 "" (concat extra "\n"))
18623 tpl (replace-match rpl t t tpl))
18624 (if (and extra (string-match "\\S-" extra))
18625 (setq end (concat end "\n" extra))))
18627 (if (string-match "\\S-" end)
18628 (concat tpl "\n" end)
18629 tpl)))
18631 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18632 "Turn an alist of packages into a string with the \\usepackage macros."
18633 (setq pkg (mapconcat (lambda(p)
18634 (cond
18635 ((stringp p) p)
18636 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18637 (format "%% Package %s omitted" (cadr p)))
18638 ((equal "" (car p))
18639 (format "\\usepackage{%s}" (cadr p)))
18641 (format "\\usepackage[%s]{%s}"
18642 (car p) (cadr p)))))
18644 "\n"))
18645 (if newline (concat pkg "\n") pkg))
18647 (defun org-dvipng-color (attr)
18648 "Return a RGB color specification for dvipng."
18649 (apply 'format "rgb %s %s %s"
18650 (mapcar 'org-normalize-color
18651 (if (featurep 'xemacs)
18652 (color-rgb-components
18653 (face-property 'default
18654 (cond ((eq attr :foreground) 'foreground)
18655 ((eq attr :background) 'background))))
18656 (color-values (face-attribute 'default attr nil))))))
18658 (defun org-dvipng-color-format (color-name)
18659 "Convert COLOR-NAME to a RGB color value for dvipng."
18660 (apply 'format "rgb %s %s %s"
18661 (mapcar 'org-normalize-color
18662 (color-values color-name))))
18664 (defun org-latex-color (attr)
18665 "Return a RGB color for the LaTeX color package."
18666 (apply 'format "%s,%s,%s"
18667 (mapcar 'org-normalize-color
18668 (if (featurep 'xemacs)
18669 (color-rgb-components
18670 (face-property 'default
18671 (cond ((eq attr :foreground) 'foreground)
18672 ((eq attr :background) 'background))))
18673 (color-values (face-attribute 'default attr nil))))))
18675 (defun org-latex-color-format (color-name)
18676 "Convert COLOR-NAME to a RGB color value."
18677 (apply 'format "%s,%s,%s"
18678 (mapcar 'org-normalize-color
18679 (color-values color-name))))
18681 (defun org-normalize-color (value)
18682 "Return string to be used as color value for an RGB component."
18683 (format "%g" (/ value 65535.0)))
18687 ;; Image display
18689 (defvar org-inline-image-overlays nil)
18690 (make-variable-buffer-local 'org-inline-image-overlays)
18692 (defun org-toggle-inline-images (&optional include-linked)
18693 "Toggle the display of inline images.
18694 INCLUDE-LINKED is passed to `org-display-inline-images'."
18695 (interactive "P")
18696 (if org-inline-image-overlays
18697 (progn
18698 (org-remove-inline-images)
18699 (message "Inline image display turned off"))
18700 (org-display-inline-images include-linked)
18701 (if (and (org-called-interactively-p)
18702 org-inline-image-overlays)
18703 (message "%d images displayed inline"
18704 (length org-inline-image-overlays))
18705 (message "No images to display inline"))))
18707 (defun org-redisplay-inline-images ()
18708 "Refresh the display of inline images."
18709 (interactive)
18710 (if (not org-inline-image-overlays)
18711 (org-toggle-inline-images)
18712 (org-toggle-inline-images)
18713 (org-toggle-inline-images)))
18715 (defun org-display-inline-images (&optional include-linked refresh beg end)
18716 "Display inline images.
18717 Normally only links without a description part are inlined, because this
18718 is how it will work for export. When INCLUDE-LINKED is set, also links
18719 with a description part will be inlined. This can be nice for a quick
18720 look at those images, but it does not reflect what exported files will look
18721 like.
18722 When REFRESH is set, refresh existing images between BEG and END.
18723 This will create new image displays only if necessary.
18724 BEG and END default to the buffer boundaries."
18725 (interactive "P")
18726 (unless refresh
18727 (org-remove-inline-images)
18728 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18729 (save-excursion
18730 (save-restriction
18731 (widen)
18732 (setq beg (or beg (point-min)) end (or end (point-max)))
18733 (goto-char beg)
18734 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18735 (substring (org-image-file-name-regexp) 0 -2)
18736 "\\)\\]" (if include-linked "" "\\]")))
18737 (case-fold-search t)
18738 old file ov img type attrwidth width)
18739 (while (re-search-forward re end t)
18740 (setq old (get-char-property-and-overlay (match-beginning 1)
18741 'org-image-overlay)
18742 file (expand-file-name
18743 (concat (or (match-string 3) "") (match-string 4))))
18744 (when (image-type-available-p 'imagemagick)
18745 (setq attrwidth (if (or (listp org-image-actual-width)
18746 (null org-image-actual-width))
18747 (save-excursion
18748 (save-match-data
18749 (when (re-search-backward
18750 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18751 (save-excursion
18752 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18753 (string-to-number (match-string 1))))))
18754 width (cond ((eq org-image-actual-width t) nil)
18755 ((null org-image-actual-width) attrwidth)
18756 ((numberp org-image-actual-width)
18757 org-image-actual-width)
18758 ((listp org-image-actual-width)
18759 (or attrwidth (car org-image-actual-width))))
18760 type (if width 'imagemagick)))
18761 (when (file-exists-p file)
18762 (if (and (car-safe old) refresh)
18763 (image-refresh (overlay-get (cdr old) 'display))
18764 (setq img (save-match-data (create-image file type nil :width width)))
18765 (when img
18766 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18767 (overlay-put ov 'display img)
18768 (overlay-put ov 'face 'default)
18769 (overlay-put ov 'org-image-overlay t)
18770 (overlay-put ov 'modification-hooks
18771 (list 'org-display-inline-remove-overlay))
18772 (push ov org-inline-image-overlays)))))))))
18774 (define-obsolete-function-alias
18775 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18777 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18778 "Remove inline-display overlay if a corresponding region is modified."
18779 (let ((inhibit-modification-hooks t))
18780 (when (and ov after)
18781 (delete ov org-inline-image-overlays)
18782 (delete-overlay ov))))
18784 (defun org-remove-inline-images ()
18785 "Remove inline display of images."
18786 (interactive)
18787 (mapc 'delete-overlay org-inline-image-overlays)
18788 (setq org-inline-image-overlays nil))
18790 ;;;; Key bindings
18792 ;; Outline functions from `outline-mode-prefix-map'
18793 ;; that can be remapped in Org:
18794 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18795 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18796 (define-key org-mode-map [remap outline-forward-same-level]
18797 'org-forward-heading-same-level)
18798 (define-key org-mode-map [remap outline-backward-same-level]
18799 'org-backward-heading-same-level)
18800 (define-key org-mode-map [remap show-branches]
18801 'org-kill-note-or-show-branches)
18802 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18803 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18804 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18806 ;; Outline functions from `outline-mode-prefix-map' that can not
18807 ;; be remapped in Org:
18809 ;; - the column "key binding" shows whether the Outline function is still
18810 ;; available in Org mode on the same key that it has been bound to in
18811 ;; Outline mode:
18812 ;; - "overridden": key used for a different functionality in Org mode
18813 ;; - else: key still bound to the same Outline function in Org mode
18815 ;; | Outline function | key binding | Org replacement |
18816 ;; |------------------------------------+-------------+-----------------------|
18817 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18818 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18819 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18820 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18821 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18822 ;; | `show-entry' | overridden | no replacement |
18823 ;; | `show-children' | `C-c C-i' | visibility cycling |
18824 ;; | `show-branches' | `C-c C-k' | still same function |
18825 ;; | `show-subtree' | overridden | visibility cycling |
18826 ;; | `show-all' | overridden | no replacement |
18827 ;; | `hide-subtree' | overridden | visibility cycling |
18828 ;; | `hide-body' | overridden | no replacement |
18829 ;; | `hide-entry' | overridden | visibility cycling |
18830 ;; | `hide-leaves' | overridden | no replacement |
18831 ;; | `hide-sublevels' | overridden | no replacement |
18832 ;; | `hide-other' | overridden | no replacement |
18834 ;; Make `C-c C-x' a prefix key
18835 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18837 ;; TAB key with modifiers
18838 (org-defkey org-mode-map "\C-i" 'org-cycle)
18839 (org-defkey org-mode-map [(tab)] 'org-cycle)
18840 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18841 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18842 ;; The following line is necessary under Suse GNU/Linux
18843 (unless (featurep 'xemacs)
18844 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18845 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18846 (define-key org-mode-map [backtab] 'org-shifttab)
18848 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18849 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18850 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18852 ;; Cursor keys with modifiers
18853 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18854 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18855 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18856 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18858 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18859 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18860 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18861 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18863 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18864 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18865 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18866 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18868 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18869 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18870 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18871 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18873 ;; Babel keys
18874 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18875 (mapc (lambda (pair)
18876 (define-key org-babel-map (car pair) (cdr pair)))
18877 org-babel-key-bindings)
18879 ;;; Extra keys for tty access.
18880 ;; We only set them when really needed because otherwise the
18881 ;; menus don't show the simple keys
18883 (when (or org-use-extra-keys
18884 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18885 (not window-system))
18886 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18887 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18888 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18889 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18890 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18891 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18892 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18893 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18894 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18895 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18896 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18897 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18898 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18899 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18900 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18901 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18902 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18903 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18904 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18905 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18906 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18907 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18908 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18909 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18910 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18911 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18912 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18913 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18915 ;; All the other keys
18917 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18918 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18919 (if (boundp 'narrow-map)
18920 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18921 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18922 (if (boundp 'narrow-map)
18923 (org-defkey narrow-map "b" 'org-narrow-to-block)
18924 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18925 (if (boundp 'narrow-map)
18926 (org-defkey narrow-map "e" 'org-narrow-to-element)
18927 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18928 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18929 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18930 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18931 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18932 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18933 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18934 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18935 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18936 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18937 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18938 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18939 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18940 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18941 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18942 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18943 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18944 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
18945 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18946 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18947 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18948 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18949 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18950 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18951 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18952 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18953 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18954 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18955 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18956 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18957 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18958 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18959 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18960 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18961 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18962 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18963 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18964 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18965 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18966 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18967 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18968 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18969 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18970 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18971 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18972 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18973 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18974 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18975 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18976 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18977 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18978 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18979 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18980 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18981 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18982 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18983 (org-defkey org-mode-map "\C-c^" 'org-sort)
18984 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18985 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18986 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18987 (org-defkey org-mode-map "\C-o" 'org-ctrl-o)
18988 (org-defkey org-mode-map "\C-m" 'org-return)
18989 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18990 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18991 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18992 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18993 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18994 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18995 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18996 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18997 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18998 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18999 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19000 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19001 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19002 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19003 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19004 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19005 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19006 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19007 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19008 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19009 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19010 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19011 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19013 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19014 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19015 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19017 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19018 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19019 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19020 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19021 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19022 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19023 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19024 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19025 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19026 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19027 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19028 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19029 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19030 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19031 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19032 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19033 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19034 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19035 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19036 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19037 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19038 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19039 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19041 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19042 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19043 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19044 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19045 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19047 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19049 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19051 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19052 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19054 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19057 (when (featurep 'xemacs)
19058 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19061 (defconst org-speed-commands-default
19063 ("Outline Navigation")
19064 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19065 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19066 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19067 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19068 ("F" . org-next-block)
19069 ("B" . org-previous-block)
19070 ("u" . (org-speed-move-safe 'outline-up-heading))
19071 ("j" . org-goto)
19072 ("g" . (org-refile t))
19073 ("Outline Visibility")
19074 ("c" . org-cycle)
19075 ("C" . org-shifttab)
19076 (" " . org-display-outline-path)
19077 ("s" . org-narrow-to-subtree)
19078 ("=" . org-columns)
19079 ("Outline Structure Editing")
19080 ("U" . org-shiftmetaup)
19081 ("D" . org-shiftmetadown)
19082 ("r" . org-metaright)
19083 ("l" . org-metaleft)
19084 ("R" . org-shiftmetaright)
19085 ("L" . org-shiftmetaleft)
19086 ("i" . (progn (forward-char 1) (call-interactively
19087 'org-insert-heading-respect-content)))
19088 ("^" . org-sort)
19089 ("w" . org-refile)
19090 ("a" . org-archive-subtree-default-with-confirmation)
19091 ("@" . org-mark-subtree)
19092 ("#" . org-toggle-comment)
19093 ("Clock Commands")
19094 ("I" . org-clock-in)
19095 ("O" . org-clock-out)
19096 ("Meta Data Editing")
19097 ("t" . org-todo)
19098 ("," . (org-priority))
19099 ("0" . (org-priority ?\ ))
19100 ("1" . (org-priority ?A))
19101 ("2" . (org-priority ?B))
19102 ("3" . (org-priority ?C))
19103 (":" . org-set-tags-command)
19104 ("e" . org-set-effort)
19105 ("E" . org-inc-effort)
19106 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19107 (org-entry-put (point) "APPT_WARNTIME" m)))
19108 ("Agenda Views etc")
19109 ("v" . org-agenda)
19110 ("/" . org-sparse-tree)
19111 ("Misc")
19112 ("o" . org-open-at-point)
19113 ("?" . org-speed-command-help)
19114 ("<" . (org-agenda-set-restriction-lock 'subtree))
19115 (">" . (org-agenda-remove-restriction-lock))
19117 "The default speed commands.")
19119 (defun org-print-speed-command (e)
19120 (if (> (length (car e)) 1)
19121 (progn
19122 (princ "\n")
19123 (princ (car e))
19124 (princ "\n")
19125 (princ (make-string (length (car e)) ?-))
19126 (princ "\n"))
19127 (princ (car e))
19128 (princ " ")
19129 (if (symbolp (cdr e))
19130 (princ (symbol-name (cdr e)))
19131 (prin1 (cdr e)))
19132 (princ "\n")))
19134 (defun org-speed-command-help ()
19135 "Show the available speed commands."
19136 (interactive)
19137 (if (not org-use-speed-commands)
19138 (error "Speed commands are not activated, customize `org-use-speed-commands'")
19139 (with-output-to-temp-buffer "*Help*"
19140 (princ "User-defined Speed commands\n===========================\n")
19141 (mapc 'org-print-speed-command org-speed-commands-user)
19142 (princ "\n")
19143 (princ "Built-in Speed commands\n=======================\n")
19144 (mapc 'org-print-speed-command org-speed-commands-default))
19145 (with-current-buffer "*Help*"
19146 (setq truncate-lines t))))
19148 (defun org-speed-move-safe (cmd)
19149 "Execute CMD, but make sure that the cursor always ends up in a headline.
19150 If not, return to the original position and throw an error."
19151 (interactive)
19152 (let ((pos (point)))
19153 (call-interactively cmd)
19154 (unless (and (bolp) (org-at-heading-p))
19155 (goto-char pos)
19156 (error "Boundary reached while executing %s" cmd))))
19158 (defvar org-self-insert-command-undo-counter 0)
19160 (defvar org-table-auto-blank-field) ; defined in org-table.el
19161 (defvar org-speed-command nil)
19163 (define-obsolete-function-alias
19164 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19166 (defun org-speed-command-activate (keys)
19167 "Hook for activating single-letter speed commands.
19168 `org-speed-commands-default' specifies a minimal command set.
19169 Use `org-speed-commands-user' for further customization."
19170 (when (or (and (bolp) (looking-at org-outline-regexp))
19171 (and (functionp org-use-speed-commands)
19172 (funcall org-use-speed-commands)))
19173 (cdr (assoc keys (append org-speed-commands-user
19174 org-speed-commands-default)))))
19176 (define-obsolete-function-alias
19177 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19179 (defun org-babel-speed-command-activate (keys)
19180 "Hook for activating single-letter code block commands."
19181 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19182 (cdr (assoc keys org-babel-key-bindings))))
19184 (defcustom org-speed-command-hook
19185 '(org-speed-command-default-hook org-babel-speed-command-hook)
19186 "Hook for activating speed commands at strategic locations.
19187 Hook functions are called in sequence until a valid handler is
19188 found.
19190 Each hook takes a single argument, a user-pressed command key
19191 which is also a `self-insert-command' from the global map.
19193 Within the hook, examine the cursor position and the command key
19194 and return nil or a valid handler as appropriate. Handler could
19195 be one of an interactive command, a function, or a form.
19197 Set `org-use-speed-commands' to non-nil value to enable this
19198 hook. The default setting is `org-speed-command-activate'."
19199 :group 'org-structure
19200 :version "24.1"
19201 :type 'hook)
19203 (defun org-self-insert-command (N)
19204 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19205 If the cursor is in a table looking at whitespace, the whitespace is
19206 overwritten, and the table is not marked as requiring realignment."
19207 (interactive "p")
19208 (org-check-before-invisible-edit 'insert)
19209 (cond
19210 ((and org-use-speed-commands
19211 (setq org-speed-command
19212 (run-hook-with-args-until-success
19213 'org-speed-command-hook (this-command-keys))))
19214 (cond
19215 ((commandp org-speed-command)
19216 (setq this-command org-speed-command)
19217 (call-interactively org-speed-command))
19218 ((functionp org-speed-command)
19219 (funcall org-speed-command))
19220 ((and org-speed-command (listp org-speed-command))
19221 (eval org-speed-command))
19222 (t (let (org-use-speed-commands)
19223 (call-interactively 'org-self-insert-command)))))
19224 ((and
19225 (org-table-p)
19226 (progn
19227 ;; check if we blank the field, and if that triggers align
19228 (and (featurep 'org-table) org-table-auto-blank-field
19229 (member last-command
19230 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19231 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19232 ;; got extra space, this field does not determine column width
19233 (let (org-table-may-need-update) (org-table-blank-field))
19234 ;; no extra space, this field may determine column width
19235 (org-table-blank-field)))
19237 (eq N 1)
19238 (looking-at "[^|\n]* |"))
19239 (let (org-table-may-need-update)
19240 (goto-char (1- (match-end 0)))
19241 (backward-delete-char 1)
19242 (goto-char (match-beginning 0))
19243 (self-insert-command N)))
19245 (setq org-table-may-need-update t)
19246 (self-insert-command N)
19247 (org-fix-tags-on-the-fly)
19248 (if org-self-insert-cluster-for-undo
19249 (if (not (eq last-command 'org-self-insert-command))
19250 (setq org-self-insert-command-undo-counter 1)
19251 (if (>= org-self-insert-command-undo-counter 20)
19252 (setq org-self-insert-command-undo-counter 1)
19253 (and (> org-self-insert-command-undo-counter 0)
19254 buffer-undo-list (listp buffer-undo-list)
19255 (not (cadr buffer-undo-list)) ; remove nil entry
19256 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19257 (setq org-self-insert-command-undo-counter
19258 (1+ org-self-insert-command-undo-counter))))))))
19260 (defun org-check-before-invisible-edit (kind)
19261 "Check is editing if kind KIND would be dangerous with invisible text around.
19262 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19263 ;; First, try to get out of here as quickly as possible, to reduce overhead
19264 (if (and org-catch-invisible-edits
19265 (or (not (boundp 'visible-mode)) (not visible-mode))
19266 (or (get-char-property (point) 'invisible)
19267 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19268 ;; OK, we need to take a closer look
19269 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19270 (invisible-before-point (if (bobp) nil (get-char-property
19271 (1- (point)) 'invisible)))
19272 (border-and-ok-direction
19274 ;; Check if we are acting predictably before invisible text
19275 (and invisible-at-point (not invisible-before-point)
19276 (memq kind '(insert delete-backward)))
19277 ;; Check if we are acting predictably after invisible text
19278 ;; This works not well, and I have turned it off. It seems
19279 ;; better to always show and stop after invisible text.
19280 ;; (and (not invisible-at-point) invisible-before-point
19281 ;; (memq kind '(insert delete)))
19283 (when (or (memq invisible-at-point '(outline org-hide-block t))
19284 (memq invisible-before-point '(outline org-hide-block t)))
19285 (if (eq org-catch-invisible-edits 'error)
19286 (error "Editing in invisible areas is prohibited - make visible first"))
19287 (if (and org-custom-properties-overlays
19288 (y-or-n-p "Display invisible properties in this buffer? "))
19289 (org-toggle-custom-properties-visibility)
19290 ;; Make the area visible
19291 (save-excursion
19292 (if invisible-before-point
19293 (goto-char (previous-single-char-property-change
19294 (point) 'invisible)))
19295 (org-cycle))
19296 (cond
19297 ((eq org-catch-invisible-edits 'show)
19298 ;; That's it, we do the edit after showing
19299 (message
19300 "Unfolding invisible region around point before editing")
19301 (sit-for 1))
19302 ((and (eq org-catch-invisible-edits 'smart)
19303 border-and-ok-direction)
19304 (message "Unfolding invisible region around point before editing"))
19306 ;; Don't do the edit, make the user repeat it in full visibility
19307 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19309 (defun org-fix-tags-on-the-fly ()
19310 (when (and (equal (char-after (point-at-bol)) ?*)
19311 (org-at-heading-p))
19312 (org-align-tags-here org-tags-column)))
19314 (defun org-delete-backward-char (N)
19315 "Like `delete-backward-char', insert whitespace at field end in tables.
19316 When deleting backwards, in tables this function will insert whitespace in
19317 front of the next \"|\" separator, to keep the table aligned. The table will
19318 still be marked for re-alignment if the field did fill the entire column,
19319 because, in this case the deletion might narrow the column."
19320 (interactive "p")
19321 (save-match-data
19322 (org-check-before-invisible-edit 'delete-backward)
19323 (if (and (org-table-p)
19324 (eq N 1)
19325 (string-match "|" (buffer-substring (point-at-bol) (point)))
19326 (looking-at ".*?|"))
19327 (let ((pos (point))
19328 (noalign (looking-at "[^|\n\r]* |"))
19329 (c org-table-may-need-update))
19330 (backward-delete-char N)
19331 (if (not overwrite-mode)
19332 (progn
19333 (skip-chars-forward "^|")
19334 (insert " ")
19335 (goto-char (1- pos))))
19336 ;; noalign: if there were two spaces at the end, this field
19337 ;; does not determine the width of the column.
19338 (if noalign (setq org-table-may-need-update c)))
19339 (backward-delete-char N)
19340 (org-fix-tags-on-the-fly))))
19342 (defun org-delete-char (N)
19343 "Like `delete-char', but insert whitespace at field end in tables.
19344 When deleting characters, in tables this function will insert whitespace in
19345 front of the next \"|\" separator, to keep the table aligned. The table will
19346 still be marked for re-alignment if the field did fill the entire column,
19347 because, in this case the deletion might narrow the column."
19348 (interactive "p")
19349 (save-match-data
19350 (org-check-before-invisible-edit 'delete)
19351 (if (and (org-table-p)
19352 (not (bolp))
19353 (not (= (char-after) ?|))
19354 (eq N 1))
19355 (if (looking-at ".*?|")
19356 (let ((pos (point))
19357 (noalign (looking-at "[^|\n\r]* |"))
19358 (c org-table-may-need-update))
19359 (replace-match
19360 (concat (substring (match-string 0) 1 -1) " |") nil t)
19361 (goto-char pos)
19362 ;; noalign: if there were two spaces at the end, this field
19363 ;; does not determine the width of the column.
19364 (if noalign (setq org-table-may-need-update c)))
19365 (delete-char N))
19366 (delete-char N)
19367 (org-fix-tags-on-the-fly))))
19369 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19370 (put 'org-self-insert-command 'delete-selection t)
19371 (put 'orgtbl-self-insert-command 'delete-selection t)
19372 (put 'org-delete-char 'delete-selection 'supersede)
19373 (put 'org-delete-backward-char 'delete-selection 'supersede)
19374 (put 'org-yank 'delete-selection 'yank)
19376 ;; Make `flyspell-mode' delay after some commands
19377 (put 'org-self-insert-command 'flyspell-delayed t)
19378 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19379 (put 'org-delete-char 'flyspell-delayed t)
19380 (put 'org-delete-backward-char 'flyspell-delayed t)
19382 ;; Make pabbrev-mode expand after org-mode commands
19383 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19384 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19386 ;; How to do this: Measure non-white length of current string
19387 ;; If equal to column width, we should realign.
19389 (defun org-remap (map &rest commands)
19390 "In MAP, remap the functions given in COMMANDS.
19391 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19392 (let (new old)
19393 (while commands
19394 (setq old (pop commands) new (pop commands))
19395 (if (fboundp 'command-remapping)
19396 (org-defkey map (vector 'remap old) new)
19397 (substitute-key-definition old new map global-map)))))
19399 (defun org-transpose-words ()
19400 "Transpose words for Org.
19401 This uses the `org-mode-transpose-word-syntax-table' syntax
19402 table, which interprets characters in `org-emphasis-alist' as
19403 word constituants."
19404 (interactive)
19405 (with-syntax-table org-mode-transpose-word-syntax-table
19406 (call-interactively 'transpose-words)))
19407 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19409 (when (eq org-enable-table-editor 'optimized)
19410 ;; If the user wants maximum table support, we need to hijack
19411 ;; some standard editing functions
19412 (org-remap org-mode-map
19413 'self-insert-command 'org-self-insert-command
19414 'delete-char 'org-delete-char
19415 'delete-backward-char 'org-delete-backward-char)
19416 (org-defkey org-mode-map "|" 'org-force-self-insert))
19418 (defvar org-ctrl-c-ctrl-c-hook nil
19419 "Hook for functions attaching themselves to `C-c C-c'.
19421 This can be used to add additional functionality to the C-c C-c
19422 key which executes context-dependent commands. This hook is run
19423 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19424 run after the last test.
19426 Each function will be called with no arguments. The function
19427 must check if the context is appropriate for it to act. If yes,
19428 it should do its thing and then return a non-nil value. If the
19429 context is wrong, just do nothing and return nil.")
19431 (defvar org-ctrl-c-ctrl-c-final-hook nil
19432 "Hook for functions attaching themselves to `C-c C-c'.
19434 This can be used to add additional functionality to the C-c C-c
19435 key which executes context-dependent commands. This hook is run
19436 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19437 before the first test.
19439 Each function will be called with no arguments. The function
19440 must check if the context is appropriate for it to act. If yes,
19441 it should do its thing and then return a non-nil value. If the
19442 context is wrong, just do nothing and return nil.")
19444 (defvar org-tab-first-hook nil
19445 "Hook for functions to attach themselves to TAB.
19446 See `org-ctrl-c-ctrl-c-hook' for more information.
19447 This hook runs as the first action when TAB is pressed, even before
19448 `org-cycle' messes around with the `outline-regexp' to cater for
19449 inline tasks and plain list item folding.
19450 If any function in this hook returns t, any other actions that
19451 would have been caused by TAB (such as table field motion or visibility
19452 cycling) will not occur.")
19454 (defvar org-tab-after-check-for-table-hook nil
19455 "Hook for functions to attach themselves to TAB.
19456 See `org-ctrl-c-ctrl-c-hook' for more information.
19457 This hook runs after it has been established that the cursor is not in a
19458 table, but before checking if the cursor is in a headline or if global cycling
19459 should be done.
19460 If any function in this hook returns t, not other actions like visibility
19461 cycling will be done.")
19463 (defvar org-tab-after-check-for-cycling-hook nil
19464 "Hook for functions to attach themselves to TAB.
19465 See `org-ctrl-c-ctrl-c-hook' for more information.
19466 This hook runs after it has been established that not table field motion and
19467 not visibility should be done because of current context. This is probably
19468 the place where a package like yasnippets can hook in.")
19470 (defvar org-tab-before-tab-emulation-hook nil
19471 "Hook for functions to attach themselves to TAB.
19472 See `org-ctrl-c-ctrl-c-hook' for more information.
19473 This hook runs after every other options for TAB have been exhausted, but
19474 before indentation and \t insertion takes place.")
19476 (defvar org-metaleft-hook nil
19477 "Hook for functions attaching themselves to `M-left'.
19478 See `org-ctrl-c-ctrl-c-hook' for more information.")
19479 (defvar org-metaright-hook nil
19480 "Hook for functions attaching themselves to `M-right'.
19481 See `org-ctrl-c-ctrl-c-hook' for more information.")
19482 (defvar org-metaup-hook nil
19483 "Hook for functions attaching themselves to `M-up'.
19484 See `org-ctrl-c-ctrl-c-hook' for more information.")
19485 (defvar org-metadown-hook nil
19486 "Hook for functions attaching themselves to `M-down'.
19487 See `org-ctrl-c-ctrl-c-hook' for more information.")
19488 (defvar org-shiftmetaleft-hook nil
19489 "Hook for functions attaching themselves to `M-S-left'.
19490 See `org-ctrl-c-ctrl-c-hook' for more information.")
19491 (defvar org-shiftmetaright-hook nil
19492 "Hook for functions attaching themselves to `M-S-right'.
19493 See `org-ctrl-c-ctrl-c-hook' for more information.")
19494 (defvar org-shiftmetaup-hook nil
19495 "Hook for functions attaching themselves to `M-S-up'.
19496 See `org-ctrl-c-ctrl-c-hook' for more information.")
19497 (defvar org-shiftmetadown-hook nil
19498 "Hook for functions attaching themselves to `M-S-down'.
19499 See `org-ctrl-c-ctrl-c-hook' for more information.")
19500 (defvar org-metareturn-hook nil
19501 "Hook for functions attaching themselves to `M-RET'.
19502 See `org-ctrl-c-ctrl-c-hook' for more information.")
19503 (defvar org-shiftup-hook nil
19504 "Hook for functions attaching themselves to `S-up'.
19505 See `org-ctrl-c-ctrl-c-hook' for more information.")
19506 (defvar org-shiftup-final-hook nil
19507 "Hook for functions attaching themselves to `S-up'.
19508 This one runs after all other options except shift-select have been excluded.
19509 See `org-ctrl-c-ctrl-c-hook' for more information.")
19510 (defvar org-shiftdown-hook nil
19511 "Hook for functions attaching themselves to `S-down'.
19512 See `org-ctrl-c-ctrl-c-hook' for more information.")
19513 (defvar org-shiftdown-final-hook nil
19514 "Hook for functions attaching themselves to `S-down'.
19515 This one runs after all other options except shift-select have been excluded.
19516 See `org-ctrl-c-ctrl-c-hook' for more information.")
19517 (defvar org-shiftleft-hook nil
19518 "Hook for functions attaching themselves to `S-left'.
19519 See `org-ctrl-c-ctrl-c-hook' for more information.")
19520 (defvar org-shiftleft-final-hook nil
19521 "Hook for functions attaching themselves to `S-left'.
19522 This one runs after all other options except shift-select have been excluded.
19523 See `org-ctrl-c-ctrl-c-hook' for more information.")
19524 (defvar org-shiftright-hook nil
19525 "Hook for functions attaching themselves to `S-right'.
19526 See `org-ctrl-c-ctrl-c-hook' for more information.")
19527 (defvar org-shiftright-final-hook nil
19528 "Hook for functions attaching themselves to `S-right'.
19529 This one runs after all other options except shift-select have been excluded.
19530 See `org-ctrl-c-ctrl-c-hook' for more information.")
19532 (defun org-modifier-cursor-error ()
19533 "Throw an error, a modified cursor command was applied in wrong context."
19534 (error "This command is active in special context like tables, headlines or items"))
19536 (defun org-shiftselect-error ()
19537 "Throw an error because Shift-Cursor command was applied in wrong context."
19538 (if (and (boundp 'shift-select-mode) shift-select-mode)
19539 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19540 (error "This command works only in special context like headlines or timestamps")))
19542 (defun org-call-for-shift-select (cmd)
19543 (let ((this-command-keys-shift-translated t))
19544 (call-interactively cmd)))
19546 (defun org-shifttab (&optional arg)
19547 "Global visibility cycling or move to previous table field.
19548 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19549 on context.
19550 See the individual commands for more information."
19551 (interactive "P")
19552 (cond
19553 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19554 ((integerp arg)
19555 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19556 (message "Content view to level: %d" arg)
19557 (org-content (prefix-numeric-value arg2))
19558 (setq org-cycle-global-status 'overview)))
19559 (t (call-interactively 'org-global-cycle))))
19561 (defun org-shiftmetaleft ()
19562 "Promote subtree or delete table column.
19563 Calls `org-promote-subtree', `org-outdent-item-tree', or
19564 `org-table-delete-column', depending on context. See the
19565 individual commands for more information."
19566 (interactive)
19567 (cond
19568 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19569 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19570 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19571 ((if (not (org-region-active-p)) (org-at-item-p)
19572 (save-excursion (goto-char (region-beginning))
19573 (org-at-item-p)))
19574 (call-interactively 'org-outdent-item-tree))
19575 (t (org-modifier-cursor-error))))
19577 (defun org-shiftmetaright ()
19578 "Demote subtree or insert table column.
19579 Calls `org-demote-subtree', `org-indent-item-tree', or
19580 `org-table-insert-column', depending on context. See the
19581 individual commands for more information."
19582 (interactive)
19583 (cond
19584 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19585 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19586 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19587 ((if (not (org-region-active-p)) (org-at-item-p)
19588 (save-excursion (goto-char (region-beginning))
19589 (org-at-item-p)))
19590 (call-interactively 'org-indent-item-tree))
19591 (t (org-modifier-cursor-error))))
19593 (defun org-shiftmetaup (&optional arg)
19594 "Move subtree up or kill table row.
19595 Calls `org-move-subtree-up' or `org-table-kill-row' or
19596 `org-move-item-up' or `org-timestamp-up', depending on context.
19597 See the individual commands for more information."
19598 (interactive "P")
19599 (cond
19600 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19601 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19602 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19603 ((org-at-item-p) (call-interactively 'org-move-item-up))
19604 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19605 (call-interactively 'org-timestamp-up)))
19606 (t (call-interactively 'org-drag-line-backward))))
19608 (defun org-shiftmetadown (&optional arg)
19609 "Move subtree down or insert table row.
19610 Calls `org-move-subtree-down' or `org-table-insert-row' or
19611 `org-move-item-down' or `org-timestamp-up', depending on context.
19612 See the individual commands for more information."
19613 (interactive "P")
19614 (cond
19615 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19616 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19617 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19618 ((org-at-item-p) (call-interactively 'org-move-item-down))
19619 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19620 (call-interactively 'org-timestamp-down)))
19621 (t (call-interactively 'org-drag-line-forward))))
19623 (defsubst org-hidden-tree-error ()
19624 (error
19625 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19627 (defun org-metaleft (&optional arg)
19628 "Promote heading or move table column to left.
19629 Calls `org-do-promote' or `org-table-move-column', depending on context.
19630 With no specific context, calls the Emacs default `backward-word'.
19631 See the individual commands for more information."
19632 (interactive "P")
19633 (cond
19634 ((run-hook-with-args-until-success 'org-metaleft-hook))
19635 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19636 ((org-with-limited-levels
19637 (or (org-at-heading-p)
19638 (and (org-region-active-p)
19639 (save-excursion
19640 (goto-char (region-beginning))
19641 (org-at-heading-p)))))
19642 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19643 (call-interactively 'org-do-promote))
19644 ;; At an inline task.
19645 ((org-at-heading-p)
19646 (call-interactively 'org-inlinetask-promote))
19647 ((or (org-at-item-p)
19648 (and (org-region-active-p)
19649 (save-excursion
19650 (goto-char (region-beginning))
19651 (org-at-item-p))))
19652 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19653 (call-interactively 'org-outdent-item))
19654 (t (call-interactively 'backward-word))))
19656 (defun org-metaright (&optional arg)
19657 "Demote a subtree, a list item or move table column to right.
19658 In front of a drawer or a block keyword, indent it correctly.
19659 With no specific context, calls the Emacs default `forward-word'.
19660 See the individual commands for more information."
19661 (interactive "P")
19662 (cond
19663 ((run-hook-with-args-until-success 'org-metaright-hook))
19664 ((org-at-table-p) (call-interactively 'org-table-move-column))
19665 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19666 ((org-at-block-p) (call-interactively 'org-indent-block))
19667 ((org-with-limited-levels
19668 (or (org-at-heading-p)
19669 (and (org-region-active-p)
19670 (save-excursion
19671 (goto-char (region-beginning))
19672 (org-at-heading-p)))))
19673 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19674 (call-interactively 'org-do-demote))
19675 ;; At an inline task.
19676 ((org-at-heading-p)
19677 (call-interactively 'org-inlinetask-demote))
19678 ((or (org-at-item-p)
19679 (and (org-region-active-p)
19680 (save-excursion
19681 (goto-char (region-beginning))
19682 (org-at-item-p))))
19683 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19684 (call-interactively 'org-indent-item))
19685 (t (call-interactively 'forward-word))))
19687 (defun org-check-for-hidden (what)
19688 "Check if there are hidden headlines/items in the current visual line.
19689 WHAT can be either `headlines' or `items'. If the current line is
19690 an outline or item heading and it has a folded subtree below it,
19691 this function returns t, nil otherwise."
19692 (let ((re (cond
19693 ((eq what 'headlines) org-outline-regexp-bol)
19694 ((eq what 'items) (org-item-beginning-re))
19695 (t (error "This should not happen"))))
19696 beg end)
19697 (save-excursion
19698 (catch 'exit
19699 (unless (org-region-active-p)
19700 (setq beg (point-at-bol))
19701 (beginning-of-line 2)
19702 (while (and (not (eobp)) ;; this is like `next-line'
19703 (get-char-property (1- (point)) 'invisible))
19704 (beginning-of-line 2))
19705 (setq end (point))
19706 (goto-char beg)
19707 (goto-char (point-at-eol))
19708 (setq end (max end (point)))
19709 (while (re-search-forward re end t)
19710 (if (get-char-property (match-beginning 0) 'invisible)
19711 (throw 'exit t))))
19712 nil))))
19714 (defun org-metaup (&optional arg)
19715 "Move subtree up or move table row up.
19716 Calls `org-move-subtree-up' or `org-table-move-row' or
19717 `org-move-item-up', depending on context. See the individual commands
19718 for more information."
19719 (interactive "P")
19720 (cond
19721 ((run-hook-with-args-until-success 'org-metaup-hook))
19722 ((org-region-active-p)
19723 (let* ((a (min (region-beginning) (region-end)))
19724 (b (1- (max (region-beginning) (region-end))))
19725 (c (save-excursion (goto-char a)
19726 (move-beginning-of-line 0)))
19727 (d (save-excursion (goto-char a)
19728 (move-end-of-line 0) (point))))
19729 (transpose-regions a b c d)
19730 (goto-char c)))
19731 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19732 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19733 ((org-at-item-p) (call-interactively 'org-move-item-up))
19734 (t (org-drag-element-backward))))
19736 (defun org-metadown (&optional arg)
19737 "Move subtree down or move table row down.
19738 Calls `org-move-subtree-down' or `org-table-move-row' or
19739 `org-move-item-down', depending on context. See the individual
19740 commands for more information."
19741 (interactive "P")
19742 (cond
19743 ((run-hook-with-args-until-success 'org-metadown-hook))
19744 ((org-region-active-p)
19745 (let* ((a (min (region-beginning) (region-end)))
19746 (b (max (region-beginning) (region-end)))
19747 (c (save-excursion (goto-char b)
19748 (move-beginning-of-line 1)))
19749 (d (save-excursion (goto-char b)
19750 (move-end-of-line 1) (1+ (point)))))
19751 (transpose-regions a b c d)
19752 (goto-char d)))
19753 ((org-at-table-p) (call-interactively 'org-table-move-row))
19754 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19755 ((org-at-item-p) (call-interactively 'org-move-item-down))
19756 (t (org-drag-element-forward))))
19758 (defun org-shiftup (&optional arg)
19759 "Increase item in timestamp or increase priority of current headline.
19760 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19761 depending on context. See the individual commands for more information."
19762 (interactive "P")
19763 (cond
19764 ((run-hook-with-args-until-success 'org-shiftup-hook))
19765 ((and org-support-shift-select (org-region-active-p))
19766 (org-call-for-shift-select 'previous-line))
19767 ((org-at-timestamp-p t)
19768 (call-interactively (if org-edit-timestamp-down-means-later
19769 'org-timestamp-down 'org-timestamp-up)))
19770 ((and (not (eq org-support-shift-select 'always))
19771 org-enable-priority-commands
19772 (org-at-heading-p))
19773 (call-interactively 'org-priority-up))
19774 ((and (not org-support-shift-select) (org-at-item-p))
19775 (call-interactively 'org-previous-item))
19776 ((org-clocktable-try-shift 'up arg))
19777 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19778 (org-support-shift-select
19779 (org-call-for-shift-select 'previous-line))
19780 (t (org-shiftselect-error))))
19782 (defun org-shiftdown (&optional arg)
19783 "Decrease item in timestamp or decrease priority of current headline.
19784 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19785 depending on context. See the individual commands for more information."
19786 (interactive "P")
19787 (cond
19788 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19789 ((and org-support-shift-select (org-region-active-p))
19790 (org-call-for-shift-select 'next-line))
19791 ((org-at-timestamp-p t)
19792 (call-interactively (if org-edit-timestamp-down-means-later
19793 'org-timestamp-up 'org-timestamp-down)))
19794 ((and (not (eq org-support-shift-select 'always))
19795 org-enable-priority-commands
19796 (org-at-heading-p))
19797 (call-interactively 'org-priority-down))
19798 ((and (not org-support-shift-select) (org-at-item-p))
19799 (call-interactively 'org-next-item))
19800 ((org-clocktable-try-shift 'down arg))
19801 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19802 (org-support-shift-select
19803 (org-call-for-shift-select 'next-line))
19804 (t (org-shiftselect-error))))
19806 (defun org-shiftright (&optional arg)
19807 "Cycle the thing at point or in the current line, depending on context.
19808 Depending on context, this does one of the following:
19810 - switch a timestamp at point one day into the future
19811 - on a headline, switch to the next TODO keyword.
19812 - on an item, switch entire list to the next bullet type
19813 - on a property line, switch to the next allowed value
19814 - on a clocktable definition line, move time block into the future"
19815 (interactive "P")
19816 (cond
19817 ((run-hook-with-args-until-success 'org-shiftright-hook))
19818 ((and org-support-shift-select (org-region-active-p))
19819 (org-call-for-shift-select 'forward-char))
19820 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19821 ((and (not (eq org-support-shift-select 'always))
19822 (org-at-heading-p))
19823 (let ((org-inhibit-logging
19824 (not org-treat-S-cursor-todo-selection-as-state-change))
19825 (org-inhibit-blocking
19826 (not org-treat-S-cursor-todo-selection-as-state-change)))
19827 (org-call-with-arg 'org-todo 'right)))
19828 ((or (and org-support-shift-select
19829 (not (eq org-support-shift-select 'always))
19830 (org-at-item-bullet-p))
19831 (and (not org-support-shift-select) (org-at-item-p)))
19832 (org-call-with-arg 'org-cycle-list-bullet nil))
19833 ((and (not (eq org-support-shift-select 'always))
19834 (org-at-property-p))
19835 (call-interactively 'org-property-next-allowed-value))
19836 ((org-clocktable-try-shift 'right arg))
19837 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19838 (org-support-shift-select
19839 (org-call-for-shift-select 'forward-char))
19840 (t (org-shiftselect-error))))
19842 (defun org-shiftleft (&optional arg)
19843 "Cycle the thing at point or in the current line, depending on context.
19844 Depending on context, this does one of the following:
19846 - switch a timestamp at point one day into the past
19847 - on a headline, switch to the previous TODO keyword.
19848 - on an item, switch entire list to the previous bullet type
19849 - on a property line, switch to the previous allowed value
19850 - on a clocktable definition line, move time block into the past"
19851 (interactive "P")
19852 (cond
19853 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19854 ((and org-support-shift-select (org-region-active-p))
19855 (org-call-for-shift-select 'backward-char))
19856 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19857 ((and (not (eq org-support-shift-select 'always))
19858 (org-at-heading-p))
19859 (let ((org-inhibit-logging
19860 (not org-treat-S-cursor-todo-selection-as-state-change))
19861 (org-inhibit-blocking
19862 (not org-treat-S-cursor-todo-selection-as-state-change)))
19863 (org-call-with-arg 'org-todo 'left)))
19864 ((or (and org-support-shift-select
19865 (not (eq org-support-shift-select 'always))
19866 (org-at-item-bullet-p))
19867 (and (not org-support-shift-select) (org-at-item-p)))
19868 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19869 ((and (not (eq org-support-shift-select 'always))
19870 (org-at-property-p))
19871 (call-interactively 'org-property-previous-allowed-value))
19872 ((org-clocktable-try-shift 'left arg))
19873 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19874 (org-support-shift-select
19875 (org-call-for-shift-select 'backward-char))
19876 (t (org-shiftselect-error))))
19878 (defun org-shiftcontrolright ()
19879 "Switch to next TODO set."
19880 (interactive)
19881 (cond
19882 ((and org-support-shift-select (org-region-active-p))
19883 (org-call-for-shift-select 'forward-word))
19884 ((and (not (eq org-support-shift-select 'always))
19885 (org-at-heading-p))
19886 (org-call-with-arg 'org-todo 'nextset))
19887 (org-support-shift-select
19888 (org-call-for-shift-select 'forward-word))
19889 (t (org-shiftselect-error))))
19891 (defun org-shiftcontrolleft ()
19892 "Switch to previous TODO set."
19893 (interactive)
19894 (cond
19895 ((and org-support-shift-select (org-region-active-p))
19896 (org-call-for-shift-select 'backward-word))
19897 ((and (not (eq org-support-shift-select 'always))
19898 (org-at-heading-p))
19899 (org-call-with-arg 'org-todo 'previousset))
19900 (org-support-shift-select
19901 (org-call-for-shift-select 'backward-word))
19902 (t (org-shiftselect-error))))
19904 (defun org-shiftcontrolup (&optional n)
19905 "Change timestamps synchronously up in CLOCK log lines.
19906 Optional argument N tells to change by that many units."
19907 (interactive "P")
19908 (cond ((and (not org-support-shift-select)
19909 (org-at-clock-log-p)
19910 (org-at-timestamp-p t))
19911 (org-clock-timestamps-up n))
19912 (t (org-shiftselect-error))))
19914 (defun org-shiftcontroldown (&optional n)
19915 "Change timestamps synchronously down in CLOCK log lines.
19916 Optional argument N tells to change by that many units."
19917 (interactive "P")
19918 (cond ((and (not org-support-shift-select)
19919 (org-at-clock-log-p)
19920 (org-at-timestamp-p t))
19921 (org-clock-timestamps-down n))
19922 (t (org-shiftselect-error))))
19924 (defun org-ctrl-c-ret ()
19925 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19926 (interactive)
19927 (cond
19928 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19929 (t (call-interactively 'org-insert-heading))))
19931 (defun org-find-visible ()
19932 (let ((s (point)))
19933 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19934 (get-char-property s 'invisible)))
19936 (defun org-find-invisible ()
19937 (let ((s (point)))
19938 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19939 (not (get-char-property s 'invisible))))
19942 (defun org-copy-visible (beg end)
19943 "Copy the visible parts of the region."
19944 (interactive "r")
19945 (let (snippets s)
19946 (save-excursion
19947 (save-restriction
19948 (narrow-to-region beg end)
19949 (setq s (goto-char (point-min)))
19950 (while (not (= (point) (point-max)))
19951 (goto-char (org-find-invisible))
19952 (push (buffer-substring s (point)) snippets)
19953 (setq s (goto-char (org-find-visible))))))
19954 (kill-new (apply 'concat (nreverse snippets)))))
19956 (defun org-copy-special ()
19957 "Copy region in table or copy current subtree.
19958 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19959 See the individual commands for more information."
19960 (interactive)
19961 (call-interactively
19962 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19964 (defun org-cut-special ()
19965 "Cut region in table or cut current subtree.
19966 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19967 See the individual commands for more information."
19968 (interactive)
19969 (call-interactively
19970 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19972 (defun org-paste-special (arg)
19973 "Paste rectangular region into table, or past subtree relative to level.
19974 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19975 See the individual commands for more information."
19976 (interactive "P")
19977 (if (org-at-table-p)
19978 (org-table-paste-rectangle)
19979 (org-paste-subtree arg)))
19981 (defsubst org-in-fixed-width-region-p ()
19982 "Is point in a fixed-width region?"
19983 (save-match-data
19984 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19986 (defun org-edit-special (&optional arg)
19987 "Call a special editor for the element at point.
19988 When at a table, call the formula editor with `org-table-edit-formulas'.
19989 When in a source code block, call `org-edit-src-code'.
19990 When in a fixed-width region, call `org-edit-fixed-width-region'.
19991 When at an #+INCLUDE keyword, visit the included file.
19992 On a link, call `ffap' to visit the link at point.
19993 Otherwise, return a user error."
19994 (interactive "P")
19995 (let ((element (org-element-at-point)))
19996 (assert (not buffer-read-only) nil
19997 "Buffer is read-only: %s" (buffer-name))
19998 (case (org-element-type element)
19999 (src-block
20000 (if (not arg) (org-edit-src-code)
20001 (let* ((info (org-babel-get-src-block-info))
20002 (lang (nth 0 info))
20003 (params (nth 2 info))
20004 (session (cdr (assq :session params))))
20005 (if (not session) (org-edit-src-code)
20006 ;; At a src-block with a session and function called with
20007 ;; an ARG: switch to the buffer related to the inferior
20008 ;; process.
20009 (switch-to-buffer
20010 (funcall (intern (concat "org-babel-prep-session:" lang))
20011 session params))))))
20012 (keyword
20013 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20014 (find-file
20015 (org-remove-double-quotes
20016 (car (org-split-string (org-element-property :value element)))))
20017 (user-error "No special environment to edit here")))
20018 (table
20019 (if (eq (org-element-property :type element) 'table.el)
20020 (org-edit-src-code)
20021 (call-interactively 'org-table-edit-formulas)))
20022 ;; Only Org tables contain `table-row' type elements.
20023 (table-row (call-interactively 'org-table-edit-formulas))
20024 ((example-block export-block) (org-edit-src-code))
20025 (fixed-width (org-edit-fixed-width-region))
20026 (otherwise
20027 ;; No notable element at point. Though, we may be at a link,
20028 ;; which is an object. Thus, scan deeper.
20029 (if (eq (org-element-type (org-element-context element)) 'link)
20030 (call-interactively 'ffap)
20031 (user-error "No special environment to edit here"))))))
20033 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20034 (defun org-ctrl-c-ctrl-c (&optional arg)
20035 "Set tags in headline, or update according to changed information at point.
20037 This command does many different things, depending on context:
20039 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20040 this is what we do.
20042 - If the cursor is on a statistics cookie, update it.
20044 - If the cursor is in a headline, prompt for tags and insert them
20045 into the current line, aligned to `org-tags-column'. When called
20046 with prefix arg, realign all tags in the current buffer.
20048 - If the cursor is in one of the special #+KEYWORD lines, this
20049 triggers scanning the buffer for these lines and updating the
20050 information.
20052 - If the cursor is inside a table, realign the table. This command
20053 works even if the automatic table editor has been turned off.
20055 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20056 the entire table.
20058 - If the cursor is at a footnote reference or definition, jump to
20059 the corresponding definition or references, respectively.
20061 - If the cursor is a the beginning of a dynamic block, update it.
20063 - If the current buffer is a capture buffer, close note and file it.
20065 - If the cursor is on a <<<target>>>, update radio targets and
20066 corresponding links in this buffer.
20068 - If the cursor is on a numbered item in a plain list, renumber the
20069 ordered list.
20071 - If the cursor is on a checkbox, toggle it.
20073 - If the cursor is on a code block, evaluate it. The variable
20074 `org-confirm-babel-evaluate' can be used to control prompting
20075 before code block evaluation, by default every code block
20076 evaluation requires confirmation. Code block evaluation can be
20077 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20078 (interactive "P")
20079 (cond
20080 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20081 org-occur-highlights
20082 org-latex-fragment-image-overlays)
20083 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20084 (org-remove-occur-highlights)
20085 (org-remove-latex-fragment-image-overlays)
20086 (message "Temporary highlights/overlays removed from current buffer"))
20087 ((and (local-variable-p 'org-finish-function (current-buffer))
20088 (fboundp org-finish-function))
20089 (funcall org-finish-function))
20090 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20092 (let* ((context (org-element-context)) (type (org-element-type context)))
20093 ;; Test if point is within a blank line.
20094 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20095 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20096 (user-error "C-c C-c can do nothing useful at this location"))
20097 ;; For convenience: at the first line of a paragraph on the
20098 ;; same line as an item, apply function on that item instead.
20099 (when (eq type 'paragraph)
20100 (let ((parent (org-element-property :parent context)))
20101 (when (and (eq (org-element-type parent) 'item)
20102 (= (point-at-bol) (org-element-property :begin parent)))
20103 (setq context parent type 'item))))
20104 ;; Act according to type of element or object at point.
20105 (case type
20106 (clock (org-clock-update-time-maybe))
20107 (dynamic-block
20108 (save-excursion
20109 (goto-char (org-element-property :post-affiliated context))
20110 (org-update-dblock)))
20111 (footnote-definition
20112 (goto-char (org-element-property :post-affiliated context))
20113 (call-interactively 'org-footnote-action))
20114 (footnote-reference (call-interactively 'org-footnote-action))
20115 ((headline inlinetask)
20116 (save-excursion (goto-char (org-element-property :begin context))
20117 (call-interactively 'org-set-tags)))
20118 (item
20119 ;; At an item: a double C-u set checkbox to "[-]"
20120 ;; unconditionally, whereas a single one will toggle its
20121 ;; presence. Without an universal argument, if the item
20122 ;; has a checkbox, toggle it. Otherwise repair the list.
20123 (let* ((box (org-element-property :checkbox context))
20124 (struct (org-element-property :structure context))
20125 (old-struct (copy-tree struct))
20126 (parents (org-list-parents-alist struct))
20127 (prevs (org-list-prevs-alist struct))
20128 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20129 (org-list-set-checkbox
20130 (org-element-property :begin context) struct
20131 (cond ((equal arg '(16)) "[-]")
20132 ((and (not box) (equal arg '(4))) "[ ]")
20133 ((or (not box) (equal arg '(4))) nil)
20134 ((eq box 'on) "[ ]")
20135 (t "[X]")))
20136 ;; Mimic `org-list-write-struct' but with grabbing
20137 ;; a return value from `org-list-struct-fix-box'.
20138 (org-list-struct-fix-ind struct parents 2)
20139 (org-list-struct-fix-item-end struct)
20140 (org-list-struct-fix-bul struct prevs)
20141 (org-list-struct-fix-ind struct parents)
20142 (let ((block-item
20143 (org-list-struct-fix-box struct parents prevs orderedp)))
20144 (if (and box (equal struct old-struct))
20145 (if (equal arg '(16))
20146 (message "Checkboxes already reset")
20147 (user-error "Cannot toggle this checkbox: %s"
20148 (if (eq box 'on)
20149 "all subitems checked"
20150 "unchecked subitems")))
20151 (org-list-struct-apply-struct struct old-struct)
20152 (org-update-checkbox-count-maybe))
20153 (when block-item
20154 (message "Checkboxes were removed due to empty box at line %d"
20155 (org-current-line block-item))))))
20156 (keyword
20157 (let ((org-inhibit-startup-visibility-stuff t)
20158 (org-startup-align-all-tables nil))
20159 (when (boundp 'org-table-coordinate-overlays)
20160 (mapc 'delete-overlay org-table-coordinate-overlays)
20161 (setq org-table-coordinate-overlays nil))
20162 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20163 (message "Local setup has been refreshed"))
20164 (plain-list
20165 ;; At a plain list, with a double C-u argument, set
20166 ;; checkboxes of each item to "[-]", whereas a single one
20167 ;; will toggle their presence according to the state of the
20168 ;; first item in the list. Without an argument, repair the
20169 ;; list.
20170 (let* ((begin (org-element-property :contents-begin context))
20171 (beginm (move-marker (make-marker) begin))
20172 (struct (org-element-property :structure context))
20173 (old-struct (copy-tree struct))
20174 (first-box (save-excursion
20175 (goto-char begin)
20176 (looking-at org-list-full-item-re)
20177 (match-string-no-properties 3)))
20178 (new-box (cond ((equal arg '(16)) "[-]")
20179 ((equal arg '(4)) (unless first-box "[ ]"))
20180 ((equal first-box "[X]") "[ ]")
20181 (t "[X]"))))
20182 (cond
20183 (arg
20184 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20185 (org-list-get-all-items
20186 begin struct (org-list-prevs-alist struct))))
20187 ((and first-box (eq (point) begin))
20188 ;; For convenience, when point is at bol on the first
20189 ;; item of the list and no argument is provided, simply
20190 ;; toggle checkbox of that item, if any.
20191 (org-list-set-checkbox begin struct new-box)))
20192 (org-list-write-struct
20193 struct (org-list-parents-alist struct) old-struct)
20194 (org-update-checkbox-count-maybe)
20195 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20196 ((property-drawer node-property)
20197 (call-interactively 'org-property-action))
20198 ((radio-target target)
20199 (call-interactively 'org-update-radio-target-regexp))
20200 (statistics-cookie
20201 (call-interactively 'org-update-statistics-cookies))
20202 ((table table-cell table-row)
20203 ;; At a table, recalculate every field and align it. Also
20204 ;; send the table if necessary. If the table has
20205 ;; a `table.el' type, just give up. At a table row or
20206 ;; cell, maybe recalculate line but always align table.
20207 (if (eq (org-element-property :type context) 'table.el)
20208 (message "Use C-c ' to edit table.el tables")
20209 (let ((org-enable-table-editor t))
20210 (if (or (eq type 'table)
20211 ;; Check if point is at a TBLFM line.
20212 (and (eq type 'table-row)
20213 (= (point) (org-element-property :end context))))
20214 (save-excursion
20215 (if (org-at-TBLFM-p) (org-calc-current-TBLFM)
20216 (goto-char (org-element-property :contents-begin context))
20217 (org-call-with-arg 'org-table-recalculate (or arg t))
20218 (orgtbl-send-table 'maybe)))
20219 (org-table-maybe-eval-formula)
20220 (cond (arg (call-interactively 'org-table-recalculate))
20221 ((org-table-maybe-recalculate-line))
20222 (t (org-table-align)))))))
20223 (timestamp (org-timestamp-change 0 'day))
20224 (otherwise
20225 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20226 (user-error
20227 "C-c C-c can do nothing useful at this location")))))))))
20229 (defun org-mode-restart ()
20230 "Restart Org-mode, to scan again for special lines.
20231 Also updates the keyword regular expressions."
20232 (interactive)
20233 (org-mode)
20234 (message "Org-mode restarted"))
20236 (defun org-kill-note-or-show-branches ()
20237 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20238 (interactive)
20239 (if (not org-finish-function)
20240 (progn
20241 (hide-subtree)
20242 (call-interactively 'show-branches))
20243 (let ((org-note-abort t))
20244 (funcall org-finish-function))))
20246 (defun org-ctrl-o (n)
20247 "Insert a new row in tables, call `open-line' elsewhere."
20248 (interactive "*p")
20249 (if (org-at-table-p)
20250 (org-table-insert-row)
20251 (open-line n)))
20253 (defun org-return (&optional indent)
20254 "Goto next table row or insert a newline.
20255 Calls `org-table-next-row' or `newline', depending on context.
20256 See the individual commands for more information."
20257 (interactive)
20258 (let (org-ts-what)
20259 (cond
20260 ((or (bobp) (org-in-src-block-p))
20261 (if indent (newline-and-indent) (newline)))
20262 ((org-at-table-p)
20263 (org-table-justify-field-maybe)
20264 (call-interactively 'org-table-next-row))
20265 ;; when `newline-and-indent' is called within a list, make sure
20266 ;; text moved stays inside the item.
20267 ((and (org-in-item-p) indent)
20268 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20269 (progn
20270 (save-match-data (newline))
20271 (org-indent-line-to (length (match-string 0))))
20272 (let ((ind (org-get-indentation)))
20273 (newline)
20274 (if (org-looking-back org-list-end-re)
20275 (org-indent-line)
20276 (org-indent-line-to ind)))))
20277 ((and org-return-follows-link
20278 (org-at-timestamp-p t)
20279 (not (eq org-ts-what 'after)))
20280 (org-follow-timestamp-link))
20281 ((and org-return-follows-link
20282 (let ((tprop (get-text-property (point) 'face)))
20283 (or (eq tprop 'org-link)
20284 (and (listp tprop) (memq 'org-link tprop)))))
20285 (call-interactively 'org-open-at-point))
20286 ((and (org-at-heading-p)
20287 (looking-at
20288 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20289 (org-show-entry)
20290 (end-of-line 1)
20291 (newline))
20292 (t (if indent (newline-and-indent) (newline))))))
20294 (defun org-return-indent ()
20295 "Goto next table row or insert a newline and indent.
20296 Calls `org-table-next-row' or `newline-and-indent', depending on
20297 context. See the individual commands for more information."
20298 (interactive)
20299 (org-return t))
20301 (defun org-ctrl-c-star ()
20302 "Compute table, or change heading status of lines.
20303 Calls `org-table-recalculate' or `org-toggle-heading',
20304 depending on context."
20305 (interactive)
20306 (cond
20307 ((org-at-table-p)
20308 (call-interactively 'org-table-recalculate))
20310 ;; Convert all lines in region to list items
20311 (call-interactively 'org-toggle-heading))))
20313 (defun org-ctrl-c-minus ()
20314 "Insert separator line in table or modify bullet status of line.
20315 Also turns a plain line or a region of lines into list items.
20316 Calls `org-table-insert-hline', `org-toggle-item', or
20317 `org-cycle-list-bullet', depending on context."
20318 (interactive)
20319 (cond
20320 ((org-at-table-p)
20321 (call-interactively 'org-table-insert-hline))
20322 ((org-region-active-p)
20323 (call-interactively 'org-toggle-item))
20324 ((org-in-item-p)
20325 (call-interactively 'org-cycle-list-bullet))
20327 (call-interactively 'org-toggle-item))))
20329 (defun org-toggle-item (arg)
20330 "Convert headings or normal lines to items, items to normal lines.
20331 If there is no active region, only the current line is considered.
20333 If the first non blank line in the region is a headline, convert
20334 all headlines to items, shifting text accordingly.
20336 If it is an item, convert all items to normal lines.
20338 If it is normal text, change region into a list of items.
20339 With a prefix argument ARG, change the region in a single item."
20340 (interactive "P")
20341 (let ((shift-text
20342 (function
20343 ;; Shift text in current section to IND, from point to END.
20344 ;; The function leaves point to END line.
20345 (lambda (ind end)
20346 (let ((min-i 1000) (end (copy-marker end)))
20347 ;; First determine the minimum indentation (MIN-I) of
20348 ;; the text.
20349 (save-excursion
20350 (catch 'exit
20351 (while (< (point) end)
20352 (let ((i (org-get-indentation)))
20353 (cond
20354 ;; Skip blank lines and inline tasks.
20355 ((looking-at "^[ \t]*$"))
20356 ((looking-at org-outline-regexp-bol))
20357 ;; We can't find less than 0 indentation.
20358 ((zerop i) (throw 'exit (setq min-i 0)))
20359 ((< i min-i) (setq min-i i))))
20360 (forward-line))))
20361 ;; Then indent each line so that a line indented to
20362 ;; MIN-I becomes indented to IND. Ignore blank lines
20363 ;; and inline tasks in the process.
20364 (let ((delta (- ind min-i)))
20365 (while (< (point) end)
20366 (unless (or (looking-at "^[ \t]*$")
20367 (looking-at org-outline-regexp-bol))
20368 (org-indent-line-to (+ (org-get-indentation) delta)))
20369 (forward-line)))))))
20370 (skip-blanks
20371 (function
20372 ;; Return beginning of first non-blank line, starting from
20373 ;; line at POS.
20374 (lambda (pos)
20375 (save-excursion
20376 (goto-char pos)
20377 (skip-chars-forward " \r\t\n")
20378 (point-at-bol)))))
20379 beg end)
20380 ;; Determine boundaries of changes.
20381 (if (org-region-active-p)
20382 (setq beg (funcall skip-blanks (region-beginning))
20383 end (copy-marker (region-end)))
20384 (setq beg (funcall skip-blanks (point-at-bol))
20385 end (copy-marker (point-at-eol))))
20386 ;; Depending on the starting line, choose an action on the text
20387 ;; between BEG and END.
20388 (org-with-limited-levels
20389 (save-excursion
20390 (goto-char beg)
20391 (cond
20392 ;; Case 1. Start at an item: de-itemize. Note that it only
20393 ;; happens when a region is active: `org-ctrl-c-minus'
20394 ;; would call `org-cycle-list-bullet' otherwise.
20395 ((org-at-item-p)
20396 (while (< (point) end)
20397 (when (org-at-item-p)
20398 (skip-chars-forward " \t")
20399 (delete-region (point) (match-end 0)))
20400 (forward-line)))
20401 ;; Case 2. Start at an heading: convert to items.
20402 ((org-at-heading-p)
20403 (let* ((bul (org-list-bullet-string "-"))
20404 (bul-len (length bul))
20405 ;; Indentation of the first heading. It should be
20406 ;; relative to the indentation of its parent, if any.
20407 (start-ind (save-excursion
20408 (cond
20409 ((not org-adapt-indentation) 0)
20410 ((not (outline-previous-heading)) 0)
20411 (t (length (match-string 0))))))
20412 ;; Level of first heading. Further headings will be
20413 ;; compared to it to determine hierarchy in the list.
20414 (ref-level (org-reduced-level (org-outline-level))))
20415 (while (< (point) end)
20416 (let* ((level (org-reduced-level (org-outline-level)))
20417 (delta (max 0 (- level ref-level))))
20418 ;; If current headline is less indented than the first
20419 ;; one, set it as reference, in order to preserve
20420 ;; subtrees.
20421 (when (< level ref-level) (setq ref-level level))
20422 (replace-match bul t t)
20423 (org-indent-line-to (+ start-ind (* delta bul-len)))
20424 ;; Ensure all text down to END (or SECTION-END) belongs
20425 ;; to the newly created item.
20426 (let ((section-end (save-excursion
20427 (or (outline-next-heading) (point)))))
20428 (forward-line)
20429 (funcall shift-text
20430 (+ start-ind (* (1+ delta) bul-len))
20431 (min end section-end)))))))
20432 ;; Case 3. Normal line with ARG: make the first line of region
20433 ;; an item, and shift indentation of others lines to
20434 ;; set them as item's body.
20435 (arg (let* ((bul (org-list-bullet-string "-"))
20436 (bul-len (length bul))
20437 (ref-ind (org-get-indentation)))
20438 (skip-chars-forward " \t")
20439 (insert bul)
20440 (forward-line)
20441 (while (< (point) end)
20442 ;; Ensure that lines less indented than first one
20443 ;; still get included in item body.
20444 (funcall shift-text
20445 (+ ref-ind bul-len)
20446 (min end (save-excursion (or (outline-next-heading)
20447 (point)))))
20448 (forward-line))))
20449 ;; Case 4. Normal line without ARG: turn each non-item line
20450 ;; into an item.
20452 (while (< (point) end)
20453 (unless (or (org-at-heading-p) (org-at-item-p))
20454 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20455 (replace-match
20456 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20457 (forward-line))))))))
20459 (defun org-toggle-heading (&optional nstars)
20460 "Convert headings to normal text, or items or text to headings.
20461 If there is no active region, only convert the current line.
20463 With a \\[universal-argument] prefix, convert the whole list at
20464 point into heading.
20466 In a region:
20468 - If the first non blank line is a headline, remove the stars
20469 from all headlines in the region.
20471 - If it is a normal line, turn each and every normal line (i.e.,
20472 not an heading or an item) in the region into headings. If you
20473 want to convert only the first line of this region, use one
20474 universal prefix argument.
20476 - If it is a plain list item, turn all plain list items into headings.
20478 When converting a line into a heading, the number of stars is chosen
20479 such that the lines become children of the current entry. However,
20480 when a numeric prefix argument is given, its value determines the
20481 number of stars to add."
20482 (interactive "P")
20483 (let ((skip-blanks
20484 (function
20485 ;; Return beginning of first non-blank line, starting from
20486 ;; line at POS.
20487 (lambda (pos)
20488 (save-excursion
20489 (goto-char pos)
20490 (while (org-at-comment-p) (forward-line))
20491 (skip-chars-forward " \r\t\n")
20492 (point-at-bol)))))
20493 beg end toggled)
20494 ;; Determine boundaries of changes. If a universal prefix has
20495 ;; been given, put the list in a region. If region ends at a bol,
20496 ;; do not consider the last line to be in the region.
20498 (when (and current-prefix-arg (org-at-item-p))
20499 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20500 (org-mark-element))
20502 (if (org-region-active-p)
20503 (setq beg (funcall skip-blanks (region-beginning))
20504 end (copy-marker (save-excursion
20505 (goto-char (region-end))
20506 (if (bolp) (point) (point-at-eol)))))
20507 (setq beg (funcall skip-blanks (point-at-bol))
20508 end (copy-marker (point-at-eol))))
20509 ;; Ensure inline tasks don't count as headings.
20510 (org-with-limited-levels
20511 (save-excursion
20512 (goto-char beg)
20513 (cond
20514 ;; Case 1. Started at an heading: de-star headings.
20515 ((org-at-heading-p)
20516 (while (< (point) end)
20517 (when (org-at-heading-p t)
20518 (looking-at org-outline-regexp) (replace-match "")
20519 (setq toggled t))
20520 (forward-line)))
20521 ;; Case 2. Started at an item: change items into headlines.
20522 ;; One star will be added by `org-list-to-subtree'.
20523 ((org-at-item-p)
20524 (let* ((stars (make-string
20525 ;; subtract the star that will be added again by
20526 ;; `org-list-to-subtree'
20527 (if (numberp nstars) (1- nstars)
20528 (or (org-current-level) 0))
20529 ?*))
20530 (add-stars
20531 (cond (nstars "") ; stars from prefix only
20532 ((equal stars "") "") ; before first heading
20533 (org-odd-levels-only "*") ; inside heading, odd
20534 (t "")))) ; inside heading, oddeven
20535 (while (< (point) end)
20536 (when (org-at-item-p)
20537 ;; Pay attention to cases when region ends before list.
20538 (let* ((struct (org-list-struct))
20539 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20540 (save-restriction
20541 (narrow-to-region (point) list-end)
20542 (insert
20543 (org-list-to-subtree
20544 (org-list-parse-list t)
20545 '(:istart (concat stars add-stars (funcall get-stars depth))
20546 :icount (concat stars add-stars (funcall get-stars depth)))))))
20547 (setq toggled t))
20548 (forward-line))))
20549 ;; Case 3. Started at normal text: make every line an heading,
20550 ;; skipping headlines and items.
20551 (t (let* ((stars
20552 (make-string
20553 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20554 (add-stars
20555 (cond (nstars "") ; stars from prefix only
20556 ((equal stars "") "*") ; before first heading
20557 (org-odd-levels-only "**") ; inside heading, odd
20558 (t "*"))) ; inside heading, oddeven
20559 (rpl (concat stars add-stars " "))
20560 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20561 (while (< (point) (if (equal nstars '(4)) lend end))
20562 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20563 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20564 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20565 (forward-line)))))))
20566 (unless toggled (message "Cannot toggle heading from here"))))
20568 (defun org-meta-return (&optional arg)
20569 "Insert a new heading or wrap a region in a table.
20570 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20571 See the individual commands for more information."
20572 (interactive "P")
20573 (cond
20574 ((run-hook-with-args-until-success 'org-metareturn-hook))
20575 ((or (org-at-drawer-p) (org-at-property-p))
20576 (newline-and-indent))
20577 ((org-at-table-p)
20578 (call-interactively 'org-table-wrap-region))
20579 (t (call-interactively 'org-insert-heading))))
20581 ;;; Menu entries
20583 (defsubst org-in-subtree-not-table-p ()
20584 "Are we in a subtree and not in a table?"
20585 (and (not (org-before-first-heading-p))
20586 (not (org-at-table-p))))
20588 ;; Define the Org-mode menus
20589 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20590 '("Tbl"
20591 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20592 ["Next Field" org-cycle (org-at-table-p)]
20593 ["Previous Field" org-shifttab (org-at-table-p)]
20594 ["Next Row" org-return (org-at-table-p)]
20595 "--"
20596 ["Blank Field" org-table-blank-field (org-at-table-p)]
20597 ["Edit Field" org-table-edit-field (org-at-table-p)]
20598 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20599 "--"
20600 ("Column"
20601 ["Move Column Left" org-metaleft (org-at-table-p)]
20602 ["Move Column Right" org-metaright (org-at-table-p)]
20603 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20604 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20605 ("Row"
20606 ["Move Row Up" org-metaup (org-at-table-p)]
20607 ["Move Row Down" org-metadown (org-at-table-p)]
20608 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20609 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20610 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20611 "--"
20612 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20613 ("Rectangle"
20614 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20615 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20616 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20617 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20618 "--"
20619 ("Calculate"
20620 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20621 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20622 ["Edit Formulas" org-edit-special (org-at-table-p)]
20623 "--"
20624 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20625 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20626 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20627 "--"
20628 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20629 "--"
20630 ["Sum Column/Rectangle" org-table-sum
20631 (or (org-at-table-p) (org-region-active-p))]
20632 ["Which Column?" org-table-current-column (org-at-table-p)])
20633 ["Debug Formulas"
20634 org-table-toggle-formula-debugger
20635 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20636 ["Show Col/Row Numbers"
20637 org-table-toggle-coordinate-overlays
20638 :style toggle
20639 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20640 "--"
20641 ["Create" org-table-create (and (not (org-at-table-p))
20642 org-enable-table-editor)]
20643 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20644 ["Import from File" org-table-import (not (org-at-table-p))]
20645 ["Export to File" org-table-export (org-at-table-p)]
20646 "--"
20647 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20649 (easy-menu-define org-org-menu org-mode-map "Org menu"
20650 '("Org"
20651 ("Show/Hide"
20652 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20653 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20654 ["Sparse Tree..." org-sparse-tree t]
20655 ["Reveal Context" org-reveal t]
20656 ["Show All" show-all t]
20657 "--"
20658 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20659 "--"
20660 ["New Heading" org-insert-heading t]
20661 ("Navigate Headings"
20662 ["Up" outline-up-heading t]
20663 ["Next" outline-next-visible-heading t]
20664 ["Previous" outline-previous-visible-heading t]
20665 ["Next Same Level" outline-forward-same-level t]
20666 ["Previous Same Level" outline-backward-same-level t]
20667 "--"
20668 ["Jump" org-goto t])
20669 ("Edit Structure"
20670 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20671 "--"
20672 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20673 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20674 "--"
20675 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20676 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20677 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20678 "--"
20679 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20680 "--"
20681 ["Copy visible text" org-copy-visible t]
20682 "--"
20683 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20684 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20685 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20686 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20687 "--"
20688 ["Sort Region/Children" org-sort t]
20689 "--"
20690 ["Convert to odd levels" org-convert-to-odd-levels t]
20691 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20692 ("Editing"
20693 ["Emphasis..." org-emphasize t]
20694 ["Edit Source Example" org-edit-special t]
20695 "--"
20696 ["Footnote new/jump" org-footnote-action t]
20697 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20698 ("Archive"
20699 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20700 "--"
20701 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20702 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20703 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20705 "--"
20706 ("Hyperlinks"
20707 ["Store Link (Global)" org-store-link t]
20708 ["Find existing link to here" org-occur-link-in-agenda-files t]
20709 ["Insert Link" org-insert-link t]
20710 ["Follow Link" org-open-at-point t]
20711 "--"
20712 ["Next link" org-next-link t]
20713 ["Previous link" org-previous-link t]
20714 "--"
20715 ["Descriptive Links"
20716 org-toggle-link-display
20717 :style radio
20718 :selected org-descriptive-links
20720 ["Literal Links"
20721 org-toggle-link-display
20722 :style radio
20723 :selected (not org-descriptive-links)])
20724 "--"
20725 ("TODO Lists"
20726 ["TODO/DONE/-" org-todo t]
20727 ("Select keyword"
20728 ["Next keyword" org-shiftright (org-at-heading-p)]
20729 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20730 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20731 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20732 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20733 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20734 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20735 "--"
20736 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20737 :selected org-enforce-todo-dependencies :style toggle :active t]
20738 "Settings for tree at point"
20739 ["Do Children sequentially" org-toggle-ordered-property :style radio
20740 :selected (org-entry-get nil "ORDERED")
20741 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20742 ["Do Children parallel" org-toggle-ordered-property :style radio
20743 :selected (not (org-entry-get nil "ORDERED"))
20744 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20745 "--"
20746 ["Set Priority" org-priority t]
20747 ["Priority Up" org-shiftup t]
20748 ["Priority Down" org-shiftdown t]
20749 "--"
20750 ["Get news from all feeds" org-feed-update-all t]
20751 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20752 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20753 ("TAGS and Properties"
20754 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20755 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20756 "--"
20757 ["Set property" org-set-property (not (org-before-first-heading-p))]
20758 ["Column view of properties" org-columns t]
20759 ["Insert Column View DBlock" org-insert-columns-dblock t])
20760 ("Dates and Scheduling"
20761 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20762 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20763 ("Change Date"
20764 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20765 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20766 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20767 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20768 ["Compute Time Range" org-evaluate-time-range t]
20769 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20770 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20771 "--"
20772 ["Custom time format" org-toggle-time-stamp-overlays
20773 :style radio :selected org-display-custom-times]
20774 "--"
20775 ["Goto Calendar" org-goto-calendar t]
20776 ["Date from Calendar" org-date-from-calendar t]
20777 "--"
20778 ["Start/Restart Timer" org-timer-start t]
20779 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20780 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20781 ["Insert Timer String" org-timer t]
20782 ["Insert Timer Item" org-timer-item t])
20783 ("Logging work"
20784 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20785 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20786 ["Clock out" org-clock-out t]
20787 ["Clock cancel" org-clock-cancel t]
20788 "--"
20789 ["Mark as default task" org-clock-mark-default-task t]
20790 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20791 ["Goto running clock" org-clock-goto t]
20792 "--"
20793 ["Display times" org-clock-display t]
20794 ["Create clock table" org-clock-report t]
20795 "--"
20796 ["Record DONE time"
20797 (progn (setq org-log-done (not org-log-done))
20798 (message "Switching to %s will %s record a timestamp"
20799 (car org-done-keywords)
20800 (if org-log-done "automatically" "not")))
20801 :style toggle :selected org-log-done])
20802 "--"
20803 ["Agenda Command..." org-agenda t]
20804 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20805 ("File List for Agenda")
20806 ("Special views current file"
20807 ["TODO Tree" org-show-todo-tree t]
20808 ["Check Deadlines" org-check-deadlines t]
20809 ["Timeline" org-timeline t]
20810 ["Tags/Property tree" org-match-sparse-tree t])
20811 "--"
20812 ["Export/Publish..." org-export-dispatch t]
20813 ("LaTeX"
20814 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20815 :selected org-cdlatex-mode]
20816 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20817 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20818 ["Modify math symbol" org-cdlatex-math-modify
20819 (org-inside-LaTeX-fragment-p)]
20820 ["Insert citation" org-reftex-citation t]
20821 "--"
20822 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20823 "--"
20824 ("MobileOrg"
20825 ["Push Files and Views" org-mobile-push t]
20826 ["Get Captured and Flagged" org-mobile-pull t]
20827 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20828 "--"
20829 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20830 "--"
20831 ("Documentation"
20832 ["Show Version" org-version t]
20833 ["Info Documentation" org-info t])
20834 ("Customize"
20835 ["Browse Org Group" org-customize t]
20836 "--"
20837 ["Expand This Menu" org-create-customize-menu
20838 (fboundp 'customize-menu-create)])
20839 ["Send bug report" org-submit-bug-report t]
20840 "--"
20841 ("Refresh/Reload"
20842 ["Refresh setup current buffer" org-mode-restart t]
20843 ["Reload Org (after update)" org-reload t]
20844 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20847 (defun org-info (&optional node)
20848 "Read documentation for Org-mode in the info system.
20849 With optional NODE, go directly to that node."
20850 (interactive)
20851 (info (format "(org)%s" (or node ""))))
20853 ;;;###autoload
20854 (defun org-submit-bug-report ()
20855 "Submit a bug report on Org-mode via mail.
20857 Don't hesitate to report any problems or inaccurate documentation.
20859 If you don't have setup sending mail from (X)Emacs, please copy the
20860 output buffer into your mail program, as it gives us important
20861 information about your Org-mode version and configuration."
20862 (interactive)
20863 (require 'reporter)
20864 (org-load-modules-maybe)
20865 (org-require-autoloaded-modules)
20866 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20867 (reporter-submit-bug-report
20868 "emacs-orgmode@gnu.org"
20869 (org-version nil 'full)
20870 (let (list)
20871 (save-window-excursion
20872 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20873 (delete-other-windows)
20874 (erase-buffer)
20875 (insert "You are about to submit a bug report to the Org-mode mailing list.
20877 We would like to add your full Org-mode and Outline configuration to the
20878 bug report. This greatly simplifies the work of the maintainer and
20879 other experts on the mailing list.
20881 HOWEVER, some variables you have customized may contain private
20882 information. The names of customers, colleagues, or friends, might
20883 appear in the form of file names, tags, todo states, or search strings.
20884 If you answer yes to the prompt, you might want to check and remove
20885 such private information before sending the email.")
20886 (add-text-properties (point-min) (point-max) '(face org-warning))
20887 (when (yes-or-no-p "Include your Org-mode configuration ")
20888 (mapatoms
20889 (lambda (v)
20890 (and (boundp v)
20891 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20892 (or (and (symbol-value v)
20893 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20894 (and
20895 (get v 'custom-type) (get v 'standard-value)
20896 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20897 (push v list)))))
20898 (kill-buffer (get-buffer "*Warn about privacy*"))
20899 list))
20900 nil nil
20901 "Remember to cover the basics, that is, what you expected to happen and
20902 what in fact did happen. You don't know how to make a good report? See
20904 http://orgmode.org/manual/Feedback.html#Feedback
20906 Your bug report will be posted to the Org-mode mailing list.
20907 ------------------------------------------------------------------------")
20908 (save-excursion
20909 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20910 (replace-match "\\1Bug: \\3 [\\2]")))))
20913 (defun org-install-agenda-files-menu ()
20914 (let ((bl (buffer-list)))
20915 (save-excursion
20916 (while bl
20917 (set-buffer (pop bl))
20918 (if (derived-mode-p 'org-mode) (setq bl nil)))
20919 (when (derived-mode-p 'org-mode)
20920 (easy-menu-change
20921 '("Org") "File List for Agenda"
20922 (append
20923 (list
20924 ["Edit File List" (org-edit-agenda-file-list) t]
20925 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20926 ["Remove Current File from List" org-remove-file t]
20927 ["Cycle through agenda files" org-cycle-agenda-files t]
20928 ["Occur in all agenda files" org-occur-in-agenda-files t]
20929 "--")
20930 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20932 ;;;; Documentation
20934 (defun org-require-autoloaded-modules ()
20935 (interactive)
20936 (mapc 'require
20937 '(org-agenda org-archive org-attach org-clock org-colview org-id
20938 org-remember org-table org-timer)))
20940 ;;;###autoload
20941 (defun org-reload (&optional uncompiled)
20942 "Reload all org lisp files.
20943 With prefix arg UNCOMPILED, load the uncompiled versions."
20944 (interactive "P")
20945 (require 'loadhist)
20946 (let* ((org-dir (org-find-library-dir "org"))
20947 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20948 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20949 (remove-re (mapconcat 'identity
20950 (mapcar (lambda (f) (concat "^" f "$"))
20951 (list (if (featurep 'xemacs)
20952 "org-colview"
20953 "org-colview-xemacs")
20954 "org" "org-loaddefs" "org-version"))
20955 "\\|"))
20956 (feats (delete-dups
20957 (mapcar 'file-name-sans-extension
20958 (mapcar 'file-name-nondirectory
20959 (delq nil
20960 (mapcar 'feature-file
20961 features))))))
20962 (lfeat (append
20963 (sort
20964 (setq feats
20965 (delq nil (mapcar
20966 (lambda (f)
20967 (if (and (string-match feature-re f)
20968 (not (string-match remove-re f)))
20969 f nil))
20970 feats)))
20971 'string-lessp)
20972 (list "org-version" "org")))
20973 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20974 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20975 load-uncore load-misses)
20976 (setq load-misses
20977 (delq 't
20978 (mapcar (lambda (f)
20979 (or (org-load-noerror-mustsuffix (concat org-dir f))
20980 (and (string= org-dir contrib-dir)
20981 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20982 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20983 (add-to-list 'load-uncore f 'append)
20986 lfeat)))
20987 (if load-uncore
20988 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20989 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20990 (if load-misses
20991 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20992 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20993 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20995 ;;;###autoload
20996 (defun org-customize ()
20997 "Call the customize function with org as argument."
20998 (interactive)
20999 (org-load-modules-maybe)
21000 (org-require-autoloaded-modules)
21001 (customize-browse 'org))
21003 (defun org-create-customize-menu ()
21004 "Create a full customization menu for Org-mode, insert it into the menu."
21005 (interactive)
21006 (org-load-modules-maybe)
21007 (org-require-autoloaded-modules)
21008 (if (fboundp 'customize-menu-create)
21009 (progn
21010 (easy-menu-change
21011 '("Org") "Customize"
21012 `(["Browse Org group" org-customize t]
21013 "--"
21014 ,(customize-menu-create 'org)
21015 ["Set" Custom-set t]
21016 ["Save" Custom-save t]
21017 ["Reset to Current" Custom-reset-current t]
21018 ["Reset to Saved" Custom-reset-saved t]
21019 ["Reset to Standard Settings" Custom-reset-standard t]))
21020 (message "\"Org\"-menu now contains full customization menu"))
21021 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21023 ;;;; Miscellaneous stuff
21025 ;;; Generally useful functions
21027 (defun org-get-at-bol (property)
21028 "Get text property PROPERTY at beginning of line."
21029 (get-text-property (point-at-bol) property))
21031 (defun org-find-text-property-in-string (prop s)
21032 "Return the first non-nil value of property PROP in string S."
21033 (or (get-text-property 0 prop s)
21034 (get-text-property (or (next-single-property-change 0 prop s) 0)
21035 prop s)))
21037 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21038 "Display the given MESSAGE as a warning."
21039 (if (fboundp 'display-warning)
21040 (display-warning 'org message
21041 (if (featurep 'xemacs) 'warning :warning))
21042 (let ((buf (get-buffer-create "*Org warnings*")))
21043 (with-current-buffer buf
21044 (goto-char (point-max))
21045 (insert "Warning (Org): " message)
21046 (unless (bolp)
21047 (newline)))
21048 (display-buffer buf)
21049 (sit-for 0))))
21051 (defun org-eval (form)
21052 "Eval FORM and return result."
21053 (condition-case error
21054 (eval form)
21055 (error (format "%%![Error: %s]" error))))
21057 (defun org-in-clocktable-p ()
21058 "Check if the cursor is in a clocktable."
21059 (let ((pos (point)) start)
21060 (save-excursion
21061 (end-of-line 1)
21062 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21063 (setq start (match-beginning 0))
21064 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21065 (>= (match-end 0) pos)
21066 start))))
21068 (defun org-in-commented-line ()
21069 "Is point in a line starting with `#'?"
21070 (equal (char-after (point-at-bol)) ?#))
21072 (defun org-in-indented-comment-line ()
21073 "Is point in a line starting with `#' after some white space?"
21074 (save-excursion
21075 (save-match-data
21076 (goto-char (point-at-bol))
21077 (looking-at "[ \t]*#"))))
21079 (defun org-in-verbatim-emphasis ()
21080 (save-match-data
21081 (and (org-in-regexp org-emph-re 2)
21082 (>= (point) (match-beginning 3))
21083 (<= (point) (match-end 4))
21084 (member (match-string 3) '("=" "~")))))
21086 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21087 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21088 (if (and marker (marker-buffer marker)
21089 (buffer-live-p (marker-buffer marker)))
21090 (progn
21091 (org-pop-to-buffer-same-window (marker-buffer marker))
21092 (if (or (> marker (point-max)) (< marker (point-min)))
21093 (widen))
21094 (goto-char marker)
21095 (org-show-context 'org-goto))
21096 (if bookmark
21097 (bookmark-jump bookmark)
21098 (error "Cannot find location"))))
21100 (defun org-quote-csv-field (s)
21101 "Quote field for inclusion in CSV material."
21102 (if (string-match "[\",]" s)
21103 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21106 (defun org-force-self-insert (N)
21107 "Needed to enforce self-insert under remapping."
21108 (interactive "p")
21109 (self-insert-command N))
21111 (defun org-string-width (s)
21112 "Compute width of string, ignoring invisible characters.
21113 This ignores character with invisibility property `org-link', and also
21114 characters with property `org-cwidth', because these will become invisible
21115 upon the next fontification round."
21116 (let (b l)
21117 (when (or (eq t buffer-invisibility-spec)
21118 (assq 'org-link buffer-invisibility-spec))
21119 (while (setq b (text-property-any 0 (length s)
21120 'invisible 'org-link s))
21121 (setq s (concat (substring s 0 b)
21122 (substring s (or (next-single-property-change
21123 b 'invisible s) (length s)))))))
21124 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21125 (setq s (concat (substring s 0 b)
21126 (substring s (or (next-single-property-change
21127 b 'org-cwidth s) (length s))))))
21128 (setq l (string-width s) b -1)
21129 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21130 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21133 (defun org-shorten-string (s maxlength)
21134 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21135 If the string is shorter or has length MAXLENGTH, just return the
21136 original string. If it is longer, the functions finds a space in the
21137 string, breaks this string off at that locations and adds three dots
21138 as ellipsis. Including the ellipsis, the string will not be longer
21139 than MAXLENGTH. If finding a good breaking point in the string does
21140 not work, the string is just chopped off in the middle of a word
21141 if necessary."
21142 (if (<= (length s) maxlength)
21144 (let* ((n (max (- maxlength 4) 1))
21145 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21146 (if (string-match re s)
21147 (concat (match-string 1 s) "...")
21148 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21150 (defun org-get-indentation (&optional line)
21151 "Get the indentation of the current line, interpreting tabs.
21152 When LINE is given, assume it represents a line and compute its indentation."
21153 (if line
21154 (if (string-match "^ *" (org-remove-tabs line))
21155 (match-end 0))
21156 (save-excursion
21157 (beginning-of-line 1)
21158 (skip-chars-forward " \t")
21159 (current-column))))
21161 (defun org-get-string-indentation (s)
21162 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21163 (let ((n -1) (i 0) (w tab-width) c)
21164 (catch 'exit
21165 (while (< (setq n (1+ n)) (length s))
21166 (setq c (aref s n))
21167 (cond ((= c ?\ ) (setq i (1+ i)))
21168 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21169 (t (throw 'exit t)))))
21172 (defun org-remove-tabs (s &optional width)
21173 "Replace tabulators in S with spaces.
21174 Assumes that s is a single line, starting in column 0."
21175 (setq width (or width tab-width))
21176 (while (string-match "\t" s)
21177 (setq s (replace-match
21178 (make-string
21179 (- (* width (/ (+ (match-beginning 0) width) width))
21180 (match-beginning 0)) ?\ )
21181 t t s)))
21184 (defun org-fix-indentation (line ind)
21185 "Fix indentation in LINE.
21186 IND is a cons cell with target and minimum indentation.
21187 If the current indentation in LINE is smaller than the minimum,
21188 leave it alone. If it is larger than ind, set it to the target."
21189 (let* ((l (org-remove-tabs line))
21190 (i (org-get-indentation l))
21191 (i1 (car ind)) (i2 (cdr ind)))
21192 (if (>= i i2) (setq l (substring line i2)))
21193 (if (> i1 0)
21194 (concat (make-string i1 ?\ ) l)
21195 l)))
21197 (defun org-remove-indentation (code &optional n)
21198 "Remove the maximum common indentation from the lines in CODE.
21199 N may optionally be the number of spaces to remove."
21200 (with-temp-buffer
21201 (insert code)
21202 (org-do-remove-indentation n)
21203 (buffer-string)))
21205 (defun org-do-remove-indentation (&optional n)
21206 "Remove the maximum common indentation from the buffer."
21207 (untabify (point-min) (point-max))
21208 (let ((min 10000) re)
21209 (if n
21210 (setq min n)
21211 (goto-char (point-min))
21212 (while (re-search-forward "^ *[^ \n]" nil t)
21213 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21214 (unless (or (= min 0) (= min 10000))
21215 (setq re (format "^ \\{%d\\}" min))
21216 (goto-char (point-min))
21217 (while (re-search-forward re nil t)
21218 (replace-match "")
21219 (end-of-line 1))
21220 min)))
21222 (defun org-fill-template (template alist)
21223 "Find each %key of ALIST in TEMPLATE and replace it."
21224 (let ((case-fold-search nil)
21225 entry key value)
21226 (setq alist (sort (copy-sequence alist)
21227 (lambda (a b) (< (length (car a)) (length (car b))))))
21228 (while (setq entry (pop alist))
21229 (setq template
21230 (replace-regexp-in-string
21231 (concat "%" (regexp-quote (car entry)))
21232 (or (cdr entry) "") template t t)))
21233 template))
21235 (defun org-base-buffer (buffer)
21236 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21237 (if (not buffer)
21238 buffer
21239 (or (buffer-base-buffer buffer)
21240 buffer)))
21242 (defun org-trim (s)
21243 "Remove whitespace at beginning and end of string."
21244 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21245 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21248 (defun org-wrap (string &optional width lines)
21249 "Wrap string to either a number of lines, or a width in characters.
21250 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21251 that costs. If there is a word longer than WIDTH, the text is actually
21252 wrapped to the length of that word.
21253 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21254 many lines, whatever width that takes.
21255 The return value is a list of lines, without newlines at the end."
21256 (let* ((words (org-split-string string "[ \t\n]+"))
21257 (maxword (apply 'max (mapcar 'org-string-width words)))
21258 w ll)
21259 (cond (width
21260 (org-do-wrap words (max maxword width)))
21261 (lines
21262 (setq w maxword)
21263 (setq ll (org-do-wrap words maxword))
21264 (if (<= (length ll) lines)
21266 (setq ll words)
21267 (while (> (length ll) lines)
21268 (setq w (1+ w))
21269 (setq ll (org-do-wrap words w)))
21270 ll))
21271 (t (error "Cannot wrap this")))))
21273 (defun org-do-wrap (words width)
21274 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21275 (let (lines line)
21276 (while words
21277 (setq line (pop words))
21278 (while (and words (< (+ (length line) (length (car words))) width))
21279 (setq line (concat line " " (pop words))))
21280 (setq lines (push line lines)))
21281 (nreverse lines)))
21283 (defun org-split-string (string &optional separators)
21284 "Splits STRING into substrings at SEPARATORS.
21285 No empty strings are returned if there are matches at the beginning
21286 and end of string."
21287 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21288 (start 0)
21289 notfirst
21290 (list nil))
21291 (while (and (string-match rexp string
21292 (if (and notfirst
21293 (= start (match-beginning 0))
21294 (< start (length string)))
21295 (1+ start) start))
21296 (< (match-beginning 0) (length string)))
21297 (setq notfirst t)
21298 (or (eq (match-beginning 0) 0)
21299 (and (eq (match-beginning 0) (match-end 0))
21300 (eq (match-beginning 0) start))
21301 (setq list
21302 (cons (substring string start (match-beginning 0))
21303 list)))
21304 (setq start (match-end 0)))
21305 (or (eq start (length string))
21306 (setq list
21307 (cons (substring string start)
21308 list)))
21309 (nreverse list)))
21311 (defun org-quote-vert (s)
21312 "Replace \"|\" with \"\\vert\"."
21313 (while (string-match "|" s)
21314 (setq s (replace-match "\\vert" t t s)))
21317 (defun org-uuidgen-p (s)
21318 "Is S an ID created by UUIDGEN?"
21319 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21321 (defun org-in-src-block-p (&optional inside)
21322 "Whether point is in a code source block.
21323 When INSIDE is non-nil, don't consider we are within a src block
21324 when point is at #+BEGIN_SRC or #+END_SRC."
21325 (let ((case-fold-search t) ov)
21326 (or (and (setq ov (overlays-at (point)))
21327 (memq 'org-block-background
21328 (overlay-properties (car ov))))
21329 (and (not inside)
21330 (save-match-data
21331 (save-excursion
21332 (beginning-of-line)
21333 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21335 (defun org-context ()
21336 "Return a list of contexts of the current cursor position.
21337 If several contexts apply, all are returned.
21338 Each context entry is a list with a symbol naming the context, and
21339 two positions indicating start and end of the context. Possible
21340 contexts are:
21342 :headline anywhere in a headline
21343 :headline-stars on the leading stars in a headline
21344 :todo-keyword on a TODO keyword (including DONE) in a headline
21345 :tags on the TAGS in a headline
21346 :priority on the priority cookie in a headline
21347 :item on the first line of a plain list item
21348 :item-bullet on the bullet/number of a plain list item
21349 :checkbox on the checkbox in a plain list item
21350 :table in an org-mode table
21351 :table-special on a special filed in a table
21352 :table-table in a table.el table
21353 :clocktable in a clocktable
21354 :src-block in a source block
21355 :link on a hyperlink
21356 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21357 :target on a <<target>>
21358 :radio-target on a <<<radio-target>>>
21359 :latex-fragment on a LaTeX fragment
21360 :latex-preview on a LaTeX fragment with overlaid preview image
21362 This function expects the position to be visible because it uses font-lock
21363 faces as a help to recognize the following contexts: :table-special, :link,
21364 and :keyword."
21365 (let* ((f (get-text-property (point) 'face))
21366 (faces (if (listp f) f (list f)))
21367 (case-fold-search t)
21368 (p (point)) clist o)
21369 ;; First the large context
21370 (cond
21371 ((org-at-heading-p t)
21372 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21373 (when (progn
21374 (beginning-of-line 1)
21375 (looking-at org-todo-line-tags-regexp))
21376 (push (org-point-in-group p 1 :headline-stars) clist)
21377 (push (org-point-in-group p 2 :todo-keyword) clist)
21378 (push (org-point-in-group p 4 :tags) clist))
21379 (goto-char p)
21380 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21381 (if (looking-at "\\[#[A-Z0-9]\\]")
21382 (push (org-point-in-group p 0 :priority) clist)))
21384 ((org-at-item-p)
21385 (push (org-point-in-group p 2 :item-bullet) clist)
21386 (push (list :item (point-at-bol)
21387 (save-excursion (org-end-of-item) (point)))
21388 clist)
21389 (and (org-at-item-checkbox-p)
21390 (push (org-point-in-group p 0 :checkbox) clist)))
21392 ((org-at-table-p)
21393 (push (list :table (org-table-begin) (org-table-end)) clist)
21394 (if (memq 'org-formula faces)
21395 (push (list :table-special
21396 (previous-single-property-change p 'face)
21397 (next-single-property-change p 'face)) clist)))
21398 ((org-at-table-p 'any)
21399 (push (list :table-table) clist)))
21400 (goto-char p)
21402 (let ((case-fold-search t))
21403 ;; New the "medium" contexts: clocktables, source blocks
21404 (cond ((org-in-clocktable-p)
21405 (push (list :clocktable
21406 (and (or (looking-at "#\\+BEGIN: clocktable")
21407 (search-backward "#+BEGIN: clocktable" nil t))
21408 (match-beginning 0))
21409 (and (re-search-forward "#\\+END:?" nil t)
21410 (match-end 0))) clist))
21411 ((org-in-src-block-p)
21412 (push (list :src-block
21413 (and (or (looking-at "#\\+BEGIN_SRC")
21414 (search-backward "#+BEGIN_SRC" nil t))
21415 (match-beginning 0))
21416 (and (search-forward "#+END_SRC" nil t)
21417 (match-beginning 0))) clist))))
21418 (goto-char p)
21420 ;; Now the small context
21421 (cond
21422 ((org-at-timestamp-p)
21423 (push (org-point-in-group p 0 :timestamp) clist))
21424 ((memq 'org-link faces)
21425 (push (list :link
21426 (previous-single-property-change p 'face)
21427 (next-single-property-change p 'face)) clist))
21428 ((memq 'org-special-keyword faces)
21429 (push (list :keyword
21430 (previous-single-property-change p 'face)
21431 (next-single-property-change p 'face)) clist))
21432 ((org-at-target-p)
21433 (push (org-point-in-group p 0 :target) clist)
21434 (goto-char (1- (match-beginning 0)))
21435 (if (looking-at org-radio-target-regexp)
21436 (push (org-point-in-group p 0 :radio-target) clist))
21437 (goto-char p))
21438 ((setq o (car (delq nil
21439 (mapcar
21440 (lambda (x)
21441 (if (memq x org-latex-fragment-image-overlays) x))
21442 (overlays-at (point))))))
21443 (push (list :latex-fragment
21444 (overlay-start o) (overlay-end o)) clist)
21445 (push (list :latex-preview
21446 (overlay-start o) (overlay-end o)) clist))
21447 ((org-inside-LaTeX-fragment-p)
21448 ;; FIXME: positions wrong.
21449 (push (list :latex-fragment (point) (point)) clist)))
21451 (setq clist (nreverse (delq nil clist)))
21452 clist))
21454 ;; FIXME: Compare with at-regexp-p Do we need both?
21455 (defun org-in-regexp (re &optional nlines visually)
21456 "Check if point is inside a match of regexp.
21457 Normally only the current line is checked, but you can include NLINES extra
21458 lines both before and after point into the search.
21459 If VISUALLY is set, require that the cursor is not after the match but
21460 really on, so that the block visually is on the match."
21461 (catch 'exit
21462 (let ((pos (point))
21463 (eol (point-at-eol (+ 1 (or nlines 0))))
21464 (inc (if visually 1 0)))
21465 (save-excursion
21466 (beginning-of-line (- 1 (or nlines 0)))
21467 (while (re-search-forward re eol t)
21468 (if (and (<= (match-beginning 0) pos)
21469 (>= (+ inc (match-end 0)) pos))
21470 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21472 (defun org-at-regexp-p (regexp)
21473 "Is point inside a match of REGEXP in the current line?"
21474 (catch 'exit
21475 (save-excursion
21476 (let ((pos (point)) (end (point-at-eol)))
21477 (beginning-of-line 1)
21478 (while (re-search-forward regexp end t)
21479 (if (and (<= (match-beginning 0) pos)
21480 (>= (match-end 0) pos))
21481 (throw 'exit t)))
21482 nil))))
21484 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21485 "Non-nil when point is between matches of START-RE and END-RE.
21487 Also return a non-nil value when point is on one of the matches.
21489 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21490 buffer positions. Default values are the positions of headlines
21491 surrounding the point.
21493 The functions returns a cons cell whose car (resp. cdr) is the
21494 position before START-RE (resp. after END-RE)."
21495 (save-match-data
21496 (let ((pos (point))
21497 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21498 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21499 beg end)
21500 (save-excursion
21501 ;; Point is on a block when on START-RE or if START-RE can be
21502 ;; found before it...
21503 (and (or (org-at-regexp-p start-re)
21504 (re-search-backward start-re limit-up t))
21505 (setq beg (match-beginning 0))
21506 ;; ... and END-RE after it...
21507 (goto-char (match-end 0))
21508 (re-search-forward end-re limit-down t)
21509 (> (setq end (match-end 0)) pos)
21510 ;; ... without another START-RE in-between.
21511 (goto-char (match-beginning 0))
21512 (not (re-search-backward start-re (1+ beg) t))
21513 ;; Return value.
21514 (cons beg end))))))
21516 (defun org-in-block-p (names)
21517 "Non-nil when point belongs to a block whose name belongs to NAMES.
21519 NAMES is a list of strings containing names of blocks.
21521 Return first block name matched, or nil. Beware that in case of
21522 nested blocks, the returned name may not belong to the closest
21523 block from point."
21524 (save-match-data
21525 (catch 'exit
21526 (let ((case-fold-search t)
21527 (lim-up (save-excursion (outline-previous-heading)))
21528 (lim-down (save-excursion (outline-next-heading))))
21529 (mapc (lambda (name)
21530 (let ((n (regexp-quote name)))
21531 (when (org-between-regexps-p
21532 (concat "^[ \t]*#\\+begin_" n)
21533 (concat "^[ \t]*#\\+end_" n)
21534 lim-up lim-down)
21535 (throw 'exit n))))
21536 names))
21537 nil)))
21539 (defun org-occur-in-agenda-files (regexp &optional nlines)
21540 "Call `multi-occur' with buffers for all agenda files."
21541 (interactive "sOrg-files matching: \np")
21542 (let* ((files (org-agenda-files))
21543 (tnames (mapcar 'file-truename files))
21544 (extra org-agenda-text-search-extra-files)
21546 (when (eq (car extra) 'agenda-archives)
21547 (setq extra (cdr extra))
21548 (setq files (org-add-archive-files files)))
21549 (while (setq f (pop extra))
21550 (unless (member (file-truename f) tnames)
21551 (add-to-list 'files f 'append)
21552 (add-to-list 'tnames (file-truename f) 'append)))
21553 (multi-occur
21554 (mapcar (lambda (x)
21555 (with-current-buffer
21556 (or (get-file-buffer x) (find-file-noselect x))
21557 (widen)
21558 (current-buffer)))
21559 files)
21560 regexp)))
21562 (if (boundp 'occur-mode-find-occurrence-hook)
21563 ;; Emacs 23
21564 (add-hook 'occur-mode-find-occurrence-hook
21565 (lambda ()
21566 (when (derived-mode-p 'org-mode)
21567 (org-reveal))))
21568 ;; Emacs 22
21569 (defadvice occur-mode-goto-occurrence
21570 (after org-occur-reveal activate)
21571 (and (derived-mode-p 'org-mode) (org-reveal)))
21572 (defadvice occur-mode-goto-occurrence-other-window
21573 (after org-occur-reveal activate)
21574 (and (derived-mode-p 'org-mode) (org-reveal)))
21575 (defadvice occur-mode-display-occurrence
21576 (after org-occur-reveal activate)
21577 (when (derived-mode-p 'org-mode)
21578 (let ((pos (occur-mode-find-occurrence)))
21579 (with-current-buffer (marker-buffer pos)
21580 (save-excursion
21581 (goto-char pos)
21582 (org-reveal)))))))
21584 (defun org-occur-link-in-agenda-files ()
21585 "Create a link and search for it in the agendas.
21586 The link is not stored in `org-stored-links', it is just created
21587 for the search purpose."
21588 (interactive)
21589 (let ((link (condition-case nil
21590 (org-store-link nil)
21591 (error "Unable to create a link to here"))))
21592 (org-occur-in-agenda-files (regexp-quote link))))
21594 (defun org-reverse-string (string)
21595 "Return the reverse of STRING."
21596 (apply 'string (reverse (string-to-list string))))
21598 (defun org-uniquify (list)
21599 "Remove duplicate elements from LIST."
21600 (let (res)
21601 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21602 res))
21604 (defun org-uniquify-alist (alist)
21605 "Merge duplicate elements of an alist.
21607 For example, in this alist:
21609 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21610 => '((a 1 3) (b 2))
21612 merge (a 1) and (a 3) into (a 1 3) and return the new alist."
21613 (let (rtn)
21614 (mapc
21615 (lambda (e)
21616 (let (n)
21617 (if (not (assoc (car e) rtn))
21618 (push e rtn)
21619 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21620 (setq rtn (assq-delete-all (car e) rtn))
21621 (push n rtn))))
21622 alist)
21623 rtn))
21625 (defun org-delete-all (elts list)
21626 "Remove all elements in ELTS from LIST."
21627 (while elts
21628 (setq list (delete (pop elts) list)))
21629 list)
21631 (defun org-count (cl-item cl-seq)
21632 "Count the number of occurrences of ITEM in SEQ.
21633 Taken from `count' in cl-seq.el with all keyword arguments removed."
21634 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21635 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21636 (while (< cl-start cl-end)
21637 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21638 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21639 (setq cl-start (1+ cl-start)))
21640 cl-count))
21642 (defun org-remove-if (predicate seq)
21643 "Remove everything from SEQ that fulfills PREDICATE."
21644 (let (res e)
21645 (while seq
21646 (setq e (pop seq))
21647 (if (not (funcall predicate e)) (push e res)))
21648 (nreverse res)))
21650 (defun org-remove-if-not (predicate seq)
21651 "Remove everything from SEQ that does not fulfill PREDICATE."
21652 (let (res e)
21653 (while seq
21654 (setq e (pop seq))
21655 (if (funcall predicate e) (push e res)))
21656 (nreverse res)))
21658 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21659 "Reduce two-argument FUNCTION across SEQ.
21660 Taken from `reduce' in cl-seq.el with all keyword arguments but
21661 \":initial-value\" removed."
21662 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21663 (cadr (memq :initial-value cl-keys)))
21664 (cl-seq (pop cl-seq))
21665 (t (funcall cl-func)))))
21666 (while cl-seq
21667 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21668 cl-accum))
21670 (defun org-back-over-empty-lines ()
21671 "Move backwards over whitespace, to the beginning of the first empty line.
21672 Returns the number of empty lines passed."
21673 (let ((pos (point)))
21674 (if (cdr (assoc 'heading org-blank-before-new-entry))
21675 (skip-chars-backward " \t\n\r")
21676 (unless (eobp)
21677 (forward-line -1)))
21678 (beginning-of-line 2)
21679 (goto-char (min (point) pos))
21680 (count-lines (point) pos)))
21682 (defun org-skip-whitespace ()
21683 (skip-chars-forward " \t\n\r"))
21685 (defun org-point-in-group (point group &optional context)
21686 "Check if POINT is in match-group GROUP.
21687 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21688 match. If the match group does not exist or point is not inside it,
21689 return nil."
21690 (and (match-beginning group)
21691 (>= point (match-beginning group))
21692 (<= point (match-end group))
21693 (if context
21694 (list context (match-beginning group) (match-end group))
21695 t)))
21697 (defun org-switch-to-buffer-other-window (&rest args)
21698 "Switch to buffer in a second window on the current frame.
21699 In particular, do not allow pop-up frames.
21700 Returns the newly created buffer."
21701 (org-no-popups
21702 (apply 'switch-to-buffer-other-window args)))
21704 (defun org-combine-plists (&rest plists)
21705 "Create a single property list from all plists in PLISTS.
21706 The process starts by copying the first list, and then setting properties
21707 from the other lists. Settings in the last list are the most significant
21708 ones and overrule settings in the other lists."
21709 (let ((rtn (copy-sequence (pop plists)))
21710 p v ls)
21711 (while plists
21712 (setq ls (pop plists))
21713 (while ls
21714 (setq p (pop ls) v (pop ls))
21715 (setq rtn (plist-put rtn p v))))
21716 rtn))
21718 (defun org-replace-escapes (string table)
21719 "Replace %-escapes in STRING with values in TABLE.
21720 TABLE is an association list with keys like \"%a\" and string values.
21721 The sequences in STRING may contain normal field width and padding information,
21722 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21723 so values can contain further %-escapes if they are define later in TABLE."
21724 (let ((tbl (copy-alist table))
21725 (case-fold-search nil)
21726 (pchg 0)
21727 e re rpl)
21728 (while (setq e (pop tbl))
21729 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21730 (when (and (cdr e) (string-match re (cdr e)))
21731 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21732 (safe "SREF"))
21733 (add-text-properties 0 3 (list 'sref sref) safe)
21734 (setcdr e (replace-match safe t t (cdr e)))))
21735 (while (string-match re string)
21736 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21737 (cdr e)))
21738 (setq string (replace-match rpl t t string))))
21739 (while (setq pchg (next-property-change pchg string))
21740 (let ((sref (get-text-property pchg 'sref string)))
21741 (when (and sref (string-match "SREF" string pchg))
21742 (setq string (replace-match sref t t string)))))
21743 string))
21745 (defun org-sublist (list start end)
21746 "Return a section of LIST, from START to END.
21747 Counting starts at 1."
21748 (let (rtn (c start))
21749 (setq list (nthcdr (1- start) list))
21750 (while (and list (<= c end))
21751 (push (pop list) rtn)
21752 (setq c (1+ c)))
21753 (nreverse rtn)))
21755 (defun org-find-base-buffer-visiting (file)
21756 "Like `find-buffer-visiting' but always return the base buffer and
21757 not an indirect buffer."
21758 (let ((buf (or (get-file-buffer file)
21759 (find-buffer-visiting file))))
21760 (if buf
21761 (or (buffer-base-buffer buf) buf)
21762 nil)))
21764 (defun org-image-file-name-regexp (&optional extensions)
21765 "Return regexp matching the file names of images.
21766 If EXTENSIONS is given, only match these."
21767 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21768 (image-file-name-regexp)
21769 (let ((image-file-name-extensions
21770 (or extensions
21771 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21772 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21773 (concat "\\."
21774 (regexp-opt (nconc (mapcar 'upcase
21775 image-file-name-extensions)
21776 image-file-name-extensions)
21778 "\\'"))))
21780 (defun org-file-image-p (file &optional extensions)
21781 "Return non-nil if FILE is an image."
21782 (save-match-data
21783 (string-match (org-image-file-name-regexp extensions) file)))
21785 (defun org-get-cursor-date (&optional with-time)
21786 "Return the date at cursor in as a time.
21787 This works in the calendar and in the agenda, anywhere else it just
21788 returns the current time.
21789 If WITH-TIME is non-nil, returns the time of the event at point (in
21790 the agenda) or the current time of the day."
21791 (let (date day defd tp tm hod mod)
21792 (when with-time
21793 (setq tp (get-text-property (point) 'time))
21794 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21795 (setq hod (string-to-number (match-string 1 tp))
21796 mod (string-to-number (match-string 2 tp))))
21797 (or tp (setq hod (nth 2 (decode-time (current-time)))
21798 mod (nth 1 (decode-time (current-time))))))
21799 (cond
21800 ((eq major-mode 'calendar-mode)
21801 (setq date (calendar-cursor-to-date)
21802 defd (encode-time 0 (or mod 0) (or hod 0)
21803 (nth 1 date) (nth 0 date) (nth 2 date))))
21804 ((eq major-mode 'org-agenda-mode)
21805 (setq day (get-text-property (point) 'day))
21806 (if day
21807 (setq date (calendar-gregorian-from-absolute day)
21808 defd (encode-time 0 (or mod 0) (or hod 0)
21809 (nth 1 date) (nth 0 date) (nth 2 date))))))
21810 (or defd (current-time))))
21812 (defun org-mark-subtree (&optional up)
21813 "Mark the current subtree.
21814 This puts point at the start of the current subtree, and mark at
21815 the end. If a numeric prefix UP is given, move up into the
21816 hierarchy of headlines by UP levels before marking the subtree."
21817 (interactive "P")
21818 (org-with-limited-levels
21819 (cond ((org-at-heading-p) (beginning-of-line))
21820 ((org-before-first-heading-p) (error "Not in a subtree"))
21821 (t (outline-previous-visible-heading 1))))
21822 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21823 (if (org-called-interactively-p 'any)
21824 (call-interactively 'org-mark-element)
21825 (org-mark-element)))
21828 ;;; Indentation
21830 (defun org-indent-line ()
21831 "Indent line depending on context."
21832 (interactive)
21833 (let* ((pos (point))
21834 (itemp (org-at-item-p))
21835 (case-fold-search t)
21836 (org-drawer-regexp (or org-drawer-regexp "\000"))
21837 (inline-task-p (and (featurep 'org-inlinetask)
21838 (org-inlinetask-in-task-p)))
21839 (inline-re (and inline-task-p
21840 (org-inlinetask-outline-regexp)))
21841 column)
21842 (if (and orgstruct-is-++ (eq pos (point)))
21843 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21844 (indent-according-to-mode))
21845 (beginning-of-line 1)
21846 (cond
21847 ;; Headings
21848 ((looking-at org-outline-regexp) (setq column 0))
21849 ;; Footnote definition
21850 ((looking-at org-footnote-definition-re) (setq column 0))
21851 ;; Literal examples
21852 ((looking-at "[ \t]*:\\( \\|$\\)")
21853 (setq column (org-get-indentation))) ; do nothing
21854 ;; Lists
21855 ((ignore-errors (goto-char (org-in-item-p)))
21856 (setq column (if itemp
21857 (org-get-indentation)
21858 (org-list-item-body-column (point))))
21859 (goto-char pos))
21860 ;; Drawers
21861 ((and (looking-at "[ \t]*:END:")
21862 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21863 (save-excursion
21864 (goto-char (1- (match-beginning 1)))
21865 (setq column (current-column))))
21866 ;; Special blocks
21867 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21868 (save-excursion
21869 (re-search-backward
21870 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21871 (setq column (org-get-indentation (match-string 0))))
21872 ((and (not (looking-at "[ \t]*#\\+begin_"))
21873 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21874 (save-excursion
21875 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21876 (setq column
21877 (cond ((equal (downcase (match-string 1)) "src")
21878 ;; src blocks: let `org-edit-src-exit' handle them
21879 (org-get-indentation))
21880 ((equal (downcase (match-string 1)) "example")
21881 (max (org-get-indentation)
21882 (org-get-indentation (match-string 0))))
21884 (org-get-indentation (match-string 0))))))
21885 ;; This line has nothing special, look at the previous relevant
21886 ;; line to compute indentation
21888 (beginning-of-line 0)
21889 (while (and (not (bobp))
21890 (not (looking-at org-table-line-regexp))
21891 (not (looking-at org-drawer-regexp))
21892 ;; When point started in an inline task, do not move
21893 ;; above task starting line.
21894 (not (and inline-task-p (looking-at inline-re)))
21895 ;; Skip drawers, blocks, empty lines, verbatim,
21896 ;; comments, tables, footnotes definitions, lists,
21897 ;; inline tasks.
21898 (or (and (looking-at "[ \t]*:END:")
21899 (re-search-backward org-drawer-regexp nil t))
21900 (and (looking-at "[ \t]*#\\+end_")
21901 (re-search-backward "[ \t]*#\\+begin_"nil t))
21902 (looking-at "[ \t]*[\n:#|]")
21903 (looking-at org-footnote-definition-re)
21904 (and (not inline-task-p)
21905 (featurep 'org-inlinetask)
21906 (org-inlinetask-in-task-p)
21907 (or (org-inlinetask-goto-beginning) t))))
21908 (beginning-of-line 0))
21909 (cond
21910 ;; There was a list item above.
21911 ((save-excursion
21912 (and (ignore-errors (goto-char (org-in-item-p)))
21913 (goto-char
21914 (org-list-get-top-point (org-list-struct)))))
21915 (looking-at org-list-full-item-re)
21916 (setq column (length (match-string 0))))
21917 ;; There was an heading above.
21918 ((looking-at "\\*+[ \t]+")
21919 (if (not org-adapt-indentation)
21920 (setq column 0)
21921 (goto-char (match-end 0))
21922 (setq column (current-column))))
21923 ;; A drawer had started and is unfinished
21924 ((looking-at org-drawer-regexp)
21925 (goto-char (1- (match-beginning 1)))
21926 (setq column (current-column)))
21927 ;; Else, nothing noticeable found: get indentation and go on.
21928 (t (setq column (org-get-indentation))))))
21929 ;; Now apply indentation and move cursor accordingly
21930 (goto-char pos)
21931 (if (<= (current-column) (current-indentation))
21932 (org-indent-line-to column)
21933 (save-excursion (org-indent-line-to column)))
21934 ;; Special polishing for properties, see `org-property-format'
21935 (setq column (current-column))
21936 (beginning-of-line 1)
21937 (if (looking-at
21938 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21939 (replace-match (concat (match-string 1)
21940 (format org-property-format
21941 (match-string 2) (match-string 3)))
21942 t t))
21943 (org-move-to-column column))))
21945 (defun org-indent-drawer ()
21946 "Indent the drawer at point."
21947 (interactive)
21948 (let ((p (point))
21949 (e (and (save-excursion (re-search-forward ":END:" nil t))
21950 (match-end 0)))
21951 (folded
21952 (save-excursion
21953 (end-of-line)
21954 (when (overlays-at (point))
21955 (member 'invisible (overlay-properties
21956 (car (overlays-at (point)))))))))
21957 (when folded (org-cycle))
21958 (indent-for-tab-command)
21959 (while (and (move-beginning-of-line 2) (< (point) e))
21960 (indent-for-tab-command))
21961 (goto-char p)
21962 (when folded (org-cycle)))
21963 (message "Drawer at point indented"))
21965 (defun org-indent-block ()
21966 "Indent the block at point."
21967 (interactive)
21968 (let ((p (point))
21969 (case-fold-search t)
21970 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21971 (match-end 0)))
21972 (folded
21973 (save-excursion
21974 (end-of-line)
21975 (when (overlays-at (point))
21976 (member 'invisible (overlay-properties
21977 (car (overlays-at (point)))))))))
21978 (when folded (org-cycle))
21979 (indent-for-tab-command)
21980 (while (and (move-beginning-of-line 2) (< (point) e))
21981 (indent-for-tab-command))
21982 (goto-char p)
21983 (when folded (org-cycle)))
21984 (message "Block at point indented"))
21986 (defun org-indent-region (start end)
21987 "Indent region."
21988 (interactive "r")
21989 (save-excursion
21990 (let ((line-end (org-current-line end)))
21991 (goto-char start)
21992 (while (< (org-current-line) line-end)
21993 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21994 (t (call-interactively 'org-indent-line)))
21995 (move-beginning-of-line 2)))))
21998 ;;; Filling
22000 ;; We use our own fill-paragraph and auto-fill functions.
22002 ;; `org-fill-paragraph' relies on adaptive filling and context
22003 ;; checking. Appropriate `fill-prefix' is computed with
22004 ;; `org-adaptive-fill-function'.
22006 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22007 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22008 ;; `org-adaptive-fill-function' value. Internally,
22009 ;; `org-comment-line-break-function' breaks the line.
22011 ;; `org-setup-filling' installs filling and auto-filling related
22012 ;; variables during `org-mode' initialization.
22014 (defun org-setup-filling ()
22015 (interactive)
22016 ;; Prevent auto-fill from inserting unwanted new items.
22017 (when (boundp 'fill-nobreak-predicate)
22018 (org-set-local
22019 'fill-nobreak-predicate
22020 (org-uniquify
22021 (append fill-nobreak-predicate
22022 '(org-fill-paragraph-separate-nobreak-p
22023 org-fill-line-break-nobreak-p
22024 org-fill-paragraph-with-timestamp-nobreak-p)))))
22025 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22026 (org-set-local 'auto-fill-inhibit-regexp nil)
22027 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22028 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22029 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22031 (defvar org-element-paragraph-separate) ; org-element.el
22032 (defun org-fill-paragraph-separate-nobreak-p ()
22033 "Non-nil when a line break at point would insert a new item."
22034 (looking-at (substring org-element-paragraph-separate 1)))
22036 (defun org-fill-line-break-nobreak-p ()
22037 "Non-nil when a line break at point would create an Org line break."
22038 (save-excursion
22039 (skip-chars-backward "[ \t]")
22040 (skip-chars-backward "\\\\")
22041 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22043 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22044 "Non-nil when a line break at point would insert a new item."
22045 (and (org-at-timestamp-p t)
22046 (not (looking-at org-ts-regexp-both))))
22048 (declare-function message-in-body-p "message" ())
22049 (defvar orgtbl-line-start-regexp) ; From org-table.el
22050 (defun org-adaptive-fill-function ()
22051 "Compute a fill prefix for the current line.
22052 Return fill prefix, as a string, or nil if current line isn't
22053 meant to be filled."
22054 (let (prefix)
22055 (catch 'exit
22056 (when (derived-mode-p 'message-mode)
22057 (save-excursion
22058 (beginning-of-line)
22059 (cond ((or (not (message-in-body-p))
22060 (looking-at orgtbl-line-start-regexp))
22061 (throw 'exit nil))
22062 ((looking-at message-cite-prefix-regexp)
22063 (throw 'exit (match-string-no-properties 0)))
22064 ((looking-at org-outline-regexp)
22065 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22066 (org-with-wide-buffer
22067 (let* ((p (line-beginning-position))
22068 (element (save-excursion (beginning-of-line)
22069 (org-element-at-point)))
22070 (type (org-element-type element))
22071 (post-affiliated (org-element-property :post-affiliated element)))
22072 (unless (and post-affiliated (< p post-affiliated))
22073 (case type
22074 (comment (looking-at "[ \t]*# ?") (match-string 0))
22075 (footnote-definition "")
22076 ((item plain-list)
22077 (make-string (org-list-item-body-column
22078 (or post-affiliated
22079 (org-element-property :begin element)))
22080 ? ))
22081 (paragraph
22082 ;; Fill prefix is usually the same as the current line,
22083 ;; except if the paragraph is at the beginning of an item.
22084 (let ((parent (org-element-property :parent element)))
22085 (cond ((eq (org-element-type parent) 'item)
22086 (make-string (org-list-item-body-column
22087 (org-element-property :begin parent))
22088 ? ))
22089 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22090 (match-string 0))
22091 (t ""))))
22092 (comment-block
22093 ;; Only fill contents if P is within block boundaries.
22094 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22095 (forward-line)
22096 (point)))
22097 (cend (save-excursion
22098 (goto-char (org-element-property :end element))
22099 (skip-chars-backward " \r\t\n")
22100 (line-beginning-position))))
22101 (when (and (>= p cbeg) (< p cend))
22102 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22103 (match-string 0)
22104 "")))))))))))
22106 (declare-function message-goto-body "message" ())
22107 (defvar message-cite-prefix-regexp) ; From message.el
22108 (defun org-fill-paragraph (&optional justify)
22109 "Fill element at point, when applicable.
22111 This function only applies to comment blocks, comments, example
22112 blocks and paragraphs. Also, as a special case, re-align table
22113 when point is at one.
22115 If JUSTIFY is non-nil (interactively, with prefix argument),
22116 justify as well. If `sentence-end-double-space' is non-nil, then
22117 period followed by one space does not end a sentence, so don't
22118 break a line there. The variable `fill-column' controls the
22119 width for filling.
22121 For convenience, when point is at a plain list, an item or
22122 a footnote definition, try to fill the first paragraph within."
22123 (interactive)
22124 (if (and (derived-mode-p 'message-mode)
22125 (or (not (message-in-body-p))
22126 (save-excursion (move-beginning-of-line 1)
22127 (looking-at message-cite-prefix-regexp))))
22128 ;; First ensure filling is correct in message-mode.
22129 (let ((fill-paragraph-function
22130 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22131 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22132 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22133 (paragraph-separate
22134 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22135 (fill-paragraph nil))
22136 (with-syntax-table org-mode-transpose-word-syntax-table
22137 ;; Move to end of line in order to get the first paragraph
22138 ;; within a plain list or a footnote definition.
22139 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22140 ;; First check if point is in a blank line at the beginning of
22141 ;; the buffer. In that case, ignore filling.
22142 (case (org-element-type element)
22143 ;; Use major mode filling function is src blocks.
22144 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22145 ;; Align Org tables, leave table.el tables as-is.
22146 (table-row (org-table-align) t)
22147 (table
22148 (when (eq (org-element-property :type element) 'org)
22149 (org-table-align))
22151 (paragraph
22152 ;; Paragraphs may contain `line-break' type objects.
22153 (let ((beg (max (point-min)
22154 (org-element-property :contents-begin element)))
22155 (end (min (point-max)
22156 (org-element-property :contents-end element))))
22157 ;; Do nothing if point is at an affiliated keyword.
22158 (if (< (line-end-position) beg) t
22159 (when (derived-mode-p 'message-mode)
22160 ;; In `message-mode', do not fill following citation
22161 ;; in current paragraph nor text before message body.
22162 (let ((body-start (save-excursion (message-goto-body))))
22163 (when body-start (setq beg (max body-start beg))))
22164 (when (save-excursion
22165 (re-search-forward
22166 (concat "^" message-cite-prefix-regexp) end t))
22167 (setq end (match-beginning 0))))
22168 ;; Fill paragraph, taking line breaks into account.
22169 ;; For that, slice the paragraph using line breaks as
22170 ;; separators, and fill the parts in reverse order to
22171 ;; avoid messing with markers.
22172 (save-excursion
22173 (goto-char end)
22174 (mapc
22175 (lambda (pos)
22176 (fill-region-as-paragraph pos (point) justify)
22177 (goto-char pos))
22178 ;; Find the list of ending positions for line breaks
22179 ;; in the current paragraph. Add paragraph
22180 ;; beginning to include first slice.
22181 (nreverse
22182 (cons beg
22183 (org-element-map
22184 (org-element--parse-objects
22185 beg end nil (org-element-restriction 'paragraph))
22186 'line-break
22187 (lambda (lb) (org-element-property :end lb)))))))
22188 t)))
22189 ;; Contents of `comment-block' type elements should be
22190 ;; filled as plain text, but only if point is within block
22191 ;; markers.
22192 (comment-block
22193 (let* ((case-fold-search t)
22194 (beg (save-excursion
22195 (goto-char (org-element-property :begin element))
22196 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22197 (forward-line)
22198 (point)))
22199 (end (save-excursion
22200 (goto-char (org-element-property :end element))
22201 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22202 (line-beginning-position))))
22203 (when (and (>= (point) beg) (< (point) end))
22204 (fill-region-as-paragraph
22205 (save-excursion
22206 (end-of-line)
22207 (re-search-backward "^[ \t]*$" beg 'move)
22208 (line-beginning-position))
22209 (save-excursion
22210 (beginning-of-line)
22211 (re-search-forward "^[ \t]*$" end 'move)
22212 (line-beginning-position))
22213 justify)))
22215 ;; Fill comments.
22216 (comment (fill-comment-paragraph justify))
22217 ;; Ignore every other element.
22218 (otherwise t))))))
22220 (defun org-auto-fill-function ()
22221 "Auto-fill function."
22222 ;; Check if auto-filling is meaningful.
22223 (let ((fc (current-fill-column)))
22224 (when (and fc (> (current-column) fc))
22225 (let* ((fill-prefix (org-adaptive-fill-function))
22226 ;; Enforce empty fill prefix, if required. Otherwise, it
22227 ;; will be computed again.
22228 (adaptive-fill-mode (not (equal fill-prefix ""))))
22229 (when fill-prefix (do-auto-fill))))))
22231 (defun org-comment-line-break-function (&optional soft)
22232 "Break line at point and indent, continuing comment if within one.
22233 The inserted newline is marked hard if variable
22234 `use-hard-newlines' is true, unless optional argument SOFT is
22235 non-nil."
22236 (if soft (insert-and-inherit ?\n) (newline 1))
22237 (save-excursion (forward-char -1) (delete-horizontal-space))
22238 (delete-horizontal-space)
22239 (indent-to-left-margin)
22240 (insert-before-markers-and-inherit fill-prefix))
22243 ;;; Comments
22245 ;; Org comments syntax is quite complex. It requires the entire line
22246 ;; to be just a comment. Also, even with the right syntax at the
22247 ;; beginning of line, some some elements (i.e. verse-block or
22248 ;; example-block) don't accept comments. Usual Emacs comment commands
22249 ;; cannot cope with those requirements. Therefore, Org replaces them.
22251 ;; Org still relies on `comment-dwim', but cannot trust
22252 ;; `comment-only-p'. So, `comment-region-function' and
22253 ;; `uncomment-region-function' both point
22254 ;; to`org-comment-or-uncomment-region'. Eventually,
22255 ;; `org-insert-comment' takes care of insertion of comments at the
22256 ;; beginning of line.
22258 ;; `org-setup-comments-handling' install comments related variables
22259 ;; during `org-mode' initialization.
22261 (defun org-setup-comments-handling ()
22262 (interactive)
22263 (org-set-local 'comment-use-syntax nil)
22264 (org-set-local 'comment-start "# ")
22265 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22266 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22267 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22268 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22270 (defun org-insert-comment ()
22271 "Insert an empty comment above current line.
22272 If the line is empty, insert comment at its beginning."
22273 (beginning-of-line)
22274 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22275 (org-indent-line)
22276 (insert "# "))
22278 (defvar comment-empty-lines) ; From newcomment.el.
22279 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22280 "Comment or uncomment each non-blank line in the region.
22281 Uncomment each non-blank line between BEG and END if it only
22282 contains commented lines. Otherwise, comment them."
22283 (save-restriction
22284 ;; Restrict region
22285 (narrow-to-region (save-excursion (goto-char beg)
22286 (skip-chars-forward " \r\t\n" end)
22287 (line-beginning-position))
22288 (save-excursion (goto-char end)
22289 (skip-chars-backward " \r\t\n" beg)
22290 (line-end-position)))
22291 (let ((uncommentp
22292 ;; UNCOMMENTP is non-nil when every non blank line between
22293 ;; BEG and END is a comment.
22294 (save-excursion
22295 (goto-char (point-min))
22296 (while (and (not (eobp))
22297 (let ((element (org-element-at-point)))
22298 (and (eq (org-element-type element) 'comment)
22299 (goto-char (min (point-max)
22300 (org-element-property
22301 :end element)))))))
22302 (eobp))))
22303 (if uncommentp
22304 ;; Only blank lines and comments in region: uncomment it.
22305 (save-excursion
22306 (goto-char (point-min))
22307 (while (not (eobp))
22308 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22309 (replace-match "" nil nil nil 1))
22310 (forward-line)))
22311 ;; Comment each line in region.
22312 (let ((min-indent (point-max)))
22313 ;; First find the minimum indentation across all lines.
22314 (save-excursion
22315 (goto-char (point-min))
22316 (while (and (not (eobp)) (not (zerop min-indent)))
22317 (unless (looking-at "[ \t]*$")
22318 (setq min-indent (min min-indent (current-indentation))))
22319 (forward-line)))
22320 ;; Then loop over all lines.
22321 (save-excursion
22322 (goto-char (point-min))
22323 (while (not (eobp))
22324 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22325 ;; Don't get fooled by invisible text (e.g. link path)
22326 ;; when moving to column MIN-INDENT.
22327 (let ((buffer-invisibility-spec nil))
22328 (org-move-to-column min-indent t))
22329 (insert comment-start))
22330 (forward-line))))))))
22333 ;;; Planning
22335 ;; This section contains tools to operate on timestamp objects, as
22336 ;; returned by, e.g. `org-element-context'.
22338 (defun org-timestamp-has-time-p (timestamp)
22339 "Non-nil when TIMESTAMP has a time specified."
22340 (org-element-property :hour-start timestamp))
22342 (defun org-timestamp-format (timestamp format &optional end utc)
22343 "Format a TIMESTAMP element into a string.
22345 FORMAT is a format specifier to be passed to
22346 `format-time-string'.
22348 When optional argument END is non-nil, use end of date-range or
22349 time-range, if possible.
22351 When optional argument UTC is non-nil, time will be expressed as
22352 Universal Time."
22353 (format-time-string
22354 format
22355 (apply 'encode-time
22356 (cons 0
22357 (mapcar
22358 (lambda (prop) (or (org-element-property prop timestamp) 0))
22359 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22360 '(:minute-start :hour-start :day-start :month-start
22361 :year-start)))))
22362 utc))
22364 (defun org-timestamp-split-range (timestamp &optional end)
22365 "Extract a timestamp object from a date or time range.
22367 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22368 the end of the range. Otherwise, extract its start.
22370 Return a new timestamp object sharing the same parent as
22371 TIMESTAMP."
22372 (let ((type (org-element-property :type timestamp)))
22373 (if (memq type '(active inactive diary)) timestamp
22374 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22375 ;; Set new type.
22376 (org-element-put-property
22377 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22378 ;; Copy start properties over end properties if END is
22379 ;; non-nil. Otherwise, copy end properties over `start' ones.
22380 (let ((p-alist '((:minute-start . :minute-end)
22381 (:hour-start . :hour-end)
22382 (:day-start . :day-end)
22383 (:month-start . :month-end)
22384 (:year-start . :year-end))))
22385 (dolist (p-cell p-alist)
22386 (org-element-put-property
22387 split-ts
22388 (funcall (if end 'car 'cdr) p-cell)
22389 (org-element-property
22390 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22391 ;; Eventually refresh `:raw-value'.
22392 (org-element-put-property split-ts :raw-value nil)
22393 (org-element-put-property
22394 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22396 (defun org-timestamp-translate (timestamp &optional boundary)
22397 "Apply `org-translate-time' on a TIMESTAMP object.
22398 When optional argument BOUNDARY is non-nil, it is either the
22399 symbol `start' or `end'. In this case, only translate the
22400 starting or ending part of TIMESTAMP if it is a date or time
22401 range. Otherwise, translate both parts."
22402 (if (and (not boundary)
22403 (memq (org-element-property :type timestamp)
22404 '(active-range inactive-range)))
22405 (concat
22406 (org-translate-time
22407 (org-element-property :raw-value
22408 (org-timestamp-split-range timestamp)))
22409 "--"
22410 (org-translate-time
22411 (org-element-property :raw-value
22412 (org-timestamp-split-range timestamp t))))
22413 (org-translate-time
22414 (org-element-property
22415 :raw-value
22416 (if (not boundary) timestamp
22417 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22421 ;;; Other stuff.
22423 (defun org-toggle-fixed-width-section (arg)
22424 "Toggle the fixed-width export.
22425 If there is no active region, the QUOTE keyword at the current headline is
22426 inserted or removed. When present, it causes the text between this headline
22427 and the next to be exported as fixed-width text, and unmodified.
22428 If there is an active region, this command adds or removes a colon as the
22429 first character of this line. If the first character of a line is a colon,
22430 this line is also exported in fixed-width font."
22431 (interactive "P")
22432 (let* ((cc 0)
22433 (regionp (org-region-active-p))
22434 (beg (if regionp (region-beginning) (point)))
22435 (end (if regionp (region-end)))
22436 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22437 (case-fold-search nil)
22438 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22439 off)
22440 (if regionp
22441 (save-excursion
22442 (goto-char beg)
22443 (setq cc (current-column))
22444 (beginning-of-line 1)
22445 (setq off (looking-at re))
22446 (while (> nlines 0)
22447 (setq nlines (1- nlines))
22448 (beginning-of-line 1)
22449 (cond
22450 (arg
22451 (org-move-to-column cc t)
22452 (insert ": \n")
22453 (forward-line -1))
22454 ((and off (looking-at re))
22455 (replace-match "" t t nil 1))
22456 ((not off) (org-move-to-column cc t) (insert ": ")))
22457 (forward-line 1)))
22458 (save-excursion
22459 (org-back-to-heading)
22460 (cond
22461 ((looking-at (format org-heading-keyword-regexp-format
22462 org-quote-string))
22463 (goto-char (match-end 1))
22464 (looking-at (concat " +" org-quote-string))
22465 (replace-match "" t t)
22466 (when (eolp) (insert " ")))
22467 ((looking-at org-outline-regexp)
22468 (goto-char (match-end 0))
22469 (insert org-quote-string " ")))))))
22471 (defun org-reftex-citation ()
22472 "Use reftex-citation to insert a citation into the buffer.
22473 This looks for a line like
22475 #+BIBLIOGRAPHY: foo plain option:-d
22477 and derives from it that foo.bib is the bibliography file relevant
22478 for this document. It then installs the necessary environment for RefTeX
22479 to work in this buffer and calls `reftex-citation' to insert a citation
22480 into the buffer.
22482 Export of such citations to both LaTeX and HTML is handled by the contributed
22483 package org-exp-bibtex by Taru Karttunen."
22484 (interactive)
22485 (let ((reftex-docstruct-symbol 'rds)
22486 (reftex-cite-format "\\cite{%l}")
22487 rds bib)
22488 (save-excursion
22489 (save-restriction
22490 (widen)
22491 (let ((case-fold-search t)
22492 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22493 (if (not (save-excursion
22494 (or (re-search-forward re nil t)
22495 (re-search-backward re nil t))))
22496 (error "No bibliography defined in file")
22497 (setq bib (concat (match-string 1) ".bib")
22498 rds (list (list 'bib bib)))))))
22499 (call-interactively 'reftex-citation)))
22501 ;;;; Functions extending outline functionality
22503 (defun org-beginning-of-line (&optional arg)
22504 "Go to the beginning of the current line. If that is invisible, continue
22505 to a visible line beginning. This makes the function of C-a more intuitive.
22506 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22507 first attempt, and only move to after the tags when the cursor is already
22508 beyond the end of the headline."
22509 (interactive "P")
22510 (let ((pos (point))
22511 (special (if (consp org-special-ctrl-a/e)
22512 (car org-special-ctrl-a/e)
22513 org-special-ctrl-a/e))
22514 refpos)
22515 (if (org-bound-and-true-p visual-line-mode)
22516 (beginning-of-visual-line 1)
22517 (beginning-of-line 1))
22518 (if (and arg (fboundp 'move-beginning-of-line))
22519 (call-interactively 'move-beginning-of-line)
22520 (if (bobp)
22522 (backward-char 1)
22523 (if (org-truely-invisible-p)
22524 (while (and (not (bobp)) (org-truely-invisible-p))
22525 (backward-char 1)
22526 (beginning-of-line 1))
22527 (forward-char 1))))
22528 (when special
22529 (cond
22530 ((and (looking-at org-complex-heading-regexp)
22531 (= (char-after (match-end 1)) ?\ ))
22532 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22533 (point-at-eol)))
22534 (goto-char
22535 (if (eq special t)
22536 (cond ((> pos refpos) refpos)
22537 ((= pos (point)) refpos)
22538 (t (point)))
22539 (cond ((> pos (point)) (point))
22540 ((not (eq last-command this-command)) (point))
22541 (t refpos)))))
22542 ((org-at-item-p)
22543 ;; Being at an item and not looking at an the item means point
22544 ;; was previously moved to beginning of a visual line, which
22545 ;; doesn't contain the item. Therefore, do nothing special,
22546 ;; just stay here.
22547 (when (looking-at org-list-full-item-re)
22548 ;; Set special position at first white space character after
22549 ;; bullet, and check-box, if any.
22550 (let ((after-bullet
22551 (let ((box (match-end 3)))
22552 (if (not box) (match-end 1)
22553 (let ((after (char-after box)))
22554 (if (and after (= after ? )) (1+ box) box))))))
22555 ;; Special case: Move point to special position when
22556 ;; currently after it or at beginning of line.
22557 (if (eq special t)
22558 (when (or (> pos after-bullet) (= (point) pos))
22559 (goto-char after-bullet))
22560 ;; Reversed case: Move point to special position when
22561 ;; point was already at beginning of line and command is
22562 ;; repeated.
22563 (when (and (= (point) pos) (eq last-command this-command))
22564 (goto-char after-bullet))))))))
22565 (org-no-warnings
22566 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22568 (defun org-end-of-line (&optional arg)
22569 "Go to the end of the line.
22570 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22571 tags on the first attempt, and only move to after the tags when
22572 the cursor is already beyond the end of the headline."
22573 (interactive "P")
22574 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22575 org-special-ctrl-a/e))
22576 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22577 'end-of-visual-line)
22578 ((fboundp 'move-end-of-line) 'move-end-of-line)
22579 (t 'end-of-line))))
22580 (if (or (not special) arg) (call-interactively move-fun)
22581 (let* ((element (save-excursion (beginning-of-line)
22582 (org-element-at-point)))
22583 (type (org-element-type element)))
22584 (cond
22585 ((memq type '(headline inlinetask))
22586 (let ((pos (point)))
22587 (beginning-of-line 1)
22588 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22589 (if (eq special t)
22590 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22591 (goto-char (match-beginning 1))
22592 (goto-char (match-end 0)))
22593 (if (or (< pos (match-end 0))
22594 (not (eq this-command last-command)))
22595 (goto-char (match-end 0))
22596 (goto-char (match-beginning 1))))
22597 (call-interactively move-fun))))
22598 ((org-element-property :hiddenp element)
22599 ;; If element is hidden, `move-end-of-line' would put point
22600 ;; after it. Use `end-of-line' to stay on current line.
22601 (call-interactively 'end-of-line))
22602 (t (call-interactively move-fun)))))
22603 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22605 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22606 (define-key org-mode-map "\C-e" 'org-end-of-line)
22608 (defun org-backward-sentence (&optional arg)
22609 "Go to beginning of sentence, or beginning of table field.
22610 This will call `backward-sentence' or `org-table-beginning-of-field',
22611 depending on context."
22612 (interactive "P")
22613 (cond
22614 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22615 (t (call-interactively 'backward-sentence))))
22617 (defun org-forward-sentence (&optional arg)
22618 "Go to end of sentence, or end of table field.
22619 This will call `forward-sentence' or `org-table-end-of-field',
22620 depending on context."
22621 (interactive "P")
22622 (cond
22623 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22624 (t (call-interactively 'forward-sentence))))
22626 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22627 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22629 (defun org-kill-line (&optional arg)
22630 "Kill line, to tags or end of line."
22631 (interactive "P")
22632 (cond
22633 ((or (not org-special-ctrl-k)
22634 (bolp)
22635 (not (org-at-heading-p)))
22636 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22637 org-ctrl-k-protect-subtree)
22638 (if (or (eq org-ctrl-k-protect-subtree 'error)
22639 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22640 (error "C-k aborted - would kill hidden subtree")))
22641 (call-interactively
22642 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22643 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22644 (kill-region (point) (match-beginning 1))
22645 (org-set-tags nil t))
22646 (t (kill-region (point) (point-at-eol)))))
22648 (define-key org-mode-map "\C-k" 'org-kill-line)
22650 (defun org-yank (&optional arg)
22651 "Yank. If the kill is a subtree, treat it specially.
22652 This command will look at the current kill and check if is a single
22653 subtree, or a series of subtrees[1]. If it passes the test, and if the
22654 cursor is at the beginning of a line or after the stars of a currently
22655 empty headline, then the yank is handled specially. How exactly depends
22656 on the value of the following variables, both set by default.
22658 org-yank-folded-subtrees
22659 When set, the subtree(s) will be folded after insertion, but only
22660 if doing so would now swallow text after the yanked text.
22662 org-yank-adjusted-subtrees
22663 When set, the subtree will be promoted or demoted in order to
22664 fit into the local outline tree structure, which means that the level
22665 will be adjusted so that it becomes the smaller one of the two
22666 *visible* surrounding headings.
22668 Any prefix to this command will cause `yank' to be called directly with
22669 no special treatment. In particular, a simple \\[universal-argument] prefix \
22670 will just
22671 plainly yank the text as it is.
22673 \[1] The test checks if the first non-white line is a heading
22674 and if there are no other headings with fewer stars."
22675 (interactive "P")
22676 (org-yank-generic 'yank arg))
22678 (defun org-yank-generic (command arg)
22679 "Perform some yank-like command.
22681 This function implements the behavior described in the `org-yank'
22682 documentation. However, it has been generalized to work for any
22683 interactive command with similar behavior."
22685 ;; pretend to be command COMMAND
22686 (setq this-command command)
22688 (if arg
22689 (call-interactively command)
22691 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22692 (and (org-kill-is-subtree-p)
22693 (or (bolp)
22694 (and (looking-at "[ \t]*$")
22695 (string-match
22696 "\\`\\*+\\'"
22697 (buffer-substring (point-at-bol) (point)))))))
22698 swallowp)
22699 (cond
22700 ((and subtreep org-yank-folded-subtrees)
22701 (let ((beg (point))
22702 end)
22703 (if (and subtreep org-yank-adjusted-subtrees)
22704 (org-paste-subtree nil nil 'for-yank)
22705 (call-interactively command))
22707 (setq end (point))
22708 (goto-char beg)
22709 (when (and (bolp) subtreep
22710 (not (setq swallowp
22711 (org-yank-folding-would-swallow-text beg end))))
22712 (org-with-limited-levels
22713 (or (looking-at org-outline-regexp)
22714 (re-search-forward org-outline-regexp-bol end t))
22715 (while (and (< (point) end) (looking-at org-outline-regexp))
22716 (hide-subtree)
22717 (org-cycle-show-empty-lines 'folded)
22718 (condition-case nil
22719 (outline-forward-same-level 1)
22720 (error (goto-char end))))))
22721 (when swallowp
22722 (message
22723 "Inserted text not folded because that would swallow text"))
22725 (goto-char end)
22726 (skip-chars-forward " \t\n\r")
22727 (beginning-of-line 1)
22728 (push-mark beg 'nomsg)))
22729 ((and subtreep org-yank-adjusted-subtrees)
22730 (let ((beg (point-at-bol)))
22731 (org-paste-subtree nil nil 'for-yank)
22732 (push-mark beg 'nomsg)))
22734 (call-interactively command))))))
22736 (defun org-yank-folding-would-swallow-text (beg end)
22737 "Would hide-subtree at BEG swallow any text after END?"
22738 (let (level)
22739 (org-with-limited-levels
22740 (save-excursion
22741 (goto-char beg)
22742 (when (or (looking-at org-outline-regexp)
22743 (re-search-forward org-outline-regexp-bol end t))
22744 (setq level (org-outline-level)))
22745 (goto-char end)
22746 (skip-chars-forward " \t\r\n\v\f")
22747 (if (or (eobp)
22748 (and (bolp) (looking-at org-outline-regexp)
22749 (<= (org-outline-level) level)))
22750 nil ; Nothing would be swallowed
22751 t))))) ; something would swallow
22753 (define-key org-mode-map "\C-y" 'org-yank)
22755 (defun org-truely-invisible-p ()
22756 "Check if point is at a character currently not visible.
22757 This version does not only check the character property, but also
22758 `visible-mode'."
22759 ;; Early versions of noutline don't have `outline-invisible-p'.
22760 (if (org-bound-and-true-p visible-mode)
22762 (outline-invisible-p)))
22764 (defun org-invisible-p2 ()
22765 "Check if point is at a character currently not visible."
22766 (save-excursion
22767 (if (and (eolp) (not (bobp))) (backward-char 1))
22768 ;; Early versions of noutline don't have `outline-invisible-p'.
22769 (outline-invisible-p)))
22771 (defun org-back-to-heading (&optional invisible-ok)
22772 "Call `outline-back-to-heading', but provide a better error message."
22773 (condition-case nil
22774 (outline-back-to-heading invisible-ok)
22775 (error (error "Before first headline at position %d in buffer %s"
22776 (point) (current-buffer)))))
22778 (defun org-before-first-heading-p ()
22779 "Before first heading?"
22780 (save-excursion
22781 (end-of-line)
22782 (null (re-search-backward org-outline-regexp-bol nil t))))
22784 (defun org-at-heading-p (&optional ignored)
22785 (outline-on-heading-p t))
22786 ;; Compatibility alias with Org versions < 7.8.03
22787 (defalias 'org-on-heading-p 'org-at-heading-p)
22789 (defun org-at-comment-p nil
22790 "Is cursor in a line starting with a # character?"
22791 (save-excursion
22792 (beginning-of-line)
22793 (looking-at "^#")))
22795 (defun org-at-drawer-p nil
22796 "Is cursor at a drawer keyword?"
22797 (save-excursion
22798 (move-beginning-of-line 1)
22799 (looking-at org-drawer-regexp)))
22801 (defun org-at-block-p nil
22802 "Is cursor at a block keyword?"
22803 (save-excursion
22804 (move-beginning-of-line 1)
22805 (looking-at org-block-regexp)))
22807 (defun org-point-at-end-of-empty-headline ()
22808 "If point is at the end of an empty headline, return t, else nil.
22809 If the heading only contains a TODO keyword, it is still still considered
22810 empty."
22811 (and (looking-at "[ \t]*$")
22812 (when org-todo-line-regexp
22813 (save-excursion
22814 (beginning-of-line 1)
22815 (let ((case-fold-search nil))
22816 (looking-at org-todo-line-regexp)
22817 (string= (match-string 3) ""))))))
22819 (defun org-at-heading-or-item-p ()
22820 (or (org-at-heading-p) (org-at-item-p)))
22822 (defun org-at-target-p ()
22823 (or (org-in-regexp org-radio-target-regexp)
22824 (org-in-regexp org-target-regexp)))
22825 ;; Compatibility alias with Org versions < 7.8.03
22826 (defalias 'org-on-target-p 'org-at-target-p)
22828 (defun org-up-heading-all (arg)
22829 "Move to the heading line of which the present line is a subheading.
22830 This function considers both visible and invisible heading lines.
22831 With argument, move up ARG levels."
22832 (if (fboundp 'outline-up-heading-all)
22833 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22834 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22836 (defun org-up-heading-safe ()
22837 "Move to the heading line of which the present line is a subheading.
22838 This version will not throw an error. It will return the level of the
22839 headline found, or nil if no higher level is found.
22841 Also, this function will be a lot faster than `outline-up-heading',
22842 because it relies on stars being the outline starters. This can really
22843 make a significant difference in outlines with very many siblings."
22844 (let (start-level re)
22845 (org-back-to-heading t)
22846 (setq start-level (funcall outline-level))
22847 (if (equal start-level 1)
22849 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22850 (if (re-search-backward re nil t)
22851 (funcall outline-level)))))
22853 (defun org-first-sibling-p ()
22854 "Is this heading the first child of its parents?"
22855 (interactive)
22856 (let ((re org-outline-regexp-bol)
22857 level l)
22858 (unless (org-at-heading-p t)
22859 (error "Not at a heading"))
22860 (setq level (funcall outline-level))
22861 (save-excursion
22862 (if (not (re-search-backward re nil t))
22864 (setq l (funcall outline-level))
22865 (< l level)))))
22867 (defun org-goto-sibling (&optional previous)
22868 "Goto the next sibling, even if it is invisible.
22869 When PREVIOUS is set, go to the previous sibling instead. Returns t
22870 when a sibling was found. When none is found, return nil and don't
22871 move point."
22872 (let ((fun (if previous 're-search-backward 're-search-forward))
22873 (pos (point))
22874 (re org-outline-regexp-bol)
22875 level l)
22876 (when (condition-case nil (org-back-to-heading t) (error nil))
22877 (setq level (funcall outline-level))
22878 (catch 'exit
22879 (or previous (forward-char 1))
22880 (while (funcall fun re nil t)
22881 (setq l (funcall outline-level))
22882 (when (< l level) (goto-char pos) (throw 'exit nil))
22883 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22884 (goto-char pos)
22885 nil))))
22887 (defun org-show-siblings ()
22888 "Show all siblings of the current headline."
22889 (save-excursion
22890 (while (org-goto-sibling) (org-flag-heading nil)))
22891 (save-excursion
22892 (while (org-goto-sibling 'previous)
22893 (org-flag-heading nil))))
22895 (defun org-goto-first-child ()
22896 "Goto the first child, even if it is invisible.
22897 Return t when a child was found. Otherwise don't move point and
22898 return nil."
22899 (let (level (pos (point)) (re org-outline-regexp-bol))
22900 (when (condition-case nil (org-back-to-heading t) (error nil))
22901 (setq level (outline-level))
22902 (forward-char 1)
22903 (if (and (re-search-forward re nil t) (> (outline-level) level))
22904 (progn (goto-char (match-beginning 0)) t)
22905 (goto-char pos) nil))))
22907 (defun org-show-hidden-entry ()
22908 "Show an entry where even the heading is hidden."
22909 (save-excursion
22910 (org-show-entry)))
22912 (defun org-flag-heading (flag &optional entry)
22913 "Flag the current heading. FLAG non-nil means make invisible.
22914 When ENTRY is non-nil, show the entire entry."
22915 (save-excursion
22916 (org-back-to-heading t)
22917 ;; Check if we should show the entire entry
22918 (if entry
22919 (progn
22920 (org-show-entry)
22921 (save-excursion
22922 (and (outline-next-heading)
22923 (org-flag-heading nil))))
22924 (outline-flag-region (max (point-min) (1- (point)))
22925 (save-excursion (outline-end-of-heading) (point))
22926 flag))))
22928 (defun org-get-next-sibling ()
22929 "Move to next heading of the same level, and return point.
22930 If there is no such heading, return nil.
22931 This is like outline-next-sibling, but invisible headings are ok."
22932 (let ((level (funcall outline-level)))
22933 (outline-next-heading)
22934 (while (and (not (eobp)) (> (funcall outline-level) level))
22935 (outline-next-heading))
22936 (if (or (eobp) (< (funcall outline-level) level))
22938 (point))))
22940 (defun org-get-last-sibling ()
22941 "Move to previous heading of the same level, and return point.
22942 If there is no such heading, return nil."
22943 (let ((opoint (point))
22944 (level (funcall outline-level)))
22945 (outline-previous-heading)
22946 (when (and (/= (point) opoint) (outline-on-heading-p t))
22947 (while (and (> (funcall outline-level) level)
22948 (not (bobp)))
22949 (outline-previous-heading))
22950 (if (< (funcall outline-level) level)
22952 (point)))))
22954 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22955 "Goto to the end of a subtree."
22956 ;; This contains an exact copy of the original function, but it uses
22957 ;; `org-back-to-heading', to make it work also in invisible
22958 ;; trees. And is uses an invisible-ok argument.
22959 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22960 ;; Furthermore, when used inside Org, finding the end of a large subtree
22961 ;; with many children and grandchildren etc, this can be much faster
22962 ;; than the outline version.
22963 (org-back-to-heading invisible-ok)
22964 (let ((first t)
22965 (level (funcall outline-level)))
22966 (if (and (derived-mode-p 'org-mode) (< level 1000))
22967 ;; A true heading (not a plain list item), in Org-mode
22968 ;; This means we can easily find the end by looking
22969 ;; only for the right number of stars. Using a regexp to do
22970 ;; this is so much faster than using a Lisp loop.
22971 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22972 (forward-char 1)
22973 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22974 ;; something else, do it the slow way
22975 (while (and (not (eobp))
22976 (or first (> (funcall outline-level) level)))
22977 (setq first nil)
22978 (outline-next-heading)))
22979 (unless to-heading
22980 (if (memq (preceding-char) '(?\n ?\^M))
22981 (progn
22982 ;; Go to end of line before heading
22983 (forward-char -1)
22984 (if (memq (preceding-char) '(?\n ?\^M))
22985 ;; leave blank line before heading
22986 (forward-char -1))))))
22987 (point))
22989 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22990 "Use Org version in org-mode, for dramatic speed-up."
22991 (if (derived-mode-p 'org-mode)
22992 (progn
22993 (org-end-of-subtree nil t)
22994 (unless (eobp) (backward-char 1)))
22995 ad-do-it))
22997 (defun org-end-of-meta-data-and-drawers ()
22998 "Jump to the first text after meta data and drawers in the current entry.
22999 This will move over empty lines, lines with planning time stamps,
23000 clocking lines, and drawers."
23001 (org-back-to-heading t)
23002 (let ((end (save-excursion (outline-next-heading) (point)))
23003 (re (concat "\\(" org-drawer-regexp "\\)"
23004 "\\|" "[ \t]*" org-keyword-time-regexp)))
23005 (forward-line 1)
23006 (while (re-search-forward re end t)
23007 (if (not (match-end 1))
23008 ;; empty or planning line
23009 (forward-line 1)
23010 ;; a drawer, find the end
23011 (re-search-forward "^[ \t]*:END:" end 'move)
23012 (forward-line 1)))
23013 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23014 (point)))
23016 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23017 "Move forward to the ARG'th subheading at same level as this one.
23018 Stop at the first and last subheadings of a superior heading.
23019 Normally this only looks at visible headings, but when INVISIBLE-OK is
23020 non-nil it will also look at invisible ones."
23021 (interactive "p")
23022 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23023 (if (and arg (< arg 0))
23024 (goto-char (point-min))
23025 (outline-next-heading))
23026 (org-at-heading-p)
23027 (let ((level (- (match-end 0) (match-beginning 0) 1))
23028 (f (if (and arg (< arg 0))
23029 're-search-backward
23030 're-search-forward))
23031 (count (if arg (abs arg) 1))
23032 (result (point)))
23033 (forward-char (if (and arg (< arg 0)) -1 1))
23034 (while (and (> count 0)
23035 (funcall f org-outline-regexp-bol nil 'move))
23036 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23037 (cond ((< l level) (setq count 0))
23038 ((and (= l level)
23039 (or invisible-ok
23040 (progn
23041 (goto-char (line-beginning-position))
23042 (not (outline-invisible-p)))))
23043 (setq count (1- count))
23044 (when (eq l level)
23045 (setq result (point)))))))
23046 (goto-char result))
23047 (beginning-of-line 1)))
23049 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23050 "Move backward to the ARG'th subheading at same level as this one.
23051 Stop at the first and last subheadings of a superior heading."
23052 (interactive "p")
23053 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23055 (defun org-next-block (arg &optional backward block-regexp)
23056 "Jump to the next block.
23057 With a prefix argument ARG, jump forward ARG many source blocks.
23058 When BACKWARD is non-nil, jump to the previous block.
23059 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23060 (interactive "p")
23061 (let ((re (or block-regexp org-block-regexp))
23062 (re-search-fn (or (and backward 're-search-backward)
23063 're-search-forward)))
23064 (if (looking-at re) (forward-char 1))
23065 (condition-case nil
23066 (funcall re-search-fn re nil nil arg)
23067 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23068 (goto-char (match-beginning 0)) (org-show-context)))
23070 (defun org-previous-block (arg &optional block-regexp)
23071 "Jump to the previous block.
23072 With a prefix argument ARG, jump backward ARG many source blocks.
23073 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23074 (interactive "p")
23075 (org-next-block arg t block-regexp))
23077 (defun org-forward-element ()
23078 "Move forward by one element.
23079 Move to the next element at the same level, when possible."
23080 (interactive)
23081 (cond ((eobp) (user-error "Cannot move further down"))
23082 ((org-with-limited-levels (org-at-heading-p))
23083 (let ((origin (point)))
23084 (goto-char (org-end-of-subtree nil t))
23085 (unless (org-with-limited-levels (org-at-heading-p))
23086 (goto-char origin)
23087 (user-error "Cannot move further down"))))
23089 (let* ((elem (org-element-at-point))
23090 (end (org-element-property :end elem))
23091 (parent (org-element-property :parent elem)))
23092 (if (and parent (= (org-element-property :contents-end parent) end))
23093 (goto-char (org-element-property :end parent))
23094 (goto-char end))))))
23096 (defun org-backward-element ()
23097 "Move backward by one element.
23098 Move to the previous element at the same level, when possible."
23099 (interactive)
23100 (cond ((bobp) (user-error "Cannot move further up"))
23101 ((org-with-limited-levels (org-at-heading-p))
23102 ;; At a headline, move to the previous one, if any, or stay
23103 ;; here.
23104 (let ((origin (point)))
23105 (org-with-limited-levels (org-backward-heading-same-level 1))
23106 ;; When current headline has no sibling above, move to its
23107 ;; parent.
23108 (when (= (point) origin)
23109 (or (org-with-limited-levels (org-up-heading-safe))
23110 (progn (goto-char origin)
23111 (user-error "Cannot move further up"))))))
23113 (let* ((trail (org-element-at-point 'keep-trail))
23114 (elem (car trail))
23115 (prev-elem (nth 1 trail))
23116 (beg (org-element-property :begin elem)))
23117 (cond
23118 ;; Move to beginning of current element if point isn't
23119 ;; there already.
23120 ((/= (point) beg) (goto-char beg))
23121 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23122 ((org-before-first-heading-p) (goto-char (point-min)))
23123 (t (org-back-to-heading)))))))
23125 (defun org-up-element ()
23126 "Move to upper element."
23127 (interactive)
23128 (if (org-with-limited-levels (org-at-heading-p))
23129 (unless (org-up-heading-safe) (error "No surrounding element"))
23130 (let* ((elem (org-element-at-point))
23131 (parent (org-element-property :parent elem)))
23132 (if parent (goto-char (org-element-property :begin parent))
23133 (if (org-with-limited-levels (org-before-first-heading-p))
23134 (error "No surrounding element")
23135 (org-with-limited-levels (org-back-to-heading)))))))
23137 (defvar org-element-greater-elements)
23138 (defun org-down-element ()
23139 "Move to inner element."
23140 (interactive)
23141 (let ((element (org-element-at-point)))
23142 (cond
23143 ((memq (org-element-type element) '(plain-list table))
23144 (goto-char (org-element-property :contents-begin element))
23145 (forward-char))
23146 ((memq (org-element-type element) org-element-greater-elements)
23147 ;; If contents are hidden, first disclose them.
23148 (when (org-element-property :hiddenp element) (org-cycle))
23149 (goto-char (or (org-element-property :contents-begin element)
23150 (error "No content for this element"))))
23151 (t (error "No inner element")))))
23153 (defun org-drag-element-backward ()
23154 "Move backward element at point."
23155 (interactive)
23156 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23157 (let* ((trail (org-element-at-point 'keep-trail))
23158 (elem (car trail))
23159 (prev-elem (nth 1 trail)))
23160 ;; Error out if no previous element or previous element is
23161 ;; a parent of the current one.
23162 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23163 (error "Cannot drag element backward")
23164 (let ((pos (point)))
23165 (org-element-swap-A-B prev-elem elem)
23166 (goto-char (+ (org-element-property :begin prev-elem)
23167 (- pos (org-element-property :begin elem)))))))))
23169 (defun org-drag-element-forward ()
23170 "Move forward element at point."
23171 (interactive)
23172 (let* ((pos (point))
23173 (elem (org-element-at-point)))
23174 (when (= (point-max) (org-element-property :end elem))
23175 (error "Cannot drag element forward"))
23176 (goto-char (org-element-property :end elem))
23177 (let ((next-elem (org-element-at-point)))
23178 (when (or (org-element-nested-p elem next-elem)
23179 (and (eq (org-element-type next-elem) 'headline)
23180 (not (eq (org-element-type elem) 'headline))))
23181 (goto-char pos)
23182 (error "Cannot drag element forward"))
23183 ;; Compute new position of point: it's shifted by NEXT-ELEM
23184 ;; body's length (without final blanks) and by the length of
23185 ;; blanks between ELEM and NEXT-ELEM.
23186 (let ((size-next (- (save-excursion
23187 (goto-char (org-element-property :end next-elem))
23188 (skip-chars-backward " \r\t\n")
23189 (forward-line)
23190 ;; Small correction if buffer doesn't end
23191 ;; with a newline character.
23192 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23193 (org-element-property :begin next-elem)))
23194 (size-blank (- (org-element-property :end elem)
23195 (save-excursion
23196 (goto-char (org-element-property :end elem))
23197 (skip-chars-backward " \r\t\n")
23198 (forward-line)
23199 (point)))))
23200 (org-element-swap-A-B elem next-elem)
23201 (goto-char (+ pos size-next size-blank))))))
23203 (defun org-drag-line-forward (arg)
23204 "Drag the line at point ARG lines forward."
23205 (interactive "p")
23206 (dotimes (n (abs arg))
23207 (let ((c (current-column)))
23208 (if (< 0 arg)
23209 (progn
23210 (beginning-of-line 2)
23211 (transpose-lines 1)
23212 (beginning-of-line 0))
23213 (transpose-lines 1)
23214 (beginning-of-line -1))
23215 (org-move-to-column c))))
23217 (defun org-drag-line-backward (arg)
23218 "Drag the line at point ARG lines backward."
23219 (interactive "p")
23220 (org-drag-line-forward (- arg)))
23222 (defun org-mark-element ()
23223 "Put point at beginning of this element, mark at end.
23225 Interactively, if this command is repeated or (in Transient Mark
23226 mode) if the mark is active, it marks the next element after the
23227 ones already marked."
23228 (interactive)
23229 (let (deactivate-mark)
23230 (if (and (org-called-interactively-p 'any)
23231 (or (and (eq last-command this-command) (mark t))
23232 (and transient-mark-mode mark-active)))
23233 (set-mark
23234 (save-excursion
23235 (goto-char (mark))
23236 (goto-char (org-element-property :end (org-element-at-point)))))
23237 (let ((element (org-element-at-point)))
23238 (end-of-line)
23239 (push-mark (org-element-property :end element) t t)
23240 (goto-char (org-element-property :begin element))))))
23242 (defun org-narrow-to-element ()
23243 "Narrow buffer to current element."
23244 (interactive)
23245 (let ((elem (org-element-at-point)))
23246 (cond
23247 ((eq (car elem) 'headline)
23248 (narrow-to-region
23249 (org-element-property :begin elem)
23250 (org-element-property :end elem)))
23251 ((memq (car elem) org-element-greater-elements)
23252 (narrow-to-region
23253 (org-element-property :contents-begin elem)
23254 (org-element-property :contents-end elem)))
23256 (narrow-to-region
23257 (org-element-property :begin elem)
23258 (org-element-property :end elem))))))
23260 (defun org-transpose-element ()
23261 "Transpose current and previous elements, keeping blank lines between.
23262 Point is moved after both elements."
23263 (interactive)
23264 (org-skip-whitespace)
23265 (let ((end (org-element-property :end (org-element-at-point))))
23266 (org-drag-element-backward)
23267 (goto-char end)))
23269 (defun org-unindent-buffer ()
23270 "Un-indent the visible part of the buffer.
23271 Relative indentation (between items, inside blocks, etc.) isn't
23272 modified."
23273 (interactive)
23274 (unless (eq major-mode 'org-mode)
23275 (error "Cannot un-indent a buffer not in Org mode"))
23276 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23277 unindent-tree ; For byte-compiler.
23278 (unindent-tree
23279 (function
23280 (lambda (contents)
23281 (mapc
23282 (lambda (element)
23283 (if (memq (org-element-type element) '(headline section))
23284 (funcall unindent-tree (org-element-contents element))
23285 (save-excursion
23286 (save-restriction
23287 (narrow-to-region
23288 (org-element-property :begin element)
23289 (org-element-property :end element))
23290 (org-do-remove-indentation)))))
23291 (reverse contents))))))
23292 (funcall unindent-tree (org-element-contents parse-tree))))
23294 (defun org-show-subtree ()
23295 "Show everything after this heading at deeper levels."
23296 (interactive)
23297 (outline-flag-region
23298 (point)
23299 (save-excursion
23300 (org-end-of-subtree t t))
23301 nil))
23303 (defun org-show-entry ()
23304 "Show the body directly following this heading.
23305 Show the heading too, if it is currently invisible."
23306 (interactive)
23307 (save-excursion
23308 (condition-case nil
23309 (progn
23310 (org-back-to-heading t)
23311 (outline-flag-region
23312 (max (point-min) (1- (point)))
23313 (save-excursion
23314 (if (re-search-forward
23315 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23316 (match-beginning 1)
23317 (point-max)))
23318 nil)
23319 (org-cycle-hide-drawers 'children))
23320 (error nil))))
23322 (defun org-make-options-regexp (kwds &optional extra)
23323 "Make a regular expression for keyword lines."
23324 (concat
23325 "^#\\+\\("
23326 (mapconcat 'regexp-quote kwds "\\|")
23327 (if extra (concat "\\|" extra))
23328 "\\):[ \t]*\\(.*\\)"))
23330 ;; Make isearch reveal the necessary context
23331 (defun org-isearch-end ()
23332 "Reveal context after isearch exits."
23333 (when isearch-success ; only if search was successful
23334 (if (featurep 'xemacs)
23335 ;; Under XEmacs, the hook is run in the correct place,
23336 ;; we directly show the context.
23337 (org-show-context 'isearch)
23338 ;; In Emacs the hook runs *before* restoring the overlays.
23339 ;; So we have to use a one-time post-command-hook to do this.
23340 ;; (Emacs 22 has a special variable, see function `org-mode')
23341 (unless (and (boundp 'isearch-mode-end-hook-quit)
23342 isearch-mode-end-hook-quit)
23343 ;; Only when the isearch was not quitted.
23344 (org-add-hook 'post-command-hook 'org-isearch-post-command
23345 'append 'local)))
23346 (org-fix-ellipsis-at-bol)))
23348 (defun org-isearch-post-command ()
23349 "Remove self from hook, and show context."
23350 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23351 (org-show-context 'isearch))
23354 ;;;; Integration with and fixes for other packages
23356 ;;; Imenu support
23358 (defvar org-imenu-markers nil
23359 "All markers currently used by Imenu.")
23360 (make-variable-buffer-local 'org-imenu-markers)
23362 (defun org-imenu-new-marker (&optional pos)
23363 "Return a new marker for use by Imenu, and remember the marker."
23364 (let ((m (make-marker)))
23365 (move-marker m (or pos (point)))
23366 (push m org-imenu-markers)
23369 (defun org-imenu-get-tree ()
23370 "Produce the index for Imenu."
23371 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23372 (setq org-imenu-markers nil)
23373 (let* ((n org-imenu-depth)
23374 (re (concat "^" (org-get-limited-outline-regexp)))
23375 (subs (make-vector (1+ n) nil))
23376 (last-level 0)
23377 m level head0 head)
23378 (save-excursion
23379 (save-restriction
23380 (widen)
23381 (goto-char (point-max))
23382 (while (re-search-backward re nil t)
23383 (setq level (org-reduced-level (funcall outline-level)))
23384 (when (and (<= level n)
23385 (looking-at org-complex-heading-regexp)
23386 (setq head0 (org-match-string-no-properties 4)))
23387 (setq head (org-link-display-format head0)
23388 m (org-imenu-new-marker))
23389 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23390 (if (>= level last-level)
23391 (push (cons head m) (aref subs level))
23392 (push (cons head (aref subs (1+ level))) (aref subs level))
23393 (loop for i from (1+ level) to n do (aset subs i nil)))
23394 (setq last-level level)))))
23395 (aref subs 1)))
23397 (eval-after-load "imenu"
23398 '(progn
23399 (add-hook 'imenu-after-jump-hook
23400 (lambda ()
23401 (if (derived-mode-p 'org-mode)
23402 (org-show-context 'org-goto))))))
23404 (defun org-link-display-format (link)
23405 "Replace a link with its the description.
23406 If there is no description, use the link target."
23407 (save-match-data
23408 (if (string-match org-bracket-link-analytic-regexp link)
23409 (replace-match (if (match-end 5)
23410 (match-string 5 link)
23411 (concat (match-string 1 link)
23412 (match-string 3 link)))
23413 nil t link)
23414 link)))
23416 (defun org-toggle-link-display ()
23417 "Toggle the literal or descriptive display of links."
23418 (interactive)
23419 (if org-descriptive-links
23420 (progn (org-remove-from-invisibility-spec '(org-link))
23421 (org-restart-font-lock)
23422 (setq org-descriptive-links nil))
23423 (progn (add-to-invisibility-spec '(org-link))
23424 (org-restart-font-lock)
23425 (setq org-descriptive-links t))))
23427 ;; Speedbar support
23429 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23430 "Overlay marking the agenda restriction line in speedbar.")
23431 (overlay-put org-speedbar-restriction-lock-overlay
23432 'face 'org-agenda-restriction-lock)
23433 (overlay-put org-speedbar-restriction-lock-overlay
23434 'help-echo "Agendas are currently limited to this item.")
23435 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23437 (defun org-speedbar-set-agenda-restriction ()
23438 "Restrict future agenda commands to the location at point in speedbar.
23439 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23440 (interactive)
23441 (require 'org-agenda)
23442 (let (p m tp np dir txt)
23443 (cond
23444 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23445 'org-imenu t))
23446 (setq m (get-text-property p 'org-imenu-marker))
23447 (with-current-buffer (marker-buffer m)
23448 (goto-char m)
23449 (org-agenda-set-restriction-lock 'subtree)))
23450 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23451 'speedbar-function 'speedbar-find-file))
23452 (setq tp (previous-single-property-change
23453 (1+ p) 'speedbar-function)
23454 np (next-single-property-change
23455 tp 'speedbar-function)
23456 dir (speedbar-line-directory)
23457 txt (buffer-substring-no-properties (or tp (point-min))
23458 (or np (point-max))))
23459 (with-current-buffer (find-file-noselect
23460 (let ((default-directory dir))
23461 (expand-file-name txt)))
23462 (unless (derived-mode-p 'org-mode)
23463 (error "Cannot restrict to non-Org-mode file"))
23464 (org-agenda-set-restriction-lock 'file)))
23465 (t (error "Don't know how to restrict Org-mode's agenda")))
23466 (move-overlay org-speedbar-restriction-lock-overlay
23467 (point-at-bol) (point-at-eol))
23468 (setq current-prefix-arg nil)
23469 (org-agenda-maybe-redo)))
23471 (eval-after-load "speedbar"
23472 '(progn
23473 (speedbar-add-supported-extension ".org")
23474 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23475 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23476 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23477 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23478 (add-hook 'speedbar-visiting-tag-hook
23479 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23481 ;;; Fixes and Hacks for problems with other packages
23483 ;; Make flyspell not check words in links, to not mess up our keymap
23484 (defvar org-element-affiliated-keywords) ; From org-element.el
23485 (defvar org-element-block-name-alist) ; From org-element.el
23486 (defun org-mode-flyspell-verify ()
23487 "Don't let flyspell put overlays at active buttons, or on
23488 {todo,all-time,additional-option-like}-keywords."
23489 (require 'org-element) ; For `org-element-affiliated-keywords'
23490 (let ((pos (max (1- (point)) (point-min)))
23491 (word (thing-at-point 'word)))
23492 (and (not (get-text-property pos 'keymap))
23493 (not (get-text-property pos 'org-no-flyspell))
23494 (not (member word org-todo-keywords-1))
23495 (not (member word org-all-time-keywords))
23496 (not (member word org-options-keywords))
23497 (not (member word (mapcar 'car org-startup-options)))
23498 (not (member-ignore-case word org-element-affiliated-keywords))
23499 (not (member-ignore-case word (org-get-export-keywords)))
23500 (not (member-ignore-case
23501 word (mapcar 'car org-element-block-name-alist)))
23502 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23504 (defun org-remove-flyspell-overlays-in (beg end)
23505 "Remove flyspell overlays in region."
23506 (and (org-bound-and-true-p flyspell-mode)
23507 (fboundp 'flyspell-delete-region-overlays)
23508 (flyspell-delete-region-overlays beg end))
23509 (add-text-properties beg end '(org-no-flyspell t)))
23511 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23512 (eval-after-load "bookmark"
23513 '(if (boundp 'bookmark-after-jump-hook)
23514 ;; We can use the hook
23515 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23516 ;; Hook not available, use advice
23517 (defadvice bookmark-jump (after org-make-visible activate)
23518 "Make the position visible."
23519 (org-bookmark-jump-unhide))))
23521 ;; Make sure saveplace shows the location if it was hidden
23522 (eval-after-load "saveplace"
23523 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23524 "Make the position visible."
23525 (org-bookmark-jump-unhide)))
23527 ;; Make sure ecb shows the location if it was hidden
23528 (eval-after-load "ecb"
23529 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23530 "Make hierarchy visible when jumping into location from ECB tree buffer."
23531 (if (derived-mode-p 'org-mode)
23532 (org-show-context))))
23534 (defun org-bookmark-jump-unhide ()
23535 "Unhide the current position, to show the bookmark location."
23536 (and (derived-mode-p 'org-mode)
23537 (or (outline-invisible-p)
23538 (save-excursion (goto-char (max (point-min) (1- (point))))
23539 (outline-invisible-p)))
23540 (org-show-context 'bookmark-jump)))
23542 ;; Make session.el ignore our circular variable
23543 (eval-after-load "session"
23544 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23546 ;;;; Finish up
23548 (provide 'org)
23550 (run-hooks 'org-load-hook)
23552 ;;; org.el ends here