Merge branch 'maint'
[org-mode/org-tableheadings.git] / lisp / org.el
blob239982362dda871344ded487c691c8be5e5b6471
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: Carsten Dominik <carsten at orgmode 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/>.
26 ;;; Commentary:
28 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org-mode develops organizational tasks around NOTES files that contain
32 ;; information about projects as plain text. Org-mode is implemented on
33 ;; top of outline-mode, which makes it possible to keep the content of
34 ;; large files well structured. Visibility cycling and structure editing
35 ;; help to work with the tree. Tables are easily created with a built-in
36 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
37 ;; and scheduling. It dynamically compiles entries into an agenda that
38 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
39 ;; Plain text URL-like links connect to websites, emails, Usenet
40 ;; messages, BBDB entries, and any files related to the projects. For
41 ;; printing and sharing of notes, an Org-mode file can be exported as a
42 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
43 ;; iCalendar file. It can also serve as a publishing tool for a set of
44 ;; linked webpages.
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
50 ;; http://orgmode.org/org.html#Installation
52 ;; Documentation
53 ;; -------------
54 ;; The documentation of Org-mode can be found in the TeXInfo file. The
55 ;; distribution also contains a PDF version of it. At the homepage of
56 ;; Org-mode, you can read the same text online as HTML. There is also an
57 ;; excellent reference card made by Philip Rooke. This card can be found
58 ;; in the etc/ directory of Emacs 22.
60 ;; A list of recent changes can be found at
61 ;; http://orgmode.org/Changes.html
63 ;;; Code:
65 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
66 (defvar org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
68 (make-variable-buffer-local 'org-table-formula-constants-local)
70 ;;;; Require other packages
72 (eval-when-compile
73 (require 'cl)
74 (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (load "org-loaddefs.el" t t t)
82 (require 'org-macs)
83 (require 'org-compat)
85 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
86 ;; some places -- e.g. see the macro `org-with-limited-levels'.
88 ;; In Org buffers, the value of `outline-regexp' is that of
89 ;; `org-outline-regexp'. The only function still directly relying on
90 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
91 ;; job when `orgstruct-mode' is active.
92 (defvar org-outline-regexp "\\*+ "
93 "Regexp to match Org headlines.")
95 (defvar org-outline-regexp-bol "^\\*+ "
96 "Regexp to match Org headlines.
97 This is similar to `org-outline-regexp' but additionally makes
98 sure that we are at the beginning of the line.")
100 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
101 "Matches a headline, putting stars and text into groups.
102 Stars are put in group 1 and the trimmed body in group 2.")
104 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
105 (unless (boundp 'calendar-view-holidays-initially-flag)
106 (org-defvaralias 'calendar-view-holidays-initially-flag
107 'view-calendar-holidays-initially))
108 (unless (boundp 'calendar-view-diary-initially-flag)
109 (org-defvaralias 'calendar-view-diary-initially-flag
110 'view-diary-entries-initially))
111 (unless (boundp 'diary-fancy-buffer)
112 (org-defvaralias 'diary-fancy-buffer 'fancy-diary-buffer))
114 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
115 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
116 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
117 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
118 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
119 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
120 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
121 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
123 (declare-function orgtbl-mode "org-table" (&optional arg))
124 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
125 (declare-function org-beamer-mode "ox-beamer" ())
126 (declare-function org-table-edit-field "org-table" (arg))
127 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
128 (declare-function org-table-set-constants "org-table" ())
129 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
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 (defcustom org-closed-keep-when-no-todo nil
857 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
858 :group 'org-todo
859 :group 'org-keywords
860 :version "24.4"
861 :package-version '(Org . "8.0")
862 :type 'boolean)
864 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
865 org-scheduled-string "\\|"
866 org-deadline-string "\\|"
867 org-closed-string "\\|"
868 org-clock-string "\\)")
869 "Matches a line with planning or clock info.")
871 (defcustom org-comment-string "COMMENT"
872 "Entries starting with this keyword will never be exported.
873 An entry can be toggled between COMMENT and normal with
874 \\[org-toggle-comment].
875 Changes become only effective after restarting Emacs."
876 :group 'org-keywords
877 :type 'string)
879 (defcustom org-quote-string "QUOTE"
880 "Entries starting with this keyword will be exported in fixed-width font.
881 Quoting applies only to the text in the entry following the headline, and does
882 not extend beyond the next headline, even if that is lower level.
883 An entry can be toggled between QUOTE and normal with
884 \\[org-toggle-fixed-width-section]."
885 :group 'org-keywords
886 :type 'string)
888 (defconst org-repeat-re
889 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
890 "Regular expression for specifying repeated events.
891 After a match, group 1 contains the repeat expression.")
893 (defgroup org-structure nil
894 "Options concerning the general structure of Org-mode files."
895 :tag "Org Structure"
896 :group 'org)
898 (defgroup org-reveal-location nil
899 "Options about how to make context of a location visible."
900 :tag "Org Reveal Location"
901 :group 'org-structure)
903 (defconst org-context-choice
904 '(choice
905 (const :tag "Always" t)
906 (const :tag "Never" nil)
907 (repeat :greedy t :tag "Individual contexts"
908 (cons
909 (choice :tag "Context"
910 (const agenda)
911 (const org-goto)
912 (const occur-tree)
913 (const tags-tree)
914 (const link-search)
915 (const mark-goto)
916 (const bookmark-jump)
917 (const isearch)
918 (const default))
919 (boolean))))
920 "Contexts for the reveal options.")
922 (defcustom org-show-hierarchy-above '((default . t))
923 "Non-nil means show full hierarchy when revealing a location.
924 Org-mode often shows locations in an org-mode file which might have
925 been invisible before. When this is set, the hierarchy of headings
926 above the exposed location is shown.
927 Turning this off for example for sparse trees makes them very compact.
928 Instead of t, this can also be an alist specifying this option for different
929 contexts. Valid contexts are
930 agenda when exposing an entry from the agenda
931 org-goto when using the command `org-goto' on key C-c C-j
932 occur-tree when using the command `org-occur' on key C-c /
933 tags-tree when constructing a sparse tree based on tags matches
934 link-search when exposing search matches associated with a link
935 mark-goto when exposing the jump goal of a mark
936 bookmark-jump when exposing a bookmark location
937 isearch when exiting from an incremental search
938 default default for all contexts not set explicitly"
939 :group 'org-reveal-location
940 :type org-context-choice)
942 (defcustom org-show-following-heading '((default . nil))
943 "Non-nil means show following heading when revealing a location.
944 Org-mode often shows locations in an org-mode file which might have
945 been invisible before. When this is set, the heading following the
946 match is shown.
947 Turning this off for example for sparse trees makes them very compact,
948 but makes it harder to edit the location of the match. In such a case,
949 use the command \\[org-reveal] to show more context.
950 Instead of t, this can also be an alist specifying this option for different
951 contexts. See `org-show-hierarchy-above' for valid contexts."
952 :group 'org-reveal-location
953 :type org-context-choice)
955 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
956 "Non-nil means show all sibling heading when revealing a location.
957 Org-mode often shows locations in an org-mode file which might have
958 been invisible before. When this is set, the sibling of the current entry
959 heading are all made visible. If `org-show-hierarchy-above' is t,
960 the same happens on each level of the hierarchy above the current entry.
962 By default this is on for the isearch context, off for all other contexts.
963 Turning this off for example for sparse trees makes them very compact,
964 but makes it harder to edit the location of the match. In such a case,
965 use the command \\[org-reveal] to show more context.
966 Instead of t, this can also be an alist specifying this option for different
967 contexts. See `org-show-hierarchy-above' for valid contexts."
968 :group 'org-reveal-location
969 :type org-context-choice
970 :version "24.4"
971 :package-version '(Org . "8.0"))
973 (defcustom org-show-entry-below '((default . nil))
974 "Non-nil means show the entry below a headline when revealing a location.
975 Org-mode often shows locations in an org-mode file which might have
976 been invisible before. When this is set, the text below the headline that is
977 exposed is also shown.
979 By default this is off for all contexts.
980 Instead of t, this can also be an alist specifying this option for different
981 contexts. See `org-show-hierarchy-above' for valid contexts."
982 :group 'org-reveal-location
983 :type org-context-choice)
985 (defcustom org-indirect-buffer-display 'other-window
986 "How should indirect tree buffers be displayed?
987 This applies to indirect buffers created with the commands
988 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
989 Valid values are:
990 current-window Display in the current window
991 other-window Just display in another window.
992 dedicated-frame Create one new frame, and re-use it each time.
993 new-frame Make a new frame each time. Note that in this case
994 previously-made indirect buffers are kept, and you need to
995 kill these buffers yourself."
996 :group 'org-structure
997 :group 'org-agenda-windows
998 :type '(choice
999 (const :tag "In current window" current-window)
1000 (const :tag "In current frame, other window" other-window)
1001 (const :tag "Each time a new frame" new-frame)
1002 (const :tag "One dedicated frame" dedicated-frame)))
1004 (defcustom org-use-speed-commands nil
1005 "Non-nil means activate single letter commands at beginning of a headline.
1006 This may also be a function to test for appropriate locations where speed
1007 commands should be active."
1008 :group 'org-structure
1009 :type '(choice
1010 (const :tag "Never" nil)
1011 (const :tag "At beginning of headline stars" t)
1012 (function)))
1014 (defcustom org-speed-commands-user nil
1015 "Alist of additional speed commands.
1016 This list will be checked before `org-speed-commands-default'
1017 when the variable `org-use-speed-commands' is non-nil
1018 and when the cursor is at the beginning of a headline.
1019 The car if each entry is a string with a single letter, which must
1020 be assigned to `self-insert-command' in the global map.
1021 The cdr is either a command to be called interactively, a function
1022 to be called, or a form to be evaluated.
1023 An entry that is just a list with a single string will be interpreted
1024 as a descriptive headline that will be added when listing the speed
1025 commands in the Help buffer using the `?' speed command."
1026 :group 'org-structure
1027 :type '(repeat :value ("k" . ignore)
1028 (choice :value ("k" . ignore)
1029 (list :tag "Descriptive Headline" (string :tag "Headline"))
1030 (cons :tag "Letter and Command"
1031 (string :tag "Command letter")
1032 (choice
1033 (function)
1034 (sexp))))))
1036 (defgroup org-cycle nil
1037 "Options concerning visibility cycling in Org-mode."
1038 :tag "Org Cycle"
1039 :group 'org-structure)
1041 (defcustom org-cycle-skip-children-state-if-no-children t
1042 "Non-nil means skip CHILDREN state in entries that don't have any."
1043 :group 'org-cycle
1044 :type 'boolean)
1046 (defcustom org-cycle-max-level nil
1047 "Maximum level which should still be subject to visibility cycling.
1048 Levels higher than this will, for cycling, be treated as text, not a headline.
1049 When `org-odd-levels-only' is set, a value of N in this variable actually
1050 means 2N-1 stars as the limiting headline.
1051 When nil, cycle all levels.
1052 Note that the limiting level of cycling is also influenced by
1053 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1054 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1055 than its value."
1056 :group 'org-cycle
1057 :type '(choice
1058 (const :tag "No limit" nil)
1059 (integer :tag "Maximum level")))
1061 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1062 "Names of drawers. Drawers are not opened by cycling on the headline above.
1063 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1064 this:
1065 :DRAWERNAME:
1066 .....
1067 :END:
1068 The drawer \"PROPERTIES\" is special for capturing properties through
1069 the property API.
1071 Drawers can be defined on the per-file basis with a line like:
1073 #+DRAWERS: HIDDEN STATE PROPERTIES"
1074 :group 'org-structure
1075 :group 'org-cycle
1076 :type '(repeat (string :tag "Drawer Name")))
1078 (defcustom org-hide-block-startup nil
1079 "Non-nil means entering Org-mode will fold all blocks.
1080 This can also be set in on a per-file basis with
1082 #+STARTUP: hideblocks
1083 #+STARTUP: showblocks"
1084 :group 'org-startup
1085 :group 'org-cycle
1086 :type 'boolean)
1088 (defcustom org-cycle-global-at-bob nil
1089 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1090 This makes it possible to do global cycling without having to use S-TAB or
1091 \\[universal-argument] TAB. For this special case to work, the first line
1092 of the buffer must not be a headline -- it may be empty or some other text.
1093 When used in this way, `org-cycle-hook' is disabled temporarily to make
1094 sure the cursor stays at the beginning of the buffer. When this option is
1095 nil, don't do anything special at the beginning of the buffer."
1096 :group 'org-cycle
1097 :type 'boolean)
1099 (defcustom org-cycle-level-after-item/entry-creation t
1100 "Non-nil means cycle entry level or item indentation in new empty entries.
1102 When the cursor is at the end of an empty headline, i.e., with only stars
1103 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1104 and then all possible ancestor states, before returning to the original state.
1105 This makes data entry extremely fast: M-RET to create a new headline,
1106 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1108 When the cursor is at the end of an empty plain list item, one TAB will
1109 make it a subitem, two or more tabs will back up to make this an item
1110 higher up in the item hierarchy."
1111 :group 'org-cycle
1112 :type 'boolean)
1114 (defcustom org-cycle-emulate-tab t
1115 "Where should `org-cycle' emulate TAB.
1116 nil Never
1117 white Only in completely white lines
1118 whitestart Only at the beginning of lines, before the first non-white char
1119 t Everywhere except in headlines
1120 exc-hl-bol Everywhere except at the start of a headline
1121 If TAB is used in a place where it does not emulate TAB, the current subtree
1122 visibility is cycled."
1123 :group 'org-cycle
1124 :type '(choice (const :tag "Never" nil)
1125 (const :tag "Only in completely white lines" white)
1126 (const :tag "Before first char in a line" whitestart)
1127 (const :tag "Everywhere except in headlines" t)
1128 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1130 (defcustom org-cycle-separator-lines 2
1131 "Number of empty lines needed to keep an empty line between collapsed trees.
1132 If you leave an empty line between the end of a subtree and the following
1133 headline, this empty line is hidden when the subtree is folded.
1134 Org-mode will leave (exactly) one empty line visible if the number of
1135 empty lines is equal or larger to the number given in this variable.
1136 So the default 2 means at least 2 empty lines after the end of a subtree
1137 are needed to produce free space between a collapsed subtree and the
1138 following headline.
1140 If the number is negative, and the number of empty lines is at least -N,
1141 all empty lines are shown.
1143 Special case: when 0, never leave empty lines in collapsed view."
1144 :group 'org-cycle
1145 :type 'integer)
1146 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1148 (defcustom org-pre-cycle-hook nil
1149 "Hook that is run before visibility cycling is happening.
1150 The function(s) in this hook must accept a single argument which indicates
1151 the new state that will be set right after running this hook. The
1152 argument is a symbol. Before a global state change, it can have the values
1153 `overview', `content', or `all'. Before a local state change, it can have
1154 the values `folded', `children', or `subtree'."
1155 :group 'org-cycle
1156 :type 'hook)
1158 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1159 org-cycle-hide-drawers
1160 org-cycle-hide-inline-tasks
1161 org-cycle-show-empty-lines
1162 org-optimize-window-after-visibility-change)
1163 "Hook that is run after `org-cycle' has changed the buffer visibility.
1164 The function(s) in this hook must accept a single argument which indicates
1165 the new state that was set by the most recent `org-cycle' command. The
1166 argument is a symbol. After a global state change, it can have the values
1167 `overview', `contents', or `all'. After a local state change, it can have
1168 the values `folded', `children', or `subtree'."
1169 :group 'org-cycle
1170 :type 'hook)
1172 (defgroup org-edit-structure nil
1173 "Options concerning structure editing in Org-mode."
1174 :tag "Org Edit Structure"
1175 :group 'org-structure)
1177 (defcustom org-odd-levels-only nil
1178 "Non-nil means skip even levels and only use odd levels for the outline.
1179 This has the effect that two stars are being added/taken away in
1180 promotion/demotion commands. It also influences how levels are
1181 handled by the exporters.
1182 Changing it requires restart of `font-lock-mode' to become effective
1183 for fontification also in regions already fontified.
1184 You may also set this on a per-file basis by adding one of the following
1185 lines to the buffer:
1187 #+STARTUP: odd
1188 #+STARTUP: oddeven"
1189 :group 'org-edit-structure
1190 :group 'org-appearance
1191 :type 'boolean)
1193 (defcustom org-adapt-indentation t
1194 "Non-nil means adapt indentation to outline node level.
1196 When this variable is set, Org assumes that you write outlines by
1197 indenting text in each node to align with the headline (after the stars).
1198 The following issues are influenced by this variable:
1200 - When this is set and the *entire* text in an entry is indented, the
1201 indentation is increased by one space in a demotion command, and
1202 decreased by one in a promotion command. If any line in the entry
1203 body starts with text at column 0, indentation is not changed at all.
1205 - Property drawers and planning information is inserted indented when
1206 this variable s set. When nil, they will not be indented.
1208 - TAB indents a line relative to context. The lines below a headline
1209 will be indented when this variable is set.
1211 Note that this is all about true indentation, by adding and removing
1212 space characters. See also `org-indent.el' which does level-dependent
1213 indentation in a virtual way, i.e. at display time in Emacs."
1214 :group 'org-edit-structure
1215 :type 'boolean)
1217 (defcustom org-special-ctrl-a/e nil
1218 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1220 When t, `C-a' will bring back the cursor to the beginning of the
1221 headline text, i.e. after the stars and after a possible TODO
1222 keyword. In an item, this will be the position after bullet and
1223 check-box, if any. When the cursor is already at that position,
1224 another `C-a' will bring it to the beginning of the line.
1226 `C-e' will jump to the end of the headline, ignoring the presence
1227 of tags in the headline. A second `C-e' will then jump to the
1228 true end of the line, after any tags. This also means that, when
1229 this variable is non-nil, `C-e' also will never jump beyond the
1230 end of the heading of a folded section, i.e. not after the
1231 ellipses.
1233 When set to the symbol `reversed', the first `C-a' or `C-e' works
1234 normally, going to the true line boundary first. Only a directly
1235 following, identical keypress will bring the cursor to the
1236 special positions.
1238 This may also be a cons cell where the behavior for `C-a' and
1239 `C-e' is set separately."
1240 :group 'org-edit-structure
1241 :type '(choice
1242 (const :tag "off" nil)
1243 (const :tag "on: after stars/bullet and before tags first" t)
1244 (const :tag "reversed: true line boundary first" reversed)
1245 (cons :tag "Set C-a and C-e separately"
1246 (choice :tag "Special C-a"
1247 (const :tag "off" nil)
1248 (const :tag "on: after stars/bullet first" t)
1249 (const :tag "reversed: before stars/bullet first" reversed))
1250 (choice :tag "Special C-e"
1251 (const :tag "off" nil)
1252 (const :tag "on: before tags first" t)
1253 (const :tag "reversed: after tags first" reversed)))))
1254 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1256 (defcustom org-special-ctrl-k nil
1257 "Non-nil means `C-k' will behave specially in headlines.
1258 When nil, `C-k' will call the default `kill-line' command.
1259 When t, the following will happen while the cursor is in the headline:
1261 - When the cursor is at the beginning of a headline, kill the entire
1262 line and possible the folded subtree below the line.
1263 - When in the middle of the headline text, kill the headline up to the tags.
1264 - When after the headline text, kill the tags."
1265 :group 'org-edit-structure
1266 :type 'boolean)
1268 (defcustom org-ctrl-k-protect-subtree nil
1269 "Non-nil means, do not delete a hidden subtree with C-k.
1270 When set to the symbol `error', simply throw an error when C-k is
1271 used to kill (part-of) a headline that has hidden text behind it.
1272 Any other non-nil value will result in a query to the user, if it is
1273 OK to kill that hidden subtree. When nil, kill without remorse."
1274 :group 'org-edit-structure
1275 :version "24.1"
1276 :type '(choice
1277 (const :tag "Do not protect hidden subtrees" nil)
1278 (const :tag "Protect hidden subtrees with a security query" t)
1279 (const :tag "Never kill a hidden subtree with C-k" error)))
1281 (defcustom org-catch-invisible-edits nil
1282 "Check if in invisible region before inserting or deleting a character.
1283 Valid values are:
1285 nil Do not check, so just do invisible edits.
1286 error Throw an error and do nothing.
1287 show Make point visible, and do the requested edit.
1288 show-and-error Make point visible, then throw an error and abort the edit.
1289 smart Make point visible, and do insertion/deletion if it is
1290 adjacent to visible text and the change feels predictable.
1291 Never delete a previously invisible character or add in the
1292 middle or right after an invisible region. Basically, this
1293 allows insertion and backward-delete right before ellipses.
1294 FIXME: maybe in this case we should not even show?"
1295 :group 'org-edit-structure
1296 :version "24.1"
1297 :type '(choice
1298 (const :tag "Do not check" nil)
1299 (const :tag "Throw error when trying to edit" error)
1300 (const :tag "Unhide, but do not do the edit" show-and-error)
1301 (const :tag "Show invisible part and do the edit" show)
1302 (const :tag "Be smart and do the right thing" smart)))
1304 (defcustom org-yank-folded-subtrees t
1305 "Non-nil means when yanking subtrees, fold them.
1306 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1307 it starts with a heading and all other headings in it are either children
1308 or siblings, then fold all the subtrees. However, do this only if no
1309 text after the yank would be swallowed into a folded tree by this action."
1310 :group 'org-edit-structure
1311 :type 'boolean)
1313 (defcustom org-yank-adjusted-subtrees nil
1314 "Non-nil means when yanking subtrees, adjust the level.
1315 With this setting, `org-paste-subtree' is used to insert the subtree, see
1316 this function for details."
1317 :group 'org-edit-structure
1318 :type 'boolean)
1320 (defcustom org-M-RET-may-split-line '((default . t))
1321 "Non-nil means M-RET will split the line at the cursor position.
1322 When nil, it will go to the end of the line before making a
1323 new line.
1324 You may also set this option in a different way for different
1325 contexts. Valid contexts are:
1327 headline when creating a new headline
1328 item when creating a new item
1329 table in a table field
1330 default the value to be used for all contexts not explicitly
1331 customized"
1332 :group 'org-structure
1333 :group 'org-table
1334 :type '(choice
1335 (const :tag "Always" t)
1336 (const :tag "Never" nil)
1337 (repeat :greedy t :tag "Individual contexts"
1338 (cons
1339 (choice :tag "Context"
1340 (const headline)
1341 (const item)
1342 (const table)
1343 (const default))
1344 (boolean)))))
1347 (defcustom org-insert-heading-respect-content nil
1348 "Non-nil means insert new headings after the current subtree.
1349 When nil, the new heading is created directly after the current line.
1350 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1351 this variable on for the duration of the command."
1352 :group 'org-structure
1353 :type 'boolean)
1355 (defcustom org-blank-before-new-entry '((heading . auto)
1356 (plain-list-item . auto))
1357 "Should `org-insert-heading' leave a blank line before new heading/item?
1358 The value is an alist, with `heading' and `plain-list-item' as CAR,
1359 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1360 which case Org will look at the surrounding headings/items and try to
1361 make an intelligent decision whether to insert a blank line or not.
1363 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1364 the setting here is ignored and no empty line is inserted to avoid breaking
1365 the list structure."
1366 :group 'org-edit-structure
1367 :type '(list
1368 (cons (const heading)
1369 (choice (const :tag "Never" nil)
1370 (const :tag "Always" t)
1371 (const :tag "Auto" auto)))
1372 (cons (const plain-list-item)
1373 (choice (const :tag "Never" nil)
1374 (const :tag "Always" t)
1375 (const :tag "Auto" auto)))))
1377 (defcustom org-insert-heading-hook nil
1378 "Hook being run after inserting a new heading."
1379 :group 'org-edit-structure
1380 :type 'hook)
1382 (defcustom org-enable-fixed-width-editor t
1383 "Non-nil means lines starting with \":\" are treated as fixed-width.
1384 This currently only means they are never auto-wrapped.
1385 When nil, such lines will be treated like ordinary lines.
1386 See also the QUOTE keyword."
1387 :group 'org-edit-structure
1388 :type 'boolean)
1390 (defcustom org-goto-auto-isearch t
1391 "Non-nil means typing characters in `org-goto' starts incremental search.
1392 When nil, you can use these keybindings to navigate the buffer:
1394 q Quit the org-goto interface
1395 n Go to the next visible heading
1396 p Go to the previous visible heading
1397 f Go one heading forward on same level
1398 b Go one heading backward on same level
1399 u Go one heading up"
1400 :group 'org-edit-structure
1401 :type 'boolean)
1403 (defgroup org-sparse-trees nil
1404 "Options concerning sparse trees in Org-mode."
1405 :tag "Org Sparse Trees"
1406 :group 'org-structure)
1408 (defcustom org-highlight-sparse-tree-matches t
1409 "Non-nil means highlight all matches that define a sparse tree.
1410 The highlights will automatically disappear the next time the buffer is
1411 changed by an edit command."
1412 :group 'org-sparse-trees
1413 :type 'boolean)
1415 (defcustom org-remove-highlights-with-change t
1416 "Non-nil means any change to the buffer will remove temporary highlights.
1417 Such highlights are created by `org-occur' and `org-clock-display'.
1418 When nil, `C-c C-c needs to be used to get rid of the highlights.
1419 The highlights created by `org-preview-latex-fragment' always need
1420 `C-c C-c' to be removed."
1421 :group 'org-sparse-trees
1422 :group 'org-time
1423 :type 'boolean)
1426 (defcustom org-occur-hook '(org-first-headline-recenter)
1427 "Hook that is run after `org-occur' has constructed a sparse tree.
1428 This can be used to recenter the window to show as much of the structure
1429 as possible."
1430 :group 'org-sparse-trees
1431 :type 'hook)
1433 (defgroup org-imenu-and-speedbar nil
1434 "Options concerning imenu and speedbar in Org-mode."
1435 :tag "Org Imenu and Speedbar"
1436 :group 'org-structure)
1438 (defcustom org-imenu-depth 2
1439 "The maximum level for Imenu access to Org-mode headlines.
1440 This also applied for speedbar access."
1441 :group 'org-imenu-and-speedbar
1442 :type 'integer)
1444 (defgroup org-table nil
1445 "Options concerning tables in Org-mode."
1446 :tag "Org Table"
1447 :group 'org)
1449 (defcustom org-enable-table-editor 'optimized
1450 "Non-nil means lines starting with \"|\" are handled by the table editor.
1451 When nil, such lines will be treated like ordinary lines.
1453 When equal to the symbol `optimized', the table editor will be optimized to
1454 do the following:
1455 - Automatic overwrite mode in front of whitespace in table fields.
1456 This makes the structure of the table stay in tact as long as the edited
1457 field does not exceed the column width.
1458 - Minimize the number of realigns. Normally, the table is aligned each time
1459 TAB or RET are pressed to move to another field. With optimization this
1460 happens only if changes to a field might have changed the column width.
1461 Optimization requires replacing the functions `self-insert-command',
1462 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1463 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1464 very good at guessing when a re-align will be necessary, but you can always
1465 force one with \\[org-ctrl-c-ctrl-c].
1467 If you would like to use the optimized version in Org-mode, but the
1468 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1470 This variable can be used to turn on and off the table editor during a session,
1471 but in order to toggle optimization, a restart is required.
1473 See also the variable `org-table-auto-blank-field'."
1474 :group 'org-table
1475 :type '(choice
1476 (const :tag "off" nil)
1477 (const :tag "on" t)
1478 (const :tag "on, optimized" optimized)))
1480 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1481 (version<= emacs-version "24.1"))
1482 "Non-nil means cluster self-insert commands for undo when possible.
1483 If this is set, then, like in the Emacs command loop, 20 consecutive
1484 characters will be undone together.
1485 This is configurable, because there is some impact on typing performance."
1486 :group 'org-table
1487 :type 'boolean)
1489 (defcustom org-table-tab-recognizes-table.el t
1490 "Non-nil means TAB will automatically notice a table.el table.
1491 When it sees such a table, it moves point into it and - if necessary -
1492 calls `table-recognize-table'."
1493 :group 'org-table-editing
1494 :type 'boolean)
1496 (defgroup org-link nil
1497 "Options concerning links in Org-mode."
1498 :tag "Org Link"
1499 :group 'org)
1501 (defvar org-link-abbrev-alist-local nil
1502 "Buffer-local version of `org-link-abbrev-alist', which see.
1503 The value of this is taken from the #+LINK lines.")
1504 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1506 (defcustom org-link-abbrev-alist nil
1507 "Alist of link abbreviations.
1508 The car of each element is a string, to be replaced at the start of a link.
1509 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1510 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1512 [[linkkey:tag][description]]
1514 The 'linkkey' must be a word word, starting with a letter, followed
1515 by letters, numbers, '-' or '_'.
1517 If REPLACE is a string, the tag will simply be appended to create the link.
1518 If the string contains \"%s\", the tag will be inserted there. If the string
1519 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1520 at that point (see the function `url-hexify-string'). If the string contains
1521 the specifier \"%(my-function)\", then the custom function `my-function' will
1522 be invoked: this function takes the tag as its only argument and must return
1523 a string.
1525 REPLACE may also be a function that will be called with the tag as the
1526 only argument to create the link, which should be returned as a string.
1528 See the manual for examples."
1529 :group 'org-link
1530 :type '(repeat
1531 (cons
1532 (string :tag "Protocol")
1533 (choice
1534 (string :tag "Format")
1535 (function)))))
1537 (defcustom org-descriptive-links t
1538 "Non-nil means Org will display descriptive links.
1539 E.g. [[http://orgmode.org][Org website]] will be displayed as
1540 \"Org Website\", hiding the link itself and just displaying its
1541 description. When set to `nil', Org will display the full links
1542 literally.
1544 You can interactively set the value of this variable by calling
1545 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1546 :group 'org-link
1547 :type 'boolean)
1549 (defcustom org-link-file-path-type 'adaptive
1550 "How the path name in file links should be stored.
1551 Valid values are:
1553 relative Relative to the current directory, i.e. the directory of the file
1554 into which the link is being inserted.
1555 absolute Absolute path, if possible with ~ for home directory.
1556 noabbrev Absolute path, no abbreviation of home directory.
1557 adaptive Use relative path for files in the current directory and sub-
1558 directories of it. For other files, use an absolute path."
1559 :group 'org-link
1560 :type '(choice
1561 (const relative)
1562 (const absolute)
1563 (const noabbrev)
1564 (const adaptive)))
1566 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1567 "Types of links that should be activated in Org-mode files.
1568 This is a list of symbols, each leading to the activation of a certain link
1569 type. In principle, it does not hurt to turn on most link types - there may
1570 be a small gain when turning off unused link types. The types are:
1572 bracket The recommended [[link][description]] or [[link]] links with hiding.
1573 angle Links in angular brackets that may contain whitespace like
1574 <bbdb:Carsten Dominik>.
1575 plain Plain links in normal text, no whitespace, like http://google.com.
1576 radio Text that is matched by a radio target, see manual for details.
1577 tag Tag settings in a headline (link to tag search).
1578 date Time stamps (link to calendar).
1579 footnote Footnote labels.
1581 Changing this variable requires a restart of Emacs to become effective."
1582 :group 'org-link
1583 :type '(set :greedy t
1584 (const :tag "Double bracket links" bracket)
1585 (const :tag "Angular bracket links" angle)
1586 (const :tag "Plain text links" plain)
1587 (const :tag "Radio target matches" radio)
1588 (const :tag "Tags" tag)
1589 (const :tag "Timestamps" date)
1590 (const :tag "Footnotes" footnote)))
1592 (defcustom org-make-link-description-function nil
1593 "Function to use for generating link descriptions from links.
1594 When nil, the link location will be used. This function must take
1595 two parameters: the first one is the link, the second one is the
1596 description generated by `org-insert-link'. The function should
1597 return the description to use."
1598 :group 'org-link
1599 :type '(choice (const nil) (function)))
1601 (defgroup org-link-store nil
1602 "Options concerning storing links in Org-mode."
1603 :tag "Org Store Link"
1604 :group 'org-link)
1606 (defcustom org-url-hexify-p t
1607 "When non-nil, hexify URL when creating a link."
1608 :type 'boolean
1609 :version "24.3"
1610 :group 'org-link-store)
1612 (defcustom org-email-link-description-format "Email %c: %.30s"
1613 "Format of the description part of a link to an email or usenet message.
1614 The following %-escapes will be replaced by corresponding information:
1616 %F full \"From\" field
1617 %f name, taken from \"From\" field, address if no name
1618 %T full \"To\" field
1619 %t first name in \"To\" field, address if no name
1620 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1621 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1622 %s subject
1623 %d date
1624 %m message-id.
1626 You may use normal field width specification between the % and the letter.
1627 This is for example useful to limit the length of the subject.
1629 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1630 :group 'org-link-store
1631 :type 'string)
1633 (defcustom org-from-is-user-regexp
1634 (let (r1 r2)
1635 (when (and user-mail-address (not (string= user-mail-address "")))
1636 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1637 (when (and user-full-name (not (string= user-full-name "")))
1638 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1639 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1640 "Regexp matched against the \"From:\" header of an email or usenet message.
1641 It should match if the message is from the user him/herself."
1642 :group 'org-link-store
1643 :type 'regexp)
1645 (defcustom org-context-in-file-links t
1646 "Non-nil means file links from `org-store-link' contain context.
1647 A search string will be added to the file name with :: as separator and
1648 used to find the context when the link is activated by the command
1649 `org-open-at-point'. When this option is t, the entire active region
1650 will be placed in the search string of the file link. If set to a
1651 positive integer, only the first n lines of context will be stored.
1653 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1654 negates this setting for the duration of the command."
1655 :group 'org-link-store
1656 :type '(choice boolean integer))
1658 (defcustom org-keep-stored-link-after-insertion nil
1659 "Non-nil means keep link in list for entire session.
1661 The command `org-store-link' adds a link pointing to the current
1662 location to an internal list. These links accumulate during a session.
1663 The command `org-insert-link' can be used to insert links into any
1664 Org-mode file (offering completion for all stored links). When this
1665 option is nil, every link which has been inserted once using \\[org-insert-link]
1666 will be removed from the list, to make completing the unused links
1667 more efficient."
1668 :group 'org-link-store
1669 :type 'boolean)
1671 (defgroup org-link-follow nil
1672 "Options concerning following links in Org-mode."
1673 :tag "Org Follow Link"
1674 :group 'org-link)
1676 (defcustom org-link-translation-function nil
1677 "Function to translate links with different syntax to Org syntax.
1678 This can be used to translate links created for example by the Planner
1679 or emacs-wiki packages to Org syntax.
1680 The function must accept two parameters, a TYPE containing the link
1681 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1682 which is everything after the link protocol. It should return a cons
1683 with possibly modified values of type and path.
1684 Org contains a function for this, so if you set this variable to
1685 `org-translate-link-from-planner', you should be able follow many
1686 links created by planner."
1687 :group 'org-link-follow
1688 :type '(choice (const nil) (function)))
1690 (defcustom org-follow-link-hook nil
1691 "Hook that is run after a link has been followed."
1692 :group 'org-link-follow
1693 :type 'hook)
1695 (defcustom org-tab-follows-link nil
1696 "Non-nil means on links TAB will follow the link.
1697 Needs to be set before org.el is loaded.
1698 This really should not be used, it does not make sense, and the
1699 implementation is bad."
1700 :group 'org-link-follow
1701 :type 'boolean)
1703 (defcustom org-return-follows-link nil
1704 "Non-nil means on links RET will follow the link.
1705 In tables, the special behavior of RET has precedence."
1706 :group 'org-link-follow
1707 :type 'boolean)
1709 (defcustom org-mouse-1-follows-link
1710 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1711 "Non-nil means mouse-1 on a link will follow the link.
1712 A longer mouse click will still set point. Does not work on XEmacs.
1713 Needs to be set before org.el is loaded."
1714 :group 'org-link-follow
1715 :type 'boolean)
1717 (defcustom org-mark-ring-length 4
1718 "Number of different positions to be recorded in the ring.
1719 Changing this requires a restart of Emacs to work correctly."
1720 :group 'org-link-follow
1721 :type 'integer)
1723 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1724 "Non-nil means internal links in Org files must exactly match a headline.
1725 When nil, the link search tries to match a phrase with all words
1726 in the search text."
1727 :group 'org-link-follow
1728 :version "24.1"
1729 :type '(choice
1730 (const :tag "Use fuzzy text search" nil)
1731 (const :tag "Match only exact headline" t)
1732 (const :tag "Match exact headline or query to create it"
1733 query-to-create)))
1735 (defcustom org-link-frame-setup
1736 '((vm . vm-visit-folder-other-frame)
1737 (vm-imap . vm-visit-imap-folder-other-frame)
1738 (gnus . org-gnus-no-new-news)
1739 (file . find-file-other-window)
1740 (wl . wl-other-frame))
1741 "Setup the frame configuration for following links.
1742 When following a link with Emacs, it may often be useful to display
1743 this link in another window or frame. This variable can be used to
1744 set this up for the different types of links.
1745 For VM, use any of
1746 `vm-visit-folder'
1747 `vm-visit-folder-other-window'
1748 `vm-visit-folder-other-frame'
1749 For Gnus, use any of
1750 `gnus'
1751 `gnus-other-frame'
1752 `org-gnus-no-new-news'
1753 For FILE, use any of
1754 `find-file'
1755 `find-file-other-window'
1756 `find-file-other-frame'
1757 For Wanderlust use any of
1758 `wl'
1759 `wl-other-frame'
1760 For the calendar, use the variable `calendar-setup'.
1761 For BBDB, it is currently only possible to display the matches in
1762 another window."
1763 :group 'org-link-follow
1764 :type '(list
1765 (cons (const vm)
1766 (choice
1767 (const vm-visit-folder)
1768 (const vm-visit-folder-other-window)
1769 (const vm-visit-folder-other-frame)))
1770 (cons (const vm-imap)
1771 (choice
1772 (const vm-visit-imap-folder)
1773 (const vm-visit-imap-folder-other-window)
1774 (const vm-visit-imap-folder-other-frame)))
1775 (cons (const gnus)
1776 (choice
1777 (const gnus)
1778 (const gnus-other-frame)
1779 (const org-gnus-no-new-news)))
1780 (cons (const file)
1781 (choice
1782 (const find-file)
1783 (const find-file-other-window)
1784 (const find-file-other-frame)))
1785 (cons (const wl)
1786 (choice
1787 (const wl)
1788 (const wl-other-frame)))))
1790 (defcustom org-display-internal-link-with-indirect-buffer nil
1791 "Non-nil means use indirect buffer to display infile links.
1792 Activating internal links (from one location in a file to another location
1793 in the same file) normally just jumps to the location. When the link is
1794 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1795 is displayed in
1796 another window. When this option is set, the other window actually displays
1797 an indirect buffer clone of the current buffer, to avoid any visibility
1798 changes to the current buffer."
1799 :group 'org-link-follow
1800 :type 'boolean)
1802 (defcustom org-open-non-existing-files nil
1803 "Non-nil means `org-open-file' will open non-existing files.
1804 When nil, an error will be generated.
1805 This variable applies only to external applications because they
1806 might choke on non-existing files. If the link is to a file that
1807 will be opened in Emacs, the variable is ignored."
1808 :group 'org-link-follow
1809 :type 'boolean)
1811 (defcustom org-open-directory-means-index-dot-org nil
1812 "Non-nil means a link to a directory really means to index.org.
1813 When nil, following a directory link will run dired or open a finder/explorer
1814 window on that directory."
1815 :group 'org-link-follow
1816 :type 'boolean)
1818 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1819 "Function and arguments to call for following mailto links.
1820 This is a list with the first element being a Lisp function, and the
1821 remaining elements being arguments to the function. In string arguments,
1822 %a will be replaced by the address, and %s will be replaced by the subject
1823 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1824 :group 'org-link-follow
1825 :type '(choice
1826 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1827 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1828 (const :tag "message-mail" (message-mail "%a" "%s"))
1829 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1831 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1832 "Non-nil means ask for confirmation before executing shell links.
1833 Shell links can be dangerous: just think about a link
1835 [[shell:rm -rf ~/*][Google Search]]
1837 This link would show up in your Org-mode document as \"Google Search\",
1838 but really it would remove your entire home directory.
1839 Therefore we advise against setting this variable to nil.
1840 Just change it to `y-or-n-p' if you want to confirm with a
1841 single keystroke rather than having to type \"yes\"."
1842 :group 'org-link-follow
1843 :type '(choice
1844 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1845 (const :tag "with y-or-n (faster)" y-or-n-p)
1846 (const :tag "no confirmation (dangerous)" nil)))
1847 (put 'org-confirm-shell-link-function
1848 'safe-local-variable
1849 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1851 (defcustom org-confirm-shell-link-not-regexp ""
1852 "A regexp to skip confirmation for shell links."
1853 :group 'org-link-follow
1854 :version "24.1"
1855 :type 'regexp)
1857 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1858 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1859 Elisp links can be dangerous: just think about a link
1861 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1863 This link would show up in your Org-mode document as \"Google Search\",
1864 but really it would remove your entire home directory.
1865 Therefore we advise against setting this variable to nil.
1866 Just change it to `y-or-n-p' if you want to confirm with a
1867 single keystroke rather than having to type \"yes\"."
1868 :group 'org-link-follow
1869 :type '(choice
1870 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1871 (const :tag "with y-or-n (faster)" y-or-n-p)
1872 (const :tag "no confirmation (dangerous)" nil)))
1873 (put 'org-confirm-shell-link-function
1874 'safe-local-variable
1875 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1877 (defcustom org-confirm-elisp-link-not-regexp ""
1878 "A regexp to skip confirmation for Elisp links."
1879 :group 'org-link-follow
1880 :version "24.1"
1881 :type 'regexp)
1883 (defconst org-file-apps-defaults-gnu
1884 '((remote . emacs)
1885 (system . mailcap)
1886 (t . mailcap))
1887 "Default file applications on a UNIX or GNU/Linux system.
1888 See `org-file-apps'.")
1890 (defconst org-file-apps-defaults-macosx
1891 '((remote . emacs)
1892 (t . "open %s")
1893 (system . "open %s")
1894 ("ps.gz" . "gv %s")
1895 ("eps.gz" . "gv %s")
1896 ("dvi" . "xdvi %s")
1897 ("fig" . "xfig %s"))
1898 "Default file applications on a MacOS X system.
1899 The system \"open\" is known as a default, but we use X11 applications
1900 for some files for which the OS does not have a good default.
1901 See `org-file-apps'.")
1903 (defconst org-file-apps-defaults-windowsnt
1904 (list
1905 '(remote . emacs)
1906 (cons t
1907 (list (if (featurep 'xemacs)
1908 'mswindows-shell-execute
1909 'w32-shell-execute)
1910 "open" 'file))
1911 (cons 'system
1912 (list (if (featurep 'xemacs)
1913 'mswindows-shell-execute
1914 'w32-shell-execute)
1915 "open" 'file)))
1916 "Default file applications on a Windows NT system.
1917 The system \"open\" is used for most files.
1918 See `org-file-apps'.")
1920 (defcustom org-file-apps
1921 '((auto-mode . emacs)
1922 ("\\.mm\\'" . default)
1923 ("\\.x?html?\\'" . default)
1924 ("\\.pdf\\'" . default))
1925 "External applications for opening `file:path' items in a document.
1926 Org-mode uses system defaults for different file types, but
1927 you can use this variable to set the application for a given file
1928 extension. The entries in this list are cons cells where the car identifies
1929 files and the cdr the corresponding command. Possible values for the
1930 file identifier are
1931 \"string\" A string as a file identifier can be interpreted in different
1932 ways, depending on its contents:
1934 - Alphanumeric characters only:
1935 Match links with this file extension.
1936 Example: (\"pdf\" . \"evince %s\")
1937 to open PDFs with evince.
1939 - Regular expression: Match links where the
1940 filename matches the regexp. If you want to
1941 use groups here, use shy groups.
1943 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1944 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1945 to open *.html and *.xhtml with firefox.
1947 - Regular expression which contains (non-shy) groups:
1948 Match links where the whole link, including \"::\", and
1949 anything after that, matches the regexp.
1950 In a custom command string, %1, %2, etc. are replaced with
1951 the parts of the link that were matched by the groups.
1952 For backwards compatibility, if a command string is given
1953 that does not use any of the group matches, this case is
1954 handled identically to the second one (i.e. match against
1955 file name only).
1956 In a custom lisp form, you can access the group matches with
1957 (match-string n link).
1959 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1960 to open [[file:document.pdf::5]] with evince at page 5.
1962 `directory' Matches a directory
1963 `remote' Matches a remote file, accessible through tramp or efs.
1964 Remote files most likely should be visited through Emacs
1965 because external applications cannot handle such paths.
1966 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1967 so all files Emacs knows how to handle. Using this with
1968 command `emacs' will open most files in Emacs. Beware that this
1969 will also open html files inside Emacs, unless you add
1970 (\"html\" . default) to the list as well.
1971 t Default for files not matched by any of the other options.
1972 `system' The system command to open files, like `open' on Windows
1973 and Mac OS X, and mailcap under GNU/Linux. This is the command
1974 that will be selected if you call `C-c C-o' with a double
1975 \\[universal-argument] \\[universal-argument] prefix.
1977 Possible values for the command are:
1978 `emacs' The file will be visited by the current Emacs process.
1979 `default' Use the default application for this file type, which is the
1980 association for t in the list, most likely in the system-specific
1981 part.
1982 This can be used to overrule an unwanted setting in the
1983 system-specific variable.
1984 `system' Use the system command for opening files, like \"open\".
1985 This command is specified by the entry whose car is `system'.
1986 Most likely, the system-specific version of this variable
1987 does define this command, but you can overrule/replace it
1988 here.
1989 string A command to be executed by a shell; %s will be replaced
1990 by the path to the file.
1991 sexp A Lisp form which will be evaluated. The file path will
1992 be available in the Lisp variable `file'.
1993 For more examples, see the system specific constants
1994 `org-file-apps-defaults-macosx'
1995 `org-file-apps-defaults-windowsnt'
1996 `org-file-apps-defaults-gnu'."
1997 :group 'org-link-follow
1998 :type '(repeat
1999 (cons (choice :value ""
2000 (string :tag "Extension")
2001 (const :tag "System command to open files" system)
2002 (const :tag "Default for unrecognized files" t)
2003 (const :tag "Remote file" remote)
2004 (const :tag "Links to a directory" directory)
2005 (const :tag "Any files that have Emacs modes"
2006 auto-mode))
2007 (choice :value ""
2008 (const :tag "Visit with Emacs" emacs)
2009 (const :tag "Use default" default)
2010 (const :tag "Use the system command" system)
2011 (string :tag "Command")
2012 (sexp :tag "Lisp form")))))
2014 (defcustom org-doi-server-url "http://dx.doi.org/"
2015 "The URL of the DOI server."
2016 :type 'string
2017 :version "24.3"
2018 :group 'org-link-follow)
2020 (defgroup org-refile nil
2021 "Options concerning refiling entries in Org-mode."
2022 :tag "Org Refile"
2023 :group 'org)
2025 (defcustom org-directory "~/org"
2026 "Directory with org files.
2027 This is just a default location to look for Org files. There is no need
2028 at all to put your files into this directory. It is only used in the
2029 following situations:
2031 1. When a capture template specifies a target file that is not an
2032 absolute path. The path will then be interpreted relative to
2033 `org-directory'
2034 2. When a capture note is filed away in an interactive way (when exiting the
2035 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2036 with `org-directory' as the default path."
2037 :group 'org-refile
2038 :group 'org-remember
2039 :group 'org-capture
2040 :type 'directory)
2042 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2043 "Default target for storing notes.
2044 Used as a fall back file for org-remember.el and org-capture.el, for
2045 templates that do not specify a target file."
2046 :group 'org-refile
2047 :group 'org-remember
2048 :group 'org-capture
2049 :type '(choice
2050 (const :tag "Default from remember-data-file" nil)
2051 file))
2053 (defcustom org-goto-interface 'outline
2054 "The default interface to be used for `org-goto'.
2055 Allowed values are:
2056 outline The interface shows an outline of the relevant file
2057 and the correct heading is found by moving through
2058 the outline or by searching with incremental search.
2059 outline-path-completion Headlines in the current buffer are offered via
2060 completion. This is the interface also used by
2061 the refile command."
2062 :group 'org-refile
2063 :type '(choice
2064 (const :tag "Outline" outline)
2065 (const :tag "Outline-path-completion" outline-path-completion)))
2067 (defcustom org-goto-max-level 5
2068 "Maximum target level when running `org-goto' with refile interface."
2069 :group 'org-refile
2070 :type 'integer)
2072 (defcustom org-reverse-note-order nil
2073 "Non-nil means store new notes at the beginning of a file or entry.
2074 When nil, new notes will be filed to the end of a file or entry.
2075 This can also be a list with cons cells of regular expressions that
2076 are matched against file names, and values."
2077 :group 'org-remember
2078 :group 'org-capture
2079 :group 'org-refile
2080 :type '(choice
2081 (const :tag "Reverse always" t)
2082 (const :tag "Reverse never" nil)
2083 (repeat :tag "By file name regexp"
2084 (cons regexp boolean))))
2086 (defcustom org-log-refile nil
2087 "Information to record when a task is refiled.
2089 Possible values are:
2091 nil Don't add anything
2092 time Add a time stamp to the task
2093 note Prompt for a note and add it with template `org-log-note-headings'
2095 This option can also be set with on a per-file-basis with
2097 #+STARTUP: nologrefile
2098 #+STARTUP: logrefile
2099 #+STARTUP: lognoterefile
2101 You can have local logging settings for a subtree by setting the LOGGING
2102 property to one or more of these keywords.
2104 When bulk-refiling from the agenda, the value `note' is forbidden and
2105 will temporarily be changed to `time'."
2106 :group 'org-refile
2107 :group 'org-progress
2108 :version "24.1"
2109 :type '(choice
2110 (const :tag "No logging" nil)
2111 (const :tag "Record timestamp" time)
2112 (const :tag "Record timestamp with note." note)))
2114 (defcustom org-refile-targets nil
2115 "Targets for refiling entries with \\[org-refile].
2116 This is a list of cons cells. Each cell contains:
2117 - a specification of the files to be considered, either a list of files,
2118 or a symbol whose function or variable value will be used to retrieve
2119 a file name or a list of file names. If you use `org-agenda-files' for
2120 that, all agenda files will be scanned for targets. Nil means consider
2121 headings in the current buffer.
2122 - A specification of how to find candidate refile targets. This may be
2123 any of:
2124 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2125 This tag has to be present in all target headlines, inheritance will
2126 not be considered.
2127 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2128 todo keyword.
2129 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2130 headlines that are refiling targets.
2131 - a cons cell (:level . N). Any headline of level N is considered a target.
2132 Note that, when `org-odd-levels-only' is set, level corresponds to
2133 order in hierarchy, not to the number of stars.
2134 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2135 Note that, when `org-odd-levels-only' is set, level corresponds to
2136 order in hierarchy, not to the number of stars.
2138 Each element of this list generates a set of possible targets.
2139 The union of these sets is presented (with completion) to
2140 the user by `org-refile'.
2142 You can set the variable `org-refile-target-verify-function' to a function
2143 to verify each headline found by the simple criteria above.
2145 When this variable is nil, all top-level headlines in the current buffer
2146 are used, equivalent to the value `((nil . (:level . 1))'."
2147 :group 'org-refile
2148 :type '(repeat
2149 (cons
2150 (choice :value org-agenda-files
2151 (const :tag "All agenda files" org-agenda-files)
2152 (const :tag "Current buffer" nil)
2153 (function) (variable) (file))
2154 (choice :tag "Identify target headline by"
2155 (cons :tag "Specific tag" (const :value :tag) (string))
2156 (cons :tag "TODO keyword" (const :value :todo) (string))
2157 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2158 (cons :tag "Level number" (const :value :level) (integer))
2159 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2161 (defcustom org-refile-target-verify-function nil
2162 "Function to verify if the headline at point should be a refile target.
2163 The function will be called without arguments, with point at the
2164 beginning of the headline. It should return t and leave point
2165 where it is if the headline is a valid target for refiling.
2167 If the target should not be selected, the function must return nil.
2168 In addition to this, it may move point to a place from where the search
2169 should be continued. For example, the function may decide that the entire
2170 subtree of the current entry should be excluded and move point to the end
2171 of the subtree."
2172 :group 'org-refile
2173 :type '(choice
2174 (const nil)
2175 (function)))
2177 (defcustom org-refile-use-cache nil
2178 "Non-nil means cache refile targets to speed up the process.
2179 The cache for a particular file will be updated automatically when
2180 the buffer has been killed, or when any of the marker used for flagging
2181 refile targets no longer points at a live buffer.
2182 If you have added new entries to a buffer that might themselves be targets,
2183 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2184 find that easier, `C-u C-u C-u C-c C-w'."
2185 :group 'org-refile
2186 :version "24.1"
2187 :type 'boolean)
2189 (defcustom org-refile-use-outline-path nil
2190 "Non-nil means provide refile targets as paths.
2191 So a level 3 headline will be available as level1/level2/level3.
2193 When the value is `file', also include the file name (without directory)
2194 into the path. In this case, you can also stop the completion after
2195 the file name, to get entries inserted as top level in the file.
2197 When `full-file-path', include the full file path."
2198 :group 'org-refile
2199 :type '(choice
2200 (const :tag "Not" nil)
2201 (const :tag "Yes" t)
2202 (const :tag "Start with file name" file)
2203 (const :tag "Start with full file path" full-file-path)))
2205 (defcustom org-outline-path-complete-in-steps t
2206 "Non-nil means complete the outline path in hierarchical steps.
2207 When Org-mode uses the refile interface to select an outline path
2208 \(see variable `org-refile-use-outline-path'), the completion of
2209 the path can be done is a single go, or if can be done in steps down
2210 the headline hierarchy. Going in steps is probably the best if you
2211 do not use a special completion package like `ido' or `icicles'.
2212 However, when using these packages, going in one step can be very
2213 fast, while still showing the whole path to the entry."
2214 :group 'org-refile
2215 :type 'boolean)
2217 (defcustom org-refile-allow-creating-parent-nodes nil
2218 "Non-nil means allow to create new nodes as refile targets.
2219 New nodes are then created by adding \"/new node name\" to the completion
2220 of an existing node. When the value of this variable is `confirm',
2221 new node creation must be confirmed by the user (recommended)
2222 When nil, the completion must match an existing entry.
2224 Note that, if the new heading is not seen by the criteria
2225 listed in `org-refile-targets', multiple instances of the same
2226 heading would be created by trying again to file under the new
2227 heading."
2228 :group 'org-refile
2229 :type '(choice
2230 (const :tag "Never" nil)
2231 (const :tag "Always" t)
2232 (const :tag "Prompt for confirmation" confirm)))
2234 (defcustom org-refile-active-region-within-subtree nil
2235 "Non-nil means also refile active region within a subtree.
2237 By default `org-refile' doesn't allow refiling regions if they
2238 don't contain a set of subtrees, but it might be convenient to
2239 do so sometimes: in that case, the first line of the region is
2240 converted to a headline before refiling."
2241 :group 'org-refile
2242 :version "24.1"
2243 :type 'boolean)
2245 (defgroup org-todo nil
2246 "Options concerning TODO items in Org-mode."
2247 :tag "Org TODO"
2248 :group 'org)
2250 (defgroup org-progress nil
2251 "Options concerning Progress logging in Org-mode."
2252 :tag "Org Progress"
2253 :group 'org-time)
2255 (defvar org-todo-interpretation-widgets
2256 '((:tag "Sequence (cycling hits every state)" sequence)
2257 (:tag "Type (cycling directly to DONE)" type))
2258 "The available interpretation symbols for customizing `org-todo-keywords'.
2259 Interested libraries should add to this list.")
2261 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2262 "List of TODO entry keyword sequences and their interpretation.
2263 \\<org-mode-map>This is a list of sequences.
2265 Each sequence starts with a symbol, either `sequence' or `type',
2266 indicating if the keywords should be interpreted as a sequence of
2267 action steps, or as different types of TODO items. The first
2268 keywords are states requiring action - these states will select a headline
2269 for inclusion into the global TODO list Org-mode produces. If one of
2270 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2271 signify that no further action is necessary. If \"|\" is not found,
2272 the last keyword is treated as the only DONE state of the sequence.
2274 The command \\[org-todo] cycles an entry through these states, and one
2275 additional state where no keyword is present. For details about this
2276 cycling, see the manual.
2278 TODO keywords and interpretation can also be set on a per-file basis with
2279 the special #+SEQ_TODO and #+TYP_TODO lines.
2281 Each keyword can optionally specify a character for fast state selection
2282 \(in combination with the variable `org-use-fast-todo-selection')
2283 and specifiers for state change logging, using the same syntax that
2284 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2285 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2286 indicates to record a time stamp each time this state is selected.
2288 Each keyword may also specify if a timestamp or a note should be
2289 recorded when entering or leaving the state, by adding additional
2290 characters in the parenthesis after the keyword. This looks like this:
2291 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2292 record only the time of the state change. With X and Y being either
2293 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2294 Y when leaving the state if and only if the *target* state does not
2295 define X. You may omit any of the fast-selection key or X or /Y,
2296 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2298 For backward compatibility, this variable may also be just a list
2299 of keywords. In this case the interpretation (sequence or type) will be
2300 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2301 :group 'org-todo
2302 :group 'org-keywords
2303 :type '(choice
2304 (repeat :tag "Old syntax, just keywords"
2305 (string :tag "Keyword"))
2306 (repeat :tag "New syntax"
2307 (cons
2308 (choice
2309 :tag "Interpretation"
2310 ;;Quick and dirty way to see
2311 ;;`org-todo-interpretations'. This takes the
2312 ;;place of item arguments
2313 :convert-widget
2314 (lambda (widget)
2315 (widget-put widget
2316 :args (mapcar
2317 #'(lambda (x)
2318 (widget-convert
2319 (cons 'const x)))
2320 org-todo-interpretation-widgets))
2321 widget))
2322 (repeat
2323 (string :tag "Keyword"))))))
2325 (defvar org-todo-keywords-1 nil
2326 "All TODO and DONE keywords active in a buffer.")
2327 (make-variable-buffer-local 'org-todo-keywords-1)
2328 (defvar org-todo-keywords-for-agenda nil)
2329 (defvar org-done-keywords-for-agenda nil)
2330 (defvar org-drawers-for-agenda nil)
2331 (defvar org-todo-keyword-alist-for-agenda nil)
2332 (defvar org-tag-alist-for-agenda nil
2333 "Alist of all tags from all agenda files.")
2334 (defvar org-tag-groups-alist-for-agenda nil
2335 "Alist of all groups tags from all current agenda files.")
2336 (defvar org-tag-groups-alist nil)
2337 (make-variable-buffer-local 'org-tag-groups-alist)
2338 (defvar org-agenda-contributing-files nil)
2339 (defvar org-not-done-keywords nil)
2340 (make-variable-buffer-local 'org-not-done-keywords)
2341 (defvar org-done-keywords nil)
2342 (make-variable-buffer-local 'org-done-keywords)
2343 (defvar org-todo-heads nil)
2344 (make-variable-buffer-local 'org-todo-heads)
2345 (defvar org-todo-sets nil)
2346 (make-variable-buffer-local 'org-todo-sets)
2347 (defvar org-todo-log-states nil)
2348 (make-variable-buffer-local 'org-todo-log-states)
2349 (defvar org-todo-kwd-alist nil)
2350 (make-variable-buffer-local 'org-todo-kwd-alist)
2351 (defvar org-todo-key-alist nil)
2352 (make-variable-buffer-local 'org-todo-key-alist)
2353 (defvar org-todo-key-trigger nil)
2354 (make-variable-buffer-local 'org-todo-key-trigger)
2356 (defcustom org-todo-interpretation 'sequence
2357 "Controls how TODO keywords are interpreted.
2358 This variable is in principle obsolete and is only used for
2359 backward compatibility, if the interpretation of todo keywords is
2360 not given already in `org-todo-keywords'. See that variable for
2361 more information."
2362 :group 'org-todo
2363 :group 'org-keywords
2364 :type '(choice (const sequence)
2365 (const type)))
2367 (defcustom org-use-fast-todo-selection t
2368 "Non-nil means use the fast todo selection scheme with C-c C-t.
2369 This variable describes if and under what circumstances the cycling
2370 mechanism for TODO keywords will be replaced by a single-key, direct
2371 selection scheme.
2373 When nil, fast selection is never used.
2375 When the symbol `prefix', it will be used when `org-todo' is called
2376 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2377 `C-u t' in an agenda buffer.
2379 When t, fast selection is used by default. In this case, the prefix
2380 argument forces cycling instead.
2382 In all cases, the special interface is only used if access keys have
2383 actually been assigned by the user, i.e. if keywords in the configuration
2384 are followed by a letter in parenthesis, like TODO(t)."
2385 :group 'org-todo
2386 :type '(choice
2387 (const :tag "Never" nil)
2388 (const :tag "By default" t)
2389 (const :tag "Only with C-u C-c C-t" prefix)))
2391 (defcustom org-provide-todo-statistics t
2392 "Non-nil means update todo statistics after insert and toggle.
2393 ALL-HEADLINES means update todo statistics by including headlines
2394 with no TODO keyword as well, counting them as not done.
2395 A list of TODO keywords means the same, but skip keywords that are
2396 not in this list.
2398 When this is set, todo statistics is updated in the parent of the
2399 current entry each time a todo state is changed."
2400 :group 'org-todo
2401 :type '(choice
2402 (const :tag "Yes, only for TODO entries" t)
2403 (const :tag "Yes, including all entries" 'all-headlines)
2404 (repeat :tag "Yes, for TODOs in this list"
2405 (string :tag "TODO keyword"))
2406 (other :tag "No TODO statistics" nil)))
2408 (defcustom org-hierarchical-todo-statistics t
2409 "Non-nil means TODO statistics covers just direct children.
2410 When nil, all entries in the subtree are considered.
2411 This has only an effect if `org-provide-todo-statistics' is set.
2412 To set this to nil for only a single subtree, use a COOKIE_DATA
2413 property and include the word \"recursive\" into the value."
2414 :group 'org-todo
2415 :type 'boolean)
2417 (defcustom org-after-todo-state-change-hook nil
2418 "Hook which is run after the state of a TODO item was changed.
2419 The new state (a string with a TODO keyword, or nil) is available in the
2420 Lisp variable `org-state'."
2421 :group 'org-todo
2422 :type 'hook)
2424 (defvar org-blocker-hook nil
2425 "Hook for functions that are allowed to block a state change.
2427 Functions in this hook should not modify the buffer.
2428 Each function gets as its single argument a property list,
2429 see `org-trigger-hook' for more information about this list.
2431 If any of the functions in this hook returns nil, the state change
2432 is blocked.")
2434 (defvar org-trigger-hook nil
2435 "Hook for functions that are triggered by a state change.
2437 Each function gets as its single argument a property list with at
2438 least the following elements:
2440 (:type type-of-change :position pos-at-entry-start
2441 :from old-state :to new-state)
2443 Depending on the type, more properties may be present.
2445 This mechanism is currently implemented for:
2447 TODO state changes
2448 ------------------
2449 :type todo-state-change
2450 :from previous state (keyword as a string), or nil, or a symbol
2451 'todo' or 'done', to indicate the general type of state.
2452 :to new state, like in :from")
2454 (defcustom org-enforce-todo-dependencies nil
2455 "Non-nil means undone TODO entries will block switching the parent to DONE.
2456 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2457 be blocked if any prior sibling is not yet done.
2458 Finally, if the parent is blocked because of ordered siblings of its own,
2459 the child will also be blocked."
2460 :set (lambda (var val)
2461 (set var val)
2462 (if val
2463 (add-hook 'org-blocker-hook
2464 'org-block-todo-from-children-or-siblings-or-parent)
2465 (remove-hook 'org-blocker-hook
2466 'org-block-todo-from-children-or-siblings-or-parent)))
2467 :group 'org-todo
2468 :type 'boolean)
2470 (defcustom org-enforce-todo-checkbox-dependencies nil
2471 "Non-nil means unchecked boxes will block switching the parent to DONE.
2472 When this is nil, checkboxes have no influence on switching TODO states.
2473 When non-nil, you first need to check off all check boxes before the TODO
2474 entry can be switched to DONE.
2475 This variable needs to be set before org.el is loaded, and you need to
2476 restart Emacs after a change to make the change effective. The only way
2477 to change is while Emacs is running is through the customize interface."
2478 :set (lambda (var val)
2479 (set var val)
2480 (if val
2481 (add-hook 'org-blocker-hook
2482 'org-block-todo-from-checkboxes)
2483 (remove-hook 'org-blocker-hook
2484 'org-block-todo-from-checkboxes)))
2485 :group 'org-todo
2486 :type 'boolean)
2488 (defcustom org-treat-insert-todo-heading-as-state-change nil
2489 "Non-nil means inserting a TODO heading is treated as state change.
2490 So when the command \\[org-insert-todo-heading] is used, state change
2491 logging will apply if appropriate. When nil, the new TODO item will
2492 be inserted directly, and no logging will take place."
2493 :group 'org-todo
2494 :type 'boolean)
2496 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2497 "Non-nil means switching TODO states with S-cursor counts as state change.
2498 This is the default behavior. However, setting this to nil allows a
2499 convenient way to select a TODO state and bypass any logging associated
2500 with that."
2501 :group 'org-todo
2502 :type 'boolean)
2504 (defcustom org-todo-state-tags-triggers nil
2505 "Tag changes that should be triggered by TODO state changes.
2506 This is a list. Each entry is
2508 (state-change (tag . flag) .......)
2510 State-change can be a string with a state, and empty string to indicate the
2511 state that has no TODO keyword, or it can be one of the symbols `todo'
2512 or `done', meaning any not-done or done state, respectively."
2513 :group 'org-todo
2514 :group 'org-tags
2515 :type '(repeat
2516 (cons (choice :tag "When changing to"
2517 (const :tag "Not-done state" todo)
2518 (const :tag "Done state" done)
2519 (string :tag "State"))
2520 (repeat
2521 (cons :tag "Tag action"
2522 (string :tag "Tag")
2523 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2525 (defcustom org-log-done nil
2526 "Information to record when a task moves to the DONE state.
2528 Possible values are:
2530 nil Don't add anything, just change the keyword
2531 time Add a time stamp to the task
2532 note Prompt for a note and add it with template `org-log-note-headings'
2534 This option can also be set with on a per-file-basis with
2536 #+STARTUP: nologdone
2537 #+STARTUP: logdone
2538 #+STARTUP: lognotedone
2540 You can have local logging settings for a subtree by setting the LOGGING
2541 property to one or more of these keywords."
2542 :group 'org-todo
2543 :group 'org-progress
2544 :type '(choice
2545 (const :tag "No logging" nil)
2546 (const :tag "Record CLOSED timestamp" time)
2547 (const :tag "Record CLOSED timestamp with note." note)))
2549 ;; Normalize old uses of org-log-done.
2550 (cond
2551 ((eq org-log-done t) (setq org-log-done 'time))
2552 ((and (listp org-log-done) (memq 'done org-log-done))
2553 (setq org-log-done 'note)))
2555 (defcustom org-log-reschedule nil
2556 "Information to record when the scheduling date of a tasks is modified.
2558 Possible values are:
2560 nil Don't add anything, just change the date
2561 time Add a time stamp to the task
2562 note Prompt for a note and add it with template `org-log-note-headings'
2564 This option can also be set with on a per-file-basis with
2566 #+STARTUP: nologreschedule
2567 #+STARTUP: logreschedule
2568 #+STARTUP: lognotereschedule"
2569 :group 'org-todo
2570 :group 'org-progress
2571 :type '(choice
2572 (const :tag "No logging" nil)
2573 (const :tag "Record timestamp" time)
2574 (const :tag "Record timestamp with note." note)))
2576 (defcustom org-log-redeadline nil
2577 "Information to record when the deadline date of a tasks is modified.
2579 Possible values are:
2581 nil Don't add anything, just change the date
2582 time Add a time stamp to the task
2583 note Prompt for a note and add it with template `org-log-note-headings'
2585 This option can also be set with on a per-file-basis with
2587 #+STARTUP: nologredeadline
2588 #+STARTUP: logredeadline
2589 #+STARTUP: lognoteredeadline
2591 You can have local logging settings for a subtree by setting the LOGGING
2592 property to one or more of these keywords."
2593 :group 'org-todo
2594 :group 'org-progress
2595 :type '(choice
2596 (const :tag "No logging" nil)
2597 (const :tag "Record timestamp" time)
2598 (const :tag "Record timestamp with note." note)))
2600 (defcustom org-log-note-clock-out nil
2601 "Non-nil means record a note when clocking out of an item.
2602 This can also be configured on a per-file basis by adding one of
2603 the following lines anywhere in the buffer:
2605 #+STARTUP: lognoteclock-out
2606 #+STARTUP: nolognoteclock-out"
2607 :group 'org-todo
2608 :group 'org-progress
2609 :type 'boolean)
2611 (defcustom org-log-done-with-time t
2612 "Non-nil means the CLOSED time stamp will contain date and time.
2613 When nil, only the date will be recorded."
2614 :group 'org-progress
2615 :type 'boolean)
2617 (defcustom org-log-note-headings
2618 '((done . "CLOSING NOTE %t")
2619 (state . "State %-12s from %-12S %t")
2620 (note . "Note taken on %t")
2621 (reschedule . "Rescheduled from %S on %t")
2622 (delschedule . "Not scheduled, was %S on %t")
2623 (redeadline . "New deadline from %S on %t")
2624 (deldeadline . "Removed deadline, was %S on %t")
2625 (refile . "Refiled on %t")
2626 (clock-out . ""))
2627 "Headings for notes added to entries.
2628 The value is an alist, with the car being a symbol indicating the note
2629 context, and the cdr is the heading to be used. The heading may also be the
2630 empty string.
2631 %t in the heading will be replaced by a time stamp.
2632 %T will be an active time stamp instead the default inactive one
2633 %d will be replaced by a short-format time stamp.
2634 %D will be replaced by an active short-format time stamp.
2635 %s will be replaced by the new TODO state, in double quotes.
2636 %S will be replaced by the old TODO state, in double quotes.
2637 %u will be replaced by the user name.
2638 %U will be replaced by the full user name.
2640 In fact, it is not a good idea to change the `state' entry, because
2641 agenda log mode depends on the format of these entries."
2642 :group 'org-todo
2643 :group 'org-progress
2644 :type '(list :greedy t
2645 (cons (const :tag "Heading when closing an item" done) string)
2646 (cons (const :tag
2647 "Heading when changing todo state (todo sequence only)"
2648 state) string)
2649 (cons (const :tag "Heading when just taking a note" note) string)
2650 (cons (const :tag "Heading when clocking out" clock-out) string)
2651 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2652 (cons (const :tag "Heading when rescheduling" reschedule) string)
2653 (cons (const :tag "Heading when changing deadline" redeadline) string)
2654 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2655 (cons (const :tag "Heading when refiling" refile) string)))
2657 (unless (assq 'note org-log-note-headings)
2658 (push '(note . "%t") org-log-note-headings))
2660 (defcustom org-log-into-drawer nil
2661 "Non-nil means insert state change notes and time stamps into a drawer.
2662 When nil, state changes notes will be inserted after the headline and
2663 any scheduling and clock lines, but not inside a drawer.
2665 The value of this variable should be the name of the drawer to use.
2666 LOGBOOK is proposed as the default drawer for this purpose, you can
2667 also set this to a string to define the drawer of your choice.
2669 A value of t is also allowed, representing \"LOGBOOK\".
2671 A value of t or nil can also be set with on a per-file-basis with
2673 #+STARTUP: logdrawer
2674 #+STARTUP: nologdrawer
2676 If this variable is set, `org-log-state-notes-insert-after-drawers'
2677 will be ignored.
2679 You can set the property LOG_INTO_DRAWER to overrule this setting for
2680 a subtree."
2681 :group 'org-todo
2682 :group 'org-progress
2683 :type '(choice
2684 (const :tag "Not into a drawer" nil)
2685 (const :tag "LOGBOOK" t)
2686 (string :tag "Other")))
2688 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2690 (defun org-log-into-drawer ()
2691 "Return the value of `org-log-into-drawer', but let properties overrule.
2692 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2693 used instead of the default value."
2694 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2695 (cond
2696 ((not p) org-log-into-drawer)
2697 ((equal p "nil") nil)
2698 ((equal p "t") "LOGBOOK")
2699 (t p))))
2701 (defcustom org-log-state-notes-insert-after-drawers nil
2702 "Non-nil means insert state change notes after any drawers in entry.
2703 Only the drawers that *immediately* follow the headline and the
2704 deadline/scheduled line are skipped.
2705 When nil, insert notes right after the heading and perhaps the line
2706 with deadline/scheduling if present.
2708 This variable will have no effect if `org-log-into-drawer' is
2709 set."
2710 :group 'org-todo
2711 :group 'org-progress
2712 :type 'boolean)
2714 (defcustom org-log-states-order-reversed t
2715 "Non-nil means the latest state note will be directly after heading.
2716 When nil, the state change notes will be ordered according to time.
2718 This option can also be set with on a per-file-basis with
2720 #+STARTUP: logstatesreversed
2721 #+STARTUP: nologstatesreversed"
2722 :group 'org-todo
2723 :group 'org-progress
2724 :type 'boolean)
2726 (defcustom org-todo-repeat-to-state nil
2727 "The TODO state to which a repeater should return the repeating task.
2728 By default this is the first task in a TODO sequence, or the previous state
2729 in a TODO_TYP set. But you can specify another task here.
2730 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2731 :group 'org-todo
2732 :version "24.1"
2733 :type '(choice (const :tag "Head of sequence" nil)
2734 (string :tag "Specific state")))
2736 (defcustom org-log-repeat 'time
2737 "Non-nil means record moving through the DONE state when triggering repeat.
2738 An auto-repeating task is immediately switched back to TODO when
2739 marked DONE. If you are not logging state changes (by adding \"@\"
2740 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2741 record a closing note, there will be no record of the task moving
2742 through DONE. This variable forces taking a note anyway.
2744 nil Don't force a record
2745 time Record a time stamp
2746 note Prompt for a note and add it with template `org-log-note-headings'
2748 This option can also be set with on a per-file-basis with
2750 #+STARTUP: nologrepeat
2751 #+STARTUP: logrepeat
2752 #+STARTUP: lognoterepeat
2754 You can have local logging settings for a subtree by setting the LOGGING
2755 property to one or more of these keywords."
2756 :group 'org-todo
2757 :group 'org-progress
2758 :type '(choice
2759 (const :tag "Don't force a record" nil)
2760 (const :tag "Force recording the DONE state" time)
2761 (const :tag "Force recording a note with the DONE state" note)))
2764 (defgroup org-priorities nil
2765 "Priorities in Org-mode."
2766 :tag "Org Priorities"
2767 :group 'org-todo)
2769 (defcustom org-enable-priority-commands t
2770 "Non-nil means priority commands are active.
2771 When nil, these commands will be disabled, so that you never accidentally
2772 set a priority."
2773 :group 'org-priorities
2774 :type 'boolean)
2776 (defcustom org-highest-priority ?A
2777 "The highest priority of TODO items. A character like ?A, ?B etc.
2778 Must have a smaller ASCII number than `org-lowest-priority'."
2779 :group 'org-priorities
2780 :type 'character)
2782 (defcustom org-lowest-priority ?C
2783 "The lowest priority of TODO items. A character like ?A, ?B etc.
2784 Must have a larger ASCII number than `org-highest-priority'."
2785 :group 'org-priorities
2786 :type 'character)
2788 (defcustom org-default-priority ?B
2789 "The default priority of TODO items.
2790 This is the priority an item gets if no explicit priority is given.
2791 When starting to cycle on an empty priority the first step in the cycle
2792 depends on `org-priority-start-cycle-with-default'. The resulting first
2793 step priority must not exceed the range from `org-highest-priority' to
2794 `org-lowest-priority' which means that `org-default-priority' has to be
2795 in this range exclusive or inclusive the range boundaries. Else the
2796 first step refuses to set the default and the second will fall back
2797 to (depending on the command used) the highest or lowest priority."
2798 :group 'org-priorities
2799 :type 'character)
2801 (defcustom org-priority-start-cycle-with-default t
2802 "Non-nil means start with default priority when starting to cycle.
2803 When this is nil, the first step in the cycle will be (depending on the
2804 command used) one higher or lower than the default priority.
2805 See also `org-default-priority'."
2806 :group 'org-priorities
2807 :type 'boolean)
2809 (defcustom org-get-priority-function nil
2810 "Function to extract the priority from a string.
2811 The string is normally the headline. If this is nil Org computes the
2812 priority from the priority cookie like [#A] in the headline. It returns
2813 an integer, increasing by 1000 for each priority level.
2814 The user can set a different function here, which should take a string
2815 as an argument and return the numeric priority."
2816 :group 'org-priorities
2817 :version "24.1"
2818 :type '(choice
2819 (const nil)
2820 (function)))
2822 (defgroup org-time nil
2823 "Options concerning time stamps and deadlines in Org-mode."
2824 :tag "Org Time"
2825 :group 'org)
2827 (defcustom org-insert-labeled-timestamps-at-point nil
2828 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2829 When nil, these labeled time stamps are forces into the second line of an
2830 entry, just after the headline. When scheduling from the global TODO list,
2831 the time stamp will always be forced into the second line."
2832 :group 'org-time
2833 :type 'boolean)
2835 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2836 "Formats for `format-time-string' which are used for time stamps.
2837 It is not recommended to change this constant.")
2839 (defcustom org-time-stamp-rounding-minutes '(0 5)
2840 "Number of minutes to round time stamps to.
2841 These are two values, the first applies when first creating a time stamp.
2842 The second applies when changing it with the commands `S-up' and `S-down'.
2843 When changing the time stamp, this means that it will change in steps
2844 of N minutes, as given by the second value.
2846 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2847 numbers should be factors of 60, so for example 5, 10, 15.
2849 When this is larger than 1, you can still force an exact time stamp by using
2850 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2851 and by using a prefix arg to `S-up/down' to specify the exact number
2852 of minutes to shift."
2853 :group 'org-time
2854 :get #'(lambda (var) ; Make sure both elements are there
2855 (if (integerp (default-value var))
2856 (list (default-value var) 5)
2857 (default-value var)))
2858 :type '(list
2859 (integer :tag "when inserting times")
2860 (integer :tag "when modifying times")))
2862 ;; Normalize old customizations of this variable.
2863 (when (integerp org-time-stamp-rounding-minutes)
2864 (setq org-time-stamp-rounding-minutes
2865 (list org-time-stamp-rounding-minutes
2866 org-time-stamp-rounding-minutes)))
2868 (defcustom org-display-custom-times nil
2869 "Non-nil means overlay custom formats over all time stamps.
2870 The formats are defined through the variable `org-time-stamp-custom-formats'.
2871 To turn this on on a per-file basis, insert anywhere in the file:
2872 #+STARTUP: customtime"
2873 :group 'org-time
2874 :set 'set-default
2875 :type 'sexp)
2876 (make-variable-buffer-local 'org-display-custom-times)
2878 (defcustom org-time-stamp-custom-formats
2879 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2880 "Custom formats for time stamps. See `format-time-string' for the syntax.
2881 These are overlaid over the default ISO format if the variable
2882 `org-display-custom-times' is set. Time like %H:%M should be at the
2883 end of the second format. The custom formats are also honored by export
2884 commands, if custom time display is turned on at the time of export."
2885 :group 'org-time
2886 :type 'sexp)
2888 (defun org-time-stamp-format (&optional long inactive)
2889 "Get the right format for a time string."
2890 (let ((f (if long (cdr org-time-stamp-formats)
2891 (car org-time-stamp-formats))))
2892 (if inactive
2893 (concat "[" (substring f 1 -1) "]")
2894 f)))
2896 (defcustom org-time-clocksum-format
2897 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2898 "The format string used when creating CLOCKSUM lines.
2899 This is also used when Org mode generates a time duration.
2901 The value can be a single format string containing two
2902 %-sequences, which will be filled with the number of hours and
2903 minutes in that order.
2905 Alternatively, the value can be a plist associating any of the
2906 keys :years, :months, :weeks, :days, :hours or :minutes with
2907 format strings. The time duration is formatted using only the
2908 time components that are needed and concatenating the results.
2909 If a time unit in absent, it falls back to the next smallest
2910 unit.
2912 The keys :require-years, :require-months, :require-days,
2913 :require-weeks, :require-hours, :require-minutes are also
2914 meaningful. A non-nil value for these keys indicates that the
2915 corresponding time component should always be included, even if
2916 its value is 0.
2919 For example,
2921 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2922 :require-minutes t)
2924 means durations longer than a day will be expressed in days,
2925 hours and minutes, and durations less than a day will always be
2926 expressed in hours and minutes (even for durations less than an
2927 hour).
2929 The value
2931 \(:days \"%dd\" :minutes \"%dm\")
2933 means durations longer than a day will be expressed in days and
2934 minutes, and durations less than a day will be expressed entirely
2935 in minutes (even for durations longer than an hour)."
2936 :group 'org-time
2937 :group 'org-clock
2938 :version "24.4"
2939 :package-version '(Org . "8.0")
2940 :type '(choice (string :tag "Format string")
2941 (set :tag "Plist"
2942 (group :inline t (const :tag "Years" :years)
2943 (string :tag "Format string"))
2944 (group :inline t
2945 (const :tag "Always show years" :require-years)
2946 (const t))
2947 (group :inline t (const :tag "Months" :months)
2948 (string :tag "Format string"))
2949 (group :inline t
2950 (const :tag "Always show months" :require-months)
2951 (const t))
2952 (group :inline t (const :tag "Weeks" :weeks)
2953 (string :tag "Format string"))
2954 (group :inline t
2955 (const :tag "Always show weeks" :require-weeks)
2956 (const t))
2957 (group :inline t (const :tag "Days" :days)
2958 (string :tag "Format string"))
2959 (group :inline t
2960 (const :tag "Always show days" :require-days)
2961 (const t))
2962 (group :inline t (const :tag "Hours" :hours)
2963 (string :tag "Format string"))
2964 (group :inline t
2965 (const :tag "Always show hours" :require-hours)
2966 (const t))
2967 (group :inline t (const :tag "Minutes" :minutes)
2968 (string :tag "Format string"))
2969 (group :inline t
2970 (const :tag "Always show minutes" :require-minutes)
2971 (const t)))))
2973 (defcustom org-time-clocksum-use-fractional nil
2974 "When non-nil, \\[org-clock-display] uses fractional times.
2975 See `org-time-clocksum-format' for more on time clock formats."
2976 :group 'org-time
2977 :group 'org-clock
2978 :version "24.3"
2979 :type 'boolean)
2981 (defcustom org-time-clocksum-use-effort-durations nil
2982 "When non-nil, \\[org-clock-display] uses effort durations.
2983 E.g. by default, one day is considered to be a 8 hours effort,
2984 so a task that has been clocked for 16 hours will be displayed
2985 as during 2 days in the clock display or in the clocktable.
2987 See `org-effort-durations' on how to set effort durations
2988 and `org-time-clocksum-format' for more on time clock formats."
2989 :group 'org-time
2990 :group 'org-clock
2991 :version "24.4"
2992 :package-version '(Org . "8.0")
2993 :type 'boolean)
2995 (defcustom org-time-clocksum-fractional-format "%.2f"
2996 "The format string used when creating CLOCKSUM lines,
2997 or when Org mode generates a time duration, if
2998 `org-time-clocksum-use-fractional' is enabled.
3000 The value can be a single format string containing one
3001 %-sequence, which will be filled with the number of hours as
3002 a float.
3004 Alternatively, the value can be a plist associating any of the
3005 keys :years, :months, :weeks, :days, :hours or :minutes with
3006 a format string. The time duration is formatted using the
3007 largest time unit which gives a non-zero integer part. If all
3008 specified formats have zero integer part, the smallest time unit
3009 is used."
3010 :group 'org-time
3011 :type '(choice (string :tag "Format string")
3012 (set (group :inline t (const :tag "Years" :years)
3013 (string :tag "Format string"))
3014 (group :inline t (const :tag "Months" :months)
3015 (string :tag "Format string"))
3016 (group :inline t (const :tag "Weeks" :weeks)
3017 (string :tag "Format string"))
3018 (group :inline t (const :tag "Days" :days)
3019 (string :tag "Format string"))
3020 (group :inline t (const :tag "Hours" :hours)
3021 (string :tag "Format string"))
3022 (group :inline t (const :tag "Minutes" :minutes)
3023 (string :tag "Format string")))))
3025 (defcustom org-deadline-warning-days 14
3026 "Number of days before expiration during which a deadline becomes active.
3027 This variable governs the display in sparse trees and in the agenda.
3028 When 0 or negative, it means use this number (the absolute value of it)
3029 even if a deadline has a different individual lead time specified.
3031 Custom commands can set this variable in the options section."
3032 :group 'org-time
3033 :group 'org-agenda-daily/weekly
3034 :type 'integer)
3036 (defcustom org-scheduled-delay-days 0
3037 "Number of days before a scheduled item becomes active.
3038 This variable governs the display in sparse trees and in the agenda.
3039 The default value (i.e. 0) means: don't delay scheduled item.
3040 When negative, it means use this number (the absolute value of it)
3041 even if a scheduled item has a different individual delay time
3042 specified.
3044 Custom commands can set this variable in the options section."
3045 :group 'org-time
3046 :group 'org-agenda-daily/weekly
3047 :version "24.4"
3048 :package-version '(Org . "8.0")
3049 :type 'integer)
3051 (defcustom org-read-date-prefer-future t
3052 "Non-nil means assume future for incomplete date input from user.
3053 This affects the following situations:
3054 1. The user gives a month but not a year.
3055 For example, if it is April and you enter \"feb 2\", this will be read
3056 as Feb 2, *next* year. \"May 5\", however, will be this year.
3057 2. The user gives a day, but no month.
3058 For example, if today is the 15th, and you enter \"3\", Org-mode will
3059 read this as the third of *next* month. However, if you enter \"17\",
3060 it will be considered as *this* month.
3062 If you set this variable to the symbol `time', then also the following
3063 will work:
3065 3. If the user gives a time.
3066 If the time is before now, it will be interpreted as tomorrow.
3068 Currently none of this works for ISO week specifications.
3070 When this option is nil, the current day, month and year will always be
3071 used as defaults.
3073 See also `org-agenda-jump-prefer-future'."
3074 :group 'org-time
3075 :type '(choice
3076 (const :tag "Never" nil)
3077 (const :tag "Check month and day" t)
3078 (const :tag "Check month, day, and time" time)))
3080 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3081 "Should the agenda jump command prefer the future for incomplete dates?
3082 The default is to do the same as configured in `org-read-date-prefer-future'.
3083 But you can also set a deviating value here.
3084 This may t or nil, or the symbol `org-read-date-prefer-future'."
3085 :group 'org-agenda
3086 :group 'org-time
3087 :version "24.1"
3088 :type '(choice
3089 (const :tag "Use org-read-date-prefer-future"
3090 org-read-date-prefer-future)
3091 (const :tag "Never" nil)
3092 (const :tag "Always" t)))
3094 (defcustom org-read-date-force-compatible-dates t
3095 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3097 Depending on the system Emacs is running on, certain dates cannot
3098 be represented with the type used internally to represent time.
3099 Dates between 1970-1-1 and 2038-1-1 can always be represented
3100 correctly. Some systems allow for earlier dates, some for later,
3101 some for both. One way to find out it to insert any date into an
3102 Org buffer, putting the cursor on the year and hitting S-up and
3103 S-down to test the range.
3105 When this variable is set to t, the date/time prompt will not let
3106 you specify dates outside the 1970-2037 range, so it is certain that
3107 these dates will work in whatever version of Emacs you are
3108 running, and also that you can move a file from one Emacs implementation
3109 to another. WHenever Org is forcing the year for you, it will display
3110 a message and beep.
3112 When this variable is nil, Org will check if the date is
3113 representable in the specific Emacs implementation you are using.
3114 If not, it will force a year, usually the current year, and beep
3115 to remind you. Currently this setting is not recommended because
3116 the likelihood that you will open your Org files in an Emacs that
3117 has limited date range is not negligible.
3119 A workaround for this problem is to use diary sexp dates for time
3120 stamps outside of this range."
3121 :group 'org-time
3122 :version "24.1"
3123 :type 'boolean)
3125 (defcustom org-read-date-display-live t
3126 "Non-nil means display current interpretation of date prompt live.
3127 This display will be in an overlay, in the minibuffer."
3128 :group 'org-time
3129 :type 'boolean)
3131 (defcustom org-read-date-popup-calendar t
3132 "Non-nil means pop up a calendar when prompting for a date.
3133 In the calendar, the date can be selected with mouse-1. However, the
3134 minibuffer will also be active, and you can simply enter the date as well.
3135 When nil, only the minibuffer will be available."
3136 :group 'org-time
3137 :type 'boolean)
3138 (org-defvaralias 'org-popup-calendar-for-date-prompt
3139 'org-read-date-popup-calendar)
3141 (make-obsolete-variable
3142 'org-read-date-minibuffer-setup-hook
3143 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3144 (defcustom org-read-date-minibuffer-setup-hook nil
3145 "Hook to be used to set up keys for the date/time interface.
3146 Add key definitions to `minibuffer-local-map', which will be a
3147 temporary copy.
3149 WARNING: This option is obsolete, you should use
3150 `org-read-date-minibuffer-local-map' to set up keys."
3151 :group 'org-time
3152 :type 'hook)
3154 (defcustom org-extend-today-until 0
3155 "The hour when your day really ends. Must be an integer.
3156 This has influence for the following applications:
3157 - When switching the agenda to \"today\". It it is still earlier than
3158 the time given here, the day recognized as TODAY is actually yesterday.
3159 - When a date is read from the user and it is still before the time given
3160 here, the current date and time will be assumed to be yesterday, 23:59.
3161 Also, timestamps inserted in capture templates follow this rule.
3163 IMPORTANT: This is a feature whose implementation is and likely will
3164 remain incomplete. Really, it is only here because past midnight seems to
3165 be the favorite working time of John Wiegley :-)"
3166 :group 'org-time
3167 :type 'integer)
3169 (defcustom org-use-effective-time nil
3170 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3171 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3172 \"effective time\" of any timestamps between midnight and 8am will be
3173 23:59 of the previous day."
3174 :group 'org-time
3175 :version "24.1"
3176 :type 'boolean)
3178 (defcustom org-use-last-clock-out-time-as-effective-time nil
3179 "When non-nil, use the last clock out time for `org-todo'.
3180 Note that this option has precedence over the combined use of
3181 `org-use-effective-time' and `org-extend-today-until'."
3182 :group 'org-time
3183 :version "24.4"
3184 :package-version '(Org . "8.0")
3185 :type 'boolean)
3187 (defcustom org-edit-timestamp-down-means-later nil
3188 "Non-nil means S-down will increase the time in a time stamp.
3189 When nil, S-up will increase."
3190 :group 'org-time
3191 :type 'boolean)
3193 (defcustom org-calendar-follow-timestamp-change t
3194 "Non-nil means make the calendar window follow timestamp changes.
3195 When a timestamp is modified and the calendar window is visible, it will be
3196 moved to the new date."
3197 :group 'org-time
3198 :type 'boolean)
3200 (defgroup org-tags nil
3201 "Options concerning tags in Org-mode."
3202 :tag "Org Tags"
3203 :group 'org)
3205 (defcustom org-tag-alist nil
3206 "List of tags allowed in Org-mode files.
3207 When this list is nil, Org-mode will base TAG input on what is already in the
3208 buffer.
3209 The value of this variable is an alist, the car of each entry must be a
3210 keyword as a string, the cdr may be a character that is used to select
3211 that tag through the fast-tag-selection interface.
3212 See the manual for details."
3213 :group 'org-tags
3214 :type '(repeat
3215 (choice
3216 (cons (string :tag "Tag name")
3217 (character :tag "Access char"))
3218 (list :tag "Start radio group"
3219 (const :startgroup)
3220 (option (string :tag "Group description")))
3221 (list :tag "Group tags delimiter"
3222 (const :grouptags))
3223 (list :tag "End radio group"
3224 (const :endgroup)
3225 (option (string :tag "Group description")))
3226 (const :tag "New line" (:newline)))))
3228 (defcustom org-tag-persistent-alist nil
3229 "List of tags that will always appear in all Org-mode files.
3230 This is in addition to any in buffer settings or customizations
3231 of `org-tag-alist'.
3232 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3233 The value of this variable is an alist, the car of each entry must be a
3234 keyword as a string, the cdr may be a character that is used to select
3235 that tag through the fast-tag-selection interface.
3236 See the manual for details.
3237 To disable these tags on a per-file basis, insert anywhere in the file:
3238 #+STARTUP: noptag"
3239 :group 'org-tags
3240 :type '(repeat
3241 (choice
3242 (cons (string :tag "Tag name")
3243 (character :tag "Access char"))
3244 (const :tag "Start radio group" (:startgroup))
3245 (const :tag "Group tags delimiter" (:grouptags))
3246 (const :tag "End radio group" (:endgroup))
3247 (const :tag "New line" (:newline)))))
3249 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3250 "If non-nil, always offer completion for all tags of all agenda files.
3251 Instead of customizing this variable directly, you might want to
3252 set it locally for capture buffers, because there no list of
3253 tags in that file can be created dynamically (there are none).
3255 (add-hook 'org-capture-mode-hook
3256 (lambda ()
3257 (set (make-local-variable
3258 'org-complete-tags-always-offer-all-agenda-tags)
3259 t)))"
3260 :group 'org-tags
3261 :version "24.1"
3262 :type 'boolean)
3264 (defvar org-file-tags nil
3265 "List of tags that can be inherited by all entries in the file.
3266 The tags will be inherited if the variable `org-use-tag-inheritance'
3267 says they should be.
3268 This variable is populated from #+FILETAGS lines.")
3270 (defcustom org-use-fast-tag-selection 'auto
3271 "Non-nil means use fast tag selection scheme.
3272 This is a special interface to select and deselect tags with single keys.
3273 When nil, fast selection is never used.
3274 When the symbol `auto', fast selection is used if and only if selection
3275 characters for tags have been configured, either through the variable
3276 `org-tag-alist' or through a #+TAGS line in the buffer.
3277 When t, fast selection is always used and selection keys are assigned
3278 automatically if necessary."
3279 :group 'org-tags
3280 :type '(choice
3281 (const :tag "Always" t)
3282 (const :tag "Never" nil)
3283 (const :tag "When selection characters are configured" auto)))
3285 (defcustom org-fast-tag-selection-single-key nil
3286 "Non-nil means fast tag selection exits after first change.
3287 When nil, you have to press RET to exit it.
3288 During fast tag selection, you can toggle this flag with `C-c'.
3289 This variable can also have the value `expert'. In this case, the window
3290 displaying the tags menu is not even shown, until you press C-c again."
3291 :group 'org-tags
3292 :type '(choice
3293 (const :tag "No" nil)
3294 (const :tag "Yes" t)
3295 (const :tag "Expert" expert)))
3297 (defvar org-fast-tag-selection-include-todo nil
3298 "Non-nil means fast tags selection interface will also offer TODO states.
3299 This is an undocumented feature, you should not rely on it.")
3301 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3302 "The column to which tags should be indented in a headline.
3303 If this number is positive, it specifies the column. If it is negative,
3304 it means that the tags should be flushright to that column. For example,
3305 -80 works well for a normal 80 character screen.
3306 When 0, place tags directly after headline text, with only one space in
3307 between."
3308 :group 'org-tags
3309 :type 'integer)
3311 (defcustom org-auto-align-tags t
3312 "Non-nil keeps tags aligned when modifying headlines.
3313 Some operations (i.e. demoting) change the length of a headline and
3314 therefore shift the tags around. With this option turned on, after
3315 each such operation the tags are again aligned to `org-tags-column'."
3316 :group 'org-tags
3317 :type 'boolean)
3319 (defcustom org-use-tag-inheritance t
3320 "Non-nil means tags in levels apply also for sublevels.
3321 When nil, only the tags directly given in a specific line apply there.
3322 This may also be a list of tags that should be inherited, or a regexp that
3323 matches tags that should be inherited. Additional control is possible
3324 with the variable `org-tags-exclude-from-inheritance' which gives an
3325 explicit list of tags to be excluded from inheritance, even if the value of
3326 `org-use-tag-inheritance' would select it for inheritance.
3328 If this option is t, a match early-on in a tree can lead to a large
3329 number of matches in the subtree when constructing the agenda or creating
3330 a sparse tree. If you only want to see the first match in a tree during
3331 a search, check out the variable `org-tags-match-list-sublevels'."
3332 :group 'org-tags
3333 :type '(choice
3334 (const :tag "Not" nil)
3335 (const :tag "Always" t)
3336 (repeat :tag "Specific tags" (string :tag "Tag"))
3337 (regexp :tag "Tags matched by regexp")))
3339 (defcustom org-tags-exclude-from-inheritance nil
3340 "List of tags that should never be inherited.
3341 This is a way to exclude a few tags from inheritance. For way to do
3342 the opposite, to actively allow inheritance for selected tags,
3343 see the variable `org-use-tag-inheritance'."
3344 :group 'org-tags
3345 :type '(repeat (string :tag "Tag")))
3347 (defun org-tag-inherit-p (tag)
3348 "Check if TAG is one that should be inherited."
3349 (cond
3350 ((member tag org-tags-exclude-from-inheritance) nil)
3351 ((eq org-use-tag-inheritance t) t)
3352 ((not org-use-tag-inheritance) nil)
3353 ((stringp org-use-tag-inheritance)
3354 (string-match org-use-tag-inheritance tag))
3355 ((listp org-use-tag-inheritance)
3356 (member tag org-use-tag-inheritance))
3357 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3359 (defcustom org-tags-match-list-sublevels t
3360 "Non-nil means list also sublevels of headlines matching a search.
3361 This variable applies to tags/property searches, and also to stuck
3362 projects because this search is based on a tags match as well.
3364 When set to the symbol `indented', sublevels are indented with
3365 leading dots.
3367 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3368 the sublevels of a headline matching a tag search often also match
3369 the same search. Listing all of them can create very long lists.
3370 Setting this variable to nil causes subtrees of a match to be skipped.
3372 This variable is semi-obsolete and probably should always be true. It
3373 is better to limit inheritance to certain tags using the variables
3374 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3375 :group 'org-tags
3376 :type '(choice
3377 (const :tag "No, don't list them" nil)
3378 (const :tag "Yes, do list them" t)
3379 (const :tag "List them, indented with leading dots" indented)))
3381 (defcustom org-tags-sort-function nil
3382 "When set, tags are sorted using this function as a comparator."
3383 :group 'org-tags
3384 :type '(choice
3385 (const :tag "No sorting" nil)
3386 (const :tag "Alphabetical" string<)
3387 (const :tag "Reverse alphabetical" string>)
3388 (function :tag "Custom function" nil)))
3390 (defvar org-tags-history nil
3391 "History of minibuffer reads for tags.")
3392 (defvar org-last-tags-completion-table nil
3393 "The last used completion table for tags.")
3394 (defvar org-after-tags-change-hook nil
3395 "Hook that is run after the tags in a line have changed.")
3397 (defgroup org-properties nil
3398 "Options concerning properties in Org-mode."
3399 :tag "Org Properties"
3400 :group 'org)
3402 (defcustom org-property-format "%-10s %s"
3403 "How property key/value pairs should be formatted by `indent-line'.
3404 When `indent-line' hits a property definition, it will format the line
3405 according to this format, mainly to make sure that the values are
3406 lined-up with respect to each other."
3407 :group 'org-properties
3408 :type 'string)
3410 (defcustom org-properties-postprocess-alist nil
3411 "Alist of properties and functions to adjust inserted values.
3412 Elements of this alist must be of the form
3414 ([string] [function])
3416 where [string] must be a property name and [function] must be a
3417 lambda expression: this lambda expression must take one argument,
3418 the value to adjust, and return the new value as a string.
3420 For example, this element will allow the property \"Remaining\"
3421 to be updated wrt the relation between the \"Effort\" property
3422 and the clock summary:
3424 ((\"Remaining\" (lambda(value)
3425 (let ((clocksum (org-clock-sum-current-item))
3426 (effort (org-duration-string-to-minutes
3427 (org-entry-get (point) \"Effort\"))))
3428 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3429 :group 'org-properties
3430 :version "24.1"
3431 :type '(alist :key-type (string :tag "Property")
3432 :value-type (function :tag "Function")))
3434 (defcustom org-use-property-inheritance nil
3435 "Non-nil means properties apply also for sublevels.
3437 This setting is chiefly used during property searches. Turning it on can
3438 cause significant overhead when doing a search, which is why it is not
3439 on by default.
3441 When nil, only the properties directly given in the current entry count.
3442 When t, every property is inherited. The value may also be a list of
3443 properties that should have inheritance, or a regular expression matching
3444 properties that should be inherited.
3446 However, note that some special properties use inheritance under special
3447 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3448 and the properties ending in \"_ALL\" when they are used as descriptor
3449 for valid values of a property.
3451 Note for programmers:
3452 When querying an entry with `org-entry-get', you can control if inheritance
3453 should be used. By default, `org-entry-get' looks only at the local
3454 properties. You can request inheritance by setting the inherit argument
3455 to t (to force inheritance) or to `selective' (to respect the setting
3456 in this variable)."
3457 :group 'org-properties
3458 :type '(choice
3459 (const :tag "Not" nil)
3460 (const :tag "Always" t)
3461 (repeat :tag "Specific properties" (string :tag "Property"))
3462 (regexp :tag "Properties matched by regexp")))
3464 (defun org-property-inherit-p (property)
3465 "Check if PROPERTY is one that should be inherited."
3466 (cond
3467 ((eq org-use-property-inheritance t) t)
3468 ((not org-use-property-inheritance) nil)
3469 ((stringp org-use-property-inheritance)
3470 (string-match org-use-property-inheritance property))
3471 ((listp org-use-property-inheritance)
3472 (member property org-use-property-inheritance))
3473 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3475 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3476 "The default column format, if no other format has been defined.
3477 This variable can be set on the per-file basis by inserting a line
3479 #+COLUMNS: %25ITEM ....."
3480 :group 'org-properties
3481 :type 'string)
3483 (defcustom org-columns-ellipses ".."
3484 "The ellipses to be used when a field in column view is truncated.
3485 When this is the empty string, as many characters as possible are shown,
3486 but then there will be no visual indication that the field has been truncated.
3487 When this is a string of length N, the last N characters of a truncated
3488 field are replaced by this string. If the column is narrower than the
3489 ellipses string, only part of the ellipses string will be shown."
3490 :group 'org-properties
3491 :type 'string)
3493 (defcustom org-columns-modify-value-for-display-function nil
3494 "Function that modifies values for display in column view.
3495 For example, it can be used to cut out a certain part from a time stamp.
3496 The function must take 2 arguments:
3498 column-title The title of the column (*not* the property name)
3499 value The value that should be modified.
3501 The function should return the value that should be displayed,
3502 or nil if the normal value should be used."
3503 :group 'org-properties
3504 :type '(choice (const nil) (function)))
3506 (defcustom org-effort-property "Effort"
3507 "The property that is being used to keep track of effort estimates.
3508 Effort estimates given in this property need to have the format H:MM."
3509 :group 'org-properties
3510 :group 'org-progress
3511 :type '(string :tag "Property"))
3513 (defconst org-global-properties-fixed
3514 '(("VISIBILITY_ALL" . "folded children content all")
3515 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3516 "List of property/value pairs that can be inherited by any entry.
3518 These are fixed values, for the preset properties. The user variable
3519 that can be used to add to this list is `org-global-properties'.
3521 The entries in this list are cons cells where the car is a property
3522 name and cdr is a string with the value. If the value represents
3523 multiple items like an \"_ALL\" property, separate the items by
3524 spaces.")
3526 (defcustom org-global-properties nil
3527 "List of property/value pairs that can be inherited by any entry.
3529 This list will be combined with the constant `org-global-properties-fixed'.
3531 The entries in this list are cons cells where the car is a property
3532 name and cdr is a string with the value.
3534 You can set buffer-local values for the same purpose in the variable
3535 `org-file-properties' this by adding lines like
3537 #+PROPERTY: NAME VALUE"
3538 :group 'org-properties
3539 :type '(repeat
3540 (cons (string :tag "Property")
3541 (string :tag "Value"))))
3543 (defvar org-file-properties nil
3544 "List of property/value pairs that can be inherited by any entry.
3545 Valid for the current buffer.
3546 This variable is populated from #+PROPERTY lines.")
3547 (make-variable-buffer-local 'org-file-properties)
3549 (defgroup org-agenda nil
3550 "Options concerning agenda views in Org-mode."
3551 :tag "Org Agenda"
3552 :group 'org)
3554 (defvar org-category nil
3555 "Variable used by org files to set a category for agenda display.
3556 Such files should use a file variable to set it, for example
3558 # -*- mode: org; org-category: \"ELisp\"
3560 or contain a special line
3562 #+CATEGORY: ELisp
3564 If the file does not specify a category, then file's base name
3565 is used instead.")
3566 (make-variable-buffer-local 'org-category)
3567 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3569 (defcustom org-agenda-files nil
3570 "The files to be used for agenda display.
3571 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3572 \\[org-remove-file]. You can also use customize to edit the list.
3574 If an entry is a directory, all files in that directory that are matched by
3575 `org-agenda-file-regexp' will be part of the file list.
3577 If the value of the variable is not a list but a single file name, then
3578 the list of agenda files is actually stored and maintained in that file, one
3579 agenda file per line. In this file paths can be given relative to
3580 `org-directory'. Tilde expansion and environment variable substitution
3581 are also made."
3582 :group 'org-agenda
3583 :type '(choice
3584 (repeat :tag "List of files and directories" file)
3585 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3587 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3588 "Regular expression to match files for `org-agenda-files'.
3589 If any element in the list in that variable contains a directory instead
3590 of a normal file, all files in that directory that are matched by this
3591 regular expression will be included."
3592 :group 'org-agenda
3593 :type 'regexp)
3595 (defcustom org-agenda-text-search-extra-files nil
3596 "List of extra files to be searched by text search commands.
3597 These files will be searched in addition to the agenda files by the
3598 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3599 Note that these files will only be searched for text search commands,
3600 not for the other agenda views like todo lists, tag searches or the weekly
3601 agenda. This variable is intended to list notes and possibly archive files
3602 that should also be searched by these two commands.
3603 In fact, if the first element in the list is the symbol `agenda-archives',
3604 then all archive files of all agenda files will be added to the search
3605 scope."
3606 :group 'org-agenda
3607 :type '(set :greedy t
3608 (const :tag "Agenda Archives" agenda-archives)
3609 (repeat :inline t (file))))
3611 (org-defvaralias 'org-agenda-multi-occur-extra-files
3612 'org-agenda-text-search-extra-files)
3614 (defcustom org-agenda-skip-unavailable-files nil
3615 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3616 A nil value means to remove them, after a query, from the list."
3617 :group 'org-agenda
3618 :type 'boolean)
3620 (defcustom org-calendar-to-agenda-key [?c]
3621 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3622 The command `org-calendar-goto-agenda' will be bound to this key. The
3623 default is the character `c' because then `c' can be used to switch back and
3624 forth between agenda and calendar."
3625 :group 'org-agenda
3626 :type 'sexp)
3628 (defcustom org-calendar-insert-diary-entry-key [?i]
3629 "The key to be installed in `calendar-mode-map' for adding diary entries.
3630 This option is irrelevant until `org-agenda-diary-file' has been configured
3631 to point to an Org-mode file. When that is the case, the command
3632 `org-agenda-diary-entry' will be bound to the key given here, by default
3633 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3634 if you want to continue doing this, you need to change this to a different
3635 key."
3636 :group 'org-agenda
3637 :type 'sexp)
3639 (defcustom org-agenda-diary-file 'diary-file
3640 "File to which to add new entries with the `i' key in agenda and calendar.
3641 When this is the symbol `diary-file', the functionality in the Emacs
3642 calendar will be used to add entries to the `diary-file'. But when this
3643 points to a file, `org-agenda-diary-entry' will be used instead."
3644 :group 'org-agenda
3645 :type '(choice
3646 (const :tag "The standard Emacs diary file" diary-file)
3647 (file :tag "Special Org file diary entries")))
3649 (eval-after-load "calendar"
3650 '(progn
3651 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3652 'org-calendar-goto-agenda)
3653 (add-hook 'calendar-mode-hook
3654 (lambda ()
3655 (unless (eq org-agenda-diary-file 'diary-file)
3656 (define-key calendar-mode-map
3657 org-calendar-insert-diary-entry-key
3658 'org-agenda-diary-entry))))))
3660 (defgroup org-latex nil
3661 "Options for embedding LaTeX code into Org-mode."
3662 :tag "Org LaTeX"
3663 :group 'org)
3665 (defcustom org-format-latex-options
3666 '(:foreground default :background default :scale 1.0
3667 :html-foreground "Black" :html-background "Transparent"
3668 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3669 "Options for creating images from LaTeX fragments.
3670 This is a property list with the following properties:
3671 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3672 `default' means use the foreground of the default face.
3673 `auto' means use the foreground from the text face.
3674 :background the background color, or \"Transparent\".
3675 `default' means use the background of the default face.
3676 `auto' means use the background from the text face.
3677 :scale a scaling factor for the size of the images, to get more pixels
3678 :html-foreground, :html-background, :html-scale
3679 the same numbers for HTML export.
3680 :matchers a list indicating which matchers should be used to
3681 find LaTeX fragments. Valid members of this list are:
3682 \"begin\" find environments
3683 \"$1\" find single characters surrounded by $.$
3684 \"$\" find math expressions surrounded by $...$
3685 \"$$\" find math expressions surrounded by $$....$$
3686 \"\\(\" find math expressions surrounded by \\(...\\)
3687 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3688 :group 'org-latex
3689 :type 'plist)
3691 (defcustom org-format-latex-signal-error t
3692 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3693 When nil, just push out a message."
3694 :group 'org-latex
3695 :version "24.1"
3696 :type 'boolean)
3698 (defcustom org-latex-to-mathml-jar-file nil
3699 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3700 Use this to specify additional executable file say a jar file.
3702 When using MathToWeb as the converter, specify the full-path to
3703 your mathtoweb.jar file."
3704 :group 'org-latex
3705 :version "24.1"
3706 :type '(choice
3707 (const :tag "None" nil)
3708 (file :tag "JAR file" :must-match t)))
3710 (defcustom org-latex-to-mathml-convert-command nil
3711 "Command to convert LaTeX fragments to MathML.
3712 Replace format-specifiers in the command as noted below and use
3713 `shell-command' to convert LaTeX to MathML.
3714 %j: Executable file in fully expanded form as specified by
3715 `org-latex-to-mathml-jar-file'.
3716 %I: Input LaTeX file in fully expanded form
3717 %o: Output MathML file
3718 This command is used by `org-create-math-formula'.
3720 When using MathToWeb as the converter, set this to
3721 \"java -jar %j -unicode -force -df %o %I\"."
3722 :group 'org-latex
3723 :version "24.1"
3724 :type '(choice
3725 (const :tag "None" nil)
3726 (string :tag "\nShell command")))
3728 (defcustom org-latex-create-formula-image-program 'dvipng
3729 "Program to convert LaTeX fragments with.
3731 dvipng Process the LaTeX fragments to dvi file, then convert
3732 dvi files to png files using dvipng.
3733 This will also include processing of non-math environments.
3734 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3735 to convert pdf files to png files"
3736 :group 'org-latex
3737 :version "24.1"
3738 :type '(choice
3739 (const :tag "dvipng" dvipng)
3740 (const :tag "imagemagick" imagemagick)))
3742 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3743 "Path to store latex preview images.
3744 A relative path here creates many directories relative to the
3745 processed org files paths. An absolute path puts all preview
3746 images at the same place."
3747 :group 'org-latex
3748 :version "24.3"
3749 :type 'string)
3751 (defun org-format-latex-mathml-available-p ()
3752 "Return t if `org-latex-to-mathml-convert-command' is usable."
3753 (save-match-data
3754 (when (and (boundp 'org-latex-to-mathml-convert-command)
3755 org-latex-to-mathml-convert-command)
3756 (let ((executable (car (split-string
3757 org-latex-to-mathml-convert-command))))
3758 (when (executable-find executable)
3759 (if (string-match
3760 "%j" org-latex-to-mathml-convert-command)
3761 (file-readable-p org-latex-to-mathml-jar-file)
3762 t))))))
3764 (defcustom org-format-latex-header "\\documentclass{article}
3765 \\usepackage[usenames]{color}
3766 \\usepackage{amsmath}
3767 \\usepackage[mathscr]{eucal}
3768 \\pagestyle{empty} % do not remove
3769 \[PACKAGES]
3770 \[DEFAULT-PACKAGES]
3771 % The settings below are copied from fullpage.sty
3772 \\setlength{\\textwidth}{\\paperwidth}
3773 \\addtolength{\\textwidth}{-3cm}
3774 \\setlength{\\oddsidemargin}{1.5cm}
3775 \\addtolength{\\oddsidemargin}{-2.54cm}
3776 \\setlength{\\evensidemargin}{\\oddsidemargin}
3777 \\setlength{\\textheight}{\\paperheight}
3778 \\addtolength{\\textheight}{-\\headheight}
3779 \\addtolength{\\textheight}{-\\headsep}
3780 \\addtolength{\\textheight}{-\\footskip}
3781 \\addtolength{\\textheight}{-3cm}
3782 \\setlength{\\topmargin}{1.5cm}
3783 \\addtolength{\\topmargin}{-2.54cm}"
3784 "The document header used for processing LaTeX fragments.
3785 It is imperative that this header make sure that no page number
3786 appears on the page. The package defined in the variables
3787 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3788 will either replace the placeholder \"[PACKAGES]\" in this
3789 header, or they will be appended."
3790 :group 'org-latex
3791 :type 'string)
3793 (defun org-set-packages-alist (var val)
3794 "Set the packages alist and make sure it has 3 elements per entry."
3795 (set var (mapcar (lambda (x)
3796 (if (and (consp x) (= (length x) 2))
3797 (list (car x) (nth 1 x) t)
3799 val)))
3801 (defun org-get-packages-alist (var)
3802 "Get the packages alist and make sure it has 3 elements per entry."
3803 (mapcar (lambda (x)
3804 (if (and (consp x) (= (length x) 2))
3805 (list (car x) (nth 1 x) t)
3807 (default-value var)))
3809 (defcustom org-latex-default-packages-alist
3810 '(("AUTO" "inputenc" t)
3811 ("T1" "fontenc" t)
3812 ("" "fixltx2e" nil)
3813 ("" "graphicx" t)
3814 ("" "longtable" nil)
3815 ("" "float" nil)
3816 ("" "wrapfig" nil)
3817 ("normalem" "ulem" t)
3818 ("" "textcomp" t)
3819 ("" "marvosym" t)
3820 ("" "wasysym" t)
3821 ("" "latexsym" t)
3822 ("" "amssymb" t)
3823 ("" "amstext" nil)
3824 ("" "hyperref" nil)
3825 "\\tolerance=1000")
3826 "Alist of default packages to be inserted in the header.
3828 Change this only if one of the packages here causes an
3829 incompatibility with another package you are using.
3831 The packages in this list are needed by one part or another of
3832 Org mode to function properly:
3834 - inputenc, fontenc: for basic font and character selection
3835 - amstext: for subscript and superscript
3836 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3837 symbols used for interpreting the entities in `org-entities'.
3838 You can skip some of these packages if you don't use any of the
3839 symbols in it.
3840 - ulem: for underline and strike-through
3841 - graphicx: for including images
3842 - float, wrapfig: for figure placement
3843 - longtable: for long tables
3844 - hyperref: for cross references
3846 Therefore you should not modify this variable unless you know
3847 what you are doing. The one reason to change it anyway is that
3848 you might be loading some other package that conflicts with one
3849 of the default packages. Each cell is of the format
3850 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3851 the package also needs to be included when compiling LaTeX
3852 snippets into images for inclusion into non-LaTeX output."
3853 :group 'org-latex
3854 :group 'org-export-latex
3855 :set 'org-set-packages-alist
3856 :get 'org-get-packages-alist
3857 :version "24.1"
3858 :type '(repeat
3859 (choice
3860 (list :tag "options/package pair"
3861 (string :tag "options")
3862 (string :tag "package")
3863 (boolean :tag "Snippet"))
3864 (string :tag "A line of LaTeX"))))
3866 (defcustom org-latex-packages-alist nil
3867 "Alist of packages to be inserted in every LaTeX header.
3869 These will be inserted after `org-latex-default-packages-alist'.
3870 Each cell is of the format:
3872 \(\"options\" \"package\" snippet-flag)
3874 SNIPPET-FLAG, when t, indicates that this package is also needed
3875 when turning LaTeX snippets into images for inclusion into
3876 non-LaTeX output.
3878 Make sure that you only list packages here which:
3880 - you want in every file
3881 - do not conflict with the setup in `org-format-latex-header'.
3882 - do not conflict with the default packages in
3883 `org-latex-default-packages-alist'."
3884 :group 'org-latex
3885 :group 'org-export-latex
3886 :set 'org-set-packages-alist
3887 :get 'org-get-packages-alist
3888 :type '(repeat
3889 (choice
3890 (list :tag "options/package pair"
3891 (string :tag "options")
3892 (string :tag "package")
3893 (boolean :tag "Snippet"))
3894 (string :tag "A line of LaTeX"))))
3896 (defgroup org-appearance nil
3897 "Settings for Org-mode appearance."
3898 :tag "Org Appearance"
3899 :group 'org)
3901 (defcustom org-level-color-stars-only nil
3902 "Non-nil means fontify only the stars in each headline.
3903 When nil, the entire headline is fontified.
3904 Changing it requires restart of `font-lock-mode' to become effective
3905 also in regions already fontified."
3906 :group 'org-appearance
3907 :type 'boolean)
3909 (defcustom org-hide-leading-stars nil
3910 "Non-nil means hide the first N-1 stars in a headline.
3911 This works by using the face `org-hide' for these stars. This
3912 face is white for a light background, and black for a dark
3913 background. You may have to customize the face `org-hide' to
3914 make this work.
3915 Changing it requires restart of `font-lock-mode' to become effective
3916 also in regions already fontified.
3917 You may also set this on a per-file basis by adding one of the following
3918 lines to the buffer:
3920 #+STARTUP: hidestars
3921 #+STARTUP: showstars"
3922 :group 'org-appearance
3923 :type 'boolean)
3925 (defcustom org-hidden-keywords nil
3926 "List of symbols corresponding to keywords to be hidden the org buffer.
3927 For example, a value '(title) for this list will make the document's title
3928 appear in the buffer without the initial #+TITLE: keyword."
3929 :group 'org-appearance
3930 :version "24.1"
3931 :type '(set (const :tag "#+AUTHOR" author)
3932 (const :tag "#+DATE" date)
3933 (const :tag "#+EMAIL" email)
3934 (const :tag "#+TITLE" title)))
3936 (defcustom org-custom-properties nil
3937 "List of properties (as strings) with a special meaning.
3938 The default use of these custom properties is to let the user
3939 hide them with `org-toggle-custom-properties-visibility'."
3940 :group 'org-properties
3941 :group 'org-appearance
3942 :version "24.3"
3943 :type '(repeat (string :tag "Property Name")))
3945 (defcustom org-fontify-done-headline nil
3946 "Non-nil means change the face of a headline if it is marked DONE.
3947 Normally, only the TODO/DONE keyword indicates the state of a headline.
3948 When this is non-nil, the headline after the keyword is set to the
3949 `org-headline-done' as an additional indication."
3950 :group 'org-appearance
3951 :type 'boolean)
3953 (defcustom org-fontify-emphasized-text t
3954 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3955 Changing this variable requires a restart of Emacs to take effect."
3956 :group 'org-appearance
3957 :type 'boolean)
3959 (defcustom org-fontify-whole-heading-line nil
3960 "Non-nil means fontify the whole line for headings.
3961 This is useful when setting a background color for the
3962 org-level-* faces."
3963 :group 'org-appearance
3964 :type 'boolean)
3966 (defcustom org-highlight-latex-and-related nil
3967 "Non-nil means highlight LaTeX related syntax in the buffer.
3968 When non nil, the value should be a list containing any of the
3969 following symbols:
3970 `latex' Highlight LaTeX snippets and environments.
3971 `script' Highlight subscript and superscript.
3972 `entities' Highlight entities."
3973 :group 'org-appearance
3974 :version "24.4"
3975 :package-version '(Org . "8.0")
3976 :type '(choice
3977 (const :tag "No highlighting" nil)
3978 (set :greedy t :tag "Highlight"
3979 (const :tag "LaTeX snippets and environments" latex)
3980 (const :tag "Subscript and superscript" script)
3981 (const :tag "Entities" entities))))
3983 (defcustom org-hide-emphasis-markers nil
3984 "Non-nil mean font-lock should hide the emphasis marker characters."
3985 :group 'org-appearance
3986 :type 'boolean)
3988 (defcustom org-pretty-entities nil
3989 "Non-nil means show entities as UTF8 characters.
3990 When nil, the \\name form remains in the buffer."
3991 :group 'org-appearance
3992 :version "24.1"
3993 :type 'boolean)
3995 (defcustom org-pretty-entities-include-sub-superscripts t
3996 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3997 :group 'org-appearance
3998 :version "24.1"
3999 :type 'boolean)
4001 (defvar org-emph-re nil
4002 "Regular expression for matching emphasis.
4003 After a match, the match groups contain these elements:
4004 0 The match of the full regular expression, including the characters
4005 before and after the proper match
4006 1 The character before the proper match, or empty at beginning of line
4007 2 The proper match, including the leading and trailing markers
4008 3 The leading marker like * or /, indicating the type of highlighting
4009 4 The text between the emphasis markers, not including the markers
4010 5 The character after the match, empty at the end of a line")
4011 (defvar org-verbatim-re nil
4012 "Regular expression for matching verbatim text.")
4013 (defvar org-emphasis-regexp-components) ; defined just below
4014 (defvar org-emphasis-alist) ; defined just below
4015 (defun org-set-emph-re (var val)
4016 "Set variable and compute the emphasis regular expression."
4017 (set var val)
4018 (when (and (boundp 'org-emphasis-alist)
4019 (boundp 'org-emphasis-regexp-components)
4020 org-emphasis-alist org-emphasis-regexp-components)
4021 (let* ((e org-emphasis-regexp-components)
4022 (pre (car e))
4023 (post (nth 1 e))
4024 (border (nth 2 e))
4025 (body (nth 3 e))
4026 (nl (nth 4 e))
4027 (body1 (concat body "*?"))
4028 (markers (mapconcat 'car org-emphasis-alist ""))
4029 (vmarkers (mapconcat
4030 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4031 org-emphasis-alist "")))
4032 ;; make sure special characters appear at the right position in the class
4033 (if (string-match "\\^" markers)
4034 (setq markers (concat (replace-match "" t t markers) "^")))
4035 (if (string-match "-" markers)
4036 (setq markers (concat (replace-match "" t t markers) "-")))
4037 (if (string-match "\\^" vmarkers)
4038 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4039 (if (string-match "-" vmarkers)
4040 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4041 (if (> nl 0)
4042 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4043 (int-to-string nl) "\\}")))
4044 ;; Make the regexp
4045 (setq org-emph-re
4046 (concat "\\([" pre "]\\|^\\)"
4047 "\\("
4048 "\\([" markers "]\\)"
4049 "\\("
4050 "[^" border "]\\|"
4051 "[^" border "]"
4052 body1
4053 "[^" border "]"
4054 "\\)"
4055 "\\3\\)"
4056 "\\([" post "]\\|$\\)"))
4057 (setq org-verbatim-re
4058 (concat "\\([" pre "]\\|^\\)"
4059 "\\("
4060 "\\([" vmarkers "]\\)"
4061 "\\("
4062 "[^" border "]\\|"
4063 "[^" border "]"
4064 body1
4065 "[^" border "]"
4066 "\\)"
4067 "\\3\\)"
4068 "\\([" post "]\\|$\\)")))))
4070 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4071 ;; set this option proved cumbersome. See this message/thread:
4072 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4073 (defvar org-emphasis-regexp-components
4074 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4075 "Components used to build the regular expression for emphasis.
4076 This is a list with five entries. Terminology: In an emphasis string
4077 like \" *strong word* \", we call the initial space PREMATCH, the final
4078 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4079 and \"trong wor\" is the body. The different components in this variable
4080 specify what is allowed/forbidden in each part:
4082 pre Chars allowed as prematch. Beginning of line will be allowed too.
4083 post Chars allowed as postmatch. End of line will be allowed too.
4084 border The chars *forbidden* as border characters.
4085 body-regexp A regexp like \".\" to match a body character. Don't use
4086 non-shy groups here, and don't allow newline here.
4087 newline The maximum number of newlines allowed in an emphasis exp.
4089 You need to reload Org or to restart Emacs after customizing this.")
4091 (defcustom org-emphasis-alist
4092 `(("*" bold)
4093 ("/" italic)
4094 ("_" underline)
4095 ("=" org-code verbatim)
4096 ("~" org-verbatim verbatim)
4097 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4098 "Alist of characters and faces to emphasize text.
4099 Text starting and ending with a special character will be emphasized,
4100 for example *bold*, _underlined_ and /italic/. This variable sets the
4101 marker characters and the face to be used by font-lock for highlighting
4102 in Org-mode Emacs buffers.
4104 You need to reload Org or to restart Emacs after customizing this."
4105 :group 'org-appearance
4106 :set 'org-set-emph-re
4107 :version "24.4"
4108 :package-version '(Org . "8.0")
4109 :type '(repeat
4110 (list
4111 (string :tag "Marker character")
4112 (choice
4113 (face :tag "Font-lock-face")
4114 (plist :tag "Face property list"))
4115 (option (const verbatim)))))
4117 (defvar org-protecting-blocks
4118 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4119 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4120 This is needed for font-lock setup.")
4122 ;;; Miscellaneous options
4124 (defgroup org-completion nil
4125 "Completion in Org-mode."
4126 :tag "Org Completion"
4127 :group 'org)
4129 (defcustom org-completion-use-ido nil
4130 "Non-nil means use ido completion wherever possible.
4131 Note that `ido-mode' must be active for this variable to be relevant.
4132 If you decide to turn this variable on, you might well want to turn off
4133 `org-outline-path-complete-in-steps'.
4134 See also `org-completion-use-iswitchb'."
4135 :group 'org-completion
4136 :type 'boolean)
4138 (defcustom org-completion-use-iswitchb nil
4139 "Non-nil means use iswitchb completion wherever possible.
4140 Note that `iswitchb-mode' must be active for this variable to be relevant.
4141 If you decide to turn this variable on, you might well want to turn off
4142 `org-outline-path-complete-in-steps'.
4143 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4144 :group 'org-completion
4145 :type 'boolean)
4147 (defcustom org-completion-fallback-command 'hippie-expand
4148 "The expansion command called by \\[pcomplete] in normal context.
4149 Normal means, no org-mode-specific context."
4150 :group 'org-completion
4151 :type 'function)
4153 ;;; Functions and variables from their packages
4154 ;; Declared here to avoid compiler warnings
4156 ;; XEmacs only
4157 (defvar outline-mode-menu-heading)
4158 (defvar outline-mode-menu-show)
4159 (defvar outline-mode-menu-hide)
4160 (defvar zmacs-regions) ; XEmacs regions
4162 ;; Emacs only
4163 (defvar mark-active)
4165 ;; Various packages
4166 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4167 (declare-function calendar-forward-day "cal-move" (arg))
4168 (declare-function calendar-goto-date "cal-move" (date))
4169 (declare-function calendar-goto-today "cal-move" ())
4170 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4171 (defvar calc-embedded-close-formula)
4172 (defvar calc-embedded-open-formula)
4173 (declare-function cdlatex-tab "ext:cdlatex" ())
4174 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4175 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4176 (defvar font-lock-unfontify-region-function)
4177 (declare-function iswitchb-read-buffer "iswitchb"
4178 (prompt &optional default require-match start matches-set))
4179 (defvar iswitchb-temp-buflist)
4180 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4181 (defvar org-agenda-tags-todo-honor-ignore-options)
4182 (declare-function org-agenda-skip "org-agenda" ())
4183 (declare-function
4184 org-agenda-format-item "org-agenda"
4185 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4186 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4187 (declare-function org-agenda-change-all-lines "org-agenda"
4188 (newhead hdmarker &optional fixface just-this))
4189 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4190 (declare-function org-agenda-maybe-redo "org-agenda" ())
4191 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4192 (beg end))
4193 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4194 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4195 "org-agenda" (&optional end))
4196 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4197 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4198 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4199 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4200 (declare-function org-indent-mode "org-indent" (&optional arg))
4201 (declare-function parse-time-string "parse-time" (string))
4202 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4203 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4204 (defvar remember-data-file)
4205 (defvar texmathp-why)
4206 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4207 (declare-function table--at-cell-p "table" (position &optional object at-column))
4209 (defvar org-latex-regexps)
4211 ;;; Autoload and prepare some org modules
4213 ;; Some table stuff that needs to be defined here, because it is used
4214 ;; by the functions setting up org-mode or checking for table context.
4216 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4217 "Detect an org-type or table-type table.")
4218 (defconst org-table-line-regexp "^[ \t]*|"
4219 "Detect an org-type table line.")
4220 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4221 "Detect an org-type table line.")
4222 (defconst org-table-hline-regexp "^[ \t]*|-"
4223 "Detect an org-type table hline.")
4224 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4225 "Detect a table-type table hline.")
4226 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4227 "Detect the first line outside a table when searching from within it.
4228 This works for both table types.")
4230 ;; Autoload the functions in org-table.el that are needed by functions here.
4232 (eval-and-compile
4233 (org-autoload "org-table"
4234 '(org-table-begin org-table-blank-field org-table-end)))
4236 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
4237 "Detect a #+TBLFM line.")
4239 ;;;###autoload
4240 (defun turn-on-orgtbl ()
4241 "Unconditionally turn on `orgtbl-mode'."
4242 (require 'org-table)
4243 (orgtbl-mode 1))
4245 (defun org-at-table-p (&optional table-type)
4246 "Return t if the cursor is inside an org-type table.
4247 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4248 (if org-enable-table-editor
4249 (save-excursion
4250 (beginning-of-line 1)
4251 (looking-at (if table-type org-table-any-line-regexp
4252 org-table-line-regexp)))
4253 nil))
4254 (defsubst org-table-p () (org-at-table-p))
4256 (defun org-at-table.el-p ()
4257 "Return t if and only if we are at a table.el table."
4258 (and (org-at-table-p 'any)
4259 (save-excursion
4260 (goto-char (org-table-begin 'any))
4261 (looking-at org-table1-hline-regexp))))
4263 (defun org-table-recognize-table.el ()
4264 "If there is a table.el table nearby, recognize it and move into it."
4265 (if org-table-tab-recognizes-table.el
4266 (if (org-at-table.el-p)
4267 (progn
4268 (beginning-of-line 1)
4269 (if (looking-at org-table-dataline-regexp)
4271 (if (looking-at org-table1-hline-regexp)
4272 (progn
4273 (beginning-of-line 2)
4274 (if (looking-at org-table-any-border-regexp)
4275 (beginning-of-line -1)))))
4276 (if (re-search-forward "|" (org-table-end t) t)
4277 (progn
4278 (require 'table)
4279 (if (table--at-cell-p (point))
4281 (message "recognizing table.el table...")
4282 (table-recognize-table)
4283 (message "recognizing table.el table...done")))
4284 (error "This should not happen"))
4286 nil)
4287 nil))
4289 (defun org-at-table-hline-p ()
4290 "Return t if the cursor is inside a hline in a table."
4291 (if org-enable-table-editor
4292 (save-excursion
4293 (beginning-of-line 1)
4294 (looking-at org-table-hline-regexp))
4295 nil))
4297 (defun org-table-map-tables (function &optional quietly)
4298 "Apply FUNCTION to the start of all tables in the buffer."
4299 (save-excursion
4300 (save-restriction
4301 (widen)
4302 (goto-char (point-min))
4303 (while (re-search-forward org-table-any-line-regexp nil t)
4304 (unless quietly
4305 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4306 (beginning-of-line 1)
4307 (when (and (looking-at org-table-line-regexp)
4308 ;; Exclude tables in src/example/verbatim/clocktable blocks
4309 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4310 (save-excursion (funcall function))
4311 (or (looking-at org-table-line-regexp)
4312 (forward-char 1)))
4313 (re-search-forward org-table-any-border-regexp nil 1))))
4314 (unless quietly (message "Mapping tables: done")))
4316 ;; Declare and autoload functions from org-agenda.el
4318 (eval-and-compile
4319 (org-autoload "org-agenda"
4320 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4322 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4323 (declare-function org-clock-update-mode-line "org-clock" ())
4324 (declare-function org-resolve-clocks "org-clock"
4325 (&optional also-non-dangling-p prompt last-valid))
4327 (defun org-at-TBLFM-p (&optional pos)
4328 "Return t when point (or POS) is in #+TBLFM line."
4329 (save-excursion
4330 (let ((pos pos)))
4331 (goto-char (or pos (point)))
4332 (beginning-of-line 1)
4333 (looking-at org-TBLFM-regexp)))
4335 (defvar org-clock-start-time)
4336 (defvar org-clock-marker (make-marker)
4337 "Marker recording the last clock-in.")
4338 (defvar org-clock-hd-marker (make-marker)
4339 "Marker recording the last clock-in, but the headline position.")
4340 (defvar org-clock-heading ""
4341 "The heading of the current clock entry.")
4342 (defun org-clock-is-active ()
4343 "Return non-nil if clock is currently running.
4344 The return value is actually the clock marker."
4345 (marker-buffer org-clock-marker))
4347 (eval-and-compile
4348 (org-autoload "org-clock" '(org-clock-remove-overlays
4349 org-clock-update-time-maybe
4350 org-clocktable-shift)))
4352 (defun org-check-running-clock ()
4353 "Check if the current buffer contains the running clock.
4354 If yes, offer to stop it and to save the buffer with the changes."
4355 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4356 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4357 (buffer-name))))
4358 (org-clock-out)
4359 (when (y-or-n-p "Save changed buffer?")
4360 (save-buffer))))
4362 (defun org-clocktable-try-shift (dir n)
4363 "Check if this line starts a clock table, if yes, shift the time block."
4364 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4365 (org-clocktable-shift dir n)))
4367 ;;;###autoload
4368 (defun org-clock-persistence-insinuate ()
4369 "Set up hooks for clock persistence."
4370 (require 'org-clock)
4371 (add-hook 'org-mode-hook 'org-clock-load)
4372 (add-hook 'kill-emacs-hook 'org-clock-save))
4374 ;; Define the variable already here, to make sure we have it.
4375 (defvar org-indent-mode nil
4376 "Non-nil if Org-Indent mode is enabled.
4377 Use the command `org-indent-mode' to change this variable.")
4379 ;; Autoload archiving code
4380 ;; The stuff that is needed for cycling and tags has to be defined here.
4382 (defgroup org-archive nil
4383 "Options concerning archiving in Org-mode."
4384 :tag "Org Archive"
4385 :group 'org-structure)
4387 (defcustom org-archive-location "%s_archive::"
4388 "The location where subtrees should be archived.
4390 The value of this variable is a string, consisting of two parts,
4391 separated by a double-colon. The first part is a filename and
4392 the second part is a headline.
4394 When the filename is omitted, archiving happens in the same file.
4395 %s in the filename will be replaced by the current file
4396 name (without the directory part). Archiving to a different file
4397 is useful to keep archived entries from contributing to the
4398 Org-mode Agenda.
4400 The archived entries will be filed as subtrees of the specified
4401 headline. When the headline is omitted, the subtrees are simply
4402 filed away at the end of the file, as top-level entries. Also in
4403 the heading you can use %s to represent the file name, this can be
4404 useful when using the same archive for a number of different files.
4406 Here are a few examples:
4407 \"%s_archive::\"
4408 If the current file is Projects.org, archive in file
4409 Projects.org_archive, as top-level trees. This is the default.
4411 \"::* Archived Tasks\"
4412 Archive in the current file, under the top-level headline
4413 \"* Archived Tasks\".
4415 \"~/org/archive.org::\"
4416 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4418 \"~/org/archive.org::* From %s\"
4419 Archive in file ~/org/archive.org (absolute path), under headlines
4420 \"From FILENAME\" where file name is the current file name.
4422 \"~/org/datetree.org::datetree/* Finished Tasks\"
4423 The \"datetree/\" string is special, signifying to archive
4424 items to the datetree. Items are placed in either the CLOSED
4425 date of the item, or the current date if there is no CLOSED date.
4426 The heading will be a subentry to the current date. There doesn't
4427 need to be a heading, but there always needs to be a slash after
4428 datetree. For example, to store archived items directly in the
4429 datetree, use \"~/org/datetree.org::datetree/\".
4431 \"basement::** Finished Tasks\"
4432 Archive in file ./basement (relative path), as level 3 trees
4433 below the level 2 heading \"** Finished Tasks\".
4435 You may set this option on a per-file basis by adding to the buffer a
4436 line like
4438 #+ARCHIVE: basement::** Finished Tasks
4440 You may also define it locally for a subtree by setting an ARCHIVE property
4441 in the entry. If such a property is found in an entry, or anywhere up
4442 the hierarchy, it will be used."
4443 :group 'org-archive
4444 :type 'string)
4446 (defcustom org-archive-tag "ARCHIVE"
4447 "The tag that marks a subtree as archived.
4448 An archived subtree does not open during visibility cycling, and does
4449 not contribute to the agenda listings.
4450 After changing this, font-lock must be restarted in the relevant buffers to
4451 get the proper fontification."
4452 :group 'org-archive
4453 :group 'org-keywords
4454 :type 'string)
4456 (defcustom org-agenda-skip-archived-trees t
4457 "Non-nil means the agenda will skip any items located in archived trees.
4458 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4459 variable is no longer recommended, you should leave it at the value t.
4460 Instead, use the key `v' to cycle the archives-mode in the agenda."
4461 :group 'org-archive
4462 :group 'org-agenda-skip
4463 :type 'boolean)
4465 (defcustom org-columns-skip-archived-trees t
4466 "Non-nil means ignore archived trees when creating column view."
4467 :group 'org-archive
4468 :group 'org-properties
4469 :type 'boolean)
4471 (defcustom org-cycle-open-archived-trees nil
4472 "Non-nil means `org-cycle' will open archived trees.
4473 An archived tree is a tree marked with the tag ARCHIVE.
4474 When nil, archived trees will stay folded. You can still open them with
4475 normal outline commands like `show-all', but not with the cycling commands."
4476 :group 'org-archive
4477 :group 'org-cycle
4478 :type 'boolean)
4480 (defcustom org-sparse-tree-open-archived-trees nil
4481 "Non-nil means sparse tree construction shows matches in archived trees.
4482 When nil, matches in these trees are highlighted, but the trees are kept in
4483 collapsed state."
4484 :group 'org-archive
4485 :group 'org-sparse-trees
4486 :type 'boolean)
4488 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4489 "The default date type when building a sparse tree.
4490 When this is nil, a date is a scheduled or a deadline timestamp.
4491 Otherwise, these types are allowed:
4493 all: all timestamps
4494 active: only active timestamps (<...>)
4495 inactive: only inactive timestamps (<...)
4496 scheduled: only scheduled timestamps
4497 deadline: only deadline timestamps"
4498 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4499 (const :tag "All timestamps" all)
4500 (const :tag "Only active timestamps" active)
4501 (const :tag "Only inactive timestamps" inactive)
4502 (const :tag "Only scheduled timestamps" scheduled)
4503 (const :tag "Only deadline timestamps" deadline)
4504 (const :tag "Only closed timestamps" closed))
4505 :version "24.3"
4506 :group 'org-sparse-trees)
4508 (defun org-cycle-hide-archived-subtrees (state)
4509 "Re-hide all archived subtrees after a visibility state change."
4510 (when (and (not org-cycle-open-archived-trees)
4511 (not (memq state '(overview folded))))
4512 (save-excursion
4513 (let* ((globalp (memq state '(contents all)))
4514 (beg (if globalp (point-min) (point)))
4515 (end (if globalp (point-max) (org-end-of-subtree t))))
4516 (org-hide-archived-subtrees beg end)
4517 (goto-char beg)
4518 (if (looking-at (concat ".*:" org-archive-tag ":"))
4519 (message "%s" (substitute-command-keys
4520 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4522 (defun org-force-cycle-archived ()
4523 "Cycle subtree even if it is archived."
4524 (interactive)
4525 (setq this-command 'org-cycle)
4526 (let ((org-cycle-open-archived-trees t))
4527 (call-interactively 'org-cycle)))
4529 (defun org-hide-archived-subtrees (beg end)
4530 "Re-hide all archived subtrees after a visibility state change."
4531 (save-excursion
4532 (let* ((re (concat ":" org-archive-tag ":")))
4533 (goto-char beg)
4534 (while (re-search-forward re end t)
4535 (when (org-at-heading-p)
4536 (org-flag-subtree t)
4537 (org-end-of-subtree t))))))
4539 (declare-function outline-end-of-heading "outline" ())
4540 (declare-function outline-flag-region "outline" (from to flag))
4541 (defun org-flag-subtree (flag)
4542 (save-excursion
4543 (org-back-to-heading t)
4544 (outline-end-of-heading)
4545 (outline-flag-region (point)
4546 (progn (org-end-of-subtree t) (point))
4547 flag)))
4549 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4551 (eval-and-compile
4552 (org-autoload "org-archive"
4553 '(org-add-archive-files)))
4555 ;; Autoload Column View Code
4557 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4558 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4559 (declare-function org-columns-compute "org-colview" (property))
4561 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4562 '(org-columns-number-to-string
4563 org-columns-get-format-and-top-level
4564 org-columns-compute
4565 org-columns-remove-overlays))
4567 ;; Autoload ID code
4569 (declare-function org-id-store-link "org-id")
4570 (declare-function org-id-locations-load "org-id")
4571 (declare-function org-id-locations-save "org-id")
4572 (defvar org-id-track-globally)
4573 (org-autoload "org-id"
4574 '(org-id-new
4575 org-id-copy
4576 org-id-get-with-outline-path-completion
4577 org-id-get-with-outline-drilling))
4579 ;;; Variables for pre-computed regular expressions, all buffer local
4581 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4582 "Matches first line of a hidden block.")
4583 (make-variable-buffer-local 'org-drawer-regexp)
4584 (defvar org-todo-regexp nil
4585 "Matches any of the TODO state keywords.")
4586 (make-variable-buffer-local 'org-todo-regexp)
4587 (defvar org-not-done-regexp nil
4588 "Matches any of the TODO state keywords except the last one.")
4589 (make-variable-buffer-local 'org-not-done-regexp)
4590 (defvar org-not-done-heading-regexp nil
4591 "Matches a TODO headline that is not done.")
4592 (make-variable-buffer-local 'org-not-done-regexp)
4593 (defvar org-todo-line-regexp nil
4594 "Matches a headline and puts TODO state into group 2 if present.")
4595 (make-variable-buffer-local 'org-todo-line-regexp)
4596 (defvar org-complex-heading-regexp nil
4597 "Matches a headline and puts everything into groups:
4598 group 1: the stars
4599 group 2: The todo keyword, maybe
4600 group 3: Priority cookie
4601 group 4: True headline
4602 group 5: Tags")
4603 (make-variable-buffer-local 'org-complex-heading-regexp)
4604 (defvar org-complex-heading-regexp-format nil
4605 "Printf format to make regexp to match an exact headline.
4606 This regexp will match the headline of any node which has the
4607 exact headline text that is put into the format, but may have any
4608 TODO state, priority and tags.")
4609 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4610 (defvar org-todo-line-tags-regexp nil
4611 "Matches a headline and puts TODO state into group 2 if present.
4612 Also put tags into group 4 if tags are present.")
4613 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4614 (defvar org-ds-keyword-length 12
4615 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4616 (make-variable-buffer-local 'org-ds-keyword-length)
4617 (defvar org-deadline-regexp nil
4618 "Matches the DEADLINE keyword.")
4619 (make-variable-buffer-local 'org-deadline-regexp)
4620 (defvar org-deadline-time-regexp nil
4621 "Matches the DEADLINE keyword together with a time stamp.")
4622 (make-variable-buffer-local 'org-deadline-time-regexp)
4623 (defvar org-deadline-time-hour-regexp nil
4624 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4625 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4626 (defvar org-deadline-line-regexp nil
4627 "Matches the DEADLINE keyword and the rest of the line.")
4628 (make-variable-buffer-local 'org-deadline-line-regexp)
4629 (defvar org-scheduled-regexp nil
4630 "Matches the SCHEDULED keyword.")
4631 (make-variable-buffer-local 'org-scheduled-regexp)
4632 (defvar org-scheduled-time-regexp nil
4633 "Matches the SCHEDULED keyword together with a time stamp.")
4634 (make-variable-buffer-local 'org-scheduled-time-regexp)
4635 (defvar org-scheduled-time-hour-regexp nil
4636 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4637 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4638 (defvar org-closed-time-regexp nil
4639 "Matches the CLOSED keyword together with a time stamp.")
4640 (make-variable-buffer-local 'org-closed-time-regexp)
4642 (defvar org-keyword-time-regexp nil
4643 "Matches any of the 4 keywords, together with the time stamp.")
4644 (make-variable-buffer-local 'org-keyword-time-regexp)
4645 (defvar org-keyword-time-not-clock-regexp nil
4646 "Matches any of the 3 keywords, together with the time stamp.")
4647 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4648 (defvar org-maybe-keyword-time-regexp nil
4649 "Matches a timestamp, possibly preceded by a keyword.")
4650 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4651 (defvar org-all-time-keywords nil
4652 "List of time keywords.")
4653 (make-variable-buffer-local 'org-all-time-keywords)
4655 (defconst org-plain-time-of-day-regexp
4656 (concat
4657 "\\(\\<[012]?[0-9]"
4658 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4659 "\\(--?"
4660 "\\(\\<[012]?[0-9]"
4661 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4662 "\\)?")
4663 "Regular expression to match a plain time or time range.
4664 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4665 groups carry important information:
4666 0 the full match
4667 1 the first time, range or not
4668 8 the second time, if it is a range.")
4670 (defconst org-plain-time-extension-regexp
4671 (concat
4672 "\\(\\<[012]?[0-9]"
4673 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4674 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4675 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4676 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4677 groups carry important information:
4678 0 the full match
4679 7 hours of duration
4680 9 minutes of duration")
4682 (defconst org-stamp-time-of-day-regexp
4683 (concat
4684 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4685 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4686 "\\(--?"
4687 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4688 "Regular expression to match a timestamp time or time range.
4689 After a match, the following groups carry important information:
4690 0 the full match
4691 1 date plus weekday, for back referencing to make sure both times are on the same day
4692 2 the first time, range or not
4693 4 the second time, if it is a range.")
4695 (defconst org-startup-options
4696 '(("fold" org-startup-folded t)
4697 ("overview" org-startup-folded t)
4698 ("nofold" org-startup-folded nil)
4699 ("showall" org-startup-folded nil)
4700 ("showeverything" org-startup-folded showeverything)
4701 ("content" org-startup-folded content)
4702 ("indent" org-startup-indented t)
4703 ("noindent" org-startup-indented nil)
4704 ("hidestars" org-hide-leading-stars t)
4705 ("showstars" org-hide-leading-stars nil)
4706 ("odd" org-odd-levels-only t)
4707 ("oddeven" org-odd-levels-only nil)
4708 ("align" org-startup-align-all-tables t)
4709 ("noalign" org-startup-align-all-tables nil)
4710 ("inlineimages" org-startup-with-inline-images t)
4711 ("noinlineimages" org-startup-with-inline-images nil)
4712 ("latexpreview" org-startup-with-latex-preview t)
4713 ("nolatexpreview" org-startup-with-latex-preview nil)
4714 ("customtime" org-display-custom-times t)
4715 ("logdone" org-log-done time)
4716 ("lognotedone" org-log-done note)
4717 ("nologdone" org-log-done nil)
4718 ("lognoteclock-out" org-log-note-clock-out t)
4719 ("nolognoteclock-out" org-log-note-clock-out nil)
4720 ("logrepeat" org-log-repeat state)
4721 ("lognoterepeat" org-log-repeat note)
4722 ("logdrawer" org-log-into-drawer t)
4723 ("nologdrawer" org-log-into-drawer nil)
4724 ("logstatesreversed" org-log-states-order-reversed t)
4725 ("nologstatesreversed" org-log-states-order-reversed nil)
4726 ("nologrepeat" org-log-repeat nil)
4727 ("logreschedule" org-log-reschedule time)
4728 ("lognotereschedule" org-log-reschedule note)
4729 ("nologreschedule" org-log-reschedule nil)
4730 ("logredeadline" org-log-redeadline time)
4731 ("lognoteredeadline" org-log-redeadline note)
4732 ("nologredeadline" org-log-redeadline nil)
4733 ("logrefile" org-log-refile time)
4734 ("lognoterefile" org-log-refile note)
4735 ("nologrefile" org-log-refile nil)
4736 ("fninline" org-footnote-define-inline t)
4737 ("nofninline" org-footnote-define-inline nil)
4738 ("fnlocal" org-footnote-section nil)
4739 ("fnauto" org-footnote-auto-label t)
4740 ("fnprompt" org-footnote-auto-label nil)
4741 ("fnconfirm" org-footnote-auto-label confirm)
4742 ("fnplain" org-footnote-auto-label plain)
4743 ("fnadjust" org-footnote-auto-adjust t)
4744 ("nofnadjust" org-footnote-auto-adjust nil)
4745 ("constcgs" constants-unit-system cgs)
4746 ("constSI" constants-unit-system SI)
4747 ("noptag" org-tag-persistent-alist nil)
4748 ("hideblocks" org-hide-block-startup t)
4749 ("nohideblocks" org-hide-block-startup nil)
4750 ("beamer" org-startup-with-beamer-mode t)
4751 ("entitiespretty" org-pretty-entities t)
4752 ("entitiesplain" org-pretty-entities nil))
4753 "Variable associated with STARTUP options for org-mode.
4754 Each element is a list of three items: the startup options (as written
4755 in the #+STARTUP line), the corresponding variable, and the value to set
4756 this variable to if the option is found. An optional forth element PUSH
4757 means to push this value onto the list in the variable.")
4759 (defun org-update-property-plist (key val props)
4760 "Update PROPS with KEY and VAL."
4761 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4762 (key (if appending (substring key 0 (- (length key) 1)) key))
4763 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4764 (previous (cdr (assoc key props))))
4765 (if appending
4766 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4767 (cons (cons key val) remainder))))
4769 (defconst org-block-regexp
4770 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4771 "Regular expression for hiding blocks.")
4772 (defconst org-heading-keyword-regexp-format
4773 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4774 "Printf format for a regexp matching a headline with some keyword.
4775 This regexp will match the headline of any node which has the
4776 exact keyword that is put into the format. The keyword isn't in
4777 any group by default, but the stars and the body are.")
4778 (defconst org-heading-keyword-maybe-regexp-format
4779 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4780 "Printf format for a regexp matching a headline, possibly with some keyword.
4781 This regexp can match any headline with the specified keyword, or
4782 without a keyword. The keyword isn't in any group by default,
4783 but the stars and the body are.")
4785 (defcustom org-group-tags t
4786 "When non-nil (the default), use group tags.
4787 This can be turned on/off through `org-toggle-tags-groups'."
4788 :group 'org-tags
4789 :group 'org-startup
4790 :type 'boolean)
4792 (defun org-toggle-tags-groups ()
4793 "Toggle support for group tags.
4794 Support for group tags is controlled by the option
4795 `org-group-tags', which is non-nil by default."
4796 (interactive)
4797 (setq org-group-tags (not org-group-tags))
4798 (cond ((and (derived-mode-p 'org-agenda-mode)
4799 org-group-tags)
4800 (org-agenda-redo))
4801 ((derived-mode-p 'org-mode)
4802 (let ((org-inhibit-startup t)) (org-mode))))
4803 (message "Groups tags support has been turned %s"
4804 (if org-group-tags "on" "off")))
4806 (defun org-set-regexps-and-options-for-tags ()
4807 "Precompute variables used for tags."
4808 (when (derived-mode-p 'org-mode)
4809 (org-set-local 'org-file-tags nil)
4810 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4811 (splitre "[ \t]+")
4812 (start 0)
4813 tags ftags key value)
4814 (save-excursion
4815 (save-restriction
4816 (widen)
4817 (goto-char (point-min))
4818 (while (re-search-forward re nil t)
4819 (setq key (upcase (org-match-string-no-properties 1))
4820 value (org-match-string-no-properties 2))
4821 (if (stringp value) (setq value (org-trim value)))
4822 (cond
4823 ((equal key "TAGS")
4824 (setq tags (append tags (if tags '("\\n") nil)
4825 (org-split-string value splitre))))
4826 ((equal key "FILETAGS")
4827 (when (string-match "\\S-" value)
4828 (setq ftags
4829 (append
4830 ftags
4831 (apply 'append
4832 (mapcar (lambda (x) (org-split-string x ":"))
4833 (org-split-string value)))))))))))
4834 ;; Process the file tags.
4835 (and ftags (org-set-local 'org-file-tags
4836 (mapcar 'org-add-prop-inherited ftags)))
4837 (org-set-local 'org-tag-groups-alist nil)
4838 ;; Process the tags.
4839 ;; FIXME
4840 (when tags
4841 (let (e tgs g)
4842 (while (setq e (pop tags))
4843 (cond
4844 ((equal e "{")
4845 (progn (push '(:startgroup) tgs)
4846 (when (equal (nth 1 tags) ":")
4847 (push (list (replace-regexp-in-string
4848 "(.+)$" "" (nth 0 tags)))
4849 org-tag-groups-alist)
4850 (setq g 0))))
4851 ((equal e ":") (push '(:grouptags) tgs))
4852 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4853 ((equal e "\\n") (push '(:newline) tgs))
4854 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4855 (push (cons (match-string 1 e)
4856 (string-to-char (match-string 2 e))) tgs)
4857 (if (and g (> g 0))
4858 (setcar org-tag-groups-alist
4859 (append (car org-tag-groups-alist)
4860 (list (match-string 1 e)))))
4861 (if g (setq g (1+ g))))
4862 (t (push (list e) tgs)
4863 (if (and g (> g 0))
4864 (setcar org-tag-groups-alist
4865 (append (car org-tag-groups-alist) (list e))))
4866 (if g (setq g (1+ g))))))
4867 (org-set-local 'org-tag-alist nil)
4868 (while (setq e (pop tgs))
4869 (or (and (stringp (car e))
4870 (assoc (car e) org-tag-alist))
4871 (push e org-tag-alist)))
4872 ;; Return a list with tag variables
4873 (list org-file-tags org-tag-alist org-tag-groups-alist))))))
4875 (defvar org-ota nil)
4876 (defun org-set-regexps-and-options ()
4877 "Precompute regular expressions used in the current buffer."
4878 (when (derived-mode-p 'org-mode)
4879 (org-set-local 'org-todo-kwd-alist nil)
4880 (org-set-local 'org-todo-key-alist nil)
4881 (org-set-local 'org-todo-key-trigger nil)
4882 (org-set-local 'org-todo-keywords-1 nil)
4883 (org-set-local 'org-done-keywords nil)
4884 (org-set-local 'org-todo-heads nil)
4885 (org-set-local 'org-todo-sets nil)
4886 (org-set-local 'org-todo-log-states nil)
4887 (org-set-local 'org-file-properties nil)
4888 (let ((re (org-make-options-regexp
4889 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4890 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4891 "SETUPFILE" "OPTIONS")
4892 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4893 (splitre "[ \t]+")
4894 (scripts org-use-sub-superscripts)
4895 kwds kws0 kwsa key log value cat arch const links hw dws
4896 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4897 (start 0))
4898 (save-excursion
4899 (save-restriction
4900 (widen)
4901 (goto-char (point-min))
4902 (while
4903 (or (and
4904 ext-setup-or-nil
4905 (not org-ota)
4906 (let (ret)
4907 (with-temp-buffer
4908 (insert ext-setup-or-nil)
4909 (let ((major-mode 'org-mode) org-ota)
4910 (setq ret (save-match-data
4911 (org-set-regexps-and-options-for-tags)))))
4912 ;; Append setupfile tags to existing tags
4913 (setq org-file-tags
4914 (delq nil (append org-file-tags (nth 0 ret)))
4915 org-tag-alist
4916 (delq nil (append org-tag-alist (nth 1 ret)))
4917 org-tag-groups-alist
4918 (delq nil (append org-tag-groups-alist (nth 2 ret)))
4919 org-ota t)))
4920 (and ext-setup-or-nil
4921 (string-match re ext-setup-or-nil start)
4922 (setq start (match-end 0)))
4923 (and (setq ext-setup-or-nil nil start 0)
4924 (re-search-forward re nil t)))
4925 (setq key (upcase (match-string 1 ext-setup-or-nil))
4926 value (org-match-string-no-properties 2 ext-setup-or-nil))
4927 (if (stringp value) (setq value (org-trim value)))
4928 (cond
4929 ((equal key "CATEGORY")
4930 (setq cat value))
4931 ((member key '("SEQ_TODO" "TODO"))
4932 (push (cons 'sequence (org-split-string value splitre)) kwds))
4933 ((equal key "TYP_TODO")
4934 (push (cons 'type (org-split-string value splitre)) kwds))
4935 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4936 ;; general TODO-like setup
4937 (push (cons (intern (downcase (match-string 1 key)))
4938 (org-split-string value splitre)) kwds))
4939 ((equal key "COLUMNS")
4940 (org-set-local 'org-columns-default-format value))
4941 ((equal key "LINK")
4942 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4943 (push (cons (match-string 1 value)
4944 (org-trim (match-string 2 value)))
4945 links)))
4946 ((equal key "PRIORITIES")
4947 (setq prio (org-split-string value " +")))
4948 ((equal key "PROPERTY")
4949 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4950 (setq props (org-update-property-plist (match-string 1 value)
4951 (match-string 2 value)
4952 props))))
4953 ((equal key "DRAWERS")
4954 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4955 ((equal key "CONSTANTS")
4956 (org-table-set-constants))
4957 ((equal key "STARTUP")
4958 (let ((opts (org-split-string value splitre))
4959 l var val)
4960 (while (setq l (pop opts))
4961 (when (setq l (assoc l org-startup-options))
4962 (setq var (nth 1 l) val (nth 2 l))
4963 (if (not (nth 3 l))
4964 (set (make-local-variable var) val)
4965 (if (not (listp (symbol-value var)))
4966 (set (make-local-variable var) nil))
4967 (set (make-local-variable var) (symbol-value var))
4968 (add-to-list var val))))))
4969 ((equal key "ARCHIVE")
4970 (setq arch value)
4971 (remove-text-properties 0 (length arch)
4972 '(face t fontified t) arch))
4973 ((equal key "OPTIONS")
4974 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4975 (setq scripts (read (match-string 2 value)))))
4976 ((and (equal key "SETUPFILE")
4977 ;; Prevent checking in Gnus messages
4978 (not buffer-read-only))
4979 (setq setup-contents (org-file-contents
4980 (expand-file-name
4981 (org-remove-double-quotes value))
4982 'noerror))
4983 (if (not ext-setup-or-nil)
4984 (setq ext-setup-or-nil setup-contents start 0)
4985 (setq ext-setup-or-nil
4986 (concat (substring ext-setup-or-nil 0 start)
4987 "\n" setup-contents "\n"
4988 (substring ext-setup-or-nil start)))))))
4989 ;; search for property blocks
4990 (goto-char (point-min))
4991 (while (re-search-forward org-block-regexp nil t)
4992 (when (equal "PROPERTY" (upcase (match-string 1)))
4993 (setq value (replace-regexp-in-string
4994 "[\n\r]" " " (match-string 4)))
4995 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4996 (setq props (org-update-property-plist (match-string 1 value)
4997 (match-string 2 value)
4998 props)))))))
4999 (org-set-local 'org-use-sub-superscripts scripts)
5000 (when cat
5001 (org-set-local 'org-category (intern cat))
5002 (push (cons "CATEGORY" cat) props))
5003 (when prio
5004 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5005 (setq prio (mapcar 'string-to-char prio))
5006 (org-set-local 'org-highest-priority (nth 0 prio))
5007 (org-set-local 'org-lowest-priority (nth 1 prio))
5008 (org-set-local 'org-default-priority (nth 2 prio)))
5009 (and props (org-set-local 'org-file-properties (nreverse props)))
5010 (and drawers (org-set-local 'org-drawers drawers))
5011 (and arch (org-set-local 'org-archive-location arch))
5012 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5013 ;; Process the TODO keywords
5014 (unless kwds
5015 ;; Use the global values as if they had been given locally.
5016 (setq kwds (default-value 'org-todo-keywords))
5017 (if (stringp (car kwds))
5018 (setq kwds (list (cons org-todo-interpretation
5019 (default-value 'org-todo-keywords)))))
5020 (setq kwds (reverse kwds)))
5021 (setq kwds (nreverse kwds))
5022 (let (inter kws kw)
5023 (while (setq kws (pop kwds))
5024 (let ((kws (or
5025 (run-hook-with-args-until-success
5026 'org-todo-setup-filter-hook kws)
5027 kws)))
5028 (setq inter (pop kws) sep (member "|" kws)
5029 kws0 (delete "|" (copy-sequence kws))
5030 kwsa nil
5031 kws1 (mapcar
5032 (lambda (x)
5033 ;; 1 2
5034 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5035 (progn
5036 (setq kw (match-string 1 x)
5037 key (and (match-end 2) (match-string 2 x))
5038 log (org-extract-log-state-settings x))
5039 (push (cons kw (and key (string-to-char key))) kwsa)
5040 (and log (push log org-todo-log-states))
5042 (error "Invalid TODO keyword %s" x)))
5043 kws0)
5044 kwsa (if kwsa (append '((:startgroup))
5045 (nreverse kwsa)
5046 '((:endgroup))))
5047 hw (car kws1)
5048 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5049 tail (list inter hw (car dws) (org-last dws))))
5050 (add-to-list 'org-todo-heads hw 'append)
5051 (push kws1 org-todo-sets)
5052 (setq org-done-keywords (append org-done-keywords dws nil))
5053 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5054 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5055 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5056 (setq org-todo-sets (nreverse org-todo-sets)
5057 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5058 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5059 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5060 ;; Compute the regular expressions and other local variables.
5061 ;; Using `org-outline-regexp-bol' would complicate them much,
5062 ;; because of the fixed white space at the end of that string.
5063 (if (not org-done-keywords)
5064 (setq org-done-keywords (and org-todo-keywords-1
5065 (list (org-last org-todo-keywords-1)))))
5066 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5067 (length org-scheduled-string)
5068 (length org-clock-string)
5069 (length org-closed-string)))
5070 org-drawer-regexp
5071 (concat "^[ \t]*:\\("
5072 (mapconcat 'regexp-quote org-drawers "\\|")
5073 "\\):[ \t]*$")
5074 org-not-done-keywords
5075 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5076 org-todo-regexp
5077 (concat "\\("
5078 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5079 "\\)")
5080 org-not-done-regexp
5081 (concat "\\("
5082 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5083 "\\)")
5084 org-not-done-heading-regexp
5085 (format org-heading-keyword-regexp-format org-not-done-regexp)
5086 org-todo-line-regexp
5087 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5088 org-complex-heading-regexp
5089 (concat "^\\(\\*+\\)"
5090 "\\(?: +" org-todo-regexp "\\)?"
5091 "\\(?: +\\(\\[#.\\]\\)\\)?"
5092 "\\(?: +\\(.*?\\)\\)??"
5093 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5094 "[ \t]*$")
5095 org-complex-heading-regexp-format
5096 (concat "^\\(\\*+\\)"
5097 "\\(?: +" org-todo-regexp "\\)?"
5098 "\\(?: +\\(\\[#.\\]\\)\\)?"
5099 "\\(?: +"
5100 ;; Stats cookies can be stuck to body.
5101 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5102 "\\(%s\\)"
5103 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5104 "\\)"
5105 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5106 "[ \t]*$")
5107 org-todo-line-tags-regexp
5108 (concat "^\\(\\*+\\)"
5109 "\\(?: +" org-todo-regexp "\\)?"
5110 "\\(?: +\\(.*?\\)\\)??"
5111 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5112 "[ \t]*$")
5113 org-deadline-regexp (concat "\\<" org-deadline-string)
5114 org-deadline-time-regexp
5115 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5116 org-deadline-time-hour-regexp
5117 (concat "\\<" org-deadline-string
5118 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5119 org-deadline-line-regexp
5120 (concat "\\<\\(" org-deadline-string "\\).*")
5121 org-scheduled-regexp
5122 (concat "\\<" org-scheduled-string)
5123 org-scheduled-time-regexp
5124 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5125 org-scheduled-time-hour-regexp
5126 (concat "\\<" org-scheduled-string
5127 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5128 org-closed-time-regexp
5129 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5130 org-keyword-time-regexp
5131 (concat "\\<\\(" org-scheduled-string
5132 "\\|" org-deadline-string
5133 "\\|" org-closed-string
5134 "\\|" org-clock-string "\\)"
5135 " *[[<]\\([^]>]+\\)[]>]")
5136 org-keyword-time-not-clock-regexp
5137 (concat "\\<\\(" org-scheduled-string
5138 "\\|" org-deadline-string
5139 "\\|" org-closed-string
5140 "\\)"
5141 " *[[<]\\([^]>]+\\)[]>]")
5142 org-maybe-keyword-time-regexp
5143 (concat "\\(\\<\\(" org-scheduled-string
5144 "\\|" org-deadline-string
5145 "\\|" org-closed-string
5146 "\\|" org-clock-string "\\)\\)?"
5147 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5148 org-all-time-keywords
5149 (mapcar (lambda (w) (substring w 0 -1))
5150 (list org-scheduled-string org-deadline-string
5151 org-clock-string org-closed-string)))
5152 (setq org-ota nil)
5153 (org-compute-latex-and-related-regexp))))
5155 (defun org-file-contents (file &optional noerror)
5156 "Return the contents of FILE, as a string."
5157 (if (or (not file)
5158 (not (file-readable-p file)))
5159 (if noerror
5160 (message "Cannot read file \"%s\"" file)
5161 (error "Cannot read file \"%s\"" file))
5162 (with-temp-buffer
5163 (insert-file-contents file)
5164 (buffer-string))))
5166 (defun org-extract-log-state-settings (x)
5167 "Extract the log state setting from a TODO keyword string.
5168 This will extract info from a string like \"WAIT(w@/!)\"."
5169 (let (kw key log1 log2)
5170 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5171 (setq kw (match-string 1 x)
5172 key (and (match-end 2) (match-string 2 x))
5173 log1 (and (match-end 3) (match-string 3 x))
5174 log2 (and (match-end 4) (match-string 4 x)))
5175 (and (or log1 log2)
5176 (list kw
5177 (and log1 (if (equal log1 "!") 'time 'note))
5178 (and log2 (if (equal log2 "!") 'time 'note)))))))
5180 (defun org-remove-keyword-keys (list)
5181 "Remove a pair of parenthesis at the end of each string in LIST."
5182 (mapcar (lambda (x)
5183 (if (string-match "(.*)$" x)
5184 (substring x 0 (match-beginning 0))
5186 list))
5188 (defun org-assign-fast-keys (alist)
5189 "Assign fast keys to a keyword-key alist.
5190 Respect keys that are already there."
5191 (let (new e (alt ?0))
5192 (while (setq e (pop alist))
5193 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5194 (cdr e)) ;; Key already assigned.
5195 (push e new)
5196 (let ((clist (string-to-list (downcase (car e))))
5197 (used (append new alist)))
5198 (when (= (car clist) ?@)
5199 (pop clist))
5200 (while (and clist (rassoc (car clist) used))
5201 (pop clist))
5202 (unless clist
5203 (while (rassoc alt used)
5204 (incf alt)))
5205 (push (cons (car e) (or (car clist) alt)) new))))
5206 (nreverse new)))
5208 ;;; Some variables used in various places
5210 (defvar org-window-configuration nil
5211 "Used in various places to store a window configuration.")
5212 (defvar org-selected-window nil
5213 "Used in various places to store a window configuration.")
5214 (defvar org-finish-function nil
5215 "Function to be called when `C-c C-c' is used.
5216 This is for getting out of special buffers like capture.")
5219 ;; FIXME: Occasionally check by commenting these, to make sure
5220 ;; no other functions uses these, forgetting to let-bind them.
5221 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5222 (defvar org-last-state)
5223 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5225 ;; Defined somewhere in this file, but used before definition.
5226 (defvar org-entities) ;; defined in org-entities.el
5227 (defvar org-struct-menu)
5228 (defvar org-org-menu)
5229 (defvar org-tbl-menu)
5231 ;;;; Define the Org-mode
5233 ;; We use a before-change function to check if a table might need
5234 ;; an update.
5235 (defvar org-table-may-need-update t
5236 "Indicates that a table might need an update.
5237 This variable is set by `org-before-change-function'.
5238 `org-table-align' sets it back to nil.")
5239 (defun org-before-change-function (beg end)
5240 "Every change indicates that a table might need an update."
5241 (setq org-table-may-need-update t))
5242 (defvar org-mode-map)
5243 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5244 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5245 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5246 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5247 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5248 (defvar org-table-buffer-is-an nil)
5250 (defvar bidi-paragraph-direction)
5251 (defvar buffer-face-mode-face)
5253 (require 'outline)
5254 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5255 (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"))
5256 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5258 ;; Other stuff we need.
5259 (require 'time-date)
5260 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5261 (require 'easymenu)
5262 (require 'overlay)
5264 ;; (require 'org-macs) moved higher up in the file before it is first used
5265 (require 'org-entities)
5266 ;; (require 'org-compat) moved higher up in the file before it is first used
5267 (require 'org-faces)
5268 (require 'org-list)
5269 (require 'org-pcomplete)
5270 (require 'org-src)
5271 (require 'org-footnote)
5272 (require 'org-macro)
5274 ;; babel
5275 (require 'ob)
5277 ;;;###autoload
5278 (define-derived-mode org-mode outline-mode "Org"
5279 "Outline-based notes management and organizer, alias
5280 \"Carsten's outline-mode for keeping track of everything.\"
5282 Org-mode develops organizational tasks around a NOTES file which
5283 contains information about projects as plain text. Org-mode is
5284 implemented on top of outline-mode, which is ideal to keep the content
5285 of large files well structured. It supports ToDo items, deadlines and
5286 time stamps, which magically appear in the diary listing of the Emacs
5287 calendar. Tables are easily created with a built-in table editor.
5288 Plain text URL-like links connect to websites, emails (VM), Usenet
5289 messages (Gnus), BBDB entries, and any files related to the project.
5290 For printing and sharing of notes, an Org-mode file (or a part of it)
5291 can be exported as a structured ASCII or HTML file.
5293 The following commands are available:
5295 \\{org-mode-map}"
5297 ;; Get rid of Outline menus, they are not needed
5298 ;; Need to do this here because define-derived-mode sets up
5299 ;; the keymap so late. Still, it is a waste to call this each time
5300 ;; we switch another buffer into org-mode.
5301 (if (featurep 'xemacs)
5302 (when (boundp 'outline-mode-menu-heading)
5303 ;; Assume this is Greg's port, it uses easymenu
5304 (easy-menu-remove outline-mode-menu-heading)
5305 (easy-menu-remove outline-mode-menu-show)
5306 (easy-menu-remove outline-mode-menu-hide))
5307 (define-key org-mode-map [menu-bar headings] 'undefined)
5308 (define-key org-mode-map [menu-bar hide] 'undefined)
5309 (define-key org-mode-map [menu-bar show] 'undefined))
5311 (org-load-modules-maybe)
5312 (easy-menu-add org-org-menu)
5313 (easy-menu-add org-tbl-menu)
5314 (org-install-agenda-files-menu)
5315 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5316 (add-to-invisibility-spec '(org-cwidth))
5317 (add-to-invisibility-spec '(org-hide-block . t))
5318 (when (featurep 'xemacs)
5319 (org-set-local 'line-move-ignore-invisible t))
5320 (org-set-local 'outline-regexp org-outline-regexp)
5321 (org-set-local 'outline-level 'org-outline-level)
5322 (setq bidi-paragraph-direction 'left-to-right)
5323 (when (and org-ellipsis
5324 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5325 (fboundp 'make-glyph-code))
5326 (unless org-display-table
5327 (setq org-display-table (make-display-table)))
5328 (set-display-table-slot
5329 org-display-table 4
5330 (vconcat (mapcar
5331 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5332 org-ellipsis)))
5333 (if (stringp org-ellipsis) org-ellipsis "..."))))
5334 (setq buffer-display-table org-display-table))
5335 (org-set-regexps-and-options-for-tags)
5336 (org-set-regexps-and-options)
5337 (org-set-font-lock-defaults)
5338 (when (and org-tag-faces (not org-tags-special-faces-re))
5339 ;; tag faces set outside customize.... force initialization.
5340 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5341 ;; Calc embedded
5342 (org-set-local 'calc-embedded-open-mode "# ")
5343 ;; Modify a few syntax entries
5344 (modify-syntax-entry ?@ "w")
5345 (modify-syntax-entry ?\" "\"")
5346 (if org-startup-truncated (setq truncate-lines t))
5347 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5348 (org-set-local 'font-lock-unfontify-region-function
5349 'org-unfontify-region)
5350 ;; Activate before-change-function
5351 (org-set-local 'org-table-may-need-update t)
5352 (org-add-hook 'before-change-functions 'org-before-change-function nil
5353 'local)
5354 ;; Check for running clock before killing a buffer
5355 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5356 ;; Initialize macros templates.
5357 (org-macro-initialize-templates)
5358 ;; Initialize radio targets.
5359 (org-update-radio-target-regexp)
5360 ;; Indentation.
5361 (org-set-local 'indent-line-function 'org-indent-line)
5362 (org-set-local 'indent-region-function 'org-indent-region)
5363 ;; Filling and auto-filling.
5364 (org-setup-filling)
5365 ;; Comments.
5366 (org-setup-comments-handling)
5367 ;; Beginning/end of defun
5368 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5369 (org-set-local 'end-of-defun-function 'org-forward-element)
5370 ;; Next error for sparse trees
5371 (org-set-local 'next-error-function 'org-occur-next-match)
5372 ;; Make sure dependence stuff works reliably, even for users who set it
5373 ;; too late :-(
5374 (if org-enforce-todo-dependencies
5375 (add-hook 'org-blocker-hook
5376 'org-block-todo-from-children-or-siblings-or-parent)
5377 (remove-hook 'org-blocker-hook
5378 'org-block-todo-from-children-or-siblings-or-parent))
5379 (if org-enforce-todo-checkbox-dependencies
5380 (add-hook 'org-blocker-hook
5381 'org-block-todo-from-checkboxes)
5382 (remove-hook 'org-blocker-hook
5383 'org-block-todo-from-checkboxes))
5385 ;; Align options lines
5386 (org-set-local
5387 'align-mode-rules-list
5388 '((org-in-buffer-settings
5389 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5390 (modes . '(org-mode)))))
5392 ;; Imenu
5393 (org-set-local 'imenu-create-index-function
5394 'org-imenu-get-tree)
5396 ;; Make isearch reveal context
5397 (if (or (featurep 'xemacs)
5398 (not (boundp 'outline-isearch-open-invisible-function)))
5399 ;; Emacs 21 and XEmacs make use of the hook
5400 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5401 ;; Emacs 22 deals with this through a special variable
5402 (org-set-local 'outline-isearch-open-invisible-function
5403 (lambda (&rest ignore) (org-show-context 'isearch)))
5404 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5406 ;; Setup the pcomplete hooks
5407 (set (make-local-variable 'pcomplete-command-completion-function)
5408 'org-pcomplete-initial)
5409 (set (make-local-variable 'pcomplete-command-name-function)
5410 'org-command-at-point)
5411 (set (make-local-variable 'pcomplete-default-completion-function)
5412 'ignore)
5413 (set (make-local-variable 'pcomplete-parse-arguments-function)
5414 'org-parse-arguments)
5415 (set (make-local-variable 'pcomplete-termination-string) "")
5416 (when (>= emacs-major-version 23)
5417 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5419 ;; If empty file that did not turn on org-mode automatically, make it to.
5420 (if (and org-insert-mode-line-in-empty-file
5421 (org-called-interactively-p 'any)
5422 (= (point-min) (point-max)))
5423 (insert "# -*- mode: org -*-\n\n"))
5424 (unless org-inhibit-startup
5425 (org-unmodified
5426 (and org-startup-with-beamer-mode (org-beamer-mode))
5427 (when org-startup-align-all-tables
5428 (org-table-map-tables 'org-table-align 'quietly))
5429 (when org-startup-with-inline-images
5430 (org-display-inline-images))
5431 (when org-startup-with-latex-preview
5432 (org-preview-latex-fragment))
5433 (unless org-inhibit-startup-visibility-stuff
5434 (org-set-startup-visibility))))
5435 ;; Try to set org-hide correctly
5436 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5438 ;; Update `customize-package-emacs-version-alist'
5439 (add-to-list 'customize-package-emacs-version-alist
5440 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5441 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5442 ("8.0" . "24.4")))
5444 (defvar org-mode-transpose-word-syntax-table
5445 (let ((st (make-syntax-table)))
5446 (mapc (lambda(c) (modify-syntax-entry
5447 (string-to-char (car c)) "w p" st))
5448 org-emphasis-alist)
5449 st))
5451 (when (fboundp 'abbrev-table-put)
5452 (abbrev-table-put org-mode-abbrev-table
5453 :parents (list text-mode-abbrev-table)))
5455 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5457 (defsubst org-fix-ellipsis-at-bol ()
5458 (save-excursion (goto-char (window-start)) (recenter 0)))
5460 (defun org-find-invisible-foreground ()
5461 (let ((candidates (remove
5462 "unspecified-bg"
5463 (nconc
5464 (list (face-background 'default)
5465 (face-background 'org-default))
5466 (mapcar
5467 (lambda (alist)
5468 (when (boundp alist)
5469 (cdr (assoc 'background-color (symbol-value alist)))))
5470 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5471 (list (face-foreground 'org-hide))))))
5472 (car (remove nil candidates))))
5474 (defun org-current-time (&optional rounding-minutes past)
5475 "Current time, possibly rounded to ROUNDING-MINUTES.
5476 When ROUNDING-MINUTES is not an integer, fall back on the car of
5477 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5478 the rounding returns a past time."
5479 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5480 (car org-time-stamp-rounding-minutes)))
5481 (time (decode-time)) res)
5482 (if (< r 1)
5483 (current-time)
5484 (setq res
5485 (apply 'encode-time
5486 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5487 (nthcdr 2 time))))
5488 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5489 (seconds-to-time (- (org-float-time res) (* r 60)))
5490 res))))
5492 (defun org-today ()
5493 "Return today date, considering `org-extend-today-until'."
5494 (time-to-days
5495 (time-subtract (current-time)
5496 (list 0 (* 3600 org-extend-today-until) 0))))
5498 ;;;; Font-Lock stuff, including the activators
5500 (defvar org-mouse-map (make-sparse-keymap))
5501 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5502 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5503 (when org-mouse-1-follows-link
5504 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5505 (when org-tab-follows-link
5506 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5507 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5509 (require 'font-lock)
5511 (defconst org-non-link-chars "]\t\n\r<>")
5512 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5513 "shell" "elisp" "doi" "message"))
5514 (defvar org-link-types-re nil
5515 "Matches a link that has a url-like prefix like \"http:\"")
5516 (defvar org-link-re-with-space nil
5517 "Matches a link with spaces, optional angular brackets around it.")
5518 (defvar org-link-re-with-space2 nil
5519 "Matches a link with spaces, optional angular brackets around it.")
5520 (defvar org-link-re-with-space3 nil
5521 "Matches a link with spaces, only for internal part in bracket links.")
5522 (defvar org-angle-link-re nil
5523 "Matches link with angular brackets, spaces are allowed.")
5524 (defvar org-plain-link-re nil
5525 "Matches plain link, without spaces.")
5526 (defvar org-bracket-link-regexp nil
5527 "Matches a link in double brackets.")
5528 (defvar org-bracket-link-analytic-regexp nil
5529 "Regular expression used to analyze links.
5530 Here is what the match groups contain after a match:
5531 1: http:
5532 2: http
5533 3: path
5534 4: [desc]
5535 5: desc")
5536 (defvar org-bracket-link-analytic-regexp++ nil
5537 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5538 (defvar org-any-link-re nil
5539 "Regular expression matching any link.")
5541 (defconst org-match-sexp-depth 3
5542 "Number of stacked braces for sub/superscript matching.")
5544 (defun org-create-multibrace-regexp (left right n)
5545 "Create a regular expression which will match a balanced sexp.
5546 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5547 as single character strings.
5548 The regexp returned will match the entire expression including the
5549 delimiters. It will also define a single group which contains the
5550 match except for the outermost delimiters. The maximum depth of
5551 stacked delimiters is N. Escaping delimiters is not possible."
5552 (let* ((nothing (concat "[^" left right "]*?"))
5553 (or "\\|")
5554 (re nothing)
5555 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5556 (while (> n 1)
5557 (setq n (1- n)
5558 re (concat re or next)
5559 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5560 (concat left "\\(" re "\\)" right)))
5562 (defvar org-match-substring-regexp
5563 (concat
5564 "\\(\\S-\\)\\([_^]\\)\\("
5565 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5566 "\\|"
5567 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5568 "\\|"
5569 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5570 "The regular expression matching a sub- or superscript.")
5572 (defvar org-match-substring-with-braces-regexp
5573 (concat
5574 "\\(\\S-\\)\\([_^]\\)\\("
5575 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5576 "\\)")
5577 "The regular expression matching a sub- or superscript, forcing braces.")
5579 (defun org-make-link-regexps ()
5580 "Update the link regular expressions.
5581 This should be called after the variable `org-link-types' has changed."
5582 (setq org-link-types-re
5583 (concat
5584 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5585 org-link-re-with-space
5586 (concat
5587 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5588 "\\([^" org-non-link-chars " ]"
5589 "[^" org-non-link-chars "]*"
5590 "[^" org-non-link-chars " ]\\)>?")
5591 org-link-re-with-space2
5592 (concat
5593 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5594 "\\([^" org-non-link-chars " ]"
5595 "[^\t\n\r]*"
5596 "[^" org-non-link-chars " ]\\)>?")
5597 org-link-re-with-space3
5598 (concat
5599 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5600 "\\([^" org-non-link-chars " ]"
5601 "[^\t\n\r]*\\)")
5602 org-angle-link-re
5603 (concat
5604 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5605 "\\([^" org-non-link-chars " ]"
5606 "[^" org-non-link-chars "]*"
5607 "\\)>")
5608 org-plain-link-re
5609 (concat
5610 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5611 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5612 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5613 org-bracket-link-regexp
5614 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5615 org-bracket-link-analytic-regexp
5616 (concat
5617 "\\[\\["
5618 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5619 "\\([^]]+\\)"
5620 "\\]"
5621 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5622 "\\]")
5623 org-bracket-link-analytic-regexp++
5624 (concat
5625 "\\[\\["
5626 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5627 "\\([^]]+\\)"
5628 "\\]"
5629 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5630 "\\]")
5631 org-any-link-re
5632 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5633 org-angle-link-re "\\)\\|\\("
5634 org-plain-link-re "\\)")))
5636 (org-make-link-regexps)
5638 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5639 "Regular expression for fast time stamp matching.")
5640 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5641 "Regular expression for fast time stamp matching.")
5642 (defconst org-ts-regexp0
5643 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5644 "Regular expression matching time strings for analysis.
5645 This one does not require the space after the date, so it can be used
5646 on a string that terminates immediately after the date.")
5647 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5648 "Regular expression matching time strings for analysis.")
5649 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5650 "Regular expression matching time stamps, with groups.")
5651 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5652 "Regular expression matching time stamps (also [..]), with groups.")
5653 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5654 "Regular expression matching a time stamp range.")
5655 (defconst org-tr-regexp-both
5656 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5657 "Regular expression matching a time stamp range.")
5658 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5659 org-ts-regexp "\\)?")
5660 "Regular expression matching a time stamp or time stamp range.")
5661 (defconst org-tsr-regexp-both
5662 (concat org-ts-regexp-both "\\(--?-?"
5663 org-ts-regexp-both "\\)?")
5664 "Regular expression matching a time stamp or time stamp range.
5665 The time stamps may be either active or inactive.")
5667 (defvar org-emph-face nil)
5669 (defun org-do-emphasis-faces (limit)
5670 "Run through the buffer and add overlays to emphasized strings."
5671 (let (rtn a)
5672 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5673 (if (not (= (char-after (match-beginning 3))
5674 (char-after (match-beginning 4))))
5675 (progn
5676 (setq rtn t)
5677 (setq a (assoc (match-string 3) org-emphasis-alist))
5678 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5679 'face
5680 (nth 1 a))
5681 (and (nth 4 a)
5682 (org-remove-flyspell-overlays-in
5683 (match-beginning 0) (match-end 0)))
5684 (add-text-properties (match-beginning 2) (match-end 2)
5685 '(font-lock-multiline t org-emphasis t))
5686 (when org-hide-emphasis-markers
5687 (add-text-properties (match-end 4) (match-beginning 5)
5688 '(invisible org-link))
5689 (add-text-properties (match-beginning 3) (match-end 3)
5690 '(invisible org-link)))))
5691 (backward-char 1))
5692 rtn))
5694 (defun org-emphasize (&optional char)
5695 "Insert or change an emphasis, i.e. a font like bold or italic.
5696 If there is an active region, change that region to a new emphasis.
5697 If there is no region, just insert the marker characters and position
5698 the cursor between them.
5699 CHAR should be the marker character. If it is a space, it means to
5700 remove the emphasis of the selected region.
5701 If CHAR is not given (for example in an interactive call) it will be
5702 prompted for."
5703 (interactive)
5704 (let ((erc org-emphasis-regexp-components)
5705 (prompt "")
5706 (string "") beg end move c s)
5707 (if (org-region-active-p)
5708 (setq beg (region-beginning) end (region-end)
5709 string (buffer-substring beg end))
5710 (setq move t))
5712 (unless char
5713 (message "Emphasis marker or tag: [%s]"
5714 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5715 (setq char (read-char-exclusive)))
5716 (if (equal char ?\ )
5717 (setq s "" move nil)
5718 (unless (assoc (char-to-string char) org-emphasis-alist)
5719 (user-error "No such emphasis marker: \"%c\"" char))
5720 (setq s (char-to-string char)))
5721 (while (and (> (length string) 1)
5722 (equal (substring string 0 1) (substring string -1))
5723 (assoc (substring string 0 1) org-emphasis-alist))
5724 (setq string (substring string 1 -1)))
5725 (setq string (concat s string s))
5726 (if beg (delete-region beg end))
5727 (unless (or (bolp)
5728 (string-match (concat "[" (nth 0 erc) "\n]")
5729 (char-to-string (char-before (point)))))
5730 (insert " "))
5731 (unless (or (eobp)
5732 (string-match (concat "[" (nth 1 erc) "\n]")
5733 (char-to-string (char-after (point)))))
5734 (insert " ") (backward-char 1))
5735 (insert string)
5736 (and move (backward-char 1))))
5738 (defconst org-nonsticky-props
5739 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5741 (defsubst org-rear-nonsticky-at (pos)
5742 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5744 (defun org-activate-plain-links (limit)
5745 "Run through the buffer and add overlays to links."
5746 (let (f hl)
5747 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5748 (not (org-in-src-block-p)))
5749 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5750 (setq f (get-text-property (match-beginning 0) 'face))
5751 (setq hl (org-match-string-no-properties 0))
5752 (if (or (eq f 'org-tag)
5753 (and (listp f) (memq 'org-tag f)))
5755 (add-text-properties (match-beginning 0) (match-end 0)
5756 (list 'mouse-face 'highlight
5757 'face 'org-link
5758 'htmlize-link `(:uri ,hl)
5759 'keymap org-mouse-map))
5760 (org-rear-nonsticky-at (match-end 0)))
5761 t)))
5763 (defun org-activate-code (limit)
5764 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5765 (progn
5766 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5767 (remove-text-properties (match-beginning 0) (match-end 0)
5768 '(display t invisible t intangible t))
5769 t)))
5771 (defcustom org-src-fontify-natively nil
5772 "When non-nil, fontify code in code blocks."
5773 :type 'boolean
5774 :version "24.1"
5775 :group 'org-appearance
5776 :group 'org-babel)
5778 (defcustom org-allow-promoting-top-level-subtree nil
5779 "When non-nil, allow promoting a top level subtree.
5780 The leading star of the top level headline will be replaced
5781 by a #."
5782 :type 'boolean
5783 :version "24.1"
5784 :group 'org-appearance)
5786 (defun org-fontify-meta-lines-and-blocks (limit)
5787 (condition-case nil
5788 (org-fontify-meta-lines-and-blocks-1 limit)
5789 (error (message "org-mode fontification error"))))
5791 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5792 "Fontify #+ lines and blocks."
5793 (let ((case-fold-search t))
5794 (if (re-search-forward
5795 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5796 limit t)
5797 (let ((beg (match-beginning 0))
5798 (block-start (match-end 0))
5799 (block-end nil)
5800 (lang (match-string 7))
5801 (beg1 (line-beginning-position 2))
5802 (dc1 (downcase (match-string 2)))
5803 (dc3 (downcase (match-string 3)))
5804 end end1 quoting block-type ovl)
5805 (cond
5806 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5807 ;; a single line of backend-specific content
5808 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5809 (remove-text-properties (match-beginning 0) (match-end 0)
5810 '(display t invisible t intangible t))
5811 (add-text-properties (match-beginning 1) (match-end 3)
5812 '(font-lock-fontified t face org-meta-line))
5813 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5814 '(font-lock-fontified t face org-block))
5815 ; for backend-specific code
5817 ((and (match-end 4) (equal dc3 "+begin"))
5818 ;; Truly a block
5819 (setq block-type (downcase (match-string 5))
5820 quoting (member block-type org-protecting-blocks))
5821 (when (re-search-forward
5822 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5823 nil t) ;; on purpose, we look further than LIMIT
5824 (setq end (min (point-max) (match-end 0))
5825 end1 (min (point-max) (1- (match-beginning 0))))
5826 (setq block-end (match-beginning 0))
5827 (when quoting
5828 (remove-text-properties beg end
5829 '(display t invisible t intangible t)))
5830 (add-text-properties
5831 beg end
5832 '(font-lock-fontified t font-lock-multiline t))
5833 (add-text-properties beg beg1 '(face org-meta-line))
5834 (add-text-properties end1 (min (point-max) (1+ end))
5835 '(face org-meta-line)) ; for end_src
5836 (cond
5837 ((and lang (not (string= lang "")) org-src-fontify-natively)
5838 (org-src-font-lock-fontify-block lang block-start block-end)
5839 ;; remove old background overlays
5840 (mapc (lambda (ov)
5841 (if (eq (overlay-get ov 'face) 'org-block-background)
5842 (delete-overlay ov)))
5843 (overlays-at (/ (+ beg1 block-end) 2)))
5844 ;; add a background overlay
5845 (setq ovl (make-overlay beg1 block-end))
5846 (overlay-put ovl 'face 'org-block-background)
5847 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5848 (quoting
5849 (add-text-properties beg1 (min (point-max) (1+ end1))
5850 '(face org-block))) ; end of source block
5851 ((not org-fontify-quote-and-verse-blocks))
5852 ((string= block-type "quote")
5853 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5854 ((string= block-type "verse")
5855 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5856 (add-text-properties beg beg1 '(face org-block-begin-line))
5857 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5858 '(face org-block-end-line))
5860 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5861 (add-text-properties
5862 beg (match-end 3)
5863 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5864 '(font-lock-fontified t invisible t)
5865 '(font-lock-fontified t face org-document-info-keyword)))
5866 (add-text-properties
5867 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5868 (if (string-equal dc1 "+title:")
5869 '(font-lock-fontified t face org-document-title)
5870 '(font-lock-fontified t face org-document-info))))
5871 ((or (equal dc1 "+results")
5872 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5873 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5874 "+call:" "+header:" "+headers:" "+name:"))
5875 (and (match-end 4) (equal dc3 "+attr")))
5876 (add-text-properties
5877 beg (match-end 0)
5878 '(font-lock-fontified t face org-meta-line))
5880 ((member dc3 '(" " ""))
5881 (add-text-properties
5882 beg (match-end 0)
5883 '(font-lock-fontified t face font-lock-comment-face)))
5884 ((not (member (char-after beg) '(?\ ?\t)))
5885 ;; just any other in-buffer setting, but not indented
5886 (add-text-properties
5887 beg (match-end 0)
5888 '(font-lock-fontified t face org-meta-line))
5890 (t nil))))))
5892 (defun org-activate-angle-links (limit)
5893 "Run through the buffer and add overlays to links."
5894 (if (and (re-search-forward org-angle-link-re limit t)
5895 (not (org-in-src-block-p)))
5896 (progn
5897 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5898 (add-text-properties (match-beginning 0) (match-end 0)
5899 (list 'mouse-face 'highlight
5900 'keymap org-mouse-map))
5901 (org-rear-nonsticky-at (match-end 0))
5902 t)))
5904 (defun org-activate-footnote-links (limit)
5905 "Run through the buffer and add overlays to footnotes."
5906 (let ((fn (org-footnote-next-reference-or-definition limit)))
5907 (when fn
5908 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5909 (org-remove-flyspell-overlays-in beg end)
5910 (add-text-properties beg end
5911 (list 'mouse-face 'highlight
5912 'keymap org-mouse-map
5913 'help-echo
5914 (if (= (point-at-bol) beg)
5915 "Footnote definition"
5916 "Footnote reference")
5917 'font-lock-fontified t
5918 'font-lock-multiline t
5919 'face 'org-footnote))))))
5921 (defun org-activate-bracket-links (limit)
5922 "Run through the buffer and add overlays to bracketed links."
5923 (if (and (re-search-forward org-bracket-link-regexp limit t)
5924 (not (org-in-src-block-p)))
5925 (let* ((hl (org-match-string-no-properties 1))
5926 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5927 (ip (org-maybe-intangible
5928 (list 'invisible 'org-link
5929 'keymap org-mouse-map 'mouse-face 'highlight
5930 'font-lock-multiline t 'help-echo help
5931 'htmlize-link `(:uri ,hl))))
5932 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5933 'font-lock-multiline t 'help-echo help
5934 'htmlize-link `(:uri ,hl))))
5935 ;; We need to remove the invisible property here. Table narrowing
5936 ;; may have made some of this invisible.
5937 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5938 (remove-text-properties (match-beginning 0) (match-end 0)
5939 '(invisible nil))
5940 (if (match-end 3)
5941 (progn
5942 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5943 (org-rear-nonsticky-at (match-beginning 3))
5944 (add-text-properties (match-beginning 3) (match-end 3) vp)
5945 (org-rear-nonsticky-at (match-end 3))
5946 (add-text-properties (match-end 3) (match-end 0) ip)
5947 (org-rear-nonsticky-at (match-end 0)))
5948 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5949 (org-rear-nonsticky-at (match-beginning 1))
5950 (add-text-properties (match-beginning 1) (match-end 1) vp)
5951 (org-rear-nonsticky-at (match-end 1))
5952 (add-text-properties (match-end 1) (match-end 0) ip)
5953 (org-rear-nonsticky-at (match-end 0)))
5954 t)))
5956 (defun org-activate-dates (limit)
5957 "Run through the buffer and add overlays to dates."
5958 (if (and (re-search-forward org-tsr-regexp-both limit t)
5959 (not (equal (char-before (match-beginning 0)) 91)))
5960 (progn
5961 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5962 (add-text-properties (match-beginning 0) (match-end 0)
5963 (list 'mouse-face 'highlight
5964 'keymap org-mouse-map))
5965 (org-rear-nonsticky-at (match-end 0))
5966 (when org-display-custom-times
5967 (if (match-end 3)
5968 (org-display-custom-time (match-beginning 3) (match-end 3)))
5969 (org-display-custom-time (match-beginning 1) (match-end 1)))
5970 t)))
5972 (defvar org-target-link-regexp nil
5973 "Regular expression matching radio targets in plain text.")
5974 (make-variable-buffer-local 'org-target-link-regexp)
5975 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5976 "Regular expression matching a link target.")
5977 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5978 "Regular expression matching a radio target.")
5979 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5980 "Regular expression matching any target.")
5982 (defun org-activate-target-links (limit)
5983 "Run through the buffer and add overlays to target matches."
5984 (when org-target-link-regexp
5985 (let ((case-fold-search t))
5986 (if (re-search-forward org-target-link-regexp limit t)
5987 (progn
5988 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5989 (add-text-properties (match-beginning 0) (match-end 0)
5990 (list 'mouse-face 'highlight
5991 'keymap org-mouse-map
5992 'help-echo "Radio target link"
5993 'org-linked-text t))
5994 (org-rear-nonsticky-at (match-end 0))
5995 t)))))
5997 (defun org-update-radio-target-regexp ()
5998 "Find all radio targets in this file and update the regular expression."
5999 (interactive)
6000 (when (memq 'radio org-activate-links)
6001 (setq org-target-link-regexp
6002 (org-make-target-link-regexp (org-all-targets 'radio)))
6003 (org-restart-font-lock)))
6005 (defun org-hide-wide-columns (limit)
6006 (let (s e)
6007 (setq s (text-property-any (point) (or limit (point-max))
6008 'org-cwidth t))
6009 (when s
6010 (setq e (next-single-property-change s 'org-cwidth))
6011 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6012 (goto-char e)
6013 t)))
6015 (defvar org-latex-and-related-regexp nil
6016 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6017 (defvar org-match-substring-regexp)
6018 (defvar org-match-substring-with-braces-regexp)
6020 (defun org-compute-latex-and-related-regexp ()
6021 "Compute regular expression for LaTeX, entities and sub/superscript.
6022 Result depends on variable `org-highlight-latex-and-related'."
6023 (org-set-local
6024 'org-latex-and-related-regexp
6025 (let* ((re-sub
6026 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6027 ((eq org-use-sub-superscripts '{})
6028 (list org-match-substring-with-braces-regexp))
6029 (org-use-sub-superscripts (list org-match-substring-regexp))))
6030 (re-latex
6031 (when (memq 'latex org-highlight-latex-and-related)
6032 (let ((matchers (plist-get org-format-latex-options :matchers)))
6033 (delq nil
6034 (mapcar (lambda (x)
6035 (and (member (car x) matchers) (nth 1 x)))
6036 org-latex-regexps)))))
6037 (re-entities
6038 (when (memq 'entities org-highlight-latex-and-related)
6039 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6040 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6042 (defun org-do-latex-and-related (limit)
6043 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6044 LIMIT bounds the search for syntax to highlight. Stop at first
6045 highlighted object, if any. Return t if some highlighting was
6046 done, nil otherwise."
6047 (when (org-string-nw-p org-latex-and-related-regexp)
6048 (catch 'found
6049 (while (re-search-forward org-latex-and-related-regexp limit t)
6050 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6051 'face))
6052 '(org-code org-verbatim underline))
6053 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6054 '(?_ ?^))
6056 0)))
6057 (font-lock-prepend-text-property
6058 (+ offset (match-beginning 0)) (match-end 0)
6059 'face 'org-latex-and-related)
6060 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6061 '(font-lock-multiline t)))
6062 (throw 'found t)))
6063 nil)))
6065 (defun org-restart-font-lock ()
6066 "Restart `font-lock-mode', to force refontification."
6067 (when (and (boundp 'font-lock-mode) font-lock-mode)
6068 (font-lock-mode -1)
6069 (font-lock-mode 1)))
6071 (defun org-all-targets (&optional radio)
6072 "Return a list of all targets in this file.
6073 When optional argument RADIO is non-nil, only find radio
6074 targets."
6075 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6076 (save-excursion
6077 (goto-char (point-min))
6078 (while (re-search-forward re nil t)
6079 ;; Make sure point is really within the object.
6080 (backward-char)
6081 (let ((obj (org-element-context)))
6082 (when (memq (org-element-type obj) '(radio-target target))
6083 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6084 rtn)))
6086 (defun org-make-target-link-regexp (targets)
6087 "Make regular expression matching all strings in TARGETS.
6088 The regular expression finds the targets also if there is a line break
6089 between words."
6090 (and targets
6091 (concat
6092 "\\<\\("
6093 (mapconcat
6094 (lambda (x)
6095 (setq x (regexp-quote x))
6096 (while (string-match " +" x)
6097 (setq x (replace-match "\\s-+" t t x)))
6099 targets
6100 "\\|")
6101 "\\)\\>")))
6103 (defun org-activate-tags (limit)
6104 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6105 (progn
6106 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6107 (add-text-properties (match-beginning 1) (match-end 1)
6108 (list 'mouse-face 'highlight
6109 'keymap org-mouse-map))
6110 (org-rear-nonsticky-at (match-end 1))
6111 t)))
6113 (defun org-outline-level ()
6114 "Compute the outline level of the heading at point.
6115 If this is called at a normal headline, the level is the number of stars.
6116 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6117 (save-excursion
6118 (if (not (condition-case nil
6119 (org-back-to-heading t)
6120 (error nil)))
6122 (looking-at org-outline-regexp)
6123 (1- (- (match-end 0) (match-beginning 0))))))
6125 (defvar org-font-lock-keywords nil)
6127 (defsubst org-re-property (property &optional literal)
6128 "Return a regexp matching a PROPERTY line.
6129 Match group 3 will be set to the value if it exists."
6130 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6131 (if literal property (regexp-quote property))
6132 "\\):\\)[ \t]+\\(?3:[^ \t\r\n].*?\\)\\(?5:[ \t]*\\)$"))
6134 (defconst org-property-re
6135 (org-re-property ".*?" 'literal)
6136 "Regular expression matching a property line.
6137 There are four matching groups:
6138 1: :PROPKEY: including the leading and trailing colon,
6139 2: PROPKEY without the leading and trailing colon,
6140 3: PROPVAL without leading or trailing spaces,
6141 4: the indentation of the current line,
6142 5: trailing whitespace.")
6144 (defvar org-font-lock-hook nil
6145 "Functions to be called for special font lock stuff.")
6147 (defvar org-font-lock-set-keywords-hook nil
6148 "Functions that can manipulate `org-font-lock-extra-keywords'.
6149 This is called after `org-font-lock-extra-keywords' is defined, but before
6150 it is installed to be used by font lock. This can be useful if something
6151 needs to be inserted at a specific position in the font-lock sequence.")
6153 (defun org-font-lock-hook (limit)
6154 "Run `org-font-lock-hook' within LIMIT."
6155 (run-hook-with-args 'org-font-lock-hook limit))
6157 (defun org-set-font-lock-defaults ()
6158 "Set font lock defaults for the current buffer."
6159 (let* ((em org-fontify-emphasized-text)
6160 (lk org-activate-links)
6161 (org-font-lock-extra-keywords
6162 (list
6163 ;; Call the hook
6164 '(org-font-lock-hook)
6165 ;; Headlines
6166 `(,(if org-fontify-whole-heading-line
6167 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6168 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6169 (1 (org-get-level-face 1))
6170 (2 (org-get-level-face 2))
6171 (3 (org-get-level-face 3)))
6172 ;; Table lines
6173 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6174 (1 'org-table t))
6175 ;; Table internals
6176 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6177 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6178 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6179 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6180 ;; Drawers
6181 (list org-drawer-regexp '(0 'org-special-keyword t))
6182 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6183 ;; Properties
6184 (list org-property-re
6185 '(1 'org-special-keyword t)
6186 '(3 'org-property-value t))
6187 ;; Links
6188 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6189 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6190 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6191 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6192 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6193 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6194 (if (memq 'footnote lk) '(org-activate-footnote-links))
6195 ;; Targets.
6196 (list org-any-target-regexp '(0 'org-target t))
6197 ;; Diary sexps.
6198 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6199 ;; Macro
6200 '("{{{.+}}}" (0 'org-macro t))
6201 '(org-hide-wide-columns (0 nil append))
6202 ;; TODO keyword
6203 (list (format org-heading-keyword-regexp-format
6204 org-todo-regexp)
6205 '(2 (org-get-todo-face 2) t))
6206 ;; DONE
6207 (if org-fontify-done-headline
6208 (list (format org-heading-keyword-regexp-format
6209 (concat
6210 "\\(?:"
6211 (mapconcat 'regexp-quote org-done-keywords "\\|")
6212 "\\)"))
6213 '(2 'org-headline-done t))
6214 nil)
6215 ;; Priorities
6216 '(org-font-lock-add-priority-faces)
6217 ;; Tags
6218 '(org-font-lock-add-tag-faces)
6219 ;; Tags groups
6220 (if (and org-group-tags org-tag-groups-alist)
6221 (list (concat org-outline-regexp-bol ".+\\(:"
6222 (regexp-opt (mapcar 'car org-tag-groups-alist))
6223 ":\\).*$")
6224 '(1 'org-tag-group prepend)))
6225 ;; Special keywords
6226 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6227 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6228 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6229 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6230 ;; Emphasis
6231 (if em
6232 (if (featurep 'xemacs)
6233 '(org-do-emphasis-faces (0 nil append))
6234 '(org-do-emphasis-faces)))
6235 ;; Checkboxes
6236 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6237 1 'org-checkbox prepend)
6238 (if (cdr (assq 'checkbox org-list-automatic-rules))
6239 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6240 (0 (org-get-checkbox-statistics-face) t)))
6241 ;; Description list items
6242 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6243 1 'org-list-dt prepend)
6244 ;; ARCHIVEd headings
6245 (list (concat
6246 org-outline-regexp-bol
6247 "\\(.*:" org-archive-tag ":.*\\)")
6248 '(1 'org-archived prepend))
6249 ;; Specials
6250 '(org-do-latex-and-related)
6251 '(org-fontify-entities)
6252 '(org-raise-scripts)
6253 ;; Code
6254 '(org-activate-code (1 'org-code t))
6255 ;; COMMENT
6256 (list (format org-heading-keyword-regexp-format
6257 (concat "\\("
6258 org-comment-string "\\|" org-quote-string
6259 "\\)"))
6260 '(2 'org-special-keyword t))
6261 ;; Blocks and meta lines
6262 '(org-fontify-meta-lines-and-blocks))))
6263 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6264 (run-hooks 'org-font-lock-set-keywords-hook)
6265 ;; Now set the full font-lock-keywords
6266 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6267 (org-set-local 'font-lock-defaults
6268 '(org-font-lock-keywords t nil nil backward-paragraph))
6269 (kill-local-variable 'font-lock-keywords) nil))
6271 (defun org-toggle-pretty-entities ()
6272 "Toggle the composition display of entities as UTF8 characters."
6273 (interactive)
6274 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6275 (org-restart-font-lock)
6276 (if org-pretty-entities
6277 (message "Entities are now displayed as UTF8 characters")
6278 (save-restriction
6279 (widen)
6280 (org-decompose-region (point-min) (point-max))
6281 (message "Entities are now displayed as plain text"))))
6283 (defvar org-custom-properties-overlays nil
6284 "List of overlays used for custom properties.")
6285 (make-variable-buffer-local 'org-custom-properties-overlays)
6287 (defun org-toggle-custom-properties-visibility ()
6288 "Display or hide properties in `org-custom-properties'."
6289 (interactive)
6290 (if org-custom-properties-overlays
6291 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6292 (setq org-custom-properties-overlays nil))
6293 (unless (not org-custom-properties)
6294 (save-excursion
6295 (save-restriction
6296 (widen)
6297 (goto-char (point-min))
6298 (while (re-search-forward org-property-re nil t)
6299 (mapc (lambda(p)
6300 (when (equal p (substring (match-string 1) 1 -1))
6301 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6302 (overlay-put o 'invisible t)
6303 (overlay-put o 'org-custom-property t)
6304 (push o org-custom-properties-overlays))))
6305 org-custom-properties)))))))
6307 (defun org-fontify-entities (limit)
6308 "Find an entity to fontify."
6309 (let (ee)
6310 (when org-pretty-entities
6311 (catch 'match
6312 (while (re-search-forward
6313 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6314 limit t)
6315 (if (and (not (org-in-indented-comment-line))
6316 (setq ee (org-entity-get (match-string 1)))
6317 (= (length (nth 6 ee)) 1))
6318 (let*
6319 ((end (if (equal (match-string 2) "{}")
6320 (match-end 2)
6321 (match-end 1))))
6322 (add-text-properties
6323 (match-beginning 0) end
6324 (list 'font-lock-fontified t))
6325 (compose-region (match-beginning 0) end
6326 (nth 6 ee) nil)
6327 (backward-char 1)
6328 (throw 'match t))))
6329 nil))))
6331 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6332 "Fontify string S like in Org-mode."
6333 (with-temp-buffer
6334 (insert s)
6335 (let ((org-odd-levels-only odd-levels))
6336 (org-mode)
6337 (font-lock-fontify-buffer)
6338 (buffer-string))))
6340 (defvar org-m nil)
6341 (defvar org-l nil)
6342 (defvar org-f nil)
6343 (defun org-get-level-face (n)
6344 "Get the right face for match N in font-lock matching of headlines."
6345 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6346 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6347 (if org-cycle-level-faces
6348 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6349 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6350 (cond
6351 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6352 ((eq n 2) org-f)
6353 (t (if org-level-color-stars-only nil org-f))))
6356 (defun org-get-todo-face (kwd)
6357 "Get the right face for a TODO keyword KWD.
6358 If KWD is a number, get the corresponding match group."
6359 (if (numberp kwd) (setq kwd (match-string kwd)))
6360 (or (org-face-from-face-or-color
6361 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6362 (and (member kwd org-done-keywords) 'org-done)
6363 'org-todo))
6365 (defun org-face-from-face-or-color (context inherit face-or-color)
6366 "Create a face list that inherits INHERIT, but sets the foreground color.
6367 When FACE-OR-COLOR is not a string, just return it."
6368 (if (stringp face-or-color)
6369 (list :inherit inherit
6370 (cdr (assoc context org-faces-easy-properties))
6371 face-or-color)
6372 face-or-color))
6374 (defun org-font-lock-add-tag-faces (limit)
6375 "Add the special tag faces."
6376 (when (and org-tag-faces org-tags-special-faces-re)
6377 (while (re-search-forward org-tags-special-faces-re limit t)
6378 (add-text-properties (match-beginning 1) (match-end 1)
6379 (list 'face (org-get-tag-face 1)
6380 'font-lock-fontified t))
6381 (backward-char 1))))
6383 (defun org-font-lock-add-priority-faces (limit)
6384 "Add the special priority faces."
6385 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6386 (when (save-match-data (org-at-heading-p))
6387 (add-text-properties
6388 (match-beginning 0) (match-end 0)
6389 (list 'face (or (org-face-from-face-or-color
6390 'priority 'org-priority
6391 (cdr (assoc (char-after (match-beginning 1))
6392 org-priority-faces)))
6393 'org-priority)
6394 'font-lock-fontified t)))))
6396 (defun org-get-tag-face (kwd)
6397 "Get the right face for a TODO keyword KWD.
6398 If KWD is a number, get the corresponding match group."
6399 (if (numberp kwd) (setq kwd (match-string kwd)))
6400 (or (org-face-from-face-or-color
6401 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6402 'org-tag))
6404 (defun org-unfontify-region (beg end &optional maybe_loudly)
6405 "Remove fontification and activation overlays from links."
6406 (font-lock-default-unfontify-region beg end)
6407 (let* ((buffer-undo-list t)
6408 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6409 (inhibit-modification-hooks t)
6410 deactivate-mark buffer-file-name buffer-file-truename)
6411 (org-decompose-region beg end)
6412 (remove-text-properties beg end
6413 '(mouse-face t keymap t org-linked-text t
6414 invisible t intangible t
6415 org-no-flyspell t org-emphasis t))
6416 (org-remove-font-lock-display-properties beg end)))
6418 (defconst org-script-display '(((raise -0.3) (height 0.7))
6419 ((raise 0.3) (height 0.7))
6420 ((raise -0.5))
6421 ((raise 0.5)))
6422 "Display properties for showing superscripts and subscripts.")
6424 (defun org-remove-font-lock-display-properties (beg end)
6425 "Remove specific display properties that have been added by font lock.
6426 The will remove the raise properties that are used to show superscripts
6427 and subscripts."
6428 (let (next prop)
6429 (while (< beg end)
6430 (setq next (next-single-property-change beg 'display nil end)
6431 prop (get-text-property beg 'display))
6432 (if (member prop org-script-display)
6433 (put-text-property beg next 'display nil))
6434 (setq beg next))))
6436 (defun org-raise-scripts (limit)
6437 "Add raise properties to sub/superscripts."
6438 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6439 (if (re-search-forward
6440 (if (eq org-use-sub-superscripts t)
6441 org-match-substring-regexp
6442 org-match-substring-with-braces-regexp)
6443 limit t)
6444 (let* ((pos (point)) table-p comment-p
6445 (mpos (match-beginning 3))
6446 (emph-p (get-text-property mpos 'org-emphasis))
6447 (link-p (get-text-property mpos 'mouse-face))
6448 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6449 (goto-char (point-at-bol))
6450 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6451 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6452 (goto-char pos)
6453 ;; Handle a_b^c
6454 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6455 (if (or comment-p emph-p link-p keyw-p)
6457 (put-text-property (match-beginning 3) (match-end 0)
6458 'display
6459 (if (equal (char-after (match-beginning 2)) ?^)
6460 (nth (if table-p 3 1) org-script-display)
6461 (nth (if table-p 2 0) org-script-display)))
6462 (add-text-properties (match-beginning 2) (match-end 2)
6463 (list 'invisible t
6464 'org-dwidth t 'org-dwidth-n 1))
6465 (if (and (eq (char-after (match-beginning 3)) ?{)
6466 (eq (char-before (match-end 3)) ?}))
6467 (progn
6468 (add-text-properties
6469 (match-beginning 3) (1+ (match-beginning 3))
6470 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6471 (add-text-properties
6472 (1- (match-end 3)) (match-end 3)
6473 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6474 t)))))
6476 ;;;; Visibility cycling, including org-goto and indirect buffer
6478 ;;; Cycling
6480 (defvar org-cycle-global-status nil)
6481 (make-variable-buffer-local 'org-cycle-global-status)
6482 (put 'org-cycle-global-status 'org-state t)
6483 (defvar org-cycle-subtree-status nil)
6484 (make-variable-buffer-local 'org-cycle-subtree-status)
6485 (put 'org-cycle-subtree-status 'org-state t)
6487 (defvar org-inlinetask-min-level)
6489 ;;;###autoload
6490 (defun org-cycle (&optional arg)
6491 "TAB-action and visibility cycling for Org-mode.
6493 This is the command invoked in Org-mode by the TAB key. Its main purpose
6494 is outline visibility cycling, but it also invokes other actions
6495 in special contexts.
6497 - When this function is called with a prefix argument, rotate the entire
6498 buffer through 3 states (global cycling)
6499 1. OVERVIEW: Show only top-level headlines.
6500 2. CONTENTS: Show all headlines of all levels, but no body text.
6501 3. SHOW ALL: Show everything.
6502 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6503 determined by the variable `org-startup-folded', and by any VISIBILITY
6504 properties in the buffer.
6505 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6506 including any drawers.
6508 - When inside a table, re-align the table and move to the next field.
6510 - When point is at the beginning of a headline, rotate the subtree started
6511 by this line through 3 different states (local cycling)
6512 1. FOLDED: Only the main headline is shown.
6513 2. CHILDREN: The main headline and the direct children are shown.
6514 From this state, you can move to one of the children
6515 and zoom in further.
6516 3. SUBTREE: Show the entire subtree, including body text.
6517 If there is no subtree, switch directly from CHILDREN to FOLDED.
6519 - When point is at the beginning of an empty headline and the variable
6520 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6521 of the headline by demoting and promoting it to likely levels. This
6522 speeds up creation document structure by pressing TAB once or several
6523 times right after creating a new headline.
6525 - When there is a numeric prefix, go up to a heading with level ARG, do
6526 a `show-subtree' and return to the previous cursor position. If ARG
6527 is negative, go up that many levels.
6529 - When point is not at the beginning of a headline, execute the global
6530 binding for TAB, which is re-indenting the line. See the option
6531 `org-cycle-emulate-tab' for details.
6533 - Special case: if point is at the beginning of the buffer and there is
6534 no headline in line 1, this function will act as if called with prefix arg
6535 (C-u TAB, same as S-TAB) also when called without prefix arg.
6536 But only if also the variable `org-cycle-global-at-bob' is t."
6537 (interactive "P")
6538 (org-load-modules-maybe)
6539 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6540 (and org-cycle-level-after-item/entry-creation
6541 (or (org-cycle-level)
6542 (org-cycle-item-indentation))))
6543 (let* (message-log-max ; Don't populate the *Messages* buffer
6544 (limit-level
6545 (or org-cycle-max-level
6546 (and (boundp 'org-inlinetask-min-level)
6547 org-inlinetask-min-level
6548 (1- org-inlinetask-min-level))))
6549 (nstars (and limit-level
6550 (if org-odd-levels-only
6551 (and limit-level (1- (* limit-level 2)))
6552 limit-level)))
6553 (org-outline-regexp
6554 (if (not (derived-mode-p 'org-mode))
6555 outline-regexp
6556 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6557 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6558 (not (looking-at org-outline-regexp))))
6559 (org-cycle-hook
6560 (if bob-special
6561 (delq 'org-optimize-window-after-visibility-change
6562 (copy-sequence org-cycle-hook))
6563 org-cycle-hook))
6564 (pos (point)))
6566 (if (or bob-special (equal arg '(4)))
6567 ;; special case: use global cycling
6568 (setq arg t))
6570 (cond
6572 ((equal arg '(16))
6573 (setq last-command 'dummy)
6574 (org-set-startup-visibility)
6575 (message "Startup visibility, plus VISIBILITY properties"))
6577 ((equal arg '(64))
6578 (show-all)
6579 (message "Entire buffer visible, including drawers"))
6581 ;; Table: enter it or move to the next field.
6582 ((org-at-table-p 'any)
6583 (if (org-at-table.el-p)
6584 (message "Use C-c ' to edit table.el tables")
6585 (if arg (org-table-edit-field t)
6586 (org-table-justify-field-maybe)
6587 (call-interactively 'org-table-next-field))))
6589 ((run-hook-with-args-until-success
6590 'org-tab-after-check-for-table-hook))
6592 ;; Global cycling: delegate to `org-cycle-internal-global'.
6593 ((eq arg t) (org-cycle-internal-global))
6595 ;; Drawers: delegate to `org-flag-drawer'.
6596 ((and org-drawers org-drawer-regexp
6597 (save-excursion
6598 (beginning-of-line 1)
6599 (looking-at org-drawer-regexp)))
6600 (org-flag-drawer ; toggle block visibility
6601 (not (get-char-property (match-end 0) 'invisible))))
6603 ;; Show-subtree, ARG levels up from here.
6604 ((integerp arg)
6605 (save-excursion
6606 (org-back-to-heading)
6607 (outline-up-heading (if (< arg 0) (- arg)
6608 (- (funcall outline-level) arg)))
6609 (org-show-subtree)))
6611 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6612 ((and (featurep 'org-inlinetask)
6613 (org-inlinetask-at-task-p)
6614 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6615 (org-inlinetask-toggle-visibility))
6617 ((org-try-cdlatex-tab))
6619 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6620 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6621 (save-excursion (beginning-of-line 1)
6622 (looking-at org-outline-regexp)))
6623 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6624 (org-cycle-internal-local))
6626 ;; From there: TAB emulation and template completion.
6627 (buffer-read-only (org-back-to-heading))
6629 ((run-hook-with-args-until-success
6630 'org-tab-after-check-for-cycling-hook))
6632 ((org-try-structure-completion))
6634 ((run-hook-with-args-until-success
6635 'org-tab-before-tab-emulation-hook))
6637 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6638 (or (not (bolp))
6639 (not (looking-at org-outline-regexp))))
6640 (call-interactively (global-key-binding "\t")))
6642 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6643 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6644 (or (and (eq org-cycle-emulate-tab 'white)
6645 (= (match-end 0) (point-at-eol)))
6646 (and (eq org-cycle-emulate-tab 'whitestart)
6647 (>= (match-end 0) pos))))
6649 (eq org-cycle-emulate-tab t))
6650 (call-interactively (global-key-binding "\t")))
6652 (t (save-excursion
6653 (org-back-to-heading)
6654 (org-cycle)))))))
6656 (defun org-cycle-internal-global ()
6657 "Do the global cycling action."
6658 ;; Hack to avoid display of messages for .org attachments in Gnus
6659 (let (message-log-max ; Don't populate the *Messages* buffer
6660 (ga (string-match "\\*fontification" (buffer-name))))
6661 (cond
6662 ((and (eq last-command this-command)
6663 (eq org-cycle-global-status 'overview))
6664 ;; We just created the overview - now do table of contents
6665 ;; This can be slow in very large buffers, so indicate action
6666 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6667 (unless ga (message "CONTENTS..."))
6668 (org-content)
6669 (unless ga (message "CONTENTS...done"))
6670 (setq org-cycle-global-status 'contents)
6671 (run-hook-with-args 'org-cycle-hook 'contents))
6673 ((and (eq last-command this-command)
6674 (eq org-cycle-global-status 'contents))
6675 ;; We just showed the table of contents - now show everything
6676 (run-hook-with-args 'org-pre-cycle-hook 'all)
6677 (show-all)
6678 (unless ga (message "SHOW ALL"))
6679 (setq org-cycle-global-status 'all)
6680 (run-hook-with-args 'org-cycle-hook 'all))
6683 ;; Default action: go to overview
6684 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6685 (org-overview)
6686 (unless ga (message "OVERVIEW"))
6687 (setq org-cycle-global-status 'overview)
6688 (run-hook-with-args 'org-cycle-hook 'overview)))))
6690 (defun org-cycle-internal-local ()
6691 "Do the local cycling action."
6692 (let (message-log-max ; Don't populate the *Messages* buffer
6693 (goal-column 0) eoh eol eos has-children children-skipped struct)
6694 ;; First, determine end of headline (EOH), end of subtree or item
6695 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6696 (save-excursion
6697 (if (org-at-item-p)
6698 (progn
6699 (beginning-of-line)
6700 (setq struct (org-list-struct))
6701 (setq eoh (point-at-eol))
6702 (setq eos (org-list-get-item-end-before-blank (point) struct))
6703 (setq has-children (org-list-has-child-p (point) struct)))
6704 (org-back-to-heading)
6705 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6706 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6707 (setq has-children
6708 (or (save-excursion
6709 (let ((level (funcall outline-level)))
6710 (outline-next-heading)
6711 (and (org-at-heading-p t)
6712 (> (funcall outline-level) level))))
6713 (save-excursion
6714 (org-list-search-forward (org-item-beginning-re) eos t)))))
6715 ;; Determine end invisible part of buffer (EOL)
6716 (beginning-of-line 2)
6717 ;; XEmacs doesn't have `next-single-char-property-change'
6718 (if (featurep 'xemacs)
6719 (while (and (not (eobp)) ;; this is like `next-line'
6720 (get-char-property (1- (point)) 'invisible))
6721 (beginning-of-line 2))
6722 (while (and (not (eobp)) ;; this is like `next-line'
6723 (get-char-property (1- (point)) 'invisible))
6724 (goto-char (next-single-char-property-change (point) 'invisible))
6725 (and (eolp) (beginning-of-line 2))))
6726 (setq eol (point)))
6727 ;; Find out what to do next and set `this-command'
6728 (cond
6729 ((= eos eoh)
6730 ;; Nothing is hidden behind this heading
6731 (unless (org-before-first-heading-p)
6732 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6733 (message "EMPTY ENTRY")
6734 (setq org-cycle-subtree-status nil)
6735 (save-excursion
6736 (goto-char eos)
6737 (outline-next-heading)
6738 (if (outline-invisible-p) (org-flag-heading nil))))
6739 ((and (or (>= eol eos)
6740 (not (string-match "\\S-" (buffer-substring eol eos))))
6741 (or has-children
6742 (not (setq children-skipped
6743 org-cycle-skip-children-state-if-no-children))))
6744 ;; Entire subtree is hidden in one line: children view
6745 (unless (org-before-first-heading-p)
6746 (run-hook-with-args 'org-pre-cycle-hook 'children))
6747 (if (org-at-item-p)
6748 (org-list-set-item-visibility (point-at-bol) struct 'children)
6749 (org-show-entry)
6750 (org-with-limited-levels (show-children))
6751 ;; FIXME: This slows down the func way too much.
6752 ;; How keep drawers hidden in subtree anyway?
6753 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6754 ;; (org-cycle-hide-drawers 'subtree))
6756 ;; Fold every list in subtree to top-level items.
6757 (when (eq org-cycle-include-plain-lists 'integrate)
6758 (save-excursion
6759 (org-back-to-heading)
6760 (while (org-list-search-forward (org-item-beginning-re) eos t)
6761 (beginning-of-line 1)
6762 (let* ((struct (org-list-struct))
6763 (prevs (org-list-prevs-alist struct))
6764 (end (org-list-get-bottom-point struct)))
6765 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6766 (org-list-get-all-items (point) struct prevs))
6767 (goto-char (if (< end eos) end eos)))))))
6768 (message "CHILDREN")
6769 (save-excursion
6770 (goto-char eos)
6771 (outline-next-heading)
6772 (if (outline-invisible-p) (org-flag-heading nil)))
6773 (setq org-cycle-subtree-status 'children)
6774 (unless (org-before-first-heading-p)
6775 (run-hook-with-args 'org-cycle-hook 'children)))
6776 ((or children-skipped
6777 (and (eq last-command this-command)
6778 (eq org-cycle-subtree-status 'children)))
6779 ;; We just showed the children, or no children are there,
6780 ;; now show everything.
6781 (unless (org-before-first-heading-p)
6782 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6783 (outline-flag-region eoh eos nil)
6784 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6785 (setq org-cycle-subtree-status 'subtree)
6786 (unless (org-before-first-heading-p)
6787 (run-hook-with-args 'org-cycle-hook 'subtree)))
6789 ;; Default action: hide the subtree.
6790 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6791 (outline-flag-region eoh eos t)
6792 (message "FOLDED")
6793 (setq org-cycle-subtree-status 'folded)
6794 (unless (org-before-first-heading-p)
6795 (run-hook-with-args 'org-cycle-hook 'folded))))))
6797 ;;;###autoload
6798 (defun org-global-cycle (&optional arg)
6799 "Cycle the global visibility. For details see `org-cycle'.
6800 With \\[universal-argument] prefix arg, switch to startup visibility.
6801 With a numeric prefix, show all headlines up to that level."
6802 (interactive "P")
6803 (let ((org-cycle-include-plain-lists
6804 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6805 (cond
6806 ((integerp arg)
6807 (show-all)
6808 (hide-sublevels arg)
6809 (setq org-cycle-global-status 'contents))
6810 ((equal arg '(4))
6811 (org-set-startup-visibility)
6812 (message "Startup visibility, plus VISIBILITY properties."))
6814 (org-cycle '(4))))))
6816 (defun org-set-startup-visibility ()
6817 "Set the visibility required by startup options and properties."
6818 (cond
6819 ((eq org-startup-folded t)
6820 (org-cycle '(4)))
6821 ((eq org-startup-folded 'content)
6822 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6823 (org-cycle '(4)) (org-cycle '(4)))))
6824 (unless (eq org-startup-folded 'showeverything)
6825 (if org-hide-block-startup (org-hide-block-all))
6826 (org-set-visibility-according-to-property 'no-cleanup)
6827 (org-cycle-hide-archived-subtrees 'all)
6828 (org-cycle-hide-drawers 'all)
6829 (org-cycle-show-empty-lines t)))
6831 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6832 "Switch subtree visibilities according to :VISIBILITY: property."
6833 (interactive)
6834 (let (org-show-entry-below state)
6835 (save-excursion
6836 (goto-char (point-min))
6837 (while (re-search-forward
6838 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6839 nil t)
6840 (setq state (match-string 1))
6841 (save-excursion
6842 (org-back-to-heading t)
6843 (hide-subtree)
6844 (org-reveal)
6845 (cond
6846 ((equal state '("fold" "folded"))
6847 (hide-subtree))
6848 ((equal state "children")
6849 (org-show-hidden-entry)
6850 (show-children))
6851 ((equal state "content")
6852 (save-excursion
6853 (save-restriction
6854 (org-narrow-to-subtree)
6855 (org-content))))
6856 ((member state '("all" "showall"))
6857 (show-subtree)))))
6858 (unless no-cleanup
6859 (org-cycle-hide-archived-subtrees 'all)
6860 (org-cycle-hide-drawers 'all)
6861 (org-cycle-show-empty-lines 'all)))))
6863 ;; This function uses outline-regexp instead of the more fundamental
6864 ;; org-outline-regexp so that org-cycle-global works outside of Org
6865 ;; buffers, where outline-regexp is needed.
6866 (defun org-overview ()
6867 "Switch to overview mode, showing only top-level headlines.
6868 Really, this shows all headlines with level equal or greater than the level
6869 of the first headline in the buffer. This is important, because if the
6870 first headline is not level one, then (hide-sublevels 1) gives confusing
6871 results."
6872 (interactive)
6873 (let ((l (org-current-line))
6874 (level (save-excursion
6875 (goto-char (point-min))
6876 (if (re-search-forward (concat "^" outline-regexp) nil t)
6877 (progn
6878 (goto-char (match-beginning 0))
6879 (funcall outline-level))))))
6880 (and level (hide-sublevels level))
6881 (recenter '(4))
6882 (org-goto-line l)))
6884 (defun org-content (&optional arg)
6885 "Show all headlines in the buffer, like a table of contents.
6886 With numerical argument N, show content up to level N."
6887 (interactive "P")
6888 (save-excursion
6889 ;; Visit all headings and show their offspring
6890 (and (integerp arg) (org-overview))
6891 (goto-char (point-max))
6892 (catch 'exit
6893 (while (and (progn (condition-case nil
6894 (outline-previous-visible-heading 1)
6895 (error (goto-char (point-min))))
6897 (looking-at org-outline-regexp))
6898 (if (integerp arg)
6899 (show-children (1- arg))
6900 (show-branches))
6901 (if (bobp) (throw 'exit nil))))))
6904 (defun org-optimize-window-after-visibility-change (state)
6905 "Adjust the window after a change in outline visibility.
6906 This function is the default value of the hook `org-cycle-hook'."
6907 (when (get-buffer-window (current-buffer))
6908 (cond
6909 ((eq state 'content) nil)
6910 ((eq state 'all) nil)
6911 ((eq state 'folded) nil)
6912 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6913 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6915 (defun org-remove-empty-overlays-at (pos)
6916 "Remove outline overlays that do not contain non-white stuff."
6917 (mapc
6918 (lambda (o)
6919 (and (eq 'outline (overlay-get o 'invisible))
6920 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6921 (overlay-end o))))
6922 (delete-overlay o)))
6923 (overlays-at pos)))
6925 (defun org-clean-visibility-after-subtree-move ()
6926 "Fix visibility issues after moving a subtree."
6927 ;; First, find a reasonable region to look at:
6928 ;; Start two siblings above, end three below
6929 (let* ((beg (save-excursion
6930 (and (org-get-last-sibling)
6931 (org-get-last-sibling))
6932 (point)))
6933 (end (save-excursion
6934 (and (org-get-next-sibling)
6935 (org-get-next-sibling)
6936 (org-get-next-sibling))
6937 (if (org-at-heading-p)
6938 (point-at-eol)
6939 (point))))
6940 (level (looking-at "\\*+"))
6941 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6942 (save-excursion
6943 (save-restriction
6944 (narrow-to-region beg end)
6945 (when re
6946 ;; Properly fold already folded siblings
6947 (goto-char (point-min))
6948 (while (re-search-forward re nil t)
6949 (if (and (not (outline-invisible-p))
6950 (save-excursion
6951 (goto-char (point-at-eol)) (outline-invisible-p)))
6952 (hide-entry))))
6953 (org-cycle-show-empty-lines 'overview)
6954 (org-cycle-hide-drawers 'overview)))))
6956 (defun org-cycle-show-empty-lines (state)
6957 "Show empty lines above all visible headlines.
6958 The region to be covered depends on STATE when called through
6959 `org-cycle-hook'. Lisp program can use t for STATE to get the
6960 entire buffer covered. Note that an empty line is only shown if there
6961 are at least `org-cycle-separator-lines' empty lines before the headline."
6962 (when (not (= org-cycle-separator-lines 0))
6963 (save-excursion
6964 (let* ((n (abs org-cycle-separator-lines))
6965 (re (cond
6966 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6967 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6968 (t (let ((ns (number-to-string (- n 2))))
6969 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6970 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6971 beg end b e)
6972 (cond
6973 ((memq state '(overview contents t))
6974 (setq beg (point-min) end (point-max)))
6975 ((memq state '(children folded))
6976 (setq beg (point) end (progn (org-end-of-subtree t t)
6977 (beginning-of-line 2)
6978 (point)))))
6979 (when beg
6980 (goto-char beg)
6981 (while (re-search-forward re end t)
6982 (unless (get-char-property (match-end 1) 'invisible)
6983 (setq e (match-end 1))
6984 (if (< org-cycle-separator-lines 0)
6985 (setq b (save-excursion
6986 (goto-char (match-beginning 0))
6987 (org-back-over-empty-lines)
6988 (if (save-excursion
6989 (goto-char (max (point-min) (1- (point))))
6990 (org-at-heading-p))
6991 (1- (point))
6992 (point))))
6993 (setq b (match-beginning 1)))
6994 (outline-flag-region b e nil)))))))
6995 ;; Never hide empty lines at the end of the file.
6996 (save-excursion
6997 (goto-char (point-max))
6998 (outline-previous-heading)
6999 (outline-end-of-heading)
7000 (if (and (looking-at "[ \t\n]+")
7001 (= (match-end 0) (point-max)))
7002 (outline-flag-region (point) (match-end 0) nil))))
7004 (defun org-show-empty-lines-in-parent ()
7005 "Move to the parent and re-show empty lines before visible headlines."
7006 (save-excursion
7007 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7008 (org-cycle-show-empty-lines context))))
7010 (defun org-files-list ()
7011 "Return `org-agenda-files' list, plus all open org-mode files.
7012 This is useful for operations that need to scan all of a user's
7013 open and agenda-wise Org files."
7014 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7015 (dolist (buf (buffer-list))
7016 (with-current-buffer buf
7017 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7018 (let ((file (expand-file-name (buffer-file-name))))
7019 (unless (member file files)
7020 (push file files))))))
7021 files))
7023 (defsubst org-entry-beginning-position ()
7024 "Return the beginning position of the current entry."
7025 (save-excursion (outline-back-to-heading t) (point)))
7027 (defsubst org-entry-end-position ()
7028 "Return the end position of the current entry."
7029 (save-excursion (outline-next-heading) (point)))
7031 (defun org-cycle-hide-drawers (state)
7032 "Re-hide all drawers after a visibility state change."
7033 (when (and (derived-mode-p 'org-mode)
7034 (not (memq state '(overview folded contents))))
7035 (save-excursion
7036 (let* ((globalp (memq state '(contents all)))
7037 (beg (if globalp (point-min) (point)))
7038 (end (if globalp (point-max)
7039 (if (eq state 'children)
7040 (save-excursion (outline-next-heading) (point))
7041 (org-end-of-subtree t)))))
7042 (goto-char beg)
7043 (while (re-search-forward org-drawer-regexp end t)
7044 (org-flag-drawer t))))))
7046 (defun org-cycle-hide-inline-tasks (state)
7047 "Re-hide inline task when switching to 'contents visibility state."
7048 (when (and (eq state 'contents)
7049 (boundp 'org-inlinetask-min-level)
7050 org-inlinetask-min-level)
7051 (hide-sublevels (1- org-inlinetask-min-level))))
7053 (defun org-flag-drawer (flag)
7054 "When FLAG is non-nil, hide the drawer we are within.
7055 Otherwise make it visible."
7056 (save-excursion
7057 (beginning-of-line 1)
7058 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7059 (let ((b (match-end 0)))
7060 (if (re-search-forward
7061 "^[ \t]*:END:"
7062 (save-excursion (outline-next-heading) (point)) t)
7063 (outline-flag-region b (point-at-eol) flag)
7064 (user-error ":END: line missing at position %s" b))))))
7066 (defun org-subtree-end-visible-p ()
7067 "Is the end of the current subtree visible?"
7068 (pos-visible-in-window-p
7069 (save-excursion (org-end-of-subtree t) (point))))
7071 (defun org-first-headline-recenter (&optional N)
7072 "Move cursor to the first headline and recenter the headline.
7073 Optional argument N means put the headline into the Nth line of the window."
7074 (goto-char (point-min))
7075 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7076 (beginning-of-line)
7077 (recenter (prefix-numeric-value N))))
7079 ;;; Saving and restoring visibility
7081 (defun org-outline-overlay-data (&optional use-markers)
7082 "Return a list of the locations of all outline overlays.
7083 These are overlays with the `invisible' property value `outline'.
7084 The return value is a list of cons cells, with start and stop
7085 positions for each overlay.
7086 If USE-MARKERS is set, return the positions as markers."
7087 (let (beg end)
7088 (save-excursion
7089 (save-restriction
7090 (widen)
7091 (delq nil
7092 (mapcar (lambda (o)
7093 (when (eq (overlay-get o 'invisible) 'outline)
7094 (setq beg (overlay-start o)
7095 end (overlay-end o))
7096 (and beg end (> end beg)
7097 (if use-markers
7098 (cons (move-marker (make-marker) beg)
7099 (move-marker (make-marker) end))
7100 (cons beg end)))))
7101 (overlays-in (point-min) (point-max))))))))
7103 (defun org-set-outline-overlay-data (data)
7104 "Create visibility overlays for all positions in DATA.
7105 DATA should have been made by `org-outline-overlay-data'."
7106 (let (o)
7107 (save-excursion
7108 (save-restriction
7109 (widen)
7110 (show-all)
7111 (mapc (lambda (c)
7112 (outline-flag-region (car c) (cdr c) t))
7113 data)))))
7115 ;;; Folding of blocks
7117 (defvar org-hide-block-overlays nil
7118 "Overlays hiding blocks.")
7119 (make-variable-buffer-local 'org-hide-block-overlays)
7121 (defun org-block-map (function &optional start end)
7122 "Call FUNCTION at the head of all source blocks in the current buffer.
7123 Optional arguments START and END can be used to limit the range."
7124 (let ((start (or start (point-min)))
7125 (end (or end (point-max))))
7126 (save-excursion
7127 (goto-char start)
7128 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7129 (save-excursion
7130 (save-match-data
7131 (goto-char (match-beginning 0))
7132 (funcall function)))))))
7134 (defun org-hide-block-toggle-all ()
7135 "Toggle the visibility of all blocks in the current buffer."
7136 (org-block-map #'org-hide-block-toggle))
7138 (defun org-hide-block-all ()
7139 "Fold all blocks in the current buffer."
7140 (interactive)
7141 (org-show-block-all)
7142 (org-block-map #'org-hide-block-toggle-maybe))
7144 (defun org-show-block-all ()
7145 "Unfold all blocks in the current buffer."
7146 (interactive)
7147 (mapc 'delete-overlay org-hide-block-overlays)
7148 (setq org-hide-block-overlays nil))
7150 (defun org-hide-block-toggle-maybe ()
7151 "Toggle visibility of block at point."
7152 (interactive)
7153 (let ((case-fold-search t))
7154 (if (save-excursion
7155 (beginning-of-line 1)
7156 (looking-at org-block-regexp))
7157 (progn (org-hide-block-toggle)
7158 t) ;; to signal that we took action
7159 nil))) ;; to signal that we did not
7161 (defun org-hide-block-toggle (&optional force)
7162 "Toggle the visibility of the current block."
7163 (interactive)
7164 (save-excursion
7165 (beginning-of-line)
7166 (if (re-search-forward org-block-regexp nil t)
7167 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7168 (end (match-end 0)) ;; end of entire body
7170 (if (memq t (mapcar (lambda (overlay)
7171 (eq (overlay-get overlay 'invisible)
7172 'org-hide-block))
7173 (overlays-at start)))
7174 (if (or (not force) (eq force 'off))
7175 (mapc (lambda (ov)
7176 (when (member ov org-hide-block-overlays)
7177 (setq org-hide-block-overlays
7178 (delq ov org-hide-block-overlays)))
7179 (when (eq (overlay-get ov 'invisible)
7180 'org-hide-block)
7181 (delete-overlay ov)))
7182 (overlays-at start)))
7183 (setq ov (make-overlay start end))
7184 (overlay-put ov 'invisible 'org-hide-block)
7185 ;; make the block accessible to isearch
7186 (overlay-put
7187 ov 'isearch-open-invisible
7188 (lambda (ov)
7189 (when (member ov org-hide-block-overlays)
7190 (setq org-hide-block-overlays
7191 (delq ov org-hide-block-overlays)))
7192 (when (eq (overlay-get ov 'invisible)
7193 'org-hide-block)
7194 (delete-overlay ov))))
7195 (push ov org-hide-block-overlays)))
7196 (user-error "Not looking at a source block"))))
7198 ;; org-tab-after-check-for-cycling-hook
7199 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7200 ;; Remove overlays when changing major mode
7201 (add-hook 'org-mode-hook
7202 (lambda () (org-add-hook 'change-major-mode-hook
7203 'org-show-block-all 'append 'local)))
7205 ;;; Org-goto
7207 (defvar org-goto-window-configuration nil)
7208 (defvar org-goto-marker nil)
7209 (defvar org-goto-map)
7210 (defun org-goto-map ()
7211 "Set the keymap `org-goto'."
7212 (setq org-goto-map
7213 (let ((map (make-sparse-keymap)))
7214 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7215 mouse-drag-region universal-argument org-occur))
7216 cmd)
7217 (while (setq cmd (pop cmds))
7218 (substitute-key-definition cmd cmd map global-map)))
7219 (suppress-keymap map)
7220 (org-defkey map "\C-m" 'org-goto-ret)
7221 (org-defkey map [(return)] 'org-goto-ret)
7222 (org-defkey map [(left)] 'org-goto-left)
7223 (org-defkey map [(right)] 'org-goto-right)
7224 (org-defkey map [(control ?g)] 'org-goto-quit)
7225 (org-defkey map "\C-i" 'org-cycle)
7226 (org-defkey map [(tab)] 'org-cycle)
7227 (org-defkey map [(down)] 'outline-next-visible-heading)
7228 (org-defkey map [(up)] 'outline-previous-visible-heading)
7229 (if org-goto-auto-isearch
7230 (if (fboundp 'define-key-after)
7231 (define-key-after map [t] 'org-goto-local-auto-isearch)
7232 nil)
7233 (org-defkey map "q" 'org-goto-quit)
7234 (org-defkey map "n" 'outline-next-visible-heading)
7235 (org-defkey map "p" 'outline-previous-visible-heading)
7236 (org-defkey map "f" 'outline-forward-same-level)
7237 (org-defkey map "b" 'outline-backward-same-level)
7238 (org-defkey map "u" 'outline-up-heading))
7239 (org-defkey map "/" 'org-occur)
7240 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7241 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7242 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7243 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7244 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7245 map)))
7247 (defconst org-goto-help
7248 "Browse buffer copy, to find location or copy text.%s
7249 RET=jump to location C-g=quit and return to previous location
7250 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7252 (defvar org-goto-start-pos) ; dynamically scoped parameter
7254 (defun org-goto (&optional alternative-interface)
7255 "Look up a different location in the current file, keeping current visibility.
7257 When you want look-up or go to a different location in a
7258 document, the fastest way is often to fold the entire buffer and
7259 then dive into the tree. This method has the disadvantage, that
7260 the previous location will be folded, which may not be what you
7261 want.
7263 This command works around this by showing a copy of the current
7264 buffer in an indirect buffer, in overview mode. You can dive
7265 into the tree in that copy, use org-occur and incremental search
7266 to find a location. When pressing RET or `Q', the command
7267 returns to the original buffer in which the visibility is still
7268 unchanged. After RET it will also jump to the location selected
7269 in the indirect buffer and expose the headline hierarchy above.
7271 With a prefix argument, use the alternative interface: e.g. if
7272 `org-goto-interface' is 'outline use 'outline-path-completion."
7273 (interactive "P")
7274 (org-goto-map)
7275 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7276 (org-refile-use-outline-path t)
7277 (org-refile-target-verify-function nil)
7278 (interface
7279 (if (not alternative-interface)
7280 org-goto-interface
7281 (if (eq org-goto-interface 'outline)
7282 'outline-path-completion
7283 'outline)))
7284 (org-goto-start-pos (point))
7285 (selected-point
7286 (if (eq interface 'outline)
7287 (car (org-get-location (current-buffer) org-goto-help))
7288 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7289 (org-refile-check-position pa)
7290 (nth 3 pa)))))
7291 (if selected-point
7292 (progn
7293 (org-mark-ring-push org-goto-start-pos)
7294 (goto-char selected-point)
7295 (if (or (outline-invisible-p) (org-invisible-p2))
7296 (org-show-context 'org-goto)))
7297 (message "Quit"))))
7299 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7300 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7301 (defvar org-goto-local-auto-isearch-map) ; defined below
7303 (defun org-get-location (buf help)
7304 "Let the user select a location in the Org-mode buffer BUF.
7305 This function uses a recursive edit. It returns the selected position
7306 or nil."
7307 (org-no-popups
7308 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7309 (isearch-hide-immediately nil)
7310 (isearch-search-fun-function
7311 (lambda () 'org-goto-local-search-headings))
7312 (org-goto-selected-point org-goto-exit-command))
7313 (save-excursion
7314 (save-window-excursion
7315 (delete-other-windows)
7316 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7317 (org-pop-to-buffer-same-window
7318 (condition-case nil
7319 (make-indirect-buffer (current-buffer) "*org-goto*")
7320 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7321 (with-output-to-temp-buffer "*Org Help*"
7322 (princ (format help (if org-goto-auto-isearch
7323 " Just type for auto-isearch."
7324 " n/p/f/b/u to navigate, q to quit."))))
7325 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7326 (setq buffer-read-only nil)
7327 (let ((org-startup-truncated t)
7328 (org-startup-folded nil)
7329 (org-startup-align-all-tables nil))
7330 (org-mode)
7331 (org-overview))
7332 (setq buffer-read-only t)
7333 (if (and (boundp 'org-goto-start-pos)
7334 (integer-or-marker-p org-goto-start-pos))
7335 (let ((org-show-hierarchy-above t)
7336 (org-show-siblings t)
7337 (org-show-following-heading t))
7338 (goto-char org-goto-start-pos)
7339 (and (outline-invisible-p) (org-show-context)))
7340 (goto-char (point-min)))
7341 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7342 (message "Select location and press RET")
7343 (use-local-map org-goto-map)
7344 (recursive-edit)))
7345 (kill-buffer "*org-goto*")
7346 (cons org-goto-selected-point org-goto-exit-command))))
7348 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7349 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7350 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7351 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7353 (defun org-goto-local-search-headings (string bound noerror)
7354 "Search and make sure that any matches are in headlines."
7355 (catch 'return
7356 (while (if isearch-forward
7357 (search-forward string bound noerror)
7358 (search-backward string bound noerror))
7359 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7360 (and (member :headline context)
7361 (not (member :tags context))))
7362 (throw 'return (point))))))
7364 (defun org-goto-local-auto-isearch ()
7365 "Start isearch."
7366 (interactive)
7367 (goto-char (point-min))
7368 (let ((keys (this-command-keys)))
7369 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7370 (isearch-mode t)
7371 (isearch-process-search-char (string-to-char keys)))))
7373 (defun org-goto-ret (&optional arg)
7374 "Finish `org-goto' by going to the new location."
7375 (interactive "P")
7376 (setq org-goto-selected-point (point)
7377 org-goto-exit-command 'return)
7378 (throw 'exit nil))
7380 (defun org-goto-left ()
7381 "Finish `org-goto' by going to the new location."
7382 (interactive)
7383 (if (org-at-heading-p)
7384 (progn
7385 (beginning-of-line 1)
7386 (setq org-goto-selected-point (point)
7387 org-goto-exit-command 'left)
7388 (throw 'exit nil))
7389 (user-error "Not on a heading")))
7391 (defun org-goto-right ()
7392 "Finish `org-goto' by going to the new location."
7393 (interactive)
7394 (if (org-at-heading-p)
7395 (progn
7396 (setq org-goto-selected-point (point)
7397 org-goto-exit-command 'right)
7398 (throw 'exit nil))
7399 (user-error "Not on a heading")))
7401 (defun org-goto-quit ()
7402 "Finish `org-goto' without cursor motion."
7403 (interactive)
7404 (setq org-goto-selected-point nil)
7405 (setq org-goto-exit-command 'quit)
7406 (throw 'exit nil))
7408 ;;; Indirect buffer display of subtrees
7410 (defvar org-indirect-dedicated-frame nil
7411 "This is the frame being used for indirect tree display.")
7412 (defvar org-last-indirect-buffer nil)
7414 (defun org-tree-to-indirect-buffer (&optional arg)
7415 "Create indirect buffer and narrow it to current subtree.
7416 With a numerical prefix ARG, go up to this level and then take that tree.
7417 If ARG is negative, go up that many levels.
7419 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7420 indirect buffer previously made with this command, to avoid proliferation of
7421 indirect buffers. However, when you call the command with a \
7422 \\[universal-argument] prefix, or
7423 when `org-indirect-buffer-display' is `new-frame', the last buffer
7424 is kept so that you can work with several indirect buffers at the same time.
7425 If `org-indirect-buffer-display' is `dedicated-frame', the \
7426 \\[universal-argument] prefix also
7427 requests that a new frame be made for the new buffer, so that the dedicated
7428 frame is not changed."
7429 (interactive "P")
7430 (let ((cbuf (current-buffer))
7431 (cwin (selected-window))
7432 (pos (point))
7433 beg end level heading ibuf)
7434 (save-excursion
7435 (org-back-to-heading t)
7436 (when (numberp arg)
7437 (setq level (org-outline-level))
7438 (if (< arg 0) (setq arg (+ level arg)))
7439 (while (> (setq level (org-outline-level)) arg)
7440 (org-up-heading-safe)))
7441 (setq beg (point)
7442 heading (org-get-heading))
7443 (org-end-of-subtree t t)
7444 (if (org-at-heading-p) (backward-char 1))
7445 (setq end (point)))
7446 (if (and (buffer-live-p org-last-indirect-buffer)
7447 (not (eq org-indirect-buffer-display 'new-frame))
7448 (not arg))
7449 (kill-buffer org-last-indirect-buffer))
7450 (setq ibuf (org-get-indirect-buffer cbuf)
7451 org-last-indirect-buffer ibuf)
7452 (cond
7453 ((or (eq org-indirect-buffer-display 'new-frame)
7454 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7455 (select-frame (make-frame))
7456 (delete-other-windows)
7457 (org-pop-to-buffer-same-window ibuf)
7458 (org-set-frame-title heading))
7459 ((eq org-indirect-buffer-display 'dedicated-frame)
7460 (raise-frame
7461 (select-frame (or (and org-indirect-dedicated-frame
7462 (frame-live-p org-indirect-dedicated-frame)
7463 org-indirect-dedicated-frame)
7464 (setq org-indirect-dedicated-frame (make-frame)))))
7465 (delete-other-windows)
7466 (org-pop-to-buffer-same-window ibuf)
7467 (org-set-frame-title (concat "Indirect: " heading)))
7468 ((eq org-indirect-buffer-display 'current-window)
7469 (org-pop-to-buffer-same-window ibuf))
7470 ((eq org-indirect-buffer-display 'other-window)
7471 (pop-to-buffer ibuf))
7472 (t (error "Invalid value")))
7473 (if (featurep 'xemacs)
7474 (save-excursion (org-mode) (turn-on-font-lock)))
7475 (narrow-to-region beg end)
7476 (show-all)
7477 (goto-char pos)
7478 (run-hook-with-args 'org-cycle-hook 'all)
7479 (and (window-live-p cwin) (select-window cwin))))
7481 (defun org-get-indirect-buffer (&optional buffer)
7482 (setq buffer (or buffer (current-buffer)))
7483 (let ((n 1) (base (buffer-name buffer)) bname)
7484 (while (buffer-live-p
7485 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7486 (setq n (1+ n)))
7487 (condition-case nil
7488 (make-indirect-buffer buffer bname 'clone)
7489 (error (make-indirect-buffer buffer bname)))))
7491 (defun org-set-frame-title (title)
7492 "Set the title of the current frame to the string TITLE."
7493 ;; FIXME: how to name a single frame in XEmacs???
7494 (unless (featurep 'xemacs)
7495 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7497 ;;;; Structure editing
7499 ;;; Inserting headlines
7501 (defun org-previous-line-empty-p (&optional next)
7502 "Is the previous line a blank line?
7503 When NEXT is non-nil, check the next line instead."
7504 (save-excursion
7505 (and (not (bobp))
7506 (or (beginning-of-line (if next 2 0)) t)
7507 (save-match-data
7508 (looking-at "[ \t]*$")))))
7510 (defun org-insert-heading (&optional arg invisible-ok)
7511 "Insert a new heading or item with same depth at point.
7512 If point is in a plain list and ARG is nil, create a new list item.
7513 With one universal prefix argument, insert a heading even in lists.
7514 With two universal prefix arguments, insert the heading at the end
7515 of the parent subtree.
7517 If point is at the beginning of a headline, insert a sibling before
7518 the current headline. If point is not at the beginning, split the line
7519 and create a new headline with the text in the current line after point
7520 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7522 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7523 This is important for non-interactive uses of the command."
7524 (interactive "P")
7525 (if (org-called-interactively-p 'any) (org-reveal))
7526 (let ((itemp (org-in-item-p)))
7527 (cond
7528 ((or (= (buffer-size) 0)
7529 (and (not (save-excursion
7530 (and (ignore-errors (org-back-to-heading invisible-ok))
7531 (org-at-heading-p))))
7532 (or arg (not itemp))))
7533 (insert
7534 (if (org-previous-line-empty-p) "" "\n")
7535 (if (org-in-src-block-p) ",* " "* "))
7536 (run-hooks 'org-insert-heading-hook))
7537 ((or arg
7538 (and (not itemp) org-insert-heading-respect-content)
7539 (not (org-insert-item
7540 (save-excursion
7541 (and itemp
7542 (goto-char itemp)
7543 (looking-at org-list-full-item-re)
7544 (match-string 3))))))
7545 (let (begn endn)
7546 (when (org-buffer-narrowed-p)
7547 (setq begn (point-min) endn (point-max))
7548 (widen))
7549 (let* ((empty-line-p nil)
7550 (eops (equal arg '(16))) ; insert at end of parent subtree
7551 (org-insert-heading-respect-content
7552 (or (not (null arg)) org-insert-heading-respect-content))
7553 (level nil)
7554 (on-heading (org-at-heading-p))
7555 ;; Get a level to fall back on
7556 (fix-level
7557 (save-excursion
7558 (org-back-to-heading t)
7559 (looking-at org-outline-regexp)
7560 (make-string (1- (length (match-string 0))) ?*)))
7561 (on-empty-line
7562 (save-excursion (beginning-of-line 1) (looking-at "^\\s-*$")))
7563 (head (save-excursion
7564 (condition-case nil
7565 (progn
7566 (org-back-to-heading invisible-ok)
7567 (when (and (not on-heading)
7568 (featurep 'org-inlinetask)
7569 (integerp org-inlinetask-min-level)
7570 (>= (length (match-string 0))
7571 org-inlinetask-min-level))
7572 ;; Find a heading level before the inline task
7573 (while (and (setq level (org-up-heading-safe))
7574 (>= level org-inlinetask-min-level)))
7575 (if (org-at-heading-p)
7576 (org-back-to-heading invisible-ok)
7577 (error "This should not happen")))
7578 (unless (and (save-excursion
7579 (save-match-data
7580 (org-backward-heading-same-level 1 invisible-ok))
7581 (= (point) (match-beginning 0)))
7582 (not (org-previous-line-empty-p t)))
7583 (setq empty-line-p (org-previous-line-empty-p)))
7584 (match-string 0))
7585 (error (or fix-level "* ")))))
7586 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7587 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7588 pos hide-previous previous-pos)
7589 (if ;; At the beginning of a heading, open a new line for insertion
7590 (and (bolp) (org-at-heading-p)
7591 (not eops)
7592 (or (bobp)
7593 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7594 (open-line (if blank 2 1))
7595 (save-excursion
7596 (setq previous-pos (point-at-bol))
7597 (end-of-line)
7598 (setq hide-previous (outline-invisible-p)))
7599 (and org-insert-heading-respect-content
7600 (save-excursion
7601 (while (outline-invisible-p)
7602 (org-show-subtree)
7603 (org-up-heading-safe))))
7604 (let ((split
7605 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7606 (save-excursion
7607 (let ((p (point)))
7608 (goto-char (point-at-bol))
7609 (and (looking-at org-complex-heading-regexp)
7610 (match-beginning 4)
7611 (> p (match-beginning 4)))))))
7612 tags pos)
7613 (cond
7614 ;; Insert a new line, possibly at end of parent subtree
7615 ((and (not arg) (not on-heading) (not on-empty-line)
7616 (not (save-excursion
7617 (beginning-of-line 1)
7618 (or (looking-at org-list-full-item-re)
7619 ;; Don't convert :end: lines to headline
7620 (looking-at "^\\s-*:end:")
7621 (looking-at "^\\s-*#\\+end_?")))))
7622 (beginning-of-line 1))
7623 (org-insert-heading-respect-content
7624 (if (not eops)
7625 (progn
7626 (org-end-of-subtree nil t)
7627 (and (looking-at "^\\*") (backward-char 1))
7628 (while (and (not (bobp))
7629 ;; Don't delete spaces in empty headlines
7630 (not (looking-back org-outline-regexp))
7631 (member (char-before) '(?\ ?\t ?\n)))
7632 (backward-delete-char 1)))
7633 (let ((p (point)))
7634 (org-up-heading-safe)
7635 (if (= p (point))
7636 (goto-char (point-max))
7637 (org-end-of-subtree nil t))))
7638 (when (featurep 'org-inlinetask)
7639 (while (and (not (eobp))
7640 (looking-at "\\(\\*+\\)[ \t]+")
7641 (>= (length (match-string 1))
7642 org-inlinetask-min-level))
7643 (org-end-of-subtree nil t)))
7644 (or (bolp) (newline))
7645 (or (org-previous-line-empty-p)
7646 (and blank (newline)))
7647 (if (or empty-line-p eops) (open-line 1)))
7648 ;; Insert a headling containing text after point
7649 ((org-at-heading-p)
7650 (when hide-previous
7651 (show-children)
7652 (org-show-entry))
7653 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7654 (setq tags (and (match-end 2) (match-string 2)))
7655 (and (match-end 1)
7656 (delete-region (match-beginning 1) (match-end 1)))
7657 (setq pos (point-at-bol))
7658 (or split (end-of-line 1))
7659 (delete-horizontal-space)
7660 (if (string-match "\\`\\*+\\'"
7661 (buffer-substring (point-at-bol) (point)))
7662 (insert " "))
7663 (newline (if blank 2 1))
7664 (when tags
7665 (save-excursion
7666 (goto-char pos)
7667 (end-of-line 1)
7668 (insert " " tags)
7669 (org-set-tags nil 'align))))
7671 (or split (end-of-line 1))
7672 (newline (cond ((and blank (not on-empty-line)) 2)
7673 (blank 1)
7674 (on-empty-line 0) (t 1)))))))
7675 (insert head) (just-one-space)
7676 (setq pos (point))
7677 (end-of-line 1)
7678 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7679 (when (and org-insert-heading-respect-content hide-previous)
7680 (save-excursion
7681 (goto-char previous-pos)
7682 (hide-subtree)))
7683 (when (and begn endn)
7684 (narrow-to-region (min (point) begn) (max (point) endn)))
7685 (run-hooks 'org-insert-heading-hook)))))))
7687 (defun org-get-heading (&optional no-tags no-todo)
7688 "Return the heading of the current entry, without the stars.
7689 When NO-TAGS is non-nil, don't include tags.
7690 When NO-TODO is non-nil, don't include TODO keywords."
7691 (save-excursion
7692 (org-back-to-heading t)
7693 (cond
7694 ((and no-tags no-todo)
7695 (looking-at org-complex-heading-regexp)
7696 (match-string 4))
7697 (no-tags
7698 (looking-at (concat org-outline-regexp
7699 "\\(.*?\\)"
7700 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7701 (match-string 1))
7702 (no-todo
7703 (looking-at org-todo-line-regexp)
7704 (match-string 3))
7705 (t (looking-at org-heading-regexp)
7706 (match-string 2)))))
7708 (defvar orgstruct-mode) ; defined below
7710 (defun org-heading-components ()
7711 "Return the components of the current heading.
7712 This is a list with the following elements:
7713 - the level as an integer
7714 - the reduced level, different if `org-odd-levels-only' is set.
7715 - the TODO keyword, or nil
7716 - the priority character, like ?A, or nil if no priority is given
7717 - the headline text itself, or the tags string if no headline text
7718 - the tags string, or nil."
7719 (save-excursion
7720 (org-back-to-heading t)
7721 (if (let (case-fold-search)
7722 (looking-at
7723 (if orgstruct-mode
7724 org-heading-regexp
7725 org-complex-heading-regexp)))
7726 (if orgstruct-mode
7727 (list (length (match-string 1))
7728 (org-reduced-level (length (match-string 1)))
7731 (match-string 2)
7732 nil)
7733 (list (length (match-string 1))
7734 (org-reduced-level (length (match-string 1)))
7735 (org-match-string-no-properties 2)
7736 (and (match-end 3) (aref (match-string 3) 2))
7737 (org-match-string-no-properties 4)
7738 (org-match-string-no-properties 5))))))
7740 (defun org-get-entry ()
7741 "Get the entry text, after heading, entire subtree."
7742 (save-excursion
7743 (org-back-to-heading t)
7744 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7746 (defun org-insert-heading-after-current ()
7747 "Insert a new heading with same level as current, after current subtree."
7748 (interactive)
7749 (org-back-to-heading)
7750 (org-insert-heading)
7751 (org-move-subtree-down)
7752 (end-of-line 1))
7754 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7755 "Insert heading with `org-insert-heading-respect-content' set to t."
7756 (interactive "P")
7757 (let ((org-insert-heading-respect-content t))
7758 (org-insert-heading arg invisible-ok)))
7760 (defun org-insert-todo-heading-respect-content (&optional force-state)
7761 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7762 (interactive "P")
7763 (let ((org-insert-heading-respect-content t))
7764 (org-insert-todo-heading force-state t)))
7766 (defun org-insert-todo-heading (arg &optional force-heading)
7767 "Insert a new heading with the same level and TODO state as current heading.
7768 If the heading has no TODO state, or if the state is DONE, use the first
7769 state (TODO by default). Also one prefix arg, force first state. With two
7770 prefix args, force inserting at the end of the parent subtree."
7771 (interactive "P")
7772 (when (or force-heading (not (org-insert-item 'checkbox)))
7773 (org-insert-heading (or (and (equal arg '(16)) '(16))
7774 force-heading))
7775 (save-excursion
7776 (org-back-to-heading)
7777 (outline-previous-heading)
7778 (looking-at org-todo-line-regexp))
7779 (let*
7780 ((new-mark-x
7781 (if (or arg
7782 (not (match-beginning 2))
7783 (member (match-string 2) org-done-keywords))
7784 (car org-todo-keywords-1)
7785 (match-string 2)))
7786 (new-mark
7788 (run-hook-with-args-until-success
7789 'org-todo-get-default-hook new-mark-x nil)
7790 new-mark-x)))
7791 (beginning-of-line 1)
7792 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7793 (if org-treat-insert-todo-heading-as-state-change
7794 (org-todo new-mark)
7795 (insert new-mark " "))))
7796 (when org-provide-todo-statistics
7797 (org-update-parent-todo-statistics))))
7799 (defun org-insert-subheading (arg)
7800 "Insert a new subheading and demote it.
7801 Works for outline headings and for plain lists alike."
7802 (interactive "P")
7803 (org-insert-heading arg)
7804 (cond
7805 ((org-at-heading-p) (org-do-demote))
7806 ((org-at-item-p) (org-indent-item))))
7808 (defun org-insert-todo-subheading (arg)
7809 "Insert a new subheading with TODO keyword or checkbox and demote it.
7810 Works for outline headings and for plain lists alike."
7811 (interactive "P")
7812 (org-insert-todo-heading arg)
7813 (cond
7814 ((org-at-heading-p) (org-do-demote))
7815 ((org-at-item-p) (org-indent-item))))
7817 ;;; Promotion and Demotion
7819 (defvar org-after-demote-entry-hook nil
7820 "Hook run after an entry has been demoted.
7821 The cursor will be at the beginning of the entry.
7822 When a subtree is being demoted, the hook will be called for each node.")
7824 (defvar org-after-promote-entry-hook nil
7825 "Hook run after an entry has been promoted.
7826 The cursor will be at the beginning of the entry.
7827 When a subtree is being promoted, the hook will be called for each node.")
7829 (defun org-promote-subtree ()
7830 "Promote the entire subtree.
7831 See also `org-promote'."
7832 (interactive)
7833 (save-excursion
7834 (org-with-limited-levels (org-map-tree 'org-promote)))
7835 (org-fix-position-after-promote))
7837 (defun org-demote-subtree ()
7838 "Demote the entire subtree. See `org-demote'.
7839 See also `org-promote'."
7840 (interactive)
7841 (save-excursion
7842 (org-with-limited-levels (org-map-tree 'org-demote)))
7843 (org-fix-position-after-promote))
7846 (defun org-do-promote ()
7847 "Promote the current heading higher up the tree.
7848 If the region is active in `transient-mark-mode', promote all headings
7849 in the region."
7850 (interactive)
7851 (save-excursion
7852 (if (org-region-active-p)
7853 (org-map-region 'org-promote (region-beginning) (region-end))
7854 (org-promote)))
7855 (org-fix-position-after-promote))
7857 (defun org-do-demote ()
7858 "Demote the current heading lower down the tree.
7859 If the region is active in `transient-mark-mode', demote all headings
7860 in the region."
7861 (interactive)
7862 (save-excursion
7863 (if (org-region-active-p)
7864 (org-map-region 'org-demote (region-beginning) (region-end))
7865 (org-demote)))
7866 (org-fix-position-after-promote))
7868 (defun org-fix-position-after-promote ()
7869 "Make sure that after pro/demotion cursor position is right."
7870 (let ((pos (point)))
7871 (when (save-excursion
7872 (beginning-of-line 1)
7873 (looking-at org-todo-line-regexp)
7874 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7875 (cond ((eobp) (insert " "))
7876 ((eolp) (insert " "))
7877 ((equal (char-after) ?\ ) (forward-char 1))))))
7879 (defun org-current-level ()
7880 "Return the level of the current entry, or nil if before the first headline.
7881 The level is the number of stars at the beginning of the headline."
7882 (save-excursion
7883 (org-with-limited-levels
7884 (if (ignore-errors (org-back-to-heading t))
7885 (funcall outline-level)))))
7887 (defun org-get-previous-line-level ()
7888 "Return the outline depth of the last headline before the current line.
7889 Returns 0 for the first headline in the buffer, and nil if before the
7890 first headline."
7891 (let ((current-level (org-current-level))
7892 (prev-level (when (> (line-number-at-pos) 1)
7893 (save-excursion
7894 (beginning-of-line 0)
7895 (org-current-level)))))
7896 (cond ((null current-level) nil) ; Before first headline
7897 ((null prev-level) 0) ; At first headline
7898 (prev-level))))
7900 (defun org-reduced-level (l)
7901 "Compute the effective level of a heading.
7902 This takes into account the setting of `org-odd-levels-only'."
7903 (cond
7904 ((zerop l) 0)
7905 (org-odd-levels-only (1+ (floor (/ l 2))))
7906 (t l)))
7908 (defun org-level-increment ()
7909 "Return the number of stars that will be added or removed at a
7910 time to headlines when structure editing, based on the value of
7911 `org-odd-levels-only'."
7912 (if org-odd-levels-only 2 1))
7914 (defun org-get-valid-level (level &optional change)
7915 "Rectify a level change under the influence of `org-odd-levels-only'
7916 LEVEL is a current level, CHANGE is by how much the level should be
7917 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7918 even level numbers will become the next higher odd number."
7919 (if org-odd-levels-only
7920 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7921 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7922 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7923 (max 1 (+ level (or change 0)))))
7925 (if (boundp 'define-obsolete-function-alias)
7926 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7927 (define-obsolete-function-alias 'org-get-legal-level
7928 'org-get-valid-level)
7929 (define-obsolete-function-alias 'org-get-legal-level
7930 'org-get-valid-level "23.1")))
7932 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7933 ;; ̀org-with-limited-levels'
7934 (defun org-promote ()
7935 "Promote the current heading higher up the tree.
7936 If the region is active in `transient-mark-mode', promote all headings
7937 in the region."
7938 (org-back-to-heading t)
7939 (let* ((level (save-match-data (funcall outline-level)))
7940 (after-change-functions (remove 'flyspell-after-change-function
7941 after-change-functions))
7942 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7943 (diff (abs (- level (length up-head) -1))))
7944 (cond ((and (= level 1) org-called-with-limited-levels
7945 org-allow-promoting-top-level-subtree)
7946 (replace-match "# " nil t))
7947 ((= level 1)
7948 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7949 (t (replace-match up-head nil t)))
7950 ;; Fixup tag positioning
7951 (unless (= level 1)
7952 (and org-auto-align-tags (org-set-tags nil t))
7953 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7954 (run-hooks 'org-after-promote-entry-hook)))
7956 (defun org-demote ()
7957 "Demote the current heading lower down the tree.
7958 If the region is active in `transient-mark-mode', demote all headings
7959 in the region."
7960 (org-back-to-heading t)
7961 (let* ((level (save-match-data (funcall outline-level)))
7962 (after-change-functions (remove 'flyspell-after-change-function
7963 after-change-functions))
7964 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7965 (diff (abs (- level (length down-head) -1))))
7966 (replace-match down-head nil t)
7967 ;; Fixup tag positioning
7968 (and org-auto-align-tags (org-set-tags nil t))
7969 (if org-adapt-indentation (org-fixup-indentation diff))
7970 (run-hooks 'org-after-demote-entry-hook)))
7972 (defun org-cycle-level ()
7973 "Cycle the level of an empty headline through possible states.
7974 This goes first to child, then to parent, level, then up the hierarchy.
7975 After top level, it switches back to sibling level."
7976 (interactive)
7977 (let ((org-adapt-indentation nil))
7978 (when (org-point-at-end-of-empty-headline)
7979 (setq this-command 'org-cycle-level) ; Only needed for caching
7980 (let ((cur-level (org-current-level))
7981 (prev-level (org-get-previous-line-level)))
7982 (cond
7983 ;; If first headline in file, promote to top-level.
7984 ((= prev-level 0)
7985 (loop repeat (/ (- cur-level 1) (org-level-increment))
7986 do (org-do-promote)))
7987 ;; If same level as prev, demote one.
7988 ((= prev-level cur-level)
7989 (org-do-demote))
7990 ;; If parent is top-level, promote to top level if not already.
7991 ((= prev-level 1)
7992 (loop repeat (/ (- cur-level 1) (org-level-increment))
7993 do (org-do-promote)))
7994 ;; If top-level, return to prev-level.
7995 ((= cur-level 1)
7996 (loop repeat (/ (- prev-level 1) (org-level-increment))
7997 do (org-do-demote)))
7998 ;; If less than prev-level, promote one.
7999 ((< cur-level prev-level)
8000 (org-do-promote))
8001 ;; If deeper than prev-level, promote until higher than
8002 ;; prev-level.
8003 ((> cur-level prev-level)
8004 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8005 do (org-do-promote))))
8006 t))))
8008 (defun org-map-tree (fun)
8009 "Call FUN for every heading underneath the current one."
8010 (org-back-to-heading)
8011 (let ((level (funcall outline-level)))
8012 (save-excursion
8013 (funcall fun)
8014 (while (and (progn
8015 (outline-next-heading)
8016 (> (funcall outline-level) level))
8017 (not (eobp)))
8018 (funcall fun)))))
8020 (defun org-map-region (fun beg end)
8021 "Call FUN for every heading between BEG and END."
8022 (let ((org-ignore-region t))
8023 (save-excursion
8024 (setq end (copy-marker end))
8025 (goto-char beg)
8026 (if (and (re-search-forward org-outline-regexp-bol nil t)
8027 (< (point) end))
8028 (funcall fun))
8029 (while (and (progn
8030 (outline-next-heading)
8031 (< (point) end))
8032 (not (eobp)))
8033 (funcall fun)))))
8035 (defvar org-property-end-re) ; silence byte-compiler
8036 (defun org-fixup-indentation (diff)
8037 "Change the indentation in the current entry by DIFF.
8038 However, if any line in the current entry has no indentation, or if it
8039 would end up with no indentation after the change, nothing at all is done."
8040 (save-excursion
8041 (let ((end (save-excursion (outline-next-heading)
8042 (point-marker)))
8043 (prohibit (if (> diff 0)
8044 "^\\S-"
8045 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8046 col)
8047 (unless (save-excursion (end-of-line 1)
8048 (re-search-forward prohibit end t))
8049 (while (and (< (point) end)
8050 (re-search-forward "^[ \t]+" end t))
8051 (goto-char (match-end 0))
8052 (setq col (current-column))
8053 (if (< diff 0) (replace-match ""))
8054 (org-indent-to-column (+ diff col))))
8055 (move-marker end nil))))
8057 (defun org-convert-to-odd-levels ()
8058 "Convert an org-mode file with all levels allowed to one with odd levels.
8059 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8060 level 5 etc."
8061 (interactive)
8062 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8063 (let ((outline-level 'org-outline-level)
8064 (org-odd-levels-only nil) n)
8065 (save-excursion
8066 (goto-char (point-min))
8067 (while (re-search-forward "^\\*\\*+ " nil t)
8068 (setq n (- (length (match-string 0)) 2))
8069 (while (>= (setq n (1- n)) 0)
8070 (org-demote))
8071 (end-of-line 1))))))
8073 (defun org-convert-to-oddeven-levels ()
8074 "Convert an org-mode file with only odd levels to one with odd/even levels.
8075 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8076 file contains a section with an even level, conversion would
8077 destroy the structure of the file. An error is signaled in this
8078 case."
8079 (interactive)
8080 (goto-char (point-min))
8081 ;; First check if there are no even levels
8082 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8083 (org-show-context t)
8084 (error "Not all levels are odd in this file. Conversion not possible"))
8085 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8086 (let ((outline-regexp org-outline-regexp)
8087 (outline-level 'org-outline-level)
8088 (org-odd-levels-only nil) n)
8089 (save-excursion
8090 (goto-char (point-min))
8091 (while (re-search-forward "^\\*\\*+ " nil t)
8092 (setq n (/ (1- (length (match-string 0))) 2))
8093 (while (>= (setq n (1- n)) 0)
8094 (org-promote))
8095 (end-of-line 1))))))
8097 (defun org-tr-level (n)
8098 "Make N odd if required."
8099 (if org-odd-levels-only (1+ (/ n 2)) n))
8101 ;;; Vertical tree motion, cutting and pasting of subtrees
8103 (defun org-move-subtree-up (&optional arg)
8104 "Move the current subtree up past ARG headlines of the same level."
8105 (interactive "p")
8106 (org-move-subtree-down (- (prefix-numeric-value arg))))
8108 (defun org-move-subtree-down (&optional arg)
8109 "Move the current subtree down past ARG headlines of the same level."
8110 (interactive "p")
8111 (setq arg (prefix-numeric-value arg))
8112 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8113 'org-get-last-sibling))
8114 (ins-point (make-marker))
8115 (cnt (abs arg))
8116 (col (current-column))
8117 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8118 ;; Select the tree
8119 (org-back-to-heading)
8120 (setq beg0 (point))
8121 (save-excursion
8122 (setq ne-beg (org-back-over-empty-lines))
8123 (setq beg (point)))
8124 (save-match-data
8125 (save-excursion (outline-end-of-heading)
8126 (setq folded (outline-invisible-p)))
8127 (outline-end-of-subtree))
8128 (outline-next-heading)
8129 (setq ne-end (org-back-over-empty-lines))
8130 (setq end (point))
8131 (goto-char beg0)
8132 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8133 ;; include less whitespace
8134 (save-excursion
8135 (goto-char beg)
8136 (forward-line (- ne-beg ne-end))
8137 (setq beg (point))))
8138 ;; Find insertion point, with error handling
8139 (while (> cnt 0)
8140 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8141 (progn (goto-char beg0)
8142 (user-error "Cannot move past superior level or buffer limit")))
8143 (setq cnt (1- cnt)))
8144 (if (> arg 0)
8145 ;; Moving forward - still need to move over subtree
8146 (progn (org-end-of-subtree t t)
8147 (save-excursion
8148 (org-back-over-empty-lines)
8149 (or (bolp) (newline)))))
8150 (setq ne-ins (org-back-over-empty-lines))
8151 (move-marker ins-point (point))
8152 (setq txt (buffer-substring beg end))
8153 (org-save-markers-in-region beg end)
8154 (delete-region beg end)
8155 (org-remove-empty-overlays-at beg)
8156 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8157 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8158 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8159 (let ((bbb (point)))
8160 (insert-before-markers txt)
8161 (org-reinstall-markers-in-region bbb)
8162 (move-marker ins-point bbb))
8163 (or (bolp) (insert "\n"))
8164 (setq ins-end (point))
8165 (goto-char ins-point)
8166 (org-skip-whitespace)
8167 (when (and (< arg 0)
8168 (org-first-sibling-p)
8169 (> ne-ins ne-beg))
8170 ;; Move whitespace back to beginning
8171 (save-excursion
8172 (goto-char ins-end)
8173 (let ((kill-whole-line t))
8174 (kill-line (- ne-ins ne-beg)) (point)))
8175 (insert (make-string (- ne-ins ne-beg) ?\n)))
8176 (move-marker ins-point nil)
8177 (if folded
8178 (hide-subtree)
8179 (org-show-entry)
8180 (show-children)
8181 (org-cycle-hide-drawers 'children))
8182 (org-clean-visibility-after-subtree-move)
8183 ;; move back to the initial column we were at
8184 (move-to-column col)))
8186 (defvar org-subtree-clip ""
8187 "Clipboard for cut and paste of subtrees.
8188 This is actually only a copy of the kill, because we use the normal kill
8189 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8191 (defvar org-subtree-clip-folded nil
8192 "Was the last copied subtree folded?
8193 This is used to fold the tree back after pasting.")
8195 (defun org-cut-subtree (&optional n)
8196 "Cut the current subtree into the clipboard.
8197 With prefix arg N, cut this many sequential subtrees.
8198 This is a short-hand for marking the subtree and then cutting it."
8199 (interactive "p")
8200 (org-copy-subtree n 'cut))
8202 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8203 "Copy the current subtree it in the clipboard.
8204 With prefix arg N, copy this many sequential subtrees.
8205 This is a short-hand for marking the subtree and then copying it.
8206 If CUT is non-nil, actually cut the subtree.
8207 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8208 of some markers in the region, even if CUT is non-nil. This is
8209 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8210 (interactive "p")
8211 (let (beg end folded (beg0 (point)))
8212 (if (org-called-interactively-p 'any)
8213 (org-back-to-heading nil) ; take what looks like a subtree
8214 (org-back-to-heading t)) ; take what is really there
8215 (setq beg (point))
8216 (skip-chars-forward " \t\r\n")
8217 (save-match-data
8218 (if nosubtrees
8219 (outline-next-heading)
8220 (save-excursion (outline-end-of-heading)
8221 (setq folded (outline-invisible-p)))
8222 (condition-case nil
8223 (org-forward-heading-same-level (1- n) t)
8224 (error nil))
8225 (org-end-of-subtree t t)))
8226 (setq end (point))
8227 (goto-char beg0)
8228 (when (> end beg)
8229 (setq org-subtree-clip-folded folded)
8230 (when (or cut force-store-markers)
8231 (org-save-markers-in-region beg end))
8232 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8233 (setq org-subtree-clip (current-kill 0))
8234 (message "%s: Subtree(s) with %d characters"
8235 (if cut "Cut" "Copied")
8236 (length org-subtree-clip)))))
8238 (defun org-paste-subtree (&optional level tree for-yank)
8239 "Paste the clipboard as a subtree, with modification of headline level.
8240 The entire subtree is promoted or demoted in order to match a new headline
8241 level.
8243 If the cursor is at the beginning of a headline, the same level as
8244 that headline is used to paste the tree.
8246 If not, the new level is derived from the *visible* headings
8247 before and after the insertion point, and taken to be the inferior headline
8248 level of the two. So if the previous visible heading is level 3 and the
8249 next is level 4 (or vice versa), level 4 will be used for insertion.
8250 This makes sure that the subtree remains an independent subtree and does
8251 not swallow low level entries.
8253 You can also force a different level, either by using a numeric prefix
8254 argument, or by inserting the heading marker by hand. For example, if the
8255 cursor is after \"*****\", then the tree will be shifted to level 5.
8257 If optional TREE is given, use this text instead of the kill ring.
8259 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8260 move back over whitespace before inserting, and move point to the end of
8261 the inserted text when done."
8262 (interactive "P")
8263 (setq tree (or tree (and kill-ring (current-kill 0))))
8264 (unless (org-kill-is-subtree-p tree)
8265 (user-error "%s"
8266 (substitute-command-keys
8267 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8268 (org-with-limited-levels
8269 (let* ((visp (not (outline-invisible-p)))
8270 (txt tree)
8271 (^re_ "\\(\\*+\\)[ \t]*")
8272 (old-level (if (string-match org-outline-regexp-bol txt)
8273 (- (match-end 0) (match-beginning 0) 1)
8274 -1))
8275 (force-level (cond (level (prefix-numeric-value level))
8276 ((and (looking-at "[ \t]*$")
8277 (string-match
8278 "^\\*+$" (buffer-substring
8279 (point-at-bol) (point))))
8280 (- (match-end 1) (match-beginning 1)))
8281 ((and (bolp)
8282 (looking-at org-outline-regexp))
8283 (- (match-end 0) (point) 1))))
8284 (previous-level (save-excursion
8285 (condition-case nil
8286 (progn
8287 (outline-previous-visible-heading 1)
8288 (if (looking-at ^re_)
8289 (- (match-end 0) (match-beginning 0) 1)
8291 (error 1))))
8292 (next-level (save-excursion
8293 (condition-case nil
8294 (progn
8295 (or (looking-at org-outline-regexp)
8296 (outline-next-visible-heading 1))
8297 (if (looking-at ^re_)
8298 (- (match-end 0) (match-beginning 0) 1)
8300 (error 1))))
8301 (new-level (or force-level (max previous-level next-level)))
8302 (shift (if (or (= old-level -1)
8303 (= new-level -1)
8304 (= old-level new-level))
8306 (- new-level old-level)))
8307 (delta (if (> shift 0) -1 1))
8308 (func (if (> shift 0) 'org-demote 'org-promote))
8309 (org-odd-levels-only nil)
8310 beg end newend)
8311 ;; Remove the forced level indicator
8312 (if force-level
8313 (delete-region (point-at-bol) (point)))
8314 ;; Paste
8315 (beginning-of-line (if (bolp) 1 2))
8316 (setq beg (point))
8317 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8318 (insert-before-markers txt)
8319 (unless (string-match "\n\\'" txt) (insert "\n"))
8320 (setq newend (point))
8321 (org-reinstall-markers-in-region beg)
8322 (setq end (point))
8323 (goto-char beg)
8324 (skip-chars-forward " \t\n\r")
8325 (setq beg (point))
8326 (if (and (outline-invisible-p) visp)
8327 (save-excursion (outline-show-heading)))
8328 ;; Shift if necessary
8329 (unless (= shift 0)
8330 (save-restriction
8331 (narrow-to-region beg end)
8332 (while (not (= shift 0))
8333 (org-map-region func (point-min) (point-max))
8334 (setq shift (+ delta shift)))
8335 (goto-char (point-min))
8336 (setq newend (point-max))))
8337 (when (or (org-called-interactively-p 'interactive) for-yank)
8338 (message "Clipboard pasted as level %d subtree" new-level))
8339 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8340 kill-ring
8341 (eq org-subtree-clip (current-kill 0))
8342 org-subtree-clip-folded)
8343 ;; The tree was folded before it was killed/copied
8344 (hide-subtree))
8345 (and for-yank (goto-char newend)))))
8347 (defun org-kill-is-subtree-p (&optional txt)
8348 "Check if the current kill is an outline subtree, or a set of trees.
8349 Returns nil if kill does not start with a headline, or if the first
8350 headline level is not the largest headline level in the tree.
8351 So this will actually accept several entries of equal levels as well,
8352 which is OK for `org-paste-subtree'.
8353 If optional TXT is given, check this string instead of the current kill."
8354 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8355 (re (org-get-limited-outline-regexp))
8356 (^re (concat "^" re))
8357 (start-level (and kill
8358 (string-match
8359 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8360 kill)
8361 (- (match-end 2) (match-beginning 2) 1)))
8362 (start (1+ (or (match-beginning 2) -1))))
8363 (if (not start-level)
8364 (progn
8365 nil) ;; does not even start with a heading
8366 (catch 'exit
8367 (while (setq start (string-match ^re kill (1+ start)))
8368 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8369 (throw 'exit nil)))
8370 t))))
8372 (defvar org-markers-to-move nil
8373 "Markers that should be moved with a cut-and-paste operation.
8374 Those markers are stored together with their positions relative to
8375 the start of the region.")
8377 (defun org-save-markers-in-region (beg end)
8378 "Check markers in region.
8379 If these markers are between BEG and END, record their position relative
8380 to BEG, so that after moving the block of text, we can put the markers back
8381 into place.
8382 This function gets called just before an entry or tree gets cut from the
8383 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8384 called immediately, to move the markers with the entries."
8385 (setq org-markers-to-move nil)
8386 (when (featurep 'org-clock)
8387 (org-clock-save-markers-for-cut-and-paste beg end))
8388 (when (featurep 'org-agenda)
8389 (org-agenda-save-markers-for-cut-and-paste beg end)))
8391 (defun org-check-and-save-marker (marker beg end)
8392 "Check if MARKER is between BEG and END.
8393 If yes, remember the marker and the distance to BEG."
8394 (when (and (marker-buffer marker)
8395 (equal (marker-buffer marker) (current-buffer)))
8396 (if (and (>= marker beg) (< marker end))
8397 (push (cons marker (- marker beg)) org-markers-to-move))))
8399 (defun org-reinstall-markers-in-region (beg)
8400 "Move all remembered markers to their position relative to BEG."
8401 (mapc (lambda (x)
8402 (move-marker (car x) (+ beg (cdr x))))
8403 org-markers-to-move)
8404 (setq org-markers-to-move nil))
8406 (defun org-narrow-to-subtree ()
8407 "Narrow buffer to the current subtree."
8408 (interactive)
8409 (save-excursion
8410 (save-match-data
8411 (org-with-limited-levels
8412 (narrow-to-region
8413 (progn (org-back-to-heading t) (point))
8414 (progn (org-end-of-subtree t t)
8415 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8416 (point)))))))
8418 (defun org-narrow-to-block ()
8419 "Narrow buffer to the current block."
8420 (interactive)
8421 (let* ((case-fold-search t)
8422 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8423 "^[ \t]*#\\+end_.*")))
8424 (if blockp
8425 (narrow-to-region (car blockp) (cdr blockp))
8426 (user-error "Not in a block"))))
8428 (eval-when-compile
8429 (defvar org-property-drawer-re))
8431 (defvar org-property-start-re) ;; defined below
8432 (defun org-clone-subtree-with-time-shift (n &optional shift)
8433 "Clone the task (subtree) at point N times.
8434 The clones will be inserted as siblings.
8436 In interactive use, the user will be prompted for the number of
8437 clones to be produced. If the entry has a timestamp, the user
8438 will also be prompted for a time shift, which may be a repeater
8439 as used in time stamps, for example `+3d'. To disable this,
8440 you can call the function with a universal prefix argument.
8442 When a valid repeater is given and the entry contains any time
8443 stamps, the clones will become a sequence in time, with time
8444 stamps in the subtree shifted for each clone produced. If SHIFT
8445 is nil or the empty string, time stamps will be left alone. The
8446 ID property of the original subtree is removed.
8448 If the original subtree did contain time stamps with a repeater,
8449 the following will happen:
8450 - the repeater will be removed in each clone
8451 - an additional clone will be produced, with the current, unshifted
8452 date(s) in the entry.
8453 - the original entry will be placed *after* all the clones, with
8454 repeater intact.
8455 - the start days in the repeater in the original entry will be shifted
8456 to past the last clone.
8457 In this way you can spell out a number of instances of a repeating task,
8458 and still retain the repeater to cover future instances of the task."
8459 (interactive "nNumber of clones to produce: ")
8460 (let ((shift
8461 (or shift
8462 (if (and (not (equal current-prefix-arg '(4)))
8463 (save-excursion
8464 (re-search-forward org-ts-regexp-both
8465 (save-excursion
8466 (org-end-of-subtree t)
8467 (point)) t)))
8468 (read-from-minibuffer
8469 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8470 ""))) ;; No time shift
8471 (n-no-remove -1)
8472 (drawer-re org-drawer-regexp)
8473 beg end template task idprop
8474 shift-n shift-what doshift nmin nmax)
8475 (if (not (and (integerp n) (> n 0)))
8476 (error "Invalid number of replications %s" n))
8477 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8478 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8479 shift)))
8480 (error "Invalid shift specification %s" shift))
8481 (when doshift
8482 (setq shift-n (string-to-number (match-string 1 shift))
8483 shift-what (cdr (assoc (match-string 2 shift)
8484 '(("d" . day) ("w" . week)
8485 ("m" . month) ("y" . year))))))
8486 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8487 (setq nmin 1 nmax n)
8488 (org-back-to-heading t)
8489 (setq beg (point))
8490 (setq idprop (org-entry-get nil "ID"))
8491 (org-end-of-subtree t t)
8492 (or (bolp) (insert "\n"))
8493 (setq end (point))
8494 (setq template (buffer-substring beg end))
8495 (when (and doshift
8496 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8497 (delete-region beg end)
8498 (setq end beg)
8499 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8500 (goto-char end)
8501 (loop for n from nmin to nmax do
8502 ;; prepare clone
8503 (with-temp-buffer
8504 (insert template)
8505 (org-mode)
8506 (goto-char (point-min))
8507 (org-show-subtree)
8508 (and idprop (if org-clone-delete-id
8509 (org-entry-delete nil "ID")
8510 (org-id-get-create t)))
8511 (unless (= n 0)
8512 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8513 (kill-whole-line))
8514 (goto-char (point-min))
8515 (while (re-search-forward drawer-re nil t)
8516 (mapc (lambda (d)
8517 (org-remove-empty-drawer-at d (point))) org-drawers)))
8518 (goto-char (point-min))
8519 (when doshift
8520 (while (re-search-forward org-ts-regexp-both nil t)
8521 (org-timestamp-change (* n shift-n) shift-what))
8522 (unless (= n n-no-remove)
8523 (goto-char (point-min))
8524 (while (re-search-forward org-ts-regexp nil t)
8525 (save-excursion
8526 (goto-char (match-beginning 0))
8527 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8528 (delete-region (match-beginning 1) (match-end 1)))))))
8529 (setq task (buffer-string)))
8530 (insert task))
8531 (goto-char beg)))
8533 ;;; Outline Sorting
8535 (defun org-sort (with-case)
8536 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8537 Optional argument WITH-CASE means sort case-sensitively."
8538 (interactive "P")
8539 (cond
8540 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8541 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8543 (org-call-with-arg 'org-sort-entries with-case))))
8545 (defun org-sort-remove-invisible (s)
8546 "Remove invisible links from string S."
8547 (remove-text-properties 0 (length s) org-rm-props s)
8548 (while (string-match org-bracket-link-regexp s)
8549 (setq s (replace-match (if (match-end 2)
8550 (match-string 3 s)
8551 (match-string 1 s)) t t s)))
8552 (let ((st (format " %s " s)))
8553 (while (string-match org-emph-re st)
8554 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8555 (setq s (substring st 1 -1)))
8558 (defvar org-priority-regexp) ; defined later in the file
8560 (defvar org-after-sorting-entries-or-items-hook nil
8561 "Hook that is run after a bunch of entries or items have been sorted.
8562 When children are sorted, the cursor is in the parent line when this
8563 hook gets called. When a region or a plain list is sorted, the cursor
8564 will be in the first entry of the sorted region/list.")
8566 (defun org-sort-entries
8567 (&optional with-case sorting-type getkey-func compare-func property)
8568 "Sort entries on a certain level of an outline tree.
8569 If there is an active region, the entries in the region are sorted.
8570 Else, if the cursor is before the first entry, sort the top-level items.
8571 Else, the children of the entry at point are sorted.
8573 Sorting can be alphabetically, numerically, by date/time as given by
8574 a time stamp, by a property, by priority order, or by a custom function.
8576 The command prompts for the sorting type unless it has been given to the
8577 function through the SORTING-TYPE argument, which needs to be a character,
8578 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8579 precise meaning of each character:
8581 n Numerically, by converting the beginning of the entry/item to a number.
8582 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8583 o By order of TODO keywords.
8584 t By date/time, either the first active time stamp in the entry, or, if
8585 none exist, by the first inactive one.
8586 s By the scheduled date/time.
8587 d By deadline date/time.
8588 c By creation time, which is assumed to be the first inactive time stamp
8589 at the beginning of a line.
8590 p By priority according to the cookie.
8591 r By the value of a property.
8593 Capital letters will reverse the sort order.
8595 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8596 called with point at the beginning of the record. It must return either
8597 a string or a number that should serve as the sorting key for that record.
8599 Comparing entries ignores case by default. However, with an optional argument
8600 WITH-CASE, the sorting considers case as well.
8602 Sorting is done against the visible part of the headlines, it ignores hidden
8603 links."
8604 (interactive "P")
8605 (let ((case-func (if with-case 'identity 'downcase))
8606 (cmstr
8607 ;; The clock marker is lost when using `sort-subr', let's
8608 ;; store the clocking string.
8609 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8610 (save-excursion
8611 (goto-char org-clock-marker)
8612 (looking-back "^.*") (match-string-no-properties 0))))
8613 start beg end stars re re2
8614 txt what tmp)
8615 ;; Find beginning and end of region to sort
8616 (cond
8617 ((org-region-active-p)
8618 ;; we will sort the region
8619 (setq end (region-end)
8620 what "region")
8621 (goto-char (region-beginning))
8622 (if (not (org-at-heading-p)) (outline-next-heading))
8623 (setq start (point)))
8624 ((or (org-at-heading-p)
8625 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8626 ;; we will sort the children of the current headline
8627 (org-back-to-heading)
8628 (setq start (point)
8629 end (progn (org-end-of-subtree t t)
8630 (or (bolp) (insert "\n"))
8631 (org-back-over-empty-lines)
8632 (point))
8633 what "children")
8634 (goto-char start)
8635 (show-subtree)
8636 (outline-next-heading))
8638 ;; we will sort the top-level entries in this file
8639 (goto-char (point-min))
8640 (or (org-at-heading-p) (outline-next-heading))
8641 (setq start (point))
8642 (goto-char (point-max))
8643 (beginning-of-line 1)
8644 (when (looking-at ".*?\\S-")
8645 ;; File ends in a non-white line
8646 (end-of-line 1)
8647 (insert "\n"))
8648 (setq end (point-max))
8649 (setq what "top-level")
8650 (goto-char start)
8651 (show-all)))
8653 (setq beg (point))
8654 (if (>= beg end) (user-error "Nothing to sort"))
8656 (looking-at "\\(\\*+\\)")
8657 (setq stars (match-string 1)
8658 re (concat "^" (regexp-quote stars) " +")
8659 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8660 txt (buffer-substring beg end))
8661 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8662 (if (and (not (equal stars "*")) (string-match re2 txt))
8663 (user-error "Region to sort contains a level above the first entry"))
8665 (unless sorting-type
8666 (message
8667 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8668 [t]ime [s]cheduled [d]eadline [c]reated
8669 A/N/P/R/O/F/T/S/D/C means reversed:"
8670 what)
8671 (setq sorting-type (read-char-exclusive))
8673 (unless getkey-func
8674 (and (= (downcase sorting-type) ?f)
8675 (setq getkey-func
8676 (org-icompleting-read "Sort using function: "
8677 obarray 'fboundp t nil nil))
8678 (setq getkey-func (intern getkey-func))))
8680 (and (= (downcase sorting-type) ?r)
8681 (not property)
8682 (setq property
8683 (org-icompleting-read "Property: "
8684 (mapcar 'list (org-buffer-property-keys t))
8685 nil t))))
8687 (message "Sorting entries...")
8689 (save-restriction
8690 (narrow-to-region start end)
8691 (let ((dcst (downcase sorting-type))
8692 (case-fold-search nil)
8693 (now (current-time)))
8694 (sort-subr
8695 (/= dcst sorting-type)
8696 ;; This function moves to the beginning character of the "record" to
8697 ;; be sorted.
8698 (lambda nil
8699 (if (re-search-forward re nil t)
8700 (goto-char (match-beginning 0))
8701 (goto-char (point-max))))
8702 ;; This function moves to the last character of the "record" being
8703 ;; sorted.
8704 (lambda nil
8705 (save-match-data
8706 (condition-case nil
8707 (outline-forward-same-level 1)
8708 (error
8709 (goto-char (point-max))))))
8710 ;; This function returns the value that gets sorted against.
8711 (lambda nil
8712 (cond
8713 ((= dcst ?n)
8714 (if (looking-at org-complex-heading-regexp)
8715 (string-to-number (org-sort-remove-invisible (match-string 4)))
8716 nil))
8717 ((= dcst ?a)
8718 (if (looking-at org-complex-heading-regexp)
8719 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8720 nil))
8721 ((= dcst ?t)
8722 (let ((end (save-excursion (outline-next-heading) (point))))
8723 (if (or (re-search-forward org-ts-regexp end t)
8724 (re-search-forward org-ts-regexp-both end t))
8725 (org-time-string-to-seconds (match-string 0))
8726 (org-float-time now))))
8727 ((= dcst ?c)
8728 (let ((end (save-excursion (outline-next-heading) (point))))
8729 (if (re-search-forward
8730 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8731 end t)
8732 (org-time-string-to-seconds (match-string 0))
8733 (org-float-time now))))
8734 ((= dcst ?s)
8735 (let ((end (save-excursion (outline-next-heading) (point))))
8736 (if (re-search-forward org-scheduled-time-regexp end t)
8737 (org-time-string-to-seconds (match-string 1))
8738 (org-float-time now))))
8739 ((= dcst ?d)
8740 (let ((end (save-excursion (outline-next-heading) (point))))
8741 (if (re-search-forward org-deadline-time-regexp end t)
8742 (org-time-string-to-seconds (match-string 1))
8743 (org-float-time now))))
8744 ((= dcst ?p)
8745 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8746 (string-to-char (match-string 2))
8747 org-default-priority))
8748 ((= dcst ?r)
8749 (or (org-entry-get nil property) ""))
8750 ((= dcst ?o)
8751 (if (looking-at org-complex-heading-regexp)
8752 (- 9999 (length (member (match-string 2)
8753 org-todo-keywords-1)))))
8754 ((= dcst ?f)
8755 (if getkey-func
8756 (progn
8757 (setq tmp (funcall getkey-func))
8758 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8759 tmp)
8760 (error "Invalid key function `%s'" getkey-func)))
8761 (t (error "Invalid sorting type `%c'" sorting-type))))
8763 (cond
8764 ((= dcst ?a) 'string<)
8765 ((= dcst ?f) compare-func)
8766 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8767 (run-hooks 'org-after-sorting-entries-or-items-hook)
8768 ;; Reset the clock marker if needed
8769 (when cmstr
8770 (save-excursion
8771 (goto-char start)
8772 (search-forward cmstr nil t)
8773 (move-marker org-clock-marker (point))))
8774 (message "Sorting entries...done")))
8776 (defun org-do-sort (table what &optional with-case sorting-type)
8777 "Sort TABLE of WHAT according to SORTING-TYPE.
8778 The user will be prompted for the SORTING-TYPE if the call to this
8779 function does not specify it. WHAT is only for the prompt, to indicate
8780 what is being sorted. The sorting key will be extracted from
8781 the car of the elements of the table.
8782 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8783 (unless sorting-type
8784 (message
8785 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8786 what)
8787 (setq sorting-type (read-char-exclusive)))
8788 (let ((dcst (downcase sorting-type))
8789 extractfun comparefun)
8790 ;; Define the appropriate functions
8791 (cond
8792 ((= dcst ?n)
8793 (setq extractfun 'string-to-number
8794 comparefun (if (= dcst sorting-type) '< '>)))
8795 ((= dcst ?a)
8796 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8797 (lambda(x) (downcase (org-sort-remove-invisible x))))
8798 comparefun (if (= dcst sorting-type)
8799 'string<
8800 (lambda (a b) (and (not (string< a b))
8801 (not (string= a b)))))))
8802 ((= dcst ?t)
8803 (setq extractfun
8804 (lambda (x)
8805 (if (or (string-match org-ts-regexp x)
8806 (string-match org-ts-regexp-both x))
8807 (org-float-time
8808 (org-time-string-to-time (match-string 0 x)))
8810 comparefun (if (= dcst sorting-type) '< '>)))
8811 (t (error "Invalid sorting type `%c'" sorting-type)))
8813 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8814 table)
8815 (lambda (a b) (funcall comparefun (car a) (car b))))))
8818 ;;; The orgstruct minor mode
8820 ;; Define a minor mode which can be used in other modes in order to
8821 ;; integrate the org-mode structure editing commands.
8823 ;; This is really a hack, because the org-mode structure commands use
8824 ;; keys which normally belong to the major mode. Here is how it
8825 ;; works: The minor mode defines all the keys necessary to operate the
8826 ;; structure commands, but wraps the commands into a function which
8827 ;; tests if the cursor is currently at a headline or a plain list
8828 ;; item. If that is the case, the structure command is used,
8829 ;; temporarily setting many Org-mode variables like regular
8830 ;; expressions for filling etc. However, when any of those keys is
8831 ;; used at a different location, function uses `key-binding' to look
8832 ;; up if the key has an associated command in another currently active
8833 ;; keymap (minor modes, major mode, global), and executes that
8834 ;; command. There might be problems if any of the keys is otherwise
8835 ;; used as a prefix key.
8837 (defcustom orgstruct-heading-prefix-regexp nil
8838 "Regexp that matches the custom prefix of Org headlines in
8839 orgstruct(++)-mode."
8840 :group 'org
8841 :version "24.4"
8842 :package-version '(Org . "8.0")
8843 :type 'string)
8844 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8846 (defcustom orgstruct-setup-hook nil
8847 "Hook run after orgstruct-mode-map is filled."
8848 :group 'org
8849 :version "24.4"
8850 :package-version '(Org . "8.0")
8851 :type 'hook)
8853 (defvar orgstruct-initialized nil)
8855 (defvar org-local-vars nil
8856 "List of local variables, for use by `orgstruct-mode'.")
8858 ;;;###autoload
8859 (define-minor-mode orgstruct-mode
8860 "Toggle the minor mode `orgstruct-mode'.
8861 This mode is for using Org-mode structure commands in other
8862 modes. The following keys behave as if Org-mode were active, if
8863 the cursor is on a headline, or on a plain list item (both as
8864 defined by Org-mode)."
8865 nil " OrgStruct" (make-sparse-keymap)
8866 (funcall (if orgstruct-mode
8867 'add-to-invisibility-spec
8868 'remove-from-invisibility-spec)
8869 '(outline . t))
8870 (when orgstruct-mode
8871 (org-load-modules-maybe)
8872 (unless orgstruct-initialized
8873 (orgstruct-setup)
8874 (setq orgstruct-initialized t))))
8876 ;;;###autoload
8877 (defun turn-on-orgstruct ()
8878 "Unconditionally turn on `orgstruct-mode'."
8879 (orgstruct-mode 1))
8881 (defvar org-fb-vars nil)
8882 (make-variable-buffer-local 'org-fb-vars)
8883 (defun orgstruct++-mode (&optional arg)
8884 "Toggle `orgstruct-mode', the enhanced version of it.
8885 In addition to setting orgstruct-mode, this also exports all
8886 indentation and autofilling variables from org-mode into the
8887 buffer. It will also recognize item context in multiline items."
8888 (interactive "P")
8889 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8890 (if (< arg 1)
8891 (progn (orgstruct-mode -1)
8892 (mapc (lambda(v)
8893 (org-set-local (car v)
8894 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8895 org-fb-vars))
8896 (orgstruct-mode 1)
8897 (setq org-fb-vars nil)
8898 (unless org-local-vars
8899 (setq org-local-vars (org-get-local-variables)))
8900 (let (var val)
8901 (mapc
8902 (lambda (x)
8903 (when (string-match
8904 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8905 (symbol-name (car x)))
8906 (setq var (car x) val (nth 1 x))
8907 (push (list var `(quote ,(eval var))) org-fb-vars)
8908 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8909 org-local-vars)
8910 (org-set-local 'orgstruct-is-++ t))))
8912 (defvar orgstruct-is-++ nil
8913 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8914 (make-variable-buffer-local 'orgstruct-is-++)
8916 ;;;###autoload
8917 (defun turn-on-orgstruct++ ()
8918 "Unconditionally turn on `orgstruct++-mode'."
8919 (orgstruct++-mode 1))
8921 (defun orgstruct-error ()
8922 "Error when there is no default binding for a structure key."
8923 (interactive)
8924 (funcall (if (fboundp 'user-error)
8925 'user-error
8926 'error)
8927 "This key has no function outside structure elements"))
8929 (defun orgstruct-setup ()
8930 "Setup orgstruct keymap."
8931 (dolist (cell '((org-demote . t)
8932 (org-metaleft . t)
8933 (org-metaright . t)
8934 (org-promote . t)
8935 (org-shiftmetaleft . t)
8936 (org-shiftmetaright . t)
8937 org-backward-element
8938 org-backward-heading-same-level
8939 org-ctrl-c-ret
8940 org-ctrl-c-minus
8941 org-ctrl-c-star
8942 org-cycle
8943 org-forward-heading-same-level
8944 org-insert-heading
8945 org-insert-heading-respect-content
8946 org-kill-note-or-show-branches
8947 org-mark-subtree
8948 org-meta-return
8949 org-metadown
8950 org-metaup
8951 org-narrow-to-subtree
8952 org-promote-subtree
8953 org-reveal
8954 org-shiftdown
8955 org-shiftleft
8956 org-shiftmetadown
8957 org-shiftmetaup
8958 org-shiftright
8959 org-shifttab
8960 org-shifttab
8961 org-shiftup
8962 org-show-subtree
8963 org-sort
8964 org-up-element
8965 outline-demote
8966 outline-next-visible-heading
8967 outline-previous-visible-heading
8968 outline-promote
8969 outline-up-heading
8970 show-children))
8971 (let ((f (or (car-safe cell) cell))
8972 (disable-when-heading-prefix (cdr-safe cell)))
8973 (when (fboundp f)
8974 (let ((new-bindings))
8975 (dolist (binding (nconc (where-is-internal f org-mode-map)
8976 (where-is-internal f outline-mode-map)))
8977 (push binding new-bindings)
8978 ;; TODO use local-function-key-map
8979 (dolist (rep '(("<tab>" . "TAB")
8980 ("<return>" . "RET")
8981 ("<escape>" . "ESC")
8982 ("<delete>" . "DEL")))
8983 (setq binding (read-kbd-macro
8984 (let ((case-fold-search))
8985 (replace-regexp-in-string
8986 (regexp-quote (cdr rep))
8987 (car rep)
8988 (key-description binding)))))
8989 (pushnew binding new-bindings :test 'equal)))
8990 (dolist (binding new-bindings)
8991 (let ((key (lookup-key orgstruct-mode-map binding)))
8992 (when (or (not key) (numberp key))
8993 (condition-case nil
8994 (org-defkey orgstruct-mode-map
8995 binding
8996 (orgstruct-make-binding f binding disable-when-heading-prefix))
8997 (error nil)))))))))
8998 (run-hooks 'orgstruct-setup-hook))
9000 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9001 "Create a function for binding in the structure minor mode.
9002 FUN is the command to call inside a table. KEY is the key that
9003 should be checked in for a command to execute outside of tables.
9004 Non-nil DISABLE-WHEN-HEADING-PREFIX means to disable the command
9005 if `orgstruct-heading-prefix-regexp' is non-nil."
9006 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9007 (let ((nname name)
9008 (i 0))
9009 (while (fboundp (intern nname))
9010 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9011 (setq name (intern nname)))
9012 (eval
9013 (let ((bindings '((org-heading-regexp
9014 (concat "^"
9015 orgstruct-heading-prefix-regexp
9016 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9017 (org-outline-regexp
9018 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9019 (org-outline-regexp-bol
9020 (concat "^" org-outline-regexp))
9021 (outline-regexp org-outline-regexp)
9022 (outline-heading-end-regexp "\n")
9023 (outline-level 'org-outline-level)
9024 (outline-heading-alist))))
9025 `(defun ,name (arg)
9026 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9027 "Outside of structure, run the binding of `"
9028 (key-description key) "'."
9029 (when disable-when-heading-prefix
9030 (concat
9031 "\nIf `orgstruct-heading-prefix-regexp' is non-nil, this command will always fall\n"
9032 "back to the default binding due to limitations of Org's implementation of\n"
9033 "`" (symbol-name fun) "'.")))
9034 (interactive "p")
9035 (let* ((disable
9036 ,(when disable-when-heading-prefix
9037 '(and orgstruct-heading-prefix-regexp
9038 (not (string= orgstruct-heading-prefix-regexp "")))))
9039 (fallback
9040 (or disable
9041 (not
9042 (let* ,bindings
9043 (org-context-p 'headline 'item
9044 ,(when (memq fun
9045 '(org-insert-heading
9046 org-insert-heading-respect-content
9047 org-meta-return))
9048 '(when orgstruct-is-++
9049 'item-body))))))))
9050 (if fallback
9051 (let* ((orgstruct-mode)
9052 (binding
9053 (loop with key = ,key
9054 for rep in
9055 '(nil
9056 ("<\\([^>]*\\)tab>" . "\\1TAB")
9057 ("<\\([^>]*\\)return>" . "\\1RET")
9058 ("<\\([^>]*\\)escape>" . "\\1ESC")
9059 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9061 (when rep
9062 (setq key (read-kbd-macro
9063 (let ((case-fold-search))
9064 (replace-regexp-in-string
9065 (car rep)
9066 (cdr rep)
9067 (key-description key))))))
9068 thereis (key-binding key))))
9069 (if (keymapp binding)
9070 (set-temporary-overlay-map binding)
9071 (let ((func (or binding
9072 (unless disable
9073 'orgstruct-error))))
9074 (when func
9075 (call-interactively func)))))
9076 (org-run-like-in-org-mode
9077 (lambda ()
9078 (interactive)
9079 (let* ,bindings
9080 (call-interactively ',fun)))))))))
9081 name))
9083 (defun org-contextualize-keys (alist contexts)
9084 "Return valid elements in ALIST depending on CONTEXTS.
9086 `org-agenda-custom-commands' or `org-capture-templates' are the
9087 values used for ALIST, and `org-agenda-custom-commands-contexts'
9088 or `org-capture-templates-contexts' are the associated contexts
9089 definitions."
9090 (let ((contexts
9091 ;; normalize contexts
9092 (mapcar
9093 (lambda(c) (cond ((listp (cadr c))
9094 (list (car c) (car c) (cadr c)))
9095 ((string= "" (cadr c))
9096 (list (car c) (car c) (caddr c)))
9097 (t c))) contexts))
9098 (a alist) c r s)
9099 ;; loop over all commands or templates
9100 (while (setq c (pop a))
9101 (let (vrules repl)
9102 (cond
9103 ((not (assoc (car c) contexts))
9104 (push c r))
9105 ((and (assoc (car c) contexts)
9106 (setq vrules (org-contextualize-validate-key
9107 (car c) contexts)))
9108 (mapc (lambda (vr)
9109 (when (not (equal (car vr) (cadr vr)))
9110 (setq repl vr))) vrules)
9111 (if (not repl) (push c r)
9112 (push (cadr repl) s)
9113 (push
9114 (cons (car c)
9115 (cdr (or (assoc (cadr repl) alist)
9116 (error "Undefined key `%s' as contextual replacement for `%s'"
9117 (cadr repl) (car c)))))
9118 r))))))
9119 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9120 (delq
9122 (delete-dups
9123 (mapcar (lambda (x)
9124 (let ((tpl (car x)))
9125 (when (not (delq
9127 (mapcar (lambda(y)
9128 (equal y tpl)) s))) x)))
9129 (reverse r))))))
9131 (defun org-contextualize-validate-key (key contexts)
9132 "Check CONTEXTS for agenda or capture KEY."
9133 (let (r rr res)
9134 (while (setq r (pop contexts))
9135 (mapc
9136 (lambda (rr)
9137 (when
9138 (and (equal key (car r))
9139 (if (functionp rr) (funcall rr)
9140 (or (and (eq (car rr) 'in-file)
9141 (buffer-file-name)
9142 (string-match (cdr rr) (buffer-file-name)))
9143 (and (eq (car rr) 'in-mode)
9144 (string-match (cdr rr) (symbol-name major-mode)))
9145 (and (eq (car rr) 'in-buffer)
9146 (string-match (cdr rr) (buffer-name)))
9147 (when (and (eq (car rr) 'not-in-file)
9148 (buffer-file-name))
9149 (not (string-match (cdr rr) (buffer-file-name))))
9150 (when (eq (car rr) 'not-in-mode)
9151 (not (string-match (cdr rr) (symbol-name major-mode))))
9152 (when (eq (car rr) 'not-in-buffer)
9153 (not (string-match (cdr rr) (buffer-name)))))))
9154 (push r res)))
9155 (car (last r))))
9156 (delete-dups (delq nil res))))
9158 (defun org-context-p (&rest contexts)
9159 "Check if local context is any of CONTEXTS.
9160 Possible values in the list of contexts are `table', `headline', and `item'."
9161 (let ((pos (point)))
9162 (goto-char (point-at-bol))
9163 (prog1 (or (and (memq 'table contexts)
9164 (looking-at "[ \t]*|"))
9165 (and (memq 'headline contexts)
9166 (looking-at org-outline-regexp))
9167 (and (memq 'item contexts)
9168 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9169 (and (memq 'item-body contexts)
9170 (org-in-item-p)))
9171 (goto-char pos))))
9173 (defun org-get-local-variables ()
9174 "Return a list of all local variables in an Org mode buffer."
9175 (let (varlist)
9176 (with-current-buffer (get-buffer-create "*Org tmp*")
9177 (erase-buffer)
9178 (org-mode)
9179 (setq varlist (buffer-local-variables)))
9180 (kill-buffer "*Org tmp*")
9181 (delq nil
9182 (mapcar
9183 (lambda (x)
9184 (setq x
9185 (if (symbolp x)
9186 (list x)
9187 (list (car x) (cdr x))))
9188 (if (and (not (get (car x) 'org-state))
9189 (string-match
9190 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9191 (symbol-name (car x))))
9192 x nil))
9193 varlist))))
9195 (defun org-clone-local-variables (from-buffer &optional regexp)
9196 "Clone local variables from FROM-BUFFER.
9197 Optional argument REGEXP selects variables to clone."
9198 (mapc
9199 (lambda (pair)
9200 (and (symbolp (car pair))
9201 (or (null regexp)
9202 (string-match regexp (symbol-name (car pair))))
9203 (set (make-local-variable (car pair))
9204 (cdr pair))))
9205 (buffer-local-variables from-buffer)))
9207 ;;;###autoload
9208 (defun org-run-like-in-org-mode (cmd)
9209 "Run a command, pretending that the current buffer is in Org-mode.
9210 This will temporarily bind local variables that are typically bound in
9211 Org-mode to the values they have in Org-mode, and then interactively
9212 call CMD."
9213 (org-load-modules-maybe)
9214 (unless org-local-vars
9215 (setq org-local-vars (org-get-local-variables)))
9216 (let (binds)
9217 (dolist (var org-local-vars)
9218 (when (or (not (boundp (car var)))
9219 (eq (symbol-value (car var))
9220 (default-value (car var))))
9221 (push (list (car var) `(quote ,(cadr var))) binds)))
9222 (eval `(let ,binds
9223 (call-interactively (quote ,cmd))))))
9225 ;;;; Archiving
9227 (defun org-get-category (&optional pos force-refresh)
9228 "Get the category applying to position POS."
9229 (save-match-data
9230 (if force-refresh (org-refresh-category-properties))
9231 (let ((pos (or pos (point))))
9232 (or (get-text-property pos 'org-category)
9233 (progn (org-refresh-category-properties)
9234 (get-text-property pos 'org-category))))))
9236 (defun org-refresh-category-properties ()
9237 "Refresh category text properties in the buffer."
9238 (let ((case-fold-search t)
9239 (inhibit-read-only t)
9240 (def-cat (cond
9241 ((null org-category)
9242 (if buffer-file-name
9243 (file-name-sans-extension
9244 (file-name-nondirectory buffer-file-name))
9245 "???"))
9246 ((symbolp org-category) (symbol-name org-category))
9247 (t org-category)))
9248 beg end cat pos optionp)
9249 (org-with-silent-modifications
9250 (save-excursion
9251 (save-restriction
9252 (widen)
9253 (goto-char (point-min))
9254 (put-text-property (point) (point-max) 'org-category def-cat)
9255 (while (re-search-forward
9256 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9257 (setq pos (match-end 0)
9258 optionp (equal (char-after (match-beginning 0)) ?#)
9259 cat (org-trim (match-string 2)))
9260 (if optionp
9261 (setq beg (point-at-bol) end (point-max))
9262 (org-back-to-heading t)
9263 (setq beg (point) end (org-end-of-subtree t t)))
9264 (put-text-property beg end 'org-category cat)
9265 (put-text-property beg end 'org-category-position beg)
9266 (goto-char pos)))))))
9268 (defun org-refresh-properties (dprop tprop)
9269 "Refresh buffer text properties.
9270 DPROP is the drawer property and TPROP is the corresponding text
9271 property to set."
9272 (let ((case-fold-search t)
9273 (inhibit-read-only t) p)
9274 (org-with-silent-modifications
9275 (save-excursion
9276 (save-restriction
9277 (widen)
9278 (goto-char (point-min))
9279 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9280 (setq p (org-match-string-no-properties 1))
9281 (save-excursion
9282 (org-back-to-heading t)
9283 (put-text-property
9284 (point-at-bol) (org-end-of-subtree t t) tprop p))))))))
9287 ;;;; Link Stuff
9289 ;;; Link abbreviations
9291 (defun org-link-expand-abbrev (link)
9292 "Apply replacements as defined in `org-link-abbrev-alist'."
9293 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9294 (let* ((key (match-string 1 link))
9295 (as (or (assoc key org-link-abbrev-alist-local)
9296 (assoc key org-link-abbrev-alist)))
9297 (tag (and (match-end 2) (match-string 3 link)))
9298 rpl)
9299 (if (not as)
9300 link
9301 (setq rpl (cdr as))
9302 (cond
9303 ((symbolp rpl) (funcall rpl tag))
9304 ((string-match "%(\\([^)]+\\))" rpl)
9305 (replace-match
9306 (save-match-data
9307 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9308 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9309 ((string-match "%h" rpl)
9310 (replace-match (url-hexify-string (or tag "")) t t rpl))
9311 (t (concat rpl tag)))))
9312 link))
9314 ;;; Storing and inserting links
9316 (defvar org-insert-link-history nil
9317 "Minibuffer history for links inserted with `org-insert-link'.")
9319 (defvar org-stored-links nil
9320 "Contains the links stored with `org-store-link'.")
9322 (defvar org-store-link-plist nil
9323 "Plist with info about the most recently link created with `org-store-link'.")
9325 (defvar org-link-protocols nil
9326 "Link protocols added to Org-mode using `org-add-link-type'.")
9328 (defvar org-store-link-functions nil
9329 "List of functions that are called to create and store a link.
9330 Each function will be called in turn until one returns a non-nil
9331 value. Each function should check if it is responsible for creating
9332 this link (for example by looking at the major mode).
9333 If not, it must exit and return nil.
9334 If yes, it should return a non-nil value after a calling
9335 `org-store-link-props' with a list of properties and values.
9336 Special properties are:
9338 :type The link prefix, like \"http\". This must be given.
9339 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9340 This is obligatory as well.
9341 :description Optional default description for the second pair
9342 of brackets in an Org-mode link. The user can still change
9343 this when inserting this link into an Org-mode buffer.
9345 In addition to these, any additional properties can be specified
9346 and then used in capture templates.")
9348 (defun org-add-link-type (type &optional follow export)
9349 "Add TYPE to the list of `org-link-types'.
9350 Re-compute all regular expressions depending on `org-link-types'
9352 FOLLOW and EXPORT are two functions.
9354 FOLLOW should take the link path as the single argument and do whatever
9355 is necessary to follow the link, for example find a file or display
9356 a mail message.
9358 EXPORT should format the link path for export to one of the export formats.
9359 It should be a function accepting three arguments:
9361 path the path of the link, the text after the prefix (like \"http:\")
9362 desc the description of the link, if any, or a description added by
9363 org-export-normalize-links if there is none
9364 format the export format, a symbol like `html' or `latex' or `ascii'..
9366 The function may use the FORMAT information to return different values
9367 depending on the format. The return value will be put literally into
9368 the exported file. If the return value is nil, this means Org should
9369 do what it normally does with links which do not have EXPORT defined.
9371 Org-mode has a built-in default for exporting links. If you are happy with
9372 this default, there is no need to define an export function for the link
9373 type. For a simple example of an export function, see `org-bbdb.el'."
9374 (add-to-list 'org-link-types type t)
9375 (org-make-link-regexps)
9376 (if (assoc type org-link-protocols)
9377 (setcdr (assoc type org-link-protocols) (list follow export))
9378 (push (list type follow export) org-link-protocols)))
9380 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9381 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9383 ;;;###autoload
9384 (defun org-store-link (arg)
9385 "\\<org-mode-map>Store an org-link to the current location.
9386 This link is added to `org-stored-links' and can later be inserted
9387 into an org-buffer with \\[org-insert-link].
9389 For some link types, a prefix arg is interpreted.
9390 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9391 For file links, arg negates `org-context-in-file-links'.
9393 A double prefix arg force skipping storing functions that are not
9394 part of Org's core.
9396 A triple prefix arg force storing a link for each line in the
9397 active region."
9398 (interactive "P")
9399 (org-load-modules-maybe)
9400 (if (and (equal arg '(64)) (org-region-active-p))
9401 (save-excursion
9402 (let ((end (region-end)))
9403 (goto-char (region-beginning))
9404 (set-mark (point))
9405 (while (< (point-at-eol) end)
9406 (move-end-of-line 1) (activate-mark)
9407 (let (current-prefix-arg)
9408 (call-interactively 'org-store-link))
9409 (move-beginning-of-line 2)
9410 (set-mark (point)))))
9411 (org-with-limited-levels
9412 (setq org-store-link-plist nil)
9413 (let (link cpltxt desc description search
9414 txt custom-id agenda-link sfuns sfunsn)
9415 (cond
9417 ;; Store a link using an external link type
9418 ((and (not (equal arg '(16)))
9419 (setq sfuns
9420 (delq
9421 nil (mapcar (lambda (f)
9422 (let (fs) (if (funcall f) (push f fs))))
9423 org-store-link-functions))
9424 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9425 (or (and (cdr sfuns)
9426 (funcall (intern
9427 (completing-read
9428 "Which function for creating the link? "
9429 sfunsn t (car sfunsn)))))
9430 (funcall (caar sfuns)))
9431 (setq link (plist-get org-store-link-plist :link)
9432 desc (or (plist-get org-store-link-plist
9433 :description) link))))
9435 ;; Store a link from a source code buffer
9436 ((org-src-edit-buffer-p)
9437 (let (label gc)
9438 (while (or (not label)
9439 (save-excursion
9440 (save-restriction
9441 (widen)
9442 (goto-char (point-min))
9443 (re-search-forward
9444 (regexp-quote (format org-coderef-label-format label))
9445 nil t))))
9446 (when label (message "Label exists already") (sit-for 2))
9447 (setq label (read-string "Code line label: " label)))
9448 (end-of-line 1)
9449 (setq link (format org-coderef-label-format label))
9450 (setq gc (- 79 (length link)))
9451 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9452 (insert link)
9453 (setq link (concat "(" label ")") desc nil)))
9455 ;; We are in the agenda, link to referenced location
9456 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9457 (let ((m (or (get-text-property (point) 'org-hd-marker)
9458 (get-text-property (point) 'org-marker))))
9459 (when m
9460 (org-with-point-at m
9461 (setq agenda-link
9462 (if (org-called-interactively-p 'any)
9463 (call-interactively 'org-store-link)
9464 (org-store-link nil)))))))
9466 ((eq major-mode 'calendar-mode)
9467 (let ((cd (calendar-cursor-to-date)))
9468 (setq link
9469 (format-time-string
9470 (car org-time-stamp-formats)
9471 (apply 'encode-time
9472 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9473 nil nil nil))))
9474 (org-store-link-props :type "calendar" :date cd)))
9476 ((eq major-mode 'help-mode)
9477 (setq link (concat "help:" (save-excursion
9478 (goto-char (point-min))
9479 (looking-at "^[^ ]+")
9480 (match-string 0))))
9481 (org-store-link-props :type "help"))
9483 ((eq major-mode 'w3-mode)
9484 (setq cpltxt (if (and (buffer-name)
9485 (not (string-match "Untitled" (buffer-name))))
9486 (buffer-name)
9487 (url-view-url t))
9488 link (url-view-url t))
9489 (org-store-link-props :type "w3" :url (url-view-url t)))
9491 ((eq major-mode 'image-mode)
9492 (setq cpltxt (concat "file:"
9493 (abbreviate-file-name buffer-file-name))
9494 link cpltxt)
9495 (org-store-link-props :type "image" :file buffer-file-name))
9497 ;; In dired, store a link to the file of the current line
9498 ((eq major-mode 'dired-mode)
9499 (let ((file (dired-get-filename nil t)))
9500 (setq file (if file
9501 (abbreviate-file-name
9502 (expand-file-name (dired-get-filename nil t)))
9503 ;; otherwise, no file so use current directory.
9504 default-directory))
9505 (setq cpltxt (concat "file:" file)
9506 link cpltxt)))
9508 ((setq search (run-hook-with-args-until-success
9509 'org-create-file-search-functions))
9510 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9511 "::" search))
9512 (setq cpltxt (or description link)))
9514 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9515 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9516 (cond
9517 ;; Store a link using the target at point
9518 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9519 (setq cpltxt
9520 (concat "file:"
9521 (abbreviate-file-name
9522 (buffer-file-name (buffer-base-buffer)))
9523 "::" (match-string 1))
9524 link cpltxt))
9525 ((and (featurep 'org-id)
9526 (or (eq org-id-link-to-org-use-id t)
9527 (and (org-called-interactively-p 'any)
9528 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9529 (and (eq org-id-link-to-org-use-id
9530 'create-if-interactive-and-no-custom-id)
9531 (not custom-id))))
9532 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9533 ;; Store a link using the ID at point
9534 (setq link (condition-case nil
9535 (prog1 (org-id-store-link)
9536 (setq desc (plist-get org-store-link-plist
9537 :description)))
9538 (error
9539 ;; Probably before first headline, link only to file
9540 (concat "file:"
9541 (abbreviate-file-name
9542 (buffer-file-name (buffer-base-buffer))))))))
9544 ;; Just link to current headline
9545 (setq cpltxt (concat "file:"
9546 (abbreviate-file-name
9547 (buffer-file-name (buffer-base-buffer)))))
9548 ;; Add a context search string
9549 (when (org-xor org-context-in-file-links arg)
9550 (let* ((ee (org-element-at-point))
9551 (et (org-element-type ee))
9552 (ev (plist-get (cadr ee) :value))
9553 (ek (plist-get (cadr ee) :key))
9554 (eok (and (stringp ek) (string-match "name" ek))))
9555 (setq txt (cond
9556 ((org-at-heading-p) nil)
9557 ((and (eq et 'keyword) eok) ev)
9558 ((org-region-active-p)
9559 (buffer-substring (region-beginning) (region-end)))))
9560 (when (or (null txt) (string-match "\\S-" txt))
9561 (setq cpltxt
9562 (concat cpltxt "::"
9563 (condition-case nil
9564 (org-make-org-heading-search-string txt)
9565 (error "")))
9566 desc (or (and (eq et 'keyword) eok ev)
9567 (nth 4 (ignore-errors (org-heading-components)))
9568 "NONE")))))
9569 (if (string-match "::\\'" cpltxt)
9570 (setq cpltxt (substring cpltxt 0 -2)))
9571 (setq link cpltxt))))
9573 ((buffer-file-name (buffer-base-buffer))
9574 ;; Just link to this file here.
9575 (setq cpltxt (concat "file:"
9576 (abbreviate-file-name
9577 (buffer-file-name (buffer-base-buffer)))))
9578 ;; Add a context string.
9579 (when (org-xor org-context-in-file-links arg)
9580 (setq txt (if (org-region-active-p)
9581 (buffer-substring (region-beginning) (region-end))
9582 (buffer-substring (point-at-bol) (point-at-eol))))
9583 ;; Only use search option if there is some text.
9584 (when (string-match "\\S-" txt)
9585 (setq cpltxt
9586 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9587 desc "NONE")))
9588 (setq link cpltxt))
9590 ((org-called-interactively-p 'interactive)
9591 (user-error "No method for storing a link from this buffer"))
9593 (t (setq link nil)))
9595 ;; We're done setting link and desc, clean up
9596 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9597 (setq link (or link cpltxt)
9598 desc (or desc cpltxt))
9599 (cond ((equal desc "NONE") (setq desc nil))
9600 ((string-match org-bracket-link-analytic-regexp desc)
9601 (let ((d0 (match-string 3 desc))
9602 (p0 (match-string 5 desc)))
9603 (setq desc
9604 (replace-regexp-in-string
9605 org-bracket-link-regexp
9606 (concat (or p0 d0)
9607 (if (equal (length (match-string 0 desc))
9608 (length desc)) "*" "")) desc)))))
9610 ;; Return the link
9611 (if (not (and (or (org-called-interactively-p 'any)
9612 executing-kbd-macro) link))
9613 (or agenda-link (and link (org-make-link-string link desc)))
9614 (push (list link desc) org-stored-links)
9615 (message "Stored: %s" (or desc link))
9616 (when custom-id
9617 (setq link (concat "file:" (abbreviate-file-name
9618 (buffer-file-name)) "::#" custom-id))
9619 (push (list link desc) org-stored-links)))))))
9621 (defun org-store-link-props (&rest plist)
9622 "Store link properties, extract names and addresses."
9623 (let (x adr)
9624 (when (setq x (plist-get plist :from))
9625 (setq adr (mail-extract-address-components x))
9626 (setq plist (plist-put plist :fromname (car adr)))
9627 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9628 (when (setq x (plist-get plist :to))
9629 (setq adr (mail-extract-address-components x))
9630 (setq plist (plist-put plist :toname (car adr)))
9631 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9632 (let ((from (plist-get plist :from))
9633 (to (plist-get plist :to)))
9634 (when (and from to org-from-is-user-regexp)
9635 (setq plist
9636 (plist-put plist :fromto
9637 (if (string-match org-from-is-user-regexp from)
9638 (concat "to %t")
9639 (concat "from %f"))))))
9640 (setq org-store-link-plist plist))
9642 (defun org-add-link-props (&rest plist)
9643 "Add these properties to the link property list."
9644 (let (key value)
9645 (while plist
9646 (setq key (pop plist) value (pop plist))
9647 (setq org-store-link-plist
9648 (plist-put org-store-link-plist key value)))))
9650 (defun org-email-link-description (&optional fmt)
9651 "Return the description part of an email link.
9652 This takes information from `org-store-link-plist' and formats it
9653 according to FMT (default from `org-email-link-description-format')."
9654 (setq fmt (or fmt org-email-link-description-format))
9655 (let* ((p org-store-link-plist)
9656 (to (plist-get p :toaddress))
9657 (from (plist-get p :fromaddress))
9658 (table
9659 (list
9660 (cons "%c" (plist-get p :fromto))
9661 (cons "%F" (plist-get p :from))
9662 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9663 (cons "%T" (plist-get p :to))
9664 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9665 (cons "%s" (plist-get p :subject))
9666 (cons "%d" (plist-get p :date))
9667 (cons "%m" (plist-get p :message-id)))))
9668 (when (string-match "%c" fmt)
9669 ;; Check if the user wrote this message
9670 (if (and org-from-is-user-regexp from to
9671 (save-match-data (string-match org-from-is-user-regexp from)))
9672 (setq fmt (replace-match "to %t" t t fmt))
9673 (setq fmt (replace-match "from %f" t t fmt))))
9674 (org-replace-escapes fmt table)))
9676 (defun org-make-org-heading-search-string (&optional string)
9677 "Make search string for the current headline or STRING."
9678 (let ((s (or string
9679 (and (derived-mode-p 'org-mode)
9680 (save-excursion
9681 (org-back-to-heading t)
9682 (org-element-property :raw-value (org-element-at-point))))))
9683 (lines org-context-in-file-links))
9684 (or string (setq s (concat "*" s))) ; Add * for headlines
9685 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9686 (when (and string (integerp lines) (> lines 0))
9687 (let ((slines (org-split-string s "\n")))
9688 (when (< lines (length slines))
9689 (setq s (mapconcat
9690 'identity
9691 (reverse (nthcdr (- (length slines) lines)
9692 (reverse slines))) "\n")))))
9693 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9695 (defun org-make-link-string (link &optional description)
9696 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9697 (unless (string-match "\\S-" link)
9698 (error "Empty link"))
9699 (when (and description
9700 (stringp description)
9701 (not (string-match "\\S-" description)))
9702 (setq description nil))
9703 (when (stringp description)
9704 ;; Remove brackets from the description, they are fatal.
9705 (while (string-match "\\[" description)
9706 (setq description (replace-match "{" t t description)))
9707 (while (string-match "\\]" description)
9708 (setq description (replace-match "}" t t description))))
9709 (when (equal link description)
9710 ;; No description needed, it is identical
9711 (setq description nil))
9712 (when (and (not description)
9713 (not (string-match (org-image-file-name-regexp) link))
9714 (not (equal link (org-link-escape link))))
9715 (setq description (org-extract-attributes link)))
9716 (setq link
9717 (cond ((string-match (org-image-file-name-regexp) link) link)
9718 ((string-match org-link-types-re link)
9719 (concat (match-string 1 link)
9720 (org-link-escape (substring link (match-end 1)))))
9721 (t (org-link-escape link))))
9722 (concat "[[" link "]"
9723 (if description (concat "[" description "]") "")
9724 "]"))
9726 (defconst org-link-escape-chars
9727 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9728 "List of characters that should be escaped in link.
9729 This is the list that is used for internal purposes.")
9731 (defconst org-link-escape-chars-browser
9732 '(?\ ?\")
9733 "List of escapes for characters that are problematic in links.
9734 This is the list that is used before handing over to the browser.")
9736 (defun org-link-escape (text &optional table merge)
9737 "Return percent escaped representation of TEXT.
9738 TEXT is a string with the text to escape.
9739 Optional argument TABLE is a list with characters that should be
9740 escaped. When nil, `org-link-escape-chars' is used.
9741 If optional argument MERGE is set, merge TABLE into
9742 `org-link-escape-chars'."
9743 (cond
9744 ((and table merge)
9745 (mapc (lambda (defchr)
9746 (unless (member defchr table)
9747 (setq table (cons defchr table)))) org-link-escape-chars))
9748 ((null table)
9749 (setq table org-link-escape-chars)))
9750 (mapconcat
9751 (lambda (char)
9752 (if (or (member char table)
9753 (and (or (< char 32) (= char 37) (> char 126))
9754 org-url-hexify-p))
9755 (mapconcat (lambda (sequence-element)
9756 (format "%%%.2X" sequence-element))
9757 (or (encode-coding-char char 'utf-8)
9758 (error "Unable to percent escape character: %s"
9759 (char-to-string char))) "")
9760 (char-to-string char))) text ""))
9762 (defun org-link-unescape (str)
9763 "Unhex hexified Unicode strings as returned from the JavaScript function
9764 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9765 (unless (and (null str) (string= "" str))
9766 (let ((pos 0) (case-fold-search t) unhexed)
9767 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9768 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9769 (setq str (replace-match unhexed t t str))
9770 (setq pos (+ pos (length unhexed))))))
9771 str)
9773 (defun org-link-unescape-compound (hex)
9774 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9775 Note: this function also decodes single byte encodings like
9776 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9777 (save-match-data
9778 (let* ((bytes (cdr (split-string hex "%")))
9779 (ret "")
9780 (eat 0)
9781 (sum 0))
9782 (while bytes
9783 (let* ((val (string-to-number (pop bytes) 16))
9784 (shift-xor
9785 (if (= 0 eat)
9786 (cond
9787 ((>= val 252) (cons 6 252))
9788 ((>= val 248) (cons 5 248))
9789 ((>= val 240) (cons 4 240))
9790 ((>= val 224) (cons 3 224))
9791 ((>= val 192) (cons 2 192))
9792 (t (cons 0 0)))
9793 (cons 6 128))))
9794 (if (>= val 192) (setq eat (car shift-xor)))
9795 (setq val (logxor val (cdr shift-xor)))
9796 (setq sum (+ (lsh sum (car shift-xor)) val))
9797 (if (> eat 0) (setq eat (- eat 1)))
9798 (cond
9799 ((= 0 eat) ;multi byte
9800 (setq ret (concat ret (org-char-to-string sum)))
9801 (setq sum 0))
9802 ((not bytes) ; single byte(s)
9803 (setq ret (org-link-unescape-single-byte-sequence hex))))
9804 )) ;; end (while bytes
9805 ret )))
9807 (defun org-link-unescape-single-byte-sequence (hex)
9808 "Unhexify hex-encoded single byte character sequences."
9809 (mapconcat (lambda (byte)
9810 (char-to-string (string-to-number byte 16)))
9811 (cdr (split-string hex "%")) ""))
9813 (defun org-xor (a b)
9814 "Exclusive or."
9815 (if a (not b) b))
9817 (defun org-fixup-message-id-for-http (s)
9818 "Replace special characters in a message id, so it can be used in an http query."
9819 (when (string-match "%" s)
9820 (setq s (mapconcat (lambda (c)
9821 (if (eq c ?%)
9822 "%25"
9823 (char-to-string c)))
9824 s "")))
9825 (while (string-match "<" s)
9826 (setq s (replace-match "%3C" t t s)))
9827 (while (string-match ">" s)
9828 (setq s (replace-match "%3E" t t s)))
9829 (while (string-match "@" s)
9830 (setq s (replace-match "%40" t t s)))
9833 (defun org-link-prettify (link)
9834 "Return a human-readable representation of LINK.
9835 The car of LINK must be a raw link the cdr of LINK must be either
9836 a link description or nil."
9837 (let ((desc (or (cadr link) "<no description>")))
9838 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9839 "<" (car link) ">")))
9841 ;;;###autoload
9842 (defun org-insert-link-global ()
9843 "Insert a link like Org-mode does.
9844 This command can be called in any mode to insert a link in Org-mode syntax."
9845 (interactive)
9846 (org-load-modules-maybe)
9847 (org-run-like-in-org-mode 'org-insert-link))
9849 (defun org-insert-all-links (&optional keep)
9850 "Insert all links in `org-stored-links'."
9851 (interactive "P")
9852 (let ((links (copy-sequence org-stored-links)) l)
9853 (while (setq l (if keep (pop links) (pop org-stored-links)))
9854 (insert "- ")
9855 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9856 (insert "\n"))))
9858 (defun org-link-fontify-links-to-this-file ()
9859 "Fontify links to the current file in `org-stored-links'."
9860 (let ((f (buffer-file-name)) a b)
9861 (setq a (mapcar (lambda(l)
9862 (let ((ll (car l)))
9863 (when (and (string-match "^file:\\(.+\\)::" ll)
9864 (equal f (expand-file-name (match-string 1 ll))))
9865 ll)))
9866 org-stored-links))
9867 (when (featurep 'org-id)
9868 (setq b (mapcar (lambda(l)
9869 (let ((ll (car l)))
9870 (when (and (string-match "^id:\\(.+\\)$" ll)
9871 (equal f (expand-file-name
9872 (or (org-id-find-id-file
9873 (match-string 1 ll)) ""))))
9874 ll)))
9875 org-stored-links)))
9876 (mapcar (lambda(l)
9877 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9878 (delq nil (append a b)))))
9880 (defvar org-link-links-in-this-file nil)
9881 (defun org-insert-link (&optional complete-file link-location default-description)
9882 "Insert a link. At the prompt, enter the link.
9884 Completion can be used to insert any of the link protocol prefixes like
9885 http or ftp in use.
9887 The history can be used to select a link previously stored with
9888 `org-store-link'. When the empty string is entered (i.e. if you just
9889 press RET at the prompt), the link defaults to the most recently
9890 stored link. As SPC triggers completion in the minibuffer, you need to
9891 use M-SPC or C-q SPC to force the insertion of a space character.
9893 You will also be prompted for a description, and if one is given, it will
9894 be displayed in the buffer instead of the link.
9896 If there is already a link at point, this command will allow you to edit link
9897 and description parts.
9899 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9900 be selected using completion. The path to the file will be relative to the
9901 current directory if the file is in the current directory or a subdirectory.
9902 Otherwise, the link will be the absolute path as completed in the minibuffer
9903 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9904 option `org-link-file-path-type'.
9906 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9907 the current directory or below.
9909 With three \\[universal-argument] prefixes, negate the meaning of
9910 `org-keep-stored-link-after-insertion'.
9912 If `org-make-link-description-function' is non-nil, this function will be
9913 called with the link target, and the result will be the default
9914 link description.
9916 If the LINK-LOCATION parameter is non-nil, this value will be
9917 used as the link location instead of reading one interactively.
9919 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9920 be used as the default description."
9921 (interactive "P")
9922 (let* ((wcf (current-window-configuration))
9923 (origbuf (current-buffer))
9924 (region (if (org-region-active-p)
9925 (buffer-substring (region-beginning) (region-end))))
9926 (remove (and region (list (region-beginning) (region-end))))
9927 (desc region)
9928 tmphist ; byte-compile incorrectly complains about this
9929 (link link-location)
9930 (abbrevs org-link-abbrev-alist-local)
9931 entry file all-prefixes auto-desc)
9932 (cond
9933 (link-location) ; specified by arg, just use it.
9934 ((org-in-regexp org-bracket-link-regexp 1)
9935 ;; We do have a link at point, and we are going to edit it.
9936 (setq remove (list (match-beginning 0) (match-end 0)))
9937 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9938 (setq link (read-string "Link: "
9939 (org-link-unescape
9940 (org-match-string-no-properties 1)))))
9941 ((or (org-in-regexp org-angle-link-re)
9942 (org-in-regexp org-plain-link-re))
9943 ;; Convert to bracket link
9944 (setq remove (list (match-beginning 0) (match-end 0))
9945 link (read-string "Link: "
9946 (org-remove-angle-brackets (match-string 0)))))
9947 ((member complete-file '((4) (16)))
9948 ;; Completing read for file names.
9949 (setq link (org-file-complete-link complete-file)))
9951 ;; Read link, with completion for stored links.
9952 (org-link-fontify-links-to-this-file)
9953 (org-switch-to-buffer-other-window "*Org Links*")
9954 (with-current-buffer "*Org Links*"
9955 (erase-buffer)
9956 (insert "Insert a link.
9957 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9958 (when org-stored-links
9959 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9960 (insert (mapconcat 'org-link-prettify
9961 (reverse org-stored-links) "\n")))
9962 (goto-char (point-min)))
9963 (let ((cw (selected-window)))
9964 (select-window (get-buffer-window "*Org Links*" 'visible))
9965 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9966 (unless (pos-visible-in-window-p (point-max))
9967 (org-fit-window-to-buffer))
9968 (and (window-live-p cw) (select-window cw)))
9969 ;; Fake a link history, containing the stored links.
9970 (setq tmphist (append (mapcar 'car org-stored-links)
9971 org-insert-link-history))
9972 (setq all-prefixes (append (mapcar 'car abbrevs)
9973 (mapcar 'car org-link-abbrev-alist)
9974 org-link-types))
9975 (unwind-protect
9976 (progn
9977 (setq link
9978 (org-completing-read
9979 "Link: "
9980 (append
9981 (mapcar (lambda (x) (concat x ":"))
9982 all-prefixes)
9983 (mapcar 'car org-stored-links))
9984 nil nil nil
9985 'tmphist
9986 (caar org-stored-links)))
9987 (if (not (string-match "\\S-" link))
9988 (user-error "No link selected"))
9989 (mapc (lambda(l)
9990 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9991 org-stored-links)
9992 (if (or (member link all-prefixes)
9993 (and (equal ":" (substring link -1))
9994 (member (substring link 0 -1) all-prefixes)
9995 (setq link (substring link 0 -1))))
9996 (setq link (with-current-buffer origbuf
9997 (org-link-try-special-completion link)))))
9998 (set-window-configuration wcf)
9999 (kill-buffer "*Org Links*"))
10000 (setq entry (assoc link org-stored-links))
10001 (or entry (push link org-insert-link-history))
10002 (setq desc (or desc (nth 1 entry)))))
10004 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10005 (not org-keep-stored-link-after-insertion))
10006 (setq org-stored-links (delq (assoc link org-stored-links)
10007 org-stored-links)))
10009 (if (string-match org-plain-link-re link)
10010 ;; URL-like link, normalize the use of angular brackets.
10011 (setq link (org-remove-angle-brackets link)))
10013 ;; Check if we are linking to the current file with a search
10014 ;; option If yes, simplify the link by using only the search
10015 ;; option.
10016 (when (and buffer-file-name
10017 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10018 (let* ((path (match-string 1 link))
10019 (case-fold-search nil)
10020 (search (match-string 2 link)))
10021 (save-match-data
10022 (if (equal (file-truename buffer-file-name) (file-truename path))
10023 ;; We are linking to this same file, with a search option
10024 (setq link search)))))
10026 ;; Check if we can/should use a relative path. If yes, simplify the link
10027 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10028 (let* ((type (match-string 1 link))
10029 (path (match-string 2 link))
10030 (origpath path)
10031 (case-fold-search nil))
10032 (cond
10033 ((or (eq org-link-file-path-type 'absolute)
10034 (equal complete-file '(16)))
10035 (setq path (abbreviate-file-name (expand-file-name path))))
10036 ((eq org-link-file-path-type 'noabbrev)
10037 (setq path (expand-file-name path)))
10038 ((eq org-link-file-path-type 'relative)
10039 (setq path (file-relative-name path)))
10041 (save-match-data
10042 (if (string-match (concat "^" (regexp-quote
10043 (expand-file-name
10044 (file-name-as-directory
10045 default-directory))))
10046 (expand-file-name path))
10047 ;; We are linking a file with relative path name.
10048 (setq path (substring (expand-file-name path)
10049 (match-end 0)))
10050 (setq path (abbreviate-file-name (expand-file-name path)))))))
10051 (setq link (concat type path))
10052 (if (equal desc origpath)
10053 (setq desc path))))
10055 (if org-make-link-description-function
10056 (setq desc
10057 (or (condition-case nil
10058 (funcall org-make-link-description-function link desc)
10059 (error (progn (message "Can't get link description from `%s'"
10060 (symbol-name org-make-link-description-function))
10061 (sit-for 2) nil)))
10062 (read-string "Description: " default-description)))
10063 (if default-description (setq desc default-description)
10064 (setq desc (or (and auto-desc desc)
10065 (read-string "Description: " desc)))))
10067 (unless (string-match "\\S-" desc) (setq desc nil))
10068 (if remove (apply 'delete-region remove))
10069 (insert (org-make-link-string link desc))))
10071 (defun org-link-try-special-completion (type)
10072 "If there is completion support for link type TYPE, offer it."
10073 (let ((fun (intern (concat "org-" type "-complete-link"))))
10074 (if (functionp fun)
10075 (funcall fun)
10076 (read-string "Link (no completion support): " (concat type ":")))))
10078 (defun org-file-complete-link (&optional arg)
10079 "Create a file link using completion."
10080 (let (file link)
10081 (setq file (org-iread-file-name "File: "))
10082 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10083 (pwd1 (file-name-as-directory (abbreviate-file-name
10084 (expand-file-name ".")))))
10085 (cond
10086 ((equal arg '(16))
10087 (setq link (concat
10088 "file:"
10089 (abbreviate-file-name (expand-file-name file)))))
10090 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10091 (setq link (concat "file:" (match-string 1 file))))
10092 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10093 (expand-file-name file))
10094 (setq link (concat
10095 "file:" (match-string 1 (expand-file-name file)))))
10096 (t (setq link (concat "file:" file)))))
10097 link))
10099 (defun org-iread-file-name (&rest args)
10100 "Read-file-name using `ido-mode' speedup if available.
10101 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10102 See `read-file-name' for a description of parameters."
10103 (org-without-partial-completion
10104 (if (and org-completion-use-ido
10105 (fboundp 'ido-read-file-name)
10106 (boundp 'ido-mode) ido-mode
10107 (listp (second args)))
10108 (let ((ido-enter-matching-directory nil))
10109 (apply 'ido-read-file-name args))
10110 (apply 'read-file-name args))))
10112 (defun org-completing-read (&rest args)
10113 "Completing-read with SPACE being a normal character."
10114 (let ((enable-recursive-minibuffers t)
10115 (minibuffer-local-completion-map
10116 (copy-keymap minibuffer-local-completion-map)))
10117 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10118 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10119 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10120 (apply 'org-icompleting-read args)))
10122 (defun org-completing-read-no-i (&rest args)
10123 (let (org-completion-use-ido org-completion-use-iswitchb)
10124 (apply 'org-completing-read args)))
10126 (defun org-iswitchb-completing-read (prompt choices &rest args)
10127 "Use iswitch as a completing-read replacement to choose from choices.
10128 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10129 from."
10130 (let* ((iswitchb-use-virtual-buffers nil)
10131 (iswitchb-make-buflist-hook
10132 (lambda ()
10133 (setq iswitchb-temp-buflist choices))))
10134 (iswitchb-read-buffer prompt)))
10136 (defun org-icompleting-read (&rest args)
10137 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10138 (org-without-partial-completion
10139 (if (and org-completion-use-ido
10140 (fboundp 'ido-completing-read)
10141 (boundp 'ido-mode) ido-mode
10142 (listp (second args)))
10143 (let ((ido-enter-matching-directory nil))
10144 (apply 'ido-completing-read (concat (car args))
10145 (if (consp (car (nth 1 args)))
10146 (mapcar 'car (nth 1 args))
10147 (nth 1 args))
10148 (cddr args)))
10149 (if (and org-completion-use-iswitchb
10150 (boundp 'iswitchb-mode) iswitchb-mode
10151 (listp (second args)))
10152 (apply 'org-iswitchb-completing-read (concat (car args))
10153 (if (consp (car (nth 1 args)))
10154 (mapcar 'car (nth 1 args))
10155 (nth 1 args))
10156 (cddr args))
10157 (apply 'completing-read args)))))
10159 (defun org-extract-attributes (s)
10160 "Extract the attributes cookie from a string and set as text property."
10161 (let (a attr (start 0) key value)
10162 (save-match-data
10163 (when (string-match "{{\\([^}]+\\)}}$" s)
10164 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10165 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10166 (setq key (match-string 1 a) value (match-string 2 a)
10167 start (match-end 0)
10168 attr (plist-put attr (intern key) value))))
10169 (org-add-props s nil 'org-attr attr))
10172 ;;; Opening/following a link
10174 (defvar org-link-search-failed nil)
10176 (defvar org-open-link-functions nil
10177 "Hook for functions finding a plain text link.
10178 These functions must take a single argument, the link content.
10179 They will be called for links that look like [[link text][description]]
10180 when LINK TEXT does not have a protocol like \"http:\" and does not look
10181 like a filename (e.g. \"./blue.png\").
10183 These functions will be called *before* Org attempts to resolve the
10184 link by doing text searches in the current buffer - so if you want a
10185 link \"[[target]]\" to still find \"<<target>>\", your function should
10186 handle this as a special case.
10188 When the function does handle the link, it must return a non-nil value.
10189 If it decides that it is not responsible for this link, it must return
10190 nil to indicate that that Org-mode can continue with other options
10191 like exact and fuzzy text search.")
10193 (defun org-next-link (&optional search-backward)
10194 "Move forward to the next link.
10195 If the link is in hidden text, expose it."
10196 (interactive "P")
10197 (when (and org-link-search-failed (eq this-command last-command))
10198 (goto-char (point-min))
10199 (message "Link search wrapped back to beginning of buffer"))
10200 (setq org-link-search-failed nil)
10201 (let* ((pos (point))
10202 (ct (org-context))
10203 (a (assoc :link ct))
10204 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10205 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10206 ((looking-at org-any-link-re)
10207 ;; Don't stay stuck at link without an org-link face
10208 (forward-char (if search-backward -1 1))))
10209 (if (funcall srch-fun org-any-link-re nil t)
10210 (progn
10211 (goto-char (match-beginning 0))
10212 (if (outline-invisible-p) (org-show-context)))
10213 (goto-char pos)
10214 (setq org-link-search-failed t)
10215 (message "No further link found"))))
10217 (defun org-previous-link ()
10218 "Move backward to the previous link.
10219 If the link is in hidden text, expose it."
10220 (interactive)
10221 (funcall 'org-next-link t))
10223 (defun org-translate-link (s)
10224 "Translate a link string if a translation function has been defined."
10225 (if (and org-link-translation-function
10226 (fboundp org-link-translation-function)
10227 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10228 (progn
10229 (setq s (funcall org-link-translation-function
10230 (match-string 1 s) (match-string 2 s)))
10231 (concat (car s) ":" (cdr s)))
10234 (defun org-translate-link-from-planner (type path)
10235 "Translate a link from Emacs Planner syntax so that Org can follow it.
10236 This is still an experimental function, your mileage may vary."
10237 (cond
10238 ((member type '("http" "https" "news" "ftp"))
10239 ;; standard Internet links are the same.
10240 nil)
10241 ((and (equal type "irc") (string-match "^//" path))
10242 ;; Planner has two / at the beginning of an irc link, we have 1.
10243 ;; We should have zero, actually....
10244 (setq path (substring path 1)))
10245 ((and (equal type "lisp") (string-match "^/" path))
10246 ;; Planner has a slash, we do not.
10247 (setq type "elisp" path (substring path 1)))
10248 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10249 ;; A typical message link. Planner has the id after the final slash,
10250 ;; we separate it with a hash mark
10251 (setq path (concat (match-string 1 path) "#"
10252 (org-remove-angle-brackets (match-string 2 path))))))
10253 (cons type path))
10255 (defun org-find-file-at-mouse (ev)
10256 "Open file link or URL at mouse."
10257 (interactive "e")
10258 (mouse-set-point ev)
10259 (org-open-at-point 'in-emacs))
10261 (defun org-open-at-mouse (ev)
10262 "Open file link or URL at mouse.
10263 See the docstring of `org-open-file' for details."
10264 (interactive "e")
10265 (mouse-set-point ev)
10266 (if (eq major-mode 'org-agenda-mode)
10267 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10268 (org-open-at-point))
10270 (defvar org-window-config-before-follow-link nil
10271 "The window configuration before following a link.
10272 This is saved in case the need arises to restore it.")
10274 (defvar org-open-link-marker (make-marker)
10275 "Marker pointing to the location where `org-open-at-point; was called.")
10277 ;;;###autoload
10278 (defun org-open-at-point-global ()
10279 "Follow a link like Org-mode does.
10280 This command can be called in any mode to follow a link that has
10281 Org-mode syntax."
10282 (interactive)
10283 (org-run-like-in-org-mode 'org-open-at-point))
10285 ;;;###autoload
10286 (defun org-open-link-from-string (s &optional arg reference-buffer)
10287 "Open a link in the string S, as if it was in Org-mode."
10288 (interactive "sLink: \nP")
10289 (let ((reference-buffer (or reference-buffer (current-buffer))))
10290 (with-temp-buffer
10291 (let ((org-inhibit-startup (not reference-buffer)))
10292 (org-mode)
10293 (insert s)
10294 (goto-char (point-min))
10295 (when reference-buffer
10296 (setq org-link-abbrev-alist-local
10297 (with-current-buffer reference-buffer
10298 org-link-abbrev-alist-local)))
10299 (org-open-at-point arg reference-buffer)))))
10301 (defvar org-open-at-point-functions nil
10302 "Hook that is run when following a link at point.
10304 Functions in this hook must return t if they identify and follow
10305 a link at point. If they don't find anything interesting at point,
10306 they must return nil.")
10308 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10309 (defun org-open-at-point (&optional arg reference-buffer)
10310 "Open link at or after point.
10311 If there is no link at point, this function will search forward up to
10312 the end of the current line.
10313 Normally, files will be opened by an appropriate application. If the
10314 optional prefix argument ARG is non-nil, Emacs will visit the file.
10315 With a double prefix argument, try to open outside of Emacs, in the
10316 application the system uses for this file type."
10317 (interactive "P")
10318 ;; if in a code block, then open the block's results
10319 (unless (call-interactively #'org-babel-open-src-block-result)
10320 (org-load-modules-maybe)
10321 (move-marker org-open-link-marker (point))
10322 (setq org-window-config-before-follow-link (current-window-configuration))
10323 (org-remove-occur-highlights nil nil t)
10324 (cond
10325 ((and (org-at-heading-p)
10326 (not (org-at-timestamp-p t))
10327 (not (org-in-regexp
10328 (concat org-plain-link-re "\\|"
10329 org-bracket-link-regexp "\\|"
10330 org-angle-link-re "\\|"
10331 "[ \t]:[^ \t\n]+:[ \t]*$")))
10332 (not (get-text-property (point) 'org-linked-text)))
10333 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10334 (lk0 (car lkall))
10335 (lk (if (stringp lk0) (list lk0) lk0))
10336 (lkend (cdr lkall)))
10337 (mapcar (lambda(l)
10338 (search-forward l nil lkend)
10339 (goto-char (match-beginning 0))
10340 (org-open-at-point))
10341 lk))
10342 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10343 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10344 ((and (org-at-timestamp-p t)
10345 (not (org-in-regexp org-bracket-link-regexp)))
10346 (org-follow-timestamp-link))
10347 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10348 (not (org-in-regexp org-any-link-re)))
10349 (org-footnote-action))
10351 (let (type path link line search (pos (point)))
10352 (catch 'match
10353 (save-excursion
10354 (skip-chars-forward "^]\n\r")
10355 (when (org-in-regexp org-bracket-link-regexp 1)
10356 (setq link (org-extract-attributes
10357 (org-link-unescape (org-match-string-no-properties 1))))
10358 (while (string-match " *\n *" link)
10359 (setq link (replace-match " " t t link)))
10360 (setq link (org-link-expand-abbrev link))
10361 (cond
10362 ((or (file-name-absolute-p link)
10363 (string-match "^\\.\\.?/" link))
10364 (setq type "file" path link))
10365 ((string-match org-link-re-with-space3 link)
10366 (setq type (match-string 1 link) path (match-string 2 link)))
10367 ((string-match "^help:+\\(.+\\)" link)
10368 (setq type "help" path (match-string 1 link)))
10369 (t (setq type "thisfile" path link)))
10370 (throw 'match t)))
10372 (when (get-text-property (point) 'org-linked-text)
10373 (setq type "thisfile"
10374 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10375 (1+ (point)) (point))
10376 path (buffer-substring
10377 (or (previous-single-property-change pos 'org-linked-text)
10378 (point-min))
10379 (or (next-single-property-change pos 'org-linked-text)
10380 (point-max)))
10381 ;; Ensure we will search for a <<<radio>>> link, not
10382 ;; a simple reference like <<ref>>
10383 path (concat "<" path))
10384 (throw 'match t))
10386 (save-excursion
10387 (when (or (org-in-regexp org-angle-link-re)
10388 (let ((match (org-in-regexp org-plain-link-re)))
10389 ;; Check a plain link is not within a bracket link
10390 (and match
10391 (save-excursion
10392 (progn
10393 (goto-char (car match))
10394 (not (org-in-regexp org-bracket-link-regexp))))))
10395 (let ((line_ending (save-excursion (end-of-line) (point))))
10396 ;; We are in a line before a plain or bracket link
10397 (or (re-search-forward org-plain-link-re line_ending t)
10398 (re-search-forward org-bracket-link-regexp line_ending t))))
10399 (setq type (match-string 1)
10400 path (org-link-unescape (match-string 2)))
10401 (throw 'match t)))
10402 (save-excursion
10403 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10404 (setq type "tags"
10405 path (match-string 1))
10406 (while (string-match ":" path)
10407 (setq path (replace-match "+" t t path)))
10408 (throw 'match t)))
10409 (when (org-in-regexp "<\\([^><\n]+\\)>")
10410 (setq type "tree-match"
10411 path (match-string 1))
10412 (throw 'match t)))
10413 (unless path
10414 (user-error "No link found"))
10416 ;; switch back to reference buffer
10417 ;; needed when if called in a temporary buffer through
10418 ;; org-open-link-from-string
10419 (with-current-buffer (or reference-buffer (current-buffer))
10421 ;; Remove any trailing spaces in path
10422 (if (string-match " +\\'" path)
10423 (setq path (replace-match "" t t path)))
10424 (if (and org-link-translation-function
10425 (fboundp org-link-translation-function))
10426 ;; Check if we need to translate the link
10427 (let ((tmp (funcall org-link-translation-function type path)))
10428 (setq type (car tmp) path (cdr tmp))))
10430 (cond
10432 ((assoc type org-link-protocols)
10433 (funcall (nth 1 (assoc type org-link-protocols)) path))
10435 ((equal type "help")
10436 (let ((f-or-v (intern path)))
10437 (cond ((fboundp f-or-v)
10438 (describe-function f-or-v))
10439 ((boundp f-or-v)
10440 (describe-variable f-or-v))
10441 (t (error "Not a known function or variable")))))
10443 ((equal type "mailto")
10444 (let ((cmd (car org-link-mailto-program))
10445 (args (cdr org-link-mailto-program)) args1
10446 (address path) (subject "") a)
10447 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10448 (setq address (match-string 1 path)
10449 subject (org-link-escape (match-string 2 path))))
10450 (while args
10451 (cond
10452 ((not (stringp (car args))) (push (pop args) args1))
10453 (t (setq a (pop args))
10454 (if (string-match "%a" a)
10455 (setq a (replace-match address t t a)))
10456 (if (string-match "%s" a)
10457 (setq a (replace-match subject t t a)))
10458 (push a args1))))
10459 (apply cmd (nreverse args1))))
10461 ((member type '("http" "https" "ftp" "news"))
10462 (browse-url
10463 (concat type ":"
10464 (if (org-string-match-p
10465 (concat "[[:nonascii:]"
10466 org-link-escape-chars-browser "]")
10467 path)
10468 (org-link-escape path org-link-escape-chars-browser)
10469 path))))
10471 ((string= type "doi")
10472 (browse-url
10473 (concat org-doi-server-url
10474 (if (org-string-match-p
10475 (concat "[[:nonascii:]"
10476 org-link-escape-chars-browser "]")
10477 path)
10478 (org-link-escape path org-link-escape-chars-browser)
10479 path))))
10481 ((member type '("message"))
10482 (browse-url (concat type ":" path)))
10484 ((string= type "tags")
10485 (org-tags-view arg path))
10487 ((string= type "tree-match")
10488 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10490 ((string= type "file")
10491 (if (string-match "::\\([0-9]+\\)\\'" path)
10492 (setq line (string-to-number (match-string 1 path))
10493 path (substring path 0 (match-beginning 0)))
10494 (if (string-match "::\\(.+\\)\\'" path)
10495 (setq search (match-string 1 path)
10496 path (substring path 0 (match-beginning 0)))))
10497 (if (string-match "[*?{]" (file-name-nondirectory path))
10498 (dired path)
10499 (org-open-file path arg line search)))
10501 ((string= type "shell")
10502 (let ((buf (generate-new-buffer "*Org Shell Output"))
10503 (cmd path))
10504 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10505 (string-match org-confirm-shell-link-not-regexp cmd))
10506 (not org-confirm-shell-link-function)
10507 (funcall org-confirm-shell-link-function
10508 (format "Execute \"%s\" in shell? "
10509 (org-add-props cmd nil
10510 'face 'org-warning))))
10511 (progn
10512 (message "Executing %s" cmd)
10513 (shell-command cmd buf)
10514 (if (featurep 'midnight)
10515 (setq clean-buffer-list-kill-buffer-names
10516 (cons buf clean-buffer-list-kill-buffer-names))))
10517 (error "Abort"))))
10519 ((string= type "elisp")
10520 (let ((cmd path))
10521 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10522 (string-match org-confirm-elisp-link-not-regexp cmd))
10523 (not org-confirm-elisp-link-function)
10524 (funcall org-confirm-elisp-link-function
10525 (format "Execute \"%s\" as elisp? "
10526 (org-add-props cmd nil
10527 'face 'org-warning))))
10528 (message "%s => %s" cmd
10529 (if (equal (string-to-char cmd) ?\()
10530 (eval (read cmd))
10531 (call-interactively (read cmd))))
10532 (error "Abort"))))
10534 ((and (string= type "thisfile")
10535 (run-hook-with-args-until-success
10536 'org-open-link-functions path)))
10538 ((string= type "thisfile")
10539 (if arg
10540 (switch-to-buffer-other-window
10541 (org-get-buffer-for-internal-link (current-buffer)))
10542 (org-mark-ring-push))
10543 (let ((cmd `(org-link-search
10544 ,path
10545 ,(cond ((equal arg '(4)) ''occur)
10546 ((equal arg '(16)) ''org-occur))
10547 ,pos)))
10548 (condition-case nil (let ((org-link-search-inhibit-query t))
10549 (eval cmd))
10550 (error (progn (widen) (eval cmd))))))
10552 (t (browse-url-at-point)))))))
10553 (move-marker org-open-link-marker nil)
10554 (run-hook-with-args 'org-follow-link-hook)))
10556 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10557 "Offer links in the current entry and return the selected link.
10558 If there is only one link, return it.
10559 If NTH is an integer, return the NTH link found.
10560 If ZERO is a string, check also this string for a link, and if
10561 there is one, return it."
10562 (with-current-buffer buffer
10563 (save-excursion
10564 (save-restriction
10565 (widen)
10566 (goto-char marker)
10567 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10568 "\\(" org-angle-link-re "\\)\\|"
10569 "\\(" org-plain-link-re "\\)"))
10570 (cnt ?0)
10571 (in-emacs (if (integerp nth) nil nth))
10572 have-zero end links link c)
10573 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10574 (push (match-string 0 zero) links)
10575 (setq cnt (1- cnt) have-zero t))
10576 (save-excursion
10577 (org-back-to-heading t)
10578 (setq end (save-excursion (outline-next-heading) (point)))
10579 (while (re-search-forward re end t)
10580 (push (match-string 0) links))
10581 (setq links (org-uniquify (reverse links))))
10582 (cond
10583 ((null links)
10584 (message "No links"))
10585 ((equal (length links) 1)
10586 (setq link (car links)))
10587 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10588 (setq link (nth (if have-zero nth (1- nth)) links)))
10589 (t ; we have to select a link
10590 (save-excursion
10591 (save-window-excursion
10592 (delete-other-windows)
10593 (with-output-to-temp-buffer "*Select Link*"
10594 (mapc (lambda (l)
10595 (if (not (string-match org-bracket-link-regexp l))
10596 (princ (format "[%c] %s\n" (incf cnt)
10597 (org-remove-angle-brackets l)))
10598 (if (match-end 3)
10599 (princ (format "[%c] %s (%s)\n" (incf cnt)
10600 (match-string 3 l) (match-string 1 l)))
10601 (princ (format "[%c] %s\n" (incf cnt)
10602 (match-string 1 l))))))
10603 links))
10604 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10605 (message "Select link to open, RET to open all:")
10606 (setq c (read-char-exclusive))
10607 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10608 (when (equal c ?q) (error "Abort"))
10609 (if (equal c ?\C-m)
10610 (setq link links)
10611 (setq nth (- c ?0))
10612 (if have-zero (setq nth (1+ nth)))
10613 (unless (and (integerp nth) (>= (length links) nth))
10614 (user-error "Invalid link selection"))
10615 (setq link (nth (1- nth) links)))))
10616 (cons link end))))))
10618 ;; Add special file links that specify the way of opening
10620 (org-add-link-type "file+sys" 'org-open-file-with-system)
10621 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10622 (defun org-open-file-with-system (path)
10623 "Open file at PATH using the system way of opening it."
10624 (org-open-file path 'system))
10625 (defun org-open-file-with-emacs (path)
10626 "Open file at PATH in Emacs."
10627 (org-open-file path 'emacs))
10630 ;;; File search
10632 (defvar org-create-file-search-functions nil
10633 "List of functions to construct the right search string for a file link.
10634 These functions are called in turn with point at the location to
10635 which the link should point.
10637 A function in the hook should first test if it would like to
10638 handle this file type, for example by checking the `major-mode'
10639 or the file extension. If it decides not to handle this file, it
10640 should just return nil to give other functions a chance. If it
10641 does handle the file, it must return the search string to be used
10642 when following the link. The search string will be part of the
10643 file link, given after a double colon, and `org-open-at-point'
10644 will automatically search for it. If special measures must be
10645 taken to make the search successful, another function should be
10646 added to the companion hook `org-execute-file-search-functions',
10647 which see.
10649 A function in this hook may also use `setq' to set the variable
10650 `description' to provide a suggestion for the descriptive text to
10651 be used for this link when it gets inserted into an Org-mode
10652 buffer with \\[org-insert-link].")
10654 (defvar org-execute-file-search-functions nil
10655 "List of functions to execute a file search triggered by a link.
10657 Functions added to this hook must accept a single argument, the
10658 search string that was part of the file link, the part after the
10659 double colon. The function must first check if it would like to
10660 handle this search, for example by checking the `major-mode' or
10661 the file extension. If it decides not to handle this search, it
10662 should just return nil to give other functions a chance. If it
10663 does handle the search, it must return a non-nil value to keep
10664 other functions from trying.
10666 Each function can access the current prefix argument through the
10667 variable `current-prefix-arg'. Note that a single prefix is used
10668 to force opening a link in Emacs, so it may be good to only use a
10669 numeric or double prefix to guide the search function.
10671 In case this is needed, a function in this hook can also restore
10672 the window configuration before `org-open-at-point' was called using:
10674 (set-window-configuration org-window-config-before-follow-link)")
10676 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10677 (defun org-link-search (s &optional type avoid-pos stealth)
10678 "Search for a link search option.
10679 If S is surrounded by forward slashes, it is interpreted as a
10680 regular expression. In org-mode files, this will create an `org-occur'
10681 sparse tree. In ordinary files, `occur' will be used to list matches.
10682 If the current buffer is in `dired-mode', grep will be used to search
10683 in all files. If AVOID-POS is given, ignore matches near that position.
10685 When optional argument STEALTH is non-nil, do not modify
10686 visibility around point, thus ignoring
10687 `org-show-hierarchy-above', `org-show-following-heading' and
10688 `org-show-siblings' variables."
10689 (let ((case-fold-search t)
10690 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10691 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10692 (append '(("") (" ") ("\t") ("\n"))
10693 org-emphasis-alist)
10694 "\\|") "\\)"))
10695 (pos (point))
10696 (pre nil) (post nil)
10697 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10698 (cond
10699 ;; First check if there are any special search functions
10700 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10701 ;; Now try the builtin stuff
10702 ((and (equal (string-to-char s0) ?#)
10703 (> (length s0) 1)
10704 (save-excursion
10705 (goto-char (point-min))
10706 (and
10707 (re-search-forward
10708 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10709 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10710 (setq type 'dedicated
10711 pos (match-beginning 0))))
10712 ;; There is an exact target for this
10713 (goto-char pos)
10714 (org-back-to-heading t)))
10715 ((save-excursion
10716 (goto-char (point-min))
10717 (and
10718 (re-search-forward
10719 (concat "<<" (regexp-quote s0) ">>") nil t)
10720 (setq type 'dedicated
10721 pos (match-beginning 0))))
10722 ;; There is an exact target for this
10723 (goto-char pos))
10724 ((save-excursion
10725 (goto-char (point-min))
10726 (and
10727 (re-search-forward
10728 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10729 (setq type 'dedicated pos (match-beginning 0))))
10730 ;; Found an element with a matching #+name affiliated keyword.
10731 (goto-char pos))
10732 ((and (string-match "^(\\(.*\\))$" s0)
10733 (save-excursion
10734 (goto-char (point-min))
10735 (and
10736 (re-search-forward
10737 (concat "[^[]" (regexp-quote
10738 (format org-coderef-label-format
10739 (match-string 1 s0))))
10740 nil t)
10741 (setq type 'dedicated
10742 pos (1+ (match-beginning 0))))))
10743 ;; There is a coderef target for this
10744 (goto-char pos))
10745 ((string-match "^/\\(.*\\)/$" s)
10746 ;; A regular expression
10747 (cond
10748 ((derived-mode-p 'org-mode)
10749 (org-occur (match-string 1 s)))
10750 (t (org-do-occur (match-string 1 s)))))
10751 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10752 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10753 (goto-char (point-min))
10754 (cond
10755 ((let (case-fold-search)
10756 (re-search-forward (format org-complex-heading-regexp-format
10757 (regexp-quote s))
10758 nil t))
10759 ;; OK, found a match
10760 (setq type 'dedicated)
10761 (goto-char (match-beginning 0)))
10762 ((and (not org-link-search-inhibit-query)
10763 (eq org-link-search-must-match-exact-headline 'query-to-create)
10764 (y-or-n-p "No match - create this as a new heading? "))
10765 (goto-char (point-max))
10766 (or (bolp) (newline))
10767 (insert "* " s "\n")
10768 (beginning-of-line 0))
10770 (goto-char pos)
10771 (error "No match"))))
10773 ;; A normal search string
10774 (when (equal (string-to-char s) ?*)
10775 ;; Anchor on headlines, post may include tags.
10776 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10777 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10778 s (substring s 1)))
10779 (remove-text-properties
10780 0 (length s)
10781 '(face nil mouse-face nil keymap nil fontified nil) s)
10782 ;; Make a series of regular expressions to find a match
10783 (setq words (org-split-string s "[ \n\r\t]+")
10785 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10786 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10787 "\\)" markers)
10788 re2a_ (concat "\\(" (mapconcat 'downcase words
10789 "[ \t\r\n]+") "\\)[ \t\r\n]")
10790 re2a (concat "[ \t\r\n]" re2a_)
10791 re4_ (concat "\\(" (mapconcat 'downcase words
10792 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10793 re4 (concat "[^a-zA-Z_]" re4_)
10795 re1 (concat pre re2 post)
10796 re3 (concat pre (if pre re4_ re4) post)
10797 re5 (concat pre ".*" re4)
10798 re2 (concat pre re2)
10799 re2a (concat pre (if pre re2a_ re2a))
10800 re4 (concat pre (if pre re4_ re4))
10801 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10802 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10803 re5 "\\)"))
10804 (cond
10805 ((eq type 'org-occur) (org-occur reall))
10806 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10807 (t (goto-char (point-min))
10808 (setq type 'fuzzy)
10809 (if (or (and (org-search-not-self 1 re0 nil t)
10810 (setq type 'dedicated))
10811 (org-search-not-self 1 re1 nil t)
10812 (org-search-not-self 1 re2 nil t)
10813 (org-search-not-self 1 re2a nil t)
10814 (org-search-not-self 1 re3 nil t)
10815 (org-search-not-self 1 re4 nil t)
10816 (org-search-not-self 1 re5 nil t))
10817 (goto-char (match-beginning 1))
10818 (goto-char pos)
10819 (error "No match"))))))
10820 (and (derived-mode-p 'org-mode)
10821 (not stealth)
10822 (org-show-context 'link-search))
10823 type))
10825 (defun org-search-not-self (group &rest args)
10826 "Execute `re-search-forward', but only accept matches that do not
10827 enclose the position of `org-open-link-marker'."
10828 (let ((m org-open-link-marker))
10829 (catch 'exit
10830 (while (apply 're-search-forward args)
10831 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10832 (goto-char (match-end group))
10833 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10834 (> (match-beginning 0) (marker-position m))
10835 (< (match-end 0) (marker-position m)))
10836 (save-match-data
10837 (or (not (org-in-regexp
10838 org-bracket-link-analytic-regexp 1))
10839 (not (match-end 4)) ; no description
10840 (and (<= (match-beginning 4) (point))
10841 (>= (match-end 4) (point))))))
10842 (throw 'exit (point))))))))
10844 (defun org-get-buffer-for-internal-link (buffer)
10845 "Return a buffer to be used for displaying the link target of internal links."
10846 (cond
10847 ((not org-display-internal-link-with-indirect-buffer)
10848 buffer)
10849 ((string-match "(Clone)$" (buffer-name buffer))
10850 (message "Buffer is already a clone, not making another one")
10851 ;; we also do not modify visibility in this case
10852 buffer)
10853 (t ; make a new indirect buffer for displaying the link
10854 (let* ((bn (buffer-name buffer))
10855 (ibn (concat bn "(Clone)"))
10856 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10857 (with-current-buffer ib (org-overview))
10858 ib))))
10860 (defun org-do-occur (regexp &optional cleanup)
10861 "Call the Emacs command `occur'.
10862 If CLEANUP is non-nil, remove the printout of the regular expression
10863 in the *Occur* buffer. This is useful if the regex is long and not useful
10864 to read."
10865 (occur regexp)
10866 (when cleanup
10867 (let ((cwin (selected-window)) win beg end)
10868 (when (setq win (get-buffer-window "*Occur*"))
10869 (select-window win))
10870 (goto-char (point-min))
10871 (when (re-search-forward "match[a-z]+" nil t)
10872 (setq beg (match-end 0))
10873 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10874 (setq end (1- (match-beginning 0)))))
10875 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10876 (goto-char (point-min))
10877 (select-window cwin))))
10879 ;;; The mark ring for links jumps
10881 (defvar org-mark-ring nil
10882 "Mark ring for positions before jumps in Org-mode.")
10883 (defvar org-mark-ring-last-goto nil
10884 "Last position in the mark ring used to go back.")
10885 ;; Fill and close the ring
10886 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10887 (loop for i from 1 to org-mark-ring-length do
10888 (push (make-marker) org-mark-ring))
10889 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10890 org-mark-ring)
10892 (defun org-mark-ring-push (&optional pos buffer)
10893 "Put the current position or POS into the mark ring and rotate it."
10894 (interactive)
10895 (setq pos (or pos (point)))
10896 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10897 (move-marker (car org-mark-ring)
10898 (or pos (point))
10899 (or buffer (current-buffer)))
10900 (message "%s"
10901 (substitute-command-keys
10902 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10904 (defun org-mark-ring-goto (&optional n)
10905 "Jump to the previous position in the mark ring.
10906 With prefix arg N, jump back that many stored positions. When
10907 called several times in succession, walk through the entire ring.
10908 Org-mode commands jumping to a different position in the current file,
10909 or to another Org-mode file, automatically push the old position
10910 onto the ring."
10911 (interactive "p")
10912 (let (p m)
10913 (if (eq last-command this-command)
10914 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10915 (setq p org-mark-ring))
10916 (setq org-mark-ring-last-goto p)
10917 (setq m (car p))
10918 (org-pop-to-buffer-same-window (marker-buffer m))
10919 (goto-char m)
10920 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10922 (defun org-remove-angle-brackets (s)
10923 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10924 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10926 (defun org-add-angle-brackets (s)
10927 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10928 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10930 (defun org-remove-double-quotes (s)
10931 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10932 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10935 ;;; Following specific links
10937 (defun org-follow-timestamp-link ()
10938 "Open an agenda view for the time-stamp date/range at point."
10939 (cond
10940 ((org-at-date-range-p t)
10941 (let ((org-agenda-start-on-weekday)
10942 (t1 (match-string 1))
10943 (t2 (match-string 2)) tt1 tt2)
10944 (setq tt1 (time-to-days (org-time-string-to-time t1))
10945 tt2 (time-to-days (org-time-string-to-time t2)))
10946 (let ((org-agenda-buffer-tmp-name
10947 (format "*Org Agenda(a:%s)"
10948 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10949 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10950 ((org-at-timestamp-p t)
10951 (let ((org-agenda-buffer-tmp-name
10952 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10953 (org-agenda-list nil (time-to-days (org-time-string-to-time
10954 (substring (match-string 1) 0 10)))
10955 1)))
10956 (t (error "This should not happen"))))
10959 ;;; Following file links
10960 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10961 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10962 (declare-function mailcap-mime-info
10963 "mailcap" (string &optional request no-decode))
10964 (defvar org-wait nil)
10965 (defun org-open-file (path &optional in-emacs line search)
10966 "Open the file at PATH.
10967 First, this expands any special file name abbreviations. Then the
10968 configuration variable `org-file-apps' is checked if it contains an
10969 entry for this file type, and if yes, the corresponding command is launched.
10971 If no application is found, Emacs simply visits the file.
10973 With optional prefix argument IN-EMACS, Emacs will visit the file.
10974 With a double \\[universal-argument] \\[universal-argument] \
10975 prefix arg, Org tries to avoid opening in Emacs
10976 and to use an external application to visit the file.
10978 Optional LINE specifies a line to go to, optional SEARCH a string
10979 to search for. If LINE or SEARCH is given, the file will be
10980 opened in Emacs, unless an entry from org-file-apps that makes
10981 use of groups in a regexp matches.
10983 If you want to change the way frames are used when following a
10984 link, please customize `org-link-frame-setup'.
10986 If the file does not exist, an error is thrown."
10987 (let* ((file (if (equal path "")
10988 buffer-file-name
10989 (substitute-in-file-name (expand-file-name path))))
10990 (file-apps (append org-file-apps (org-default-apps)))
10991 (apps (org-remove-if
10992 'org-file-apps-entry-match-against-dlink-p file-apps))
10993 (apps-dlink (org-remove-if-not
10994 'org-file-apps-entry-match-against-dlink-p file-apps))
10995 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10996 (dirp (if remp nil (file-directory-p file)))
10997 (file (if (and dirp org-open-directory-means-index-dot-org)
10998 (concat (file-name-as-directory file) "index.org")
10999 file))
11000 (a-m-a-p (assq 'auto-mode apps))
11001 (dfile (downcase file))
11002 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11003 (link (cond ((and (eq line nil)
11004 (eq search nil))
11005 file)
11006 (line
11007 (concat file "::" (number-to-string line)))
11008 (search
11009 (concat file "::" search))))
11010 (dlink (downcase link))
11011 (old-buffer (current-buffer))
11012 (old-pos (point))
11013 (old-mode major-mode)
11014 ext cmd link-match-data)
11015 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11016 (setq ext (match-string 1 dfile))
11017 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11018 (setq ext (match-string 1 dfile))))
11019 (cond
11020 ((member in-emacs '((16) system))
11021 (setq cmd (cdr (assoc 'system apps))))
11022 (in-emacs (setq cmd 'emacs))
11024 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11025 (and dirp (cdr (assoc 'directory apps)))
11026 ; first, try matching against apps-dlink
11027 ; if we get a match here, store the match data for later
11028 (let ((match (assoc-default dlink apps-dlink
11029 'string-match)))
11030 (if match
11031 (progn (setq link-match-data (match-data))
11032 match)
11033 (progn (setq in-emacs (or in-emacs line search))
11034 nil))) ; if we have no match in apps-dlink,
11035 ; always open the file in emacs if line or search
11036 ; is given (for backwards compatibility)
11037 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11038 'string-match)
11039 (cdr (assoc ext apps))
11040 (cdr (assoc t apps))))))
11041 (when (eq cmd 'system)
11042 (setq cmd (cdr (assoc 'system apps))))
11043 (when (eq cmd 'default)
11044 (setq cmd (cdr (assoc t apps))))
11045 (when (eq cmd 'mailcap)
11046 (require 'mailcap)
11047 (mailcap-parse-mailcaps)
11048 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11049 (command (mailcap-mime-info mime-type)))
11050 (if (stringp command)
11051 (setq cmd command)
11052 (setq cmd 'emacs))))
11053 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11054 (not (file-exists-p file))
11055 (not org-open-non-existing-files))
11056 (user-error "No such file: %s" file))
11057 (cond
11058 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11059 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11060 (while (string-match "['\"]%s['\"]" cmd)
11061 (setq cmd (replace-match "%s" t t cmd)))
11062 (while (string-match "%s" cmd)
11063 (setq cmd (replace-match
11064 (save-match-data
11065 (shell-quote-argument
11066 (convert-standard-filename file)))
11067 t t cmd)))
11069 ;; Replace "%1", "%2" etc. in command with group matches from regex
11070 (save-match-data
11071 (let ((match-index 1)
11072 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11073 (set-match-data link-match-data)
11074 (while (<= match-index number-of-groups)
11075 (let ((regex (concat "%" (number-to-string match-index)))
11076 (replace-with (match-string match-index dlink)))
11077 (while (string-match regex cmd)
11078 (setq cmd (replace-match replace-with t t cmd))))
11079 (setq match-index (+ match-index 1)))))
11081 (save-window-excursion
11082 (message "Running %s...done" cmd)
11083 (start-process-shell-command cmd nil cmd)
11084 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11085 ((or (stringp cmd)
11086 (eq cmd 'emacs))
11087 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11088 (widen)
11089 (if line (org-goto-line line)
11090 (if search (org-link-search search))))
11091 ((consp cmd)
11092 (let ((file (convert-standard-filename file)))
11093 (save-match-data
11094 (set-match-data link-match-data)
11095 (eval cmd))))
11096 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11097 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11098 (or (not (equal old-buffer (current-buffer)))
11099 (not (equal old-pos (point))))
11100 (org-mark-ring-push old-pos old-buffer))))
11102 (defun org-file-apps-entry-match-against-dlink-p (entry)
11103 "This function returns non-nil if `entry' uses a regular
11104 expression which should be matched against the whole link by
11105 org-open-file.
11107 It assumes that is the case when the entry uses a regular
11108 expression which has at least one grouping construct and the
11109 action is either a lisp form or a command string containing
11110 '%1', i.e. using at least one subexpression match as a
11111 parameter."
11112 (let ((selector (car entry))
11113 (action (cdr entry)))
11114 (if (stringp selector)
11115 (and (> (regexp-opt-depth selector) 0)
11116 (or (and (stringp action)
11117 (string-match "%[0-9]" action))
11118 (consp action)))
11119 nil)))
11121 (defun org-default-apps ()
11122 "Return the default applications for this operating system."
11123 (cond
11124 ((eq system-type 'darwin)
11125 org-file-apps-defaults-macosx)
11126 ((eq system-type 'windows-nt)
11127 org-file-apps-defaults-windowsnt)
11128 (t org-file-apps-defaults-gnu)))
11130 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11131 "Convert extensions to regular expressions in the cars of LIST.
11132 Also, weed out any non-string entries, because the return value is used
11133 only for regexp matching.
11134 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11135 point to the symbol `emacs', indicating that the file should
11136 be opened in Emacs."
11137 (append
11138 (delq nil
11139 (mapcar (lambda (x)
11140 (if (not (stringp (car x)))
11142 (if (string-match "\\W" (car x))
11144 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11145 list))
11146 (if add-auto-mode
11147 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11149 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11150 (defun org-file-remote-p (file)
11151 "Test whether FILE specifies a location on a remote system.
11152 Return non-nil if the location is indeed remote.
11154 For example, the filename \"/user@host:/foo\" specifies a location
11155 on the system \"/user@host:\"."
11156 (cond ((fboundp 'file-remote-p)
11157 (file-remote-p file))
11158 ((fboundp 'tramp-handle-file-remote-p)
11159 (tramp-handle-file-remote-p file))
11160 ((and (boundp 'ange-ftp-name-format)
11161 (string-match (car ange-ftp-name-format) file))
11162 t)))
11165 ;;;; Refiling
11167 (defun org-get-org-file ()
11168 "Read a filename, with default directory `org-directory'."
11169 (let ((default (or org-default-notes-file remember-data-file)))
11170 (read-file-name (format "File name [%s]: " default)
11171 (file-name-as-directory org-directory)
11172 default)))
11174 (defun org-notes-order-reversed-p ()
11175 "Check if the current file should receive notes in reversed order."
11176 (cond
11177 ((not org-reverse-note-order) nil)
11178 ((eq t org-reverse-note-order) t)
11179 ((not (listp org-reverse-note-order)) nil)
11180 (t (catch 'exit
11181 (let ((all org-reverse-note-order)
11182 entry)
11183 (while (setq entry (pop all))
11184 (if (string-match (car entry) buffer-file-name)
11185 (throw 'exit (cdr entry))))
11186 nil)))))
11188 (defvar org-refile-target-table nil
11189 "The list of refile targets, created by `org-refile'.")
11191 (defvar org-agenda-new-buffers nil
11192 "Buffers created to visit agenda files.")
11194 (defvar org-refile-cache nil
11195 "Cache for refile targets.")
11197 (defvar org-refile-markers nil
11198 "All the markers used for caching refile locations.")
11200 (defun org-refile-marker (pos)
11201 "Get a new refile marker, but only if caching is in use."
11202 (if (not org-refile-use-cache)
11204 (let ((m (make-marker)))
11205 (move-marker m pos)
11206 (push m org-refile-markers)
11207 m)))
11209 (defun org-refile-cache-clear ()
11210 "Clear the refile cache and disable all the markers."
11211 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11212 (setq org-refile-markers nil)
11213 (setq org-refile-cache nil)
11214 (message "Refile cache has been cleared"))
11216 (defun org-refile-cache-check-set (set)
11217 "Check if all the markers in the cache still have live buffers."
11218 (let (marker)
11219 (catch 'exit
11220 (while (and set (setq marker (nth 3 (pop set))))
11221 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11222 (when (and marker (null (marker-buffer marker)))
11223 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11224 (sit-for 3)
11225 (throw 'exit nil)))
11226 t)))
11228 (defun org-refile-cache-put (set &rest identifiers)
11229 "Push the refile targets SET into the cache, under IDENTIFIERS."
11230 (let* ((key (sha1 (prin1-to-string identifiers)))
11231 (entry (assoc key org-refile-cache)))
11232 (if entry
11233 (setcdr entry set)
11234 (push (cons key set) org-refile-cache))))
11236 (defun org-refile-cache-get (&rest identifiers)
11237 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11238 (cond
11239 ((not org-refile-cache) nil)
11240 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11242 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11243 org-refile-cache))))
11244 (and set (org-refile-cache-check-set set) set)))))
11246 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11247 "Produce a table with refile targets."
11248 (let ((case-fold-search nil)
11249 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11250 (entries (or org-refile-targets '((nil . (:level . 1)))))
11251 targets tgs txt re files f desc descre fast-path-p level pos0)
11252 (message "Getting targets...")
11253 (with-current-buffer (or default-buffer (current-buffer))
11254 (while (setq entry (pop entries))
11255 (setq files (car entry) desc (cdr entry))
11256 (setq fast-path-p nil)
11257 (cond
11258 ((null files) (setq files (list (current-buffer))))
11259 ((eq files 'org-agenda-files)
11260 (setq files (org-agenda-files 'unrestricted)))
11261 ((and (symbolp files) (fboundp files))
11262 (setq files (funcall files)))
11263 ((and (symbolp files) (boundp files))
11264 (setq files (symbol-value files))))
11265 (if (stringp files) (setq files (list files)))
11266 (cond
11267 ((eq (car desc) :tag)
11268 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11269 ((eq (car desc) :todo)
11270 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11271 ((eq (car desc) :regexp)
11272 (setq descre (cdr desc)))
11273 ((eq (car desc) :level)
11274 (setq descre (concat "^\\*\\{" (number-to-string
11275 (if org-odd-levels-only
11276 (1- (* 2 (cdr desc)))
11277 (cdr desc)))
11278 "\\}[ \t]")))
11279 ((eq (car desc) :maxlevel)
11280 (setq fast-path-p t)
11281 (setq descre (concat "^\\*\\{1," (number-to-string
11282 (if org-odd-levels-only
11283 (1- (* 2 (cdr desc)))
11284 (cdr desc)))
11285 "\\}[ \t]")))
11286 (t (error "Bad refiling target description %s" desc)))
11287 (while (setq f (pop files))
11288 (with-current-buffer
11289 (if (bufferp f) f (org-get-agenda-file-buffer f))
11291 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11292 (progn
11293 (if (bufferp f) (setq f (buffer-file-name
11294 (buffer-base-buffer f))))
11295 (setq f (and f (expand-file-name f)))
11296 (if (eq org-refile-use-outline-path 'file)
11297 (push (list (file-name-nondirectory f) f nil nil) tgs))
11298 (save-excursion
11299 (save-restriction
11300 (widen)
11301 (goto-char (point-min))
11302 (while (re-search-forward descre nil t)
11303 (goto-char (setq pos0 (point-at-bol)))
11304 (catch 'next
11305 (when org-refile-target-verify-function
11306 (save-match-data
11307 (or (funcall org-refile-target-verify-function)
11308 (throw 'next t))))
11309 (when (and (looking-at org-complex-heading-regexp)
11310 (not (member (match-string 4) excluded-entries))
11311 (match-string 4))
11312 (setq level (org-reduced-level
11313 (- (match-end 1) (match-beginning 1)))
11314 txt (org-link-display-format (match-string 4))
11315 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11316 re (format org-complex-heading-regexp-format
11317 (regexp-quote (match-string 4))))
11318 (when org-refile-use-outline-path
11319 (setq txt (mapconcat
11320 'org-protect-slash
11321 (append
11322 (if (eq org-refile-use-outline-path
11323 'file)
11324 (list (file-name-nondirectory
11325 (buffer-file-name
11326 (buffer-base-buffer))))
11327 (if (eq org-refile-use-outline-path
11328 'full-file-path)
11329 (list (buffer-file-name
11330 (buffer-base-buffer)))))
11331 (org-get-outline-path fast-path-p
11332 level txt)
11333 (list txt))
11334 "/")))
11335 (push (list txt f re (org-refile-marker (point)))
11336 tgs)))
11337 (when (= (point) pos0)
11338 ;; verification function has not moved point
11339 (goto-char (point-at-eol))))))))
11340 (when org-refile-use-cache
11341 (org-refile-cache-put tgs (buffer-file-name) descre))
11342 (setq targets (append tgs targets))))))
11343 (message "Getting targets...done")
11344 (nreverse targets)))
11346 (defun org-protect-slash (s)
11347 (while (string-match "/" s)
11348 (setq s (replace-match "\\" t t s)))
11351 (defvar org-olpa (make-vector 20 nil))
11353 (defun org-get-outline-path (&optional fastp level heading)
11354 "Return the outline path to the current entry, as a list.
11356 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11357 routine which makes outline path derivations for an entire file,
11358 avoiding backtracing. Refile target collection makes use of that."
11359 (if fastp
11360 (progn
11361 (if (> level 19)
11362 (error "Outline path failure, more than 19 levels"))
11363 (loop for i from level upto 19 do
11364 (aset org-olpa i nil))
11365 (prog1
11366 (delq nil (append org-olpa nil))
11367 (aset org-olpa level heading)))
11368 (let (rtn case-fold-search)
11369 (save-excursion
11370 (save-restriction
11371 (widen)
11372 (while (org-up-heading-safe)
11373 (when (looking-at org-complex-heading-regexp)
11374 (push (org-trim
11375 (replace-regexp-in-string
11376 ;; Remove statistical/checkboxes cookies
11377 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11378 (org-match-string-no-properties 4)))
11379 rtn)))
11380 rtn)))))
11382 (defun org-format-outline-path (path &optional width prefix separator)
11383 "Format the outline path PATH for display.
11384 WIDTH is the maximum number of characters that is available.
11385 PREFIX is a prefix to be included in the returned string,
11386 such as the file name.
11387 SEPARATOR is inserted between the different parts of the path,
11388 the default is \"/\"."
11389 (setq width (or width 79))
11390 (if prefix (setq width (- width (length prefix))))
11391 (if (not path)
11392 (or prefix "")
11393 (let* ((nsteps (length path))
11394 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11395 (maxwidth (if (<= total-width width)
11396 10000 ;; everything fits
11397 ;; we need to shorten the level headings
11398 (/ (- width nsteps) nsteps)))
11399 (org-odd-levels-only nil)
11400 (n 0)
11401 (total (1+ (length prefix))))
11402 (setq maxwidth (max maxwidth 10))
11403 (concat prefix
11404 (if prefix (or separator "/"))
11405 (mapconcat
11406 (lambda (h)
11407 (setq n (1+ n))
11408 (if (and (= n nsteps) (< maxwidth 10000))
11409 (setq maxwidth (- total-width total)))
11410 (if (< (length h) maxwidth)
11411 (progn (setq total (+ total (length h) 1)) h)
11412 (setq h (substring h 0 (- maxwidth 2))
11413 total (+ total maxwidth 1))
11414 (if (string-match "[ \t]+\\'" h)
11415 (setq h (substring h 0 (match-beginning 0))))
11416 (setq h (concat h "..")))
11417 (org-add-props h nil 'face
11418 (nth (% (1- n) org-n-level-faces)
11419 org-level-faces))
11421 path (or separator "/"))))))
11423 (defun org-display-outline-path (&optional file current separator just-return-string)
11424 "Display the current outline path in the echo area.
11426 If FILE is non-nil, prepend the output with the file name.
11427 If CURRENT is non-nil, append the current heading to the output.
11428 SEPARATOR is passed through to `org-format-outline-path'. It separates
11429 the different parts of the path and defaults to \"/\".
11430 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11431 (interactive "P")
11432 (let* (case-fold-search
11433 message-log-max ; Don't populate the *Messages* buffer
11434 (bfn (buffer-file-name (buffer-base-buffer)))
11435 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11436 res)
11437 (if current (setq path (append path
11438 (save-excursion
11439 (org-back-to-heading t)
11440 (if (looking-at org-complex-heading-regexp)
11441 (list (match-string 4)))))))
11442 (setq res
11443 (org-format-outline-path
11444 path
11445 (1- (frame-width))
11446 (and file bfn (concat (file-name-nondirectory bfn) separator))
11447 separator))
11448 (if just-return-string
11449 (org-no-properties res)
11450 (message "%s" res))))
11452 (defvar org-refile-history nil
11453 "History for refiling operations.")
11455 (defvar org-after-refile-insert-hook nil
11456 "Hook run after `org-refile' has inserted its stuff at the new location.
11457 Note that this is still *before* the stuff will be removed from
11458 the *old* location.")
11460 (defvar org-capture-last-stored-marker)
11461 (defvar org-refile-keep nil
11462 "Non-nil means `org-refile' will copy instead of refile.")
11464 (defun org-copy ()
11465 "Like `org-refile', but copy."
11466 (interactive)
11467 (let ((org-refile-keep t))
11468 (funcall 'org-refile nil nil nil "Copy")))
11470 (defun org-refile (&optional goto default-buffer rfloc msg)
11471 "Move the entry or entries at point to another heading.
11472 The list of target headings is compiled using the information in
11473 `org-refile-targets', which see.
11475 At the target location, the entry is filed as a subitem of the target
11476 heading. Depending on `org-reverse-note-order', the new subitem will
11477 either be the first or the last subitem.
11479 If there is an active region, all entries in that region will be moved.
11480 However, the region must fulfill the requirement that the first heading
11481 is the first one sets the top-level of the moved text - at most siblings
11482 below it are allowed.
11484 With prefix arg GOTO, the command will only visit the target location
11485 and not actually move anything.
11487 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11488 go to the location where the last refiling operation has put the subtree.
11489 With a prefix argument of `2', refile to the running clock.
11491 RFLOC can be a refile location obtained in a different way.
11493 MSG is a string to replace \"Refile\" in the default prompt with
11494 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11496 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11498 If you are using target caching (see `org-refile-use-cache'),
11499 you have to clear the target cache in order to find new targets.
11500 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11501 prefix argument (`C-u C-u C-u C-c C-w')."
11503 (interactive "P")
11504 (if (member goto '(0 (64)))
11505 (org-refile-cache-clear)
11506 (let* ((actionmsg (or msg "Refile"))
11507 (cbuf (current-buffer))
11508 (regionp (org-region-active-p))
11509 (region-start (and regionp (region-beginning)))
11510 (region-end (and regionp (region-end)))
11511 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11512 pos it nbuf file re level reversed)
11513 (setq last-command nil)
11514 (when regionp
11515 (goto-char region-start)
11516 (or (bolp) (goto-char (point-at-bol)))
11517 (setq region-start (point))
11518 (unless (or (org-kill-is-subtree-p
11519 (buffer-substring region-start region-end))
11520 (prog1 org-refile-active-region-within-subtree
11521 (let ((s (point-at-eol)))
11522 (org-toggle-heading)
11523 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11524 (user-error "The region is not a (sequence of) subtree(s)")))
11525 (if (equal goto '(16))
11526 (org-refile-goto-last-stored)
11527 (when (or
11528 (and (equal goto 2)
11529 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11530 (prog1
11531 (setq it (list (or org-clock-heading "running clock")
11532 (buffer-file-name
11533 (marker-buffer org-clock-hd-marker))
11535 (marker-position org-clock-hd-marker)))
11536 (setq goto nil)))
11537 (setq it (or rfloc
11538 (let (heading-text)
11539 (save-excursion
11540 (unless goto
11541 (org-back-to-heading t)
11542 (setq heading-text
11543 (nth 4 (org-heading-components))))
11545 (org-refile-get-location
11546 (cond (goto "Goto")
11547 (regionp (concat actionmsg " region to"))
11548 (t (concat actionmsg " subtree \""
11549 heading-text "\" to")))
11550 default-buffer
11551 (and (not (equal '(4) goto))
11552 org-refile-allow-creating-parent-nodes)
11553 goto))))))
11554 (setq file (nth 1 it)
11555 re (nth 2 it)
11556 pos (nth 3 it))
11557 (if (and (not goto)
11559 (equal (buffer-file-name) file)
11560 (if regionp
11561 (and (>= pos region-start)
11562 (<= pos region-end))
11563 (and (>= pos (point))
11564 (< pos (save-excursion
11565 (org-end-of-subtree t t))))))
11566 (error "Cannot refile to position inside the tree or region"))
11568 (setq nbuf (or (find-buffer-visiting file)
11569 (find-file-noselect file)))
11570 (if goto
11571 (progn
11572 (org-pop-to-buffer-same-window nbuf)
11573 (goto-char pos)
11574 (org-show-context 'org-goto))
11575 (if regionp
11576 (progn
11577 (org-kill-new (buffer-substring region-start region-end))
11578 (org-save-markers-in-region region-start region-end))
11579 (org-copy-subtree 1 nil t))
11580 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11581 (find-file-noselect file)))
11582 (setq reversed (org-notes-order-reversed-p))
11583 (save-excursion
11584 (save-restriction
11585 (widen)
11586 (if pos
11587 (progn
11588 (goto-char pos)
11589 (looking-at org-outline-regexp)
11590 (setq level (org-get-valid-level (funcall outline-level) 1))
11591 (goto-char
11592 (if reversed
11593 (or (outline-next-heading) (point-max))
11594 (or (save-excursion (org-get-next-sibling))
11595 (org-end-of-subtree t t)
11596 (point-max)))))
11597 (setq level 1)
11598 (if (not reversed)
11599 (goto-char (point-max))
11600 (goto-char (point-min))
11601 (or (outline-next-heading) (goto-char (point-max)))))
11602 (if (not (bolp)) (newline))
11603 (org-paste-subtree level)
11604 (when org-log-refile
11605 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11606 (unless (eq org-log-refile 'note)
11607 (save-excursion (org-add-log-note))))
11608 (and org-auto-align-tags
11609 (let ((org-loop-over-headlines-in-active-region nil))
11610 (org-set-tags nil t)))
11611 (with-demoted-errors
11612 (bookmark-set "org-refile-last-stored"))
11613 ;; If we are refiling for capture, make sure that the
11614 ;; last-capture pointers point here
11615 (when (org-bound-and-true-p org-refile-for-capture)
11616 (with-demoted-errors
11617 (bookmark-set "org-capture-last-stored-marker"))
11618 (move-marker org-capture-last-stored-marker (point)))
11619 (if (fboundp 'deactivate-mark) (deactivate-mark))
11620 (run-hooks 'org-after-refile-insert-hook))))
11621 (unless org-refile-keep
11622 (if regionp
11623 (delete-region (point) (+ (point) (- region-end region-start)))
11624 (delete-region
11625 (and (org-back-to-heading t) (point))
11626 (min (buffer-size) (org-end-of-subtree t t) (point)))))
11627 (when (featurep 'org-inlinetask)
11628 (org-inlinetask-remove-END-maybe))
11629 (setq org-markers-to-move nil)
11630 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11632 (defun org-refile-goto-last-stored ()
11633 "Go to the location where the last refile was stored."
11634 (interactive)
11635 (bookmark-jump "org-refile-last-stored")
11636 (message "This is the location of the last refile"))
11638 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11639 no-exclude)
11640 "Prompt the user for a refile location, using PROMPT.
11641 PROMPT should not be suffixed with a colon and a space, because
11642 this function appends the default value from
11643 `org-refile-history' automatically, if that is not empty.
11644 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11645 this is used for the GOTO interface."
11646 (let ((org-refile-targets org-refile-targets)
11647 (org-refile-use-outline-path org-refile-use-outline-path)
11648 excluded-entries)
11649 (when (and (derived-mode-p 'org-mode)
11650 (not org-refile-use-cache)
11651 (not no-exclude))
11652 (org-map-tree
11653 (lambda()
11654 (setq excluded-entries
11655 (append excluded-entries (list (org-get-heading t t)))))))
11656 (setq org-refile-target-table
11657 (org-refile-get-targets default-buffer excluded-entries)))
11658 (unless org-refile-target-table
11659 (user-error "No refile targets"))
11660 (let* ((cbuf (current-buffer))
11661 (partial-completion-mode nil)
11662 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11663 (cfunc (if (and org-refile-use-outline-path
11664 org-outline-path-complete-in-steps)
11665 'org-olpath-completing-read
11666 'org-icompleting-read))
11667 (extra (if org-refile-use-outline-path "/" ""))
11668 (cbnex (concat (buffer-name) extra))
11669 (filename (and cfn (expand-file-name cfn)))
11670 (tbl (mapcar
11671 (lambda (x)
11672 (if (and (not (member org-refile-use-outline-path
11673 '(file full-file-path)))
11674 (not (equal filename (nth 1 x))))
11675 (cons (concat (car x) extra " ("
11676 (file-name-nondirectory (nth 1 x)) ")")
11677 (cdr x))
11678 (cons (concat (car x) extra) (cdr x))))
11679 org-refile-target-table))
11680 (completion-ignore-case t)
11681 cdef
11682 (prompt (concat prompt
11683 (or (and (car org-refile-history)
11684 (concat " (default " (car org-refile-history) ")"))
11685 (and (assoc cbnex tbl) (setq cdef cbnex)
11686 (concat " (default " cbnex ")"))) ": "))
11687 pa answ parent-target child parent old-hist)
11688 (setq old-hist org-refile-history)
11689 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11690 nil 'org-refile-history (or cdef (car org-refile-history))))
11691 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11692 (org-refile-check-position pa)
11693 (if pa
11694 (progn
11695 (when (or (not org-refile-history)
11696 (not (eq old-hist org-refile-history))
11697 (not (equal (car pa) (car org-refile-history))))
11698 (setq org-refile-history
11699 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11700 org-refile-history
11701 (cdr org-refile-history))))
11702 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11703 (pop org-refile-history)))
11705 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11706 (progn
11707 (setq parent (match-string 1 answ)
11708 child (match-string 2 answ))
11709 (setq parent-target (or (assoc parent tbl)
11710 (assoc (concat parent "/") tbl)))
11711 (when (and parent-target
11712 (or (eq new-nodes t)
11713 (and (eq new-nodes 'confirm)
11714 (y-or-n-p (format "Create new node \"%s\"? "
11715 child)))))
11716 (org-refile-new-child parent-target child)))
11717 (user-error "Invalid target location")))))
11719 (declare-function org-string-nw-p "org-macs" (s))
11720 (defun org-refile-check-position (refile-pointer)
11721 "Check if the refile pointer matches the headline to which it points."
11722 (let* ((file (nth 1 refile-pointer))
11723 (re (nth 2 refile-pointer))
11724 (pos (nth 3 refile-pointer))
11725 buffer)
11726 (if (and (not (markerp pos)) (not file))
11727 (user-error "Please save the buffer to a file before refiling")
11728 (when (org-string-nw-p re)
11729 (setq buffer (if (markerp pos)
11730 (marker-buffer pos)
11731 (or (find-buffer-visiting file)
11732 (find-file-noselect file))))
11733 (with-current-buffer buffer
11734 (save-excursion
11735 (save-restriction
11736 (widen)
11737 (goto-char pos)
11738 (beginning-of-line 1)
11739 (unless (org-looking-at-p re)
11740 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11742 (defun org-refile-new-child (parent-target child)
11743 "Use refile target PARENT-TARGET to add new CHILD below it."
11744 (unless parent-target
11745 (error "Cannot find parent for new node"))
11746 (let ((file (nth 1 parent-target))
11747 (pos (nth 3 parent-target))
11748 level)
11749 (with-current-buffer (or (find-buffer-visiting file)
11750 (find-file-noselect file))
11751 (save-excursion
11752 (save-restriction
11753 (widen)
11754 (if pos
11755 (goto-char pos)
11756 (goto-char (point-max))
11757 (if (not (bolp)) (newline)))
11758 (when (looking-at org-outline-regexp)
11759 (setq level (funcall outline-level))
11760 (org-end-of-subtree t t))
11761 (org-back-over-empty-lines)
11762 (insert "\n" (make-string
11763 (if pos (org-get-valid-level level 1) 1) ?*)
11764 " " child "\n")
11765 (beginning-of-line 0)
11766 (list (concat (car parent-target) "/" child) file "" (point)))))))
11768 (defun org-olpath-completing-read (prompt collection &rest args)
11769 "Read an outline path like a file name."
11770 (let ((thetable collection)
11771 (org-completion-use-ido nil) ; does not work with ido.
11772 (org-completion-use-iswitchb nil)) ; or iswitchb
11773 (apply
11774 'org-icompleting-read prompt
11775 (lambda (string predicate &optional flag)
11776 (let (rtn r f (l (length string)))
11777 (cond
11778 ((eq flag nil)
11779 ;; try completion
11780 (try-completion string thetable))
11781 ((eq flag t)
11782 ;; all-completions
11783 (setq rtn (all-completions string thetable predicate))
11784 (mapcar
11785 (lambda (x)
11786 (setq r (substring x l))
11787 (if (string-match " ([^)]*)$" x)
11788 (setq f (match-string 0 x))
11789 (setq f ""))
11790 (if (string-match "/" r)
11791 (concat string (substring r 0 (match-end 0)) f)
11793 rtn))
11794 ((eq flag 'lambda)
11795 ;; exact match?
11796 (assoc string thetable)))))
11797 args)))
11799 ;;;; Dynamic blocks
11801 (defun org-find-dblock (name)
11802 "Find the first dynamic block with name NAME in the buffer.
11803 If not found, stay at current position and return nil."
11804 (let ((case-fold-search t) pos)
11805 (save-excursion
11806 (goto-char (point-min))
11807 (setq pos (and (re-search-forward
11808 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11809 (match-beginning 0))))
11810 (if pos (goto-char pos))
11811 pos))
11813 (defconst org-dblock-start-re
11814 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11815 "Matches the start line of a dynamic block, with parameters.")
11817 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11818 "Matches the end of a dynamic block.")
11820 (defun org-create-dblock (plist)
11821 "Create a dynamic block section, with parameters taken from PLIST.
11822 PLIST must contain a :name entry which is used as name of the block."
11823 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11824 (end-of-line 1)
11825 (newline))
11826 (let ((col (current-column))
11827 (name (plist-get plist :name)))
11828 (insert "#+BEGIN: " name)
11829 (while plist
11830 (if (eq (car plist) :name)
11831 (setq plist (cddr plist))
11832 (insert " " (prin1-to-string (pop plist)))))
11833 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11834 (beginning-of-line -2)))
11836 (defun org-prepare-dblock ()
11837 "Prepare dynamic block for refresh.
11838 This empties the block, puts the cursor at the insert position and returns
11839 the property list including an extra property :name with the block name."
11840 (unless (looking-at org-dblock-start-re)
11841 (user-error "Not at a dynamic block"))
11842 (let* ((begdel (1+ (match-end 0)))
11843 (name (org-no-properties (match-string 1)))
11844 (params (append (list :name name)
11845 (read (concat "(" (match-string 3) ")")))))
11846 (save-excursion
11847 (beginning-of-line 1)
11848 (skip-chars-forward " \t")
11849 (setq params (plist-put params :indentation-column (current-column))))
11850 (unless (re-search-forward org-dblock-end-re nil t)
11851 (error "Dynamic block not terminated"))
11852 (setq params
11853 (append params
11854 (list :content (buffer-substring
11855 begdel (match-beginning 0)))))
11856 (delete-region begdel (match-beginning 0))
11857 (goto-char begdel)
11858 (open-line 1)
11859 params))
11861 (defun org-map-dblocks (&optional command)
11862 "Apply COMMAND to all dynamic blocks in the current buffer.
11863 If COMMAND is not given, use `org-update-dblock'."
11864 (let ((cmd (or command 'org-update-dblock)))
11865 (save-excursion
11866 (goto-char (point-min))
11867 (while (re-search-forward org-dblock-start-re nil t)
11868 (goto-char (match-beginning 0))
11869 (save-excursion
11870 (condition-case nil
11871 (funcall cmd)
11872 (error (message "Error during update of dynamic block"))))
11873 (unless (re-search-forward org-dblock-end-re nil t)
11874 (error "Dynamic block not terminated"))))))
11876 (defun org-dblock-update (&optional arg)
11877 "User command for updating dynamic blocks.
11878 Update the dynamic block at point. With prefix ARG, update all dynamic
11879 blocks in the buffer."
11880 (interactive "P")
11881 (if arg
11882 (org-update-all-dblocks)
11883 (or (looking-at org-dblock-start-re)
11884 (org-beginning-of-dblock))
11885 (org-update-dblock)))
11887 (defun org-update-dblock ()
11888 "Update the dynamic block at point.
11889 This means to empty the block, parse for parameters and then call
11890 the correct writing function."
11891 (interactive)
11892 (save-window-excursion
11893 (let* ((pos (point))
11894 (line (org-current-line))
11895 (params (org-prepare-dblock))
11896 (name (plist-get params :name))
11897 (indent (plist-get params :indentation-column))
11898 (cmd (intern (concat "org-dblock-write:" name))))
11899 (message "Updating dynamic block `%s' at line %d..." name line)
11900 (funcall cmd params)
11901 (message "Updating dynamic block `%s' at line %d...done" name line)
11902 (goto-char pos)
11903 (when (and indent (> indent 0))
11904 (setq indent (make-string indent ?\ ))
11905 (save-excursion
11906 (org-beginning-of-dblock)
11907 (forward-line 1)
11908 (while (not (looking-at org-dblock-end-re))
11909 (insert indent)
11910 (beginning-of-line 2))
11911 (when (looking-at org-dblock-end-re)
11912 (and (looking-at "[ \t]+")
11913 (replace-match ""))
11914 (insert indent)))))))
11916 (defun org-beginning-of-dblock ()
11917 "Find the beginning of the dynamic block at point.
11918 Error if there is no such block at point."
11919 (let ((pos (point))
11920 beg)
11921 (end-of-line 1)
11922 (if (and (re-search-backward org-dblock-start-re nil t)
11923 (setq beg (match-beginning 0))
11924 (re-search-forward org-dblock-end-re nil t)
11925 (> (match-end 0) pos))
11926 (goto-char beg)
11927 (goto-char pos)
11928 (error "Not in a dynamic block"))))
11930 (defun org-update-all-dblocks ()
11931 "Update all dynamic blocks in the buffer.
11932 This function can be used in a hook."
11933 (interactive)
11934 (when (derived-mode-p 'org-mode)
11935 (org-map-dblocks 'org-update-dblock)))
11938 ;;;; Completion
11940 (defun org-get-export-keywords ()
11941 "Return a list of all currently understood export keywords.
11942 Export keywords include options, block names, attributes and
11943 keywords relative to each registered export back-end."
11944 (delq nil
11945 (let (keywords)
11946 (mapc
11947 (lambda (back-end)
11948 (let ((props (cdr back-end)))
11949 ;; Back-end name (for keywords, like #+LATEX:)
11950 (push (upcase (symbol-name (car back-end))) keywords)
11951 ;; Back-end options.
11952 (mapc (lambda (option) (push (cadr option) keywords))
11953 (plist-get (cdr back-end) :options-alist))))
11954 (org-bound-and-true-p org-export-registered-backends))
11955 keywords)))
11957 (defconst org-options-keywords
11958 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11959 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11960 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11961 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11962 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11964 (defcustom org-structure-template-alist
11965 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11966 "<src lang=\"?\">\n\n</src>")
11967 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11968 "<example>\n?\n</example>")
11969 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11970 "<quote>\n?\n</quote>")
11971 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11972 "<verse>\n?\n</verse>")
11973 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11974 "<verbatim>\n?\n</verbatim>")
11975 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11976 "<center>\n?\n</center>")
11977 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11978 "<literal style=\"latex\">\n?\n</literal>")
11979 ("L" "#+LaTeX: "
11980 "<literal style=\"latex\">?</literal>")
11981 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11982 "<literal style=\"html\">\n?\n</literal>")
11983 ("H" "#+HTML: "
11984 "<literal style=\"html\">?</literal>")
11985 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11986 ("A" "#+ASCII: ")
11987 ("i" "#+INDEX: ?"
11988 "#+INDEX: ?")
11989 ("I" "#+INCLUDE: %file ?"
11990 "<include file=%file markup=\"?\">"))
11991 "Structure completion elements.
11992 This is a list of abbreviation keys and values. The value gets inserted
11993 if you type `<' followed by the key and then press the completion key,
11994 usually `M-TAB'. %file will be replaced by a file name after prompting
11995 for the file using completion. The cursor will be placed at the position
11996 of the `?` in the template.
11997 There are two templates for each key, the first uses the original Org syntax,
11998 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11999 the default when the /org-mtags.el/ module has been loaded. See also the
12000 variable `org-mtags-prefer-muse-templates'."
12001 :group 'org-completion
12002 :type '(repeat
12003 (string :tag "Key")
12004 (string :tag "Template")
12005 (string :tag "Muse Template")))
12007 (defun org-try-structure-completion ()
12008 "Try to complete a structure template before point.
12009 This looks for strings like \"<e\" on an otherwise empty line and
12010 expands them."
12011 (let ((l (buffer-substring (point-at-bol) (point)))
12013 (when (and (looking-at "[ \t]*$")
12014 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12015 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12016 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12017 (match-beginning 1)) a)
12018 t)))
12020 (defun org-complete-expand-structure-template (start cell)
12021 "Expand a structure template."
12022 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12023 (rpl (nth (if musep 2 1) cell))
12024 (ind ""))
12025 (delete-region start (point))
12026 (when (string-match "\\`#\\+" rpl)
12027 (cond
12028 ((bolp))
12029 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12030 (setq ind (buffer-substring (point-at-bol) (point))))
12031 (t (newline))))
12032 (setq start (point))
12033 (if (string-match "%file" rpl)
12034 (setq rpl (replace-match
12035 (concat
12036 "\""
12037 (save-match-data
12038 (abbreviate-file-name (read-file-name "Include file: ")))
12039 "\"")
12040 t t rpl)))
12041 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12042 (concat "\n" ind)))
12043 (insert rpl)
12044 (if (re-search-backward "\\?" start t) (delete-char 1))))
12046 ;;;; TODO, DEADLINE, Comments
12048 (defun org-toggle-comment ()
12049 "Change the COMMENT state of an entry."
12050 (interactive)
12051 (save-excursion
12052 (org-back-to-heading)
12053 (let (case-fold-search)
12054 (cond
12055 ((looking-at (format org-heading-keyword-regexp-format
12056 org-comment-string))
12057 (goto-char (match-end 1))
12058 (looking-at (concat " +" org-comment-string))
12059 (replace-match "" t t)
12060 (when (eolp) (insert " ")))
12061 ((looking-at org-outline-regexp)
12062 (goto-char (match-end 0))
12063 (insert org-comment-string " "))))))
12065 (defvar org-last-todo-state-is-todo nil
12066 "This is non-nil when the last TODO state change led to a TODO state.
12067 If the last change removed the TODO tag or switched to DONE, then
12068 this is nil.")
12070 (defvar org-setting-tags nil) ; dynamically skipped
12072 (defvar org-todo-setup-filter-hook nil
12073 "Hook for functions that pre-filter todo specs.
12074 Each function takes a todo spec and returns either nil or the spec
12075 transformed into canonical form." )
12077 (defvar org-todo-get-default-hook nil
12078 "Hook for functions that get a default item for todo.
12079 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12080 nil or a string to be used for the todo mark." )
12082 (defvar org-agenda-headline-snapshot-before-repeat)
12084 (defun org-current-effective-time ()
12085 "Return current time adjusted for `org-extend-today-until' variable."
12086 (let* ((ct (org-current-time))
12087 (dct (decode-time ct))
12088 (ct1
12089 (cond
12090 (org-use-last-clock-out-time-as-effective-time
12091 (or (org-clock-get-last-clock-out-time) ct))
12092 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12093 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12094 (t ct))))
12095 ct1))
12097 (defun org-todo-yesterday (&optional arg)
12098 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12099 (interactive "P")
12100 (if (eq major-mode 'org-agenda-mode)
12101 (apply 'org-agenda-todo-yesterday arg)
12102 (let* ((hour (third (decode-time
12103 (org-current-time))))
12104 (org-extend-today-until (1+ hour)))
12105 (org-todo arg))))
12107 (defvar org-block-entry-blocking ""
12108 "First entry preventing the TODO state change.")
12110 (defun org-todo (&optional arg)
12111 "Change the TODO state of an item.
12112 The state of an item is given by a keyword at the start of the heading,
12113 like
12114 *** TODO Write paper
12115 *** DONE Call mom
12117 The different keywords are specified in the variable `org-todo-keywords'.
12118 By default the available states are \"TODO\" and \"DONE\".
12119 So for this example: when the item starts with TODO, it is changed to DONE.
12120 When it starts with DONE, the DONE is removed. And when neither TODO nor
12121 DONE are present, add TODO at the beginning of the heading.
12123 With \\[universal-argument] prefix arg, use completion to determine the new \
12124 state.
12125 With numeric prefix arg, switch to that state.
12126 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12127 keywords (nextset).
12128 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12129 With a numeric prefix arg of 0, inhibit note taking for the change.
12131 For calling through lisp, arg is also interpreted in the following way:
12132 'none -> empty state
12133 \"\"(empty string) -> switch to empty state
12134 'done -> switch to DONE
12135 'nextset -> switch to the next set of keywords
12136 'previousset -> switch to the previous set of keywords
12137 \"WAITING\" -> switch to the specified keyword, but only if it
12138 really is a member of `org-todo-keywords'."
12139 (interactive "P")
12140 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12141 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12142 'region-start-level 'region))
12143 org-loop-over-headlines-in-active-region)
12144 (org-map-entries
12145 `(org-todo ,arg)
12146 org-loop-over-headlines-in-active-region
12147 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12148 (if (equal arg '(16)) (setq arg 'nextset))
12149 (let ((org-blocker-hook org-blocker-hook)
12150 commentp
12151 case-fold-search)
12152 (when (equal arg '(64))
12153 (setq arg nil org-blocker-hook nil))
12154 (when (and org-blocker-hook
12155 (or org-inhibit-blocking
12156 (org-entry-get nil "NOBLOCKING")))
12157 (setq org-blocker-hook nil))
12158 (save-excursion
12159 (catch 'exit
12160 (org-back-to-heading t)
12161 (when (looking-at (concat "^\\*+ " org-comment-string))
12162 (org-toggle-comment)
12163 (setq commentp t))
12164 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12165 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12166 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12167 (let* ((match-data (match-data))
12168 (startpos (point-at-bol))
12169 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12170 (org-log-done org-log-done)
12171 (org-log-repeat org-log-repeat)
12172 (org-todo-log-states org-todo-log-states)
12173 (org-inhibit-logging
12174 (if (equal arg 0)
12175 (progn (setq arg nil) 'note) org-inhibit-logging))
12176 (this (match-string 1))
12177 (hl-pos (match-beginning 0))
12178 (head (org-get-todo-sequence-head this))
12179 (ass (assoc head org-todo-kwd-alist))
12180 (interpret (nth 1 ass))
12181 (done-word (nth 3 ass))
12182 (final-done-word (nth 4 ass))
12183 (org-last-state (or this ""))
12184 (completion-ignore-case t)
12185 (member (member this org-todo-keywords-1))
12186 (tail (cdr member))
12187 (org-state (cond
12188 ((and org-todo-key-trigger
12189 (or (and (equal arg '(4))
12190 (eq org-use-fast-todo-selection 'prefix))
12191 (and (not arg) org-use-fast-todo-selection
12192 (not (eq org-use-fast-todo-selection
12193 'prefix)))))
12194 ;; Use fast selection
12195 (org-fast-todo-selection))
12196 ((and (equal arg '(4))
12197 (or (not org-use-fast-todo-selection)
12198 (not org-todo-key-trigger)))
12199 ;; Read a state with completion
12200 (org-icompleting-read
12201 "State: " (mapcar 'list org-todo-keywords-1)
12202 nil t))
12203 ((eq arg 'right)
12204 (if this
12205 (if tail (car tail) nil)
12206 (car org-todo-keywords-1)))
12207 ((eq arg 'left)
12208 (if (equal member org-todo-keywords-1)
12210 (if this
12211 (nth (- (length org-todo-keywords-1)
12212 (length tail) 2)
12213 org-todo-keywords-1)
12214 (org-last org-todo-keywords-1))))
12215 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12216 (setq arg nil))) ; hack to fall back to cycling
12217 (arg
12218 ;; user or caller requests a specific state
12219 (cond
12220 ((equal arg "") nil)
12221 ((eq arg 'none) nil)
12222 ((eq arg 'done) (or done-word (car org-done-keywords)))
12223 ((eq arg 'nextset)
12224 (or (car (cdr (member head org-todo-heads)))
12225 (car org-todo-heads)))
12226 ((eq arg 'previousset)
12227 (let ((org-todo-heads (reverse org-todo-heads)))
12228 (or (car (cdr (member head org-todo-heads)))
12229 (car org-todo-heads))))
12230 ((car (member arg org-todo-keywords-1)))
12231 ((stringp arg)
12232 (user-error "State `%s' not valid in this file" arg))
12233 ((nth (1- (prefix-numeric-value arg))
12234 org-todo-keywords-1))))
12235 ((null member) (or head (car org-todo-keywords-1)))
12236 ((equal this final-done-word) nil) ;; -> make empty
12237 ((null tail) nil) ;; -> first entry
12238 ((memq interpret '(type priority))
12239 (if (eq this-command last-command)
12240 (car tail)
12241 (if (> (length tail) 0)
12242 (or done-word (car org-done-keywords))
12243 nil)))
12245 (car tail))))
12246 (org-state (or
12247 (run-hook-with-args-until-success
12248 'org-todo-get-default-hook org-state org-last-state)
12249 org-state))
12250 (next (if org-state (concat " " org-state " ") " "))
12251 (change-plist (list :type 'todo-state-change :from this :to org-state
12252 :position startpos))
12253 dolog now-done-p)
12254 (when org-blocker-hook
12255 (setq org-last-todo-state-is-todo
12256 (not (member this org-done-keywords)))
12257 (unless (save-excursion
12258 (save-match-data
12259 (org-with-wide-buffer
12260 (run-hook-with-args-until-failure
12261 'org-blocker-hook change-plist))))
12262 (if (org-called-interactively-p 'interactive)
12263 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12264 this org-state org-block-entry-blocking)
12265 ;; fail silently
12266 (message "TODO state change from %s to %s blocked (by \"%s\")"
12267 this org-state org-block-entry-blocking)
12268 (throw 'exit nil))))
12269 (store-match-data match-data)
12270 (replace-match next t t)
12271 (unless (pos-visible-in-window-p hl-pos)
12272 (message "TODO state changed to %s" (org-trim next)))
12273 (unless head
12274 (setq head (org-get-todo-sequence-head org-state)
12275 ass (assoc head org-todo-kwd-alist)
12276 interpret (nth 1 ass)
12277 done-word (nth 3 ass)
12278 final-done-word (nth 4 ass)))
12279 (when (memq arg '(nextset previousset))
12280 (message "Keyword-Set %d/%d: %s"
12281 (- (length org-todo-sets) -1
12282 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12283 (length org-todo-sets)
12284 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12285 (setq org-last-todo-state-is-todo
12286 (not (member org-state org-done-keywords)))
12287 (setq now-done-p (and (member org-state org-done-keywords)
12288 (not (member this org-done-keywords))))
12289 (and logging (org-local-logging logging))
12290 (when (and (or org-todo-log-states org-log-done)
12291 (not (eq org-inhibit-logging t))
12292 (not (memq arg '(nextset previousset))))
12293 ;; we need to look at recording a time and note
12294 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12295 (nth 2 (assoc this org-todo-log-states))))
12296 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12297 (setq dolog 'time))
12298 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12299 (and org-state
12300 (member org-state org-not-done-keywords)
12301 (not (member this org-not-done-keywords))))
12302 ;; This is now a todo state and was not one before
12303 ;; If there was a CLOSED time stamp, get rid of it.
12304 (org-add-planning-info nil nil 'closed))
12305 (when (and now-done-p org-log-done)
12306 ;; It is now done, and it was not done before
12307 (org-add-planning-info 'closed (org-current-effective-time))
12308 (if (and (not dolog) (eq 'note org-log-done))
12309 (org-add-log-setup 'done org-state this 'findpos 'note)))
12310 (when (and org-state dolog)
12311 ;; This is a non-nil state, and we need to log it
12312 (org-add-log-setup 'state org-state this 'findpos dolog)))
12313 ;; Fixup tag positioning
12314 (org-todo-trigger-tag-changes org-state)
12315 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12316 (when org-provide-todo-statistics
12317 (org-update-parent-todo-statistics))
12318 (run-hooks 'org-after-todo-state-change-hook)
12319 (if (and arg (not (member org-state org-done-keywords)))
12320 (setq head (org-get-todo-sequence-head org-state)))
12321 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12322 ;; Do we need to trigger a repeat?
12323 (when now-done-p
12324 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12325 ;; This is for the agenda, take a snapshot of the headline.
12326 (save-match-data
12327 (setq org-agenda-headline-snapshot-before-repeat
12328 (org-get-heading))))
12329 (org-auto-repeat-maybe org-state))
12330 ;; Fixup cursor location if close to the keyword
12331 (if (and (outline-on-heading-p)
12332 (not (bolp))
12333 (save-excursion (beginning-of-line 1)
12334 (looking-at org-todo-line-regexp))
12335 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12336 (progn
12337 (goto-char (or (match-end 2) (match-end 1)))
12338 (and (looking-at " ") (just-one-space))))
12339 (when org-trigger-hook
12340 (save-excursion
12341 (run-hook-with-args 'org-trigger-hook change-plist)))
12342 (when commentp (org-toggle-comment))))))))
12344 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12345 "Block turning an entry into a TODO, using the hierarchy.
12346 This checks whether the current task should be blocked from state
12347 changes. Such blocking occurs when:
12349 1. The task has children which are not all in a completed state.
12351 2. A task has a parent with the property :ORDERED:, and there
12352 are siblings prior to the current task with incomplete
12353 status.
12355 3. The parent of the task is blocked because it has siblings that should
12356 be done first, or is child of a block grandparent TODO entry."
12358 (if (not org-enforce-todo-dependencies)
12359 t ; if locally turned off don't block
12360 (catch 'dont-block
12361 ;; If this is not a todo state change, or if this entry is already DONE,
12362 ;; do not block
12363 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12364 (member (plist-get change-plist :from)
12365 (cons 'done org-done-keywords))
12366 (member (plist-get change-plist :to)
12367 (cons 'todo org-not-done-keywords))
12368 (not (plist-get change-plist :to)))
12369 (throw 'dont-block t))
12370 ;; If this task has children, and any are undone, it's blocked
12371 (save-excursion
12372 (org-back-to-heading t)
12373 (let ((this-level (funcall outline-level)))
12374 (outline-next-heading)
12375 (let ((child-level (funcall outline-level)))
12376 (while (and (not (eobp))
12377 (> child-level this-level))
12378 ;; this todo has children, check whether they are all
12379 ;; completed
12380 (if (and (not (org-entry-is-done-p))
12381 (org-entry-is-todo-p))
12382 (progn (setq org-block-entry-blocking (org-get-heading))
12383 (throw 'dont-block nil)))
12384 (outline-next-heading)
12385 (setq child-level (funcall outline-level))))))
12386 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12387 ;; any previous siblings are undone, it's blocked
12388 (save-excursion
12389 (org-back-to-heading t)
12390 (let* ((pos (point))
12391 (parent-pos (and (org-up-heading-safe) (point))))
12392 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12393 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12394 (forward-line 1)
12395 (re-search-forward org-not-done-heading-regexp pos t))
12396 (setq org-block-entry-blocking (match-string 0))
12397 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12398 ;; Search further up the hierarchy, to see if an ancestor is blocked
12399 (while t
12400 (goto-char parent-pos)
12401 (if (not (looking-at org-not-done-heading-regexp))
12402 (throw 'dont-block t)) ; do not block, parent is not a TODO
12403 (setq pos (point))
12404 (setq parent-pos (and (org-up-heading-safe) (point)))
12405 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12406 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12407 (forward-line 1)
12408 (re-search-forward org-not-done-heading-regexp pos t)
12409 (setq org-block-entry-blocking (org-get-heading)))
12410 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12412 (defcustom org-track-ordered-property-with-tag nil
12413 "Should the ORDERED property also be shown as a tag?
12414 The ORDERED property decides if an entry should require subtasks to be
12415 completed in sequence. Since a property is not very visible, setting
12416 this option means that toggling the ORDERED property with the command
12417 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12418 not relevant for the behavior, but it makes things more visible.
12420 Note that toggling the tag with tags commands will not change the property
12421 and therefore not influence behavior!
12423 This can be t, meaning the tag ORDERED should be used, It can also be a
12424 string to select a different tag for this task."
12425 :group 'org-todo
12426 :type '(choice
12427 (const :tag "No tracking" nil)
12428 (const :tag "Track with ORDERED tag" t)
12429 (string :tag "Use other tag")))
12431 (defun org-toggle-ordered-property ()
12432 "Toggle the ORDERED property of the current entry.
12433 For better visibility, you can track the value of this property with a tag.
12434 See variable `org-track-ordered-property-with-tag'."
12435 (interactive)
12436 (let* ((t1 org-track-ordered-property-with-tag)
12437 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12438 (save-excursion
12439 (org-back-to-heading)
12440 (if (org-entry-get nil "ORDERED")
12441 (progn
12442 (org-delete-property "ORDERED" "PROPERTIES")
12443 (and tag (org-toggle-tag tag 'off))
12444 (message "Subtasks can be completed in arbitrary order"))
12445 (org-entry-put nil "ORDERED" "t")
12446 (and tag (org-toggle-tag tag 'on))
12447 (message "Subtasks must be completed in sequence")))))
12449 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12450 (defun org-block-todo-from-checkboxes (change-plist)
12451 "Block turning an entry into a TODO, using checkboxes.
12452 This checks whether the current task should be blocked from state
12453 changes because there are unchecked boxes in this entry."
12454 (if (not org-enforce-todo-checkbox-dependencies)
12455 t ; if locally turned off don't block
12456 (catch 'dont-block
12457 ;; If this is not a todo state change, or if this entry is already DONE,
12458 ;; do not block
12459 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12460 (member (plist-get change-plist :from)
12461 (cons 'done org-done-keywords))
12462 (member (plist-get change-plist :to)
12463 (cons 'todo org-not-done-keywords))
12464 (not (plist-get change-plist :to)))
12465 (throw 'dont-block t))
12466 ;; If this task has checkboxes that are not checked, it's blocked
12467 (save-excursion
12468 (org-back-to-heading t)
12469 (let ((beg (point)) end)
12470 (outline-next-heading)
12471 (setq end (point))
12472 (goto-char beg)
12473 (if (org-list-search-forward
12474 (concat (org-item-beginning-re)
12475 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12476 "\\[[- ]\\]")
12477 end t)
12478 (progn
12479 (if (boundp 'org-blocked-by-checkboxes)
12480 (setq org-blocked-by-checkboxes t))
12481 (throw 'dont-block nil)))))
12482 t))) ; do not block
12484 (defun org-entry-blocked-p ()
12485 "Is the current entry blocked?"
12486 (org-with-silent-modifications
12487 (if (org-entry-get nil "NOBLOCKING")
12488 nil ;; Never block this entry
12489 (not (run-hook-with-args-until-failure
12490 'org-blocker-hook
12491 (list :type 'todo-state-change
12492 :position (point)
12493 :from 'todo
12494 :to 'done))))))
12496 (defun org-update-statistics-cookies (all)
12497 "Update the statistics cookie, either from TODO or from checkboxes.
12498 This should be called with the cursor in a line with a statistics cookie."
12499 (interactive "P")
12500 (if all
12501 (progn
12502 (org-update-checkbox-count 'all)
12503 (org-map-entries 'org-update-parent-todo-statistics))
12504 (if (not (org-at-heading-p))
12505 (org-update-checkbox-count)
12506 (let ((pos (point-marker))
12507 end l1 l2)
12508 (ignore-errors (org-back-to-heading t))
12509 (if (not (org-at-heading-p))
12510 (org-update-checkbox-count)
12511 (setq l1 (org-outline-level))
12512 (setq end (save-excursion
12513 (outline-next-heading)
12514 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12515 (point)))
12516 (if (and (save-excursion
12517 (re-search-forward
12518 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12519 (not (save-excursion (re-search-forward
12520 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12521 (org-update-checkbox-count)
12522 (if (and l2 (> l2 l1))
12523 (progn
12524 (goto-char end)
12525 (org-update-parent-todo-statistics))
12526 (goto-char pos)
12527 (beginning-of-line 1)
12528 (while (re-search-forward
12529 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12530 (point-at-eol) t)
12531 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12532 (goto-char pos)
12533 (move-marker pos nil)))))
12535 (defvar org-entry-property-inherited-from) ;; defined below
12536 (defun org-update-parent-todo-statistics ()
12537 "Update any statistics cookie in the parent of the current headline.
12538 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12539 the entire subtree and this will travel up the hierarchy and update
12540 statistics everywhere."
12541 (let* ((prop (save-excursion (org-up-heading-safe)
12542 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12543 (recursive (or (not org-hierarchical-todo-statistics)
12544 (and prop (string-match "\\<recursive\\>" prop))))
12545 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12547 (first t)
12548 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12549 level ltoggle l1 new ndel
12550 (cnt-all 0) (cnt-done 0) is-percent kwd
12551 checkbox-beg ov ovs ove cookie-present)
12552 (catch 'exit
12553 (save-excursion
12554 (beginning-of-line 1)
12555 (setq ltoggle (funcall outline-level))
12556 ;; Three situations are to consider:
12558 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12559 ;; to the top-level ancestor on the headline;
12561 ;; 2. If parent has "recursive" property, repeat up to the
12562 ;; headline setting that property, taking inheritance into
12563 ;; account;
12565 ;; 3. Else, move up to direct parent and proceed only once.
12566 (while (and (setq level (org-up-heading-safe))
12567 (or recursive first)
12568 (>= (point) lim))
12569 (setq first nil cookie-present nil)
12570 (unless (and level
12571 (not (string-match
12572 "\\<checkbox\\>"
12573 (downcase (or (org-entry-get nil "COOKIE_DATA")
12574 "")))))
12575 (throw 'exit nil))
12576 (while (re-search-forward box-re (point-at-eol) t)
12577 (setq cnt-all 0 cnt-done 0 cookie-present t)
12578 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12579 (save-match-data
12580 (unless (outline-next-heading) (throw 'exit nil))
12581 (while (and (looking-at org-complex-heading-regexp)
12582 (> (setq l1 (length (match-string 1))) level))
12583 (setq kwd (and (or recursive (= l1 ltoggle))
12584 (match-string 2)))
12585 (if (or (eq org-provide-todo-statistics 'all-headlines)
12586 (and (listp org-provide-todo-statistics)
12587 (or (member kwd org-provide-todo-statistics)
12588 (member kwd org-done-keywords))))
12589 (setq cnt-all (1+ cnt-all))
12590 (if (eq org-provide-todo-statistics t)
12591 (and kwd (setq cnt-all (1+ cnt-all)))))
12592 (and (member kwd org-done-keywords)
12593 (setq cnt-done (1+ cnt-done)))
12594 (outline-next-heading)))
12595 (setq new
12596 (if is-percent
12597 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12598 (format "[%d/%d]" cnt-done cnt-all))
12599 ndel (- (match-end 0) checkbox-beg))
12600 ;; handle overlays when updating cookie from column view
12601 (when (setq ov (car (overlays-at checkbox-beg)))
12602 (setq ovs (overlay-start ov) ove (overlay-end ov))
12603 (delete-overlay ov))
12604 (goto-char checkbox-beg)
12605 (insert new)
12606 (delete-region (point) (+ (point) ndel))
12607 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12608 (when ov (move-overlay ov ovs ove)))
12609 (when cookie-present
12610 (run-hook-with-args 'org-after-todo-statistics-hook
12611 cnt-done (- cnt-all cnt-done))))))
12612 (run-hooks 'org-todo-statistics-hook)))
12614 (defvar org-after-todo-statistics-hook nil
12615 "Hook that is called after a TODO statistics cookie has been updated.
12616 Each function is called with two arguments: the number of not-done entries
12617 and the number of done entries.
12619 For example, the following function, when added to this hook, will switch
12620 an entry to DONE when all children are done, and back to TODO when new
12621 entries are set to a TODO status. Note that this hook is only called
12622 when there is a statistics cookie in the headline!
12624 (defun org-summary-todo (n-done n-not-done)
12625 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12626 (let (org-log-done org-log-states) ; turn off logging
12627 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12630 (defvar org-todo-statistics-hook nil
12631 "Hook that is run whenever Org thinks TODO statistics should be updated.
12632 This hook runs even if there is no statistics cookie present, in which case
12633 `org-after-todo-statistics-hook' would not run.")
12635 (defun org-todo-trigger-tag-changes (state)
12636 "Apply the changes defined in `org-todo-state-tags-triggers'."
12637 (let ((l org-todo-state-tags-triggers)
12638 changes)
12639 (when (or (not state) (equal state ""))
12640 (setq changes (append changes (cdr (assoc "" l)))))
12641 (when (and (stringp state) (> (length state) 0))
12642 (setq changes (append changes (cdr (assoc state l)))))
12643 (when (member state org-not-done-keywords)
12644 (setq changes (append changes (cdr (assoc 'todo l)))))
12645 (when (member state org-done-keywords)
12646 (setq changes (append changes (cdr (assoc 'done l)))))
12647 (dolist (c changes)
12648 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12650 (defun org-local-logging (value)
12651 "Get logging settings from a property VALUE."
12652 (let* (words w a)
12653 ;; directly set the variables, they are already local.
12654 (setq org-log-done nil
12655 org-log-repeat nil
12656 org-todo-log-states nil)
12657 (setq words (org-split-string value))
12658 (while (setq w (pop words))
12659 (cond
12660 ((setq a (assoc w org-startup-options))
12661 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12662 (set (nth 1 a) (nth 2 a))))
12663 ((setq a (org-extract-log-state-settings w))
12664 (and (member (car a) org-todo-keywords-1)
12665 (push a org-todo-log-states)))))))
12667 (defun org-get-todo-sequence-head (kwd)
12668 "Return the head of the TODO sequence to which KWD belongs.
12669 If KWD is not set, check if there is a text property remembering the
12670 right sequence."
12671 (let (p)
12672 (cond
12673 ((not kwd)
12674 (or (get-text-property (point-at-bol) 'org-todo-head)
12675 (progn
12676 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12677 nil (point-at-eol)))
12678 (get-text-property p 'org-todo-head))))
12679 ((not (member kwd org-todo-keywords-1))
12680 (car org-todo-keywords-1))
12681 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12683 (defun org-fast-todo-selection ()
12684 "Fast TODO keyword selection with single keys.
12685 Returns the new TODO keyword, or nil if no state change should occur."
12686 (let* ((fulltable org-todo-key-alist)
12687 (done-keywords org-done-keywords) ;; needed for the faces.
12688 (maxlen (apply 'max (mapcar
12689 (lambda (x)
12690 (if (stringp (car x)) (string-width (car x)) 0))
12691 fulltable)))
12692 (expert nil)
12693 (fwidth (+ maxlen 3 1 3))
12694 (ncol (/ (- (window-width) 4) fwidth))
12695 tg cnt e c tbl
12696 groups ingroup)
12697 (save-excursion
12698 (save-window-excursion
12699 (if expert
12700 (set-buffer (get-buffer-create " *Org todo*"))
12701 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12702 (erase-buffer)
12703 (org-set-local 'org-done-keywords done-keywords)
12704 (setq tbl fulltable cnt 0)
12705 (while (setq e (pop tbl))
12706 (cond
12707 ((equal e '(:startgroup))
12708 (push '() groups) (setq ingroup t)
12709 (when (not (= cnt 0))
12710 (setq cnt 0)
12711 (insert "\n"))
12712 (insert "{ "))
12713 ((equal e '(:endgroup))
12714 (setq ingroup nil cnt 0)
12715 (insert "}\n"))
12716 ((equal e '(:newline))
12717 (when (not (= cnt 0))
12718 (setq cnt 0)
12719 (insert "\n")
12720 (setq e (car tbl))
12721 (while (equal (car tbl) '(:newline))
12722 (insert "\n")
12723 (setq tbl (cdr tbl)))))
12725 (setq tg (car e) c (cdr e))
12726 (if ingroup (push tg (car groups)))
12727 (setq tg (org-add-props tg nil 'face
12728 (org-get-todo-face tg)))
12729 (if (and (= cnt 0) (not ingroup)) (insert " "))
12730 (insert "[" c "] " tg (make-string
12731 (- fwidth 4 (length tg)) ?\ ))
12732 (when (= (setq cnt (1+ cnt)) ncol)
12733 (insert "\n")
12734 (if ingroup (insert " "))
12735 (setq cnt 0)))))
12736 (insert "\n")
12737 (goto-char (point-min))
12738 (if (not expert) (org-fit-window-to-buffer))
12739 (message "[a-z..]:Set [SPC]:clear")
12740 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12741 (cond
12742 ((or (= c ?\C-g)
12743 (and (= c ?q) (not (rassoc c fulltable))))
12744 (setq quit-flag t))
12745 ((= c ?\ ) nil)
12746 ((setq e (rassoc c fulltable) tg (car e))
12748 (t (setq quit-flag t)))))))
12750 (defun org-entry-is-todo-p ()
12751 (member (org-get-todo-state) org-not-done-keywords))
12753 (defun org-entry-is-done-p ()
12754 (member (org-get-todo-state) org-done-keywords))
12756 (defun org-get-todo-state ()
12757 "Return the TODO keyword of the current subtree."
12758 (save-excursion
12759 (org-back-to-heading t)
12760 (and (looking-at org-todo-line-regexp)
12761 (match-end 2)
12762 (match-string 2))))
12764 (defun org-at-date-range-p (&optional inactive-ok)
12765 "Is the cursor inside a date range?"
12766 (interactive)
12767 (save-excursion
12768 (catch 'exit
12769 (let ((pos (point)))
12770 (skip-chars-backward "^[<\r\n")
12771 (skip-chars-backward "<[")
12772 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12773 (>= (match-end 0) pos)
12774 (throw 'exit t))
12775 (skip-chars-backward "^<[\r\n")
12776 (skip-chars-backward "<[")
12777 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12778 (>= (match-end 0) pos)
12779 (throw 'exit t)))
12780 nil)))
12782 (defun org-get-repeat (&optional tagline)
12783 "Check if there is a deadline/schedule with repeater in this entry."
12784 (save-match-data
12785 (save-excursion
12786 (org-back-to-heading t)
12787 (and (re-search-forward (if tagline
12788 (concat tagline "\\s-*" org-repeat-re)
12789 org-repeat-re)
12790 (org-entry-end-position) t)
12791 (match-string-no-properties 1)))))
12793 (defvar org-last-changed-timestamp)
12794 (defvar org-last-inserted-timestamp)
12795 (defvar org-log-post-message)
12796 (defvar org-log-note-purpose)
12797 (defvar org-log-note-how)
12798 (defvar org-log-note-extra)
12799 (defun org-auto-repeat-maybe (done-word)
12800 "Check if the current headline contains a repeated deadline/schedule.
12801 If yes, set TODO state back to what it was and change the base date
12802 of repeating deadline/scheduled time stamps to new date.
12803 This function is run automatically after each state change to a DONE state."
12804 ;; last-state is dynamically scoped into this function
12805 (let* ((repeat (org-get-repeat))
12806 (aa (assoc org-last-state org-todo-kwd-alist))
12807 (interpret (nth 1 aa))
12808 (head (nth 2 aa))
12809 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12810 (msg "Entry repeats: ")
12811 (org-log-done nil)
12812 (org-todo-log-states nil)
12813 re type n what ts time to-state)
12814 (when repeat
12815 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12816 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12817 org-todo-repeat-to-state))
12818 (unless (and to-state (member to-state org-todo-keywords-1))
12819 (setq to-state (if (eq interpret 'type) org-last-state head)))
12820 (org-todo to-state)
12821 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12822 (org-entry-put nil "LAST_REPEAT" (format-time-string
12823 (org-time-stamp-format t t))))
12824 (when org-log-repeat
12825 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12826 (memq 'org-add-log-note post-command-hook))
12827 ;; OK, we are already setup for some record
12828 (if (eq org-log-repeat 'note)
12829 ;; make sure we take a note, not only a time stamp
12830 (setq org-log-note-how 'note))
12831 ;; Set up for taking a record
12832 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12833 org-last-state
12834 'findpos org-log-repeat)))
12835 (org-back-to-heading t)
12836 (org-add-planning-info nil nil 'closed)
12837 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12838 org-deadline-time-regexp "\\)\\|\\("
12839 org-ts-regexp "\\)"))
12840 (while (re-search-forward
12841 re (save-excursion (outline-next-heading) (point)) t)
12842 (setq type (if (match-end 1) org-scheduled-string
12843 (if (match-end 3) org-deadline-string "Plain:"))
12844 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12845 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12846 (setq n (string-to-number (match-string 2 ts))
12847 what (match-string 3 ts))
12848 (if (equal what "w") (setq n (* n 7) what "d"))
12849 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12850 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12851 ;; Preparation, see if we need to modify the start date for the change
12852 (when (match-end 1)
12853 (setq time (save-match-data (org-time-string-to-time ts)))
12854 (cond
12855 ((equal (match-string 1 ts) ".")
12856 ;; Shift starting date to today
12857 (org-timestamp-change
12858 (- (org-today) (time-to-days time))
12859 'day))
12860 ((equal (match-string 1 ts) "+")
12861 (let ((nshiftmax 10) (nshift 0))
12862 (while (or (= nshift 0)
12863 (<= (time-to-days time)
12864 (time-to-days (current-time))))
12865 (when (= (incf nshift) nshiftmax)
12866 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12867 (error "Abort")))
12868 (org-timestamp-change n (cdr (assoc what whata)))
12869 (org-at-timestamp-p t)
12870 (setq ts (match-string 1))
12871 (setq time (save-match-data (org-time-string-to-time ts)))))
12872 (org-timestamp-change (- n) (cdr (assoc what whata)))
12873 ;; rematch, so that we have everything in place for the real shift
12874 (org-at-timestamp-p t)
12875 (setq ts (match-string 1))
12876 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12877 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12878 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12879 (setq org-log-post-message msg)
12880 (message "%s" msg))))
12882 (defun org-show-todo-tree (arg)
12883 "Make a compact tree which shows all headlines marked with TODO.
12884 The tree will show the lines where the regexp matches, and all higher
12885 headlines above the match.
12886 With a \\[universal-argument] prefix, prompt for a regexp to match.
12887 With a numeric prefix N, construct a sparse tree for the Nth element
12888 of `org-todo-keywords-1'."
12889 (interactive "P")
12890 (let ((case-fold-search nil)
12891 (kwd-re
12892 (cond ((null arg) org-not-done-regexp)
12893 ((equal arg '(4))
12894 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12895 (mapcar 'list org-todo-keywords-1))))
12896 (concat "\\("
12897 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12898 "\\)\\>")))
12899 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12900 (regexp-quote (nth (1- (prefix-numeric-value arg))
12901 org-todo-keywords-1)))
12902 (t (user-error "Invalid prefix argument: %s" arg)))))
12903 (message "%d TODO entries found"
12904 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12906 (defun org-deadline (arg &optional time)
12907 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12908 With one universal prefix argument, remove any deadline from the item.
12909 With two universal prefix arguments, prompt for a warning delay.
12910 With argument TIME, set the deadline at the corresponding date. TIME
12911 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12912 (interactive "P")
12913 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12914 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12915 'region-start-level 'region))
12916 org-loop-over-headlines-in-active-region)
12917 (org-map-entries
12918 `(org-deadline ',arg ,time)
12919 org-loop-over-headlines-in-active-region
12920 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12921 (let* ((old-date (org-entry-get nil "DEADLINE"))
12922 (old-date-time (if old-date (org-time-string-to-time old-date)))
12923 (repeater (and old-date
12924 (string-match
12925 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12926 old-date)
12927 (match-string 1 old-date))))
12928 (cond
12929 ((equal arg '(4))
12930 (when (and old-date org-log-redeadline)
12931 (org-add-log-setup 'deldeadline nil old-date 'findpos
12932 org-log-redeadline))
12933 (org-remove-timestamp-with-keyword org-deadline-string)
12934 (message "Item no longer has a deadline."))
12935 ((equal arg '(16))
12936 (save-excursion
12937 (if (re-search-forward
12938 org-deadline-time-regexp
12939 (save-excursion (outline-next-heading) (point)) t)
12940 (let* ((rpl0 (match-string 1))
12941 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12942 (replace-match
12943 (concat org-deadline-string
12944 " <" rpl
12945 (format " -%dd"
12946 (abs
12947 (- (time-to-days
12948 (save-match-data
12949 (org-read-date nil t nil "Warn starting from" old-date-time)))
12950 (time-to-days old-date-time))))
12951 ">") t t))
12952 (user-error "No deadline information to update"))))
12954 (org-add-planning-info 'deadline time 'closed)
12955 (when (and old-date org-log-redeadline
12956 (not (equal old-date
12957 (substring org-last-inserted-timestamp 1 -1))))
12958 (org-add-log-setup 'redeadline nil old-date 'findpos
12959 org-log-redeadline))
12960 (when repeater
12961 (save-excursion
12962 (org-back-to-heading t)
12963 (when (re-search-forward (concat org-deadline-string " "
12964 org-last-inserted-timestamp)
12965 (save-excursion
12966 (outline-next-heading) (point)) t)
12967 (goto-char (1- (match-end 0)))
12968 (insert " " repeater)
12969 (setq org-last-inserted-timestamp
12970 (concat (substring org-last-inserted-timestamp 0 -1)
12971 " " repeater
12972 (substring org-last-inserted-timestamp -1))))))
12973 (message "Deadline on %s" org-last-inserted-timestamp))))))
12975 (defun org-schedule (arg &optional time)
12976 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12977 With one universal prefix argument, remove any scheduling date from the item.
12978 With two universal prefix arguments, prompt for a delay cookie.
12979 With argument TIME, scheduled at the corresponding date. TIME can
12980 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12981 (interactive "P")
12982 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12983 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12984 'region-start-level 'region))
12985 org-loop-over-headlines-in-active-region)
12986 (org-map-entries
12987 `(org-schedule ',arg ,time)
12988 org-loop-over-headlines-in-active-region
12989 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12990 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12991 (old-date-time (if old-date (org-time-string-to-time old-date)))
12992 (repeater (and old-date
12993 (string-match
12994 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12995 old-date)
12996 (match-string 1 old-date))))
12997 (cond
12998 ((equal arg '(4))
12999 (progn
13000 (when (and old-date org-log-reschedule)
13001 (org-add-log-setup 'delschedule nil old-date 'findpos
13002 org-log-reschedule))
13003 (org-remove-timestamp-with-keyword org-scheduled-string)
13004 (message "Item is no longer scheduled.")))
13005 ((equal arg '(16))
13006 (save-excursion
13007 (if (re-search-forward
13008 org-scheduled-time-regexp
13009 (save-excursion (outline-next-heading) (point)) t)
13010 (let* ((rpl0 (match-string 1))
13011 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13012 (replace-match
13013 (concat org-scheduled-string
13014 " <" rpl
13015 (format " -%dd"
13016 (abs
13017 (- (time-to-days
13018 (save-match-data
13019 (org-read-date nil t nil "Delay until" old-date-time)))
13020 (time-to-days old-date-time))))
13021 ">") t t))
13022 (user-error "No scheduled information to update"))))
13024 (org-add-planning-info 'scheduled time 'closed)
13025 (when (and old-date org-log-reschedule
13026 (not (equal old-date
13027 (substring org-last-inserted-timestamp 1 -1))))
13028 (org-add-log-setup 'reschedule nil old-date 'findpos
13029 org-log-reschedule))
13030 (when repeater
13031 (save-excursion
13032 (org-back-to-heading t)
13033 (when (re-search-forward (concat org-scheduled-string " "
13034 org-last-inserted-timestamp)
13035 (save-excursion
13036 (outline-next-heading) (point)) t)
13037 (goto-char (1- (match-end 0)))
13038 (insert " " repeater)
13039 (setq org-last-inserted-timestamp
13040 (concat (substring org-last-inserted-timestamp 0 -1)
13041 " " repeater
13042 (substring org-last-inserted-timestamp -1))))))
13043 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13045 (defun org-get-scheduled-time (pom &optional inherit)
13046 "Get the scheduled time as a time tuple, of a format suitable
13047 for calling org-schedule with, or if there is no scheduling,
13048 returns nil."
13049 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13050 (when time
13051 (apply 'encode-time (org-parse-time-string time)))))
13053 (defun org-get-deadline-time (pom &optional inherit)
13054 "Get the deadline as a time tuple, of a format suitable for
13055 calling org-deadline with, or if there is no scheduling, returns
13056 nil."
13057 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13058 (when time
13059 (apply 'encode-time (org-parse-time-string time)))))
13061 (defun org-remove-timestamp-with-keyword (keyword)
13062 "Remove all time stamps with KEYWORD in the current entry."
13063 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13064 beg)
13065 (save-excursion
13066 (org-back-to-heading t)
13067 (setq beg (point))
13068 (outline-next-heading)
13069 (while (re-search-backward re beg t)
13070 (replace-match "")
13071 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13072 (equal (char-before) ?\ ))
13073 (backward-delete-char 1)
13074 (if (string-match "^[ \t]*$" (buffer-substring
13075 (point-at-bol) (point-at-eol)))
13076 (delete-region (point-at-bol)
13077 (min (point-max) (1+ (point-at-eol))))))))))
13079 (defun org-add-planning-info (what &optional time &rest remove)
13080 "Insert new timestamp with keyword in the line directly after the headline.
13081 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13082 If non is given, the user is prompted for a date.
13083 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13084 be removed."
13085 (interactive)
13086 (let (org-time-was-given org-end-time-was-given ts
13087 end default-time default-input)
13089 (catch 'exit
13090 (when (and (memq what '(scheduled deadline))
13091 (or (not time)
13092 (and (stringp time)
13093 (string-match "^[-+]+[0-9]" time))))
13094 ;; Try to get a default date/time from existing timestamp
13095 (save-excursion
13096 (org-back-to-heading t)
13097 (setq end (save-excursion (outline-next-heading) (point)))
13098 (when (re-search-forward (if (eq what 'scheduled)
13099 org-scheduled-time-regexp
13100 org-deadline-time-regexp)
13101 end t)
13102 (setq ts (match-string 1)
13103 default-time
13104 (apply 'encode-time (org-parse-time-string ts))
13105 default-input (and ts (org-get-compact-tod ts))))))
13106 (when what
13107 (setq time
13108 (if (stringp time)
13109 ;; This is a string (relative or absolute), set proper date
13110 (apply 'encode-time
13111 (org-read-date-analyze
13112 time default-time (decode-time default-time)))
13113 ;; If necessary, get the time from the user
13114 (or time (org-read-date nil 'to-time nil nil
13115 default-time default-input)))))
13117 (when (and org-insert-labeled-timestamps-at-point
13118 (member what '(scheduled deadline)))
13119 (insert
13120 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13121 (org-insert-time-stamp time org-time-was-given
13122 nil nil nil (list org-end-time-was-given))
13123 (setq what nil))
13124 (save-excursion
13125 (save-restriction
13126 (let (col list elt ts buffer-invisibility-spec)
13127 (org-back-to-heading t)
13128 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13129 (goto-char (match-end 1))
13130 (setq col (current-column))
13131 (goto-char (match-end 0))
13132 (if (eobp) (insert "\n") (forward-char 1))
13133 (when (and (not what)
13134 (not (looking-at
13135 (concat "[ \t]*"
13136 org-keyword-time-not-clock-regexp))))
13137 ;; Nothing to add, nothing to remove...... :-)
13138 (throw 'exit nil))
13139 (if (and (not (looking-at org-outline-regexp))
13140 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13141 "[^\r\n]*"))
13142 (not (equal (match-string 1) org-clock-string)))
13143 (narrow-to-region (match-beginning 0) (match-end 0))
13144 (insert-before-markers "\n")
13145 (backward-char 1)
13146 (narrow-to-region (point) (point))
13147 (and org-adapt-indentation (org-indent-to-column col)))
13148 ;; Check if we have to remove something.
13149 (setq list (cons what remove))
13150 (while list
13151 (setq elt (pop list))
13152 (when (or (and (eq elt 'scheduled)
13153 (re-search-forward org-scheduled-time-regexp nil t))
13154 (and (eq elt 'deadline)
13155 (re-search-forward org-deadline-time-regexp nil t))
13156 (and (eq elt 'closed)
13157 (re-search-forward org-closed-time-regexp nil t)))
13158 (replace-match "")
13159 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13160 (and (looking-at "[ \t]+") (replace-match ""))
13161 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13162 (when what
13163 (insert
13164 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13165 (cond ((eq what 'scheduled) org-scheduled-string)
13166 ((eq what 'deadline) org-deadline-string)
13167 ((eq what 'closed) org-closed-string))
13168 " ")
13169 (setq ts (org-insert-time-stamp
13170 time
13171 (or org-time-was-given
13172 (and (eq what 'closed) org-log-done-with-time))
13173 (eq what 'closed)
13174 nil nil (list org-end-time-was-given)))
13175 (insert
13176 (if (not (or (bolp) (eq (char-before) ?\ )
13177 (memq (char-after) '(32 10))
13178 (eobp))) " " ""))
13179 (end-of-line 1))
13180 (goto-char (point-min))
13181 (widen)
13182 (if (and (looking-at "[ \t]*\n")
13183 (equal (char-before) ?\n))
13184 (delete-region (1- (point)) (point-at-eol)))
13185 ts))))))
13187 (defvar org-log-note-marker (make-marker))
13188 (defvar org-log-note-purpose nil)
13189 (defvar org-log-note-state nil)
13190 (defvar org-log-note-previous-state nil)
13191 (defvar org-log-note-how nil)
13192 (defvar org-log-note-extra nil)
13193 (defvar org-log-note-window-configuration nil)
13194 (defvar org-log-note-return-to (make-marker))
13195 (defvar org-log-note-effective-time nil
13196 "Remembered current time so that dynamically scoped
13197 `org-extend-today-until' affects tha timestamps in state change
13198 log")
13200 (defvar org-log-post-message nil
13201 "Message to be displayed after a log note has been stored.
13202 The auto-repeater uses this.")
13204 (defun org-add-note ()
13205 "Add a note to the current entry.
13206 This is done in the same way as adding a state change note."
13207 (interactive)
13208 (org-add-log-setup 'note nil nil 'findpos nil))
13210 (defvar org-property-end-re)
13211 (defun org-add-log-setup (&optional purpose state prev-state
13212 findpos how extra)
13213 "Set up the post command hook to take a note.
13214 If this is about to TODO state change, the new state is expected in STATE.
13215 When FINDPOS is non-nil, find the correct position for the note in
13216 the current entry. If not, assume that it can be inserted at point.
13217 HOW is an indicator what kind of note should be created.
13218 EXTRA is additional text that will be inserted into the notes buffer."
13219 (let* ((org-log-into-drawer (org-log-into-drawer))
13220 (drawer (cond ((stringp org-log-into-drawer)
13221 org-log-into-drawer)
13222 (org-log-into-drawer "LOGBOOK"))))
13223 (save-restriction
13224 (save-excursion
13225 (when findpos
13226 (org-back-to-heading t)
13227 (narrow-to-region (point) (save-excursion
13228 (outline-next-heading) (point)))
13229 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13230 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13231 "[^\r\n]*\\)?"))
13232 (goto-char (match-end 0))
13233 (cond
13234 (drawer
13235 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13236 nil t)
13237 (progn
13238 (goto-char (match-end 0))
13239 (or org-log-states-order-reversed
13240 (and (re-search-forward org-property-end-re nil t)
13241 (goto-char (1- (match-beginning 0))))))
13242 (insert "\n:" drawer ":\n:END:")
13243 (beginning-of-line 0)
13244 (org-indent-line)
13245 (beginning-of-line 2)
13246 (org-indent-line)
13247 (end-of-line 0)))
13248 ((and org-log-state-notes-insert-after-drawers
13249 (save-excursion
13250 (forward-line) (looking-at org-drawer-regexp)))
13251 (forward-line)
13252 (while (looking-at org-drawer-regexp)
13253 (goto-char (match-end 0))
13254 (re-search-forward org-property-end-re (point-max) t)
13255 (forward-line))
13256 (forward-line -1)))
13257 (unless org-log-states-order-reversed
13258 (and (= (char-after) ?\n) (forward-char 1))
13259 (org-skip-over-state-notes)
13260 (skip-chars-backward " \t\n\r")))
13261 (move-marker org-log-note-marker (point))
13262 (setq org-log-note-purpose purpose
13263 org-log-note-state state
13264 org-log-note-previous-state prev-state
13265 org-log-note-how how
13266 org-log-note-extra extra
13267 org-log-note-effective-time (org-current-effective-time))
13268 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13270 (defun org-skip-over-state-notes ()
13271 "Skip past the list of State notes in an entry."
13272 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13273 (when (ignore-errors (goto-char (org-in-item-p)))
13274 (let* ((struct (org-list-struct))
13275 (prevs (org-list-prevs-alist struct)))
13276 (while (looking-at "[ \t]*- State")
13277 (goto-char (or (org-list-get-next-item (point) struct prevs)
13278 (org-list-get-item-end (point) struct)))))))
13280 (defun org-add-log-note (&optional purpose)
13281 "Pop up a window for taking a note, and add this note later at point."
13282 (remove-hook 'post-command-hook 'org-add-log-note)
13283 (setq org-log-note-window-configuration (current-window-configuration))
13284 (delete-other-windows)
13285 (move-marker org-log-note-return-to (point))
13286 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13287 (goto-char org-log-note-marker)
13288 (org-switch-to-buffer-other-window "*Org Note*")
13289 (erase-buffer)
13290 (if (memq org-log-note-how '(time state))
13291 (let (current-prefix-arg) (org-store-log-note))
13292 (let ((org-inhibit-startup t)) (org-mode))
13293 (insert (format "# Insert note for %s.
13294 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13295 (cond
13296 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13297 ((eq org-log-note-purpose 'done) "closed todo item")
13298 ((eq org-log-note-purpose 'state)
13299 (format "state change from \"%s\" to \"%s\""
13300 (or org-log-note-previous-state "")
13301 (or org-log-note-state "")))
13302 ((eq org-log-note-purpose 'reschedule)
13303 "rescheduling")
13304 ((eq org-log-note-purpose 'delschedule)
13305 "no longer scheduled")
13306 ((eq org-log-note-purpose 'redeadline)
13307 "changing deadline")
13308 ((eq org-log-note-purpose 'deldeadline)
13309 "removing deadline")
13310 ((eq org-log-note-purpose 'refile)
13311 "refiling")
13312 ((eq org-log-note-purpose 'note)
13313 "this entry")
13314 (t (error "This should not happen")))))
13315 (if org-log-note-extra (insert org-log-note-extra))
13316 (org-set-local 'org-finish-function 'org-store-log-note)
13317 (run-hooks 'org-log-buffer-setup-hook)))
13319 (defvar org-note-abort nil) ; dynamically scoped
13320 (defun org-store-log-note ()
13321 "Finish taking a log note, and insert it to where it belongs."
13322 (let ((txt (buffer-string)))
13323 (kill-buffer (current-buffer))
13324 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13325 lines ind bul)
13326 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13327 (setq txt (replace-match "" t t txt)))
13328 (if (string-match "\\s-+\\'" txt)
13329 (setq txt (replace-match "" t t txt)))
13330 (setq lines (org-split-string txt "\n"))
13331 (when (and note (string-match "\\S-" note))
13332 (setq note
13333 (org-replace-escapes
13334 note
13335 (list (cons "%u" (user-login-name))
13336 (cons "%U" user-full-name)
13337 (cons "%t" (format-time-string
13338 (org-time-stamp-format 'long 'inactive)
13339 org-log-note-effective-time))
13340 (cons "%T" (format-time-string
13341 (org-time-stamp-format 'long nil)
13342 org-log-note-effective-time))
13343 (cons "%d" (format-time-string
13344 (org-time-stamp-format nil 'inactive)
13345 org-log-note-effective-time))
13346 (cons "%D" (format-time-string
13347 (org-time-stamp-format nil nil)
13348 org-log-note-effective-time))
13349 (cons "%s" (if org-log-note-state
13350 (concat "\"" org-log-note-state "\"")
13351 ""))
13352 (cons "%S" (if org-log-note-previous-state
13353 (concat "\"" org-log-note-previous-state "\"")
13354 "\"\"")))))
13355 (if lines (setq note (concat note " \\\\")))
13356 (push note lines))
13357 (when (or current-prefix-arg org-note-abort)
13358 (when org-log-into-drawer
13359 (org-remove-empty-drawer-at
13360 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13361 org-log-note-marker))
13362 (setq lines nil))
13363 (when lines
13364 (with-current-buffer (marker-buffer org-log-note-marker)
13365 (save-excursion
13366 (goto-char org-log-note-marker)
13367 (move-marker org-log-note-marker nil)
13368 (end-of-line 1)
13369 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13370 (setq ind (save-excursion
13371 (if (ignore-errors (goto-char (org-in-item-p)))
13372 (let ((struct (org-list-struct)))
13373 (org-list-get-ind
13374 (org-list-get-top-point struct) struct))
13375 (skip-chars-backward " \r\t\n")
13376 (cond
13377 ((and (org-at-heading-p)
13378 org-adapt-indentation)
13379 (1+ (org-current-level)))
13380 ((org-at-heading-p) 0)
13381 (t (org-get-indentation))))))
13382 (setq bul (org-list-bullet-string "-"))
13383 (org-indent-line-to ind)
13384 (insert bul (pop lines))
13385 (let ((ind-body (+ (length bul) ind)))
13386 (while lines
13387 (insert "\n")
13388 (org-indent-line-to ind-body)
13389 (insert (pop lines))))
13390 (message "Note stored")
13391 (org-back-to-heading t)
13392 (org-cycle-hide-drawers 'children))
13393 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13394 ;; from within `org-add-log-note' because `buffer-undo-list'
13395 ;; is then modified outside of `org-with-remote-undo'.
13396 (when (eq this-command 'org-agenda-todo)
13397 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13398 ;; Don't add undo information when called from `org-agenda-todo'
13399 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13400 (set-window-configuration org-log-note-window-configuration)
13401 (with-current-buffer (marker-buffer org-log-note-return-to)
13402 (goto-char org-log-note-return-to))
13403 (move-marker org-log-note-return-to nil)
13404 (and org-log-post-message (message "%s" org-log-post-message))))
13406 (defun org-remove-empty-drawer-at (drawer pos)
13407 "Remove an empty drawer DRAWER at position POS.
13408 POS may also be a marker."
13409 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13410 (save-excursion
13411 (save-restriction
13412 (widen)
13413 (goto-char pos)
13414 (if (org-in-regexp
13415 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13416 (replace-match ""))))))
13418 (defvar org-ts-type nil)
13419 (defun org-sparse-tree (&optional arg type)
13420 "Create a sparse tree, prompt for the details.
13421 This command can create sparse trees. You first need to select the type
13422 of match used to create the tree:
13424 t Show all TODO entries.
13425 T Show entries with a specific TODO keyword.
13426 m Show entries selected by a tags/property match.
13427 p Enter a property name and its value (both with completion on existing
13428 names/values) and show entries with that property.
13429 r Show entries matching a regular expression (`/' can be used as well).
13430 b Show deadlines and scheduled items before a date.
13431 a Show deadlines and scheduled items after a date.
13432 d Show deadlines due within `org-deadline-warning-days'.
13433 D Show deadlines and scheduled items between a date range."
13434 (interactive "P")
13435 (let (ans kwd value ts-type)
13436 (setq type (or type org-sparse-tree-default-date-type))
13437 (setq org-ts-type type)
13438 (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"
13439 (cond ((eq type 'all) "all timestamps")
13440 ((eq type 'scheduled) "only scheduled")
13441 ((eq type 'deadline) "only deadline")
13442 ((eq type 'active) "only active timestamps")
13443 ((eq type 'inactive) "only inactive timestamps")
13444 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13445 ((eq type 'closed) "with a closed time-stamp")
13446 (t "scheduled/deadline")))
13447 (setq ans (read-char-exclusive))
13448 (cond
13449 ((equal ans ?c)
13450 (org-sparse-tree
13451 arg (cadr (member type '(scheduled-or-deadline
13452 all scheduled deadline active inactive closed)))))
13453 ((equal ans ?d)
13454 (call-interactively 'org-check-deadlines))
13455 ((equal ans ?b)
13456 (call-interactively 'org-check-before-date))
13457 ((equal ans ?a)
13458 (call-interactively 'org-check-after-date))
13459 ((equal ans ?D)
13460 (call-interactively 'org-check-dates-range))
13461 ((equal ans ?t)
13462 (call-interactively 'org-show-todo-tree))
13463 ((equal ans ?T)
13464 (org-show-todo-tree '(4)))
13465 ((member ans '(?T ?m))
13466 (call-interactively 'org-match-sparse-tree))
13467 ((member ans '(?p ?P))
13468 (setq kwd (org-icompleting-read "Property: "
13469 (mapcar 'list (org-buffer-property-keys))))
13470 (setq value (org-icompleting-read "Value: "
13471 (mapcar 'list (org-property-values kwd))))
13472 (unless (string-match "\\`{.*}\\'" value)
13473 (setq value (concat "\"" value "\"")))
13474 (org-match-sparse-tree arg (concat kwd "=" value)))
13475 ((member ans '(?r ?R ?/))
13476 (call-interactively 'org-occur))
13477 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13479 (defvar org-occur-highlights nil
13480 "List of overlays used for occur matches.")
13481 (make-variable-buffer-local 'org-occur-highlights)
13482 (defvar org-occur-parameters nil
13483 "Parameters of the active org-occur calls.
13484 This is a list, each call to org-occur pushes as cons cell,
13485 containing the regular expression and the callback, onto the list.
13486 The list can contain several entries if `org-occur' has been called
13487 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13488 will only contain one set of parameters. When the highlights are
13489 removed (for example with `C-c C-c', or with the next edit (depending
13490 on `org-remove-highlights-with-change'), this variable is emptied
13491 as well.")
13492 (make-variable-buffer-local 'org-occur-parameters)
13494 (defun org-occur (regexp &optional keep-previous callback)
13495 "Make a compact tree which shows all matches of REGEXP.
13496 The tree will show the lines where the regexp matches, and all higher
13497 headlines above the match. It will also show the heading after the match,
13498 to make sure editing the matching entry is easy.
13499 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13500 call to `org-occur' will be kept, to allow stacking of calls to this
13501 command.
13502 If CALLBACK is non-nil, it is a function which is called to confirm
13503 that the match should indeed be shown."
13504 (interactive "sRegexp: \nP")
13505 (when (equal regexp "")
13506 (user-error "Regexp cannot be empty"))
13507 (unless keep-previous
13508 (org-remove-occur-highlights nil nil t))
13509 (push (cons regexp callback) org-occur-parameters)
13510 (let ((cnt 0))
13511 (save-excursion
13512 (goto-char (point-min))
13513 (if (or (not keep-previous) ; do not want to keep
13514 (not org-occur-highlights)) ; no previous matches
13515 ;; hide everything
13516 (org-overview))
13517 (while (re-search-forward regexp nil t)
13518 (when (or (not callback)
13519 (save-match-data (funcall callback)))
13520 (setq cnt (1+ cnt))
13521 (when org-highlight-sparse-tree-matches
13522 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13523 (org-show-context 'occur-tree))))
13524 (when org-remove-highlights-with-change
13525 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13526 nil 'local))
13527 (unless org-sparse-tree-open-archived-trees
13528 (org-hide-archived-subtrees (point-min) (point-max)))
13529 (run-hooks 'org-occur-hook)
13530 (if (org-called-interactively-p 'interactive)
13531 (message "%d match(es) for regexp %s" cnt regexp))
13532 cnt))
13534 (defun org-occur-next-match (&optional n reset)
13535 "Function for `next-error-function' to find sparse tree matches.
13536 N is the number of matches to move, when negative move backwards.
13537 RESET is entirely ignored - this function always goes back to the
13538 starting point when no match is found."
13539 (let* ((limit (if (< n 0) (point-min) (point-max)))
13540 (search-func (if (< n 0)
13541 'previous-single-char-property-change
13542 'next-single-char-property-change))
13543 (n (abs n))
13544 (pos (point))
13546 (catch 'exit
13547 (while (setq p1 (funcall search-func (point) 'org-type))
13548 (when (equal p1 limit)
13549 (goto-char pos)
13550 (error "No more matches"))
13551 (when (equal (get-char-property p1 'org-type) 'org-occur)
13552 (setq n (1- n))
13553 (when (= n 0)
13554 (goto-char p1)
13555 (throw 'exit (point))))
13556 (goto-char p1))
13557 (goto-char p1)
13558 (error "No more matches"))))
13560 (defun org-show-context (&optional key)
13561 "Make sure point and context are visible.
13562 How much context is shown depends upon the variables
13563 `org-show-hierarchy-above', `org-show-following-heading',
13564 `org-show-entry-below' and `org-show-siblings'."
13565 (let ((heading-p (org-at-heading-p t))
13566 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13567 (following-p (org-get-alist-option org-show-following-heading key))
13568 (entry-p (org-get-alist-option org-show-entry-below key))
13569 (siblings-p (org-get-alist-option org-show-siblings key)))
13570 ;; Show heading or entry text
13571 (if (and heading-p (not entry-p))
13572 (org-flag-heading nil) ; only show the heading
13573 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13574 (org-show-hidden-entry))) ; show entire entry
13575 (when following-p
13576 ;; Show next sibling, or heading below text
13577 (save-excursion
13578 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13579 (org-flag-heading nil))))
13580 (when siblings-p (org-show-siblings))
13581 (when hierarchy-p
13582 ;; show all higher headings, possibly with siblings
13583 (save-excursion
13584 (while (and (condition-case nil
13585 (progn (org-up-heading-all 1) t)
13586 (error nil))
13587 (not (bobp)))
13588 (org-flag-heading nil)
13589 (when siblings-p (org-show-siblings)))))
13590 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13592 (defvar org-reveal-start-hook nil
13593 "Hook run before revealing a location.")
13595 (defun org-reveal (&optional siblings)
13596 "Show current entry, hierarchy above it, and the following headline.
13597 This can be used to show a consistent set of context around locations
13598 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13599 not t for the search context.
13601 With optional argument SIBLINGS, on each level of the hierarchy all
13602 siblings are shown. This repairs the tree structure to what it would
13603 look like when opened with hierarchical calls to `org-cycle'.
13604 With double optional argument \\[universal-argument] \\[universal-argument], \
13605 go to the parent and show the
13606 entire tree."
13607 (interactive "P")
13608 (run-hooks 'org-reveal-start-hook)
13609 (let ((org-show-hierarchy-above t)
13610 (org-show-following-heading t)
13611 (org-show-siblings (if siblings t org-show-siblings)))
13612 (org-show-context nil))
13613 (when (equal siblings '(16))
13614 (save-excursion
13615 (when (org-up-heading-safe)
13616 (org-show-subtree)
13617 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13619 (defun org-highlight-new-match (beg end)
13620 "Highlight from BEG to END and mark the highlight is an occur headline."
13621 (let ((ov (make-overlay beg end)))
13622 (overlay-put ov 'face 'secondary-selection)
13623 (overlay-put ov 'org-type 'org-occur)
13624 (push ov org-occur-highlights)))
13626 (defun org-remove-occur-highlights (&optional beg end noremove)
13627 "Remove the occur highlights from the buffer.
13628 BEG and END are ignored. If NOREMOVE is nil, remove this function
13629 from the `before-change-functions' in the current buffer."
13630 (interactive)
13631 (unless org-inhibit-highlight-removal
13632 (mapc 'delete-overlay org-occur-highlights)
13633 (setq org-occur-highlights nil)
13634 (setq org-occur-parameters nil)
13635 (unless noremove
13636 (remove-hook 'before-change-functions
13637 'org-remove-occur-highlights 'local))))
13639 ;;;; Priorities
13641 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13642 "Regular expression matching the priority indicator.")
13644 (defvar org-remove-priority-next-time nil)
13646 (defun org-priority-up ()
13647 "Increase the priority of the current item."
13648 (interactive)
13649 (org-priority 'up))
13651 (defun org-priority-down ()
13652 "Decrease the priority of the current item."
13653 (interactive)
13654 (org-priority 'down))
13656 (defun org-priority (&optional action show)
13657 "Change the priority of an item.
13658 ACTION can be `set', `up', `down', or a character."
13659 (interactive "P")
13660 (if (equal action '(4))
13661 (org-show-priority)
13662 (unless org-enable-priority-commands
13663 (user-error "Priority commands are disabled"))
13664 (setq action (or action 'set))
13665 (let (current new news have remove)
13666 (save-excursion
13667 (org-back-to-heading t)
13668 (if (looking-at org-priority-regexp)
13669 (setq current (string-to-char (match-string 2))
13670 have t))
13671 (cond
13672 ((eq action 'remove)
13673 (setq remove t new ?\ ))
13674 ((or (eq action 'set)
13675 (if (featurep 'xemacs) (characterp action) (integerp action)))
13676 (if (not (eq action 'set))
13677 (setq new action)
13678 (message "Priority %c-%c, SPC to remove: "
13679 org-highest-priority org-lowest-priority)
13680 (save-match-data
13681 (setq new (read-char-exclusive))))
13682 (if (and (= (upcase org-highest-priority) org-highest-priority)
13683 (= (upcase org-lowest-priority) org-lowest-priority))
13684 (setq new (upcase new)))
13685 (cond ((equal new ?\ ) (setq remove t))
13686 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13687 (user-error "Priority must be between `%c' and `%c'"
13688 org-highest-priority org-lowest-priority))))
13689 ((eq action 'up)
13690 (setq new (if have
13691 (1- current) ; normal cycling
13692 ;; last priority was empty
13693 (if (eq last-command this-command)
13694 org-lowest-priority ; wrap around empty to lowest
13695 ;; default
13696 (if org-priority-start-cycle-with-default
13697 org-default-priority
13698 (1- org-default-priority))))))
13699 ((eq action 'down)
13700 (setq new (if have
13701 (1+ current) ; normal cycling
13702 ;; last priority was empty
13703 (if (eq last-command this-command)
13704 org-highest-priority ; wrap around empty to highest
13705 ;; default
13706 (if org-priority-start-cycle-with-default
13707 org-default-priority
13708 (1+ org-default-priority))))))
13709 (t (user-error "Invalid action")))
13710 (if (or (< (upcase new) org-highest-priority)
13711 (> (upcase new) org-lowest-priority))
13712 (if (and (memq action '(up down))
13713 (not have) (not (eq last-command this-command)))
13714 ;; `new' is from default priority
13715 (error
13716 "The default can not be set, see `org-default-priority' why")
13717 ;; normal cycling: `new' is beyond highest/lowest priority
13718 ;; and is wrapped around to the empty priority
13719 (setq remove t)))
13720 (setq news (format "%c" new))
13721 (if have
13722 (if remove
13723 (replace-match "" t t nil 1)
13724 (replace-match news t t nil 2))
13725 (if remove
13726 (user-error "No priority cookie found in line")
13727 (let ((case-fold-search nil))
13728 (looking-at org-todo-line-regexp))
13729 (if (match-end 2)
13730 (progn
13731 (goto-char (match-end 2))
13732 (insert " [#" news "]"))
13733 (goto-char (match-beginning 3))
13734 (insert "[#" news "] "))))
13735 (org-preserve-lc (org-set-tags nil 'align)))
13736 (if remove
13737 (message "Priority removed")
13738 (message "Priority of current item set to %s" news)))))
13740 (defun org-show-priority ()
13741 "Show the priority of the current item.
13742 This priority is composed of the main priority given with the [#A] cookies,
13743 and by additional input from the age of a schedules or deadline entry."
13744 (interactive)
13745 (let ((pri (if (eq major-mode 'org-agenda-mode)
13746 (org-get-at-bol 'priority)
13747 (save-excursion
13748 (save-match-data
13749 (beginning-of-line)
13750 (and (looking-at org-heading-regexp)
13751 (org-get-priority (match-string 0))))))))
13752 (message "Priority is %d" (if pri pri -1000))))
13754 (defun org-get-priority (s)
13755 "Find priority cookie and return priority."
13756 (save-match-data
13757 (if (functionp org-get-priority-function)
13758 (funcall org-get-priority-function)
13759 (if (not (string-match org-priority-regexp s))
13760 (* 1000 (- org-lowest-priority org-default-priority))
13761 (* 1000 (- org-lowest-priority
13762 (string-to-char (match-string 2 s))))))))
13764 ;;;; Tags
13766 (defvar org-agenda-archives-mode)
13767 (defvar org-map-continue-from nil
13768 "Position from where mapping should continue.
13769 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13771 (defvar org-scanner-tags nil
13772 "The current tag list while the tags scanner is running.")
13773 (defvar org-trust-scanner-tags nil
13774 "Should `org-get-tags-at' use the tags for the scanner.
13775 This is for internal dynamical scoping only.
13776 When this is non-nil, the function `org-get-tags-at' will return the value
13777 of `org-scanner-tags' instead of building the list by itself. This
13778 can lead to large speed-ups when the tags scanner is used in a file with
13779 many entries, and when the list of tags is retrieved, for example to
13780 obtain a list of properties. Building the tags list for each entry in such
13781 a file becomes an N^2 operation - but with this variable set, it scales
13782 as N.")
13784 (defun org-scan-tags (action matcher todo-only &optional start-level)
13785 "Sca headline tags with inheritance and produce output ACTION.
13787 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13788 or `agenda' to produce an entry list for an agenda view. It can also be
13789 a Lisp form or a function that should be called at each matched headline, in
13790 this case the return value is a list of all return values from these calls.
13792 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13793 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13794 only lines with a not-done TODO keyword are included in the output.
13795 This should be the same variable that was scoped into
13796 and set by `org-make-tags-matcher' when it constructed MATCHER.
13798 START-LEVEL can be a string with asterisks, reducing the scope to
13799 headlines matching this string."
13800 (require 'org-agenda)
13801 (let* ((re (concat "^"
13802 (if start-level
13803 ;; Get the correct level to match
13804 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13805 org-outline-regexp)
13806 " *\\(\\<\\("
13807 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13808 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13809 (props (list 'face 'default
13810 'done-face 'org-agenda-done
13811 'undone-face 'default
13812 'mouse-face 'highlight
13813 'org-not-done-regexp org-not-done-regexp
13814 'org-todo-regexp org-todo-regexp
13815 'org-complex-heading-regexp org-complex-heading-regexp
13816 'help-echo
13817 (format "mouse-2 or RET jump to org file %s"
13818 (abbreviate-file-name
13819 (or (buffer-file-name (buffer-base-buffer))
13820 (buffer-name (buffer-base-buffer)))))))
13821 (org-map-continue-from nil)
13822 lspos tags tags-list
13823 (tags-alist (list (cons 0 org-file-tags)))
13824 (llast 0) rtn rtn1 level category i txt
13825 todo marker entry priority)
13826 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13827 (setq action (list 'lambda nil action)))
13828 (save-excursion
13829 (goto-char (point-min))
13830 (when (eq action 'sparse-tree)
13831 (org-overview)
13832 (org-remove-occur-highlights))
13833 (while (let (case-fold-search)
13834 (re-search-forward re nil t))
13835 (setq org-map-continue-from nil)
13836 (catch :skip
13837 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13838 tags (if (match-end 4) (org-match-string-no-properties 4)))
13839 (goto-char (setq lspos (match-beginning 0)))
13840 (setq level (org-reduced-level (org-outline-level))
13841 category (org-get-category))
13842 (setq i llast llast level)
13843 ;; remove tag lists from same and sublevels
13844 (while (>= i level)
13845 (when (setq entry (assoc i tags-alist))
13846 (setq tags-alist (delete entry tags-alist)))
13847 (setq i (1- i)))
13848 ;; add the next tags
13849 (when tags
13850 (setq tags (org-split-string tags ":")
13851 tags-alist
13852 (cons (cons level tags) tags-alist)))
13853 ;; compile tags for current headline
13854 (setq tags-list
13855 (if org-use-tag-inheritance
13856 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13857 tags)
13858 org-scanner-tags tags-list)
13859 (when org-use-tag-inheritance
13860 (setcdr (car tags-alist)
13861 (mapcar (lambda (x)
13862 (setq x (copy-sequence x))
13863 (org-add-prop-inherited x))
13864 (cdar tags-alist))))
13865 (when (and tags org-use-tag-inheritance
13866 (or (not (eq t org-use-tag-inheritance))
13867 org-tags-exclude-from-inheritance))
13868 ;; selective inheritance, remove uninherited ones
13869 (setcdr (car tags-alist)
13870 (org-remove-uninherited-tags (cdar tags-alist))))
13871 (when (and
13873 ;; eval matcher only when the todo condition is OK
13874 (and (or (not todo-only) (member todo org-not-done-keywords))
13875 (let ((case-fold-search t) (org-trust-scanner-tags t))
13876 (eval matcher)))
13878 ;; Call the skipper, but return t if it does not skip,
13879 ;; so that the `and' form continues evaluating
13880 (progn
13881 (unless (eq action 'sparse-tree) (org-agenda-skip))
13884 ;; Check if timestamps are deselecting this entry
13885 (or (not todo-only)
13886 (and (member todo org-not-done-keywords)
13887 (or (not org-agenda-tags-todo-honor-ignore-options)
13888 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13890 ;; select this headline
13891 (cond
13892 ((eq action 'sparse-tree)
13893 (and org-highlight-sparse-tree-matches
13894 (org-get-heading) (match-end 0)
13895 (org-highlight-new-match
13896 (match-beginning 1) (match-end 1)))
13897 (org-show-context 'tags-tree))
13898 ((eq action 'agenda)
13899 (setq txt (org-agenda-format-item
13901 (concat
13902 (if (eq org-tags-match-list-sublevels 'indented)
13903 (make-string (1- level) ?.) "")
13904 (org-get-heading))
13905 level category
13906 tags-list)
13907 priority (org-get-priority txt))
13908 (goto-char lspos)
13909 (setq marker (org-agenda-new-marker))
13910 (org-add-props txt props
13911 'org-marker marker 'org-hd-marker marker 'org-category category
13912 'todo-state todo
13913 'priority priority 'type "tagsmatch")
13914 (push txt rtn))
13915 ((functionp action)
13916 (setq org-map-continue-from nil)
13917 (save-excursion
13918 (setq rtn1 (funcall action))
13919 (push rtn1 rtn)))
13920 (t (user-error "Invalid action")))
13922 ;; if we are to skip sublevels, jump to end of subtree
13923 (unless org-tags-match-list-sublevels
13924 (org-end-of-subtree t)
13925 (backward-char 1))))
13926 ;; Get the correct position from where to continue
13927 (if org-map-continue-from
13928 (goto-char org-map-continue-from)
13929 (and (= (point) lspos) (end-of-line 1)))))
13930 (when (and (eq action 'sparse-tree)
13931 (not org-sparse-tree-open-archived-trees))
13932 (org-hide-archived-subtrees (point-min) (point-max)))
13933 (nreverse rtn)))
13935 (defun org-remove-uninherited-tags (tags)
13936 "Remove all tags that are not inherited from the list TAGS."
13937 (cond
13938 ((eq org-use-tag-inheritance t)
13939 (if org-tags-exclude-from-inheritance
13940 (org-delete-all org-tags-exclude-from-inheritance tags)
13941 tags))
13942 ((not org-use-tag-inheritance) nil)
13943 ((stringp org-use-tag-inheritance)
13944 (delq nil (mapcar
13945 (lambda (x)
13946 (if (and (string-match org-use-tag-inheritance x)
13947 (not (member x org-tags-exclude-from-inheritance)))
13948 x nil))
13949 tags)))
13950 ((listp org-use-tag-inheritance)
13951 (delq nil (mapcar
13952 (lambda (x)
13953 (if (member x org-use-tag-inheritance) x nil))
13954 tags)))))
13956 (defun org-match-sparse-tree (&optional todo-only match)
13957 "Create a sparse tree according to tags string MATCH.
13958 MATCH can contain positive and negative selection of tags, like
13959 \"+WORK+URGENT-WITHBOSS\".
13960 If optional argument TODO-ONLY is non-nil, only select lines that are
13961 also TODO lines."
13962 (interactive "P")
13963 (org-agenda-prepare-buffers (list (current-buffer)))
13964 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13966 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13968 (defvar org-cached-props nil)
13969 (defun org-cached-entry-get (pom property)
13970 (if (or (eq t org-use-property-inheritance)
13971 (and (stringp org-use-property-inheritance)
13972 (string-match org-use-property-inheritance property))
13973 (and (listp org-use-property-inheritance)
13974 (member property org-use-property-inheritance)))
13975 ;; Caching is not possible, check it directly
13976 (org-entry-get pom property 'inherit)
13977 ;; Get all properties, so that we can do complicated checks easily
13978 (cdr (assoc property (or org-cached-props
13979 (setq org-cached-props
13980 (org-entry-properties pom)))))))
13982 (defun org-global-tags-completion-table (&optional files)
13983 "Return the list of all tags in all agenda buffer/files.
13984 Optional FILES argument is a list of files which can be used
13985 instead of the agenda files."
13986 (save-excursion
13987 (org-uniquify
13988 (delq nil
13989 (apply 'append
13990 (mapcar
13991 (lambda (file)
13992 (set-buffer (find-file-noselect file))
13993 (append (org-get-buffer-tags)
13994 (mapcar (lambda (x) (if (stringp (car-safe x))
13995 (list (car-safe x)) nil))
13996 org-tag-alist)))
13997 (if (and files (car files))
13998 files
13999 (org-agenda-files))))))))
14001 (defun org-make-tags-matcher (match)
14002 "Create the TAGS/TODO matcher form for the selection string MATCH.
14004 The variable `todo-only' is scoped dynamically into this function.
14005 It will be set to t if the matcher restricts matching to TODO entries,
14006 otherwise will not be touched.
14008 Returns a cons of the selection string MATCH and the constructed
14009 lisp form implementing the matcher. The matcher is to be evaluated
14010 at an Org entry, with point on the headline, and returns t if the
14011 entry matches the selection string MATCH. The returned lisp form
14012 references two variables with information about the entry, which
14013 must be bound around the form's evaluation: todo, the TODO keyword
14014 at the entry (or nil of none); and tags-list, the list of all tags
14015 at the entry including inherited ones. Additionally, the category
14016 of the entry (if any) must be specified as the text property
14017 'org-category on the headline.
14019 See also `org-scan-tags'.
14021 (declare (special todo-only))
14022 (unless (boundp 'todo-only)
14023 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14024 (unless match
14025 ;; Get a new match request, with completion against the global
14026 ;; tags table and the local tags in current buffer
14027 (let ((org-last-tags-completion-table
14028 (org-uniquify
14029 (delq nil (append (org-get-buffer-tags)
14030 (org-global-tags-completion-table))))))
14031 (setq match (org-completing-read-no-i
14032 "Match: " 'org-tags-completion-function nil nil nil
14033 'org-tags-history))))
14035 ;; Parse the string and create a lisp form
14036 (let ((match0 match)
14037 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14038 minus tag mm
14039 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14040 orterms term orlist re-p str-p level-p level-op time-p
14041 prop-p pn pv po gv rest)
14042 ;; Expand group tags
14043 (setq match (org-tags-expand match))
14044 (if (string-match "/+" match)
14045 ;; match contains also a todo-matching request
14046 (progn
14047 (setq tagsmatch (substring match 0 (match-beginning 0))
14048 todomatch (substring match (match-end 0)))
14049 (if (string-match "^!" todomatch)
14050 (setq todo-only t todomatch (substring todomatch 1)))
14051 (if (string-match "^\\s-*$" todomatch)
14052 (setq todomatch nil)))
14053 ;; only matching tags
14054 (setq tagsmatch match todomatch nil))
14056 ;; Make the tags matcher
14057 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14058 (setq tagsmatcher t)
14059 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14060 (while (setq term (pop orterms))
14061 (while (and (equal (substring term -1) "\\") orterms)
14062 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14063 (while (string-match re term)
14064 (setq rest (substring term (match-end 0))
14065 minus (and (match-end 1)
14066 (equal (match-string 1 term) "-"))
14067 tag (save-match-data (replace-regexp-in-string
14068 "\\\\-" "-"
14069 (match-string 2 term)))
14070 re-p (equal (string-to-char tag) ?{)
14071 level-p (match-end 4)
14072 prop-p (match-end 5)
14073 mm (cond
14074 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14075 (level-p
14076 (setq level-op (org-op-to-function (match-string 3 term)))
14077 `(,level-op level ,(string-to-number
14078 (match-string 4 term))))
14079 (prop-p
14080 (setq pn (match-string 5 term)
14081 po (match-string 6 term)
14082 pv (match-string 7 term)
14083 re-p (equal (string-to-char pv) ?{)
14084 str-p (equal (string-to-char pv) ?\")
14085 time-p (save-match-data
14086 (string-match "^\"[[<].*[]>]\"$" pv))
14087 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14088 (if time-p (setq pv (org-matcher-time pv)))
14089 (setq po (org-op-to-function po (if time-p 'time str-p)))
14090 (cond
14091 ((equal pn "CATEGORY")
14092 (setq gv '(get-text-property (point) 'org-category)))
14093 ((equal pn "TODO")
14094 (setq gv 'todo))
14096 (setq gv `(org-cached-entry-get nil ,pn))))
14097 (if re-p
14098 (if (eq po 'org<>)
14099 `(not (string-match ,pv (or ,gv "")))
14100 `(string-match ,pv (or ,gv "")))
14101 (if str-p
14102 `(,po (or ,gv "") ,pv)
14103 `(,po (string-to-number (or ,gv ""))
14104 ,(string-to-number pv) ))))
14105 (t `(member ,tag tags-list)))
14106 mm (if minus (list 'not mm) mm)
14107 term rest)
14108 (push mm tagsmatcher))
14109 (push (if (> (length tagsmatcher) 1)
14110 (cons 'and tagsmatcher)
14111 (car tagsmatcher))
14112 orlist)
14113 (setq tagsmatcher nil))
14114 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14115 (setq tagsmatcher
14116 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14117 ;; Make the todo matcher
14118 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14119 (setq todomatcher t)
14120 (setq orterms (org-split-string todomatch "|") orlist nil)
14121 (while (setq term (pop orterms))
14122 (while (string-match re term)
14123 (setq minus (and (match-end 1)
14124 (equal (match-string 1 term) "-"))
14125 kwd (match-string 2 term)
14126 re-p (equal (string-to-char kwd) ?{)
14127 term (substring term (match-end 0))
14128 mm (if re-p
14129 `(string-match ,(substring kwd 1 -1) todo)
14130 (list 'equal 'todo kwd))
14131 mm (if minus (list 'not mm) mm))
14132 (push mm todomatcher))
14133 (push (if (> (length todomatcher) 1)
14134 (cons 'and todomatcher)
14135 (car todomatcher))
14136 orlist)
14137 (setq todomatcher nil))
14138 (setq todomatcher (if (> (length orlist) 1)
14139 (cons 'or orlist) (car orlist))))
14141 ;; Return the string and lisp forms of the matcher
14142 (setq matcher (if todomatcher
14143 (list 'and tagsmatcher todomatcher)
14144 tagsmatcher))
14145 (when todo-only
14146 (setq matcher (list 'and '(member todo org-not-done-keywords)
14147 matcher)))
14148 (cons match0 matcher)))
14150 (defun org-tags-expand (match &optional single-as-list downcased)
14151 "Expand group tags in MATCH.
14153 This replaces every group tag in MATCH with a regexp tag search.
14154 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14155 will be replaced like this:
14157 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14158 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14159 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14161 Replacing by a regexp preserves the structure of the match.
14162 E.g., this expansion
14164 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14166 will match anything tagged with \"Lab\" and \"Home\", or tagged
14167 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14169 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14170 assumed to be a single group tag, and the function will return
14171 the list of tags in this group.
14173 When DOWNCASE is non-nil, expand downcased TAGS."
14174 (if org-group-tags
14175 (let* ((case-fold-search t)
14176 (stable org-mode-syntax-table)
14177 (tal (or org-tag-groups-alist-for-agenda
14178 org-tag-groups-alist))
14179 (tal (if downcased
14180 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14181 (tml (mapcar 'car tal))
14182 (rtnmatch match) rpl)
14183 ;; @ and _ are allowed as word-components in tags
14184 (modify-syntax-entry ?@ "w" stable)
14185 (modify-syntax-entry ?_ "w" stable)
14186 (while (and tml
14187 (with-syntax-table stable
14188 (string-match
14189 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14190 (regexp-opt tml) "\\>\\)") rtnmatch)))
14191 (let* ((dir (match-string 1 rtnmatch))
14192 (tag (match-string 2 rtnmatch))
14193 (tag (if downcased (downcase tag) tag)))
14194 (setq tml (delete tag tml))
14195 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14196 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14197 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14198 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14199 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14200 (if single-as-list
14201 (or (reverse rpl) (list rtnmatch))
14202 rtnmatch))
14203 (if single-as-list (list (if downcased (downcase match) match))
14204 match)))
14206 (defun org-op-to-function (op &optional stringp)
14207 "Turn an operator into the appropriate function."
14208 (setq op
14209 (cond
14210 ((equal op "<" ) '(< string< org-time<))
14211 ((equal op ">" ) '(> org-string> org-time>))
14212 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14213 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14214 ((member op '("=" "==")) '(= string= org-time=))
14215 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14216 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14218 (defun org<> (a b) (not (= a b)))
14219 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14220 (defun org-string>= (a b) (not (string< a b)))
14221 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14222 (defun org-string<> (a b) (not (string= a b)))
14223 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14224 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14225 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14226 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14227 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14228 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14229 (defun org-2ft (s)
14230 "Convert S to a floating point time.
14231 If S is already a number, just return it. If it is a string, parse
14232 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14233 (cond
14234 ((numberp s) s)
14235 ((stringp s)
14236 (condition-case nil
14237 (float-time (apply 'encode-time (org-parse-time-string s)))
14238 (error 0.)))
14239 (t 0.)))
14241 (defun org-time-today ()
14242 "Time in seconds today at 0:00.
14243 Returns the float number of seconds since the beginning of the
14244 epoch to the beginning of today (00:00)."
14245 (float-time (apply 'encode-time
14246 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14248 (defun org-matcher-time (s)
14249 "Interpret a time comparison value."
14250 (save-match-data
14251 (cond
14252 ((string= s "<now>") (float-time))
14253 ((string= s "<today>") (org-time-today))
14254 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14255 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14256 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14257 (+ (org-time-today)
14258 (* (string-to-number (match-string 1 s))
14259 (cdr (assoc (match-string 2 s)
14260 '(("d" . 86400.0) ("w" . 604800.0)
14261 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14262 (t (org-2ft s)))))
14264 (defun org-match-any-p (re list)
14265 "Does re match any element of list?"
14266 (setq list (mapcar (lambda (x) (string-match re x)) list))
14267 (delq nil list))
14269 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14270 (defvar org-tags-overlay (make-overlay 1 1))
14271 (org-detach-overlay org-tags-overlay)
14273 (defun org-get-local-tags-at (&optional pos)
14274 "Get a list of tags defined in the current headline."
14275 (org-get-tags-at pos 'local))
14277 (defun org-get-local-tags ()
14278 "Get a list of tags defined in the current headline."
14279 (org-get-tags-at nil 'local))
14281 (defun org-get-tags-at (&optional pos local)
14282 "Get a list of all headline tags applicable at POS.
14283 POS defaults to point. If tags are inherited, the list contains
14284 the targets in the same sequence as the headlines appear, i.e.
14285 the tags of the current headline come last.
14286 When LOCAL is non-nil, only return tags from the current headline,
14287 ignore inherited ones."
14288 (interactive)
14289 (if (and org-trust-scanner-tags
14290 (or (not pos) (equal pos (point)))
14291 (not local))
14292 org-scanner-tags
14293 (let (tags ltags lastpos parent)
14294 (save-excursion
14295 (save-restriction
14296 (widen)
14297 (goto-char (or pos (point)))
14298 (save-match-data
14299 (catch 'done
14300 (condition-case nil
14301 (progn
14302 (org-back-to-heading t)
14303 (while (not (equal lastpos (point)))
14304 (setq lastpos (point))
14305 (when (looking-at
14306 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14307 (setq ltags (org-split-string
14308 (org-match-string-no-properties 1) ":"))
14309 (when parent
14310 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14311 (setq tags (append
14312 (if parent
14313 (org-remove-uninherited-tags ltags)
14314 ltags)
14315 tags)))
14316 (or org-use-tag-inheritance (throw 'done t))
14317 (if local (throw 'done t))
14318 (or (org-up-heading-safe) (error nil))
14319 (setq parent t)))
14320 (error nil)))))
14321 (if local
14322 tags
14323 (reverse (delete-dups
14324 (reverse (append
14325 (org-remove-uninherited-tags
14326 org-file-tags) tags)))))))))
14328 (defun org-add-prop-inherited (s)
14329 (add-text-properties 0 (length s) '(inherited t) s)
14332 (defun org-toggle-tag (tag &optional onoff)
14333 "Toggle the tag TAG for the current line.
14334 If ONOFF is `on' or `off', don't toggle but set to this state."
14335 (let (res current)
14336 (save-excursion
14337 (org-back-to-heading t)
14338 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14339 (point-at-eol) t)
14340 (progn
14341 (setq current (match-string 1))
14342 (replace-match ""))
14343 (setq current ""))
14344 (setq current (nreverse (org-split-string current ":")))
14345 (cond
14346 ((eq onoff 'on)
14347 (setq res t)
14348 (or (member tag current) (push tag current)))
14349 ((eq onoff 'off)
14350 (or (not (member tag current)) (setq current (delete tag current))))
14351 (t (if (member tag current)
14352 (setq current (delete tag current))
14353 (setq res t)
14354 (push tag current))))
14355 (end-of-line 1)
14356 (if current
14357 (progn
14358 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14359 (org-set-tags nil t))
14360 (delete-horizontal-space))
14361 (run-hooks 'org-after-tags-change-hook))
14362 res))
14364 (defun org-align-tags-here (to-col)
14365 ;; Assumes that this is a headline
14366 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14367 (beginning-of-line 1)
14368 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14369 (< pos (match-beginning 2)))
14370 (progn
14371 (setq tags-l (- (match-end 2) (match-beginning 2)))
14372 (goto-char (match-beginning 1))
14373 (insert " ")
14374 (delete-region (point) (1+ (match-beginning 2)))
14375 (setq ncol (max (current-column)
14376 (1+ col)
14377 (if (> to-col 0)
14378 to-col
14379 (- (abs to-col) tags-l))))
14380 (setq p (point))
14381 (insert (make-string (- ncol (current-column)) ?\ ))
14382 (setq ncol (current-column))
14383 (when indent-tabs-mode (tabify p (point-at-eol)))
14384 (org-move-to-column (min ncol col) t))
14385 (goto-char pos))))
14387 (defun org-set-tags-command (&optional arg just-align)
14388 "Call the set-tags command for the current entry."
14389 (interactive "P")
14390 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14391 (org-set-tags arg just-align)
14392 (save-excursion
14393 (unless (and (org-region-active-p)
14394 org-loop-over-headlines-in-active-region)
14395 (org-back-to-heading t))
14396 (org-set-tags arg just-align))))
14398 (defun org-set-tags-to (data)
14399 "Set the tags of the current entry to DATA, replacing the current tags.
14400 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14401 If DATA is nil or the empty string, any tags will be removed."
14402 (interactive "sTags: ")
14403 (setq data
14404 (cond
14405 ((eq data nil) "")
14406 ((equal data "") "")
14407 ((stringp data)
14408 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14409 ":"))
14410 ((listp data)
14411 (concat ":" (mapconcat 'identity data ":") ":"))))
14412 (when data
14413 (save-excursion
14414 (org-back-to-heading t)
14415 (when (looking-at org-complex-heading-regexp)
14416 (if (match-end 5)
14417 (progn
14418 (goto-char (match-beginning 5))
14419 (insert data)
14420 (delete-region (point) (point-at-eol))
14421 (org-set-tags nil 'align))
14422 (goto-char (point-at-eol))
14423 (insert " " data)
14424 (org-set-tags nil 'align)))
14425 (beginning-of-line 1)
14426 (if (looking-at ".*?\\([ \t]+\\)$")
14427 (delete-region (match-beginning 1) (match-end 1))))))
14429 (defun org-align-all-tags ()
14430 "Align the tags i all headings."
14431 (interactive)
14432 (save-excursion
14433 (or (ignore-errors (org-back-to-heading t))
14434 (outline-next-heading))
14435 (if (org-at-heading-p)
14436 (org-set-tags t)
14437 (message "No headings"))))
14439 (defvar org-indent-indentation-per-level)
14440 (defun org-set-tags (&optional arg just-align)
14441 "Set the tags for the current headline.
14442 With prefix ARG, realign all tags in headings in the current buffer."
14443 (interactive "P")
14444 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14445 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14446 'region-start-level 'region))
14447 org-loop-over-headlines-in-active-region)
14448 (org-map-entries
14449 ;; We don't use ARG and JUST-ALIGN here these args are not
14450 ;; useful when looping over headlines
14451 `(org-set-tags)
14452 org-loop-over-headlines-in-active-region
14453 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14454 (let* ((re org-outline-regexp-bol)
14455 (current (unless arg (org-get-tags-string)))
14456 (col (current-column))
14457 (org-setting-tags t)
14458 table current-tags inherited-tags ; computed below when needed
14459 tags p0 c0 c1 rpl di tc level)
14460 (if arg
14461 (save-excursion
14462 (goto-char (point-min))
14463 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14464 (while (re-search-forward re nil t)
14465 (org-set-tags nil t)
14466 (end-of-line 1)))
14467 (message "All tags realigned to column %d" org-tags-column))
14468 (if just-align
14469 (setq tags current)
14470 ;; Get a new set of tags from the user
14471 (save-excursion
14472 (setq table (append org-tag-persistent-alist
14473 (or org-tag-alist (org-get-buffer-tags))
14474 (and
14475 org-complete-tags-always-offer-all-agenda-tags
14476 (org-global-tags-completion-table
14477 (org-agenda-files))))
14478 org-last-tags-completion-table table
14479 current-tags (org-split-string current ":")
14480 inherited-tags (nreverse
14481 (nthcdr (length current-tags)
14482 (nreverse (org-get-tags-at))))
14483 tags
14484 (if (or (eq t org-use-fast-tag-selection)
14485 (and org-use-fast-tag-selection
14486 (delq nil (mapcar 'cdr table))))
14487 (org-fast-tag-selection
14488 current-tags inherited-tags table
14489 (if org-fast-tag-selection-include-todo
14490 org-todo-key-alist))
14491 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14492 (org-trim
14493 (org-icompleting-read "Tags: "
14494 'org-tags-completion-function
14495 nil nil current 'org-tags-history))))))
14496 (while (string-match "[-+&]+" tags)
14497 ;; No boolean logic, just a list
14498 (setq tags (replace-match ":" t t tags))))
14500 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14502 (if org-tags-sort-function
14503 (setq tags (mapconcat 'identity
14504 (sort (org-split-string
14505 tags (org-re "[^[:alnum:]_@#%]+"))
14506 org-tags-sort-function) ":")))
14508 (if (string-match "\\`[\t ]*\\'" tags)
14509 (setq tags "")
14510 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14511 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14513 ;; Insert new tags at the correct column
14514 (beginning-of-line 1)
14515 (setq level (or (and (looking-at org-outline-regexp)
14516 (- (match-end 0) (point) 1))
14518 (cond
14519 ((and (equal current "") (equal tags "")))
14520 ((re-search-forward
14521 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14522 (point-at-eol) t)
14523 (if (equal tags "")
14524 (setq rpl "")
14525 (goto-char (match-beginning 0))
14526 (setq c0 (current-column)
14527 ;; compute offset for the case of org-indent-mode active
14528 di (if org-indent-mode
14529 (* (1- org-indent-indentation-per-level) (1- level))
14531 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14532 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14533 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14534 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14535 (replace-match rpl t t)
14536 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14537 tags)
14538 (t (error "Tags alignment failed")))
14539 (org-move-to-column col)
14540 (unless just-align
14541 (run-hooks 'org-after-tags-change-hook))))))
14543 (defun org-change-tag-in-region (beg end tag off)
14544 "Add or remove TAG for each entry in the region.
14545 This works in the agenda, and also in an org-mode buffer."
14546 (interactive
14547 (list (region-beginning) (region-end)
14548 (let ((org-last-tags-completion-table
14549 (if (derived-mode-p 'org-mode)
14550 (org-uniquify
14551 (delq nil (append (org-get-buffer-tags)
14552 (org-global-tags-completion-table))))
14553 (org-global-tags-completion-table))))
14554 (org-icompleting-read
14555 "Tag: " 'org-tags-completion-function nil nil nil
14556 'org-tags-history))
14557 (progn
14558 (message "[s]et or [r]emove? ")
14559 (equal (read-char-exclusive) ?r))))
14560 (if (fboundp 'deactivate-mark) (deactivate-mark))
14561 (let ((agendap (equal major-mode 'org-agenda-mode))
14562 l1 l2 m buf pos newhead (cnt 0))
14563 (goto-char end)
14564 (setq l2 (1- (org-current-line)))
14565 (goto-char beg)
14566 (setq l1 (org-current-line))
14567 (loop for l from l1 to l2 do
14568 (org-goto-line l)
14569 (setq m (get-text-property (point) 'org-hd-marker))
14570 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14571 (and agendap m))
14572 (setq buf (if agendap (marker-buffer m) (current-buffer))
14573 pos (if agendap m (point)))
14574 (with-current-buffer buf
14575 (save-excursion
14576 (save-restriction
14577 (goto-char pos)
14578 (setq cnt (1+ cnt))
14579 (org-toggle-tag tag (if off 'off 'on))
14580 (setq newhead (org-get-heading)))))
14581 (and agendap (org-agenda-change-all-lines newhead m))))
14582 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14584 (defun org-tags-completion-function (string predicate &optional flag)
14585 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14586 (confirm (lambda (x) (stringp (car x)))))
14587 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14588 (setq s1 (match-string 1 string)
14589 s2 (match-string 2 string))
14590 (setq s1 "" s2 string))
14591 (cond
14592 ((eq flag nil)
14593 ;; try completion
14594 (setq rtn (try-completion s2 ctable confirm))
14595 (if (stringp rtn)
14596 (setq rtn
14597 (concat s1 s2 (substring rtn (length s2))
14598 (if (and org-add-colon-after-tag-completion
14599 (assoc rtn ctable))
14600 ":" ""))))
14601 rtn)
14602 ((eq flag t)
14603 ;; all-completions
14604 (all-completions s2 ctable confirm))
14605 ((eq flag 'lambda)
14606 ;; exact match?
14607 (assoc s2 ctable)))))
14609 (defun org-fast-tag-insert (kwd tags face &optional end)
14610 "Insert KDW, and the TAGS, the latter with face FACE.
14611 Also insert END."
14612 (insert (format "%-12s" (concat kwd ":"))
14613 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14614 (or end "")))
14616 (defun org-fast-tag-show-exit (flag)
14617 (save-excursion
14618 (org-goto-line 3)
14619 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14620 (replace-match ""))
14621 (when flag
14622 (end-of-line 1)
14623 (org-move-to-column (- (window-width) 19) t)
14624 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14626 (defun org-set-current-tags-overlay (current prefix)
14627 "Add an overlay to CURRENT tag with PREFIX."
14628 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14629 (if (featurep 'xemacs)
14630 (org-overlay-display org-tags-overlay (concat prefix s)
14631 'secondary-selection)
14632 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14633 (org-overlay-display org-tags-overlay (concat prefix s)))))
14635 (defvar org-last-tag-selection-key nil)
14636 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14637 "Fast tag selection with single keys.
14638 CURRENT is the current list of tags in the headline, INHERITED is the
14639 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14640 possibly with grouping information. TODO-TABLE is a similar table with
14641 TODO keywords, should these have keys assigned to them.
14642 If the keys are nil, a-z are automatically assigned.
14643 Returns the new tags string, or nil to not change the current settings."
14644 (let* ((fulltable (append table todo-table))
14645 (maxlen (apply 'max (mapcar
14646 (lambda (x)
14647 (if (stringp (car x)) (string-width (car x)) 0))
14648 fulltable)))
14649 (buf (current-buffer))
14650 (expert (eq org-fast-tag-selection-single-key 'expert))
14651 (buffer-tags nil)
14652 (fwidth (+ maxlen 3 1 3))
14653 (ncol (/ (- (window-width) 4) fwidth))
14654 (i-face 'org-done)
14655 (c-face 'org-todo)
14656 tg cnt e c char c1 c2 ntable tbl rtn
14657 ov-start ov-end ov-prefix
14658 (exit-after-next org-fast-tag-selection-single-key)
14659 (done-keywords org-done-keywords)
14660 groups ingroup)
14661 (save-excursion
14662 (beginning-of-line 1)
14663 (if (looking-at
14664 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14665 (setq ov-start (match-beginning 1)
14666 ov-end (match-end 1)
14667 ov-prefix "")
14668 (setq ov-start (1- (point-at-eol))
14669 ov-end (1+ ov-start))
14670 (skip-chars-forward "^\n\r")
14671 (setq ov-prefix
14672 (concat
14673 (buffer-substring (1- (point)) (point))
14674 (if (> (current-column) org-tags-column)
14676 (make-string (- org-tags-column (current-column)) ?\ ))))))
14677 (move-overlay org-tags-overlay ov-start ov-end)
14678 (save-window-excursion
14679 (if expert
14680 (set-buffer (get-buffer-create " *Org tags*"))
14681 (delete-other-windows)
14682 (split-window-vertically)
14683 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14684 (erase-buffer)
14685 (org-set-local 'org-done-keywords done-keywords)
14686 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14687 (org-fast-tag-insert "Current" current c-face "\n\n")
14688 (org-fast-tag-show-exit exit-after-next)
14689 (org-set-current-tags-overlay current ov-prefix)
14690 (setq tbl fulltable char ?a cnt 0)
14691 (while (setq e (pop tbl))
14692 (cond
14693 ((equal (car e) :startgroup)
14694 (push '() groups) (setq ingroup t)
14695 (when (not (= cnt 0))
14696 (setq cnt 0)
14697 (insert "\n"))
14698 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14699 ((equal (car e) :endgroup)
14700 (setq ingroup nil cnt 0)
14701 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14702 ((equal e '(:newline))
14703 (when (not (= cnt 0))
14704 (setq cnt 0)
14705 (insert "\n")
14706 (setq e (car tbl))
14707 (while (equal (car tbl) '(:newline))
14708 (insert "\n")
14709 (setq tbl (cdr tbl)))))
14710 ((equal e '(:grouptags)) nil)
14712 (setq tg (copy-sequence (car e)) c2 nil)
14713 (if (cdr e)
14714 (setq c (cdr e))
14715 ;; automatically assign a character.
14716 (setq c1 (string-to-char
14717 (downcase (substring
14718 tg (if (= (string-to-char tg) ?@) 1 0)))))
14719 (if (or (rassoc c1 ntable) (rassoc c1 table))
14720 (while (or (rassoc char ntable) (rassoc char table))
14721 (setq char (1+ char)))
14722 (setq c2 c1))
14723 (setq c (or c2 char)))
14724 (if ingroup (push tg (car groups)))
14725 (setq tg (org-add-props tg nil 'face
14726 (cond
14727 ((not (assoc tg table))
14728 (org-get-todo-face tg))
14729 ((member tg current) c-face)
14730 ((member tg inherited) i-face))))
14731 (if (equal (caar tbl) :grouptags)
14732 (org-add-props tg nil 'face 'org-tag-group))
14733 (if (and (= cnt 0) (not ingroup)) (insert " "))
14734 (insert "[" c "] " tg (make-string
14735 (- fwidth 4 (length tg)) ?\ ))
14736 (push (cons tg c) ntable)
14737 (when (= (setq cnt (1+ cnt)) ncol)
14738 (insert "\n")
14739 (if ingroup (insert " "))
14740 (setq cnt 0)))))
14741 (setq ntable (nreverse ntable))
14742 (insert "\n")
14743 (goto-char (point-min))
14744 (if (not expert) (org-fit-window-to-buffer))
14745 (setq rtn
14746 (catch 'exit
14747 (while t
14748 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14749 (if (not groups) "no " "")
14750 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14751 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14752 (setq org-last-tag-selection-key c)
14753 (cond
14754 ((= c ?\r) (throw 'exit t))
14755 ((= c ?!)
14756 (setq groups (not groups))
14757 (goto-char (point-min))
14758 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14759 ((= c ?\C-c)
14760 (if (not expert)
14761 (org-fast-tag-show-exit
14762 (setq exit-after-next (not exit-after-next)))
14763 (setq expert nil)
14764 (delete-other-windows)
14765 (set-window-buffer (split-window-vertically) " *Org tags*")
14766 (org-switch-to-buffer-other-window " *Org tags*")
14767 (org-fit-window-to-buffer)))
14768 ((or (= c ?\C-g)
14769 (and (= c ?q) (not (rassoc c ntable))))
14770 (org-detach-overlay org-tags-overlay)
14771 (setq quit-flag t))
14772 ((= c ?\ )
14773 (setq current nil)
14774 (if exit-after-next (setq exit-after-next 'now)))
14775 ((= c ?\t)
14776 (condition-case nil
14777 (setq tg (org-icompleting-read
14778 "Tag: "
14779 (or buffer-tags
14780 (with-current-buffer buf
14781 (org-get-buffer-tags)))))
14782 (quit (setq tg "")))
14783 (when (string-match "\\S-" tg)
14784 (add-to-list 'buffer-tags (list tg))
14785 (if (member tg current)
14786 (setq current (delete tg current))
14787 (push tg current)))
14788 (if exit-after-next (setq exit-after-next 'now)))
14789 ((setq e (rassoc c todo-table) tg (car e))
14790 (with-current-buffer buf
14791 (save-excursion (org-todo tg)))
14792 (if exit-after-next (setq exit-after-next 'now)))
14793 ((setq e (rassoc c ntable) tg (car e))
14794 (if (member tg current)
14795 (setq current (delete tg current))
14796 (loop for g in groups do
14797 (if (member tg g)
14798 (mapc (lambda (x)
14799 (setq current (delete x current)))
14800 g)))
14801 (push tg current))
14802 (if exit-after-next (setq exit-after-next 'now))))
14804 ;; Create a sorted list
14805 (setq current
14806 (sort current
14807 (lambda (a b)
14808 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14809 (if (eq exit-after-next 'now) (throw 'exit t))
14810 (goto-char (point-min))
14811 (beginning-of-line 2)
14812 (delete-region (point) (point-at-eol))
14813 (org-fast-tag-insert "Current" current c-face)
14814 (org-set-current-tags-overlay current ov-prefix)
14815 (while (re-search-forward
14816 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14817 (setq tg (match-string 1))
14818 (add-text-properties
14819 (match-beginning 1) (match-end 1)
14820 (list 'face
14821 (cond
14822 ((member tg current) c-face)
14823 ((member tg inherited) i-face)
14824 (t (get-text-property (match-beginning 1) 'face))))))
14825 (goto-char (point-min)))))
14826 (org-detach-overlay org-tags-overlay)
14827 (if rtn
14828 (mapconcat 'identity current ":")
14829 nil))))
14831 (defun org-get-tags-string ()
14832 "Get the TAGS string in the current headline."
14833 (unless (org-at-heading-p t)
14834 (user-error "Not on a heading"))
14835 (save-excursion
14836 (beginning-of-line 1)
14837 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14838 (org-match-string-no-properties 1)
14839 "")))
14841 (defun org-get-tags ()
14842 "Get the list of tags specified in the current headline."
14843 (org-split-string (org-get-tags-string) ":"))
14845 (defun org-get-buffer-tags ()
14846 "Get a table of all tags used in the buffer, for completion."
14847 (let (tags)
14848 (save-excursion
14849 (goto-char (point-min))
14850 (while (re-search-forward
14851 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14852 (when (equal (char-after (point-at-bol 0)) ?*)
14853 (mapc (lambda (x) (add-to-list 'tags x))
14854 (org-split-string (org-match-string-no-properties 1) ":")))))
14855 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14856 (mapcar 'list tags)))
14858 ;;;; The mapping API
14860 (defun org-map-entries (func &optional match scope &rest skip)
14861 "Call FUNC at each headline selected by MATCH in SCOPE.
14863 FUNC is a function or a lisp form. The function will be called without
14864 arguments, with the cursor positioned at the beginning of the headline.
14865 The return values of all calls to the function will be collected and
14866 returned as a list.
14868 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14869 does not need to preserve point. After evaluation, the cursor will be
14870 moved to the end of the line (presumably of the headline of the
14871 processed entry) and search continues from there. Under some
14872 circumstances, this may not produce the wanted results. For example,
14873 if you have removed (e.g. archived) the current (sub)tree it could
14874 mean that the next entry will be skipped entirely. In such cases, you
14875 can specify the position from where search should continue by making
14876 FUNC set the variable `org-map-continue-from' to the desired buffer
14877 position.
14879 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14880 Only headlines that are matched by this query will be considered during
14881 the iteration. When MATCH is nil or t, all headlines will be
14882 visited by the iteration.
14884 SCOPE determines the scope of this command. It can be any of:
14886 nil The current buffer, respecting the restriction if any
14887 tree The subtree started with the entry at point
14888 region The entries within the active region, if any
14889 region-start-level
14890 The entries within the active region, but only those at
14891 the same level than the first one.
14892 file The current buffer, without restriction
14893 file-with-archives
14894 The current buffer, and any archives associated with it
14895 agenda All agenda files
14896 agenda-with-archives
14897 All agenda files with any archive files associated with them
14898 \(file1 file2 ...)
14899 If this is a list, all files in the list will be scanned
14901 The remaining args are treated as settings for the skipping facilities of
14902 the scanner. The following items can be given here:
14904 archive skip trees with the archive tag
14905 comment skip trees with the COMMENT keyword
14906 function or Emacs Lisp form:
14907 will be used as value for `org-agenda-skip-function', so
14908 whenever the function returns a position, FUNC will not be
14909 called for that entry and search will continue from the
14910 position returned
14912 If your function needs to retrieve the tags including inherited tags
14913 at the *current* entry, you can use the value of the variable
14914 `org-scanner-tags' which will be much faster than getting the value
14915 with `org-get-tags-at'. If your function gets properties with
14916 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14917 to t around the call to `org-entry-properties' to get the same speedup.
14918 Note that if your function moves around to retrieve tags and properties at
14919 a *different* entry, you cannot use these techniques."
14920 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14921 (not (org-region-active-p)))
14922 (let* ((org-agenda-archives-mode nil) ; just to make sure
14923 (org-agenda-skip-archived-trees (memq 'archive skip))
14924 (org-agenda-skip-comment-trees (memq 'comment skip))
14925 (org-agenda-skip-function
14926 (car (org-delete-all '(comment archive) skip)))
14927 (org-tags-match-list-sublevels t)
14928 (start-level (eq scope 'region-start-level))
14929 matcher file res
14930 org-todo-keywords-for-agenda
14931 org-done-keywords-for-agenda
14932 org-todo-keyword-alist-for-agenda
14933 org-drawers-for-agenda
14934 org-tag-alist-for-agenda
14935 todo-only)
14937 (cond
14938 ((eq match t) (setq matcher t))
14939 ((eq match nil) (setq matcher t))
14940 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14942 (save-window-excursion
14943 (save-restriction
14944 (cond ((eq scope 'tree)
14945 (org-back-to-heading t)
14946 (org-narrow-to-subtree)
14947 (setq scope nil))
14948 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14949 (org-region-active-p))
14950 ;; If needed, set start-level to a string like "2"
14951 (when start-level
14952 (save-excursion
14953 (goto-char (region-beginning))
14954 (unless (org-at-heading-p) (outline-next-heading))
14955 (setq start-level (org-current-level))))
14956 (narrow-to-region (region-beginning)
14957 (save-excursion
14958 (goto-char (region-end))
14959 (unless (and (bolp) (org-at-heading-p))
14960 (outline-next-heading))
14961 (point)))
14962 (setq scope nil)))
14964 (if (not scope)
14965 (progn
14966 (org-agenda-prepare-buffers
14967 (list (buffer-file-name (current-buffer))))
14968 (setq res (org-scan-tags func matcher todo-only start-level)))
14969 ;; Get the right scope
14970 (cond
14971 ((and scope (listp scope) (symbolp (car scope)))
14972 (setq scope (eval scope)))
14973 ((eq scope 'agenda)
14974 (setq scope (org-agenda-files t)))
14975 ((eq scope 'agenda-with-archives)
14976 (setq scope (org-agenda-files t))
14977 (setq scope (org-add-archive-files scope)))
14978 ((eq scope 'file)
14979 (setq scope (list (buffer-file-name))))
14980 ((eq scope 'file-with-archives)
14981 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14982 (org-agenda-prepare-buffers scope)
14983 (while (setq file (pop scope))
14984 (with-current-buffer (org-find-base-buffer-visiting file)
14985 (save-excursion
14986 (save-restriction
14987 (widen)
14988 (goto-char (point-min))
14989 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14990 res)))
14992 ;;;; Properties
14994 ;;; Setting and retrieving properties
14996 (defconst org-special-properties
14997 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14998 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14999 "The special properties valid in Org-mode.
15001 These are properties that are not defined in the property drawer,
15002 but in some other way.")
15004 (defconst org-default-properties
15005 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15006 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15007 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15008 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15009 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15010 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15011 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15012 "Some properties that are used by Org-mode for various purposes.
15013 Being in this list makes sure that they are offered for completion.")
15015 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15016 "Regular expression matching the first line of a property drawer.")
15018 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15019 "Regular expression matching the last line of a property drawer.")
15021 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
15022 "Regular expression matching the first line of a property drawer.")
15024 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
15025 "Regular expression matching the first line of a property drawer.")
15027 (defconst org-property-drawer-re
15028 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
15029 org-property-end-re "\\)\n?")
15030 "Matches an entire property drawer.")
15032 (defconst org-clock-drawer-re
15033 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
15034 org-property-end-re "\\)\n?")
15035 "Matches an entire clock drawer.")
15037 (defun org-property-action ()
15038 "Do an action on properties."
15039 (interactive)
15040 (let (c)
15041 (org-at-property-p)
15042 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15043 (setq c (read-char-exclusive))
15044 (cond
15045 ((equal c ?s)
15046 (call-interactively 'org-set-property))
15047 ((equal c ?d)
15048 (call-interactively 'org-delete-property))
15049 ((equal c ?D)
15050 (call-interactively 'org-delete-property-globally))
15051 ((equal c ?c)
15052 (call-interactively 'org-compute-property-at-point))
15053 (t (user-error "No such property action %c" c)))))
15055 (defun org-inc-effort ()
15056 "Increment the value of the effort property in the current entry."
15057 (interactive)
15058 (org-set-effort nil t))
15060 (defvar org-clock-effort) ;; Defined in org-clock.el
15061 (defvar org-clock-current-task) ;; Defined in org-clock.el
15062 (defun org-set-effort (&optional value increment)
15063 "Set the effort property of the current entry.
15064 With numerical prefix arg, use the nth allowed value, 0 stands for the
15065 10th allowed value.
15067 When INCREMENT is non-nil, set the property to the next allowed value."
15068 (interactive "P")
15069 (if (equal value 0) (setq value 10))
15070 (let* ((completion-ignore-case t)
15071 (prop org-effort-property)
15072 (cur (org-entry-get nil prop))
15073 (allowed (org-property-get-allowed-values nil prop 'table))
15074 (existing (mapcar 'list (org-property-values prop)))
15075 (heading (nth 4 (org-heading-components)))
15077 (val (cond
15078 ((stringp value) value)
15079 ((and allowed (integerp value))
15080 (or (car (nth (1- value) allowed))
15081 (car (org-last allowed))))
15082 ((and allowed increment)
15083 (or (caadr (member (list cur) allowed))
15084 (user-error "Allowed effort values are not set")))
15085 (allowed
15086 (message "Select 1-9,0, [RET%s]: %s"
15087 (if cur (concat "=" cur) "")
15088 (mapconcat 'car allowed " "))
15089 (setq rpl (read-char-exclusive))
15090 (if (equal rpl ?\r)
15092 (setq rpl (- rpl ?0))
15093 (if (equal rpl 0) (setq rpl 10))
15094 (if (and (> rpl 0) (<= rpl (length allowed)))
15095 (car (nth (1- rpl) allowed))
15096 (org-completing-read "Effort: " allowed nil))))
15098 (let (org-completion-use-ido org-completion-use-iswitchb)
15099 (org-completing-read
15100 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15101 (concat "[" cur "]") "")
15102 ": ")
15103 existing nil nil "" nil cur))))))
15104 (unless (equal (org-entry-get nil prop) val)
15105 (org-entry-put nil prop val))
15106 (save-excursion
15107 (org-back-to-heading t)
15108 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15109 (when (string= heading org-clock-current-task)
15110 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15111 (org-clock-update-mode-line))
15112 (message "%s is now %s" prop val)))
15114 (defun org-at-property-p ()
15115 "Is cursor inside a property drawer?"
15116 (save-excursion
15117 (when (equal 'node-property (car (org-element-at-point)))
15118 (beginning-of-line 1)
15119 (looking-at org-property-re))))
15121 (defun org-get-property-block (&optional beg end force)
15122 "Return the (beg . end) range of the body of the property drawer.
15123 BEG and END are the beginning and end of the current subtree, or of
15124 the part before the first headline. If they are not given, they will
15125 be found. If the drawer does not exist and FORCE is non-nil, create
15126 the drawer."
15127 (catch 'exit
15128 (save-excursion
15129 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15130 (progn (org-back-to-heading t) (point))))
15131 (end (or end (and (not (outline-next-heading)) (point-max))
15132 (point))))
15133 (goto-char beg)
15134 (if (re-search-forward org-property-start-re end t)
15135 (setq beg (1+ (match-end 0)))
15136 (if force
15137 (save-excursion
15138 (org-insert-property-drawer)
15139 (setq end (progn (outline-next-heading) (point))))
15140 (throw 'exit nil))
15141 (goto-char beg)
15142 (if (re-search-forward org-property-start-re end t)
15143 (setq beg (1+ (match-end 0)))))
15144 (if (re-search-forward org-property-end-re end t)
15145 (setq end (match-beginning 0))
15146 (or force (throw 'exit nil))
15147 (goto-char beg)
15148 (setq end beg)
15149 (org-indent-line)
15150 (insert ":END:\n"))
15151 (cons beg end)))))
15153 (defun org-entry-properties (&optional pom which specific)
15154 "Get all properties of the entry at point-or-marker POM.
15155 This includes the TODO keyword, the tags, time strings for deadline,
15156 scheduled, and clocking, and any additional properties defined in the
15157 entry. The return value is an alist, keys may occur multiple times
15158 if the property key was used several times.
15159 POM may also be nil, in which case the current entry is used.
15160 If WHICH is nil or `all', get all properties. If WHICH is
15161 `special' or `standard', only get that subclass. If WHICH
15162 is a string only get exactly this property. SPECIFIC can be a string, the
15163 specific property we are interested in. Specifying it can speed
15164 things up because then unnecessary parsing is avoided."
15165 (setq which (or which 'all))
15166 (org-with-point-at pom
15167 (let ((clockstr (substring org-clock-string 0 -1))
15168 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15169 (case-fold-search nil)
15170 beg end range props sum-props key key1 value string clocksum clocksumt)
15171 (save-excursion
15172 (when (condition-case nil
15173 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
15174 (error nil))
15175 (setq beg (point))
15176 (setq sum-props (get-text-property (point) 'org-summaries))
15177 (setq clocksum (get-text-property (point) :org-clock-minutes)
15178 clocksumt (get-text-property (point) :org-clock-minutes-today))
15179 (outline-next-heading)
15180 (setq end (point))
15181 (when (memq which '(all special))
15182 ;; Get the special properties, like TODO and tags
15183 (goto-char beg)
15184 (when (and (or (not specific) (string= specific "TODO"))
15185 (looking-at org-todo-line-regexp) (match-end 2))
15186 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15187 (when (and (or (not specific) (string= specific "PRIORITY"))
15188 (looking-at org-priority-regexp))
15189 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15190 (when (or (not specific) (string= specific "FILE"))
15191 (push (cons "FILE" buffer-file-name) props))
15192 (when (and (or (not specific) (string= specific "TAGS"))
15193 (setq value (org-get-tags-string))
15194 (string-match "\\S-" value))
15195 (push (cons "TAGS" value) props))
15196 (when (and (or (not specific) (string= specific "ALLTAGS"))
15197 (setq value (org-get-tags-at)))
15198 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15199 ":"))
15200 props))
15201 (when (or (not specific) (string= specific "BLOCKED"))
15202 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15203 (when (or (not specific)
15204 (member specific
15205 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15206 "TIMESTAMP" "TIMESTAMP_IA")))
15207 (catch 'match
15208 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15209 (setq key (if (match-end 1)
15210 (substring (org-match-string-no-properties 1)
15211 0 -1))
15212 string (if (equal key clockstr)
15213 (org-trim
15214 (buffer-substring-no-properties
15215 (match-beginning 3) (goto-char
15216 (point-at-eol))))
15217 (substring (org-match-string-no-properties 3)
15218 1 -1)))
15219 ;; Get the correct property name from the key. This is
15220 ;; necessary if the user has configured time keywords.
15221 (setq key1 (concat key ":"))
15222 (cond
15223 ((not key)
15224 (setq key
15225 (if (= (char-after (match-beginning 3)) ?\[)
15226 "TIMESTAMP_IA" "TIMESTAMP")))
15227 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15228 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15229 ((equal key1 org-closed-string) (setq key "CLOSED"))
15230 ((equal key1 org-clock-string) (setq key "CLOCK")))
15231 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15232 (progn
15233 (push (cons key string) props)
15234 ;; no need to search further if match is found
15235 (throw 'match t))
15236 (when (or (equal key "CLOCK") (not (assoc key props)))
15237 (push (cons key string) props)))))))
15239 (when (memq which '(all standard))
15240 ;; Get the standard properties, like :PROP: ...
15241 (setq range (org-get-property-block beg end))
15242 (when range
15243 (goto-char (car range))
15244 (while (re-search-forward org-property-re
15245 (cdr range) t)
15246 (setq key (org-match-string-no-properties 2)
15247 value (org-trim (or (org-match-string-no-properties 3) "")))
15248 (unless (member key excluded)
15249 (push (cons key (or value "")) props)))))
15250 (if clocksum
15251 (push (cons "CLOCKSUM"
15252 (org-columns-number-to-string (/ (float clocksum) 60.)
15253 'add_times))
15254 props))
15255 (if clocksumt
15256 (push (cons "CLOCKSUM_T"
15257 (org-columns-number-to-string (/ (float clocksumt) 60.)
15258 'add_times))
15259 props))
15260 (unless (assoc "CATEGORY" props)
15261 (push (cons "CATEGORY" (org-get-category)) props))
15262 (append sum-props (nreverse props)))))))
15264 (defun org-entry-get (pom property &optional inherit literal-nil)
15265 "Get value of PROPERTY for entry or content at point-or-marker POM.
15266 If INHERIT is non-nil and the entry does not have the property,
15267 then also check higher levels of the hierarchy.
15268 If INHERIT is the symbol `selective', use inheritance only if the setting
15269 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15270 If the property is present but empty, the return value is the empty string.
15271 If the property is not present at all, nil is returned.
15273 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15274 do not interpret it as the list atom nil. This is used for inheritance
15275 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15276 (org-with-point-at pom
15277 (if (and inherit (if (eq inherit 'selective)
15278 (org-property-inherit-p property)
15280 (org-entry-get-with-inheritance property literal-nil)
15281 (if (member property org-special-properties)
15282 ;; We need a special property. Use `org-entry-properties' to
15283 ;; retrieve it, but specify the wanted property
15284 (cdr (assoc property (org-entry-properties nil 'special property)))
15285 (let ((range (org-get-property-block)))
15286 (when (and range (not (eq (car range) (cdr range))))
15287 (let* ((props (list (or (assoc property org-file-properties)
15288 (assoc property org-global-properties)
15289 (assoc property org-global-properties-fixed))))
15290 (ap (lambda (key)
15291 (when (re-search-forward
15292 (org-re-property key) (cdr range) t)
15293 (setq props
15294 (org-update-property-plist
15296 (if (match-end 3)
15297 (org-match-string-no-properties 3) "")
15298 props)))))
15299 val)
15300 (goto-char (car range))
15301 (funcall ap property)
15302 (goto-char (car range))
15303 (while (funcall ap (concat property "+")))
15304 (setq val (cdr (assoc property props)))
15305 (when val (if literal-nil val (org-not-nil val))))))))))
15307 (defun org-property-or-variable-value (var &optional inherit)
15308 "Check if there is a property fixing the value of VAR.
15309 If yes, return this value. If not, return the current value of the variable."
15310 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15311 (if (and prop (stringp prop) (string-match "\\S-" prop))
15312 (read prop)
15313 (symbol-value var))))
15315 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15316 "Delete the property PROPERTY from entry at point-or-marker POM.
15317 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15318 an empty drawer to delete."
15319 (org-with-point-at pom
15320 (if (member property org-special-properties)
15321 nil ; cannot delete these properties.
15322 (let ((range (org-get-property-block)))
15323 (if (and range
15324 (goto-char (car range))
15325 (re-search-forward
15326 (org-re-property property)
15327 (cdr range) t))
15328 (progn
15329 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15330 (and delete-empty-drawer
15331 (org-remove-empty-drawer-at
15332 delete-empty-drawer (car range)))
15334 nil)))))
15336 ;; Multi-values properties are properties that contain multiple values
15337 ;; These values are assumed to be single words, separated by whitespace.
15338 (defun org-entry-add-to-multivalued-property (pom property value)
15339 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15340 (let* ((old (org-entry-get pom property))
15341 (values (and old (org-split-string old "[ \t]"))))
15342 (setq value (org-entry-protect-space value))
15343 (unless (member value values)
15344 (setq values (append values (list value)))
15345 (org-entry-put pom property
15346 (mapconcat 'identity values " ")))))
15348 (defun org-entry-remove-from-multivalued-property (pom property value)
15349 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15350 (let* ((old (org-entry-get pom property))
15351 (values (and old (org-split-string old "[ \t]"))))
15352 (setq value (org-entry-protect-space value))
15353 (when (member value values)
15354 (setq values (delete value values))
15355 (org-entry-put pom property
15356 (mapconcat 'identity values " ")))))
15358 (defun org-entry-member-in-multivalued-property (pom property value)
15359 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15360 (let* ((old (org-entry-get pom property))
15361 (values (and old (org-split-string old "[ \t]"))))
15362 (setq value (org-entry-protect-space value))
15363 (member value values)))
15365 (defun org-entry-get-multivalued-property (pom property)
15366 "Return a list of values in a multivalued property."
15367 (let* ((value (org-entry-get pom property))
15368 (values (and value (org-split-string value "[ \t]"))))
15369 (mapcar 'org-entry-restore-space values)))
15371 (defun org-entry-put-multivalued-property (pom property &rest values)
15372 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15373 VALUES should be a list of strings. Spaces will be protected."
15374 (org-entry-put pom property
15375 (mapconcat 'org-entry-protect-space values " "))
15376 (let* ((value (org-entry-get pom property))
15377 (values (and value (org-split-string value "[ \t]"))))
15378 (mapcar 'org-entry-restore-space values)))
15380 (defun org-entry-protect-space (s)
15381 "Protect spaces and newline in string S."
15382 (while (string-match " " s)
15383 (setq s (replace-match "%20" t t s)))
15384 (while (string-match "\n" s)
15385 (setq s (replace-match "%0A" t t s)))
15388 (defun org-entry-restore-space (s)
15389 "Restore spaces and newline in string S."
15390 (while (string-match "%20" s)
15391 (setq s (replace-match " " t t s)))
15392 (while (string-match "%0A" s)
15393 (setq s (replace-match "\n" t t s)))
15396 (defvar org-entry-property-inherited-from (make-marker)
15397 "Marker pointing to the entry from where a property was inherited.
15398 Each call to `org-entry-get-with-inheritance' will set this marker to the
15399 location of the entry where the inheritance search matched. If there was
15400 no match, the marker will point nowhere.
15401 Note that also `org-entry-get' calls this function, if the INHERIT flag
15402 is set.")
15404 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15405 "Get PROPERTY of entry or content at point, search higher levels if needed.
15406 The search will stop at the first ancestor which has the property defined.
15407 If the value found is \"nil\", return nil to show that the property
15408 should be considered as undefined (this is the meaning of nil here).
15409 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15410 (move-marker org-entry-property-inherited-from nil)
15411 (let (tmp)
15412 (save-excursion
15413 (save-restriction
15414 (widen)
15415 (catch 'ex
15416 (while t
15417 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15418 (or (ignore-errors (org-back-to-heading t))
15419 (goto-char (point-min)))
15420 (move-marker org-entry-property-inherited-from (point))
15421 (throw 'ex tmp))
15422 (or (ignore-errors (org-up-heading-safe))
15423 (throw 'ex nil))))))
15424 (setq tmp (or tmp
15425 (cdr (assoc property org-file-properties))
15426 (cdr (assoc property org-global-properties))
15427 (cdr (assoc property org-global-properties-fixed))))
15428 (if literal-nil tmp (org-not-nil tmp))))
15430 (defvar org-property-changed-functions nil
15431 "Hook called when the value of a property has changed.
15432 Each hook function should accept two arguments, the name of the property
15433 and the new value.")
15435 (defun org-entry-put (pom property value)
15436 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15437 (org-with-point-at pom
15438 (org-back-to-heading t)
15439 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15440 range)
15441 (cond
15442 ((equal property "TODO")
15443 (when (and (stringp value) (string-match "\\S-" value)
15444 (not (member value org-todo-keywords-1)))
15445 (user-error "\"%s\" is not a valid TODO state" value))
15446 (if (or (not value)
15447 (not (string-match "\\S-" value)))
15448 (setq value 'none))
15449 (org-todo value)
15450 (org-set-tags nil 'align))
15451 ((equal property "PRIORITY")
15452 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15453 (string-to-char value) ?\ ))
15454 (org-set-tags nil 'align))
15455 ((equal property "CLOCKSUM")
15456 (if (not (re-search-forward
15457 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15458 (error "Cannot find a clock log")
15459 (goto-char (- (match-end 1) 2))
15460 (cond
15461 ((eq value 'earlier) (org-timestamp-down))
15462 ((eq value 'later) (org-timestamp-up)))
15463 (org-clock-sum-current-item)))
15464 ((equal property "SCHEDULED")
15465 (if (re-search-forward org-scheduled-time-regexp end t)
15466 (cond
15467 ((eq value 'earlier) (org-timestamp-change -1 'day))
15468 ((eq value 'later) (org-timestamp-change 1 'day))
15469 (t (call-interactively 'org-schedule)))
15470 (call-interactively 'org-schedule)))
15471 ((equal property "DEADLINE")
15472 (if (re-search-forward org-deadline-time-regexp end t)
15473 (cond
15474 ((eq value 'earlier) (org-timestamp-change -1 'day))
15475 ((eq value 'later) (org-timestamp-change 1 'day))
15476 (t (call-interactively 'org-deadline)))
15477 (call-interactively 'org-deadline)))
15478 ((member property org-special-properties)
15479 (error "The %s property can not yet be set with `org-entry-put'"
15480 property))
15481 (t ; a non-special property
15482 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15483 (setq range (org-get-property-block beg end 'force))
15484 (goto-char (car range))
15485 (if (re-search-forward
15486 (org-re-property property) (cdr range) t)
15487 (progn
15488 (delete-region (match-beginning 0) (match-end 0))
15489 (goto-char (match-beginning 0)))
15490 (goto-char (cdr range))
15491 (insert "\n")
15492 (backward-char 1)
15493 (org-indent-line))
15494 (insert ":" property ":")
15495 (and value (insert " " value))
15496 (org-indent-line)))))
15497 (run-hook-with-args 'org-property-changed-functions property value)))
15499 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15500 "Get all property keys in the current buffer.
15501 With INCLUDE-SPECIALS, also list the special properties that reflect things
15502 like tags and TODO state.
15503 With INCLUDE-DEFAULTS, also include properties that has special meaning
15504 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15505 and others.
15506 With INCLUDE-COLUMNS, also include property names given in COLUMN
15507 formats in the current buffer."
15508 (let (rtn range cfmt s p)
15509 (save-excursion
15510 (save-restriction
15511 (widen)
15512 (goto-char (point-min))
15513 (while (re-search-forward org-property-start-re nil t)
15514 (setq range (org-get-property-block))
15515 (goto-char (car range))
15516 (while (re-search-forward org-property-re
15517 (cdr range) t)
15518 (add-to-list 'rtn (org-match-string-no-properties 2)))
15519 (outline-next-heading))))
15521 (when include-specials
15522 (setq rtn (append org-special-properties rtn)))
15524 (when include-defaults
15525 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15526 (add-to-list 'rtn org-effort-property))
15528 (when include-columns
15529 (save-excursion
15530 (save-restriction
15531 (widen)
15532 (goto-char (point-min))
15533 (while (re-search-forward
15534 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15535 nil t)
15536 (setq cfmt (match-string 2) s 0)
15537 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15538 cfmt s)
15539 (setq s (match-end 0)
15540 p (match-string 1 cfmt))
15541 (unless (or (equal p "ITEM")
15542 (member p org-special-properties))
15543 (add-to-list 'rtn (match-string 1 cfmt))))))))
15545 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15547 (defun org-property-values (key)
15548 "Return a list of all values of property KEY in the current buffer."
15549 (save-excursion
15550 (save-restriction
15551 (widen)
15552 (goto-char (point-min))
15553 (let ((re (org-re-property key))
15554 values)
15555 (while (re-search-forward re nil t)
15556 (add-to-list 'values (org-trim (match-string 3))))
15557 (delete "" values)))))
15559 (defun org-insert-property-drawer ()
15560 "Insert a property drawer into the current entry."
15561 (org-back-to-heading t)
15562 (looking-at org-outline-regexp)
15563 (let ((indent (if org-adapt-indentation
15564 (- (match-end 0) (match-beginning 0))
15566 (beg (point))
15567 (re (concat "^[ \t]*" org-keyword-time-regexp))
15568 end hiddenp)
15569 (outline-next-heading)
15570 (setq end (point))
15571 (goto-char beg)
15572 (while (re-search-forward re end t))
15573 (setq hiddenp (outline-invisible-p))
15574 (end-of-line 1)
15575 (and (equal (char-after) ?\n) (forward-char 1))
15576 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15577 (if (member (match-string 1) '("CLOCK:" ":END:"))
15578 ;; just skip this line
15579 (beginning-of-line 2)
15580 ;; Drawer start, find the end
15581 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15582 (beginning-of-line 1)))
15583 (org-skip-over-state-notes)
15584 (skip-chars-backward " \t\n\r")
15585 (if (eq (char-before) ?*) (forward-char 1))
15586 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15587 (beginning-of-line 0)
15588 (org-indent-to-column indent)
15589 (beginning-of-line 2)
15590 (org-indent-to-column indent)
15591 (beginning-of-line 0)
15592 (if hiddenp
15593 (save-excursion
15594 (org-back-to-heading t)
15595 (hide-entry))
15596 (org-flag-drawer t))))
15598 (defun org-insert-drawer (&optional arg drawer)
15599 "Insert a drawer at point.
15601 Optional argument DRAWER, when non-nil, is a string representing
15602 drawer's name. Otherwise, the user is prompted for a name.
15604 If a region is active, insert the drawer around that region
15605 instead.
15607 Point is left between drawer's boundaries."
15608 (interactive "P")
15609 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15610 "LOGBOOK"))
15611 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15612 ;; internally by Org. They are meant to be inserted
15613 ;; automatically.
15614 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15615 ;; Remove system drawers from list. Note: For some reason,
15616 ;; `org-completing-read' ignores the predicate while
15617 ;; `completing-read' handles it fine.
15618 (drawer (if arg "PROPERTIES"
15619 (or drawer
15620 (completing-read
15621 "Drawer: " org-drawers
15622 (lambda (d) (not (member d system-drawers))))))))
15623 (cond
15624 ;; With C-u, fall back on `org-insert-property-drawer'
15625 (arg (org-insert-property-drawer))
15626 ;; With an active region, insert a drawer at point.
15627 ((not (org-region-active-p))
15628 (progn
15629 (unless (bolp) (insert "\n"))
15630 (insert (format ":%s:\n\n:END:\n" drawer))
15631 (forward-line -2)))
15632 ;; Otherwise, insert the drawer at point
15634 (let ((rbeg (region-beginning))
15635 (rend (copy-marker (region-end))))
15636 (unwind-protect
15637 (progn
15638 (goto-char rbeg)
15639 (beginning-of-line)
15640 (when (save-excursion
15641 (re-search-forward org-outline-regexp-bol rend t))
15642 (user-error "Drawers cannot contain headlines"))
15643 ;; Position point at the beginning of the first
15644 ;; non-blank line in region. Insert drawer's opening
15645 ;; there, then indent it.
15646 (org-skip-whitespace)
15647 (beginning-of-line)
15648 (insert ":" drawer ":\n")
15649 (forward-line -1)
15650 (indent-for-tab-command)
15651 ;; Move point to the beginning of the first blank line
15652 ;; after the last non-blank line in region. Insert
15653 ;; drawer's closing, then indent it.
15654 (goto-char rend)
15655 (skip-chars-backward " \r\t\n")
15656 (insert "\n:END:")
15657 (deactivate-mark t)
15658 (indent-for-tab-command)
15659 (unless (eolp) (insert "\n")))
15660 ;; Clear marker, whatever the outcome of insertion is.
15661 (set-marker rend nil)))))))
15663 (defvar org-property-set-functions-alist nil
15664 "Property set function alist.
15665 Each entry should have the following format:
15667 (PROPERTY . READ-FUNCTION)
15669 The read function will be called with the same argument as
15670 `org-completing-read'.")
15672 (defun org-set-property-function (property)
15673 "Get the function that should be used to set PROPERTY.
15674 This is computed according to `org-property-set-functions-alist'."
15675 (or (cdr (assoc property org-property-set-functions-alist))
15676 'org-completing-read))
15678 (defun org-read-property-value (property)
15679 "Read PROPERTY value from user."
15680 (let* ((completion-ignore-case t)
15681 (allowed (org-property-get-allowed-values nil property 'table))
15682 (cur (org-entry-get nil property))
15683 (prompt (concat property " value"
15684 (if (and cur (string-match "\\S-" cur))
15685 (concat " [" cur "]") "") ": "))
15686 (set-function (org-set-property-function property))
15687 (val (if allowed
15688 (funcall set-function prompt allowed nil
15689 (not (get-text-property 0 'org-unrestricted
15690 (caar allowed))))
15691 (let (org-completion-use-ido org-completion-use-iswitchb)
15692 (funcall set-function prompt
15693 (mapcar 'list (org-property-values property))
15694 nil nil "" nil cur)))))
15695 (if (equal val "")
15697 val)))
15699 (defvar org-last-set-property nil)
15700 (defvar org-last-set-property-value nil)
15701 (defun org-read-property-name ()
15702 "Read a property name."
15703 (let* ((completion-ignore-case t)
15704 (keys (org-buffer-property-keys nil t t))
15705 (default-prop (or (save-excursion
15706 (save-match-data
15707 (beginning-of-line)
15708 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15709 (null (string= (match-string 1) "END"))
15710 (match-string 1))))
15711 org-last-set-property))
15712 (property (org-icompleting-read
15713 (concat "Property"
15714 (if default-prop (concat " [" default-prop "]") "")
15715 ": ")
15716 (mapcar 'list keys)
15717 nil nil nil nil
15718 default-prop)))
15719 (if (member property keys)
15720 property
15721 (or (cdr (assoc (downcase property)
15722 (mapcar (lambda (x) (cons (downcase x) x))
15723 keys)))
15724 property))))
15726 (defun org-set-property-and-value (use-last)
15727 "Allow to set [PROPERTY]: [value] direction from prompt.
15728 When use-default, don't even ask, just use the last
15729 \"[PROPERTY]: [value]\" string from the history."
15730 (interactive "P")
15731 (let* ((completion-ignore-case t)
15732 (pv (or (and use-last org-last-set-property-value)
15733 (org-completing-read
15734 "Enter a \"[Property]: [value]\" pair: "
15735 nil nil nil nil nil
15736 org-last-set-property-value)))
15737 prop val)
15738 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15739 (setq prop (match-string 1 pv)
15740 val (match-string 2 pv))
15741 (org-set-property prop val))))
15743 (defun org-set-property (property value)
15744 "In the current entry, set PROPERTY to VALUE.
15745 When called interactively, this will prompt for a property name, offering
15746 completion on existing and default properties. And then it will prompt
15747 for a value, offering completion either on allowed values (via an inherited
15748 xxx_ALL property) or on existing values in other instances of this property
15749 in the current file."
15750 (interactive (list nil nil))
15751 (let* ((property (or property (org-read-property-name)))
15752 (value (or value (org-read-property-value property)))
15753 (fn (cdr (assoc property org-properties-postprocess-alist))))
15754 (setq org-last-set-property property)
15755 (setq org-last-set-property-value (concat property ": " value))
15756 ;; Possibly postprocess the inserted value:
15757 (when fn (setq value (funcall fn value)))
15758 (unless (equal (org-entry-get nil property) value)
15759 (org-entry-put nil property value))))
15761 (defun org-delete-property (property &optional delete-empty-drawer)
15762 "In the current entry, delete PROPERTY.
15763 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15764 an empty drawer to delete."
15765 (interactive
15766 (let* ((completion-ignore-case t)
15767 (prop (org-icompleting-read "Property: "
15768 (org-entry-properties nil 'standard))))
15769 (list prop)))
15770 (message "Property %s %s" property
15771 (if (org-entry-delete nil property delete-empty-drawer)
15772 "deleted"
15773 "was not present in the entry")))
15775 (defun org-delete-property-globally (property)
15776 "Remove PROPERTY globally, from all entries."
15777 (interactive
15778 (let* ((completion-ignore-case t)
15779 (prop (org-icompleting-read
15780 "Globally remove property: "
15781 (mapcar 'list (org-buffer-property-keys)))))
15782 (list prop)))
15783 (save-excursion
15784 (save-restriction
15785 (widen)
15786 (goto-char (point-min))
15787 (let ((cnt 0))
15788 (while (re-search-forward
15789 (org-re-property property)
15790 nil t)
15791 (setq cnt (1+ cnt))
15792 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15793 (message "Property \"%s\" removed from %d entries" property cnt)))))
15795 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15797 (defun org-compute-property-at-point ()
15798 "Compute the property at point.
15799 This looks for an enclosing column format, extracts the operator and
15800 then applies it to the property in the column format's scope."
15801 (interactive)
15802 (unless (org-at-property-p)
15803 (user-error "Not at a property"))
15804 (let ((prop (org-match-string-no-properties 2)))
15805 (org-columns-get-format-and-top-level)
15806 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15807 (user-error "No operator defined for property %s" prop))
15808 (org-columns-compute prop)))
15810 (defvar org-property-allowed-value-functions nil
15811 "Hook for functions supplying allowed values for a specific property.
15812 The functions must take a single argument, the name of the property, and
15813 return a flat list of allowed values. If \":ETC\" is one of
15814 the values, this means that these values are intended as defaults for
15815 completion, but that other values should be allowed too.
15816 The functions must return nil if they are not responsible for this
15817 property.")
15819 (defun org-property-get-allowed-values (pom property &optional table)
15820 "Get allowed values for the property PROPERTY.
15821 When TABLE is non-nil, return an alist that can directly be used for
15822 completion."
15823 (let (vals)
15824 (cond
15825 ((equal property "TODO")
15826 (setq vals (org-with-point-at pom
15827 (append org-todo-keywords-1 '("")))))
15828 ((equal property "PRIORITY")
15829 (let ((n org-lowest-priority))
15830 (while (>= n org-highest-priority)
15831 (push (char-to-string n) vals)
15832 (setq n (1- n)))))
15833 ((member property org-special-properties))
15834 ((setq vals (run-hook-with-args-until-success
15835 'org-property-allowed-value-functions property)))
15837 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15838 (when (and vals (string-match "\\S-" vals))
15839 (setq vals (car (read-from-string (concat "(" vals ")"))))
15840 (setq vals (mapcar (lambda (x)
15841 (cond ((stringp x) x)
15842 ((numberp x) (number-to-string x))
15843 ((symbolp x) (symbol-name x))
15844 (t "???")))
15845 vals)))))
15846 (when (member ":ETC" vals)
15847 (setq vals (remove ":ETC" vals))
15848 (org-add-props (car vals) '(org-unrestricted t)))
15849 (if table (mapcar 'list vals) vals)))
15851 (defun org-property-previous-allowed-value (&optional previous)
15852 "Switch to the next allowed value for this property."
15853 (interactive)
15854 (org-property-next-allowed-value t))
15856 (defun org-property-next-allowed-value (&optional previous)
15857 "Switch to the next allowed value for this property."
15858 (interactive)
15859 (unless (org-at-property-p)
15860 (user-error "Not at a property"))
15861 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15862 (key (match-string 2))
15863 (value (match-string 3))
15864 (allowed (or (org-property-get-allowed-values (point) key)
15865 (and (member value '("[ ]" "[-]" "[X]"))
15866 '("[ ]" "[X]"))))
15867 (heading (save-match-data (nth 4 (org-heading-components))))
15868 nval)
15869 (unless allowed
15870 (user-error "Allowed values for this property have not been defined"))
15871 (if previous (setq allowed (reverse allowed)))
15872 (if (member value allowed)
15873 (setq nval (car (cdr (member value allowed)))))
15874 (setq nval (or nval (car allowed)))
15875 (if (equal nval value)
15876 (user-error "Only one allowed value for this property"))
15877 (org-at-property-p)
15878 (replace-match (concat " :" key ": " nval) t t)
15879 (org-indent-line)
15880 (beginning-of-line 1)
15881 (skip-chars-forward " \t")
15882 (when (equal prop org-effort-property)
15883 (save-excursion
15884 (org-back-to-heading t)
15885 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15886 (when (string= org-clock-current-task heading)
15887 (setq org-clock-effort nval)
15888 (org-clock-update-mode-line)))
15889 (run-hook-with-args 'org-property-changed-functions key nval)))
15891 (defun org-find-olp (path &optional this-buffer)
15892 "Return a marker pointing to the entry at outline path OLP.
15893 If anything goes wrong, throw an error.
15894 You can wrap this call to catch the error like this:
15896 (condition-case msg
15897 (org-mobile-locate-entry (match-string 4))
15898 (error (nth 1 msg)))
15900 The return value will then be either a string with the error message,
15901 or a marker if everything is OK.
15903 If THIS-BUFFER is set, the outline path does not contain a file,
15904 only headings."
15905 (let* ((file (if this-buffer buffer-file-name (pop path)))
15906 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15907 (level 1)
15908 (lmin 1)
15909 (lmax 1)
15910 limit re end found pos heading cnt flevel)
15911 (unless buffer (error "File not found :%s" file))
15912 (with-current-buffer buffer
15913 (save-excursion
15914 (save-restriction
15915 (widen)
15916 (setq limit (point-max))
15917 (goto-char (point-min))
15918 (while (setq heading (pop path))
15919 (setq re (format org-complex-heading-regexp-format
15920 (regexp-quote heading)))
15921 (setq cnt 0 pos (point))
15922 (while (re-search-forward re end t)
15923 (setq level (- (match-end 1) (match-beginning 1)))
15924 (if (and (>= level lmin) (<= level lmax))
15925 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15926 (when (= cnt 0) (error "Heading not found on level %d: %s"
15927 lmax heading))
15928 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15929 lmax heading))
15930 (goto-char found)
15931 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15932 (setq end (save-excursion (org-end-of-subtree t t))))
15933 (when (org-at-heading-p)
15934 (point-marker)))))))
15936 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15937 "Find node HEADING in BUFFER.
15938 Return a marker to the heading if it was found, or nil if not.
15939 If POS-ONLY is set, return just the position instead of a marker.
15941 The heading text must match exact, but it may have a TODO keyword,
15942 a priority cookie and tags in the standard locations."
15943 (with-current-buffer (or buffer (current-buffer))
15944 (save-excursion
15945 (save-restriction
15946 (widen)
15947 (goto-char (point-min))
15948 (let (case-fold-search)
15949 (if (re-search-forward
15950 (format org-complex-heading-regexp-format
15951 (regexp-quote heading)) nil t)
15952 (if pos-only
15953 (match-beginning 0)
15954 (move-marker (make-marker) (match-beginning 0)))))))))
15956 (defun org-find-exact-heading-in-directory (heading &optional dir)
15957 "Find Org node headline HEADING in all .org files in directory DIR.
15958 When the target headline is found, return a marker to this location."
15959 (let ((files (directory-files (or dir default-directory)
15960 nil "\\`[^.#].*\\.org\\'"))
15961 file visiting m buffer)
15962 (catch 'found
15963 (while (setq file (pop files))
15964 (message "trying %s" file)
15965 (setq visiting (org-find-base-buffer-visiting file))
15966 (setq buffer (or visiting (find-file-noselect file)))
15967 (setq m (org-find-exact-headline-in-buffer
15968 heading buffer))
15969 (when (and (not m) (not visiting)) (kill-buffer buffer))
15970 (and m (throw 'found m))))))
15972 (defun org-find-entry-with-id (ident)
15973 "Locate the entry that contains the ID property with exact value IDENT.
15974 IDENT can be a string, a symbol or a number, this function will search for
15975 the string representation of it.
15976 Return the position where this entry starts, or nil if there is no such entry."
15977 (interactive "sID: ")
15978 (let ((id (cond
15979 ((stringp ident) ident)
15980 ((symbol-name ident) (symbol-name ident))
15981 ((numberp ident) (number-to-string ident))
15982 (t (error "IDENT %s must be a string, symbol or number" ident))))
15983 (case-fold-search nil))
15984 (save-excursion
15985 (save-restriction
15986 (widen)
15987 (goto-char (point-min))
15988 (when (re-search-forward
15989 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15990 nil t)
15991 (org-back-to-heading t)
15992 (point))))))
15994 ;;;; Timestamps
15996 (defvar org-last-changed-timestamp nil)
15997 (defvar org-last-inserted-timestamp nil
15998 "The last time stamp inserted with `org-insert-time-stamp'.")
15999 (defvar org-time-was-given) ; dynamically scoped parameter
16000 (defvar org-end-time-was-given) ; dynamically scoped parameter
16001 (defvar org-ts-what) ; dynamically scoped parameter
16003 (defun org-time-stamp (arg &optional inactive)
16004 "Prompt for a date/time and insert a time stamp.
16005 If the user specifies a time like HH:MM or if this command is
16006 called with at least one prefix argument, the time stamp contains
16007 the date and the time. Otherwise, only the date is be included.
16009 All parts of a date not specified by the user is filled in from
16010 the current date/time. So if you just press return without
16011 typing anything, the time stamp will represent the current
16012 date/time.
16014 If there is already a timestamp at the cursor, it will be
16015 modified.
16017 With two universal prefix arguments, insert an active timestamp
16018 with the current time without prompting the user."
16019 (interactive "P")
16020 (let* ((ts nil)
16021 (default-time
16022 ;; Default time is either today, or, when entering a range,
16023 ;; the range start.
16024 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16025 (save-excursion
16026 (re-search-backward
16027 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16028 (- (point) 20) t)))
16029 (apply 'encode-time (org-parse-time-string (match-string 1)))
16030 (current-time)))
16031 (default-input (and ts (org-get-compact-tod ts)))
16032 (repeater (save-excursion
16033 (save-match-data
16034 (beginning-of-line)
16035 (when (re-search-forward
16036 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16037 (save-excursion (progn (end-of-line) (point))) t)
16038 (match-string 0)))))
16039 org-time-was-given org-end-time-was-given time)
16040 (cond
16041 ((and (org-at-timestamp-p t)
16042 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16043 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16044 (insert "--")
16045 (setq time (let ((this-command this-command))
16046 (org-read-date arg 'totime nil nil
16047 default-time default-input inactive)))
16048 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16049 ((org-at-timestamp-p t)
16050 (setq time (let ((this-command this-command))
16051 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16052 (when (org-at-timestamp-p t) ; just to get the match data
16053 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16054 (replace-match "")
16055 (setq org-last-changed-timestamp
16056 (org-insert-time-stamp
16057 time (or org-time-was-given arg)
16058 inactive nil nil (list org-end-time-was-given)))
16059 (when repeater (goto-char (1- (point))) (insert " " repeater)
16060 (setq org-last-changed-timestamp
16061 (concat (substring org-last-inserted-timestamp 0 -1)
16062 " " repeater ">"))))
16063 (message "Timestamp updated"))
16064 ((equal arg '(16))
16065 (org-insert-time-stamp (current-time) t))
16067 (setq time (let ((this-command this-command))
16068 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16069 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16070 nil nil (list org-end-time-was-given))))))
16072 ;; FIXME: can we use this for something else, like computing time differences?
16073 (defun org-get-compact-tod (s)
16074 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16075 (let* ((t1 (match-string 1 s))
16076 (h1 (string-to-number (match-string 2 s)))
16077 (m1 (string-to-number (match-string 3 s)))
16078 (t2 (and (match-end 4) (match-string 5 s)))
16079 (h2 (and t2 (string-to-number (match-string 6 s))))
16080 (m2 (and t2 (string-to-number (match-string 7 s))))
16081 dh dm)
16082 (if (not t2)
16084 (setq dh (- h2 h1) dm (- m2 m1))
16085 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16086 (concat t1 "+" (number-to-string dh)
16087 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
16089 (defun org-time-stamp-inactive (&optional arg)
16090 "Insert an inactive time stamp.
16091 An inactive time stamp is enclosed in square brackets instead of angle
16092 brackets. It is inactive in the sense that it does not trigger agenda entries,
16093 does not link to the calendar and cannot be changed with the S-cursor keys.
16094 So these are more for recording a certain time/date."
16095 (interactive "P")
16096 (org-time-stamp arg 'inactive))
16098 (defvar org-date-ovl (make-overlay 1 1))
16099 (overlay-put org-date-ovl 'face 'org-date-selected)
16100 (org-detach-overlay org-date-ovl)
16102 (defvar org-ans1) ; dynamically scoped parameter
16103 (defvar org-ans2) ; dynamically scoped parameter
16105 (defvar org-plain-time-of-day-regexp) ; defined below
16107 (defvar org-overriding-default-time nil) ; dynamically scoped
16108 (defvar org-read-date-overlay nil)
16109 (defvar org-dcst nil) ; dynamically scoped
16110 (defvar org-read-date-history nil)
16111 (defvar org-read-date-final-answer nil)
16112 (defvar org-read-date-analyze-futurep nil)
16113 (defvar org-read-date-analyze-forced-year nil)
16114 (defvar org-read-date-inactive)
16116 (defvar org-read-date-minibuffer-local-map
16117 (let ((map (make-sparse-keymap)))
16118 (set-keymap-parent map minibuffer-local-map)
16119 (org-defkey map (kbd ".")
16120 (lambda () (interactive)
16121 ;; Are we at the beginning of the prompt?
16122 (if (looking-back "^[^:]+: ")
16123 (org-eval-in-calendar '(calendar-goto-today))
16124 (insert "."))))
16125 (org-defkey map (kbd "C-.")
16126 (lambda () (interactive)
16127 (org-eval-in-calendar '(calendar-goto-today))))
16128 (org-defkey map [(meta shift left)]
16129 (lambda () (interactive)
16130 (org-eval-in-calendar '(calendar-backward-month 1))))
16131 (org-defkey map [(meta shift right)]
16132 (lambda () (interactive)
16133 (org-eval-in-calendar '(calendar-forward-month 1))))
16134 (org-defkey map [(meta shift up)]
16135 (lambda () (interactive)
16136 (org-eval-in-calendar '(calendar-backward-year 1))))
16137 (org-defkey map [(meta shift down)]
16138 (lambda () (interactive)
16139 (org-eval-in-calendar '(calendar-forward-year 1))))
16140 (org-defkey map [?\e (shift left)]
16141 (lambda () (interactive)
16142 (org-eval-in-calendar '(calendar-backward-month 1))))
16143 (org-defkey map [?\e (shift right)]
16144 (lambda () (interactive)
16145 (org-eval-in-calendar '(calendar-forward-month 1))))
16146 (org-defkey map [?\e (shift up)]
16147 (lambda () (interactive)
16148 (org-eval-in-calendar '(calendar-backward-year 1))))
16149 (org-defkey map [?\e (shift down)]
16150 (lambda () (interactive)
16151 (org-eval-in-calendar '(calendar-forward-year 1))))
16152 (org-defkey map [(shift up)]
16153 (lambda () (interactive)
16154 (org-eval-in-calendar '(calendar-backward-week 1))))
16155 (org-defkey map [(shift down)]
16156 (lambda () (interactive)
16157 (org-eval-in-calendar '(calendar-forward-week 1))))
16158 (org-defkey map [(shift left)]
16159 (lambda () (interactive)
16160 (org-eval-in-calendar '(calendar-backward-day 1))))
16161 (org-defkey map [(shift right)]
16162 (lambda () (interactive)
16163 (org-eval-in-calendar '(calendar-forward-day 1))))
16164 (org-defkey map "!"
16165 (lambda () (interactive)
16166 (org-eval-in-calendar '(diary-view-entries))
16167 (message "")))
16168 (org-defkey map ">"
16169 (lambda () (interactive)
16170 (org-eval-in-calendar '(scroll-calendar-left 1))))
16171 (org-defkey map "<"
16172 (lambda () (interactive)
16173 (org-eval-in-calendar '(scroll-calendar-right 1))))
16174 (org-defkey map "\C-v"
16175 (lambda () (interactive)
16176 (org-eval-in-calendar
16177 '(calendar-scroll-left-three-months 1))))
16178 (org-defkey map "\M-v"
16179 (lambda () (interactive)
16180 (org-eval-in-calendar
16181 '(calendar-scroll-right-three-months 1))))
16182 map)
16183 "Keymap for minibuffer commands when using `org-read-date'.")
16185 (defun org-read-date (&optional org-with-time to-time from-string prompt
16186 default-time default-input inactive)
16187 "Read a date, possibly a time, and make things smooth for the user.
16188 The prompt will suggest to enter an ISO date, but you can also enter anything
16189 which will at least partially be understood by `parse-time-string'.
16190 Unrecognized parts of the date will default to the current day, month, year,
16191 hour and minute. If this command is called to replace a timestamp at point,
16192 or to enter the second timestamp of a range, the default time is taken
16193 from the existing stamp. Furthermore, the command prefers the future,
16194 so if you are giving a date where the year is not given, and the day-month
16195 combination is already past in the current year, it will assume you
16196 mean next year. For details, see the manual. A few examples:
16198 3-2-5 --> 2003-02-05
16199 feb 15 --> currentyear-02-15
16200 2/15 --> currentyear-02-15
16201 sep 12 9 --> 2009-09-12
16202 12:45 --> today 12:45
16203 22 sept 0:34 --> currentyear-09-22 0:34
16204 12 --> currentyear-currentmonth-12
16205 Fri --> nearest Friday after today
16206 -Tue --> last Tuesday
16207 etc.
16209 Furthermore you can specify a relative date by giving, as the *first* thing
16210 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16211 change in days weeks, months, years.
16212 With a single plus or minus, the date is relative to today. With a double
16213 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16214 +4d --> four days from today
16215 +4 --> same as above
16216 +2w --> two weeks from today
16217 ++5 --> five days from default date
16219 The function understands only English month and weekday abbreviations.
16221 While prompting, a calendar is popped up - you can also select the
16222 date with the mouse (button 1). The calendar shows a period of three
16223 months. To scroll it to other months, use the keys `>' and `<'.
16224 If you don't like the calendar, turn it off with
16225 \(setq org-read-date-popup-calendar nil)
16227 With optional argument TO-TIME, the date will immediately be converted
16228 to an internal time.
16229 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16230 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16231 still enter a time, and this function will inform the calling routine
16232 about this change. The calling routine may then choose to change the
16233 format used to insert the time stamp into the buffer to include the time.
16234 With optional argument FROM-STRING, read from this string instead from
16235 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16236 the time/date that is used for everything that is not specified by the
16237 user."
16238 (require 'parse-time)
16239 (let* ((org-time-stamp-rounding-minutes
16240 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16241 (org-dcst org-display-custom-times)
16242 (ct (org-current-time))
16243 (org-def (or org-overriding-default-time default-time ct))
16244 (org-defdecode (decode-time org-def))
16245 (dummy (progn
16246 (when (< (nth 2 org-defdecode) org-extend-today-until)
16247 (setcar (nthcdr 2 org-defdecode) -1)
16248 (setcar (nthcdr 1 org-defdecode) 59)
16249 (setq org-def (apply 'encode-time org-defdecode)
16250 org-defdecode (decode-time org-def)))))
16251 (mouse-autoselect-window nil) ; Don't let the mouse jump
16252 (calendar-frame-setup nil)
16253 (calendar-setup nil)
16254 (calendar-move-hook nil)
16255 (calendar-view-diary-initially-flag nil)
16256 (calendar-view-holidays-initially-flag nil)
16257 (timestr (format-time-string
16258 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16259 (prompt (concat (if prompt (concat prompt " ") "")
16260 (format "Date+time [%s]: " timestr)))
16261 ans (org-ans0 "") org-ans1 org-ans2 final)
16263 (cond
16264 (from-string (setq ans from-string))
16265 (org-read-date-popup-calendar
16266 (save-excursion
16267 (save-window-excursion
16268 (calendar)
16269 (org-eval-in-calendar '(setq cursor-type nil) t)
16270 (unwind-protect
16271 (progn
16272 (calendar-forward-day (- (time-to-days org-def)
16273 (calendar-absolute-from-gregorian
16274 (calendar-current-date))))
16275 (org-eval-in-calendar nil t)
16276 (let* ((old-map (current-local-map))
16277 (map (copy-keymap calendar-mode-map))
16278 (minibuffer-local-map
16279 (copy-keymap org-read-date-minibuffer-local-map)))
16280 (org-defkey map (kbd "RET") 'org-calendar-select)
16281 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16282 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16283 (unwind-protect
16284 (progn
16285 (use-local-map map)
16286 (setq org-read-date-inactive inactive)
16287 (add-hook 'post-command-hook 'org-read-date-display)
16288 (setq org-ans0 (read-string prompt default-input
16289 'org-read-date-history nil))
16290 ;; org-ans0: from prompt
16291 ;; org-ans1: from mouse click
16292 ;; org-ans2: from calendar motion
16293 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16294 (remove-hook 'post-command-hook 'org-read-date-display)
16295 (use-local-map old-map)
16296 (when org-read-date-overlay
16297 (delete-overlay org-read-date-overlay)
16298 (setq org-read-date-overlay nil)))))
16299 (bury-buffer "*Calendar*")))))
16301 (t ; Naked prompt only
16302 (unwind-protect
16303 (setq ans (read-string prompt default-input
16304 'org-read-date-history timestr))
16305 (when org-read-date-overlay
16306 (delete-overlay org-read-date-overlay)
16307 (setq org-read-date-overlay nil)))))
16309 (setq final (org-read-date-analyze ans org-def org-defdecode))
16311 (when org-read-date-analyze-forced-year
16312 (message "Year was forced into %s"
16313 (if org-read-date-force-compatible-dates
16314 "compatible range (1970-2037)"
16315 "range representable on this machine"))
16316 (ding))
16318 ;; One round trip to get rid of 34th of August and stuff like that....
16319 (setq final (decode-time (apply 'encode-time final)))
16321 (setq org-read-date-final-answer ans)
16323 (if to-time
16324 (apply 'encode-time final)
16325 (if (and (boundp 'org-time-was-given) org-time-was-given)
16326 (format "%04d-%02d-%02d %02d:%02d"
16327 (nth 5 final) (nth 4 final) (nth 3 final)
16328 (nth 2 final) (nth 1 final))
16329 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16331 (defvar org-def)
16332 (defvar org-defdecode)
16333 (defvar org-with-time)
16334 (defun org-read-date-display ()
16335 "Display the current date prompt interpretation in the minibuffer."
16336 (when org-read-date-display-live
16337 (when org-read-date-overlay
16338 (delete-overlay org-read-date-overlay))
16339 (when (minibufferp (current-buffer))
16340 (save-excursion
16341 (end-of-line 1)
16342 (while (not (equal (buffer-substring
16343 (max (point-min) (- (point) 4)) (point))
16344 " "))
16345 (insert " ")))
16346 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16347 " " (or org-ans1 org-ans2)))
16348 (org-end-time-was-given nil)
16349 (f (org-read-date-analyze ans org-def org-defdecode))
16350 (fmts (if org-dcst
16351 org-time-stamp-custom-formats
16352 org-time-stamp-formats))
16353 (fmt (if (or org-with-time
16354 (and (boundp 'org-time-was-given) org-time-was-given))
16355 (cdr fmts)
16356 (car fmts)))
16357 (txt (format-time-string fmt (apply 'encode-time f)))
16358 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16359 (txt (concat "=> " txt)))
16360 (when (and org-end-time-was-given
16361 (string-match org-plain-time-of-day-regexp txt))
16362 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16363 org-end-time-was-given
16364 (substring txt (match-end 0)))))
16365 (when org-read-date-analyze-futurep
16366 (setq txt (concat txt " (=>F)")))
16367 (setq org-read-date-overlay
16368 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16369 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16371 (defun org-read-date-analyze (ans org-def org-defdecode)
16372 "Analyze the combined answer of the date prompt."
16373 ;; FIXME: cleanup and comment
16374 (let ((nowdecode (decode-time (current-time)))
16375 delta deltan deltaw deltadef year month day
16376 hour minute second wday pm h2 m2 tl wday1
16377 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16378 (setq org-read-date-analyze-futurep nil
16379 org-read-date-analyze-forced-year nil)
16380 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16381 (setq ans "+0"))
16383 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16384 (setq ans (replace-match "" t t ans)
16385 deltan (car delta)
16386 deltaw (nth 1 delta)
16387 deltadef (nth 2 delta)))
16389 ;; Check if there is an iso week date in there. If yes, store the
16390 ;; info and postpone interpreting it until the rest of the parsing
16391 ;; is done.
16392 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16393 (setq iso-year (if (match-end 1)
16394 (org-small-year-to-year
16395 (string-to-number (match-string 1 ans))))
16396 iso-weekday (if (match-end 3)
16397 (string-to-number (match-string 3 ans)))
16398 iso-week (string-to-number (match-string 2 ans)))
16399 (setq ans (replace-match "" t t ans)))
16401 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16402 (when (string-match
16403 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16404 (setq year (if (match-end 2)
16405 (string-to-number (match-string 2 ans))
16406 (progn (setq kill-year t)
16407 (string-to-number (format-time-string "%Y"))))
16408 month (string-to-number (match-string 3 ans))
16409 day (string-to-number (match-string 4 ans)))
16410 (if (< year 100) (setq year (+ 2000 year)))
16411 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16412 t nil ans)))
16414 ;; Help matching dotted european dates
16415 (when (string-match
16416 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16417 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16418 (setq kill-year t)
16419 (string-to-number (format-time-string "%Y")))
16420 day (string-to-number (match-string 1 ans))
16421 month (string-to-number (match-string 2 ans))
16422 ans (replace-match (format "%04d-%02d-%02d" year month day)
16423 t nil ans)))
16425 ;; Help matching american dates, like 5/30 or 5/30/7
16426 (when (string-match
16427 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16428 (setq year (if (match-end 4)
16429 (string-to-number (match-string 4 ans))
16430 (progn (setq kill-year t)
16431 (string-to-number (format-time-string "%Y"))))
16432 month (string-to-number (match-string 1 ans))
16433 day (string-to-number (match-string 2 ans)))
16434 (if (< year 100) (setq year (+ 2000 year)))
16435 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16436 t nil ans)))
16437 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16438 ;; If there is a time with am/pm, and *no* time without it, we convert
16439 ;; so that matching will be successful.
16440 (loop for i from 1 to 2 do ; twice, for end time as well
16441 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16442 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16443 (setq hour (string-to-number (match-string 1 ans))
16444 minute (if (match-end 3)
16445 (string-to-number (match-string 3 ans))
16447 pm (equal ?p
16448 (string-to-char (downcase (match-string 4 ans)))))
16449 (if (and (= hour 12) (not pm))
16450 (setq hour 0)
16451 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16452 (setq ans (replace-match (format "%02d:%02d" hour minute)
16453 t t ans))))
16455 ;; Check if a time range is given as a duration
16456 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16457 (setq hour (string-to-number (match-string 1 ans))
16458 h2 (+ hour (string-to-number (match-string 3 ans)))
16459 minute (string-to-number (match-string 2 ans))
16460 m2 (+ minute (if (match-end 5) (string-to-number
16461 (match-string 5 ans))0)))
16462 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16463 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16464 t t ans)))
16466 ;; Check if there is a time range
16467 (when (boundp 'org-end-time-was-given)
16468 (setq org-time-was-given nil)
16469 (when (and (string-match org-plain-time-of-day-regexp ans)
16470 (match-end 8))
16471 (setq org-end-time-was-given (match-string 8 ans))
16472 (setq ans (concat (substring ans 0 (match-beginning 7))
16473 (substring ans (match-end 7))))))
16475 (setq tl (parse-time-string ans)
16476 day (or (nth 3 tl) (nth 3 org-defdecode))
16477 month (or (nth 4 tl)
16478 (if (and org-read-date-prefer-future
16479 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16480 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16481 (nth 4 org-defdecode)))
16482 year (or (and (not kill-year) (nth 5 tl))
16483 (if (and org-read-date-prefer-future
16484 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16485 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16486 (nth 5 org-defdecode)))
16487 hour (or (nth 2 tl) (nth 2 org-defdecode))
16488 minute (or (nth 1 tl) (nth 1 org-defdecode))
16489 second (or (nth 0 tl) 0)
16490 wday (nth 6 tl))
16492 (when (and (eq org-read-date-prefer-future 'time)
16493 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16494 (equal day (nth 3 nowdecode))
16495 (equal month (nth 4 nowdecode))
16496 (equal year (nth 5 nowdecode))
16497 (nth 2 tl)
16498 (or (< (nth 2 tl) (nth 2 nowdecode))
16499 (and (= (nth 2 tl) (nth 2 nowdecode))
16500 (nth 1 tl)
16501 (< (nth 1 tl) (nth 1 nowdecode)))))
16502 (setq day (1+ day)
16503 futurep t))
16505 ;; Special date definitions below
16506 (cond
16507 (iso-week
16508 ;; There was an iso week
16509 (require 'cal-iso)
16510 (setq futurep nil)
16511 (setq year (or iso-year year)
16512 day (or iso-weekday wday 1)
16513 wday nil ; to make sure that the trigger below does not match
16514 iso-date (calendar-gregorian-from-absolute
16515 (calendar-absolute-from-iso
16516 (list iso-week day year))))
16517 ; FIXME: Should we also push ISO weeks into the future?
16518 ; (when (and org-read-date-prefer-future
16519 ; (not iso-year)
16520 ; (< (calendar-absolute-from-gregorian iso-date)
16521 ; (time-to-days (current-time))))
16522 ; (setq year (1+ year)
16523 ; iso-date (calendar-gregorian-from-absolute
16524 ; (calendar-absolute-from-iso
16525 ; (list iso-week day year)))))
16526 (setq month (car iso-date)
16527 year (nth 2 iso-date)
16528 day (nth 1 iso-date)))
16529 (deltan
16530 (setq futurep nil)
16531 (unless deltadef
16532 (let ((now (decode-time (current-time))))
16533 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16534 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16535 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16536 ((equal deltaw "m") (setq month (+ month deltan)))
16537 ((equal deltaw "y") (setq year (+ year deltan)))))
16538 ((and wday (not (nth 3 tl)))
16539 ;; Weekday was given, but no day, so pick that day in the week
16540 ;; on or after the derived date.
16541 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16542 (unless (equal wday wday1)
16543 (setq day (+ day (% (- wday wday1 -7) 7))))))
16544 (if (and (boundp 'org-time-was-given)
16545 (nth 2 tl))
16546 (setq org-time-was-given t))
16547 (if (< year 100) (setq year (+ 2000 year)))
16548 ;; Check of the date is representable
16549 (if org-read-date-force-compatible-dates
16550 (progn
16551 (if (< year 1970)
16552 (setq year 1970 org-read-date-analyze-forced-year t))
16553 (if (> year 2037)
16554 (setq year 2037 org-read-date-analyze-forced-year t)))
16555 (condition-case nil
16556 (ignore (encode-time second minute hour day month year))
16557 (error
16558 (setq year (nth 5 org-defdecode))
16559 (setq org-read-date-analyze-forced-year t))))
16560 (setq org-read-date-analyze-futurep futurep)
16561 (list second minute hour day month year)))
16563 (defvar parse-time-weekdays)
16564 (defun org-read-date-get-relative (s today default)
16565 "Check string S for special relative date string.
16566 TODAY and DEFAULT are internal times, for today and for a default.
16567 Return shift list (N what def-flag)
16568 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16569 N is the number of WHATs to shift.
16570 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16571 the DEFAULT date rather than TODAY."
16572 (require 'parse-time)
16573 (when (and
16574 (string-match
16575 (concat
16576 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16577 "\\([0-9]+\\)?"
16578 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16579 "\\([ \t]\\|$\\)") s)
16580 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16581 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16582 (string-to-char (substring (match-string 1 s) -1))
16583 ?+))
16584 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16585 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16586 (what (if (match-end 3) (match-string 3 s) "d"))
16587 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16588 (date (if rel default today))
16589 (wday (nth 6 (decode-time date)))
16590 delta)
16591 (if wday1
16592 (progn
16593 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16594 (if (= delta 0) (setq delta 7))
16595 (if (= dir ?-)
16596 (progn
16597 (setq delta (- delta 7))
16598 (if (= delta 0) (setq delta -7))))
16599 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16600 (list delta "d" rel))
16601 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16603 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16604 "Turn a user-specified date into the internal representation.
16605 The internal representation needed by the calendar is (month day year).
16606 This is a wrapper to handle the brain-dead convention in calendar that
16607 user function argument order change dependent on argument order."
16608 (if (boundp 'calendar-date-style)
16609 (cond
16610 ((eq calendar-date-style 'american)
16611 (list arg1 arg2 arg3))
16612 ((eq calendar-date-style 'european)
16613 (list arg2 arg1 arg3))
16614 ((eq calendar-date-style 'iso)
16615 (list arg2 arg3 arg1)))
16616 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16617 (if (org-bound-and-true-p european-calendar-style)
16618 (list arg2 arg1 arg3)
16619 (list arg1 arg2 arg3)))))
16621 (defun org-eval-in-calendar (form &optional keepdate)
16622 "Eval FORM in the calendar window and return to current window.
16623 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16624 otherwise stick to the current value of `org-ans2'."
16625 (let ((sf (selected-frame))
16626 (sw (selected-window)))
16627 (select-window (get-buffer-window "*Calendar*" t))
16628 (eval form)
16629 (when (and (not keepdate) (calendar-cursor-to-date))
16630 (let* ((date (calendar-cursor-to-date))
16631 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16632 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16633 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16634 (select-window sw)
16635 (org-select-frame-set-input-focus sf)))
16637 (defun org-calendar-select ()
16638 "Return to `org-read-date' with the date currently selected.
16639 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16640 (interactive)
16641 (when (calendar-cursor-to-date)
16642 (let* ((date (calendar-cursor-to-date))
16643 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16644 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16645 (if (active-minibuffer-window) (exit-minibuffer))))
16647 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16648 "Insert a date stamp for the date given by the internal TIME.
16649 WITH-HM means use the stamp format that includes the time of the day.
16650 INACTIVE means use square brackets instead of angular ones, so that the
16651 stamp will not contribute to the agenda.
16652 PRE and POST are optional strings to be inserted before and after the
16653 stamp.
16654 The command returns the inserted time stamp."
16655 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16656 stamp)
16657 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16658 (insert-before-markers (or pre ""))
16659 (when (listp extra)
16660 (setq extra (car extra))
16661 (if (and (stringp extra)
16662 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16663 (setq extra (format "-%02d:%02d"
16664 (string-to-number (match-string 1 extra))
16665 (string-to-number (match-string 2 extra))))
16666 (setq extra nil)))
16667 (when extra
16668 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16669 (insert-before-markers (setq stamp (format-time-string fmt time)))
16670 (insert-before-markers (or post ""))
16671 (setq org-last-inserted-timestamp stamp)))
16673 (defun org-toggle-time-stamp-overlays ()
16674 "Toggle the use of custom time stamp formats."
16675 (interactive)
16676 (setq org-display-custom-times (not org-display-custom-times))
16677 (unless org-display-custom-times
16678 (let ((p (point-min)) (bmp (buffer-modified-p)))
16679 (while (setq p (next-single-property-change p 'display))
16680 (if (and (get-text-property p 'display)
16681 (eq (get-text-property p 'face) 'org-date))
16682 (remove-text-properties
16683 p (setq p (next-single-property-change p 'display))
16684 '(display t))))
16685 (set-buffer-modified-p bmp)))
16686 (if (featurep 'xemacs)
16687 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16688 (org-restart-font-lock)
16689 (setq org-table-may-need-update t)
16690 (if org-display-custom-times
16691 (message "Time stamps are overlaid with custom format")
16692 (message "Time stamp overlays removed")))
16694 (defun org-display-custom-time (beg end)
16695 "Overlay modified time stamp format over timestamp between BEG and END."
16696 (let* ((ts (buffer-substring beg end))
16697 t1 w1 with-hm tf time str w2 (off 0))
16698 (save-match-data
16699 (setq t1 (org-parse-time-string ts t))
16700 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16701 (setq off (- (match-end 0) (match-beginning 0)))))
16702 (setq end (- end off))
16703 (setq w1 (- end beg)
16704 with-hm (and (nth 1 t1) (nth 2 t1))
16705 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16706 time (org-fix-decoded-time t1)
16707 str (org-add-props
16708 (format-time-string
16709 (substring tf 1 -1) (apply 'encode-time time))
16710 nil 'mouse-face 'highlight)
16711 w2 (length str))
16712 (if (not (= w2 w1))
16713 (add-text-properties (1+ beg) (+ 2 beg)
16714 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16715 (if (featurep 'xemacs)
16716 (progn
16717 (put-text-property beg end 'invisible t)
16718 (put-text-property beg end 'end-glyph (make-glyph str)))
16719 (put-text-property beg end 'display str))))
16721 (defun org-translate-time (string)
16722 "Translate all timestamps in STRING to custom format.
16723 But do this only if the variable `org-display-custom-times' is set."
16724 (when org-display-custom-times
16725 (save-match-data
16726 (let* ((start 0)
16727 (re org-ts-regexp-both)
16728 t1 with-hm inactive tf time str beg end)
16729 (while (setq start (string-match re string start))
16730 (setq beg (match-beginning 0)
16731 end (match-end 0)
16732 t1 (save-match-data
16733 (org-parse-time-string (substring string beg end) t))
16734 with-hm (and (nth 1 t1) (nth 2 t1))
16735 inactive (equal (substring string beg (1+ beg)) "[")
16736 tf (funcall (if with-hm 'cdr 'car)
16737 org-time-stamp-custom-formats)
16738 time (org-fix-decoded-time t1)
16739 str (format-time-string
16740 (concat
16741 (if inactive "[" "<") (substring tf 1 -1)
16742 (if inactive "]" ">"))
16743 (apply 'encode-time time))
16744 string (replace-match str t t string)
16745 start (+ start (length str)))))))
16746 string)
16748 (defun org-fix-decoded-time (time)
16749 "Set 0 instead of nil for the first 6 elements of time.
16750 Don't touch the rest."
16751 (let ((n 0))
16752 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16754 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16756 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16757 "Difference between TIMESTAMP-STRING and now in days.
16758 If SECONDS is non-nil, return the difference in seconds."
16759 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16760 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16761 (funcall fdiff (current-time)))))
16763 (defun org-deadline-close (timestamp-string &optional ndays)
16764 "Is the time in TIMESTAMP-STRING close to the current date?"
16765 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16766 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16767 (not (org-entry-is-done-p))))
16769 (defun org-get-wdays (ts &optional delay zero-delay)
16770 "Get the deadline lead time appropriate for timestring TS.
16771 When DELAY is non-nil, get the delay time for scheduled items
16772 instead of the deadline lead time. When ZERO-DELAY is non-nil
16773 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16774 don't try to find the delay cookie in the scheduled timestamp."
16775 (let ((tv (if delay org-scheduled-delay-days
16776 org-deadline-warning-days)))
16777 (cond
16778 ((or (and delay (< tv 0))
16779 (and delay zero-delay (<= tv 0))
16780 (and (not delay) (<= tv 0)))
16781 ;; Enforce this value no matter what
16782 (- tv))
16783 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16784 ;; lead time is specified.
16785 (floor (* (string-to-number (match-string 1 ts))
16786 (cdr (assoc (match-string 2 ts)
16787 '(("d" . 1) ("w" . 7)
16788 ("m" . 30.4) ("y" . 365.25)
16789 ("h" . 0.041667)))))))
16790 ;; go for the default.
16791 (t tv))))
16793 (defun org-calendar-select-mouse (ev)
16794 "Return to `org-read-date' with the date currently selected.
16795 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16796 (interactive "e")
16797 (mouse-set-point ev)
16798 (when (calendar-cursor-to-date)
16799 (let* ((date (calendar-cursor-to-date))
16800 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16801 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16802 (if (active-minibuffer-window) (exit-minibuffer))))
16804 (defun org-check-deadlines (ndays)
16805 "Check if there are any deadlines due or past due.
16806 A deadline is considered due if it happens within `org-deadline-warning-days'
16807 days from today's date. If the deadline appears in an entry marked DONE,
16808 it is not shown. The prefix arg NDAYS can be used to test that many
16809 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16810 (interactive "P")
16811 (let* ((org-warn-days
16812 (cond
16813 ((equal ndays '(4)) 100000)
16814 (ndays (prefix-numeric-value ndays))
16815 (t (abs org-deadline-warning-days))))
16816 (case-fold-search nil)
16817 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16818 (callback
16819 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16821 (message "%d deadlines past-due or due within %d days"
16822 (org-occur regexp nil callback)
16823 org-warn-days)))
16825 (defsubst org-re-timestamp (type)
16826 "Return a regexp for timestamp TYPE.
16827 Allowed values for TYPE are:
16829 all: all timestamps
16830 active: only active timestamps (<...>)
16831 inactive: only inactive timestamps ([...])
16832 scheduled: only scheduled timestamps
16833 deadline: only deadline timestamps
16834 closed: only closed time-stamps
16836 When TYPE is nil, fall back on returning a regexp that matches
16837 both scheduled and deadline timestamps."
16838 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16839 ((eq type 'active) org-ts-regexp)
16840 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16841 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16842 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16843 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16844 ((eq type 'scheduled-or-deadline)
16845 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16847 (defun org-check-before-date (date)
16848 "Check if there are deadlines or scheduled entries before DATE."
16849 (interactive (list (org-read-date)))
16850 (let ((case-fold-search nil)
16851 (regexp (org-re-timestamp org-ts-type))
16852 (callback
16853 (lambda () (time-less-p
16854 (org-time-string-to-time (match-string 1))
16855 (org-time-string-to-time date)))))
16856 (message "%d entries before %s"
16857 (org-occur regexp nil callback) date)))
16859 (defun org-check-after-date (date)
16860 "Check if there are deadlines or scheduled entries after DATE."
16861 (interactive (list (org-read-date)))
16862 (let ((case-fold-search nil)
16863 (regexp (org-re-timestamp org-ts-type))
16864 (callback
16865 (lambda () (not
16866 (time-less-p
16867 (org-time-string-to-time (match-string 1))
16868 (org-time-string-to-time date))))))
16869 (message "%d entries after %s"
16870 (org-occur regexp nil callback) date)))
16872 (defun org-check-dates-range (start-date end-date)
16873 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16874 (interactive (list (org-read-date nil nil nil "Range starts")
16875 (org-read-date nil nil nil "Range end")))
16876 (let ((case-fold-search nil)
16877 (regexp (org-re-timestamp org-ts-type))
16878 (callback
16879 (lambda ()
16880 (let ((match (match-string 1)))
16881 (and
16882 (not (time-less-p
16883 (org-time-string-to-time match)
16884 (org-time-string-to-time start-date)))
16885 (time-less-p
16886 (org-time-string-to-time match)
16887 (org-time-string-to-time end-date)))))))
16888 (message "%d entries between %s and %s"
16889 (org-occur regexp nil callback) start-date end-date)))
16891 (defun org-evaluate-time-range (&optional to-buffer)
16892 "Evaluate a time range by computing the difference between start and end.
16893 Normally the result is just printed in the echo area, but with prefix arg
16894 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16895 If the time range is actually in a table, the result is inserted into the
16896 next column.
16897 For time difference computation, a year is assumed to be exactly 365
16898 days in order to avoid rounding problems."
16899 (interactive "P")
16901 (org-clock-update-time-maybe)
16902 (save-excursion
16903 (unless (org-at-date-range-p t)
16904 (goto-char (point-at-bol))
16905 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16906 (if (not (org-at-date-range-p t))
16907 (user-error "Not at a time-stamp range, and none found in current line")))
16908 (let* ((ts1 (match-string 1))
16909 (ts2 (match-string 2))
16910 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16911 (match-end (match-end 0))
16912 (time1 (org-time-string-to-time ts1))
16913 (time2 (org-time-string-to-time ts2))
16914 (t1 (org-float-time time1))
16915 (t2 (org-float-time time2))
16916 (diff (abs (- t2 t1)))
16917 (negative (< (- t2 t1) 0))
16918 ;; (ys (floor (* 365 24 60 60)))
16919 (ds (* 24 60 60))
16920 (hs (* 60 60))
16921 (fy "%dy %dd %02d:%02d")
16922 (fy1 "%dy %dd")
16923 (fd "%dd %02d:%02d")
16924 (fd1 "%dd")
16925 (fh "%02d:%02d")
16926 y d h m align)
16927 (if havetime
16928 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16930 d (floor (/ diff ds)) diff (mod diff ds)
16931 h (floor (/ diff hs)) diff (mod diff hs)
16932 m (floor (/ diff 60)))
16933 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16935 d (floor (+ (/ diff ds) 0.5))
16936 h 0 m 0))
16937 (if (not to-buffer)
16938 (message "%s" (org-make-tdiff-string y d h m))
16939 (if (org-at-table-p)
16940 (progn
16941 (goto-char match-end)
16942 (setq align t)
16943 (and (looking-at " *|") (goto-char (match-end 0))))
16944 (goto-char match-end))
16945 (if (looking-at
16946 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16947 (replace-match ""))
16948 (if negative (insert " -"))
16949 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16950 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16951 (insert " " (format fh h m))))
16952 (if align (org-table-align))
16953 (message "Time difference inserted")))))
16955 (defun org-make-tdiff-string (y d h m)
16956 (let ((fmt "")
16957 (l nil))
16958 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16959 l (push y l)))
16960 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16961 l (push d l)))
16962 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16963 l (push h l)))
16964 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16965 l (push m l)))
16966 (apply 'format fmt (nreverse l))))
16968 (defun org-time-string-to-time (s &optional buffer pos)
16969 "Convert a timestamp string into internal time."
16970 (condition-case errdata
16971 (apply 'encode-time (org-parse-time-string s))
16972 (error (error "Bad timestamp `%s'%s\nError was: %s"
16973 s (if (not (and buffer pos))
16975 (format " at %d in buffer `%s'" pos buffer))
16976 (cdr errdata)))))
16978 (defun org-time-string-to-seconds (s)
16979 "Convert a timestamp string to a number of seconds."
16980 (org-float-time (org-time-string-to-time s)))
16982 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16983 "Convert a time stamp to an absolute day number.
16984 If there is a specifier for a cyclic time stamp, get the closest
16985 date to DAYNR.
16986 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16987 The variable `date' is bound by the calendar when this is called."
16988 (cond
16989 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16990 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16991 daynr
16992 (+ daynr 1000)))
16993 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16994 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16995 (time-to-days (current-time))) (match-string 0 s)
16996 prefer show-all))
16997 (t (time-to-days
16998 (condition-case errdata
16999 (apply 'encode-time (org-parse-time-string s))
17000 (error (error "Bad timestamp `%s'%s\nError was: %s"
17001 s (if (not (and buffer pos))
17003 (format " at %d in buffer `%s'" pos buffer))
17004 (cdr errdata))))))))
17006 (defun org-days-to-iso-week (days)
17007 "Return the iso week number."
17008 (require 'cal-iso)
17009 (car (calendar-iso-from-absolute days)))
17011 (defun org-small-year-to-year (year)
17012 "Convert 2-digit years into 4-digit years.
17013 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17014 The year 2000 cannot be abbreviated. Any year larger than 99
17015 is returned unchanged."
17016 (if (< year 38)
17017 (setq year (+ 2000 year))
17018 (if (< year 100)
17019 (setq year (+ 1900 year))))
17020 year)
17022 (defun org-time-from-absolute (d)
17023 "Return the time corresponding to date D.
17024 D may be an absolute day number, or a calendar-type list (month day year)."
17025 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17026 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17028 (defun org-calendar-holiday ()
17029 "List of holidays, for Diary display in Org-mode."
17030 (require 'holidays)
17031 (let ((hl (funcall
17032 (if (fboundp 'calendar-check-holidays)
17033 'calendar-check-holidays 'check-calendar-holidays) date)))
17034 (if hl (mapconcat 'identity hl "; "))))
17036 (defun org-diary-sexp-entry (sexp entry date)
17037 "Process a SEXP diary ENTRY for DATE."
17038 (require 'diary-lib)
17039 (let ((result (if calendar-debug-sexp
17040 (let ((stack-trace-on-error t))
17041 (eval (car (read-from-string sexp))))
17042 (condition-case nil
17043 (eval (car (read-from-string sexp)))
17044 (error
17045 (beep)
17046 (message "Bad sexp at line %d in %s: %s"
17047 (org-current-line)
17048 (buffer-file-name) sexp)
17049 (sleep-for 2))))))
17050 (cond ((stringp result) (split-string result "; "))
17051 ((and (consp result)
17052 (not (consp (cdr result)))
17053 (stringp (cdr result))) (cdr result))
17054 ((and (consp result)
17055 (stringp (car result))) result)
17056 (result entry))))
17058 (defun org-diary-to-ical-string (frombuf)
17059 "Get iCalendar entries from diary entries in buffer FROMBUF.
17060 This uses the icalendar.el library."
17061 (let* ((tmpdir (if (featurep 'xemacs)
17062 (temp-directory)
17063 temporary-file-directory))
17064 (tmpfile (make-temp-name
17065 (expand-file-name "orgics" tmpdir)))
17066 buf rtn b e)
17067 (with-current-buffer frombuf
17068 (icalendar-export-region (point-min) (point-max) tmpfile)
17069 (setq buf (find-buffer-visiting tmpfile))
17070 (set-buffer buf)
17071 (goto-char (point-min))
17072 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17073 (setq b (match-beginning 0)))
17074 (goto-char (point-max))
17075 (if (re-search-backward "^END:VEVENT" nil t)
17076 (setq e (match-end 0)))
17077 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17078 (kill-buffer buf)
17079 (delete-file tmpfile)
17080 rtn))
17082 (defun org-closest-date (start current change prefer show-all)
17083 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17084 When PREFER is `past', return a date that is either CURRENT or past.
17085 When PREFER is `future', return a date that is either CURRENT or future.
17086 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17087 ;; Make the proper lists from the dates
17088 (catch 'exit
17089 (let ((a1 '(("h" . hour)
17090 ("d" . day)
17091 ("w" . week)
17092 ("m" . month)
17093 ("y" . year)))
17094 (shour (nth 2 (org-parse-time-string start)))
17095 dn dw sday cday n1 n2 n0
17096 d m y y1 y2 date1 date2 nmonths nm ny m2)
17098 (setq start (org-date-to-gregorian start)
17099 current (org-date-to-gregorian
17100 (if show-all
17101 current
17102 (time-to-days (current-time))))
17103 sday (calendar-absolute-from-gregorian start)
17104 cday (calendar-absolute-from-gregorian current))
17106 (if (<= cday sday) (throw 'exit sday))
17108 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17109 (setq dn (string-to-number (match-string 1 change))
17110 dw (cdr (assoc (match-string 2 change) a1)))
17111 (user-error "Invalid change specifier: %s" change))
17112 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17113 (cond
17114 ((eq dw 'hour)
17115 (let ((missing-hours
17116 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17117 dn)))
17118 (setq n1 (if (zerop missing-hours) cday
17119 (- cday (1+ (floor (/ missing-hours 24)))))
17120 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17121 ((eq dw 'day)
17122 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17123 n2 (+ n1 dn)))
17124 ((eq dw 'year)
17125 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17126 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17127 (setq date1 (list m d y1)
17128 n1 (calendar-absolute-from-gregorian date1)
17129 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17130 n2 (calendar-absolute-from-gregorian date2)))
17131 ((eq dw 'month)
17132 ;; approx number of month between the two dates
17133 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17134 ;; How often does dn fit in there?
17135 (setq d (nth 1 start) m (car start) y (nth 2 start)
17136 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17137 m (+ m nm)
17138 ny (floor (/ m 12))
17139 y (+ y ny)
17140 m (- m (* ny 12)))
17141 (while (> m 12) (setq m (- m 12) y (1+ y)))
17142 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17143 (setq m2 (+ m dn) y2 y)
17144 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17145 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17146 (while (<= n2 cday)
17147 (setq n1 n2 m m2 y y2)
17148 (setq m2 (+ m dn) y2 y)
17149 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17150 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17151 ;; Make sure n1 is the earlier date
17152 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17153 (if show-all
17154 (cond
17155 ((eq prefer 'past) (if (= cday n2) n2 n1))
17156 ((eq prefer 'future) (if (= cday n1) n1 n2))
17157 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17158 (cond
17159 ((eq prefer 'past) (if (= cday n2) n2 n1))
17160 ((eq prefer 'future) (if (= cday n1) n1 n2))
17161 (t (if (= cday n1) n1 n2)))))))
17163 (defun org-date-to-gregorian (date)
17164 "Turn any specification of DATE into a Gregorian date for the calendar."
17165 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17166 ((and (listp date) (= (length date) 3)) date)
17167 ((stringp date)
17168 (setq date (org-parse-time-string date))
17169 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17170 ((listp date)
17171 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17173 (defun org-parse-time-string (s &optional nodefault)
17174 "Parse the standard Org-mode time string.
17175 This should be a lot faster than the normal `parse-time-string'.
17176 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17177 hour and minute fields will be nil if not given."
17178 (cond ((string-match org-ts-regexp0 s)
17179 (list 0
17180 (if (or (match-beginning 8) (not nodefault))
17181 (string-to-number (or (match-string 8 s) "0")))
17182 (if (or (match-beginning 7) (not nodefault))
17183 (string-to-number (or (match-string 7 s) "0")))
17184 (string-to-number (match-string 4 s))
17185 (string-to-number (match-string 3 s))
17186 (string-to-number (match-string 2 s))
17187 nil nil nil))
17188 ((string-match "^<[^>]+>$" s)
17189 (decode-time (seconds-to-time (org-matcher-time s))))
17190 (t (error "Not a standard Org-mode time string: %s" s))))
17192 (defun org-timestamp-up (&optional arg)
17193 "Increase the date item at the cursor by one.
17194 If the cursor is on the year, change the year. If it is on the month,
17195 the day or the time, change that.
17196 With prefix ARG, change by that many units."
17197 (interactive "p")
17198 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17200 (defun org-timestamp-down (&optional arg)
17201 "Decrease the date item at the cursor by one.
17202 If the cursor is on the year, change the year. If it is on the month,
17203 the day or the time, change that.
17204 With prefix ARG, change by that many units."
17205 (interactive "p")
17206 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17208 (defun org-timestamp-up-day (&optional arg)
17209 "Increase the date in the time stamp by one day.
17210 With prefix ARG, change that many days."
17211 (interactive "p")
17212 (if (and (not (org-at-timestamp-p t))
17213 (org-at-heading-p))
17214 (org-todo 'up)
17215 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17217 (defun org-timestamp-down-day (&optional arg)
17218 "Decrease the date in the time stamp by one day.
17219 With prefix ARG, change that many days."
17220 (interactive "p")
17221 (if (and (not (org-at-timestamp-p t))
17222 (org-at-heading-p))
17223 (org-todo 'down)
17224 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17226 (defun org-at-timestamp-p (&optional inactive-ok)
17227 "Determine if the cursor is in or at a timestamp."
17228 (interactive)
17229 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17230 (pos (point))
17231 (ans (or (looking-at tsr)
17232 (save-excursion
17233 (skip-chars-backward "^[<\n\r\t")
17234 (if (> (point) (point-min)) (backward-char 1))
17235 (and (looking-at tsr)
17236 (> (- (match-end 0) pos) -1))))))
17237 (and ans
17238 (boundp 'org-ts-what)
17239 (setq org-ts-what
17240 (cond
17241 ((= pos (match-beginning 0)) 'bracket)
17242 ;; Point is considered to be "on the bracket" whether
17243 ;; it's really on it or right after it.
17244 ((= pos (1- (match-end 0))) 'bracket)
17245 ((= pos (match-end 0)) 'after)
17246 ((org-pos-in-match-range pos 2) 'year)
17247 ((org-pos-in-match-range pos 3) 'month)
17248 ((org-pos-in-match-range pos 7) 'hour)
17249 ((org-pos-in-match-range pos 8) 'minute)
17250 ((or (org-pos-in-match-range pos 4)
17251 (org-pos-in-match-range pos 5)) 'day)
17252 ((and (> pos (or (match-end 8) (match-end 5)))
17253 (< pos (match-end 0)))
17254 (- pos (or (match-end 8) (match-end 5))))
17255 (t 'day))))
17256 ans))
17258 (defun org-toggle-timestamp-type ()
17259 "Toggle the type (<active> or [inactive]) of a time stamp."
17260 (interactive)
17261 (when (org-at-timestamp-p t)
17262 (let ((beg (match-beginning 0)) (end (match-end 0))
17263 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17264 (save-excursion
17265 (goto-char beg)
17266 (while (re-search-forward "[][<>]" end t)
17267 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17268 t t)))
17269 (message "Timestamp is now %sactive"
17270 (if (equal (char-after beg) ?<) "" "in")))))
17272 (defun org-at-clock-log-p nil
17273 "Is the cursor on the clock log line?"
17274 (save-excursion
17275 (move-beginning-of-line 1)
17276 (looking-at "^[ \t]*CLOCK:")))
17278 (defvar org-clock-history) ; defined in org-clock.el
17279 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17280 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17281 "Change the date in the time stamp at point.
17282 The date will be changed by N times WHAT. WHAT can be `day', `month',
17283 `year', `minute', `second'. If WHAT is not given, the cursor position
17284 in the timestamp determines what will be changed.
17285 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17286 (let ((origin (point)) origin-cat
17287 with-hm inactive
17288 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17289 org-ts-what
17290 extra rem
17291 ts time time0 fixnext clrgx)
17292 (if (not (org-at-timestamp-p t))
17293 (user-error "Not at a timestamp"))
17294 (if (and (not what) (eq org-ts-what 'bracket))
17295 (org-toggle-timestamp-type)
17296 ;; Point isn't on brackets. Remember the part of the time-stamp
17297 ;; the point was in. Indeed, size of time-stamps may change,
17298 ;; but point must be kept in the same category nonetheless.
17299 (setq origin-cat org-ts-what)
17300 (if (and (not what) (not (eq org-ts-what 'day))
17301 org-display-custom-times
17302 (get-text-property (point) 'display)
17303 (not (get-text-property (1- (point)) 'display)))
17304 (setq org-ts-what 'day))
17305 (setq org-ts-what (or what org-ts-what)
17306 inactive (= (char-after (match-beginning 0)) ?\[)
17307 ts (match-string 0))
17308 (replace-match "")
17309 (when (string-match
17310 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17312 (setq extra (match-string 1 ts))
17313 (if suppress-tmp-delay
17314 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17315 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17316 (setq with-hm t))
17317 (setq time0 (org-parse-time-string ts))
17318 (when (and updown
17319 (eq org-ts-what 'minute)
17320 (not current-prefix-arg))
17321 ;; This looks like s-up and s-down. Change by one rounding step.
17322 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17323 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17324 (setcar (cdr time0) (+ (nth 1 time0)
17325 (if (> n 0) (- rem) (- dm rem))))))
17326 (setq time
17327 (encode-time (or (car time0) 0)
17328 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17329 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17330 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17331 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17332 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17333 (nthcdr 6 time0)))
17334 (when (and (member org-ts-what '(hour minute))
17335 extra
17336 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17337 (setq extra (org-modify-ts-extra
17338 extra
17339 (if (eq org-ts-what 'hour) 2 5)
17340 n dm)))
17341 (when (integerp org-ts-what)
17342 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17343 (if (eq what 'calendar)
17344 (let ((cal-date (org-get-date-from-calendar)))
17345 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17346 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17347 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17348 (setcar time0 (or (car time0) 0))
17349 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17350 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17351 (setq time (apply 'encode-time time0))))
17352 ;; Insert the new time-stamp, and ensure point stays in the same
17353 ;; category as before (i.e. not after the last position in that
17354 ;; category).
17355 (let ((pos (point)))
17356 ;; Stay before inserted string. `save-excursion' is of no use.
17357 (setq org-last-changed-timestamp
17358 (org-insert-time-stamp time with-hm inactive nil nil extra))
17359 (goto-char pos))
17360 (save-match-data
17361 (looking-at org-ts-regexp3)
17362 (goto-char (cond
17363 ;; `day' category ends before `hour' if any, or at
17364 ;; the end of the day name.
17365 ((eq origin-cat 'day)
17366 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17367 ((eq origin-cat 'hour) (min (match-end 7) origin))
17368 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17369 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17370 ;; `year' and `month' have both fixed size: point
17371 ;; couldn't have moved into another part.
17372 (t origin))))
17373 ;; Update clock if on a CLOCK line.
17374 (org-clock-update-time-maybe)
17375 ;; Maybe adjust the closest clock in `org-clock-history'
17376 (when org-clock-adjust-closest
17377 (if (not (and (org-at-clock-log-p)
17378 (< 1 (length (delq nil (mapcar 'marker-position
17379 org-clock-history))))))
17380 (message "No clock to adjust")
17381 (cond ((save-excursion ; fix previous clock?
17382 (re-search-backward org-ts-regexp0 nil t)
17383 (org-looking-back (concat org-clock-string " \\[")))
17384 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17385 ((save-excursion ; fix next clock?
17386 (re-search-backward org-ts-regexp0 nil t)
17387 (looking-at (concat org-ts-regexp0 "\\] =>")))
17388 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17389 (save-window-excursion
17390 ;; Find closest clock to point, adjust the previous/next one in history
17391 (let* ((p (save-excursion (org-back-to-heading t)))
17392 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17393 (clfixnth
17394 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17395 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17396 (if (not clfixpos)
17397 (message "No clock to adjust")
17398 (save-excursion
17399 (org-goto-marker-or-bmk clfixpos)
17400 (org-show-subtree)
17401 (when (re-search-forward clrgx nil t)
17402 (goto-char (match-beginning 1))
17403 (let (org-clock-adjust-closest)
17404 (org-timestamp-change n org-ts-what updown))
17405 (message "Clock adjusted in %s for heading: %s"
17406 (file-name-nondirectory (buffer-file-name))
17407 (org-get-heading t t)))))))))
17408 ;; Try to recenter the calendar window, if any.
17409 (if (and org-calendar-follow-timestamp-change
17410 (get-buffer-window "*Calendar*" t)
17411 (memq org-ts-what '(day month year)))
17412 (org-recenter-calendar (time-to-days time))))))
17414 (defun org-modify-ts-extra (s pos n dm)
17415 "Change the different parts of the lead-time and repeat fields in timestamp."
17416 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17417 ng h m new rem)
17418 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17419 (cond
17420 ((or (org-pos-in-match-range pos 2)
17421 (org-pos-in-match-range pos 3))
17422 (setq m (string-to-number (match-string 3 s))
17423 h (string-to-number (match-string 2 s)))
17424 (if (org-pos-in-match-range pos 2)
17425 (setq h (+ h n))
17426 (setq n (* dm (org-no-warnings (signum n))))
17427 (when (not (= 0 (setq rem (% m dm))))
17428 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17429 (setq m (+ m n)))
17430 (if (< m 0) (setq m (+ m 60) h (1- h)))
17431 (if (> m 59) (setq m (- m 60) h (1+ h)))
17432 (setq h (min 24 (max 0 h)))
17433 (setq ng 1 new (format "-%02d:%02d" h m)))
17434 ((org-pos-in-match-range pos 6)
17435 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17436 ((org-pos-in-match-range pos 5)
17437 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17439 ((org-pos-in-match-range pos 9)
17440 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17441 ((org-pos-in-match-range pos 8)
17442 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17444 (when ng
17445 (setq s (concat
17446 (substring s 0 (match-beginning ng))
17448 (substring s (match-end ng))))))
17451 (defun org-recenter-calendar (date)
17452 "If the calendar is visible, recenter it to DATE."
17453 (let ((cwin (get-buffer-window "*Calendar*" t)))
17454 (when cwin
17455 (let ((calendar-move-hook nil))
17456 (with-selected-window cwin
17457 (calendar-goto-date (if (listp date) date
17458 (calendar-gregorian-from-absolute date))))))))
17460 (defun org-goto-calendar (&optional arg)
17461 "Go to the Emacs calendar at the current date.
17462 If there is a time stamp in the current line, go to that date.
17463 A prefix ARG can be used to force the current date."
17464 (interactive "P")
17465 (let ((tsr org-ts-regexp) diff
17466 (calendar-move-hook nil)
17467 (calendar-view-holidays-initially-flag nil)
17468 (calendar-view-diary-initially-flag nil))
17469 (if (or (org-at-timestamp-p)
17470 (save-excursion
17471 (beginning-of-line 1)
17472 (looking-at (concat ".*" tsr))))
17473 (let ((d1 (time-to-days (current-time)))
17474 (d2 (time-to-days
17475 (org-time-string-to-time (match-string 1)))))
17476 (setq diff (- d2 d1))))
17477 (calendar)
17478 (calendar-goto-today)
17479 (if (and diff (not arg)) (calendar-forward-day diff))))
17481 (defun org-get-date-from-calendar ()
17482 "Return a list (month day year) of date at point in calendar."
17483 (with-current-buffer "*Calendar*"
17484 (save-match-data
17485 (calendar-cursor-to-date))))
17487 (defun org-date-from-calendar ()
17488 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17489 If there is already a time stamp at the cursor position, update it."
17490 (interactive)
17491 (if (org-at-timestamp-p t)
17492 (org-timestamp-change 0 'calendar)
17493 (let ((cal-date (org-get-date-from-calendar)))
17494 (org-insert-time-stamp
17495 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17497 (defcustom org-effort-durations
17498 `(("h" . 60)
17499 ("d" . ,(* 60 8))
17500 ("w" . ,(* 60 8 5))
17501 ("m" . ,(* 60 8 5 4))
17502 ("y" . ,(* 60 8 5 40)))
17503 "Conversion factor to minutes for an effort modifier.
17505 Each entry has the form (MODIFIER . MINUTES).
17507 In an effort string, a number followed by MODIFIER is multiplied
17508 by the specified number of MINUTES to obtain an effort in
17509 minutes.
17511 For example, if the value of this variable is ((\"hours\" . 60)), then an
17512 effort string \"2hours\" is equivalent to 120 minutes."
17513 :group 'org-agenda
17514 :version "24.1"
17515 :type '(alist :key-type (string :tag "Modifier")
17516 :value-type (number :tag "Minutes")))
17518 (defun org-minutes-to-clocksum-string (m)
17519 "Format number of minutes as a clocksum string.
17520 The format is determined by `org-time-clocksum-format',
17521 `org-time-clocksum-use-fractional' and
17522 `org-time-clocksum-fractional-format' and
17523 `org-time-clocksum-use-effort-durations'."
17524 (let ((clocksum "")
17525 (m (round m)) ; Don't allow fractions of minutes
17526 h d w mo y fmt n)
17527 (setq h (if org-time-clocksum-use-effort-durations
17528 (cdr (assoc "h" org-effort-durations)) 60)
17529 d (if org-time-clocksum-use-effort-durations
17530 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17531 w (if org-time-clocksum-use-effort-durations
17532 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17533 mo (if org-time-clocksum-use-effort-durations
17534 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17535 y (if org-time-clocksum-use-effort-durations
17536 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17537 ;; fractional format
17538 (if org-time-clocksum-use-fractional
17539 (cond
17540 ;; single format string
17541 ((stringp org-time-clocksum-fractional-format)
17542 (format org-time-clocksum-fractional-format (/ m (float h))))
17543 ;; choice of fractional formats for different time units
17544 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17545 (> (/ (truncate m) (* y d h)) 0))
17546 (format fmt (/ m (* y d (float h)))))
17547 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17548 (> (/ (truncate m) (* mo d h)) 0))
17549 (format fmt (/ m (* mo d (float h)))))
17550 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17551 (> (/ (truncate m) (* w d h)) 0))
17552 (format fmt (/ m (* w d (float h)))))
17553 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17554 (> (/ (truncate m) (* d h)) 0))
17555 (format fmt (/ m (* d (float h)))))
17556 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17557 (> (/ (truncate m) h) 0))
17558 (format fmt (/ m (float h))))
17559 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17560 (format fmt m))
17561 ;; fall back to smallest time unit with a format
17562 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17563 (format fmt (/ m (float h))))
17564 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17565 (format fmt (/ m (* d (float h)))))
17566 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17567 (format fmt (/ m (* w d (float h)))))
17568 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17569 (format fmt (/ m (* mo d (float h)))))
17570 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17571 (format fmt (/ m (* y d (float h))))))
17572 ;; standard (non-fractional) format, with single format string
17573 (if (stringp org-time-clocksum-format)
17574 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17575 ;; separate formats components
17576 (and (setq fmt (plist-get org-time-clocksum-format :years))
17577 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17578 (plist-get org-time-clocksum-format :require-years))
17579 (setq clocksum (concat clocksum (format fmt n))
17580 m (- m (* n y d h))))
17581 (and (setq fmt (plist-get org-time-clocksum-format :months))
17582 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17583 (plist-get org-time-clocksum-format :require-months))
17584 (setq clocksum (concat clocksum (format fmt n))
17585 m (- m (* n mo d h))))
17586 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17587 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17588 (plist-get org-time-clocksum-format :require-weeks))
17589 (setq clocksum (concat clocksum (format fmt n))
17590 m (- m (* n w d h))))
17591 (and (setq fmt (plist-get org-time-clocksum-format :days))
17592 (or (> (setq n (/ (truncate m) (* d h))) 0)
17593 (plist-get org-time-clocksum-format :require-days))
17594 (setq clocksum (concat clocksum (format fmt n))
17595 m (- m (* n d h))))
17596 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17597 (or (> (setq n (/ (truncate m) h)) 0)
17598 (plist-get org-time-clocksum-format :require-hours))
17599 (setq clocksum (concat clocksum (format fmt n))
17600 m (- m (* n h))))
17601 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17602 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17603 (setq clocksum (concat clocksum (format fmt m))))
17604 ;; return formatted time duration
17605 clocksum))))
17607 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17608 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17609 "Org mode version 8.0")
17611 (defun org-hours-to-clocksum-string (n)
17612 (org-minutes-to-clocksum-string (* n 60)))
17614 (defun org-hh:mm-string-to-minutes (s)
17615 "Convert a string H:MM to a number of minutes.
17616 If the string is just a number, interpret it as minutes.
17617 In fact, the first hh:mm or number in the string will be taken,
17618 there can be extra stuff in the string.
17619 If no number is found, the return value is 0."
17620 (cond
17621 ((integerp s) s)
17622 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17623 (+ (* (string-to-number (match-string 1 s)) 60)
17624 (string-to-number (match-string 2 s))))
17625 ((string-match "\\([0-9]+\\)" s)
17626 (string-to-number (match-string 1 s)))
17627 (t 0)))
17629 (defcustom org-image-actual-width t
17630 "Should we use the actual width of images when inlining them?
17632 When set to `t', always use the image width.
17634 When set to a number, use imagemagick (when available) to set
17635 the image's width to this value.
17637 When set to a number in a list, try to get the width from any
17638 #+ATTR.* keyword if it matches a width specification like
17640 #+ATTR_HTML: :width 300px
17642 and fall back on that number if none is found.
17644 When set to nil, try to get the width from an #+ATTR.* keyword
17645 and fall back on the original width if none is found.
17647 This requires Emacs >= 24.1, build with imagemagick support."
17648 :group 'org-appearance
17649 :version "24.4"
17650 :package-version '(Org . "8.0")
17651 :type '(choice
17652 (const :tag "Use the image width" t)
17653 (integer :tag "Use a number of pixels")
17654 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17655 (const :tag "Use #+ATTR* or don't resize" nil)))
17657 (defcustom org-agenda-inhibit-startup nil
17658 "Inhibit startup when preparing agenda buffers.
17659 When this variable is `t' (the default), the initialization of
17660 the Org agenda buffers is inhibited: e.g. the visibility state
17661 is not set, the tables are not re-aligned, etc."
17662 :type 'boolean
17663 :version "24.3"
17664 :group 'org-agenda)
17666 (defun org-duration-string-to-minutes (s &optional output-to-string)
17667 "Convert a duration string S to minutes.
17669 A bare number is interpreted as minutes, modifiers can be set by
17670 customizing `org-effort-durations' (which see).
17672 Entries containing a colon are interpreted as H:MM by
17673 `org-hh:mm-string-to-minutes'."
17674 (let ((result 0)
17675 (re (concat "\\([0-9.]+\\) *\\("
17676 (regexp-opt (mapcar 'car org-effort-durations))
17677 "\\)")))
17678 (while (string-match re s)
17679 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17680 (string-to-number (match-string 1 s))))
17681 (setq s (replace-match "" nil t s)))
17682 (setq result (floor result))
17683 (incf result (org-hh:mm-string-to-minutes s))
17684 (if output-to-string (number-to-string result) result)))
17686 ;;;; Files
17688 (defun org-save-all-org-buffers ()
17689 "Save all Org-mode buffers without user confirmation."
17690 (interactive)
17691 (message "Saving all Org-mode buffers...")
17692 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17693 (when (featurep 'org-id) (org-id-locations-save))
17694 (message "Saving all Org-mode buffers... done"))
17696 (defun org-revert-all-org-buffers ()
17697 "Revert all Org-mode buffers.
17698 Prompt for confirmation when there are unsaved changes.
17699 Be sure you know what you are doing before letting this function
17700 overwrite your changes.
17702 This function is useful in a setup where one tracks org files
17703 with a version control system, to revert on one machine after pulling
17704 changes from another. I believe the procedure must be like this:
17706 1. M-x org-save-all-org-buffers
17707 2. Pull changes from the other machine, resolve conflicts
17708 3. M-x org-revert-all-org-buffers"
17709 (interactive)
17710 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17711 (user-error "Abort"))
17712 (save-excursion
17713 (save-window-excursion
17714 (mapc
17715 (lambda (b)
17716 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17717 (with-current-buffer b buffer-file-name))
17718 (org-pop-to-buffer-same-window b)
17719 (revert-buffer t 'no-confirm)))
17720 (buffer-list))
17721 (when (and (featurep 'org-id) org-id-track-globally)
17722 (org-id-locations-load)))))
17724 ;;;; Agenda files
17726 ;;;###autoload
17727 (defun org-switchb (&optional arg)
17728 "Switch between Org buffers.
17729 With one prefix argument, restrict available buffers to files.
17730 With two prefix arguments, restrict available buffers to agenda files.
17732 Defaults to `iswitchb' for buffer name completion.
17733 Set `org-completion-use-ido' to make it use ido instead."
17734 (interactive "P")
17735 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17736 ((equal arg '(16)) (org-buffer-list 'agenda))
17737 (t (org-buffer-list))))
17738 (org-completion-use-iswitchb org-completion-use-iswitchb)
17739 (org-completion-use-ido org-completion-use-ido))
17740 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17741 (setq org-completion-use-iswitchb t))
17742 (org-pop-to-buffer-same-window
17743 (org-icompleting-read "Org buffer: "
17744 (mapcar 'list (mapcar 'buffer-name blist))
17745 nil t))))
17747 ;;; Define some older names previously used for this functionality
17748 ;;;###autoload
17749 (defalias 'org-ido-switchb 'org-switchb)
17750 ;;;###autoload
17751 (defalias 'org-iswitchb 'org-switchb)
17753 (defun org-buffer-list (&optional predicate exclude-tmp)
17754 "Return a list of Org buffers.
17755 PREDICATE can be `export', `files' or `agenda'.
17757 export restrict the list to Export buffers.
17758 files restrict the list to buffers visiting Org files.
17759 agenda restrict the list to buffers visiting agenda files.
17761 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17762 (let* ((bfn nil)
17763 (agenda-files (and (eq predicate 'agenda)
17764 (mapcar 'file-truename (org-agenda-files t))))
17765 (filter
17766 (cond
17767 ((eq predicate 'files)
17768 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17769 ((eq predicate 'export)
17770 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17771 ((eq predicate 'agenda)
17772 (lambda (b)
17773 (with-current-buffer b
17774 (and (derived-mode-p 'org-mode)
17775 (setq bfn (buffer-file-name b))
17776 (member (file-truename bfn) agenda-files)))))
17777 (t (lambda (b) (with-current-buffer b
17778 (or (derived-mode-p 'org-mode)
17779 (string-match "\*Org .*Export"
17780 (buffer-name b)))))))))
17781 (delq nil
17782 (mapcar
17783 (lambda(b)
17784 (if (and (funcall filter b)
17785 (or (not exclude-tmp)
17786 (not (string-match "tmp" (buffer-name b)))))
17788 nil))
17789 (buffer-list)))))
17791 (defun org-agenda-files (&optional unrestricted archives)
17792 "Get the list of agenda files.
17793 Optional UNRESTRICTED means return the full list even if a restriction
17794 is currently in place.
17795 When ARCHIVES is t, include all archive files that are really being
17796 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17797 `org-agenda-archives-mode' is t."
17798 (let ((files
17799 (cond
17800 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17801 ((stringp org-agenda-files) (org-read-agenda-file-list))
17802 ((listp org-agenda-files) org-agenda-files)
17803 (t (error "Invalid value of `org-agenda-files'")))))
17804 (setq files (apply 'append
17805 (mapcar (lambda (f)
17806 (if (file-directory-p f)
17807 (directory-files
17808 f t org-agenda-file-regexp)
17809 (list f)))
17810 files)))
17811 (when org-agenda-skip-unavailable-files
17812 (setq files (delq nil
17813 (mapcar (function
17814 (lambda (file)
17815 (and (file-readable-p file) file)))
17816 files))))
17817 (when (or (eq archives t)
17818 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17819 (setq files (org-add-archive-files files)))
17820 files))
17822 (defun org-agenda-file-p (&optional file)
17823 "Return non-nil, if FILE is an agenda file.
17824 If FILE is omitted, use the file associated with the current
17825 buffer."
17826 (member (or file (buffer-file-name))
17827 (org-agenda-files t)))
17829 (defun org-edit-agenda-file-list ()
17830 "Edit the list of agenda files.
17831 Depending on setup, this either uses customize to edit the variable
17832 `org-agenda-files', or it visits the file that is holding the list. In the
17833 latter case, the buffer is set up in a way that saving it automatically kills
17834 the buffer and restores the previous window configuration."
17835 (interactive)
17836 (if (stringp org-agenda-files)
17837 (let ((cw (current-window-configuration)))
17838 (find-file org-agenda-files)
17839 (org-set-local 'org-window-configuration cw)
17840 (org-add-hook 'after-save-hook
17841 (lambda ()
17842 (set-window-configuration
17843 (prog1 org-window-configuration
17844 (kill-buffer (current-buffer))))
17845 (org-install-agenda-files-menu)
17846 (message "New agenda file list installed"))
17847 nil 'local)
17848 (message "%s" (substitute-command-keys
17849 "Edit list and finish with \\[save-buffer]")))
17850 (customize-variable 'org-agenda-files)))
17852 (defun org-store-new-agenda-file-list (list)
17853 "Set new value for the agenda file list and save it correctly."
17854 (if (stringp org-agenda-files)
17855 (let ((fe (org-read-agenda-file-list t)) b u)
17856 (while (setq b (find-buffer-visiting org-agenda-files))
17857 (kill-buffer b))
17858 (with-temp-file org-agenda-files
17859 (insert
17860 (mapconcat
17861 (lambda (f) ;; Keep un-expanded entries.
17862 (if (setq u (assoc f fe))
17863 (cdr u)
17865 list "\n")
17866 "\n")))
17867 (let ((org-mode-hook nil) (org-inhibit-startup t)
17868 (org-insert-mode-line-in-empty-file nil))
17869 (setq org-agenda-files list)
17870 (customize-save-variable 'org-agenda-files org-agenda-files))))
17872 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17873 "Read the list of agenda files from a file.
17874 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17875 filenames, used by `org-store-new-agenda-file-list' to write back
17876 un-expanded file names."
17877 (when (file-directory-p org-agenda-files)
17878 (error "`org-agenda-files' cannot be a single directory"))
17879 (when (stringp org-agenda-files)
17880 (with-temp-buffer
17881 (insert-file-contents org-agenda-files)
17882 (mapcar
17883 (lambda (f)
17884 (let ((e (expand-file-name (substitute-in-file-name f)
17885 org-directory)))
17886 (if pair-with-expansion
17887 (cons e f)
17888 e)))
17889 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17891 ;;;###autoload
17892 (defun org-cycle-agenda-files ()
17893 "Cycle through the files in `org-agenda-files'.
17894 If the current buffer visits an agenda file, find the next one in the list.
17895 If the current buffer does not, find the first agenda file."
17896 (interactive)
17897 (let* ((fs (org-agenda-files t))
17898 (files (append fs (list (car fs))))
17899 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17900 file)
17901 (unless files (user-error "No agenda files"))
17902 (catch 'exit
17903 (while (setq file (pop files))
17904 (if (equal (file-truename file) tcf)
17905 (when (car files)
17906 (find-file (car files))
17907 (throw 'exit t))))
17908 (find-file (car fs)))
17909 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17911 (defun org-agenda-file-to-front (&optional to-end)
17912 "Move/add the current file to the top of the agenda file list.
17913 If the file is not present in the list, it is added to the front. If it is
17914 present, it is moved there. With optional argument TO-END, add/move to the
17915 end of the list."
17916 (interactive "P")
17917 (let ((org-agenda-skip-unavailable-files nil)
17918 (file-alist (mapcar (lambda (x)
17919 (cons (file-truename x) x))
17920 (org-agenda-files t)))
17921 (ctf (file-truename
17922 (or buffer-file-name
17923 (user-error "Please save the current buffer to a file"))))
17924 x had)
17925 (setq x (assoc ctf file-alist) had x)
17927 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17928 (if to-end
17929 (setq file-alist (append (delq x file-alist) (list x)))
17930 (setq file-alist (cons x (delq x file-alist))))
17931 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17932 (org-install-agenda-files-menu)
17933 (message "File %s to %s of agenda file list"
17934 (if had "moved" "added") (if to-end "end" "front"))))
17936 (defun org-remove-file (&optional file)
17937 "Remove current file from the list of files in variable `org-agenda-files'.
17938 These are the files which are being checked for agenda entries.
17939 Optional argument FILE means use this file instead of the current."
17940 (interactive)
17941 (let* ((org-agenda-skip-unavailable-files nil)
17942 (file (or file buffer-file-name
17943 (user-error "Current buffer does not visit a file")))
17944 (true-file (file-truename file))
17945 (afile (abbreviate-file-name file))
17946 (files (delq nil (mapcar
17947 (lambda (x)
17948 (if (equal true-file
17949 (file-truename x))
17950 nil x))
17951 (org-agenda-files t)))))
17952 (if (not (= (length files) (length (org-agenda-files t))))
17953 (progn
17954 (org-store-new-agenda-file-list files)
17955 (org-install-agenda-files-menu)
17956 (message "Removed file: %s" afile))
17957 (message "File was not in list: %s (not removed)" afile))))
17959 (defun org-file-menu-entry (file)
17960 (vector file (list 'find-file file) t))
17962 (defun org-check-agenda-file (file)
17963 "Make sure FILE exists. If not, ask user what to do."
17964 (when (not (file-exists-p file))
17965 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17966 (abbreviate-file-name file))
17967 (let ((r (downcase (read-char-exclusive))))
17968 (cond
17969 ((equal r ?r)
17970 (org-remove-file file)
17971 (throw 'nextfile t))
17972 (t (error "Abort"))))))
17974 (defun org-get-agenda-file-buffer (file)
17975 "Get a buffer visiting FILE. If the buffer needs to be created, add
17976 it to the list of buffers which might be released later."
17977 (let ((buf (org-find-base-buffer-visiting file)))
17978 (if buf
17979 buf ; just return it
17980 ;; Make a new buffer and remember it
17981 (setq buf (find-file-noselect file))
17982 (if buf (push buf org-agenda-new-buffers))
17983 buf)))
17985 (defun org-release-buffers (blist)
17986 "Release all buffers in list, asking the user for confirmation when needed.
17987 When a buffer is unmodified, it is just killed. When modified, it is saved
17988 \(if the user agrees) and then killed."
17989 (let (buf file)
17990 (while (setq buf (pop blist))
17991 (setq file (buffer-file-name buf))
17992 (when (and (buffer-modified-p buf)
17993 file
17994 (y-or-n-p (format "Save file %s? " file)))
17995 (with-current-buffer buf (save-buffer)))
17996 (kill-buffer buf))))
17998 (defun org-agenda-prepare-buffers (files)
17999 "Create buffers for all agenda files, protect archived trees and comments."
18000 (interactive)
18001 (let ((pa '(:org-archived t))
18002 (pc '(:org-comment t))
18003 (pall '(:org-archived t :org-comment t))
18004 (inhibit-read-only t)
18005 (org-inhibit-startup org-agenda-inhibit-startup)
18006 (rea (concat ":" org-archive-tag ":"))
18007 file re)
18008 (setq org-tag-alist-for-agenda nil
18009 org-tag-groups-alist-for-agenda nil)
18010 (save-excursion
18011 (save-restriction
18012 (while (setq file (pop files))
18013 (catch 'nextfile
18014 (if (bufferp file)
18015 (set-buffer file)
18016 (org-check-agenda-file file)
18017 (set-buffer (org-get-agenda-file-buffer file)))
18018 (widen)
18019 (org-set-regexps-and-options-for-tags)
18020 (goto-char (point-min))
18021 (let ((case-fold-search t))
18022 (when (search-forward "#+setupfile" nil t)
18023 ;; Don't set all regexps and options systematically as
18024 ;; this is only run for setting agenda tags from setup
18025 ;; file
18026 (org-set-regexps-and-options)))
18027 (org-refresh-category-properties)
18028 (org-refresh-properties org-effort-property 'org-effort)
18029 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
18030 (setq org-todo-keywords-for-agenda
18031 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18032 (setq org-done-keywords-for-agenda
18033 (append org-done-keywords-for-agenda org-done-keywords))
18034 (setq org-todo-keyword-alist-for-agenda
18035 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18036 (setq org-drawers-for-agenda
18037 (append org-drawers-for-agenda org-drawers))
18038 (setq org-tag-alist-for-agenda
18039 (org-uniquify
18040 (append org-tag-alist-for-agenda
18041 org-tag-alist
18042 org-tag-persistent-alist)))
18043 (if org-group-tags
18044 (setq org-tag-groups-alist-for-agenda
18045 (org-uniquify-alist
18046 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18047 (org-with-silent-modifications
18048 (save-excursion
18049 (remove-text-properties (point-min) (point-max) pall)
18050 (when org-agenda-skip-archived-trees
18051 (goto-char (point-min))
18052 (while (re-search-forward rea nil t)
18053 (if (org-at-heading-p t)
18054 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18055 (goto-char (point-min))
18056 (setq re (format org-heading-keyword-regexp-format
18057 org-comment-string))
18058 (while (re-search-forward re nil t)
18059 (add-text-properties
18060 (match-beginning 0) (org-end-of-subtree t) pc))))))))
18061 (setq org-todo-keywords-for-agenda
18062 (org-uniquify org-todo-keywords-for-agenda))
18063 (setq org-todo-keyword-alist-for-agenda
18064 (org-uniquify org-todo-keyword-alist-for-agenda))))
18067 ;;;; CDLaTeX minor mode
18069 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18070 "Keymap for the minor `org-cdlatex-mode'.")
18072 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18073 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18074 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18075 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18076 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18078 (defvar org-cdlatex-texmathp-advice-is-done nil
18079 "Flag remembering if we have applied the advice to texmathp already.")
18081 (define-minor-mode org-cdlatex-mode
18082 "Toggle the minor `org-cdlatex-mode'.
18083 This mode supports entering LaTeX environment and math in LaTeX fragments
18084 in Org-mode.
18085 \\{org-cdlatex-mode-map}"
18086 nil " OCDL" nil
18087 (when org-cdlatex-mode
18088 (require 'cdlatex)
18089 (run-hooks 'cdlatex-mode-hook)
18090 (cdlatex-compute-tables))
18091 (unless org-cdlatex-texmathp-advice-is-done
18092 (setq org-cdlatex-texmathp-advice-is-done t)
18093 (defadvice texmathp (around org-math-always-on activate)
18094 "Always return t in org-mode buffers.
18095 This is because we want to insert math symbols without dollars even outside
18096 the LaTeX math segments. If Orgmode thinks that point is actually inside
18097 an embedded LaTeX fragment, let texmathp do its job.
18098 \\[org-cdlatex-mode-map]"
18099 (interactive)
18100 (let (p)
18101 (cond
18102 ((not (derived-mode-p 'org-mode)) ad-do-it)
18103 ((eq this-command 'cdlatex-math-symbol)
18104 (setq ad-return-value t
18105 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18107 (let ((p (org-inside-LaTeX-fragment-p)))
18108 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18109 (setq ad-return-value t
18110 texmathp-why '("Org-mode embedded math" . 0))
18111 (if p ad-do-it)))))))))
18113 (defun turn-on-org-cdlatex ()
18114 "Unconditionally turn on `org-cdlatex-mode'."
18115 (org-cdlatex-mode 1))
18117 (defun org-try-cdlatex-tab ()
18118 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18119 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18120 - inside a LaTeX fragment, or
18121 - after the first word in a line, where an abbreviation expansion could
18122 insert a LaTeX environment."
18123 (when org-cdlatex-mode
18124 (cond
18125 ;; Before any word on the line: No expansion possible.
18126 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18127 ;; Just after first word on the line: Expand it. Make sure it
18128 ;; cannot happen on headlines, though.
18129 ((save-excursion
18130 (skip-chars-backward "a-zA-Z0-9*")
18131 (skip-chars-backward " \t")
18132 (and (bolp) (not (org-at-heading-p))))
18133 (cdlatex-tab) t)
18134 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18136 (defun org-cdlatex-underscore-caret (&optional arg)
18137 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18138 Revert to the normal definition outside of these fragments."
18139 (interactive "P")
18140 (if (org-inside-LaTeX-fragment-p)
18141 (call-interactively 'cdlatex-sub-superscript)
18142 (let (org-cdlatex-mode)
18143 (call-interactively (key-binding (vector last-input-event))))))
18145 (defun org-cdlatex-math-modify (&optional arg)
18146 "Execute `cdlatex-math-modify' in LaTeX fragments.
18147 Revert to the normal definition outside of these fragments."
18148 (interactive "P")
18149 (if (org-inside-LaTeX-fragment-p)
18150 (call-interactively 'cdlatex-math-modify)
18151 (let (org-cdlatex-mode)
18152 (call-interactively (key-binding (vector last-input-event))))))
18156 ;;;; LaTeX fragments
18158 (defvar org-latex-regexps
18159 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18160 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18161 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18162 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18163 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18164 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18165 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18166 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18167 "Regular expressions for matching embedded LaTeX.")
18169 (defun org-inside-LaTeX-fragment-p ()
18170 "Test if point is inside a LaTeX fragment.
18171 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18172 sequence appearing also before point.
18173 Even though the matchers for math are configurable, this function assumes
18174 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18175 delimiters are skipped when they have been removed by customization.
18176 The return value is nil, or a cons cell with the delimiter and the
18177 position of this delimiter.
18179 This function does a reasonably good job, but can locally be fooled by
18180 for example currency specifications. For example it will assume being in
18181 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18182 fragments that are properly closed, but during editing, we have to live
18183 with the uncertainty caused by missing closing delimiters. This function
18184 looks only before point, not after."
18185 (catch 'exit
18186 (let ((pos (point))
18187 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18188 (lim (progn
18189 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18190 (point)))
18191 dd-on str (start 0) m re)
18192 (goto-char pos)
18193 (when dodollar
18194 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18195 re (nth 1 (assoc "$" org-latex-regexps)))
18196 (while (string-match re str start)
18197 (cond
18198 ((= (match-end 0) (length str))
18199 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18200 ((= (match-end 0) (- (length str) 5))
18201 (throw 'exit nil))
18202 (t (setq start (match-end 0))))))
18203 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18204 (goto-char pos)
18205 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18206 (and (match-beginning 2) (throw 'exit nil))
18207 ;; count $$
18208 (while (re-search-backward "\\$\\$" lim t)
18209 (setq dd-on (not dd-on)))
18210 (goto-char pos)
18211 (if dd-on (cons "$$" m))))))
18213 (defun org-inside-latex-macro-p ()
18214 "Is point inside a LaTeX macro or its arguments?"
18215 (save-match-data
18216 (org-in-regexp
18217 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18219 (defvar org-latex-fragment-image-overlays nil
18220 "List of overlays carrying the images of latex fragments.")
18221 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18223 (defun org-remove-latex-fragment-image-overlays ()
18224 "Remove all overlays with LaTeX fragment images in current buffer."
18225 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18226 (setq org-latex-fragment-image-overlays nil))
18228 (defun org-preview-latex-fragment (&optional subtree)
18229 "Preview the LaTeX fragment at point, or all locally or globally.
18230 If the cursor is in a LaTeX fragment, create the image and overlay
18231 it over the source code. If there is no fragment at point, display
18232 all fragments in the current text, from one headline to the next. With
18233 prefix SUBTREE, display all fragments in the current subtree. With a
18234 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18235 the cursor is before the first headline,
18236 display all fragments in the buffer.
18237 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18238 (interactive "P")
18239 (unless buffer-file-name
18240 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18241 (when (display-graphic-p)
18242 (org-remove-latex-fragment-image-overlays)
18243 (save-excursion
18244 (save-restriction
18245 (let (beg end at msg)
18246 (cond
18247 ((or (equal subtree '(16))
18248 (not (save-excursion
18249 (re-search-backward org-outline-regexp-bol nil t))))
18250 (setq beg (point-min) end (point-max)
18251 msg "Creating images for buffer...%s"))
18252 ((equal subtree '(4))
18253 (org-back-to-heading)
18254 (setq beg (point) end (org-end-of-subtree t)
18255 msg "Creating images for subtree...%s"))
18257 (if (setq at (org-inside-LaTeX-fragment-p))
18258 (goto-char (max (point-min) (- (cdr at) 2)))
18259 (org-back-to-heading))
18260 (setq beg (point) end (progn (outline-next-heading) (point))
18261 msg (if at "Creating image...%s"
18262 "Creating images for entry...%s"))))
18263 (message msg "")
18264 (narrow-to-region beg end)
18265 (goto-char beg)
18266 (org-format-latex
18267 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18268 (file-name-nondirectory
18269 buffer-file-name)))
18270 default-directory 'overlays msg at 'forbuffer
18271 org-latex-create-formula-image-program)
18272 (message msg "done. Use `C-c C-c' to remove images."))))))
18274 (defun org-format-latex (prefix &optional dir overlays msg at
18275 forbuffer processing-type)
18276 "Replace LaTeX fragments with links to an image, and produce images.
18277 Some of the options can be changed using the variable
18278 `org-format-latex-options'."
18279 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18280 (let* ((prefixnodir (file-name-nondirectory prefix))
18281 (absprefix (expand-file-name prefix dir))
18282 (todir (file-name-directory absprefix))
18283 (opt org-format-latex-options)
18284 (optnew org-format-latex-options)
18285 (matchers (plist-get opt :matchers))
18286 (re-list org-latex-regexps)
18287 (cnt 0) txt hash link beg end re e checkdir
18288 string
18289 m n block-type block linkfile movefile ov)
18290 ;; Check the different regular expressions
18291 (while (setq e (pop re-list))
18292 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18293 block (if block-type "\n\n" ""))
18294 (when (member m matchers)
18295 (goto-char (point-min))
18296 (while (re-search-forward re nil t)
18297 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18298 (or (not overlays)
18299 (not (eq (get-char-property (match-beginning n)
18300 'org-overlay-type)
18301 'org-latex-overlay))))
18302 (cond
18303 ((eq processing-type 'verbatim))
18304 ((eq processing-type 'mathjax)
18305 ;; Prepare for MathJax processing.
18306 (setq string (match-string n))
18307 (when (member m '("$" "$1"))
18308 (save-excursion
18309 (delete-region (match-beginning n) (match-end n))
18310 (goto-char (match-beginning n))
18311 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18312 ((or (eq processing-type 'dvipng)
18313 (eq processing-type 'imagemagick))
18314 ;; Process to an image.
18315 (setq txt (match-string n)
18316 beg (match-beginning n) end (match-end n)
18317 cnt (1+ cnt))
18318 (let ((face (face-at-point))
18319 (fg (plist-get opt :foreground))
18320 (bg (plist-get opt :background))
18321 ;; Ensure full list is printed.
18322 print-length print-level)
18323 (when forbuffer
18324 ;; Get the colors from the face at point.
18325 (goto-char beg)
18326 (when (eq fg 'auto)
18327 (setq fg (face-attribute face :foreground nil 'default)))
18328 (when (eq bg 'auto)
18329 (setq bg (face-attribute face :background nil 'default)))
18330 (setq optnew (copy-sequence opt))
18331 (plist-put optnew :foreground fg)
18332 (plist-put optnew :background bg))
18333 (setq hash (sha1 (prin1-to-string
18334 (list org-format-latex-header
18335 org-latex-default-packages-alist
18336 org-latex-packages-alist
18337 org-format-latex-options
18338 forbuffer txt fg bg)))
18339 linkfile (format "%s_%s.png" prefix hash)
18340 movefile (format "%s_%s.png" absprefix hash)))
18341 (setq link (concat block "[[file:" linkfile "]]" block))
18342 (if msg (message msg cnt))
18343 (goto-char beg)
18344 (unless checkdir ; Ensure the directory exists.
18345 (setq checkdir t)
18346 (or (file-directory-p todir) (make-directory todir t)))
18347 (unless (file-exists-p movefile)
18348 (org-create-formula-image
18349 txt movefile optnew forbuffer processing-type))
18350 (if overlays
18351 (progn
18352 (mapc (lambda (o)
18353 (if (eq (overlay-get o 'org-overlay-type)
18354 'org-latex-overlay)
18355 (delete-overlay o)))
18356 (overlays-in beg end))
18357 (setq ov (make-overlay beg end))
18358 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18359 (if (featurep 'xemacs)
18360 (progn
18361 (overlay-put ov 'invisible t)
18362 (overlay-put
18363 ov 'end-glyph
18364 (make-glyph (vector 'png :file movefile))))
18365 (overlay-put
18366 ov 'display
18367 (list 'image :type 'png :file movefile :ascent 'center)))
18368 (push ov org-latex-fragment-image-overlays)
18369 (goto-char end))
18370 (delete-region beg end)
18371 (insert (org-add-props link
18372 (list 'org-latex-src
18373 (replace-regexp-in-string
18374 "\"" "" txt)
18375 'org-latex-src-embed-type
18376 (if block-type 'paragraph 'character))))))
18377 ((eq processing-type 'mathml)
18378 ;; Process to MathML
18379 (unless (save-match-data (org-format-latex-mathml-available-p))
18380 (user-error "LaTeX to MathML converter not configured"))
18381 (setq txt (match-string n)
18382 beg (match-beginning n) end (match-end n)
18383 cnt (1+ cnt))
18384 (if msg (message msg cnt))
18385 (goto-char beg)
18386 (delete-region beg end)
18387 (insert (org-format-latex-as-mathml
18388 txt block-type prefix dir)))
18390 (error "Unknown conversion type %s for LaTeX fragments"
18391 processing-type)))))))))
18393 (defun org-create-math-formula (latex-frag &optional mathml-file)
18394 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18395 Use `org-latex-to-mathml-convert-command'. If the conversion is
18396 sucessful, return the portion between \"<math...> </math>\"
18397 elements otherwise return nil. When MATHML-FILE is specified,
18398 write the results in to that file. When invoked as an
18399 interactive command, prompt for LATEX-FRAG, with initial value
18400 set to the current active region and echo the results for user
18401 inspection."
18402 (interactive (list (let ((frag (when (org-region-active-p)
18403 (buffer-substring-no-properties
18404 (region-beginning) (region-end)))))
18405 (read-string "LaTeX Fragment: " frag nil frag))))
18406 (unless latex-frag (error "Invalid LaTeX fragment"))
18407 (let* ((tmp-in-file (file-relative-name
18408 (make-temp-name (expand-file-name "ltxmathml-in"))))
18409 (ignore (write-region latex-frag nil tmp-in-file))
18410 (tmp-out-file (file-relative-name
18411 (make-temp-name (expand-file-name "ltxmathml-out"))))
18412 (cmd (format-spec
18413 org-latex-to-mathml-convert-command
18414 `((?j . ,(shell-quote-argument
18415 (expand-file-name org-latex-to-mathml-jar-file)))
18416 (?I . ,(shell-quote-argument tmp-in-file))
18417 (?o . ,(shell-quote-argument tmp-out-file)))))
18418 mathml shell-command-output)
18419 (when (org-called-interactively-p 'any)
18420 (unless (org-format-latex-mathml-available-p)
18421 (user-error "LaTeX to MathML converter not configured")))
18422 (message "Running %s" cmd)
18423 (setq shell-command-output (shell-command-to-string cmd))
18424 (setq mathml
18425 (when (file-readable-p tmp-out-file)
18426 (with-current-buffer (find-file-noselect tmp-out-file t)
18427 (goto-char (point-min))
18428 (when (re-search-forward
18429 (concat
18430 (regexp-quote
18431 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18432 "\\(.\\|\n\\)*"
18433 (regexp-quote "</math>")) nil t)
18434 (prog1 (match-string 0) (kill-buffer))))))
18435 (cond
18436 (mathml
18437 (setq mathml
18438 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18439 (when mathml-file
18440 (write-region mathml nil mathml-file))
18441 (when (org-called-interactively-p 'any)
18442 (message mathml)))
18443 ((message "LaTeX to MathML conversion failed")
18444 (message shell-command-output)))
18445 (delete-file tmp-in-file)
18446 (when (file-exists-p tmp-out-file)
18447 (delete-file tmp-out-file))
18448 mathml))
18450 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18451 prefix &optional dir)
18452 "Use `org-create-math-formula' but check local cache first."
18453 (let* ((absprefix (expand-file-name prefix dir))
18454 (print-length nil) (print-level nil)
18455 (formula-id (concat
18456 "formula-"
18457 (sha1
18458 (prin1-to-string
18459 (list latex-frag
18460 org-latex-to-mathml-convert-command)))))
18461 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18462 (formula-cache-dir (file-name-directory formula-cache)))
18464 (unless (file-directory-p formula-cache-dir)
18465 (make-directory formula-cache-dir t))
18467 (unless (file-exists-p formula-cache)
18468 (org-create-math-formula latex-frag formula-cache))
18470 (if (file-exists-p formula-cache)
18471 ;; Successful conversion. Return the link to MathML file.
18472 (org-add-props
18473 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18474 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18475 'org-latex-src-embed-type (if latex-frag-type
18476 'paragraph 'character)))
18477 ;; Failed conversion. Return the LaTeX fragment verbatim
18478 latex-frag)))
18480 (defun org-create-formula-image (string tofile options buffer &optional type)
18481 "Create an image from LaTeX source using dvipng or convert.
18482 This function calls either `org-create-formula-image-with-dvipng'
18483 or `org-create-formula-image-with-imagemagick' depending on the
18484 value of `org-latex-create-formula-image-program' or on the value
18485 of the optional TYPE variable.
18487 Note: ultimately these two function should be combined as they
18488 share a good deal of logic."
18489 (org-check-external-command
18490 "latex" "needed to convert LaTeX fragments to images")
18491 (funcall
18492 (case (or type org-latex-create-formula-image-program)
18493 ('dvipng
18494 (org-check-external-command
18495 "dvipng" "needed to convert LaTeX fragments to images")
18496 #'org-create-formula-image-with-dvipng)
18497 ('imagemagick
18498 (org-check-external-command
18499 "convert" "you need to install imagemagick")
18500 #'org-create-formula-image-with-imagemagick)
18501 (t (error
18502 "Invalid value of `org-latex-create-formula-image-program'")))
18503 string tofile options buffer))
18505 (declare-function org-export--get-global-options "ox" (&optional backend))
18506 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18507 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18508 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18509 (defun org-create-formula--latex-header ()
18510 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18511 (let ((info (org-combine-plists (org-export--get-global-options 'latex)
18512 (org-export--get-inbuffer-options 'latex))))
18513 (org-latex-guess-babel-language
18514 (org-latex-guess-inputenc
18515 (org-splice-latex-header
18516 org-format-latex-header
18517 org-latex-default-packages-alist
18518 org-latex-packages-alist t
18519 (plist-get info :latex-header)))
18520 info)))
18522 ;; This function borrows from Ganesh Swami's latex2png.el
18523 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18524 "This calls dvipng."
18525 (require 'ox-latex)
18526 (let* ((tmpdir (if (featurep 'xemacs)
18527 (temp-directory)
18528 temporary-file-directory))
18529 (texfilebase (make-temp-name
18530 (expand-file-name "orgtex" tmpdir)))
18531 (texfile (concat texfilebase ".tex"))
18532 (dvifile (concat texfilebase ".dvi"))
18533 (pngfile (concat texfilebase ".png"))
18534 (fnh (if (featurep 'xemacs)
18535 (font-height (face-font 'default))
18536 (face-attribute 'default :height nil)))
18537 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18538 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18539 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18540 "Black"))
18541 (bg (or (plist-get options (if buffer :background :html-background))
18542 "Transparent")))
18543 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18544 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18545 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18546 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18547 (let ((latex-header (org-create-formula--latex-header)))
18548 (with-temp-file texfile
18549 (insert latex-header)
18550 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18551 (let ((dir default-directory))
18552 (condition-case nil
18553 (progn
18554 (cd tmpdir)
18555 (call-process "latex" nil nil nil texfile))
18556 (error nil))
18557 (cd dir))
18558 (if (not (file-exists-p dvifile))
18559 (progn (message "Failed to create dvi file from %s" texfile) nil)
18560 (condition-case nil
18561 (if (featurep 'xemacs)
18562 (call-process "dvipng" nil nil nil
18563 "-fg" fg "-bg" bg
18564 "-T" "tight"
18565 "-o" pngfile
18566 dvifile)
18567 (call-process "dvipng" nil nil nil
18568 "-fg" fg "-bg" bg
18569 "-D" dpi
18570 ;;"-x" scale "-y" scale
18571 "-T" "tight"
18572 "-o" pngfile
18573 dvifile))
18574 (error nil))
18575 (if (not (file-exists-p pngfile))
18576 (if org-format-latex-signal-error
18577 (error "Failed to create png file from %s" texfile)
18578 (message "Failed to create png file from %s" texfile)
18579 nil)
18580 ;; Use the requested file name and clean up
18581 (copy-file pngfile tofile 'replace)
18582 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18583 (if (file-exists-p (concat texfilebase e))
18584 (delete-file (concat texfilebase e))))
18585 pngfile))))
18587 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18588 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18589 "This calls convert, which is included into imagemagick."
18590 (require 'ox-latex)
18591 (let* ((tmpdir (if (featurep 'xemacs)
18592 (temp-directory)
18593 temporary-file-directory))
18594 (texfilebase (make-temp-name
18595 (expand-file-name "orgtex" tmpdir)))
18596 (texfile (concat texfilebase ".tex"))
18597 (pdffile (concat texfilebase ".pdf"))
18598 (pngfile (concat texfilebase ".png"))
18599 (fnh (if (featurep 'xemacs)
18600 (font-height (face-font 'default))
18601 (face-attribute 'default :height nil)))
18602 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18603 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18604 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18605 "black"))
18606 (bg (or (plist-get options (if buffer :background :html-background))
18607 "white")))
18608 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18609 (setq fg (org-latex-color-format fg)))
18610 (if (eq bg 'default) (setq bg (org-latex-color :background))
18611 (setq bg (org-latex-color-format
18612 (if (string= bg "Transparent") "white" bg))))
18613 (let ((latex-header (org-create-formula--latex-header)))
18614 (with-temp-file texfile
18615 (insert latex-header)
18616 (insert "\n\\begin{document}\n"
18617 "\\definecolor{fg}{rgb}{" fg "}\n"
18618 "\\definecolor{bg}{rgb}{" bg "}\n"
18619 "\n\\pagecolor{bg}\n"
18620 "\n{\\color{fg}\n"
18621 string
18622 "\n}\n"
18623 "\n\\end{document}\n")))
18624 (org-latex-compile texfile t)
18625 (if (not (file-exists-p pdffile))
18626 (progn (message "Failed to create pdf file from %s" texfile) nil)
18627 (condition-case nil
18628 (if (featurep 'xemacs)
18629 (call-process "convert" nil nil nil
18630 "-density" "96"
18631 "-trim"
18632 "-antialias"
18633 pdffile
18634 "-quality" "100"
18635 ;; "-sharpen" "0x1.0"
18636 pngfile)
18637 (call-process "convert" nil nil nil
18638 "-density" dpi
18639 "-trim"
18640 "-antialias"
18641 pdffile
18642 "-quality" "100"
18643 ;; "-sharpen" "0x1.0"
18644 pngfile))
18645 (error nil))
18646 (if (not (file-exists-p pngfile))
18647 (if org-format-latex-signal-error
18648 (error "Failed to create png file from %s" texfile)
18649 (message "Failed to create png file from %s" texfile)
18650 nil)
18651 ;; Use the requested file name and clean up
18652 (copy-file pngfile tofile 'replace)
18653 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18654 (if (file-exists-p (concat texfilebase e))
18655 (delete-file (concat texfilebase e))))
18656 pngfile))))
18658 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18659 "Fill a LaTeX header template TPL.
18660 In the template, the following place holders will be recognized:
18662 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18663 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18664 [PACKAGES] \\usepackage statements for PKG
18665 [NO-PACKAGES] do not include PKG
18666 [EXTRA] the string EXTRA
18667 [NO-EXTRA] do not include EXTRA
18669 For backward compatibility, if both the positive and the negative place
18670 holder is missing, the positive one (without the \"NO-\") will be
18671 assumed to be present at the end of the template.
18672 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18673 EXTRA is a string.
18674 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18675 (let (rpl (end ""))
18676 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18677 (setq rpl (if (or (match-end 1) (not def-pkg))
18678 "" (org-latex-packages-to-string def-pkg snippets-p t))
18679 tpl (replace-match rpl t t tpl))
18680 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18682 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18683 (setq rpl (if (or (match-end 1) (not pkg))
18684 "" (org-latex-packages-to-string pkg snippets-p t))
18685 tpl (replace-match rpl t t tpl))
18686 (if pkg (setq end
18687 (concat end "\n"
18688 (org-latex-packages-to-string pkg snippets-p)))))
18690 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18691 (setq rpl (if (or (match-end 1) (not extra))
18692 "" (concat extra "\n"))
18693 tpl (replace-match rpl t t tpl))
18694 (if (and extra (string-match "\\S-" extra))
18695 (setq end (concat end "\n" extra))))
18697 (if (string-match "\\S-" end)
18698 (concat tpl "\n" end)
18699 tpl)))
18701 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18702 "Turn an alist of packages into a string with the \\usepackage macros."
18703 (setq pkg (mapconcat (lambda(p)
18704 (cond
18705 ((stringp p) p)
18706 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18707 (format "%% Package %s omitted" (cadr p)))
18708 ((equal "" (car p))
18709 (format "\\usepackage{%s}" (cadr p)))
18711 (format "\\usepackage[%s]{%s}"
18712 (car p) (cadr p)))))
18714 "\n"))
18715 (if newline (concat pkg "\n") pkg))
18717 (defun org-dvipng-color (attr)
18718 "Return a RGB color specification for dvipng."
18719 (apply 'format "rgb %s %s %s"
18720 (mapcar 'org-normalize-color
18721 (if (featurep 'xemacs)
18722 (color-rgb-components
18723 (face-property 'default
18724 (cond ((eq attr :foreground) 'foreground)
18725 ((eq attr :background) 'background))))
18726 (color-values (face-attribute 'default attr nil))))))
18728 (defun org-dvipng-color-format (color-name)
18729 "Convert COLOR-NAME to a RGB color value for dvipng."
18730 (apply 'format "rgb %s %s %s"
18731 (mapcar 'org-normalize-color
18732 (color-values color-name))))
18734 (defun org-latex-color (attr)
18735 "Return a RGB color for the LaTeX color package."
18736 (apply 'format "%s,%s,%s"
18737 (mapcar 'org-normalize-color
18738 (if (featurep 'xemacs)
18739 (color-rgb-components
18740 (face-property 'default
18741 (cond ((eq attr :foreground) 'foreground)
18742 ((eq attr :background) 'background))))
18743 (color-values (face-attribute 'default attr nil))))))
18745 (defun org-latex-color-format (color-name)
18746 "Convert COLOR-NAME to a RGB color value."
18747 (apply 'format "%s,%s,%s"
18748 (mapcar 'org-normalize-color
18749 (color-values color-name))))
18751 (defun org-normalize-color (value)
18752 "Return string to be used as color value for an RGB component."
18753 (format "%g" (/ value 65535.0)))
18757 ;; Image display
18759 (defvar org-inline-image-overlays nil)
18760 (make-variable-buffer-local 'org-inline-image-overlays)
18762 (defun org-toggle-inline-images (&optional include-linked)
18763 "Toggle the display of inline images.
18764 INCLUDE-LINKED is passed to `org-display-inline-images'."
18765 (interactive "P")
18766 (if org-inline-image-overlays
18767 (progn
18768 (org-remove-inline-images)
18769 (message "Inline image display turned off"))
18770 (org-display-inline-images include-linked)
18771 (if (and (org-called-interactively-p)
18772 org-inline-image-overlays)
18773 (message "%d images displayed inline"
18774 (length org-inline-image-overlays))
18775 (message "No images to display inline"))))
18777 (defun org-redisplay-inline-images ()
18778 "Refresh the display of inline images."
18779 (interactive)
18780 (if (not org-inline-image-overlays)
18781 (org-toggle-inline-images)
18782 (org-toggle-inline-images)
18783 (org-toggle-inline-images)))
18785 (defun org-display-inline-images (&optional include-linked refresh beg end)
18786 "Display inline images.
18787 Normally only links without a description part are inlined, because this
18788 is how it will work for export. When INCLUDE-LINKED is set, also links
18789 with a description part will be inlined. This can be nice for a quick
18790 look at those images, but it does not reflect what exported files will look
18791 like.
18792 When REFRESH is set, refresh existing images between BEG and END.
18793 This will create new image displays only if necessary.
18794 BEG and END default to the buffer boundaries."
18795 (interactive "P")
18796 (when (display-graphic-p)
18797 (unless refresh
18798 (org-remove-inline-images)
18799 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18800 (save-excursion
18801 (save-restriction
18802 (widen)
18803 (setq beg (or beg (point-min)) end (or end (point-max)))
18804 (goto-char beg)
18805 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18806 (substring (org-image-file-name-regexp) 0 -2)
18807 "\\)\\]" (if include-linked "" "\\]")))
18808 (case-fold-search t)
18809 old file ov img type attrwidth width)
18810 (while (re-search-forward re end t)
18811 (setq old (get-char-property-and-overlay (match-beginning 1)
18812 'org-image-overlay)
18813 file (expand-file-name
18814 (concat (or (match-string 3) "") (match-string 4))))
18815 (when (image-type-available-p 'imagemagick)
18816 (setq attrwidth (if (or (listp org-image-actual-width)
18817 (null org-image-actual-width))
18818 (save-excursion
18819 (save-match-data
18820 (when (re-search-backward
18821 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18822 (save-excursion
18823 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18824 (string-to-number (match-string 1))))))
18825 width (cond ((eq org-image-actual-width t) nil)
18826 ((null org-image-actual-width) attrwidth)
18827 ((numberp org-image-actual-width)
18828 org-image-actual-width)
18829 ((listp org-image-actual-width)
18830 (or attrwidth (car org-image-actual-width))))
18831 type (if width 'imagemagick)))
18832 (when (file-exists-p file)
18833 (if (and (car-safe old) refresh)
18834 (image-refresh (overlay-get (cdr old) 'display))
18835 (setq img (save-match-data (create-image file type nil :width width)))
18836 (when img
18837 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18838 (overlay-put ov 'display img)
18839 (overlay-put ov 'face 'default)
18840 (overlay-put ov 'org-image-overlay t)
18841 (overlay-put ov 'modification-hooks
18842 (list 'org-display-inline-remove-overlay))
18843 (push ov org-inline-image-overlays))))))))))
18845 (define-obsolete-function-alias
18846 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18848 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18849 "Remove inline-display overlay if a corresponding region is modified."
18850 (let ((inhibit-modification-hooks t))
18851 (when (and ov after)
18852 (delete ov org-inline-image-overlays)
18853 (delete-overlay ov))))
18855 (defun org-remove-inline-images ()
18856 "Remove inline display of images."
18857 (interactive)
18858 (mapc 'delete-overlay org-inline-image-overlays)
18859 (setq org-inline-image-overlays nil))
18861 ;;;; Key bindings
18863 ;; Outline functions from `outline-mode-prefix-map'
18864 ;; that can be remapped in Org:
18865 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18866 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18867 (define-key org-mode-map [remap outline-forward-same-level]
18868 'org-forward-heading-same-level)
18869 (define-key org-mode-map [remap outline-backward-same-level]
18870 'org-backward-heading-same-level)
18871 (define-key org-mode-map [remap show-branches]
18872 'org-kill-note-or-show-branches)
18873 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18874 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18875 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18877 ;; Outline functions from `outline-mode-prefix-map' that can not
18878 ;; be remapped in Org:
18880 ;; - the column "key binding" shows whether the Outline function is still
18881 ;; available in Org mode on the same key that it has been bound to in
18882 ;; Outline mode:
18883 ;; - "overridden": key used for a different functionality in Org mode
18884 ;; - else: key still bound to the same Outline function in Org mode
18886 ;; | Outline function | key binding | Org replacement |
18887 ;; |------------------------------------+-------------+-----------------------|
18888 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18889 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18890 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18891 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18892 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18893 ;; | `show-entry' | overridden | no replacement |
18894 ;; | `show-children' | `C-c C-i' | visibility cycling |
18895 ;; | `show-branches' | `C-c C-k' | still same function |
18896 ;; | `show-subtree' | overridden | visibility cycling |
18897 ;; | `show-all' | overridden | no replacement |
18898 ;; | `hide-subtree' | overridden | visibility cycling |
18899 ;; | `hide-body' | overridden | no replacement |
18900 ;; | `hide-entry' | overridden | visibility cycling |
18901 ;; | `hide-leaves' | overridden | no replacement |
18902 ;; | `hide-sublevels' | overridden | no replacement |
18903 ;; | `hide-other' | overridden | no replacement |
18905 ;; Make `C-c C-x' a prefix key
18906 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18908 ;; TAB key with modifiers
18909 (org-defkey org-mode-map "\C-i" 'org-cycle)
18910 (org-defkey org-mode-map [(tab)] 'org-cycle)
18911 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18912 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18913 ;; The following line is necessary under Suse GNU/Linux
18914 (unless (featurep 'xemacs)
18915 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18916 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18917 (define-key org-mode-map [backtab] 'org-shifttab)
18919 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18920 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18921 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18923 ;; Cursor keys with modifiers
18924 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18925 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18926 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18927 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18929 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18930 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18931 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18932 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18934 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18935 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18936 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18937 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18939 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18940 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18941 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18942 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18944 ;; Babel keys
18945 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18946 (mapc (lambda (pair)
18947 (define-key org-babel-map (car pair) (cdr pair)))
18948 org-babel-key-bindings)
18950 ;;; Extra keys for tty access.
18951 ;; We only set them when really needed because otherwise the
18952 ;; menus don't show the simple keys
18954 (when (or org-use-extra-keys
18955 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18956 (not window-system))
18957 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18958 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18959 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18960 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18961 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18962 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18963 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18964 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18965 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18966 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18967 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18968 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18969 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18970 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18971 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18972 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18973 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18974 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18975 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18976 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18977 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18978 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18979 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18980 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18981 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18982 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18983 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18984 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18986 ;; All the other keys
18988 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18989 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18990 (if (boundp 'narrow-map)
18991 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18992 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18993 (if (boundp 'narrow-map)
18994 (org-defkey narrow-map "b" 'org-narrow-to-block)
18995 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18996 (if (boundp 'narrow-map)
18997 (org-defkey narrow-map "e" 'org-narrow-to-element)
18998 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18999 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19000 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19001 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19002 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19003 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19004 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19005 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19006 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19007 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19008 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19009 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19010 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19011 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19012 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19013 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19014 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19015 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19016 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19017 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19018 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19019 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19020 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19021 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19022 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19023 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19024 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19025 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19026 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19027 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19028 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19029 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19030 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19031 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19032 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19033 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19034 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19035 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19036 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19037 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19038 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19039 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19040 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19041 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19042 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19043 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19044 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19045 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19046 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19047 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19048 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19049 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19050 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19051 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19052 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19053 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19054 (org-defkey org-mode-map "\C-c^" 'org-sort)
19055 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19056 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19057 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19058 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19059 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-element)
19060 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-element)
19061 (org-defkey org-mode-map "\C-m" 'org-return)
19062 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19063 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19064 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19065 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19066 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19067 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19068 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19069 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19070 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19071 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19072 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19073 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19074 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19075 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19076 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19077 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19078 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19079 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19080 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19081 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19082 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19083 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19084 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19086 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19087 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19088 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19090 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19091 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19092 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19093 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19094 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19095 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19096 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19097 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19098 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19099 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19100 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19101 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19102 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19103 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19104 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19105 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19106 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19107 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19108 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19109 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19110 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19111 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19112 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19114 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19115 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19116 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19117 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19118 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19120 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19122 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19124 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19125 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19127 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19130 (when (featurep 'xemacs)
19131 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19134 (defconst org-speed-commands-default
19136 ("Outline Navigation")
19137 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19138 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19139 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19140 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19141 ("F" . org-next-block)
19142 ("B" . org-previous-block)
19143 ("u" . (org-speed-move-safe 'outline-up-heading))
19144 ("j" . org-goto)
19145 ("g" . (org-refile t))
19146 ("Outline Visibility")
19147 ("c" . org-cycle)
19148 ("C" . org-shifttab)
19149 (" " . org-display-outline-path)
19150 ("s" . org-narrow-to-subtree)
19151 ("=" . org-columns)
19152 ("Outline Structure Editing")
19153 ("U" . org-shiftmetaup)
19154 ("D" . org-shiftmetadown)
19155 ("r" . org-metaright)
19156 ("l" . org-metaleft)
19157 ("R" . org-shiftmetaright)
19158 ("L" . org-shiftmetaleft)
19159 ("i" . (progn (forward-char 1) (call-interactively
19160 'org-insert-heading-respect-content)))
19161 ("^" . org-sort)
19162 ("w" . org-refile)
19163 ("a" . org-archive-subtree-default-with-confirmation)
19164 ("@" . org-mark-subtree)
19165 ("#" . org-toggle-comment)
19166 ("Clock Commands")
19167 ("I" . org-clock-in)
19168 ("O" . org-clock-out)
19169 ("Meta Data Editing")
19170 ("t" . org-todo)
19171 ("," . (org-priority))
19172 ("0" . (org-priority ?\ ))
19173 ("1" . (org-priority ?A))
19174 ("2" . (org-priority ?B))
19175 ("3" . (org-priority ?C))
19176 (":" . org-set-tags-command)
19177 ("e" . org-set-effort)
19178 ("E" . org-inc-effort)
19179 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19180 (org-entry-put (point) "APPT_WARNTIME" m)))
19181 ("Agenda Views etc")
19182 ("v" . org-agenda)
19183 ("/" . org-sparse-tree)
19184 ("Misc")
19185 ("o" . org-open-at-point)
19186 ("?" . org-speed-command-help)
19187 ("<" . (org-agenda-set-restriction-lock 'subtree))
19188 (">" . (org-agenda-remove-restriction-lock))
19190 "The default speed commands.")
19192 (defun org-print-speed-command (e)
19193 (if (> (length (car e)) 1)
19194 (progn
19195 (princ "\n")
19196 (princ (car e))
19197 (princ "\n")
19198 (princ (make-string (length (car e)) ?-))
19199 (princ "\n"))
19200 (princ (car e))
19201 (princ " ")
19202 (if (symbolp (cdr e))
19203 (princ (symbol-name (cdr e)))
19204 (prin1 (cdr e)))
19205 (princ "\n")))
19207 (defun org-speed-command-help ()
19208 "Show the available speed commands."
19209 (interactive)
19210 (if (not org-use-speed-commands)
19211 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19212 (with-output-to-temp-buffer "*Help*"
19213 (princ "User-defined Speed commands\n===========================\n")
19214 (mapc 'org-print-speed-command org-speed-commands-user)
19215 (princ "\n")
19216 (princ "Built-in Speed commands\n=======================\n")
19217 (mapc 'org-print-speed-command org-speed-commands-default))
19218 (with-current-buffer "*Help*"
19219 (setq truncate-lines t))))
19221 (defun org-speed-move-safe (cmd)
19222 "Execute CMD, but make sure that the cursor always ends up in a headline.
19223 If not, return to the original position and throw an error."
19224 (interactive)
19225 (let ((pos (point)))
19226 (call-interactively cmd)
19227 (unless (and (bolp) (org-at-heading-p))
19228 (goto-char pos)
19229 (error "Boundary reached while executing %s" cmd))))
19231 (defvar org-self-insert-command-undo-counter 0)
19233 (defvar org-table-auto-blank-field) ; defined in org-table.el
19234 (defvar org-speed-command nil)
19236 (define-obsolete-function-alias
19237 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19239 (defun org-speed-command-activate (keys)
19240 "Hook for activating single-letter speed commands.
19241 `org-speed-commands-default' specifies a minimal command set.
19242 Use `org-speed-commands-user' for further customization."
19243 (when (or (and (bolp) (looking-at org-outline-regexp))
19244 (and (functionp org-use-speed-commands)
19245 (funcall org-use-speed-commands)))
19246 (cdr (assoc keys (append org-speed-commands-user
19247 org-speed-commands-default)))))
19249 (define-obsolete-function-alias
19250 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19252 (defun org-babel-speed-command-activate (keys)
19253 "Hook for activating single-letter code block commands."
19254 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19255 (cdr (assoc keys org-babel-key-bindings))))
19257 (defcustom org-speed-command-hook
19258 '(org-speed-command-default-hook org-babel-speed-command-hook)
19259 "Hook for activating speed commands at strategic locations.
19260 Hook functions are called in sequence until a valid handler is
19261 found.
19263 Each hook takes a single argument, a user-pressed command key
19264 which is also a `self-insert-command' from the global map.
19266 Within the hook, examine the cursor position and the command key
19267 and return nil or a valid handler as appropriate. Handler could
19268 be one of an interactive command, a function, or a form.
19270 Set `org-use-speed-commands' to non-nil value to enable this
19271 hook. The default setting is `org-speed-command-activate'."
19272 :group 'org-structure
19273 :version "24.1"
19274 :type 'hook)
19276 (defun org-self-insert-command (N)
19277 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19278 If the cursor is in a table looking at whitespace, the whitespace is
19279 overwritten, and the table is not marked as requiring realignment."
19280 (interactive "p")
19281 (org-check-before-invisible-edit 'insert)
19282 (cond
19283 ((and org-use-speed-commands
19284 (setq org-speed-command
19285 (run-hook-with-args-until-success
19286 'org-speed-command-hook (this-command-keys))))
19287 (cond
19288 ((commandp org-speed-command)
19289 (setq this-command org-speed-command)
19290 (call-interactively org-speed-command))
19291 ((functionp org-speed-command)
19292 (funcall org-speed-command))
19293 ((and org-speed-command (listp org-speed-command))
19294 (eval org-speed-command))
19295 (t (let (org-use-speed-commands)
19296 (call-interactively 'org-self-insert-command)))))
19297 ((and
19298 (org-table-p)
19299 (progn
19300 ;; check if we blank the field, and if that triggers align
19301 (and (featurep 'org-table) org-table-auto-blank-field
19302 (member last-command
19303 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19304 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19305 ;; got extra space, this field does not determine column width
19306 (let (org-table-may-need-update) (org-table-blank-field))
19307 ;; no extra space, this field may determine column width
19308 (org-table-blank-field)))
19310 (eq N 1)
19311 (looking-at "[^|\n]* |"))
19312 (let (org-table-may-need-update)
19313 (goto-char (1- (match-end 0)))
19314 (backward-delete-char 1)
19315 (goto-char (match-beginning 0))
19316 (self-insert-command N)))
19318 (setq org-table-may-need-update t)
19319 (self-insert-command N)
19320 (org-fix-tags-on-the-fly)
19321 (if org-self-insert-cluster-for-undo
19322 (if (not (eq last-command 'org-self-insert-command))
19323 (setq org-self-insert-command-undo-counter 1)
19324 (if (>= org-self-insert-command-undo-counter 20)
19325 (setq org-self-insert-command-undo-counter 1)
19326 (and (> org-self-insert-command-undo-counter 0)
19327 buffer-undo-list (listp buffer-undo-list)
19328 (not (cadr buffer-undo-list)) ; remove nil entry
19329 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19330 (setq org-self-insert-command-undo-counter
19331 (1+ org-self-insert-command-undo-counter))))))))
19333 (defun org-check-before-invisible-edit (kind)
19334 "Check is editing if kind KIND would be dangerous with invisible text around.
19335 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19336 ;; First, try to get out of here as quickly as possible, to reduce overhead
19337 (if (and org-catch-invisible-edits
19338 (or (not (boundp 'visible-mode)) (not visible-mode))
19339 (or (get-char-property (point) 'invisible)
19340 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19341 ;; OK, we need to take a closer look
19342 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19343 (invisible-before-point (if (bobp) nil (get-char-property
19344 (1- (point)) 'invisible)))
19345 (border-and-ok-direction
19347 ;; Check if we are acting predictably before invisible text
19348 (and invisible-at-point (not invisible-before-point)
19349 (memq kind '(insert delete-backward)))
19350 ;; Check if we are acting predictably after invisible text
19351 ;; This works not well, and I have turned it off. It seems
19352 ;; better to always show and stop after invisible text.
19353 ;; (and (not invisible-at-point) invisible-before-point
19354 ;; (memq kind '(insert delete)))
19356 (when (or (memq invisible-at-point '(outline org-hide-block t))
19357 (memq invisible-before-point '(outline org-hide-block t)))
19358 (if (eq org-catch-invisible-edits 'error)
19359 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19360 (if (and org-custom-properties-overlays
19361 (y-or-n-p "Display invisible properties in this buffer? "))
19362 (org-toggle-custom-properties-visibility)
19363 ;; Make the area visible
19364 (save-excursion
19365 (if invisible-before-point
19366 (goto-char (previous-single-char-property-change
19367 (point) 'invisible)))
19368 (org-cycle))
19369 (cond
19370 ((eq org-catch-invisible-edits 'show)
19371 ;; That's it, we do the edit after showing
19372 (message
19373 "Unfolding invisible region around point before editing")
19374 (sit-for 1))
19375 ((and (eq org-catch-invisible-edits 'smart)
19376 border-and-ok-direction)
19377 (message "Unfolding invisible region around point before editing"))
19379 ;; Don't do the edit, make the user repeat it in full visibility
19380 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19382 (defun org-fix-tags-on-the-fly ()
19383 (when (and (equal (char-after (point-at-bol)) ?*)
19384 (org-at-heading-p))
19385 (org-align-tags-here org-tags-column)))
19387 (defun org-delete-backward-char (N)
19388 "Like `delete-backward-char', insert whitespace at field end in tables.
19389 When deleting backwards, in tables this function will insert whitespace in
19390 front of the next \"|\" separator, to keep the table aligned. The table will
19391 still be marked for re-alignment if the field did fill the entire column,
19392 because, in this case the deletion might narrow the column."
19393 (interactive "p")
19394 (save-match-data
19395 (org-check-before-invisible-edit 'delete-backward)
19396 (if (and (org-table-p)
19397 (eq N 1)
19398 (string-match "|" (buffer-substring (point-at-bol) (point)))
19399 (looking-at ".*?|"))
19400 (let ((pos (point))
19401 (noalign (looking-at "[^|\n\r]* |"))
19402 (c org-table-may-need-update))
19403 (backward-delete-char N)
19404 (if (not overwrite-mode)
19405 (progn
19406 (skip-chars-forward "^|")
19407 (insert " ")
19408 (goto-char (1- pos))))
19409 ;; noalign: if there were two spaces at the end, this field
19410 ;; does not determine the width of the column.
19411 (if noalign (setq org-table-may-need-update c)))
19412 (backward-delete-char N)
19413 (org-fix-tags-on-the-fly))))
19415 (defun org-delete-char (N)
19416 "Like `delete-char', but insert whitespace at field end in tables.
19417 When deleting characters, in tables this function will insert whitespace in
19418 front of the next \"|\" separator, to keep the table aligned. The table will
19419 still be marked for re-alignment if the field did fill the entire column,
19420 because, in this case the deletion might narrow the column."
19421 (interactive "p")
19422 (save-match-data
19423 (org-check-before-invisible-edit 'delete)
19424 (if (and (org-table-p)
19425 (not (bolp))
19426 (not (= (char-after) ?|))
19427 (eq N 1))
19428 (if (looking-at ".*?|")
19429 (let ((pos (point))
19430 (noalign (looking-at "[^|\n\r]* |"))
19431 (c org-table-may-need-update))
19432 (replace-match
19433 (concat (substring (match-string 0) 1 -1) " |") nil t)
19434 (goto-char pos)
19435 ;; noalign: if there were two spaces at the end, this field
19436 ;; does not determine the width of the column.
19437 (if noalign (setq org-table-may-need-update c)))
19438 (delete-char N))
19439 (delete-char N)
19440 (org-fix-tags-on-the-fly))))
19442 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19443 (put 'org-self-insert-command 'delete-selection t)
19444 (put 'orgtbl-self-insert-command 'delete-selection t)
19445 (put 'org-delete-char 'delete-selection 'supersede)
19446 (put 'org-delete-backward-char 'delete-selection 'supersede)
19447 (put 'org-yank 'delete-selection 'yank)
19449 ;; Make `flyspell-mode' delay after some commands
19450 (put 'org-self-insert-command 'flyspell-delayed t)
19451 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19452 (put 'org-delete-char 'flyspell-delayed t)
19453 (put 'org-delete-backward-char 'flyspell-delayed t)
19455 ;; Make pabbrev-mode expand after org-mode commands
19456 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19457 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19459 ;; How to do this: Measure non-white length of current string
19460 ;; If equal to column width, we should realign.
19462 (defun org-remap (map &rest commands)
19463 "In MAP, remap the functions given in COMMANDS.
19464 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19465 (let (new old)
19466 (while commands
19467 (setq old (pop commands) new (pop commands))
19468 (if (fboundp 'command-remapping)
19469 (org-defkey map (vector 'remap old) new)
19470 (substitute-key-definition old new map global-map)))))
19472 (defun org-transpose-words ()
19473 "Transpose words for Org.
19474 This uses the `org-mode-transpose-word-syntax-table' syntax
19475 table, which interprets characters in `org-emphasis-alist' as
19476 word constituants."
19477 (interactive)
19478 (with-syntax-table org-mode-transpose-word-syntax-table
19479 (call-interactively 'transpose-words)))
19480 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19482 (when (eq org-enable-table-editor 'optimized)
19483 ;; If the user wants maximum table support, we need to hijack
19484 ;; some standard editing functions
19485 (org-remap org-mode-map
19486 'self-insert-command 'org-self-insert-command
19487 'delete-char 'org-delete-char
19488 'delete-backward-char 'org-delete-backward-char)
19489 (org-defkey org-mode-map "|" 'org-force-self-insert))
19491 (defvar org-ctrl-c-ctrl-c-hook nil
19492 "Hook for functions attaching themselves to `C-c C-c'.
19494 This can be used to add additional functionality to the C-c C-c
19495 key which executes context-dependent commands. This hook is run
19496 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19497 run after the last test.
19499 Each function will be called with no arguments. The function
19500 must check if the context is appropriate for it to act. If yes,
19501 it should do its thing and then return a non-nil value. If the
19502 context is wrong, just do nothing and return nil.")
19504 (defvar org-ctrl-c-ctrl-c-final-hook nil
19505 "Hook for functions attaching themselves to `C-c C-c'.
19507 This can be used to add additional functionality to the C-c C-c
19508 key which executes context-dependent commands. This hook is run
19509 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19510 before the first test.
19512 Each function will be called with no arguments. The function
19513 must check if the context is appropriate for it to act. If yes,
19514 it should do its thing and then return a non-nil value. If the
19515 context is wrong, just do nothing and return nil.")
19517 (defvar org-tab-first-hook nil
19518 "Hook for functions to attach themselves to TAB.
19519 See `org-ctrl-c-ctrl-c-hook' for more information.
19520 This hook runs as the first action when TAB is pressed, even before
19521 `org-cycle' messes around with the `outline-regexp' to cater for
19522 inline tasks and plain list item folding.
19523 If any function in this hook returns t, any other actions that
19524 would have been caused by TAB (such as table field motion or visibility
19525 cycling) will not occur.")
19527 (defvar org-tab-after-check-for-table-hook nil
19528 "Hook for functions to attach themselves to TAB.
19529 See `org-ctrl-c-ctrl-c-hook' for more information.
19530 This hook runs after it has been established that the cursor is not in a
19531 table, but before checking if the cursor is in a headline or if global cycling
19532 should be done.
19533 If any function in this hook returns t, not other actions like visibility
19534 cycling will be done.")
19536 (defvar org-tab-after-check-for-cycling-hook nil
19537 "Hook for functions to attach themselves to TAB.
19538 See `org-ctrl-c-ctrl-c-hook' for more information.
19539 This hook runs after it has been established that not table field motion and
19540 not visibility should be done because of current context. This is probably
19541 the place where a package like yasnippets can hook in.")
19543 (defvar org-tab-before-tab-emulation-hook nil
19544 "Hook for functions to attach themselves to TAB.
19545 See `org-ctrl-c-ctrl-c-hook' for more information.
19546 This hook runs after every other options for TAB have been exhausted, but
19547 before indentation and \t insertion takes place.")
19549 (defvar org-metaleft-hook nil
19550 "Hook for functions attaching themselves to `M-left'.
19551 See `org-ctrl-c-ctrl-c-hook' for more information.")
19552 (defvar org-metaright-hook nil
19553 "Hook for functions attaching themselves to `M-right'.
19554 See `org-ctrl-c-ctrl-c-hook' for more information.")
19555 (defvar org-metaup-hook nil
19556 "Hook for functions attaching themselves to `M-up'.
19557 See `org-ctrl-c-ctrl-c-hook' for more information.")
19558 (defvar org-metadown-hook nil
19559 "Hook for functions attaching themselves to `M-down'.
19560 See `org-ctrl-c-ctrl-c-hook' for more information.")
19561 (defvar org-shiftmetaleft-hook nil
19562 "Hook for functions attaching themselves to `M-S-left'.
19563 See `org-ctrl-c-ctrl-c-hook' for more information.")
19564 (defvar org-shiftmetaright-hook nil
19565 "Hook for functions attaching themselves to `M-S-right'.
19566 See `org-ctrl-c-ctrl-c-hook' for more information.")
19567 (defvar org-shiftmetaup-hook nil
19568 "Hook for functions attaching themselves to `M-S-up'.
19569 See `org-ctrl-c-ctrl-c-hook' for more information.")
19570 (defvar org-shiftmetadown-hook nil
19571 "Hook for functions attaching themselves to `M-S-down'.
19572 See `org-ctrl-c-ctrl-c-hook' for more information.")
19573 (defvar org-metareturn-hook nil
19574 "Hook for functions attaching themselves to `M-RET'.
19575 See `org-ctrl-c-ctrl-c-hook' for more information.")
19576 (defvar org-shiftup-hook nil
19577 "Hook for functions attaching themselves to `S-up'.
19578 See `org-ctrl-c-ctrl-c-hook' for more information.")
19579 (defvar org-shiftup-final-hook nil
19580 "Hook for functions attaching themselves to `S-up'.
19581 This one runs after all other options except shift-select have been excluded.
19582 See `org-ctrl-c-ctrl-c-hook' for more information.")
19583 (defvar org-shiftdown-hook nil
19584 "Hook for functions attaching themselves to `S-down'.
19585 See `org-ctrl-c-ctrl-c-hook' for more information.")
19586 (defvar org-shiftdown-final-hook nil
19587 "Hook for functions attaching themselves to `S-down'.
19588 This one runs after all other options except shift-select have been excluded.
19589 See `org-ctrl-c-ctrl-c-hook' for more information.")
19590 (defvar org-shiftleft-hook nil
19591 "Hook for functions attaching themselves to `S-left'.
19592 See `org-ctrl-c-ctrl-c-hook' for more information.")
19593 (defvar org-shiftleft-final-hook nil
19594 "Hook for functions attaching themselves to `S-left'.
19595 This one runs after all other options except shift-select have been excluded.
19596 See `org-ctrl-c-ctrl-c-hook' for more information.")
19597 (defvar org-shiftright-hook nil
19598 "Hook for functions attaching themselves to `S-right'.
19599 See `org-ctrl-c-ctrl-c-hook' for more information.")
19600 (defvar org-shiftright-final-hook nil
19601 "Hook for functions attaching themselves to `S-right'.
19602 This one runs after all other options except shift-select have been excluded.
19603 See `org-ctrl-c-ctrl-c-hook' for more information.")
19605 (defun org-modifier-cursor-error ()
19606 "Throw an error, a modified cursor command was applied in wrong context."
19607 (user-error "This command is active in special context like tables, headlines or items"))
19609 (defun org-shiftselect-error ()
19610 "Throw an error because Shift-Cursor command was applied in wrong context."
19611 (if (and (boundp 'shift-select-mode) shift-select-mode)
19612 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19613 (user-error "This command works only in special context like headlines or timestamps")))
19615 (defun org-call-for-shift-select (cmd)
19616 (let ((this-command-keys-shift-translated t))
19617 (call-interactively cmd)))
19619 (defun org-shifttab (&optional arg)
19620 "Global visibility cycling or move to previous table field.
19621 Call `org-table-previous-field' within a table.
19622 When ARG is nil, cycle globally through visibility states.
19623 When ARG is a numeric prefix, show contents of this level."
19624 (interactive "P")
19625 (cond
19626 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19627 ((integerp arg)
19628 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19629 (message "Content view to level: %d" arg)
19630 (org-content (prefix-numeric-value arg2))
19631 (org-cycle-show-empty-lines t)
19632 (setq org-cycle-global-status 'overview)))
19633 (t (call-interactively 'org-global-cycle))))
19635 (defun org-shiftmetaleft ()
19636 "Promote subtree or delete table column.
19637 Calls `org-promote-subtree', `org-outdent-item-tree', or
19638 `org-table-delete-column', depending on context. See the
19639 individual commands for more information."
19640 (interactive)
19641 (cond
19642 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19643 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19644 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19645 ((if (not (org-region-active-p)) (org-at-item-p)
19646 (save-excursion (goto-char (region-beginning))
19647 (org-at-item-p)))
19648 (call-interactively 'org-outdent-item-tree))
19649 (t (org-modifier-cursor-error))))
19651 (defun org-shiftmetaright ()
19652 "Demote subtree or insert table column.
19653 Calls `org-demote-subtree', `org-indent-item-tree', or
19654 `org-table-insert-column', depending on context. See the
19655 individual commands for more information."
19656 (interactive)
19657 (cond
19658 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19659 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19660 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19661 ((if (not (org-region-active-p)) (org-at-item-p)
19662 (save-excursion (goto-char (region-beginning))
19663 (org-at-item-p)))
19664 (call-interactively 'org-indent-item-tree))
19665 (t (org-modifier-cursor-error))))
19667 (defun org-shiftmetaup (&optional arg)
19668 "Move subtree up or kill table row.
19669 Calls `org-move-subtree-up' or `org-table-kill-row' or
19670 `org-move-item-up' or `org-timestamp-up', depending on context.
19671 See the individual commands for more information."
19672 (interactive "P")
19673 (cond
19674 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19675 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19676 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19677 ((org-at-item-p) (call-interactively 'org-move-item-up))
19678 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19679 (call-interactively 'org-timestamp-up)))
19680 (t (call-interactively 'org-drag-line-backward))))
19682 (defun org-shiftmetadown (&optional arg)
19683 "Move subtree down or insert table row.
19684 Calls `org-move-subtree-down' or `org-table-insert-row' or
19685 `org-move-item-down' or `org-timestamp-up', depending on context.
19686 See the individual commands for more information."
19687 (interactive "P")
19688 (cond
19689 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19690 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19691 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19692 ((org-at-item-p) (call-interactively 'org-move-item-down))
19693 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19694 (call-interactively 'org-timestamp-down)))
19695 (t (call-interactively 'org-drag-line-forward))))
19697 (defsubst org-hidden-tree-error ()
19698 (user-error
19699 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19701 (defun org-metaleft (&optional arg)
19702 "Promote heading or move table column to left.
19703 Calls `org-do-promote' or `org-table-move-column', depending on context.
19704 With no specific context, calls the Emacs default `backward-word'.
19705 See the individual commands for more information."
19706 (interactive "P")
19707 (cond
19708 ((run-hook-with-args-until-success 'org-metaleft-hook))
19709 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19710 ((org-with-limited-levels
19711 (or (org-at-heading-p)
19712 (and (org-region-active-p)
19713 (save-excursion
19714 (goto-char (region-beginning))
19715 (org-at-heading-p)))))
19716 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19717 (call-interactively 'org-do-promote))
19718 ;; At an inline task.
19719 ((org-at-heading-p)
19720 (call-interactively 'org-inlinetask-promote))
19721 ((or (org-at-item-p)
19722 (and (org-region-active-p)
19723 (save-excursion
19724 (goto-char (region-beginning))
19725 (org-at-item-p))))
19726 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19727 (call-interactively 'org-outdent-item))
19728 (t (call-interactively 'backward-word))))
19730 (defun org-metaright (&optional arg)
19731 "Demote a subtree, a list item or move table column to right.
19732 In front of a drawer or a block keyword, indent it correctly.
19733 With no specific context, calls the Emacs default `forward-word'.
19734 See the individual commands for more information."
19735 (interactive "P")
19736 (cond
19737 ((run-hook-with-args-until-success 'org-metaright-hook))
19738 ((org-at-table-p) (call-interactively 'org-table-move-column))
19739 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19740 ((org-at-block-p) (call-interactively 'org-indent-block))
19741 ((org-with-limited-levels
19742 (or (org-at-heading-p)
19743 (and (org-region-active-p)
19744 (save-excursion
19745 (goto-char (region-beginning))
19746 (org-at-heading-p)))))
19747 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19748 (call-interactively 'org-do-demote))
19749 ;; At an inline task.
19750 ((org-at-heading-p)
19751 (call-interactively 'org-inlinetask-demote))
19752 ((or (org-at-item-p)
19753 (and (org-region-active-p)
19754 (save-excursion
19755 (goto-char (region-beginning))
19756 (org-at-item-p))))
19757 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19758 (call-interactively 'org-indent-item))
19759 (t (call-interactively 'forward-word))))
19761 (defun org-check-for-hidden (what)
19762 "Check if there are hidden headlines/items in the current visual line.
19763 WHAT can be either `headlines' or `items'. If the current line is
19764 an outline or item heading and it has a folded subtree below it,
19765 this function returns t, nil otherwise."
19766 (let ((re (cond
19767 ((eq what 'headlines) org-outline-regexp-bol)
19768 ((eq what 'items) (org-item-beginning-re))
19769 (t (error "This should not happen"))))
19770 beg end)
19771 (save-excursion
19772 (catch 'exit
19773 (unless (org-region-active-p)
19774 (setq beg (point-at-bol))
19775 (beginning-of-line 2)
19776 (while (and (not (eobp)) ;; this is like `next-line'
19777 (get-char-property (1- (point)) 'invisible))
19778 (beginning-of-line 2))
19779 (setq end (point))
19780 (goto-char beg)
19781 (goto-char (point-at-eol))
19782 (setq end (max end (point)))
19783 (while (re-search-forward re end t)
19784 (if (get-char-property (match-beginning 0) 'invisible)
19785 (throw 'exit t))))
19786 nil))))
19788 (defun org-metaup (&optional arg)
19789 "Move subtree up or move table row up.
19790 Calls `org-move-subtree-up' or `org-table-move-row' or
19791 `org-move-item-up', depending on context. See the individual commands
19792 for more information."
19793 (interactive "P")
19794 (cond
19795 ((run-hook-with-args-until-success 'org-metaup-hook))
19796 ((org-region-active-p)
19797 (let* ((a (min (region-beginning) (region-end)))
19798 (b (1- (max (region-beginning) (region-end))))
19799 (c (save-excursion (goto-char a)
19800 (move-beginning-of-line 0)))
19801 (d (save-excursion (goto-char a)
19802 (move-end-of-line 0) (point))))
19803 (transpose-regions a b c d)
19804 (goto-char c)))
19805 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19806 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19807 ((org-at-item-p) (call-interactively 'org-move-item-up))
19808 (t (org-drag-element-backward))))
19810 (defun org-metadown (&optional arg)
19811 "Move subtree down or move table row down.
19812 Calls `org-move-subtree-down' or `org-table-move-row' or
19813 `org-move-item-down', depending on context. See the individual
19814 commands for more information."
19815 (interactive "P")
19816 (cond
19817 ((run-hook-with-args-until-success 'org-metadown-hook))
19818 ((org-region-active-p)
19819 (let* ((a (min (region-beginning) (region-end)))
19820 (b (max (region-beginning) (region-end)))
19821 (c (save-excursion (goto-char b)
19822 (move-beginning-of-line 1)))
19823 (d (save-excursion (goto-char b)
19824 (move-end-of-line 1) (1+ (point)))))
19825 (transpose-regions a b c d)
19826 (goto-char d)))
19827 ((org-at-table-p) (call-interactively 'org-table-move-row))
19828 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19829 ((org-at-item-p) (call-interactively 'org-move-item-down))
19830 (t (org-drag-element-forward))))
19832 (defun org-shiftup (&optional arg)
19833 "Increase item in timestamp or increase priority of current headline.
19834 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19835 depending on context. See the individual commands for more information."
19836 (interactive "P")
19837 (cond
19838 ((run-hook-with-args-until-success 'org-shiftup-hook))
19839 ((and org-support-shift-select (org-region-active-p))
19840 (org-call-for-shift-select 'previous-line))
19841 ((org-at-timestamp-p t)
19842 (call-interactively (if org-edit-timestamp-down-means-later
19843 'org-timestamp-down 'org-timestamp-up)))
19844 ((and (not (eq org-support-shift-select 'always))
19845 org-enable-priority-commands
19846 (org-at-heading-p))
19847 (call-interactively 'org-priority-up))
19848 ((and (not org-support-shift-select) (org-at-item-p))
19849 (call-interactively 'org-previous-item))
19850 ((org-clocktable-try-shift 'up arg))
19851 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19852 (org-support-shift-select
19853 (org-call-for-shift-select 'previous-line))
19854 (t (org-shiftselect-error))))
19856 (defun org-shiftdown (&optional arg)
19857 "Decrease item in timestamp or decrease priority of current headline.
19858 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19859 depending on context. See the individual commands for more information."
19860 (interactive "P")
19861 (cond
19862 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19863 ((and org-support-shift-select (org-region-active-p))
19864 (org-call-for-shift-select 'next-line))
19865 ((org-at-timestamp-p t)
19866 (call-interactively (if org-edit-timestamp-down-means-later
19867 'org-timestamp-up 'org-timestamp-down)))
19868 ((and (not (eq org-support-shift-select 'always))
19869 org-enable-priority-commands
19870 (org-at-heading-p))
19871 (call-interactively 'org-priority-down))
19872 ((and (not org-support-shift-select) (org-at-item-p))
19873 (call-interactively 'org-next-item))
19874 ((org-clocktable-try-shift 'down arg))
19875 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19876 (org-support-shift-select
19877 (org-call-for-shift-select 'next-line))
19878 (t (org-shiftselect-error))))
19880 (defun org-shiftright (&optional arg)
19881 "Cycle the thing at point or in the current line, depending on context.
19882 Depending on context, this does one of the following:
19884 - switch a timestamp at point one day into the future
19885 - on a headline, switch to the next TODO keyword.
19886 - on an item, switch entire list to the next bullet type
19887 - on a property line, switch to the next allowed value
19888 - on a clocktable definition line, move time block into the future"
19889 (interactive "P")
19890 (cond
19891 ((run-hook-with-args-until-success 'org-shiftright-hook))
19892 ((and org-support-shift-select (org-region-active-p))
19893 (org-call-for-shift-select 'forward-char))
19894 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19895 ((and (not (eq org-support-shift-select 'always))
19896 (org-at-heading-p))
19897 (let ((org-inhibit-logging
19898 (not org-treat-S-cursor-todo-selection-as-state-change))
19899 (org-inhibit-blocking
19900 (not org-treat-S-cursor-todo-selection-as-state-change)))
19901 (org-call-with-arg 'org-todo 'right)))
19902 ((or (and org-support-shift-select
19903 (not (eq org-support-shift-select 'always))
19904 (org-at-item-bullet-p))
19905 (and (not org-support-shift-select) (org-at-item-p)))
19906 (org-call-with-arg 'org-cycle-list-bullet nil))
19907 ((and (not (eq org-support-shift-select 'always))
19908 (org-at-property-p))
19909 (call-interactively 'org-property-next-allowed-value))
19910 ((org-clocktable-try-shift 'right arg))
19911 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19912 (org-support-shift-select
19913 (org-call-for-shift-select 'forward-char))
19914 (t (org-shiftselect-error))))
19916 (defun org-shiftleft (&optional arg)
19917 "Cycle the thing at point or in the current line, depending on context.
19918 Depending on context, this does one of the following:
19920 - switch a timestamp at point one day into the past
19921 - on a headline, switch to the previous TODO keyword.
19922 - on an item, switch entire list to the previous bullet type
19923 - on a property line, switch to the previous allowed value
19924 - on a clocktable definition line, move time block into the past"
19925 (interactive "P")
19926 (cond
19927 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19928 ((and org-support-shift-select (org-region-active-p))
19929 (org-call-for-shift-select 'backward-char))
19930 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19931 ((and (not (eq org-support-shift-select 'always))
19932 (org-at-heading-p))
19933 (let ((org-inhibit-logging
19934 (not org-treat-S-cursor-todo-selection-as-state-change))
19935 (org-inhibit-blocking
19936 (not org-treat-S-cursor-todo-selection-as-state-change)))
19937 (org-call-with-arg 'org-todo 'left)))
19938 ((or (and org-support-shift-select
19939 (not (eq org-support-shift-select 'always))
19940 (org-at-item-bullet-p))
19941 (and (not org-support-shift-select) (org-at-item-p)))
19942 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19943 ((and (not (eq org-support-shift-select 'always))
19944 (org-at-property-p))
19945 (call-interactively 'org-property-previous-allowed-value))
19946 ((org-clocktable-try-shift 'left arg))
19947 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19948 (org-support-shift-select
19949 (org-call-for-shift-select 'backward-char))
19950 (t (org-shiftselect-error))))
19952 (defun org-shiftcontrolright ()
19953 "Switch to next TODO set."
19954 (interactive)
19955 (cond
19956 ((and org-support-shift-select (org-region-active-p))
19957 (org-call-for-shift-select 'forward-word))
19958 ((and (not (eq org-support-shift-select 'always))
19959 (org-at-heading-p))
19960 (org-call-with-arg 'org-todo 'nextset))
19961 (org-support-shift-select
19962 (org-call-for-shift-select 'forward-word))
19963 (t (org-shiftselect-error))))
19965 (defun org-shiftcontrolleft ()
19966 "Switch to previous TODO set."
19967 (interactive)
19968 (cond
19969 ((and org-support-shift-select (org-region-active-p))
19970 (org-call-for-shift-select 'backward-word))
19971 ((and (not (eq org-support-shift-select 'always))
19972 (org-at-heading-p))
19973 (org-call-with-arg 'org-todo 'previousset))
19974 (org-support-shift-select
19975 (org-call-for-shift-select 'backward-word))
19976 (t (org-shiftselect-error))))
19978 (defun org-shiftcontrolup (&optional n)
19979 "Change timestamps synchronously up in CLOCK log lines.
19980 Optional argument N tells to change by that many units."
19981 (interactive "P")
19982 (cond ((and (not org-support-shift-select)
19983 (org-at-clock-log-p)
19984 (org-at-timestamp-p t))
19985 (org-clock-timestamps-up n))
19986 (t (org-shiftselect-error))))
19988 (defun org-shiftcontroldown (&optional n)
19989 "Change timestamps synchronously down in CLOCK log lines.
19990 Optional argument N tells to change by that many units."
19991 (interactive "P")
19992 (cond ((and (not org-support-shift-select)
19993 (org-at-clock-log-p)
19994 (org-at-timestamp-p t))
19995 (org-clock-timestamps-down n))
19996 (t (org-shiftselect-error))))
19998 (defun org-ctrl-c-ret ()
19999 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20000 (interactive)
20001 (cond
20002 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20003 (t (call-interactively 'org-insert-heading))))
20005 (defun org-find-visible ()
20006 (let ((s (point)))
20007 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20008 (get-char-property s 'invisible)))
20010 (defun org-find-invisible ()
20011 (let ((s (point)))
20012 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20013 (not (get-char-property s 'invisible))))
20016 (defun org-copy-visible (beg end)
20017 "Copy the visible parts of the region."
20018 (interactive "r")
20019 (let (snippets s)
20020 (save-excursion
20021 (save-restriction
20022 (narrow-to-region beg end)
20023 (setq s (goto-char (point-min)))
20024 (while (not (= (point) (point-max)))
20025 (goto-char (org-find-invisible))
20026 (push (buffer-substring s (point)) snippets)
20027 (setq s (goto-char (org-find-visible))))))
20028 (kill-new (apply 'concat (nreverse snippets)))))
20030 (defun org-copy-special ()
20031 "Copy region in table or copy current subtree.
20032 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20033 See the individual commands for more information."
20034 (interactive)
20035 (call-interactively
20036 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20038 (defun org-cut-special ()
20039 "Cut region in table or cut current subtree.
20040 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20041 See the individual commands for more information."
20042 (interactive)
20043 (call-interactively
20044 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20046 (defun org-paste-special (arg)
20047 "Paste rectangular region into table, or past subtree relative to level.
20048 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20049 See the individual commands for more information."
20050 (interactive "P")
20051 (if (org-at-table-p)
20052 (org-table-paste-rectangle)
20053 (org-paste-subtree arg)))
20055 (defsubst org-in-fixed-width-region-p ()
20056 "Is point in a fixed-width region?"
20057 (save-match-data
20058 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20060 (defun org-edit-special (&optional arg)
20061 "Call a special editor for the element at point.
20062 When at a table, call the formula editor with `org-table-edit-formulas'.
20063 When in a source code block, call `org-edit-src-code'.
20064 When in a fixed-width region, call `org-edit-fixed-width-region'.
20065 When at an #+INCLUDE keyword, visit the included file.
20066 On a link, call `ffap' to visit the link at point.
20067 Otherwise, return a user error."
20068 (interactive "P")
20069 (let ((element (org-element-at-point)))
20070 (assert (not buffer-read-only) nil
20071 "Buffer is read-only: %s" (buffer-name))
20072 (case (org-element-type element)
20073 (src-block
20074 (if (not arg) (org-edit-src-code)
20075 (let* ((info (org-babel-get-src-block-info))
20076 (lang (nth 0 info))
20077 (params (nth 2 info))
20078 (session (cdr (assq :session params))))
20079 (if (not session) (org-edit-src-code)
20080 ;; At a src-block with a session and function called with
20081 ;; an ARG: switch to the buffer related to the inferior
20082 ;; process.
20083 (switch-to-buffer
20084 (funcall (intern (concat "org-babel-prep-session:" lang))
20085 session params))))))
20086 (keyword
20087 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20088 (find-file
20089 (org-remove-double-quotes
20090 (car (org-split-string (org-element-property :value element)))))
20091 (user-error "No special environment to edit here")))
20092 (table
20093 (if (eq (org-element-property :type element) 'table.el)
20094 (org-edit-src-code)
20095 (call-interactively 'org-table-edit-formulas)))
20096 ;; Only Org tables contain `table-row' type elements.
20097 (table-row (call-interactively 'org-table-edit-formulas))
20098 ((example-block export-block) (org-edit-src-code))
20099 (fixed-width (org-edit-fixed-width-region))
20100 (otherwise
20101 ;; No notable element at point. Though, we may be at a link,
20102 ;; which is an object. Thus, scan deeper.
20103 (if (eq (org-element-type (org-element-context element)) 'link)
20104 (call-interactively 'ffap)
20105 (user-error "No special environment to edit here"))))))
20107 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20108 (defun org-ctrl-c-ctrl-c (&optional arg)
20109 "Set tags in headline, or update according to changed information at point.
20111 This command does many different things, depending on context:
20113 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20114 this is what we do.
20116 - If the cursor is on a statistics cookie, update it.
20118 - If the cursor is in a headline, prompt for tags and insert them
20119 into the current line, aligned to `org-tags-column'. When called
20120 with prefix arg, realign all tags in the current buffer.
20122 - If the cursor is in one of the special #+KEYWORD lines, this
20123 triggers scanning the buffer for these lines and updating the
20124 information.
20126 - If the cursor is inside a table, realign the table. This command
20127 works even if the automatic table editor has been turned off.
20129 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20130 the entire table.
20132 - If the cursor is at a footnote reference or definition, jump to
20133 the corresponding definition or references, respectively.
20135 - If the cursor is a the beginning of a dynamic block, update it.
20137 - If the current buffer is a capture buffer, close note and file it.
20139 - If the cursor is on a <<<target>>>, update radio targets and
20140 corresponding links in this buffer.
20142 - If the cursor is on a numbered item in a plain list, renumber the
20143 ordered list.
20145 - If the cursor is on a checkbox, toggle it.
20147 - If the cursor is on a code block, evaluate it. The variable
20148 `org-confirm-babel-evaluate' can be used to control prompting
20149 before code block evaluation, by default every code block
20150 evaluation requires confirmation. Code block evaluation can be
20151 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20152 (interactive "P")
20153 (cond
20154 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20155 org-occur-highlights
20156 org-latex-fragment-image-overlays)
20157 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20158 (org-remove-occur-highlights)
20159 (org-remove-latex-fragment-image-overlays)
20160 (message "Temporary highlights/overlays removed from current buffer"))
20161 ((and (local-variable-p 'org-finish-function (current-buffer))
20162 (fboundp org-finish-function))
20163 (funcall org-finish-function))
20164 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20166 (let* ((context (org-element-context)) (type (org-element-type context)))
20167 ;; Test if point is within a blank line.
20168 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20169 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20170 (user-error "C-c C-c can do nothing useful at this location"))
20171 ;; For convenience: at the first line of a paragraph on the
20172 ;; same line as an item, apply function on that item instead.
20173 (when (eq type 'paragraph)
20174 (let ((parent (org-element-property :parent context)))
20175 (when (and (eq (org-element-type parent) 'item)
20176 (= (point-at-bol) (org-element-property :begin parent)))
20177 (setq context parent type 'item))))
20178 ;; Act according to type of element or object at point.
20179 (case type
20180 (clock (org-clock-update-time-maybe))
20181 (dynamic-block
20182 (save-excursion
20183 (goto-char (org-element-property :post-affiliated context))
20184 (org-update-dblock)))
20185 (footnote-definition
20186 (goto-char (org-element-property :post-affiliated context))
20187 (call-interactively 'org-footnote-action))
20188 (footnote-reference (call-interactively 'org-footnote-action))
20189 ((headline inlinetask)
20190 (save-excursion (goto-char (org-element-property :begin context))
20191 (call-interactively 'org-set-tags)))
20192 (item
20193 ;; At an item: a double C-u set checkbox to "[-]"
20194 ;; unconditionally, whereas a single one will toggle its
20195 ;; presence. Without an universal argument, if the item
20196 ;; has a checkbox, toggle it. Otherwise repair the list.
20197 (let* ((box (org-element-property :checkbox context))
20198 (struct (org-element-property :structure context))
20199 (old-struct (copy-tree struct))
20200 (parents (org-list-parents-alist struct))
20201 (prevs (org-list-prevs-alist struct))
20202 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20203 (org-list-set-checkbox
20204 (org-element-property :begin context) struct
20205 (cond ((equal arg '(16)) "[-]")
20206 ((and (not box) (equal arg '(4))) "[ ]")
20207 ((or (not box) (equal arg '(4))) nil)
20208 ((eq box 'on) "[ ]")
20209 (t "[X]")))
20210 ;; Mimic `org-list-write-struct' but with grabbing
20211 ;; a return value from `org-list-struct-fix-box'.
20212 (org-list-struct-fix-ind struct parents 2)
20213 (org-list-struct-fix-item-end struct)
20214 (org-list-struct-fix-bul struct prevs)
20215 (org-list-struct-fix-ind struct parents)
20216 (let ((block-item
20217 (org-list-struct-fix-box struct parents prevs orderedp)))
20218 (if (and box (equal struct old-struct))
20219 (if (equal arg '(16))
20220 (message "Checkboxes already reset")
20221 (user-error "Cannot toggle this checkbox: %s"
20222 (if (eq box 'on)
20223 "all subitems checked"
20224 "unchecked subitems")))
20225 (org-list-struct-apply-struct struct old-struct)
20226 (org-update-checkbox-count-maybe))
20227 (when block-item
20228 (message "Checkboxes were removed due to empty box at line %d"
20229 (org-current-line block-item))))))
20230 (keyword
20231 (let ((org-inhibit-startup-visibility-stuff t)
20232 (org-startup-align-all-tables nil))
20233 (when (boundp 'org-table-coordinate-overlays)
20234 (mapc 'delete-overlay org-table-coordinate-overlays)
20235 (setq org-table-coordinate-overlays nil))
20236 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20237 (message "Local setup has been refreshed"))
20238 (plain-list
20239 ;; At a plain list, with a double C-u argument, set
20240 ;; checkboxes of each item to "[-]", whereas a single one
20241 ;; will toggle their presence according to the state of the
20242 ;; first item in the list. Without an argument, repair the
20243 ;; list.
20244 (let* ((begin (org-element-property :contents-begin context))
20245 (beginm (move-marker (make-marker) begin))
20246 (struct (org-element-property :structure context))
20247 (old-struct (copy-tree struct))
20248 (first-box (save-excursion
20249 (goto-char begin)
20250 (looking-at org-list-full-item-re)
20251 (match-string-no-properties 3)))
20252 (new-box (cond ((equal arg '(16)) "[-]")
20253 ((equal arg '(4)) (unless first-box "[ ]"))
20254 ((equal first-box "[X]") "[ ]")
20255 (t "[X]"))))
20256 (cond
20257 (arg
20258 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20259 (org-list-get-all-items
20260 begin struct (org-list-prevs-alist struct))))
20261 ((and first-box (eq (point) begin))
20262 ;; For convenience, when point is at bol on the first
20263 ;; item of the list and no argument is provided, simply
20264 ;; toggle checkbox of that item, if any.
20265 (org-list-set-checkbox begin struct new-box)))
20266 (org-list-write-struct
20267 struct (org-list-parents-alist struct) old-struct)
20268 (org-update-checkbox-count-maybe)
20269 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20270 ((property-drawer node-property)
20271 (call-interactively 'org-property-action))
20272 ((radio-target target)
20273 (call-interactively 'org-update-radio-target-regexp))
20274 (statistics-cookie
20275 (call-interactively 'org-update-statistics-cookies))
20276 ((table table-cell table-row)
20277 ;; At a table, recalculate every field and align it. Also
20278 ;; send the table if necessary. If the table has
20279 ;; a `table.el' type, just give up. At a table row or
20280 ;; cell, maybe recalculate line but always align table.
20281 (if (eq (org-element-property :type context) 'table.el)
20282 (message "Use C-c ' to edit table.el tables")
20283 (let ((org-enable-table-editor t))
20284 (if (or (eq type 'table)
20285 ;; Check if point is at a TBLFM line.
20286 (and (eq type 'table-row)
20287 (= (point) (org-element-property :end context))))
20288 (save-excursion
20289 (if (org-at-TBLFM-p)
20290 (progn (require 'org-table)
20291 (org-table-calc-current-TBLFM))
20292 (goto-char (org-element-property :contents-begin context))
20293 (org-call-with-arg 'org-table-recalculate (or arg t))
20294 (orgtbl-send-table 'maybe)))
20295 (org-table-maybe-eval-formula)
20296 (cond (arg (call-interactively 'org-table-recalculate))
20297 ((org-table-maybe-recalculate-line))
20298 (t (org-table-align)))))))
20299 (timestamp (org-timestamp-change 0 'day))
20300 (otherwise
20301 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20302 (user-error
20303 "C-c C-c can do nothing useful at this location")))))))))
20305 (defun org-mode-restart ()
20306 "Restart Org-mode, to scan again for special lines.
20307 Also updates the keyword regular expressions."
20308 (interactive)
20309 (org-mode)
20310 (message "Org-mode restarted"))
20312 (defun org-kill-note-or-show-branches ()
20313 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20314 (interactive)
20315 (if (not org-finish-function)
20316 (progn
20317 (hide-subtree)
20318 (call-interactively 'show-branches))
20319 (let ((org-note-abort t))
20320 (funcall org-finish-function))))
20322 (defun org-open-line (n)
20323 "Insert a new row in tables, call `open-line' elsewhere."
20324 (interactive "*p")
20325 (if (org-at-table-p)
20326 (org-table-insert-row)
20327 (open-line n)))
20329 (defun org-return (&optional indent)
20330 "Goto next table row or insert a newline.
20331 Calls `org-table-next-row' or `newline', depending on context.
20332 See the individual commands for more information."
20333 (interactive)
20334 (let (org-ts-what)
20335 (cond
20336 ((or (bobp) (org-in-src-block-p))
20337 (if indent (newline-and-indent) (newline)))
20338 ((org-at-table-p)
20339 (org-table-justify-field-maybe)
20340 (call-interactively 'org-table-next-row))
20341 ;; when `newline-and-indent' is called within a list, make sure
20342 ;; text moved stays inside the item.
20343 ((and (org-in-item-p) indent)
20344 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20345 (progn
20346 (save-match-data (newline))
20347 (org-indent-line-to (length (match-string 0))))
20348 (let ((ind (org-get-indentation)))
20349 (newline)
20350 (if (org-looking-back org-list-end-re)
20351 (org-indent-line)
20352 (org-indent-line-to ind)))))
20353 ((and org-return-follows-link
20354 (org-at-timestamp-p t)
20355 (not (eq org-ts-what 'after)))
20356 (org-follow-timestamp-link))
20357 ((and org-return-follows-link
20358 (let ((tprop (get-text-property (point) 'face)))
20359 (or (eq tprop 'org-link)
20360 (and (listp tprop) (memq 'org-link tprop)))))
20361 (call-interactively 'org-open-at-point))
20362 ((and (org-at-heading-p)
20363 (looking-at
20364 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20365 (org-show-entry)
20366 (end-of-line 1)
20367 (newline))
20368 (t (if indent (newline-and-indent) (newline))))))
20370 (defun org-return-indent ()
20371 "Goto next table row or insert a newline and indent.
20372 Calls `org-table-next-row' or `newline-and-indent', depending on
20373 context. See the individual commands for more information."
20374 (interactive)
20375 (org-return t))
20377 (defun org-ctrl-c-star ()
20378 "Compute table, or change heading status of lines.
20379 Calls `org-table-recalculate' or `org-toggle-heading',
20380 depending on context."
20381 (interactive)
20382 (cond
20383 ((org-at-table-p)
20384 (call-interactively 'org-table-recalculate))
20386 ;; Convert all lines in region to list items
20387 (call-interactively 'org-toggle-heading))))
20389 (defun org-ctrl-c-minus ()
20390 "Insert separator line in table or modify bullet status of line.
20391 Also turns a plain line or a region of lines into list items.
20392 Calls `org-table-insert-hline', `org-toggle-item', or
20393 `org-cycle-list-bullet', depending on context."
20394 (interactive)
20395 (cond
20396 ((org-at-table-p)
20397 (call-interactively 'org-table-insert-hline))
20398 ((org-region-active-p)
20399 (call-interactively 'org-toggle-item))
20400 ((org-in-item-p)
20401 (call-interactively 'org-cycle-list-bullet))
20403 (call-interactively 'org-toggle-item))))
20405 (defun org-toggle-item (arg)
20406 "Convert headings or normal lines to items, items to normal lines.
20407 If there is no active region, only the current line is considered.
20409 If the first non blank line in the region is a headline, convert
20410 all headlines to items, shifting text accordingly.
20412 If it is an item, convert all items to normal lines.
20414 If it is normal text, change region into a list of items.
20415 With a prefix argument ARG, change the region in a single item."
20416 (interactive "P")
20417 (let ((shift-text
20418 (function
20419 ;; Shift text in current section to IND, from point to END.
20420 ;; The function leaves point to END line.
20421 (lambda (ind end)
20422 (let ((min-i 1000) (end (copy-marker end)))
20423 ;; First determine the minimum indentation (MIN-I) of
20424 ;; the text.
20425 (save-excursion
20426 (catch 'exit
20427 (while (< (point) end)
20428 (let ((i (org-get-indentation)))
20429 (cond
20430 ;; Skip blank lines and inline tasks.
20431 ((looking-at "^[ \t]*$"))
20432 ((looking-at org-outline-regexp-bol))
20433 ;; We can't find less than 0 indentation.
20434 ((zerop i) (throw 'exit (setq min-i 0)))
20435 ((< i min-i) (setq min-i i))))
20436 (forward-line))))
20437 ;; Then indent each line so that a line indented to
20438 ;; MIN-I becomes indented to IND. Ignore blank lines
20439 ;; and inline tasks in the process.
20440 (let ((delta (- ind min-i)))
20441 (while (< (point) end)
20442 (unless (or (looking-at "^[ \t]*$")
20443 (looking-at org-outline-regexp-bol))
20444 (org-indent-line-to (+ (org-get-indentation) delta)))
20445 (forward-line)))))))
20446 (skip-blanks
20447 (function
20448 ;; Return beginning of first non-blank line, starting from
20449 ;; line at POS.
20450 (lambda (pos)
20451 (save-excursion
20452 (goto-char pos)
20453 (skip-chars-forward " \r\t\n")
20454 (point-at-bol)))))
20455 beg end)
20456 ;; Determine boundaries of changes.
20457 (if (org-region-active-p)
20458 (setq beg (funcall skip-blanks (region-beginning))
20459 end (copy-marker (region-end)))
20460 (setq beg (funcall skip-blanks (point-at-bol))
20461 end (copy-marker (point-at-eol))))
20462 ;; Depending on the starting line, choose an action on the text
20463 ;; between BEG and END.
20464 (org-with-limited-levels
20465 (save-excursion
20466 (goto-char beg)
20467 (cond
20468 ;; Case 1. Start at an item: de-itemize. Note that it only
20469 ;; happens when a region is active: `org-ctrl-c-minus'
20470 ;; would call `org-cycle-list-bullet' otherwise.
20471 ((org-at-item-p)
20472 (while (< (point) end)
20473 (when (org-at-item-p)
20474 (skip-chars-forward " \t")
20475 (delete-region (point) (match-end 0)))
20476 (forward-line)))
20477 ;; Case 2. Start at an heading: convert to items.
20478 ((org-at-heading-p)
20479 (let* ((bul (org-list-bullet-string "-"))
20480 (bul-len (length bul))
20481 ;; Indentation of the first heading. It should be
20482 ;; relative to the indentation of its parent, if any.
20483 (start-ind (save-excursion
20484 (cond
20485 ((not org-adapt-indentation) 0)
20486 ((not (outline-previous-heading)) 0)
20487 (t (length (match-string 0))))))
20488 ;; Level of first heading. Further headings will be
20489 ;; compared to it to determine hierarchy in the list.
20490 (ref-level (org-reduced-level (org-outline-level))))
20491 (while (< (point) end)
20492 (let* ((level (org-reduced-level (org-outline-level)))
20493 (delta (max 0 (- level ref-level))))
20494 ;; If current headline is less indented than the first
20495 ;; one, set it as reference, in order to preserve
20496 ;; subtrees.
20497 (when (< level ref-level) (setq ref-level level))
20498 (replace-match bul t t)
20499 (org-indent-line-to (+ start-ind (* delta bul-len)))
20500 ;; Ensure all text down to END (or SECTION-END) belongs
20501 ;; to the newly created item.
20502 (let ((section-end (save-excursion
20503 (or (outline-next-heading) (point)))))
20504 (forward-line)
20505 (funcall shift-text
20506 (+ start-ind (* (1+ delta) bul-len))
20507 (min end section-end)))))))
20508 ;; Case 3. Normal line with ARG: make the first line of region
20509 ;; an item, and shift indentation of others lines to
20510 ;; set them as item's body.
20511 (arg (let* ((bul (org-list-bullet-string "-"))
20512 (bul-len (length bul))
20513 (ref-ind (org-get-indentation)))
20514 (skip-chars-forward " \t")
20515 (insert bul)
20516 (forward-line)
20517 (while (< (point) end)
20518 ;; Ensure that lines less indented than first one
20519 ;; still get included in item body.
20520 (funcall shift-text
20521 (+ ref-ind bul-len)
20522 (min end (save-excursion (or (outline-next-heading)
20523 (point)))))
20524 (forward-line))))
20525 ;; Case 4. Normal line without ARG: turn each non-item line
20526 ;; into an item.
20528 (while (< (point) end)
20529 (unless (or (org-at-heading-p) (org-at-item-p))
20530 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20531 (replace-match
20532 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20533 (forward-line))))))))
20535 (defun org-toggle-heading (&optional nstars)
20536 "Convert headings to normal text, or items or text to headings.
20537 If there is no active region, only convert the current line.
20539 With a \\[universal-argument] prefix, convert the whole list at
20540 point into heading.
20542 In a region:
20544 - If the first non blank line is a headline, remove the stars
20545 from all headlines in the region.
20547 - If it is a normal line, turn each and every normal line (i.e.,
20548 not an heading or an item) in the region into headings. If you
20549 want to convert only the first line of this region, use one
20550 universal prefix argument.
20552 - If it is a plain list item, turn all plain list items into headings.
20554 When converting a line into a heading, the number of stars is chosen
20555 such that the lines become children of the current entry. However,
20556 when a numeric prefix argument is given, its value determines the
20557 number of stars to add."
20558 (interactive "P")
20559 (let ((skip-blanks
20560 (function
20561 ;; Return beginning of first non-blank line, starting from
20562 ;; line at POS.
20563 (lambda (pos)
20564 (save-excursion
20565 (goto-char pos)
20566 (while (org-at-comment-p) (forward-line))
20567 (skip-chars-forward " \r\t\n")
20568 (point-at-bol)))))
20569 beg end toggled)
20570 ;; Determine boundaries of changes. If a universal prefix has
20571 ;; been given, put the list in a region. If region ends at a bol,
20572 ;; do not consider the last line to be in the region.
20574 (when (and current-prefix-arg (org-at-item-p))
20575 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20576 (org-mark-element))
20578 (if (org-region-active-p)
20579 (setq beg (funcall skip-blanks (region-beginning))
20580 end (copy-marker (save-excursion
20581 (goto-char (region-end))
20582 (if (bolp) (point) (point-at-eol)))))
20583 (setq beg (funcall skip-blanks (point-at-bol))
20584 end (copy-marker (point-at-eol))))
20585 ;; Ensure inline tasks don't count as headings.
20586 (org-with-limited-levels
20587 (save-excursion
20588 (goto-char beg)
20589 (cond
20590 ;; Case 1. Started at an heading: de-star headings.
20591 ((org-at-heading-p)
20592 (while (< (point) end)
20593 (when (org-at-heading-p t)
20594 (looking-at org-outline-regexp) (replace-match "")
20595 (setq toggled t))
20596 (forward-line)))
20597 ;; Case 2. Started at an item: change items into headlines.
20598 ;; One star will be added by `org-list-to-subtree'.
20599 ((org-at-item-p)
20600 (let* ((stars (make-string
20601 ;; subtract the star that will be added again by
20602 ;; `org-list-to-subtree'
20603 (if (numberp nstars) (1- nstars)
20604 (or (org-current-level) 0))
20605 ?*))
20606 (add-stars
20607 (cond (nstars "") ; stars from prefix only
20608 ((equal stars "") "") ; before first heading
20609 (org-odd-levels-only "*") ; inside heading, odd
20610 (t "")))) ; inside heading, oddeven
20611 (while (< (point) end)
20612 (when (org-at-item-p)
20613 ;; Pay attention to cases when region ends before list.
20614 (let* ((struct (org-list-struct))
20615 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20616 (save-restriction
20617 (narrow-to-region (point) list-end)
20618 (insert
20619 (org-list-to-subtree
20620 (org-list-parse-list t)
20621 '(:istart (concat stars add-stars (funcall get-stars depth))
20622 :icount (concat stars add-stars (funcall get-stars depth)))))))
20623 (setq toggled t))
20624 (forward-line))))
20625 ;; Case 3. Started at normal text: make every line an heading,
20626 ;; skipping headlines and items.
20627 (t (let* ((stars
20628 (make-string
20629 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20630 (add-stars
20631 (cond (nstars "") ; stars from prefix only
20632 ((equal stars "") "*") ; before first heading
20633 (org-odd-levels-only "**") ; inside heading, odd
20634 (t "*"))) ; inside heading, oddeven
20635 (rpl (concat stars add-stars " "))
20636 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20637 (while (< (point) (if (equal nstars '(4)) lend end))
20638 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20639 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20640 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20641 (forward-line)))))))
20642 (unless toggled (message "Cannot toggle heading from here"))))
20644 (defun org-meta-return (&optional arg)
20645 "Insert a new heading or wrap a region in a table.
20646 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20647 See the individual commands for more information."
20648 (interactive "P")
20649 (org-check-before-invisible-edit 'insert)
20650 (cond
20651 ((run-hook-with-args-until-success 'org-metareturn-hook))
20652 ((or (org-at-drawer-p) (org-in-drawer-p) (org-at-property-p))
20653 (newline-and-indent))
20654 ((org-at-table-p)
20655 (call-interactively 'org-table-wrap-region))
20656 (t (call-interactively 'org-insert-heading))))
20658 ;;; Menu entries
20660 (defsubst org-in-subtree-not-table-p ()
20661 "Are we in a subtree and not in a table?"
20662 (and (not (org-before-first-heading-p))
20663 (not (org-at-table-p))))
20665 ;; Define the Org-mode menus
20666 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20667 '("Tbl"
20668 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20669 ["Next Field" org-cycle (org-at-table-p)]
20670 ["Previous Field" org-shifttab (org-at-table-p)]
20671 ["Next Row" org-return (org-at-table-p)]
20672 "--"
20673 ["Blank Field" org-table-blank-field (org-at-table-p)]
20674 ["Edit Field" org-table-edit-field (org-at-table-p)]
20675 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20676 "--"
20677 ("Column"
20678 ["Move Column Left" org-metaleft (org-at-table-p)]
20679 ["Move Column Right" org-metaright (org-at-table-p)]
20680 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20681 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20682 ("Row"
20683 ["Move Row Up" org-metaup (org-at-table-p)]
20684 ["Move Row Down" org-metadown (org-at-table-p)]
20685 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20686 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20687 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20688 "--"
20689 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20690 ("Rectangle"
20691 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20692 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20693 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20694 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20695 "--"
20696 ("Calculate"
20697 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20698 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20699 ["Edit Formulas" org-edit-special (org-at-table-p)]
20700 "--"
20701 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20702 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20703 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20704 "--"
20705 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20706 "--"
20707 ["Sum Column/Rectangle" org-table-sum
20708 (or (org-at-table-p) (org-region-active-p))]
20709 ["Which Column?" org-table-current-column (org-at-table-p)])
20710 ["Debug Formulas"
20711 org-table-toggle-formula-debugger
20712 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20713 ["Show Col/Row Numbers"
20714 org-table-toggle-coordinate-overlays
20715 :style toggle
20716 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20717 "--"
20718 ["Create" org-table-create (and (not (org-at-table-p))
20719 org-enable-table-editor)]
20720 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20721 ["Import from File" org-table-import (not (org-at-table-p))]
20722 ["Export to File" org-table-export (org-at-table-p)]
20723 "--"
20724 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20726 (easy-menu-define org-org-menu org-mode-map "Org menu"
20727 '("Org"
20728 ("Show/Hide"
20729 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20730 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20731 ["Sparse Tree..." org-sparse-tree t]
20732 ["Reveal Context" org-reveal t]
20733 ["Show All" show-all t]
20734 "--"
20735 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20736 "--"
20737 ["New Heading" org-insert-heading t]
20738 ("Navigate Headings"
20739 ["Up" outline-up-heading t]
20740 ["Next" outline-next-visible-heading t]
20741 ["Previous" outline-previous-visible-heading t]
20742 ["Next Same Level" outline-forward-same-level t]
20743 ["Previous Same Level" outline-backward-same-level t]
20744 "--"
20745 ["Jump" org-goto t])
20746 ("Edit Structure"
20747 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20748 "--"
20749 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20750 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20751 "--"
20752 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20753 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20754 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20755 "--"
20756 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20757 "--"
20758 ["Copy visible text" org-copy-visible t]
20759 "--"
20760 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20761 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20762 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20763 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20764 "--"
20765 ["Sort Region/Children" org-sort t]
20766 "--"
20767 ["Convert to odd levels" org-convert-to-odd-levels t]
20768 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20769 ("Editing"
20770 ["Emphasis..." org-emphasize t]
20771 ["Edit Source Example" org-edit-special t]
20772 "--"
20773 ["Footnote new/jump" org-footnote-action t]
20774 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20775 ("Archive"
20776 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20777 "--"
20778 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20779 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20780 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20782 "--"
20783 ("Hyperlinks"
20784 ["Store Link (Global)" org-store-link t]
20785 ["Find existing link to here" org-occur-link-in-agenda-files t]
20786 ["Insert Link" org-insert-link t]
20787 ["Follow Link" org-open-at-point t]
20788 "--"
20789 ["Next link" org-next-link t]
20790 ["Previous link" org-previous-link t]
20791 "--"
20792 ["Descriptive Links"
20793 org-toggle-link-display
20794 :style radio
20795 :selected org-descriptive-links
20797 ["Literal Links"
20798 org-toggle-link-display
20799 :style radio
20800 :selected (not org-descriptive-links)])
20801 "--"
20802 ("TODO Lists"
20803 ["TODO/DONE/-" org-todo t]
20804 ("Select keyword"
20805 ["Next keyword" org-shiftright (org-at-heading-p)]
20806 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20807 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20808 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20809 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20810 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20811 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20812 "--"
20813 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20814 :selected org-enforce-todo-dependencies :style toggle :active t]
20815 "Settings for tree at point"
20816 ["Do Children sequentially" org-toggle-ordered-property :style radio
20817 :selected (org-entry-get nil "ORDERED")
20818 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20819 ["Do Children parallel" org-toggle-ordered-property :style radio
20820 :selected (not (org-entry-get nil "ORDERED"))
20821 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20822 "--"
20823 ["Set Priority" org-priority t]
20824 ["Priority Up" org-shiftup t]
20825 ["Priority Down" org-shiftdown t]
20826 "--"
20827 ["Get news from all feeds" org-feed-update-all t]
20828 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20829 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20830 ("TAGS and Properties"
20831 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20832 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20833 "--"
20834 ["Set property" org-set-property (not (org-before-first-heading-p))]
20835 ["Column view of properties" org-columns t]
20836 ["Insert Column View DBlock" org-insert-columns-dblock t])
20837 ("Dates and Scheduling"
20838 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20839 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20840 ("Change Date"
20841 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20842 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20843 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20844 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20845 ["Compute Time Range" org-evaluate-time-range t]
20846 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20847 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20848 "--"
20849 ["Custom time format" org-toggle-time-stamp-overlays
20850 :style radio :selected org-display-custom-times]
20851 "--"
20852 ["Goto Calendar" org-goto-calendar t]
20853 ["Date from Calendar" org-date-from-calendar t]
20854 "--"
20855 ["Start/Restart Timer" org-timer-start t]
20856 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20857 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20858 ["Insert Timer String" org-timer t]
20859 ["Insert Timer Item" org-timer-item t])
20860 ("Logging work"
20861 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20862 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20863 ["Clock out" org-clock-out t]
20864 ["Clock cancel" org-clock-cancel t]
20865 "--"
20866 ["Mark as default task" org-clock-mark-default-task t]
20867 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20868 ["Goto running clock" org-clock-goto t]
20869 "--"
20870 ["Display times" org-clock-display t]
20871 ["Create clock table" org-clock-report t]
20872 "--"
20873 ["Record DONE time"
20874 (progn (setq org-log-done (not org-log-done))
20875 (message "Switching to %s will %s record a timestamp"
20876 (car org-done-keywords)
20877 (if org-log-done "automatically" "not")))
20878 :style toggle :selected org-log-done])
20879 "--"
20880 ["Agenda Command..." org-agenda t]
20881 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20882 ("File List for Agenda")
20883 ("Special views current file"
20884 ["TODO Tree" org-show-todo-tree t]
20885 ["Check Deadlines" org-check-deadlines t]
20886 ["Timeline" org-timeline t]
20887 ["Tags/Property tree" org-match-sparse-tree t])
20888 "--"
20889 ["Export/Publish..." org-export-dispatch t]
20890 ("LaTeX"
20891 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20892 :selected org-cdlatex-mode]
20893 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20894 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20895 ["Modify math symbol" org-cdlatex-math-modify
20896 (org-inside-LaTeX-fragment-p)]
20897 ["Insert citation" org-reftex-citation t]
20898 "--"
20899 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20900 "--"
20901 ("MobileOrg"
20902 ["Push Files and Views" org-mobile-push t]
20903 ["Get Captured and Flagged" org-mobile-pull t]
20904 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20905 "--"
20906 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20907 "--"
20908 ("Documentation"
20909 ["Show Version" org-version t]
20910 ["Info Documentation" org-info t])
20911 ("Customize"
20912 ["Browse Org Group" org-customize t]
20913 "--"
20914 ["Expand This Menu" org-create-customize-menu
20915 (fboundp 'customize-menu-create)])
20916 ["Send bug report" org-submit-bug-report t]
20917 "--"
20918 ("Refresh/Reload"
20919 ["Refresh setup current buffer" org-mode-restart t]
20920 ["Reload Org (after update)" org-reload t]
20921 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20924 (defun org-info (&optional node)
20925 "Read documentation for Org-mode in the info system.
20926 With optional NODE, go directly to that node."
20927 (interactive)
20928 (info (format "(org)%s" (or node ""))))
20930 ;;;###autoload
20931 (defun org-submit-bug-report ()
20932 "Submit a bug report on Org-mode via mail.
20934 Don't hesitate to report any problems or inaccurate documentation.
20936 If you don't have setup sending mail from (X)Emacs, please copy the
20937 output buffer into your mail program, as it gives us important
20938 information about your Org-mode version and configuration."
20939 (interactive)
20940 (require 'reporter)
20941 (org-load-modules-maybe)
20942 (org-require-autoloaded-modules)
20943 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20944 (reporter-submit-bug-report
20945 "emacs-orgmode@gnu.org"
20946 (org-version nil 'full)
20947 (let (list)
20948 (save-window-excursion
20949 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20950 (delete-other-windows)
20951 (erase-buffer)
20952 (insert "You are about to submit a bug report to the Org-mode mailing list.
20954 We would like to add your full Org-mode and Outline configuration to the
20955 bug report. This greatly simplifies the work of the maintainer and
20956 other experts on the mailing list.
20958 HOWEVER, some variables you have customized may contain private
20959 information. The names of customers, colleagues, or friends, might
20960 appear in the form of file names, tags, todo states, or search strings.
20961 If you answer yes to the prompt, you might want to check and remove
20962 such private information before sending the email.")
20963 (add-text-properties (point-min) (point-max) '(face org-warning))
20964 (when (yes-or-no-p "Include your Org-mode configuration ")
20965 (mapatoms
20966 (lambda (v)
20967 (and (boundp v)
20968 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20969 (or (and (symbol-value v)
20970 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20971 (and
20972 (get v 'custom-type) (get v 'standard-value)
20973 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20974 (push v list)))))
20975 (kill-buffer (get-buffer "*Warn about privacy*"))
20976 list))
20977 nil nil
20978 "Remember to cover the basics, that is, what you expected to happen and
20979 what in fact did happen. You don't know how to make a good report? See
20981 http://orgmode.org/manual/Feedback.html#Feedback
20983 Your bug report will be posted to the Org-mode mailing list.
20984 ------------------------------------------------------------------------")
20985 (save-excursion
20986 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20987 (replace-match "\\1Bug: \\3 [\\2]")))))
20990 (defun org-install-agenda-files-menu ()
20991 (let ((bl (buffer-list)))
20992 (save-excursion
20993 (while bl
20994 (set-buffer (pop bl))
20995 (if (derived-mode-p 'org-mode) (setq bl nil)))
20996 (when (derived-mode-p 'org-mode)
20997 (easy-menu-change
20998 '("Org") "File List for Agenda"
20999 (append
21000 (list
21001 ["Edit File List" (org-edit-agenda-file-list) t]
21002 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21003 ["Remove Current File from List" org-remove-file t]
21004 ["Cycle through agenda files" org-cycle-agenda-files t]
21005 ["Occur in all agenda files" org-occur-in-agenda-files t]
21006 "--")
21007 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21009 ;;;; Documentation
21011 (defun org-require-autoloaded-modules ()
21012 (interactive)
21013 (mapc 'require
21014 '(org-agenda org-archive org-attach org-clock org-colview org-id
21015 org-remember org-table org-timer)))
21017 ;;;###autoload
21018 (defun org-reload (&optional uncompiled)
21019 "Reload all org lisp files.
21020 With prefix arg UNCOMPILED, load the uncompiled versions."
21021 (interactive "P")
21022 (require 'loadhist)
21023 (let* ((org-dir (org-find-library-dir "org"))
21024 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21025 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21026 (remove-re (mapconcat 'identity
21027 (mapcar (lambda (f) (concat "^" f "$"))
21028 (list (if (featurep 'xemacs)
21029 "org-colview"
21030 "org-colview-xemacs")
21031 "org" "org-loaddefs" "org-version"))
21032 "\\|"))
21033 (feats (delete-dups
21034 (mapcar 'file-name-sans-extension
21035 (mapcar 'file-name-nondirectory
21036 (delq nil
21037 (mapcar 'feature-file
21038 features))))))
21039 (lfeat (append
21040 (sort
21041 (setq feats
21042 (delq nil (mapcar
21043 (lambda (f)
21044 (if (and (string-match feature-re f)
21045 (not (string-match remove-re f)))
21046 f nil))
21047 feats)))
21048 'string-lessp)
21049 (list "org-version" "org")))
21050 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21051 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21052 load-uncore load-misses)
21053 (setq load-misses
21054 (delq 't
21055 (mapcar (lambda (f)
21056 (or (org-load-noerror-mustsuffix (concat org-dir f))
21057 (and (string= org-dir contrib-dir)
21058 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21059 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21060 (add-to-list 'load-uncore f 'append)
21063 lfeat)))
21064 (if load-uncore
21065 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21066 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21067 (if load-misses
21068 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21069 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21070 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21072 ;;;###autoload
21073 (defun org-customize ()
21074 "Call the customize function with org as argument."
21075 (interactive)
21076 (org-load-modules-maybe)
21077 (org-require-autoloaded-modules)
21078 (customize-browse 'org))
21080 (defun org-create-customize-menu ()
21081 "Create a full customization menu for Org-mode, insert it into the menu."
21082 (interactive)
21083 (org-load-modules-maybe)
21084 (org-require-autoloaded-modules)
21085 (if (fboundp 'customize-menu-create)
21086 (progn
21087 (easy-menu-change
21088 '("Org") "Customize"
21089 `(["Browse Org group" org-customize t]
21090 "--"
21091 ,(customize-menu-create 'org)
21092 ["Set" Custom-set t]
21093 ["Save" Custom-save t]
21094 ["Reset to Current" Custom-reset-current t]
21095 ["Reset to Saved" Custom-reset-saved t]
21096 ["Reset to Standard Settings" Custom-reset-standard t]))
21097 (message "\"Org\"-menu now contains full customization menu"))
21098 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21100 ;;;; Miscellaneous stuff
21102 ;;; Generally useful functions
21104 (defun org-get-at-bol (property)
21105 "Get text property PROPERTY at beginning of line."
21106 (get-text-property (point-at-bol) property))
21108 (defun org-find-text-property-in-string (prop s)
21109 "Return the first non-nil value of property PROP in string S."
21110 (or (get-text-property 0 prop s)
21111 (get-text-property (or (next-single-property-change 0 prop s) 0)
21112 prop s)))
21114 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21115 "Display the given MESSAGE as a warning."
21116 (if (fboundp 'display-warning)
21117 (display-warning 'org message
21118 (if (featurep 'xemacs) 'warning :warning))
21119 (let ((buf (get-buffer-create "*Org warnings*")))
21120 (with-current-buffer buf
21121 (goto-char (point-max))
21122 (insert "Warning (Org): " message)
21123 (unless (bolp)
21124 (newline)))
21125 (display-buffer buf)
21126 (sit-for 0))))
21128 (defun org-eval (form)
21129 "Eval FORM and return result."
21130 (condition-case error
21131 (eval form)
21132 (error (format "%%![Error: %s]" error))))
21134 (defun org-in-clocktable-p ()
21135 "Check if the cursor is in a clocktable."
21136 (let ((pos (point)) start)
21137 (save-excursion
21138 (end-of-line 1)
21139 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21140 (setq start (match-beginning 0))
21141 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21142 (>= (match-end 0) pos)
21143 start))))
21145 (defun org-in-commented-line ()
21146 "Is point in a line starting with `#'?"
21147 (equal (char-after (point-at-bol)) ?#))
21149 (defun org-in-indented-comment-line ()
21150 "Is point in a line starting with `#' after some white space?"
21151 (save-excursion
21152 (save-match-data
21153 (goto-char (point-at-bol))
21154 (looking-at "[ \t]*#"))))
21156 (defun org-in-verbatim-emphasis ()
21157 (save-match-data
21158 (and (org-in-regexp org-emph-re 2)
21159 (>= (point) (match-beginning 3))
21160 (<= (point) (match-end 4))
21161 (member (match-string 3) '("=" "~")))))
21163 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21164 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21165 (if (and marker (marker-buffer marker)
21166 (buffer-live-p (marker-buffer marker)))
21167 (progn
21168 (org-pop-to-buffer-same-window (marker-buffer marker))
21169 (if (or (> marker (point-max)) (< marker (point-min)))
21170 (widen))
21171 (goto-char marker)
21172 (org-show-context 'org-goto))
21173 (if bookmark
21174 (bookmark-jump bookmark)
21175 (error "Cannot find location"))))
21177 (defun org-quote-csv-field (s)
21178 "Quote field for inclusion in CSV material."
21179 (if (string-match "[\",]" s)
21180 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21183 (defun org-force-self-insert (N)
21184 "Needed to enforce self-insert under remapping."
21185 (interactive "p")
21186 (self-insert-command N))
21188 (defun org-string-width (s)
21189 "Compute width of string, ignoring invisible characters.
21190 This ignores character with invisibility property `org-link', and also
21191 characters with property `org-cwidth', because these will become invisible
21192 upon the next fontification round."
21193 (let (b l)
21194 (when (or (eq t buffer-invisibility-spec)
21195 (assq 'org-link buffer-invisibility-spec))
21196 (while (setq b (text-property-any 0 (length s)
21197 'invisible 'org-link s))
21198 (setq s (concat (substring s 0 b)
21199 (substring s (or (next-single-property-change
21200 b 'invisible s) (length s)))))))
21201 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21202 (setq s (concat (substring s 0 b)
21203 (substring s (or (next-single-property-change
21204 b 'org-cwidth s) (length s))))))
21205 (setq l (string-width s) b -1)
21206 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21207 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21210 (defun org-shorten-string (s maxlength)
21211 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21212 If the string is shorter or has length MAXLENGTH, just return the
21213 original string. If it is longer, the functions finds a space in the
21214 string, breaks this string off at that locations and adds three dots
21215 as ellipsis. Including the ellipsis, the string will not be longer
21216 than MAXLENGTH. If finding a good breaking point in the string does
21217 not work, the string is just chopped off in the middle of a word
21218 if necessary."
21219 (if (<= (length s) maxlength)
21221 (let* ((n (max (- maxlength 4) 1))
21222 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21223 (if (string-match re s)
21224 (concat (match-string 1 s) "...")
21225 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21227 (defun org-get-indentation (&optional line)
21228 "Get the indentation of the current line, interpreting tabs.
21229 When LINE is given, assume it represents a line and compute its indentation."
21230 (if line
21231 (if (string-match "^ *" (org-remove-tabs line))
21232 (match-end 0))
21233 (save-excursion
21234 (beginning-of-line 1)
21235 (skip-chars-forward " \t")
21236 (current-column))))
21238 (defun org-get-string-indentation (s)
21239 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21240 (let ((n -1) (i 0) (w tab-width) c)
21241 (catch 'exit
21242 (while (< (setq n (1+ n)) (length s))
21243 (setq c (aref s n))
21244 (cond ((= c ?\ ) (setq i (1+ i)))
21245 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21246 (t (throw 'exit t)))))
21249 (defun org-remove-tabs (s &optional width)
21250 "Replace tabulators in S with spaces.
21251 Assumes that s is a single line, starting in column 0."
21252 (setq width (or width tab-width))
21253 (while (string-match "\t" s)
21254 (setq s (replace-match
21255 (make-string
21256 (- (* width (/ (+ (match-beginning 0) width) width))
21257 (match-beginning 0)) ?\ )
21258 t t s)))
21261 (defun org-fix-indentation (line ind)
21262 "Fix indentation in LINE.
21263 IND is a cons cell with target and minimum indentation.
21264 If the current indentation in LINE is smaller than the minimum,
21265 leave it alone. If it is larger than ind, set it to the target."
21266 (let* ((l (org-remove-tabs line))
21267 (i (org-get-indentation l))
21268 (i1 (car ind)) (i2 (cdr ind)))
21269 (if (>= i i2) (setq l (substring line i2)))
21270 (if (> i1 0)
21271 (concat (make-string i1 ?\ ) l)
21272 l)))
21274 (defun org-remove-indentation (code &optional n)
21275 "Remove the maximum common indentation from the lines in CODE.
21276 N may optionally be the number of spaces to remove."
21277 (with-temp-buffer
21278 (insert code)
21279 (org-do-remove-indentation n)
21280 (buffer-string)))
21282 (defun org-do-remove-indentation (&optional n)
21283 "Remove the maximum common indentation from the buffer."
21284 (untabify (point-min) (point-max))
21285 (let ((min 10000) re)
21286 (if n
21287 (setq min n)
21288 (goto-char (point-min))
21289 (while (re-search-forward "^ *[^ \n]" nil t)
21290 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21291 (unless (or (= min 0) (= min 10000))
21292 (setq re (format "^ \\{%d\\}" min))
21293 (goto-char (point-min))
21294 (while (re-search-forward re nil t)
21295 (replace-match "")
21296 (end-of-line 1))
21297 min)))
21299 (defun org-fill-template (template alist)
21300 "Find each %key of ALIST in TEMPLATE and replace it."
21301 (let ((case-fold-search nil)
21302 entry key value)
21303 (setq alist (sort (copy-sequence alist)
21304 (lambda (a b) (< (length (car a)) (length (car b))))))
21305 (while (setq entry (pop alist))
21306 (setq template
21307 (replace-regexp-in-string
21308 (concat "%" (regexp-quote (car entry)))
21309 (or (cdr entry) "") template t t)))
21310 template))
21312 (defun org-base-buffer (buffer)
21313 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21314 (if (not buffer)
21315 buffer
21316 (or (buffer-base-buffer buffer)
21317 buffer)))
21319 (defun org-trim (s)
21320 "Remove whitespace at beginning and end of string."
21321 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21322 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21325 (defun org-wrap (string &optional width lines)
21326 "Wrap string to either a number of lines, or a width in characters.
21327 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21328 that costs. If there is a word longer than WIDTH, the text is actually
21329 wrapped to the length of that word.
21330 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21331 many lines, whatever width that takes.
21332 The return value is a list of lines, without newlines at the end."
21333 (let* ((words (org-split-string string "[ \t\n]+"))
21334 (maxword (apply 'max (mapcar 'org-string-width words)))
21335 w ll)
21336 (cond (width
21337 (org-do-wrap words (max maxword width)))
21338 (lines
21339 (setq w maxword)
21340 (setq ll (org-do-wrap words maxword))
21341 (if (<= (length ll) lines)
21343 (setq ll words)
21344 (while (> (length ll) lines)
21345 (setq w (1+ w))
21346 (setq ll (org-do-wrap words w)))
21347 ll))
21348 (t (error "Cannot wrap this")))))
21350 (defun org-do-wrap (words width)
21351 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21352 (let (lines line)
21353 (while words
21354 (setq line (pop words))
21355 (while (and words (< (+ (length line) (length (car words))) width))
21356 (setq line (concat line " " (pop words))))
21357 (setq lines (push line lines)))
21358 (nreverse lines)))
21360 (defun org-split-string (string &optional separators)
21361 "Splits STRING into substrings at SEPARATORS.
21362 No empty strings are returned if there are matches at the beginning
21363 and end of string."
21364 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21365 (start 0)
21366 notfirst
21367 (list nil))
21368 (while (and (string-match rexp string
21369 (if (and notfirst
21370 (= start (match-beginning 0))
21371 (< start (length string)))
21372 (1+ start) start))
21373 (< (match-beginning 0) (length string)))
21374 (setq notfirst t)
21375 (or (eq (match-beginning 0) 0)
21376 (and (eq (match-beginning 0) (match-end 0))
21377 (eq (match-beginning 0) start))
21378 (setq list
21379 (cons (substring string start (match-beginning 0))
21380 list)))
21381 (setq start (match-end 0)))
21382 (or (eq start (length string))
21383 (setq list
21384 (cons (substring string start)
21385 list)))
21386 (nreverse list)))
21388 (defun org-quote-vert (s)
21389 "Replace \"|\" with \"\\vert\"."
21390 (while (string-match "|" s)
21391 (setq s (replace-match "\\vert" t t s)))
21394 (defun org-uuidgen-p (s)
21395 "Is S an ID created by UUIDGEN?"
21396 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21398 (defun org-in-src-block-p (&optional inside)
21399 "Whether point is in a code source block.
21400 When INSIDE is non-nil, don't consider we are within a src block
21401 when point is at #+BEGIN_SRC or #+END_SRC."
21402 (let ((case-fold-search t) ov)
21403 (or (and (setq ov (overlays-at (point)))
21404 (memq 'org-block-background
21405 (overlay-properties (car ov))))
21406 (and (not inside)
21407 (save-match-data
21408 (save-excursion
21409 (beginning-of-line)
21410 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21412 (defun org-context ()
21413 "Return a list of contexts of the current cursor position.
21414 If several contexts apply, all are returned.
21415 Each context entry is a list with a symbol naming the context, and
21416 two positions indicating start and end of the context. Possible
21417 contexts are:
21419 :headline anywhere in a headline
21420 :headline-stars on the leading stars in a headline
21421 :todo-keyword on a TODO keyword (including DONE) in a headline
21422 :tags on the TAGS in a headline
21423 :priority on the priority cookie in a headline
21424 :item on the first line of a plain list item
21425 :item-bullet on the bullet/number of a plain list item
21426 :checkbox on the checkbox in a plain list item
21427 :table in an org-mode table
21428 :table-special on a special filed in a table
21429 :table-table in a table.el table
21430 :clocktable in a clocktable
21431 :src-block in a source block
21432 :link on a hyperlink
21433 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21434 :target on a <<target>>
21435 :radio-target on a <<<radio-target>>>
21436 :latex-fragment on a LaTeX fragment
21437 :latex-preview on a LaTeX fragment with overlaid preview image
21439 This function expects the position to be visible because it uses font-lock
21440 faces as a help to recognize the following contexts: :table-special, :link,
21441 and :keyword."
21442 (let* ((f (get-text-property (point) 'face))
21443 (faces (if (listp f) f (list f)))
21444 (case-fold-search t)
21445 (p (point)) clist o)
21446 ;; First the large context
21447 (cond
21448 ((org-at-heading-p t)
21449 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21450 (when (progn
21451 (beginning-of-line 1)
21452 (looking-at org-todo-line-tags-regexp))
21453 (push (org-point-in-group p 1 :headline-stars) clist)
21454 (push (org-point-in-group p 2 :todo-keyword) clist)
21455 (push (org-point-in-group p 4 :tags) clist))
21456 (goto-char p)
21457 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21458 (if (looking-at "\\[#[A-Z0-9]\\]")
21459 (push (org-point-in-group p 0 :priority) clist)))
21461 ((org-at-item-p)
21462 (push (org-point-in-group p 2 :item-bullet) clist)
21463 (push (list :item (point-at-bol)
21464 (save-excursion (org-end-of-item) (point)))
21465 clist)
21466 (and (org-at-item-checkbox-p)
21467 (push (org-point-in-group p 0 :checkbox) clist)))
21469 ((org-at-table-p)
21470 (push (list :table (org-table-begin) (org-table-end)) clist)
21471 (if (memq 'org-formula faces)
21472 (push (list :table-special
21473 (previous-single-property-change p 'face)
21474 (next-single-property-change p 'face)) clist)))
21475 ((org-at-table-p 'any)
21476 (push (list :table-table) clist)))
21477 (goto-char p)
21479 (let ((case-fold-search t))
21480 ;; New the "medium" contexts: clocktables, source blocks
21481 (cond ((org-in-clocktable-p)
21482 (push (list :clocktable
21483 (and (or (looking-at "#\\+BEGIN: clocktable")
21484 (search-backward "#+BEGIN: clocktable" nil t))
21485 (match-beginning 0))
21486 (and (re-search-forward "#\\+END:?" nil t)
21487 (match-end 0))) clist))
21488 ((org-in-src-block-p)
21489 (push (list :src-block
21490 (and (or (looking-at "#\\+BEGIN_SRC")
21491 (search-backward "#+BEGIN_SRC" nil t))
21492 (match-beginning 0))
21493 (and (search-forward "#+END_SRC" nil t)
21494 (match-beginning 0))) clist))))
21495 (goto-char p)
21497 ;; Now the small context
21498 (cond
21499 ((org-at-timestamp-p)
21500 (push (org-point-in-group p 0 :timestamp) clist))
21501 ((memq 'org-link faces)
21502 (push (list :link
21503 (previous-single-property-change p 'face)
21504 (next-single-property-change p 'face)) clist))
21505 ((memq 'org-special-keyword faces)
21506 (push (list :keyword
21507 (previous-single-property-change p 'face)
21508 (next-single-property-change p 'face)) clist))
21509 ((org-at-target-p)
21510 (push (org-point-in-group p 0 :target) clist)
21511 (goto-char (1- (match-beginning 0)))
21512 (if (looking-at org-radio-target-regexp)
21513 (push (org-point-in-group p 0 :radio-target) clist))
21514 (goto-char p))
21515 ((setq o (car (delq nil
21516 (mapcar
21517 (lambda (x)
21518 (if (memq x org-latex-fragment-image-overlays) x))
21519 (overlays-at (point))))))
21520 (push (list :latex-fragment
21521 (overlay-start o) (overlay-end o)) clist)
21522 (push (list :latex-preview
21523 (overlay-start o) (overlay-end o)) clist))
21524 ((org-inside-LaTeX-fragment-p)
21525 ;; FIXME: positions wrong.
21526 (push (list :latex-fragment (point) (point)) clist)))
21528 (setq clist (nreverse (delq nil clist)))
21529 clist))
21531 ;; FIXME: Compare with at-regexp-p Do we need both?
21532 (defun org-in-regexp (re &optional nlines visually)
21533 "Check if point is inside a match of regexp.
21534 Normally only the current line is checked, but you can include NLINES extra
21535 lines both before and after point into the search.
21536 If VISUALLY is set, require that the cursor is not after the match but
21537 really on, so that the block visually is on the match."
21538 (catch 'exit
21539 (let ((pos (point))
21540 (eol (point-at-eol (+ 1 (or nlines 0))))
21541 (inc (if visually 1 0)))
21542 (save-excursion
21543 (beginning-of-line (- 1 (or nlines 0)))
21544 (while (re-search-forward re eol t)
21545 (if (and (<= (match-beginning 0) pos)
21546 (>= (+ inc (match-end 0)) pos))
21547 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21549 (defun org-at-regexp-p (regexp)
21550 "Is point inside a match of REGEXP in the current line?"
21551 (catch 'exit
21552 (save-excursion
21553 (let ((pos (point)) (end (point-at-eol)))
21554 (beginning-of-line 1)
21555 (while (re-search-forward regexp end t)
21556 (if (and (<= (match-beginning 0) pos)
21557 (>= (match-end 0) pos))
21558 (throw 'exit t)))
21559 nil))))
21561 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21562 "Non-nil when point is between matches of START-RE and END-RE.
21564 Also return a non-nil value when point is on one of the matches.
21566 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21567 buffer positions. Default values are the positions of headlines
21568 surrounding the point.
21570 The functions returns a cons cell whose car (resp. cdr) is the
21571 position before START-RE (resp. after END-RE)."
21572 (save-match-data
21573 (let ((pos (point))
21574 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21575 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21576 beg end)
21577 (save-excursion
21578 ;; Point is on a block when on START-RE or if START-RE can be
21579 ;; found before it...
21580 (and (or (org-at-regexp-p start-re)
21581 (re-search-backward start-re limit-up t))
21582 (setq beg (match-beginning 0))
21583 ;; ... and END-RE after it...
21584 (goto-char (match-end 0))
21585 (re-search-forward end-re limit-down t)
21586 (> (setq end (match-end 0)) pos)
21587 ;; ... without another START-RE in-between.
21588 (goto-char (match-beginning 0))
21589 (not (re-search-backward start-re (1+ beg) t))
21590 ;; Return value.
21591 (cons beg end))))))
21593 (defun org-in-block-p (names)
21594 "Non-nil when point belongs to a block whose name belongs to NAMES.
21596 NAMES is a list of strings containing names of blocks.
21598 Return first block name matched, or nil. Beware that in case of
21599 nested blocks, the returned name may not belong to the closest
21600 block from point."
21601 (save-match-data
21602 (catch 'exit
21603 (let ((case-fold-search t)
21604 (lim-up (save-excursion (outline-previous-heading)))
21605 (lim-down (save-excursion (outline-next-heading))))
21606 (mapc (lambda (name)
21607 (let ((n (regexp-quote name)))
21608 (when (org-between-regexps-p
21609 (concat "^[ \t]*#\\+begin_" n)
21610 (concat "^[ \t]*#\\+end_" n)
21611 lim-up lim-down)
21612 (throw 'exit n))))
21613 names))
21614 nil)))
21616 (defun org-in-drawer-p ()
21617 "Is point within a drawer?"
21618 (save-match-data
21619 (let ((case-fold-search t)
21620 (lim-up (save-excursion (outline-previous-heading)))
21621 (lim-down (save-excursion (outline-next-heading))))
21622 (org-between-regexps-p
21623 (concat "^[ \t]*:" (regexp-opt org-drawers) ":")
21624 "^[ \t]*:end:.*$"
21625 lim-up lim-down))))
21627 (defun org-occur-in-agenda-files (regexp &optional nlines)
21628 "Call `multi-occur' with buffers for all agenda files."
21629 (interactive "sOrg-files matching: \np")
21630 (let* ((files (org-agenda-files))
21631 (tnames (mapcar 'file-truename files))
21632 (extra org-agenda-text-search-extra-files)
21634 (when (eq (car extra) 'agenda-archives)
21635 (setq extra (cdr extra))
21636 (setq files (org-add-archive-files files)))
21637 (while (setq f (pop extra))
21638 (unless (member (file-truename f) tnames)
21639 (add-to-list 'files f 'append)
21640 (add-to-list 'tnames (file-truename f) 'append)))
21641 (multi-occur
21642 (mapcar (lambda (x)
21643 (with-current-buffer
21644 (or (get-file-buffer x) (find-file-noselect x))
21645 (widen)
21646 (current-buffer)))
21647 files)
21648 regexp)))
21650 (if (boundp 'occur-mode-find-occurrence-hook)
21651 ;; Emacs 23
21652 (add-hook 'occur-mode-find-occurrence-hook
21653 (lambda ()
21654 (when (derived-mode-p 'org-mode)
21655 (org-reveal))))
21656 ;; Emacs 22
21657 (defadvice occur-mode-goto-occurrence
21658 (after org-occur-reveal activate)
21659 (and (derived-mode-p 'org-mode) (org-reveal)))
21660 (defadvice occur-mode-goto-occurrence-other-window
21661 (after org-occur-reveal activate)
21662 (and (derived-mode-p 'org-mode) (org-reveal)))
21663 (defadvice occur-mode-display-occurrence
21664 (after org-occur-reveal activate)
21665 (when (derived-mode-p 'org-mode)
21666 (let ((pos (occur-mode-find-occurrence)))
21667 (with-current-buffer (marker-buffer pos)
21668 (save-excursion
21669 (goto-char pos)
21670 (org-reveal)))))))
21672 (defun org-occur-link-in-agenda-files ()
21673 "Create a link and search for it in the agendas.
21674 The link is not stored in `org-stored-links', it is just created
21675 for the search purpose."
21676 (interactive)
21677 (let ((link (condition-case nil
21678 (org-store-link nil)
21679 (error "Unable to create a link to here"))))
21680 (org-occur-in-agenda-files (regexp-quote link))))
21682 (defun org-reverse-string (string)
21683 "Return the reverse of STRING."
21684 (apply 'string (reverse (string-to-list string))))
21686 (defsubst org-uniquify (list)
21687 "Non-destructively remove duplicate elements from LIST."
21688 (let ((res (copy-sequence list))) (delete-dups res)))
21690 (defun org-uniquify-alist (alist)
21691 "Merge elements of ALIST with the same key.
21693 For example, in this alist:
21695 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21696 => '((a 1 3) (b 2))
21698 merge (a 1) and (a 3) into (a 1 3).
21700 The function returns the new ALIST."
21701 (let (rtn)
21702 (mapc
21703 (lambda (e)
21704 (let (n)
21705 (if (not (assoc (car e) rtn))
21706 (push e rtn)
21707 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21708 (setq rtn (assq-delete-all (car e) rtn))
21709 (push n rtn))))
21710 alist)
21711 rtn))
21713 (defun org-delete-all (elts list)
21714 "Remove all elements in ELTS from LIST."
21715 (while elts
21716 (setq list (delete (pop elts) list)))
21717 list)
21719 (defun org-count (cl-item cl-seq)
21720 "Count the number of occurrences of ITEM in SEQ.
21721 Taken from `count' in cl-seq.el with all keyword arguments removed."
21722 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21723 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21724 (while (< cl-start cl-end)
21725 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21726 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21727 (setq cl-start (1+ cl-start)))
21728 cl-count))
21730 (defun org-remove-if (predicate seq)
21731 "Remove everything from SEQ that fulfills PREDICATE."
21732 (let (res e)
21733 (while seq
21734 (setq e (pop seq))
21735 (if (not (funcall predicate e)) (push e res)))
21736 (nreverse res)))
21738 (defun org-remove-if-not (predicate seq)
21739 "Remove everything from SEQ that does not fulfill PREDICATE."
21740 (let (res e)
21741 (while seq
21742 (setq e (pop seq))
21743 (if (funcall predicate e) (push e res)))
21744 (nreverse res)))
21746 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21747 "Reduce two-argument FUNCTION across SEQ.
21748 Taken from `reduce' in cl-seq.el with all keyword arguments but
21749 \":initial-value\" removed."
21750 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21751 (cadr (memq :initial-value cl-keys)))
21752 (cl-seq (pop cl-seq))
21753 (t (funcall cl-func)))))
21754 (while cl-seq
21755 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21756 cl-accum))
21758 (defun org-every (pred seq)
21759 "Return true if PREDICATE is true of every element of SEQ.
21760 Adapted from `every' in cl.el."
21761 (catch 'org-every
21762 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
21765 (defun org-some (pred seq)
21766 "Return true if PREDICATE is true of any element of SEQ.
21767 Adapted from `some' in cl.el."
21768 (catch 'org-some
21769 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
21770 nil))
21772 (defun org-back-over-empty-lines ()
21773 "Move backwards over whitespace, to the beginning of the first empty line.
21774 Returns the number of empty lines passed."
21775 (let ((pos (point)))
21776 (if (cdr (assoc 'heading org-blank-before-new-entry))
21777 (skip-chars-backward " \t\n\r")
21778 (unless (eobp)
21779 (forward-line -1)))
21780 (beginning-of-line 2)
21781 (goto-char (min (point) pos))
21782 (count-lines (point) pos)))
21784 (defun org-skip-whitespace ()
21785 (skip-chars-forward " \t\n\r"))
21787 (defun org-point-in-group (point group &optional context)
21788 "Check if POINT is in match-group GROUP.
21789 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21790 match. If the match group does not exist or point is not inside it,
21791 return nil."
21792 (and (match-beginning group)
21793 (>= point (match-beginning group))
21794 (<= point (match-end group))
21795 (if context
21796 (list context (match-beginning group) (match-end group))
21797 t)))
21799 (defun org-switch-to-buffer-other-window (&rest args)
21800 "Switch to buffer in a second window on the current frame.
21801 In particular, do not allow pop-up frames.
21802 Returns the newly created buffer."
21803 (org-no-popups
21804 (apply 'switch-to-buffer-other-window args)))
21806 (defun org-combine-plists (&rest plists)
21807 "Create a single property list from all plists in PLISTS.
21808 The process starts by copying the first list, and then setting properties
21809 from the other lists. Settings in the last list are the most significant
21810 ones and overrule settings in the other lists."
21811 (let ((rtn (copy-sequence (pop plists)))
21812 p v ls)
21813 (while plists
21814 (setq ls (pop plists))
21815 (while ls
21816 (setq p (pop ls) v (pop ls))
21817 (setq rtn (plist-put rtn p v))))
21818 rtn))
21820 (defun org-replace-escapes (string table)
21821 "Replace %-escapes in STRING with values in TABLE.
21822 TABLE is an association list with keys like \"%a\" and string values.
21823 The sequences in STRING may contain normal field width and padding information,
21824 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21825 so values can contain further %-escapes if they are define later in TABLE."
21826 (let ((tbl (copy-alist table))
21827 (case-fold-search nil)
21828 (pchg 0)
21829 e re rpl)
21830 (while (setq e (pop tbl))
21831 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21832 (when (and (cdr e) (string-match re (cdr e)))
21833 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21834 (safe "SREF"))
21835 (add-text-properties 0 3 (list 'sref sref) safe)
21836 (setcdr e (replace-match safe t t (cdr e)))))
21837 (while (string-match re string)
21838 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21839 (cdr e)))
21840 (setq string (replace-match rpl t t string))))
21841 (while (setq pchg (next-property-change pchg string))
21842 (let ((sref (get-text-property pchg 'sref string)))
21843 (when (and sref (string-match "SREF" string pchg))
21844 (setq string (replace-match sref t t string)))))
21845 string))
21847 (defun org-sublist (list start end)
21848 "Return a section of LIST, from START to END.
21849 Counting starts at 1."
21850 (let (rtn (c start))
21851 (setq list (nthcdr (1- start) list))
21852 (while (and list (<= c end))
21853 (push (pop list) rtn)
21854 (setq c (1+ c)))
21855 (nreverse rtn)))
21857 (defun org-find-base-buffer-visiting (file)
21858 "Like `find-buffer-visiting' but always return the base buffer and
21859 not an indirect buffer."
21860 (let ((buf (or (get-file-buffer file)
21861 (find-buffer-visiting file))))
21862 (if buf
21863 (or (buffer-base-buffer buf) buf)
21864 nil)))
21866 (defun org-image-file-name-regexp (&optional extensions)
21867 "Return regexp matching the file names of images.
21868 If EXTENSIONS is given, only match these."
21869 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21870 (image-file-name-regexp)
21871 (let ((image-file-name-extensions
21872 (or extensions
21873 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21874 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21875 (concat "\\."
21876 (regexp-opt (nconc (mapcar 'upcase
21877 image-file-name-extensions)
21878 image-file-name-extensions)
21880 "\\'"))))
21882 (defun org-file-image-p (file &optional extensions)
21883 "Return non-nil if FILE is an image."
21884 (save-match-data
21885 (string-match (org-image-file-name-regexp extensions) file)))
21887 (defun org-get-cursor-date (&optional with-time)
21888 "Return the date at cursor in as a time.
21889 This works in the calendar and in the agenda, anywhere else it just
21890 returns the current time.
21891 If WITH-TIME is non-nil, returns the time of the event at point (in
21892 the agenda) or the current time of the day."
21893 (let (date day defd tp tm hod mod)
21894 (when with-time
21895 (setq tp (get-text-property (point) 'time))
21896 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21897 (setq hod (string-to-number (match-string 1 tp))
21898 mod (string-to-number (match-string 2 tp))))
21899 (or tp (setq hod (nth 2 (decode-time (current-time)))
21900 mod (nth 1 (decode-time (current-time))))))
21901 (cond
21902 ((eq major-mode 'calendar-mode)
21903 (setq date (calendar-cursor-to-date)
21904 defd (encode-time 0 (or mod 0) (or hod 0)
21905 (nth 1 date) (nth 0 date) (nth 2 date))))
21906 ((eq major-mode 'org-agenda-mode)
21907 (setq day (get-text-property (point) 'day))
21908 (if day
21909 (setq date (calendar-gregorian-from-absolute day)
21910 defd (encode-time 0 (or mod 0) (or hod 0)
21911 (nth 1 date) (nth 0 date) (nth 2 date))))))
21912 (or defd (current-time))))
21914 (defun org-mark-subtree (&optional up)
21915 "Mark the current subtree.
21916 This puts point at the start of the current subtree, and mark at
21917 the end. If a numeric prefix UP is given, move up into the
21918 hierarchy of headlines by UP levels before marking the subtree."
21919 (interactive "P")
21920 (org-with-limited-levels
21921 (cond ((org-at-heading-p) (beginning-of-line))
21922 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21923 (t (outline-previous-visible-heading 1))))
21924 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21925 (if (org-called-interactively-p 'any)
21926 (call-interactively 'org-mark-element)
21927 (org-mark-element)))
21930 ;;; Indentation
21932 (defun org-indent-line ()
21933 "Indent line depending on context."
21934 (interactive)
21935 (let* ((pos (point))
21936 (itemp (org-at-item-p))
21937 (case-fold-search t)
21938 (org-drawer-regexp (or org-drawer-regexp "\000"))
21939 (inline-task-p (and (featurep 'org-inlinetask)
21940 (org-inlinetask-in-task-p)))
21941 (inline-re (and inline-task-p
21942 (org-inlinetask-outline-regexp)))
21943 column)
21944 (if (and orgstruct-is-++ (eq pos (point)))
21945 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21946 (indent-according-to-mode))
21947 (beginning-of-line 1)
21948 (cond
21949 ;; Headings
21950 ((looking-at org-outline-regexp) (setq column 0))
21951 ;; Footnote definition
21952 ((looking-at org-footnote-definition-re) (setq column 0))
21953 ;; Literal examples
21954 ((looking-at "[ \t]*:\\( \\|$\\)")
21955 (setq column (org-get-indentation))) ; do nothing
21956 ;; Lists
21957 ((ignore-errors (goto-char (org-in-item-p)))
21958 (setq column (if itemp
21959 (org-get-indentation)
21960 (org-list-item-body-column (point))))
21961 (goto-char pos))
21962 ;; Drawers
21963 ((and (looking-at "[ \t]*:END:")
21964 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21965 (save-excursion
21966 (goto-char (1- (match-beginning 1)))
21967 (setq column (current-column))))
21968 ;; Special blocks
21969 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21970 (save-excursion
21971 (re-search-backward
21972 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21973 (setq column (org-get-indentation (match-string 0))))
21974 ((and (not (looking-at "[ \t]*#\\+begin_"))
21975 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21976 (save-excursion
21977 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21978 (setq column
21979 (cond ((equal (downcase (match-string 1)) "src")
21980 ;; src blocks: let `org-edit-src-exit' handle them
21981 (org-get-indentation))
21982 ((equal (downcase (match-string 1)) "example")
21983 (max (org-get-indentation)
21984 (org-get-indentation (match-string 0))))
21986 (org-get-indentation (match-string 0))))))
21987 ;; This line has nothing special, look at the previous relevant
21988 ;; line to compute indentation
21990 (beginning-of-line 0)
21991 (while (and (not (bobp))
21992 (not (looking-at org-table-line-regexp))
21993 (not (looking-at org-drawer-regexp))
21994 ;; When point started in an inline task, do not move
21995 ;; above task starting line.
21996 (not (and inline-task-p (looking-at inline-re)))
21997 ;; Skip drawers, blocks, empty lines, verbatim,
21998 ;; comments, tables, footnotes definitions, lists,
21999 ;; inline tasks.
22000 (or (and (looking-at "[ \t]*:END:")
22001 (re-search-backward org-drawer-regexp nil t))
22002 (and (looking-at "[ \t]*#\\+end_")
22003 (re-search-backward "[ \t]*#\\+begin_"nil t))
22004 (looking-at "[ \t]*[\n:#|]")
22005 (looking-at org-footnote-definition-re)
22006 (and (not inline-task-p)
22007 (featurep 'org-inlinetask)
22008 (org-inlinetask-in-task-p)
22009 (or (org-inlinetask-goto-beginning) t))))
22010 (beginning-of-line 0))
22011 (cond
22012 ;; There was a list item above.
22013 ((save-excursion
22014 (and (ignore-errors (goto-char (org-in-item-p)))
22015 (goto-char
22016 (org-list-get-top-point (org-list-struct)))))
22017 (looking-at org-list-full-item-re)
22018 (setq column (length (match-string 0))))
22019 ;; There was an heading above.
22020 ((looking-at "\\*+[ \t]+")
22021 (if (not org-adapt-indentation)
22022 (setq column 0)
22023 (goto-char (match-end 0))
22024 (setq column (current-column))))
22025 ;; A drawer had started and is unfinished
22026 ((looking-at org-drawer-regexp)
22027 (goto-char (1- (match-beginning 1)))
22028 (setq column (current-column)))
22029 ;; Else, nothing noticeable found: get indentation and go on.
22030 (t (setq column (org-get-indentation))))))
22031 ;; Now apply indentation and move cursor accordingly
22032 (goto-char pos)
22033 (if (<= (current-column) (current-indentation))
22034 (org-indent-line-to column)
22035 (save-excursion (org-indent-line-to column)))
22036 ;; Special polishing for properties, see `org-property-format'
22037 (setq column (current-column))
22038 (beginning-of-line 1)
22039 (if (looking-at org-property-re)
22040 (replace-match (concat (match-string 4)
22041 (format org-property-format
22042 (match-string 1) (match-string 3)))
22043 t t))
22044 (org-move-to-column column))))
22046 (defun org-indent-drawer ()
22047 "Indent the drawer at point."
22048 (interactive)
22049 (let ((p (point))
22050 (e (and (save-excursion (re-search-forward ":END:" nil t))
22051 (match-end 0)))
22052 (folded
22053 (save-excursion
22054 (end-of-line)
22055 (when (overlays-at (point))
22056 (member 'invisible (overlay-properties
22057 (car (overlays-at (point)))))))))
22058 (when folded (org-cycle))
22059 (indent-for-tab-command)
22060 (while (and (move-beginning-of-line 2) (< (point) e))
22061 (indent-for-tab-command))
22062 (goto-char p)
22063 (when folded (org-cycle)))
22064 (message "Drawer at point indented"))
22066 (defun org-indent-block ()
22067 "Indent the block at point."
22068 (interactive)
22069 (let ((p (point))
22070 (case-fold-search t)
22071 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22072 (match-end 0)))
22073 (folded
22074 (save-excursion
22075 (end-of-line)
22076 (when (overlays-at (point))
22077 (member 'invisible (overlay-properties
22078 (car (overlays-at (point)))))))))
22079 (when folded (org-cycle))
22080 (indent-for-tab-command)
22081 (while (and (move-beginning-of-line 2) (< (point) e))
22082 (indent-for-tab-command))
22083 (goto-char p)
22084 (when folded (org-cycle)))
22085 (message "Block at point indented"))
22087 (defun org-indent-region (start end)
22088 "Indent region."
22089 (interactive "r")
22090 (save-excursion
22091 (let ((line-end (org-current-line end)))
22092 (goto-char start)
22093 (while (< (org-current-line) line-end)
22094 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
22095 (t (call-interactively 'org-indent-line)))
22096 (move-beginning-of-line 2)))))
22099 ;;; Filling
22101 ;; We use our own fill-paragraph and auto-fill functions.
22103 ;; `org-fill-paragraph' relies on adaptive filling and context
22104 ;; checking. Appropriate `fill-prefix' is computed with
22105 ;; `org-adaptive-fill-function'.
22107 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22108 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22109 ;; `org-adaptive-fill-function' value. Internally,
22110 ;; `org-comment-line-break-function' breaks the line.
22112 ;; `org-setup-filling' installs filling and auto-filling related
22113 ;; variables during `org-mode' initialization.
22115 (defvar org-element-paragraph-separate) ; org-element.el
22116 (defun org-setup-filling ()
22117 (require 'org-element)
22118 ;; Prevent auto-fill from inserting unwanted new items.
22119 (when (boundp 'fill-nobreak-predicate)
22120 (org-set-local
22121 'fill-nobreak-predicate
22122 (org-uniquify
22123 (append fill-nobreak-predicate
22124 '(org-fill-line-break-nobreak-p
22125 org-fill-paragraph-with-timestamp-nobreak-p)))))
22126 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22127 (org-set-local 'paragraph-start paragraph-ending)
22128 (org-set-local 'paragraph-separate paragraph-ending))
22129 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22130 (org-set-local 'auto-fill-inhibit-regexp nil)
22131 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22132 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22133 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22135 (defun org-fill-line-break-nobreak-p ()
22136 "Non-nil when a new line at point would create an Org line break."
22137 (save-excursion
22138 (skip-chars-backward "[ \t]")
22139 (skip-chars-backward "\\\\")
22140 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22142 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22143 "Non-nil when a new line at point would split a timestamp."
22144 (and (org-at-timestamp-p t)
22145 (not (looking-at org-ts-regexp-both))))
22147 (declare-function message-in-body-p "message" ())
22148 (defvar orgtbl-line-start-regexp) ; From org-table.el
22149 (defun org-adaptive-fill-function ()
22150 "Compute a fill prefix for the current line.
22151 Return fill prefix, as a string, or nil if current line isn't
22152 meant to be filled."
22153 (let (prefix)
22154 (catch 'exit
22155 (when (derived-mode-p 'message-mode)
22156 (save-excursion
22157 (beginning-of-line)
22158 (cond ((or (not (message-in-body-p))
22159 (looking-at orgtbl-line-start-regexp))
22160 (throw 'exit nil))
22161 ((looking-at message-cite-prefix-regexp)
22162 (throw 'exit (match-string-no-properties 0)))
22163 ((looking-at org-outline-regexp)
22164 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22165 (org-with-wide-buffer
22166 (let* ((p (line-beginning-position))
22167 (element (save-excursion
22168 (beginning-of-line)
22169 (or (ignore-errors (org-element-at-point))
22170 (user-error "An element cannot be parsed line %d"
22171 (line-number-at-pos (point))))))
22172 (type (org-element-type element))
22173 (post-affiliated (org-element-property :post-affiliated element)))
22174 (unless (and post-affiliated (< p post-affiliated))
22175 (case type
22176 (comment (looking-at "[ \t]*# ?") (match-string 0))
22177 (footnote-definition "")
22178 ((item plain-list)
22179 (make-string (org-list-item-body-column
22180 (or post-affiliated
22181 (org-element-property :begin element)))
22182 ? ))
22183 (paragraph
22184 ;; Fill prefix is usually the same as the current line,
22185 ;; except if the paragraph is at the beginning of an item.
22186 (let ((parent (org-element-property :parent element)))
22187 (cond ((eq (org-element-type parent) 'item)
22188 (make-string (org-list-item-body-column
22189 (org-element-property :begin parent))
22190 ? ))
22191 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22192 (match-string 0))
22193 (t ""))))
22194 (comment-block
22195 ;; Only fill contents if P is within block boundaries.
22196 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22197 (forward-line)
22198 (point)))
22199 (cend (save-excursion
22200 (goto-char (org-element-property :end element))
22201 (skip-chars-backward " \r\t\n")
22202 (line-beginning-position))))
22203 (when (and (>= p cbeg) (< p cend))
22204 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22205 (match-string 0)
22206 "")))))))))))
22208 (declare-function message-goto-body "message" ())
22209 (defvar message-cite-prefix-regexp) ; From message.el
22210 (defun org-fill-paragraph (&optional justify)
22211 "Fill element at point, when applicable.
22213 This function only applies to comment blocks, comments, example
22214 blocks and paragraphs. Also, as a special case, re-align table
22215 when point is at one.
22217 If JUSTIFY is non-nil (interactively, with prefix argument),
22218 justify as well. If `sentence-end-double-space' is non-nil, then
22219 period followed by one space does not end a sentence, so don't
22220 break a line there. The variable `fill-column' controls the
22221 width for filling.
22223 For convenience, when point is at a plain list, an item or
22224 a footnote definition, try to fill the first paragraph within."
22225 (interactive)
22226 (if (and (derived-mode-p 'message-mode)
22227 (or (not (message-in-body-p))
22228 (save-excursion (move-beginning-of-line 1)
22229 (looking-at message-cite-prefix-regexp))))
22230 ;; First ensure filling is correct in message-mode.
22231 (let ((fill-paragraph-function
22232 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22233 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22234 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22235 (paragraph-separate
22236 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22237 (fill-paragraph nil))
22238 (with-syntax-table org-mode-transpose-word-syntax-table
22239 ;; Move to end of line in order to get the first paragraph
22240 ;; within a plain list or a footnote definition.
22241 (let ((element (save-excursion
22242 (end-of-line)
22243 (or (ignore-errors (org-element-at-point))
22244 (user-error "An element cannot be parsed line %d"
22245 (line-number-at-pos (point)))))))
22246 ;; First check if point is in a blank line at the beginning of
22247 ;; the buffer. In that case, ignore filling.
22248 (case (org-element-type element)
22249 ;; Use major mode filling function is src blocks.
22250 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22251 ;; Align Org tables, leave table.el tables as-is.
22252 (table-row (org-table-align) t)
22253 (table
22254 (when (eq (org-element-property :type element) 'org)
22255 (save-excursion
22256 (goto-char (org-element-property :post-affiliated element))
22257 (org-table-align)))
22259 (paragraph
22260 ;; Paragraphs may contain `line-break' type objects.
22261 (let ((beg (max (point-min)
22262 (org-element-property :contents-begin element)))
22263 (end (min (point-max)
22264 (org-element-property :contents-end element))))
22265 ;; Do nothing if point is at an affiliated keyword.
22266 (if (< (line-end-position) beg) t
22267 (when (derived-mode-p 'message-mode)
22268 ;; In `message-mode', do not fill following citation
22269 ;; in current paragraph nor text before message body.
22270 (let ((body-start (save-excursion (message-goto-body))))
22271 (when body-start (setq beg (max body-start beg))))
22272 (when (save-excursion
22273 (re-search-forward
22274 (concat "^" message-cite-prefix-regexp) end t))
22275 (setq end (match-beginning 0))))
22276 ;; Fill paragraph, taking line breaks into account.
22277 ;; For that, slice the paragraph using line breaks as
22278 ;; separators, and fill the parts in reverse order to
22279 ;; avoid messing with markers.
22280 (save-excursion
22281 (goto-char end)
22282 (mapc
22283 (lambda (pos)
22284 (fill-region-as-paragraph pos (point) justify)
22285 (goto-char pos))
22286 ;; Find the list of ending positions for line breaks
22287 ;; in the current paragraph. Add paragraph
22288 ;; beginning to include first slice.
22289 (nreverse
22290 (cons beg
22291 (org-element-map
22292 (org-element--parse-objects
22293 beg end nil (org-element-restriction 'paragraph))
22294 'line-break
22295 (lambda (lb) (org-element-property :end lb)))))))
22296 t)))
22297 ;; Contents of `comment-block' type elements should be
22298 ;; filled as plain text, but only if point is within block
22299 ;; markers.
22300 (comment-block
22301 (let* ((case-fold-search t)
22302 (beg (save-excursion
22303 (goto-char (org-element-property :begin element))
22304 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22305 (forward-line)
22306 (point)))
22307 (end (save-excursion
22308 (goto-char (org-element-property :end element))
22309 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22310 (line-beginning-position))))
22311 (when (and (>= (point) beg) (< (point) end))
22312 (fill-region-as-paragraph
22313 (save-excursion
22314 (end-of-line)
22315 (re-search-backward "^[ \t]*$" beg 'move)
22316 (line-beginning-position))
22317 (save-excursion
22318 (beginning-of-line)
22319 (re-search-forward "^[ \t]*$" end 'move)
22320 (line-beginning-position))
22321 justify)))
22323 ;; Fill comments.
22324 (comment (fill-comment-paragraph justify))
22325 ;; Ignore every other element.
22326 (otherwise t))))))
22328 (defun org-auto-fill-function ()
22329 "Auto-fill function."
22330 ;; Check if auto-filling is meaningful.
22331 (let ((fc (current-fill-column)))
22332 (when (and fc (> (current-column) fc))
22333 (let* ((fill-prefix (org-adaptive-fill-function))
22334 ;; Enforce empty fill prefix, if required. Otherwise, it
22335 ;; will be computed again.
22336 (adaptive-fill-mode (not (equal fill-prefix ""))))
22337 (when fill-prefix (do-auto-fill))))))
22339 (defun org-comment-line-break-function (&optional soft)
22340 "Break line at point and indent, continuing comment if within one.
22341 The inserted newline is marked hard if variable
22342 `use-hard-newlines' is true, unless optional argument SOFT is
22343 non-nil."
22344 (if soft (insert-and-inherit ?\n) (newline 1))
22345 (save-excursion (forward-char -1) (delete-horizontal-space))
22346 (delete-horizontal-space)
22347 (indent-to-left-margin)
22348 (insert-before-markers-and-inherit fill-prefix))
22351 ;;; Comments
22353 ;; Org comments syntax is quite complex. It requires the entire line
22354 ;; to be just a comment. Also, even with the right syntax at the
22355 ;; beginning of line, some some elements (i.e. verse-block or
22356 ;; example-block) don't accept comments. Usual Emacs comment commands
22357 ;; cannot cope with those requirements. Therefore, Org replaces them.
22359 ;; Org still relies on `comment-dwim', but cannot trust
22360 ;; `comment-only-p'. So, `comment-region-function' and
22361 ;; `uncomment-region-function' both point
22362 ;; to`org-comment-or-uncomment-region'. Eventually,
22363 ;; `org-insert-comment' takes care of insertion of comments at the
22364 ;; beginning of line.
22366 ;; `org-setup-comments-handling' install comments related variables
22367 ;; during `org-mode' initialization.
22369 (defun org-setup-comments-handling ()
22370 (interactive)
22371 (org-set-local 'comment-use-syntax nil)
22372 (org-set-local 'comment-start "# ")
22373 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22374 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22375 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22376 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22378 (defun org-insert-comment ()
22379 "Insert an empty comment above current line.
22380 If the line is empty, insert comment at its beginning."
22381 (beginning-of-line)
22382 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22383 (org-indent-line)
22384 (insert "# "))
22386 (defvar comment-empty-lines) ; From newcomment.el.
22387 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22388 "Comment or uncomment each non-blank line in the region.
22389 Uncomment each non-blank line between BEG and END if it only
22390 contains commented lines. Otherwise, comment them."
22391 (save-restriction
22392 ;; Restrict region
22393 (narrow-to-region (save-excursion (goto-char beg)
22394 (skip-chars-forward " \r\t\n" end)
22395 (line-beginning-position))
22396 (save-excursion (goto-char end)
22397 (skip-chars-backward " \r\t\n" beg)
22398 (line-end-position)))
22399 (let ((uncommentp
22400 ;; UNCOMMENTP is non-nil when every non blank line between
22401 ;; BEG and END is a comment.
22402 (save-excursion
22403 (goto-char (point-min))
22404 (while (and (not (eobp))
22405 (let ((element (org-element-at-point)))
22406 (and (eq (org-element-type element) 'comment)
22407 (goto-char (min (point-max)
22408 (org-element-property
22409 :end element)))))))
22410 (eobp))))
22411 (if uncommentp
22412 ;; Only blank lines and comments in region: uncomment it.
22413 (save-excursion
22414 (goto-char (point-min))
22415 (while (not (eobp))
22416 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22417 (replace-match "" nil nil nil 1))
22418 (forward-line)))
22419 ;; Comment each line in region.
22420 (let ((min-indent (point-max)))
22421 ;; First find the minimum indentation across all lines.
22422 (save-excursion
22423 (goto-char (point-min))
22424 (while (and (not (eobp)) (not (zerop min-indent)))
22425 (unless (looking-at "[ \t]*$")
22426 (setq min-indent (min min-indent (current-indentation))))
22427 (forward-line)))
22428 ;; Then loop over all lines.
22429 (save-excursion
22430 (goto-char (point-min))
22431 (while (not (eobp))
22432 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22433 ;; Don't get fooled by invisible text (e.g. link path)
22434 ;; when moving to column MIN-INDENT.
22435 (let ((buffer-invisibility-spec nil))
22436 (org-move-to-column min-indent t))
22437 (insert comment-start))
22438 (forward-line))))))))
22441 ;;; Planning
22443 ;; This section contains tools to operate on timestamp objects, as
22444 ;; returned by, e.g. `org-element-context'.
22446 (defun org-timestamp-has-time-p (timestamp)
22447 "Non-nil when TIMESTAMP has a time specified."
22448 (org-element-property :hour-start timestamp))
22450 (defun org-timestamp-format (timestamp format &optional end utc)
22451 "Format a TIMESTAMP element into a string.
22453 FORMAT is a format specifier to be passed to
22454 `format-time-string'.
22456 When optional argument END is non-nil, use end of date-range or
22457 time-range, if possible.
22459 When optional argument UTC is non-nil, time will be expressed as
22460 Universal Time."
22461 (format-time-string
22462 format
22463 (apply 'encode-time
22464 (cons 0
22465 (mapcar
22466 (lambda (prop) (or (org-element-property prop timestamp) 0))
22467 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22468 '(:minute-start :hour-start :day-start :month-start
22469 :year-start)))))
22470 utc))
22472 (defun org-timestamp-split-range (timestamp &optional end)
22473 "Extract a timestamp object from a date or time range.
22475 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22476 the end of the range. Otherwise, extract its start.
22478 Return a new timestamp object sharing the same parent as
22479 TIMESTAMP."
22480 (let ((type (org-element-property :type timestamp)))
22481 (if (memq type '(active inactive diary)) timestamp
22482 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22483 ;; Set new type.
22484 (org-element-put-property
22485 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22486 ;; Copy start properties over end properties if END is
22487 ;; non-nil. Otherwise, copy end properties over `start' ones.
22488 (let ((p-alist '((:minute-start . :minute-end)
22489 (:hour-start . :hour-end)
22490 (:day-start . :day-end)
22491 (:month-start . :month-end)
22492 (:year-start . :year-end))))
22493 (dolist (p-cell p-alist)
22494 (org-element-put-property
22495 split-ts
22496 (funcall (if end 'car 'cdr) p-cell)
22497 (org-element-property
22498 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22499 ;; Eventually refresh `:raw-value'.
22500 (org-element-put-property split-ts :raw-value nil)
22501 (org-element-put-property
22502 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22504 (defun org-timestamp-translate (timestamp &optional boundary)
22505 "Apply `org-translate-time' on a TIMESTAMP object.
22506 When optional argument BOUNDARY is non-nil, it is either the
22507 symbol `start' or `end'. In this case, only translate the
22508 starting or ending part of TIMESTAMP if it is a date or time
22509 range. Otherwise, translate both parts."
22510 (if (and (not boundary)
22511 (memq (org-element-property :type timestamp)
22512 '(active-range inactive-range)))
22513 (concat
22514 (org-translate-time
22515 (org-element-property :raw-value
22516 (org-timestamp-split-range timestamp)))
22517 "--"
22518 (org-translate-time
22519 (org-element-property :raw-value
22520 (org-timestamp-split-range timestamp t))))
22521 (org-translate-time
22522 (org-element-property
22523 :raw-value
22524 (if (not boundary) timestamp
22525 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22529 ;;; Other stuff.
22531 (defun org-toggle-fixed-width-section (arg)
22532 "Toggle the fixed-width export.
22533 If there is no active region, the QUOTE keyword at the current headline is
22534 inserted or removed. When present, it causes the text between this headline
22535 and the next to be exported as fixed-width text, and unmodified.
22536 If there is an active region, this command adds or removes a colon as the
22537 first character of this line. If the first character of a line is a colon,
22538 this line is also exported in fixed-width font."
22539 (interactive "P")
22540 (let* ((cc 0)
22541 (regionp (org-region-active-p))
22542 (beg (if regionp (region-beginning) (point)))
22543 (end (if regionp (region-end)))
22544 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22545 (case-fold-search nil)
22546 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22547 off)
22548 (if regionp
22549 (save-excursion
22550 (goto-char beg)
22551 (setq cc (current-column))
22552 (beginning-of-line 1)
22553 (setq off (looking-at re))
22554 (while (> nlines 0)
22555 (setq nlines (1- nlines))
22556 (beginning-of-line 1)
22557 (cond
22558 (arg
22559 (org-move-to-column cc t)
22560 (insert ": \n")
22561 (forward-line -1))
22562 ((and off (looking-at re))
22563 (replace-match "" t t nil 1))
22564 ((not off) (org-move-to-column cc t) (insert ": ")))
22565 (forward-line 1)))
22566 (save-excursion
22567 (org-back-to-heading)
22568 (cond
22569 ((looking-at (format org-heading-keyword-regexp-format
22570 org-quote-string))
22571 (goto-char (match-end 1))
22572 (looking-at (concat " +" org-quote-string))
22573 (replace-match "" t t)
22574 (when (eolp) (insert " ")))
22575 ((looking-at org-outline-regexp)
22576 (goto-char (match-end 0))
22577 (insert org-quote-string " ")))))))
22579 (defun org-reftex-citation ()
22580 "Use reftex-citation to insert a citation into the buffer.
22581 This looks for a line like
22583 #+BIBLIOGRAPHY: foo plain option:-d
22585 and derives from it that foo.bib is the bibliography file relevant
22586 for this document. It then installs the necessary environment for RefTeX
22587 to work in this buffer and calls `reftex-citation' to insert a citation
22588 into the buffer.
22590 Export of such citations to both LaTeX and HTML is handled by the contributed
22591 package ox-bibtex by Taru Karttunen."
22592 (interactive)
22593 (let ((reftex-docstruct-symbol 'rds)
22594 (reftex-cite-format "\\cite{%l}")
22595 rds bib)
22596 (save-excursion
22597 (save-restriction
22598 (widen)
22599 (let ((case-fold-search t)
22600 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22601 (if (not (save-excursion
22602 (or (re-search-forward re nil t)
22603 (re-search-backward re nil t))))
22604 (error "No bibliography defined in file")
22605 (setq bib (concat (match-string 1) ".bib")
22606 rds (list (list 'bib bib)))))))
22607 (call-interactively 'reftex-citation)))
22609 ;;;; Functions extending outline functionality
22611 (defun org-beginning-of-line (&optional arg)
22612 "Go to the beginning of the current line. If that is invisible, continue
22613 to a visible line beginning. This makes the function of C-a more intuitive.
22614 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22615 first attempt, and only move to after the tags when the cursor is already
22616 beyond the end of the headline."
22617 (interactive "P")
22618 (let ((pos (point))
22619 (special (if (consp org-special-ctrl-a/e)
22620 (car org-special-ctrl-a/e)
22621 org-special-ctrl-a/e))
22622 refpos)
22623 (if (org-bound-and-true-p visual-line-mode)
22624 (beginning-of-visual-line 1)
22625 (beginning-of-line 1))
22626 (if (and arg (fboundp 'move-beginning-of-line))
22627 (call-interactively 'move-beginning-of-line)
22628 (if (bobp)
22630 (backward-char 1)
22631 (if (org-truely-invisible-p)
22632 (while (and (not (bobp)) (org-truely-invisible-p))
22633 (backward-char 1)
22634 (beginning-of-line 1))
22635 (forward-char 1))))
22636 (when special
22637 (cond
22638 ((and (looking-at org-complex-heading-regexp)
22639 (= (char-after (match-end 1)) ?\ ))
22640 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22641 (point-at-eol)))
22642 (goto-char
22643 (if (eq special t)
22644 (cond ((> pos refpos) refpos)
22645 ((= pos (point)) refpos)
22646 (t (point)))
22647 (cond ((> pos (point)) (point))
22648 ((not (eq last-command this-command)) (point))
22649 (t refpos)))))
22650 ((org-at-item-p)
22651 ;; Being at an item and not looking at an the item means point
22652 ;; was previously moved to beginning of a visual line, which
22653 ;; doesn't contain the item. Therefore, do nothing special,
22654 ;; just stay here.
22655 (when (looking-at org-list-full-item-re)
22656 ;; Set special position at first white space character after
22657 ;; bullet, and check-box, if any.
22658 (let ((after-bullet
22659 (let ((box (match-end 3)))
22660 (if (not box) (match-end 1)
22661 (let ((after (char-after box)))
22662 (if (and after (= after ? )) (1+ box) box))))))
22663 ;; Special case: Move point to special position when
22664 ;; currently after it or at beginning of line.
22665 (if (eq special t)
22666 (when (or (> pos after-bullet) (= (point) pos))
22667 (goto-char after-bullet))
22668 ;; Reversed case: Move point to special position when
22669 ;; point was already at beginning of line and command is
22670 ;; repeated.
22671 (when (and (= (point) pos) (eq last-command this-command))
22672 (goto-char after-bullet))))))))
22673 (org-no-warnings
22674 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22675 (setq disable-point-adjustment
22676 (or (not (invisible-p (point)))
22677 (not (invisible-p (max (point-min) (1- (point))))))))
22679 (defun org-end-of-line (&optional arg)
22680 "Go to the end of the line.
22681 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22682 tags on the first attempt, and only move to after the tags when
22683 the cursor is already beyond the end of the headline."
22684 (interactive "P")
22685 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22686 org-special-ctrl-a/e))
22687 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22688 'end-of-visual-line)
22689 ((fboundp 'move-end-of-line) 'move-end-of-line)
22690 (t 'end-of-line))))
22691 (if (or (not special) arg) (call-interactively move-fun)
22692 (let* ((element (save-excursion (beginning-of-line)
22693 (org-element-at-point)))
22694 (type (org-element-type element)))
22695 (cond
22696 ((memq type '(headline inlinetask))
22697 (let ((pos (point)))
22698 (beginning-of-line 1)
22699 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22700 (if (eq special t)
22701 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22702 (goto-char (match-beginning 1))
22703 (goto-char (match-end 0)))
22704 (if (or (< pos (match-end 0))
22705 (not (eq this-command last-command)))
22706 (goto-char (match-end 0))
22707 (goto-char (match-beginning 1))))
22708 (call-interactively move-fun))))
22709 ((org-element-property :hiddenp element)
22710 ;; If element is hidden, `move-end-of-line' would put point
22711 ;; after it. Use `end-of-line' to stay on current line.
22712 (call-interactively 'end-of-line))
22713 (t (call-interactively move-fun)))))
22714 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22715 (setq disable-point-adjustment
22716 (or (not (invisible-p (point)))
22717 (not (invisible-p (max (point-min) (1- (point))))))))
22719 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22720 (define-key org-mode-map "\C-e" 'org-end-of-line)
22722 (defun org-backward-sentence (&optional arg)
22723 "Go to beginning of sentence, or beginning of table field.
22724 This will call `backward-sentence' or `org-table-beginning-of-field',
22725 depending on context."
22726 (interactive "P")
22727 (cond
22728 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22729 (t (call-interactively 'backward-sentence))))
22731 (defun org-forward-sentence (&optional arg)
22732 "Go to end of sentence, or end of table field.
22733 This will call `forward-sentence' or `org-table-end-of-field',
22734 depending on context."
22735 (interactive "P")
22736 (cond
22737 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22738 (t (call-interactively 'forward-sentence))))
22740 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22741 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22743 (defun org-kill-line (&optional arg)
22744 "Kill line, to tags or end of line."
22745 (interactive "P")
22746 (cond
22747 ((or (not org-special-ctrl-k)
22748 (bolp)
22749 (not (org-at-heading-p)))
22750 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22751 org-ctrl-k-protect-subtree)
22752 (if (or (eq org-ctrl-k-protect-subtree 'error)
22753 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22754 (user-error "C-k aborted as it would kill a hidden subtree")))
22755 (call-interactively
22756 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22757 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22758 (kill-region (point) (match-beginning 1))
22759 (org-set-tags nil t))
22760 (t (kill-region (point) (point-at-eol)))))
22762 (define-key org-mode-map "\C-k" 'org-kill-line)
22764 (defun org-yank (&optional arg)
22765 "Yank. If the kill is a subtree, treat it specially.
22766 This command will look at the current kill and check if is a single
22767 subtree, or a series of subtrees[1]. If it passes the test, and if the
22768 cursor is at the beginning of a line or after the stars of a currently
22769 empty headline, then the yank is handled specially. How exactly depends
22770 on the value of the following variables, both set by default.
22772 org-yank-folded-subtrees
22773 When set, the subtree(s) will be folded after insertion, but only
22774 if doing so would now swallow text after the yanked text.
22776 org-yank-adjusted-subtrees
22777 When set, the subtree will be promoted or demoted in order to
22778 fit into the local outline tree structure, which means that the level
22779 will be adjusted so that it becomes the smaller one of the two
22780 *visible* surrounding headings.
22782 Any prefix to this command will cause `yank' to be called directly with
22783 no special treatment. In particular, a simple \\[universal-argument] prefix \
22784 will just
22785 plainly yank the text as it is.
22787 \[1] The test checks if the first non-white line is a heading
22788 and if there are no other headings with fewer stars."
22789 (interactive "P")
22790 (org-yank-generic 'yank arg))
22792 (defun org-yank-generic (command arg)
22793 "Perform some yank-like command.
22795 This function implements the behavior described in the `org-yank'
22796 documentation. However, it has been generalized to work for any
22797 interactive command with similar behavior."
22799 ;; pretend to be command COMMAND
22800 (setq this-command command)
22802 (if arg
22803 (call-interactively command)
22805 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22806 (and (org-kill-is-subtree-p)
22807 (or (bolp)
22808 (and (looking-at "[ \t]*$")
22809 (string-match
22810 "\\`\\*+\\'"
22811 (buffer-substring (point-at-bol) (point)))))))
22812 swallowp)
22813 (cond
22814 ((and subtreep org-yank-folded-subtrees)
22815 (let ((beg (point))
22816 end)
22817 (if (and subtreep org-yank-adjusted-subtrees)
22818 (org-paste-subtree nil nil 'for-yank)
22819 (call-interactively command))
22821 (setq end (point))
22822 (goto-char beg)
22823 (when (and (bolp) subtreep
22824 (not (setq swallowp
22825 (org-yank-folding-would-swallow-text beg end))))
22826 (org-with-limited-levels
22827 (or (looking-at org-outline-regexp)
22828 (re-search-forward org-outline-regexp-bol end t))
22829 (while (and (< (point) end) (looking-at org-outline-regexp))
22830 (hide-subtree)
22831 (org-cycle-show-empty-lines 'folded)
22832 (condition-case nil
22833 (outline-forward-same-level 1)
22834 (error (goto-char end))))))
22835 (when swallowp
22836 (message
22837 "Inserted text not folded because that would swallow text"))
22839 (goto-char end)
22840 (skip-chars-forward " \t\n\r")
22841 (beginning-of-line 1)
22842 (push-mark beg 'nomsg)))
22843 ((and subtreep org-yank-adjusted-subtrees)
22844 (let ((beg (point-at-bol)))
22845 (org-paste-subtree nil nil 'for-yank)
22846 (push-mark beg 'nomsg)))
22848 (call-interactively command))))))
22850 (defun org-yank-folding-would-swallow-text (beg end)
22851 "Would hide-subtree at BEG swallow any text after END?"
22852 (let (level)
22853 (org-with-limited-levels
22854 (save-excursion
22855 (goto-char beg)
22856 (when (or (looking-at org-outline-regexp)
22857 (re-search-forward org-outline-regexp-bol end t))
22858 (setq level (org-outline-level)))
22859 (goto-char end)
22860 (skip-chars-forward " \t\r\n\v\f")
22861 (if (or (eobp)
22862 (and (bolp) (looking-at org-outline-regexp)
22863 (<= (org-outline-level) level)))
22864 nil ; Nothing would be swallowed
22865 t))))) ; something would swallow
22867 (define-key org-mode-map "\C-y" 'org-yank)
22869 (defun org-truely-invisible-p ()
22870 "Check if point is at a character currently not visible.
22871 This version does not only check the character property, but also
22872 `visible-mode'."
22873 ;; Early versions of noutline don't have `outline-invisible-p'.
22874 (if (org-bound-and-true-p visible-mode)
22876 (outline-invisible-p)))
22878 (defun org-invisible-p2 ()
22879 "Check if point is at a character currently not visible."
22880 (save-excursion
22881 (if (and (eolp) (not (bobp))) (backward-char 1))
22882 ;; Early versions of noutline don't have `outline-invisible-p'.
22883 (outline-invisible-p)))
22885 (defun org-back-to-heading (&optional invisible-ok)
22886 "Call `outline-back-to-heading', but provide a better error message."
22887 (condition-case nil
22888 (outline-back-to-heading invisible-ok)
22889 (error (error "Before first headline at position %d in buffer %s"
22890 (point) (current-buffer)))))
22892 (defun org-before-first-heading-p ()
22893 "Before first heading?"
22894 (save-excursion
22895 (end-of-line)
22896 (null (re-search-backward org-outline-regexp-bol nil t))))
22898 (defun org-at-heading-p (&optional ignored)
22899 (outline-on-heading-p t))
22900 ;; Compatibility alias with Org versions < 7.8.03
22901 (defalias 'org-on-heading-p 'org-at-heading-p)
22903 (defun org-at-comment-p nil
22904 "Is cursor in a line starting with a # character?"
22905 (save-excursion
22906 (beginning-of-line)
22907 (looking-at "^#")))
22909 (defun org-at-drawer-p nil
22910 "Is cursor at a drawer keyword?"
22911 (save-excursion
22912 (move-beginning-of-line 1)
22913 (looking-at org-drawer-regexp)))
22915 (defun org-at-block-p nil
22916 "Is cursor at a block keyword?"
22917 (save-excursion
22918 (move-beginning-of-line 1)
22919 (looking-at org-block-regexp)))
22921 (defun org-point-at-end-of-empty-headline ()
22922 "If point is at the end of an empty headline, return t, else nil.
22923 If the heading only contains a TODO keyword, it is still still considered
22924 empty."
22925 (and (looking-at "[ \t]*$")
22926 (when org-todo-line-regexp
22927 (save-excursion
22928 (beginning-of-line 1)
22929 (let ((case-fold-search nil))
22930 (looking-at org-todo-line-regexp)
22931 (string= (match-string 3) ""))))))
22933 (defun org-at-heading-or-item-p ()
22934 (or (org-at-heading-p) (org-at-item-p)))
22936 (defun org-at-target-p ()
22937 (or (org-in-regexp org-radio-target-regexp)
22938 (org-in-regexp org-target-regexp)))
22939 ;; Compatibility alias with Org versions < 7.8.03
22940 (defalias 'org-on-target-p 'org-at-target-p)
22942 (defun org-up-heading-all (arg)
22943 "Move to the heading line of which the present line is a subheading.
22944 This function considers both visible and invisible heading lines.
22945 With argument, move up ARG levels."
22946 (if (fboundp 'outline-up-heading-all)
22947 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22948 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22950 (defun org-up-heading-safe ()
22951 "Move to the heading line of which the present line is a subheading.
22952 This version will not throw an error. It will return the level of the
22953 headline found, or nil if no higher level is found.
22955 Also, this function will be a lot faster than `outline-up-heading',
22956 because it relies on stars being the outline starters. This can really
22957 make a significant difference in outlines with very many siblings."
22958 (let (start-level re)
22959 (org-back-to-heading t)
22960 (setq start-level (funcall outline-level))
22961 (if (equal start-level 1)
22963 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22964 (if (re-search-backward re nil t)
22965 (funcall outline-level)))))
22967 (defun org-first-sibling-p ()
22968 "Is this heading the first child of its parents?"
22969 (interactive)
22970 (let ((re org-outline-regexp-bol)
22971 level l)
22972 (unless (org-at-heading-p t)
22973 (user-error "Not at a heading"))
22974 (setq level (funcall outline-level))
22975 (save-excursion
22976 (if (not (re-search-backward re nil t))
22978 (setq l (funcall outline-level))
22979 (< l level)))))
22981 (defun org-goto-sibling (&optional previous)
22982 "Goto the next sibling, even if it is invisible.
22983 When PREVIOUS is set, go to the previous sibling instead. Returns t
22984 when a sibling was found. When none is found, return nil and don't
22985 move point."
22986 (let ((fun (if previous 're-search-backward 're-search-forward))
22987 (pos (point))
22988 (re org-outline-regexp-bol)
22989 level l)
22990 (when (condition-case nil (org-back-to-heading t) (error nil))
22991 (setq level (funcall outline-level))
22992 (catch 'exit
22993 (or previous (forward-char 1))
22994 (while (funcall fun re nil t)
22995 (setq l (funcall outline-level))
22996 (when (< l level) (goto-char pos) (throw 'exit nil))
22997 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22998 (goto-char pos)
22999 nil))))
23001 (defun org-show-siblings ()
23002 "Show all siblings of the current headline."
23003 (save-excursion
23004 (while (org-goto-sibling) (org-flag-heading nil)))
23005 (save-excursion
23006 (while (org-goto-sibling 'previous)
23007 (org-flag-heading nil))))
23009 (defun org-goto-first-child ()
23010 "Goto the first child, even if it is invisible.
23011 Return t when a child was found. Otherwise don't move point and
23012 return nil."
23013 (let (level (pos (point)) (re org-outline-regexp-bol))
23014 (when (condition-case nil (org-back-to-heading t) (error nil))
23015 (setq level (outline-level))
23016 (forward-char 1)
23017 (if (and (re-search-forward re nil t) (> (outline-level) level))
23018 (progn (goto-char (match-beginning 0)) t)
23019 (goto-char pos) nil))))
23021 (defun org-show-hidden-entry ()
23022 "Show an entry where even the heading is hidden."
23023 (save-excursion
23024 (org-show-entry)))
23026 (defun org-flag-heading (flag &optional entry)
23027 "Flag the current heading. FLAG non-nil means make invisible.
23028 When ENTRY is non-nil, show the entire entry."
23029 (save-excursion
23030 (org-back-to-heading t)
23031 ;; Check if we should show the entire entry
23032 (if entry
23033 (progn
23034 (org-show-entry)
23035 (save-excursion
23036 (and (outline-next-heading)
23037 (org-flag-heading nil))))
23038 (outline-flag-region (max (point-min) (1- (point)))
23039 (save-excursion (outline-end-of-heading) (point))
23040 flag))))
23042 (defun org-get-next-sibling ()
23043 "Move to next heading of the same level, and return point.
23044 If there is no such heading, return nil.
23045 This is like outline-next-sibling, but invisible headings are ok."
23046 (let ((level (funcall outline-level)))
23047 (outline-next-heading)
23048 (while (and (not (eobp)) (> (funcall outline-level) level))
23049 (outline-next-heading))
23050 (if (or (eobp) (< (funcall outline-level) level))
23052 (point))))
23054 (defun org-get-last-sibling ()
23055 "Move to previous heading of the same level, and return point.
23056 If there is no such heading, return nil."
23057 (let ((opoint (point))
23058 (level (funcall outline-level)))
23059 (outline-previous-heading)
23060 (when (and (/= (point) opoint) (outline-on-heading-p t))
23061 (while (and (> (funcall outline-level) level)
23062 (not (bobp)))
23063 (outline-previous-heading))
23064 (if (< (funcall outline-level) level)
23066 (point)))))
23068 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23069 "Goto to the end of a subtree."
23070 ;; This contains an exact copy of the original function, but it uses
23071 ;; `org-back-to-heading', to make it work also in invisible
23072 ;; trees. And is uses an invisible-ok argument.
23073 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23074 ;; Furthermore, when used inside Org, finding the end of a large subtree
23075 ;; with many children and grandchildren etc, this can be much faster
23076 ;; than the outline version.
23077 (org-back-to-heading invisible-ok)
23078 (let ((first t)
23079 (level (funcall outline-level)))
23080 (if (and (derived-mode-p 'org-mode) (< level 1000))
23081 ;; A true heading (not a plain list item), in Org-mode
23082 ;; This means we can easily find the end by looking
23083 ;; only for the right number of stars. Using a regexp to do
23084 ;; this is so much faster than using a Lisp loop.
23085 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23086 (forward-char 1)
23087 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23088 ;; something else, do it the slow way
23089 (while (and (not (eobp))
23090 (or first (> (funcall outline-level) level)))
23091 (setq first nil)
23092 (outline-next-heading)))
23093 (unless to-heading
23094 (if (memq (preceding-char) '(?\n ?\^M))
23095 (progn
23096 ;; Go to end of line before heading
23097 (forward-char -1)
23098 (if (memq (preceding-char) '(?\n ?\^M))
23099 ;; leave blank line before heading
23100 (forward-char -1))))))
23101 (point))
23103 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23104 "Use Org version in org-mode, for dramatic speed-up."
23105 (if (derived-mode-p 'org-mode)
23106 (progn
23107 (org-end-of-subtree nil t)
23108 (unless (eobp) (backward-char 1)))
23109 ad-do-it))
23111 (defun org-end-of-meta-data-and-drawers ()
23112 "Jump to the first text after meta data and drawers in the current entry.
23113 This will move over empty lines, lines with planning time stamps,
23114 clocking lines, and drawers."
23115 (org-back-to-heading t)
23116 (let ((end (save-excursion (outline-next-heading) (point)))
23117 (re (concat "\\(" org-drawer-regexp "\\)"
23118 "\\|" "[ \t]*" org-keyword-time-regexp)))
23119 (forward-line 1)
23120 (while (re-search-forward re end t)
23121 (if (not (match-end 1))
23122 ;; empty or planning line
23123 (forward-line 1)
23124 ;; a drawer, find the end
23125 (re-search-forward "^[ \t]*:END:" end 'move)
23126 (forward-line 1)))
23127 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23128 (point)))
23130 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23131 "Move forward to the ARG'th subheading at same level as this one.
23132 Stop at the first and last subheadings of a superior heading.
23133 Normally this only looks at visible headings, but when INVISIBLE-OK is
23134 non-nil it will also look at invisible ones."
23135 (interactive "p")
23136 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23137 (if (and arg (< arg 0))
23138 (goto-char (point-min))
23139 (outline-next-heading))
23140 (org-at-heading-p)
23141 (let ((level (- (match-end 0) (match-beginning 0) 1))
23142 (f (if (and arg (< arg 0))
23143 're-search-backward
23144 're-search-forward))
23145 (count (if arg (abs arg) 1))
23146 (result (point)))
23147 (while (and (prog1 (> count 0)
23148 (forward-char (if (and arg (< arg 0)) -1 1)))
23149 (funcall f org-outline-regexp-bol nil 'move))
23150 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23151 (cond ((< l level) (setq count 0))
23152 ((and (= l level)
23153 (or invisible-ok
23154 (progn
23155 (goto-char (line-beginning-position))
23156 (not (outline-invisible-p)))))
23157 (setq count (1- count))
23158 (when (eq l level)
23159 (setq result (point)))))))
23160 (goto-char result))
23161 (beginning-of-line 1)))
23163 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23164 "Move backward to the ARG'th subheading at same level as this one.
23165 Stop at the first and last subheadings of a superior heading."
23166 (interactive "p")
23167 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23169 (defun org-next-block (arg &optional backward block-regexp)
23170 "Jump to the next block.
23171 With a prefix argument ARG, jump forward ARG many source blocks.
23172 When BACKWARD is non-nil, jump to the previous block.
23173 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23174 (interactive "p")
23175 (let ((re (or block-regexp org-block-regexp))
23176 (re-search-fn (or (and backward 're-search-backward)
23177 're-search-forward)))
23178 (if (looking-at re) (forward-char 1))
23179 (condition-case nil
23180 (funcall re-search-fn re nil nil arg)
23181 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23182 (goto-char (match-beginning 0)) (org-show-context)))
23184 (defun org-previous-block (arg &optional block-regexp)
23185 "Jump to the previous block.
23186 With a prefix argument ARG, jump backward ARG many source blocks.
23187 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23188 (interactive "p")
23189 (org-next-block arg t block-regexp))
23191 (defun org-forward-element ()
23192 "Move forward by one element.
23193 Move to the next element at the same level, when possible."
23194 (interactive)
23195 (cond ((eobp) (user-error "Cannot move further down"))
23196 ((org-with-limited-levels (org-at-heading-p))
23197 (let ((origin (point)))
23198 (goto-char (org-end-of-subtree nil t))
23199 (unless (org-with-limited-levels (org-at-heading-p))
23200 (goto-char origin)
23201 (user-error "Cannot move further down"))))
23203 (let* ((elem (org-element-at-point))
23204 (end (org-element-property :end elem))
23205 (parent (org-element-property :parent elem)))
23206 (if (and parent (= (org-element-property :contents-end parent) end))
23207 (goto-char (org-element-property :end parent))
23208 (goto-char end))))))
23210 (defun org-backward-element ()
23211 "Move backward by one element.
23212 Move to the previous element at the same level, when possible."
23213 (interactive)
23214 (cond ((bobp) (user-error "Cannot move further up"))
23215 ((org-with-limited-levels (org-at-heading-p))
23216 ;; At a headline, move to the previous one, if any, or stay
23217 ;; here.
23218 (let ((origin (point)))
23219 (org-with-limited-levels (org-backward-heading-same-level 1))
23220 ;; When current headline has no sibling above, move to its
23221 ;; parent.
23222 (when (= (point) origin)
23223 (or (org-with-limited-levels (org-up-heading-safe))
23224 (progn (goto-char origin)
23225 (user-error "Cannot move further up"))))))
23227 (let* ((trail (org-element-at-point 'keep-trail))
23228 (elem (car trail))
23229 (prev-elem (nth 1 trail))
23230 (beg (org-element-property :begin elem)))
23231 (cond
23232 ;; Move to beginning of current element if point isn't
23233 ;; there already.
23234 ((/= (point) beg) (goto-char beg))
23235 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23236 ((org-before-first-heading-p) (goto-char (point-min)))
23237 (t (org-back-to-heading)))))))
23239 (defun org-up-element ()
23240 "Move to upper element."
23241 (interactive)
23242 (if (org-with-limited-levels (org-at-heading-p))
23243 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23244 (let* ((elem (org-element-at-point))
23245 (parent (org-element-property :parent elem)))
23246 (if parent (goto-char (org-element-property :begin parent))
23247 (if (org-with-limited-levels (org-before-first-heading-p))
23248 (user-error "No surrounding element")
23249 (org-with-limited-levels (org-back-to-heading)))))))
23251 (defvar org-element-greater-elements)
23252 (defun org-down-element ()
23253 "Move to inner element."
23254 (interactive)
23255 (let ((element (org-element-at-point)))
23256 (cond
23257 ((memq (org-element-type element) '(plain-list table))
23258 (goto-char (org-element-property :contents-begin element))
23259 (forward-char))
23260 ((memq (org-element-type element) org-element-greater-elements)
23261 ;; If contents are hidden, first disclose them.
23262 (when (org-element-property :hiddenp element) (org-cycle))
23263 (goto-char (or (org-element-property :contents-begin element)
23264 (user-error "No content for this element"))))
23265 (t (user-error "No inner element")))))
23267 (defun org-drag-element-backward ()
23268 "Move backward element at point."
23269 (interactive)
23270 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23271 (let* ((trail (org-element-at-point 'keep-trail))
23272 (elem (car trail))
23273 (prev-elem (nth 1 trail)))
23274 ;; Error out if no previous element or previous element is
23275 ;; a parent of the current one.
23276 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23277 (user-error "Cannot drag element backward")
23278 (let ((pos (point)))
23279 (org-element-swap-A-B prev-elem elem)
23280 (goto-char (+ (org-element-property :begin prev-elem)
23281 (- pos (org-element-property :begin elem)))))))))
23283 (defun org-drag-element-forward ()
23284 "Move forward element at point."
23285 (interactive)
23286 (let* ((pos (point))
23287 (elem (org-element-at-point)))
23288 (when (= (point-max) (org-element-property :end elem))
23289 (user-error "Cannot drag element forward"))
23290 (goto-char (org-element-property :end elem))
23291 (let ((next-elem (org-element-at-point)))
23292 (when (or (org-element-nested-p elem next-elem)
23293 (and (eq (org-element-type next-elem) 'headline)
23294 (not (eq (org-element-type elem) 'headline))))
23295 (goto-char pos)
23296 (user-error "Cannot drag element forward"))
23297 ;; Compute new position of point: it's shifted by NEXT-ELEM
23298 ;; body's length (without final blanks) and by the length of
23299 ;; blanks between ELEM and NEXT-ELEM.
23300 (let ((size-next (- (save-excursion
23301 (goto-char (org-element-property :end next-elem))
23302 (skip-chars-backward " \r\t\n")
23303 (forward-line)
23304 ;; Small correction if buffer doesn't end
23305 ;; with a newline character.
23306 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23307 (org-element-property :begin next-elem)))
23308 (size-blank (- (org-element-property :end elem)
23309 (save-excursion
23310 (goto-char (org-element-property :end elem))
23311 (skip-chars-backward " \r\t\n")
23312 (forward-line)
23313 (point)))))
23314 (org-element-swap-A-B elem next-elem)
23315 (goto-char (+ pos size-next size-blank))))))
23317 (defun org-drag-line-forward (arg)
23318 "Drag the line at point ARG lines forward."
23319 (interactive "p")
23320 (dotimes (n (abs arg))
23321 (let ((c (current-column)))
23322 (if (< 0 arg)
23323 (progn
23324 (beginning-of-line 2)
23325 (transpose-lines 1)
23326 (beginning-of-line 0))
23327 (transpose-lines 1)
23328 (beginning-of-line -1))
23329 (org-move-to-column c))))
23331 (defun org-drag-line-backward (arg)
23332 "Drag the line at point ARG lines backward."
23333 (interactive "p")
23334 (org-drag-line-forward (- arg)))
23336 (defun org-mark-element ()
23337 "Put point at beginning of this element, mark at end.
23339 Interactively, if this command is repeated or (in Transient Mark
23340 mode) if the mark is active, it marks the next element after the
23341 ones already marked."
23342 (interactive)
23343 (let (deactivate-mark)
23344 (if (and (org-called-interactively-p 'any)
23345 (or (and (eq last-command this-command) (mark t))
23346 (and transient-mark-mode mark-active)))
23347 (set-mark
23348 (save-excursion
23349 (goto-char (mark))
23350 (goto-char (org-element-property :end (org-element-at-point)))))
23351 (let ((element (org-element-at-point)))
23352 (end-of-line)
23353 (push-mark (org-element-property :end element) t t)
23354 (goto-char (org-element-property :begin element))))))
23356 (defun org-narrow-to-element ()
23357 "Narrow buffer to current element."
23358 (interactive)
23359 (let ((elem (org-element-at-point)))
23360 (cond
23361 ((eq (car elem) 'headline)
23362 (narrow-to-region
23363 (org-element-property :begin elem)
23364 (org-element-property :end elem)))
23365 ((memq (car elem) org-element-greater-elements)
23366 (narrow-to-region
23367 (org-element-property :contents-begin elem)
23368 (org-element-property :contents-end elem)))
23370 (narrow-to-region
23371 (org-element-property :begin elem)
23372 (org-element-property :end elem))))))
23374 (defun org-transpose-element ()
23375 "Transpose current and previous elements, keeping blank lines between.
23376 Point is moved after both elements."
23377 (interactive)
23378 (org-skip-whitespace)
23379 (let ((end (org-element-property :end (org-element-at-point))))
23380 (org-drag-element-backward)
23381 (goto-char end)))
23383 (defun org-unindent-buffer ()
23384 "Un-indent the visible part of the buffer.
23385 Relative indentation (between items, inside blocks, etc.) isn't
23386 modified."
23387 (interactive)
23388 (unless (eq major-mode 'org-mode)
23389 (user-error "Cannot un-indent a buffer not in Org mode"))
23390 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23391 unindent-tree ; For byte-compiler.
23392 (unindent-tree
23393 (function
23394 (lambda (contents)
23395 (mapc
23396 (lambda (element)
23397 (if (memq (org-element-type element) '(headline section))
23398 (funcall unindent-tree (org-element-contents element))
23399 (save-excursion
23400 (save-restriction
23401 (narrow-to-region
23402 (org-element-property :begin element)
23403 (org-element-property :end element))
23404 (org-do-remove-indentation)))))
23405 (reverse contents))))))
23406 (funcall unindent-tree (org-element-contents parse-tree))))
23408 (defun org-show-subtree ()
23409 "Show everything after this heading at deeper levels."
23410 (interactive)
23411 (outline-flag-region
23412 (point)
23413 (save-excursion
23414 (org-end-of-subtree t t))
23415 nil))
23417 (defun org-show-entry ()
23418 "Show the body directly following this heading.
23419 Show the heading too, if it is currently invisible."
23420 (interactive)
23421 (save-excursion
23422 (condition-case nil
23423 (progn
23424 (org-back-to-heading t)
23425 (outline-flag-region
23426 (max (point-min) (1- (point)))
23427 (save-excursion
23428 (if (re-search-forward
23429 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23430 (match-beginning 1)
23431 (point-max)))
23432 nil)
23433 (org-cycle-hide-drawers 'children))
23434 (error nil))))
23436 (defun org-make-options-regexp (kwds &optional extra)
23437 "Make a regular expression for keyword lines."
23438 (concat
23439 "^#\\+\\("
23440 (mapconcat 'regexp-quote kwds "\\|")
23441 (if extra (concat "\\|" extra))
23442 "\\):[ \t]*\\(.*\\)"))
23444 ;; Make isearch reveal the necessary context
23445 (defun org-isearch-end ()
23446 "Reveal context after isearch exits."
23447 (when isearch-success ; only if search was successful
23448 (if (featurep 'xemacs)
23449 ;; Under XEmacs, the hook is run in the correct place,
23450 ;; we directly show the context.
23451 (org-show-context 'isearch)
23452 ;; In Emacs the hook runs *before* restoring the overlays.
23453 ;; So we have to use a one-time post-command-hook to do this.
23454 ;; (Emacs 22 has a special variable, see function `org-mode')
23455 (unless (and (boundp 'isearch-mode-end-hook-quit)
23456 isearch-mode-end-hook-quit)
23457 ;; Only when the isearch was not quitted.
23458 (org-add-hook 'post-command-hook 'org-isearch-post-command
23459 'append 'local)))
23460 (org-fix-ellipsis-at-bol)))
23462 (defun org-isearch-post-command ()
23463 "Remove self from hook, and show context."
23464 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23465 (org-show-context 'isearch))
23468 ;;;; Integration with and fixes for other packages
23470 ;;; Imenu support
23472 (defvar org-imenu-markers nil
23473 "All markers currently used by Imenu.")
23474 (make-variable-buffer-local 'org-imenu-markers)
23476 (defun org-imenu-new-marker (&optional pos)
23477 "Return a new marker for use by Imenu, and remember the marker."
23478 (let ((m (make-marker)))
23479 (move-marker m (or pos (point)))
23480 (push m org-imenu-markers)
23483 (defun org-imenu-get-tree ()
23484 "Produce the index for Imenu."
23485 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23486 (setq org-imenu-markers nil)
23487 (let* ((n org-imenu-depth)
23488 (re (concat "^" (org-get-limited-outline-regexp)))
23489 (subs (make-vector (1+ n) nil))
23490 (last-level 0)
23491 m level head0 head)
23492 (save-excursion
23493 (save-restriction
23494 (widen)
23495 (goto-char (point-max))
23496 (while (re-search-backward re nil t)
23497 (setq level (org-reduced-level (funcall outline-level)))
23498 (when (and (<= level n)
23499 (looking-at org-complex-heading-regexp)
23500 (setq head0 (org-match-string-no-properties 4)))
23501 (setq head (org-link-display-format head0)
23502 m (org-imenu-new-marker))
23503 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23504 (if (>= level last-level)
23505 (push (cons head m) (aref subs level))
23506 (push (cons head (aref subs (1+ level))) (aref subs level))
23507 (loop for i from (1+ level) to n do (aset subs i nil)))
23508 (setq last-level level)))))
23509 (aref subs 1)))
23511 (eval-after-load "imenu"
23512 '(progn
23513 (add-hook 'imenu-after-jump-hook
23514 (lambda ()
23515 (if (derived-mode-p 'org-mode)
23516 (org-show-context 'org-goto))))))
23518 (defun org-link-display-format (link)
23519 "Replace a link with its the description.
23520 If there is no description, use the link target."
23521 (save-match-data
23522 (if (string-match org-bracket-link-analytic-regexp link)
23523 (replace-match (if (match-end 5)
23524 (match-string 5 link)
23525 (concat (match-string 1 link)
23526 (match-string 3 link)))
23527 nil t link)
23528 link)))
23530 (defun org-toggle-link-display ()
23531 "Toggle the literal or descriptive display of links."
23532 (interactive)
23533 (if org-descriptive-links
23534 (progn (org-remove-from-invisibility-spec '(org-link))
23535 (org-restart-font-lock)
23536 (setq org-descriptive-links nil))
23537 (progn (add-to-invisibility-spec '(org-link))
23538 (org-restart-font-lock)
23539 (setq org-descriptive-links t))))
23541 ;; Speedbar support
23543 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23544 "Overlay marking the agenda restriction line in speedbar.")
23545 (overlay-put org-speedbar-restriction-lock-overlay
23546 'face 'org-agenda-restriction-lock)
23547 (overlay-put org-speedbar-restriction-lock-overlay
23548 'help-echo "Agendas are currently limited to this item.")
23549 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23551 (defun org-speedbar-set-agenda-restriction ()
23552 "Restrict future agenda commands to the location at point in speedbar.
23553 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23554 (interactive)
23555 (require 'org-agenda)
23556 (let (p m tp np dir txt)
23557 (cond
23558 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23559 'org-imenu t))
23560 (setq m (get-text-property p 'org-imenu-marker))
23561 (with-current-buffer (marker-buffer m)
23562 (goto-char m)
23563 (org-agenda-set-restriction-lock 'subtree)))
23564 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23565 'speedbar-function 'speedbar-find-file))
23566 (setq tp (previous-single-property-change
23567 (1+ p) 'speedbar-function)
23568 np (next-single-property-change
23569 tp 'speedbar-function)
23570 dir (speedbar-line-directory)
23571 txt (buffer-substring-no-properties (or tp (point-min))
23572 (or np (point-max))))
23573 (with-current-buffer (find-file-noselect
23574 (let ((default-directory dir))
23575 (expand-file-name txt)))
23576 (unless (derived-mode-p 'org-mode)
23577 (user-error "Cannot restrict to non-Org-mode file"))
23578 (org-agenda-set-restriction-lock 'file)))
23579 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23580 (move-overlay org-speedbar-restriction-lock-overlay
23581 (point-at-bol) (point-at-eol))
23582 (setq current-prefix-arg nil)
23583 (org-agenda-maybe-redo)))
23585 (defvar speedbar-file-key-map)
23586 (declare-function speedbar-add-supported-extension "speedbar" (extension))
23587 (eval-after-load "speedbar"
23588 '(progn
23589 (speedbar-add-supported-extension ".org")
23590 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23591 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23592 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23593 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23594 (add-hook 'speedbar-visiting-tag-hook
23595 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23597 ;;; Fixes and Hacks for problems with other packages
23599 ;; Make flyspell not check words in links, to not mess up our keymap
23600 (defvar org-element-affiliated-keywords) ; From org-element.el
23601 (defvar org-element-block-name-alist) ; From org-element.el
23602 (defun org-mode-flyspell-verify ()
23603 "Don't let flyspell put overlays at active buttons, or on
23604 {todo,all-time,additional-option-like}-keywords."
23605 (require 'org-element) ; For `org-element-affiliated-keywords'
23606 (let ((pos (max (1- (point)) (point-min)))
23607 (word (thing-at-point 'word)))
23608 (and (not (get-text-property pos 'keymap))
23609 (not (get-text-property pos 'org-no-flyspell))
23610 (not (member word org-todo-keywords-1))
23611 (not (member word org-all-time-keywords))
23612 (not (member word org-options-keywords))
23613 (not (member word (mapcar 'car org-startup-options)))
23614 (not (member-ignore-case word org-element-affiliated-keywords))
23615 (not (member-ignore-case word (org-get-export-keywords)))
23616 (not (member-ignore-case
23617 word (mapcar 'car org-element-block-name-alist)))
23618 (not (member-ignore-case word '("BEGIN" "END" "ATTR")))
23619 (not (org-in-src-block-p)))))
23621 (defun org-remove-flyspell-overlays-in (beg end)
23622 "Remove flyspell overlays in region."
23623 (and (org-bound-and-true-p flyspell-mode)
23624 (fboundp 'flyspell-delete-region-overlays)
23625 (flyspell-delete-region-overlays beg end))
23626 (add-text-properties beg end '(org-no-flyspell t)))
23628 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23629 (eval-after-load "bookmark"
23630 '(if (boundp 'bookmark-after-jump-hook)
23631 ;; We can use the hook
23632 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23633 ;; Hook not available, use advice
23634 (defadvice bookmark-jump (after org-make-visible activate)
23635 "Make the position visible."
23636 (org-bookmark-jump-unhide))))
23638 ;; Make sure saveplace shows the location if it was hidden
23639 (eval-after-load "saveplace"
23640 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23641 "Make the position visible."
23642 (org-bookmark-jump-unhide)))
23644 ;; Make sure ecb shows the location if it was hidden
23645 (eval-after-load "ecb"
23646 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23647 "Make hierarchy visible when jumping into location from ECB tree buffer."
23648 (if (derived-mode-p 'org-mode)
23649 (org-show-context))))
23651 (defun org-bookmark-jump-unhide ()
23652 "Unhide the current position, to show the bookmark location."
23653 (and (derived-mode-p 'org-mode)
23654 (or (outline-invisible-p)
23655 (save-excursion (goto-char (max (point-min) (1- (point))))
23656 (outline-invisible-p)))
23657 (org-show-context 'bookmark-jump)))
23659 ;; Make session.el ignore our circular variable
23660 (defvar session-globals-exclude)
23661 (eval-after-load "session"
23662 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23664 ;;;; Finish up
23666 (provide 'org)
23668 (run-hooks 'org-load-hook)
23670 ;;; org.el ends here