ox: Fix "Wrong argument type" error when attributes start with :key ""
[org-mode/org-tableheadings.git] / lisp / org.el
blobb9e6d9e95d211ad55ef692f7ddee44c40974f4c1
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 '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 '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 gnus)
1771 (choice
1772 (const gnus)
1773 (const gnus-other-frame)
1774 (const org-gnus-no-new-news)))
1775 (cons (const file)
1776 (choice
1777 (const find-file)
1778 (const find-file-other-window)
1779 (const find-file-other-frame)))
1780 (cons (const wl)
1781 (choice
1782 (const wl)
1783 (const wl-other-frame)))))
1785 (defcustom org-display-internal-link-with-indirect-buffer nil
1786 "Non-nil means use indirect buffer to display infile links.
1787 Activating internal links (from one location in a file to another location
1788 in the same file) normally just jumps to the location. When the link is
1789 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1790 is displayed in
1791 another window. When this option is set, the other window actually displays
1792 an indirect buffer clone of the current buffer, to avoid any visibility
1793 changes to the current buffer."
1794 :group 'org-link-follow
1795 :type 'boolean)
1797 (defcustom org-open-non-existing-files nil
1798 "Non-nil means `org-open-file' will open non-existing files.
1799 When nil, an error will be generated.
1800 This variable applies only to external applications because they
1801 might choke on non-existing files. If the link is to a file that
1802 will be opened in Emacs, the variable is ignored."
1803 :group 'org-link-follow
1804 :type 'boolean)
1806 (defcustom org-open-directory-means-index-dot-org nil
1807 "Non-nil means a link to a directory really means to index.org.
1808 When nil, following a directory link will run dired or open a finder/explorer
1809 window on that directory."
1810 :group 'org-link-follow
1811 :type 'boolean)
1813 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1814 "Function and arguments to call for following mailto links.
1815 This is a list with the first element being a Lisp function, and the
1816 remaining elements being arguments to the function. In string arguments,
1817 %a will be replaced by the address, and %s will be replaced by the subject
1818 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1819 :group 'org-link-follow
1820 :type '(choice
1821 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1822 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1823 (const :tag "message-mail" (message-mail "%a" "%s"))
1824 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1826 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1827 "Non-nil means ask for confirmation before executing shell links.
1828 Shell links can be dangerous: just think about a link
1830 [[shell:rm -rf ~/*][Google Search]]
1832 This link would show up in your Org-mode document as \"Google Search\",
1833 but really it would remove your entire home directory.
1834 Therefore we advise against setting this variable to nil.
1835 Just change it to `y-or-n-p' if you want to confirm with a
1836 single keystroke rather than having to type \"yes\"."
1837 :group 'org-link-follow
1838 :type '(choice
1839 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1840 (const :tag "with y-or-n (faster)" y-or-n-p)
1841 (const :tag "no confirmation (dangerous)" nil)))
1842 (put 'org-confirm-shell-link-function
1843 'safe-local-variable
1844 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1846 (defcustom org-confirm-shell-link-not-regexp ""
1847 "A regexp to skip confirmation for shell links."
1848 :group 'org-link-follow
1849 :version "24.1"
1850 :type 'regexp)
1852 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1853 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1854 Elisp links can be dangerous: just think about a link
1856 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1858 This link would show up in your Org-mode document as \"Google Search\",
1859 but really it would remove your entire home directory.
1860 Therefore we advise against setting this variable to nil.
1861 Just change it to `y-or-n-p' if you want to confirm with a
1862 single keystroke rather than having to type \"yes\"."
1863 :group 'org-link-follow
1864 :type '(choice
1865 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1866 (const :tag "with y-or-n (faster)" y-or-n-p)
1867 (const :tag "no confirmation (dangerous)" nil)))
1868 (put 'org-confirm-shell-link-function
1869 'safe-local-variable
1870 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1872 (defcustom org-confirm-elisp-link-not-regexp ""
1873 "A regexp to skip confirmation for Elisp links."
1874 :group 'org-link-follow
1875 :version "24.1"
1876 :type 'regexp)
1878 (defconst org-file-apps-defaults-gnu
1879 '((remote . emacs)
1880 (system . mailcap)
1881 (t . mailcap))
1882 "Default file applications on a UNIX or GNU/Linux system.
1883 See `org-file-apps'.")
1885 (defconst org-file-apps-defaults-macosx
1886 '((remote . emacs)
1887 (t . "open %s")
1888 (system . "open %s")
1889 ("ps.gz" . "gv %s")
1890 ("eps.gz" . "gv %s")
1891 ("dvi" . "xdvi %s")
1892 ("fig" . "xfig %s"))
1893 "Default file applications on a MacOS X system.
1894 The system \"open\" is known as a default, but we use X11 applications
1895 for some files for which the OS does not have a good default.
1896 See `org-file-apps'.")
1898 (defconst org-file-apps-defaults-windowsnt
1899 (list
1900 '(remote . emacs)
1901 (cons t
1902 (list (if (featurep 'xemacs)
1903 'mswindows-shell-execute
1904 'w32-shell-execute)
1905 "open" 'file))
1906 (cons 'system
1907 (list (if (featurep 'xemacs)
1908 'mswindows-shell-execute
1909 'w32-shell-execute)
1910 "open" 'file)))
1911 "Default file applications on a Windows NT system.
1912 The system \"open\" is used for most files.
1913 See `org-file-apps'.")
1915 (defcustom org-file-apps
1916 '((auto-mode . emacs)
1917 ("\\.mm\\'" . default)
1918 ("\\.x?html?\\'" . default)
1919 ("\\.pdf\\'" . default))
1920 "External applications for opening `file:path' items in a document.
1921 Org-mode uses system defaults for different file types, but
1922 you can use this variable to set the application for a given file
1923 extension. The entries in this list are cons cells where the car identifies
1924 files and the cdr the corresponding command. Possible values for the
1925 file identifier are
1926 \"string\" A string as a file identifier can be interpreted in different
1927 ways, depending on its contents:
1929 - Alphanumeric characters only:
1930 Match links with this file extension.
1931 Example: (\"pdf\" . \"evince %s\")
1932 to open PDFs with evince.
1934 - Regular expression: Match links where the
1935 filename matches the regexp. If you want to
1936 use groups here, use shy groups.
1938 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1939 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1940 to open *.html and *.xhtml with firefox.
1942 - Regular expression which contains (non-shy) groups:
1943 Match links where the whole link, including \"::\", and
1944 anything after that, matches the regexp.
1945 In a custom command string, %1, %2, etc. are replaced with
1946 the parts of the link that were matched by the groups.
1947 For backwards compatibility, if a command string is given
1948 that does not use any of the group matches, this case is
1949 handled identically to the second one (i.e. match against
1950 file name only).
1951 In a custom lisp form, you can access the group matches with
1952 (match-string n link).
1954 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1955 to open [[file:document.pdf::5]] with evince at page 5.
1957 `directory' Matches a directory
1958 `remote' Matches a remote file, accessible through tramp or efs.
1959 Remote files most likely should be visited through Emacs
1960 because external applications cannot handle such paths.
1961 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1962 so all files Emacs knows how to handle. Using this with
1963 command `emacs' will open most files in Emacs. Beware that this
1964 will also open html files inside Emacs, unless you add
1965 (\"html\" . default) to the list as well.
1966 t Default for files not matched by any of the other options.
1967 `system' The system command to open files, like `open' on Windows
1968 and Mac OS X, and mailcap under GNU/Linux. This is the command
1969 that will be selected if you call `C-c C-o' with a double
1970 \\[universal-argument] \\[universal-argument] prefix.
1972 Possible values for the command are:
1973 `emacs' The file will be visited by the current Emacs process.
1974 `default' Use the default application for this file type, which is the
1975 association for t in the list, most likely in the system-specific
1976 part.
1977 This can be used to overrule an unwanted setting in the
1978 system-specific variable.
1979 `system' Use the system command for opening files, like \"open\".
1980 This command is specified by the entry whose car is `system'.
1981 Most likely, the system-specific version of this variable
1982 does define this command, but you can overrule/replace it
1983 here.
1984 string A command to be executed by a shell; %s will be replaced
1985 by the path to the file.
1986 sexp A Lisp form which will be evaluated. The file path will
1987 be available in the Lisp variable `file'.
1988 For more examples, see the system specific constants
1989 `org-file-apps-defaults-macosx'
1990 `org-file-apps-defaults-windowsnt'
1991 `org-file-apps-defaults-gnu'."
1992 :group 'org-link-follow
1993 :type '(repeat
1994 (cons (choice :value ""
1995 (string :tag "Extension")
1996 (const :tag "System command to open files" system)
1997 (const :tag "Default for unrecognized files" t)
1998 (const :tag "Remote file" remote)
1999 (const :tag "Links to a directory" directory)
2000 (const :tag "Any files that have Emacs modes"
2001 auto-mode))
2002 (choice :value ""
2003 (const :tag "Visit with Emacs" emacs)
2004 (const :tag "Use default" default)
2005 (const :tag "Use the system command" system)
2006 (string :tag "Command")
2007 (sexp :tag "Lisp form")))))
2009 (defcustom org-doi-server-url "http://dx.doi.org/"
2010 "The URL of the DOI server."
2011 :type 'string
2012 :version "24.3"
2013 :group 'org-link-follow)
2015 (defgroup org-refile nil
2016 "Options concerning refiling entries in Org-mode."
2017 :tag "Org Refile"
2018 :group 'org)
2020 (defcustom org-directory "~/org"
2021 "Directory with org files.
2022 This is just a default location to look for Org files. There is no need
2023 at all to put your files into this directory. It is only used in the
2024 following situations:
2026 1. When a capture template specifies a target file that is not an
2027 absolute path. The path will then be interpreted relative to
2028 `org-directory'
2029 2. When a capture note is filed away in an interactive way (when exiting the
2030 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2031 with `org-directory' as the default path."
2032 :group 'org-refile
2033 :group 'org-remember
2034 :group 'org-capture
2035 :type 'directory)
2037 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2038 "Default target for storing notes.
2039 Used as a fall back file for org-remember.el and org-capture.el, for
2040 templates that do not specify a target file."
2041 :group 'org-refile
2042 :group 'org-remember
2043 :group 'org-capture
2044 :type '(choice
2045 (const :tag "Default from remember-data-file" nil)
2046 file))
2048 (defcustom org-goto-interface 'outline
2049 "The default interface to be used for `org-goto'.
2050 Allowed values are:
2051 outline The interface shows an outline of the relevant file
2052 and the correct heading is found by moving through
2053 the outline or by searching with incremental search.
2054 outline-path-completion Headlines in the current buffer are offered via
2055 completion. This is the interface also used by
2056 the refile command."
2057 :group 'org-refile
2058 :type '(choice
2059 (const :tag "Outline" outline)
2060 (const :tag "Outline-path-completion" outline-path-completion)))
2062 (defcustom org-goto-max-level 5
2063 "Maximum target level when running `org-goto' with refile interface."
2064 :group 'org-refile
2065 :type 'integer)
2067 (defcustom org-reverse-note-order nil
2068 "Non-nil means store new notes at the beginning of a file or entry.
2069 When nil, new notes will be filed to the end of a file or entry.
2070 This can also be a list with cons cells of regular expressions that
2071 are matched against file names, and values."
2072 :group 'org-remember
2073 :group 'org-capture
2074 :group 'org-refile
2075 :type '(choice
2076 (const :tag "Reverse always" t)
2077 (const :tag "Reverse never" nil)
2078 (repeat :tag "By file name regexp"
2079 (cons regexp boolean))))
2081 (defcustom org-log-refile nil
2082 "Information to record when a task is refiled.
2084 Possible values are:
2086 nil Don't add anything
2087 time Add a time stamp to the task
2088 note Prompt for a note and add it with template `org-log-note-headings'
2090 This option can also be set with on a per-file-basis with
2092 #+STARTUP: nologrefile
2093 #+STARTUP: logrefile
2094 #+STARTUP: lognoterefile
2096 You can have local logging settings for a subtree by setting the LOGGING
2097 property to one or more of these keywords.
2099 When bulk-refiling from the agenda, the value `note' is forbidden and
2100 will temporarily be changed to `time'."
2101 :group 'org-refile
2102 :group 'org-progress
2103 :version "24.1"
2104 :type '(choice
2105 (const :tag "No logging" nil)
2106 (const :tag "Record timestamp" time)
2107 (const :tag "Record timestamp with note." note)))
2109 (defcustom org-refile-targets nil
2110 "Targets for refiling entries with \\[org-refile].
2111 This is a list of cons cells. Each cell contains:
2112 - a specification of the files to be considered, either a list of files,
2113 or a symbol whose function or variable value will be used to retrieve
2114 a file name or a list of file names. If you use `org-agenda-files' for
2115 that, all agenda files will be scanned for targets. Nil means consider
2116 headings in the current buffer.
2117 - A specification of how to find candidate refile targets. This may be
2118 any of:
2119 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2120 This tag has to be present in all target headlines, inheritance will
2121 not be considered.
2122 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2123 todo keyword.
2124 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2125 headlines that are refiling targets.
2126 - a cons cell (:level . N). Any headline of level N is considered a target.
2127 Note that, when `org-odd-levels-only' is set, level corresponds to
2128 order in hierarchy, not to the number of stars.
2129 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2130 Note that, when `org-odd-levels-only' is set, level corresponds to
2131 order in hierarchy, not to the number of stars.
2133 Each element of this list generates a set of possible targets.
2134 The union of these sets is presented (with completion) to
2135 the user by `org-refile'.
2137 You can set the variable `org-refile-target-verify-function' to a function
2138 to verify each headline found by the simple criteria above.
2140 When this variable is nil, all top-level headlines in the current buffer
2141 are used, equivalent to the value `((nil . (:level . 1))'."
2142 :group 'org-refile
2143 :type '(repeat
2144 (cons
2145 (choice :value org-agenda-files
2146 (const :tag "All agenda files" org-agenda-files)
2147 (const :tag "Current buffer" nil)
2148 (function) (variable) (file))
2149 (choice :tag "Identify target headline by"
2150 (cons :tag "Specific tag" (const :value :tag) (string))
2151 (cons :tag "TODO keyword" (const :value :todo) (string))
2152 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2153 (cons :tag "Level number" (const :value :level) (integer))
2154 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2156 (defcustom org-refile-target-verify-function nil
2157 "Function to verify if the headline at point should be a refile target.
2158 The function will be called without arguments, with point at the
2159 beginning of the headline. It should return t and leave point
2160 where it is if the headline is a valid target for refiling.
2162 If the target should not be selected, the function must return nil.
2163 In addition to this, it may move point to a place from where the search
2164 should be continued. For example, the function may decide that the entire
2165 subtree of the current entry should be excluded and move point to the end
2166 of the subtree."
2167 :group 'org-refile
2168 :type 'function)
2170 (defcustom org-refile-use-cache nil
2171 "Non-nil means cache refile targets to speed up the process.
2172 The cache for a particular file will be updated automatically when
2173 the buffer has been killed, or when any of the marker used for flagging
2174 refile targets no longer points at a live buffer.
2175 If you have added new entries to a buffer that might themselves be targets,
2176 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2177 find that easier, `C-u C-u C-u C-c C-w'."
2178 :group 'org-refile
2179 :version "24.1"
2180 :type 'boolean)
2182 (defcustom org-refile-use-outline-path nil
2183 "Non-nil means provide refile targets as paths.
2184 So a level 3 headline will be available as level1/level2/level3.
2186 When the value is `file', also include the file name (without directory)
2187 into the path. In this case, you can also stop the completion after
2188 the file name, to get entries inserted as top level in the file.
2190 When `full-file-path', include the full file path."
2191 :group 'org-refile
2192 :type '(choice
2193 (const :tag "Not" nil)
2194 (const :tag "Yes" t)
2195 (const :tag "Start with file name" file)
2196 (const :tag "Start with full file path" full-file-path)))
2198 (defcustom org-outline-path-complete-in-steps t
2199 "Non-nil means complete the outline path in hierarchical steps.
2200 When Org-mode uses the refile interface to select an outline path
2201 \(see variable `org-refile-use-outline-path'), the completion of
2202 the path can be done is a single go, or if can be done in steps down
2203 the headline hierarchy. Going in steps is probably the best if you
2204 do not use a special completion package like `ido' or `icicles'.
2205 However, when using these packages, going in one step can be very
2206 fast, while still showing the whole path to the entry."
2207 :group 'org-refile
2208 :type 'boolean)
2210 (defcustom org-refile-allow-creating-parent-nodes nil
2211 "Non-nil means allow to create new nodes as refile targets.
2212 New nodes are then created by adding \"/new node name\" to the completion
2213 of an existing node. When the value of this variable is `confirm',
2214 new node creation must be confirmed by the user (recommended)
2215 When nil, the completion must match an existing entry.
2217 Note that, if the new heading is not seen by the criteria
2218 listed in `org-refile-targets', multiple instances of the same
2219 heading would be created by trying again to file under the new
2220 heading."
2221 :group 'org-refile
2222 :type '(choice
2223 (const :tag "Never" nil)
2224 (const :tag "Always" t)
2225 (const :tag "Prompt for confirmation" confirm)))
2227 (defcustom org-refile-active-region-within-subtree nil
2228 "Non-nil means also refile active region within a subtree.
2230 By default `org-refile' doesn't allow refiling regions if they
2231 don't contain a set of subtrees, but it might be convenient to
2232 do so sometimes: in that case, the first line of the region is
2233 converted to a headline before refiling."
2234 :group 'org-refile
2235 :version "24.1"
2236 :type 'boolean)
2238 (defgroup org-todo nil
2239 "Options concerning TODO items in Org-mode."
2240 :tag "Org TODO"
2241 :group 'org)
2243 (defgroup org-progress nil
2244 "Options concerning Progress logging in Org-mode."
2245 :tag "Org Progress"
2246 :group 'org-time)
2248 (defvar org-todo-interpretation-widgets
2249 '((:tag "Sequence (cycling hits every state)" sequence)
2250 (:tag "Type (cycling directly to DONE)" type))
2251 "The available interpretation symbols for customizing `org-todo-keywords'.
2252 Interested libraries should add to this list.")
2254 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2255 "List of TODO entry keyword sequences and their interpretation.
2256 \\<org-mode-map>This is a list of sequences.
2258 Each sequence starts with a symbol, either `sequence' or `type',
2259 indicating if the keywords should be interpreted as a sequence of
2260 action steps, or as different types of TODO items. The first
2261 keywords are states requiring action - these states will select a headline
2262 for inclusion into the global TODO list Org-mode produces. If one of
2263 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2264 signify that no further action is necessary. If \"|\" is not found,
2265 the last keyword is treated as the only DONE state of the sequence.
2267 The command \\[org-todo] cycles an entry through these states, and one
2268 additional state where no keyword is present. For details about this
2269 cycling, see the manual.
2271 TODO keywords and interpretation can also be set on a per-file basis with
2272 the special #+SEQ_TODO and #+TYP_TODO lines.
2274 Each keyword can optionally specify a character for fast state selection
2275 \(in combination with the variable `org-use-fast-todo-selection')
2276 and specifiers for state change logging, using the same syntax that
2277 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2278 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2279 indicates to record a time stamp each time this state is selected.
2281 Each keyword may also specify if a timestamp or a note should be
2282 recorded when entering or leaving the state, by adding additional
2283 characters in the parenthesis after the keyword. This looks like this:
2284 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2285 record only the time of the state change. With X and Y being either
2286 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2287 Y when leaving the state if and only if the *target* state does not
2288 define X. You may omit any of the fast-selection key or X or /Y,
2289 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2291 For backward compatibility, this variable may also be just a list
2292 of keywords. In this case the interpretation (sequence or type) will be
2293 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2294 :group 'org-todo
2295 :group 'org-keywords
2296 :type '(choice
2297 (repeat :tag "Old syntax, just keywords"
2298 (string :tag "Keyword"))
2299 (repeat :tag "New syntax"
2300 (cons
2301 (choice
2302 :tag "Interpretation"
2303 ;;Quick and dirty way to see
2304 ;;`org-todo-interpretations'. This takes the
2305 ;;place of item arguments
2306 :convert-widget
2307 (lambda (widget)
2308 (widget-put widget
2309 :args (mapcar
2310 #'(lambda (x)
2311 (widget-convert
2312 (cons 'const x)))
2313 org-todo-interpretation-widgets))
2314 widget))
2315 (repeat
2316 (string :tag "Keyword"))))))
2318 (defvar org-todo-keywords-1 nil
2319 "All TODO and DONE keywords active in a buffer.")
2320 (make-variable-buffer-local 'org-todo-keywords-1)
2321 (defvar org-todo-keywords-for-agenda nil)
2322 (defvar org-done-keywords-for-agenda nil)
2323 (defvar org-drawers-for-agenda nil)
2324 (defvar org-todo-keyword-alist-for-agenda nil)
2325 (defvar org-tag-alist-for-agenda nil
2326 "Alist of all tags from all agenda files.")
2327 (defvar org-tag-groups-alist-for-agenda nil
2328 "Alist of all groups tags from all current agenda files.")
2329 (defvar org-tag-groups-alist nil)
2330 (make-variable-buffer-local 'org-tag-groups-alist)
2331 (defvar org-agenda-contributing-files nil)
2332 (defvar org-not-done-keywords nil)
2333 (make-variable-buffer-local 'org-not-done-keywords)
2334 (defvar org-done-keywords nil)
2335 (make-variable-buffer-local 'org-done-keywords)
2336 (defvar org-todo-heads nil)
2337 (make-variable-buffer-local 'org-todo-heads)
2338 (defvar org-todo-sets nil)
2339 (make-variable-buffer-local 'org-todo-sets)
2340 (defvar org-todo-log-states nil)
2341 (make-variable-buffer-local 'org-todo-log-states)
2342 (defvar org-todo-kwd-alist nil)
2343 (make-variable-buffer-local 'org-todo-kwd-alist)
2344 (defvar org-todo-key-alist nil)
2345 (make-variable-buffer-local 'org-todo-key-alist)
2346 (defvar org-todo-key-trigger nil)
2347 (make-variable-buffer-local 'org-todo-key-trigger)
2349 (defcustom org-todo-interpretation 'sequence
2350 "Controls how TODO keywords are interpreted.
2351 This variable is in principle obsolete and is only used for
2352 backward compatibility, if the interpretation of todo keywords is
2353 not given already in `org-todo-keywords'. See that variable for
2354 more information."
2355 :group 'org-todo
2356 :group 'org-keywords
2357 :type '(choice (const sequence)
2358 (const type)))
2360 (defcustom org-use-fast-todo-selection t
2361 "Non-nil means use the fast todo selection scheme with C-c C-t.
2362 This variable describes if and under what circumstances the cycling
2363 mechanism for TODO keywords will be replaced by a single-key, direct
2364 selection scheme.
2366 When nil, fast selection is never used.
2368 When the symbol `prefix', it will be used when `org-todo' is called
2369 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2370 `C-u t' in an agenda buffer.
2372 When t, fast selection is used by default. In this case, the prefix
2373 argument forces cycling instead.
2375 In all cases, the special interface is only used if access keys have
2376 actually been assigned by the user, i.e. if keywords in the configuration
2377 are followed by a letter in parenthesis, like TODO(t)."
2378 :group 'org-todo
2379 :type '(choice
2380 (const :tag "Never" nil)
2381 (const :tag "By default" t)
2382 (const :tag "Only with C-u C-c C-t" prefix)))
2384 (defcustom org-provide-todo-statistics t
2385 "Non-nil means update todo statistics after insert and toggle.
2386 ALL-HEADLINES means update todo statistics by including headlines
2387 with no TODO keyword as well, counting them as not done.
2388 A list of TODO keywords means the same, but skip keywords that are
2389 not in this list.
2391 When this is set, todo statistics is updated in the parent of the
2392 current entry each time a todo state is changed."
2393 :group 'org-todo
2394 :type '(choice
2395 (const :tag "Yes, only for TODO entries" t)
2396 (const :tag "Yes, including all entries" 'all-headlines)
2397 (repeat :tag "Yes, for TODOs in this list"
2398 (string :tag "TODO keyword"))
2399 (other :tag "No TODO statistics" nil)))
2401 (defcustom org-hierarchical-todo-statistics t
2402 "Non-nil means TODO statistics covers just direct children.
2403 When nil, all entries in the subtree are considered.
2404 This has only an effect if `org-provide-todo-statistics' is set.
2405 To set this to nil for only a single subtree, use a COOKIE_DATA
2406 property and include the word \"recursive\" into the value."
2407 :group 'org-todo
2408 :type 'boolean)
2410 (defcustom org-after-todo-state-change-hook nil
2411 "Hook which is run after the state of a TODO item was changed.
2412 The new state (a string with a TODO keyword, or nil) is available in the
2413 Lisp variable `org-state'."
2414 :group 'org-todo
2415 :type 'hook)
2417 (defvar org-blocker-hook nil
2418 "Hook for functions that are allowed to block a state change.
2420 Functions in this hook should not modify the buffer.
2421 Each function gets as its single argument a property list,
2422 see `org-trigger-hook' for more information about this list.
2424 If any of the functions in this hook returns nil, the state change
2425 is blocked.")
2427 (defvar org-trigger-hook nil
2428 "Hook for functions that are triggered by a state change.
2430 Each function gets as its single argument a property list with at
2431 least the following elements:
2433 (:type type-of-change :position pos-at-entry-start
2434 :from old-state :to new-state)
2436 Depending on the type, more properties may be present.
2438 This mechanism is currently implemented for:
2440 TODO state changes
2441 ------------------
2442 :type todo-state-change
2443 :from previous state (keyword as a string), or nil, or a symbol
2444 'todo' or 'done', to indicate the general type of state.
2445 :to new state, like in :from")
2447 (defcustom org-enforce-todo-dependencies nil
2448 "Non-nil means undone TODO entries will block switching the parent to DONE.
2449 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2450 be blocked if any prior sibling is not yet done.
2451 Finally, if the parent is blocked because of ordered siblings of its own,
2452 the child will also be blocked."
2453 :set (lambda (var val)
2454 (set var val)
2455 (if val
2456 (add-hook 'org-blocker-hook
2457 'org-block-todo-from-children-or-siblings-or-parent)
2458 (remove-hook 'org-blocker-hook
2459 'org-block-todo-from-children-or-siblings-or-parent)))
2460 :group 'org-todo
2461 :type 'boolean)
2463 (defcustom org-enforce-todo-checkbox-dependencies nil
2464 "Non-nil means unchecked boxes will block switching the parent to DONE.
2465 When this is nil, checkboxes have no influence on switching TODO states.
2466 When non-nil, you first need to check off all check boxes before the TODO
2467 entry can be switched to DONE.
2468 This variable needs to be set before org.el is loaded, and you need to
2469 restart Emacs after a change to make the change effective. The only way
2470 to change is while Emacs is running is through the customize interface."
2471 :set (lambda (var val)
2472 (set var val)
2473 (if val
2474 (add-hook 'org-blocker-hook
2475 'org-block-todo-from-checkboxes)
2476 (remove-hook 'org-blocker-hook
2477 'org-block-todo-from-checkboxes)))
2478 :group 'org-todo
2479 :type 'boolean)
2481 (defcustom org-treat-insert-todo-heading-as-state-change nil
2482 "Non-nil means inserting a TODO heading is treated as state change.
2483 So when the command \\[org-insert-todo-heading] is used, state change
2484 logging will apply if appropriate. When nil, the new TODO item will
2485 be inserted directly, and no logging will take place."
2486 :group 'org-todo
2487 :type 'boolean)
2489 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2490 "Non-nil means switching TODO states with S-cursor counts as state change.
2491 This is the default behavior. However, setting this to nil allows a
2492 convenient way to select a TODO state and bypass any logging associated
2493 with that."
2494 :group 'org-todo
2495 :type 'boolean)
2497 (defcustom org-todo-state-tags-triggers nil
2498 "Tag changes that should be triggered by TODO state changes.
2499 This is a list. Each entry is
2501 (state-change (tag . flag) .......)
2503 State-change can be a string with a state, and empty string to indicate the
2504 state that has no TODO keyword, or it can be one of the symbols `todo'
2505 or `done', meaning any not-done or done state, respectively."
2506 :group 'org-todo
2507 :group 'org-tags
2508 :type '(repeat
2509 (cons (choice :tag "When changing to"
2510 (const :tag "Not-done state" todo)
2511 (const :tag "Done state" done)
2512 (string :tag "State"))
2513 (repeat
2514 (cons :tag "Tag action"
2515 (string :tag "Tag")
2516 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2518 (defcustom org-log-done nil
2519 "Information to record when a task moves to the DONE state.
2521 Possible values are:
2523 nil Don't add anything, just change the keyword
2524 time Add a time stamp to the task
2525 note Prompt for a note and add it with template `org-log-note-headings'
2527 This option can also be set with on a per-file-basis with
2529 #+STARTUP: nologdone
2530 #+STARTUP: logdone
2531 #+STARTUP: lognotedone
2533 You can have local logging settings for a subtree by setting the LOGGING
2534 property to one or more of these keywords."
2535 :group 'org-todo
2536 :group 'org-progress
2537 :type '(choice
2538 (const :tag "No logging" nil)
2539 (const :tag "Record CLOSED timestamp" time)
2540 (const :tag "Record CLOSED timestamp with note." note)))
2542 ;; Normalize old uses of org-log-done.
2543 (cond
2544 ((eq org-log-done t) (setq org-log-done 'time))
2545 ((and (listp org-log-done) (memq 'done org-log-done))
2546 (setq org-log-done 'note)))
2548 (defcustom org-log-reschedule nil
2549 "Information to record when the scheduling date of a tasks is modified.
2551 Possible values are:
2553 nil Don't add anything, just change the date
2554 time Add a time stamp to the task
2555 note Prompt for a note and add it with template `org-log-note-headings'
2557 This option can also be set with on a per-file-basis with
2559 #+STARTUP: nologreschedule
2560 #+STARTUP: logreschedule
2561 #+STARTUP: lognotereschedule"
2562 :group 'org-todo
2563 :group 'org-progress
2564 :type '(choice
2565 (const :tag "No logging" nil)
2566 (const :tag "Record timestamp" time)
2567 (const :tag "Record timestamp with note." note)))
2569 (defcustom org-log-redeadline nil
2570 "Information to record when the deadline date of a tasks is modified.
2572 Possible values are:
2574 nil Don't add anything, just change the date
2575 time Add a time stamp to the task
2576 note Prompt for a note and add it with template `org-log-note-headings'
2578 This option can also be set with on a per-file-basis with
2580 #+STARTUP: nologredeadline
2581 #+STARTUP: logredeadline
2582 #+STARTUP: lognoteredeadline
2584 You can have local logging settings for a subtree by setting the LOGGING
2585 property to one or more of these keywords."
2586 :group 'org-todo
2587 :group 'org-progress
2588 :type '(choice
2589 (const :tag "No logging" nil)
2590 (const :tag "Record timestamp" time)
2591 (const :tag "Record timestamp with note." note)))
2593 (defcustom org-log-note-clock-out nil
2594 "Non-nil means record a note when clocking out of an item.
2595 This can also be configured on a per-file basis by adding one of
2596 the following lines anywhere in the buffer:
2598 #+STARTUP: lognoteclock-out
2599 #+STARTUP: nolognoteclock-out"
2600 :group 'org-todo
2601 :group 'org-progress
2602 :type 'boolean)
2604 (defcustom org-log-done-with-time t
2605 "Non-nil means the CLOSED time stamp will contain date and time.
2606 When nil, only the date will be recorded."
2607 :group 'org-progress
2608 :type 'boolean)
2610 (defcustom org-log-note-headings
2611 '((done . "CLOSING NOTE %t")
2612 (state . "State %-12s from %-12S %t")
2613 (note . "Note taken on %t")
2614 (reschedule . "Rescheduled from %S on %t")
2615 (delschedule . "Not scheduled, was %S on %t")
2616 (redeadline . "New deadline from %S on %t")
2617 (deldeadline . "Removed deadline, was %S on %t")
2618 (refile . "Refiled on %t")
2619 (clock-out . ""))
2620 "Headings for notes added to entries.
2621 The value is an alist, with the car being a symbol indicating the note
2622 context, and the cdr is the heading to be used. The heading may also be the
2623 empty string.
2624 %t in the heading will be replaced by a time stamp.
2625 %T will be an active time stamp instead the default inactive one
2626 %d will be replaced by a short-format time stamp.
2627 %D will be replaced by an active short-format time stamp.
2628 %s will be replaced by the new TODO state, in double quotes.
2629 %S will be replaced by the old TODO state, in double quotes.
2630 %u will be replaced by the user name.
2631 %U will be replaced by the full user name.
2633 In fact, it is not a good idea to change the `state' entry, because
2634 agenda log mode depends on the format of these entries."
2635 :group 'org-todo
2636 :group 'org-progress
2637 :type '(list :greedy t
2638 (cons (const :tag "Heading when closing an item" done) string)
2639 (cons (const :tag
2640 "Heading when changing todo state (todo sequence only)"
2641 state) string)
2642 (cons (const :tag "Heading when just taking a note" note) string)
2643 (cons (const :tag "Heading when clocking out" clock-out) string)
2644 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2645 (cons (const :tag "Heading when rescheduling" reschedule) string)
2646 (cons (const :tag "Heading when changing deadline" redeadline) string)
2647 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2648 (cons (const :tag "Heading when refiling" refile) string)))
2650 (unless (assq 'note org-log-note-headings)
2651 (push '(note . "%t") org-log-note-headings))
2653 (defcustom org-log-into-drawer nil
2654 "Non-nil means insert state change notes and time stamps into a drawer.
2655 When nil, state changes notes will be inserted after the headline and
2656 any scheduling and clock lines, but not inside a drawer.
2658 The value of this variable should be the name of the drawer to use.
2659 LOGBOOK is proposed as the default drawer for this purpose, you can
2660 also set this to a string to define the drawer of your choice.
2662 A value of t is also allowed, representing \"LOGBOOK\".
2664 A value of t or nil can also be set with on a per-file-basis with
2666 #+STARTUP: logdrawer
2667 #+STARTUP: nologdrawer
2669 If this variable is set, `org-log-state-notes-insert-after-drawers'
2670 will be ignored.
2672 You can set the property LOG_INTO_DRAWER to overrule this setting for
2673 a subtree."
2674 :group 'org-todo
2675 :group 'org-progress
2676 :type '(choice
2677 (const :tag "Not into a drawer" nil)
2678 (const :tag "LOGBOOK" t)
2679 (string :tag "Other")))
2681 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2683 (defun org-log-into-drawer ()
2684 "Return the value of `org-log-into-drawer', but let properties overrule.
2685 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2686 used instead of the default value."
2687 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2688 (cond
2689 ((not p) org-log-into-drawer)
2690 ((equal p "nil") nil)
2691 ((equal p "t") "LOGBOOK")
2692 (t p))))
2694 (defcustom org-log-state-notes-insert-after-drawers nil
2695 "Non-nil means insert state change notes after any drawers in entry.
2696 Only the drawers that *immediately* follow the headline and the
2697 deadline/scheduled line are skipped.
2698 When nil, insert notes right after the heading and perhaps the line
2699 with deadline/scheduling if present.
2701 This variable will have no effect if `org-log-into-drawer' is
2702 set."
2703 :group 'org-todo
2704 :group 'org-progress
2705 :type 'boolean)
2707 (defcustom org-log-states-order-reversed t
2708 "Non-nil means the latest state note will be directly after heading.
2709 When nil, the state change notes will be ordered according to time.
2711 This option can also be set with on a per-file-basis with
2713 #+STARTUP: logstatesreversed
2714 #+STARTUP: nologstatesreversed"
2715 :group 'org-todo
2716 :group 'org-progress
2717 :type 'boolean)
2719 (defcustom org-todo-repeat-to-state nil
2720 "The TODO state to which a repeater should return the repeating task.
2721 By default this is the first task in a TODO sequence, or the previous state
2722 in a TODO_TYP set. But you can specify another task here.
2723 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2724 :group 'org-todo
2725 :version "24.1"
2726 :type '(choice (const :tag "Head of sequence" nil)
2727 (string :tag "Specific state")))
2729 (defcustom org-log-repeat 'time
2730 "Non-nil means record moving through the DONE state when triggering repeat.
2731 An auto-repeating task is immediately switched back to TODO when
2732 marked DONE. If you are not logging state changes (by adding \"@\"
2733 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2734 record a closing note, there will be no record of the task moving
2735 through DONE. This variable forces taking a note anyway.
2737 nil Don't force a record
2738 time Record a time stamp
2739 note Prompt for a note and add it with template `org-log-note-headings'
2741 This option can also be set with on a per-file-basis with
2743 #+STARTUP: nologrepeat
2744 #+STARTUP: logrepeat
2745 #+STARTUP: lognoterepeat
2747 You can have local logging settings for a subtree by setting the LOGGING
2748 property to one or more of these keywords."
2749 :group 'org-todo
2750 :group 'org-progress
2751 :type '(choice
2752 (const :tag "Don't force a record" nil)
2753 (const :tag "Force recording the DONE state" time)
2754 (const :tag "Force recording a note with the DONE state" note)))
2757 (defgroup org-priorities nil
2758 "Priorities in Org-mode."
2759 :tag "Org Priorities"
2760 :group 'org-todo)
2762 (defcustom org-enable-priority-commands t
2763 "Non-nil means priority commands are active.
2764 When nil, these commands will be disabled, so that you never accidentally
2765 set a priority."
2766 :group 'org-priorities
2767 :type 'boolean)
2769 (defcustom org-highest-priority ?A
2770 "The highest priority of TODO items. A character like ?A, ?B etc.
2771 Must have a smaller ASCII number than `org-lowest-priority'."
2772 :group 'org-priorities
2773 :type 'character)
2775 (defcustom org-lowest-priority ?C
2776 "The lowest priority of TODO items. A character like ?A, ?B etc.
2777 Must have a larger ASCII number than `org-highest-priority'."
2778 :group 'org-priorities
2779 :type 'character)
2781 (defcustom org-default-priority ?B
2782 "The default priority of TODO items.
2783 This is the priority an item gets if no explicit priority is given.
2784 When starting to cycle on an empty priority the first step in the cycle
2785 depends on `org-priority-start-cycle-with-default'. The resulting first
2786 step priority must not exceed the range from `org-highest-priority' to
2787 `org-lowest-priority' which means that `org-default-priority' has to be
2788 in this range exclusive or inclusive the range boundaries. Else the
2789 first step refuses to set the default and the second will fall back
2790 to (depending on the command used) the highest or lowest priority."
2791 :group 'org-priorities
2792 :type 'character)
2794 (defcustom org-priority-start-cycle-with-default t
2795 "Non-nil means start with default priority when starting to cycle.
2796 When this is nil, the first step in the cycle will be (depending on the
2797 command used) one higher or lower than the default priority.
2798 See also `org-default-priority'."
2799 :group 'org-priorities
2800 :type 'boolean)
2802 (defcustom org-get-priority-function nil
2803 "Function to extract the priority from a string.
2804 The string is normally the headline. If this is nil Org computes the
2805 priority from the priority cookie like [#A] in the headline. It returns
2806 an integer, increasing by 1000 for each priority level.
2807 The user can set a different function here, which should take a string
2808 as an argument and return the numeric priority."
2809 :group 'org-priorities
2810 :version "24.1"
2811 :type 'function)
2813 (defgroup org-time nil
2814 "Options concerning time stamps and deadlines in Org-mode."
2815 :tag "Org Time"
2816 :group 'org)
2818 (defcustom org-insert-labeled-timestamps-at-point nil
2819 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2820 When nil, these labeled time stamps are forces into the second line of an
2821 entry, just after the headline. When scheduling from the global TODO list,
2822 the time stamp will always be forced into the second line."
2823 :group 'org-time
2824 :type 'boolean)
2826 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2827 "Formats for `format-time-string' which are used for time stamps.
2828 It is not recommended to change this constant.")
2830 (defcustom org-time-stamp-rounding-minutes '(0 5)
2831 "Number of minutes to round time stamps to.
2832 These are two values, the first applies when first creating a time stamp.
2833 The second applies when changing it with the commands `S-up' and `S-down'.
2834 When changing the time stamp, this means that it will change in steps
2835 of N minutes, as given by the second value.
2837 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2838 numbers should be factors of 60, so for example 5, 10, 15.
2840 When this is larger than 1, you can still force an exact time stamp by using
2841 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2842 and by using a prefix arg to `S-up/down' to specify the exact number
2843 of minutes to shift."
2844 :group 'org-time
2845 :get #'(lambda (var) ; Make sure both elements are there
2846 (if (integerp (default-value var))
2847 (list (default-value var) 5)
2848 (default-value var)))
2849 :type '(list
2850 (integer :tag "when inserting times")
2851 (integer :tag "when modifying times")))
2853 ;; Normalize old customizations of this variable.
2854 (when (integerp org-time-stamp-rounding-minutes)
2855 (setq org-time-stamp-rounding-minutes
2856 (list org-time-stamp-rounding-minutes
2857 org-time-stamp-rounding-minutes)))
2859 (defcustom org-display-custom-times nil
2860 "Non-nil means overlay custom formats over all time stamps.
2861 The formats are defined through the variable `org-time-stamp-custom-formats'.
2862 To turn this on on a per-file basis, insert anywhere in the file:
2863 #+STARTUP: customtime"
2864 :group 'org-time
2865 :set 'set-default
2866 :type 'sexp)
2867 (make-variable-buffer-local 'org-display-custom-times)
2869 (defcustom org-time-stamp-custom-formats
2870 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2871 "Custom formats for time stamps. See `format-time-string' for the syntax.
2872 These are overlaid over the default ISO format if the variable
2873 `org-display-custom-times' is set. Time like %H:%M should be at the
2874 end of the second format. The custom formats are also honored by export
2875 commands, if custom time display is turned on at the time of export."
2876 :group 'org-time
2877 :type 'sexp)
2879 (defun org-time-stamp-format (&optional long inactive)
2880 "Get the right format for a time string."
2881 (let ((f (if long (cdr org-time-stamp-formats)
2882 (car org-time-stamp-formats))))
2883 (if inactive
2884 (concat "[" (substring f 1 -1) "]")
2885 f)))
2887 (defcustom org-time-clocksum-format
2888 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2889 "The format string used when creating CLOCKSUM lines.
2890 This is also used when Org mode generates a time duration.
2892 The value can be a single format string containing two
2893 %-sequences, which will be filled with the number of hours and
2894 minutes in that order.
2896 Alternatively, the value can be a plist associating any of the
2897 keys :years, :months, :weeks, :days, :hours or :minutes with
2898 format strings. The time duration is formatted using only the
2899 time components that are needed and concatenating the results.
2900 If a time unit in absent, it falls back to the next smallest
2901 unit.
2903 The keys :require-years, :require-months, :require-days,
2904 :require-weeks, :require-hours, :require-minutes are also
2905 meaningful. A non-nil value for these keys indicates that the
2906 corresponding time component should always be included, even if
2907 its value is 0.
2910 For example,
2912 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2913 :require-minutes t)
2915 means durations longer than a day will be expressed in days,
2916 hours and minutes, and durations less than a day will always be
2917 expressed in hours and minutes (even for durations less than an
2918 hour).
2920 The value
2922 \(:days \"%dd\" :minutes \"%dm\")
2924 means durations longer than a day will be expressed in days and
2925 minutes, and durations less than a day will be expressed entirely
2926 in minutes (even for durations longer than an hour)."
2927 :group 'org-time
2928 :group 'org-clock
2929 :version "24.4"
2930 :package-version '(Org . "8.0")
2931 :type '(choice (string :tag "Format string")
2932 (set :tag "Plist"
2933 (group :inline t (const :tag "Years" :years)
2934 (string :tag "Format string"))
2935 (group :inline t
2936 (const :tag "Always show years" :require-years)
2937 (const t))
2938 (group :inline t (const :tag "Months" :months)
2939 (string :tag "Format string"))
2940 (group :inline t
2941 (const :tag "Always show months" :require-months)
2942 (const t))
2943 (group :inline t (const :tag "Weeks" :weeks)
2944 (string :tag "Format string"))
2945 (group :inline t
2946 (const :tag "Always show weeks" :require-weeks)
2947 (const t))
2948 (group :inline t (const :tag "Days" :days)
2949 (string :tag "Format string"))
2950 (group :inline t
2951 (const :tag "Always show days" :require-days)
2952 (const t))
2953 (group :inline t (const :tag "Hours" :hours)
2954 (string :tag "Format string"))
2955 (group :inline t
2956 (const :tag "Always show hours" :require-hours)
2957 (const t))
2958 (group :inline t (const :tag "Minutes" :minutes)
2959 (string :tag "Format string"))
2960 (group :inline t
2961 (const :tag "Always show minutes" :require-minutes)
2962 (const t)))))
2964 (defcustom org-time-clocksum-use-fractional nil
2965 "When non-nil, \\[org-clock-display] uses fractional times.
2966 See `org-time-clocksum-format' for more on time clock formats."
2967 :group 'org-time
2968 :group 'org-clock
2969 :version "24.3"
2970 :type 'boolean)
2972 (defcustom org-time-clocksum-use-effort-durations nil
2973 "When non-nil, \\[org-clock-display] uses effort durations.
2974 E.g. by default, one day is considered to be a 8 hours effort,
2975 so a task that has been clocked for 16 hours will be displayed
2976 as during 2 days in the clock display or in the clocktable.
2978 See `org-effort-durations' on how to set effort durations
2979 and `org-time-clocksum-format' for more on time clock formats."
2980 :group 'org-time
2981 :group 'org-clock
2982 :version "24.4"
2983 :package-version '(Org . "8.0")
2984 :type 'boolean)
2986 (defcustom org-time-clocksum-fractional-format "%.2f"
2987 "The format string used when creating CLOCKSUM lines,
2988 or when Org mode generates a time duration, if
2989 `org-time-clocksum-use-fractional' is enabled.
2991 The value can be a single format string containing one
2992 %-sequence, which will be filled with the number of hours as
2993 a float.
2995 Alternatively, the value can be a plist associating any of the
2996 keys :years, :months, :weeks, :days, :hours or :minutes with
2997 a format string. The time duration is formatted using the
2998 largest time unit which gives a non-zero integer part. If all
2999 specified formats have zero integer part, the smallest time unit
3000 is used."
3001 :group 'org-time
3002 :type '(choice (string :tag "Format string")
3003 (set (group :inline t (const :tag "Years" :years)
3004 (string :tag "Format string"))
3005 (group :inline t (const :tag "Months" :months)
3006 (string :tag "Format string"))
3007 (group :inline t (const :tag "Weeks" :weeks)
3008 (string :tag "Format string"))
3009 (group :inline t (const :tag "Days" :days)
3010 (string :tag "Format string"))
3011 (group :inline t (const :tag "Hours" :hours)
3012 (string :tag "Format string"))
3013 (group :inline t (const :tag "Minutes" :minutes)
3014 (string :tag "Format string")))))
3016 (defcustom org-deadline-warning-days 14
3017 "Number of days before expiration during which a deadline becomes active.
3018 This variable governs the display in sparse trees and in the agenda.
3019 When 0 or negative, it means use this number (the absolute value of it)
3020 even if a deadline has a different individual lead time specified.
3022 Custom commands can set this variable in the options section."
3023 :group 'org-time
3024 :group 'org-agenda-daily/weekly
3025 :type 'integer)
3027 (defcustom org-scheduled-delay-days 0
3028 "Number of days before a scheduled item becomes active.
3029 This variable governs the display in sparse trees and in the agenda.
3030 The default value (i.e. 0) means: don't delay scheduled item.
3031 When negative, it means use this number (the absolute value of it)
3032 even if a scheduled item has a different individual delay time
3033 specified.
3035 Custom commands can set this variable in the options section."
3036 :group 'org-time
3037 :group 'org-agenda-daily/weekly
3038 :version "24.4"
3039 :package-version '(Org . "8.0")
3040 :type 'integer)
3042 (defcustom org-read-date-prefer-future t
3043 "Non-nil means assume future for incomplete date input from user.
3044 This affects the following situations:
3045 1. The user gives a month but not a year.
3046 For example, if it is April and you enter \"feb 2\", this will be read
3047 as Feb 2, *next* year. \"May 5\", however, will be this year.
3048 2. The user gives a day, but no month.
3049 For example, if today is the 15th, and you enter \"3\", Org-mode will
3050 read this as the third of *next* month. However, if you enter \"17\",
3051 it will be considered as *this* month.
3053 If you set this variable to the symbol `time', then also the following
3054 will work:
3056 3. If the user gives a time.
3057 If the time is before now, it will be interpreted as tomorrow.
3059 Currently none of this works for ISO week specifications.
3061 When this option is nil, the current day, month and year will always be
3062 used as defaults.
3064 See also `org-agenda-jump-prefer-future'."
3065 :group 'org-time
3066 :type '(choice
3067 (const :tag "Never" nil)
3068 (const :tag "Check month and day" t)
3069 (const :tag "Check month, day, and time" time)))
3071 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3072 "Should the agenda jump command prefer the future for incomplete dates?
3073 The default is to do the same as configured in `org-read-date-prefer-future'.
3074 But you can also set a deviating value here.
3075 This may t or nil, or the symbol `org-read-date-prefer-future'."
3076 :group 'org-agenda
3077 :group 'org-time
3078 :version "24.1"
3079 :type '(choice
3080 (const :tag "Use org-read-date-prefer-future"
3081 org-read-date-prefer-future)
3082 (const :tag "Never" nil)
3083 (const :tag "Always" t)))
3085 (defcustom org-read-date-force-compatible-dates t
3086 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3088 Depending on the system Emacs is running on, certain dates cannot
3089 be represented with the type used internally to represent time.
3090 Dates between 1970-1-1 and 2038-1-1 can always be represented
3091 correctly. Some systems allow for earlier dates, some for later,
3092 some for both. One way to find out it to insert any date into an
3093 Org buffer, putting the cursor on the year and hitting S-up and
3094 S-down to test the range.
3096 When this variable is set to t, the date/time prompt will not let
3097 you specify dates outside the 1970-2037 range, so it is certain that
3098 these dates will work in whatever version of Emacs you are
3099 running, and also that you can move a file from one Emacs implementation
3100 to another. WHenever Org is forcing the year for you, it will display
3101 a message and beep.
3103 When this variable is nil, Org will check if the date is
3104 representable in the specific Emacs implementation you are using.
3105 If not, it will force a year, usually the current year, and beep
3106 to remind you. Currently this setting is not recommended because
3107 the likelihood that you will open your Org files in an Emacs that
3108 has limited date range is not negligible.
3110 A workaround for this problem is to use diary sexp dates for time
3111 stamps outside of this range."
3112 :group 'org-time
3113 :version "24.1"
3114 :type 'boolean)
3116 (defcustom org-read-date-display-live t
3117 "Non-nil means display current interpretation of date prompt live.
3118 This display will be in an overlay, in the minibuffer."
3119 :group 'org-time
3120 :type 'boolean)
3122 (defcustom org-read-date-popup-calendar t
3123 "Non-nil means pop up a calendar when prompting for a date.
3124 In the calendar, the date can be selected with mouse-1. However, the
3125 minibuffer will also be active, and you can simply enter the date as well.
3126 When nil, only the minibuffer will be available."
3127 :group 'org-time
3128 :type 'boolean)
3129 (org-defvaralias 'org-popup-calendar-for-date-prompt
3130 'org-read-date-popup-calendar)
3132 (make-obsolete-variable
3133 'org-read-date-minibuffer-setup-hook
3134 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3135 (defcustom org-read-date-minibuffer-setup-hook nil
3136 "Hook to be used to set up keys for the date/time interface.
3137 Add key definitions to `minibuffer-local-map', which will be a
3138 temporary copy.
3140 WARNING: This option is obsolete, you should use
3141 `org-read-date-minibuffer-local-map' to set up keys."
3142 :group 'org-time
3143 :type 'hook)
3145 (defcustom org-extend-today-until 0
3146 "The hour when your day really ends. Must be an integer.
3147 This has influence for the following applications:
3148 - When switching the agenda to \"today\". It it is still earlier than
3149 the time given here, the day recognized as TODAY is actually yesterday.
3150 - When a date is read from the user and it is still before the time given
3151 here, the current date and time will be assumed to be yesterday, 23:59.
3152 Also, timestamps inserted in capture templates follow this rule.
3154 IMPORTANT: This is a feature whose implementation is and likely will
3155 remain incomplete. Really, it is only here because past midnight seems to
3156 be the favorite working time of John Wiegley :-)"
3157 :group 'org-time
3158 :type 'integer)
3160 (defcustom org-use-effective-time nil
3161 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3162 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3163 \"effective time\" of any timestamps between midnight and 8am will be
3164 23:59 of the previous day."
3165 :group 'org-time
3166 :version "24.1"
3167 :type 'boolean)
3169 (defcustom org-use-last-clock-out-time-as-effective-time nil
3170 "When non-nil, use the last clock out time for `org-todo'.
3171 Note that this option has precedence over the combined use of
3172 `org-use-effective-time' and `org-extend-today-until'."
3173 :group 'org-time
3174 :version "24.4"
3175 :package-version '(Org . "8.0")
3176 :type 'boolean)
3178 (defcustom org-edit-timestamp-down-means-later nil
3179 "Non-nil means S-down will increase the time in a time stamp.
3180 When nil, S-up will increase."
3181 :group 'org-time
3182 :type 'boolean)
3184 (defcustom org-calendar-follow-timestamp-change t
3185 "Non-nil means make the calendar window follow timestamp changes.
3186 When a timestamp is modified and the calendar window is visible, it will be
3187 moved to the new date."
3188 :group 'org-time
3189 :type 'boolean)
3191 (defgroup org-tags nil
3192 "Options concerning tags in Org-mode."
3193 :tag "Org Tags"
3194 :group 'org)
3196 (defcustom org-tag-alist nil
3197 "List of tags allowed in Org-mode files.
3198 When this list is nil, Org-mode will base TAG input on what is already in the
3199 buffer.
3200 The value of this variable is an alist, the car of each entry must be a
3201 keyword as a string, the cdr may be a character that is used to select
3202 that tag through the fast-tag-selection interface.
3203 See the manual for details."
3204 :group 'org-tags
3205 :type '(repeat
3206 (choice
3207 (cons (string :tag "Tag name")
3208 (character :tag "Access char"))
3209 (list :tag "Start radio group"
3210 (const :startgroup)
3211 (option (string :tag "Group description")))
3212 (list :tag "Group tags delimiter"
3213 (const :grouptags))
3214 (list :tag "End radio group"
3215 (const :endgroup)
3216 (option (string :tag "Group description")))
3217 (const :tag "New line" (:newline)))))
3219 (defcustom org-tag-persistent-alist nil
3220 "List of tags that will always appear in all Org-mode files.
3221 This is in addition to any in buffer settings or customizations
3222 of `org-tag-alist'.
3223 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3224 The value of this variable is an alist, the car of each entry must be a
3225 keyword as a string, the cdr may be a character that is used to select
3226 that tag through the fast-tag-selection interface.
3227 See the manual for details.
3228 To disable these tags on a per-file basis, insert anywhere in the file:
3229 #+STARTUP: noptag"
3230 :group 'org-tags
3231 :type '(repeat
3232 (choice
3233 (cons (string :tag "Tag name")
3234 (character :tag "Access char"))
3235 (const :tag "Start radio group" (:startgroup))
3236 (const :tag "Group tags delimiter" (:grouptags))
3237 (const :tag "End radio group" (:endgroup))
3238 (const :tag "New line" (:newline)))))
3240 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3241 "If non-nil, always offer completion for all tags of all agenda files.
3242 Instead of customizing this variable directly, you might want to
3243 set it locally for capture buffers, because there no list of
3244 tags in that file can be created dynamically (there are none).
3246 (add-hook 'org-capture-mode-hook
3247 (lambda ()
3248 (set (make-local-variable
3249 'org-complete-tags-always-offer-all-agenda-tags)
3250 t)))"
3251 :group 'org-tags
3252 :version "24.1"
3253 :type 'boolean)
3255 (defvar org-file-tags nil
3256 "List of tags that can be inherited by all entries in the file.
3257 The tags will be inherited if the variable `org-use-tag-inheritance'
3258 says they should be.
3259 This variable is populated from #+FILETAGS lines.")
3261 (defcustom org-use-fast-tag-selection 'auto
3262 "Non-nil means use fast tag selection scheme.
3263 This is a special interface to select and deselect tags with single keys.
3264 When nil, fast selection is never used.
3265 When the symbol `auto', fast selection is used if and only if selection
3266 characters for tags have been configured, either through the variable
3267 `org-tag-alist' or through a #+TAGS line in the buffer.
3268 When t, fast selection is always used and selection keys are assigned
3269 automatically if necessary."
3270 :group 'org-tags
3271 :type '(choice
3272 (const :tag "Always" t)
3273 (const :tag "Never" nil)
3274 (const :tag "When selection characters are configured" 'auto)))
3276 (defcustom org-fast-tag-selection-single-key nil
3277 "Non-nil means fast tag selection exits after first change.
3278 When nil, you have to press RET to exit it.
3279 During fast tag selection, you can toggle this flag with `C-c'.
3280 This variable can also have the value `expert'. In this case, the window
3281 displaying the tags menu is not even shown, until you press C-c again."
3282 :group 'org-tags
3283 :type '(choice
3284 (const :tag "No" nil)
3285 (const :tag "Yes" t)
3286 (const :tag "Expert" expert)))
3288 (defvar org-fast-tag-selection-include-todo nil
3289 "Non-nil means fast tags selection interface will also offer TODO states.
3290 This is an undocumented feature, you should not rely on it.")
3292 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3293 "The column to which tags should be indented in a headline.
3294 If this number is positive, it specifies the column. If it is negative,
3295 it means that the tags should be flushright to that column. For example,
3296 -80 works well for a normal 80 character screen.
3297 When 0, place tags directly after headline text, with only one space in
3298 between."
3299 :group 'org-tags
3300 :type 'integer)
3302 (defcustom org-auto-align-tags t
3303 "Non-nil keeps tags aligned when modifying headlines.
3304 Some operations (i.e. demoting) change the length of a headline and
3305 therefore shift the tags around. With this option turned on, after
3306 each such operation the tags are again aligned to `org-tags-column'."
3307 :group 'org-tags
3308 :type 'boolean)
3310 (defcustom org-use-tag-inheritance t
3311 "Non-nil means tags in levels apply also for sublevels.
3312 When nil, only the tags directly given in a specific line apply there.
3313 This may also be a list of tags that should be inherited, or a regexp that
3314 matches tags that should be inherited. Additional control is possible
3315 with the variable `org-tags-exclude-from-inheritance' which gives an
3316 explicit list of tags to be excluded from inheritance, even if the value of
3317 `org-use-tag-inheritance' would select it for inheritance.
3319 If this option is t, a match early-on in a tree can lead to a large
3320 number of matches in the subtree when constructing the agenda or creating
3321 a sparse tree. If you only want to see the first match in a tree during
3322 a search, check out the variable `org-tags-match-list-sublevels'."
3323 :group 'org-tags
3324 :type '(choice
3325 (const :tag "Not" nil)
3326 (const :tag "Always" t)
3327 (repeat :tag "Specific tags" (string :tag "Tag"))
3328 (regexp :tag "Tags matched by regexp")))
3330 (defcustom org-tags-exclude-from-inheritance nil
3331 "List of tags that should never be inherited.
3332 This is a way to exclude a few tags from inheritance. For way to do
3333 the opposite, to actively allow inheritance for selected tags,
3334 see the variable `org-use-tag-inheritance'."
3335 :group 'org-tags
3336 :type '(repeat (string :tag "Tag")))
3338 (defun org-tag-inherit-p (tag)
3339 "Check if TAG is one that should be inherited."
3340 (cond
3341 ((member tag org-tags-exclude-from-inheritance) nil)
3342 ((eq org-use-tag-inheritance t) t)
3343 ((not org-use-tag-inheritance) nil)
3344 ((stringp org-use-tag-inheritance)
3345 (string-match org-use-tag-inheritance tag))
3346 ((listp org-use-tag-inheritance)
3347 (member tag org-use-tag-inheritance))
3348 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3350 (defcustom org-tags-match-list-sublevels t
3351 "Non-nil means list also sublevels of headlines matching a search.
3352 This variable applies to tags/property searches, and also to stuck
3353 projects because this search is based on a tags match as well.
3355 When set to the symbol `indented', sublevels are indented with
3356 leading dots.
3358 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3359 the sublevels of a headline matching a tag search often also match
3360 the same search. Listing all of them can create very long lists.
3361 Setting this variable to nil causes subtrees of a match to be skipped.
3363 This variable is semi-obsolete and probably should always be true. It
3364 is better to limit inheritance to certain tags using the variables
3365 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3366 :group 'org-tags
3367 :type '(choice
3368 (const :tag "No, don't list them" nil)
3369 (const :tag "Yes, do list them" t)
3370 (const :tag "List them, indented with leading dots" indented)))
3372 (defcustom org-tags-sort-function nil
3373 "When set, tags are sorted using this function as a comparator."
3374 :group 'org-tags
3375 :type '(choice
3376 (const :tag "No sorting" nil)
3377 (const :tag "Alphabetical" string<)
3378 (const :tag "Reverse alphabetical" string>)
3379 (function :tag "Custom function" nil)))
3381 (defvar org-tags-history nil
3382 "History of minibuffer reads for tags.")
3383 (defvar org-last-tags-completion-table nil
3384 "The last used completion table for tags.")
3385 (defvar org-after-tags-change-hook nil
3386 "Hook that is run after the tags in a line have changed.")
3388 (defgroup org-properties nil
3389 "Options concerning properties in Org-mode."
3390 :tag "Org Properties"
3391 :group 'org)
3393 (defcustom org-property-format "%-10s %s"
3394 "How property key/value pairs should be formatted by `indent-line'.
3395 When `indent-line' hits a property definition, it will format the line
3396 according to this format, mainly to make sure that the values are
3397 lined-up with respect to each other."
3398 :group 'org-properties
3399 :type 'string)
3401 (defcustom org-properties-postprocess-alist nil
3402 "Alist of properties and functions to adjust inserted values.
3403 Elements of this alist must be of the form
3405 ([string] [function])
3407 where [string] must be a property name and [function] must be a
3408 lambda expression: this lambda expression must take one argument,
3409 the value to adjust, and return the new value as a string.
3411 For example, this element will allow the property \"Remaining\"
3412 to be updated wrt the relation between the \"Effort\" property
3413 and the clock summary:
3415 ((\"Remaining\" (lambda(value)
3416 (let ((clocksum (org-clock-sum-current-item))
3417 (effort (org-duration-string-to-minutes
3418 (org-entry-get (point) \"Effort\"))))
3419 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3420 :group 'org-properties
3421 :version "24.1"
3422 :type '(alist :key-type (string :tag "Property")
3423 :value-type (function :tag "Function")))
3425 (defcustom org-use-property-inheritance nil
3426 "Non-nil means properties apply also for sublevels.
3428 This setting is chiefly used during property searches. Turning it on can
3429 cause significant overhead when doing a search, which is why it is not
3430 on by default.
3432 When nil, only the properties directly given in the current entry count.
3433 When t, every property is inherited. The value may also be a list of
3434 properties that should have inheritance, or a regular expression matching
3435 properties that should be inherited.
3437 However, note that some special properties use inheritance under special
3438 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3439 and the properties ending in \"_ALL\" when they are used as descriptor
3440 for valid values of a property.
3442 Note for programmers:
3443 When querying an entry with `org-entry-get', you can control if inheritance
3444 should be used. By default, `org-entry-get' looks only at the local
3445 properties. You can request inheritance by setting the inherit argument
3446 to t (to force inheritance) or to `selective' (to respect the setting
3447 in this variable)."
3448 :group 'org-properties
3449 :type '(choice
3450 (const :tag "Not" nil)
3451 (const :tag "Always" t)
3452 (repeat :tag "Specific properties" (string :tag "Property"))
3453 (regexp :tag "Properties matched by regexp")))
3455 (defun org-property-inherit-p (property)
3456 "Check if PROPERTY is one that should be inherited."
3457 (cond
3458 ((eq org-use-property-inheritance t) t)
3459 ((not org-use-property-inheritance) nil)
3460 ((stringp org-use-property-inheritance)
3461 (string-match org-use-property-inheritance property))
3462 ((listp org-use-property-inheritance)
3463 (member property org-use-property-inheritance))
3464 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3466 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3467 "The default column format, if no other format has been defined.
3468 This variable can be set on the per-file basis by inserting a line
3470 #+COLUMNS: %25ITEM ....."
3471 :group 'org-properties
3472 :type 'string)
3474 (defcustom org-columns-ellipses ".."
3475 "The ellipses to be used when a field in column view is truncated.
3476 When this is the empty string, as many characters as possible are shown,
3477 but then there will be no visual indication that the field has been truncated.
3478 When this is a string of length N, the last N characters of a truncated
3479 field are replaced by this string. If the column is narrower than the
3480 ellipses string, only part of the ellipses string will be shown."
3481 :group 'org-properties
3482 :type 'string)
3484 (defcustom org-columns-modify-value-for-display-function nil
3485 "Function that modifies values for display in column view.
3486 For example, it can be used to cut out a certain part from a time stamp.
3487 The function must take 2 arguments:
3489 column-title The title of the column (*not* the property name)
3490 value The value that should be modified.
3492 The function should return the value that should be displayed,
3493 or nil if the normal value should be used."
3494 :group 'org-properties
3495 :type 'function)
3497 (defcustom org-effort-property "Effort"
3498 "The property that is being used to keep track of effort estimates.
3499 Effort estimates given in this property need to have the format H:MM."
3500 :group 'org-properties
3501 :group 'org-progress
3502 :type '(string :tag "Property"))
3504 (defconst org-global-properties-fixed
3505 '(("VISIBILITY_ALL" . "folded children content all")
3506 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3507 "List of property/value pairs that can be inherited by any entry.
3509 These are fixed values, for the preset properties. The user variable
3510 that can be used to add to this list is `org-global-properties'.
3512 The entries in this list are cons cells where the car is a property
3513 name and cdr is a string with the value. If the value represents
3514 multiple items like an \"_ALL\" property, separate the items by
3515 spaces.")
3517 (defcustom org-global-properties nil
3518 "List of property/value pairs that can be inherited by any entry.
3520 This list will be combined with the constant `org-global-properties-fixed'.
3522 The entries in this list are cons cells where the car is a property
3523 name and cdr is a string with the value.
3525 You can set buffer-local values for the same purpose in the variable
3526 `org-file-properties' this by adding lines like
3528 #+PROPERTY: NAME VALUE"
3529 :group 'org-properties
3530 :type '(repeat
3531 (cons (string :tag "Property")
3532 (string :tag "Value"))))
3534 (defvar org-file-properties nil
3535 "List of property/value pairs that can be inherited by any entry.
3536 Valid for the current buffer.
3537 This variable is populated from #+PROPERTY lines.")
3538 (make-variable-buffer-local 'org-file-properties)
3540 (defgroup org-agenda nil
3541 "Options concerning agenda views in Org-mode."
3542 :tag "Org Agenda"
3543 :group 'org)
3545 (defvar org-category nil
3546 "Variable used by org files to set a category for agenda display.
3547 Such files should use a file variable to set it, for example
3549 # -*- mode: org; org-category: \"ELisp\"
3551 or contain a special line
3553 #+CATEGORY: ELisp
3555 If the file does not specify a category, then file's base name
3556 is used instead.")
3557 (make-variable-buffer-local 'org-category)
3558 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3560 (defcustom org-agenda-files nil
3561 "The files to be used for agenda display.
3562 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3563 \\[org-remove-file]. You can also use customize to edit the list.
3565 If an entry is a directory, all files in that directory that are matched by
3566 `org-agenda-file-regexp' will be part of the file list.
3568 If the value of the variable is not a list but a single file name, then
3569 the list of agenda files is actually stored and maintained in that file, one
3570 agenda file per line. In this file paths can be given relative to
3571 `org-directory'. Tilde expansion and environment variable substitution
3572 are also made."
3573 :group 'org-agenda
3574 :type '(choice
3575 (repeat :tag "List of files and directories" file)
3576 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3578 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3579 "Regular expression to match files for `org-agenda-files'.
3580 If any element in the list in that variable contains a directory instead
3581 of a normal file, all files in that directory that are matched by this
3582 regular expression will be included."
3583 :group 'org-agenda
3584 :type 'regexp)
3586 (defcustom org-agenda-text-search-extra-files nil
3587 "List of extra files to be searched by text search commands.
3588 These files will be searched in addition to the agenda files by the
3589 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3590 Note that these files will only be searched for text search commands,
3591 not for the other agenda views like todo lists, tag searches or the weekly
3592 agenda. This variable is intended to list notes and possibly archive files
3593 that should also be searched by these two commands.
3594 In fact, if the first element in the list is the symbol `agenda-archives',
3595 then all archive files of all agenda files will be added to the search
3596 scope."
3597 :group 'org-agenda
3598 :type '(set :greedy t
3599 (const :tag "Agenda Archives" agenda-archives)
3600 (repeat :inline t (file))))
3602 (org-defvaralias 'org-agenda-multi-occur-extra-files
3603 'org-agenda-text-search-extra-files)
3605 (defcustom org-agenda-skip-unavailable-files nil
3606 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3607 A nil value means to remove them, after a query, from the list."
3608 :group 'org-agenda
3609 :type 'boolean)
3611 (defcustom org-calendar-to-agenda-key [?c]
3612 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3613 The command `org-calendar-goto-agenda' will be bound to this key. The
3614 default is the character `c' because then `c' can be used to switch back and
3615 forth between agenda and calendar."
3616 :group 'org-agenda
3617 :type 'sexp)
3619 (defcustom org-calendar-insert-diary-entry-key [?i]
3620 "The key to be installed in `calendar-mode-map' for adding diary entries.
3621 This option is irrelevant until `org-agenda-diary-file' has been configured
3622 to point to an Org-mode file. When that is the case, the command
3623 `org-agenda-diary-entry' will be bound to the key given here, by default
3624 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3625 if you want to continue doing this, you need to change this to a different
3626 key."
3627 :group 'org-agenda
3628 :type 'sexp)
3630 (defcustom org-agenda-diary-file 'diary-file
3631 "File to which to add new entries with the `i' key in agenda and calendar.
3632 When this is the symbol `diary-file', the functionality in the Emacs
3633 calendar will be used to add entries to the `diary-file'. But when this
3634 points to a file, `org-agenda-diary-entry' will be used instead."
3635 :group 'org-agenda
3636 :type '(choice
3637 (const :tag "The standard Emacs diary file" diary-file)
3638 (file :tag "Special Org file diary entries")))
3640 (eval-after-load "calendar"
3641 '(progn
3642 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3643 'org-calendar-goto-agenda)
3644 (add-hook 'calendar-mode-hook
3645 (lambda ()
3646 (unless (eq org-agenda-diary-file 'diary-file)
3647 (define-key calendar-mode-map
3648 org-calendar-insert-diary-entry-key
3649 'org-agenda-diary-entry))))))
3651 (defgroup org-latex nil
3652 "Options for embedding LaTeX code into Org-mode."
3653 :tag "Org LaTeX"
3654 :group 'org)
3656 (defcustom org-format-latex-options
3657 '(:foreground default :background default :scale 1.0
3658 :html-foreground "Black" :html-background "Transparent"
3659 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3660 "Options for creating images from LaTeX fragments.
3661 This is a property list with the following properties:
3662 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3663 `default' means use the foreground of the default face.
3664 `auto' means use the foreground from the text face.
3665 :background the background color, or \"Transparent\".
3666 `default' means use the background of the default face.
3667 `auto' means use the background from the text face.
3668 :scale a scaling factor for the size of the images, to get more pixels
3669 :html-foreground, :html-background, :html-scale
3670 the same numbers for HTML export.
3671 :matchers a list indicating which matchers should be used to
3672 find LaTeX fragments. Valid members of this list are:
3673 \"begin\" find environments
3674 \"$1\" find single characters surrounded by $.$
3675 \"$\" find math expressions surrounded by $...$
3676 \"$$\" find math expressions surrounded by $$....$$
3677 \"\\(\" find math expressions surrounded by \\(...\\)
3678 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3679 :group 'org-latex
3680 :type 'plist)
3682 (defcustom org-format-latex-signal-error t
3683 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3684 When nil, just push out a message."
3685 :group 'org-latex
3686 :version "24.1"
3687 :type 'boolean)
3689 (defcustom org-latex-to-mathml-jar-file nil
3690 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3691 Use this to specify additional executable file say a jar file.
3693 When using MathToWeb as the converter, specify the full-path to
3694 your mathtoweb.jar file."
3695 :group 'org-latex
3696 :version "24.1"
3697 :type '(choice
3698 (const :tag "None" nil)
3699 (file :tag "JAR file" :must-match t)))
3701 (defcustom org-latex-to-mathml-convert-command nil
3702 "Command to convert LaTeX fragments to MathML.
3703 Replace format-specifiers in the command as noted below and use
3704 `shell-command' to convert LaTeX to MathML.
3705 %j: Executable file in fully expanded form as specified by
3706 `org-latex-to-mathml-jar-file'.
3707 %I: Input LaTeX file in fully expanded form
3708 %o: Output MathML file
3709 This command is used by `org-create-math-formula'.
3711 When using MathToWeb as the converter, set this to
3712 \"java -jar %j -unicode -force -df %o %I\"."
3713 :group 'org-latex
3714 :version "24.1"
3715 :type '(choice
3716 (const :tag "None" nil)
3717 (string :tag "\nShell command")))
3719 (defcustom org-latex-create-formula-image-program 'dvipng
3720 "Program to convert LaTeX fragments with.
3722 dvipng Process the LaTeX fragments to dvi file, then convert
3723 dvi files to png files using dvipng.
3724 This will also include processing of non-math environments.
3725 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3726 to convert pdf files to png files"
3727 :group 'org-latex
3728 :version "24.1"
3729 :type '(choice
3730 (const :tag "dvipng" dvipng)
3731 (const :tag "imagemagick" imagemagick)))
3733 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3734 "Path to store latex preview images.
3735 A relative path here creates many directories relative to the
3736 processed org files paths. An absolute path puts all preview
3737 images at the same place."
3738 :group 'org-latex
3739 :version "24.3"
3740 :type 'string)
3742 (defun org-format-latex-mathml-available-p ()
3743 "Return t if `org-latex-to-mathml-convert-command' is usable."
3744 (save-match-data
3745 (when (and (boundp 'org-latex-to-mathml-convert-command)
3746 org-latex-to-mathml-convert-command)
3747 (let ((executable (car (split-string
3748 org-latex-to-mathml-convert-command))))
3749 (when (executable-find executable)
3750 (if (string-match
3751 "%j" org-latex-to-mathml-convert-command)
3752 (file-readable-p org-latex-to-mathml-jar-file)
3753 t))))))
3755 (defcustom org-format-latex-header "\\documentclass{article}
3756 \\usepackage[usenames]{color}
3757 \\usepackage{amsmath}
3758 \\usepackage[mathscr]{eucal}
3759 \\pagestyle{empty} % do not remove
3760 \[PACKAGES]
3761 \[DEFAULT-PACKAGES]
3762 % The settings below are copied from fullpage.sty
3763 \\setlength{\\textwidth}{\\paperwidth}
3764 \\addtolength{\\textwidth}{-3cm}
3765 \\setlength{\\oddsidemargin}{1.5cm}
3766 \\addtolength{\\oddsidemargin}{-2.54cm}
3767 \\setlength{\\evensidemargin}{\\oddsidemargin}
3768 \\setlength{\\textheight}{\\paperheight}
3769 \\addtolength{\\textheight}{-\\headheight}
3770 \\addtolength{\\textheight}{-\\headsep}
3771 \\addtolength{\\textheight}{-\\footskip}
3772 \\addtolength{\\textheight}{-3cm}
3773 \\setlength{\\topmargin}{1.5cm}
3774 \\addtolength{\\topmargin}{-2.54cm}"
3775 "The document header used for processing LaTeX fragments.
3776 It is imperative that this header make sure that no page number
3777 appears on the page. The package defined in the variables
3778 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3779 will either replace the placeholder \"[PACKAGES]\" in this
3780 header, or they will be appended."
3781 :group 'org-latex
3782 :type 'string)
3784 (defun org-set-packages-alist (var val)
3785 "Set the packages alist and make sure it has 3 elements per entry."
3786 (set var (mapcar (lambda (x)
3787 (if (and (consp x) (= (length x) 2))
3788 (list (car x) (nth 1 x) t)
3790 val)))
3792 (defun org-get-packages-alist (var)
3793 "Get the packages alist and make sure it has 3 elements per entry."
3794 (mapcar (lambda (x)
3795 (if (and (consp x) (= (length x) 2))
3796 (list (car x) (nth 1 x) t)
3798 (default-value var)))
3800 (defcustom org-latex-default-packages-alist
3801 '(("AUTO" "inputenc" t)
3802 ("T1" "fontenc" t)
3803 ("" "fixltx2e" nil)
3804 ("" "graphicx" t)
3805 ("" "longtable" nil)
3806 ("" "float" nil)
3807 ("" "wrapfig" nil)
3808 ("" "soul" t)
3809 ("" "textcomp" t)
3810 ("" "marvosym" t)
3811 ("" "wasysym" t)
3812 ("" "latexsym" t)
3813 ("" "amssymb" t)
3814 ("" "amstext" nil)
3815 ("" "hyperref" nil)
3816 "\\tolerance=1000")
3817 "Alist of default packages to be inserted in the header.
3819 Change this only if one of the packages here causes an
3820 incompatibility with another package you are using.
3822 The packages in this list are needed by one part or another of
3823 Org mode to function properly:
3825 - inputenc, fontenc: for basic font and character selection
3826 - amstext: for subscript and superscript
3827 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3828 symbols used for interpreting the entities in `org-entities'.
3829 You can skip some of these packages if you don't use any of the
3830 symbols in it.
3831 - graphicx: for including images
3832 - float, wrapfig: for figure placement
3833 - longtable: for long tables
3834 - hyperref: for cross references
3836 Therefore you should not modify this variable unless you know
3837 what you are doing. The one reason to change it anyway is that
3838 you might be loading some other package that conflicts with one
3839 of the default packages. Each cell is of the format
3840 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3841 the package also needs to be included when compiling LaTeX
3842 snippets into images for inclusion into non-LaTeX output."
3843 :group 'org-latex
3844 :group 'org-export-latex
3845 :set 'org-set-packages-alist
3846 :get 'org-get-packages-alist
3847 :version "24.1"
3848 :type '(repeat
3849 (choice
3850 (list :tag "options/package pair"
3851 (string :tag "options")
3852 (string :tag "package")
3853 (boolean :tag "Snippet"))
3854 (string :tag "A line of LaTeX"))))
3856 (defcustom org-latex-packages-alist nil
3857 "Alist of packages to be inserted in every LaTeX header.
3859 These will be inserted after `org-latex-default-packages-alist'.
3860 Each cell is of the format:
3862 \(\"options\" \"package\" snippet-flag)
3864 SNIPPET-FLAG, when t, indicates that this package is also needed
3865 when turning LaTeX snippets into images for inclusion into
3866 non-LaTeX output.
3868 Make sure that you only list packages here which:
3870 - you want in every file
3871 - do not conflict with the setup in `org-format-latex-header'.
3872 - do not conflict with the default packages in
3873 `org-latex-default-packages-alist'."
3874 :group 'org-latex
3875 :group 'org-export-latex
3876 :set 'org-set-packages-alist
3877 :get 'org-get-packages-alist
3878 :type '(repeat
3879 (choice
3880 (list :tag "options/package pair"
3881 (string :tag "options")
3882 (string :tag "package")
3883 (boolean :tag "Snippet"))
3884 (string :tag "A line of LaTeX"))))
3886 (defgroup org-appearance nil
3887 "Settings for Org-mode appearance."
3888 :tag "Org Appearance"
3889 :group 'org)
3891 (defcustom org-level-color-stars-only nil
3892 "Non-nil means fontify only the stars in each headline.
3893 When nil, the entire headline is fontified.
3894 Changing it requires restart of `font-lock-mode' to become effective
3895 also in regions already fontified."
3896 :group 'org-appearance
3897 :type 'boolean)
3899 (defcustom org-hide-leading-stars nil
3900 "Non-nil means hide the first N-1 stars in a headline.
3901 This works by using the face `org-hide' for these stars. This
3902 face is white for a light background, and black for a dark
3903 background. You may have to customize the face `org-hide' to
3904 make this work.
3905 Changing it requires restart of `font-lock-mode' to become effective
3906 also in regions already fontified.
3907 You may also set this on a per-file basis by adding one of the following
3908 lines to the buffer:
3910 #+STARTUP: hidestars
3911 #+STARTUP: showstars"
3912 :group 'org-appearance
3913 :type 'boolean)
3915 (defcustom org-hidden-keywords nil
3916 "List of symbols corresponding to keywords to be hidden the org buffer.
3917 For example, a value '(title) for this list will make the document's title
3918 appear in the buffer without the initial #+TITLE: keyword."
3919 :group 'org-appearance
3920 :version "24.1"
3921 :type '(set (const :tag "#+AUTHOR" author)
3922 (const :tag "#+DATE" date)
3923 (const :tag "#+EMAIL" email)
3924 (const :tag "#+TITLE" title)))
3926 (defcustom org-custom-properties nil
3927 "List of properties (as strings) with a special meaning.
3928 The default use of these custom properties is to let the user
3929 hide them with `org-toggle-custom-properties-visibility'."
3930 :group 'org-properties
3931 :group 'org-appearance
3932 :version "24.3"
3933 :type '(repeat (string :tag "Property Name")))
3935 (defcustom org-fontify-done-headline nil
3936 "Non-nil means change the face of a headline if it is marked DONE.
3937 Normally, only the TODO/DONE keyword indicates the state of a headline.
3938 When this is non-nil, the headline after the keyword is set to the
3939 `org-headline-done' as an additional indication."
3940 :group 'org-appearance
3941 :type 'boolean)
3943 (defcustom org-fontify-emphasized-text t
3944 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3945 Changing this variable requires a restart of Emacs to take effect."
3946 :group 'org-appearance
3947 :type 'boolean)
3949 (defcustom org-fontify-whole-heading-line nil
3950 "Non-nil means fontify the whole line for headings.
3951 This is useful when setting a background color for the
3952 org-level-* faces."
3953 :group 'org-appearance
3954 :type 'boolean)
3956 (defcustom org-highlight-latex-and-related nil
3957 "Non-nil means highlight LaTeX related syntax in the buffer.
3958 When non nil, the value should be a list containing any of the
3959 following symbols:
3960 `latex' Highlight LaTeX snippets and environments.
3961 `script' Highlight subscript and superscript.
3962 `entities' Highlight entities."
3963 :group 'org-appearance
3964 :version "24.4"
3965 :package-version '(Org . "8.0")
3966 :type '(choice
3967 (const :tag "No highlighting" nil)
3968 (set :greedy t :tag "Highlight"
3969 (const :tag "LaTeX snippets and environments" latex)
3970 (const :tag "Subscript and superscript" script)
3971 (const :tag "Entities" entities))))
3973 (defcustom org-hide-emphasis-markers nil
3974 "Non-nil mean font-lock should hide the emphasis marker characters."
3975 :group 'org-appearance
3976 :type 'boolean)
3978 (defcustom org-pretty-entities nil
3979 "Non-nil means show entities as UTF8 characters.
3980 When nil, the \\name form remains in the buffer."
3981 :group 'org-appearance
3982 :version "24.1"
3983 :type 'boolean)
3985 (defcustom org-pretty-entities-include-sub-superscripts t
3986 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3987 :group 'org-appearance
3988 :version "24.1"
3989 :type 'boolean)
3991 (defvar org-emph-re nil
3992 "Regular expression for matching emphasis.
3993 After a match, the match groups contain these elements:
3994 0 The match of the full regular expression, including the characters
3995 before and after the proper match
3996 1 The character before the proper match, or empty at beginning of line
3997 2 The proper match, including the leading and trailing markers
3998 3 The leading marker like * or /, indicating the type of highlighting
3999 4 The text between the emphasis markers, not including the markers
4000 5 The character after the match, empty at the end of a line")
4001 (defvar org-verbatim-re nil
4002 "Regular expression for matching verbatim text.")
4003 (defvar org-emphasis-regexp-components) ; defined just below
4004 (defvar org-emphasis-alist) ; defined just below
4005 (defun org-set-emph-re (var val)
4006 "Set variable and compute the emphasis regular expression."
4007 (set var val)
4008 (when (and (boundp 'org-emphasis-alist)
4009 (boundp 'org-emphasis-regexp-components)
4010 org-emphasis-alist org-emphasis-regexp-components)
4011 (let* ((e org-emphasis-regexp-components)
4012 (pre (car e))
4013 (post (nth 1 e))
4014 (border (nth 2 e))
4015 (body (nth 3 e))
4016 (nl (nth 4 e))
4017 (body1 (concat body "*?"))
4018 (markers (mapconcat 'car org-emphasis-alist ""))
4019 (vmarkers (mapconcat
4020 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4021 org-emphasis-alist "")))
4022 ;; make sure special characters appear at the right position in the class
4023 (if (string-match "\\^" markers)
4024 (setq markers (concat (replace-match "" t t markers) "^")))
4025 (if (string-match "-" markers)
4026 (setq markers (concat (replace-match "" t t markers) "-")))
4027 (if (string-match "\\^" vmarkers)
4028 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4029 (if (string-match "-" vmarkers)
4030 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4031 (if (> nl 0)
4032 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4033 (int-to-string nl) "\\}")))
4034 ;; Make the regexp
4035 (setq org-emph-re
4036 (concat "\\([" pre "]\\|^\\)"
4037 "\\("
4038 "\\([" markers "]\\)"
4039 "\\("
4040 "[^" border "]\\|"
4041 "[^" border "]"
4042 body1
4043 "[^" border "]"
4044 "\\)"
4045 "\\3\\)"
4046 "\\([" post "]\\|$\\)"))
4047 (setq org-verbatim-re
4048 (concat "\\([" pre "]\\|^\\)"
4049 "\\("
4050 "\\([" vmarkers "]\\)"
4051 "\\("
4052 "[^" border "]\\|"
4053 "[^" border "]"
4054 body1
4055 "[^" border "]"
4056 "\\)"
4057 "\\3\\)"
4058 "\\([" post "]\\|$\\)")))))
4060 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4061 ;; set this option proved cumbersome. See this message/thread:
4062 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4063 (defvar org-emphasis-regexp-components
4064 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4065 "Components used to build the regular expression for emphasis.
4066 This is a list with five entries. Terminology: In an emphasis string
4067 like \" *strong word* \", we call the initial space PREMATCH, the final
4068 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4069 and \"trong wor\" is the body. The different components in this variable
4070 specify what is allowed/forbidden in each part:
4072 pre Chars allowed as prematch. Beginning of line will be allowed too.
4073 post Chars allowed as postmatch. End of line will be allowed too.
4074 border The chars *forbidden* as border characters.
4075 body-regexp A regexp like \".\" to match a body character. Don't use
4076 non-shy groups here, and don't allow newline here.
4077 newline The maximum number of newlines allowed in an emphasis exp.
4079 You need to reload Org or to restart Emacs after customizing this.")
4081 (defcustom org-emphasis-alist
4082 `(("*" bold)
4083 ("/" italic)
4084 ("_" underline)
4085 ("=" org-code verbatim)
4086 ("~" org-verbatim verbatim)
4087 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4088 "Alist of characters and faces to emphasize text.
4089 Text starting and ending with a special character will be emphasized,
4090 for example *bold*, _underlined_ and /italic/. This variable sets the
4091 marker characters and the face to be used by font-lock for highlighting
4092 in Org-mode Emacs buffers.
4094 You need to reload Org or to restart Emacs after customizing this."
4095 :group 'org-appearance
4096 :set 'org-set-emph-re
4097 :version "24.4"
4098 :package-version '(Org . "8.0")
4099 :type '(repeat
4100 (list
4101 (string :tag "Marker character")
4102 (choice
4103 (face :tag "Font-lock-face")
4104 (plist :tag "Face property list"))
4105 (option (const verbatim)))))
4107 (defvar org-protecting-blocks
4108 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4109 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4110 This is needed for font-lock setup.")
4112 ;;; Miscellaneous options
4114 (defgroup org-completion nil
4115 "Completion in Org-mode."
4116 :tag "Org Completion"
4117 :group 'org)
4119 (defcustom org-completion-use-ido nil
4120 "Non-nil means use ido completion wherever possible.
4121 Note that `ido-mode' must be active for this variable to be relevant.
4122 If you decide to turn this variable on, you might well want to turn off
4123 `org-outline-path-complete-in-steps'.
4124 See also `org-completion-use-iswitchb'."
4125 :group 'org-completion
4126 :type 'boolean)
4128 (defcustom org-completion-use-iswitchb nil
4129 "Non-nil means use iswitchb completion wherever possible.
4130 Note that `iswitchb-mode' must be active for this variable to be relevant.
4131 If you decide to turn this variable on, you might well want to turn off
4132 `org-outline-path-complete-in-steps'.
4133 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4134 :group 'org-completion
4135 :type 'boolean)
4137 (defcustom org-completion-fallback-command 'hippie-expand
4138 "The expansion command called by \\[pcomplete] in normal context.
4139 Normal means, no org-mode-specific context."
4140 :group 'org-completion
4141 :type 'function)
4143 ;;; Functions and variables from their packages
4144 ;; Declared here to avoid compiler warnings
4146 ;; XEmacs only
4147 (defvar outline-mode-menu-heading)
4148 (defvar outline-mode-menu-show)
4149 (defvar outline-mode-menu-hide)
4150 (defvar zmacs-regions) ; XEmacs regions
4152 ;; Emacs only
4153 (defvar mark-active)
4155 ;; Various packages
4156 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4157 (declare-function calendar-forward-day "cal-move" (arg))
4158 (declare-function calendar-goto-date "cal-move" (date))
4159 (declare-function calendar-goto-today "cal-move" ())
4160 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4161 (defvar calc-embedded-close-formula)
4162 (defvar calc-embedded-open-formula)
4163 (declare-function cdlatex-tab "ext:cdlatex" ())
4164 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4165 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4166 (defvar font-lock-unfontify-region-function)
4167 (declare-function iswitchb-read-buffer "iswitchb"
4168 (prompt &optional default require-match start matches-set))
4169 (defvar iswitchb-temp-buflist)
4170 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4171 (defvar org-agenda-tags-todo-honor-ignore-options)
4172 (declare-function org-agenda-skip "org-agenda" ())
4173 (declare-function
4174 org-agenda-format-item "org-agenda"
4175 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4176 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4177 (declare-function org-agenda-change-all-lines "org-agenda"
4178 (newhead hdmarker &optional fixface just-this))
4179 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4180 (declare-function org-agenda-maybe-redo "org-agenda" ())
4181 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4182 (beg end))
4183 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4184 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4185 "org-agenda" (&optional end))
4186 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4187 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4188 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4189 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4190 (declare-function org-indent-mode "org-indent" (&optional arg))
4191 (declare-function parse-time-string "parse-time" (string))
4192 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4193 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4194 (defvar remember-data-file)
4195 (defvar texmathp-why)
4196 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4197 (declare-function table--at-cell-p "table" (position &optional object at-column))
4199 (defvar org-latex-regexps)
4201 ;;; Autoload and prepare some org modules
4203 ;; Some table stuff that needs to be defined here, because it is used
4204 ;; by the functions setting up org-mode or checking for table context.
4206 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4207 "Detect an org-type or table-type table.")
4208 (defconst org-table-line-regexp "^[ \t]*|"
4209 "Detect an org-type table line.")
4210 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4211 "Detect an org-type table line.")
4212 (defconst org-table-hline-regexp "^[ \t]*|-"
4213 "Detect an org-type table hline.")
4214 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4215 "Detect a table-type table hline.")
4216 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4217 "Detect the first line outside a table when searching from within it.
4218 This works for both table types.")
4220 ;; Autoload the functions in org-table.el that are needed by functions here.
4222 (eval-and-compile
4223 (org-autoload "org-table"
4224 '(org-table-begin org-table-blank-field org-table-end)))
4226 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
4227 "Detect a #+TBLFM line.")
4229 ;;;###autoload
4230 (defun turn-on-orgtbl ()
4231 "Unconditionally turn on `orgtbl-mode'."
4232 (require 'org-table)
4233 (orgtbl-mode 1))
4235 (defun org-at-table-p (&optional table-type)
4236 "Return t if the cursor is inside an org-type table.
4237 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4238 (if org-enable-table-editor
4239 (save-excursion
4240 (beginning-of-line 1)
4241 (looking-at (if table-type org-table-any-line-regexp
4242 org-table-line-regexp)))
4243 nil))
4244 (defsubst org-table-p () (org-at-table-p))
4246 (defun org-at-table.el-p ()
4247 "Return t if and only if we are at a table.el table."
4248 (and (org-at-table-p 'any)
4249 (save-excursion
4250 (goto-char (org-table-begin 'any))
4251 (looking-at org-table1-hline-regexp))))
4253 (defun org-table-recognize-table.el ()
4254 "If there is a table.el table nearby, recognize it and move into it."
4255 (if org-table-tab-recognizes-table.el
4256 (if (org-at-table.el-p)
4257 (progn
4258 (beginning-of-line 1)
4259 (if (looking-at org-table-dataline-regexp)
4261 (if (looking-at org-table1-hline-regexp)
4262 (progn
4263 (beginning-of-line 2)
4264 (if (looking-at org-table-any-border-regexp)
4265 (beginning-of-line -1)))))
4266 (if (re-search-forward "|" (org-table-end t) t)
4267 (progn
4268 (require 'table)
4269 (if (table--at-cell-p (point))
4271 (message "recognizing table.el table...")
4272 (table-recognize-table)
4273 (message "recognizing table.el table...done")))
4274 (error "This should not happen"))
4276 nil)
4277 nil))
4279 (defun org-at-table-hline-p ()
4280 "Return t if the cursor is inside a hline in a table."
4281 (if org-enable-table-editor
4282 (save-excursion
4283 (beginning-of-line 1)
4284 (looking-at org-table-hline-regexp))
4285 nil))
4287 (defvar org-table-clean-did-remove-column nil)
4288 (defun org-table-map-tables (function &optional quietly)
4289 "Apply FUNCTION to the start of all tables in the buffer."
4290 (save-excursion
4291 (save-restriction
4292 (widen)
4293 (goto-char (point-min))
4294 (while (re-search-forward org-table-any-line-regexp nil t)
4295 (unless quietly
4296 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4297 (beginning-of-line 1)
4298 (when (and (looking-at org-table-line-regexp)
4299 ;; Exclude tables in src/example/verbatim/clocktable blocks
4300 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4301 (save-excursion (funcall function))
4302 (or (looking-at org-table-line-regexp)
4303 (forward-char 1)))
4304 (re-search-forward org-table-any-border-regexp nil 1))))
4305 (unless quietly (message "Mapping tables: done")))
4307 ;; Declare and autoload functions from ox.el and al.
4309 (declare-function org-export-get-environment "ox"
4310 (&optional backend subtreep ext-plist))
4311 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4313 ;; Declare and autoload functions from org-agenda.el
4315 (eval-and-compile
4316 (org-autoload "org-agenda"
4317 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4319 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4320 (declare-function org-clock-update-mode-line "org-clock" ())
4321 (declare-function org-resolve-clocks "org-clock"
4322 (&optional also-non-dangling-p prompt last-valid))
4324 (defun org-at-TBLFM-p (&optional pos)
4325 "Return t when point (or POS) is in #+TBLFM line."
4326 (save-excursion
4327 (let ((pos pos)))
4328 (goto-char (or pos (point)))
4329 (beginning-of-line 1)
4330 (looking-at org-TBLFM-regexp)))
4332 (defvar org-clock-start-time)
4333 (defvar org-clock-marker (make-marker)
4334 "Marker recording the last clock-in.")
4335 (defvar org-clock-hd-marker (make-marker)
4336 "Marker recording the last clock-in, but the headline position.")
4337 (defvar org-clock-heading ""
4338 "The heading of the current clock entry.")
4339 (defun org-clock-is-active ()
4340 "Return non-nil if clock is currently running.
4341 The return value is actually the clock marker."
4342 (marker-buffer org-clock-marker))
4344 (eval-and-compile
4345 (org-autoload "org-clock" '(org-clock-remove-overlays
4346 org-clock-update-time-maybe
4347 org-clocktable-shift)))
4349 (defun org-check-running-clock ()
4350 "Check if the current buffer contains the running clock.
4351 If yes, offer to stop it and to save the buffer with the changes."
4352 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4353 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4354 (buffer-name))))
4355 (org-clock-out)
4356 (when (y-or-n-p "Save changed buffer?")
4357 (save-buffer))))
4359 (defun org-clocktable-try-shift (dir n)
4360 "Check if this line starts a clock table, if yes, shift the time block."
4361 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4362 (org-clocktable-shift dir n)))
4364 ;;;###autoload
4365 (defun org-clock-persistence-insinuate ()
4366 "Set up hooks for clock persistence."
4367 (require 'org-clock)
4368 (add-hook 'org-mode-hook 'org-clock-load)
4369 (add-hook 'kill-emacs-hook 'org-clock-save))
4371 ;; Define the variable already here, to make sure we have it.
4372 (defvar org-indent-mode nil
4373 "Non-nil if Org-Indent mode is enabled.
4374 Use the command `org-indent-mode' to change this variable.")
4376 ;; Autoload archiving code
4377 ;; The stuff that is needed for cycling and tags has to be defined here.
4379 (defgroup org-archive nil
4380 "Options concerning archiving in Org-mode."
4381 :tag "Org Archive"
4382 :group 'org-structure)
4384 (defcustom org-archive-location "%s_archive::"
4385 "The location where subtrees should be archived.
4387 The value of this variable is a string, consisting of two parts,
4388 separated by a double-colon. The first part is a filename and
4389 the second part is a headline.
4391 When the filename is omitted, archiving happens in the same file.
4392 %s in the filename will be replaced by the current file
4393 name (without the directory part). Archiving to a different file
4394 is useful to keep archived entries from contributing to the
4395 Org-mode Agenda.
4397 The archived entries will be filed as subtrees of the specified
4398 headline. When the headline is omitted, the subtrees are simply
4399 filed away at the end of the file, as top-level entries. Also in
4400 the heading you can use %s to represent the file name, this can be
4401 useful when using the same archive for a number of different files.
4403 Here are a few examples:
4404 \"%s_archive::\"
4405 If the current file is Projects.org, archive in file
4406 Projects.org_archive, as top-level trees. This is the default.
4408 \"::* Archived Tasks\"
4409 Archive in the current file, under the top-level headline
4410 \"* Archived Tasks\".
4412 \"~/org/archive.org::\"
4413 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4415 \"~/org/archive.org::* From %s\"
4416 Archive in file ~/org/archive.org (absolute path), under headlines
4417 \"From FILENAME\" where file name is the current file name.
4419 \"~/org/datetree.org::datetree/* Finished Tasks\"
4420 The \"datetree/\" string is special, signifying to archive
4421 items to the datetree. Items are placed in either the CLOSED
4422 date of the item, or the current date if there is no CLOSED date.
4423 The heading will be a subentry to the current date. There doesn't
4424 need to be a heading, but there always needs to be a slash after
4425 datetree. For example, to store archived items directly in the
4426 datetree, use \"~/org/datetree.org::datetree/\".
4428 \"basement::** Finished Tasks\"
4429 Archive in file ./basement (relative path), as level 3 trees
4430 below the level 2 heading \"** Finished Tasks\".
4432 You may set this option on a per-file basis by adding to the buffer a
4433 line like
4435 #+ARCHIVE: basement::** Finished Tasks
4437 You may also define it locally for a subtree by setting an ARCHIVE property
4438 in the entry. If such a property is found in an entry, or anywhere up
4439 the hierarchy, it will be used."
4440 :group 'org-archive
4441 :type 'string)
4443 (defcustom org-archive-tag "ARCHIVE"
4444 "The tag that marks a subtree as archived.
4445 An archived subtree does not open during visibility cycling, and does
4446 not contribute to the agenda listings.
4447 After changing this, font-lock must be restarted in the relevant buffers to
4448 get the proper fontification."
4449 :group 'org-archive
4450 :group 'org-keywords
4451 :type 'string)
4453 (defcustom org-agenda-skip-archived-trees t
4454 "Non-nil means the agenda will skip any items located in archived trees.
4455 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4456 variable is no longer recommended, you should leave it at the value t.
4457 Instead, use the key `v' to cycle the archives-mode in the agenda."
4458 :group 'org-archive
4459 :group 'org-agenda-skip
4460 :type 'boolean)
4462 (defcustom org-columns-skip-archived-trees t
4463 "Non-nil means ignore archived trees when creating column view."
4464 :group 'org-archive
4465 :group 'org-properties
4466 :type 'boolean)
4468 (defcustom org-cycle-open-archived-trees nil
4469 "Non-nil means `org-cycle' will open archived trees.
4470 An archived tree is a tree marked with the tag ARCHIVE.
4471 When nil, archived trees will stay folded. You can still open them with
4472 normal outline commands like `show-all', but not with the cycling commands."
4473 :group 'org-archive
4474 :group 'org-cycle
4475 :type 'boolean)
4477 (defcustom org-sparse-tree-open-archived-trees nil
4478 "Non-nil means sparse tree construction shows matches in archived trees.
4479 When nil, matches in these trees are highlighted, but the trees are kept in
4480 collapsed state."
4481 :group 'org-archive
4482 :group 'org-sparse-trees
4483 :type 'boolean)
4485 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4486 "The default date type when building a sparse tree.
4487 When this is nil, a date is a scheduled or a deadline timestamp.
4488 Otherwise, these types are allowed:
4490 all: all timestamps
4491 active: only active timestamps (<...>)
4492 inactive: only inactive timestamps (<...)
4493 scheduled: only scheduled timestamps
4494 deadline: only deadline timestamps"
4495 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4496 (const :tag "All timestamps" all)
4497 (const :tag "Only active timestamps" active)
4498 (const :tag "Only inactive timestamps" inactive)
4499 (const :tag "Only scheduled timestamps" scheduled)
4500 (const :tag "Only deadline timestamps" deadline)
4501 (const :tag "Only closed timestamps" closed))
4502 :version "24.3"
4503 :group 'org-sparse-trees)
4505 (defun org-cycle-hide-archived-subtrees (state)
4506 "Re-hide all archived subtrees after a visibility state change."
4507 (when (and (not org-cycle-open-archived-trees)
4508 (not (memq state '(overview folded))))
4509 (save-excursion
4510 (let* ((globalp (memq state '(contents all)))
4511 (beg (if globalp (point-min) (point)))
4512 (end (if globalp (point-max) (org-end-of-subtree t))))
4513 (org-hide-archived-subtrees beg end)
4514 (goto-char beg)
4515 (if (looking-at (concat ".*:" org-archive-tag ":"))
4516 (message "%s" (substitute-command-keys
4517 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4519 (defun org-force-cycle-archived ()
4520 "Cycle subtree even if it is archived."
4521 (interactive)
4522 (setq this-command 'org-cycle)
4523 (let ((org-cycle-open-archived-trees t))
4524 (call-interactively 'org-cycle)))
4526 (defun org-hide-archived-subtrees (beg end)
4527 "Re-hide all archived subtrees after a visibility state change."
4528 (save-excursion
4529 (let* ((re (concat ":" org-archive-tag ":")))
4530 (goto-char beg)
4531 (while (re-search-forward re end t)
4532 (when (org-at-heading-p)
4533 (org-flag-subtree t)
4534 (org-end-of-subtree t))))))
4536 (declare-function outline-end-of-heading "outline" ())
4537 (declare-function outline-flag-region "outline" (from to flag))
4538 (defun org-flag-subtree (flag)
4539 (save-excursion
4540 (org-back-to-heading t)
4541 (outline-end-of-heading)
4542 (outline-flag-region (point)
4543 (progn (org-end-of-subtree t) (point))
4544 flag)))
4546 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4548 (eval-and-compile
4549 (org-autoload "org-archive"
4550 '(org-add-archive-files)))
4552 ;; Autoload Column View Code
4554 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4555 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4556 (declare-function org-columns-compute "org-colview" (property))
4558 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4559 '(org-columns-number-to-string
4560 org-columns-get-format-and-top-level
4561 org-columns-compute
4562 org-columns-remove-overlays))
4564 ;; Autoload ID code
4566 (declare-function org-id-store-link "org-id")
4567 (declare-function org-id-locations-load "org-id")
4568 (declare-function org-id-locations-save "org-id")
4569 (defvar org-id-track-globally)
4570 (org-autoload "org-id"
4571 '(org-id-new
4572 org-id-copy
4573 org-id-get-with-outline-path-completion
4574 org-id-get-with-outline-drilling))
4576 ;;; Variables for pre-computed regular expressions, all buffer local
4578 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4579 "Matches first line of a hidden block.")
4580 (make-variable-buffer-local 'org-drawer-regexp)
4581 (defvar org-todo-regexp nil
4582 "Matches any of the TODO state keywords.")
4583 (make-variable-buffer-local 'org-todo-regexp)
4584 (defvar org-not-done-regexp nil
4585 "Matches any of the TODO state keywords except the last one.")
4586 (make-variable-buffer-local 'org-not-done-regexp)
4587 (defvar org-not-done-heading-regexp nil
4588 "Matches a TODO headline that is not done.")
4589 (make-variable-buffer-local 'org-not-done-regexp)
4590 (defvar org-todo-line-regexp nil
4591 "Matches a headline and puts TODO state into group 2 if present.")
4592 (make-variable-buffer-local 'org-todo-line-regexp)
4593 (defvar org-complex-heading-regexp nil
4594 "Matches a headline and puts everything into groups:
4595 group 1: the stars
4596 group 2: The todo keyword, maybe
4597 group 3: Priority cookie
4598 group 4: True headline
4599 group 5: Tags")
4600 (make-variable-buffer-local 'org-complex-heading-regexp)
4601 (defvar org-complex-heading-regexp-format nil
4602 "Printf format to make regexp to match an exact headline.
4603 This regexp will match the headline of any node which has the
4604 exact headline text that is put into the format, but may have any
4605 TODO state, priority and tags.")
4606 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4607 (defvar org-todo-line-tags-regexp nil
4608 "Matches a headline and puts TODO state into group 2 if present.
4609 Also put tags into group 4 if tags are present.")
4610 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4611 (defvar org-ds-keyword-length 12
4612 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4613 (make-variable-buffer-local 'org-ds-keyword-length)
4614 (defvar org-deadline-regexp nil
4615 "Matches the DEADLINE keyword.")
4616 (make-variable-buffer-local 'org-deadline-regexp)
4617 (defvar org-deadline-time-regexp nil
4618 "Matches the DEADLINE keyword together with a time stamp.")
4619 (make-variable-buffer-local 'org-deadline-time-regexp)
4620 (defvar org-deadline-time-hour-regexp nil
4621 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4622 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4623 (defvar org-deadline-line-regexp nil
4624 "Matches the DEADLINE keyword and the rest of the line.")
4625 (make-variable-buffer-local 'org-deadline-line-regexp)
4626 (defvar org-scheduled-regexp nil
4627 "Matches the SCHEDULED keyword.")
4628 (make-variable-buffer-local 'org-scheduled-regexp)
4629 (defvar org-scheduled-time-regexp nil
4630 "Matches the SCHEDULED keyword together with a time stamp.")
4631 (make-variable-buffer-local 'org-scheduled-time-regexp)
4632 (defvar org-scheduled-time-hour-regexp nil
4633 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4634 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4635 (defvar org-closed-time-regexp nil
4636 "Matches the CLOSED keyword together with a time stamp.")
4637 (make-variable-buffer-local 'org-closed-time-regexp)
4639 (defvar org-keyword-time-regexp nil
4640 "Matches any of the 4 keywords, together with the time stamp.")
4641 (make-variable-buffer-local 'org-keyword-time-regexp)
4642 (defvar org-keyword-time-not-clock-regexp nil
4643 "Matches any of the 3 keywords, together with the time stamp.")
4644 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4645 (defvar org-maybe-keyword-time-regexp nil
4646 "Matches a timestamp, possibly preceded by a keyword.")
4647 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4648 (defvar org-all-time-keywords nil
4649 "List of time keywords.")
4650 (make-variable-buffer-local 'org-all-time-keywords)
4652 (defconst org-plain-time-of-day-regexp
4653 (concat
4654 "\\(\\<[012]?[0-9]"
4655 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4656 "\\(--?"
4657 "\\(\\<[012]?[0-9]"
4658 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4659 "\\)?")
4660 "Regular expression to match a plain time or time range.
4661 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4662 groups carry important information:
4663 0 the full match
4664 1 the first time, range or not
4665 8 the second time, if it is a range.")
4667 (defconst org-plain-time-extension-regexp
4668 (concat
4669 "\\(\\<[012]?[0-9]"
4670 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4671 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4672 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4673 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4674 groups carry important information:
4675 0 the full match
4676 7 hours of duration
4677 9 minutes of duration")
4679 (defconst org-stamp-time-of-day-regexp
4680 (concat
4681 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4682 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4683 "\\(--?"
4684 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4685 "Regular expression to match a timestamp time or time range.
4686 After a match, the following groups carry important information:
4687 0 the full match
4688 1 date plus weekday, for back referencing to make sure both times are on the same day
4689 2 the first time, range or not
4690 4 the second time, if it is a range.")
4692 (defconst org-startup-options
4693 '(("fold" org-startup-folded t)
4694 ("overview" org-startup-folded t)
4695 ("nofold" org-startup-folded nil)
4696 ("showall" org-startup-folded nil)
4697 ("showeverything" org-startup-folded showeverything)
4698 ("content" org-startup-folded content)
4699 ("indent" org-startup-indented t)
4700 ("noindent" org-startup-indented nil)
4701 ("hidestars" org-hide-leading-stars t)
4702 ("showstars" org-hide-leading-stars nil)
4703 ("odd" org-odd-levels-only t)
4704 ("oddeven" org-odd-levels-only nil)
4705 ("align" org-startup-align-all-tables t)
4706 ("noalign" org-startup-align-all-tables nil)
4707 ("inlineimages" org-startup-with-inline-images t)
4708 ("noinlineimages" org-startup-with-inline-images nil)
4709 ("latexpreview" org-startup-with-latex-preview t)
4710 ("nolatexpreview" org-startup-with-latex-preview nil)
4711 ("customtime" org-display-custom-times t)
4712 ("logdone" org-log-done time)
4713 ("lognotedone" org-log-done note)
4714 ("nologdone" org-log-done nil)
4715 ("lognoteclock-out" org-log-note-clock-out t)
4716 ("nolognoteclock-out" org-log-note-clock-out nil)
4717 ("logrepeat" org-log-repeat state)
4718 ("lognoterepeat" org-log-repeat note)
4719 ("logdrawer" org-log-into-drawer t)
4720 ("nologdrawer" org-log-into-drawer nil)
4721 ("logstatesreversed" org-log-states-order-reversed t)
4722 ("nologstatesreversed" org-log-states-order-reversed nil)
4723 ("nologrepeat" org-log-repeat nil)
4724 ("logreschedule" org-log-reschedule time)
4725 ("lognotereschedule" org-log-reschedule note)
4726 ("nologreschedule" org-log-reschedule nil)
4727 ("logredeadline" org-log-redeadline time)
4728 ("lognoteredeadline" org-log-redeadline note)
4729 ("nologredeadline" org-log-redeadline nil)
4730 ("logrefile" org-log-refile time)
4731 ("lognoterefile" org-log-refile note)
4732 ("nologrefile" org-log-refile nil)
4733 ("fninline" org-footnote-define-inline t)
4734 ("nofninline" org-footnote-define-inline nil)
4735 ("fnlocal" org-footnote-section nil)
4736 ("fnauto" org-footnote-auto-label t)
4737 ("fnprompt" org-footnote-auto-label nil)
4738 ("fnconfirm" org-footnote-auto-label confirm)
4739 ("fnplain" org-footnote-auto-label plain)
4740 ("fnadjust" org-footnote-auto-adjust t)
4741 ("nofnadjust" org-footnote-auto-adjust nil)
4742 ("constcgs" constants-unit-system cgs)
4743 ("constSI" constants-unit-system SI)
4744 ("noptag" org-tag-persistent-alist nil)
4745 ("hideblocks" org-hide-block-startup t)
4746 ("nohideblocks" org-hide-block-startup nil)
4747 ("beamer" org-startup-with-beamer-mode t)
4748 ("entitiespretty" org-pretty-entities t)
4749 ("entitiesplain" org-pretty-entities nil))
4750 "Variable associated with STARTUP options for org-mode.
4751 Each element is a list of three items: the startup options (as written
4752 in the #+STARTUP line), the corresponding variable, and the value to set
4753 this variable to if the option is found. An optional forth element PUSH
4754 means to push this value onto the list in the variable.")
4756 (defun org-update-property-plist (key val props)
4757 "Update PROPS with KEY and VAL."
4758 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4759 (key (if appending (substring key 0 (- (length key) 1)) key))
4760 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4761 (previous (cdr (assoc key props))))
4762 (if appending
4763 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4764 (cons (cons key val) remainder))))
4766 (defconst org-block-regexp
4767 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4768 "Regular expression for hiding blocks.")
4769 (defconst org-heading-keyword-regexp-format
4770 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4771 "Printf format for a regexp matching a headline with some keyword.
4772 This regexp will match the headline of any node which has the
4773 exact keyword that is put into the format. The keyword isn't in
4774 any group by default, but the stars and the body are.")
4775 (defconst org-heading-keyword-maybe-regexp-format
4776 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4777 "Printf format for a regexp matching a headline, possibly with some keyword.
4778 This regexp can match any headline with the specified keyword, or
4779 without a keyword. The keyword isn't in any group by default,
4780 but the stars and the body are.")
4782 (defcustom org-group-tags t
4783 "When non-nil (the default), use group tags.
4784 This can be turned on/off through `org-toggle-tags-groups'."
4785 :group 'org-tags
4786 :group 'org-startup
4787 :type 'boolean)
4789 (defun org-toggle-tags-groups ()
4790 "Toggle support for group tags.
4791 Support for group tags is controlled by the option
4792 `org-group-tags', which is non-nil by default."
4793 (interactive)
4794 (setq org-group-tags (not org-group-tags))
4795 (cond ((and (derived-mode-p 'org-agenda-mode)
4796 org-group-tags)
4797 (org-agenda-redo))
4798 ((derived-mode-p 'org-mode)
4799 (let ((org-inhibit-startup t)) (org-mode))))
4800 (message "Groups tags support has been turned %s"
4801 (if org-group-tags "on" "off")))
4803 (defun org-set-regexps-and-options-for-tags ()
4804 "Precompute regular expressions used for tags in the current buffer."
4805 (when (derived-mode-p 'org-mode)
4806 (org-set-local 'org-file-tags nil)
4807 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4808 (splitre "[ \t]+")
4809 (start 0)
4810 tags ftags key value)
4811 (save-excursion
4812 (save-restriction
4813 (widen)
4814 (goto-char (point-min))
4815 (while (re-search-forward re nil t)
4816 (setq key (upcase (org-match-string-no-properties 1))
4817 value (org-match-string-no-properties 2))
4818 (if (stringp value) (setq value (org-trim value)))
4819 (cond
4820 ((equal key "TAGS")
4821 (setq tags (append tags (if tags '("\\n") nil)
4822 (org-split-string value splitre))))
4823 ((equal key "FILETAGS")
4824 (when (string-match "\\S-" value)
4825 (setq ftags
4826 (append
4827 ftags
4828 (apply 'append
4829 (mapcar (lambda (x) (org-split-string x ":"))
4830 (org-split-string value)))))))))))
4831 ;; Process the file tags.
4832 (and ftags (org-set-local 'org-file-tags
4833 (mapcar 'org-add-prop-inherited ftags)))
4834 (org-set-local 'org-tag-groups-alist nil)
4835 ;; Process the tags.
4836 ;; FIXME
4837 (when tags
4838 (let (e tgs g)
4839 (while (setq e (pop tags))
4840 (cond
4841 ((equal e "{")
4842 (progn (push '(:startgroup) tgs)
4843 (when (equal (nth 1 tags) ":")
4844 (push (list (replace-regexp-in-string
4845 "(.+)$" "" (nth 0 tags)))
4846 org-tag-groups-alist)
4847 (setq g 0))))
4848 ((equal e ":") (push '(:grouptags) tgs))
4849 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4850 ((equal e "\\n") (push '(:newline) tgs))
4851 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4852 (push (cons (match-string 1 e)
4853 (string-to-char (match-string 2 e))) tgs)
4854 (if (and g (> g 0))
4855 (setcar org-tag-groups-alist
4856 (append (car org-tag-groups-alist)
4857 (list (match-string 1 e)))))
4858 (if g (setq g (1+ g))))
4859 (t (push (list e) tgs)
4860 (if (and g (> g 0))
4861 (setcar org-tag-groups-alist
4862 (append (car org-tag-groups-alist) (list e))))
4863 (if g (setq g (1+ g))))))
4864 (org-set-local 'org-tag-alist nil)
4865 (while (setq e (pop tgs))
4866 (or (and (stringp (car e))
4867 (assoc (car e) org-tag-alist))
4868 (push e org-tag-alist)))
4869 ;; Return a list with tag variables
4870 (list org-file-tags org-tag-alist org-tag-groups-alist))))))
4872 (defun org-set-regexps-and-options ()
4873 "Precompute regular expressions used in the current buffer."
4874 (when (derived-mode-p 'org-mode)
4875 (org-set-local 'org-todo-kwd-alist nil)
4876 (org-set-local 'org-todo-key-alist nil)
4877 (org-set-local 'org-todo-key-trigger nil)
4878 (org-set-local 'org-todo-keywords-1 nil)
4879 (org-set-local 'org-done-keywords nil)
4880 (org-set-local 'org-todo-heads nil)
4881 (org-set-local 'org-todo-sets nil)
4882 (org-set-local 'org-todo-log-states nil)
4883 (org-set-local 'org-file-properties nil)
4884 (let ((re (org-make-options-regexp
4885 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4886 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4887 "SETUPFILE" "OPTIONS")
4888 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4889 (splitre "[ \t]+")
4890 (scripts org-use-sub-superscripts)
4891 kwds kws0 kwsa key log value cat arch const links hw dws
4892 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4893 (start 0))
4894 (save-excursion
4895 (save-restriction
4896 (widen)
4897 (goto-char (point-min))
4898 (while
4899 (or (and
4900 ext-setup-or-nil
4901 (let (ret)
4902 (with-temp-buffer
4903 (insert ext-setup-or-nil)
4904 (let ((major-mode 'org-mode))
4905 (setq ret (save-match-data
4906 (org-set-regexps-and-options-for-tags)))))
4907 ;; Append setupfile tags to existing tags
4908 (setq org-file-tags
4909 (delq nil (append org-file-tags (nth 0 ret)))
4910 org-tag-alist
4911 (delq nil (append org-tag-alist (nth 1 ret)))
4912 org-tag-groups-alist
4913 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
4914 (and ext-setup-or-nil
4915 (string-match re ext-setup-or-nil start)
4916 (setq start (match-end 0)))
4917 (and (setq ext-setup-or-nil nil start 0)
4918 (re-search-forward re nil t)))
4919 (setq key (upcase (match-string 1 ext-setup-or-nil))
4920 value (org-match-string-no-properties 2 ext-setup-or-nil))
4921 (if (stringp value) (setq value (org-trim value)))
4922 (cond
4923 ((equal key "CATEGORY")
4924 (setq cat value))
4925 ((member key '("SEQ_TODO" "TODO"))
4926 (push (cons 'sequence (org-split-string value splitre)) kwds))
4927 ((equal key "TYP_TODO")
4928 (push (cons 'type (org-split-string value splitre)) kwds))
4929 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4930 ;; general TODO-like setup
4931 (push (cons (intern (downcase (match-string 1 key)))
4932 (org-split-string value splitre)) kwds))
4933 ((equal key "COLUMNS")
4934 (org-set-local 'org-columns-default-format value))
4935 ((equal key "LINK")
4936 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4937 (push (cons (match-string 1 value)
4938 (org-trim (match-string 2 value)))
4939 links)))
4940 ((equal key "PRIORITIES")
4941 (setq prio (org-split-string value " +")))
4942 ((equal key "PROPERTY")
4943 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4944 (setq props (org-update-property-plist (match-string 1 value)
4945 (match-string 2 value)
4946 props))))
4947 ((equal key "DRAWERS")
4948 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4949 ((equal key "CONSTANTS")
4950 (org-table-set-constants))
4951 ((equal key "STARTUP")
4952 (let ((opts (org-split-string value splitre))
4953 l var val)
4954 (while (setq l (pop opts))
4955 (when (setq l (assoc l org-startup-options))
4956 (setq var (nth 1 l) val (nth 2 l))
4957 (if (not (nth 3 l))
4958 (set (make-local-variable var) val)
4959 (if (not (listp (symbol-value var)))
4960 (set (make-local-variable var) nil))
4961 (set (make-local-variable var) (symbol-value var))
4962 (add-to-list var val))))))
4963 ((equal key "ARCHIVE")
4964 (setq arch value)
4965 (remove-text-properties 0 (length arch)
4966 '(face t fontified t) arch))
4967 ((equal key "OPTIONS")
4968 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4969 (setq scripts (read (match-string 2 value)))))
4970 ((and (equal key "SETUPFILE")
4971 ;; Prevent checking in Gnus messages
4972 (not buffer-read-only))
4973 (setq setup-contents (org-file-contents
4974 (expand-file-name
4975 (org-remove-double-quotes value))
4976 'noerror))
4977 (if (not ext-setup-or-nil)
4978 (setq ext-setup-or-nil setup-contents start 0)
4979 (setq ext-setup-or-nil
4980 (concat (substring ext-setup-or-nil 0 start)
4981 "\n" setup-contents "\n"
4982 (substring ext-setup-or-nil start)))))))
4983 ;; search for property blocks
4984 (goto-char (point-min))
4985 (while (re-search-forward org-block-regexp nil t)
4986 (when (equal "PROPERTY" (upcase (match-string 1)))
4987 (setq value (replace-regexp-in-string
4988 "[\n\r]" " " (match-string 4)))
4989 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4990 (setq props (org-update-property-plist (match-string 1 value)
4991 (match-string 2 value)
4992 props)))))))
4993 (org-set-local 'org-use-sub-superscripts scripts)
4994 (when cat
4995 (org-set-local 'org-category (intern cat))
4996 (push (cons "CATEGORY" cat) props))
4997 (when prio
4998 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4999 (setq prio (mapcar 'string-to-char prio))
5000 (org-set-local 'org-highest-priority (nth 0 prio))
5001 (org-set-local 'org-lowest-priority (nth 1 prio))
5002 (org-set-local 'org-default-priority (nth 2 prio)))
5003 (and props (org-set-local 'org-file-properties (nreverse props)))
5004 (and drawers (org-set-local 'org-drawers drawers))
5005 (and arch (org-set-local 'org-archive-location arch))
5006 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5007 ;; Process the TODO keywords
5008 (unless kwds
5009 ;; Use the global values as if they had been given locally.
5010 (setq kwds (default-value 'org-todo-keywords))
5011 (if (stringp (car kwds))
5012 (setq kwds (list (cons org-todo-interpretation
5013 (default-value 'org-todo-keywords)))))
5014 (setq kwds (reverse kwds)))
5015 (setq kwds (nreverse kwds))
5016 (let (inter kws kw)
5017 (while (setq kws (pop kwds))
5018 (let ((kws (or
5019 (run-hook-with-args-until-success
5020 'org-todo-setup-filter-hook kws)
5021 kws)))
5022 (setq inter (pop kws) sep (member "|" kws)
5023 kws0 (delete "|" (copy-sequence kws))
5024 kwsa nil
5025 kws1 (mapcar
5026 (lambda (x)
5027 ;; 1 2
5028 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5029 (progn
5030 (setq kw (match-string 1 x)
5031 key (and (match-end 2) (match-string 2 x))
5032 log (org-extract-log-state-settings x))
5033 (push (cons kw (and key (string-to-char key))) kwsa)
5034 (and log (push log org-todo-log-states))
5036 (error "Invalid TODO keyword %s" x)))
5037 kws0)
5038 kwsa (if kwsa (append '((:startgroup))
5039 (nreverse kwsa)
5040 '((:endgroup))))
5041 hw (car kws1)
5042 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5043 tail (list inter hw (car dws) (org-last dws))))
5044 (add-to-list 'org-todo-heads hw 'append)
5045 (push kws1 org-todo-sets)
5046 (setq org-done-keywords (append org-done-keywords dws nil))
5047 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5048 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5049 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5050 (setq org-todo-sets (nreverse org-todo-sets)
5051 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5052 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5053 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5054 ;; Compute the regular expressions and other local variables.
5055 ;; Using `org-outline-regexp-bol' would complicate them much,
5056 ;; because of the fixed white space at the end of that string.
5057 (if (not org-done-keywords)
5058 (setq org-done-keywords (and org-todo-keywords-1
5059 (list (org-last org-todo-keywords-1)))))
5060 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5061 (length org-scheduled-string)
5062 (length org-clock-string)
5063 (length org-closed-string)))
5064 org-drawer-regexp
5065 (concat "^[ \t]*:\\("
5066 (mapconcat 'regexp-quote org-drawers "\\|")
5067 "\\):[ \t]*$")
5068 org-not-done-keywords
5069 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5070 org-todo-regexp
5071 (concat "\\("
5072 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5073 "\\)")
5074 org-not-done-regexp
5075 (concat "\\("
5076 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5077 "\\)")
5078 org-not-done-heading-regexp
5079 (format org-heading-keyword-regexp-format org-not-done-regexp)
5080 org-todo-line-regexp
5081 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5082 org-complex-heading-regexp
5083 (concat "^\\(\\*+\\)"
5084 "\\(?: +" org-todo-regexp "\\)?"
5085 "\\(?: +\\(\\[#.\\]\\)\\)?"
5086 "\\(?: +\\(.*?\\)\\)??"
5087 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5088 "[ \t]*$")
5089 org-complex-heading-regexp-format
5090 (concat "^\\(\\*+\\)"
5091 "\\(?: +" org-todo-regexp "\\)?"
5092 "\\(?: +\\(\\[#.\\]\\)\\)?"
5093 "\\(?: +"
5094 ;; Stats cookies can be stuck to body.
5095 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5096 "\\(%s\\)"
5097 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5098 "\\)"
5099 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5100 "[ \t]*$")
5101 org-todo-line-tags-regexp
5102 (concat "^\\(\\*+\\)"
5103 "\\(?: +" org-todo-regexp "\\)?"
5104 "\\(?: +\\(.*?\\)\\)??"
5105 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5106 "[ \t]*$")
5107 org-deadline-regexp (concat "\\<" org-deadline-string)
5108 org-deadline-time-regexp
5109 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5110 org-deadline-time-hour-regexp
5111 (concat "\\<" org-deadline-string
5112 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5113 org-deadline-line-regexp
5114 (concat "\\<\\(" org-deadline-string "\\).*")
5115 org-scheduled-regexp
5116 (concat "\\<" org-scheduled-string)
5117 org-scheduled-time-regexp
5118 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5119 org-scheduled-time-hour-regexp
5120 (concat "\\<" org-scheduled-string
5121 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5122 org-closed-time-regexp
5123 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5124 org-keyword-time-regexp
5125 (concat "\\<\\(" org-scheduled-string
5126 "\\|" org-deadline-string
5127 "\\|" org-closed-string
5128 "\\|" org-clock-string "\\)"
5129 " *[[<]\\([^]>]+\\)[]>]")
5130 org-keyword-time-not-clock-regexp
5131 (concat "\\<\\(" org-scheduled-string
5132 "\\|" org-deadline-string
5133 "\\|" org-closed-string
5134 "\\)"
5135 " *[[<]\\([^]>]+\\)[]>]")
5136 org-maybe-keyword-time-regexp
5137 (concat "\\(\\<\\(" org-scheduled-string
5138 "\\|" org-deadline-string
5139 "\\|" org-closed-string
5140 "\\|" org-clock-string "\\)\\)?"
5141 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5142 org-all-time-keywords
5143 (mapcar (lambda (w) (substring w 0 -1))
5144 (list org-scheduled-string org-deadline-string
5145 org-clock-string org-closed-string)))
5146 (org-compute-latex-and-related-regexp)
5147 (org-set-font-lock-defaults))))
5149 (defun org-file-contents (file &optional noerror)
5150 "Return the contents of FILE, as a string."
5151 (if (or (not file)
5152 (not (file-readable-p file)))
5153 (if noerror
5154 (message "Cannot read file \"%s\"" file)
5155 (error "Cannot read file \"%s\"" file))
5156 (with-temp-buffer
5157 (insert-file-contents file)
5158 (buffer-string))))
5160 (defun org-extract-log-state-settings (x)
5161 "Extract the log state setting from a TODO keyword string.
5162 This will extract info from a string like \"WAIT(w@/!)\"."
5163 (let (kw key log1 log2)
5164 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5165 (setq kw (match-string 1 x)
5166 key (and (match-end 2) (match-string 2 x))
5167 log1 (and (match-end 3) (match-string 3 x))
5168 log2 (and (match-end 4) (match-string 4 x)))
5169 (and (or log1 log2)
5170 (list kw
5171 (and log1 (if (equal log1 "!") 'time 'note))
5172 (and log2 (if (equal log2 "!") 'time 'note)))))))
5174 (defun org-remove-keyword-keys (list)
5175 "Remove a pair of parenthesis at the end of each string in LIST."
5176 (mapcar (lambda (x)
5177 (if (string-match "(.*)$" x)
5178 (substring x 0 (match-beginning 0))
5180 list))
5182 (defun org-assign-fast-keys (alist)
5183 "Assign fast keys to a keyword-key alist.
5184 Respect keys that are already there."
5185 (let (new e (alt ?0))
5186 (while (setq e (pop alist))
5187 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5188 (cdr e)) ;; Key already assigned.
5189 (push e new)
5190 (let ((clist (string-to-list (downcase (car e))))
5191 (used (append new alist)))
5192 (when (= (car clist) ?@)
5193 (pop clist))
5194 (while (and clist (rassoc (car clist) used))
5195 (pop clist))
5196 (unless clist
5197 (while (rassoc alt used)
5198 (incf alt)))
5199 (push (cons (car e) (or (car clist) alt)) new))))
5200 (nreverse new)))
5202 ;;; Some variables used in various places
5204 (defvar org-window-configuration nil
5205 "Used in various places to store a window configuration.")
5206 (defvar org-selected-window nil
5207 "Used in various places to store a window configuration.")
5208 (defvar org-finish-function nil
5209 "Function to be called when `C-c C-c' is used.
5210 This is for getting out of special buffers like capture.")
5213 ;; FIXME: Occasionally check by commenting these, to make sure
5214 ;; no other functions uses these, forgetting to let-bind them.
5215 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5216 (defvar org-last-state)
5217 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5219 ;; Defined somewhere in this file, but used before definition.
5220 (defvar org-entities) ;; defined in org-entities.el
5221 (defvar org-struct-menu)
5222 (defvar org-org-menu)
5223 (defvar org-tbl-menu)
5225 ;;;; Define the Org-mode
5227 ;; We use a before-change function to check if a table might need
5228 ;; an update.
5229 (defvar org-table-may-need-update t
5230 "Indicates that a table might need an update.
5231 This variable is set by `org-before-change-function'.
5232 `org-table-align' sets it back to nil.")
5233 (defun org-before-change-function (beg end)
5234 "Every change indicates that a table might need an update."
5235 (setq org-table-may-need-update t))
5236 (defvar org-mode-map)
5237 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5238 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5239 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5240 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5241 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5242 (defvar org-table-buffer-is-an nil)
5244 (defvar bidi-paragraph-direction)
5245 (defvar buffer-face-mode-face)
5247 (require 'outline)
5248 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5249 (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"))
5250 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5252 ;; Other stuff we need.
5253 (require 'time-date)
5254 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5255 (require 'easymenu)
5256 (require 'overlay)
5258 ;; (require 'org-macs) moved higher up in the file before it is first used
5259 (require 'org-entities)
5260 ;; (require 'org-compat) moved higher up in the file before it is first used
5261 (require 'org-faces)
5262 (require 'org-list)
5263 (require 'org-pcomplete)
5264 (require 'org-src)
5265 (require 'org-footnote)
5266 (require 'org-macro)
5268 ;; babel
5269 (require 'ob)
5271 ;;;###autoload
5272 (define-derived-mode org-mode outline-mode "Org"
5273 "Outline-based notes management and organizer, alias
5274 \"Carsten's outline-mode for keeping track of everything.\"
5276 Org-mode develops organizational tasks around a NOTES file which
5277 contains information about projects as plain text. Org-mode is
5278 implemented on top of outline-mode, which is ideal to keep the content
5279 of large files well structured. It supports ToDo items, deadlines and
5280 time stamps, which magically appear in the diary listing of the Emacs
5281 calendar. Tables are easily created with a built-in table editor.
5282 Plain text URL-like links connect to websites, emails (VM), Usenet
5283 messages (Gnus), BBDB entries, and any files related to the project.
5284 For printing and sharing of notes, an Org-mode file (or a part of it)
5285 can be exported as a structured ASCII or HTML file.
5287 The following commands are available:
5289 \\{org-mode-map}"
5291 ;; Get rid of Outline menus, they are not needed
5292 ;; Need to do this here because define-derived-mode sets up
5293 ;; the keymap so late. Still, it is a waste to call this each time
5294 ;; we switch another buffer into org-mode.
5295 (if (featurep 'xemacs)
5296 (when (boundp 'outline-mode-menu-heading)
5297 ;; Assume this is Greg's port, it uses easymenu
5298 (easy-menu-remove outline-mode-menu-heading)
5299 (easy-menu-remove outline-mode-menu-show)
5300 (easy-menu-remove outline-mode-menu-hide))
5301 (define-key org-mode-map [menu-bar headings] 'undefined)
5302 (define-key org-mode-map [menu-bar hide] 'undefined)
5303 (define-key org-mode-map [menu-bar show] 'undefined))
5305 (org-load-modules-maybe)
5306 (easy-menu-add org-org-menu)
5307 (easy-menu-add org-tbl-menu)
5308 (org-install-agenda-files-menu)
5309 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5310 (add-to-invisibility-spec '(org-cwidth))
5311 (add-to-invisibility-spec '(org-hide-block . t))
5312 (when (featurep 'xemacs)
5313 (org-set-local 'line-move-ignore-invisible t))
5314 (org-set-local 'outline-regexp org-outline-regexp)
5315 (org-set-local 'outline-level 'org-outline-level)
5316 (setq bidi-paragraph-direction 'left-to-right)
5317 ;; FIXME Circumvent a bug in outline.el (Emacs <24.4)
5318 (set (make-local-variable 'paragraph-start) "\f\\|[ \t]*$\\|\\*+ ")
5319 (when (and org-ellipsis
5320 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5321 (fboundp 'make-glyph-code))
5322 (unless org-display-table
5323 (setq org-display-table (make-display-table)))
5324 (set-display-table-slot
5325 org-display-table 4
5326 (vconcat (mapcar
5327 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5328 org-ellipsis)))
5329 (if (stringp org-ellipsis) org-ellipsis "..."))))
5330 (setq buffer-display-table org-display-table))
5331 (org-set-regexps-and-options-for-tags)
5332 (org-set-regexps-and-options)
5333 (when (and org-tag-faces (not org-tags-special-faces-re))
5334 ;; tag faces set outside customize.... force initialization.
5335 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5336 ;; Calc embedded
5337 (org-set-local 'calc-embedded-open-mode "# ")
5338 ;; Modify a few syntax entries
5339 (modify-syntax-entry ?@ "w")
5340 (modify-syntax-entry ?\" "\"")
5341 (if org-startup-truncated (setq truncate-lines t))
5342 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5343 (org-set-local 'font-lock-unfontify-region-function
5344 'org-unfontify-region)
5345 ;; Activate before-change-function
5346 (org-set-local 'org-table-may-need-update t)
5347 (org-add-hook 'before-change-functions 'org-before-change-function nil
5348 'local)
5349 ;; Check for running clock before killing a buffer
5350 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5351 ;; Initialize macros templates.
5352 (org-macro-initialize-templates)
5353 ;; Initialize radio targets.
5354 (org-update-radio-target-regexp)
5355 ;; Indentation.
5356 (org-set-local 'indent-line-function 'org-indent-line)
5357 (org-set-local 'indent-region-function 'org-indent-region)
5358 ;; Filling and auto-filling.
5359 (org-setup-filling)
5360 ;; Comments.
5361 (org-setup-comments-handling)
5362 ;; Beginning/end of defun
5363 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5364 (org-set-local 'end-of-defun-function 'org-forward-element)
5365 ;; Next error for sparse trees
5366 (org-set-local 'next-error-function 'org-occur-next-match)
5367 ;; Make sure dependence stuff works reliably, even for users who set it
5368 ;; too late :-(
5369 (if org-enforce-todo-dependencies
5370 (add-hook 'org-blocker-hook
5371 'org-block-todo-from-children-or-siblings-or-parent)
5372 (remove-hook 'org-blocker-hook
5373 'org-block-todo-from-children-or-siblings-or-parent))
5374 (if org-enforce-todo-checkbox-dependencies
5375 (add-hook 'org-blocker-hook
5376 'org-block-todo-from-checkboxes)
5377 (remove-hook 'org-blocker-hook
5378 'org-block-todo-from-checkboxes))
5380 ;; Align options lines
5381 (org-set-local
5382 'align-mode-rules-list
5383 '((org-in-buffer-settings
5384 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5385 (modes . '(org-mode)))))
5387 ;; Imenu
5388 (org-set-local 'imenu-create-index-function
5389 'org-imenu-get-tree)
5391 ;; Make isearch reveal context
5392 (if (or (featurep 'xemacs)
5393 (not (boundp 'outline-isearch-open-invisible-function)))
5394 ;; Emacs 21 and XEmacs make use of the hook
5395 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5396 ;; Emacs 22 deals with this through a special variable
5397 (org-set-local 'outline-isearch-open-invisible-function
5398 (lambda (&rest ignore) (org-show-context 'isearch)))
5399 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5401 ;; Setup the pcomplete hooks
5402 (set (make-local-variable 'pcomplete-command-completion-function)
5403 'org-pcomplete-initial)
5404 (set (make-local-variable 'pcomplete-command-name-function)
5405 'org-command-at-point)
5406 (set (make-local-variable 'pcomplete-default-completion-function)
5407 'ignore)
5408 (set (make-local-variable 'pcomplete-parse-arguments-function)
5409 'org-parse-arguments)
5410 (set (make-local-variable 'pcomplete-termination-string) "")
5411 (when (>= emacs-major-version 23)
5412 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5414 ;; If empty file that did not turn on org-mode automatically, make it to.
5415 (if (and org-insert-mode-line-in-empty-file
5416 (org-called-interactively-p 'any)
5417 (= (point-min) (point-max)))
5418 (insert "# -*- mode: org -*-\n\n"))
5419 (unless org-inhibit-startup
5420 (org-unmodified
5421 (and org-startup-with-beamer-mode (org-beamer-mode))
5422 (when org-startup-align-all-tables
5423 (org-table-map-tables 'org-table-align 'quietly))
5424 (when org-startup-with-inline-images
5425 (org-display-inline-images))
5426 (when org-startup-with-latex-preview
5427 (org-preview-latex-fragment))
5428 (unless org-inhibit-startup-visibility-stuff
5429 (org-set-startup-visibility))))
5430 ;; Try to set org-hide correctly
5431 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5433 ;; Update `customize-package-emacs-version-alist'
5434 (add-to-list 'customize-package-emacs-version-alist
5435 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5436 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5437 ("8.0" . "24.4")))
5439 (defvar org-mode-transpose-word-syntax-table
5440 (let ((st (make-syntax-table)))
5441 (mapc (lambda(c) (modify-syntax-entry
5442 (string-to-char (car c)) "w p" st))
5443 org-emphasis-alist)
5444 st))
5446 (when (fboundp 'abbrev-table-put)
5447 (abbrev-table-put org-mode-abbrev-table
5448 :parents (list text-mode-abbrev-table)))
5450 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5452 (defsubst org-fix-ellipsis-at-bol ()
5453 (save-excursion (goto-char (window-start)) (recenter 0)))
5455 (defun org-find-invisible-foreground ()
5456 (let ((candidates (remove
5457 "unspecified-bg"
5458 (nconc
5459 (list (face-background 'default)
5460 (face-background 'org-default))
5461 (mapcar
5462 (lambda (alist)
5463 (when (boundp alist)
5464 (cdr (assoc 'background-color (symbol-value alist)))))
5465 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5466 (list (face-foreground 'org-hide))))))
5467 (car (remove nil candidates))))
5469 (defun org-current-time (&optional rounding-minutes past)
5470 "Current time, possibly rounded to ROUNDING-MINUTES.
5471 When ROUNDING-MINUTES is not an integer, fall back on the car of
5472 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5473 the rounding returns a past time."
5474 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5475 (car org-time-stamp-rounding-minutes)))
5476 (time (decode-time)) res)
5477 (if (< r 1)
5478 (current-time)
5479 (setq res
5480 (apply 'encode-time
5481 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5482 (nthcdr 2 time))))
5483 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5484 (seconds-to-time (- (org-float-time res) (* r 60)))
5485 res))))
5487 (defun org-today ()
5488 "Return today date, considering `org-extend-today-until'."
5489 (time-to-days
5490 (time-subtract (current-time)
5491 (list 0 (* 3600 org-extend-today-until) 0))))
5493 ;;;; Font-Lock stuff, including the activators
5495 (defvar org-mouse-map (make-sparse-keymap))
5496 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5497 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5498 (when org-mouse-1-follows-link
5499 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5500 (when org-tab-follows-link
5501 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5502 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5504 (require 'font-lock)
5506 (defconst org-non-link-chars "]\t\n\r<>")
5507 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5508 "shell" "elisp" "doi" "message"))
5509 (defvar org-link-types-re nil
5510 "Matches a link that has a url-like prefix like \"http:\"")
5511 (defvar org-link-re-with-space nil
5512 "Matches a link with spaces, optional angular brackets around it.")
5513 (defvar org-link-re-with-space2 nil
5514 "Matches a link with spaces, optional angular brackets around it.")
5515 (defvar org-link-re-with-space3 nil
5516 "Matches a link with spaces, only for internal part in bracket links.")
5517 (defvar org-angle-link-re nil
5518 "Matches link with angular brackets, spaces are allowed.")
5519 (defvar org-plain-link-re nil
5520 "Matches plain link, without spaces.")
5521 (defvar org-bracket-link-regexp nil
5522 "Matches a link in double brackets.")
5523 (defvar org-bracket-link-analytic-regexp nil
5524 "Regular expression used to analyze links.
5525 Here is what the match groups contain after a match:
5526 1: http:
5527 2: http
5528 3: path
5529 4: [desc]
5530 5: desc")
5531 (defvar org-bracket-link-analytic-regexp++ nil
5532 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5533 (defvar org-any-link-re nil
5534 "Regular expression matching any link.")
5536 (defconst org-match-sexp-depth 3
5537 "Number of stacked braces for sub/superscript matching.")
5539 (defun org-create-multibrace-regexp (left right n)
5540 "Create a regular expression which will match a balanced sexp.
5541 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5542 as single character strings.
5543 The regexp returned will match the entire expression including the
5544 delimiters. It will also define a single group which contains the
5545 match except for the outermost delimiters. The maximum depth of
5546 stacked delimiters is N. Escaping delimiters is not possible."
5547 (let* ((nothing (concat "[^" left right "]*?"))
5548 (or "\\|")
5549 (re nothing)
5550 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5551 (while (> n 1)
5552 (setq n (1- n)
5553 re (concat re or next)
5554 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5555 (concat left "\\(" re "\\)" right)))
5557 (defvar org-match-substring-regexp
5558 (concat
5559 "\\(\\S-\\)\\([_^]\\)\\("
5560 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5561 "\\|"
5562 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5563 "\\|"
5564 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5565 "The regular expression matching a sub- or superscript.")
5567 (defvar org-match-substring-with-braces-regexp
5568 (concat
5569 "\\(\\S-\\)\\([_^]\\)\\("
5570 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5571 "\\)")
5572 "The regular expression matching a sub- or superscript, forcing braces.")
5574 (defun org-make-link-regexps ()
5575 "Update the link regular expressions.
5576 This should be called after the variable `org-link-types' has changed."
5577 (setq org-link-types-re
5578 (concat
5579 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5580 org-link-re-with-space
5581 (concat
5582 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5583 "\\([^" org-non-link-chars " ]"
5584 "[^" org-non-link-chars "]*"
5585 "[^" org-non-link-chars " ]\\)>?")
5586 org-link-re-with-space2
5587 (concat
5588 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5589 "\\([^" org-non-link-chars " ]"
5590 "[^\t\n\r]*"
5591 "[^" org-non-link-chars " ]\\)>?")
5592 org-link-re-with-space3
5593 (concat
5594 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5595 "\\([^" org-non-link-chars " ]"
5596 "[^\t\n\r]*\\)")
5597 org-angle-link-re
5598 (concat
5599 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5600 "\\([^" org-non-link-chars " ]"
5601 "[^" org-non-link-chars "]*"
5602 "\\)>")
5603 org-plain-link-re
5604 (concat
5605 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5606 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5607 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5608 org-bracket-link-regexp
5609 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5610 org-bracket-link-analytic-regexp
5611 (concat
5612 "\\[\\["
5613 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5614 "\\([^]]+\\)"
5615 "\\]"
5616 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5617 "\\]")
5618 org-bracket-link-analytic-regexp++
5619 (concat
5620 "\\[\\["
5621 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5622 "\\([^]]+\\)"
5623 "\\]"
5624 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5625 "\\]")
5626 org-any-link-re
5627 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5628 org-angle-link-re "\\)\\|\\("
5629 org-plain-link-re "\\)")))
5631 (org-make-link-regexps)
5633 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5634 "Regular expression for fast time stamp matching.")
5635 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5636 "Regular expression for fast time stamp matching.")
5637 (defconst org-ts-regexp0
5638 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5639 "Regular expression matching time strings for analysis.
5640 This one does not require the space after the date, so it can be used
5641 on a string that terminates immediately after the date.")
5642 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5643 "Regular expression matching time strings for analysis.")
5644 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5645 "Regular expression matching time stamps, with groups.")
5646 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5647 "Regular expression matching time stamps (also [..]), with groups.")
5648 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5649 "Regular expression matching a time stamp range.")
5650 (defconst org-tr-regexp-both
5651 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5652 "Regular expression matching a time stamp range.")
5653 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5654 org-ts-regexp "\\)?")
5655 "Regular expression matching a time stamp or time stamp range.")
5656 (defconst org-tsr-regexp-both
5657 (concat org-ts-regexp-both "\\(--?-?"
5658 org-ts-regexp-both "\\)?")
5659 "Regular expression matching a time stamp or time stamp range.
5660 The time stamps may be either active or inactive.")
5662 (defvar org-emph-face nil)
5664 (defun org-do-emphasis-faces (limit)
5665 "Run through the buffer and add overlays to emphasized strings."
5666 (let (rtn a)
5667 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5668 (if (not (= (char-after (match-beginning 3))
5669 (char-after (match-beginning 4))))
5670 (progn
5671 (setq rtn t)
5672 (setq a (assoc (match-string 3) org-emphasis-alist))
5673 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5674 'face
5675 (nth 1 a))
5676 (and (nth 4 a)
5677 (org-remove-flyspell-overlays-in
5678 (match-beginning 0) (match-end 0)))
5679 (add-text-properties (match-beginning 2) (match-end 2)
5680 '(font-lock-multiline t org-emphasis t))
5681 (when org-hide-emphasis-markers
5682 (add-text-properties (match-end 4) (match-beginning 5)
5683 '(invisible org-link))
5684 (add-text-properties (match-beginning 3) (match-end 3)
5685 '(invisible org-link)))))
5686 (backward-char 1))
5687 rtn))
5689 (defun org-emphasize (&optional char)
5690 "Insert or change an emphasis, i.e. a font like bold or italic.
5691 If there is an active region, change that region to a new emphasis.
5692 If there is no region, just insert the marker characters and position
5693 the cursor between them.
5694 CHAR should be the marker character. If it is a space, it means to
5695 remove the emphasis of the selected region.
5696 If CHAR is not given (for example in an interactive call) it will be
5697 prompted for."
5698 (interactive)
5699 (let ((erc org-emphasis-regexp-components)
5700 (prompt "")
5701 (string "") beg end move c s)
5702 (if (org-region-active-p)
5703 (setq beg (region-beginning) end (region-end)
5704 string (buffer-substring beg end))
5705 (setq move t))
5707 (unless char
5708 (message "Emphasis marker or tag: [%s]"
5709 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5710 (setq char (read-char-exclusive)))
5711 (if (equal char ?\ )
5712 (setq s "" move nil)
5713 (unless (assoc (char-to-string char) org-emphasis-alist)
5714 (user-error "No such emphasis marker: \"%c\"" char))
5715 (setq s (char-to-string char)))
5716 (while (and (> (length string) 1)
5717 (equal (substring string 0 1) (substring string -1))
5718 (assoc (substring string 0 1) org-emphasis-alist))
5719 (setq string (substring string 1 -1)))
5720 (setq string (concat s string s))
5721 (if beg (delete-region beg end))
5722 (unless (or (bolp)
5723 (string-match (concat "[" (nth 0 erc) "\n]")
5724 (char-to-string (char-before (point)))))
5725 (insert " "))
5726 (unless (or (eobp)
5727 (string-match (concat "[" (nth 1 erc) "\n]")
5728 (char-to-string (char-after (point)))))
5729 (insert " ") (backward-char 1))
5730 (insert string)
5731 (and move (backward-char 1))))
5733 (defconst org-nonsticky-props
5734 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5736 (defsubst org-rear-nonsticky-at (pos)
5737 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5739 (defun org-activate-plain-links (limit)
5740 "Run through the buffer and add overlays to links."
5741 (let (f hl)
5742 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5743 (not (org-in-src-block-p)))
5744 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5745 (setq f (get-text-property (match-beginning 0) 'face))
5746 (setq hl (org-match-string-no-properties 0))
5747 (if (or (eq f 'org-tag)
5748 (and (listp f) (memq 'org-tag f)))
5750 (add-text-properties (match-beginning 0) (match-end 0)
5751 (list 'mouse-face 'highlight
5752 'face 'org-link
5753 'htmlize-link `(:uri ,hl)
5754 'keymap org-mouse-map))
5755 (org-rear-nonsticky-at (match-end 0)))
5756 t)))
5758 (defun org-activate-code (limit)
5759 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5760 (progn
5761 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5762 (remove-text-properties (match-beginning 0) (match-end 0)
5763 '(display t invisible t intangible t))
5764 t)))
5766 (defcustom org-src-fontify-natively nil
5767 "When non-nil, fontify code in code blocks."
5768 :type 'boolean
5769 :version "24.1"
5770 :group 'org-appearance
5771 :group 'org-babel)
5773 (defcustom org-allow-promoting-top-level-subtree nil
5774 "When non-nil, allow promoting a top level subtree.
5775 The leading star of the top level headline will be replaced
5776 by a #."
5777 :type 'boolean
5778 :version "24.1"
5779 :group 'org-appearance)
5781 (defun org-fontify-meta-lines-and-blocks (limit)
5782 (condition-case nil
5783 (org-fontify-meta-lines-and-blocks-1 limit)
5784 (error (message "org-mode fontification error"))))
5786 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5787 "Fontify #+ lines and blocks."
5788 (let ((case-fold-search t))
5789 (if (re-search-forward
5790 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5791 limit t)
5792 (let ((beg (match-beginning 0))
5793 (block-start (match-end 0))
5794 (block-end nil)
5795 (lang (match-string 7))
5796 (beg1 (line-beginning-position 2))
5797 (dc1 (downcase (match-string 2)))
5798 (dc3 (downcase (match-string 3)))
5799 end end1 quoting block-type ovl)
5800 (cond
5801 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5802 ;; a single line of backend-specific content
5803 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5804 (remove-text-properties (match-beginning 0) (match-end 0)
5805 '(display t invisible t intangible t))
5806 (add-text-properties (match-beginning 1) (match-end 3)
5807 '(font-lock-fontified t face org-meta-line))
5808 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5809 '(font-lock-fontified t face org-block))
5810 ; for backend-specific code
5812 ((and (match-end 4) (equal dc3 "+begin"))
5813 ;; Truly a block
5814 (setq block-type (downcase (match-string 5))
5815 quoting (member block-type org-protecting-blocks))
5816 (when (re-search-forward
5817 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5818 nil t) ;; on purpose, we look further than LIMIT
5819 (setq end (min (point-max) (match-end 0))
5820 end1 (min (point-max) (1- (match-beginning 0))))
5821 (setq block-end (match-beginning 0))
5822 (when quoting
5823 (remove-text-properties beg end
5824 '(display t invisible t intangible t)))
5825 (add-text-properties
5826 beg end
5827 '(font-lock-fontified t font-lock-multiline t))
5828 (add-text-properties beg beg1 '(face org-meta-line))
5829 (add-text-properties end1 (min (point-max) (1+ end))
5830 '(face org-meta-line)) ; for end_src
5831 (cond
5832 ((and lang (not (string= lang "")) org-src-fontify-natively)
5833 (org-src-font-lock-fontify-block lang block-start block-end)
5834 ;; remove old background overlays
5835 (mapc (lambda (ov)
5836 (if (eq (overlay-get ov 'face) 'org-block-background)
5837 (delete-overlay ov)))
5838 (overlays-at (/ (+ beg1 block-end) 2)))
5839 ;; add a background overlay
5840 (setq ovl (make-overlay beg1 block-end))
5841 (overlay-put ovl 'face 'org-block-background)
5842 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5843 (quoting
5844 (add-text-properties beg1 (min (point-max) (1+ end1))
5845 '(face org-block))) ; end of source block
5846 ((not org-fontify-quote-and-verse-blocks))
5847 ((string= block-type "quote")
5848 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5849 ((string= block-type "verse")
5850 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5851 (add-text-properties beg beg1 '(face org-block-begin-line))
5852 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5853 '(face org-block-end-line))
5855 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5856 (add-text-properties
5857 beg (match-end 3)
5858 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5859 '(font-lock-fontified t invisible t)
5860 '(font-lock-fontified t face org-document-info-keyword)))
5861 (add-text-properties
5862 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5863 (if (string-equal dc1 "+title:")
5864 '(font-lock-fontified t face org-document-title)
5865 '(font-lock-fontified t face org-document-info))))
5866 ((or (equal dc1 "+results")
5867 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5868 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5869 "+call:" "+header:" "+headers:" "+name:"))
5870 (and (match-end 4) (equal dc3 "+attr")))
5871 (add-text-properties
5872 beg (match-end 0)
5873 '(font-lock-fontified t face org-meta-line))
5875 ((member dc3 '(" " ""))
5876 (add-text-properties
5877 beg (match-end 0)
5878 '(font-lock-fontified t face font-lock-comment-face)))
5879 ((not (member (char-after beg) '(?\ ?\t)))
5880 ;; just any other in-buffer setting, but not indented
5881 (add-text-properties
5882 beg (match-end 0)
5883 '(font-lock-fontified t face org-meta-line))
5885 (t nil))))))
5887 (defun org-activate-angle-links (limit)
5888 "Run through the buffer and add overlays to links."
5889 (if (and (re-search-forward org-angle-link-re limit t)
5890 (not (org-in-src-block-p)))
5891 (progn
5892 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5893 (add-text-properties (match-beginning 0) (match-end 0)
5894 (list 'mouse-face 'highlight
5895 'keymap org-mouse-map))
5896 (org-rear-nonsticky-at (match-end 0))
5897 t)))
5899 (defun org-activate-footnote-links (limit)
5900 "Run through the buffer and add overlays to footnotes."
5901 (let ((fn (org-footnote-next-reference-or-definition limit)))
5902 (when fn
5903 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5904 (org-remove-flyspell-overlays-in beg end)
5905 (add-text-properties beg end
5906 (list 'mouse-face 'highlight
5907 'keymap org-mouse-map
5908 'help-echo
5909 (if (= (point-at-bol) beg)
5910 "Footnote definition"
5911 "Footnote reference")
5912 'font-lock-fontified t
5913 'font-lock-multiline t
5914 'face 'org-footnote))))))
5916 (defun org-activate-bracket-links (limit)
5917 "Run through the buffer and add overlays to bracketed links."
5918 (if (and (re-search-forward org-bracket-link-regexp limit t)
5919 (not (org-in-src-block-p)))
5920 (let* ((hl (org-match-string-no-properties 1))
5921 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5922 (ip (org-maybe-intangible
5923 (list 'invisible 'org-link
5924 'keymap org-mouse-map 'mouse-face 'highlight
5925 'font-lock-multiline t 'help-echo help
5926 'htmlize-link `(:uri ,hl))))
5927 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5928 'font-lock-multiline t 'help-echo help
5929 'htmlize-link `(:uri ,hl))))
5930 ;; We need to remove the invisible property here. Table narrowing
5931 ;; may have made some of this invisible.
5932 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5933 (remove-text-properties (match-beginning 0) (match-end 0)
5934 '(invisible nil))
5935 (if (match-end 3)
5936 (progn
5937 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5938 (org-rear-nonsticky-at (match-beginning 3))
5939 (add-text-properties (match-beginning 3) (match-end 3) vp)
5940 (org-rear-nonsticky-at (match-end 3))
5941 (add-text-properties (match-end 3) (match-end 0) ip)
5942 (org-rear-nonsticky-at (match-end 0)))
5943 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5944 (org-rear-nonsticky-at (match-beginning 1))
5945 (add-text-properties (match-beginning 1) (match-end 1) vp)
5946 (org-rear-nonsticky-at (match-end 1))
5947 (add-text-properties (match-end 1) (match-end 0) ip)
5948 (org-rear-nonsticky-at (match-end 0)))
5949 t)))
5951 (defun org-activate-dates (limit)
5952 "Run through the buffer and add overlays to dates."
5953 (if (and (re-search-forward org-tsr-regexp-both limit t)
5954 (not (equal (char-before (match-beginning 0)) 91)))
5955 (progn
5956 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5957 (add-text-properties (match-beginning 0) (match-end 0)
5958 (list 'mouse-face 'highlight
5959 'keymap org-mouse-map))
5960 (org-rear-nonsticky-at (match-end 0))
5961 (when org-display-custom-times
5962 (if (match-end 3)
5963 (org-display-custom-time (match-beginning 3) (match-end 3)))
5964 (org-display-custom-time (match-beginning 1) (match-end 1)))
5965 t)))
5967 (defvar org-target-link-regexp nil
5968 "Regular expression matching radio targets in plain text.")
5969 (make-variable-buffer-local 'org-target-link-regexp)
5970 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5971 "Regular expression matching a link target.")
5972 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5973 "Regular expression matching a radio target.")
5974 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5975 "Regular expression matching any target.")
5977 (defun org-activate-target-links (limit)
5978 "Run through the buffer and add overlays to target matches."
5979 (when org-target-link-regexp
5980 (let ((case-fold-search t))
5981 (if (re-search-forward org-target-link-regexp limit t)
5982 (progn
5983 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5984 (add-text-properties (match-beginning 0) (match-end 0)
5985 (list 'mouse-face 'highlight
5986 'keymap org-mouse-map
5987 'help-echo "Radio target link"
5988 'org-linked-text t))
5989 (org-rear-nonsticky-at (match-end 0))
5990 t)))))
5992 (defun org-update-radio-target-regexp ()
5993 "Find all radio targets in this file and update the regular expression."
5994 (interactive)
5995 (when (memq 'radio org-activate-links)
5996 (setq org-target-link-regexp
5997 (org-make-target-link-regexp (org-all-targets 'radio)))
5998 (org-restart-font-lock)))
6000 (defun org-hide-wide-columns (limit)
6001 (let (s e)
6002 (setq s (text-property-any (point) (or limit (point-max))
6003 'org-cwidth t))
6004 (when s
6005 (setq e (next-single-property-change s 'org-cwidth))
6006 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6007 (goto-char e)
6008 t)))
6010 (defvar org-latex-and-related-regexp nil
6011 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6012 (defvar org-match-substring-regexp)
6013 (defvar org-match-substring-with-braces-regexp)
6015 (defun org-compute-latex-and-related-regexp ()
6016 "Compute regular expression for LaTeX, entities and sub/superscript.
6017 Result depends on variable `org-highlight-latex-and-related'."
6018 (org-set-local
6019 'org-latex-and-related-regexp
6020 (let* ((re-sub
6021 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6022 ((eq org-use-sub-superscripts '{})
6023 (list org-match-substring-with-braces-regexp))
6024 (org-use-sub-superscripts (list org-match-substring-regexp))))
6025 (re-latex
6026 (when (memq 'latex org-highlight-latex-and-related)
6027 (let ((matchers (plist-get org-format-latex-options :matchers)))
6028 (delq nil
6029 (mapcar (lambda (x)
6030 (and (member (car x) matchers) (nth 1 x)))
6031 org-latex-regexps)))))
6032 (re-entities
6033 (when (memq 'entities org-highlight-latex-and-related)
6034 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6035 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6037 (defun org-do-latex-and-related (limit)
6038 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6039 LIMIT bounds the search for syntax to highlight. Stop at first
6040 highlighted object, if any. Return t if some highlighting was
6041 done, nil otherwise."
6042 (when (org-string-nw-p org-latex-and-related-regexp)
6043 (catch 'found
6044 (while (re-search-forward org-latex-and-related-regexp limit t)
6045 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6046 'face))
6047 '(org-code org-verbatim underline))
6048 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6049 '(?_ ?^))
6051 0)))
6052 (font-lock-prepend-text-property
6053 (+ offset (match-beginning 0)) (match-end 0)
6054 'face 'org-latex-and-related)
6055 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6056 '(font-lock-multiline t)))
6057 (throw 'found t)))
6058 nil)))
6060 (defun org-restart-font-lock ()
6061 "Restart `font-lock-mode', to force refontification."
6062 (when (and (boundp 'font-lock-mode) font-lock-mode)
6063 (font-lock-mode -1)
6064 (font-lock-mode 1)))
6066 (defun org-all-targets (&optional radio)
6067 "Return a list of all targets in this file.
6068 When optional argument RADIO is non-nil, only find radio
6069 targets."
6070 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6071 (save-excursion
6072 (goto-char (point-min))
6073 (while (re-search-forward re nil t)
6074 ;; Make sure point is really within the object.
6075 (backward-char)
6076 (let ((obj (org-element-context)))
6077 (when (memq (org-element-type obj) '(radio-target target))
6078 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6079 rtn)))
6081 (defun org-make-target-link-regexp (targets)
6082 "Make regular expression matching all strings in TARGETS.
6083 The regular expression finds the targets also if there is a line break
6084 between words."
6085 (and targets
6086 (concat
6087 "\\<\\("
6088 (mapconcat
6089 (lambda (x)
6090 (setq x (regexp-quote x))
6091 (while (string-match " +" x)
6092 (setq x (replace-match "\\s-+" t t x)))
6094 targets
6095 "\\|")
6096 "\\)\\>")))
6098 (defun org-activate-tags (limit)
6099 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6100 (progn
6101 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6102 (add-text-properties (match-beginning 1) (match-end 1)
6103 (list 'mouse-face 'highlight
6104 'keymap org-mouse-map))
6105 (org-rear-nonsticky-at (match-end 1))
6106 t)))
6108 (defun org-outline-level ()
6109 "Compute the outline level of the heading at point.
6110 If this is called at a normal headline, the level is the number of stars.
6111 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6112 (save-excursion
6113 (if (not (condition-case nil
6114 (org-back-to-heading t)
6115 (error nil)))
6117 (looking-at org-outline-regexp)
6118 (1- (- (match-end 0) (match-beginning 0))))))
6120 (defvar org-font-lock-keywords nil)
6122 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
6123 "Regular expression matching a property line.")
6125 (defvar org-font-lock-hook nil
6126 "Functions to be called for special font lock stuff.")
6128 (defvar org-font-lock-set-keywords-hook nil
6129 "Functions that can manipulate `org-font-lock-extra-keywords'.
6130 This is called after `org-font-lock-extra-keywords' is defined, but before
6131 it is installed to be used by font lock. This can be useful if something
6132 needs to be inserted at a specific position in the font-lock sequence.")
6134 (defun org-font-lock-hook (limit)
6135 "Run `org-font-lock-hook' within LIMIT."
6136 (run-hook-with-args 'org-font-lock-hook limit))
6138 (defun org-set-font-lock-defaults ()
6139 "Set font lock defaults for the current buffer."
6140 (let* ((em org-fontify-emphasized-text)
6141 (lk org-activate-links)
6142 (org-font-lock-extra-keywords
6143 (list
6144 ;; Call the hook
6145 '(org-font-lock-hook)
6146 ;; Headlines
6147 `(,(if org-fontify-whole-heading-line
6148 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6149 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6150 (1 (org-get-level-face 1))
6151 (2 (org-get-level-face 2))
6152 (3 (org-get-level-face 3)))
6153 ;; Table lines
6154 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6155 (1 'org-table t))
6156 ;; Table internals
6157 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6158 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6159 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6160 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6161 ;; Drawers
6162 (list org-drawer-regexp '(0 'org-special-keyword t))
6163 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6164 ;; Properties
6165 (list org-property-re
6166 '(1 'org-special-keyword t)
6167 '(3 'org-property-value t))
6168 ;; Links
6169 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6170 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6171 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6172 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6173 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6174 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6175 (if (memq 'footnote lk) '(org-activate-footnote-links))
6176 ;; Targets.
6177 (list org-any-target-regexp '(0 'org-target t))
6178 ;; Diary sexps.
6179 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6180 ;; Macro
6181 '("{{{.+}}}" (0 'org-macro t))
6182 '(org-hide-wide-columns (0 nil append))
6183 ;; TODO keyword
6184 (list (format org-heading-keyword-regexp-format
6185 org-todo-regexp)
6186 '(2 (org-get-todo-face 2) t))
6187 ;; DONE
6188 (if org-fontify-done-headline
6189 (list (format org-heading-keyword-regexp-format
6190 (concat
6191 "\\(?:"
6192 (mapconcat 'regexp-quote org-done-keywords "\\|")
6193 "\\)"))
6194 '(2 'org-headline-done t))
6195 nil)
6196 ;; Priorities
6197 '(org-font-lock-add-priority-faces)
6198 ;; Tags
6199 '(org-font-lock-add-tag-faces)
6200 ;; Tags groups
6201 (if (and org-group-tags org-tag-groups-alist)
6202 (list (concat org-outline-regexp-bol ".+\\(:"
6203 (regexp-opt (mapcar 'car org-tag-groups-alist))
6204 ":\\).*$")
6205 '(1 'org-tag-group prepend)))
6206 ;; Special keywords
6207 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6208 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6209 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6210 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6211 ;; Emphasis
6212 (if em
6213 (if (featurep 'xemacs)
6214 '(org-do-emphasis-faces (0 nil append))
6215 '(org-do-emphasis-faces)))
6216 ;; Checkboxes
6217 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6218 1 'org-checkbox prepend)
6219 (if (cdr (assq 'checkbox org-list-automatic-rules))
6220 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6221 (0 (org-get-checkbox-statistics-face) t)))
6222 ;; Description list items
6223 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6224 1 'org-list-dt prepend)
6225 ;; ARCHIVEd headings
6226 (list (concat
6227 org-outline-regexp-bol
6228 "\\(.*:" org-archive-tag ":.*\\)")
6229 '(1 'org-archived prepend))
6230 ;; Specials
6231 '(org-do-latex-and-related)
6232 '(org-fontify-entities)
6233 '(org-raise-scripts)
6234 ;; Code
6235 '(org-activate-code (1 'org-code t))
6236 ;; COMMENT
6237 (list (format org-heading-keyword-regexp-format
6238 (concat "\\("
6239 org-comment-string "\\|" org-quote-string
6240 "\\)"))
6241 '(2 'org-special-keyword t))
6242 ;; Blocks and meta lines
6243 '(org-fontify-meta-lines-and-blocks))))
6244 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6245 (run-hooks 'org-font-lock-set-keywords-hook)
6246 ;; Now set the full font-lock-keywords
6247 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6248 (org-set-local 'font-lock-defaults
6249 '(org-font-lock-keywords t nil nil backward-paragraph))
6250 (kill-local-variable 'font-lock-keywords) nil))
6252 (defun org-toggle-pretty-entities ()
6253 "Toggle the composition display of entities as UTF8 characters."
6254 (interactive)
6255 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6256 (org-restart-font-lock)
6257 (if org-pretty-entities
6258 (message "Entities are now displayed as UTF8 characters")
6259 (save-restriction
6260 (widen)
6261 (org-decompose-region (point-min) (point-max))
6262 (message "Entities are now displayed as plain text"))))
6264 (defvar org-custom-properties-overlays nil
6265 "List of overlays used for custom properties.")
6266 (make-variable-buffer-local 'org-custom-properties-overlays)
6268 (defun org-toggle-custom-properties-visibility ()
6269 "Display or hide properties in `org-custom-properties'."
6270 (interactive)
6271 (if org-custom-properties-overlays
6272 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6273 (setq org-custom-properties-overlays nil))
6274 (unless (not org-custom-properties)
6275 (save-excursion
6276 (save-restriction
6277 (widen)
6278 (goto-char (point-min))
6279 (while (re-search-forward org-property-re nil t)
6280 (mapc (lambda(p)
6281 (when (equal p (substring (match-string 1) 1 -1))
6282 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6283 (overlay-put o 'invisible t)
6284 (overlay-put o 'org-custom-property t)
6285 (push o org-custom-properties-overlays))))
6286 org-custom-properties)))))))
6288 (defun org-fontify-entities (limit)
6289 "Find an entity to fontify."
6290 (let (ee)
6291 (when org-pretty-entities
6292 (catch 'match
6293 (while (re-search-forward
6294 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6295 limit t)
6296 (if (and (not (org-in-indented-comment-line))
6297 (setq ee (org-entity-get (match-string 1)))
6298 (= (length (nth 6 ee)) 1))
6299 (let*
6300 ((end (if (equal (match-string 2) "{}")
6301 (match-end 2)
6302 (match-end 1))))
6303 (add-text-properties
6304 (match-beginning 0) end
6305 (list 'font-lock-fontified t))
6306 (compose-region (match-beginning 0) end
6307 (nth 6 ee) nil)
6308 (backward-char 1)
6309 (throw 'match t))))
6310 nil))))
6312 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6313 "Fontify string S like in Org-mode."
6314 (with-temp-buffer
6315 (insert s)
6316 (let ((org-odd-levels-only odd-levels))
6317 (org-mode)
6318 (font-lock-fontify-buffer)
6319 (buffer-string))))
6321 (defvar org-m nil)
6322 (defvar org-l nil)
6323 (defvar org-f nil)
6324 (defun org-get-level-face (n)
6325 "Get the right face for match N in font-lock matching of headlines."
6326 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6327 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6328 (if org-cycle-level-faces
6329 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6330 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6331 (cond
6332 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6333 ((eq n 2) org-f)
6334 (t (if org-level-color-stars-only nil org-f))))
6337 (defun org-get-todo-face (kwd)
6338 "Get the right face for a TODO keyword KWD.
6339 If KWD is a number, get the corresponding match group."
6340 (if (numberp kwd) (setq kwd (match-string kwd)))
6341 (or (org-face-from-face-or-color
6342 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6343 (and (member kwd org-done-keywords) 'org-done)
6344 'org-todo))
6346 (defun org-face-from-face-or-color (context inherit face-or-color)
6347 "Create a face list that inherits INHERIT, but sets the foreground color.
6348 When FACE-OR-COLOR is not a string, just return it."
6349 (if (stringp face-or-color)
6350 (list :inherit inherit
6351 (cdr (assoc context org-faces-easy-properties))
6352 face-or-color)
6353 face-or-color))
6355 (defun org-font-lock-add-tag-faces (limit)
6356 "Add the special tag faces."
6357 (when (and org-tag-faces org-tags-special-faces-re)
6358 (while (re-search-forward org-tags-special-faces-re limit t)
6359 (add-text-properties (match-beginning 1) (match-end 1)
6360 (list 'face (org-get-tag-face 1)
6361 'font-lock-fontified t))
6362 (backward-char 1))))
6364 (defun org-font-lock-add-priority-faces (limit)
6365 "Add the special priority faces."
6366 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6367 (when (save-match-data (org-at-heading-p))
6368 (add-text-properties
6369 (match-beginning 0) (match-end 0)
6370 (list 'face (or (org-face-from-face-or-color
6371 'priority 'org-priority
6372 (cdr (assoc (char-after (match-beginning 1))
6373 org-priority-faces)))
6374 'org-priority)
6375 'font-lock-fontified t)))))
6377 (defun org-get-tag-face (kwd)
6378 "Get the right face for a TODO keyword KWD.
6379 If KWD is a number, get the corresponding match group."
6380 (if (numberp kwd) (setq kwd (match-string kwd)))
6381 (or (org-face-from-face-or-color
6382 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6383 'org-tag))
6385 (defun org-unfontify-region (beg end &optional maybe_loudly)
6386 "Remove fontification and activation overlays from links."
6387 (font-lock-default-unfontify-region beg end)
6388 (let* ((buffer-undo-list t)
6389 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6390 (inhibit-modification-hooks t)
6391 deactivate-mark buffer-file-name buffer-file-truename)
6392 (org-decompose-region beg end)
6393 (remove-text-properties beg end
6394 '(mouse-face t keymap t org-linked-text t
6395 invisible t intangible t
6396 org-no-flyspell t org-emphasis t))
6397 (org-remove-font-lock-display-properties beg end)))
6399 (defconst org-script-display '(((raise -0.3) (height 0.7))
6400 ((raise 0.3) (height 0.7))
6401 ((raise -0.5))
6402 ((raise 0.5)))
6403 "Display properties for showing superscripts and subscripts.")
6405 (defun org-remove-font-lock-display-properties (beg end)
6406 "Remove specific display properties that have been added by font lock.
6407 The will remove the raise properties that are used to show superscripts
6408 and subscripts."
6409 (let (next prop)
6410 (while (< beg end)
6411 (setq next (next-single-property-change beg 'display nil end)
6412 prop (get-text-property beg 'display))
6413 (if (member prop org-script-display)
6414 (put-text-property beg next 'display nil))
6415 (setq beg next))))
6417 (defun org-raise-scripts (limit)
6418 "Add raise properties to sub/superscripts."
6419 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6420 (if (re-search-forward
6421 (if (eq org-use-sub-superscripts t)
6422 org-match-substring-regexp
6423 org-match-substring-with-braces-regexp)
6424 limit t)
6425 (let* ((pos (point)) table-p comment-p
6426 (mpos (match-beginning 3))
6427 (emph-p (get-text-property mpos 'org-emphasis))
6428 (link-p (get-text-property mpos 'mouse-face))
6429 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6430 (goto-char (point-at-bol))
6431 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6432 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6433 (goto-char pos)
6434 ;; Handle a_b^c
6435 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6436 (if (or comment-p emph-p link-p keyw-p)
6438 (put-text-property (match-beginning 3) (match-end 0)
6439 'display
6440 (if (equal (char-after (match-beginning 2)) ?^)
6441 (nth (if table-p 3 1) org-script-display)
6442 (nth (if table-p 2 0) org-script-display)))
6443 (add-text-properties (match-beginning 2) (match-end 2)
6444 (list 'invisible t
6445 'org-dwidth t 'org-dwidth-n 1))
6446 (if (and (eq (char-after (match-beginning 3)) ?{)
6447 (eq (char-before (match-end 3)) ?}))
6448 (progn
6449 (add-text-properties
6450 (match-beginning 3) (1+ (match-beginning 3))
6451 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6452 (add-text-properties
6453 (1- (match-end 3)) (match-end 3)
6454 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6455 t)))))
6457 ;;;; Visibility cycling, including org-goto and indirect buffer
6459 ;;; Cycling
6461 (defvar org-cycle-global-status nil)
6462 (make-variable-buffer-local 'org-cycle-global-status)
6463 (put 'org-cycle-global-status 'org-state t)
6464 (defvar org-cycle-subtree-status nil)
6465 (make-variable-buffer-local 'org-cycle-subtree-status)
6466 (put 'org-cycle-subtree-status 'org-state t)
6468 (defvar org-inlinetask-min-level)
6470 ;;;###autoload
6471 (defun org-cycle (&optional arg)
6472 "TAB-action and visibility cycling for Org-mode.
6474 This is the command invoked in Org-mode by the TAB key. Its main purpose
6475 is outline visibility cycling, but it also invokes other actions
6476 in special contexts.
6478 - When this function is called with a prefix argument, rotate the entire
6479 buffer through 3 states (global cycling)
6480 1. OVERVIEW: Show only top-level headlines.
6481 2. CONTENTS: Show all headlines of all levels, but no body text.
6482 3. SHOW ALL: Show everything.
6483 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6484 determined by the variable `org-startup-folded', and by any VISIBILITY
6485 properties in the buffer.
6486 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6487 including any drawers.
6489 - When inside a table, re-align the table and move to the next field.
6491 - When point is at the beginning of a headline, rotate the subtree started
6492 by this line through 3 different states (local cycling)
6493 1. FOLDED: Only the main headline is shown.
6494 2. CHILDREN: The main headline and the direct children are shown.
6495 From this state, you can move to one of the children
6496 and zoom in further.
6497 3. SUBTREE: Show the entire subtree, including body text.
6498 If there is no subtree, switch directly from CHILDREN to FOLDED.
6500 - When point is at the beginning of an empty headline and the variable
6501 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6502 of the headline by demoting and promoting it to likely levels. This
6503 speeds up creation document structure by pressing TAB once or several
6504 times right after creating a new headline.
6506 - When there is a numeric prefix, go up to a heading with level ARG, do
6507 a `show-subtree' and return to the previous cursor position. If ARG
6508 is negative, go up that many levels.
6510 - When point is not at the beginning of a headline, execute the global
6511 binding for TAB, which is re-indenting the line. See the option
6512 `org-cycle-emulate-tab' for details.
6514 - Special case: if point is at the beginning of the buffer and there is
6515 no headline in line 1, this function will act as if called with prefix arg
6516 (C-u TAB, same as S-TAB) also when called without prefix arg.
6517 But only if also the variable `org-cycle-global-at-bob' is t."
6518 (interactive "P")
6519 (org-load-modules-maybe)
6520 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6521 (and org-cycle-level-after-item/entry-creation
6522 (or (org-cycle-level)
6523 (org-cycle-item-indentation))))
6524 (let* (message-log-max ; Don't populate the *Messages* buffer
6525 (limit-level
6526 (or org-cycle-max-level
6527 (and (boundp 'org-inlinetask-min-level)
6528 org-inlinetask-min-level
6529 (1- org-inlinetask-min-level))))
6530 (nstars (and limit-level
6531 (if org-odd-levels-only
6532 (and limit-level (1- (* limit-level 2)))
6533 limit-level)))
6534 (org-outline-regexp
6535 (if (not (derived-mode-p 'org-mode))
6536 outline-regexp
6537 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6538 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6539 (not (looking-at org-outline-regexp))))
6540 (org-cycle-hook
6541 (if bob-special
6542 (delq 'org-optimize-window-after-visibility-change
6543 (copy-sequence org-cycle-hook))
6544 org-cycle-hook))
6545 (pos (point)))
6547 (if (or bob-special (equal arg '(4)))
6548 ;; special case: use global cycling
6549 (setq arg t))
6551 (cond
6553 ((equal arg '(16))
6554 (setq last-command 'dummy)
6555 (org-set-startup-visibility)
6556 (message "Startup visibility, plus VISIBILITY properties"))
6558 ((equal arg '(64))
6559 (show-all)
6560 (message "Entire buffer visible, including drawers"))
6562 ;; Table: enter it or move to the next field.
6563 ((org-at-table-p 'any)
6564 (if (org-at-table.el-p)
6565 (message "Use C-c ' to edit table.el tables")
6566 (if arg (org-table-edit-field t)
6567 (org-table-justify-field-maybe)
6568 (call-interactively 'org-table-next-field))))
6570 ((run-hook-with-args-until-success
6571 'org-tab-after-check-for-table-hook))
6573 ;; Global cycling: delegate to `org-cycle-internal-global'.
6574 ((eq arg t) (org-cycle-internal-global))
6576 ;; Drawers: delegate to `org-flag-drawer'.
6577 ((and org-drawers org-drawer-regexp
6578 (save-excursion
6579 (beginning-of-line 1)
6580 (looking-at org-drawer-regexp)))
6581 (org-flag-drawer ; toggle block visibility
6582 (not (get-char-property (match-end 0) 'invisible))))
6584 ;; Show-subtree, ARG levels up from here.
6585 ((integerp arg)
6586 (save-excursion
6587 (org-back-to-heading)
6588 (outline-up-heading (if (< arg 0) (- arg)
6589 (- (funcall outline-level) arg)))
6590 (org-show-subtree)))
6592 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6593 ((and (featurep 'org-inlinetask)
6594 (org-inlinetask-at-task-p)
6595 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6596 (org-inlinetask-toggle-visibility))
6598 ((org-try-cdlatex-tab))
6600 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6601 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6602 (save-excursion (beginning-of-line 1)
6603 (looking-at org-outline-regexp)))
6604 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6605 (org-cycle-internal-local))
6607 ;; From there: TAB emulation and template completion.
6608 (buffer-read-only (org-back-to-heading))
6610 ((run-hook-with-args-until-success
6611 'org-tab-after-check-for-cycling-hook))
6613 ((org-try-structure-completion))
6615 ((run-hook-with-args-until-success
6616 'org-tab-before-tab-emulation-hook))
6618 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6619 (or (not (bolp))
6620 (not (looking-at org-outline-regexp))))
6621 (call-interactively (global-key-binding "\t")))
6623 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6624 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6625 (or (and (eq org-cycle-emulate-tab 'white)
6626 (= (match-end 0) (point-at-eol)))
6627 (and (eq org-cycle-emulate-tab 'whitestart)
6628 (>= (match-end 0) pos))))
6630 (eq org-cycle-emulate-tab t))
6631 (call-interactively (global-key-binding "\t")))
6633 (t (save-excursion
6634 (org-back-to-heading)
6635 (org-cycle)))))))
6637 (defun org-cycle-internal-global ()
6638 "Do the global cycling action."
6639 ;; Hack to avoid display of messages for .org attachments in Gnus
6640 (let (message-log-max ; Don't populate the *Messages* buffer
6641 (ga (string-match "\\*fontification" (buffer-name))))
6642 (cond
6643 ((and (eq last-command this-command)
6644 (eq org-cycle-global-status 'overview))
6645 ;; We just created the overview - now do table of contents
6646 ;; This can be slow in very large buffers, so indicate action
6647 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6648 (unless ga (message "CONTENTS..."))
6649 (org-content)
6650 (unless ga (message "CONTENTS...done"))
6651 (setq org-cycle-global-status 'contents)
6652 (run-hook-with-args 'org-cycle-hook 'contents))
6654 ((and (eq last-command this-command)
6655 (eq org-cycle-global-status 'contents))
6656 ;; We just showed the table of contents - now show everything
6657 (run-hook-with-args 'org-pre-cycle-hook 'all)
6658 (show-all)
6659 (unless ga (message "SHOW ALL"))
6660 (setq org-cycle-global-status 'all)
6661 (run-hook-with-args 'org-cycle-hook 'all))
6664 ;; Default action: go to overview
6665 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6666 (org-overview)
6667 (unless ga (message "OVERVIEW"))
6668 (setq org-cycle-global-status 'overview)
6669 (run-hook-with-args 'org-cycle-hook 'overview)))))
6671 (defun org-cycle-internal-local ()
6672 "Do the local cycling action."
6673 (let (message-log-max ; Don't populate the *Messages* buffer
6674 (goal-column 0) eoh eol eos has-children children-skipped struct)
6675 ;; First, determine end of headline (EOH), end of subtree or item
6676 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6677 (save-excursion
6678 (if (org-at-item-p)
6679 (progn
6680 (beginning-of-line)
6681 (setq struct (org-list-struct))
6682 (setq eoh (point-at-eol))
6683 (setq eos (org-list-get-item-end-before-blank (point) struct))
6684 (setq has-children (org-list-has-child-p (point) struct)))
6685 (org-back-to-heading)
6686 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6687 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6688 (setq has-children
6689 (or (save-excursion
6690 (let ((level (funcall outline-level)))
6691 (outline-next-heading)
6692 (and (org-at-heading-p t)
6693 (> (funcall outline-level) level))))
6694 (save-excursion
6695 (org-list-search-forward (org-item-beginning-re) eos t)))))
6696 ;; Determine end invisible part of buffer (EOL)
6697 (beginning-of-line 2)
6698 ;; XEmacs doesn't have `next-single-char-property-change'
6699 (if (featurep 'xemacs)
6700 (while (and (not (eobp)) ;; this is like `next-line'
6701 (get-char-property (1- (point)) 'invisible))
6702 (beginning-of-line 2))
6703 (while (and (not (eobp)) ;; this is like `next-line'
6704 (get-char-property (1- (point)) 'invisible))
6705 (goto-char (next-single-char-property-change (point) 'invisible))
6706 (and (eolp) (beginning-of-line 2))))
6707 (setq eol (point)))
6708 ;; Find out what to do next and set `this-command'
6709 (cond
6710 ((= eos eoh)
6711 ;; Nothing is hidden behind this heading
6712 (unless (org-before-first-heading-p)
6713 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6714 (message "EMPTY ENTRY")
6715 (setq org-cycle-subtree-status nil)
6716 (save-excursion
6717 (goto-char eos)
6718 (outline-next-heading)
6719 (if (outline-invisible-p) (org-flag-heading nil))))
6720 ((and (or (>= eol eos)
6721 (not (string-match "\\S-" (buffer-substring eol eos))))
6722 (or has-children
6723 (not (setq children-skipped
6724 org-cycle-skip-children-state-if-no-children))))
6725 ;; Entire subtree is hidden in one line: children view
6726 (unless (org-before-first-heading-p)
6727 (run-hook-with-args 'org-pre-cycle-hook 'children))
6728 (if (org-at-item-p)
6729 (org-list-set-item-visibility (point-at-bol) struct 'children)
6730 (org-show-entry)
6731 (org-with-limited-levels (show-children))
6732 ;; FIXME: This slows down the func way too much.
6733 ;; How keep drawers hidden in subtree anyway?
6734 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6735 ;; (org-cycle-hide-drawers 'subtree))
6737 ;; Fold every list in subtree to top-level items.
6738 (when (eq org-cycle-include-plain-lists 'integrate)
6739 (save-excursion
6740 (org-back-to-heading)
6741 (while (org-list-search-forward (org-item-beginning-re) eos t)
6742 (beginning-of-line 1)
6743 (let* ((struct (org-list-struct))
6744 (prevs (org-list-prevs-alist struct))
6745 (end (org-list-get-bottom-point struct)))
6746 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6747 (org-list-get-all-items (point) struct prevs))
6748 (goto-char (if (< end eos) end eos)))))))
6749 (message "CHILDREN")
6750 (save-excursion
6751 (goto-char eos)
6752 (outline-next-heading)
6753 (if (outline-invisible-p) (org-flag-heading nil)))
6754 (setq org-cycle-subtree-status 'children)
6755 (unless (org-before-first-heading-p)
6756 (run-hook-with-args 'org-cycle-hook 'children)))
6757 ((or children-skipped
6758 (and (eq last-command this-command)
6759 (eq org-cycle-subtree-status 'children)))
6760 ;; We just showed the children, or no children are there,
6761 ;; now show everything.
6762 (unless (org-before-first-heading-p)
6763 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6764 (outline-flag-region eoh eos nil)
6765 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6766 (setq org-cycle-subtree-status 'subtree)
6767 (unless (org-before-first-heading-p)
6768 (run-hook-with-args 'org-cycle-hook 'subtree)))
6770 ;; Default action: hide the subtree.
6771 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6772 (outline-flag-region eoh eos t)
6773 (message "FOLDED")
6774 (setq org-cycle-subtree-status 'folded)
6775 (unless (org-before-first-heading-p)
6776 (run-hook-with-args 'org-cycle-hook 'folded))))))
6778 ;;;###autoload
6779 (defun org-global-cycle (&optional arg)
6780 "Cycle the global visibility. For details see `org-cycle'.
6781 With \\[universal-argument] prefix arg, switch to startup visibility.
6782 With a numeric prefix, show all headlines up to that level."
6783 (interactive "P")
6784 (let ((org-cycle-include-plain-lists
6785 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6786 (cond
6787 ((integerp arg)
6788 (show-all)
6789 (hide-sublevels arg)
6790 (setq org-cycle-global-status 'contents))
6791 ((equal arg '(4))
6792 (org-set-startup-visibility)
6793 (message "Startup visibility, plus VISIBILITY properties."))
6795 (org-cycle '(4))))))
6797 (defun org-set-startup-visibility ()
6798 "Set the visibility required by startup options and properties."
6799 (cond
6800 ((eq org-startup-folded t)
6801 (org-cycle '(4)))
6802 ((eq org-startup-folded 'content)
6803 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6804 (org-cycle '(4)) (org-cycle '(4)))))
6805 (unless (eq org-startup-folded 'showeverything)
6806 (if org-hide-block-startup (org-hide-block-all))
6807 (org-set-visibility-according-to-property 'no-cleanup)
6808 (org-cycle-hide-archived-subtrees 'all)
6809 (org-cycle-hide-drawers 'all)
6810 (org-cycle-show-empty-lines t)))
6812 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6813 "Switch subtree visibilities according to :VISIBILITY: property."
6814 (interactive)
6815 (let (org-show-entry-below state)
6816 (save-excursion
6817 (goto-char (point-min))
6818 (while (re-search-forward
6819 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6820 nil t)
6821 (setq state (match-string 1))
6822 (save-excursion
6823 (org-back-to-heading t)
6824 (hide-subtree)
6825 (org-reveal)
6826 (cond
6827 ((equal state '("fold" "folded"))
6828 (hide-subtree))
6829 ((equal state "children")
6830 (org-show-hidden-entry)
6831 (show-children))
6832 ((equal state "content")
6833 (save-excursion
6834 (save-restriction
6835 (org-narrow-to-subtree)
6836 (org-content))))
6837 ((member state '("all" "showall"))
6838 (show-subtree)))))
6839 (unless no-cleanup
6840 (org-cycle-hide-archived-subtrees 'all)
6841 (org-cycle-hide-drawers 'all)
6842 (org-cycle-show-empty-lines 'all)))))
6844 ;; This function uses outline-regexp instead of the more fundamental
6845 ;; org-outline-regexp so that org-cycle-global works outside of Org
6846 ;; buffers, where outline-regexp is needed.
6847 (defun org-overview ()
6848 "Switch to overview mode, showing only top-level headlines.
6849 Really, this shows all headlines with level equal or greater than the level
6850 of the first headline in the buffer. This is important, because if the
6851 first headline is not level one, then (hide-sublevels 1) gives confusing
6852 results."
6853 (interactive)
6854 (let ((l (org-current-line))
6855 (level (save-excursion
6856 (goto-char (point-min))
6857 (if (re-search-forward (concat "^" outline-regexp) nil t)
6858 (progn
6859 (goto-char (match-beginning 0))
6860 (funcall outline-level))))))
6861 (and level (hide-sublevels level))
6862 (recenter '(4))
6863 (org-goto-line l)))
6865 (defun org-content (&optional arg)
6866 "Show all headlines in the buffer, like a table of contents.
6867 With numerical argument N, show content up to level N."
6868 (interactive "P")
6869 (save-excursion
6870 ;; Visit all headings and show their offspring
6871 (and (integerp arg) (org-overview))
6872 (goto-char (point-max))
6873 (catch 'exit
6874 (while (and (progn (condition-case nil
6875 (outline-previous-visible-heading 1)
6876 (error (goto-char (point-min))))
6878 (looking-at org-outline-regexp))
6879 (if (integerp arg)
6880 (show-children (1- arg))
6881 (show-branches))
6882 (if (bobp) (throw 'exit nil))))))
6885 (defun org-optimize-window-after-visibility-change (state)
6886 "Adjust the window after a change in outline visibility.
6887 This function is the default value of the hook `org-cycle-hook'."
6888 (when (get-buffer-window (current-buffer))
6889 (cond
6890 ((eq state 'content) nil)
6891 ((eq state 'all) nil)
6892 ((eq state 'folded) nil)
6893 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6894 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6896 (defun org-remove-empty-overlays-at (pos)
6897 "Remove outline overlays that do not contain non-white stuff."
6898 (mapc
6899 (lambda (o)
6900 (and (eq 'outline (overlay-get o 'invisible))
6901 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6902 (overlay-end o))))
6903 (delete-overlay o)))
6904 (overlays-at pos)))
6906 (defun org-clean-visibility-after-subtree-move ()
6907 "Fix visibility issues after moving a subtree."
6908 ;; First, find a reasonable region to look at:
6909 ;; Start two siblings above, end three below
6910 (let* ((beg (save-excursion
6911 (and (org-get-last-sibling)
6912 (org-get-last-sibling))
6913 (point)))
6914 (end (save-excursion
6915 (and (org-get-next-sibling)
6916 (org-get-next-sibling)
6917 (org-get-next-sibling))
6918 (if (org-at-heading-p)
6919 (point-at-eol)
6920 (point))))
6921 (level (looking-at "\\*+"))
6922 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6923 (save-excursion
6924 (save-restriction
6925 (narrow-to-region beg end)
6926 (when re
6927 ;; Properly fold already folded siblings
6928 (goto-char (point-min))
6929 (while (re-search-forward re nil t)
6930 (if (and (not (outline-invisible-p))
6931 (save-excursion
6932 (goto-char (point-at-eol)) (outline-invisible-p)))
6933 (hide-entry))))
6934 (org-cycle-show-empty-lines 'overview)
6935 (org-cycle-hide-drawers 'overview)))))
6937 (defun org-cycle-show-empty-lines (state)
6938 "Show empty lines above all visible headlines.
6939 The region to be covered depends on STATE when called through
6940 `org-cycle-hook'. Lisp program can use t for STATE to get the
6941 entire buffer covered. Note that an empty line is only shown if there
6942 are at least `org-cycle-separator-lines' empty lines before the headline."
6943 (when (not (= org-cycle-separator-lines 0))
6944 (save-excursion
6945 (let* ((n (abs org-cycle-separator-lines))
6946 (re (cond
6947 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6948 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6949 (t (let ((ns (number-to-string (- n 2))))
6950 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6951 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6952 beg end b e)
6953 (cond
6954 ((memq state '(overview contents t))
6955 (setq beg (point-min) end (point-max)))
6956 ((memq state '(children folded))
6957 (setq beg (point) end (progn (org-end-of-subtree t t)
6958 (beginning-of-line 2)
6959 (point)))))
6960 (when beg
6961 (goto-char beg)
6962 (while (re-search-forward re end t)
6963 (unless (get-char-property (match-end 1) 'invisible)
6964 (setq e (match-end 1))
6965 (if (< org-cycle-separator-lines 0)
6966 (setq b (save-excursion
6967 (goto-char (match-beginning 0))
6968 (org-back-over-empty-lines)
6969 (if (save-excursion
6970 (goto-char (max (point-min) (1- (point))))
6971 (org-at-heading-p))
6972 (1- (point))
6973 (point))))
6974 (setq b (match-beginning 1)))
6975 (outline-flag-region b e nil)))))))
6976 ;; Never hide empty lines at the end of the file.
6977 (save-excursion
6978 (goto-char (point-max))
6979 (outline-previous-heading)
6980 (outline-end-of-heading)
6981 (if (and (looking-at "[ \t\n]+")
6982 (= (match-end 0) (point-max)))
6983 (outline-flag-region (point) (match-end 0) nil))))
6985 (defun org-show-empty-lines-in-parent ()
6986 "Move to the parent and re-show empty lines before visible headlines."
6987 (save-excursion
6988 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6989 (org-cycle-show-empty-lines context))))
6991 (defun org-files-list ()
6992 "Return `org-agenda-files' list, plus all open org-mode files.
6993 This is useful for operations that need to scan all of a user's
6994 open and agenda-wise Org files."
6995 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6996 (dolist (buf (buffer-list))
6997 (with-current-buffer buf
6998 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6999 (let ((file (expand-file-name (buffer-file-name))))
7000 (unless (member file files)
7001 (push file files))))))
7002 files))
7004 (defsubst org-entry-beginning-position ()
7005 "Return the beginning position of the current entry."
7006 (save-excursion (outline-back-to-heading t) (point)))
7008 (defsubst org-entry-end-position ()
7009 "Return the end position of the current entry."
7010 (save-excursion (outline-next-heading) (point)))
7012 (defun org-cycle-hide-drawers (state)
7013 "Re-hide all drawers after a visibility state change."
7014 (when (and (derived-mode-p 'org-mode)
7015 (not (memq state '(overview folded contents))))
7016 (save-excursion
7017 (let* ((globalp (memq state '(contents all)))
7018 (beg (if globalp (point-min) (point)))
7019 (end (if globalp (point-max)
7020 (if (eq state 'children)
7021 (save-excursion (outline-next-heading) (point))
7022 (org-end-of-subtree t)))))
7023 (goto-char beg)
7024 (while (re-search-forward org-drawer-regexp end t)
7025 (org-flag-drawer t))))))
7027 (defun org-cycle-hide-inline-tasks (state)
7028 "Re-hide inline task when switching to 'contents visibility state."
7029 (when (and (eq state 'contents)
7030 (boundp 'org-inlinetask-min-level)
7031 org-inlinetask-min-level)
7032 (hide-sublevels (1- org-inlinetask-min-level))))
7034 (defun org-flag-drawer (flag)
7035 "When FLAG is non-nil, hide the drawer we are within.
7036 Otherwise make it visible."
7037 (save-excursion
7038 (beginning-of-line 1)
7039 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7040 (let ((b (match-end 0)))
7041 (if (re-search-forward
7042 "^[ \t]*:END:"
7043 (save-excursion (outline-next-heading) (point)) t)
7044 (outline-flag-region b (point-at-eol) flag)
7045 (user-error ":END: line missing at position %s" b))))))
7047 (defun org-subtree-end-visible-p ()
7048 "Is the end of the current subtree visible?"
7049 (pos-visible-in-window-p
7050 (save-excursion (org-end-of-subtree t) (point))))
7052 (defun org-first-headline-recenter (&optional N)
7053 "Move cursor to the first headline and recenter the headline.
7054 Optional argument N means put the headline into the Nth line of the window."
7055 (goto-char (point-min))
7056 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7057 (beginning-of-line)
7058 (recenter (prefix-numeric-value N))))
7060 ;;; Saving and restoring visibility
7062 (defun org-outline-overlay-data (&optional use-markers)
7063 "Return a list of the locations of all outline overlays.
7064 These are overlays with the `invisible' property value `outline'.
7065 The return value is a list of cons cells, with start and stop
7066 positions for each overlay.
7067 If USE-MARKERS is set, return the positions as markers."
7068 (let (beg end)
7069 (save-excursion
7070 (save-restriction
7071 (widen)
7072 (delq nil
7073 (mapcar (lambda (o)
7074 (when (eq (overlay-get o 'invisible) 'outline)
7075 (setq beg (overlay-start o)
7076 end (overlay-end o))
7077 (and beg end (> end beg)
7078 (if use-markers
7079 (cons (move-marker (make-marker) beg)
7080 (move-marker (make-marker) end))
7081 (cons beg end)))))
7082 (overlays-in (point-min) (point-max))))))))
7084 (defun org-set-outline-overlay-data (data)
7085 "Create visibility overlays for all positions in DATA.
7086 DATA should have been made by `org-outline-overlay-data'."
7087 (let (o)
7088 (save-excursion
7089 (save-restriction
7090 (widen)
7091 (show-all)
7092 (mapc (lambda (c)
7093 (outline-flag-region (car c) (cdr c) t))
7094 data)))))
7096 ;;; Folding of blocks
7098 (defvar org-hide-block-overlays nil
7099 "Overlays hiding blocks.")
7100 (make-variable-buffer-local 'org-hide-block-overlays)
7102 (defun org-block-map (function &optional start end)
7103 "Call FUNCTION at the head of all source blocks in the current buffer.
7104 Optional arguments START and END can be used to limit the range."
7105 (let ((start (or start (point-min)))
7106 (end (or end (point-max))))
7107 (save-excursion
7108 (goto-char start)
7109 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7110 (save-excursion
7111 (save-match-data
7112 (goto-char (match-beginning 0))
7113 (funcall function)))))))
7115 (defun org-hide-block-toggle-all ()
7116 "Toggle the visibility of all blocks in the current buffer."
7117 (org-block-map #'org-hide-block-toggle))
7119 (defun org-hide-block-all ()
7120 "Fold all blocks in the current buffer."
7121 (interactive)
7122 (org-show-block-all)
7123 (org-block-map #'org-hide-block-toggle-maybe))
7125 (defun org-show-block-all ()
7126 "Unfold all blocks in the current buffer."
7127 (interactive)
7128 (mapc 'delete-overlay org-hide-block-overlays)
7129 (setq org-hide-block-overlays nil))
7131 (defun org-hide-block-toggle-maybe ()
7132 "Toggle visibility of block at point."
7133 (interactive)
7134 (let ((case-fold-search t))
7135 (if (save-excursion
7136 (beginning-of-line 1)
7137 (looking-at org-block-regexp))
7138 (progn (org-hide-block-toggle)
7139 t) ;; to signal that we took action
7140 nil))) ;; to signal that we did not
7142 (defun org-hide-block-toggle (&optional force)
7143 "Toggle the visibility of the current block."
7144 (interactive)
7145 (save-excursion
7146 (beginning-of-line)
7147 (if (re-search-forward org-block-regexp nil t)
7148 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7149 (end (match-end 0)) ;; end of entire body
7151 (if (memq t (mapcar (lambda (overlay)
7152 (eq (overlay-get overlay 'invisible)
7153 'org-hide-block))
7154 (overlays-at start)))
7155 (if (or (not force) (eq force 'off))
7156 (mapc (lambda (ov)
7157 (when (member ov org-hide-block-overlays)
7158 (setq org-hide-block-overlays
7159 (delq ov org-hide-block-overlays)))
7160 (when (eq (overlay-get ov 'invisible)
7161 'org-hide-block)
7162 (delete-overlay ov)))
7163 (overlays-at start)))
7164 (setq ov (make-overlay start end))
7165 (overlay-put ov 'invisible 'org-hide-block)
7166 ;; make the block accessible to isearch
7167 (overlay-put
7168 ov 'isearch-open-invisible
7169 (lambda (ov)
7170 (when (member ov org-hide-block-overlays)
7171 (setq org-hide-block-overlays
7172 (delq ov org-hide-block-overlays)))
7173 (when (eq (overlay-get ov 'invisible)
7174 'org-hide-block)
7175 (delete-overlay ov))))
7176 (push ov org-hide-block-overlays)))
7177 (user-error "Not looking at a source block"))))
7179 ;; org-tab-after-check-for-cycling-hook
7180 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7181 ;; Remove overlays when changing major mode
7182 (add-hook 'org-mode-hook
7183 (lambda () (org-add-hook 'change-major-mode-hook
7184 'org-show-block-all 'append 'local)))
7186 ;;; Org-goto
7188 (defvar org-goto-window-configuration nil)
7189 (defvar org-goto-marker nil)
7190 (defvar org-goto-map)
7191 (defun org-goto-map ()
7192 "Set the keymap `org-goto'."
7193 (setq org-goto-map
7194 (let ((map (make-sparse-keymap)))
7195 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7196 mouse-drag-region universal-argument org-occur))
7197 cmd)
7198 (while (setq cmd (pop cmds))
7199 (substitute-key-definition cmd cmd map global-map)))
7200 (suppress-keymap map)
7201 (org-defkey map "\C-m" 'org-goto-ret)
7202 (org-defkey map [(return)] 'org-goto-ret)
7203 (org-defkey map [(left)] 'org-goto-left)
7204 (org-defkey map [(right)] 'org-goto-right)
7205 (org-defkey map [(control ?g)] 'org-goto-quit)
7206 (org-defkey map "\C-i" 'org-cycle)
7207 (org-defkey map [(tab)] 'org-cycle)
7208 (org-defkey map [(down)] 'outline-next-visible-heading)
7209 (org-defkey map [(up)] 'outline-previous-visible-heading)
7210 (if org-goto-auto-isearch
7211 (if (fboundp 'define-key-after)
7212 (define-key-after map [t] 'org-goto-local-auto-isearch)
7213 nil)
7214 (org-defkey map "q" 'org-goto-quit)
7215 (org-defkey map "n" 'outline-next-visible-heading)
7216 (org-defkey map "p" 'outline-previous-visible-heading)
7217 (org-defkey map "f" 'outline-forward-same-level)
7218 (org-defkey map "b" 'outline-backward-same-level)
7219 (org-defkey map "u" 'outline-up-heading))
7220 (org-defkey map "/" 'org-occur)
7221 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7222 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7223 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7224 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7225 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7226 map)))
7228 (defconst org-goto-help
7229 "Browse buffer copy, to find location or copy text.%s
7230 RET=jump to location C-g=quit and return to previous location
7231 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7233 (defvar org-goto-start-pos) ; dynamically scoped parameter
7235 (defun org-goto (&optional alternative-interface)
7236 "Look up a different location in the current file, keeping current visibility.
7238 When you want look-up or go to a different location in a
7239 document, the fastest way is often to fold the entire buffer and
7240 then dive into the tree. This method has the disadvantage, that
7241 the previous location will be folded, which may not be what you
7242 want.
7244 This command works around this by showing a copy of the current
7245 buffer in an indirect buffer, in overview mode. You can dive
7246 into the tree in that copy, use org-occur and incremental search
7247 to find a location. When pressing RET or `Q', the command
7248 returns to the original buffer in which the visibility is still
7249 unchanged. After RET it will also jump to the location selected
7250 in the indirect buffer and expose the headline hierarchy above.
7252 With a prefix argument, use the alternative interface: e.g. if
7253 `org-goto-interface' is 'outline use 'outline-path-completion."
7254 (interactive "P")
7255 (org-goto-map)
7256 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7257 (org-refile-use-outline-path t)
7258 (org-refile-target-verify-function nil)
7259 (interface
7260 (if (not alternative-interface)
7261 org-goto-interface
7262 (if (eq org-goto-interface 'outline)
7263 'outline-path-completion
7264 'outline)))
7265 (org-goto-start-pos (point))
7266 (selected-point
7267 (if (eq interface 'outline)
7268 (car (org-get-location (current-buffer) org-goto-help))
7269 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7270 (org-refile-check-position pa)
7271 (nth 3 pa)))))
7272 (if selected-point
7273 (progn
7274 (org-mark-ring-push org-goto-start-pos)
7275 (goto-char selected-point)
7276 (if (or (outline-invisible-p) (org-invisible-p2))
7277 (org-show-context 'org-goto)))
7278 (message "Quit"))))
7280 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7281 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7282 (defvar org-goto-local-auto-isearch-map) ; defined below
7284 (defun org-get-location (buf help)
7285 "Let the user select a location in the Org-mode buffer BUF.
7286 This function uses a recursive edit. It returns the selected position
7287 or nil."
7288 (org-no-popups
7289 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7290 (isearch-hide-immediately nil)
7291 (isearch-search-fun-function
7292 (lambda () 'org-goto-local-search-headings))
7293 (org-goto-selected-point org-goto-exit-command))
7294 (save-excursion
7295 (save-window-excursion
7296 (delete-other-windows)
7297 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7298 (org-pop-to-buffer-same-window
7299 (condition-case nil
7300 (make-indirect-buffer (current-buffer) "*org-goto*")
7301 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7302 (with-output-to-temp-buffer "*Org Help*"
7303 (princ (format help (if org-goto-auto-isearch
7304 " Just type for auto-isearch."
7305 " n/p/f/b/u to navigate, q to quit."))))
7306 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7307 (setq buffer-read-only nil)
7308 (let ((org-startup-truncated t)
7309 (org-startup-folded nil)
7310 (org-startup-align-all-tables nil))
7311 (org-mode)
7312 (org-overview))
7313 (setq buffer-read-only t)
7314 (if (and (boundp 'org-goto-start-pos)
7315 (integer-or-marker-p org-goto-start-pos))
7316 (let ((org-show-hierarchy-above t)
7317 (org-show-siblings t)
7318 (org-show-following-heading t))
7319 (goto-char org-goto-start-pos)
7320 (and (outline-invisible-p) (org-show-context)))
7321 (goto-char (point-min)))
7322 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7323 (message "Select location and press RET")
7324 (use-local-map org-goto-map)
7325 (recursive-edit)))
7326 (kill-buffer "*org-goto*")
7327 (cons org-goto-selected-point org-goto-exit-command))))
7329 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7330 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7331 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7332 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7334 (defun org-goto-local-search-headings (string bound noerror)
7335 "Search and make sure that any matches are in headlines."
7336 (catch 'return
7337 (while (if isearch-forward
7338 (search-forward string bound noerror)
7339 (search-backward string bound noerror))
7340 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7341 (and (member :headline context)
7342 (not (member :tags context))))
7343 (throw 'return (point))))))
7345 (defun org-goto-local-auto-isearch ()
7346 "Start isearch."
7347 (interactive)
7348 (goto-char (point-min))
7349 (let ((keys (this-command-keys)))
7350 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7351 (isearch-mode t)
7352 (isearch-process-search-char (string-to-char keys)))))
7354 (defun org-goto-ret (&optional arg)
7355 "Finish `org-goto' by going to the new location."
7356 (interactive "P")
7357 (setq org-goto-selected-point (point)
7358 org-goto-exit-command 'return)
7359 (throw 'exit nil))
7361 (defun org-goto-left ()
7362 "Finish `org-goto' by going to the new location."
7363 (interactive)
7364 (if (org-at-heading-p)
7365 (progn
7366 (beginning-of-line 1)
7367 (setq org-goto-selected-point (point)
7368 org-goto-exit-command 'left)
7369 (throw 'exit nil))
7370 (user-error "Not on a heading")))
7372 (defun org-goto-right ()
7373 "Finish `org-goto' by going to the new location."
7374 (interactive)
7375 (if (org-at-heading-p)
7376 (progn
7377 (setq org-goto-selected-point (point)
7378 org-goto-exit-command 'right)
7379 (throw 'exit nil))
7380 (user-error "Not on a heading")))
7382 (defun org-goto-quit ()
7383 "Finish `org-goto' without cursor motion."
7384 (interactive)
7385 (setq org-goto-selected-point nil)
7386 (setq org-goto-exit-command 'quit)
7387 (throw 'exit nil))
7389 ;;; Indirect buffer display of subtrees
7391 (defvar org-indirect-dedicated-frame nil
7392 "This is the frame being used for indirect tree display.")
7393 (defvar org-last-indirect-buffer nil)
7395 (defun org-tree-to-indirect-buffer (&optional arg)
7396 "Create indirect buffer and narrow it to current subtree.
7397 With a numerical prefix ARG, go up to this level and then take that tree.
7398 If ARG is negative, go up that many levels.
7400 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7401 indirect buffer previously made with this command, to avoid proliferation of
7402 indirect buffers. However, when you call the command with a \
7403 \\[universal-argument] prefix, or
7404 when `org-indirect-buffer-display' is `new-frame', the last buffer
7405 is kept so that you can work with several indirect buffers at the same time.
7406 If `org-indirect-buffer-display' is `dedicated-frame', the \
7407 \\[universal-argument] prefix also
7408 requests that a new frame be made for the new buffer, so that the dedicated
7409 frame is not changed."
7410 (interactive "P")
7411 (let ((cbuf (current-buffer))
7412 (cwin (selected-window))
7413 (pos (point))
7414 beg end level heading ibuf)
7415 (save-excursion
7416 (org-back-to-heading t)
7417 (when (numberp arg)
7418 (setq level (org-outline-level))
7419 (if (< arg 0) (setq arg (+ level arg)))
7420 (while (> (setq level (org-outline-level)) arg)
7421 (org-up-heading-safe)))
7422 (setq beg (point)
7423 heading (org-get-heading))
7424 (org-end-of-subtree t t)
7425 (if (org-at-heading-p) (backward-char 1))
7426 (setq end (point)))
7427 (if (and (buffer-live-p org-last-indirect-buffer)
7428 (not (eq org-indirect-buffer-display 'new-frame))
7429 (not arg))
7430 (kill-buffer org-last-indirect-buffer))
7431 (setq ibuf (org-get-indirect-buffer cbuf)
7432 org-last-indirect-buffer ibuf)
7433 (cond
7434 ((or (eq org-indirect-buffer-display 'new-frame)
7435 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7436 (select-frame (make-frame))
7437 (delete-other-windows)
7438 (org-pop-to-buffer-same-window ibuf)
7439 (org-set-frame-title heading))
7440 ((eq org-indirect-buffer-display 'dedicated-frame)
7441 (raise-frame
7442 (select-frame (or (and org-indirect-dedicated-frame
7443 (frame-live-p org-indirect-dedicated-frame)
7444 org-indirect-dedicated-frame)
7445 (setq org-indirect-dedicated-frame (make-frame)))))
7446 (delete-other-windows)
7447 (org-pop-to-buffer-same-window ibuf)
7448 (org-set-frame-title (concat "Indirect: " heading)))
7449 ((eq org-indirect-buffer-display 'current-window)
7450 (org-pop-to-buffer-same-window ibuf))
7451 ((eq org-indirect-buffer-display 'other-window)
7452 (pop-to-buffer ibuf))
7453 (t (error "Invalid value")))
7454 (if (featurep 'xemacs)
7455 (save-excursion (org-mode) (turn-on-font-lock)))
7456 (narrow-to-region beg end)
7457 (show-all)
7458 (goto-char pos)
7459 (run-hook-with-args 'org-cycle-hook 'all)
7460 (and (window-live-p cwin) (select-window cwin))))
7462 (defun org-get-indirect-buffer (&optional buffer)
7463 (setq buffer (or buffer (current-buffer)))
7464 (let ((n 1) (base (buffer-name buffer)) bname)
7465 (while (buffer-live-p
7466 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7467 (setq n (1+ n)))
7468 (condition-case nil
7469 (make-indirect-buffer buffer bname 'clone)
7470 (error (make-indirect-buffer buffer bname)))))
7472 (defun org-set-frame-title (title)
7473 "Set the title of the current frame to the string TITLE."
7474 ;; FIXME: how to name a single frame in XEmacs???
7475 (unless (featurep 'xemacs)
7476 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7478 ;;;; Structure editing
7480 ;;; Inserting headlines
7482 (defun org-previous-line-empty-p (&optional next)
7483 "Is the previous line a blank line?
7484 When NEXT is non-nil, check the next line instead."
7485 (save-excursion
7486 (and (not (bobp))
7487 (or (beginning-of-line (if next 2 0)) t)
7488 (save-match-data
7489 (looking-at "[ \t]*$")))))
7491 (defun org-insert-heading (&optional arg invisible-ok)
7492 "Insert a new heading or item with same depth at point.
7493 If point is in a plain list and ARG is nil, create a new list item.
7494 With one universal prefix argument, insert a heading even in lists.
7495 With two universal prefix arguments, insert the heading at the end
7496 of the parent subtree.
7498 If point is at the beginning of a headline, insert a sibling before
7499 the current headline. If point is not at the beginning, split the line
7500 and create a new headline with the text in the current line after point
7501 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7503 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7504 This is important for non-interactive uses of the command."
7505 (interactive "P")
7506 (if (org-called-interactively-p 'any) (org-reveal))
7507 (cond
7508 ((or (= (buffer-size) 0)
7509 (and (not (save-excursion
7510 (and (ignore-errors (org-back-to-heading invisible-ok))
7511 (org-at-heading-p))))
7512 (or arg (not (org-in-item-p)))))
7513 (insert
7514 (if (org-previous-line-empty-p) "" "\n")
7515 (if (org-in-src-block-p) ",* " "* "))
7516 (run-hooks 'org-insert-heading-hook))
7517 ((or arg
7518 (and (not (org-in-item-p)) org-insert-heading-respect-content)
7519 (not (org-insert-item
7520 (save-excursion
7521 (beginning-of-line)
7522 (looking-at org-list-full-item-re)
7523 (match-string 3)))))
7524 (let (begn endn)
7525 (when (org-buffer-narrowed-p)
7526 (setq begn (point-min) endn (point-max))
7527 (widen))
7528 (let* ((empty-line-p nil)
7529 (eops (equal arg '(16))) ; insert at end of parent subtree
7530 (org-insert-heading-respect-content
7531 (or (not (null arg)) org-insert-heading-respect-content))
7532 (level nil)
7533 (on-heading (org-at-heading-p))
7534 ;; Get a level to fall back on
7535 (fix-level
7536 (save-excursion
7537 (org-back-to-heading t)
7538 (looking-at org-outline-regexp)
7539 (make-string (1- (length (match-string 0))) ?*)))
7540 (on-empty-line
7541 (save-excursion (beginning-of-line 1) (looking-at "^\\s-*$")))
7542 (head (save-excursion
7543 (condition-case nil
7544 (progn
7545 (org-back-to-heading invisible-ok)
7546 (when (and (not on-heading)
7547 (featurep 'org-inlinetask)
7548 (integerp org-inlinetask-min-level)
7549 (>= (length (match-string 0))
7550 org-inlinetask-min-level))
7551 ;; Find a heading level before the inline task
7552 (while (and (setq level (org-up-heading-safe))
7553 (>= level org-inlinetask-min-level)))
7554 (if (org-at-heading-p)
7555 (org-back-to-heading invisible-ok)
7556 (error "This should not happen")))
7557 (unless (and (save-excursion
7558 (save-match-data
7559 (org-backward-heading-same-level 1 invisible-ok))
7560 (= (point) (match-beginning 0)))
7561 (not (org-previous-line-empty-p t)))
7562 (setq empty-line-p (org-previous-line-empty-p)))
7563 (match-string 0))
7564 (error (or fix-level "* ")))))
7565 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7566 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7567 pos hide-previous previous-pos)
7568 (if ;; At the beginning of a heading, open a new line for insertion
7569 (and (bolp) (org-at-heading-p)
7570 (not eops)
7571 (or (bobp)
7572 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7573 (open-line (if blank 2 1))
7574 (save-excursion
7575 (setq previous-pos (point-at-bol))
7576 (end-of-line)
7577 (setq hide-previous (outline-invisible-p)))
7578 (and org-insert-heading-respect-content
7579 (save-excursion
7580 (while (outline-invisible-p)
7581 (org-show-subtree)
7582 (org-up-heading-safe))))
7583 (let ((split
7584 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7585 (save-excursion
7586 (let ((p (point)))
7587 (goto-char (point-at-bol))
7588 (and (looking-at org-complex-heading-regexp)
7589 (match-beginning 4)
7590 (> p (match-beginning 4)))))))
7591 tags pos)
7592 (cond
7593 ;; Insert a new line, possibly at end of parent subtree
7594 ((and (not arg) (not on-heading) (not on-empty-line)
7595 (not (save-excursion
7596 (beginning-of-line 1)
7597 (or (looking-at org-list-full-item-re)
7598 ;; Don't convert :end: lines to headline
7599 (looking-at "^\\s-*:end:")
7600 (looking-at "^\\s-*#\\+end_?")))))
7601 (beginning-of-line 1))
7602 (org-insert-heading-respect-content
7603 (if (not eops)
7604 (progn
7605 (org-end-of-subtree nil t)
7606 (and (looking-at "^\\*") (backward-char 1))
7607 (while (and (not (bobp))
7608 ;; Don't delete spaces in empty headlines
7609 (not (looking-back org-outline-regexp))
7610 (member (char-before) '(?\ ?\t ?\n)))
7611 (backward-delete-char 1)))
7612 (let ((p (point)))
7613 (org-up-heading-safe)
7614 (if (= p (point))
7615 (goto-char (point-max))
7616 (org-end-of-subtree nil t))))
7617 (when (featurep 'org-inlinetask)
7618 (while (and (not (eobp))
7619 (looking-at "\\(\\*+\\)[ \t]+")
7620 (>= (length (match-string 1))
7621 org-inlinetask-min-level))
7622 (org-end-of-subtree nil t)))
7623 (or (bolp) (newline))
7624 (or (org-previous-line-empty-p)
7625 (and blank (newline)))
7626 (if (or empty-line-p eops) (open-line 1)))
7627 ;; Insert a headling containing text after point
7628 ((org-at-heading-p)
7629 (when hide-previous
7630 (show-children)
7631 (org-show-entry))
7632 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7633 (setq tags (and (match-end 2) (match-string 2)))
7634 (and (match-end 1)
7635 (delete-region (match-beginning 1) (match-end 1)))
7636 (setq pos (point-at-bol))
7637 (or split (end-of-line 1))
7638 (delete-horizontal-space)
7639 (if (string-match "\\`\\*+\\'"
7640 (buffer-substring (point-at-bol) (point)))
7641 (insert " "))
7642 (newline (if blank 2 1))
7643 (when tags
7644 (save-excursion
7645 (goto-char pos)
7646 (end-of-line 1)
7647 (insert " " tags)
7648 (org-set-tags nil 'align))))
7650 (or split (end-of-line 1))
7651 (newline (cond ((and blank (not on-empty-line)) 2)
7652 (blank 1)
7653 (on-empty-line 0) (t 1)))))))
7654 (insert head) (just-one-space)
7655 (setq pos (point))
7656 (end-of-line 1)
7657 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7658 (when (and org-insert-heading-respect-content hide-previous)
7659 (save-excursion
7660 (goto-char previous-pos)
7661 (hide-subtree)))
7662 (when (and begn endn)
7663 (narrow-to-region (min (point) begn) (max (point) endn)))
7664 (run-hooks 'org-insert-heading-hook))))))
7666 (defun org-get-heading (&optional no-tags no-todo)
7667 "Return the heading of the current entry, without the stars.
7668 When NO-TAGS is non-nil, don't include tags.
7669 When NO-TODO is non-nil, don't include TODO keywords."
7670 (save-excursion
7671 (org-back-to-heading t)
7672 (cond
7673 ((and no-tags no-todo)
7674 (looking-at org-complex-heading-regexp)
7675 (match-string 4))
7676 (no-tags
7677 (looking-at (concat org-outline-regexp
7678 "\\(.*?\\)"
7679 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7680 (match-string 1))
7681 (no-todo
7682 (looking-at org-todo-line-regexp)
7683 (match-string 3))
7684 (t (looking-at org-heading-regexp)
7685 (match-string 2)))))
7687 (defvar orgstruct-mode) ; defined below
7689 (defun org-heading-components ()
7690 "Return the components of the current heading.
7691 This is a list with the following elements:
7692 - the level as an integer
7693 - the reduced level, different if `org-odd-levels-only' is set.
7694 - the TODO keyword, or nil
7695 - the priority character, like ?A, or nil if no priority is given
7696 - the headline text itself, or the tags string if no headline text
7697 - the tags string, or nil."
7698 (save-excursion
7699 (org-back-to-heading t)
7700 (if (let (case-fold-search)
7701 (looking-at
7702 (if orgstruct-mode
7703 org-heading-regexp
7704 org-complex-heading-regexp)))
7705 (if orgstruct-mode
7706 (list (length (match-string 1))
7707 (org-reduced-level (length (match-string 1)))
7710 (match-string 2)
7711 nil)
7712 (list (length (match-string 1))
7713 (org-reduced-level (length (match-string 1)))
7714 (org-match-string-no-properties 2)
7715 (and (match-end 3) (aref (match-string 3) 2))
7716 (org-match-string-no-properties 4)
7717 (org-match-string-no-properties 5))))))
7719 (defun org-get-entry ()
7720 "Get the entry text, after heading, entire subtree."
7721 (save-excursion
7722 (org-back-to-heading t)
7723 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7725 (defun org-insert-heading-after-current ()
7726 "Insert a new heading with same level as current, after current subtree."
7727 (interactive)
7728 (org-back-to-heading)
7729 (org-insert-heading)
7730 (org-move-subtree-down)
7731 (end-of-line 1))
7733 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7734 "Insert heading with `org-insert-heading-respect-content' set to t."
7735 (interactive "P")
7736 (let ((org-insert-heading-respect-content t))
7737 (org-insert-heading arg invisible-ok)))
7739 (defun org-insert-todo-heading-respect-content (&optional force-state)
7740 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7741 (interactive "P")
7742 (let ((org-insert-heading-respect-content t))
7743 (org-insert-todo-heading force-state t)))
7745 (defun org-insert-todo-heading (arg &optional force-heading)
7746 "Insert a new heading with the same level and TODO state as current heading.
7747 If the heading has no TODO state, or if the state is DONE, use the first
7748 state (TODO by default). Also one prefix arg, force first state. With two
7749 prefix args, force inserting at the end of the parent subtree."
7750 (interactive "P")
7751 (when (or force-heading (not (org-insert-item 'checkbox)))
7752 (org-insert-heading (or (and (equal arg '(16)) '(16))
7753 force-heading))
7754 (save-excursion
7755 (org-back-to-heading)
7756 (outline-previous-heading)
7757 (looking-at org-todo-line-regexp))
7758 (let*
7759 ((new-mark-x
7760 (if (or arg
7761 (not (match-beginning 2))
7762 (member (match-string 2) org-done-keywords))
7763 (car org-todo-keywords-1)
7764 (match-string 2)))
7765 (new-mark
7767 (run-hook-with-args-until-success
7768 'org-todo-get-default-hook new-mark-x nil)
7769 new-mark-x)))
7770 (beginning-of-line 1)
7771 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7772 (if org-treat-insert-todo-heading-as-state-change
7773 (org-todo new-mark)
7774 (insert new-mark " "))))
7775 (when org-provide-todo-statistics
7776 (org-update-parent-todo-statistics))))
7778 (defun org-insert-subheading (arg)
7779 "Insert a new subheading and demote it.
7780 Works for outline headings and for plain lists alike."
7781 (interactive "P")
7782 (org-insert-heading arg)
7783 (cond
7784 ((org-at-heading-p) (org-do-demote))
7785 ((org-at-item-p) (org-indent-item))))
7787 (defun org-insert-todo-subheading (arg)
7788 "Insert a new subheading with TODO keyword or checkbox and demote it.
7789 Works for outline headings and for plain lists alike."
7790 (interactive "P")
7791 (org-insert-todo-heading arg)
7792 (cond
7793 ((org-at-heading-p) (org-do-demote))
7794 ((org-at-item-p) (org-indent-item))))
7796 ;;; Promotion and Demotion
7798 (defvar org-after-demote-entry-hook nil
7799 "Hook run after an entry has been demoted.
7800 The cursor will be at the beginning of the entry.
7801 When a subtree is being demoted, the hook will be called for each node.")
7803 (defvar org-after-promote-entry-hook nil
7804 "Hook run after an entry has been promoted.
7805 The cursor will be at the beginning of the entry.
7806 When a subtree is being promoted, the hook will be called for each node.")
7808 (defun org-promote-subtree ()
7809 "Promote the entire subtree.
7810 See also `org-promote'."
7811 (interactive)
7812 (save-excursion
7813 (org-with-limited-levels (org-map-tree 'org-promote)))
7814 (org-fix-position-after-promote))
7816 (defun org-demote-subtree ()
7817 "Demote the entire subtree. See `org-demote'.
7818 See also `org-promote'."
7819 (interactive)
7820 (save-excursion
7821 (org-with-limited-levels (org-map-tree 'org-demote)))
7822 (org-fix-position-after-promote))
7825 (defun org-do-promote ()
7826 "Promote the current heading higher up the tree.
7827 If the region is active in `transient-mark-mode', promote all headings
7828 in the region."
7829 (interactive)
7830 (save-excursion
7831 (if (org-region-active-p)
7832 (org-map-region 'org-promote (region-beginning) (region-end))
7833 (org-promote)))
7834 (org-fix-position-after-promote))
7836 (defun org-do-demote ()
7837 "Demote the current heading lower down the tree.
7838 If the region is active in `transient-mark-mode', demote all headings
7839 in the region."
7840 (interactive)
7841 (save-excursion
7842 (if (org-region-active-p)
7843 (org-map-region 'org-demote (region-beginning) (region-end))
7844 (org-demote)))
7845 (org-fix-position-after-promote))
7847 (defun org-fix-position-after-promote ()
7848 "Make sure that after pro/demotion cursor position is right."
7849 (let ((pos (point)))
7850 (when (save-excursion
7851 (beginning-of-line 1)
7852 (looking-at org-todo-line-regexp)
7853 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7854 (cond ((eobp) (insert " "))
7855 ((eolp) (insert " "))
7856 ((equal (char-after) ?\ ) (forward-char 1))))))
7858 (defun org-current-level ()
7859 "Return the level of the current entry, or nil if before the first headline.
7860 The level is the number of stars at the beginning of the headline."
7861 (save-excursion
7862 (org-with-limited-levels
7863 (if (ignore-errors (org-back-to-heading t))
7864 (funcall outline-level)))))
7866 (defun org-get-previous-line-level ()
7867 "Return the outline depth of the last headline before the current line.
7868 Returns 0 for the first headline in the buffer, and nil if before the
7869 first headline."
7870 (let ((current-level (org-current-level))
7871 (prev-level (when (> (line-number-at-pos) 1)
7872 (save-excursion
7873 (beginning-of-line 0)
7874 (org-current-level)))))
7875 (cond ((null current-level) nil) ; Before first headline
7876 ((null prev-level) 0) ; At first headline
7877 (prev-level))))
7879 (defun org-reduced-level (l)
7880 "Compute the effective level of a heading.
7881 This takes into account the setting of `org-odd-levels-only'."
7882 (cond
7883 ((zerop l) 0)
7884 (org-odd-levels-only (1+ (floor (/ l 2))))
7885 (t l)))
7887 (defun org-level-increment ()
7888 "Return the number of stars that will be added or removed at a
7889 time to headlines when structure editing, based on the value of
7890 `org-odd-levels-only'."
7891 (if org-odd-levels-only 2 1))
7893 (defun org-get-valid-level (level &optional change)
7894 "Rectify a level change under the influence of `org-odd-levels-only'
7895 LEVEL is a current level, CHANGE is by how much the level should be
7896 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7897 even level numbers will become the next higher odd number."
7898 (if org-odd-levels-only
7899 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7900 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7901 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7902 (max 1 (+ level (or change 0)))))
7904 (if (boundp 'define-obsolete-function-alias)
7905 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7906 (define-obsolete-function-alias 'org-get-legal-level
7907 'org-get-valid-level)
7908 (define-obsolete-function-alias 'org-get-legal-level
7909 'org-get-valid-level "23.1")))
7911 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7912 ;; ̀org-with-limited-levels'
7913 (defun org-promote ()
7914 "Promote the current heading higher up the tree.
7915 If the region is active in `transient-mark-mode', promote all headings
7916 in the region."
7917 (org-back-to-heading t)
7918 (let* ((level (save-match-data (funcall outline-level)))
7919 (after-change-functions (remove 'flyspell-after-change-function
7920 after-change-functions))
7921 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7922 (diff (abs (- level (length up-head) -1))))
7923 (cond ((and (= level 1) org-called-with-limited-levels
7924 org-allow-promoting-top-level-subtree)
7925 (replace-match "# " nil t))
7926 ((= level 1)
7927 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7928 (t (replace-match up-head nil t)))
7929 ;; Fixup tag positioning
7930 (unless (= level 1)
7931 (and org-auto-align-tags (org-set-tags nil t))
7932 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7933 (run-hooks 'org-after-promote-entry-hook)))
7935 (defun org-demote ()
7936 "Demote the current heading lower down the tree.
7937 If the region is active in `transient-mark-mode', demote all headings
7938 in the region."
7939 (org-back-to-heading t)
7940 (let* ((level (save-match-data (funcall outline-level)))
7941 (after-change-functions (remove 'flyspell-after-change-function
7942 after-change-functions))
7943 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7944 (diff (abs (- level (length down-head) -1))))
7945 (replace-match down-head nil t)
7946 ;; Fixup tag positioning
7947 (and org-auto-align-tags (org-set-tags nil t))
7948 (if org-adapt-indentation (org-fixup-indentation diff))
7949 (run-hooks 'org-after-demote-entry-hook)))
7951 (defun org-cycle-level ()
7952 "Cycle the level of an empty headline through possible states.
7953 This goes first to child, then to parent, level, then up the hierarchy.
7954 After top level, it switches back to sibling level."
7955 (interactive)
7956 (let ((org-adapt-indentation nil))
7957 (when (org-point-at-end-of-empty-headline)
7958 (setq this-command 'org-cycle-level) ; Only needed for caching
7959 (let ((cur-level (org-current-level))
7960 (prev-level (org-get-previous-line-level)))
7961 (cond
7962 ;; If first headline in file, promote to top-level.
7963 ((= prev-level 0)
7964 (loop repeat (/ (- cur-level 1) (org-level-increment))
7965 do (org-do-promote)))
7966 ;; If same level as prev, demote one.
7967 ((= prev-level cur-level)
7968 (org-do-demote))
7969 ;; If parent is top-level, promote to top level if not already.
7970 ((= prev-level 1)
7971 (loop repeat (/ (- cur-level 1) (org-level-increment))
7972 do (org-do-promote)))
7973 ;; If top-level, return to prev-level.
7974 ((= cur-level 1)
7975 (loop repeat (/ (- prev-level 1) (org-level-increment))
7976 do (org-do-demote)))
7977 ;; If less than prev-level, promote one.
7978 ((< cur-level prev-level)
7979 (org-do-promote))
7980 ;; If deeper than prev-level, promote until higher than
7981 ;; prev-level.
7982 ((> cur-level prev-level)
7983 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7984 do (org-do-promote))))
7985 t))))
7987 (defun org-map-tree (fun)
7988 "Call FUN for every heading underneath the current one."
7989 (org-back-to-heading)
7990 (let ((level (funcall outline-level)))
7991 (save-excursion
7992 (funcall fun)
7993 (while (and (progn
7994 (outline-next-heading)
7995 (> (funcall outline-level) level))
7996 (not (eobp)))
7997 (funcall fun)))))
7999 (defun org-map-region (fun beg end)
8000 "Call FUN for every heading between BEG and END."
8001 (let ((org-ignore-region t))
8002 (save-excursion
8003 (setq end (copy-marker end))
8004 (goto-char beg)
8005 (if (and (re-search-forward org-outline-regexp-bol nil t)
8006 (< (point) end))
8007 (funcall fun))
8008 (while (and (progn
8009 (outline-next-heading)
8010 (< (point) end))
8011 (not (eobp)))
8012 (funcall fun)))))
8014 (defvar org-property-end-re) ; silence byte-compiler
8015 (defun org-fixup-indentation (diff)
8016 "Change the indentation in the current entry by DIFF.
8017 However, if any line in the current entry has no indentation, or if it
8018 would end up with no indentation after the change, nothing at all is done."
8019 (save-excursion
8020 (let ((end (save-excursion (outline-next-heading)
8021 (point-marker)))
8022 (prohibit (if (> diff 0)
8023 "^\\S-"
8024 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8025 col)
8026 (unless (save-excursion (end-of-line 1)
8027 (re-search-forward prohibit end t))
8028 (while (and (< (point) end)
8029 (re-search-forward "^[ \t]+" end t))
8030 (goto-char (match-end 0))
8031 (setq col (current-column))
8032 (if (< diff 0) (replace-match ""))
8033 (org-indent-to-column (+ diff col))))
8034 (move-marker end nil))))
8036 (defun org-convert-to-odd-levels ()
8037 "Convert an org-mode file with all levels allowed to one with odd levels.
8038 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8039 level 5 etc."
8040 (interactive)
8041 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8042 (let ((outline-level 'org-outline-level)
8043 (org-odd-levels-only nil) n)
8044 (save-excursion
8045 (goto-char (point-min))
8046 (while (re-search-forward "^\\*\\*+ " nil t)
8047 (setq n (- (length (match-string 0)) 2))
8048 (while (>= (setq n (1- n)) 0)
8049 (org-demote))
8050 (end-of-line 1))))))
8052 (defun org-convert-to-oddeven-levels ()
8053 "Convert an org-mode file with only odd levels to one with odd/even levels.
8054 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8055 file contains a section with an even level, conversion would
8056 destroy the structure of the file. An error is signaled in this
8057 case."
8058 (interactive)
8059 (goto-char (point-min))
8060 ;; First check if there are no even levels
8061 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8062 (org-show-context t)
8063 (error "Not all levels are odd in this file. Conversion not possible"))
8064 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8065 (let ((outline-regexp org-outline-regexp)
8066 (outline-level 'org-outline-level)
8067 (org-odd-levels-only nil) n)
8068 (save-excursion
8069 (goto-char (point-min))
8070 (while (re-search-forward "^\\*\\*+ " nil t)
8071 (setq n (/ (1- (length (match-string 0))) 2))
8072 (while (>= (setq n (1- n)) 0)
8073 (org-promote))
8074 (end-of-line 1))))))
8076 (defun org-tr-level (n)
8077 "Make N odd if required."
8078 (if org-odd-levels-only (1+ (/ n 2)) n))
8080 ;;; Vertical tree motion, cutting and pasting of subtrees
8082 (defun org-move-subtree-up (&optional arg)
8083 "Move the current subtree up past ARG headlines of the same level."
8084 (interactive "p")
8085 (org-move-subtree-down (- (prefix-numeric-value arg))))
8087 (defun org-move-subtree-down (&optional arg)
8088 "Move the current subtree down past ARG headlines of the same level."
8089 (interactive "p")
8090 (setq arg (prefix-numeric-value arg))
8091 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8092 'org-get-last-sibling))
8093 (ins-point (make-marker))
8094 (cnt (abs arg))
8095 (col (current-column))
8096 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8097 ;; Select the tree
8098 (org-back-to-heading)
8099 (setq beg0 (point))
8100 (save-excursion
8101 (setq ne-beg (org-back-over-empty-lines))
8102 (setq beg (point)))
8103 (save-match-data
8104 (save-excursion (outline-end-of-heading)
8105 (setq folded (outline-invisible-p)))
8106 (outline-end-of-subtree))
8107 (outline-next-heading)
8108 (setq ne-end (org-back-over-empty-lines))
8109 (setq end (point))
8110 (goto-char beg0)
8111 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8112 ;; include less whitespace
8113 (save-excursion
8114 (goto-char beg)
8115 (forward-line (- ne-beg ne-end))
8116 (setq beg (point))))
8117 ;; Find insertion point, with error handling
8118 (while (> cnt 0)
8119 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8120 (progn (goto-char beg0)
8121 (user-error "Cannot move past superior level or buffer limit")))
8122 (setq cnt (1- cnt)))
8123 (if (> arg 0)
8124 ;; Moving forward - still need to move over subtree
8125 (progn (org-end-of-subtree t t)
8126 (save-excursion
8127 (org-back-over-empty-lines)
8128 (or (bolp) (newline)))))
8129 (setq ne-ins (org-back-over-empty-lines))
8130 (move-marker ins-point (point))
8131 (setq txt (buffer-substring beg end))
8132 (org-save-markers-in-region beg end)
8133 (delete-region beg end)
8134 (org-remove-empty-overlays-at beg)
8135 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8136 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8137 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8138 (let ((bbb (point)))
8139 (insert-before-markers txt)
8140 (org-reinstall-markers-in-region bbb)
8141 (move-marker ins-point bbb))
8142 (or (bolp) (insert "\n"))
8143 (setq ins-end (point))
8144 (goto-char ins-point)
8145 (org-skip-whitespace)
8146 (when (and (< arg 0)
8147 (org-first-sibling-p)
8148 (> ne-ins ne-beg))
8149 ;; Move whitespace back to beginning
8150 (save-excursion
8151 (goto-char ins-end)
8152 (let ((kill-whole-line t))
8153 (kill-line (- ne-ins ne-beg)) (point)))
8154 (insert (make-string (- ne-ins ne-beg) ?\n)))
8155 (move-marker ins-point nil)
8156 (if folded
8157 (hide-subtree)
8158 (org-show-entry)
8159 (show-children)
8160 (org-cycle-hide-drawers 'children))
8161 (org-clean-visibility-after-subtree-move)
8162 ;; move back to the initial column we were at
8163 (move-to-column col)))
8165 (defvar org-subtree-clip ""
8166 "Clipboard for cut and paste of subtrees.
8167 This is actually only a copy of the kill, because we use the normal kill
8168 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8170 (defvar org-subtree-clip-folded nil
8171 "Was the last copied subtree folded?
8172 This is used to fold the tree back after pasting.")
8174 (defun org-cut-subtree (&optional n)
8175 "Cut the current subtree into the clipboard.
8176 With prefix arg N, cut this many sequential subtrees.
8177 This is a short-hand for marking the subtree and then cutting it."
8178 (interactive "p")
8179 (org-copy-subtree n 'cut))
8181 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8182 "Cut the current subtree into the clipboard.
8183 With prefix arg N, cut this many sequential subtrees.
8184 This is a short-hand for marking the subtree and then copying it.
8185 If CUT is non-nil, actually cut the subtree.
8186 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8187 of some markers in the region, even if CUT is non-nil. This is
8188 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8189 (interactive "p")
8190 (let (beg end folded (beg0 (point)))
8191 (if (org-called-interactively-p 'any)
8192 (org-back-to-heading nil) ; take what looks like a subtree
8193 (org-back-to-heading t)) ; take what is really there
8194 (setq beg (point))
8195 (skip-chars-forward " \t\r\n")
8196 (save-match-data
8197 (if nosubtrees
8198 (outline-next-heading)
8199 (save-excursion (outline-end-of-heading)
8200 (setq folded (outline-invisible-p)))
8201 (condition-case nil
8202 (org-forward-heading-same-level (1- n) t)
8203 (error nil))
8204 (org-end-of-subtree t t)))
8205 (setq end (point))
8206 (goto-char beg0)
8207 (when (> end beg)
8208 (setq org-subtree-clip-folded folded)
8209 (when (or cut force-store-markers)
8210 (org-save-markers-in-region beg end))
8211 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8212 (setq org-subtree-clip (current-kill 0))
8213 (message "%s: Subtree(s) with %d characters"
8214 (if cut "Cut" "Copied")
8215 (length org-subtree-clip)))))
8217 (defun org-paste-subtree (&optional level tree for-yank)
8218 "Paste the clipboard as a subtree, with modification of headline level.
8219 The entire subtree is promoted or demoted in order to match a new headline
8220 level.
8222 If the cursor is at the beginning of a headline, the same level as
8223 that headline is used to paste the tree.
8225 If not, the new level is derived from the *visible* headings
8226 before and after the insertion point, and taken to be the inferior headline
8227 level of the two. So if the previous visible heading is level 3 and the
8228 next is level 4 (or vice versa), level 4 will be used for insertion.
8229 This makes sure that the subtree remains an independent subtree and does
8230 not swallow low level entries.
8232 You can also force a different level, either by using a numeric prefix
8233 argument, or by inserting the heading marker by hand. For example, if the
8234 cursor is after \"*****\", then the tree will be shifted to level 5.
8236 If optional TREE is given, use this text instead of the kill ring.
8238 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8239 move back over whitespace before inserting, and move point to the end of
8240 the inserted text when done."
8241 (interactive "P")
8242 (setq tree (or tree (and kill-ring (current-kill 0))))
8243 (unless (org-kill-is-subtree-p tree)
8244 (user-error "%s"
8245 (substitute-command-keys
8246 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8247 (org-with-limited-levels
8248 (let* ((visp (not (outline-invisible-p)))
8249 (txt tree)
8250 (^re_ "\\(\\*+\\)[ \t]*")
8251 (old-level (if (string-match org-outline-regexp-bol txt)
8252 (- (match-end 0) (match-beginning 0) 1)
8253 -1))
8254 (force-level (cond (level (prefix-numeric-value level))
8255 ((and (looking-at "[ \t]*$")
8256 (string-match
8257 "^\\*+$" (buffer-substring
8258 (point-at-bol) (point))))
8259 (- (match-end 1) (match-beginning 1)))
8260 ((and (bolp)
8261 (looking-at org-outline-regexp))
8262 (- (match-end 0) (point) 1))))
8263 (previous-level (save-excursion
8264 (condition-case nil
8265 (progn
8266 (outline-previous-visible-heading 1)
8267 (if (looking-at ^re_)
8268 (- (match-end 0) (match-beginning 0) 1)
8270 (error 1))))
8271 (next-level (save-excursion
8272 (condition-case nil
8273 (progn
8274 (or (looking-at org-outline-regexp)
8275 (outline-next-visible-heading 1))
8276 (if (looking-at ^re_)
8277 (- (match-end 0) (match-beginning 0) 1)
8279 (error 1))))
8280 (new-level (or force-level (max previous-level next-level)))
8281 (shift (if (or (= old-level -1)
8282 (= new-level -1)
8283 (= old-level new-level))
8285 (- new-level old-level)))
8286 (delta (if (> shift 0) -1 1))
8287 (func (if (> shift 0) 'org-demote 'org-promote))
8288 (org-odd-levels-only nil)
8289 beg end newend)
8290 ;; Remove the forced level indicator
8291 (if force-level
8292 (delete-region (point-at-bol) (point)))
8293 ;; Paste
8294 (beginning-of-line (if (bolp) 1 2))
8295 (setq beg (point))
8296 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8297 (insert-before-markers txt)
8298 (unless (string-match "\n\\'" txt) (insert "\n"))
8299 (setq newend (point))
8300 (org-reinstall-markers-in-region beg)
8301 (setq end (point))
8302 (goto-char beg)
8303 (skip-chars-forward " \t\n\r")
8304 (setq beg (point))
8305 (if (and (outline-invisible-p) visp)
8306 (save-excursion (outline-show-heading)))
8307 ;; Shift if necessary
8308 (unless (= shift 0)
8309 (save-restriction
8310 (narrow-to-region beg end)
8311 (while (not (= shift 0))
8312 (org-map-region func (point-min) (point-max))
8313 (setq shift (+ delta shift)))
8314 (goto-char (point-min))
8315 (setq newend (point-max))))
8316 (when (or (org-called-interactively-p 'interactive) for-yank)
8317 (message "Clipboard pasted as level %d subtree" new-level))
8318 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8319 kill-ring
8320 (eq org-subtree-clip (current-kill 0))
8321 org-subtree-clip-folded)
8322 ;; The tree was folded before it was killed/copied
8323 (hide-subtree))
8324 (and for-yank (goto-char newend)))))
8326 (defun org-kill-is-subtree-p (&optional txt)
8327 "Check if the current kill is an outline subtree, or a set of trees.
8328 Returns nil if kill does not start with a headline, or if the first
8329 headline level is not the largest headline level in the tree.
8330 So this will actually accept several entries of equal levels as well,
8331 which is OK for `org-paste-subtree'.
8332 If optional TXT is given, check this string instead of the current kill."
8333 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8334 (re (org-get-limited-outline-regexp))
8335 (^re (concat "^" re))
8336 (start-level (and kill
8337 (string-match
8338 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8339 kill)
8340 (- (match-end 2) (match-beginning 2) 1)))
8341 (start (1+ (or (match-beginning 2) -1))))
8342 (if (not start-level)
8343 (progn
8344 nil) ;; does not even start with a heading
8345 (catch 'exit
8346 (while (setq start (string-match ^re kill (1+ start)))
8347 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8348 (throw 'exit nil)))
8349 t))))
8351 (defvar org-markers-to-move nil
8352 "Markers that should be moved with a cut-and-paste operation.
8353 Those markers are stored together with their positions relative to
8354 the start of the region.")
8356 (defun org-save-markers-in-region (beg end)
8357 "Check markers in region.
8358 If these markers are between BEG and END, record their position relative
8359 to BEG, so that after moving the block of text, we can put the markers back
8360 into place.
8361 This function gets called just before an entry or tree gets cut from the
8362 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8363 called immediately, to move the markers with the entries."
8364 (setq org-markers-to-move nil)
8365 (when (featurep 'org-clock)
8366 (org-clock-save-markers-for-cut-and-paste beg end))
8367 (when (featurep 'org-agenda)
8368 (org-agenda-save-markers-for-cut-and-paste beg end)))
8370 (defun org-check-and-save-marker (marker beg end)
8371 "Check if MARKER is between BEG and END.
8372 If yes, remember the marker and the distance to BEG."
8373 (when (and (marker-buffer marker)
8374 (equal (marker-buffer marker) (current-buffer)))
8375 (if (and (>= marker beg) (< marker end))
8376 (push (cons marker (- marker beg)) org-markers-to-move))))
8378 (defun org-reinstall-markers-in-region (beg)
8379 "Move all remembered markers to their position relative to BEG."
8380 (mapc (lambda (x)
8381 (move-marker (car x) (+ beg (cdr x))))
8382 org-markers-to-move)
8383 (setq org-markers-to-move nil))
8385 (defun org-narrow-to-subtree ()
8386 "Narrow buffer to the current subtree."
8387 (interactive)
8388 (save-excursion
8389 (save-match-data
8390 (org-with-limited-levels
8391 (narrow-to-region
8392 (progn (org-back-to-heading t) (point))
8393 (progn (org-end-of-subtree t t)
8394 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8395 (point)))))))
8397 (defun org-narrow-to-block ()
8398 "Narrow buffer to the current block."
8399 (interactive)
8400 (let* ((case-fold-search t)
8401 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8402 "^[ \t]*#\\+end_.*")))
8403 (if blockp
8404 (narrow-to-region (car blockp) (cdr blockp))
8405 (user-error "Not in a block"))))
8407 (eval-when-compile
8408 (defvar org-property-drawer-re))
8410 (defvar org-property-start-re) ;; defined below
8411 (defun org-clone-subtree-with-time-shift (n &optional shift)
8412 "Clone the task (subtree) at point N times.
8413 The clones will be inserted as siblings.
8415 In interactive use, the user will be prompted for the number of
8416 clones to be produced. If the entry has a timestamp, the user
8417 will also be prompted for a time shift, which may be a repeater
8418 as used in time stamps, for example `+3d'. To disable this,
8419 you can call the function with a universal prefix argument.
8421 When a valid repeater is given and the entry contains any time
8422 stamps, the clones will become a sequence in time, with time
8423 stamps in the subtree shifted for each clone produced. If SHIFT
8424 is nil or the empty string, time stamps will be left alone. The
8425 ID property of the original subtree is removed.
8427 If the original subtree did contain time stamps with a repeater,
8428 the following will happen:
8429 - the repeater will be removed in each clone
8430 - an additional clone will be produced, with the current, unshifted
8431 date(s) in the entry.
8432 - the original entry will be placed *after* all the clones, with
8433 repeater intact.
8434 - the start days in the repeater in the original entry will be shifted
8435 to past the last clone.
8436 In this way you can spell out a number of instances of a repeating task,
8437 and still retain the repeater to cover future instances of the task."
8438 (interactive "nNumber of clones to produce: ")
8439 (let ((shift
8440 (or shift
8441 (if (and (not (equal current-prefix-arg '(4)))
8442 (save-excursion
8443 (re-search-forward org-ts-regexp-both
8444 (save-excursion
8445 (org-end-of-subtree t)
8446 (point)) t)))
8447 (read-from-minibuffer
8448 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8449 ""))) ;; No time shift
8450 (n-no-remove -1)
8451 (drawer-re org-drawer-regexp)
8452 beg end template task idprop
8453 shift-n shift-what doshift nmin nmax)
8454 (if (not (and (integerp n) (> n 0)))
8455 (error "Invalid number of replications %s" n))
8456 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8457 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8458 shift)))
8459 (error "Invalid shift specification %s" shift))
8460 (when doshift
8461 (setq shift-n (string-to-number (match-string 1 shift))
8462 shift-what (cdr (assoc (match-string 2 shift)
8463 '(("d" . day) ("w" . week)
8464 ("m" . month) ("y" . year))))))
8465 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8466 (setq nmin 1 nmax n)
8467 (org-back-to-heading t)
8468 (setq beg (point))
8469 (setq idprop (org-entry-get nil "ID"))
8470 (org-end-of-subtree t t)
8471 (or (bolp) (insert "\n"))
8472 (setq end (point))
8473 (setq template (buffer-substring beg end))
8474 (when (and doshift
8475 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8476 (delete-region beg end)
8477 (setq end beg)
8478 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8479 (goto-char end)
8480 (loop for n from nmin to nmax do
8481 ;; prepare clone
8482 (with-temp-buffer
8483 (insert template)
8484 (org-mode)
8485 (goto-char (point-min))
8486 (org-show-subtree)
8487 (and idprop (if org-clone-delete-id
8488 (org-entry-delete nil "ID")
8489 (org-id-get-create t)))
8490 (unless (= n 0)
8491 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8492 (kill-whole-line))
8493 (goto-char (point-min))
8494 (while (re-search-forward drawer-re nil t)
8495 (mapc (lambda (d)
8496 (org-remove-empty-drawer-at d (point))) org-drawers)))
8497 (goto-char (point-min))
8498 (when doshift
8499 (while (re-search-forward org-ts-regexp-both nil t)
8500 (org-timestamp-change (* n shift-n) shift-what))
8501 (unless (= n n-no-remove)
8502 (goto-char (point-min))
8503 (while (re-search-forward org-ts-regexp nil t)
8504 (save-excursion
8505 (goto-char (match-beginning 0))
8506 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8507 (delete-region (match-beginning 1) (match-end 1)))))))
8508 (setq task (buffer-string)))
8509 (insert task))
8510 (goto-char beg)))
8512 ;;; Outline Sorting
8514 (defun org-sort (with-case)
8515 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8516 Optional argument WITH-CASE means sort case-sensitively."
8517 (interactive "P")
8518 (cond
8519 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8520 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8522 (org-call-with-arg 'org-sort-entries with-case))))
8524 (defun org-sort-remove-invisible (s)
8525 "Remove invisible links from string S."
8526 (remove-text-properties 0 (length s) org-rm-props s)
8527 (while (string-match org-bracket-link-regexp s)
8528 (setq s (replace-match (if (match-end 2)
8529 (match-string 3 s)
8530 (match-string 1 s)) t t s)))
8531 (let ((st (format " %s " s)))
8532 (while (string-match org-emph-re st)
8533 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8534 (setq s (substring st 1 -1)))
8537 (defvar org-priority-regexp) ; defined later in the file
8539 (defvar org-after-sorting-entries-or-items-hook nil
8540 "Hook that is run after a bunch of entries or items have been sorted.
8541 When children are sorted, the cursor is in the parent line when this
8542 hook gets called. When a region or a plain list is sorted, the cursor
8543 will be in the first entry of the sorted region/list.")
8545 (defun org-sort-entries
8546 (&optional with-case sorting-type getkey-func compare-func property)
8547 "Sort entries on a certain level of an outline tree.
8548 If there is an active region, the entries in the region are sorted.
8549 Else, if the cursor is before the first entry, sort the top-level items.
8550 Else, the children of the entry at point are sorted.
8552 Sorting can be alphabetically, numerically, by date/time as given by
8553 a time stamp, by a property, by priority order, or by a custom function.
8555 The command prompts for the sorting type unless it has been given to the
8556 function through the SORTING-TYPE argument, which needs to be a character,
8557 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8558 precise meaning of each character:
8560 n Numerically, by converting the beginning of the entry/item to a number.
8561 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8562 o By order of TODO keywords.
8563 t By date/time, either the first active time stamp in the entry, or, if
8564 none exist, by the first inactive one.
8565 s By the scheduled date/time.
8566 d By deadline date/time.
8567 c By creation time, which is assumed to be the first inactive time stamp
8568 at the beginning of a line.
8569 p By priority according to the cookie.
8570 r By the value of a property.
8572 Capital letters will reverse the sort order.
8574 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8575 called with point at the beginning of the record. It must return either
8576 a string or a number that should serve as the sorting key for that record.
8578 Comparing entries ignores case by default. However, with an optional argument
8579 WITH-CASE, the sorting considers case as well.
8581 Sorting is done against the visible part of the headlines, it ignores hidden
8582 links."
8583 (interactive "P")
8584 (let ((case-func (if with-case 'identity 'downcase))
8585 (cmstr
8586 ;; The clock marker is lost when using `sort-subr', let's
8587 ;; store the clocking string.
8588 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8589 (save-excursion
8590 (goto-char org-clock-marker)
8591 (looking-back "^.*") (match-string-no-properties 0))))
8592 start beg end stars re re2
8593 txt what tmp)
8594 ;; Find beginning and end of region to sort
8595 (cond
8596 ((org-region-active-p)
8597 ;; we will sort the region
8598 (setq end (region-end)
8599 what "region")
8600 (goto-char (region-beginning))
8601 (if (not (org-at-heading-p)) (outline-next-heading))
8602 (setq start (point)))
8603 ((or (org-at-heading-p)
8604 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8605 ;; we will sort the children of the current headline
8606 (org-back-to-heading)
8607 (setq start (point)
8608 end (progn (org-end-of-subtree t t)
8609 (or (bolp) (insert "\n"))
8610 (org-back-over-empty-lines)
8611 (point))
8612 what "children")
8613 (goto-char start)
8614 (show-subtree)
8615 (outline-next-heading))
8617 ;; we will sort the top-level entries in this file
8618 (goto-char (point-min))
8619 (or (org-at-heading-p) (outline-next-heading))
8620 (setq start (point))
8621 (goto-char (point-max))
8622 (beginning-of-line 1)
8623 (when (looking-at ".*?\\S-")
8624 ;; File ends in a non-white line
8625 (end-of-line 1)
8626 (insert "\n"))
8627 (setq end (point-max))
8628 (setq what "top-level")
8629 (goto-char start)
8630 (show-all)))
8632 (setq beg (point))
8633 (if (>= beg end) (user-error "Nothing to sort"))
8635 (looking-at "\\(\\*+\\)")
8636 (setq stars (match-string 1)
8637 re (concat "^" (regexp-quote stars) " +")
8638 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8639 txt (buffer-substring beg end))
8640 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8641 (if (and (not (equal stars "*")) (string-match re2 txt))
8642 (user-error "Region to sort contains a level above the first entry"))
8644 (unless sorting-type
8645 (message
8646 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8647 [t]ime [s]cheduled [d]eadline [c]reated
8648 A/N/P/R/O/F/T/S/D/C means reversed:"
8649 what)
8650 (setq sorting-type (read-char-exclusive))
8652 (unless getkey-func
8653 (and (= (downcase sorting-type) ?f)
8654 (setq getkey-func
8655 (org-icompleting-read "Sort using function: "
8656 obarray 'fboundp t nil nil))
8657 (setq getkey-func (intern getkey-func))))
8659 (and (= (downcase sorting-type) ?r)
8660 (not property)
8661 (setq property
8662 (org-icompleting-read "Property: "
8663 (mapcar 'list (org-buffer-property-keys t))
8664 nil t))))
8666 (message "Sorting entries...")
8668 (save-restriction
8669 (narrow-to-region start end)
8670 (let ((dcst (downcase sorting-type))
8671 (case-fold-search nil)
8672 (now (current-time)))
8673 (sort-subr
8674 (/= dcst sorting-type)
8675 ;; This function moves to the beginning character of the "record" to
8676 ;; be sorted.
8677 (lambda nil
8678 (if (re-search-forward re nil t)
8679 (goto-char (match-beginning 0))
8680 (goto-char (point-max))))
8681 ;; This function moves to the last character of the "record" being
8682 ;; sorted.
8683 (lambda nil
8684 (save-match-data
8685 (condition-case nil
8686 (outline-forward-same-level 1)
8687 (error
8688 (goto-char (point-max))))))
8689 ;; This function returns the value that gets sorted against.
8690 (lambda nil
8691 (cond
8692 ((= dcst ?n)
8693 (if (looking-at org-complex-heading-regexp)
8694 (string-to-number (org-sort-remove-invisible (match-string 4)))
8695 nil))
8696 ((= dcst ?a)
8697 (if (looking-at org-complex-heading-regexp)
8698 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8699 nil))
8700 ((= dcst ?t)
8701 (let ((end (save-excursion (outline-next-heading) (point))))
8702 (if (or (re-search-forward org-ts-regexp end t)
8703 (re-search-forward org-ts-regexp-both end t))
8704 (org-time-string-to-seconds (match-string 0))
8705 (org-float-time now))))
8706 ((= dcst ?c)
8707 (let ((end (save-excursion (outline-next-heading) (point))))
8708 (if (re-search-forward
8709 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8710 end t)
8711 (org-time-string-to-seconds (match-string 0))
8712 (org-float-time now))))
8713 ((= dcst ?s)
8714 (let ((end (save-excursion (outline-next-heading) (point))))
8715 (if (re-search-forward org-scheduled-time-regexp end t)
8716 (org-time-string-to-seconds (match-string 1))
8717 (org-float-time now))))
8718 ((= dcst ?d)
8719 (let ((end (save-excursion (outline-next-heading) (point))))
8720 (if (re-search-forward org-deadline-time-regexp end t)
8721 (org-time-string-to-seconds (match-string 1))
8722 (org-float-time now))))
8723 ((= dcst ?p)
8724 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8725 (string-to-char (match-string 2))
8726 org-default-priority))
8727 ((= dcst ?r)
8728 (or (org-entry-get nil property) ""))
8729 ((= dcst ?o)
8730 (if (looking-at org-complex-heading-regexp)
8731 (- 9999 (length (member (match-string 2)
8732 org-todo-keywords-1)))))
8733 ((= dcst ?f)
8734 (if getkey-func
8735 (progn
8736 (setq tmp (funcall getkey-func))
8737 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8738 tmp)
8739 (error "Invalid key function `%s'" getkey-func)))
8740 (t (error "Invalid sorting type `%c'" sorting-type))))
8742 (cond
8743 ((= dcst ?a) 'string<)
8744 ((= dcst ?f) compare-func)
8745 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8746 (run-hooks 'org-after-sorting-entries-or-items-hook)
8747 ;; Reset the clock marker if needed
8748 (when cmstr
8749 (save-excursion
8750 (goto-char start)
8751 (search-forward cmstr nil t)
8752 (move-marker org-clock-marker (point))))
8753 (message "Sorting entries...done")))
8755 (defun org-do-sort (table what &optional with-case sorting-type)
8756 "Sort TABLE of WHAT according to SORTING-TYPE.
8757 The user will be prompted for the SORTING-TYPE if the call to this
8758 function does not specify it. WHAT is only for the prompt, to indicate
8759 what is being sorted. The sorting key will be extracted from
8760 the car of the elements of the table.
8761 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8762 (unless sorting-type
8763 (message
8764 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8765 what)
8766 (setq sorting-type (read-char-exclusive)))
8767 (let ((dcst (downcase sorting-type))
8768 extractfun comparefun)
8769 ;; Define the appropriate functions
8770 (cond
8771 ((= dcst ?n)
8772 (setq extractfun 'string-to-number
8773 comparefun (if (= dcst sorting-type) '< '>)))
8774 ((= dcst ?a)
8775 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8776 (lambda(x) (downcase (org-sort-remove-invisible x))))
8777 comparefun (if (= dcst sorting-type)
8778 'string<
8779 (lambda (a b) (and (not (string< a b))
8780 (not (string= a b)))))))
8781 ((= dcst ?t)
8782 (setq extractfun
8783 (lambda (x)
8784 (if (or (string-match org-ts-regexp x)
8785 (string-match org-ts-regexp-both x))
8786 (org-float-time
8787 (org-time-string-to-time (match-string 0 x)))
8789 comparefun (if (= dcst sorting-type) '< '>)))
8790 (t (error "Invalid sorting type `%c'" sorting-type)))
8792 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8793 table)
8794 (lambda (a b) (funcall comparefun (car a) (car b))))))
8797 ;;; The orgstruct minor mode
8799 ;; Define a minor mode which can be used in other modes in order to
8800 ;; integrate the org-mode structure editing commands.
8802 ;; This is really a hack, because the org-mode structure commands use
8803 ;; keys which normally belong to the major mode. Here is how it
8804 ;; works: The minor mode defines all the keys necessary to operate the
8805 ;; structure commands, but wraps the commands into a function which
8806 ;; tests if the cursor is currently at a headline or a plain list
8807 ;; item. If that is the case, the structure command is used,
8808 ;; temporarily setting many Org-mode variables like regular
8809 ;; expressions for filling etc. However, when any of those keys is
8810 ;; used at a different location, function uses `key-binding' to look
8811 ;; up if the key has an associated command in another currently active
8812 ;; keymap (minor modes, major mode, global), and executes that
8813 ;; command. There might be problems if any of the keys is otherwise
8814 ;; used as a prefix key.
8816 (defcustom orgstruct-heading-prefix-regexp nil
8817 "Regexp that matches the custom prefix of Org headlines in
8818 orgstruct(++)-mode."
8819 :group 'org
8820 :version "24.4"
8821 :package-version '(Org . "8.0")
8822 :type 'string)
8823 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8825 (defcustom orgstruct-setup-hook nil
8826 "Hook run after orgstruct-mode-map is filled."
8827 :group 'org
8828 :version "24.4"
8829 :package-version '(Org . "8.0")
8830 :type 'hook)
8832 (defvar orgstruct-initialized nil)
8834 (defvar org-local-vars nil
8835 "List of local variables, for use by `orgstruct-mode'.")
8837 ;;;###autoload
8838 (define-minor-mode orgstruct-mode
8839 "Toggle the minor mode `orgstruct-mode'.
8840 This mode is for using Org-mode structure commands in other
8841 modes. The following keys behave as if Org-mode were active, if
8842 the cursor is on a headline, or on a plain list item (both as
8843 defined by Org-mode)."
8844 nil " OrgStruct" (make-sparse-keymap)
8845 (funcall (if orgstruct-mode
8846 'add-to-invisibility-spec
8847 'remove-from-invisibility-spec)
8848 '(outline . t))
8849 (when orgstruct-mode
8850 (org-load-modules-maybe)
8851 (unless orgstruct-initialized
8852 (orgstruct-setup)
8853 (setq orgstruct-initialized t))))
8855 ;;;###autoload
8856 (defun turn-on-orgstruct ()
8857 "Unconditionally turn on `orgstruct-mode'."
8858 (orgstruct-mode 1))
8860 (defvar org-fb-vars nil)
8861 (make-variable-buffer-local 'org-fb-vars)
8862 (defun orgstruct++-mode (&optional arg)
8863 "Toggle `orgstruct-mode', the enhanced version of it.
8864 In addition to setting orgstruct-mode, this also exports all
8865 indentation and autofilling variables from org-mode into the
8866 buffer. It will also recognize item context in multiline items."
8867 (interactive "P")
8868 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8869 (if (< arg 1)
8870 (progn (orgstruct-mode -1)
8871 (mapc (lambda(v)
8872 (org-set-local (car v)
8873 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8874 org-fb-vars))
8875 (orgstruct-mode 1)
8876 (setq org-fb-vars nil)
8877 (let (var val)
8878 (mapc
8879 (lambda (x)
8880 (when (string-match
8881 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8882 (symbol-name (car x)))
8883 (setq var (car x) val (nth 1 x))
8884 (push (list var `(quote ,(eval var))) org-fb-vars)
8885 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8886 org-local-vars)
8887 (org-set-local 'orgstruct-is-++ t))))
8889 (defvar orgstruct-is-++ nil
8890 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8891 (make-variable-buffer-local 'orgstruct-is-++)
8893 ;;;###autoload
8894 (defun turn-on-orgstruct++ ()
8895 "Unconditionally turn on `orgstruct++-mode'."
8896 (orgstruct++-mode 1))
8898 (defun orgstruct-error ()
8899 "Error when there is no default binding for a structure key."
8900 (interactive)
8901 (funcall (if (fboundp 'user-error)
8902 'user-error
8903 'error)
8904 "This key has no function outside structure elements"))
8906 (defun orgstruct-setup ()
8907 "Setup orgstruct keymap."
8908 (dolist (cell '((org-demote . t)
8909 (org-metaleft . t)
8910 (org-metaright . t)
8911 (org-promote . t)
8912 (org-shiftmetaleft . t)
8913 (org-shiftmetaright . t)
8914 org-backward-element
8915 org-backward-heading-same-level
8916 org-ctrl-c-ret
8917 org-ctrl-c-minus
8918 org-ctrl-c-star
8919 org-cycle
8920 org-forward-heading-same-level
8921 org-insert-heading
8922 org-insert-heading-respect-content
8923 org-kill-note-or-show-branches
8924 org-mark-subtree
8925 org-meta-return
8926 org-metadown
8927 org-metaup
8928 org-narrow-to-subtree
8929 org-promote-subtree
8930 org-reveal
8931 org-shiftdown
8932 org-shiftleft
8933 org-shiftmetadown
8934 org-shiftmetaup
8935 org-shiftright
8936 org-shifttab
8937 org-shifttab
8938 org-shiftup
8939 org-show-subtree
8940 org-sort
8941 org-up-element
8942 outline-demote
8943 outline-next-visible-heading
8944 outline-previous-visible-heading
8945 outline-promote
8946 outline-up-heading
8947 show-children))
8948 (let ((f (or (car-safe cell) cell))
8949 (disable-when-heading-prefix (cdr-safe cell)))
8950 (when (fboundp f)
8951 (dolist (binding (nconc (where-is-internal f org-mode-map)
8952 (where-is-internal f outline-mode-map)))
8953 ;; TODO use local-function-key-map
8954 (dolist (rep '(("<tab>" . "TAB")
8955 ("<return>" . "RET")
8956 ("<escape>" . "ESC")
8957 ("<delete>" . "DEL")))
8958 (setq binding (read-kbd-macro
8959 (let ((case-fold-search))
8960 (replace-regexp-in-string
8961 (regexp-quote (cdr rep))
8962 (car rep)
8963 (key-description binding))))))
8964 (let ((key (lookup-key orgstruct-mode-map binding)))
8965 (when (or (not key) (numberp key))
8966 (condition-case nil
8967 (org-defkey orgstruct-mode-map
8968 binding
8969 (orgstruct-make-binding f binding disable-when-heading-prefix))
8970 (error nil))))))))
8971 (run-hooks 'orgstruct-setup-hook))
8973 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
8974 "Create a function for binding in the structure minor mode.
8975 FUN is the command to call inside a table. KEY is the key that
8976 should be checked in for a command to execute outside of tables.
8977 Non-nil DISABLE-WHEN-HEADING-PREFIX means to disable the command
8978 if `orgstruct-heading-prefix-regexp' is non-nil."
8979 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8980 (let ((nname name)
8981 (i 0))
8982 (while (fboundp (intern nname))
8983 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8984 (setq name (intern nname)))
8985 (eval
8986 (let ((bindings '((org-heading-regexp
8987 (concat "^"
8988 orgstruct-heading-prefix-regexp
8989 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8990 (org-outline-regexp
8991 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8992 (org-outline-regexp-bol
8993 (concat "^" org-outline-regexp))
8994 (outline-regexp org-outline-regexp)
8995 (outline-heading-end-regexp "\n")
8996 (outline-level 'org-outline-level)
8997 (outline-heading-alist))))
8998 `(defun ,name (arg)
8999 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9000 "Outside of structure, run the binding of `"
9001 (key-description key) "'."
9002 (when disable-when-heading-prefix
9003 (concat
9004 "\nIf `orgstruct-heading-prefix-regexp' is non-nil, this command will always fall\n"
9005 "back to the default binding due to limitations of Org's implementation of\n"
9006 "`" (symbol-name fun) "'.")))
9007 (interactive "p")
9008 (let* ((disable
9009 ,(when disable-when-heading-prefix
9010 '(and orgstruct-heading-prefix-regexp
9011 (not (string= orgstruct-heading-prefix-regexp "")))))
9012 (fallback
9013 (or disable
9014 (not
9015 (let* ,bindings
9016 (org-context-p 'headline 'item
9017 ,(when (memq fun '(org-insert-heading))
9018 '(when orgstruct-is-++
9019 'item-body))))))))
9020 (if fallback
9021 (let* ((orgstruct-mode)
9022 (binding
9023 (loop with key = ,key
9024 for rep in
9025 '(nil
9026 ("<\\([^>]*\\)tab>" . "\\1TAB")
9027 ("<\\([^>]*\\)return>" . "\\1RET")
9028 ("<\\([^>]*\\)escape>" . "\\1ESC")
9029 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9031 (when rep
9032 (setq key (read-kbd-macro
9033 (let ((case-fold-search))
9034 (replace-regexp-in-string
9035 (car rep)
9036 (cdr rep)
9037 (key-description key))))))
9038 thereis (key-binding key))))
9039 (if (keymapp binding)
9040 (set-temporary-overlay-map binding)
9041 (let ((func (or binding
9042 (unless disable
9043 'orgstruct-error))))
9044 (when func
9045 (call-interactively func)))))
9046 (org-run-like-in-org-mode
9047 (lambda ()
9048 (interactive)
9049 (let* ,bindings
9050 (call-interactively ',fun)))))))))
9051 name))
9053 (defun org-contextualize-keys (alist contexts)
9054 "Return valid elements in ALIST depending on CONTEXTS.
9056 `org-agenda-custom-commands' or `org-capture-templates' are the
9057 values used for ALIST, and `org-agenda-custom-commands-contexts'
9058 or `org-capture-templates-contexts' are the associated contexts
9059 definitions."
9060 (let ((contexts
9061 ;; normalize contexts
9062 (mapcar
9063 (lambda(c) (cond ((listp (cadr c))
9064 (list (car c) (car c) (cadr c)))
9065 ((string= "" (cadr c))
9066 (list (car c) (car c) (caddr c)))
9067 (t c))) contexts))
9068 (a alist) c r s)
9069 ;; loop over all commands or templates
9070 (while (setq c (pop a))
9071 (let (vrules repl)
9072 (cond
9073 ((not (assoc (car c) contexts))
9074 (push c r))
9075 ((and (assoc (car c) contexts)
9076 (setq vrules (org-contextualize-validate-key
9077 (car c) contexts)))
9078 (mapc (lambda (vr)
9079 (when (not (equal (car vr) (cadr vr)))
9080 (setq repl vr))) vrules)
9081 (if (not repl) (push c r)
9082 (push (cadr repl) s)
9083 (push
9084 (cons (car c)
9085 (cdr (or (assoc (cadr repl) alist)
9086 (error "Undefined key `%s' as contextual replacement for `%s'"
9087 (cadr repl) (car c)))))
9088 r))))))
9089 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9090 (delq
9092 (delete-dups
9093 (mapcar (lambda (x)
9094 (let ((tpl (car x)))
9095 (when (not (delq
9097 (mapcar (lambda(y)
9098 (equal y tpl)) s))) x)))
9099 (reverse r))))))
9101 (defun org-contextualize-validate-key (key contexts)
9102 "Check CONTEXTS for agenda or capture KEY."
9103 (let (r rr res)
9104 (while (setq r (pop contexts))
9105 (mapc
9106 (lambda (rr)
9107 (when
9108 (and (equal key (car r))
9109 (if (functionp rr) (funcall rr)
9110 (or (and (eq (car rr) 'in-file)
9111 (buffer-file-name)
9112 (string-match (cdr rr) (buffer-file-name)))
9113 (and (eq (car rr) 'in-mode)
9114 (string-match (cdr rr) (symbol-name major-mode)))
9115 (and (eq (car rr) 'in-buffer)
9116 (string-match (cdr rr) (buffer-name)))
9117 (when (and (eq (car rr) 'not-in-file)
9118 (buffer-file-name))
9119 (not (string-match (cdr rr) (buffer-file-name))))
9120 (when (eq (car rr) 'not-in-mode)
9121 (not (string-match (cdr rr) (symbol-name major-mode))))
9122 (when (eq (car rr) 'not-in-buffer)
9123 (not (string-match (cdr rr) (buffer-name)))))))
9124 (push r res)))
9125 (car (last r))))
9126 (delete-dups (delq nil res))))
9128 (defun org-context-p (&rest contexts)
9129 "Check if local context is any of CONTEXTS.
9130 Possible values in the list of contexts are `table', `headline', and `item'."
9131 (let ((pos (point)))
9132 (goto-char (point-at-bol))
9133 (prog1 (or (and (memq 'table contexts)
9134 (looking-at "[ \t]*|"))
9135 (and (memq 'headline contexts)
9136 (looking-at org-outline-regexp))
9137 (and (memq 'item contexts)
9138 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9139 (and (memq 'item-body contexts)
9140 (org-in-item-p)))
9141 (goto-char pos))))
9143 (defun org-get-local-variables ()
9144 "Return a list of all local variables in an Org mode buffer."
9145 (let (varlist)
9146 (with-current-buffer (get-buffer-create "*Org tmp*")
9147 (erase-buffer)
9148 (org-mode)
9149 (setq varlist (buffer-local-variables)))
9150 (kill-buffer "*Org tmp*")
9151 (delq nil
9152 (mapcar
9153 (lambda (x)
9154 (setq x
9155 (if (symbolp x)
9156 (list x)
9157 (list (car x) (cdr x))))
9158 (if (and (not (get (car x) 'org-state))
9159 (string-match
9160 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9161 (symbol-name (car x))))
9162 x nil))
9163 varlist))))
9165 (defun org-clone-local-variables (from-buffer &optional regexp)
9166 "Clone local variables from FROM-BUFFER.
9167 Optional argument REGEXP selects variables to clone."
9168 (mapc
9169 (lambda (pair)
9170 (and (symbolp (car pair))
9171 (or (null regexp)
9172 (string-match regexp (symbol-name (car pair))))
9173 (set (make-local-variable (car pair))
9174 (cdr pair))))
9175 (buffer-local-variables from-buffer)))
9177 ;;;###autoload
9178 (defun org-run-like-in-org-mode (cmd)
9179 "Run a command, pretending that the current buffer is in Org-mode.
9180 This will temporarily bind local variables that are typically bound in
9181 Org-mode to the values they have in Org-mode, and then interactively
9182 call CMD."
9183 (org-load-modules-maybe)
9184 (unless org-local-vars
9185 (setq org-local-vars (org-get-local-variables)))
9186 (let (binds)
9187 (dolist (var org-local-vars)
9188 (when (or (not (boundp (car var)))
9189 (eq (symbol-value (car var))
9190 (default-value (car var))))
9191 (push (list (car var) `(quote ,(cadr var))) binds)))
9192 (eval `(let ,binds
9193 (call-interactively (quote ,cmd))))))
9195 ;;;; Archiving
9197 (defun org-get-category (&optional pos force-refresh)
9198 "Get the category applying to position POS."
9199 (save-match-data
9200 (if force-refresh (org-refresh-category-properties))
9201 (let ((pos (or pos (point))))
9202 (or (get-text-property pos 'org-category)
9203 (progn (org-refresh-category-properties)
9204 (get-text-property pos 'org-category))))))
9206 (defun org-refresh-category-properties ()
9207 "Refresh category text properties in the buffer."
9208 (let ((case-fold-search t)
9209 (inhibit-read-only t)
9210 (def-cat (cond
9211 ((null org-category)
9212 (if buffer-file-name
9213 (file-name-sans-extension
9214 (file-name-nondirectory buffer-file-name))
9215 "???"))
9216 ((symbolp org-category) (symbol-name org-category))
9217 (t org-category)))
9218 beg end cat pos optionp)
9219 (org-with-silent-modifications
9220 (save-excursion
9221 (save-restriction
9222 (widen)
9223 (goto-char (point-min))
9224 (put-text-property (point) (point-max) 'org-category def-cat)
9225 (while (re-search-forward
9226 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9227 (setq pos (match-end 0)
9228 optionp (equal (char-after (match-beginning 0)) ?#)
9229 cat (org-trim (match-string 2)))
9230 (if optionp
9231 (setq beg (point-at-bol) end (point-max))
9232 (org-back-to-heading t)
9233 (setq beg (point) end (org-end-of-subtree t t)))
9234 (put-text-property beg end 'org-category cat)
9235 (put-text-property beg end 'org-category-position beg)
9236 (goto-char pos)))))))
9238 (defun org-refresh-properties (dprop tprop)
9239 "Refresh buffer text properties.
9240 DPROP is the drawer property and TPROP is the corresponding text
9241 property to set."
9242 (let ((case-fold-search t)
9243 (inhibit-read-only t) p)
9244 (org-with-silent-modifications
9245 (save-excursion
9246 (save-restriction
9247 (widen)
9248 (goto-char (point-min))
9249 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9250 (setq p (org-match-string-no-properties 1))
9251 (save-excursion
9252 (org-back-to-heading t)
9253 (put-text-property
9254 (point-at-bol) (org-end-of-subtree t t) tprop p))))))))
9257 ;;;; Link Stuff
9259 ;;; Link abbreviations
9261 (defun org-link-expand-abbrev (link)
9262 "Apply replacements as defined in `org-link-abbrev-alist'."
9263 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9264 (let* ((key (match-string 1 link))
9265 (as (or (assoc key org-link-abbrev-alist-local)
9266 (assoc key org-link-abbrev-alist)))
9267 (tag (and (match-end 2) (match-string 3 link)))
9268 rpl)
9269 (if (not as)
9270 link
9271 (setq rpl (cdr as))
9272 (cond
9273 ((symbolp rpl) (funcall rpl tag))
9274 ((string-match "%(\\([^)]+\\))" rpl)
9275 (replace-match
9276 (save-match-data
9277 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9278 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9279 ((string-match "%h" rpl)
9280 (replace-match (url-hexify-string (or tag "")) t t rpl))
9281 (t (concat rpl tag)))))
9282 link))
9284 ;;; Storing and inserting links
9286 (defvar org-insert-link-history nil
9287 "Minibuffer history for links inserted with `org-insert-link'.")
9289 (defvar org-stored-links nil
9290 "Contains the links stored with `org-store-link'.")
9292 (defvar org-store-link-plist nil
9293 "Plist with info about the most recently link created with `org-store-link'.")
9295 (defvar org-link-protocols nil
9296 "Link protocols added to Org-mode using `org-add-link-type'.")
9298 (defvar org-store-link-functions nil
9299 "List of functions that are called to create and store a link.
9300 Each function will be called in turn until one returns a non-nil
9301 value. Each function should check if it is responsible for creating
9302 this link (for example by looking at the major mode).
9303 If not, it must exit and return nil.
9304 If yes, it should return a non-nil value after a calling
9305 `org-store-link-props' with a list of properties and values.
9306 Special properties are:
9308 :type The link prefix, like \"http\". This must be given.
9309 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9310 This is obligatory as well.
9311 :description Optional default description for the second pair
9312 of brackets in an Org-mode link. The user can still change
9313 this when inserting this link into an Org-mode buffer.
9315 In addition to these, any additional properties can be specified
9316 and then used in capture templates.")
9318 (defun org-add-link-type (type &optional follow export)
9319 "Add TYPE to the list of `org-link-types'.
9320 Re-compute all regular expressions depending on `org-link-types'
9322 FOLLOW and EXPORT are two functions.
9324 FOLLOW should take the link path as the single argument and do whatever
9325 is necessary to follow the link, for example find a file or display
9326 a mail message.
9328 EXPORT should format the link path for export to one of the export formats.
9329 It should be a function accepting three arguments:
9331 path the path of the link, the text after the prefix (like \"http:\")
9332 desc the description of the link, if any, or a description added by
9333 org-export-normalize-links if there is none
9334 format the export format, a symbol like `html' or `latex' or `ascii'..
9336 The function may use the FORMAT information to return different values
9337 depending on the format. The return value will be put literally into
9338 the exported file. If the return value is nil, this means Org should
9339 do what it normally does with links which do not have EXPORT defined.
9341 Org-mode has a built-in default for exporting links. If you are happy with
9342 this default, there is no need to define an export function for the link
9343 type. For a simple example of an export function, see `org-bbdb.el'."
9344 (add-to-list 'org-link-types type t)
9345 (org-make-link-regexps)
9346 (if (assoc type org-link-protocols)
9347 (setcdr (assoc type org-link-protocols) (list follow export))
9348 (push (list type follow export) org-link-protocols)))
9350 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9351 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9353 ;;;###autoload
9354 (defun org-store-link (arg)
9355 "\\<org-mode-map>Store an org-link to the current location.
9356 This link is added to `org-stored-links' and can later be inserted
9357 into an org-buffer with \\[org-insert-link].
9359 For some link types, a prefix arg is interpreted.
9360 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9361 For file links, arg negates `org-context-in-file-links'.
9363 A double prefix arg force skipping storing functions that are not
9364 part of Org's core.
9366 A triple prefix arg force storing a link for each line in the
9367 active region."
9368 (interactive "P")
9369 (org-load-modules-maybe)
9370 (if (and (equal arg '(64)) (org-region-active-p))
9371 (save-excursion
9372 (let ((end (region-end)))
9373 (goto-char (region-beginning))
9374 (set-mark (point))
9375 (while (< (point-at-eol) end)
9376 (move-end-of-line 1) (activate-mark)
9377 (let (current-prefix-arg)
9378 (call-interactively 'org-store-link))
9379 (move-beginning-of-line 2)
9380 (set-mark (point)))))
9381 (org-with-limited-levels
9382 (setq org-store-link-plist nil)
9383 (let (link cpltxt desc description search
9384 txt custom-id agenda-link sfuns sfunsn)
9385 (cond
9387 ;; Store a link using an external link type
9388 ((and (not (equal arg '(16)))
9389 (setq sfuns
9390 (delq
9391 nil (mapcar (lambda (f)
9392 (let (fs) (if (funcall f) (push f fs))))
9393 org-store-link-functions))
9394 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9395 (or (and (cdr sfuns)
9396 (funcall (intern
9397 (completing-read
9398 "Which function for creating the link? "
9399 sfunsn t (car sfunsn)))))
9400 (funcall (caar sfuns)))
9401 (setq link (plist-get org-store-link-plist :link)
9402 desc (or (plist-get org-store-link-plist
9403 :description) link))))
9405 ;; Store a link from a source code buffer
9406 ((org-src-edit-buffer-p)
9407 (let (label gc)
9408 (while (or (not label)
9409 (save-excursion
9410 (save-restriction
9411 (widen)
9412 (goto-char (point-min))
9413 (re-search-forward
9414 (regexp-quote (format org-coderef-label-format label))
9415 nil t))))
9416 (when label (message "Label exists already") (sit-for 2))
9417 (setq label (read-string "Code line label: " label)))
9418 (end-of-line 1)
9419 (setq link (format org-coderef-label-format label))
9420 (setq gc (- 79 (length link)))
9421 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9422 (insert link)
9423 (setq link (concat "(" label ")") desc nil)))
9425 ;; We are in the agenda, link to referenced location
9426 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9427 (let ((m (or (get-text-property (point) 'org-hd-marker)
9428 (get-text-property (point) 'org-marker))))
9429 (when m
9430 (org-with-point-at m
9431 (setq agenda-link
9432 (if (org-called-interactively-p 'any)
9433 (call-interactively 'org-store-link)
9434 (org-store-link nil)))))))
9436 ((eq major-mode 'calendar-mode)
9437 (let ((cd (calendar-cursor-to-date)))
9438 (setq link
9439 (format-time-string
9440 (car org-time-stamp-formats)
9441 (apply 'encode-time
9442 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9443 nil nil nil))))
9444 (org-store-link-props :type "calendar" :date cd)))
9446 ((eq major-mode 'help-mode)
9447 (setq link (concat "help:" (save-excursion
9448 (goto-char (point-min))
9449 (looking-at "^[^ ]+")
9450 (match-string 0))))
9451 (org-store-link-props :type "help"))
9453 ((eq major-mode 'w3-mode)
9454 (setq cpltxt (if (and (buffer-name)
9455 (not (string-match "Untitled" (buffer-name))))
9456 (buffer-name)
9457 (url-view-url t))
9458 link (url-view-url t))
9459 (org-store-link-props :type "w3" :url (url-view-url t)))
9461 ((eq major-mode 'image-mode)
9462 (setq cpltxt (concat "file:"
9463 (abbreviate-file-name buffer-file-name))
9464 link cpltxt)
9465 (org-store-link-props :type "image" :file buffer-file-name))
9467 ;; In dired, store a link to the file of the current line
9468 ((eq major-mode 'dired-mode)
9469 (let ((file (dired-get-filename nil t)))
9470 (setq file (if file
9471 (abbreviate-file-name
9472 (expand-file-name (dired-get-filename nil t)))
9473 ;; otherwise, no file so use current directory.
9474 default-directory))
9475 (setq cpltxt (concat "file:" file)
9476 link cpltxt)))
9478 ((setq search (run-hook-with-args-until-success
9479 'org-create-file-search-functions))
9480 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9481 "::" search))
9482 (setq cpltxt (or description link)))
9484 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9485 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9486 (cond
9487 ;; Store a link using the target at point
9488 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9489 (setq cpltxt
9490 (concat "file:"
9491 (abbreviate-file-name
9492 (buffer-file-name (buffer-base-buffer)))
9493 "::" (match-string 1))
9494 link cpltxt))
9495 ((and (featurep 'org-id)
9496 (or (eq org-id-link-to-org-use-id t)
9497 (and (org-called-interactively-p 'any)
9498 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9499 (and (eq org-id-link-to-org-use-id
9500 'create-if-interactive-and-no-custom-id)
9501 (not custom-id))))
9502 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9503 ;; Store a link using the ID at point
9504 (setq link (condition-case nil
9505 (prog1 (org-id-store-link)
9506 (setq desc (plist-get org-store-link-plist
9507 :description)))
9508 (error
9509 ;; Probably before first headline, link only to file
9510 (concat "file:"
9511 (abbreviate-file-name
9512 (buffer-file-name (buffer-base-buffer))))))))
9514 ;; Just link to current headline
9515 (setq cpltxt (concat "file:"
9516 (abbreviate-file-name
9517 (buffer-file-name (buffer-base-buffer)))))
9518 ;; Add a context search string
9519 (when (org-xor org-context-in-file-links arg)
9520 (let* ((ee (org-element-at-point))
9521 (et (org-element-type ee))
9522 (ev (plist-get (cadr ee) :value))
9523 (ek (plist-get (cadr ee) :key))
9524 (eok (and (stringp ek) (string-match "name" ek))))
9525 (setq txt (cond
9526 ((org-at-heading-p) nil)
9527 ((and (eq et 'keyword) eok) ev)
9528 ((org-region-active-p)
9529 (buffer-substring (region-beginning) (region-end)))))
9530 (when (or (null txt) (string-match "\\S-" txt))
9531 (setq cpltxt
9532 (concat cpltxt "::"
9533 (condition-case nil
9534 (org-make-org-heading-search-string txt)
9535 (error "")))
9536 desc (or (and (eq et 'keyword) eok ev)
9537 (nth 4 (ignore-errors (org-heading-components)))
9538 "NONE")))))
9539 (if (string-match "::\\'" cpltxt)
9540 (setq cpltxt (substring cpltxt 0 -2)))
9541 (setq link cpltxt))))
9543 ((buffer-file-name (buffer-base-buffer))
9544 ;; Just link to this file here.
9545 (setq cpltxt (concat "file:"
9546 (abbreviate-file-name
9547 (buffer-file-name (buffer-base-buffer)))))
9548 ;; Add a context string.
9549 (when (org-xor org-context-in-file-links arg)
9550 (setq txt (if (org-region-active-p)
9551 (buffer-substring (region-beginning) (region-end))
9552 (buffer-substring (point-at-bol) (point-at-eol))))
9553 ;; Only use search option if there is some text.
9554 (when (string-match "\\S-" txt)
9555 (setq cpltxt
9556 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9557 desc "NONE")))
9558 (setq link cpltxt))
9560 ((org-called-interactively-p 'interactive)
9561 (user-error "No method for storing a link from this buffer"))
9563 (t (setq link nil)))
9565 ;; We're done setting link and desc, clean up
9566 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9567 (setq link (or link cpltxt)
9568 desc (or desc cpltxt))
9569 (cond ((equal desc "NONE") (setq desc nil))
9570 ((string-match org-bracket-link-analytic-regexp desc)
9571 (let ((d0 (match-string 3 desc))
9572 (p0 (match-string 5 desc)))
9573 (setq desc
9574 (replace-regexp-in-string
9575 org-bracket-link-regexp
9576 (concat (or p0 d0)
9577 (if (equal (length (match-string 0 desc))
9578 (length desc)) "*" "")) desc)))))
9580 ;; Return the link
9581 (if (not (and (or (org-called-interactively-p 'any)
9582 executing-kbd-macro) link))
9583 (or agenda-link (and link (org-make-link-string link desc)))
9584 (push (list link desc) org-stored-links)
9585 (message "Stored: %s" (or desc link))
9586 (when custom-id
9587 (setq link (concat "file:" (abbreviate-file-name
9588 (buffer-file-name)) "::#" custom-id))
9589 (push (list link desc) org-stored-links)))))))
9591 (defun org-store-link-props (&rest plist)
9592 "Store link properties, extract names and addresses."
9593 (let (x adr)
9594 (when (setq x (plist-get plist :from))
9595 (setq adr (mail-extract-address-components x))
9596 (setq plist (plist-put plist :fromname (car adr)))
9597 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9598 (when (setq x (plist-get plist :to))
9599 (setq adr (mail-extract-address-components x))
9600 (setq plist (plist-put plist :toname (car adr)))
9601 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9602 (let ((from (plist-get plist :from))
9603 (to (plist-get plist :to)))
9604 (when (and from to org-from-is-user-regexp)
9605 (setq plist
9606 (plist-put plist :fromto
9607 (if (string-match org-from-is-user-regexp from)
9608 (concat "to %t")
9609 (concat "from %f"))))))
9610 (setq org-store-link-plist plist))
9612 (defun org-add-link-props (&rest plist)
9613 "Add these properties to the link property list."
9614 (let (key value)
9615 (while plist
9616 (setq key (pop plist) value (pop plist))
9617 (setq org-store-link-plist
9618 (plist-put org-store-link-plist key value)))))
9620 (defun org-email-link-description (&optional fmt)
9621 "Return the description part of an email link.
9622 This takes information from `org-store-link-plist' and formats it
9623 according to FMT (default from `org-email-link-description-format')."
9624 (setq fmt (or fmt org-email-link-description-format))
9625 (let* ((p org-store-link-plist)
9626 (to (plist-get p :toaddress))
9627 (from (plist-get p :fromaddress))
9628 (table
9629 (list
9630 (cons "%c" (plist-get p :fromto))
9631 (cons "%F" (plist-get p :from))
9632 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9633 (cons "%T" (plist-get p :to))
9634 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9635 (cons "%s" (plist-get p :subject))
9636 (cons "%d" (plist-get p :date))
9637 (cons "%m" (plist-get p :message-id)))))
9638 (when (string-match "%c" fmt)
9639 ;; Check if the user wrote this message
9640 (if (and org-from-is-user-regexp from to
9641 (save-match-data (string-match org-from-is-user-regexp from)))
9642 (setq fmt (replace-match "to %t" t t fmt))
9643 (setq fmt (replace-match "from %f" t t fmt))))
9644 (org-replace-escapes fmt table)))
9646 (defun org-make-org-heading-search-string (&optional string)
9647 "Make search string for the current headline or STRING."
9648 (let ((s (or string
9649 (and (derived-mode-p 'org-mode)
9650 (save-excursion
9651 (org-back-to-heading t)
9652 (org-element-property :raw-value (org-element-at-point))))))
9653 (lines org-context-in-file-links))
9654 (or string (setq s (concat "*" s))) ; Add * for headlines
9655 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9656 (when (and string (integerp lines) (> lines 0))
9657 (let ((slines (org-split-string s "\n")))
9658 (when (< lines (length slines))
9659 (setq s (mapconcat
9660 'identity
9661 (reverse (nthcdr (- (length slines) lines)
9662 (reverse slines))) "\n")))))
9663 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9665 (defun org-make-link-string (link &optional description)
9666 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9667 (unless (string-match "\\S-" link)
9668 (error "Empty link"))
9669 (when (and description
9670 (stringp description)
9671 (not (string-match "\\S-" description)))
9672 (setq description nil))
9673 (when (stringp description)
9674 ;; Remove brackets from the description, they are fatal.
9675 (while (string-match "\\[" description)
9676 (setq description (replace-match "{" t t description)))
9677 (while (string-match "\\]" description)
9678 (setq description (replace-match "}" t t description))))
9679 (when (equal link description)
9680 ;; No description needed, it is identical
9681 (setq description nil))
9682 (when (and (not description)
9683 (not (string-match (org-image-file-name-regexp) link))
9684 (not (equal link (org-link-escape link))))
9685 (setq description (org-extract-attributes link)))
9686 (setq link
9687 (cond ((string-match (org-image-file-name-regexp) link) link)
9688 ((string-match org-link-types-re link)
9689 (concat (match-string 1 link)
9690 (org-link-escape (substring link (match-end 1)))))
9691 (t (org-link-escape link))))
9692 (concat "[[" link "]"
9693 (if description (concat "[" description "]") "")
9694 "]"))
9696 (defconst org-link-escape-chars
9697 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9698 "List of characters that should be escaped in link.
9699 This is the list that is used for internal purposes.")
9701 (defconst org-link-escape-chars-browser
9702 '(?\ )
9703 "List of escapes for characters that are problematic in links.
9704 This is the list that is used before handing over to the browser.")
9706 (defun org-link-escape (text &optional table merge)
9707 "Return percent escaped representation of TEXT.
9708 TEXT is a string with the text to escape.
9709 Optional argument TABLE is a list with characters that should be
9710 escaped. When nil, `org-link-escape-chars' is used.
9711 If optional argument MERGE is set, merge TABLE into
9712 `org-link-escape-chars'."
9713 (cond
9714 ((and table merge)
9715 (mapc (lambda (defchr)
9716 (unless (member defchr table)
9717 (setq table (cons defchr table)))) org-link-escape-chars))
9718 ((null table)
9719 (setq table org-link-escape-chars)))
9720 (mapconcat
9721 (lambda (char)
9722 (if (or (member char table)
9723 (and (or (< char 32) (= char 37) (> char 126))
9724 org-url-hexify-p))
9725 (mapconcat (lambda (sequence-element)
9726 (format "%%%.2X" sequence-element))
9727 (or (encode-coding-char char 'utf-8)
9728 (error "Unable to percent escape character: %s"
9729 (char-to-string char))) "")
9730 (char-to-string char))) text ""))
9732 (defun org-link-unescape (str)
9733 "Unhex hexified Unicode strings as returned from the JavaScript function
9734 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9735 (unless (and (null str) (string= "" str))
9736 (let ((pos 0) (case-fold-search t) unhexed)
9737 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9738 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9739 (setq str (replace-match unhexed t t str))
9740 (setq pos (+ pos (length unhexed))))))
9741 str)
9743 (defun org-link-unescape-compound (hex)
9744 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9745 Note: this function also decodes single byte encodings like
9746 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9747 (save-match-data
9748 (let* ((bytes (cdr (split-string hex "%")))
9749 (ret "")
9750 (eat 0)
9751 (sum 0))
9752 (while bytes
9753 (let* ((val (string-to-number (pop bytes) 16))
9754 (shift-xor
9755 (if (= 0 eat)
9756 (cond
9757 ((>= val 252) (cons 6 252))
9758 ((>= val 248) (cons 5 248))
9759 ((>= val 240) (cons 4 240))
9760 ((>= val 224) (cons 3 224))
9761 ((>= val 192) (cons 2 192))
9762 (t (cons 0 0)))
9763 (cons 6 128))))
9764 (if (>= val 192) (setq eat (car shift-xor)))
9765 (setq val (logxor val (cdr shift-xor)))
9766 (setq sum (+ (lsh sum (car shift-xor)) val))
9767 (if (> eat 0) (setq eat (- eat 1)))
9768 (cond
9769 ((= 0 eat) ;multi byte
9770 (setq ret (concat ret (org-char-to-string sum)))
9771 (setq sum 0))
9772 ((not bytes) ; single byte(s)
9773 (setq ret (org-link-unescape-single-byte-sequence hex))))
9774 )) ;; end (while bytes
9775 ret )))
9777 (defun org-link-unescape-single-byte-sequence (hex)
9778 "Unhexify hex-encoded single byte character sequences."
9779 (mapconcat (lambda (byte)
9780 (char-to-string (string-to-number byte 16)))
9781 (cdr (split-string hex "%")) ""))
9783 (defun org-xor (a b)
9784 "Exclusive or."
9785 (if a (not b) b))
9787 (defun org-fixup-message-id-for-http (s)
9788 "Replace special characters in a message id, so it can be used in an http query."
9789 (when (string-match "%" s)
9790 (setq s (mapconcat (lambda (c)
9791 (if (eq c ?%)
9792 "%25"
9793 (char-to-string c)))
9794 s "")))
9795 (while (string-match "<" s)
9796 (setq s (replace-match "%3C" t t s)))
9797 (while (string-match ">" s)
9798 (setq s (replace-match "%3E" t t s)))
9799 (while (string-match "@" s)
9800 (setq s (replace-match "%40" t t s)))
9803 (defun org-link-prettify (link)
9804 "Return a human-readable representation of LINK.
9805 The car of LINK must be a raw link the cdr of LINK must be either
9806 a link description or nil."
9807 (let ((desc (or (cadr link) "<no description>")))
9808 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9809 "<" (car link) ">")))
9811 ;;;###autoload
9812 (defun org-insert-link-global ()
9813 "Insert a link like Org-mode does.
9814 This command can be called in any mode to insert a link in Org-mode syntax."
9815 (interactive)
9816 (org-load-modules-maybe)
9817 (org-run-like-in-org-mode 'org-insert-link))
9819 (defun org-insert-all-links (&optional keep)
9820 "Insert all links in `org-stored-links'."
9821 (interactive "P")
9822 (let ((links (copy-sequence org-stored-links)) l)
9823 (while (setq l (if keep (pop links) (pop org-stored-links)))
9824 (insert "- ")
9825 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9826 (insert "\n"))))
9828 (defun org-link-fontify-links-to-this-file ()
9829 "Fontify links to the current file in `org-stored-links'."
9830 (let ((f (buffer-file-name)) a b)
9831 (setq a (mapcar (lambda(l)
9832 (let ((ll (car l)))
9833 (when (and (string-match "^file:\\(.+\\)::" ll)
9834 (equal f (expand-file-name (match-string 1 ll))))
9835 ll)))
9836 org-stored-links))
9837 (when (featurep 'org-id)
9838 (setq b (mapcar (lambda(l)
9839 (let ((ll (car l)))
9840 (when (and (string-match "^id:\\(.+\\)$" ll)
9841 (equal f (expand-file-name
9842 (or (org-id-find-id-file
9843 (match-string 1 ll)) ""))))
9844 ll)))
9845 org-stored-links)))
9846 (mapcar (lambda(l)
9847 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9848 (delq nil (append a b)))))
9850 (defvar org-link-links-in-this-file nil)
9851 (defun org-insert-link (&optional complete-file link-location default-description)
9852 "Insert a link. At the prompt, enter the link.
9854 Completion can be used to insert any of the link protocol prefixes like
9855 http or ftp in use.
9857 The history can be used to select a link previously stored with
9858 `org-store-link'. When the empty string is entered (i.e. if you just
9859 press RET at the prompt), the link defaults to the most recently
9860 stored link. As SPC triggers completion in the minibuffer, you need to
9861 use M-SPC or C-q SPC to force the insertion of a space character.
9863 You will also be prompted for a description, and if one is given, it will
9864 be displayed in the buffer instead of the link.
9866 If there is already a link at point, this command will allow you to edit link
9867 and description parts.
9869 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9870 be selected using completion. The path to the file will be relative to the
9871 current directory if the file is in the current directory or a subdirectory.
9872 Otherwise, the link will be the absolute path as completed in the minibuffer
9873 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9874 option `org-link-file-path-type'.
9876 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9877 the current directory or below.
9879 With three \\[universal-argument] prefixes, negate the meaning of
9880 `org-keep-stored-link-after-insertion'.
9882 If `org-make-link-description-function' is non-nil, this function will be
9883 called with the link target, and the result will be the default
9884 link description.
9886 If the LINK-LOCATION parameter is non-nil, this value will be
9887 used as the link location instead of reading one interactively.
9889 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9890 be used as the default description."
9891 (interactive "P")
9892 (let* ((wcf (current-window-configuration))
9893 (origbuf (current-buffer))
9894 (region (if (org-region-active-p)
9895 (buffer-substring (region-beginning) (region-end))))
9896 (remove (and region (list (region-beginning) (region-end))))
9897 (desc region)
9898 tmphist ; byte-compile incorrectly complains about this
9899 (link link-location)
9900 (abbrevs org-link-abbrev-alist-local)
9901 entry file all-prefixes auto-desc)
9902 (cond
9903 (link-location) ; specified by arg, just use it.
9904 ((org-in-regexp org-bracket-link-regexp 1)
9905 ;; We do have a link at point, and we are going to edit it.
9906 (setq remove (list (match-beginning 0) (match-end 0)))
9907 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9908 (setq link (read-string "Link: "
9909 (org-link-unescape
9910 (org-match-string-no-properties 1)))))
9911 ((or (org-in-regexp org-angle-link-re)
9912 (org-in-regexp org-plain-link-re))
9913 ;; Convert to bracket link
9914 (setq remove (list (match-beginning 0) (match-end 0))
9915 link (read-string "Link: "
9916 (org-remove-angle-brackets (match-string 0)))))
9917 ((member complete-file '((4) (16)))
9918 ;; Completing read for file names.
9919 (setq link (org-file-complete-link complete-file)))
9921 ;; Read link, with completion for stored links.
9922 (org-link-fontify-links-to-this-file)
9923 (org-switch-to-buffer-other-window "*Org Links*")
9924 (with-current-buffer "*Org Links*"
9925 (erase-buffer)
9926 (insert "Insert a link.
9927 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9928 (when org-stored-links
9929 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9930 (insert (mapconcat 'org-link-prettify
9931 (reverse org-stored-links) "\n")))
9932 (goto-char (point-min)))
9933 (let ((cw (selected-window)))
9934 (select-window (get-buffer-window "*Org Links*" 'visible))
9935 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9936 (unless (pos-visible-in-window-p (point-max))
9937 (org-fit-window-to-buffer))
9938 (and (window-live-p cw) (select-window cw)))
9939 ;; Fake a link history, containing the stored links.
9940 (setq tmphist (append (mapcar 'car org-stored-links)
9941 org-insert-link-history))
9942 (setq all-prefixes (append (mapcar 'car abbrevs)
9943 (mapcar 'car org-link-abbrev-alist)
9944 org-link-types))
9945 (unwind-protect
9946 (progn
9947 (setq link
9948 (org-completing-read
9949 "Link: "
9950 (append
9951 (mapcar (lambda (x) (concat x ":"))
9952 all-prefixes)
9953 (mapcar 'car org-stored-links))
9954 nil nil nil
9955 'tmphist
9956 (caar org-stored-links)))
9957 (if (not (string-match "\\S-" link))
9958 (user-error "No link selected"))
9959 (mapc (lambda(l)
9960 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9961 org-stored-links)
9962 (if (or (member link all-prefixes)
9963 (and (equal ":" (substring link -1))
9964 (member (substring link 0 -1) all-prefixes)
9965 (setq link (substring link 0 -1))))
9966 (setq link (with-current-buffer origbuf
9967 (org-link-try-special-completion link)))))
9968 (set-window-configuration wcf)
9969 (kill-buffer "*Org Links*"))
9970 (setq entry (assoc link org-stored-links))
9971 (or entry (push link org-insert-link-history))
9972 (setq desc (or desc (nth 1 entry)))))
9974 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9975 (not org-keep-stored-link-after-insertion))
9976 (setq org-stored-links (delq (assoc link org-stored-links)
9977 org-stored-links)))
9979 (if (string-match org-plain-link-re link)
9980 ;; URL-like link, normalize the use of angular brackets.
9981 (setq link (org-remove-angle-brackets link)))
9983 ;; Check if we are linking to the current file with a search
9984 ;; option If yes, simplify the link by using only the search
9985 ;; option.
9986 (when (and buffer-file-name
9987 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9988 (let* ((path (match-string 1 link))
9989 (case-fold-search nil)
9990 (search (match-string 2 link)))
9991 (save-match-data
9992 (if (equal (file-truename buffer-file-name) (file-truename path))
9993 ;; We are linking to this same file, with a search option
9994 (setq link search)))))
9996 ;; Check if we can/should use a relative path. If yes, simplify the link
9997 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9998 (let* ((type (match-string 1 link))
9999 (path (match-string 2 link))
10000 (origpath path)
10001 (case-fold-search nil))
10002 (cond
10003 ((or (eq org-link-file-path-type 'absolute)
10004 (equal complete-file '(16)))
10005 (setq path (abbreviate-file-name (expand-file-name path))))
10006 ((eq org-link-file-path-type 'noabbrev)
10007 (setq path (expand-file-name path)))
10008 ((eq org-link-file-path-type 'relative)
10009 (setq path (file-relative-name path)))
10011 (save-match-data
10012 (if (string-match (concat "^" (regexp-quote
10013 (expand-file-name
10014 (file-name-as-directory
10015 default-directory))))
10016 (expand-file-name path))
10017 ;; We are linking a file with relative path name.
10018 (setq path (substring (expand-file-name path)
10019 (match-end 0)))
10020 (setq path (abbreviate-file-name (expand-file-name path)))))))
10021 (setq link (concat type path))
10022 (if (equal desc origpath)
10023 (setq desc path))))
10025 (if org-make-link-description-function
10026 (setq desc
10027 (or (condition-case nil
10028 (funcall org-make-link-description-function link desc)
10029 (error (progn (message "Can't get link description from `%s'"
10030 (symbol-name org-make-link-description-function))
10031 (sit-for 2) nil)))
10032 (read-string "Description: " default-description)))
10033 (if default-description (setq desc default-description)
10034 (setq desc (or (and auto-desc desc)
10035 (read-string "Description: " desc)))))
10037 (unless (string-match "\\S-" desc) (setq desc nil))
10038 (if remove (apply 'delete-region remove))
10039 (insert (org-make-link-string link desc))))
10041 (defun org-link-try-special-completion (type)
10042 "If there is completion support for link type TYPE, offer it."
10043 (let ((fun (intern (concat "org-" type "-complete-link"))))
10044 (if (functionp fun)
10045 (funcall fun)
10046 (read-string "Link (no completion support): " (concat type ":")))))
10048 (defun org-file-complete-link (&optional arg)
10049 "Create a file link using completion."
10050 (let (file link)
10051 (setq file (org-iread-file-name "File: "))
10052 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10053 (pwd1 (file-name-as-directory (abbreviate-file-name
10054 (expand-file-name ".")))))
10055 (cond
10056 ((equal arg '(16))
10057 (setq link (concat
10058 "file:"
10059 (abbreviate-file-name (expand-file-name file)))))
10060 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10061 (setq link (concat "file:" (match-string 1 file))))
10062 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10063 (expand-file-name file))
10064 (setq link (concat
10065 "file:" (match-string 1 (expand-file-name file)))))
10066 (t (setq link (concat "file:" file)))))
10067 link))
10069 (defun org-iread-file-name (&rest args)
10070 "Read-file-name using `ido-mode' speedup if available.
10071 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10072 See `read-file-name' for a description of parameters."
10073 (org-without-partial-completion
10074 (if (and org-completion-use-ido
10075 (fboundp 'ido-read-file-name)
10076 (boundp 'ido-mode) ido-mode
10077 (listp (second args)))
10078 (let ((ido-enter-matching-directory nil))
10079 (apply 'ido-read-file-name args))
10080 (apply 'read-file-name args))))
10082 (defun org-completing-read (&rest args)
10083 "Completing-read with SPACE being a normal character."
10084 (let ((enable-recursive-minibuffers t)
10085 (minibuffer-local-completion-map
10086 (copy-keymap minibuffer-local-completion-map)))
10087 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10088 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10089 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10090 (apply 'org-icompleting-read args)))
10092 (defun org-completing-read-no-i (&rest args)
10093 (let (org-completion-use-ido org-completion-use-iswitchb)
10094 (apply 'org-completing-read args)))
10096 (defun org-iswitchb-completing-read (prompt choices &rest args)
10097 "Use iswitch as a completing-read replacement to choose from choices.
10098 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10099 from."
10100 (let* ((iswitchb-use-virtual-buffers nil)
10101 (iswitchb-make-buflist-hook
10102 (lambda ()
10103 (setq iswitchb-temp-buflist choices))))
10104 (iswitchb-read-buffer prompt)))
10106 (defun org-icompleting-read (&rest args)
10107 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10108 (org-without-partial-completion
10109 (if (and org-completion-use-ido
10110 (fboundp 'ido-completing-read)
10111 (boundp 'ido-mode) ido-mode
10112 (listp (second args)))
10113 (let ((ido-enter-matching-directory nil))
10114 (apply 'ido-completing-read (concat (car args))
10115 (if (consp (car (nth 1 args)))
10116 (mapcar 'car (nth 1 args))
10117 (nth 1 args))
10118 (cddr args)))
10119 (if (and org-completion-use-iswitchb
10120 (boundp 'iswitchb-mode) iswitchb-mode
10121 (listp (second args)))
10122 (apply 'org-iswitchb-completing-read (concat (car args))
10123 (if (consp (car (nth 1 args)))
10124 (mapcar 'car (nth 1 args))
10125 (nth 1 args))
10126 (cddr args))
10127 (apply 'completing-read args)))))
10129 (defun org-extract-attributes (s)
10130 "Extract the attributes cookie from a string and set as text property."
10131 (let (a attr (start 0) key value)
10132 (save-match-data
10133 (when (string-match "{{\\([^}]+\\)}}$" s)
10134 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10135 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10136 (setq key (match-string 1 a) value (match-string 2 a)
10137 start (match-end 0)
10138 attr (plist-put attr (intern key) value))))
10139 (org-add-props s nil 'org-attr attr))
10142 ;;; Opening/following a link
10144 (defvar org-link-search-failed nil)
10146 (defvar org-open-link-functions nil
10147 "Hook for functions finding a plain text link.
10148 These functions must take a single argument, the link content.
10149 They will be called for links that look like [[link text][description]]
10150 when LINK TEXT does not have a protocol like \"http:\" and does not look
10151 like a filename (e.g. \"./blue.png\").
10153 These functions will be called *before* Org attempts to resolve the
10154 link by doing text searches in the current buffer - so if you want a
10155 link \"[[target]]\" to still find \"<<target>>\", your function should
10156 handle this as a special case.
10158 When the function does handle the link, it must return a non-nil value.
10159 If it decides that it is not responsible for this link, it must return
10160 nil to indicate that that Org-mode can continue with other options
10161 like exact and fuzzy text search.")
10163 (defun org-next-link (&optional search-backward)
10164 "Move forward to the next link.
10165 If the link is in hidden text, expose it."
10166 (interactive "P")
10167 (when (and org-link-search-failed (eq this-command last-command))
10168 (goto-char (point-min))
10169 (message "Link search wrapped back to beginning of buffer"))
10170 (setq org-link-search-failed nil)
10171 (let* ((pos (point))
10172 (ct (org-context))
10173 (a (assoc :link ct))
10174 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10175 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10176 ((looking-at org-any-link-re)
10177 ;; Don't stay stuck at link without an org-link face
10178 (forward-char (if search-backward -1 1))))
10179 (if (funcall srch-fun org-any-link-re nil t)
10180 (progn
10181 (goto-char (match-beginning 0))
10182 (if (outline-invisible-p) (org-show-context)))
10183 (goto-char pos)
10184 (setq org-link-search-failed t)
10185 (message "No further link found"))))
10187 (defun org-previous-link ()
10188 "Move backward to the previous link.
10189 If the link is in hidden text, expose it."
10190 (interactive)
10191 (funcall 'org-next-link t))
10193 (defun org-translate-link (s)
10194 "Translate a link string if a translation function has been defined."
10195 (if (and org-link-translation-function
10196 (fboundp org-link-translation-function)
10197 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10198 (progn
10199 (setq s (funcall org-link-translation-function
10200 (match-string 1 s) (match-string 2 s)))
10201 (concat (car s) ":" (cdr s)))
10204 (defun org-translate-link-from-planner (type path)
10205 "Translate a link from Emacs Planner syntax so that Org can follow it.
10206 This is still an experimental function, your mileage may vary."
10207 (cond
10208 ((member type '("http" "https" "news" "ftp"))
10209 ;; standard Internet links are the same.
10210 nil)
10211 ((and (equal type "irc") (string-match "^//" path))
10212 ;; Planner has two / at the beginning of an irc link, we have 1.
10213 ;; We should have zero, actually....
10214 (setq path (substring path 1)))
10215 ((and (equal type "lisp") (string-match "^/" path))
10216 ;; Planner has a slash, we do not.
10217 (setq type "elisp" path (substring path 1)))
10218 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10219 ;; A typical message link. Planner has the id after the final slash,
10220 ;; we separate it with a hash mark
10221 (setq path (concat (match-string 1 path) "#"
10222 (org-remove-angle-brackets (match-string 2 path))))))
10223 (cons type path))
10225 (defun org-find-file-at-mouse (ev)
10226 "Open file link or URL at mouse."
10227 (interactive "e")
10228 (mouse-set-point ev)
10229 (org-open-at-point 'in-emacs))
10231 (defun org-open-at-mouse (ev)
10232 "Open file link or URL at mouse.
10233 See the docstring of `org-open-file' for details."
10234 (interactive "e")
10235 (mouse-set-point ev)
10236 (if (eq major-mode 'org-agenda-mode)
10237 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10238 (org-open-at-point))
10240 (defvar org-window-config-before-follow-link nil
10241 "The window configuration before following a link.
10242 This is saved in case the need arises to restore it.")
10244 (defvar org-open-link-marker (make-marker)
10245 "Marker pointing to the location where `org-open-at-point; was called.")
10247 ;;;###autoload
10248 (defun org-open-at-point-global ()
10249 "Follow a link like Org-mode does.
10250 This command can be called in any mode to follow a link that has
10251 Org-mode syntax."
10252 (interactive)
10253 (org-run-like-in-org-mode 'org-open-at-point))
10255 ;;;###autoload
10256 (defun org-open-link-from-string (s &optional arg reference-buffer)
10257 "Open a link in the string S, as if it was in Org-mode."
10258 (interactive "sLink: \nP")
10259 (let ((reference-buffer (or reference-buffer (current-buffer))))
10260 (with-temp-buffer
10261 (let ((org-inhibit-startup (not reference-buffer)))
10262 (org-mode)
10263 (insert s)
10264 (goto-char (point-min))
10265 (when reference-buffer
10266 (setq org-link-abbrev-alist-local
10267 (with-current-buffer reference-buffer
10268 org-link-abbrev-alist-local)))
10269 (org-open-at-point arg reference-buffer)))))
10271 (defvar org-open-at-point-functions nil
10272 "Hook that is run when following a link at point.
10274 Functions in this hook must return t if they identify and follow
10275 a link at point. If they don't find anything interesting at point,
10276 they must return nil.")
10278 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10279 (defun org-open-at-point (&optional arg reference-buffer)
10280 "Open link at or after point.
10281 If there is no link at point, this function will search forward up to
10282 the end of the current line.
10283 Normally, files will be opened by an appropriate application. If the
10284 optional prefix argument ARG is non-nil, Emacs will visit the file.
10285 With a double prefix argument, try to open outside of Emacs, in the
10286 application the system uses for this file type."
10287 (interactive "P")
10288 ;; if in a code block, then open the block's results
10289 (unless (call-interactively #'org-babel-open-src-block-result)
10290 (org-load-modules-maybe)
10291 (move-marker org-open-link-marker (point))
10292 (setq org-window-config-before-follow-link (current-window-configuration))
10293 (org-remove-occur-highlights nil nil t)
10294 (cond
10295 ((and (org-at-heading-p)
10296 (not (org-at-timestamp-p t))
10297 (not (org-in-regexp
10298 (concat org-plain-link-re "\\|"
10299 org-bracket-link-regexp "\\|"
10300 org-angle-link-re "\\|"
10301 "[ \t]:[^ \t\n]+:[ \t]*$")))
10302 (not (get-text-property (point) 'org-linked-text)))
10303 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10304 (lk0 (car lkall))
10305 (lk (if (stringp lk0) (list lk0) lk0))
10306 (lkend (cdr lkall)))
10307 (mapcar (lambda(l)
10308 (search-forward l nil lkend)
10309 (goto-char (match-beginning 0))
10310 (org-open-at-point))
10311 lk))
10312 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10313 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10314 ((and (org-at-timestamp-p t)
10315 (not (org-in-regexp org-bracket-link-regexp)))
10316 (org-follow-timestamp-link))
10317 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10318 (not (org-in-regexp org-any-link-re)))
10319 (org-footnote-action))
10321 (let (type path link line search (pos (point)))
10322 (catch 'match
10323 (save-excursion
10324 (skip-chars-forward "^]\n\r")
10325 (when (org-in-regexp org-bracket-link-regexp 1)
10326 (setq link (org-extract-attributes
10327 (org-link-unescape (org-match-string-no-properties 1))))
10328 (while (string-match " *\n *" link)
10329 (setq link (replace-match " " t t link)))
10330 (setq link (org-link-expand-abbrev link))
10331 (cond
10332 ((or (file-name-absolute-p link)
10333 (string-match "^\\.\\.?/" link))
10334 (setq type "file" path link))
10335 ((string-match org-link-re-with-space3 link)
10336 (setq type (match-string 1 link) path (match-string 2 link)))
10337 ((string-match "^help:+\\(.+\\)" link)
10338 (setq type "help" path (match-string 1 link)))
10339 (t (setq type "thisfile" path link)))
10340 (throw 'match t)))
10342 (when (get-text-property (point) 'org-linked-text)
10343 (setq type "thisfile"
10344 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10345 (1+ (point)) (point))
10346 path (buffer-substring
10347 (or (previous-single-property-change pos 'org-linked-text)
10348 (point-min))
10349 (or (next-single-property-change pos 'org-linked-text)
10350 (point-max)))
10351 ;; Ensure we will search for a <<<radio>>> link, not
10352 ;; a simple reference like <<ref>>
10353 path (concat "<" path))
10354 (throw 'match t))
10356 (save-excursion
10357 (when (or (org-in-regexp org-angle-link-re)
10358 (let ((match (org-in-regexp org-plain-link-re)))
10359 ;; Check a plain link is not within a bracket link
10360 (and match
10361 (save-excursion
10362 (progn
10363 (goto-char (car match))
10364 (not (org-in-regexp org-bracket-link-regexp))))))
10365 (let ((line_ending (save-excursion (end-of-line) (point))))
10366 ;; We are in a line before a plain or bracket link
10367 (or (re-search-forward org-plain-link-re line_ending t)
10368 (re-search-forward org-bracket-link-regexp line_ending t))))
10369 (setq type (match-string 1)
10370 path (org-link-unescape (match-string 2)))
10371 (throw 'match t)))
10372 (save-excursion
10373 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10374 (setq type "tags"
10375 path (match-string 1))
10376 (while (string-match ":" path)
10377 (setq path (replace-match "+" t t path)))
10378 (throw 'match t)))
10379 (when (org-in-regexp "<\\([^><\n]+\\)>")
10380 (setq type "tree-match"
10381 path (match-string 1))
10382 (throw 'match t)))
10383 (unless path
10384 (user-error "No link found"))
10386 ;; switch back to reference buffer
10387 ;; needed when if called in a temporary buffer through
10388 ;; org-open-link-from-string
10389 (with-current-buffer (or reference-buffer (current-buffer))
10391 ;; Remove any trailing spaces in path
10392 (if (string-match " +\\'" path)
10393 (setq path (replace-match "" t t path)))
10394 (if (and org-link-translation-function
10395 (fboundp org-link-translation-function))
10396 ;; Check if we need to translate the link
10397 (let ((tmp (funcall org-link-translation-function type path)))
10398 (setq type (car tmp) path (cdr tmp))))
10400 (cond
10402 ((assoc type org-link-protocols)
10403 (funcall (nth 1 (assoc type org-link-protocols)) path))
10405 ((equal type "help")
10406 (let ((f-or-v (intern path)))
10407 (cond ((fboundp f-or-v)
10408 (describe-function f-or-v))
10409 ((boundp f-or-v)
10410 (describe-variable f-or-v))
10411 (t (error "Not a known function or variable")))))
10413 ((equal type "mailto")
10414 (let ((cmd (car org-link-mailto-program))
10415 (args (cdr org-link-mailto-program)) args1
10416 (address path) (subject "") a)
10417 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10418 (setq address (match-string 1 path)
10419 subject (org-link-escape (match-string 2 path))))
10420 (while args
10421 (cond
10422 ((not (stringp (car args))) (push (pop args) args1))
10423 (t (setq a (pop args))
10424 (if (string-match "%a" a)
10425 (setq a (replace-match address t t a)))
10426 (if (string-match "%s" a)
10427 (setq a (replace-match subject t t a)))
10428 (push a args1))))
10429 (apply cmd (nreverse args1))))
10431 ((member type '("http" "https" "ftp" "news"))
10432 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10433 (org-link-escape
10434 path org-link-escape-chars-browser)
10435 path))))
10437 ((string= type "doi")
10438 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10439 (org-link-escape
10440 path org-link-escape-chars-browser)
10441 path))))
10443 ((member type '("message"))
10444 (browse-url (concat type ":" path)))
10446 ((string= type "tags")
10447 (org-tags-view arg path))
10449 ((string= type "tree-match")
10450 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10452 ((string= type "file")
10453 (if (string-match "::\\([0-9]+\\)\\'" path)
10454 (setq line (string-to-number (match-string 1 path))
10455 path (substring path 0 (match-beginning 0)))
10456 (if (string-match "::\\(.+\\)\\'" path)
10457 (setq search (match-string 1 path)
10458 path (substring path 0 (match-beginning 0)))))
10459 (if (string-match "[*?{]" (file-name-nondirectory path))
10460 (dired path)
10461 (org-open-file path arg line search)))
10463 ((string= type "shell")
10464 (let ((buf (generate-new-buffer "*Org Shell Output"))
10465 (cmd path))
10466 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10467 (string-match org-confirm-shell-link-not-regexp cmd))
10468 (not org-confirm-shell-link-function)
10469 (funcall org-confirm-shell-link-function
10470 (format "Execute \"%s\" in shell? "
10471 (org-add-props cmd nil
10472 'face 'org-warning))))
10473 (progn
10474 (message "Executing %s" cmd)
10475 (shell-command cmd buf)
10476 (if (featurep 'midnight)
10477 (setq clean-buffer-list-kill-buffer-names
10478 (cons buf clean-buffer-list-kill-buffer-names))))
10479 (error "Abort"))))
10481 ((string= type "elisp")
10482 (let ((cmd path))
10483 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10484 (string-match org-confirm-elisp-link-not-regexp cmd))
10485 (not org-confirm-elisp-link-function)
10486 (funcall org-confirm-elisp-link-function
10487 (format "Execute \"%s\" as elisp? "
10488 (org-add-props cmd nil
10489 'face 'org-warning))))
10490 (message "%s => %s" cmd
10491 (if (equal (string-to-char cmd) ?\()
10492 (eval (read cmd))
10493 (call-interactively (read cmd))))
10494 (error "Abort"))))
10496 ((and (string= type "thisfile")
10497 (run-hook-with-args-until-success
10498 'org-open-link-functions path)))
10500 ((string= type "thisfile")
10501 (if arg
10502 (switch-to-buffer-other-window
10503 (org-get-buffer-for-internal-link (current-buffer)))
10504 (org-mark-ring-push))
10505 (let ((cmd `(org-link-search
10506 ,path
10507 ,(cond ((equal arg '(4)) ''occur)
10508 ((equal arg '(16)) ''org-occur))
10509 ,pos)))
10510 (condition-case nil (let ((org-link-search-inhibit-query t))
10511 (eval cmd))
10512 (error (progn (widen) (eval cmd))))))
10514 (t (browse-url-at-point)))))))
10515 (move-marker org-open-link-marker nil)
10516 (run-hook-with-args 'org-follow-link-hook)))
10518 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10519 "Offer links in the current entry and return the selected link.
10520 If there is only one link, return it.
10521 If NTH is an integer, return the NTH link found.
10522 If ZERO is a string, check also this string for a link, and if
10523 there is one, return it."
10524 (with-current-buffer buffer
10525 (save-excursion
10526 (save-restriction
10527 (widen)
10528 (goto-char marker)
10529 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10530 "\\(" org-angle-link-re "\\)\\|"
10531 "\\(" org-plain-link-re "\\)"))
10532 (cnt ?0)
10533 (in-emacs (if (integerp nth) nil nth))
10534 have-zero end links link c)
10535 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10536 (push (match-string 0 zero) links)
10537 (setq cnt (1- cnt) have-zero t))
10538 (save-excursion
10539 (org-back-to-heading t)
10540 (setq end (save-excursion (outline-next-heading) (point)))
10541 (while (re-search-forward re end t)
10542 (push (match-string 0) links))
10543 (setq links (org-uniquify (reverse links))))
10544 (cond
10545 ((null links)
10546 (message "No links"))
10547 ((equal (length links) 1)
10548 (setq link (car links)))
10549 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10550 (setq link (nth (if have-zero nth (1- nth)) links)))
10551 (t ; we have to select a link
10552 (save-excursion
10553 (save-window-excursion
10554 (delete-other-windows)
10555 (with-output-to-temp-buffer "*Select Link*"
10556 (mapc (lambda (l)
10557 (if (not (string-match org-bracket-link-regexp l))
10558 (princ (format "[%c] %s\n" (incf cnt)
10559 (org-remove-angle-brackets l)))
10560 (if (match-end 3)
10561 (princ (format "[%c] %s (%s)\n" (incf cnt)
10562 (match-string 3 l) (match-string 1 l)))
10563 (princ (format "[%c] %s\n" (incf cnt)
10564 (match-string 1 l))))))
10565 links))
10566 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10567 (message "Select link to open, RET to open all:")
10568 (setq c (read-char-exclusive))
10569 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10570 (when (equal c ?q) (error "Abort"))
10571 (if (equal c ?\C-m)
10572 (setq link links)
10573 (setq nth (- c ?0))
10574 (if have-zero (setq nth (1+ nth)))
10575 (unless (and (integerp nth) (>= (length links) nth))
10576 (user-error "Invalid link selection"))
10577 (setq link (nth (1- nth) links)))))
10578 (cons link end))))))
10580 ;; Add special file links that specify the way of opening
10582 (org-add-link-type "file+sys" 'org-open-file-with-system)
10583 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10584 (defun org-open-file-with-system (path)
10585 "Open file at PATH using the system way of opening it."
10586 (org-open-file path 'system))
10587 (defun org-open-file-with-emacs (path)
10588 "Open file at PATH in Emacs."
10589 (org-open-file path 'emacs))
10592 ;;; File search
10594 (defvar org-create-file-search-functions nil
10595 "List of functions to construct the right search string for a file link.
10596 These functions are called in turn with point at the location to
10597 which the link should point.
10599 A function in the hook should first test if it would like to
10600 handle this file type, for example by checking the `major-mode'
10601 or the file extension. If it decides not to handle this file, it
10602 should just return nil to give other functions a chance. If it
10603 does handle the file, it must return the search string to be used
10604 when following the link. The search string will be part of the
10605 file link, given after a double colon, and `org-open-at-point'
10606 will automatically search for it. If special measures must be
10607 taken to make the search successful, another function should be
10608 added to the companion hook `org-execute-file-search-functions',
10609 which see.
10611 A function in this hook may also use `setq' to set the variable
10612 `description' to provide a suggestion for the descriptive text to
10613 be used for this link when it gets inserted into an Org-mode
10614 buffer with \\[org-insert-link].")
10616 (defvar org-execute-file-search-functions nil
10617 "List of functions to execute a file search triggered by a link.
10619 Functions added to this hook must accept a single argument, the
10620 search string that was part of the file link, the part after the
10621 double colon. The function must first check if it would like to
10622 handle this search, for example by checking the `major-mode' or
10623 the file extension. If it decides not to handle this search, it
10624 should just return nil to give other functions a chance. If it
10625 does handle the search, it must return a non-nil value to keep
10626 other functions from trying.
10628 Each function can access the current prefix argument through the
10629 variable `current-prefix-arg'. Note that a single prefix is used
10630 to force opening a link in Emacs, so it may be good to only use a
10631 numeric or double prefix to guide the search function.
10633 In case this is needed, a function in this hook can also restore
10634 the window configuration before `org-open-at-point' was called using:
10636 (set-window-configuration org-window-config-before-follow-link)")
10638 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10639 (defun org-link-search (s &optional type avoid-pos stealth)
10640 "Search for a link search option.
10641 If S is surrounded by forward slashes, it is interpreted as a
10642 regular expression. In org-mode files, this will create an `org-occur'
10643 sparse tree. In ordinary files, `occur' will be used to list matches.
10644 If the current buffer is in `dired-mode', grep will be used to search
10645 in all files. If AVOID-POS is given, ignore matches near that position.
10647 When optional argument STEALTH is non-nil, do not modify
10648 visibility around point, thus ignoring
10649 `org-show-hierarchy-above', `org-show-following-heading' and
10650 `org-show-siblings' variables."
10651 (let ((case-fold-search t)
10652 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10653 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10654 (append '(("") (" ") ("\t") ("\n"))
10655 org-emphasis-alist)
10656 "\\|") "\\)"))
10657 (pos (point))
10658 (pre nil) (post nil)
10659 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10660 (cond
10661 ;; First check if there are any special search functions
10662 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10663 ;; Now try the builtin stuff
10664 ((and (equal (string-to-char s0) ?#)
10665 (> (length s0) 1)
10666 (save-excursion
10667 (goto-char (point-min))
10668 (and
10669 (re-search-forward
10670 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10671 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10672 (setq type 'dedicated
10673 pos (match-beginning 0))))
10674 ;; There is an exact target for this
10675 (goto-char pos)
10676 (org-back-to-heading t)))
10677 ((save-excursion
10678 (goto-char (point-min))
10679 (and
10680 (re-search-forward
10681 (concat "<<" (regexp-quote s0) ">>") nil t)
10682 (setq type 'dedicated
10683 pos (match-beginning 0))))
10684 ;; There is an exact target for this
10685 (goto-char pos))
10686 ((save-excursion
10687 (goto-char (point-min))
10688 (and
10689 (re-search-forward
10690 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10691 (setq type 'dedicated pos (match-beginning 0))))
10692 ;; Found an element with a matching #+name affiliated keyword.
10693 (goto-char pos))
10694 ((and (string-match "^(\\(.*\\))$" s0)
10695 (save-excursion
10696 (goto-char (point-min))
10697 (and
10698 (re-search-forward
10699 (concat "[^[]" (regexp-quote
10700 (format org-coderef-label-format
10701 (match-string 1 s0))))
10702 nil t)
10703 (setq type 'dedicated
10704 pos (1+ (match-beginning 0))))))
10705 ;; There is a coderef target for this
10706 (goto-char pos))
10707 ((string-match "^/\\(.*\\)/$" s)
10708 ;; A regular expression
10709 (cond
10710 ((derived-mode-p 'org-mode)
10711 (org-occur (match-string 1 s)))
10712 (t (org-do-occur (match-string 1 s)))))
10713 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10714 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10715 (goto-char (point-min))
10716 (cond
10717 ((let (case-fold-search)
10718 (re-search-forward (format org-complex-heading-regexp-format
10719 (regexp-quote s))
10720 nil t))
10721 ;; OK, found a match
10722 (setq type 'dedicated)
10723 (goto-char (match-beginning 0)))
10724 ((and (not org-link-search-inhibit-query)
10725 (eq org-link-search-must-match-exact-headline 'query-to-create)
10726 (y-or-n-p "No match - create this as a new heading? "))
10727 (goto-char (point-max))
10728 (or (bolp) (newline))
10729 (insert "* " s "\n")
10730 (beginning-of-line 0))
10732 (goto-char pos)
10733 (error "No match"))))
10735 ;; A normal search string
10736 (when (equal (string-to-char s) ?*)
10737 ;; Anchor on headlines, post may include tags.
10738 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10739 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10740 s (substring s 1)))
10741 (remove-text-properties
10742 0 (length s)
10743 '(face nil mouse-face nil keymap nil fontified nil) s)
10744 ;; Make a series of regular expressions to find a match
10745 (setq words (org-split-string s "[ \n\r\t]+")
10747 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10748 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10749 "\\)" markers)
10750 re2a_ (concat "\\(" (mapconcat 'downcase words
10751 "[ \t\r\n]+") "\\)[ \t\r\n]")
10752 re2a (concat "[ \t\r\n]" re2a_)
10753 re4_ (concat "\\(" (mapconcat 'downcase words
10754 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10755 re4 (concat "[^a-zA-Z_]" re4_)
10757 re1 (concat pre re2 post)
10758 re3 (concat pre (if pre re4_ re4) post)
10759 re5 (concat pre ".*" re4)
10760 re2 (concat pre re2)
10761 re2a (concat pre (if pre re2a_ re2a))
10762 re4 (concat pre (if pre re4_ re4))
10763 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10764 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10765 re5 "\\)"))
10766 (cond
10767 ((eq type 'org-occur) (org-occur reall))
10768 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10769 (t (goto-char (point-min))
10770 (setq type 'fuzzy)
10771 (if (or (and (org-search-not-self 1 re0 nil t)
10772 (setq type 'dedicated))
10773 (org-search-not-self 1 re1 nil t)
10774 (org-search-not-self 1 re2 nil t)
10775 (org-search-not-self 1 re2a nil t)
10776 (org-search-not-self 1 re3 nil t)
10777 (org-search-not-self 1 re4 nil t)
10778 (org-search-not-self 1 re5 nil t))
10779 (goto-char (match-beginning 1))
10780 (goto-char pos)
10781 (error "No match"))))))
10782 (and (derived-mode-p 'org-mode)
10783 (not stealth)
10784 (org-show-context 'link-search))
10785 type))
10787 (defun org-search-not-self (group &rest args)
10788 "Execute `re-search-forward', but only accept matches that do not
10789 enclose the position of `org-open-link-marker'."
10790 (let ((m org-open-link-marker))
10791 (catch 'exit
10792 (while (apply 're-search-forward args)
10793 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10794 (goto-char (match-end group))
10795 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10796 (> (match-beginning 0) (marker-position m))
10797 (< (match-end 0) (marker-position m)))
10798 (save-match-data
10799 (or (not (org-in-regexp
10800 org-bracket-link-analytic-regexp 1))
10801 (not (match-end 4)) ; no description
10802 (and (<= (match-beginning 4) (point))
10803 (>= (match-end 4) (point))))))
10804 (throw 'exit (point))))))))
10806 (defun org-get-buffer-for-internal-link (buffer)
10807 "Return a buffer to be used for displaying the link target of internal links."
10808 (cond
10809 ((not org-display-internal-link-with-indirect-buffer)
10810 buffer)
10811 ((string-match "(Clone)$" (buffer-name buffer))
10812 (message "Buffer is already a clone, not making another one")
10813 ;; we also do not modify visibility in this case
10814 buffer)
10815 (t ; make a new indirect buffer for displaying the link
10816 (let* ((bn (buffer-name buffer))
10817 (ibn (concat bn "(Clone)"))
10818 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10819 (with-current-buffer ib (org-overview))
10820 ib))))
10822 (defun org-do-occur (regexp &optional cleanup)
10823 "Call the Emacs command `occur'.
10824 If CLEANUP is non-nil, remove the printout of the regular expression
10825 in the *Occur* buffer. This is useful if the regex is long and not useful
10826 to read."
10827 (occur regexp)
10828 (when cleanup
10829 (let ((cwin (selected-window)) win beg end)
10830 (when (setq win (get-buffer-window "*Occur*"))
10831 (select-window win))
10832 (goto-char (point-min))
10833 (when (re-search-forward "match[a-z]+" nil t)
10834 (setq beg (match-end 0))
10835 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10836 (setq end (1- (match-beginning 0)))))
10837 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10838 (goto-char (point-min))
10839 (select-window cwin))))
10841 ;;; The mark ring for links jumps
10843 (defvar org-mark-ring nil
10844 "Mark ring for positions before jumps in Org-mode.")
10845 (defvar org-mark-ring-last-goto nil
10846 "Last position in the mark ring used to go back.")
10847 ;; Fill and close the ring
10848 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10849 (loop for i from 1 to org-mark-ring-length do
10850 (push (make-marker) org-mark-ring))
10851 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10852 org-mark-ring)
10854 (defun org-mark-ring-push (&optional pos buffer)
10855 "Put the current position or POS into the mark ring and rotate it."
10856 (interactive)
10857 (setq pos (or pos (point)))
10858 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10859 (move-marker (car org-mark-ring)
10860 (or pos (point))
10861 (or buffer (current-buffer)))
10862 (message "%s"
10863 (substitute-command-keys
10864 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10866 (defun org-mark-ring-goto (&optional n)
10867 "Jump to the previous position in the mark ring.
10868 With prefix arg N, jump back that many stored positions. When
10869 called several times in succession, walk through the entire ring.
10870 Org-mode commands jumping to a different position in the current file,
10871 or to another Org-mode file, automatically push the old position
10872 onto the ring."
10873 (interactive "p")
10874 (let (p m)
10875 (if (eq last-command this-command)
10876 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10877 (setq p org-mark-ring))
10878 (setq org-mark-ring-last-goto p)
10879 (setq m (car p))
10880 (org-pop-to-buffer-same-window (marker-buffer m))
10881 (goto-char m)
10882 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10884 (defun org-remove-angle-brackets (s)
10885 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10886 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10888 (defun org-add-angle-brackets (s)
10889 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10890 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10892 (defun org-remove-double-quotes (s)
10893 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10894 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10897 ;;; Following specific links
10899 (defun org-follow-timestamp-link ()
10900 "Open an agenda view for the time-stamp date/range at point."
10901 (cond
10902 ((org-at-date-range-p t)
10903 (let ((org-agenda-start-on-weekday)
10904 (t1 (match-string 1))
10905 (t2 (match-string 2)) tt1 tt2)
10906 (setq tt1 (time-to-days (org-time-string-to-time t1))
10907 tt2 (time-to-days (org-time-string-to-time t2)))
10908 (let ((org-agenda-buffer-tmp-name
10909 (format "*Org Agenda(a:%s)"
10910 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10911 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10912 ((org-at-timestamp-p t)
10913 (let ((org-agenda-buffer-tmp-name
10914 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10915 (org-agenda-list nil (time-to-days (org-time-string-to-time
10916 (substring (match-string 1) 0 10)))
10917 1)))
10918 (t (error "This should not happen"))))
10921 ;;; Following file links
10922 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10923 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10924 (declare-function mailcap-mime-info
10925 "mailcap" (string &optional request no-decode))
10926 (defvar org-wait nil)
10927 (defun org-open-file (path &optional in-emacs line search)
10928 "Open the file at PATH.
10929 First, this expands any special file name abbreviations. Then the
10930 configuration variable `org-file-apps' is checked if it contains an
10931 entry for this file type, and if yes, the corresponding command is launched.
10933 If no application is found, Emacs simply visits the file.
10935 With optional prefix argument IN-EMACS, Emacs will visit the file.
10936 With a double \\[universal-argument] \\[universal-argument] \
10937 prefix arg, Org tries to avoid opening in Emacs
10938 and to use an external application to visit the file.
10940 Optional LINE specifies a line to go to, optional SEARCH a string
10941 to search for. If LINE or SEARCH is given, the file will be
10942 opened in Emacs, unless an entry from org-file-apps that makes
10943 use of groups in a regexp matches.
10945 If you want to change the way frames are used when following a
10946 link, please customize `org-link-frame-setup'.
10948 If the file does not exist, an error is thrown."
10949 (let* ((file (if (equal path "")
10950 buffer-file-name
10951 (substitute-in-file-name (expand-file-name path))))
10952 (file-apps (append org-file-apps (org-default-apps)))
10953 (apps (org-remove-if
10954 'org-file-apps-entry-match-against-dlink-p file-apps))
10955 (apps-dlink (org-remove-if-not
10956 'org-file-apps-entry-match-against-dlink-p file-apps))
10957 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10958 (dirp (if remp nil (file-directory-p file)))
10959 (file (if (and dirp org-open-directory-means-index-dot-org)
10960 (concat (file-name-as-directory file) "index.org")
10961 file))
10962 (a-m-a-p (assq 'auto-mode apps))
10963 (dfile (downcase file))
10964 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10965 (link (cond ((and (eq line nil)
10966 (eq search nil))
10967 file)
10968 (line
10969 (concat file "::" (number-to-string line)))
10970 (search
10971 (concat file "::" search))))
10972 (dlink (downcase link))
10973 (old-buffer (current-buffer))
10974 (old-pos (point))
10975 (old-mode major-mode)
10976 ext cmd link-match-data)
10977 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10978 (setq ext (match-string 1 dfile))
10979 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10980 (setq ext (match-string 1 dfile))))
10981 (cond
10982 ((member in-emacs '((16) system))
10983 (setq cmd (cdr (assoc 'system apps))))
10984 (in-emacs (setq cmd 'emacs))
10986 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10987 (and dirp (cdr (assoc 'directory apps)))
10988 ; first, try matching against apps-dlink
10989 ; if we get a match here, store the match data for later
10990 (let ((match (assoc-default dlink apps-dlink
10991 'string-match)))
10992 (if match
10993 (progn (setq link-match-data (match-data))
10994 match)
10995 (progn (setq in-emacs (or in-emacs line search))
10996 nil))) ; if we have no match in apps-dlink,
10997 ; always open the file in emacs if line or search
10998 ; is given (for backwards compatibility)
10999 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11000 'string-match)
11001 (cdr (assoc ext apps))
11002 (cdr (assoc t apps))))))
11003 (when (eq cmd 'system)
11004 (setq cmd (cdr (assoc 'system apps))))
11005 (when (eq cmd 'default)
11006 (setq cmd (cdr (assoc t apps))))
11007 (when (eq cmd 'mailcap)
11008 (require 'mailcap)
11009 (mailcap-parse-mailcaps)
11010 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11011 (command (mailcap-mime-info mime-type)))
11012 (if (stringp command)
11013 (setq cmd command)
11014 (setq cmd 'emacs))))
11015 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11016 (not (file-exists-p file))
11017 (not org-open-non-existing-files))
11018 (user-error "No such file: %s" file))
11019 (cond
11020 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11021 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11022 (while (string-match "['\"]%s['\"]" cmd)
11023 (setq cmd (replace-match "%s" t t cmd)))
11024 (while (string-match "%s" cmd)
11025 (setq cmd (replace-match
11026 (save-match-data
11027 (shell-quote-argument
11028 (convert-standard-filename file)))
11029 t t cmd)))
11031 ;; Replace "%1", "%2" etc. in command with group matches from regex
11032 (save-match-data
11033 (let ((match-index 1)
11034 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11035 (set-match-data link-match-data)
11036 (while (<= match-index number-of-groups)
11037 (let ((regex (concat "%" (number-to-string match-index)))
11038 (replace-with (match-string match-index dlink)))
11039 (while (string-match regex cmd)
11040 (setq cmd (replace-match replace-with t t cmd))))
11041 (setq match-index (+ match-index 1)))))
11043 (save-window-excursion
11044 (message "Running %s...done" cmd)
11045 (start-process-shell-command cmd nil cmd)
11046 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11047 ((or (stringp cmd)
11048 (eq cmd 'emacs))
11049 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11050 (widen)
11051 (if line (org-goto-line line)
11052 (if search (org-link-search search))))
11053 ((consp cmd)
11054 (let ((file (convert-standard-filename file)))
11055 (save-match-data
11056 (set-match-data link-match-data)
11057 (eval cmd))))
11058 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11059 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11060 (or (not (equal old-buffer (current-buffer)))
11061 (not (equal old-pos (point))))
11062 (org-mark-ring-push old-pos old-buffer))))
11064 (defun org-file-apps-entry-match-against-dlink-p (entry)
11065 "This function returns non-nil if `entry' uses a regular
11066 expression which should be matched against the whole link by
11067 org-open-file.
11069 It assumes that is the case when the entry uses a regular
11070 expression which has at least one grouping construct and the
11071 action is either a lisp form or a command string containing
11072 '%1', i.e. using at least one subexpression match as a
11073 parameter."
11074 (let ((selector (car entry))
11075 (action (cdr entry)))
11076 (if (stringp selector)
11077 (and (> (regexp-opt-depth selector) 0)
11078 (or (and (stringp action)
11079 (string-match "%[0-9]" action))
11080 (consp action)))
11081 nil)))
11083 (defun org-default-apps ()
11084 "Return the default applications for this operating system."
11085 (cond
11086 ((eq system-type 'darwin)
11087 org-file-apps-defaults-macosx)
11088 ((eq system-type 'windows-nt)
11089 org-file-apps-defaults-windowsnt)
11090 (t org-file-apps-defaults-gnu)))
11092 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11093 "Convert extensions to regular expressions in the cars of LIST.
11094 Also, weed out any non-string entries, because the return value is used
11095 only for regexp matching.
11096 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11097 point to the symbol `emacs', indicating that the file should
11098 be opened in Emacs."
11099 (append
11100 (delq nil
11101 (mapcar (lambda (x)
11102 (if (not (stringp (car x)))
11104 (if (string-match "\\W" (car x))
11106 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11107 list))
11108 (if add-auto-mode
11109 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11111 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11112 (defun org-file-remote-p (file)
11113 "Test whether FILE specifies a location on a remote system.
11114 Return non-nil if the location is indeed remote.
11116 For example, the filename \"/user@host:/foo\" specifies a location
11117 on the system \"/user@host:\"."
11118 (cond ((fboundp 'file-remote-p)
11119 (file-remote-p file))
11120 ((fboundp 'tramp-handle-file-remote-p)
11121 (tramp-handle-file-remote-p file))
11122 ((and (boundp 'ange-ftp-name-format)
11123 (string-match (car ange-ftp-name-format) file))
11124 t)))
11127 ;;;; Refiling
11129 (defun org-get-org-file ()
11130 "Read a filename, with default directory `org-directory'."
11131 (let ((default (or org-default-notes-file remember-data-file)))
11132 (read-file-name (format "File name [%s]: " default)
11133 (file-name-as-directory org-directory)
11134 default)))
11136 (defun org-notes-order-reversed-p ()
11137 "Check if the current file should receive notes in reversed order."
11138 (cond
11139 ((not org-reverse-note-order) nil)
11140 ((eq t org-reverse-note-order) t)
11141 ((not (listp org-reverse-note-order)) nil)
11142 (t (catch 'exit
11143 (let ((all org-reverse-note-order)
11144 entry)
11145 (while (setq entry (pop all))
11146 (if (string-match (car entry) buffer-file-name)
11147 (throw 'exit (cdr entry))))
11148 nil)))))
11150 (defvar org-refile-target-table nil
11151 "The list of refile targets, created by `org-refile'.")
11153 (defvar org-agenda-new-buffers nil
11154 "Buffers created to visit agenda files.")
11156 (defvar org-refile-cache nil
11157 "Cache for refile targets.")
11159 (defvar org-refile-markers nil
11160 "All the markers used for caching refile locations.")
11162 (defun org-refile-marker (pos)
11163 "Get a new refile marker, but only if caching is in use."
11164 (if (not org-refile-use-cache)
11166 (let ((m (make-marker)))
11167 (move-marker m pos)
11168 (push m org-refile-markers)
11169 m)))
11171 (defun org-refile-cache-clear ()
11172 "Clear the refile cache and disable all the markers."
11173 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11174 (setq org-refile-markers nil)
11175 (setq org-refile-cache nil)
11176 (message "Refile cache has been cleared"))
11178 (defun org-refile-cache-check-set (set)
11179 "Check if all the markers in the cache still have live buffers."
11180 (let (marker)
11181 (catch 'exit
11182 (while (and set (setq marker (nth 3 (pop set))))
11183 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11184 (when (and marker (null (marker-buffer marker)))
11185 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11186 (sit-for 3)
11187 (throw 'exit nil)))
11188 t)))
11190 (defun org-refile-cache-put (set &rest identifiers)
11191 "Push the refile targets SET into the cache, under IDENTIFIERS."
11192 (let* ((key (sha1 (prin1-to-string identifiers)))
11193 (entry (assoc key org-refile-cache)))
11194 (if entry
11195 (setcdr entry set)
11196 (push (cons key set) org-refile-cache))))
11198 (defun org-refile-cache-get (&rest identifiers)
11199 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11200 (cond
11201 ((not org-refile-cache) nil)
11202 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11204 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11205 org-refile-cache))))
11206 (and set (org-refile-cache-check-set set) set)))))
11208 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11209 "Produce a table with refile targets."
11210 (let ((case-fold-search nil)
11211 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11212 (entries (or org-refile-targets '((nil . (:level . 1)))))
11213 targets tgs txt re files f desc descre fast-path-p level pos0)
11214 (message "Getting targets...")
11215 (with-current-buffer (or default-buffer (current-buffer))
11216 (while (setq entry (pop entries))
11217 (setq files (car entry) desc (cdr entry))
11218 (setq fast-path-p nil)
11219 (cond
11220 ((null files) (setq files (list (current-buffer))))
11221 ((eq files 'org-agenda-files)
11222 (setq files (org-agenda-files 'unrestricted)))
11223 ((and (symbolp files) (fboundp files))
11224 (setq files (funcall files)))
11225 ((and (symbolp files) (boundp files))
11226 (setq files (symbol-value files))))
11227 (if (stringp files) (setq files (list files)))
11228 (cond
11229 ((eq (car desc) :tag)
11230 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11231 ((eq (car desc) :todo)
11232 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11233 ((eq (car desc) :regexp)
11234 (setq descre (cdr desc)))
11235 ((eq (car desc) :level)
11236 (setq descre (concat "^\\*\\{" (number-to-string
11237 (if org-odd-levels-only
11238 (1- (* 2 (cdr desc)))
11239 (cdr desc)))
11240 "\\}[ \t]")))
11241 ((eq (car desc) :maxlevel)
11242 (setq fast-path-p t)
11243 (setq descre (concat "^\\*\\{1," (number-to-string
11244 (if org-odd-levels-only
11245 (1- (* 2 (cdr desc)))
11246 (cdr desc)))
11247 "\\}[ \t]")))
11248 (t (error "Bad refiling target description %s" desc)))
11249 (while (setq f (pop files))
11250 (with-current-buffer
11251 (if (bufferp f) f (org-get-agenda-file-buffer f))
11253 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11254 (progn
11255 (if (bufferp f) (setq f (buffer-file-name
11256 (buffer-base-buffer f))))
11257 (setq f (and f (expand-file-name f)))
11258 (if (eq org-refile-use-outline-path 'file)
11259 (push (list (file-name-nondirectory f) f nil nil) tgs))
11260 (save-excursion
11261 (save-restriction
11262 (widen)
11263 (goto-char (point-min))
11264 (while (re-search-forward descre nil t)
11265 (goto-char (setq pos0 (point-at-bol)))
11266 (catch 'next
11267 (when org-refile-target-verify-function
11268 (save-match-data
11269 (or (funcall org-refile-target-verify-function)
11270 (throw 'next t))))
11271 (when (and (looking-at org-complex-heading-regexp)
11272 (not (member (match-string 4) excluded-entries))
11273 (match-string 4))
11274 (setq level (org-reduced-level
11275 (- (match-end 1) (match-beginning 1)))
11276 txt (org-link-display-format (match-string 4))
11277 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11278 re (format org-complex-heading-regexp-format
11279 (regexp-quote (match-string 4))))
11280 (when org-refile-use-outline-path
11281 (setq txt (mapconcat
11282 'org-protect-slash
11283 (append
11284 (if (eq org-refile-use-outline-path
11285 'file)
11286 (list (file-name-nondirectory
11287 (buffer-file-name
11288 (buffer-base-buffer))))
11289 (if (eq org-refile-use-outline-path
11290 'full-file-path)
11291 (list (buffer-file-name
11292 (buffer-base-buffer)))))
11293 (org-get-outline-path fast-path-p
11294 level txt)
11295 (list txt))
11296 "/")))
11297 (push (list txt f re (org-refile-marker (point)))
11298 tgs)))
11299 (when (= (point) pos0)
11300 ;; verification function has not moved point
11301 (goto-char (point-at-eol))))))))
11302 (when org-refile-use-cache
11303 (org-refile-cache-put tgs (buffer-file-name) descre))
11304 (setq targets (append tgs targets))))))
11305 (message "Getting targets...done")
11306 (nreverse targets)))
11308 (defun org-protect-slash (s)
11309 (while (string-match "/" s)
11310 (setq s (replace-match "\\" t t s)))
11313 (defvar org-olpa (make-vector 20 nil))
11315 (defun org-get-outline-path (&optional fastp level heading)
11316 "Return the outline path to the current entry, as a list.
11318 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11319 routine which makes outline path derivations for an entire file,
11320 avoiding backtracing. Refile target collection makes use of that."
11321 (if fastp
11322 (progn
11323 (if (> level 19)
11324 (error "Outline path failure, more than 19 levels"))
11325 (loop for i from level upto 19 do
11326 (aset org-olpa i nil))
11327 (prog1
11328 (delq nil (append org-olpa nil))
11329 (aset org-olpa level heading)))
11330 (let (rtn case-fold-search)
11331 (save-excursion
11332 (save-restriction
11333 (widen)
11334 (while (org-up-heading-safe)
11335 (when (looking-at org-complex-heading-regexp)
11336 (push (org-trim
11337 (replace-regexp-in-string
11338 ;; Remove statistical/checkboxes cookies
11339 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11340 (org-match-string-no-properties 4)))
11341 rtn)))
11342 rtn)))))
11344 (defun org-format-outline-path (path &optional width prefix separator)
11345 "Format the outline path PATH for display.
11346 WIDTH is the maximum number of characters that is available.
11347 PREFIX is a prefix to be included in the returned string,
11348 such as the file name.
11349 SEPARATOR is inserted between the different parts of the path,
11350 the default is \"/\"."
11351 (setq width (or width 79))
11352 (if prefix (setq width (- width (length prefix))))
11353 (if (not path)
11354 (or prefix "")
11355 (let* ((nsteps (length path))
11356 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11357 (maxwidth (if (<= total-width width)
11358 10000 ;; everything fits
11359 ;; we need to shorten the level headings
11360 (/ (- width nsteps) nsteps)))
11361 (org-odd-levels-only nil)
11362 (n 0)
11363 (total (1+ (length prefix))))
11364 (setq maxwidth (max maxwidth 10))
11365 (concat prefix
11366 (if prefix (or separator "/"))
11367 (mapconcat
11368 (lambda (h)
11369 (setq n (1+ n))
11370 (if (and (= n nsteps) (< maxwidth 10000))
11371 (setq maxwidth (- total-width total)))
11372 (if (< (length h) maxwidth)
11373 (progn (setq total (+ total (length h) 1)) h)
11374 (setq h (substring h 0 (- maxwidth 2))
11375 total (+ total maxwidth 1))
11376 (if (string-match "[ \t]+\\'" h)
11377 (setq h (substring h 0 (match-beginning 0))))
11378 (setq h (concat h "..")))
11379 (org-add-props h nil 'face
11380 (nth (% (1- n) org-n-level-faces)
11381 org-level-faces))
11383 path (or separator "/"))))))
11385 (defun org-display-outline-path (&optional file current separator just-return-string)
11386 "Display the current outline path in the echo area.
11388 If FILE is non-nil, prepend the output with the file name.
11389 If CURRENT is non-nil, append the current heading to the output.
11390 SEPARATOR is passed through to `org-format-outline-path'. It separates
11391 the different parts of the path and defaults to \"/\".
11392 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11393 (interactive "P")
11394 (let* (case-fold-search
11395 message-log-max ; Don't populate the *Messages* buffer
11396 (bfn (buffer-file-name (buffer-base-buffer)))
11397 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11398 res)
11399 (if current (setq path (append path
11400 (save-excursion
11401 (org-back-to-heading t)
11402 (if (looking-at org-complex-heading-regexp)
11403 (list (match-string 4)))))))
11404 (setq res
11405 (org-format-outline-path
11406 path
11407 (1- (frame-width))
11408 (and file bfn (concat (file-name-nondirectory bfn) separator))
11409 separator))
11410 (if just-return-string
11411 (org-no-properties res)
11412 (message "%s" res))))
11414 (defvar org-refile-history nil
11415 "History for refiling operations.")
11417 (defvar org-after-refile-insert-hook nil
11418 "Hook run after `org-refile' has inserted its stuff at the new location.
11419 Note that this is still *before* the stuff will be removed from
11420 the *old* location.")
11422 (defvar org-capture-last-stored-marker)
11423 (defvar org-refile-keep nil
11424 "Non-nil means `org-refile' will copy instead of refile.")
11426 (defun org-copy ()
11427 "Like `org-refile', but copy."
11428 (interactive)
11429 (let ((org-refile-keep t))
11430 (funcall 'org-refile nil nil nil "Copy")))
11432 (defun org-refile (&optional goto default-buffer rfloc msg)
11433 "Move the entry or entries at point to another heading.
11434 The list of target headings is compiled using the information in
11435 `org-refile-targets', which see.
11437 At the target location, the entry is filed as a subitem of the target
11438 heading. Depending on `org-reverse-note-order', the new subitem will
11439 either be the first or the last subitem.
11441 If there is an active region, all entries in that region will be moved.
11442 However, the region must fulfill the requirement that the first heading
11443 is the first one sets the top-level of the moved text - at most siblings
11444 below it are allowed.
11446 With prefix arg GOTO, the command will only visit the target location
11447 and not actually move anything.
11449 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11450 go to the location where the last refiling operation has put the subtree.
11451 With a prefix argument of `2', refile to the running clock.
11453 RFLOC can be a refile location obtained in a different way.
11455 MSG is a string to replace \"Refile\" in the default prompt with
11456 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11458 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11460 If you are using target caching (see `org-refile-use-cache'),
11461 you have to clear the target cache in order to find new targets.
11462 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11463 prefix argument (`C-u C-u C-u C-c C-w')."
11465 (interactive "P")
11466 (if (member goto '(0 (64)))
11467 (org-refile-cache-clear)
11468 (let* ((actionmsg (or msg "Refile"))
11469 (cbuf (current-buffer))
11470 (regionp (org-region-active-p))
11471 (region-start (and regionp (region-beginning)))
11472 (region-end (and regionp (region-end)))
11473 (region-length (and regionp (- region-end region-start)))
11474 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11475 pos it nbuf file re level reversed)
11476 (setq last-command nil)
11477 (when regionp
11478 (goto-char region-start)
11479 (or (bolp) (goto-char (point-at-bol)))
11480 (setq region-start (point))
11481 (unless (or (org-kill-is-subtree-p
11482 (buffer-substring region-start region-end))
11483 (prog1 org-refile-active-region-within-subtree
11484 (org-toggle-heading)))
11485 (user-error "The region is not a (sequence of) subtree(s)")))
11486 (if (equal goto '(16))
11487 (org-refile-goto-last-stored)
11488 (when (or
11489 (and (equal goto 2)
11490 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11491 (prog1
11492 (setq it (list (or org-clock-heading "running clock")
11493 (buffer-file-name
11494 (marker-buffer org-clock-hd-marker))
11496 (marker-position org-clock-hd-marker)))
11497 (setq goto nil)))
11498 (setq it (or rfloc
11499 (let (heading-text)
11500 (save-excursion
11501 (unless goto
11502 (org-back-to-heading t)
11503 (setq heading-text
11504 (nth 4 (org-heading-components))))
11506 (org-refile-get-location
11507 (cond (goto "Goto")
11508 (regionp (concat actionmsg " region to"))
11509 (t (concat actionmsg " subtree \""
11510 heading-text "\" to")))
11511 default-buffer
11512 (and (not (equal '(4) goto))
11513 org-refile-allow-creating-parent-nodes)
11514 goto))))))
11515 (setq file (nth 1 it)
11516 re (nth 2 it)
11517 pos (nth 3 it))
11518 (if (and (not goto)
11520 (equal (buffer-file-name) file)
11521 (if regionp
11522 (and (>= pos region-start)
11523 (<= pos region-end))
11524 (and (>= pos (point))
11525 (< pos (save-excursion
11526 (org-end-of-subtree t t))))))
11527 (error "Cannot refile to position inside the tree or region"))
11529 (setq nbuf (or (find-buffer-visiting file)
11530 (find-file-noselect file)))
11531 (if goto
11532 (progn
11533 (org-pop-to-buffer-same-window nbuf)
11534 (goto-char pos)
11535 (org-show-context 'org-goto))
11536 (if regionp
11537 (progn
11538 (org-kill-new (buffer-substring region-start region-end))
11539 (org-save-markers-in-region region-start region-end))
11540 (org-copy-subtree 1 nil t))
11541 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11542 (find-file-noselect file)))
11543 (setq reversed (org-notes-order-reversed-p))
11544 (save-excursion
11545 (save-restriction
11546 (widen)
11547 (if pos
11548 (progn
11549 (goto-char pos)
11550 (looking-at org-outline-regexp)
11551 (setq level (org-get-valid-level (funcall outline-level) 1))
11552 (goto-char
11553 (if reversed
11554 (or (outline-next-heading) (point-max))
11555 (or (save-excursion (org-get-next-sibling))
11556 (org-end-of-subtree t t)
11557 (point-max)))))
11558 (setq level 1)
11559 (if (not reversed)
11560 (goto-char (point-max))
11561 (goto-char (point-min))
11562 (or (outline-next-heading) (goto-char (point-max)))))
11563 (if (not (bolp)) (newline))
11564 (org-paste-subtree level)
11565 (when org-log-refile
11566 (org-add-log-setup 'refile nil nil 'findpos
11567 org-log-refile)
11568 (unless (eq org-log-refile 'note)
11569 (save-excursion (org-add-log-note))))
11570 (and org-auto-align-tags
11571 (let ((org-loop-over-headlines-in-active-region nil))
11572 (org-set-tags nil t)))
11573 (with-demoted-errors
11574 (bookmark-set "org-refile-last-stored"))
11575 ;; If we are refiling for capture, make sure that the
11576 ;; last-capture pointers point here
11577 (when (org-bound-and-true-p org-refile-for-capture)
11578 (with-demoted-errors
11579 (bookmark-set "org-capture-last-stored-marker"))
11580 (move-marker org-capture-last-stored-marker (point)))
11581 (if (fboundp 'deactivate-mark) (deactivate-mark))
11582 (run-hooks 'org-after-refile-insert-hook))))
11583 (unless org-refile-keep
11584 (if regionp
11585 (delete-region (point) (+ (point) region-length))
11586 (org-cut-subtree)))
11587 (when (featurep 'org-inlinetask)
11588 (org-inlinetask-remove-END-maybe))
11589 (setq org-markers-to-move nil)
11590 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11592 (defun org-refile-goto-last-stored ()
11593 "Go to the location where the last refile was stored."
11594 (interactive)
11595 (bookmark-jump "org-refile-last-stored")
11596 (message "This is the location of the last refile"))
11598 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11599 no-exclude)
11600 "Prompt the user for a refile location, using PROMPT.
11601 PROMPT should not be suffixed with a colon and a space, because
11602 this function appends the default value from
11603 `org-refile-history' automatically, if that is not empty.
11604 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11605 this is used for the GOTO interface."
11606 (let ((org-refile-targets org-refile-targets)
11607 (org-refile-use-outline-path org-refile-use-outline-path)
11608 excluded-entries)
11609 (when (and (derived-mode-p 'org-mode)
11610 (not org-refile-use-cache)
11611 (not no-exclude))
11612 (org-map-tree
11613 (lambda()
11614 (setq excluded-entries
11615 (append excluded-entries (list (org-get-heading t t)))))))
11616 (setq org-refile-target-table
11617 (org-refile-get-targets default-buffer excluded-entries)))
11618 (unless org-refile-target-table
11619 (user-error "No refile targets"))
11620 (let* ((cbuf (current-buffer))
11621 (partial-completion-mode nil)
11622 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11623 (cfunc (if (and org-refile-use-outline-path
11624 org-outline-path-complete-in-steps)
11625 'org-olpath-completing-read
11626 'org-icompleting-read))
11627 (extra (if org-refile-use-outline-path "/" ""))
11628 (cbnex (concat (buffer-name) extra))
11629 (filename (and cfn (expand-file-name cfn)))
11630 (tbl (mapcar
11631 (lambda (x)
11632 (if (and (not (member org-refile-use-outline-path
11633 '(file full-file-path)))
11634 (not (equal filename (nth 1 x))))
11635 (cons (concat (car x) extra " ("
11636 (file-name-nondirectory (nth 1 x)) ")")
11637 (cdr x))
11638 (cons (concat (car x) extra) (cdr x))))
11639 org-refile-target-table))
11640 (completion-ignore-case t)
11641 cdef
11642 (prompt (concat prompt
11643 (or (and (car org-refile-history)
11644 (concat " (default " (car org-refile-history) ")"))
11645 (and (assoc cbnex tbl) (setq cdef cbnex)
11646 (concat " (default " cbnex ")"))) ": "))
11647 pa answ parent-target child parent old-hist)
11648 (setq old-hist org-refile-history)
11649 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11650 nil 'org-refile-history (or cdef (car org-refile-history))))
11651 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11652 (org-refile-check-position pa)
11653 (if pa
11654 (progn
11655 (when (or (not org-refile-history)
11656 (not (eq old-hist org-refile-history))
11657 (not (equal (car pa) (car org-refile-history))))
11658 (setq org-refile-history
11659 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11660 org-refile-history
11661 (cdr org-refile-history))))
11662 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11663 (pop org-refile-history)))
11665 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11666 (progn
11667 (setq parent (match-string 1 answ)
11668 child (match-string 2 answ))
11669 (setq parent-target (or (assoc parent tbl)
11670 (assoc (concat parent "/") tbl)))
11671 (when (and parent-target
11672 (or (eq new-nodes t)
11673 (and (eq new-nodes 'confirm)
11674 (y-or-n-p (format "Create new node \"%s\"? "
11675 child)))))
11676 (org-refile-new-child parent-target child)))
11677 (user-error "Invalid target location")))))
11679 (declare-function org-string-nw-p "org-macs" (s))
11680 (defun org-refile-check-position (refile-pointer)
11681 "Check if the refile pointer matches the headline to which it points."
11682 (let* ((file (nth 1 refile-pointer))
11683 (re (nth 2 refile-pointer))
11684 (pos (nth 3 refile-pointer))
11685 buffer)
11686 (if (and (not (markerp pos)) (not file))
11687 (user-error "Please save the buffer to a file before refiling")
11688 (when (org-string-nw-p re)
11689 (setq buffer (if (markerp pos)
11690 (marker-buffer pos)
11691 (or (find-buffer-visiting file)
11692 (find-file-noselect file))))
11693 (with-current-buffer buffer
11694 (save-excursion
11695 (save-restriction
11696 (widen)
11697 (goto-char pos)
11698 (beginning-of-line 1)
11699 (unless (org-looking-at-p re)
11700 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11702 (defun org-refile-new-child (parent-target child)
11703 "Use refile target PARENT-TARGET to add new CHILD below it."
11704 (unless parent-target
11705 (error "Cannot find parent for new node"))
11706 (let ((file (nth 1 parent-target))
11707 (pos (nth 3 parent-target))
11708 level)
11709 (with-current-buffer (or (find-buffer-visiting file)
11710 (find-file-noselect file))
11711 (save-excursion
11712 (save-restriction
11713 (widen)
11714 (if pos
11715 (goto-char pos)
11716 (goto-char (point-max))
11717 (if (not (bolp)) (newline)))
11718 (when (looking-at org-outline-regexp)
11719 (setq level (funcall outline-level))
11720 (org-end-of-subtree t t))
11721 (org-back-over-empty-lines)
11722 (insert "\n" (make-string
11723 (if pos (org-get-valid-level level 1) 1) ?*)
11724 " " child "\n")
11725 (beginning-of-line 0)
11726 (list (concat (car parent-target) "/" child) file "" (point)))))))
11728 (defun org-olpath-completing-read (prompt collection &rest args)
11729 "Read an outline path like a file name."
11730 (let ((thetable collection)
11731 (org-completion-use-ido nil) ; does not work with ido.
11732 (org-completion-use-iswitchb nil)) ; or iswitchb
11733 (apply
11734 'org-icompleting-read prompt
11735 (lambda (string predicate &optional flag)
11736 (let (rtn r f (l (length string)))
11737 (cond
11738 ((eq flag nil)
11739 ;; try completion
11740 (try-completion string thetable))
11741 ((eq flag t)
11742 ;; all-completions
11743 (setq rtn (all-completions string thetable predicate))
11744 (mapcar
11745 (lambda (x)
11746 (setq r (substring x l))
11747 (if (string-match " ([^)]*)$" x)
11748 (setq f (match-string 0 x))
11749 (setq f ""))
11750 (if (string-match "/" r)
11751 (concat string (substring r 0 (match-end 0)) f)
11753 rtn))
11754 ((eq flag 'lambda)
11755 ;; exact match?
11756 (assoc string thetable)))))
11757 args)))
11759 ;;;; Dynamic blocks
11761 (defun org-find-dblock (name)
11762 "Find the first dynamic block with name NAME in the buffer.
11763 If not found, stay at current position and return nil."
11764 (let ((case-fold-search t) pos)
11765 (save-excursion
11766 (goto-char (point-min))
11767 (setq pos (and (re-search-forward
11768 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11769 (match-beginning 0))))
11770 (if pos (goto-char pos))
11771 pos))
11773 (defconst org-dblock-start-re
11774 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11775 "Matches the start line of a dynamic block, with parameters.")
11777 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11778 "Matches the end of a dynamic block.")
11780 (defun org-create-dblock (plist)
11781 "Create a dynamic block section, with parameters taken from PLIST.
11782 PLIST must contain a :name entry which is used as name of the block."
11783 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11784 (end-of-line 1)
11785 (newline))
11786 (let ((col (current-column))
11787 (name (plist-get plist :name)))
11788 (insert "#+BEGIN: " name)
11789 (while plist
11790 (if (eq (car plist) :name)
11791 (setq plist (cddr plist))
11792 (insert " " (prin1-to-string (pop plist)))))
11793 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11794 (beginning-of-line -2)))
11796 (defun org-prepare-dblock ()
11797 "Prepare dynamic block for refresh.
11798 This empties the block, puts the cursor at the insert position and returns
11799 the property list including an extra property :name with the block name."
11800 (unless (looking-at org-dblock-start-re)
11801 (user-error "Not at a dynamic block"))
11802 (let* ((begdel (1+ (match-end 0)))
11803 (name (org-no-properties (match-string 1)))
11804 (params (append (list :name name)
11805 (read (concat "(" (match-string 3) ")")))))
11806 (save-excursion
11807 (beginning-of-line 1)
11808 (skip-chars-forward " \t")
11809 (setq params (plist-put params :indentation-column (current-column))))
11810 (unless (re-search-forward org-dblock-end-re nil t)
11811 (error "Dynamic block not terminated"))
11812 (setq params
11813 (append params
11814 (list :content (buffer-substring
11815 begdel (match-beginning 0)))))
11816 (delete-region begdel (match-beginning 0))
11817 (goto-char begdel)
11818 (open-line 1)
11819 params))
11821 (defun org-map-dblocks (&optional command)
11822 "Apply COMMAND to all dynamic blocks in the current buffer.
11823 If COMMAND is not given, use `org-update-dblock'."
11824 (let ((cmd (or command 'org-update-dblock)))
11825 (save-excursion
11826 (goto-char (point-min))
11827 (while (re-search-forward org-dblock-start-re nil t)
11828 (goto-char (match-beginning 0))
11829 (save-excursion
11830 (condition-case nil
11831 (funcall cmd)
11832 (error (message "Error during update of dynamic block"))))
11833 (unless (re-search-forward org-dblock-end-re nil t)
11834 (error "Dynamic block not terminated"))))))
11836 (defun org-dblock-update (&optional arg)
11837 "User command for updating dynamic blocks.
11838 Update the dynamic block at point. With prefix ARG, update all dynamic
11839 blocks in the buffer."
11840 (interactive "P")
11841 (if arg
11842 (org-update-all-dblocks)
11843 (or (looking-at org-dblock-start-re)
11844 (org-beginning-of-dblock))
11845 (org-update-dblock)))
11847 (defun org-update-dblock ()
11848 "Update the dynamic block at point.
11849 This means to empty the block, parse for parameters and then call
11850 the correct writing function."
11851 (interactive)
11852 (save-window-excursion
11853 (let* ((pos (point))
11854 (line (org-current-line))
11855 (params (org-prepare-dblock))
11856 (name (plist-get params :name))
11857 (indent (plist-get params :indentation-column))
11858 (cmd (intern (concat "org-dblock-write:" name))))
11859 (message "Updating dynamic block `%s' at line %d..." name line)
11860 (funcall cmd params)
11861 (message "Updating dynamic block `%s' at line %d...done" name line)
11862 (goto-char pos)
11863 (when (and indent (> indent 0))
11864 (setq indent (make-string indent ?\ ))
11865 (save-excursion
11866 (org-beginning-of-dblock)
11867 (forward-line 1)
11868 (while (not (looking-at org-dblock-end-re))
11869 (insert indent)
11870 (beginning-of-line 2))
11871 (when (looking-at org-dblock-end-re)
11872 (and (looking-at "[ \t]+")
11873 (replace-match ""))
11874 (insert indent)))))))
11876 (defun org-beginning-of-dblock ()
11877 "Find the beginning of the dynamic block at point.
11878 Error if there is no such block at point."
11879 (let ((pos (point))
11880 beg)
11881 (end-of-line 1)
11882 (if (and (re-search-backward org-dblock-start-re nil t)
11883 (setq beg (match-beginning 0))
11884 (re-search-forward org-dblock-end-re nil t)
11885 (> (match-end 0) pos))
11886 (goto-char beg)
11887 (goto-char pos)
11888 (error "Not in a dynamic block"))))
11890 (defun org-update-all-dblocks ()
11891 "Update all dynamic blocks in the buffer.
11892 This function can be used in a hook."
11893 (interactive)
11894 (when (derived-mode-p 'org-mode)
11895 (org-map-dblocks 'org-update-dblock)))
11898 ;;;; Completion
11900 (defun org-get-export-keywords ()
11901 "Return a list of all currently understood export keywords.
11902 Export keywords include options, block names, attributes and
11903 keywords relative to each registered export back-end."
11904 (delq nil
11905 (let (keywords)
11906 (mapc
11907 (lambda (back-end)
11908 (let ((props (cdr back-end)))
11909 ;; Back-end name (for keywords, like #+LATEX:)
11910 (push (upcase (symbol-name (car back-end))) keywords)
11911 ;; Back-end options.
11912 (mapc (lambda (option) (push (cadr option) keywords))
11913 (plist-get (cdr back-end) :options-alist))))
11914 (org-bound-and-true-p org-export-registered-backends))
11915 keywords)))
11917 (defconst org-options-keywords
11918 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11919 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11920 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11921 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11922 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11924 (defcustom org-structure-template-alist
11925 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11926 "<src lang=\"?\">\n\n</src>")
11927 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11928 "<example>\n?\n</example>")
11929 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11930 "<quote>\n?\n</quote>")
11931 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11932 "<verse>\n?\n</verse>")
11933 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11934 "<verbatim>\n?\n</verbatim>")
11935 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11936 "<center>\n?\n</center>")
11937 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11938 "<literal style=\"latex\">\n?\n</literal>")
11939 ("L" "#+LaTeX: "
11940 "<literal style=\"latex\">?</literal>")
11941 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11942 "<literal style=\"html\">\n?\n</literal>")
11943 ("H" "#+HTML: "
11944 "<literal style=\"html\">?</literal>")
11945 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11946 ("A" "#+ASCII: ")
11947 ("i" "#+INDEX: ?"
11948 "#+INDEX: ?")
11949 ("I" "#+INCLUDE: %file ?"
11950 "<include file=%file markup=\"?\">"))
11951 "Structure completion elements.
11952 This is a list of abbreviation keys and values. The value gets inserted
11953 if you type `<' followed by the key and then press the completion key,
11954 usually `M-TAB'. %file will be replaced by a file name after prompting
11955 for the file using completion. The cursor will be placed at the position
11956 of the `?` in the template.
11957 There are two templates for each key, the first uses the original Org syntax,
11958 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11959 the default when the /org-mtags.el/ module has been loaded. See also the
11960 variable `org-mtags-prefer-muse-templates'."
11961 :group 'org-completion
11962 :type '(repeat
11963 (string :tag "Key")
11964 (string :tag "Template")
11965 (string :tag "Muse Template")))
11967 (defun org-try-structure-completion ()
11968 "Try to complete a structure template before point.
11969 This looks for strings like \"<e\" on an otherwise empty line and
11970 expands them."
11971 (let ((l (buffer-substring (point-at-bol) (point)))
11973 (when (and (looking-at "[ \t]*$")
11974 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11975 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11976 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11977 (match-beginning 1)) a)
11978 t)))
11980 (defun org-complete-expand-structure-template (start cell)
11981 "Expand a structure template."
11982 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11983 (rpl (nth (if musep 2 1) cell))
11984 (ind ""))
11985 (delete-region start (point))
11986 (when (string-match "\\`#\\+" rpl)
11987 (cond
11988 ((bolp))
11989 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11990 (setq ind (buffer-substring (point-at-bol) (point))))
11991 (t (newline))))
11992 (setq start (point))
11993 (if (string-match "%file" rpl)
11994 (setq rpl (replace-match
11995 (concat
11996 "\""
11997 (save-match-data
11998 (abbreviate-file-name (read-file-name "Include file: ")))
11999 "\"")
12000 t t rpl)))
12001 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12002 (concat "\n" ind)))
12003 (insert rpl)
12004 (if (re-search-backward "\\?" start t) (delete-char 1))))
12006 ;;;; TODO, DEADLINE, Comments
12008 (defun org-toggle-comment ()
12009 "Change the COMMENT state of an entry."
12010 (interactive)
12011 (save-excursion
12012 (org-back-to-heading)
12013 (let (case-fold-search)
12014 (cond
12015 ((looking-at (format org-heading-keyword-regexp-format
12016 org-comment-string))
12017 (goto-char (match-end 1))
12018 (looking-at (concat " +" org-comment-string))
12019 (replace-match "" t t)
12020 (when (eolp) (insert " ")))
12021 ((looking-at org-outline-regexp)
12022 (goto-char (match-end 0))
12023 (insert org-comment-string " "))))))
12025 (defvar org-last-todo-state-is-todo nil
12026 "This is non-nil when the last TODO state change led to a TODO state.
12027 If the last change removed the TODO tag or switched to DONE, then
12028 this is nil.")
12030 (defvar org-setting-tags nil) ; dynamically skipped
12032 (defvar org-todo-setup-filter-hook nil
12033 "Hook for functions that pre-filter todo specs.
12034 Each function takes a todo spec and returns either nil or the spec
12035 transformed into canonical form." )
12037 (defvar org-todo-get-default-hook nil
12038 "Hook for functions that get a default item for todo.
12039 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12040 nil or a string to be used for the todo mark." )
12042 (defvar org-agenda-headline-snapshot-before-repeat)
12044 (defun org-current-effective-time ()
12045 "Return current time adjusted for `org-extend-today-until' variable."
12046 (let* ((ct (org-current-time))
12047 (dct (decode-time ct))
12048 (ct1
12049 (cond
12050 (org-use-last-clock-out-time-as-effective-time
12051 (or (org-clock-get-last-clock-out-time) ct))
12052 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12053 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12054 (t ct))))
12055 ct1))
12057 (defun org-todo-yesterday (&optional arg)
12058 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12059 (interactive "P")
12060 (if (eq major-mode 'org-agenda-mode)
12061 (apply 'org-agenda-todo-yesterday arg)
12062 (let* ((hour (third (decode-time
12063 (org-current-time))))
12064 (org-extend-today-until (1+ hour)))
12065 (org-todo arg))))
12067 (defvar org-block-entry-blocking ""
12068 "First entry preventing the TODO state change.")
12070 (defun org-todo (&optional arg)
12071 "Change the TODO state of an item.
12072 The state of an item is given by a keyword at the start of the heading,
12073 like
12074 *** TODO Write paper
12075 *** DONE Call mom
12077 The different keywords are specified in the variable `org-todo-keywords'.
12078 By default the available states are \"TODO\" and \"DONE\".
12079 So for this example: when the item starts with TODO, it is changed to DONE.
12080 When it starts with DONE, the DONE is removed. And when neither TODO nor
12081 DONE are present, add TODO at the beginning of the heading.
12083 With \\[universal-argument] prefix arg, use completion to determine the new \
12084 state.
12085 With numeric prefix arg, switch to that state.
12086 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12087 keywords (nextset).
12088 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12089 With a numeric prefix arg of 0, inhibit note taking for the change.
12091 For calling through lisp, arg is also interpreted in the following way:
12092 'none -> empty state
12093 \"\"(empty string) -> switch to empty state
12094 'done -> switch to DONE
12095 'nextset -> switch to the next set of keywords
12096 'previousset -> switch to the previous set of keywords
12097 \"WAITING\" -> switch to the specified keyword, but only if it
12098 really is a member of `org-todo-keywords'."
12099 (interactive "P")
12100 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12101 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12102 'region-start-level 'region))
12103 org-loop-over-headlines-in-active-region)
12104 (org-map-entries
12105 `(org-todo ,arg)
12106 org-loop-over-headlines-in-active-region
12107 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12108 (if (equal arg '(16)) (setq arg 'nextset))
12109 (let ((org-blocker-hook org-blocker-hook)
12110 commentp
12111 case-fold-search)
12112 (when (equal arg '(64))
12113 (setq arg nil org-blocker-hook nil))
12114 (when (and org-blocker-hook
12115 (or org-inhibit-blocking
12116 (org-entry-get nil "NOBLOCKING")))
12117 (setq org-blocker-hook nil))
12118 (save-excursion
12119 (catch 'exit
12120 (org-back-to-heading t)
12121 (when (looking-at (concat "^\\*+ " org-comment-string))
12122 (org-toggle-comment)
12123 (setq commentp t))
12124 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12125 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12126 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12127 (let* ((match-data (match-data))
12128 (startpos (point-at-bol))
12129 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12130 (org-log-done org-log-done)
12131 (org-log-repeat org-log-repeat)
12132 (org-todo-log-states org-todo-log-states)
12133 (org-inhibit-logging
12134 (if (equal arg 0)
12135 (progn (setq arg nil) 'note) org-inhibit-logging))
12136 (this (match-string 1))
12137 (hl-pos (match-beginning 0))
12138 (head (org-get-todo-sequence-head this))
12139 (ass (assoc head org-todo-kwd-alist))
12140 (interpret (nth 1 ass))
12141 (done-word (nth 3 ass))
12142 (final-done-word (nth 4 ass))
12143 (org-last-state (or this ""))
12144 (completion-ignore-case t)
12145 (member (member this org-todo-keywords-1))
12146 (tail (cdr member))
12147 (org-state (cond
12148 ((and org-todo-key-trigger
12149 (or (and (equal arg '(4))
12150 (eq org-use-fast-todo-selection 'prefix))
12151 (and (not arg) org-use-fast-todo-selection
12152 (not (eq org-use-fast-todo-selection
12153 'prefix)))))
12154 ;; Use fast selection
12155 (org-fast-todo-selection))
12156 ((and (equal arg '(4))
12157 (or (not org-use-fast-todo-selection)
12158 (not org-todo-key-trigger)))
12159 ;; Read a state with completion
12160 (org-icompleting-read
12161 "State: " (mapcar 'list org-todo-keywords-1)
12162 nil t))
12163 ((eq arg 'right)
12164 (if this
12165 (if tail (car tail) nil)
12166 (car org-todo-keywords-1)))
12167 ((eq arg 'left)
12168 (if (equal member org-todo-keywords-1)
12170 (if this
12171 (nth (- (length org-todo-keywords-1)
12172 (length tail) 2)
12173 org-todo-keywords-1)
12174 (org-last org-todo-keywords-1))))
12175 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12176 (setq arg nil))) ; hack to fall back to cycling
12177 (arg
12178 ;; user or caller requests a specific state
12179 (cond
12180 ((equal arg "") nil)
12181 ((eq arg 'none) nil)
12182 ((eq arg 'done) (or done-word (car org-done-keywords)))
12183 ((eq arg 'nextset)
12184 (or (car (cdr (member head org-todo-heads)))
12185 (car org-todo-heads)))
12186 ((eq arg 'previousset)
12187 (let ((org-todo-heads (reverse org-todo-heads)))
12188 (or (car (cdr (member head org-todo-heads)))
12189 (car org-todo-heads))))
12190 ((car (member arg org-todo-keywords-1)))
12191 ((stringp arg)
12192 (user-error "State `%s' not valid in this file" arg))
12193 ((nth (1- (prefix-numeric-value arg))
12194 org-todo-keywords-1))))
12195 ((null member) (or head (car org-todo-keywords-1)))
12196 ((equal this final-done-word) nil) ;; -> make empty
12197 ((null tail) nil) ;; -> first entry
12198 ((memq interpret '(type priority))
12199 (if (eq this-command last-command)
12200 (car tail)
12201 (if (> (length tail) 0)
12202 (or done-word (car org-done-keywords))
12203 nil)))
12205 (car tail))))
12206 (org-state (or
12207 (run-hook-with-args-until-success
12208 'org-todo-get-default-hook org-state org-last-state)
12209 org-state))
12210 (next (if org-state (concat " " org-state " ") " "))
12211 (change-plist (list :type 'todo-state-change :from this :to org-state
12212 :position startpos))
12213 dolog now-done-p)
12214 (when org-blocker-hook
12215 (setq org-last-todo-state-is-todo
12216 (not (member this org-done-keywords)))
12217 (unless (save-excursion
12218 (save-match-data
12219 (org-with-wide-buffer
12220 (run-hook-with-args-until-failure
12221 'org-blocker-hook change-plist))))
12222 (if (org-called-interactively-p 'interactive)
12223 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12224 this org-state org-block-entry-blocking)
12225 ;; fail silently
12226 (message "TODO state change from %s to %s blocked (by \"%s\")"
12227 this org-state org-block-entry-blocking)
12228 (throw 'exit nil))))
12229 (store-match-data match-data)
12230 (replace-match next t t)
12231 (unless (pos-visible-in-window-p hl-pos)
12232 (message "TODO state changed to %s" (org-trim next)))
12233 (unless head
12234 (setq head (org-get-todo-sequence-head org-state)
12235 ass (assoc head org-todo-kwd-alist)
12236 interpret (nth 1 ass)
12237 done-word (nth 3 ass)
12238 final-done-word (nth 4 ass)))
12239 (when (memq arg '(nextset previousset))
12240 (message "Keyword-Set %d/%d: %s"
12241 (- (length org-todo-sets) -1
12242 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12243 (length org-todo-sets)
12244 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12245 (setq org-last-todo-state-is-todo
12246 (not (member org-state org-done-keywords)))
12247 (setq now-done-p (and (member org-state org-done-keywords)
12248 (not (member this org-done-keywords))))
12249 (and logging (org-local-logging logging))
12250 (when (and (or org-todo-log-states org-log-done)
12251 (not (eq org-inhibit-logging t))
12252 (not (memq arg '(nextset previousset))))
12253 ;; we need to look at recording a time and note
12254 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12255 (nth 2 (assoc this org-todo-log-states))))
12256 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12257 (setq dolog 'time))
12258 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12259 (and org-state
12260 (member org-state org-not-done-keywords)
12261 (not (member this org-not-done-keywords))))
12262 ;; This is now a todo state and was not one before
12263 ;; If there was a CLOSED time stamp, get rid of it.
12264 (org-add-planning-info nil nil 'closed))
12265 (when (and now-done-p org-log-done)
12266 ;; It is now done, and it was not done before
12267 (org-add-planning-info 'closed (org-current-effective-time))
12268 (if (and (not dolog) (eq 'note org-log-done))
12269 (org-add-log-setup 'done org-state this 'findpos 'note)))
12270 (when (and org-state dolog)
12271 ;; This is a non-nil state, and we need to log it
12272 (org-add-log-setup 'state org-state this 'findpos dolog)))
12273 ;; Fixup tag positioning
12274 (org-todo-trigger-tag-changes org-state)
12275 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12276 (when org-provide-todo-statistics
12277 (org-update-parent-todo-statistics))
12278 (run-hooks 'org-after-todo-state-change-hook)
12279 (if (and arg (not (member org-state org-done-keywords)))
12280 (setq head (org-get-todo-sequence-head org-state)))
12281 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12282 ;; Do we need to trigger a repeat?
12283 (when now-done-p
12284 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12285 ;; This is for the agenda, take a snapshot of the headline.
12286 (save-match-data
12287 (setq org-agenda-headline-snapshot-before-repeat
12288 (org-get-heading))))
12289 (org-auto-repeat-maybe org-state))
12290 ;; Fixup cursor location if close to the keyword
12291 (if (and (outline-on-heading-p)
12292 (not (bolp))
12293 (save-excursion (beginning-of-line 1)
12294 (looking-at org-todo-line-regexp))
12295 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12296 (progn
12297 (goto-char (or (match-end 2) (match-end 1)))
12298 (and (looking-at " ") (just-one-space))))
12299 (when org-trigger-hook
12300 (save-excursion
12301 (run-hook-with-args 'org-trigger-hook change-plist)))
12302 (when commentp (org-toggle-comment))))))))
12304 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12305 "Block turning an entry into a TODO, using the hierarchy.
12306 This checks whether the current task should be blocked from state
12307 changes. Such blocking occurs when:
12309 1. The task has children which are not all in a completed state.
12311 2. A task has a parent with the property :ORDERED:, and there
12312 are siblings prior to the current task with incomplete
12313 status.
12315 3. The parent of the task is blocked because it has siblings that should
12316 be done first, or is child of a block grandparent TODO entry."
12318 (if (not org-enforce-todo-dependencies)
12319 t ; if locally turned off don't block
12320 (catch 'dont-block
12321 ;; If this is not a todo state change, or if this entry is already DONE,
12322 ;; do not block
12323 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12324 (member (plist-get change-plist :from)
12325 (cons 'done org-done-keywords))
12326 (member (plist-get change-plist :to)
12327 (cons 'todo org-not-done-keywords))
12328 (not (plist-get change-plist :to)))
12329 (throw 'dont-block t))
12330 ;; If this task has children, and any are undone, it's blocked
12331 (save-excursion
12332 (org-back-to-heading t)
12333 (let ((this-level (funcall outline-level)))
12334 (outline-next-heading)
12335 (let ((child-level (funcall outline-level)))
12336 (while (and (not (eobp))
12337 (> child-level this-level))
12338 ;; this todo has children, check whether they are all
12339 ;; completed
12340 (if (and (not (org-entry-is-done-p))
12341 (org-entry-is-todo-p))
12342 (progn (setq org-block-entry-blocking (org-get-heading))
12343 (throw 'dont-block nil)))
12344 (outline-next-heading)
12345 (setq child-level (funcall outline-level))))))
12346 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12347 ;; any previous siblings are undone, it's blocked
12348 (save-excursion
12349 (org-back-to-heading t)
12350 (let* ((pos (point))
12351 (parent-pos (and (org-up-heading-safe) (point))))
12352 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12353 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12354 (forward-line 1)
12355 (re-search-forward org-not-done-heading-regexp pos t))
12356 (setq org-block-entry-blocking (match-string 0))
12357 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12358 ;; Search further up the hierarchy, to see if an ancestor is blocked
12359 (while t
12360 (goto-char parent-pos)
12361 (if (not (looking-at org-not-done-heading-regexp))
12362 (throw 'dont-block t)) ; do not block, parent is not a TODO
12363 (setq pos (point))
12364 (setq parent-pos (and (org-up-heading-safe) (point)))
12365 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12366 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12367 (forward-line 1)
12368 (re-search-forward org-not-done-heading-regexp pos t)
12369 (setq org-block-entry-blocking (org-get-heading)))
12370 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12372 (defcustom org-track-ordered-property-with-tag nil
12373 "Should the ORDERED property also be shown as a tag?
12374 The ORDERED property decides if an entry should require subtasks to be
12375 completed in sequence. Since a property is not very visible, setting
12376 this option means that toggling the ORDERED property with the command
12377 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12378 not relevant for the behavior, but it makes things more visible.
12380 Note that toggling the tag with tags commands will not change the property
12381 and therefore not influence behavior!
12383 This can be t, meaning the tag ORDERED should be used, It can also be a
12384 string to select a different tag for this task."
12385 :group 'org-todo
12386 :type '(choice
12387 (const :tag "No tracking" nil)
12388 (const :tag "Track with ORDERED tag" t)
12389 (string :tag "Use other tag")))
12391 (defun org-toggle-ordered-property ()
12392 "Toggle the ORDERED property of the current entry.
12393 For better visibility, you can track the value of this property with a tag.
12394 See variable `org-track-ordered-property-with-tag'."
12395 (interactive)
12396 (let* ((t1 org-track-ordered-property-with-tag)
12397 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12398 (save-excursion
12399 (org-back-to-heading)
12400 (if (org-entry-get nil "ORDERED")
12401 (progn
12402 (org-delete-property "ORDERED" "PROPERTIES")
12403 (and tag (org-toggle-tag tag 'off))
12404 (message "Subtasks can be completed in arbitrary order"))
12405 (org-entry-put nil "ORDERED" "t")
12406 (and tag (org-toggle-tag tag 'on))
12407 (message "Subtasks must be completed in sequence")))))
12409 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12410 (defun org-block-todo-from-checkboxes (change-plist)
12411 "Block turning an entry into a TODO, using checkboxes.
12412 This checks whether the current task should be blocked from state
12413 changes because there are unchecked boxes in this entry."
12414 (if (not org-enforce-todo-checkbox-dependencies)
12415 t ; if locally turned off don't block
12416 (catch 'dont-block
12417 ;; If this is not a todo state change, or if this entry is already DONE,
12418 ;; do not block
12419 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12420 (member (plist-get change-plist :from)
12421 (cons 'done org-done-keywords))
12422 (member (plist-get change-plist :to)
12423 (cons 'todo org-not-done-keywords))
12424 (not (plist-get change-plist :to)))
12425 (throw 'dont-block t))
12426 ;; If this task has checkboxes that are not checked, it's blocked
12427 (save-excursion
12428 (org-back-to-heading t)
12429 (let ((beg (point)) end)
12430 (outline-next-heading)
12431 (setq end (point))
12432 (goto-char beg)
12433 (if (org-list-search-forward
12434 (concat (org-item-beginning-re)
12435 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12436 "\\[[- ]\\]")
12437 end t)
12438 (progn
12439 (if (boundp 'org-blocked-by-checkboxes)
12440 (setq org-blocked-by-checkboxes t))
12441 (throw 'dont-block nil)))))
12442 t))) ; do not block
12444 (defun org-entry-blocked-p ()
12445 "Is the current entry blocked?"
12446 (org-with-silent-modifications
12447 (if (org-entry-get nil "NOBLOCKING")
12448 nil ;; Never block this entry
12449 (not (run-hook-with-args-until-failure
12450 'org-blocker-hook
12451 (list :type 'todo-state-change
12452 :position (point)
12453 :from 'todo
12454 :to 'done))))))
12456 (defun org-update-statistics-cookies (all)
12457 "Update the statistics cookie, either from TODO or from checkboxes.
12458 This should be called with the cursor in a line with a statistics cookie."
12459 (interactive "P")
12460 (if all
12461 (progn
12462 (org-update-checkbox-count 'all)
12463 (org-map-entries 'org-update-parent-todo-statistics))
12464 (if (not (org-at-heading-p))
12465 (org-update-checkbox-count)
12466 (let ((pos (point-marker))
12467 end l1 l2)
12468 (ignore-errors (org-back-to-heading t))
12469 (if (not (org-at-heading-p))
12470 (org-update-checkbox-count)
12471 (setq l1 (org-outline-level))
12472 (setq end (save-excursion
12473 (outline-next-heading)
12474 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12475 (point)))
12476 (if (and (save-excursion
12477 (re-search-forward
12478 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12479 (not (save-excursion (re-search-forward
12480 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12481 (org-update-checkbox-count)
12482 (if (and l2 (> l2 l1))
12483 (progn
12484 (goto-char end)
12485 (org-update-parent-todo-statistics))
12486 (goto-char pos)
12487 (beginning-of-line 1)
12488 (while (re-search-forward
12489 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12490 (point-at-eol) t)
12491 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12492 (goto-char pos)
12493 (move-marker pos nil)))))
12495 (defvar org-entry-property-inherited-from) ;; defined below
12496 (defun org-update-parent-todo-statistics ()
12497 "Update any statistics cookie in the parent of the current headline.
12498 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12499 the entire subtree and this will travel up the hierarchy and update
12500 statistics everywhere."
12501 (let* ((prop (save-excursion (org-up-heading-safe)
12502 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12503 (recursive (or (not org-hierarchical-todo-statistics)
12504 (and prop (string-match "\\<recursive\\>" prop))))
12505 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12507 (first t)
12508 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12509 level ltoggle l1 new ndel
12510 (cnt-all 0) (cnt-done 0) is-percent kwd
12511 checkbox-beg ov ovs ove cookie-present)
12512 (catch 'exit
12513 (save-excursion
12514 (beginning-of-line 1)
12515 (setq ltoggle (funcall outline-level))
12516 ;; Three situations are to consider:
12518 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12519 ;; to the top-level ancestor on the headline;
12521 ;; 2. If parent has "recursive" property, repeat up to the
12522 ;; headline setting that property, taking inheritance into
12523 ;; account;
12525 ;; 3. Else, move up to direct parent and proceed only once.
12526 (while (and (setq level (org-up-heading-safe))
12527 (or recursive first)
12528 (>= (point) lim))
12529 (setq first nil cookie-present nil)
12530 (unless (and level
12531 (not (string-match
12532 "\\<checkbox\\>"
12533 (downcase (or (org-entry-get nil "COOKIE_DATA")
12534 "")))))
12535 (throw 'exit nil))
12536 (while (re-search-forward box-re (point-at-eol) t)
12537 (setq cnt-all 0 cnt-done 0 cookie-present t)
12538 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12539 (save-match-data
12540 (unless (outline-next-heading) (throw 'exit nil))
12541 (while (and (looking-at org-complex-heading-regexp)
12542 (> (setq l1 (length (match-string 1))) level))
12543 (setq kwd (and (or recursive (= l1 ltoggle))
12544 (match-string 2)))
12545 (if (or (eq org-provide-todo-statistics 'all-headlines)
12546 (and (listp org-provide-todo-statistics)
12547 (or (member kwd org-provide-todo-statistics)
12548 (member kwd org-done-keywords))))
12549 (setq cnt-all (1+ cnt-all))
12550 (if (eq org-provide-todo-statistics t)
12551 (and kwd (setq cnt-all (1+ cnt-all)))))
12552 (and (member kwd org-done-keywords)
12553 (setq cnt-done (1+ cnt-done)))
12554 (outline-next-heading)))
12555 (setq new
12556 (if is-percent
12557 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12558 (format "[%d/%d]" cnt-done cnt-all))
12559 ndel (- (match-end 0) checkbox-beg))
12560 ;; handle overlays when updating cookie from column view
12561 (when (setq ov (car (overlays-at checkbox-beg)))
12562 (setq ovs (overlay-start ov) ove (overlay-end ov))
12563 (delete-overlay ov))
12564 (goto-char checkbox-beg)
12565 (insert new)
12566 (delete-region (point) (+ (point) ndel))
12567 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12568 (when ov (move-overlay ov ovs ove)))
12569 (when cookie-present
12570 (run-hook-with-args 'org-after-todo-statistics-hook
12571 cnt-done (- cnt-all cnt-done))))))
12572 (run-hooks 'org-todo-statistics-hook)))
12574 (defvar org-after-todo-statistics-hook nil
12575 "Hook that is called after a TODO statistics cookie has been updated.
12576 Each function is called with two arguments: the number of not-done entries
12577 and the number of done entries.
12579 For example, the following function, when added to this hook, will switch
12580 an entry to DONE when all children are done, and back to TODO when new
12581 entries are set to a TODO status. Note that this hook is only called
12582 when there is a statistics cookie in the headline!
12584 (defun org-summary-todo (n-done n-not-done)
12585 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12586 (let (org-log-done org-log-states) ; turn off logging
12587 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12590 (defvar org-todo-statistics-hook nil
12591 "Hook that is run whenever Org thinks TODO statistics should be updated.
12592 This hook runs even if there is no statistics cookie present, in which case
12593 `org-after-todo-statistics-hook' would not run.")
12595 (defun org-todo-trigger-tag-changes (state)
12596 "Apply the changes defined in `org-todo-state-tags-triggers'."
12597 (let ((l org-todo-state-tags-triggers)
12598 changes)
12599 (when (or (not state) (equal state ""))
12600 (setq changes (append changes (cdr (assoc "" l)))))
12601 (when (and (stringp state) (> (length state) 0))
12602 (setq changes (append changes (cdr (assoc state l)))))
12603 (when (member state org-not-done-keywords)
12604 (setq changes (append changes (cdr (assoc 'todo l)))))
12605 (when (member state org-done-keywords)
12606 (setq changes (append changes (cdr (assoc 'done l)))))
12607 (dolist (c changes)
12608 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12610 (defun org-local-logging (value)
12611 "Get logging settings from a property VALUE."
12612 (let* (words w a)
12613 ;; directly set the variables, they are already local.
12614 (setq org-log-done nil
12615 org-log-repeat nil
12616 org-todo-log-states nil)
12617 (setq words (org-split-string value))
12618 (while (setq w (pop words))
12619 (cond
12620 ((setq a (assoc w org-startup-options))
12621 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12622 (set (nth 1 a) (nth 2 a))))
12623 ((setq a (org-extract-log-state-settings w))
12624 (and (member (car a) org-todo-keywords-1)
12625 (push a org-todo-log-states)))))))
12627 (defun org-get-todo-sequence-head (kwd)
12628 "Return the head of the TODO sequence to which KWD belongs.
12629 If KWD is not set, check if there is a text property remembering the
12630 right sequence."
12631 (let (p)
12632 (cond
12633 ((not kwd)
12634 (or (get-text-property (point-at-bol) 'org-todo-head)
12635 (progn
12636 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12637 nil (point-at-eol)))
12638 (get-text-property p 'org-todo-head))))
12639 ((not (member kwd org-todo-keywords-1))
12640 (car org-todo-keywords-1))
12641 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12643 (defun org-fast-todo-selection ()
12644 "Fast TODO keyword selection with single keys.
12645 Returns the new TODO keyword, or nil if no state change should occur."
12646 (let* ((fulltable org-todo-key-alist)
12647 (done-keywords org-done-keywords) ;; needed for the faces.
12648 (maxlen (apply 'max (mapcar
12649 (lambda (x)
12650 (if (stringp (car x)) (string-width (car x)) 0))
12651 fulltable)))
12652 (expert nil)
12653 (fwidth (+ maxlen 3 1 3))
12654 (ncol (/ (- (window-width) 4) fwidth))
12655 tg cnt e c tbl
12656 groups ingroup)
12657 (save-excursion
12658 (save-window-excursion
12659 (if expert
12660 (set-buffer (get-buffer-create " *Org todo*"))
12661 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12662 (erase-buffer)
12663 (org-set-local 'org-done-keywords done-keywords)
12664 (setq tbl fulltable cnt 0)
12665 (while (setq e (pop tbl))
12666 (cond
12667 ((equal e '(:startgroup))
12668 (push '() groups) (setq ingroup t)
12669 (when (not (= cnt 0))
12670 (setq cnt 0)
12671 (insert "\n"))
12672 (insert "{ "))
12673 ((equal e '(:endgroup))
12674 (setq ingroup nil cnt 0)
12675 (insert "}\n"))
12676 ((equal e '(:newline))
12677 (when (not (= cnt 0))
12678 (setq cnt 0)
12679 (insert "\n")
12680 (setq e (car tbl))
12681 (while (equal (car tbl) '(:newline))
12682 (insert "\n")
12683 (setq tbl (cdr tbl)))))
12685 (setq tg (car e) c (cdr e))
12686 (if ingroup (push tg (car groups)))
12687 (setq tg (org-add-props tg nil 'face
12688 (org-get-todo-face tg)))
12689 (if (and (= cnt 0) (not ingroup)) (insert " "))
12690 (insert "[" c "] " tg (make-string
12691 (- fwidth 4 (length tg)) ?\ ))
12692 (when (= (setq cnt (1+ cnt)) ncol)
12693 (insert "\n")
12694 (if ingroup (insert " "))
12695 (setq cnt 0)))))
12696 (insert "\n")
12697 (goto-char (point-min))
12698 (if (not expert) (org-fit-window-to-buffer))
12699 (message "[a-z..]:Set [SPC]:clear")
12700 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12701 (cond
12702 ((or (= c ?\C-g)
12703 (and (= c ?q) (not (rassoc c fulltable))))
12704 (setq quit-flag t))
12705 ((= c ?\ ) nil)
12706 ((setq e (rassoc c fulltable) tg (car e))
12708 (t (setq quit-flag t)))))))
12710 (defun org-entry-is-todo-p ()
12711 (member (org-get-todo-state) org-not-done-keywords))
12713 (defun org-entry-is-done-p ()
12714 (member (org-get-todo-state) org-done-keywords))
12716 (defun org-get-todo-state ()
12717 "Return the TODO keyword of the current subtree."
12718 (save-excursion
12719 (org-back-to-heading t)
12720 (and (looking-at org-todo-line-regexp)
12721 (match-end 2)
12722 (match-string 2))))
12724 (defun org-at-date-range-p (&optional inactive-ok)
12725 "Is the cursor inside a date range?"
12726 (interactive)
12727 (save-excursion
12728 (catch 'exit
12729 (let ((pos (point)))
12730 (skip-chars-backward "^[<\r\n")
12731 (skip-chars-backward "<[")
12732 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12733 (>= (match-end 0) pos)
12734 (throw 'exit t))
12735 (skip-chars-backward "^<[\r\n")
12736 (skip-chars-backward "<[")
12737 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12738 (>= (match-end 0) pos)
12739 (throw 'exit t)))
12740 nil)))
12742 (defun org-get-repeat (&optional tagline)
12743 "Check if there is a deadline/schedule with repeater in this entry."
12744 (save-match-data
12745 (save-excursion
12746 (org-back-to-heading t)
12747 (and (re-search-forward (if tagline
12748 (concat tagline "\\s-*" org-repeat-re)
12749 org-repeat-re)
12750 (org-entry-end-position) t)
12751 (match-string-no-properties 1)))))
12753 (defvar org-last-changed-timestamp)
12754 (defvar org-last-inserted-timestamp)
12755 (defvar org-log-post-message)
12756 (defvar org-log-note-purpose)
12757 (defvar org-log-note-how)
12758 (defvar org-log-note-extra)
12759 (defun org-auto-repeat-maybe (done-word)
12760 "Check if the current headline contains a repeated deadline/schedule.
12761 If yes, set TODO state back to what it was and change the base date
12762 of repeating deadline/scheduled time stamps to new date.
12763 This function is run automatically after each state change to a DONE state."
12764 ;; last-state is dynamically scoped into this function
12765 (let* ((repeat (org-get-repeat))
12766 (aa (assoc org-last-state org-todo-kwd-alist))
12767 (interpret (nth 1 aa))
12768 (head (nth 2 aa))
12769 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12770 (msg "Entry repeats: ")
12771 (org-log-done nil)
12772 (org-todo-log-states nil)
12773 re type n what ts time to-state)
12774 (when repeat
12775 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12776 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12777 org-todo-repeat-to-state))
12778 (unless (and to-state (member to-state org-todo-keywords-1))
12779 (setq to-state (if (eq interpret 'type) org-last-state head)))
12780 (org-todo to-state)
12781 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12782 (org-entry-put nil "LAST_REPEAT" (format-time-string
12783 (org-time-stamp-format t t))))
12784 (when org-log-repeat
12785 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12786 (memq 'org-add-log-note post-command-hook))
12787 ;; OK, we are already setup for some record
12788 (if (eq org-log-repeat 'note)
12789 ;; make sure we take a note, not only a time stamp
12790 (setq org-log-note-how 'note))
12791 ;; Set up for taking a record
12792 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12793 org-last-state
12794 'findpos org-log-repeat)))
12795 (org-back-to-heading t)
12796 (org-add-planning-info nil nil 'closed)
12797 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12798 org-deadline-time-regexp "\\)\\|\\("
12799 org-ts-regexp "\\)"))
12800 (while (re-search-forward
12801 re (save-excursion (outline-next-heading) (point)) t)
12802 (setq type (if (match-end 1) org-scheduled-string
12803 (if (match-end 3) org-deadline-string "Plain:"))
12804 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12805 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12806 (setq n (string-to-number (match-string 2 ts))
12807 what (match-string 3 ts))
12808 (if (equal what "w") (setq n (* n 7) what "d"))
12809 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12810 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12811 ;; Preparation, see if we need to modify the start date for the change
12812 (when (match-end 1)
12813 (setq time (save-match-data (org-time-string-to-time ts)))
12814 (cond
12815 ((equal (match-string 1 ts) ".")
12816 ;; Shift starting date to today
12817 (org-timestamp-change
12818 (- (org-today) (time-to-days time))
12819 'day))
12820 ((equal (match-string 1 ts) "+")
12821 (let ((nshiftmax 10) (nshift 0))
12822 (while (or (= nshift 0)
12823 (<= (time-to-days time)
12824 (time-to-days (current-time))))
12825 (when (= (incf nshift) nshiftmax)
12826 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12827 (error "Abort")))
12828 (org-timestamp-change n (cdr (assoc what whata)))
12829 (org-at-timestamp-p t)
12830 (setq ts (match-string 1))
12831 (setq time (save-match-data (org-time-string-to-time ts)))))
12832 (org-timestamp-change (- n) (cdr (assoc what whata)))
12833 ;; rematch, so that we have everything in place for the real shift
12834 (org-at-timestamp-p t)
12835 (setq ts (match-string 1))
12836 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12837 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12838 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12839 (setq org-log-post-message msg)
12840 (message "%s" msg))))
12842 (defun org-show-todo-tree (arg)
12843 "Make a compact tree which shows all headlines marked with TODO.
12844 The tree will show the lines where the regexp matches, and all higher
12845 headlines above the match.
12846 With a \\[universal-argument] prefix, prompt for a regexp to match.
12847 With a numeric prefix N, construct a sparse tree for the Nth element
12848 of `org-todo-keywords-1'."
12849 (interactive "P")
12850 (let ((case-fold-search nil)
12851 (kwd-re
12852 (cond ((null arg) org-not-done-regexp)
12853 ((equal arg '(4))
12854 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12855 (mapcar 'list org-todo-keywords-1))))
12856 (concat "\\("
12857 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12858 "\\)\\>")))
12859 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12860 (regexp-quote (nth (1- (prefix-numeric-value arg))
12861 org-todo-keywords-1)))
12862 (t (user-error "Invalid prefix argument: %s" arg)))))
12863 (message "%d TODO entries found"
12864 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12866 (defun org-deadline (arg &optional time)
12867 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12868 With one universal prefix argument, remove any deadline from the item.
12869 With two universal prefix arguments, prompt for a warning delay.
12870 With argument TIME, set the deadline at the corresponding date. TIME
12871 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12872 (interactive "P")
12873 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12874 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12875 'region-start-level 'region))
12876 org-loop-over-headlines-in-active-region)
12877 (org-map-entries
12878 `(org-deadline ',arg ,time)
12879 org-loop-over-headlines-in-active-region
12880 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12881 (let* ((old-date (org-entry-get nil "DEADLINE"))
12882 (old-date-time (if old-date (org-time-string-to-time old-date)))
12883 (repeater (and old-date
12884 (string-match
12885 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12886 old-date)
12887 (match-string 1 old-date))))
12888 (cond
12889 ((equal arg '(4))
12890 (when (and old-date org-log-redeadline)
12891 (org-add-log-setup 'deldeadline nil old-date 'findpos
12892 org-log-redeadline))
12893 (org-remove-timestamp-with-keyword org-deadline-string)
12894 (message "Item no longer has a deadline."))
12895 ((equal arg '(16))
12896 (save-excursion
12897 (if (re-search-forward
12898 org-deadline-time-regexp
12899 (save-excursion (outline-next-heading) (point)) t)
12900 (let* ((rpl0 (match-string 1))
12901 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12902 (replace-match
12903 (concat org-deadline-string
12904 " <" rpl
12905 (format " -%dd"
12906 (abs
12907 (- (time-to-days
12908 (save-match-data
12909 (org-read-date nil t nil "Warn starting from" old-date-time)))
12910 (time-to-days old-date-time))))
12911 ">") t t))
12912 (user-error "No deadline information to update"))))
12914 (org-add-planning-info 'deadline time 'closed)
12915 (when (and old-date org-log-redeadline
12916 (not (equal old-date
12917 (substring org-last-inserted-timestamp 1 -1))))
12918 (org-add-log-setup 'redeadline nil old-date 'findpos
12919 org-log-redeadline))
12920 (when repeater
12921 (save-excursion
12922 (org-back-to-heading t)
12923 (when (re-search-forward (concat org-deadline-string " "
12924 org-last-inserted-timestamp)
12925 (save-excursion
12926 (outline-next-heading) (point)) t)
12927 (goto-char (1- (match-end 0)))
12928 (insert " " repeater)
12929 (setq org-last-inserted-timestamp
12930 (concat (substring org-last-inserted-timestamp 0 -1)
12931 " " repeater
12932 (substring org-last-inserted-timestamp -1))))))
12933 (message "Deadline on %s" org-last-inserted-timestamp))))))
12935 (defun org-schedule (arg &optional time)
12936 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12937 With one universal prefix argument, remove any scheduling date from the item.
12938 With two universal prefix arguments, prompt for a delay cookie.
12939 With argument TIME, scheduled at the corresponding date. TIME can
12940 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12941 (interactive "P")
12942 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12943 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12944 'region-start-level 'region))
12945 org-loop-over-headlines-in-active-region)
12946 (org-map-entries
12947 `(org-schedule ',arg ,time)
12948 org-loop-over-headlines-in-active-region
12949 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12950 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12951 (old-date-time (if old-date (org-time-string-to-time old-date)))
12952 (repeater (and old-date
12953 (string-match
12954 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12955 old-date)
12956 (match-string 1 old-date))))
12957 (cond
12958 ((equal arg '(4))
12959 (progn
12960 (when (and old-date org-log-reschedule)
12961 (org-add-log-setup 'delschedule nil old-date 'findpos
12962 org-log-reschedule))
12963 (org-remove-timestamp-with-keyword org-scheduled-string)
12964 (message "Item is no longer scheduled.")))
12965 ((equal arg '(16))
12966 (save-excursion
12967 (if (re-search-forward
12968 org-scheduled-time-regexp
12969 (save-excursion (outline-next-heading) (point)) t)
12970 (let* ((rpl0 (match-string 1))
12971 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12972 (replace-match
12973 (concat org-scheduled-string
12974 " <" rpl
12975 (format " -%dd"
12976 (abs
12977 (- (time-to-days
12978 (save-match-data
12979 (org-read-date nil t nil "Delay until" old-date-time)))
12980 (time-to-days old-date-time))))
12981 ">") t t))
12982 (user-error "No scheduled information to update"))))
12984 (org-add-planning-info 'scheduled time 'closed)
12985 (when (and old-date org-log-reschedule
12986 (not (equal old-date
12987 (substring org-last-inserted-timestamp 1 -1))))
12988 (org-add-log-setup 'reschedule nil old-date 'findpos
12989 org-log-reschedule))
12990 (when repeater
12991 (save-excursion
12992 (org-back-to-heading t)
12993 (when (re-search-forward (concat org-scheduled-string " "
12994 org-last-inserted-timestamp)
12995 (save-excursion
12996 (outline-next-heading) (point)) t)
12997 (goto-char (1- (match-end 0)))
12998 (insert " " repeater)
12999 (setq org-last-inserted-timestamp
13000 (concat (substring org-last-inserted-timestamp 0 -1)
13001 " " repeater
13002 (substring org-last-inserted-timestamp -1))))))
13003 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13005 (defun org-get-scheduled-time (pom &optional inherit)
13006 "Get the scheduled time as a time tuple, of a format suitable
13007 for calling org-schedule with, or if there is no scheduling,
13008 returns nil."
13009 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13010 (when time
13011 (apply 'encode-time (org-parse-time-string time)))))
13013 (defun org-get-deadline-time (pom &optional inherit)
13014 "Get the deadline as a time tuple, of a format suitable for
13015 calling org-deadline with, or if there is no scheduling, returns
13016 nil."
13017 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13018 (when time
13019 (apply 'encode-time (org-parse-time-string time)))))
13021 (defun org-remove-timestamp-with-keyword (keyword)
13022 "Remove all time stamps with KEYWORD in the current entry."
13023 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13024 beg)
13025 (save-excursion
13026 (org-back-to-heading t)
13027 (setq beg (point))
13028 (outline-next-heading)
13029 (while (re-search-backward re beg t)
13030 (replace-match "")
13031 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13032 (equal (char-before) ?\ ))
13033 (backward-delete-char 1)
13034 (if (string-match "^[ \t]*$" (buffer-substring
13035 (point-at-bol) (point-at-eol)))
13036 (delete-region (point-at-bol)
13037 (min (point-max) (1+ (point-at-eol))))))))))
13039 (defun org-add-planning-info (what &optional time &rest remove)
13040 "Insert new timestamp with keyword in the line directly after the headline.
13041 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13042 If non is given, the user is prompted for a date.
13043 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13044 be removed."
13045 (interactive)
13046 (let (org-time-was-given org-end-time-was-given ts
13047 end default-time default-input)
13049 (catch 'exit
13050 (when (and (memq what '(scheduled deadline))
13051 (or (not time)
13052 (and (stringp time)
13053 (string-match "^[-+]+[0-9]" time))))
13054 ;; Try to get a default date/time from existing timestamp
13055 (save-excursion
13056 (org-back-to-heading t)
13057 (setq end (save-excursion (outline-next-heading) (point)))
13058 (when (re-search-forward (if (eq what 'scheduled)
13059 org-scheduled-time-regexp
13060 org-deadline-time-regexp)
13061 end t)
13062 (setq ts (match-string 1)
13063 default-time
13064 (apply 'encode-time (org-parse-time-string ts))
13065 default-input (and ts (org-get-compact-tod ts))))))
13066 (when what
13067 (setq time
13068 (if (stringp time)
13069 ;; This is a string (relative or absolute), set proper date
13070 (apply 'encode-time
13071 (org-read-date-analyze
13072 time default-time (decode-time default-time)))
13073 ;; If necessary, get the time from the user
13074 (or time (org-read-date nil 'to-time nil nil
13075 default-time default-input)))))
13077 (when (and org-insert-labeled-timestamps-at-point
13078 (member what '(scheduled deadline)))
13079 (insert
13080 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13081 (org-insert-time-stamp time org-time-was-given
13082 nil nil nil (list org-end-time-was-given))
13083 (setq what nil))
13084 (save-excursion
13085 (save-restriction
13086 (let (col list elt ts buffer-invisibility-spec)
13087 (org-back-to-heading t)
13088 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13089 (goto-char (match-end 1))
13090 (setq col (current-column))
13091 (goto-char (match-end 0))
13092 (if (eobp) (insert "\n") (forward-char 1))
13093 (when (and (not what)
13094 (not (looking-at
13095 (concat "[ \t]*"
13096 org-keyword-time-not-clock-regexp))))
13097 ;; Nothing to add, nothing to remove...... :-)
13098 (throw 'exit nil))
13099 (if (and (not (looking-at org-outline-regexp))
13100 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13101 "[^\r\n]*"))
13102 (not (equal (match-string 1) org-clock-string)))
13103 (narrow-to-region (match-beginning 0) (match-end 0))
13104 (insert-before-markers "\n")
13105 (backward-char 1)
13106 (narrow-to-region (point) (point))
13107 (and org-adapt-indentation (org-indent-to-column col)))
13108 ;; Check if we have to remove something.
13109 (setq list (cons what remove))
13110 (while list
13111 (setq elt (pop list))
13112 (when (or (and (eq elt 'scheduled)
13113 (re-search-forward org-scheduled-time-regexp nil t))
13114 (and (eq elt 'deadline)
13115 (re-search-forward org-deadline-time-regexp nil t))
13116 (and (eq elt 'closed)
13117 (re-search-forward org-closed-time-regexp nil t)))
13118 (replace-match "")
13119 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13120 (and (looking-at "[ \t]+") (replace-match ""))
13121 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13122 (when what
13123 (insert
13124 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13125 (cond ((eq what 'scheduled) org-scheduled-string)
13126 ((eq what 'deadline) org-deadline-string)
13127 ((eq what 'closed) org-closed-string))
13128 " ")
13129 (setq ts (org-insert-time-stamp
13130 time
13131 (or org-time-was-given
13132 (and (eq what 'closed) org-log-done-with-time))
13133 (eq what 'closed)
13134 nil nil (list org-end-time-was-given)))
13135 (insert
13136 (if (not (or (bolp) (eq (char-before) ?\ )
13137 (memq (char-after) '(32 10))
13138 (eobp))) " " ""))
13139 (end-of-line 1))
13140 (goto-char (point-min))
13141 (widen)
13142 (if (and (looking-at "[ \t]*\n")
13143 (equal (char-before) ?\n))
13144 (delete-region (1- (point)) (point-at-eol)))
13145 ts))))))
13147 (defvar org-log-note-marker (make-marker))
13148 (defvar org-log-note-purpose nil)
13149 (defvar org-log-note-state nil)
13150 (defvar org-log-note-previous-state nil)
13151 (defvar org-log-note-how nil)
13152 (defvar org-log-note-extra nil)
13153 (defvar org-log-note-window-configuration nil)
13154 (defvar org-log-note-return-to (make-marker))
13155 (defvar org-log-note-effective-time nil
13156 "Remembered current time so that dynamically scoped
13157 `org-extend-today-until' affects tha timestamps in state change
13158 log")
13160 (defvar org-log-post-message nil
13161 "Message to be displayed after a log note has been stored.
13162 The auto-repeater uses this.")
13164 (defun org-add-note ()
13165 "Add a note to the current entry.
13166 This is done in the same way as adding a state change note."
13167 (interactive)
13168 (org-add-log-setup 'note nil nil 'findpos nil))
13170 (defvar org-property-end-re)
13171 (defun org-add-log-setup (&optional purpose state prev-state
13172 findpos how extra)
13173 "Set up the post command hook to take a note.
13174 If this is about to TODO state change, the new state is expected in STATE.
13175 When FINDPOS is non-nil, find the correct position for the note in
13176 the current entry. If not, assume that it can be inserted at point.
13177 HOW is an indicator what kind of note should be created.
13178 EXTRA is additional text that will be inserted into the notes buffer."
13179 (let* ((org-log-into-drawer (org-log-into-drawer))
13180 (drawer (cond ((stringp org-log-into-drawer)
13181 org-log-into-drawer)
13182 (org-log-into-drawer "LOGBOOK"))))
13183 (save-restriction
13184 (save-excursion
13185 (when findpos
13186 (org-back-to-heading t)
13187 (narrow-to-region (point) (save-excursion
13188 (outline-next-heading) (point)))
13189 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13190 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13191 "[^\r\n]*\\)?"))
13192 (goto-char (match-end 0))
13193 (cond
13194 (drawer
13195 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13196 nil t)
13197 (progn
13198 (goto-char (match-end 0))
13199 (or org-log-states-order-reversed
13200 (and (re-search-forward org-property-end-re nil t)
13201 (goto-char (1- (match-beginning 0))))))
13202 (insert "\n:" drawer ":\n:END:")
13203 (beginning-of-line 0)
13204 (org-indent-line)
13205 (beginning-of-line 2)
13206 (org-indent-line)
13207 (end-of-line 0)))
13208 ((and org-log-state-notes-insert-after-drawers
13209 (save-excursion
13210 (forward-line) (looking-at org-drawer-regexp)))
13211 (forward-line)
13212 (while (looking-at org-drawer-regexp)
13213 (goto-char (match-end 0))
13214 (re-search-forward org-property-end-re (point-max) t)
13215 (forward-line))
13216 (forward-line -1)))
13217 (unless org-log-states-order-reversed
13218 (and (= (char-after) ?\n) (forward-char 1))
13219 (org-skip-over-state-notes)
13220 (skip-chars-backward " \t\n\r")))
13221 (move-marker org-log-note-marker (point))
13222 (setq org-log-note-purpose purpose
13223 org-log-note-state state
13224 org-log-note-previous-state prev-state
13225 org-log-note-how how
13226 org-log-note-extra extra
13227 org-log-note-effective-time (org-current-effective-time))
13228 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13230 (defun org-skip-over-state-notes ()
13231 "Skip past the list of State notes in an entry."
13232 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13233 (when (ignore-errors (goto-char (org-in-item-p)))
13234 (let* ((struct (org-list-struct))
13235 (prevs (org-list-prevs-alist struct)))
13236 (while (looking-at "[ \t]*- State")
13237 (goto-char (or (org-list-get-next-item (point) struct prevs)
13238 (org-list-get-item-end (point) struct)))))))
13240 (defun org-add-log-note (&optional purpose)
13241 "Pop up a window for taking a note, and add this note later at point."
13242 (remove-hook 'post-command-hook 'org-add-log-note)
13243 (setq org-log-note-window-configuration (current-window-configuration))
13244 (delete-other-windows)
13245 (move-marker org-log-note-return-to (point))
13246 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13247 (goto-char org-log-note-marker)
13248 (org-switch-to-buffer-other-window "*Org Note*")
13249 (erase-buffer)
13250 (if (memq org-log-note-how '(time state))
13251 (let (current-prefix-arg) (org-store-log-note))
13252 (let ((org-inhibit-startup t)) (org-mode))
13253 (insert (format "# Insert note for %s.
13254 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13255 (cond
13256 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13257 ((eq org-log-note-purpose 'done) "closed todo item")
13258 ((eq org-log-note-purpose 'state)
13259 (format "state change from \"%s\" to \"%s\""
13260 (or org-log-note-previous-state "")
13261 (or org-log-note-state "")))
13262 ((eq org-log-note-purpose 'reschedule)
13263 "rescheduling")
13264 ((eq org-log-note-purpose 'delschedule)
13265 "no longer scheduled")
13266 ((eq org-log-note-purpose 'redeadline)
13267 "changing deadline")
13268 ((eq org-log-note-purpose 'deldeadline)
13269 "removing deadline")
13270 ((eq org-log-note-purpose 'refile)
13271 "refiling")
13272 ((eq org-log-note-purpose 'note)
13273 "this entry")
13274 (t (error "This should not happen")))))
13275 (if org-log-note-extra (insert org-log-note-extra))
13276 (org-set-local 'org-finish-function 'org-store-log-note)
13277 (run-hooks 'org-log-buffer-setup-hook)))
13279 (defvar org-note-abort nil) ; dynamically scoped
13280 (defun org-store-log-note ()
13281 "Finish taking a log note, and insert it to where it belongs."
13282 (let ((txt (buffer-string)))
13283 (kill-buffer (current-buffer))
13284 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13285 lines ind bul)
13286 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13287 (setq txt (replace-match "" t t txt)))
13288 (if (string-match "\\s-+\\'" txt)
13289 (setq txt (replace-match "" t t txt)))
13290 (setq lines (org-split-string txt "\n"))
13291 (when (and note (string-match "\\S-" note))
13292 (setq note
13293 (org-replace-escapes
13294 note
13295 (list (cons "%u" (user-login-name))
13296 (cons "%U" user-full-name)
13297 (cons "%t" (format-time-string
13298 (org-time-stamp-format 'long 'inactive)
13299 org-log-note-effective-time))
13300 (cons "%T" (format-time-string
13301 (org-time-stamp-format 'long nil)
13302 org-log-note-effective-time))
13303 (cons "%d" (format-time-string
13304 (org-time-stamp-format nil 'inactive)
13305 org-log-note-effective-time))
13306 (cons "%D" (format-time-string
13307 (org-time-stamp-format nil nil)
13308 org-log-note-effective-time))
13309 (cons "%s" (if org-log-note-state
13310 (concat "\"" org-log-note-state "\"")
13311 ""))
13312 (cons "%S" (if org-log-note-previous-state
13313 (concat "\"" org-log-note-previous-state "\"")
13314 "\"\"")))))
13315 (if lines (setq note (concat note " \\\\")))
13316 (push note lines))
13317 (when (or current-prefix-arg org-note-abort)
13318 (when org-log-into-drawer
13319 (org-remove-empty-drawer-at
13320 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13321 org-log-note-marker))
13322 (setq lines nil))
13323 (when lines
13324 (with-current-buffer (marker-buffer org-log-note-marker)
13325 (save-excursion
13326 (goto-char org-log-note-marker)
13327 (move-marker org-log-note-marker nil)
13328 (end-of-line 1)
13329 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13330 (setq ind (save-excursion
13331 (if (ignore-errors (goto-char (org-in-item-p)))
13332 (let ((struct (org-list-struct)))
13333 (org-list-get-ind
13334 (org-list-get-top-point struct) struct))
13335 (skip-chars-backward " \r\t\n")
13336 (cond
13337 ((and (org-at-heading-p)
13338 org-adapt-indentation)
13339 (1+ (org-current-level)))
13340 ((org-at-heading-p) 0)
13341 (t (org-get-indentation))))))
13342 (setq bul (org-list-bullet-string "-"))
13343 (org-indent-line-to ind)
13344 (insert bul (pop lines))
13345 (let ((ind-body (+ (length bul) ind)))
13346 (while lines
13347 (insert "\n")
13348 (org-indent-line-to ind-body)
13349 (insert (pop lines))))
13350 (message "Note stored")
13351 (org-back-to-heading t)
13352 (org-cycle-hide-drawers 'children))
13353 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13354 ;; from within `org-add-log-note' because `buffer-undo-list'
13355 ;; is then modified outside of `org-with-remote-undo'.
13356 (when (eq this-command 'org-agenda-todo)
13357 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13358 ;; Don't add undo information when called from `org-agenda-todo'
13359 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13360 (set-window-configuration org-log-note-window-configuration)
13361 (with-current-buffer (marker-buffer org-log-note-return-to)
13362 (goto-char org-log-note-return-to))
13363 (move-marker org-log-note-return-to nil)
13364 (and org-log-post-message (message "%s" org-log-post-message))))
13366 (defun org-remove-empty-drawer-at (drawer pos)
13367 "Remove an empty drawer DRAWER at position POS.
13368 POS may also be a marker."
13369 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13370 (save-excursion
13371 (save-restriction
13372 (widen)
13373 (goto-char pos)
13374 (if (org-in-regexp
13375 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13376 (replace-match ""))))))
13378 (defvar org-ts-type nil)
13379 (defun org-sparse-tree (&optional arg type)
13380 "Create a sparse tree, prompt for the details.
13381 This command can create sparse trees. You first need to select the type
13382 of match used to create the tree:
13384 t Show all TODO entries.
13385 T Show entries with a specific TODO keyword.
13386 m Show entries selected by a tags/property match.
13387 p Enter a property name and its value (both with completion on existing
13388 names/values) and show entries with that property.
13389 r Show entries matching a regular expression (`/' can be used as well).
13390 b Show deadlines and scheduled items before a date.
13391 a Show deadlines and scheduled items after a date.
13392 d Show deadlines due within `org-deadline-warning-days'.
13393 D Show deadlines and scheduled items between a date range."
13394 (interactive "P")
13395 (let (ans kwd value ts-type)
13396 (setq type (or type org-sparse-tree-default-date-type))
13397 (setq org-ts-type type)
13398 (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"
13399 (cond ((eq type 'all) "all timestamps")
13400 ((eq type 'scheduled) "only scheduled")
13401 ((eq type 'deadline) "only deadline")
13402 ((eq type 'active) "only active timestamps")
13403 ((eq type 'inactive) "only inactive timestamps")
13404 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13405 ((eq type 'closed) "with a closed time-stamp")
13406 (t "scheduled/deadline")))
13407 (setq ans (read-char-exclusive))
13408 (cond
13409 ((equal ans ?c)
13410 (org-sparse-tree
13411 arg (cadr (member type '(scheduled-or-deadline
13412 all scheduled deadline active inactive closed)))))
13413 ((equal ans ?d)
13414 (call-interactively 'org-check-deadlines))
13415 ((equal ans ?b)
13416 (call-interactively 'org-check-before-date))
13417 ((equal ans ?a)
13418 (call-interactively 'org-check-after-date))
13419 ((equal ans ?D)
13420 (call-interactively 'org-check-dates-range))
13421 ((equal ans ?t)
13422 (call-interactively 'org-show-todo-tree))
13423 ((equal ans ?T)
13424 (org-show-todo-tree '(4)))
13425 ((member ans '(?T ?m))
13426 (call-interactively 'org-match-sparse-tree))
13427 ((member ans '(?p ?P))
13428 (setq kwd (org-icompleting-read "Property: "
13429 (mapcar 'list (org-buffer-property-keys))))
13430 (setq value (org-icompleting-read "Value: "
13431 (mapcar 'list (org-property-values kwd))))
13432 (unless (string-match "\\`{.*}\\'" value)
13433 (setq value (concat "\"" value "\"")))
13434 (org-match-sparse-tree arg (concat kwd "=" value)))
13435 ((member ans '(?r ?R ?/))
13436 (call-interactively 'org-occur))
13437 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13439 (defvar org-occur-highlights nil
13440 "List of overlays used for occur matches.")
13441 (make-variable-buffer-local 'org-occur-highlights)
13442 (defvar org-occur-parameters nil
13443 "Parameters of the active org-occur calls.
13444 This is a list, each call to org-occur pushes as cons cell,
13445 containing the regular expression and the callback, onto the list.
13446 The list can contain several entries if `org-occur' has been called
13447 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13448 will only contain one set of parameters. When the highlights are
13449 removed (for example with `C-c C-c', or with the next edit (depending
13450 on `org-remove-highlights-with-change'), this variable is emptied
13451 as well.")
13452 (make-variable-buffer-local 'org-occur-parameters)
13454 (defun org-occur (regexp &optional keep-previous callback)
13455 "Make a compact tree which shows all matches of REGEXP.
13456 The tree will show the lines where the regexp matches, and all higher
13457 headlines above the match. It will also show the heading after the match,
13458 to make sure editing the matching entry is easy.
13459 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13460 call to `org-occur' will be kept, to allow stacking of calls to this
13461 command.
13462 If CALLBACK is non-nil, it is a function which is called to confirm
13463 that the match should indeed be shown."
13464 (interactive "sRegexp: \nP")
13465 (when (equal regexp "")
13466 (user-error "Regexp cannot be empty"))
13467 (unless keep-previous
13468 (org-remove-occur-highlights nil nil t))
13469 (push (cons regexp callback) org-occur-parameters)
13470 (let ((cnt 0))
13471 (save-excursion
13472 (goto-char (point-min))
13473 (if (or (not keep-previous) ; do not want to keep
13474 (not org-occur-highlights)) ; no previous matches
13475 ;; hide everything
13476 (org-overview))
13477 (while (re-search-forward regexp nil t)
13478 (when (or (not callback)
13479 (save-match-data (funcall callback)))
13480 (setq cnt (1+ cnt))
13481 (when org-highlight-sparse-tree-matches
13482 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13483 (org-show-context 'occur-tree))))
13484 (when org-remove-highlights-with-change
13485 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13486 nil 'local))
13487 (unless org-sparse-tree-open-archived-trees
13488 (org-hide-archived-subtrees (point-min) (point-max)))
13489 (run-hooks 'org-occur-hook)
13490 (if (org-called-interactively-p 'interactive)
13491 (message "%d match(es) for regexp %s" cnt regexp))
13492 cnt))
13494 (defun org-occur-next-match (&optional n reset)
13495 "Function for `next-error-function' to find sparse tree matches.
13496 N is the number of matches to move, when negative move backwards.
13497 RESET is entirely ignored - this function always goes back to the
13498 starting point when no match is found."
13499 (let* ((limit (if (< n 0) (point-min) (point-max)))
13500 (search-func (if (< n 0)
13501 'previous-single-char-property-change
13502 'next-single-char-property-change))
13503 (n (abs n))
13504 (pos (point))
13506 (catch 'exit
13507 (while (setq p1 (funcall search-func (point) 'org-type))
13508 (when (equal p1 limit)
13509 (goto-char pos)
13510 (error "No more matches"))
13511 (when (equal (get-char-property p1 'org-type) 'org-occur)
13512 (setq n (1- n))
13513 (when (= n 0)
13514 (goto-char p1)
13515 (throw 'exit (point))))
13516 (goto-char p1))
13517 (goto-char p1)
13518 (error "No more matches"))))
13520 (defun org-show-context (&optional key)
13521 "Make sure point and context are visible.
13522 How much context is shown depends upon the variables
13523 `org-show-hierarchy-above', `org-show-following-heading',
13524 `org-show-entry-below' and `org-show-siblings'."
13525 (let ((heading-p (org-at-heading-p t))
13526 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13527 (following-p (org-get-alist-option org-show-following-heading key))
13528 (entry-p (org-get-alist-option org-show-entry-below key))
13529 (siblings-p (org-get-alist-option org-show-siblings key)))
13530 ;; Show heading or entry text
13531 (if (and heading-p (not entry-p))
13532 (org-flag-heading nil) ; only show the heading
13533 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13534 (org-show-hidden-entry))) ; show entire entry
13535 (when following-p
13536 ;; Show next sibling, or heading below text
13537 (save-excursion
13538 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13539 (org-flag-heading nil))))
13540 (when siblings-p (org-show-siblings))
13541 (when hierarchy-p
13542 ;; show all higher headings, possibly with siblings
13543 (save-excursion
13544 (while (and (condition-case nil
13545 (progn (org-up-heading-all 1) t)
13546 (error nil))
13547 (not (bobp)))
13548 (org-flag-heading nil)
13549 (when siblings-p (org-show-siblings)))))
13550 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13552 (defvar org-reveal-start-hook nil
13553 "Hook run before revealing a location.")
13555 (defun org-reveal (&optional siblings)
13556 "Show current entry, hierarchy above it, and the following headline.
13557 This can be used to show a consistent set of context around locations
13558 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13559 not t for the search context.
13561 With optional argument SIBLINGS, on each level of the hierarchy all
13562 siblings are shown. This repairs the tree structure to what it would
13563 look like when opened with hierarchical calls to `org-cycle'.
13564 With double optional argument \\[universal-argument] \\[universal-argument], \
13565 go to the parent and show the
13566 entire tree."
13567 (interactive "P")
13568 (run-hooks 'org-reveal-start-hook)
13569 (let ((org-show-hierarchy-above t)
13570 (org-show-following-heading t)
13571 (org-show-siblings (if siblings t org-show-siblings)))
13572 (org-show-context nil))
13573 (when (equal siblings '(16))
13574 (save-excursion
13575 (when (org-up-heading-safe)
13576 (org-show-subtree)
13577 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13579 (defun org-highlight-new-match (beg end)
13580 "Highlight from BEG to END and mark the highlight is an occur headline."
13581 (let ((ov (make-overlay beg end)))
13582 (overlay-put ov 'face 'secondary-selection)
13583 (overlay-put ov 'org-type 'org-occur)
13584 (push ov org-occur-highlights)))
13586 (defun org-remove-occur-highlights (&optional beg end noremove)
13587 "Remove the occur highlights from the buffer.
13588 BEG and END are ignored. If NOREMOVE is nil, remove this function
13589 from the `before-change-functions' in the current buffer."
13590 (interactive)
13591 (unless org-inhibit-highlight-removal
13592 (mapc 'delete-overlay org-occur-highlights)
13593 (setq org-occur-highlights nil)
13594 (setq org-occur-parameters nil)
13595 (unless noremove
13596 (remove-hook 'before-change-functions
13597 'org-remove-occur-highlights 'local))))
13599 ;;;; Priorities
13601 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13602 "Regular expression matching the priority indicator.")
13604 (defvar org-remove-priority-next-time nil)
13606 (defun org-priority-up ()
13607 "Increase the priority of the current item."
13608 (interactive)
13609 (org-priority 'up))
13611 (defun org-priority-down ()
13612 "Decrease the priority of the current item."
13613 (interactive)
13614 (org-priority 'down))
13616 (defun org-priority (&optional action show)
13617 "Change the priority of an item.
13618 ACTION can be `set', `up', `down', or a character."
13619 (interactive "P")
13620 (if (equal action '(4))
13621 (org-show-priority)
13622 (unless org-enable-priority-commands
13623 (user-error "Priority commands are disabled"))
13624 (setq action (or action 'set))
13625 (let (current new news have remove)
13626 (save-excursion
13627 (org-back-to-heading t)
13628 (if (looking-at org-priority-regexp)
13629 (setq current (string-to-char (match-string 2))
13630 have t))
13631 (cond
13632 ((eq action 'remove)
13633 (setq remove t new ?\ ))
13634 ((or (eq action 'set)
13635 (if (featurep 'xemacs) (characterp action) (integerp action)))
13636 (if (not (eq action 'set))
13637 (setq new action)
13638 (message "Priority %c-%c, SPC to remove: "
13639 org-highest-priority org-lowest-priority)
13640 (save-match-data
13641 (setq new (read-char-exclusive))))
13642 (if (and (= (upcase org-highest-priority) org-highest-priority)
13643 (= (upcase org-lowest-priority) org-lowest-priority))
13644 (setq new (upcase new)))
13645 (cond ((equal new ?\ ) (setq remove t))
13646 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13647 (user-error "Priority must be between `%c' and `%c'"
13648 org-highest-priority org-lowest-priority))))
13649 ((eq action 'up)
13650 (setq new (if have
13651 (1- current) ; normal cycling
13652 ;; last priority was empty
13653 (if (eq last-command this-command)
13654 org-lowest-priority ; wrap around empty to lowest
13655 ;; default
13656 (if org-priority-start-cycle-with-default
13657 org-default-priority
13658 (1- org-default-priority))))))
13659 ((eq action 'down)
13660 (setq new (if have
13661 (1+ current) ; normal cycling
13662 ;; last priority was empty
13663 (if (eq last-command this-command)
13664 org-highest-priority ; wrap around empty to highest
13665 ;; default
13666 (if org-priority-start-cycle-with-default
13667 org-default-priority
13668 (1+ org-default-priority))))))
13669 (t (user-error "Invalid action")))
13670 (if (or (< (upcase new) org-highest-priority)
13671 (> (upcase new) org-lowest-priority))
13672 (if (and (memq action '(up down))
13673 (not have) (not (eq last-command this-command)))
13674 ;; `new' is from default priority
13675 (error
13676 "The default can not be set, see `org-default-priority' why")
13677 ;; normal cycling: `new' is beyond highest/lowest priority
13678 ;; and is wrapped around to the empty priority
13679 (setq remove t)))
13680 (setq news (format "%c" new))
13681 (if have
13682 (if remove
13683 (replace-match "" t t nil 1)
13684 (replace-match news t t nil 2))
13685 (if remove
13686 (user-error "No priority cookie found in line")
13687 (let ((case-fold-search nil))
13688 (looking-at org-todo-line-regexp))
13689 (if (match-end 2)
13690 (progn
13691 (goto-char (match-end 2))
13692 (insert " [#" news "]"))
13693 (goto-char (match-beginning 3))
13694 (insert "[#" news "] "))))
13695 (org-preserve-lc (org-set-tags nil 'align)))
13696 (if remove
13697 (message "Priority removed")
13698 (message "Priority of current item set to %s" news)))))
13700 (defun org-show-priority ()
13701 "Show the priority of the current item.
13702 This priority is composed of the main priority given with the [#A] cookies,
13703 and by additional input from the age of a schedules or deadline entry."
13704 (interactive)
13705 (let ((pri (if (eq major-mode 'org-agenda-mode)
13706 (org-get-at-bol 'priority)
13707 (save-excursion
13708 (save-match-data
13709 (beginning-of-line)
13710 (and (looking-at org-heading-regexp)
13711 (org-get-priority (match-string 0))))))))
13712 (message "Priority is %d" (if pri pri -1000))))
13714 (defun org-get-priority (s)
13715 "Find priority cookie and return priority."
13716 (save-match-data
13717 (if (functionp org-get-priority-function)
13718 (funcall org-get-priority-function)
13719 (if (not (string-match org-priority-regexp s))
13720 (* 1000 (- org-lowest-priority org-default-priority))
13721 (* 1000 (- org-lowest-priority
13722 (string-to-char (match-string 2 s))))))))
13724 ;;;; Tags
13726 (defvar org-agenda-archives-mode)
13727 (defvar org-map-continue-from nil
13728 "Position from where mapping should continue.
13729 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13731 (defvar org-scanner-tags nil
13732 "The current tag list while the tags scanner is running.")
13733 (defvar org-trust-scanner-tags nil
13734 "Should `org-get-tags-at' use the tags for the scanner.
13735 This is for internal dynamical scoping only.
13736 When this is non-nil, the function `org-get-tags-at' will return the value
13737 of `org-scanner-tags' instead of building the list by itself. This
13738 can lead to large speed-ups when the tags scanner is used in a file with
13739 many entries, and when the list of tags is retrieved, for example to
13740 obtain a list of properties. Building the tags list for each entry in such
13741 a file becomes an N^2 operation - but with this variable set, it scales
13742 as N.")
13744 (defun org-scan-tags (action matcher todo-only &optional start-level)
13745 "Sca headline tags with inheritance and produce output ACTION.
13747 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13748 or `agenda' to produce an entry list for an agenda view. It can also be
13749 a Lisp form or a function that should be called at each matched headline, in
13750 this case the return value is a list of all return values from these calls.
13752 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13753 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13754 only lines with a not-done TODO keyword are included in the output.
13755 This should be the same variable that was scoped into
13756 and set by `org-make-tags-matcher' when it constructed MATCHER.
13758 START-LEVEL can be a string with asterisks, reducing the scope to
13759 headlines matching this string."
13760 (require 'org-agenda)
13761 (let* ((re (concat "^"
13762 (if start-level
13763 ;; Get the correct level to match
13764 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13765 org-outline-regexp)
13766 " *\\(\\<\\("
13767 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13768 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13769 (props (list 'face 'default
13770 'done-face 'org-agenda-done
13771 'undone-face 'default
13772 'mouse-face 'highlight
13773 'org-not-done-regexp org-not-done-regexp
13774 'org-todo-regexp org-todo-regexp
13775 'org-complex-heading-regexp org-complex-heading-regexp
13776 'help-echo
13777 (format "mouse-2 or RET jump to org file %s"
13778 (abbreviate-file-name
13779 (or (buffer-file-name (buffer-base-buffer))
13780 (buffer-name (buffer-base-buffer)))))))
13781 (case-fold-search nil)
13782 (org-map-continue-from nil)
13783 lspos tags tags-list
13784 (tags-alist (list (cons 0 org-file-tags)))
13785 (llast 0) rtn rtn1 level category i txt
13786 todo marker entry priority)
13787 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13788 (setq action (list 'lambda nil action)))
13789 (save-excursion
13790 (goto-char (point-min))
13791 (when (eq action 'sparse-tree)
13792 (org-overview)
13793 (org-remove-occur-highlights))
13794 (while (re-search-forward re nil t)
13795 (setq org-map-continue-from nil)
13796 (catch :skip
13797 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13798 tags (if (match-end 4) (org-match-string-no-properties 4)))
13799 (goto-char (setq lspos (match-beginning 0)))
13800 (setq level (org-reduced-level (org-outline-level))
13801 category (org-get-category))
13802 (setq i llast llast level)
13803 ;; remove tag lists from same and sublevels
13804 (while (>= i level)
13805 (when (setq entry (assoc i tags-alist))
13806 (setq tags-alist (delete entry tags-alist)))
13807 (setq i (1- i)))
13808 ;; add the next tags
13809 (when tags
13810 (setq tags (org-split-string tags ":")
13811 tags-alist
13812 (cons (cons level tags) tags-alist)))
13813 ;; compile tags for current headline
13814 (setq tags-list
13815 (if org-use-tag-inheritance
13816 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13817 tags)
13818 org-scanner-tags tags-list)
13819 (when org-use-tag-inheritance
13820 (setcdr (car tags-alist)
13821 (mapcar (lambda (x)
13822 (setq x (copy-sequence x))
13823 (org-add-prop-inherited x))
13824 (cdar tags-alist))))
13825 (when (and tags org-use-tag-inheritance
13826 (or (not (eq t org-use-tag-inheritance))
13827 org-tags-exclude-from-inheritance))
13828 ;; selective inheritance, remove uninherited ones
13829 (setcdr (car tags-alist)
13830 (org-remove-uninherited-tags (cdar tags-alist))))
13831 (when (and
13833 ;; eval matcher only when the todo condition is OK
13834 (and (or (not todo-only) (member todo org-not-done-keywords))
13835 (let ((case-fold-search t) (org-trust-scanner-tags t))
13836 (eval matcher)))
13838 ;; Call the skipper, but return t if it does not skip,
13839 ;; so that the `and' form continues evaluating
13840 (progn
13841 (unless (eq action 'sparse-tree) (org-agenda-skip))
13844 ;; Check if timestamps are deselecting this entry
13845 (or (not todo-only)
13846 (and (member todo org-not-done-keywords)
13847 (or (not org-agenda-tags-todo-honor-ignore-options)
13848 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13850 ;; select this headline
13851 (cond
13852 ((eq action 'sparse-tree)
13853 (and org-highlight-sparse-tree-matches
13854 (org-get-heading) (match-end 0)
13855 (org-highlight-new-match
13856 (match-beginning 1) (match-end 1)))
13857 (org-show-context 'tags-tree))
13858 ((eq action 'agenda)
13859 (setq txt (org-agenda-format-item
13861 (concat
13862 (if (eq org-tags-match-list-sublevels 'indented)
13863 (make-string (1- level) ?.) "")
13864 (org-get-heading))
13865 level category
13866 tags-list)
13867 priority (org-get-priority txt))
13868 (goto-char lspos)
13869 (setq marker (org-agenda-new-marker))
13870 (org-add-props txt props
13871 'org-marker marker 'org-hd-marker marker 'org-category category
13872 'todo-state todo
13873 'priority priority 'type "tagsmatch")
13874 (push txt rtn))
13875 ((functionp action)
13876 (setq org-map-continue-from nil)
13877 (save-excursion
13878 (setq rtn1 (funcall action))
13879 (push rtn1 rtn)))
13880 (t (user-error "Invalid action")))
13882 ;; if we are to skip sublevels, jump to end of subtree
13883 (unless org-tags-match-list-sublevels
13884 (org-end-of-subtree t)
13885 (backward-char 1))))
13886 ;; Get the correct position from where to continue
13887 (if org-map-continue-from
13888 (goto-char org-map-continue-from)
13889 (and (= (point) lspos) (end-of-line 1)))))
13890 (when (and (eq action 'sparse-tree)
13891 (not org-sparse-tree-open-archived-trees))
13892 (org-hide-archived-subtrees (point-min) (point-max)))
13893 (nreverse rtn)))
13895 (defun org-remove-uninherited-tags (tags)
13896 "Remove all tags that are not inherited from the list TAGS."
13897 (cond
13898 ((eq org-use-tag-inheritance t)
13899 (if org-tags-exclude-from-inheritance
13900 (org-delete-all org-tags-exclude-from-inheritance tags)
13901 tags))
13902 ((not org-use-tag-inheritance) nil)
13903 ((stringp org-use-tag-inheritance)
13904 (delq nil (mapcar
13905 (lambda (x)
13906 (if (and (string-match org-use-tag-inheritance x)
13907 (not (member x org-tags-exclude-from-inheritance)))
13908 x nil))
13909 tags)))
13910 ((listp org-use-tag-inheritance)
13911 (delq nil (mapcar
13912 (lambda (x)
13913 (if (member x org-use-tag-inheritance) x nil))
13914 tags)))))
13916 (defun org-match-sparse-tree (&optional todo-only match)
13917 "Create a sparse tree according to tags string MATCH.
13918 MATCH can contain positive and negative selection of tags, like
13919 \"+WORK+URGENT-WITHBOSS\".
13920 If optional argument TODO-ONLY is non-nil, only select lines that are
13921 also TODO lines."
13922 (interactive "P")
13923 (org-agenda-prepare-buffers (list (current-buffer)))
13924 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13926 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13928 (defvar org-cached-props nil)
13929 (defun org-cached-entry-get (pom property)
13930 (if (or (eq t org-use-property-inheritance)
13931 (and (stringp org-use-property-inheritance)
13932 (string-match org-use-property-inheritance property))
13933 (and (listp org-use-property-inheritance)
13934 (member property org-use-property-inheritance)))
13935 ;; Caching is not possible, check it directly
13936 (org-entry-get pom property 'inherit)
13937 ;; Get all properties, so that we can do complicated checks easily
13938 (cdr (assoc property (or org-cached-props
13939 (setq org-cached-props
13940 (org-entry-properties pom)))))))
13942 (defun org-global-tags-completion-table (&optional files)
13943 "Return the list of all tags in all agenda buffer/files.
13944 Optional FILES argument is a list of files which can be used
13945 instead of the agenda files."
13946 (save-excursion
13947 (org-uniquify
13948 (delq nil
13949 (apply 'append
13950 (mapcar
13951 (lambda (file)
13952 (set-buffer (find-file-noselect file))
13953 (append (org-get-buffer-tags)
13954 (mapcar (lambda (x) (if (stringp (car-safe x))
13955 (list (car-safe x)) nil))
13956 org-tag-alist)))
13957 (if (and files (car files))
13958 files
13959 (org-agenda-files))))))))
13961 (defun org-make-tags-matcher (match)
13962 "Create the TAGS/TODO matcher form for the selection string MATCH.
13964 The variable `todo-only' is scoped dynamically into this function.
13965 It will be set to t if the matcher restricts matching to TODO entries,
13966 otherwise will not be touched.
13968 Returns a cons of the selection string MATCH and the constructed
13969 lisp form implementing the matcher. The matcher is to be evaluated
13970 at an Org entry, with point on the headline, and returns t if the
13971 entry matches the selection string MATCH. The returned lisp form
13972 references two variables with information about the entry, which
13973 must be bound around the form's evaluation: todo, the TODO keyword
13974 at the entry (or nil of none); and tags-list, the list of all tags
13975 at the entry including inherited ones. Additionally, the category
13976 of the entry (if any) must be specified as the text property
13977 'org-category on the headline.
13979 See also `org-scan-tags'.
13981 (declare (special todo-only))
13982 (unless (boundp 'todo-only)
13983 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
13984 (unless match
13985 ;; Get a new match request, with completion against the global
13986 ;; tags table and the local tags in current buffer
13987 (let ((org-last-tags-completion-table
13988 (org-uniquify
13989 (delq nil (append (org-get-buffer-tags)
13990 (org-global-tags-completion-table))))))
13991 (setq match (org-completing-read-no-i
13992 "Match: " 'org-tags-completion-function nil nil nil
13993 'org-tags-history))))
13995 ;; Parse the string and create a lisp form
13996 (let ((match0 match)
13997 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13998 minus tag mm
13999 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14000 orterms term orlist re-p str-p level-p level-op time-p
14001 prop-p pn pv po gv rest)
14002 ;; Expand group tags
14003 (setq match (org-tags-expand match))
14004 (if (string-match "/+" match)
14005 ;; match contains also a todo-matching request
14006 (progn
14007 (setq tagsmatch (substring match 0 (match-beginning 0))
14008 todomatch (substring match (match-end 0)))
14009 (if (string-match "^!" todomatch)
14010 (setq todo-only t todomatch (substring todomatch 1)))
14011 (if (string-match "^\\s-*$" todomatch)
14012 (setq todomatch nil)))
14013 ;; only matching tags
14014 (setq tagsmatch match todomatch nil))
14016 ;; Make the tags matcher
14017 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14018 (setq tagsmatcher t)
14019 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14020 (while (setq term (pop orterms))
14021 (while (and (equal (substring term -1) "\\") orterms)
14022 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14023 (while (string-match re term)
14024 (setq rest (substring term (match-end 0))
14025 minus (and (match-end 1)
14026 (equal (match-string 1 term) "-"))
14027 tag (save-match-data (replace-regexp-in-string
14028 "\\\\-" "-"
14029 (match-string 2 term)))
14030 re-p (equal (string-to-char tag) ?{)
14031 level-p (match-end 4)
14032 prop-p (match-end 5)
14033 mm (cond
14034 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14035 (level-p
14036 (setq level-op (org-op-to-function (match-string 3 term)))
14037 `(,level-op level ,(string-to-number
14038 (match-string 4 term))))
14039 (prop-p
14040 (setq pn (match-string 5 term)
14041 po (match-string 6 term)
14042 pv (match-string 7 term)
14043 re-p (equal (string-to-char pv) ?{)
14044 str-p (equal (string-to-char pv) ?\")
14045 time-p (save-match-data
14046 (string-match "^\"[[<].*[]>]\"$" pv))
14047 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14048 (if time-p (setq pv (org-matcher-time pv)))
14049 (setq po (org-op-to-function po (if time-p 'time str-p)))
14050 (cond
14051 ((equal pn "CATEGORY")
14052 (setq gv '(get-text-property (point) 'org-category)))
14053 ((equal pn "TODO")
14054 (setq gv 'todo))
14056 (setq gv `(org-cached-entry-get nil ,pn))))
14057 (if re-p
14058 (if (eq po 'org<>)
14059 `(not (string-match ,pv (or ,gv "")))
14060 `(string-match ,pv (or ,gv "")))
14061 (if str-p
14062 `(,po (or ,gv "") ,pv)
14063 `(,po (string-to-number (or ,gv ""))
14064 ,(string-to-number pv) ))))
14065 (t `(member ,tag tags-list)))
14066 mm (if minus (list 'not mm) mm)
14067 term rest)
14068 (push mm tagsmatcher))
14069 (push (if (> (length tagsmatcher) 1)
14070 (cons 'and tagsmatcher)
14071 (car tagsmatcher))
14072 orlist)
14073 (setq tagsmatcher nil))
14074 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14075 (setq tagsmatcher
14076 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14077 ;; Make the todo matcher
14078 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14079 (setq todomatcher t)
14080 (setq orterms (org-split-string todomatch "|") orlist nil)
14081 (while (setq term (pop orterms))
14082 (while (string-match re term)
14083 (setq minus (and (match-end 1)
14084 (equal (match-string 1 term) "-"))
14085 kwd (match-string 2 term)
14086 re-p (equal (string-to-char kwd) ?{)
14087 term (substring term (match-end 0))
14088 mm (if re-p
14089 `(string-match ,(substring kwd 1 -1) todo)
14090 (list 'equal 'todo kwd))
14091 mm (if minus (list 'not mm) mm))
14092 (push mm todomatcher))
14093 (push (if (> (length todomatcher) 1)
14094 (cons 'and todomatcher)
14095 (car todomatcher))
14096 orlist)
14097 (setq todomatcher nil))
14098 (setq todomatcher (if (> (length orlist) 1)
14099 (cons 'or orlist) (car orlist))))
14101 ;; Return the string and lisp forms of the matcher
14102 (setq matcher (if todomatcher
14103 (list 'and tagsmatcher todomatcher)
14104 tagsmatcher))
14105 (when todo-only
14106 (setq matcher (list 'and '(member todo org-not-done-keywords)
14107 matcher)))
14108 (cons match0 matcher)))
14110 (defun org-tags-expand (match &optional single-as-list downcased)
14111 "Expand group tags in MATCH.
14113 This replaces every group tag in MATCH with a regexp tag search.
14114 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14115 will be replaced like this:
14117 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14118 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14119 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14121 Replacing by a regexp preserves the structure of the match.
14122 E.g., this expansion
14124 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14126 will match anything tagged with \"Lab\" and \"Home\", or tagged
14127 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14129 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14130 assumed to be a single group tag, and the function will return
14131 the list of tags in this group.
14133 When DOWNCASE is non-nil, expand downcased TAGS."
14134 (if org-group-tags
14135 (let* ((case-fold-search t)
14136 (stable org-mode-syntax-table)
14137 (tal (or org-tag-groups-alist-for-agenda
14138 org-tag-groups-alist))
14139 (tal (if downcased
14140 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14141 (tml (mapcar 'car tal))
14142 (rtnmatch match) rpl)
14143 ;; @ and _ are allowed as word-components in tags
14144 (modify-syntax-entry ?@ "w" stable)
14145 (modify-syntax-entry ?_ "w" stable)
14146 (while (and tml
14147 (string-match
14148 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14149 (regexp-opt tml) "\\>\\)") rtnmatch))
14150 (let* ((dir (match-string 1 rtnmatch))
14151 (tag (match-string 2 rtnmatch))
14152 (tag (if downcased (downcase tag) tag)))
14153 (setq tml (delete tag tml))
14154 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14155 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14156 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14157 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14158 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14159 (if single-as-list
14160 (or (reverse rpl) (list rtnmatch))
14161 rtnmatch))
14162 (if single-as-list (list (if downcased (downcase match) match))
14163 match)))
14165 (defun org-op-to-function (op &optional stringp)
14166 "Turn an operator into the appropriate function."
14167 (setq op
14168 (cond
14169 ((equal op "<" ) '(< string< org-time<))
14170 ((equal op ">" ) '(> org-string> org-time>))
14171 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14172 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14173 ((member op '("=" "==")) '(= string= org-time=))
14174 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14175 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14177 (defun org<> (a b) (not (= a b)))
14178 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14179 (defun org-string>= (a b) (not (string< a b)))
14180 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14181 (defun org-string<> (a b) (not (string= a b)))
14182 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14183 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14184 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14185 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14186 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14187 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14188 (defun org-2ft (s)
14189 "Convert S to a floating point time.
14190 If S is already a number, just return it. If it is a string, parse
14191 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14192 (cond
14193 ((numberp s) s)
14194 ((stringp s)
14195 (condition-case nil
14196 (float-time (apply 'encode-time (org-parse-time-string s)))
14197 (error 0.)))
14198 (t 0.)))
14200 (defun org-time-today ()
14201 "Time in seconds today at 0:00.
14202 Returns the float number of seconds since the beginning of the
14203 epoch to the beginning of today (00:00)."
14204 (float-time (apply 'encode-time
14205 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14207 (defun org-matcher-time (s)
14208 "Interpret a time comparison value."
14209 (save-match-data
14210 (cond
14211 ((string= s "<now>") (float-time))
14212 ((string= s "<today>") (org-time-today))
14213 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14214 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14215 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14216 (+ (org-time-today)
14217 (* (string-to-number (match-string 1 s))
14218 (cdr (assoc (match-string 2 s)
14219 '(("d" . 86400.0) ("w" . 604800.0)
14220 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14221 (t (org-2ft s)))))
14223 (defun org-match-any-p (re list)
14224 "Does re match any element of list?"
14225 (setq list (mapcar (lambda (x) (string-match re x)) list))
14226 (delq nil list))
14228 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14229 (defvar org-tags-overlay (make-overlay 1 1))
14230 (org-detach-overlay org-tags-overlay)
14232 (defun org-get-local-tags-at (&optional pos)
14233 "Get a list of tags defined in the current headline."
14234 (org-get-tags-at pos 'local))
14236 (defun org-get-local-tags ()
14237 "Get a list of tags defined in the current headline."
14238 (org-get-tags-at nil 'local))
14240 (defun org-get-tags-at (&optional pos local)
14241 "Get a list of all headline tags applicable at POS.
14242 POS defaults to point. If tags are inherited, the list contains
14243 the targets in the same sequence as the headlines appear, i.e.
14244 the tags of the current headline come last.
14245 When LOCAL is non-nil, only return tags from the current headline,
14246 ignore inherited ones."
14247 (interactive)
14248 (if (and org-trust-scanner-tags
14249 (or (not pos) (equal pos (point)))
14250 (not local))
14251 org-scanner-tags
14252 (let (tags ltags lastpos parent)
14253 (save-excursion
14254 (save-restriction
14255 (widen)
14256 (goto-char (or pos (point)))
14257 (save-match-data
14258 (catch 'done
14259 (condition-case nil
14260 (progn
14261 (org-back-to-heading t)
14262 (while (not (equal lastpos (point)))
14263 (setq lastpos (point))
14264 (when (looking-at
14265 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14266 (setq ltags (org-split-string
14267 (org-match-string-no-properties 1) ":"))
14268 (when parent
14269 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14270 (setq tags (append
14271 (if parent
14272 (org-remove-uninherited-tags ltags)
14273 ltags)
14274 tags)))
14275 (or org-use-tag-inheritance (throw 'done t))
14276 (if local (throw 'done t))
14277 (or (org-up-heading-safe) (error nil))
14278 (setq parent t)))
14279 (error nil)))))
14280 (if local
14281 tags
14282 (reverse (delete-dups
14283 (reverse (append
14284 (org-remove-uninherited-tags
14285 org-file-tags) tags)))))))))
14287 (defun org-add-prop-inherited (s)
14288 (add-text-properties 0 (length s) '(inherited t) s)
14291 (defun org-toggle-tag (tag &optional onoff)
14292 "Toggle the tag TAG for the current line.
14293 If ONOFF is `on' or `off', don't toggle but set to this state."
14294 (let (res current)
14295 (save-excursion
14296 (org-back-to-heading t)
14297 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14298 (point-at-eol) t)
14299 (progn
14300 (setq current (match-string 1))
14301 (replace-match ""))
14302 (setq current ""))
14303 (setq current (nreverse (org-split-string current ":")))
14304 (cond
14305 ((eq onoff 'on)
14306 (setq res t)
14307 (or (member tag current) (push tag current)))
14308 ((eq onoff 'off)
14309 (or (not (member tag current)) (setq current (delete tag current))))
14310 (t (if (member tag current)
14311 (setq current (delete tag current))
14312 (setq res t)
14313 (push tag current))))
14314 (end-of-line 1)
14315 (if current
14316 (progn
14317 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14318 (org-set-tags nil t))
14319 (delete-horizontal-space))
14320 (run-hooks 'org-after-tags-change-hook))
14321 res))
14323 (defun org-align-tags-here (to-col)
14324 ;; Assumes that this is a headline
14325 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14326 (beginning-of-line 1)
14327 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14328 (< pos (match-beginning 2)))
14329 (progn
14330 (setq tags-l (- (match-end 2) (match-beginning 2)))
14331 (goto-char (match-beginning 1))
14332 (insert " ")
14333 (delete-region (point) (1+ (match-beginning 2)))
14334 (setq ncol (max (current-column)
14335 (1+ col)
14336 (if (> to-col 0)
14337 to-col
14338 (- (abs to-col) tags-l))))
14339 (setq p (point))
14340 (insert (make-string (- ncol (current-column)) ?\ ))
14341 (setq ncol (current-column))
14342 (when indent-tabs-mode (tabify p (point-at-eol)))
14343 (org-move-to-column (min ncol col) t))
14344 (goto-char pos))))
14346 (defun org-set-tags-command (&optional arg just-align)
14347 "Call the set-tags command for the current entry."
14348 (interactive "P")
14349 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14350 (org-set-tags arg just-align)
14351 (save-excursion
14352 (unless (and (org-region-active-p)
14353 org-loop-over-headlines-in-active-region)
14354 (org-back-to-heading t))
14355 (org-set-tags arg just-align))))
14357 (defun org-set-tags-to (data)
14358 "Set the tags of the current entry to DATA, replacing the current tags.
14359 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14360 If DATA is nil or the empty string, any tags will be removed."
14361 (interactive "sTags: ")
14362 (setq data
14363 (cond
14364 ((eq data nil) "")
14365 ((equal data "") "")
14366 ((stringp data)
14367 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14368 ":"))
14369 ((listp data)
14370 (concat ":" (mapconcat 'identity data ":") ":"))))
14371 (when data
14372 (save-excursion
14373 (org-back-to-heading t)
14374 (when (looking-at org-complex-heading-regexp)
14375 (if (match-end 5)
14376 (progn
14377 (goto-char (match-beginning 5))
14378 (insert data)
14379 (delete-region (point) (point-at-eol))
14380 (org-set-tags nil 'align))
14381 (goto-char (point-at-eol))
14382 (insert " " data)
14383 (org-set-tags nil 'align)))
14384 (beginning-of-line 1)
14385 (if (looking-at ".*?\\([ \t]+\\)$")
14386 (delete-region (match-beginning 1) (match-end 1))))))
14388 (defun org-align-all-tags ()
14389 "Align the tags i all headings."
14390 (interactive)
14391 (save-excursion
14392 (or (ignore-errors (org-back-to-heading t))
14393 (outline-next-heading))
14394 (if (org-at-heading-p)
14395 (org-set-tags t)
14396 (message "No headings"))))
14398 (defvar org-indent-indentation-per-level)
14399 (defun org-set-tags (&optional arg just-align)
14400 "Set the tags for the current headline.
14401 With prefix ARG, realign all tags in headings in the current buffer."
14402 (interactive "P")
14403 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14404 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14405 'region-start-level 'region))
14406 org-loop-over-headlines-in-active-region)
14407 (org-map-entries
14408 ;; We don't use ARG and JUST-ALIGN here these args are not
14409 ;; useful when looping over headlines
14410 `(org-set-tags)
14411 org-loop-over-headlines-in-active-region
14412 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14413 (let* ((re org-outline-regexp-bol)
14414 (current (unless arg (org-get-tags-string)))
14415 (col (current-column))
14416 (org-setting-tags t)
14417 table current-tags inherited-tags ; computed below when needed
14418 tags p0 c0 c1 rpl di tc level)
14419 (if arg
14420 (save-excursion
14421 (goto-char (point-min))
14422 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14423 (while (re-search-forward re nil t)
14424 (org-set-tags nil t)
14425 (end-of-line 1)))
14426 (message "All tags realigned to column %d" org-tags-column))
14427 (if just-align
14428 (setq tags current)
14429 ;; Get a new set of tags from the user
14430 (save-excursion
14431 (setq table (append org-tag-persistent-alist
14432 (or org-tag-alist (org-get-buffer-tags))
14433 (and
14434 org-complete-tags-always-offer-all-agenda-tags
14435 (org-global-tags-completion-table
14436 (org-agenda-files))))
14437 org-last-tags-completion-table table
14438 current-tags (org-split-string current ":")
14439 inherited-tags (nreverse
14440 (nthcdr (length current-tags)
14441 (nreverse (org-get-tags-at))))
14442 tags
14443 (if (or (eq t org-use-fast-tag-selection)
14444 (and org-use-fast-tag-selection
14445 (delq nil (mapcar 'cdr table))))
14446 (org-fast-tag-selection
14447 current-tags inherited-tags table
14448 (if org-fast-tag-selection-include-todo
14449 org-todo-key-alist))
14450 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14451 (org-trim
14452 (org-icompleting-read "Tags: "
14453 'org-tags-completion-function
14454 nil nil current 'org-tags-history))))))
14455 (while (string-match "[-+&]+" tags)
14456 ;; No boolean logic, just a list
14457 (setq tags (replace-match ":" t t tags))))
14459 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14461 (if org-tags-sort-function
14462 (setq tags (mapconcat 'identity
14463 (sort (org-split-string
14464 tags (org-re "[^[:alnum:]_@#%]+"))
14465 org-tags-sort-function) ":")))
14467 (if (string-match "\\`[\t ]*\\'" tags)
14468 (setq tags "")
14469 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14470 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14472 ;; Insert new tags at the correct column
14473 (beginning-of-line 1)
14474 (setq level (or (and (looking-at org-outline-regexp)
14475 (- (match-end 0) (point) 1))
14477 (cond
14478 ((and (equal current "") (equal tags "")))
14479 ((re-search-forward
14480 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14481 (point-at-eol) t)
14482 (if (equal tags "")
14483 (setq rpl "")
14484 (goto-char (match-beginning 0))
14485 (setq c0 (current-column)
14486 ;; compute offset for the case of org-indent-mode active
14487 di (if org-indent-mode
14488 (* (1- org-indent-indentation-per-level) (1- level))
14490 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14491 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14492 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14493 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14494 (replace-match rpl t t)
14495 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14496 tags)
14497 (t (error "Tags alignment failed")))
14498 (org-move-to-column col)
14499 (unless just-align
14500 (run-hooks 'org-after-tags-change-hook))))))
14502 (defun org-change-tag-in-region (beg end tag off)
14503 "Add or remove TAG for each entry in the region.
14504 This works in the agenda, and also in an org-mode buffer."
14505 (interactive
14506 (list (region-beginning) (region-end)
14507 (let ((org-last-tags-completion-table
14508 (if (derived-mode-p 'org-mode)
14509 (org-uniquify
14510 (delq nil (append (org-get-buffer-tags)
14511 (org-global-tags-completion-table))))
14512 (org-global-tags-completion-table))))
14513 (org-icompleting-read
14514 "Tag: " 'org-tags-completion-function nil nil nil
14515 'org-tags-history))
14516 (progn
14517 (message "[s]et or [r]emove? ")
14518 (equal (read-char-exclusive) ?r))))
14519 (if (fboundp 'deactivate-mark) (deactivate-mark))
14520 (let ((agendap (equal major-mode 'org-agenda-mode))
14521 l1 l2 m buf pos newhead (cnt 0))
14522 (goto-char end)
14523 (setq l2 (1- (org-current-line)))
14524 (goto-char beg)
14525 (setq l1 (org-current-line))
14526 (loop for l from l1 to l2 do
14527 (org-goto-line l)
14528 (setq m (get-text-property (point) 'org-hd-marker))
14529 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14530 (and agendap m))
14531 (setq buf (if agendap (marker-buffer m) (current-buffer))
14532 pos (if agendap m (point)))
14533 (with-current-buffer buf
14534 (save-excursion
14535 (save-restriction
14536 (goto-char pos)
14537 (setq cnt (1+ cnt))
14538 (org-toggle-tag tag (if off 'off 'on))
14539 (setq newhead (org-get-heading)))))
14540 (and agendap (org-agenda-change-all-lines newhead m))))
14541 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14543 (defun org-tags-completion-function (string predicate &optional flag)
14544 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14545 (confirm (lambda (x) (stringp (car x)))))
14546 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14547 (setq s1 (match-string 1 string)
14548 s2 (match-string 2 string))
14549 (setq s1 "" s2 string))
14550 (cond
14551 ((eq flag nil)
14552 ;; try completion
14553 (setq rtn (try-completion s2 ctable confirm))
14554 (if (stringp rtn)
14555 (setq rtn
14556 (concat s1 s2 (substring rtn (length s2))
14557 (if (and org-add-colon-after-tag-completion
14558 (assoc rtn ctable))
14559 ":" ""))))
14560 rtn)
14561 ((eq flag t)
14562 ;; all-completions
14563 (all-completions s2 ctable confirm))
14564 ((eq flag 'lambda)
14565 ;; exact match?
14566 (assoc s2 ctable)))))
14568 (defun org-fast-tag-insert (kwd tags face &optional end)
14569 "Insert KDW, and the TAGS, the latter with face FACE.
14570 Also insert END."
14571 (insert (format "%-12s" (concat kwd ":"))
14572 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14573 (or end "")))
14575 (defun org-fast-tag-show-exit (flag)
14576 (save-excursion
14577 (org-goto-line 3)
14578 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14579 (replace-match ""))
14580 (when flag
14581 (end-of-line 1)
14582 (org-move-to-column (- (window-width) 19) t)
14583 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14585 (defun org-set-current-tags-overlay (current prefix)
14586 "Add an overlay to CURRENT tag with PREFIX."
14587 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14588 (if (featurep 'xemacs)
14589 (org-overlay-display org-tags-overlay (concat prefix s)
14590 'secondary-selection)
14591 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14592 (org-overlay-display org-tags-overlay (concat prefix s)))))
14594 (defvar org-last-tag-selection-key nil)
14595 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14596 "Fast tag selection with single keys.
14597 CURRENT is the current list of tags in the headline, INHERITED is the
14598 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14599 possibly with grouping information. TODO-TABLE is a similar table with
14600 TODO keywords, should these have keys assigned to them.
14601 If the keys are nil, a-z are automatically assigned.
14602 Returns the new tags string, or nil to not change the current settings."
14603 (let* ((fulltable (append table todo-table))
14604 (maxlen (apply 'max (mapcar
14605 (lambda (x)
14606 (if (stringp (car x)) (string-width (car x)) 0))
14607 fulltable)))
14608 (buf (current-buffer))
14609 (expert (eq org-fast-tag-selection-single-key 'expert))
14610 (buffer-tags nil)
14611 (fwidth (+ maxlen 3 1 3))
14612 (ncol (/ (- (window-width) 4) fwidth))
14613 (i-face 'org-done)
14614 (c-face 'org-todo)
14615 tg cnt e c char c1 c2 ntable tbl rtn
14616 ov-start ov-end ov-prefix
14617 (exit-after-next org-fast-tag-selection-single-key)
14618 (done-keywords org-done-keywords)
14619 groups ingroup)
14620 (save-excursion
14621 (beginning-of-line 1)
14622 (if (looking-at
14623 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14624 (setq ov-start (match-beginning 1)
14625 ov-end (match-end 1)
14626 ov-prefix "")
14627 (setq ov-start (1- (point-at-eol))
14628 ov-end (1+ ov-start))
14629 (skip-chars-forward "^\n\r")
14630 (setq ov-prefix
14631 (concat
14632 (buffer-substring (1- (point)) (point))
14633 (if (> (current-column) org-tags-column)
14635 (make-string (- org-tags-column (current-column)) ?\ ))))))
14636 (move-overlay org-tags-overlay ov-start ov-end)
14637 (save-window-excursion
14638 (if expert
14639 (set-buffer (get-buffer-create " *Org tags*"))
14640 (delete-other-windows)
14641 (split-window-vertically)
14642 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14643 (erase-buffer)
14644 (org-set-local 'org-done-keywords done-keywords)
14645 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14646 (org-fast-tag-insert "Current" current c-face "\n\n")
14647 (org-fast-tag-show-exit exit-after-next)
14648 (org-set-current-tags-overlay current ov-prefix)
14649 (setq tbl fulltable char ?a cnt 0)
14650 (while (setq e (pop tbl))
14651 (cond
14652 ((equal (car e) :startgroup)
14653 (push '() groups) (setq ingroup t)
14654 (when (not (= cnt 0))
14655 (setq cnt 0)
14656 (insert "\n"))
14657 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14658 ((equal (car e) :endgroup)
14659 (setq ingroup nil cnt 0)
14660 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14661 ((equal e '(:newline))
14662 (when (not (= cnt 0))
14663 (setq cnt 0)
14664 (insert "\n")
14665 (setq e (car tbl))
14666 (while (equal (car tbl) '(:newline))
14667 (insert "\n")
14668 (setq tbl (cdr tbl)))))
14669 ((equal e '(:grouptags)) nil)
14671 (setq tg (copy-sequence (car e)) c2 nil)
14672 (if (cdr e)
14673 (setq c (cdr e))
14674 ;; automatically assign a character.
14675 (setq c1 (string-to-char
14676 (downcase (substring
14677 tg (if (= (string-to-char tg) ?@) 1 0)))))
14678 (if (or (rassoc c1 ntable) (rassoc c1 table))
14679 (while (or (rassoc char ntable) (rassoc char table))
14680 (setq char (1+ char)))
14681 (setq c2 c1))
14682 (setq c (or c2 char)))
14683 (if ingroup (push tg (car groups)))
14684 (setq tg (org-add-props tg nil 'face
14685 (cond
14686 ((not (assoc tg table))
14687 (org-get-todo-face tg))
14688 ((member tg current) c-face)
14689 ((member tg inherited) i-face))))
14690 (if (equal (caar tbl) :grouptags)
14691 (org-add-props tg nil 'face 'org-tag-group))
14692 (if (and (= cnt 0) (not ingroup)) (insert " "))
14693 (insert "[" c "] " tg (make-string
14694 (- fwidth 4 (length tg)) ?\ ))
14695 (push (cons tg c) ntable)
14696 (when (= (setq cnt (1+ cnt)) ncol)
14697 (insert "\n")
14698 (if ingroup (insert " "))
14699 (setq cnt 0)))))
14700 (setq ntable (nreverse ntable))
14701 (insert "\n")
14702 (goto-char (point-min))
14703 (if (not expert) (org-fit-window-to-buffer))
14704 (setq rtn
14705 (catch 'exit
14706 (while t
14707 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14708 (if (not groups) "no " "")
14709 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14710 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14711 (setq org-last-tag-selection-key c)
14712 (cond
14713 ((= c ?\r) (throw 'exit t))
14714 ((= c ?!)
14715 (setq groups (not groups))
14716 (goto-char (point-min))
14717 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14718 ((= c ?\C-c)
14719 (if (not expert)
14720 (org-fast-tag-show-exit
14721 (setq exit-after-next (not exit-after-next)))
14722 (setq expert nil)
14723 (delete-other-windows)
14724 (set-window-buffer (split-window-vertically) " *Org tags*")
14725 (org-switch-to-buffer-other-window " *Org tags*")
14726 (org-fit-window-to-buffer)))
14727 ((or (= c ?\C-g)
14728 (and (= c ?q) (not (rassoc c ntable))))
14729 (org-detach-overlay org-tags-overlay)
14730 (setq quit-flag t))
14731 ((= c ?\ )
14732 (setq current nil)
14733 (if exit-after-next (setq exit-after-next 'now)))
14734 ((= c ?\t)
14735 (condition-case nil
14736 (setq tg (org-icompleting-read
14737 "Tag: "
14738 (or buffer-tags
14739 (with-current-buffer buf
14740 (org-get-buffer-tags)))))
14741 (quit (setq tg "")))
14742 (when (string-match "\\S-" tg)
14743 (add-to-list 'buffer-tags (list tg))
14744 (if (member tg current)
14745 (setq current (delete tg current))
14746 (push tg current)))
14747 (if exit-after-next (setq exit-after-next 'now)))
14748 ((setq e (rassoc c todo-table) tg (car e))
14749 (with-current-buffer buf
14750 (save-excursion (org-todo tg)))
14751 (if exit-after-next (setq exit-after-next 'now)))
14752 ((setq e (rassoc c ntable) tg (car e))
14753 (if (member tg current)
14754 (setq current (delete tg current))
14755 (loop for g in groups do
14756 (if (member tg g)
14757 (mapc (lambda (x)
14758 (setq current (delete x current)))
14759 g)))
14760 (push tg current))
14761 (if exit-after-next (setq exit-after-next 'now))))
14763 ;; Create a sorted list
14764 (setq current
14765 (sort current
14766 (lambda (a b)
14767 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14768 (if (eq exit-after-next 'now) (throw 'exit t))
14769 (goto-char (point-min))
14770 (beginning-of-line 2)
14771 (delete-region (point) (point-at-eol))
14772 (org-fast-tag-insert "Current" current c-face)
14773 (org-set-current-tags-overlay current ov-prefix)
14774 (while (re-search-forward
14775 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14776 (setq tg (match-string 1))
14777 (add-text-properties
14778 (match-beginning 1) (match-end 1)
14779 (list 'face
14780 (cond
14781 ((member tg current) c-face)
14782 ((member tg inherited) i-face)
14783 (t (get-text-property (match-beginning 1) 'face))))))
14784 (goto-char (point-min)))))
14785 (org-detach-overlay org-tags-overlay)
14786 (if rtn
14787 (mapconcat 'identity current ":")
14788 nil))))
14790 (defun org-get-tags-string ()
14791 "Get the TAGS string in the current headline."
14792 (unless (org-at-heading-p t)
14793 (user-error "Not on a heading"))
14794 (save-excursion
14795 (beginning-of-line 1)
14796 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14797 (org-match-string-no-properties 1)
14798 "")))
14800 (defun org-get-tags ()
14801 "Get the list of tags specified in the current headline."
14802 (org-split-string (org-get-tags-string) ":"))
14804 (defun org-get-buffer-tags ()
14805 "Get a table of all tags used in the buffer, for completion."
14806 (let (tags)
14807 (save-excursion
14808 (goto-char (point-min))
14809 (while (re-search-forward
14810 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14811 (when (equal (char-after (point-at-bol 0)) ?*)
14812 (mapc (lambda (x) (add-to-list 'tags x))
14813 (org-split-string (org-match-string-no-properties 1) ":")))))
14814 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14815 (mapcar 'list tags)))
14817 ;;;; The mapping API
14819 (defun org-map-entries (func &optional match scope &rest skip)
14820 "Call FUNC at each headline selected by MATCH in SCOPE.
14822 FUNC is a function or a lisp form. The function will be called without
14823 arguments, with the cursor positioned at the beginning of the headline.
14824 The return values of all calls to the function will be collected and
14825 returned as a list.
14827 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14828 does not need to preserve point. After evaluation, the cursor will be
14829 moved to the end of the line (presumably of the headline of the
14830 processed entry) and search continues from there. Under some
14831 circumstances, this may not produce the wanted results. For example,
14832 if you have removed (e.g. archived) the current (sub)tree it could
14833 mean that the next entry will be skipped entirely. In such cases, you
14834 can specify the position from where search should continue by making
14835 FUNC set the variable `org-map-continue-from' to the desired buffer
14836 position.
14838 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14839 Only headlines that are matched by this query will be considered during
14840 the iteration. When MATCH is nil or t, all headlines will be
14841 visited by the iteration.
14843 SCOPE determines the scope of this command. It can be any of:
14845 nil The current buffer, respecting the restriction if any
14846 tree The subtree started with the entry at point
14847 region The entries within the active region, if any
14848 region-start-level
14849 The entries within the active region, but only those at
14850 the same level than the first one.
14851 file The current buffer, without restriction
14852 file-with-archives
14853 The current buffer, and any archives associated with it
14854 agenda All agenda files
14855 agenda-with-archives
14856 All agenda files with any archive files associated with them
14857 \(file1 file2 ...)
14858 If this is a list, all files in the list will be scanned
14860 The remaining args are treated as settings for the skipping facilities of
14861 the scanner. The following items can be given here:
14863 archive skip trees with the archive tag
14864 comment skip trees with the COMMENT keyword
14865 function or Emacs Lisp form:
14866 will be used as value for `org-agenda-skip-function', so
14867 whenever the function returns a position, FUNC will not be
14868 called for that entry and search will continue from the
14869 position returned
14871 If your function needs to retrieve the tags including inherited tags
14872 at the *current* entry, you can use the value of the variable
14873 `org-scanner-tags' which will be much faster than getting the value
14874 with `org-get-tags-at'. If your function gets properties with
14875 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14876 to t around the call to `org-entry-properties' to get the same speedup.
14877 Note that if your function moves around to retrieve tags and properties at
14878 a *different* entry, you cannot use these techniques."
14879 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14880 (not (org-region-active-p)))
14881 (let* ((org-agenda-archives-mode nil) ; just to make sure
14882 (org-agenda-skip-archived-trees (memq 'archive skip))
14883 (org-agenda-skip-comment-trees (memq 'comment skip))
14884 (org-agenda-skip-function
14885 (car (org-delete-all '(comment archive) skip)))
14886 (org-tags-match-list-sublevels t)
14887 (start-level (eq scope 'region-start-level))
14888 matcher file res
14889 org-todo-keywords-for-agenda
14890 org-done-keywords-for-agenda
14891 org-todo-keyword-alist-for-agenda
14892 org-drawers-for-agenda
14893 org-tag-alist-for-agenda
14894 todo-only)
14896 (cond
14897 ((eq match t) (setq matcher t))
14898 ((eq match nil) (setq matcher t))
14899 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14901 (save-window-excursion
14902 (save-restriction
14903 (cond ((eq scope 'tree)
14904 (org-back-to-heading t)
14905 (org-narrow-to-subtree)
14906 (setq scope nil))
14907 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14908 (org-region-active-p))
14909 ;; If needed, set start-level to a string like "2"
14910 (when start-level
14911 (save-excursion
14912 (goto-char (region-beginning))
14913 (unless (org-at-heading-p) (outline-next-heading))
14914 (setq start-level (org-current-level))))
14915 (narrow-to-region (region-beginning)
14916 (save-excursion
14917 (goto-char (region-end))
14918 (unless (and (bolp) (org-at-heading-p))
14919 (outline-next-heading))
14920 (point)))
14921 (setq scope nil)))
14923 (if (not scope)
14924 (progn
14925 (org-agenda-prepare-buffers
14926 (list (buffer-file-name (current-buffer))))
14927 (setq res (org-scan-tags func matcher todo-only start-level)))
14928 ;; Get the right scope
14929 (cond
14930 ((and scope (listp scope) (symbolp (car scope)))
14931 (setq scope (eval scope)))
14932 ((eq scope 'agenda)
14933 (setq scope (org-agenda-files t)))
14934 ((eq scope 'agenda-with-archives)
14935 (setq scope (org-agenda-files t))
14936 (setq scope (org-add-archive-files scope)))
14937 ((eq scope 'file)
14938 (setq scope (list (buffer-file-name))))
14939 ((eq scope 'file-with-archives)
14940 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14941 (org-agenda-prepare-buffers scope)
14942 (while (setq file (pop scope))
14943 (with-current-buffer (org-find-base-buffer-visiting file)
14944 (save-excursion
14945 (save-restriction
14946 (widen)
14947 (goto-char (point-min))
14948 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14949 res)))
14951 ;;;; Properties
14953 ;;; Setting and retrieving properties
14955 (defconst org-special-properties
14956 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14957 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14958 "The special properties valid in Org-mode.
14960 These are properties that are not defined in the property drawer,
14961 but in some other way.")
14963 (defconst org-default-properties
14964 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14965 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14966 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14967 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14968 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14969 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14970 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14971 "Some properties that are used by Org-mode for various purposes.
14972 Being in this list makes sure that they are offered for completion.")
14974 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14975 "Regular expression matching the first line of a property drawer.")
14977 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14978 "Regular expression matching the last line of a property drawer.")
14980 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14981 "Regular expression matching the first line of a property drawer.")
14983 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14984 "Regular expression matching the first line of a property drawer.")
14986 (defconst org-property-drawer-re
14987 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14988 org-property-end-re "\\)\n?")
14989 "Matches an entire property drawer.")
14991 (defconst org-clock-drawer-re
14992 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14993 org-property-end-re "\\)\n?")
14994 "Matches an entire clock drawer.")
14996 (defsubst org-re-property (property)
14997 "Return a regexp matching a PROPERTY line.
14998 Match group 1 will be set to the value."
14999 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
15001 (defsubst org-re-property-keyword (property)
15002 "Return a regexp matching a PROPERTY line, possibly with no
15003 value for the property."
15004 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
15006 (defun org-property-action ()
15007 "Do an action on properties."
15008 (interactive)
15009 (let (c)
15010 (org-at-property-p)
15011 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15012 (setq c (read-char-exclusive))
15013 (cond
15014 ((equal c ?s)
15015 (call-interactively 'org-set-property))
15016 ((equal c ?d)
15017 (call-interactively 'org-delete-property))
15018 ((equal c ?D)
15019 (call-interactively 'org-delete-property-globally))
15020 ((equal c ?c)
15021 (call-interactively 'org-compute-property-at-point))
15022 (t (user-error "No such property action %c" c)))))
15024 (defun org-inc-effort ()
15025 "Increment the value of the effort property in the current entry."
15026 (interactive)
15027 (org-set-effort nil t))
15029 (defvar org-clock-effort) ;; Defined in org-clock.el
15030 (defvar org-clock-current-task) ;; Defined in org-clock.el
15031 (defun org-set-effort (&optional value increment)
15032 "Set the effort property of the current entry.
15033 With numerical prefix arg, use the nth allowed value, 0 stands for the
15034 10th allowed value.
15036 When INCREMENT is non-nil, set the property to the next allowed value."
15037 (interactive "P")
15038 (if (equal value 0) (setq value 10))
15039 (let* ((completion-ignore-case t)
15040 (prop org-effort-property)
15041 (cur (org-entry-get nil prop))
15042 (allowed (org-property-get-allowed-values nil prop 'table))
15043 (existing (mapcar 'list (org-property-values prop)))
15044 (heading (nth 4 (org-heading-components)))
15046 (val (cond
15047 ((stringp value) value)
15048 ((and allowed (integerp value))
15049 (or (car (nth (1- value) allowed))
15050 (car (org-last allowed))))
15051 ((and allowed increment)
15052 (or (caadr (member (list cur) allowed))
15053 (user-error "Allowed effort values are not set")))
15054 (allowed
15055 (message "Select 1-9,0, [RET%s]: %s"
15056 (if cur (concat "=" cur) "")
15057 (mapconcat 'car allowed " "))
15058 (setq rpl (read-char-exclusive))
15059 (if (equal rpl ?\r)
15061 (setq rpl (- rpl ?0))
15062 (if (equal rpl 0) (setq rpl 10))
15063 (if (and (> rpl 0) (<= rpl (length allowed)))
15064 (car (nth (1- rpl) allowed))
15065 (org-completing-read "Effort: " allowed nil))))
15067 (let (org-completion-use-ido org-completion-use-iswitchb)
15068 (org-completing-read
15069 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15070 (concat "[" cur "]") "")
15071 ": ")
15072 existing nil nil "" nil cur))))))
15073 (unless (equal (org-entry-get nil prop) val)
15074 (org-entry-put nil prop val))
15075 (save-excursion
15076 (org-back-to-heading t)
15077 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15078 (when (string= heading org-clock-current-task)
15079 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15080 (org-clock-update-mode-line))
15081 (message "%s is now %s" prop val)))
15083 (defun org-at-property-p ()
15084 "Is cursor inside a property drawer?"
15085 (save-excursion
15086 (beginning-of-line 1)
15087 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
15088 (save-match-data ;; Used by calling procedures
15089 (let ((p (point))
15090 (range (unless (org-before-first-heading-p)
15091 (org-get-property-block))))
15092 (and range (<= (car range) p) (< p (cdr range))))))))
15094 (defun org-get-property-block (&optional beg end force)
15095 "Return the (beg . end) range of the body of the property drawer.
15096 BEG and END are the beginning and end of the current subtree, or of
15097 the part before the first headline. If they are not given, they will
15098 be found. If the drawer does not exist and FORCE is non-nil, create
15099 the drawer."
15100 (catch 'exit
15101 (save-excursion
15102 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15103 (progn (org-back-to-heading t) (point))))
15104 (end (or end (and (not (outline-next-heading)) (point-max))
15105 (point))))
15106 (goto-char beg)
15107 (if (re-search-forward org-property-start-re end t)
15108 (setq beg (1+ (match-end 0)))
15109 (if force
15110 (save-excursion
15111 (org-insert-property-drawer)
15112 (setq end (progn (outline-next-heading) (point))))
15113 (throw 'exit nil))
15114 (goto-char beg)
15115 (if (re-search-forward org-property-start-re end t)
15116 (setq beg (1+ (match-end 0)))))
15117 (if (re-search-forward org-property-end-re end t)
15118 (setq end (match-beginning 0))
15119 (or force (throw 'exit nil))
15120 (goto-char beg)
15121 (setq end beg)
15122 (org-indent-line)
15123 (insert ":END:\n"))
15124 (cons beg end)))))
15126 (defun org-entry-properties (&optional pom which specific)
15127 "Get all properties of the entry at point-or-marker POM.
15128 This includes the TODO keyword, the tags, time strings for deadline,
15129 scheduled, and clocking, and any additional properties defined in the
15130 entry. The return value is an alist, keys may occur multiple times
15131 if the property key was used several times.
15132 POM may also be nil, in which case the current entry is used.
15133 If WHICH is nil or `all', get all properties. If WHICH is
15134 `special' or `standard', only get that subclass. If WHICH
15135 is a string only get exactly this property. SPECIFIC can be a string, the
15136 specific property we are interested in. Specifying it can speed
15137 things up because then unnecessary parsing is avoided."
15138 (setq which (or which 'all))
15139 (org-with-point-at pom
15140 (let ((clockstr (substring org-clock-string 0 -1))
15141 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15142 (case-fold-search nil)
15143 beg end range props sum-props key key1 value string clocksum clocksumt)
15144 (save-excursion
15145 (when (condition-case nil
15146 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
15147 (error nil))
15148 (setq beg (point))
15149 (setq sum-props (get-text-property (point) 'org-summaries))
15150 (setq clocksum (get-text-property (point) :org-clock-minutes)
15151 clocksumt (get-text-property (point) :org-clock-minutes-today))
15152 (outline-next-heading)
15153 (setq end (point))
15154 (when (memq which '(all special))
15155 ;; Get the special properties, like TODO and tags
15156 (goto-char beg)
15157 (when (and (or (not specific) (string= specific "TODO"))
15158 (looking-at org-todo-line-regexp) (match-end 2))
15159 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15160 (when (and (or (not specific) (string= specific "PRIORITY"))
15161 (looking-at org-priority-regexp))
15162 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15163 (when (or (not specific) (string= specific "FILE"))
15164 (push (cons "FILE" buffer-file-name) props))
15165 (when (and (or (not specific) (string= specific "TAGS"))
15166 (setq value (org-get-tags-string))
15167 (string-match "\\S-" value))
15168 (push (cons "TAGS" value) props))
15169 (when (and (or (not specific) (string= specific "ALLTAGS"))
15170 (setq value (org-get-tags-at)))
15171 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15172 ":"))
15173 props))
15174 (when (or (not specific) (string= specific "BLOCKED"))
15175 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15176 (when (or (not specific)
15177 (member specific
15178 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15179 "TIMESTAMP" "TIMESTAMP_IA")))
15180 (catch 'match
15181 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15182 (setq key (if (match-end 1)
15183 (substring (org-match-string-no-properties 1)
15184 0 -1))
15185 string (if (equal key clockstr)
15186 (org-trim
15187 (buffer-substring-no-properties
15188 (match-beginning 3) (goto-char
15189 (point-at-eol))))
15190 (substring (org-match-string-no-properties 3)
15191 1 -1)))
15192 ;; Get the correct property name from the key. This is
15193 ;; necessary if the user has configured time keywords.
15194 (setq key1 (concat key ":"))
15195 (cond
15196 ((not key)
15197 (setq key
15198 (if (= (char-after (match-beginning 3)) ?\[)
15199 "TIMESTAMP_IA" "TIMESTAMP")))
15200 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15201 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15202 ((equal key1 org-closed-string) (setq key "CLOSED"))
15203 ((equal key1 org-clock-string) (setq key "CLOCK")))
15204 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15205 (progn
15206 (push (cons key string) props)
15207 ;; no need to search further if match is found
15208 (throw 'match t))
15209 (when (or (equal key "CLOCK") (not (assoc key props)))
15210 (push (cons key string) props)))))))
15212 (when (memq which '(all standard))
15213 ;; Get the standard properties, like :PROP: ...
15214 (setq range (org-get-property-block beg end))
15215 (when range
15216 (goto-char (car range))
15217 (while (re-search-forward
15218 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15219 (cdr range) t)
15220 (setq key (org-match-string-no-properties 1)
15221 value (org-trim (or (org-match-string-no-properties 2) "")))
15222 (unless (member key excluded)
15223 (push (cons key (or value "")) props)))))
15224 (if clocksum
15225 (push (cons "CLOCKSUM"
15226 (org-columns-number-to-string (/ (float clocksum) 60.)
15227 'add_times))
15228 props))
15229 (if clocksumt
15230 (push (cons "CLOCKSUM_T"
15231 (org-columns-number-to-string (/ (float clocksumt) 60.)
15232 'add_times))
15233 props))
15234 (unless (assoc "CATEGORY" props)
15235 (push (cons "CATEGORY" (org-get-category)) props))
15236 (append sum-props (nreverse props)))))))
15238 (defun org-entry-get (pom property &optional inherit literal-nil)
15239 "Get value of PROPERTY for entry or content at point-or-marker POM.
15240 If INHERIT is non-nil and the entry does not have the property,
15241 then also check higher levels of the hierarchy.
15242 If INHERIT is the symbol `selective', use inheritance only if the setting
15243 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15244 If the property is present but empty, the return value is the empty string.
15245 If the property is not present at all, nil is returned.
15247 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15248 do not interpret it as the list atom nil. This is used for inheritance
15249 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15250 (org-with-point-at pom
15251 (if (and inherit (if (eq inherit 'selective)
15252 (org-property-inherit-p property)
15254 (org-entry-get-with-inheritance property literal-nil)
15255 (if (member property org-special-properties)
15256 ;; We need a special property. Use `org-entry-properties' to
15257 ;; retrieve it, but specify the wanted property
15258 (cdr (assoc property (org-entry-properties nil 'special property)))
15259 (let ((range (org-get-property-block)))
15260 (when (and range (not (eq (car range) (cdr range))))
15261 (let* ((props (list (or (assoc property org-file-properties)
15262 (assoc property org-global-properties)
15263 (assoc property org-global-properties-fixed))))
15264 (ap (lambda (key)
15265 (when (re-search-forward
15266 (org-re-property key) (cdr range) t)
15267 (setq props
15268 (org-update-property-plist
15270 (if (match-end 1)
15271 (org-match-string-no-properties 1) "")
15272 props)))))
15273 val)
15274 (goto-char (car range))
15275 (funcall ap property)
15276 (goto-char (car range))
15277 (while (funcall ap (concat property "+")))
15278 (setq val (cdr (assoc property props)))
15279 (when val (if literal-nil val (org-not-nil val))))))))))
15281 (defun org-property-or-variable-value (var &optional inherit)
15282 "Check if there is a property fixing the value of VAR.
15283 If yes, return this value. If not, return the current value of the variable."
15284 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15285 (if (and prop (stringp prop) (string-match "\\S-" prop))
15286 (read prop)
15287 (symbol-value var))))
15289 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15290 "Delete the property PROPERTY from entry at point-or-marker POM.
15291 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15292 an empty drawer to delete."
15293 (org-with-point-at pom
15294 (if (member property org-special-properties)
15295 nil ; cannot delete these properties.
15296 (let ((range (org-get-property-block)))
15297 (if (and range
15298 (goto-char (car range))
15299 (re-search-forward
15300 (org-re-property property)
15301 (cdr range) t))
15302 (progn
15303 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15304 (and delete-empty-drawer
15305 (org-remove-empty-drawer-at
15306 delete-empty-drawer (car range)))
15308 nil)))))
15310 ;; Multi-values properties are properties that contain multiple values
15311 ;; These values are assumed to be single words, separated by whitespace.
15312 (defun org-entry-add-to-multivalued-property (pom property value)
15313 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15314 (let* ((old (org-entry-get pom property))
15315 (values (and old (org-split-string old "[ \t]"))))
15316 (setq value (org-entry-protect-space value))
15317 (unless (member value values)
15318 (setq values (append values (list value)))
15319 (org-entry-put pom property
15320 (mapconcat 'identity values " ")))))
15322 (defun org-entry-remove-from-multivalued-property (pom property value)
15323 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15324 (let* ((old (org-entry-get pom property))
15325 (values (and old (org-split-string old "[ \t]"))))
15326 (setq value (org-entry-protect-space value))
15327 (when (member value values)
15328 (setq values (delete value values))
15329 (org-entry-put pom property
15330 (mapconcat 'identity values " ")))))
15332 (defun org-entry-member-in-multivalued-property (pom property value)
15333 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15334 (let* ((old (org-entry-get pom property))
15335 (values (and old (org-split-string old "[ \t]"))))
15336 (setq value (org-entry-protect-space value))
15337 (member value values)))
15339 (defun org-entry-get-multivalued-property (pom property)
15340 "Return a list of values in a multivalued property."
15341 (let* ((value (org-entry-get pom property))
15342 (values (and value (org-split-string value "[ \t]"))))
15343 (mapcar 'org-entry-restore-space values)))
15345 (defun org-entry-put-multivalued-property (pom property &rest values)
15346 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15347 VALUES should be a list of strings. Spaces will be protected."
15348 (org-entry-put pom property
15349 (mapconcat 'org-entry-protect-space values " "))
15350 (let* ((value (org-entry-get pom property))
15351 (values (and value (org-split-string value "[ \t]"))))
15352 (mapcar 'org-entry-restore-space values)))
15354 (defun org-entry-protect-space (s)
15355 "Protect spaces and newline in string S."
15356 (while (string-match " " s)
15357 (setq s (replace-match "%20" t t s)))
15358 (while (string-match "\n" s)
15359 (setq s (replace-match "%0A" t t s)))
15362 (defun org-entry-restore-space (s)
15363 "Restore spaces and newline in string S."
15364 (while (string-match "%20" s)
15365 (setq s (replace-match " " t t s)))
15366 (while (string-match "%0A" s)
15367 (setq s (replace-match "\n" t t s)))
15370 (defvar org-entry-property-inherited-from (make-marker)
15371 "Marker pointing to the entry from where a property was inherited.
15372 Each call to `org-entry-get-with-inheritance' will set this marker to the
15373 location of the entry where the inheritance search matched. If there was
15374 no match, the marker will point nowhere.
15375 Note that also `org-entry-get' calls this function, if the INHERIT flag
15376 is set.")
15378 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15379 "Get PROPERTY of entry or content at point, search higher levels if needed.
15380 The search will stop at the first ancestor which has the property defined.
15381 If the value found is \"nil\", return nil to show that the property
15382 should be considered as undefined (this is the meaning of nil here).
15383 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15384 (move-marker org-entry-property-inherited-from nil)
15385 (let (tmp)
15386 (save-excursion
15387 (save-restriction
15388 (widen)
15389 (catch 'ex
15390 (while t
15391 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15392 (or (ignore-errors (org-back-to-heading t))
15393 (goto-char (point-min)))
15394 (move-marker org-entry-property-inherited-from (point))
15395 (throw 'ex tmp))
15396 (or (ignore-errors (org-up-heading-safe))
15397 (throw 'ex nil))))))
15398 (setq tmp (or tmp
15399 (cdr (assoc property org-file-properties))
15400 (cdr (assoc property org-global-properties))
15401 (cdr (assoc property org-global-properties-fixed))))
15402 (if literal-nil tmp (org-not-nil tmp))))
15404 (defvar org-property-changed-functions nil
15405 "Hook called when the value of a property has changed.
15406 Each hook function should accept two arguments, the name of the property
15407 and the new value.")
15409 (defun org-entry-put (pom property value)
15410 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15411 (org-with-point-at pom
15412 (org-back-to-heading t)
15413 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15414 range)
15415 (cond
15416 ((equal property "TODO")
15417 (when (and (stringp value) (string-match "\\S-" value)
15418 (not (member value org-todo-keywords-1)))
15419 (user-error "\"%s\" is not a valid TODO state" value))
15420 (if (or (not value)
15421 (not (string-match "\\S-" value)))
15422 (setq value 'none))
15423 (org-todo value)
15424 (org-set-tags nil 'align))
15425 ((equal property "PRIORITY")
15426 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15427 (string-to-char value) ?\ ))
15428 (org-set-tags nil 'align))
15429 ((equal property "CLOCKSUM")
15430 (if (not (re-search-forward
15431 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15432 (error "Cannot find a clock log")
15433 (goto-char (- (match-end 1) 2))
15434 (cond
15435 ((eq value 'earlier) (org-timestamp-down))
15436 ((eq value 'later) (org-timestamp-up)))
15437 (org-clock-sum-current-item)))
15438 ((equal property "SCHEDULED")
15439 (if (re-search-forward org-scheduled-time-regexp end t)
15440 (cond
15441 ((eq value 'earlier) (org-timestamp-change -1 'day))
15442 ((eq value 'later) (org-timestamp-change 1 'day))
15443 (t (call-interactively 'org-schedule)))
15444 (call-interactively 'org-schedule)))
15445 ((equal property "DEADLINE")
15446 (if (re-search-forward org-deadline-time-regexp end t)
15447 (cond
15448 ((eq value 'earlier) (org-timestamp-change -1 'day))
15449 ((eq value 'later) (org-timestamp-change 1 'day))
15450 (t (call-interactively 'org-deadline)))
15451 (call-interactively 'org-deadline)))
15452 ((member property org-special-properties)
15453 (error "The %s property can not yet be set with `org-entry-put'"
15454 property))
15455 (t ; a non-special property
15456 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15457 (setq range (org-get-property-block beg end 'force))
15458 (goto-char (car range))
15459 (if (re-search-forward
15460 (org-re-property-keyword property) (cdr range) t)
15461 (progn
15462 (delete-region (match-beginning 0) (match-end 0))
15463 (goto-char (match-beginning 0)))
15464 (goto-char (cdr range))
15465 (insert "\n")
15466 (backward-char 1)
15467 (org-indent-line))
15468 (insert ":" property ":")
15469 (and value (insert " " value))
15470 (org-indent-line)))))
15471 (run-hook-with-args 'org-property-changed-functions property value)))
15473 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15474 "Get all property keys in the current buffer.
15475 With INCLUDE-SPECIALS, also list the special properties that reflect things
15476 like tags and TODO state.
15477 With INCLUDE-DEFAULTS, also include properties that has special meaning
15478 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15479 and others.
15480 With INCLUDE-COLUMNS, also include property names given in COLUMN
15481 formats in the current buffer."
15482 (let (rtn range cfmt s p)
15483 (save-excursion
15484 (save-restriction
15485 (widen)
15486 (goto-char (point-min))
15487 (while (re-search-forward org-property-start-re nil t)
15488 (setq range (org-get-property-block))
15489 (goto-char (car range))
15490 (while (re-search-forward
15491 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15492 (cdr range) t)
15493 (add-to-list 'rtn (org-match-string-no-properties 1)))
15494 (outline-next-heading))))
15496 (when include-specials
15497 (setq rtn (append org-special-properties rtn)))
15499 (when include-defaults
15500 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15501 (add-to-list 'rtn org-effort-property))
15503 (when include-columns
15504 (save-excursion
15505 (save-restriction
15506 (widen)
15507 (goto-char (point-min))
15508 (while (re-search-forward
15509 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15510 nil t)
15511 (setq cfmt (match-string 2) s 0)
15512 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15513 cfmt s)
15514 (setq s (match-end 0)
15515 p (match-string 1 cfmt))
15516 (unless (or (equal p "ITEM")
15517 (member p org-special-properties))
15518 (add-to-list 'rtn (match-string 1 cfmt))))))))
15520 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15522 (defun org-property-values (key)
15523 "Return a list of all values of property KEY in the current buffer."
15524 (save-excursion
15525 (save-restriction
15526 (widen)
15527 (goto-char (point-min))
15528 (let ((re (org-re-property key))
15529 values)
15530 (while (re-search-forward re nil t)
15531 (add-to-list 'values (org-trim (match-string 1))))
15532 (delete "" values)))))
15534 (defun org-insert-property-drawer ()
15535 "Insert a property drawer into the current entry."
15536 (org-back-to-heading t)
15537 (looking-at org-outline-regexp)
15538 (let ((indent (if org-adapt-indentation
15539 (- (match-end 0) (match-beginning 0))
15541 (beg (point))
15542 (re (concat "^[ \t]*" org-keyword-time-regexp))
15543 end hiddenp)
15544 (outline-next-heading)
15545 (setq end (point))
15546 (goto-char beg)
15547 (while (re-search-forward re end t))
15548 (setq hiddenp (outline-invisible-p))
15549 (end-of-line 1)
15550 (and (equal (char-after) ?\n) (forward-char 1))
15551 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15552 (if (member (match-string 1) '("CLOCK:" ":END:"))
15553 ;; just skip this line
15554 (beginning-of-line 2)
15555 ;; Drawer start, find the end
15556 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15557 (beginning-of-line 1)))
15558 (org-skip-over-state-notes)
15559 (skip-chars-backward " \t\n\r")
15560 (if (eq (char-before) ?*) (forward-char 1))
15561 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15562 (beginning-of-line 0)
15563 (org-indent-to-column indent)
15564 (beginning-of-line 2)
15565 (org-indent-to-column indent)
15566 (beginning-of-line 0)
15567 (if hiddenp
15568 (save-excursion
15569 (org-back-to-heading t)
15570 (hide-entry))
15571 (org-flag-drawer t))))
15573 (defun org-insert-drawer (&optional arg drawer)
15574 "Insert a drawer at point.
15576 Optional argument DRAWER, when non-nil, is a string representing
15577 drawer's name. Otherwise, the user is prompted for a name.
15579 If a region is active, insert the drawer around that region
15580 instead.
15582 Point is left between drawer's boundaries."
15583 (interactive "P")
15584 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15585 "LOGBOOK"))
15586 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15587 ;; internally by Org. They are meant to be inserted
15588 ;; automatically.
15589 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15590 ;; Remove system drawers from list. Note: For some reason,
15591 ;; `org-completing-read' ignores the predicate while
15592 ;; `completing-read' handles it fine.
15593 (drawer (if arg "PROPERTIES"
15594 (or drawer
15595 (completing-read
15596 "Drawer: " org-drawers
15597 (lambda (d) (not (member d system-drawers))))))))
15598 (cond
15599 ;; With C-u, fall back on `org-insert-property-drawer'
15600 (arg (org-insert-property-drawer))
15601 ;; With an active region, insert a drawer at point.
15602 ((not (org-region-active-p))
15603 (progn
15604 (unless (bolp) (insert "\n"))
15605 (insert (format ":%s:\n\n:END:\n" drawer))
15606 (forward-line -2)))
15607 ;; Otherwise, insert the drawer at point
15609 (let ((rbeg (region-beginning))
15610 (rend (copy-marker (region-end))))
15611 (unwind-protect
15612 (progn
15613 (goto-char rbeg)
15614 (beginning-of-line)
15615 (when (save-excursion
15616 (re-search-forward org-outline-regexp-bol rend t))
15617 (user-error "Drawers cannot contain headlines"))
15618 ;; Position point at the beginning of the first
15619 ;; non-blank line in region. Insert drawer's opening
15620 ;; there, then indent it.
15621 (org-skip-whitespace)
15622 (beginning-of-line)
15623 (insert ":" drawer ":\n")
15624 (forward-line -1)
15625 (indent-for-tab-command)
15626 ;; Move point to the beginning of the first blank line
15627 ;; after the last non-blank line in region. Insert
15628 ;; drawer's closing, then indent it.
15629 (goto-char rend)
15630 (skip-chars-backward " \r\t\n")
15631 (insert "\n:END:")
15632 (deactivate-mark t)
15633 (indent-for-tab-command)
15634 (unless (eolp) (insert "\n")))
15635 ;; Clear marker, whatever the outcome of insertion is.
15636 (set-marker rend nil)))))))
15638 (defvar org-property-set-functions-alist nil
15639 "Property set function alist.
15640 Each entry should have the following format:
15642 (PROPERTY . READ-FUNCTION)
15644 The read function will be called with the same argument as
15645 `org-completing-read'.")
15647 (defun org-set-property-function (property)
15648 "Get the function that should be used to set PROPERTY.
15649 This is computed according to `org-property-set-functions-alist'."
15650 (or (cdr (assoc property org-property-set-functions-alist))
15651 'org-completing-read))
15653 (defun org-read-property-value (property)
15654 "Read PROPERTY value from user."
15655 (let* ((completion-ignore-case t)
15656 (allowed (org-property-get-allowed-values nil property 'table))
15657 (cur (org-entry-get nil property))
15658 (prompt (concat property " value"
15659 (if (and cur (string-match "\\S-" cur))
15660 (concat " [" cur "]") "") ": "))
15661 (set-function (org-set-property-function property))
15662 (val (if allowed
15663 (funcall set-function prompt allowed nil
15664 (not (get-text-property 0 'org-unrestricted
15665 (caar allowed))))
15666 (let (org-completion-use-ido org-completion-use-iswitchb)
15667 (funcall set-function prompt
15668 (mapcar 'list (org-property-values property))
15669 nil nil "" nil cur)))))
15670 (if (equal val "")
15672 val)))
15674 (defvar org-last-set-property nil)
15675 (defvar org-last-set-property-value nil)
15676 (defun org-read-property-name ()
15677 "Read a property name."
15678 (let* ((completion-ignore-case t)
15679 (keys (org-buffer-property-keys nil t t))
15680 (default-prop (or (save-excursion
15681 (save-match-data
15682 (beginning-of-line)
15683 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15684 (null (string= (match-string 1) "END"))
15685 (match-string 1))))
15686 org-last-set-property))
15687 (property (org-icompleting-read
15688 (concat "Property"
15689 (if default-prop (concat " [" default-prop "]") "")
15690 ": ")
15691 (mapcar 'list keys)
15692 nil nil nil nil
15693 default-prop)))
15694 (if (member property keys)
15695 property
15696 (or (cdr (assoc (downcase property)
15697 (mapcar (lambda (x) (cons (downcase x) x))
15698 keys)))
15699 property))))
15701 (defun org-set-property-and-value (use-last)
15702 "Allow to set [PROPERTY]: [value] direction from prompt.
15703 When use-default, don't even ask, just use the last
15704 \"[PROPERTY]: [value]\" string from the history."
15705 (interactive "P")
15706 (let* ((completion-ignore-case t)
15707 (pv (or (and use-last org-last-set-property-value)
15708 (org-completing-read
15709 "Enter a \"[Property]: [value]\" pair: "
15710 nil nil nil nil nil
15711 org-last-set-property-value)))
15712 prop val)
15713 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15714 (setq prop (match-string 1 pv)
15715 val (match-string 2 pv))
15716 (org-set-property prop val))))
15718 (defun org-set-property (property value)
15719 "In the current entry, set PROPERTY to VALUE.
15720 When called interactively, this will prompt for a property name, offering
15721 completion on existing and default properties. And then it will prompt
15722 for a value, offering completion either on allowed values (via an inherited
15723 xxx_ALL property) or on existing values in other instances of this property
15724 in the current file."
15725 (interactive (list nil nil))
15726 (let* ((property (or property (org-read-property-name)))
15727 (value (or value (org-read-property-value property)))
15728 (fn (cdr (assoc property org-properties-postprocess-alist))))
15729 (setq org-last-set-property property)
15730 (setq org-last-set-property-value (concat property ": " value))
15731 ;; Possibly postprocess the inserted value:
15732 (when fn (setq value (funcall fn value)))
15733 (unless (equal (org-entry-get nil property) value)
15734 (org-entry-put nil property value))))
15736 (defun org-delete-property (property &optional delete-empty-drawer)
15737 "In the current entry, delete PROPERTY.
15738 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15739 an empty drawer to delete."
15740 (interactive
15741 (let* ((completion-ignore-case t)
15742 (prop (org-icompleting-read "Property: "
15743 (org-entry-properties nil 'standard))))
15744 (list prop)))
15745 (message "Property %s %s" property
15746 (if (org-entry-delete nil property delete-empty-drawer)
15747 "deleted"
15748 "was not present in the entry")))
15750 (defun org-delete-property-globally (property)
15751 "Remove PROPERTY globally, from all entries."
15752 (interactive
15753 (let* ((completion-ignore-case t)
15754 (prop (org-icompleting-read
15755 "Globally remove property: "
15756 (mapcar 'list (org-buffer-property-keys)))))
15757 (list prop)))
15758 (save-excursion
15759 (save-restriction
15760 (widen)
15761 (goto-char (point-min))
15762 (let ((cnt 0))
15763 (while (re-search-forward
15764 (org-re-property property)
15765 nil t)
15766 (setq cnt (1+ cnt))
15767 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15768 (message "Property \"%s\" removed from %d entries" property cnt)))))
15770 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15772 (defun org-compute-property-at-point ()
15773 "Compute the property at point.
15774 This looks for an enclosing column format, extracts the operator and
15775 then applies it to the property in the column format's scope."
15776 (interactive)
15777 (unless (org-at-property-p)
15778 (user-error "Not at a property"))
15779 (let ((prop (org-match-string-no-properties 2)))
15780 (org-columns-get-format-and-top-level)
15781 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15782 (user-error "No operator defined for property %s" prop))
15783 (org-columns-compute prop)))
15785 (defvar org-property-allowed-value-functions nil
15786 "Hook for functions supplying allowed values for a specific property.
15787 The functions must take a single argument, the name of the property, and
15788 return a flat list of allowed values. If \":ETC\" is one of
15789 the values, this means that these values are intended as defaults for
15790 completion, but that other values should be allowed too.
15791 The functions must return nil if they are not responsible for this
15792 property.")
15794 (defun org-property-get-allowed-values (pom property &optional table)
15795 "Get allowed values for the property PROPERTY.
15796 When TABLE is non-nil, return an alist that can directly be used for
15797 completion."
15798 (let (vals)
15799 (cond
15800 ((equal property "TODO")
15801 (setq vals (org-with-point-at pom
15802 (append org-todo-keywords-1 '("")))))
15803 ((equal property "PRIORITY")
15804 (let ((n org-lowest-priority))
15805 (while (>= n org-highest-priority)
15806 (push (char-to-string n) vals)
15807 (setq n (1- n)))))
15808 ((member property org-special-properties))
15809 ((setq vals (run-hook-with-args-until-success
15810 'org-property-allowed-value-functions property)))
15812 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15813 (when (and vals (string-match "\\S-" vals))
15814 (setq vals (car (read-from-string (concat "(" vals ")"))))
15815 (setq vals (mapcar (lambda (x)
15816 (cond ((stringp x) x)
15817 ((numberp x) (number-to-string x))
15818 ((symbolp x) (symbol-name x))
15819 (t "???")))
15820 vals)))))
15821 (when (member ":ETC" vals)
15822 (setq vals (remove ":ETC" vals))
15823 (org-add-props (car vals) '(org-unrestricted t)))
15824 (if table (mapcar 'list vals) vals)))
15826 (defun org-property-previous-allowed-value (&optional previous)
15827 "Switch to the next allowed value for this property."
15828 (interactive)
15829 (org-property-next-allowed-value t))
15831 (defun org-property-next-allowed-value (&optional previous)
15832 "Switch to the next allowed value for this property."
15833 (interactive)
15834 (unless (org-at-property-p)
15835 (user-error "Not at a property"))
15836 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15837 (key (match-string 2))
15838 (value (match-string 3))
15839 (allowed (or (org-property-get-allowed-values (point) key)
15840 (and (member value '("[ ]" "[-]" "[X]"))
15841 '("[ ]" "[X]"))))
15842 (heading (save-match-data (nth 4 (org-heading-components))))
15843 nval)
15844 (unless allowed
15845 (user-error "Allowed values for this property have not been defined"))
15846 (if previous (setq allowed (reverse allowed)))
15847 (if (member value allowed)
15848 (setq nval (car (cdr (member value allowed)))))
15849 (setq nval (or nval (car allowed)))
15850 (if (equal nval value)
15851 (user-error "Only one allowed value for this property"))
15852 (org-at-property-p)
15853 (replace-match (concat " :" key ": " nval) t t)
15854 (org-indent-line)
15855 (beginning-of-line 1)
15856 (skip-chars-forward " \t")
15857 (when (equal prop org-effort-property)
15858 (save-excursion
15859 (org-back-to-heading t)
15860 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15861 (when (string= org-clock-current-task heading)
15862 (setq org-clock-effort nval)
15863 (org-clock-update-mode-line)))
15864 (run-hook-with-args 'org-property-changed-functions key nval)))
15866 (defun org-find-olp (path &optional this-buffer)
15867 "Return a marker pointing to the entry at outline path OLP.
15868 If anything goes wrong, throw an error.
15869 You can wrap this call to catch the error like this:
15871 (condition-case msg
15872 (org-mobile-locate-entry (match-string 4))
15873 (error (nth 1 msg)))
15875 The return value will then be either a string with the error message,
15876 or a marker if everything is OK.
15878 If THIS-BUFFER is set, the outline path does not contain a file,
15879 only headings."
15880 (let* ((file (if this-buffer buffer-file-name (pop path)))
15881 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15882 (level 1)
15883 (lmin 1)
15884 (lmax 1)
15885 limit re end found pos heading cnt flevel)
15886 (unless buffer (error "File not found :%s" file))
15887 (with-current-buffer buffer
15888 (save-excursion
15889 (save-restriction
15890 (widen)
15891 (setq limit (point-max))
15892 (goto-char (point-min))
15893 (while (setq heading (pop path))
15894 (setq re (format org-complex-heading-regexp-format
15895 (regexp-quote heading)))
15896 (setq cnt 0 pos (point))
15897 (while (re-search-forward re end t)
15898 (setq level (- (match-end 1) (match-beginning 1)))
15899 (if (and (>= level lmin) (<= level lmax))
15900 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15901 (when (= cnt 0) (error "Heading not found on level %d: %s"
15902 lmax heading))
15903 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15904 lmax heading))
15905 (goto-char found)
15906 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15907 (setq end (save-excursion (org-end-of-subtree t t))))
15908 (when (org-at-heading-p)
15909 (point-marker)))))))
15911 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15912 "Find node HEADING in BUFFER.
15913 Return a marker to the heading if it was found, or nil if not.
15914 If POS-ONLY is set, return just the position instead of a marker.
15916 The heading text must match exact, but it may have a TODO keyword,
15917 a priority cookie and tags in the standard locations."
15918 (with-current-buffer (or buffer (current-buffer))
15919 (save-excursion
15920 (save-restriction
15921 (widen)
15922 (goto-char (point-min))
15923 (let (case-fold-search)
15924 (if (re-search-forward
15925 (format org-complex-heading-regexp-format
15926 (regexp-quote heading)) nil t)
15927 (if pos-only
15928 (match-beginning 0)
15929 (move-marker (make-marker) (match-beginning 0)))))))))
15931 (defun org-find-exact-heading-in-directory (heading &optional dir)
15932 "Find Org node headline HEADING in all .org files in directory DIR.
15933 When the target headline is found, return a marker to this location."
15934 (let ((files (directory-files (or dir default-directory)
15935 nil "\\`[^.#].*\\.org\\'"))
15936 file visiting m buffer)
15937 (catch 'found
15938 (while (setq file (pop files))
15939 (message "trying %s" file)
15940 (setq visiting (org-find-base-buffer-visiting file))
15941 (setq buffer (or visiting (find-file-noselect file)))
15942 (setq m (org-find-exact-headline-in-buffer
15943 heading buffer))
15944 (when (and (not m) (not visiting)) (kill-buffer buffer))
15945 (and m (throw 'found m))))))
15947 (defun org-find-entry-with-id (ident)
15948 "Locate the entry that contains the ID property with exact value IDENT.
15949 IDENT can be a string, a symbol or a number, this function will search for
15950 the string representation of it.
15951 Return the position where this entry starts, or nil if there is no such entry."
15952 (interactive "sID: ")
15953 (let ((id (cond
15954 ((stringp ident) ident)
15955 ((symbol-name ident) (symbol-name ident))
15956 ((numberp ident) (number-to-string ident))
15957 (t (error "IDENT %s must be a string, symbol or number" ident))))
15958 (case-fold-search nil))
15959 (save-excursion
15960 (save-restriction
15961 (widen)
15962 (goto-char (point-min))
15963 (when (re-search-forward
15964 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15965 nil t)
15966 (org-back-to-heading t)
15967 (point))))))
15969 ;;;; Timestamps
15971 (defvar org-last-changed-timestamp nil)
15972 (defvar org-last-inserted-timestamp nil
15973 "The last time stamp inserted with `org-insert-time-stamp'.")
15974 (defvar org-time-was-given) ; dynamically scoped parameter
15975 (defvar org-end-time-was-given) ; dynamically scoped parameter
15976 (defvar org-ts-what) ; dynamically scoped parameter
15978 (defun org-time-stamp (arg &optional inactive)
15979 "Prompt for a date/time and insert a time stamp.
15980 If the user specifies a time like HH:MM or if this command is
15981 called with at least one prefix argument, the time stamp contains
15982 the date and the time. Otherwise, only the date is be included.
15984 All parts of a date not specified by the user is filled in from
15985 the current date/time. So if you just press return without
15986 typing anything, the time stamp will represent the current
15987 date/time.
15989 If there is already a timestamp at the cursor, it will be
15990 modified.
15992 With two universal prefix arguments, insert an active timestamp
15993 with the current time without prompting the user."
15994 (interactive "P")
15995 (let* ((ts nil)
15996 (default-time
15997 ;; Default time is either today, or, when entering a range,
15998 ;; the range start.
15999 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16000 (save-excursion
16001 (re-search-backward
16002 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16003 (- (point) 20) t)))
16004 (apply 'encode-time (org-parse-time-string (match-string 1)))
16005 (current-time)))
16006 (default-input (and ts (org-get-compact-tod ts)))
16007 (repeater (save-excursion
16008 (save-match-data
16009 (beginning-of-line)
16010 (when (re-search-forward
16011 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16012 (save-excursion (progn (end-of-line) (point))) t)
16013 (match-string 0)))))
16014 org-time-was-given org-end-time-was-given time)
16015 (cond
16016 ((and (org-at-timestamp-p t)
16017 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16018 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16019 (insert "--")
16020 (setq time (let ((this-command this-command))
16021 (org-read-date arg 'totime nil nil
16022 default-time default-input inactive)))
16023 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16024 ((org-at-timestamp-p t)
16025 (setq time (let ((this-command this-command))
16026 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16027 (when (org-at-timestamp-p t) ; just to get the match data
16028 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16029 (replace-match "")
16030 (setq org-last-changed-timestamp
16031 (org-insert-time-stamp
16032 time (or org-time-was-given arg)
16033 inactive nil nil (list org-end-time-was-given)))
16034 (when repeater (goto-char (1- (point))) (insert " " repeater)
16035 (setq org-last-changed-timestamp
16036 (concat (substring org-last-inserted-timestamp 0 -1)
16037 " " repeater ">"))))
16038 (message "Timestamp updated"))
16039 ((equal arg '(16))
16040 (org-insert-time-stamp (current-time) t))
16042 (setq time (let ((this-command this-command))
16043 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16044 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16045 nil nil (list org-end-time-was-given))))))
16047 ;; FIXME: can we use this for something else, like computing time differences?
16048 (defun org-get-compact-tod (s)
16049 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16050 (let* ((t1 (match-string 1 s))
16051 (h1 (string-to-number (match-string 2 s)))
16052 (m1 (string-to-number (match-string 3 s)))
16053 (t2 (and (match-end 4) (match-string 5 s)))
16054 (h2 (and t2 (string-to-number (match-string 6 s))))
16055 (m2 (and t2 (string-to-number (match-string 7 s))))
16056 dh dm)
16057 (if (not t2)
16059 (setq dh (- h2 h1) dm (- m2 m1))
16060 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16061 (concat t1 "+" (number-to-string dh)
16062 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
16064 (defun org-time-stamp-inactive (&optional arg)
16065 "Insert an inactive time stamp.
16066 An inactive time stamp is enclosed in square brackets instead of angle
16067 brackets. It is inactive in the sense that it does not trigger agenda entries,
16068 does not link to the calendar and cannot be changed with the S-cursor keys.
16069 So these are more for recording a certain time/date."
16070 (interactive "P")
16071 (org-time-stamp arg 'inactive))
16073 (defvar org-date-ovl (make-overlay 1 1))
16074 (overlay-put org-date-ovl 'face 'org-date-selected)
16075 (org-detach-overlay org-date-ovl)
16077 (defvar org-ans1) ; dynamically scoped parameter
16078 (defvar org-ans2) ; dynamically scoped parameter
16080 (defvar org-plain-time-of-day-regexp) ; defined below
16082 (defvar org-overriding-default-time nil) ; dynamically scoped
16083 (defvar org-read-date-overlay nil)
16084 (defvar org-dcst nil) ; dynamically scoped
16085 (defvar org-read-date-history nil)
16086 (defvar org-read-date-final-answer nil)
16087 (defvar org-read-date-analyze-futurep nil)
16088 (defvar org-read-date-analyze-forced-year nil)
16089 (defvar org-read-date-inactive)
16091 (defvar org-read-date-minibuffer-local-map
16092 (let ((map (make-sparse-keymap)))
16093 (set-keymap-parent map minibuffer-local-map)
16094 (org-defkey map (kbd ".")
16095 (lambda () (interactive)
16096 ;; Are we at the beginning of the prompt?
16097 (if (looking-back "^[^:]+: ")
16098 (org-eval-in-calendar '(calendar-goto-today))
16099 (insert "."))))
16100 (org-defkey map (kbd "C-.")
16101 (lambda () (interactive)
16102 (org-eval-in-calendar '(calendar-goto-today))))
16103 (org-defkey map [(meta shift left)]
16104 (lambda () (interactive)
16105 (org-eval-in-calendar '(calendar-backward-month 1))))
16106 (org-defkey map [(meta shift right)]
16107 (lambda () (interactive)
16108 (org-eval-in-calendar '(calendar-forward-month 1))))
16109 (org-defkey map [(meta shift up)]
16110 (lambda () (interactive)
16111 (org-eval-in-calendar '(calendar-backward-year 1))))
16112 (org-defkey map [(meta shift down)]
16113 (lambda () (interactive)
16114 (org-eval-in-calendar '(calendar-forward-year 1))))
16115 (org-defkey map [?\e (shift left)]
16116 (lambda () (interactive)
16117 (org-eval-in-calendar '(calendar-backward-month 1))))
16118 (org-defkey map [?\e (shift right)]
16119 (lambda () (interactive)
16120 (org-eval-in-calendar '(calendar-forward-month 1))))
16121 (org-defkey map [?\e (shift up)]
16122 (lambda () (interactive)
16123 (org-eval-in-calendar '(calendar-backward-year 1))))
16124 (org-defkey map [?\e (shift down)]
16125 (lambda () (interactive)
16126 (org-eval-in-calendar '(calendar-forward-year 1))))
16127 (org-defkey map [(shift up)]
16128 (lambda () (interactive)
16129 (org-eval-in-calendar '(calendar-backward-week 1))))
16130 (org-defkey map [(shift down)]
16131 (lambda () (interactive)
16132 (org-eval-in-calendar '(calendar-forward-week 1))))
16133 (org-defkey map [(shift left)]
16134 (lambda () (interactive)
16135 (org-eval-in-calendar '(calendar-backward-day 1))))
16136 (org-defkey map [(shift right)]
16137 (lambda () (interactive)
16138 (org-eval-in-calendar '(calendar-forward-day 1))))
16139 (org-defkey map "!"
16140 (lambda () (interactive)
16141 (org-eval-in-calendar '(diary-view-entries))
16142 (message "")))
16143 (org-defkey map ">"
16144 (lambda () (interactive)
16145 (org-eval-in-calendar '(scroll-calendar-left 1))))
16146 (org-defkey map "<"
16147 (lambda () (interactive)
16148 (org-eval-in-calendar '(scroll-calendar-right 1))))
16149 (org-defkey map "\C-v"
16150 (lambda () (interactive)
16151 (org-eval-in-calendar
16152 '(calendar-scroll-left-three-months 1))))
16153 (org-defkey map "\M-v"
16154 (lambda () (interactive)
16155 (org-eval-in-calendar
16156 '(calendar-scroll-right-three-months 1))))
16157 map)
16158 "Keymap for minibuffer commands when using `org-read-date'.")
16160 (defun org-read-date (&optional org-with-time to-time from-string prompt
16161 default-time default-input inactive)
16162 "Read a date, possibly a time, and make things smooth for the user.
16163 The prompt will suggest to enter an ISO date, but you can also enter anything
16164 which will at least partially be understood by `parse-time-string'.
16165 Unrecognized parts of the date will default to the current day, month, year,
16166 hour and minute. If this command is called to replace a timestamp at point,
16167 or to enter the second timestamp of a range, the default time is taken
16168 from the existing stamp. Furthermore, the command prefers the future,
16169 so if you are giving a date where the year is not given, and the day-month
16170 combination is already past in the current year, it will assume you
16171 mean next year. For details, see the manual. A few examples:
16173 3-2-5 --> 2003-02-05
16174 feb 15 --> currentyear-02-15
16175 2/15 --> currentyear-02-15
16176 sep 12 9 --> 2009-09-12
16177 12:45 --> today 12:45
16178 22 sept 0:34 --> currentyear-09-22 0:34
16179 12 --> currentyear-currentmonth-12
16180 Fri --> nearest Friday after today
16181 -Tue --> last Tuesday
16182 etc.
16184 Furthermore you can specify a relative date by giving, as the *first* thing
16185 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16186 change in days weeks, months, years.
16187 With a single plus or minus, the date is relative to today. With a double
16188 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16189 +4d --> four days from today
16190 +4 --> same as above
16191 +2w --> two weeks from today
16192 ++5 --> five days from default date
16194 The function understands only English month and weekday abbreviations.
16196 While prompting, a calendar is popped up - you can also select the
16197 date with the mouse (button 1). The calendar shows a period of three
16198 months. To scroll it to other months, use the keys `>' and `<'.
16199 If you don't like the calendar, turn it off with
16200 \(setq org-read-date-popup-calendar nil)
16202 With optional argument TO-TIME, the date will immediately be converted
16203 to an internal time.
16204 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16205 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16206 still enter a time, and this function will inform the calling routine
16207 about this change. The calling routine may then choose to change the
16208 format used to insert the time stamp into the buffer to include the time.
16209 With optional argument FROM-STRING, read from this string instead from
16210 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16211 the time/date that is used for everything that is not specified by the
16212 user."
16213 (require 'parse-time)
16214 (let* ((org-time-stamp-rounding-minutes
16215 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16216 (org-dcst org-display-custom-times)
16217 (ct (org-current-time))
16218 (org-def (or org-overriding-default-time default-time ct))
16219 (org-defdecode (decode-time org-def))
16220 (dummy (progn
16221 (when (< (nth 2 org-defdecode) org-extend-today-until)
16222 (setcar (nthcdr 2 org-defdecode) -1)
16223 (setcar (nthcdr 1 org-defdecode) 59)
16224 (setq org-def (apply 'encode-time org-defdecode)
16225 org-defdecode (decode-time org-def)))))
16226 (mouse-autoselect-window nil) ; Don't let the mouse jump
16227 (calendar-frame-setup nil)
16228 (calendar-setup nil)
16229 (calendar-move-hook nil)
16230 (calendar-view-diary-initially-flag nil)
16231 (calendar-view-holidays-initially-flag nil)
16232 (timestr (format-time-string
16233 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16234 (prompt (concat (if prompt (concat prompt " ") "")
16235 (format "Date+time [%s]: " timestr)))
16236 ans (org-ans0 "") org-ans1 org-ans2 final)
16238 (cond
16239 (from-string (setq ans from-string))
16240 (org-read-date-popup-calendar
16241 (save-excursion
16242 (save-window-excursion
16243 (calendar)
16244 (org-eval-in-calendar '(setq cursor-type nil) t)
16245 (unwind-protect
16246 (progn
16247 (calendar-forward-day (- (time-to-days org-def)
16248 (calendar-absolute-from-gregorian
16249 (calendar-current-date))))
16250 (org-eval-in-calendar nil t)
16251 (let* ((old-map (current-local-map))
16252 (map (copy-keymap calendar-mode-map))
16253 (minibuffer-local-map
16254 (copy-keymap org-read-date-minibuffer-local-map)))
16255 (org-defkey map (kbd "RET") 'org-calendar-select)
16256 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16257 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16258 (unwind-protect
16259 (progn
16260 (use-local-map map)
16261 (setq org-read-date-inactive inactive)
16262 (add-hook 'post-command-hook 'org-read-date-display)
16263 (setq org-ans0 (read-string prompt default-input
16264 'org-read-date-history nil))
16265 ;; org-ans0: from prompt
16266 ;; org-ans1: from mouse click
16267 ;; org-ans2: from calendar motion
16268 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16269 (remove-hook 'post-command-hook 'org-read-date-display)
16270 (use-local-map old-map)
16271 (when org-read-date-overlay
16272 (delete-overlay org-read-date-overlay)
16273 (setq org-read-date-overlay nil)))))
16274 (bury-buffer "*Calendar*")))))
16276 (t ; Naked prompt only
16277 (unwind-protect
16278 (setq ans (read-string prompt default-input
16279 'org-read-date-history timestr))
16280 (when org-read-date-overlay
16281 (delete-overlay org-read-date-overlay)
16282 (setq org-read-date-overlay nil)))))
16284 (setq final (org-read-date-analyze ans org-def org-defdecode))
16286 (when org-read-date-analyze-forced-year
16287 (message "Year was forced into %s"
16288 (if org-read-date-force-compatible-dates
16289 "compatible range (1970-2037)"
16290 "range representable on this machine"))
16291 (ding))
16293 ;; One round trip to get rid of 34th of August and stuff like that....
16294 (setq final (decode-time (apply 'encode-time final)))
16296 (setq org-read-date-final-answer ans)
16298 (if to-time
16299 (apply 'encode-time final)
16300 (if (and (boundp 'org-time-was-given) org-time-was-given)
16301 (format "%04d-%02d-%02d %02d:%02d"
16302 (nth 5 final) (nth 4 final) (nth 3 final)
16303 (nth 2 final) (nth 1 final))
16304 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16306 (defvar org-def)
16307 (defvar org-defdecode)
16308 (defvar org-with-time)
16309 (defun org-read-date-display ()
16310 "Display the current date prompt interpretation in the minibuffer."
16311 (when org-read-date-display-live
16312 (when org-read-date-overlay
16313 (delete-overlay org-read-date-overlay))
16314 (when (minibufferp (current-buffer))
16315 (save-excursion
16316 (end-of-line 1)
16317 (while (not (equal (buffer-substring
16318 (max (point-min) (- (point) 4)) (point))
16319 " "))
16320 (insert " ")))
16321 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16322 " " (or org-ans1 org-ans2)))
16323 (org-end-time-was-given nil)
16324 (f (org-read-date-analyze ans org-def org-defdecode))
16325 (fmts (if org-dcst
16326 org-time-stamp-custom-formats
16327 org-time-stamp-formats))
16328 (fmt (if (or org-with-time
16329 (and (boundp 'org-time-was-given) org-time-was-given))
16330 (cdr fmts)
16331 (car fmts)))
16332 (txt (format-time-string fmt (apply 'encode-time f)))
16333 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16334 (txt (concat "=> " txt)))
16335 (when (and org-end-time-was-given
16336 (string-match org-plain-time-of-day-regexp txt))
16337 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16338 org-end-time-was-given
16339 (substring txt (match-end 0)))))
16340 (when org-read-date-analyze-futurep
16341 (setq txt (concat txt " (=>F)")))
16342 (setq org-read-date-overlay
16343 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16344 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16346 (defun org-read-date-analyze (ans org-def org-defdecode)
16347 "Analyze the combined answer of the date prompt."
16348 ;; FIXME: cleanup and comment
16349 (let ((nowdecode (decode-time (current-time)))
16350 delta deltan deltaw deltadef year month day
16351 hour minute second wday pm h2 m2 tl wday1
16352 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16353 (setq org-read-date-analyze-futurep nil
16354 org-read-date-analyze-forced-year nil)
16355 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16356 (setq ans "+0"))
16358 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16359 (setq ans (replace-match "" t t ans)
16360 deltan (car delta)
16361 deltaw (nth 1 delta)
16362 deltadef (nth 2 delta)))
16364 ;; Check if there is an iso week date in there. If yes, store the
16365 ;; info and postpone interpreting it until the rest of the parsing
16366 ;; is done.
16367 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16368 (setq iso-year (if (match-end 1)
16369 (org-small-year-to-year
16370 (string-to-number (match-string 1 ans))))
16371 iso-weekday (if (match-end 3)
16372 (string-to-number (match-string 3 ans)))
16373 iso-week (string-to-number (match-string 2 ans)))
16374 (setq ans (replace-match "" t t ans)))
16376 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16377 (when (string-match
16378 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16379 (setq year (if (match-end 2)
16380 (string-to-number (match-string 2 ans))
16381 (progn (setq kill-year t)
16382 (string-to-number (format-time-string "%Y"))))
16383 month (string-to-number (match-string 3 ans))
16384 day (string-to-number (match-string 4 ans)))
16385 (if (< year 100) (setq year (+ 2000 year)))
16386 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16387 t nil ans)))
16389 ;; Help matching dotted european dates
16390 (when (string-match
16391 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16392 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16393 (setq kill-year t)
16394 (string-to-number (format-time-string "%Y")))
16395 day (string-to-number (match-string 1 ans))
16396 month (string-to-number (match-string 2 ans))
16397 ans (replace-match (format "%04d-%02d-%02d" year month day)
16398 t nil ans)))
16400 ;; Help matching american dates, like 5/30 or 5/30/7
16401 (when (string-match
16402 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16403 (setq year (if (match-end 4)
16404 (string-to-number (match-string 4 ans))
16405 (progn (setq kill-year t)
16406 (string-to-number (format-time-string "%Y"))))
16407 month (string-to-number (match-string 1 ans))
16408 day (string-to-number (match-string 2 ans)))
16409 (if (< year 100) (setq year (+ 2000 year)))
16410 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16411 t nil ans)))
16412 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16413 ;; If there is a time with am/pm, and *no* time without it, we convert
16414 ;; so that matching will be successful.
16415 (loop for i from 1 to 2 do ; twice, for end time as well
16416 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16417 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16418 (setq hour (string-to-number (match-string 1 ans))
16419 minute (if (match-end 3)
16420 (string-to-number (match-string 3 ans))
16422 pm (equal ?p
16423 (string-to-char (downcase (match-string 4 ans)))))
16424 (if (and (= hour 12) (not pm))
16425 (setq hour 0)
16426 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16427 (setq ans (replace-match (format "%02d:%02d" hour minute)
16428 t t ans))))
16430 ;; Check if a time range is given as a duration
16431 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16432 (setq hour (string-to-number (match-string 1 ans))
16433 h2 (+ hour (string-to-number (match-string 3 ans)))
16434 minute (string-to-number (match-string 2 ans))
16435 m2 (+ minute (if (match-end 5) (string-to-number
16436 (match-string 5 ans))0)))
16437 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16438 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16439 t t ans)))
16441 ;; Check if there is a time range
16442 (when (boundp 'org-end-time-was-given)
16443 (setq org-time-was-given nil)
16444 (when (and (string-match org-plain-time-of-day-regexp ans)
16445 (match-end 8))
16446 (setq org-end-time-was-given (match-string 8 ans))
16447 (setq ans (concat (substring ans 0 (match-beginning 7))
16448 (substring ans (match-end 7))))))
16450 (setq tl (parse-time-string ans)
16451 day (or (nth 3 tl) (nth 3 org-defdecode))
16452 month (or (nth 4 tl)
16453 (if (and org-read-date-prefer-future
16454 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16455 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16456 (nth 4 org-defdecode)))
16457 year (or (and (not kill-year) (nth 5 tl))
16458 (if (and org-read-date-prefer-future
16459 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16460 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16461 (nth 5 org-defdecode)))
16462 hour (or (nth 2 tl) (nth 2 org-defdecode))
16463 minute (or (nth 1 tl) (nth 1 org-defdecode))
16464 second (or (nth 0 tl) 0)
16465 wday (nth 6 tl))
16467 (when (and (eq org-read-date-prefer-future 'time)
16468 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16469 (equal day (nth 3 nowdecode))
16470 (equal month (nth 4 nowdecode))
16471 (equal year (nth 5 nowdecode))
16472 (nth 2 tl)
16473 (or (< (nth 2 tl) (nth 2 nowdecode))
16474 (and (= (nth 2 tl) (nth 2 nowdecode))
16475 (nth 1 tl)
16476 (< (nth 1 tl) (nth 1 nowdecode)))))
16477 (setq day (1+ day)
16478 futurep t))
16480 ;; Special date definitions below
16481 (cond
16482 (iso-week
16483 ;; There was an iso week
16484 (require 'cal-iso)
16485 (setq futurep nil)
16486 (setq year (or iso-year year)
16487 day (or iso-weekday wday 1)
16488 wday nil ; to make sure that the trigger below does not match
16489 iso-date (calendar-gregorian-from-absolute
16490 (calendar-absolute-from-iso
16491 (list iso-week day year))))
16492 ; FIXME: Should we also push ISO weeks into the future?
16493 ; (when (and org-read-date-prefer-future
16494 ; (not iso-year)
16495 ; (< (calendar-absolute-from-gregorian iso-date)
16496 ; (time-to-days (current-time))))
16497 ; (setq year (1+ year)
16498 ; iso-date (calendar-gregorian-from-absolute
16499 ; (calendar-absolute-from-iso
16500 ; (list iso-week day year)))))
16501 (setq month (car iso-date)
16502 year (nth 2 iso-date)
16503 day (nth 1 iso-date)))
16504 (deltan
16505 (setq futurep nil)
16506 (unless deltadef
16507 (let ((now (decode-time (current-time))))
16508 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16509 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16510 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16511 ((equal deltaw "m") (setq month (+ month deltan)))
16512 ((equal deltaw "y") (setq year (+ year deltan)))))
16513 ((and wday (not (nth 3 tl)))
16514 ;; Weekday was given, but no day, so pick that day in the week
16515 ;; on or after the derived date.
16516 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16517 (unless (equal wday wday1)
16518 (setq day (+ day (% (- wday wday1 -7) 7))))))
16519 (if (and (boundp 'org-time-was-given)
16520 (nth 2 tl))
16521 (setq org-time-was-given t))
16522 (if (< year 100) (setq year (+ 2000 year)))
16523 ;; Check of the date is representable
16524 (if org-read-date-force-compatible-dates
16525 (progn
16526 (if (< year 1970)
16527 (setq year 1970 org-read-date-analyze-forced-year t))
16528 (if (> year 2037)
16529 (setq year 2037 org-read-date-analyze-forced-year t)))
16530 (condition-case nil
16531 (ignore (encode-time second minute hour day month year))
16532 (error
16533 (setq year (nth 5 org-defdecode))
16534 (setq org-read-date-analyze-forced-year t))))
16535 (setq org-read-date-analyze-futurep futurep)
16536 (list second minute hour day month year)))
16538 (defvar parse-time-weekdays)
16539 (defun org-read-date-get-relative (s today default)
16540 "Check string S for special relative date string.
16541 TODAY and DEFAULT are internal times, for today and for a default.
16542 Return shift list (N what def-flag)
16543 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16544 N is the number of WHATs to shift.
16545 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16546 the DEFAULT date rather than TODAY."
16547 (require 'parse-time)
16548 (when (and
16549 (string-match
16550 (concat
16551 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16552 "\\([0-9]+\\)?"
16553 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16554 "\\([ \t]\\|$\\)") s)
16555 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16556 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16557 (string-to-char (substring (match-string 1 s) -1))
16558 ?+))
16559 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16560 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16561 (what (if (match-end 3) (match-string 3 s) "d"))
16562 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16563 (date (if rel default today))
16564 (wday (nth 6 (decode-time date)))
16565 delta)
16566 (if wday1
16567 (progn
16568 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16569 (if (= delta 0) (setq delta 7))
16570 (if (= dir ?-)
16571 (progn
16572 (setq delta (- delta 7))
16573 (if (= delta 0) (setq delta -7))))
16574 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16575 (list delta "d" rel))
16576 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16578 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16579 "Turn a user-specified date into the internal representation.
16580 The internal representation needed by the calendar is (month day year).
16581 This is a wrapper to handle the brain-dead convention in calendar that
16582 user function argument order change dependent on argument order."
16583 (if (boundp 'calendar-date-style)
16584 (cond
16585 ((eq calendar-date-style 'american)
16586 (list arg1 arg2 arg3))
16587 ((eq calendar-date-style 'european)
16588 (list arg2 arg1 arg3))
16589 ((eq calendar-date-style 'iso)
16590 (list arg2 arg3 arg1)))
16591 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16592 (if (org-bound-and-true-p european-calendar-style)
16593 (list arg2 arg1 arg3)
16594 (list arg1 arg2 arg3)))))
16596 (defun org-eval-in-calendar (form &optional keepdate)
16597 "Eval FORM in the calendar window and return to current window.
16598 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16599 otherwise stick to the current value of `org-ans2'."
16600 (let ((sf (selected-frame))
16601 (sw (selected-window)))
16602 (select-window (get-buffer-window "*Calendar*" t))
16603 (eval form)
16604 (when (and (not keepdate) (calendar-cursor-to-date))
16605 (let* ((date (calendar-cursor-to-date))
16606 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16607 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16608 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16609 (select-window sw)
16610 (org-select-frame-set-input-focus sf)))
16612 (defun org-calendar-select ()
16613 "Return to `org-read-date' with the date currently selected.
16614 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16615 (interactive)
16616 (when (calendar-cursor-to-date)
16617 (let* ((date (calendar-cursor-to-date))
16618 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16619 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16620 (if (active-minibuffer-window) (exit-minibuffer))))
16622 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16623 "Insert a date stamp for the date given by the internal TIME.
16624 WITH-HM means use the stamp format that includes the time of the day.
16625 INACTIVE means use square brackets instead of angular ones, so that the
16626 stamp will not contribute to the agenda.
16627 PRE and POST are optional strings to be inserted before and after the
16628 stamp.
16629 The command returns the inserted time stamp."
16630 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16631 stamp)
16632 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16633 (insert-before-markers (or pre ""))
16634 (when (listp extra)
16635 (setq extra (car extra))
16636 (if (and (stringp extra)
16637 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16638 (setq extra (format "-%02d:%02d"
16639 (string-to-number (match-string 1 extra))
16640 (string-to-number (match-string 2 extra))))
16641 (setq extra nil)))
16642 (when extra
16643 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16644 (insert-before-markers (setq stamp (format-time-string fmt time)))
16645 (insert-before-markers (or post ""))
16646 (setq org-last-inserted-timestamp stamp)))
16648 (defun org-toggle-time-stamp-overlays ()
16649 "Toggle the use of custom time stamp formats."
16650 (interactive)
16651 (setq org-display-custom-times (not org-display-custom-times))
16652 (unless org-display-custom-times
16653 (let ((p (point-min)) (bmp (buffer-modified-p)))
16654 (while (setq p (next-single-property-change p 'display))
16655 (if (and (get-text-property p 'display)
16656 (eq (get-text-property p 'face) 'org-date))
16657 (remove-text-properties
16658 p (setq p (next-single-property-change p 'display))
16659 '(display t))))
16660 (set-buffer-modified-p bmp)))
16661 (if (featurep 'xemacs)
16662 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16663 (org-restart-font-lock)
16664 (setq org-table-may-need-update t)
16665 (if org-display-custom-times
16666 (message "Time stamps are overlaid with custom format")
16667 (message "Time stamp overlays removed")))
16669 (defun org-display-custom-time (beg end)
16670 "Overlay modified time stamp format over timestamp between BEG and END."
16671 (let* ((ts (buffer-substring beg end))
16672 t1 w1 with-hm tf time str w2 (off 0))
16673 (save-match-data
16674 (setq t1 (org-parse-time-string ts t))
16675 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16676 (setq off (- (match-end 0) (match-beginning 0)))))
16677 (setq end (- end off))
16678 (setq w1 (- end beg)
16679 with-hm (and (nth 1 t1) (nth 2 t1))
16680 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16681 time (org-fix-decoded-time t1)
16682 str (org-add-props
16683 (format-time-string
16684 (substring tf 1 -1) (apply 'encode-time time))
16685 nil 'mouse-face 'highlight)
16686 w2 (length str))
16687 (if (not (= w2 w1))
16688 (add-text-properties (1+ beg) (+ 2 beg)
16689 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16690 (if (featurep 'xemacs)
16691 (progn
16692 (put-text-property beg end 'invisible t)
16693 (put-text-property beg end 'end-glyph (make-glyph str)))
16694 (put-text-property beg end 'display str))))
16696 (defun org-translate-time (string)
16697 "Translate all timestamps in STRING to custom format.
16698 But do this only if the variable `org-display-custom-times' is set."
16699 (when org-display-custom-times
16700 (save-match-data
16701 (let* ((start 0)
16702 (re org-ts-regexp-both)
16703 t1 with-hm inactive tf time str beg end)
16704 (while (setq start (string-match re string start))
16705 (setq beg (match-beginning 0)
16706 end (match-end 0)
16707 t1 (save-match-data
16708 (org-parse-time-string (substring string beg end) t))
16709 with-hm (and (nth 1 t1) (nth 2 t1))
16710 inactive (equal (substring string beg (1+ beg)) "[")
16711 tf (funcall (if with-hm 'cdr 'car)
16712 org-time-stamp-custom-formats)
16713 time (org-fix-decoded-time t1)
16714 str (format-time-string
16715 (concat
16716 (if inactive "[" "<") (substring tf 1 -1)
16717 (if inactive "]" ">"))
16718 (apply 'encode-time time))
16719 string (replace-match str t t string)
16720 start (+ start (length str)))))))
16721 string)
16723 (defun org-fix-decoded-time (time)
16724 "Set 0 instead of nil for the first 6 elements of time.
16725 Don't touch the rest."
16726 (let ((n 0))
16727 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16729 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16731 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16732 "Difference between TIMESTAMP-STRING and now in days.
16733 If SECONDS is non-nil, return the difference in seconds."
16734 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16735 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16736 (funcall fdiff (current-time)))))
16738 (defun org-deadline-close (timestamp-string &optional ndays)
16739 "Is the time in TIMESTAMP-STRING close to the current date?"
16740 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16741 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16742 (not (org-entry-is-done-p))))
16744 (defun org-get-wdays (ts &optional delay zero-delay)
16745 "Get the deadline lead time appropriate for timestring TS.
16746 When DELAY is non-nil, get the delay time for scheduled items
16747 instead of the deadline lead time. When ZERO-DELAY is non-nil
16748 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16749 don't try to find the delay cookie in the scheduled timestamp."
16750 (let ((tv (if delay org-scheduled-delay-days
16751 org-deadline-warning-days)))
16752 (cond
16753 ((or (and delay (< tv 0))
16754 (and delay zero-delay (<= tv 0))
16755 (and (not delay) (<= tv 0)))
16756 ;; Enforce this value no matter what
16757 (- tv))
16758 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16759 ;; lead time is specified.
16760 (floor (* (string-to-number (match-string 1 ts))
16761 (cdr (assoc (match-string 2 ts)
16762 '(("d" . 1) ("w" . 7)
16763 ("m" . 30.4) ("y" . 365.25)
16764 ("h" . 0.041667)))))))
16765 ;; go for the default.
16766 (t tv))))
16768 (defun org-calendar-select-mouse (ev)
16769 "Return to `org-read-date' with the date currently selected.
16770 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16771 (interactive "e")
16772 (mouse-set-point ev)
16773 (when (calendar-cursor-to-date)
16774 (let* ((date (calendar-cursor-to-date))
16775 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16776 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16777 (if (active-minibuffer-window) (exit-minibuffer))))
16779 (defun org-check-deadlines (ndays)
16780 "Check if there are any deadlines due or past due.
16781 A deadline is considered due if it happens within `org-deadline-warning-days'
16782 days from today's date. If the deadline appears in an entry marked DONE,
16783 it is not shown. The prefix arg NDAYS can be used to test that many
16784 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16785 (interactive "P")
16786 (let* ((org-warn-days
16787 (cond
16788 ((equal ndays '(4)) 100000)
16789 (ndays (prefix-numeric-value ndays))
16790 (t (abs org-deadline-warning-days))))
16791 (case-fold-search nil)
16792 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16793 (callback
16794 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16796 (message "%d deadlines past-due or due within %d days"
16797 (org-occur regexp nil callback)
16798 org-warn-days)))
16800 (defsubst org-re-timestamp (type)
16801 "Return a regexp for timestamp TYPE.
16802 Allowed values for TYPE are:
16804 all: all timestamps
16805 active: only active timestamps (<...>)
16806 inactive: only inactive timestamps ([...])
16807 scheduled: only scheduled timestamps
16808 deadline: only deadline timestamps
16809 closed: only closed time-stamps
16811 When TYPE is nil, fall back on returning a regexp that matches
16812 both scheduled and deadline timestamps."
16813 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16814 ((eq type 'active) org-ts-regexp)
16815 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16816 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16817 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16818 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16819 ((eq type 'scheduled-or-deadline)
16820 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16822 (defun org-check-before-date (date)
16823 "Check if there are deadlines or scheduled entries before DATE."
16824 (interactive (list (org-read-date)))
16825 (let ((case-fold-search nil)
16826 (regexp (org-re-timestamp org-ts-type))
16827 (callback
16828 (lambda () (time-less-p
16829 (org-time-string-to-time (match-string 1))
16830 (org-time-string-to-time date)))))
16831 (message "%d entries before %s"
16832 (org-occur regexp nil callback) date)))
16834 (defun org-check-after-date (date)
16835 "Check if there are deadlines or scheduled entries after DATE."
16836 (interactive (list (org-read-date)))
16837 (let ((case-fold-search nil)
16838 (regexp (org-re-timestamp org-ts-type))
16839 (callback
16840 (lambda () (not
16841 (time-less-p
16842 (org-time-string-to-time (match-string 1))
16843 (org-time-string-to-time date))))))
16844 (message "%d entries after %s"
16845 (org-occur regexp nil callback) date)))
16847 (defun org-check-dates-range (start-date end-date)
16848 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16849 (interactive (list (org-read-date nil nil nil "Range starts")
16850 (org-read-date nil nil nil "Range end")))
16851 (let ((case-fold-search nil)
16852 (regexp (org-re-timestamp org-ts-type))
16853 (callback
16854 (lambda ()
16855 (let ((match (match-string 1)))
16856 (and
16857 (not (time-less-p
16858 (org-time-string-to-time match)
16859 (org-time-string-to-time start-date)))
16860 (time-less-p
16861 (org-time-string-to-time match)
16862 (org-time-string-to-time end-date)))))))
16863 (message "%d entries between %s and %s"
16864 (org-occur regexp nil callback) start-date end-date)))
16866 (defun org-evaluate-time-range (&optional to-buffer)
16867 "Evaluate a time range by computing the difference between start and end.
16868 Normally the result is just printed in the echo area, but with prefix arg
16869 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16870 If the time range is actually in a table, the result is inserted into the
16871 next column.
16872 For time difference computation, a year is assumed to be exactly 365
16873 days in order to avoid rounding problems."
16874 (interactive "P")
16876 (org-clock-update-time-maybe)
16877 (save-excursion
16878 (unless (org-at-date-range-p t)
16879 (goto-char (point-at-bol))
16880 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16881 (if (not (org-at-date-range-p t))
16882 (user-error "Not at a time-stamp range, and none found in current line")))
16883 (let* ((ts1 (match-string 1))
16884 (ts2 (match-string 2))
16885 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16886 (match-end (match-end 0))
16887 (time1 (org-time-string-to-time ts1))
16888 (time2 (org-time-string-to-time ts2))
16889 (t1 (org-float-time time1))
16890 (t2 (org-float-time time2))
16891 (diff (abs (- t2 t1)))
16892 (negative (< (- t2 t1) 0))
16893 ;; (ys (floor (* 365 24 60 60)))
16894 (ds (* 24 60 60))
16895 (hs (* 60 60))
16896 (fy "%dy %dd %02d:%02d")
16897 (fy1 "%dy %dd")
16898 (fd "%dd %02d:%02d")
16899 (fd1 "%dd")
16900 (fh "%02d:%02d")
16901 y d h m align)
16902 (if havetime
16903 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16905 d (floor (/ diff ds)) diff (mod diff ds)
16906 h (floor (/ diff hs)) diff (mod diff hs)
16907 m (floor (/ diff 60)))
16908 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16910 d (floor (+ (/ diff ds) 0.5))
16911 h 0 m 0))
16912 (if (not to-buffer)
16913 (message "%s" (org-make-tdiff-string y d h m))
16914 (if (org-at-table-p)
16915 (progn
16916 (goto-char match-end)
16917 (setq align t)
16918 (and (looking-at " *|") (goto-char (match-end 0))))
16919 (goto-char match-end))
16920 (if (looking-at
16921 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16922 (replace-match ""))
16923 (if negative (insert " -"))
16924 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16925 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16926 (insert " " (format fh h m))))
16927 (if align (org-table-align))
16928 (message "Time difference inserted")))))
16930 (defun org-make-tdiff-string (y d h m)
16931 (let ((fmt "")
16932 (l nil))
16933 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16934 l (push y l)))
16935 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16936 l (push d l)))
16937 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16938 l (push h l)))
16939 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16940 l (push m l)))
16941 (apply 'format fmt (nreverse l))))
16943 (defun org-time-string-to-time (s &optional buffer pos)
16944 "Convert a timestamp string into internal time."
16945 (condition-case errdata
16946 (apply 'encode-time (org-parse-time-string s))
16947 (error (error "Bad timestamp `%s'%s\nError was: %s"
16948 s (if (not (and buffer pos))
16950 (format " at %d in buffer `%s'" pos buffer))
16951 (cdr errdata)))))
16953 (defun org-time-string-to-seconds (s)
16954 "Convert a timestamp string to a number of seconds."
16955 (org-float-time (org-time-string-to-time s)))
16957 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16958 "Convert a time stamp to an absolute day number.
16959 If there is a specifier for a cyclic time stamp, get the closest
16960 date to DAYNR.
16961 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16962 The variable `date' is bound by the calendar when this is called."
16963 (cond
16964 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16965 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16966 daynr
16967 (+ daynr 1000)))
16968 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16969 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16970 (time-to-days (current-time))) (match-string 0 s)
16971 prefer show-all))
16972 (t (time-to-days
16973 (condition-case errdata
16974 (apply 'encode-time (org-parse-time-string s))
16975 (error (error "Bad timestamp `%s'%s\nError was: %s"
16976 s (if (not (and buffer pos))
16978 (format " at %d in buffer `%s'" pos buffer))
16979 (cdr errdata))))))))
16981 (defun org-days-to-iso-week (days)
16982 "Return the iso week number."
16983 (require 'cal-iso)
16984 (car (calendar-iso-from-absolute days)))
16986 (defun org-small-year-to-year (year)
16987 "Convert 2-digit years into 4-digit years.
16988 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
16989 The year 2000 cannot be abbreviated. Any year larger than 99
16990 is returned unchanged."
16991 (if (< year 38)
16992 (setq year (+ 2000 year))
16993 (if (< year 100)
16994 (setq year (+ 1900 year))))
16995 year)
16997 (defun org-time-from-absolute (d)
16998 "Return the time corresponding to date D.
16999 D may be an absolute day number, or a calendar-type list (month day year)."
17000 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17001 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17003 (defun org-calendar-holiday ()
17004 "List of holidays, for Diary display in Org-mode."
17005 (require 'holidays)
17006 (let ((hl (funcall
17007 (if (fboundp 'calendar-check-holidays)
17008 'calendar-check-holidays 'check-calendar-holidays) date)))
17009 (if hl (mapconcat 'identity hl "; "))))
17011 (defun org-diary-sexp-entry (sexp entry date)
17012 "Process a SEXP diary ENTRY for DATE."
17013 (require 'diary-lib)
17014 (let ((result (if calendar-debug-sexp
17015 (let ((stack-trace-on-error t))
17016 (eval (car (read-from-string sexp))))
17017 (condition-case nil
17018 (eval (car (read-from-string sexp)))
17019 (error
17020 (beep)
17021 (message "Bad sexp at line %d in %s: %s"
17022 (org-current-line)
17023 (buffer-file-name) sexp)
17024 (sleep-for 2))))))
17025 (cond ((stringp result) (split-string result "; "))
17026 ((and (consp result)
17027 (not (consp (cdr result)))
17028 (stringp (cdr result))) (cdr result))
17029 ((and (consp result)
17030 (stringp (car result))) result)
17031 (result entry))))
17033 (defun org-diary-to-ical-string (frombuf)
17034 "Get iCalendar entries from diary entries in buffer FROMBUF.
17035 This uses the icalendar.el library."
17036 (let* ((tmpdir (if (featurep 'xemacs)
17037 (temp-directory)
17038 temporary-file-directory))
17039 (tmpfile (make-temp-name
17040 (expand-file-name "orgics" tmpdir)))
17041 buf rtn b e)
17042 (with-current-buffer frombuf
17043 (icalendar-export-region (point-min) (point-max) tmpfile)
17044 (setq buf (find-buffer-visiting tmpfile))
17045 (set-buffer buf)
17046 (goto-char (point-min))
17047 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17048 (setq b (match-beginning 0)))
17049 (goto-char (point-max))
17050 (if (re-search-backward "^END:VEVENT" nil t)
17051 (setq e (match-end 0)))
17052 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17053 (kill-buffer buf)
17054 (delete-file tmpfile)
17055 rtn))
17057 (defun org-closest-date (start current change prefer show-all)
17058 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17059 When PREFER is `past', return a date that is either CURRENT or past.
17060 When PREFER is `future', return a date that is either CURRENT or future.
17061 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17062 ;; Make the proper lists from the dates
17063 (catch 'exit
17064 (let ((a1 '(("h" . hour)
17065 ("d" . day)
17066 ("w" . week)
17067 ("m" . month)
17068 ("y" . year)))
17069 (shour (nth 2 (org-parse-time-string start)))
17070 dn dw sday cday n1 n2 n0
17071 d m y y1 y2 date1 date2 nmonths nm ny m2)
17073 (setq start (org-date-to-gregorian start)
17074 current (org-date-to-gregorian
17075 (if show-all
17076 current
17077 (time-to-days (current-time))))
17078 sday (calendar-absolute-from-gregorian start)
17079 cday (calendar-absolute-from-gregorian current))
17081 (if (<= cday sday) (throw 'exit sday))
17083 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17084 (setq dn (string-to-number (match-string 1 change))
17085 dw (cdr (assoc (match-string 2 change) a1)))
17086 (user-error "Invalid change specifier: %s" change))
17087 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17088 (cond
17089 ((eq dw 'hour)
17090 (let ((missing-hours
17091 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17092 dn)))
17093 (setq n1 (if (zerop missing-hours) cday
17094 (- cday (1+ (floor (/ missing-hours 24)))))
17095 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17096 ((eq dw 'day)
17097 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17098 n2 (+ n1 dn)))
17099 ((eq dw 'year)
17100 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17101 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17102 (setq date1 (list m d y1)
17103 n1 (calendar-absolute-from-gregorian date1)
17104 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17105 n2 (calendar-absolute-from-gregorian date2)))
17106 ((eq dw 'month)
17107 ;; approx number of month between the two dates
17108 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17109 ;; How often does dn fit in there?
17110 (setq d (nth 1 start) m (car start) y (nth 2 start)
17111 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17112 m (+ m nm)
17113 ny (floor (/ m 12))
17114 y (+ y ny)
17115 m (- m (* ny 12)))
17116 (while (> m 12) (setq m (- m 12) y (1+ y)))
17117 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17118 (setq m2 (+ m dn) y2 y)
17119 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17120 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17121 (while (<= n2 cday)
17122 (setq n1 n2 m m2 y y2)
17123 (setq m2 (+ m dn) y2 y)
17124 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17125 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17126 ;; Make sure n1 is the earlier date
17127 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17128 (if show-all
17129 (cond
17130 ((eq prefer 'past) (if (= cday n2) n2 n1))
17131 ((eq prefer 'future) (if (= cday n1) n1 n2))
17132 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17133 (cond
17134 ((eq prefer 'past) (if (= cday n2) n2 n1))
17135 ((eq prefer 'future) (if (= cday n1) n1 n2))
17136 (t (if (= cday n1) n1 n2)))))))
17138 (defun org-date-to-gregorian (date)
17139 "Turn any specification of DATE into a Gregorian date for the calendar."
17140 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17141 ((and (listp date) (= (length date) 3)) date)
17142 ((stringp date)
17143 (setq date (org-parse-time-string date))
17144 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17145 ((listp date)
17146 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17148 (defun org-parse-time-string (s &optional nodefault)
17149 "Parse the standard Org-mode time string.
17150 This should be a lot faster than the normal `parse-time-string'.
17151 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17152 hour and minute fields will be nil if not given."
17153 (cond ((string-match org-ts-regexp0 s)
17154 (list 0
17155 (if (or (match-beginning 8) (not nodefault))
17156 (string-to-number (or (match-string 8 s) "0")))
17157 (if (or (match-beginning 7) (not nodefault))
17158 (string-to-number (or (match-string 7 s) "0")))
17159 (string-to-number (match-string 4 s))
17160 (string-to-number (match-string 3 s))
17161 (string-to-number (match-string 2 s))
17162 nil nil nil))
17163 ((string-match "^<[^>]+>$" s)
17164 (decode-time (seconds-to-time (org-matcher-time s))))
17165 (t (error "Not a standard Org-mode time string: %s" s))))
17167 (defun org-timestamp-up (&optional arg)
17168 "Increase the date item at the cursor by one.
17169 If the cursor is on the year, change the year. If it is on the month,
17170 the day or the time, change that.
17171 With prefix ARG, change by that many units."
17172 (interactive "p")
17173 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17175 (defun org-timestamp-down (&optional arg)
17176 "Decrease the date item at the cursor by one.
17177 If the cursor is on the year, change the year. If it is on the month,
17178 the day or the time, change that.
17179 With prefix ARG, change by that many units."
17180 (interactive "p")
17181 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17183 (defun org-timestamp-up-day (&optional arg)
17184 "Increase the date in the time stamp by one day.
17185 With prefix ARG, change that many days."
17186 (interactive "p")
17187 (if (and (not (org-at-timestamp-p t))
17188 (org-at-heading-p))
17189 (org-todo 'up)
17190 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17192 (defun org-timestamp-down-day (&optional arg)
17193 "Decrease the date in the time stamp by one day.
17194 With prefix ARG, change that many days."
17195 (interactive "p")
17196 (if (and (not (org-at-timestamp-p t))
17197 (org-at-heading-p))
17198 (org-todo 'down)
17199 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17201 (defun org-at-timestamp-p (&optional inactive-ok)
17202 "Determine if the cursor is in or at a timestamp."
17203 (interactive)
17204 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17205 (pos (point))
17206 (ans (or (looking-at tsr)
17207 (save-excursion
17208 (skip-chars-backward "^[<\n\r\t")
17209 (if (> (point) (point-min)) (backward-char 1))
17210 (and (looking-at tsr)
17211 (> (- (match-end 0) pos) -1))))))
17212 (and ans
17213 (boundp 'org-ts-what)
17214 (setq org-ts-what
17215 (cond
17216 ((= pos (match-beginning 0)) 'bracket)
17217 ;; Point is considered to be "on the bracket" whether
17218 ;; it's really on it or right after it.
17219 ((= pos (1- (match-end 0))) 'bracket)
17220 ((= pos (match-end 0)) 'after)
17221 ((org-pos-in-match-range pos 2) 'year)
17222 ((org-pos-in-match-range pos 3) 'month)
17223 ((org-pos-in-match-range pos 7) 'hour)
17224 ((org-pos-in-match-range pos 8) 'minute)
17225 ((or (org-pos-in-match-range pos 4)
17226 (org-pos-in-match-range pos 5)) 'day)
17227 ((and (> pos (or (match-end 8) (match-end 5)))
17228 (< pos (match-end 0)))
17229 (- pos (or (match-end 8) (match-end 5))))
17230 (t 'day))))
17231 ans))
17233 (defun org-toggle-timestamp-type ()
17234 "Toggle the type (<active> or [inactive]) of a time stamp."
17235 (interactive)
17236 (when (org-at-timestamp-p t)
17237 (let ((beg (match-beginning 0)) (end (match-end 0))
17238 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17239 (save-excursion
17240 (goto-char beg)
17241 (while (re-search-forward "[][<>]" end t)
17242 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17243 t t)))
17244 (message "Timestamp is now %sactive"
17245 (if (equal (char-after beg) ?<) "" "in")))))
17247 (defun org-at-clock-log-p nil
17248 "Is the cursor on the clock log line?"
17249 (save-excursion
17250 (move-beginning-of-line 1)
17251 (looking-at "^[ \t]*CLOCK:")))
17253 (defvar org-clock-history) ; defined in org-clock.el
17254 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17255 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17256 "Change the date in the time stamp at point.
17257 The date will be changed by N times WHAT. WHAT can be `day', `month',
17258 `year', `minute', `second'. If WHAT is not given, the cursor position
17259 in the timestamp determines what will be changed.
17260 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17261 (let ((origin (point)) origin-cat
17262 with-hm inactive
17263 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17264 org-ts-what
17265 extra rem
17266 ts time time0 fixnext clrgx)
17267 (if (not (org-at-timestamp-p t))
17268 (user-error "Not at a timestamp"))
17269 (if (and (not what) (eq org-ts-what 'bracket))
17270 (org-toggle-timestamp-type)
17271 ;; Point isn't on brackets. Remember the part of the time-stamp
17272 ;; the point was in. Indeed, size of time-stamps may change,
17273 ;; but point must be kept in the same category nonetheless.
17274 (setq origin-cat org-ts-what)
17275 (if (and (not what) (not (eq org-ts-what 'day))
17276 org-display-custom-times
17277 (get-text-property (point) 'display)
17278 (not (get-text-property (1- (point)) 'display)))
17279 (setq org-ts-what 'day))
17280 (setq org-ts-what (or what org-ts-what)
17281 inactive (= (char-after (match-beginning 0)) ?\[)
17282 ts (match-string 0))
17283 (replace-match "")
17284 (when (string-match
17285 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17287 (setq extra (match-string 1 ts))
17288 (if suppress-tmp-delay
17289 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17290 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17291 (setq with-hm t))
17292 (setq time0 (org-parse-time-string ts))
17293 (when (and updown
17294 (eq org-ts-what 'minute)
17295 (not current-prefix-arg))
17296 ;; This looks like s-up and s-down. Change by one rounding step.
17297 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17298 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17299 (setcar (cdr time0) (+ (nth 1 time0)
17300 (if (> n 0) (- rem) (- dm rem))))))
17301 (setq time
17302 (encode-time (or (car time0) 0)
17303 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17304 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17305 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17306 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17307 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17308 (nthcdr 6 time0)))
17309 (when (and (member org-ts-what '(hour minute))
17310 extra
17311 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17312 (setq extra (org-modify-ts-extra
17313 extra
17314 (if (eq org-ts-what 'hour) 2 5)
17315 n dm)))
17316 (when (integerp org-ts-what)
17317 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17318 (if (eq what 'calendar)
17319 (let ((cal-date (org-get-date-from-calendar)))
17320 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17321 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17322 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17323 (setcar time0 (or (car time0) 0))
17324 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17325 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17326 (setq time (apply 'encode-time time0))))
17327 ;; Insert the new time-stamp, and ensure point stays in the same
17328 ;; category as before (i.e. not after the last position in that
17329 ;; category).
17330 (let ((pos (point)))
17331 ;; Stay before inserted string. `save-excursion' is of no use.
17332 (setq org-last-changed-timestamp
17333 (org-insert-time-stamp time with-hm inactive nil nil extra))
17334 (goto-char pos))
17335 (save-match-data
17336 (looking-at org-ts-regexp3)
17337 (goto-char (cond
17338 ;; `day' category ends before `hour' if any, or at
17339 ;; the end of the day name.
17340 ((eq origin-cat 'day)
17341 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17342 ((eq origin-cat 'hour) (min (match-end 7) origin))
17343 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17344 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17345 ;; `year' and `month' have both fixed size: point
17346 ;; couldn't have moved into another part.
17347 (t origin))))
17348 ;; Update clock if on a CLOCK line.
17349 (org-clock-update-time-maybe)
17350 ;; Maybe adjust the closest clock in `org-clock-history'
17351 (when org-clock-adjust-closest
17352 (if (not (and (org-at-clock-log-p)
17353 (< 1 (length (delq nil (mapcar 'marker-position
17354 org-clock-history))))))
17355 (message "No clock to adjust")
17356 (cond ((save-excursion ; fix previous clock?
17357 (re-search-backward org-ts-regexp0 nil t)
17358 (org-looking-back (concat org-clock-string " \\[")))
17359 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17360 ((save-excursion ; fix next clock?
17361 (re-search-backward org-ts-regexp0 nil t)
17362 (looking-at (concat org-ts-regexp0 "\\] =>")))
17363 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17364 (save-window-excursion
17365 ;; Find closest clock to point, adjust the previous/next one in history
17366 (let* ((p (save-excursion (org-back-to-heading t)))
17367 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17368 (clfixnth
17369 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17370 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17371 (if (not clfixpos)
17372 (message "No clock to adjust")
17373 (save-excursion
17374 (org-goto-marker-or-bmk clfixpos)
17375 (org-show-subtree)
17376 (when (re-search-forward clrgx nil t)
17377 (goto-char (match-beginning 1))
17378 (let (org-clock-adjust-closest)
17379 (org-timestamp-change n org-ts-what updown))
17380 (message "Clock adjusted in %s for heading: %s"
17381 (file-name-nondirectory (buffer-file-name))
17382 (org-get-heading t t)))))))))
17383 ;; Try to recenter the calendar window, if any.
17384 (if (and org-calendar-follow-timestamp-change
17385 (get-buffer-window "*Calendar*" t)
17386 (memq org-ts-what '(day month year)))
17387 (org-recenter-calendar (time-to-days time))))))
17389 (defun org-modify-ts-extra (s pos n dm)
17390 "Change the different parts of the lead-time and repeat fields in timestamp."
17391 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17392 ng h m new rem)
17393 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17394 (cond
17395 ((or (org-pos-in-match-range pos 2)
17396 (org-pos-in-match-range pos 3))
17397 (setq m (string-to-number (match-string 3 s))
17398 h (string-to-number (match-string 2 s)))
17399 (if (org-pos-in-match-range pos 2)
17400 (setq h (+ h n))
17401 (setq n (* dm (org-no-warnings (signum n))))
17402 (when (not (= 0 (setq rem (% m dm))))
17403 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17404 (setq m (+ m n)))
17405 (if (< m 0) (setq m (+ m 60) h (1- h)))
17406 (if (> m 59) (setq m (- m 60) h (1+ h)))
17407 (setq h (min 24 (max 0 h)))
17408 (setq ng 1 new (format "-%02d:%02d" h m)))
17409 ((org-pos-in-match-range pos 6)
17410 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17411 ((org-pos-in-match-range pos 5)
17412 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17414 ((org-pos-in-match-range pos 9)
17415 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17416 ((org-pos-in-match-range pos 8)
17417 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17419 (when ng
17420 (setq s (concat
17421 (substring s 0 (match-beginning ng))
17423 (substring s (match-end ng))))))
17426 (defun org-recenter-calendar (date)
17427 "If the calendar is visible, recenter it to DATE."
17428 (let ((cwin (get-buffer-window "*Calendar*" t)))
17429 (when cwin
17430 (let ((calendar-move-hook nil))
17431 (with-selected-window cwin
17432 (calendar-goto-date (if (listp date) date
17433 (calendar-gregorian-from-absolute date))))))))
17435 (defun org-goto-calendar (&optional arg)
17436 "Go to the Emacs calendar at the current date.
17437 If there is a time stamp in the current line, go to that date.
17438 A prefix ARG can be used to force the current date."
17439 (interactive "P")
17440 (let ((tsr org-ts-regexp) diff
17441 (calendar-move-hook nil)
17442 (calendar-view-holidays-initially-flag nil)
17443 (calendar-view-diary-initially-flag nil))
17444 (if (or (org-at-timestamp-p)
17445 (save-excursion
17446 (beginning-of-line 1)
17447 (looking-at (concat ".*" tsr))))
17448 (let ((d1 (time-to-days (current-time)))
17449 (d2 (time-to-days
17450 (org-time-string-to-time (match-string 1)))))
17451 (setq diff (- d2 d1))))
17452 (calendar)
17453 (calendar-goto-today)
17454 (if (and diff (not arg)) (calendar-forward-day diff))))
17456 (defun org-get-date-from-calendar ()
17457 "Return a list (month day year) of date at point in calendar."
17458 (with-current-buffer "*Calendar*"
17459 (save-match-data
17460 (calendar-cursor-to-date))))
17462 (defun org-date-from-calendar ()
17463 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17464 If there is already a time stamp at the cursor position, update it."
17465 (interactive)
17466 (if (org-at-timestamp-p t)
17467 (org-timestamp-change 0 'calendar)
17468 (let ((cal-date (org-get-date-from-calendar)))
17469 (org-insert-time-stamp
17470 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17472 (defcustom org-effort-durations
17473 `(("h" . 60)
17474 ("d" . ,(* 60 8))
17475 ("w" . ,(* 60 8 5))
17476 ("m" . ,(* 60 8 5 4))
17477 ("y" . ,(* 60 8 5 40)))
17478 "Conversion factor to minutes for an effort modifier.
17480 Each entry has the form (MODIFIER . MINUTES).
17482 In an effort string, a number followed by MODIFIER is multiplied
17483 by the specified number of MINUTES to obtain an effort in
17484 minutes.
17486 For example, if the value of this variable is ((\"hours\" . 60)), then an
17487 effort string \"2hours\" is equivalent to 120 minutes."
17488 :group 'org-agenda
17489 :version "24.1"
17490 :type '(alist :key-type (string :tag "Modifier")
17491 :value-type (number :tag "Minutes")))
17493 (defun org-minutes-to-clocksum-string (m)
17494 "Format number of minutes as a clocksum string.
17495 The format is determined by `org-time-clocksum-format',
17496 `org-time-clocksum-use-fractional' and
17497 `org-time-clocksum-fractional-format' and
17498 `org-time-clocksum-use-effort-durations'."
17499 (let ((clocksum "")
17500 (m (round m)) ; Don't allow fractions of minutes
17501 h d w mo y fmt n)
17502 (setq h (if org-time-clocksum-use-effort-durations
17503 (cdr (assoc "h" org-effort-durations)) 60)
17504 d (if org-time-clocksum-use-effort-durations
17505 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17506 w (if org-time-clocksum-use-effort-durations
17507 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17508 mo (if org-time-clocksum-use-effort-durations
17509 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17510 y (if org-time-clocksum-use-effort-durations
17511 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17512 ;; fractional format
17513 (if org-time-clocksum-use-fractional
17514 (cond
17515 ;; single format string
17516 ((stringp org-time-clocksum-fractional-format)
17517 (format org-time-clocksum-fractional-format (/ m (float h))))
17518 ;; choice of fractional formats for different time units
17519 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17520 (> (/ (truncate m) (* y d h)) 0))
17521 (format fmt (/ m (* y d (float h)))))
17522 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17523 (> (/ (truncate m) (* mo d h)) 0))
17524 (format fmt (/ m (* mo d (float h)))))
17525 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17526 (> (/ (truncate m) (* w d h)) 0))
17527 (format fmt (/ m (* w d (float h)))))
17528 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17529 (> (/ (truncate m) (* d h)) 0))
17530 (format fmt (/ m (* d (float h)))))
17531 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17532 (> (/ (truncate m) h) 0))
17533 (format fmt (/ m (float h))))
17534 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17535 (format fmt m))
17536 ;; fall back to smallest time unit with a format
17537 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17538 (format fmt (/ m (float h))))
17539 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17540 (format fmt (/ m (* d (float h)))))
17541 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17542 (format fmt (/ m (* w d (float h)))))
17543 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17544 (format fmt (/ m (* mo d (float h)))))
17545 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17546 (format fmt (/ m (* y d (float h))))))
17547 ;; standard (non-fractional) format, with single format string
17548 (if (stringp org-time-clocksum-format)
17549 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17550 ;; separate formats components
17551 (and (setq fmt (plist-get org-time-clocksum-format :years))
17552 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17553 (plist-get org-time-clocksum-format :require-years))
17554 (setq clocksum (concat clocksum (format fmt n))
17555 m (- m (* n y d h))))
17556 (and (setq fmt (plist-get org-time-clocksum-format :months))
17557 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17558 (plist-get org-time-clocksum-format :require-months))
17559 (setq clocksum (concat clocksum (format fmt n))
17560 m (- m (* n mo d h))))
17561 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17562 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17563 (plist-get org-time-clocksum-format :require-weeks))
17564 (setq clocksum (concat clocksum (format fmt n))
17565 m (- m (* n w d h))))
17566 (and (setq fmt (plist-get org-time-clocksum-format :days))
17567 (or (> (setq n (/ (truncate m) (* d h))) 0)
17568 (plist-get org-time-clocksum-format :require-days))
17569 (setq clocksum (concat clocksum (format fmt n))
17570 m (- m (* n d h))))
17571 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17572 (or (> (setq n (/ (truncate m) h)) 0)
17573 (plist-get org-time-clocksum-format :require-hours))
17574 (setq clocksum (concat clocksum (format fmt n))
17575 m (- m (* n h))))
17576 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17577 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17578 (setq clocksum (concat clocksum (format fmt m))))
17579 ;; return formatted time duration
17580 clocksum))))
17582 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17583 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17584 "Org mode version 8.0")
17586 (defun org-hours-to-clocksum-string (n)
17587 (org-minutes-to-clocksum-string (* n 60)))
17589 (defun org-hh:mm-string-to-minutes (s)
17590 "Convert a string H:MM to a number of minutes.
17591 If the string is just a number, interpret it as minutes.
17592 In fact, the first hh:mm or number in the string will be taken,
17593 there can be extra stuff in the string.
17594 If no number is found, the return value is 0."
17595 (cond
17596 ((integerp s) s)
17597 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17598 (+ (* (string-to-number (match-string 1 s)) 60)
17599 (string-to-number (match-string 2 s))))
17600 ((string-match "\\([0-9]+\\)" s)
17601 (string-to-number (match-string 1 s)))
17602 (t 0)))
17604 (defcustom org-image-actual-width t
17605 "Should we use the actual width of images when inlining them?
17607 When set to `t', always use the image width.
17609 When set to a number, use imagemagick (when available) to set
17610 the image's width to this value.
17612 When set to a number in a list, try to get the width from any
17613 #+ATTR.* keyword if it matches a width specification like
17615 #+ATTR_HTML: :width 300px
17617 and fall back on that number if none is found.
17619 When set to nil, try to get the width from an #+ATTR.* keyword
17620 and fall back on the original width if none is found.
17622 This requires Emacs >= 24.1, build with imagemagick support."
17623 :group 'org-appearance
17624 :version "24.4"
17625 :package-version '(Org . "8.0")
17626 :type '(choice
17627 (const :tag "Use the image width" t)
17628 (integer :tag "Use a number of pixels")
17629 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17630 (const :tag "Use #+ATTR* or don't resize" nil)))
17632 (defcustom org-agenda-inhibit-startup nil
17633 "Inhibit startup when preparing agenda buffers.
17634 When this variable is `t' (the default), the initialization of
17635 the Org agenda buffers is inhibited: e.g. the visibility state
17636 is not set, the tables are not re-aligned, etc."
17637 :type 'boolean
17638 :version "24.3"
17639 :group 'org-agenda)
17641 (defun org-duration-string-to-minutes (s &optional output-to-string)
17642 "Convert a duration string S to minutes.
17644 A bare number is interpreted as minutes, modifiers can be set by
17645 customizing `org-effort-durations' (which see).
17647 Entries containing a colon are interpreted as H:MM by
17648 `org-hh:mm-string-to-minutes'."
17649 (let ((result 0)
17650 (re (concat "\\([0-9.]+\\) *\\("
17651 (regexp-opt (mapcar 'car org-effort-durations))
17652 "\\)")))
17653 (while (string-match re s)
17654 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17655 (string-to-number (match-string 1 s))))
17656 (setq s (replace-match "" nil t s)))
17657 (setq result (floor result))
17658 (incf result (org-hh:mm-string-to-minutes s))
17659 (if output-to-string (number-to-string result) result)))
17661 ;;;; Files
17663 (defun org-save-all-org-buffers ()
17664 "Save all Org-mode buffers without user confirmation."
17665 (interactive)
17666 (message "Saving all Org-mode buffers...")
17667 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17668 (when (featurep 'org-id) (org-id-locations-save))
17669 (message "Saving all Org-mode buffers... done"))
17671 (defun org-revert-all-org-buffers ()
17672 "Revert all Org-mode buffers.
17673 Prompt for confirmation when there are unsaved changes.
17674 Be sure you know what you are doing before letting this function
17675 overwrite your changes.
17677 This function is useful in a setup where one tracks org files
17678 with a version control system, to revert on one machine after pulling
17679 changes from another. I believe the procedure must be like this:
17681 1. M-x org-save-all-org-buffers
17682 2. Pull changes from the other machine, resolve conflicts
17683 3. M-x org-revert-all-org-buffers"
17684 (interactive)
17685 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17686 (user-error "Abort"))
17687 (save-excursion
17688 (save-window-excursion
17689 (mapc
17690 (lambda (b)
17691 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17692 (with-current-buffer b buffer-file-name))
17693 (org-pop-to-buffer-same-window b)
17694 (revert-buffer t 'no-confirm)))
17695 (buffer-list))
17696 (when (and (featurep 'org-id) org-id-track-globally)
17697 (org-id-locations-load)))))
17699 ;;;; Agenda files
17701 ;;;###autoload
17702 (defun org-switchb (&optional arg)
17703 "Switch between Org buffers.
17704 With one prefix argument, restrict available buffers to files.
17705 With two prefix arguments, restrict available buffers to agenda files.
17707 Defaults to `iswitchb' for buffer name completion.
17708 Set `org-completion-use-ido' to make it use ido instead."
17709 (interactive "P")
17710 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17711 ((equal arg '(16)) (org-buffer-list 'agenda))
17712 (t (org-buffer-list))))
17713 (org-completion-use-iswitchb org-completion-use-iswitchb)
17714 (org-completion-use-ido org-completion-use-ido))
17715 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17716 (setq org-completion-use-iswitchb t))
17717 (org-pop-to-buffer-same-window
17718 (org-icompleting-read "Org buffer: "
17719 (mapcar 'list (mapcar 'buffer-name blist))
17720 nil t))))
17722 ;;; Define some older names previously used for this functionality
17723 ;;;###autoload
17724 (defalias 'org-ido-switchb 'org-switchb)
17725 ;;;###autoload
17726 (defalias 'org-iswitchb 'org-switchb)
17728 (defun org-buffer-list (&optional predicate exclude-tmp)
17729 "Return a list of Org buffers.
17730 PREDICATE can be `export', `files' or `agenda'.
17732 export restrict the list to Export buffers.
17733 files restrict the list to buffers visiting Org files.
17734 agenda restrict the list to buffers visiting agenda files.
17736 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17737 (let* ((bfn nil)
17738 (agenda-files (and (eq predicate 'agenda)
17739 (mapcar 'file-truename (org-agenda-files t))))
17740 (filter
17741 (cond
17742 ((eq predicate 'files)
17743 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17744 ((eq predicate 'export)
17745 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17746 ((eq predicate 'agenda)
17747 (lambda (b)
17748 (with-current-buffer b
17749 (and (derived-mode-p 'org-mode)
17750 (setq bfn (buffer-file-name b))
17751 (member (file-truename bfn) agenda-files)))))
17752 (t (lambda (b) (with-current-buffer b
17753 (or (derived-mode-p 'org-mode)
17754 (string-match "\*Org .*Export"
17755 (buffer-name b)))))))))
17756 (delq nil
17757 (mapcar
17758 (lambda(b)
17759 (if (and (funcall filter b)
17760 (or (not exclude-tmp)
17761 (not (string-match "tmp" (buffer-name b)))))
17763 nil))
17764 (buffer-list)))))
17766 (defun org-agenda-files (&optional unrestricted archives)
17767 "Get the list of agenda files.
17768 Optional UNRESTRICTED means return the full list even if a restriction
17769 is currently in place.
17770 When ARCHIVES is t, include all archive files that are really being
17771 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17772 `org-agenda-archives-mode' is t."
17773 (let ((files
17774 (cond
17775 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17776 ((stringp org-agenda-files) (org-read-agenda-file-list))
17777 ((listp org-agenda-files) org-agenda-files)
17778 (t (error "Invalid value of `org-agenda-files'")))))
17779 (setq files (apply 'append
17780 (mapcar (lambda (f)
17781 (if (file-directory-p f)
17782 (directory-files
17783 f t org-agenda-file-regexp)
17784 (list f)))
17785 files)))
17786 (when org-agenda-skip-unavailable-files
17787 (setq files (delq nil
17788 (mapcar (function
17789 (lambda (file)
17790 (and (file-readable-p file) file)))
17791 files))))
17792 (when (or (eq archives t)
17793 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17794 (setq files (org-add-archive-files files)))
17795 files))
17797 (defun org-agenda-file-p (&optional file)
17798 "Return non-nil, if FILE is an agenda file.
17799 If FILE is omitted, use the file associated with the current
17800 buffer."
17801 (member (or file (buffer-file-name))
17802 (org-agenda-files t)))
17804 (defun org-edit-agenda-file-list ()
17805 "Edit the list of agenda files.
17806 Depending on setup, this either uses customize to edit the variable
17807 `org-agenda-files', or it visits the file that is holding the list. In the
17808 latter case, the buffer is set up in a way that saving it automatically kills
17809 the buffer and restores the previous window configuration."
17810 (interactive)
17811 (if (stringp org-agenda-files)
17812 (let ((cw (current-window-configuration)))
17813 (find-file org-agenda-files)
17814 (org-set-local 'org-window-configuration cw)
17815 (org-add-hook 'after-save-hook
17816 (lambda ()
17817 (set-window-configuration
17818 (prog1 org-window-configuration
17819 (kill-buffer (current-buffer))))
17820 (org-install-agenda-files-menu)
17821 (message "New agenda file list installed"))
17822 nil 'local)
17823 (message "%s" (substitute-command-keys
17824 "Edit list and finish with \\[save-buffer]")))
17825 (customize-variable 'org-agenda-files)))
17827 (defun org-store-new-agenda-file-list (list)
17828 "Set new value for the agenda file list and save it correctly."
17829 (if (stringp org-agenda-files)
17830 (let ((fe (org-read-agenda-file-list t)) b u)
17831 (while (setq b (find-buffer-visiting org-agenda-files))
17832 (kill-buffer b))
17833 (with-temp-file org-agenda-files
17834 (insert
17835 (mapconcat
17836 (lambda (f) ;; Keep un-expanded entries.
17837 (if (setq u (assoc f fe))
17838 (cdr u)
17840 list "\n")
17841 "\n")))
17842 (let ((org-mode-hook nil) (org-inhibit-startup t)
17843 (org-insert-mode-line-in-empty-file nil))
17844 (setq org-agenda-files list)
17845 (customize-save-variable 'org-agenda-files org-agenda-files))))
17847 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17848 "Read the list of agenda files from a file.
17849 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17850 filenames, used by `org-store-new-agenda-file-list' to write back
17851 un-expanded file names."
17852 (when (file-directory-p org-agenda-files)
17853 (error "`org-agenda-files' cannot be a single directory"))
17854 (when (stringp org-agenda-files)
17855 (with-temp-buffer
17856 (insert-file-contents org-agenda-files)
17857 (mapcar
17858 (lambda (f)
17859 (let ((e (expand-file-name (substitute-in-file-name f)
17860 org-directory)))
17861 (if pair-with-expansion
17862 (cons e f)
17863 e)))
17864 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17866 ;;;###autoload
17867 (defun org-cycle-agenda-files ()
17868 "Cycle through the files in `org-agenda-files'.
17869 If the current buffer visits an agenda file, find the next one in the list.
17870 If the current buffer does not, find the first agenda file."
17871 (interactive)
17872 (let* ((fs (org-agenda-files t))
17873 (files (append fs (list (car fs))))
17874 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17875 file)
17876 (unless files (user-error "No agenda files"))
17877 (catch 'exit
17878 (while (setq file (pop files))
17879 (if (equal (file-truename file) tcf)
17880 (when (car files)
17881 (find-file (car files))
17882 (throw 'exit t))))
17883 (find-file (car fs)))
17884 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17886 (defun org-agenda-file-to-front (&optional to-end)
17887 "Move/add the current file to the top of the agenda file list.
17888 If the file is not present in the list, it is added to the front. If it is
17889 present, it is moved there. With optional argument TO-END, add/move to the
17890 end of the list."
17891 (interactive "P")
17892 (let ((org-agenda-skip-unavailable-files nil)
17893 (file-alist (mapcar (lambda (x)
17894 (cons (file-truename x) x))
17895 (org-agenda-files t)))
17896 (ctf (file-truename
17897 (or buffer-file-name
17898 (user-error "Please save the current buffer to a file"))))
17899 x had)
17900 (setq x (assoc ctf file-alist) had x)
17902 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17903 (if to-end
17904 (setq file-alist (append (delq x file-alist) (list x)))
17905 (setq file-alist (cons x (delq x file-alist))))
17906 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17907 (org-install-agenda-files-menu)
17908 (message "File %s to %s of agenda file list"
17909 (if had "moved" "added") (if to-end "end" "front"))))
17911 (defun org-remove-file (&optional file)
17912 "Remove current file from the list of files in variable `org-agenda-files'.
17913 These are the files which are being checked for agenda entries.
17914 Optional argument FILE means use this file instead of the current."
17915 (interactive)
17916 (let* ((org-agenda-skip-unavailable-files nil)
17917 (file (or file buffer-file-name
17918 (user-error "Current buffer does not visit a file")))
17919 (true-file (file-truename file))
17920 (afile (abbreviate-file-name file))
17921 (files (delq nil (mapcar
17922 (lambda (x)
17923 (if (equal true-file
17924 (file-truename x))
17925 nil x))
17926 (org-agenda-files t)))))
17927 (if (not (= (length files) (length (org-agenda-files t))))
17928 (progn
17929 (org-store-new-agenda-file-list files)
17930 (org-install-agenda-files-menu)
17931 (message "Removed file: %s" afile))
17932 (message "File was not in list: %s (not removed)" afile))))
17934 (defun org-file-menu-entry (file)
17935 (vector file (list 'find-file file) t))
17937 (defun org-check-agenda-file (file)
17938 "Make sure FILE exists. If not, ask user what to do."
17939 (when (not (file-exists-p file))
17940 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17941 (abbreviate-file-name file))
17942 (let ((r (downcase (read-char-exclusive))))
17943 (cond
17944 ((equal r ?r)
17945 (org-remove-file file)
17946 (throw 'nextfile t))
17947 (t (error "Abort"))))))
17949 (defun org-get-agenda-file-buffer (file)
17950 "Get a buffer visiting FILE. If the buffer needs to be created, add
17951 it to the list of buffers which might be released later."
17952 (let ((buf (org-find-base-buffer-visiting file)))
17953 (if buf
17954 buf ; just return it
17955 ;; Make a new buffer and remember it
17956 (setq buf (find-file-noselect file))
17957 (if buf (push buf org-agenda-new-buffers))
17958 buf)))
17960 (defun org-release-buffers (blist)
17961 "Release all buffers in list, asking the user for confirmation when needed.
17962 When a buffer is unmodified, it is just killed. When modified, it is saved
17963 \(if the user agrees) and then killed."
17964 (let (buf file)
17965 (while (setq buf (pop blist))
17966 (setq file (buffer-file-name buf))
17967 (when (and (buffer-modified-p buf)
17968 file
17969 (y-or-n-p (format "Save file %s? " file)))
17970 (with-current-buffer buf (save-buffer)))
17971 (kill-buffer buf))))
17973 (defun org-agenda-prepare-buffers (files)
17974 "Create buffers for all agenda files, protect archived trees and comments."
17975 (interactive)
17976 (let ((pa '(:org-archived t))
17977 (pc '(:org-comment t))
17978 (pall '(:org-archived t :org-comment t))
17979 (inhibit-read-only t)
17980 (org-inhibit-startup org-agenda-inhibit-startup)
17981 (rea (concat ":" org-archive-tag ":"))
17982 file re)
17983 (setq org-tag-alist-for-agenda nil
17984 org-tag-groups-alist-for-agenda nil)
17985 (save-excursion
17986 (save-restriction
17987 (while (setq file (pop files))
17988 (catch 'nextfile
17989 (if (bufferp file)
17990 (set-buffer file)
17991 (org-check-agenda-file file)
17992 (set-buffer (org-get-agenda-file-buffer file)))
17993 (widen)
17994 (org-set-regexps-and-options-for-tags)
17995 (goto-char (point-min))
17996 (let ((case-fold-search t))
17997 (when (search-forward "#+setupfile" nil t)
17998 ;; Don't set all regexps and options systematically as
17999 ;; this is only run for setting agenda tags from setup
18000 ;; file
18001 (org-set-regexps-and-options)))
18002 (org-refresh-category-properties)
18003 (org-refresh-properties org-effort-property 'org-effort)
18004 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
18005 (setq org-todo-keywords-for-agenda
18006 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18007 (setq org-done-keywords-for-agenda
18008 (append org-done-keywords-for-agenda org-done-keywords))
18009 (setq org-todo-keyword-alist-for-agenda
18010 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18011 (setq org-drawers-for-agenda
18012 (append org-drawers-for-agenda org-drawers))
18013 (setq org-tag-alist-for-agenda
18014 (org-uniquify
18015 (append org-tag-alist-for-agenda
18016 org-tag-alist
18017 org-tag-persistent-alist)))
18018 (if org-group-tags
18019 (setq org-tag-groups-alist-for-agenda
18020 (org-uniquify-alist
18021 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18022 (org-with-silent-modifications
18023 (save-excursion
18024 (remove-text-properties (point-min) (point-max) pall)
18025 (when org-agenda-skip-archived-trees
18026 (goto-char (point-min))
18027 (while (re-search-forward rea nil t)
18028 (if (org-at-heading-p t)
18029 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18030 (goto-char (point-min))
18031 (setq re (format org-heading-keyword-regexp-format
18032 org-comment-string))
18033 (while (re-search-forward re nil t)
18034 (add-text-properties
18035 (match-beginning 0) (org-end-of-subtree t) pc))))))))
18036 (setq org-todo-keywords-for-agenda
18037 (org-uniquify org-todo-keywords-for-agenda))
18038 (setq org-todo-keyword-alist-for-agenda
18039 (org-uniquify org-todo-keyword-alist-for-agenda))))
18042 ;;;; CDLaTeX minor mode
18044 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18045 "Keymap for the minor `org-cdlatex-mode'.")
18047 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18048 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18049 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18050 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18051 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18053 (defvar org-cdlatex-texmathp-advice-is-done nil
18054 "Flag remembering if we have applied the advice to texmathp already.")
18056 (define-minor-mode org-cdlatex-mode
18057 "Toggle the minor `org-cdlatex-mode'.
18058 This mode supports entering LaTeX environment and math in LaTeX fragments
18059 in Org-mode.
18060 \\{org-cdlatex-mode-map}"
18061 nil " OCDL" nil
18062 (when org-cdlatex-mode
18063 (require 'cdlatex)
18064 (run-hooks 'cdlatex-mode-hook)
18065 (cdlatex-compute-tables))
18066 (unless org-cdlatex-texmathp-advice-is-done
18067 (setq org-cdlatex-texmathp-advice-is-done t)
18068 (defadvice texmathp (around org-math-always-on activate)
18069 "Always return t in org-mode buffers.
18070 This is because we want to insert math symbols without dollars even outside
18071 the LaTeX math segments. If Orgmode thinks that point is actually inside
18072 an embedded LaTeX fragment, let texmathp do its job.
18073 \\[org-cdlatex-mode-map]"
18074 (interactive)
18075 (let (p)
18076 (cond
18077 ((not (derived-mode-p 'org-mode)) ad-do-it)
18078 ((eq this-command 'cdlatex-math-symbol)
18079 (setq ad-return-value t
18080 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18082 (let ((p (org-inside-LaTeX-fragment-p)))
18083 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18084 (setq ad-return-value t
18085 texmathp-why '("Org-mode embedded math" . 0))
18086 (if p ad-do-it)))))))))
18088 (defun turn-on-org-cdlatex ()
18089 "Unconditionally turn on `org-cdlatex-mode'."
18090 (org-cdlatex-mode 1))
18092 (defun org-try-cdlatex-tab ()
18093 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18094 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18095 - inside a LaTeX fragment, or
18096 - after the first word in a line, where an abbreviation expansion could
18097 insert a LaTeX environment."
18098 (when org-cdlatex-mode
18099 (cond
18100 ;; Before any word on the line: No expansion possible.
18101 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18102 ;; Just after first word on the line: Expand it. Make sure it
18103 ;; cannot happen on headlines, though.
18104 ((save-excursion
18105 (skip-chars-backward "a-zA-Z0-9*")
18106 (skip-chars-backward " \t")
18107 (and (bolp) (not (org-at-heading-p))))
18108 (cdlatex-tab) t)
18109 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18111 (defun org-cdlatex-underscore-caret (&optional arg)
18112 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18113 Revert to the normal definition outside of these fragments."
18114 (interactive "P")
18115 (if (org-inside-LaTeX-fragment-p)
18116 (call-interactively 'cdlatex-sub-superscript)
18117 (let (org-cdlatex-mode)
18118 (call-interactively (key-binding (vector last-input-event))))))
18120 (defun org-cdlatex-math-modify (&optional arg)
18121 "Execute `cdlatex-math-modify' in LaTeX fragments.
18122 Revert to the normal definition outside of these fragments."
18123 (interactive "P")
18124 (if (org-inside-LaTeX-fragment-p)
18125 (call-interactively 'cdlatex-math-modify)
18126 (let (org-cdlatex-mode)
18127 (call-interactively (key-binding (vector last-input-event))))))
18131 ;;;; LaTeX fragments
18133 (defvar org-latex-regexps
18134 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18135 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18136 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18137 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18138 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18139 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18140 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18141 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18142 "Regular expressions for matching embedded LaTeX.")
18144 (defun org-inside-LaTeX-fragment-p ()
18145 "Test if point is inside a LaTeX fragment.
18146 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18147 sequence appearing also before point.
18148 Even though the matchers for math are configurable, this function assumes
18149 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18150 delimiters are skipped when they have been removed by customization.
18151 The return value is nil, or a cons cell with the delimiter and the
18152 position of this delimiter.
18154 This function does a reasonably good job, but can locally be fooled by
18155 for example currency specifications. For example it will assume being in
18156 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18157 fragments that are properly closed, but during editing, we have to live
18158 with the uncertainty caused by missing closing delimiters. This function
18159 looks only before point, not after."
18160 (catch 'exit
18161 (let ((pos (point))
18162 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18163 (lim (progn
18164 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18165 (point)))
18166 dd-on str (start 0) m re)
18167 (goto-char pos)
18168 (when dodollar
18169 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18170 re (nth 1 (assoc "$" org-latex-regexps)))
18171 (while (string-match re str start)
18172 (cond
18173 ((= (match-end 0) (length str))
18174 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18175 ((= (match-end 0) (- (length str) 5))
18176 (throw 'exit nil))
18177 (t (setq start (match-end 0))))))
18178 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18179 (goto-char pos)
18180 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18181 (and (match-beginning 2) (throw 'exit nil))
18182 ;; count $$
18183 (while (re-search-backward "\\$\\$" lim t)
18184 (setq dd-on (not dd-on)))
18185 (goto-char pos)
18186 (if dd-on (cons "$$" m))))))
18188 (defun org-inside-latex-macro-p ()
18189 "Is point inside a LaTeX macro or its arguments?"
18190 (save-match-data
18191 (org-in-regexp
18192 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18194 (defvar org-latex-fragment-image-overlays nil
18195 "List of overlays carrying the images of latex fragments.")
18196 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18198 (defun org-remove-latex-fragment-image-overlays ()
18199 "Remove all overlays with LaTeX fragment images in current buffer."
18200 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18201 (setq org-latex-fragment-image-overlays nil))
18203 (defun org-preview-latex-fragment (&optional subtree)
18204 "Preview the LaTeX fragment at point, or all locally or globally.
18205 If the cursor is in a LaTeX fragment, create the image and overlay
18206 it over the source code. If there is no fragment at point, display
18207 all fragments in the current text, from one headline to the next. With
18208 prefix SUBTREE, display all fragments in the current subtree. With a
18209 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18210 the cursor is before the first headline,
18211 display all fragments in the buffer.
18212 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18213 (interactive "P")
18214 (unless buffer-file-name
18215 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18216 (org-remove-latex-fragment-image-overlays)
18217 (save-excursion
18218 (save-restriction
18219 (let (beg end at msg)
18220 (cond
18221 ((or (equal subtree '(16))
18222 (not (save-excursion
18223 (re-search-backward org-outline-regexp-bol nil t))))
18224 (setq beg (point-min) end (point-max)
18225 msg "Creating images for buffer...%s"))
18226 ((equal subtree '(4))
18227 (org-back-to-heading)
18228 (setq beg (point) end (org-end-of-subtree t)
18229 msg "Creating images for subtree...%s"))
18231 (if (setq at (org-inside-LaTeX-fragment-p))
18232 (goto-char (max (point-min) (- (cdr at) 2)))
18233 (org-back-to-heading))
18234 (setq beg (point) end (progn (outline-next-heading) (point))
18235 msg (if at "Creating image...%s"
18236 "Creating images for entry...%s"))))
18237 (message msg "")
18238 (narrow-to-region beg end)
18239 (goto-char beg)
18240 (org-format-latex
18241 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18242 (file-name-nondirectory
18243 buffer-file-name)))
18244 default-directory 'overlays msg at 'forbuffer
18245 org-latex-create-formula-image-program)
18246 (message msg "done. Use `C-c C-c' to remove images.")))))
18248 (defun org-format-latex (prefix &optional dir overlays msg at
18249 forbuffer processing-type)
18250 "Replace LaTeX fragments with links to an image, and produce images.
18251 Some of the options can be changed using the variable
18252 `org-format-latex-options'."
18253 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18254 (let* ((prefixnodir (file-name-nondirectory prefix))
18255 (absprefix (expand-file-name prefix dir))
18256 (todir (file-name-directory absprefix))
18257 (opt org-format-latex-options)
18258 (optnew org-format-latex-options)
18259 (matchers (plist-get opt :matchers))
18260 (re-list org-latex-regexps)
18261 (cnt 0) txt hash link beg end re e checkdir
18262 string
18263 m n block-type block linkfile movefile ov)
18264 ;; Check the different regular expressions
18265 (while (setq e (pop re-list))
18266 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18267 block (if block-type "\n\n" ""))
18268 (when (member m matchers)
18269 (goto-char (point-min))
18270 (while (re-search-forward re nil t)
18271 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18272 (or (not overlays)
18273 (not (eq (get-char-property (match-beginning n)
18274 'org-overlay-type)
18275 'org-latex-overlay))))
18276 (cond
18277 ((eq processing-type 'verbatim))
18278 ((eq processing-type 'mathjax)
18279 ;; Prepare for MathJax processing.
18280 (setq string (match-string n))
18281 (when (member m '("$" "$1"))
18282 (save-excursion
18283 (delete-region (match-beginning n) (match-end n))
18284 (goto-char (match-beginning n))
18285 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18286 ((or (eq processing-type 'dvipng)
18287 (eq processing-type 'imagemagick))
18288 ;; Process to an image.
18289 (setq txt (match-string n)
18290 beg (match-beginning n) end (match-end n)
18291 cnt (1+ cnt))
18292 (let ((face (face-at-point))
18293 (fg (plist-get opt :foreground))
18294 (bg (plist-get opt :background))
18295 ;; Ensure full list is printed.
18296 print-length print-level)
18297 (when forbuffer
18298 ;; Get the colors from the face at point.
18299 (goto-char beg)
18300 (when (eq fg 'auto)
18301 (setq fg (face-attribute face :foreground nil 'default)))
18302 (when (eq bg 'auto)
18303 (setq bg (face-attribute face :background nil 'default)))
18304 (setq optnew (copy-sequence opt))
18305 (plist-put optnew :foreground fg)
18306 (plist-put optnew :background bg))
18307 (setq hash (sha1 (prin1-to-string
18308 (list org-format-latex-header
18309 org-latex-default-packages-alist
18310 org-latex-packages-alist
18311 org-format-latex-options
18312 forbuffer txt fg bg)))
18313 linkfile (format "%s_%s.png" prefix hash)
18314 movefile (format "%s_%s.png" absprefix hash)))
18315 (setq link (concat block "[[file:" linkfile "]]" block))
18316 (if msg (message msg cnt))
18317 (goto-char beg)
18318 (unless checkdir ; Ensure the directory exists.
18319 (setq checkdir t)
18320 (or (file-directory-p todir) (make-directory todir t)))
18321 (unless (file-exists-p movefile)
18322 (org-create-formula-image
18323 txt movefile optnew forbuffer processing-type))
18324 (if overlays
18325 (progn
18326 (mapc (lambda (o)
18327 (if (eq (overlay-get o 'org-overlay-type)
18328 'org-latex-overlay)
18329 (delete-overlay o)))
18330 (overlays-in beg end))
18331 (setq ov (make-overlay beg end))
18332 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18333 (if (featurep 'xemacs)
18334 (progn
18335 (overlay-put ov 'invisible t)
18336 (overlay-put
18337 ov 'end-glyph
18338 (make-glyph (vector 'png :file movefile))))
18339 (overlay-put
18340 ov 'display
18341 (list 'image :type 'png :file movefile :ascent 'center)))
18342 (push ov org-latex-fragment-image-overlays)
18343 (goto-char end))
18344 (delete-region beg end)
18345 (insert (org-add-props link
18346 (list 'org-latex-src
18347 (replace-regexp-in-string
18348 "\"" "" txt)
18349 'org-latex-src-embed-type
18350 (if block-type 'paragraph 'character))))))
18351 ((eq processing-type 'mathml)
18352 ;; Process to MathML
18353 (unless (save-match-data (org-format-latex-mathml-available-p))
18354 (user-error "LaTeX to MathML converter not configured"))
18355 (setq txt (match-string n)
18356 beg (match-beginning n) end (match-end n)
18357 cnt (1+ cnt))
18358 (if msg (message msg cnt))
18359 (goto-char beg)
18360 (delete-region beg end)
18361 (insert (org-format-latex-as-mathml
18362 txt block-type prefix dir)))
18364 (error "Unknown conversion type %s for LaTeX fragments"
18365 processing-type)))))))))
18367 (defun org-create-math-formula (latex-frag &optional mathml-file)
18368 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18369 Use `org-latex-to-mathml-convert-command'. If the conversion is
18370 sucessful, return the portion between \"<math...> </math>\"
18371 elements otherwise return nil. When MATHML-FILE is specified,
18372 write the results in to that file. When invoked as an
18373 interactive command, prompt for LATEX-FRAG, with initial value
18374 set to the current active region and echo the results for user
18375 inspection."
18376 (interactive (list (let ((frag (when (org-region-active-p)
18377 (buffer-substring-no-properties
18378 (region-beginning) (region-end)))))
18379 (read-string "LaTeX Fragment: " frag nil frag))))
18380 (unless latex-frag (error "Invalid LaTeX fragment"))
18381 (let* ((tmp-in-file (file-relative-name
18382 (make-temp-name (expand-file-name "ltxmathml-in"))))
18383 (ignore (write-region latex-frag nil tmp-in-file))
18384 (tmp-out-file (file-relative-name
18385 (make-temp-name (expand-file-name "ltxmathml-out"))))
18386 (cmd (format-spec
18387 org-latex-to-mathml-convert-command
18388 `((?j . ,(shell-quote-argument
18389 (expand-file-name org-latex-to-mathml-jar-file)))
18390 (?I . ,(shell-quote-argument tmp-in-file))
18391 (?o . ,(shell-quote-argument tmp-out-file)))))
18392 mathml shell-command-output)
18393 (when (org-called-interactively-p 'any)
18394 (unless (org-format-latex-mathml-available-p)
18395 (user-error "LaTeX to MathML converter not configured")))
18396 (message "Running %s" cmd)
18397 (setq shell-command-output (shell-command-to-string cmd))
18398 (setq mathml
18399 (when (file-readable-p tmp-out-file)
18400 (with-current-buffer (find-file-noselect tmp-out-file t)
18401 (goto-char (point-min))
18402 (when (re-search-forward
18403 (concat
18404 (regexp-quote
18405 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18406 "\\(.\\|\n\\)*"
18407 (regexp-quote "</math>")) nil t)
18408 (prog1 (match-string 0) (kill-buffer))))))
18409 (cond
18410 (mathml
18411 (setq mathml
18412 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18413 (when mathml-file
18414 (write-region mathml nil mathml-file))
18415 (when (org-called-interactively-p 'any)
18416 (message mathml)))
18417 ((message "LaTeX to MathML conversion failed")
18418 (message shell-command-output)))
18419 (delete-file tmp-in-file)
18420 (when (file-exists-p tmp-out-file)
18421 (delete-file tmp-out-file))
18422 mathml))
18424 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18425 prefix &optional dir)
18426 "Use `org-create-math-formula' but check local cache first."
18427 (let* ((absprefix (expand-file-name prefix dir))
18428 (print-length nil) (print-level nil)
18429 (formula-id (concat
18430 "formula-"
18431 (sha1
18432 (prin1-to-string
18433 (list latex-frag
18434 org-latex-to-mathml-convert-command)))))
18435 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18436 (formula-cache-dir (file-name-directory formula-cache)))
18438 (unless (file-directory-p formula-cache-dir)
18439 (make-directory formula-cache-dir t))
18441 (unless (file-exists-p formula-cache)
18442 (org-create-math-formula latex-frag formula-cache))
18444 (if (file-exists-p formula-cache)
18445 ;; Successful conversion. Return the link to MathML file.
18446 (org-add-props
18447 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18448 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18449 'org-latex-src-embed-type (if latex-frag-type
18450 'paragraph 'character)))
18451 ;; Failed conversion. Return the LaTeX fragment verbatim
18452 latex-frag)))
18454 (defun org-create-formula-image (string tofile options buffer &optional type)
18455 "Create an image from LaTeX source using dvipng or convert.
18456 This function calls either `org-create-formula-image-with-dvipng'
18457 or `org-create-formula-image-with-imagemagick' depending on the
18458 value of `org-latex-create-formula-image-program' or on the value
18459 of the optional TYPE variable.
18461 Note: ultimately these two function should be combined as they
18462 share a good deal of logic."
18463 (org-check-external-command
18464 "latex" "needed to convert LaTeX fragments to images")
18465 (funcall
18466 (case (or type org-latex-create-formula-image-program)
18467 ('dvipng
18468 (org-check-external-command
18469 "dvipng" "needed to convert LaTeX fragments to images")
18470 #'org-create-formula-image-with-dvipng)
18471 ('imagemagick
18472 (org-check-external-command
18473 "convert" "you need to install imagemagick")
18474 #'org-create-formula-image-with-imagemagick)
18475 (t (error
18476 "Invalid value of `org-latex-create-formula-image-program'")))
18477 string tofile options buffer))
18479 (declare-function org-export--get-global-options "ox" (&optional backend))
18480 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18481 (defun org-create-formula--latex-header ()
18482 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18483 (org-latex-guess-inputenc
18484 (org-splice-latex-header
18485 org-format-latex-header
18486 org-latex-default-packages-alist
18487 org-latex-packages-alist t
18488 (plist-get
18489 (org-combine-plists
18490 (org-export--get-global-options 'latex)
18491 (org-export--get-inbuffer-options 'latex))
18492 :latex-header))))
18494 ;; This function borrows from Ganesh Swami's latex2png.el
18495 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18496 "This calls dvipng."
18497 (require 'ox-latex)
18498 (let* ((tmpdir (if (featurep 'xemacs)
18499 (temp-directory)
18500 temporary-file-directory))
18501 (texfilebase (make-temp-name
18502 (expand-file-name "orgtex" tmpdir)))
18503 (texfile (concat texfilebase ".tex"))
18504 (dvifile (concat texfilebase ".dvi"))
18505 (pngfile (concat texfilebase ".png"))
18506 (fnh (if (featurep 'xemacs)
18507 (font-height (face-font 'default))
18508 (face-attribute 'default :height nil)))
18509 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18510 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18511 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18512 "Black"))
18513 (bg (or (plist-get options (if buffer :background :html-background))
18514 "Transparent")))
18515 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18516 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18517 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18518 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18519 (let ((latex-header (org-create-formula--latex-header)))
18520 (with-temp-file texfile
18521 (insert latex-header)
18522 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18523 (let ((dir default-directory))
18524 (condition-case nil
18525 (progn
18526 (cd tmpdir)
18527 (call-process "latex" nil nil nil texfile))
18528 (error nil))
18529 (cd dir))
18530 (if (not (file-exists-p dvifile))
18531 (progn (message "Failed to create dvi file from %s" texfile) nil)
18532 (condition-case nil
18533 (if (featurep 'xemacs)
18534 (call-process "dvipng" nil nil nil
18535 "-fg" fg "-bg" bg
18536 "-T" "tight"
18537 "-o" pngfile
18538 dvifile)
18539 (call-process "dvipng" nil nil nil
18540 "-fg" fg "-bg" bg
18541 "-D" dpi
18542 ;;"-x" scale "-y" scale
18543 "-T" "tight"
18544 "-o" pngfile
18545 dvifile))
18546 (error nil))
18547 (if (not (file-exists-p pngfile))
18548 (if org-format-latex-signal-error
18549 (error "Failed to create png file from %s" texfile)
18550 (message "Failed to create png file from %s" texfile)
18551 nil)
18552 ;; Use the requested file name and clean up
18553 (copy-file pngfile tofile 'replace)
18554 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18555 (if (file-exists-p (concat texfilebase e))
18556 (delete-file (concat texfilebase e))))
18557 pngfile))))
18559 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18560 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18561 "This calls convert, which is included into imagemagick."
18562 (require 'ox-latex)
18563 (let* ((tmpdir (if (featurep 'xemacs)
18564 (temp-directory)
18565 temporary-file-directory))
18566 (texfilebase (make-temp-name
18567 (expand-file-name "orgtex" tmpdir)))
18568 (texfile (concat texfilebase ".tex"))
18569 (pdffile (concat texfilebase ".pdf"))
18570 (pngfile (concat texfilebase ".png"))
18571 (fnh (if (featurep 'xemacs)
18572 (font-height (face-font 'default))
18573 (face-attribute 'default :height nil)))
18574 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18575 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18576 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18577 "black"))
18578 (bg (or (plist-get options (if buffer :background :html-background))
18579 "white")))
18580 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18581 (setq fg (org-latex-color-format fg)))
18582 (if (eq bg 'default) (setq bg (org-latex-color :background))
18583 (setq bg (org-latex-color-format
18584 (if (string= bg "Transparent") "white" bg))))
18585 (let ((latex-header (org-create-formula--latex-header)))
18586 (with-temp-file texfile
18587 (insert latex-header)
18588 (insert "\n\\begin{document}\n"
18589 "\\definecolor{fg}{rgb}{" fg "}\n"
18590 "\\definecolor{bg}{rgb}{" bg "}\n"
18591 "\n\\pagecolor{bg}\n"
18592 "\n{\\color{fg}\n"
18593 string
18594 "\n}\n"
18595 "\n\\end{document}\n")))
18596 (org-latex-compile texfile t)
18597 (if (not (file-exists-p pdffile))
18598 (progn (message "Failed to create pdf file from %s" texfile) nil)
18599 (condition-case nil
18600 (if (featurep 'xemacs)
18601 (call-process "convert" nil nil nil
18602 "-density" "96"
18603 "-trim"
18604 "-antialias"
18605 pdffile
18606 "-quality" "100"
18607 ;; "-sharpen" "0x1.0"
18608 pngfile)
18609 (call-process "convert" nil nil nil
18610 "-density" dpi
18611 "-trim"
18612 "-antialias"
18613 pdffile
18614 "-quality" "100"
18615 ;; "-sharpen" "0x1.0"
18616 pngfile))
18617 (error nil))
18618 (if (not (file-exists-p pngfile))
18619 (if org-format-latex-signal-error
18620 (error "Failed to create png file from %s" texfile)
18621 (message "Failed to create png file from %s" texfile)
18622 nil)
18623 ;; Use the requested file name and clean up
18624 (copy-file pngfile tofile 'replace)
18625 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18626 (if (file-exists-p (concat texfilebase e))
18627 (delete-file (concat texfilebase e))))
18628 pngfile))))
18630 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18631 "Fill a LaTeX header template TPL.
18632 In the template, the following place holders will be recognized:
18634 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18635 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18636 [PACKAGES] \\usepackage statements for PKG
18637 [NO-PACKAGES] do not include PKG
18638 [EXTRA] the string EXTRA
18639 [NO-EXTRA] do not include EXTRA
18641 For backward compatibility, if both the positive and the negative place
18642 holder is missing, the positive one (without the \"NO-\") will be
18643 assumed to be present at the end of the template.
18644 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18645 EXTRA is a string.
18646 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18647 (let (rpl (end ""))
18648 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18649 (setq rpl (if (or (match-end 1) (not def-pkg))
18650 "" (org-latex-packages-to-string def-pkg snippets-p t))
18651 tpl (replace-match rpl t t tpl))
18652 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18654 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18655 (setq rpl (if (or (match-end 1) (not pkg))
18656 "" (org-latex-packages-to-string pkg snippets-p t))
18657 tpl (replace-match rpl t t tpl))
18658 (if pkg (setq end
18659 (concat end "\n"
18660 (org-latex-packages-to-string pkg snippets-p)))))
18662 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18663 (setq rpl (if (or (match-end 1) (not extra))
18664 "" (concat extra "\n"))
18665 tpl (replace-match rpl t t tpl))
18666 (if (and extra (string-match "\\S-" extra))
18667 (setq end (concat end "\n" extra))))
18669 (if (string-match "\\S-" end)
18670 (concat tpl "\n" end)
18671 tpl)))
18673 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18674 "Turn an alist of packages into a string with the \\usepackage macros."
18675 (setq pkg (mapconcat (lambda(p)
18676 (cond
18677 ((stringp p) p)
18678 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18679 (format "%% Package %s omitted" (cadr p)))
18680 ((equal "" (car p))
18681 (format "\\usepackage{%s}" (cadr p)))
18683 (format "\\usepackage[%s]{%s}"
18684 (car p) (cadr p)))))
18686 "\n"))
18687 (if newline (concat pkg "\n") pkg))
18689 (defun org-dvipng-color (attr)
18690 "Return a RGB color specification for dvipng."
18691 (apply 'format "rgb %s %s %s"
18692 (mapcar 'org-normalize-color
18693 (if (featurep 'xemacs)
18694 (color-rgb-components
18695 (face-property 'default
18696 (cond ((eq attr :foreground) 'foreground)
18697 ((eq attr :background) 'background))))
18698 (color-values (face-attribute 'default attr nil))))))
18700 (defun org-dvipng-color-format (color-name)
18701 "Convert COLOR-NAME to a RGB color value for dvipng."
18702 (apply 'format "rgb %s %s %s"
18703 (mapcar 'org-normalize-color
18704 (color-values color-name))))
18706 (defun org-latex-color (attr)
18707 "Return a RGB color for the LaTeX color package."
18708 (apply 'format "%s,%s,%s"
18709 (mapcar 'org-normalize-color
18710 (if (featurep 'xemacs)
18711 (color-rgb-components
18712 (face-property 'default
18713 (cond ((eq attr :foreground) 'foreground)
18714 ((eq attr :background) 'background))))
18715 (color-values (face-attribute 'default attr nil))))))
18717 (defun org-latex-color-format (color-name)
18718 "Convert COLOR-NAME to a RGB color value."
18719 (apply 'format "%s,%s,%s"
18720 (mapcar 'org-normalize-color
18721 (color-values color-name))))
18723 (defun org-normalize-color (value)
18724 "Return string to be used as color value for an RGB component."
18725 (format "%g" (/ value 65535.0)))
18729 ;; Image display
18731 (defvar org-inline-image-overlays nil)
18732 (make-variable-buffer-local 'org-inline-image-overlays)
18734 (defun org-toggle-inline-images (&optional include-linked)
18735 "Toggle the display of inline images.
18736 INCLUDE-LINKED is passed to `org-display-inline-images'."
18737 (interactive "P")
18738 (if org-inline-image-overlays
18739 (progn
18740 (org-remove-inline-images)
18741 (message "Inline image display turned off"))
18742 (org-display-inline-images include-linked)
18743 (if (and (org-called-interactively-p)
18744 org-inline-image-overlays)
18745 (message "%d images displayed inline"
18746 (length org-inline-image-overlays))
18747 (message "No images to display inline"))))
18749 (defun org-redisplay-inline-images ()
18750 "Refresh the display of inline images."
18751 (interactive)
18752 (if (not org-inline-image-overlays)
18753 (org-toggle-inline-images)
18754 (org-toggle-inline-images)
18755 (org-toggle-inline-images)))
18757 (defun org-display-inline-images (&optional include-linked refresh beg end)
18758 "Display inline images.
18759 Normally only links without a description part are inlined, because this
18760 is how it will work for export. When INCLUDE-LINKED is set, also links
18761 with a description part will be inlined. This can be nice for a quick
18762 look at those images, but it does not reflect what exported files will look
18763 like.
18764 When REFRESH is set, refresh existing images between BEG and END.
18765 This will create new image displays only if necessary.
18766 BEG and END default to the buffer boundaries."
18767 (interactive "P")
18768 (unless refresh
18769 (org-remove-inline-images)
18770 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18771 (save-excursion
18772 (save-restriction
18773 (widen)
18774 (setq beg (or beg (point-min)) end (or end (point-max)))
18775 (goto-char beg)
18776 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18777 (substring (org-image-file-name-regexp) 0 -2)
18778 "\\)\\]" (if include-linked "" "\\]")))
18779 (case-fold-search t)
18780 old file ov img type attrwidth width)
18781 (while (re-search-forward re end t)
18782 (setq old (get-char-property-and-overlay (match-beginning 1)
18783 'org-image-overlay)
18784 file (expand-file-name
18785 (concat (or (match-string 3) "") (match-string 4))))
18786 (when (image-type-available-p 'imagemagick)
18787 (setq attrwidth (if (or (listp org-image-actual-width)
18788 (null org-image-actual-width))
18789 (save-excursion
18790 (save-match-data
18791 (when (re-search-backward
18792 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18793 (save-excursion
18794 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18795 (string-to-number (match-string 1))))))
18796 width (cond ((eq org-image-actual-width t) nil)
18797 ((null org-image-actual-width) attrwidth)
18798 ((numberp org-image-actual-width)
18799 org-image-actual-width)
18800 ((listp org-image-actual-width)
18801 (or attrwidth (car org-image-actual-width))))
18802 type (if width 'imagemagick)))
18803 (when (file-exists-p file)
18804 (if (and (car-safe old) refresh)
18805 (image-refresh (overlay-get (cdr old) 'display))
18806 (setq img (save-match-data (create-image file type nil :width width)))
18807 (when img
18808 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18809 (overlay-put ov 'display img)
18810 (overlay-put ov 'face 'default)
18811 (overlay-put ov 'org-image-overlay t)
18812 (overlay-put ov 'modification-hooks
18813 (list 'org-display-inline-remove-overlay))
18814 (push ov org-inline-image-overlays)))))))))
18816 (define-obsolete-function-alias
18817 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18819 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18820 "Remove inline-display overlay if a corresponding region is modified."
18821 (let ((inhibit-modification-hooks t))
18822 (when (and ov after)
18823 (delete ov org-inline-image-overlays)
18824 (delete-overlay ov))))
18826 (defun org-remove-inline-images ()
18827 "Remove inline display of images."
18828 (interactive)
18829 (mapc 'delete-overlay org-inline-image-overlays)
18830 (setq org-inline-image-overlays nil))
18832 ;;;; Key bindings
18834 ;; Outline functions from `outline-mode-prefix-map'
18835 ;; that can be remapped in Org:
18836 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18837 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18838 (define-key org-mode-map [remap outline-forward-same-level]
18839 'org-forward-heading-same-level)
18840 (define-key org-mode-map [remap outline-backward-same-level]
18841 'org-backward-heading-same-level)
18842 (define-key org-mode-map [remap show-branches]
18843 'org-kill-note-or-show-branches)
18844 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18845 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18846 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18848 ;; Outline functions from `outline-mode-prefix-map' that can not
18849 ;; be remapped in Org:
18851 ;; - the column "key binding" shows whether the Outline function is still
18852 ;; available in Org mode on the same key that it has been bound to in
18853 ;; Outline mode:
18854 ;; - "overridden": key used for a different functionality in Org mode
18855 ;; - else: key still bound to the same Outline function in Org mode
18857 ;; | Outline function | key binding | Org replacement |
18858 ;; |------------------------------------+-------------+-----------------------|
18859 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18860 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18861 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18862 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18863 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18864 ;; | `show-entry' | overridden | no replacement |
18865 ;; | `show-children' | `C-c C-i' | visibility cycling |
18866 ;; | `show-branches' | `C-c C-k' | still same function |
18867 ;; | `show-subtree' | overridden | visibility cycling |
18868 ;; | `show-all' | overridden | no replacement |
18869 ;; | `hide-subtree' | overridden | visibility cycling |
18870 ;; | `hide-body' | overridden | no replacement |
18871 ;; | `hide-entry' | overridden | visibility cycling |
18872 ;; | `hide-leaves' | overridden | no replacement |
18873 ;; | `hide-sublevels' | overridden | no replacement |
18874 ;; | `hide-other' | overridden | no replacement |
18876 ;; Make `C-c C-x' a prefix key
18877 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18879 ;; TAB key with modifiers
18880 (org-defkey org-mode-map "\C-i" 'org-cycle)
18881 (org-defkey org-mode-map [(tab)] 'org-cycle)
18882 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18883 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18884 ;; The following line is necessary under Suse GNU/Linux
18885 (unless (featurep 'xemacs)
18886 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18887 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18888 (define-key org-mode-map [backtab] 'org-shifttab)
18890 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18891 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18892 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18894 ;; Cursor keys with modifiers
18895 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18896 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18897 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18898 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18900 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18901 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18902 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18903 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18905 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18906 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18907 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18908 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18910 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18911 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18912 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18913 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18915 ;; Babel keys
18916 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18917 (mapc (lambda (pair)
18918 (define-key org-babel-map (car pair) (cdr pair)))
18919 org-babel-key-bindings)
18921 ;;; Extra keys for tty access.
18922 ;; We only set them when really needed because otherwise the
18923 ;; menus don't show the simple keys
18925 (when (or org-use-extra-keys
18926 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18927 (not window-system))
18928 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18929 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18930 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18931 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18932 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18933 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18934 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18935 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18936 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18937 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18938 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18939 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18940 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18941 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18942 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18943 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18944 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18945 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18946 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18947 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18948 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18949 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18950 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18951 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18952 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18953 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18954 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18955 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18957 ;; All the other keys
18959 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18960 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18961 (if (boundp 'narrow-map)
18962 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18963 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18964 (if (boundp 'narrow-map)
18965 (org-defkey narrow-map "b" 'org-narrow-to-block)
18966 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18967 (if (boundp 'narrow-map)
18968 (org-defkey narrow-map "e" 'org-narrow-to-element)
18969 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18970 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18971 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18972 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18973 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18974 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18975 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18976 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18977 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18978 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18979 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18980 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18981 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18982 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18983 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18984 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18985 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18986 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
18987 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18988 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18989 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18990 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18991 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18992 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18993 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18994 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18995 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18996 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18997 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18998 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18999 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19000 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19001 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19002 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19003 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19004 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19005 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19006 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19007 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19008 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19009 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19010 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19011 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19012 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19013 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19014 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19015 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19016 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19017 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19018 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19019 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19020 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19021 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19022 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19023 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19024 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19025 (org-defkey org-mode-map "\C-c^" 'org-sort)
19026 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19027 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19028 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19029 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19030 (org-defkey org-mode-map "\C-m" 'org-return)
19031 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19032 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19033 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19034 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19035 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19036 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19037 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19038 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19039 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19040 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19041 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19042 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19043 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19044 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19045 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19046 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19047 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19048 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19049 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19050 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19051 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19052 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19053 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19055 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19056 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19057 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19059 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19060 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19061 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19062 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19063 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19064 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19065 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19066 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19067 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19068 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19069 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19070 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19071 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19072 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19073 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19074 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19075 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19076 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19077 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19078 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19079 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19080 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19081 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19083 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19084 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19085 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19086 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19087 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19089 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19091 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19093 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19094 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19096 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19099 (when (featurep 'xemacs)
19100 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19103 (defconst org-speed-commands-default
19105 ("Outline Navigation")
19106 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19107 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19108 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19109 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19110 ("F" . org-next-block)
19111 ("B" . org-previous-block)
19112 ("u" . (org-speed-move-safe 'outline-up-heading))
19113 ("j" . org-goto)
19114 ("g" . (org-refile t))
19115 ("Outline Visibility")
19116 ("c" . org-cycle)
19117 ("C" . org-shifttab)
19118 (" " . org-display-outline-path)
19119 ("s" . org-narrow-to-subtree)
19120 ("=" . org-columns)
19121 ("Outline Structure Editing")
19122 ("U" . org-shiftmetaup)
19123 ("D" . org-shiftmetadown)
19124 ("r" . org-metaright)
19125 ("l" . org-metaleft)
19126 ("R" . org-shiftmetaright)
19127 ("L" . org-shiftmetaleft)
19128 ("i" . (progn (forward-char 1) (call-interactively
19129 'org-insert-heading-respect-content)))
19130 ("^" . org-sort)
19131 ("w" . org-refile)
19132 ("a" . org-archive-subtree-default-with-confirmation)
19133 ("@" . org-mark-subtree)
19134 ("#" . org-toggle-comment)
19135 ("Clock Commands")
19136 ("I" . org-clock-in)
19137 ("O" . org-clock-out)
19138 ("Meta Data Editing")
19139 ("t" . org-todo)
19140 ("," . (org-priority))
19141 ("0" . (org-priority ?\ ))
19142 ("1" . (org-priority ?A))
19143 ("2" . (org-priority ?B))
19144 ("3" . (org-priority ?C))
19145 (":" . org-set-tags-command)
19146 ("e" . org-set-effort)
19147 ("E" . org-inc-effort)
19148 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19149 (org-entry-put (point) "APPT_WARNTIME" m)))
19150 ("Agenda Views etc")
19151 ("v" . org-agenda)
19152 ("/" . org-sparse-tree)
19153 ("Misc")
19154 ("o" . org-open-at-point)
19155 ("?" . org-speed-command-help)
19156 ("<" . (org-agenda-set-restriction-lock 'subtree))
19157 (">" . (org-agenda-remove-restriction-lock))
19159 "The default speed commands.")
19161 (defun org-print-speed-command (e)
19162 (if (> (length (car e)) 1)
19163 (progn
19164 (princ "\n")
19165 (princ (car e))
19166 (princ "\n")
19167 (princ (make-string (length (car e)) ?-))
19168 (princ "\n"))
19169 (princ (car e))
19170 (princ " ")
19171 (if (symbolp (cdr e))
19172 (princ (symbol-name (cdr e)))
19173 (prin1 (cdr e)))
19174 (princ "\n")))
19176 (defun org-speed-command-help ()
19177 "Show the available speed commands."
19178 (interactive)
19179 (if (not org-use-speed-commands)
19180 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19181 (with-output-to-temp-buffer "*Help*"
19182 (princ "User-defined Speed commands\n===========================\n")
19183 (mapc 'org-print-speed-command org-speed-commands-user)
19184 (princ "\n")
19185 (princ "Built-in Speed commands\n=======================\n")
19186 (mapc 'org-print-speed-command org-speed-commands-default))
19187 (with-current-buffer "*Help*"
19188 (setq truncate-lines t))))
19190 (defun org-speed-move-safe (cmd)
19191 "Execute CMD, but make sure that the cursor always ends up in a headline.
19192 If not, return to the original position and throw an error."
19193 (interactive)
19194 (let ((pos (point)))
19195 (call-interactively cmd)
19196 (unless (and (bolp) (org-at-heading-p))
19197 (goto-char pos)
19198 (error "Boundary reached while executing %s" cmd))))
19200 (defvar org-self-insert-command-undo-counter 0)
19202 (defvar org-table-auto-blank-field) ; defined in org-table.el
19203 (defvar org-speed-command nil)
19205 (define-obsolete-function-alias
19206 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19208 (defun org-speed-command-activate (keys)
19209 "Hook for activating single-letter speed commands.
19210 `org-speed-commands-default' specifies a minimal command set.
19211 Use `org-speed-commands-user' for further customization."
19212 (when (or (and (bolp) (looking-at org-outline-regexp))
19213 (and (functionp org-use-speed-commands)
19214 (funcall org-use-speed-commands)))
19215 (cdr (assoc keys (append org-speed-commands-user
19216 org-speed-commands-default)))))
19218 (define-obsolete-function-alias
19219 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19221 (defun org-babel-speed-command-activate (keys)
19222 "Hook for activating single-letter code block commands."
19223 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19224 (cdr (assoc keys org-babel-key-bindings))))
19226 (defcustom org-speed-command-hook
19227 '(org-speed-command-default-hook org-babel-speed-command-hook)
19228 "Hook for activating speed commands at strategic locations.
19229 Hook functions are called in sequence until a valid handler is
19230 found.
19232 Each hook takes a single argument, a user-pressed command key
19233 which is also a `self-insert-command' from the global map.
19235 Within the hook, examine the cursor position and the command key
19236 and return nil or a valid handler as appropriate. Handler could
19237 be one of an interactive command, a function, or a form.
19239 Set `org-use-speed-commands' to non-nil value to enable this
19240 hook. The default setting is `org-speed-command-activate'."
19241 :group 'org-structure
19242 :version "24.1"
19243 :type 'hook)
19245 (defun org-self-insert-command (N)
19246 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19247 If the cursor is in a table looking at whitespace, the whitespace is
19248 overwritten, and the table is not marked as requiring realignment."
19249 (interactive "p")
19250 (org-check-before-invisible-edit 'insert)
19251 (cond
19252 ((and org-use-speed-commands
19253 (setq org-speed-command
19254 (run-hook-with-args-until-success
19255 'org-speed-command-hook (this-command-keys))))
19256 (cond
19257 ((commandp org-speed-command)
19258 (setq this-command org-speed-command)
19259 (call-interactively org-speed-command))
19260 ((functionp org-speed-command)
19261 (funcall org-speed-command))
19262 ((and org-speed-command (listp org-speed-command))
19263 (eval org-speed-command))
19264 (t (let (org-use-speed-commands)
19265 (call-interactively 'org-self-insert-command)))))
19266 ((and
19267 (org-table-p)
19268 (progn
19269 ;; check if we blank the field, and if that triggers align
19270 (and (featurep 'org-table) org-table-auto-blank-field
19271 (member last-command
19272 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19273 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19274 ;; got extra space, this field does not determine column width
19275 (let (org-table-may-need-update) (org-table-blank-field))
19276 ;; no extra space, this field may determine column width
19277 (org-table-blank-field)))
19279 (eq N 1)
19280 (looking-at "[^|\n]* |"))
19281 (let (org-table-may-need-update)
19282 (goto-char (1- (match-end 0)))
19283 (backward-delete-char 1)
19284 (goto-char (match-beginning 0))
19285 (self-insert-command N)))
19287 (setq org-table-may-need-update t)
19288 (self-insert-command N)
19289 (org-fix-tags-on-the-fly)
19290 (if org-self-insert-cluster-for-undo
19291 (if (not (eq last-command 'org-self-insert-command))
19292 (setq org-self-insert-command-undo-counter 1)
19293 (if (>= org-self-insert-command-undo-counter 20)
19294 (setq org-self-insert-command-undo-counter 1)
19295 (and (> org-self-insert-command-undo-counter 0)
19296 buffer-undo-list (listp buffer-undo-list)
19297 (not (cadr buffer-undo-list)) ; remove nil entry
19298 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19299 (setq org-self-insert-command-undo-counter
19300 (1+ org-self-insert-command-undo-counter))))))))
19302 (defun org-check-before-invisible-edit (kind)
19303 "Check is editing if kind KIND would be dangerous with invisible text around.
19304 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19305 ;; First, try to get out of here as quickly as possible, to reduce overhead
19306 (if (and org-catch-invisible-edits
19307 (or (not (boundp 'visible-mode)) (not visible-mode))
19308 (or (get-char-property (point) 'invisible)
19309 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19310 ;; OK, we need to take a closer look
19311 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19312 (invisible-before-point (if (bobp) nil (get-char-property
19313 (1- (point)) 'invisible)))
19314 (border-and-ok-direction
19316 ;; Check if we are acting predictably before invisible text
19317 (and invisible-at-point (not invisible-before-point)
19318 (memq kind '(insert delete-backward)))
19319 ;; Check if we are acting predictably after invisible text
19320 ;; This works not well, and I have turned it off. It seems
19321 ;; better to always show and stop after invisible text.
19322 ;; (and (not invisible-at-point) invisible-before-point
19323 ;; (memq kind '(insert delete)))
19325 (when (or (memq invisible-at-point '(outline org-hide-block t))
19326 (memq invisible-before-point '(outline org-hide-block t)))
19327 (if (eq org-catch-invisible-edits 'error)
19328 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19329 (if (and org-custom-properties-overlays
19330 (y-or-n-p "Display invisible properties in this buffer? "))
19331 (org-toggle-custom-properties-visibility)
19332 ;; Make the area visible
19333 (save-excursion
19334 (if invisible-before-point
19335 (goto-char (previous-single-char-property-change
19336 (point) 'invisible)))
19337 (org-cycle))
19338 (cond
19339 ((eq org-catch-invisible-edits 'show)
19340 ;; That's it, we do the edit after showing
19341 (message
19342 "Unfolding invisible region around point before editing")
19343 (sit-for 1))
19344 ((and (eq org-catch-invisible-edits 'smart)
19345 border-and-ok-direction)
19346 (message "Unfolding invisible region around point before editing"))
19348 ;; Don't do the edit, make the user repeat it in full visibility
19349 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19351 (defun org-fix-tags-on-the-fly ()
19352 (when (and (equal (char-after (point-at-bol)) ?*)
19353 (org-at-heading-p))
19354 (org-align-tags-here org-tags-column)))
19356 (defun org-delete-backward-char (N)
19357 "Like `delete-backward-char', insert whitespace at field end in tables.
19358 When deleting backwards, in tables this function will insert whitespace in
19359 front of the next \"|\" separator, to keep the table aligned. The table will
19360 still be marked for re-alignment if the field did fill the entire column,
19361 because, in this case the deletion might narrow the column."
19362 (interactive "p")
19363 (save-match-data
19364 (org-check-before-invisible-edit 'delete-backward)
19365 (if (and (org-table-p)
19366 (eq N 1)
19367 (string-match "|" (buffer-substring (point-at-bol) (point)))
19368 (looking-at ".*?|"))
19369 (let ((pos (point))
19370 (noalign (looking-at "[^|\n\r]* |"))
19371 (c org-table-may-need-update))
19372 (backward-delete-char N)
19373 (if (not overwrite-mode)
19374 (progn
19375 (skip-chars-forward "^|")
19376 (insert " ")
19377 (goto-char (1- pos))))
19378 ;; noalign: if there were two spaces at the end, this field
19379 ;; does not determine the width of the column.
19380 (if noalign (setq org-table-may-need-update c)))
19381 (backward-delete-char N)
19382 (org-fix-tags-on-the-fly))))
19384 (defun org-delete-char (N)
19385 "Like `delete-char', but insert whitespace at field end in tables.
19386 When deleting characters, in tables this function will insert whitespace in
19387 front of the next \"|\" separator, to keep the table aligned. The table will
19388 still be marked for re-alignment if the field did fill the entire column,
19389 because, in this case the deletion might narrow the column."
19390 (interactive "p")
19391 (save-match-data
19392 (org-check-before-invisible-edit 'delete)
19393 (if (and (org-table-p)
19394 (not (bolp))
19395 (not (= (char-after) ?|))
19396 (eq N 1))
19397 (if (looking-at ".*?|")
19398 (let ((pos (point))
19399 (noalign (looking-at "[^|\n\r]* |"))
19400 (c org-table-may-need-update))
19401 (replace-match
19402 (concat (substring (match-string 0) 1 -1) " |") nil t)
19403 (goto-char pos)
19404 ;; noalign: if there were two spaces at the end, this field
19405 ;; does not determine the width of the column.
19406 (if noalign (setq org-table-may-need-update c)))
19407 (delete-char N))
19408 (delete-char N)
19409 (org-fix-tags-on-the-fly))))
19411 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19412 (put 'org-self-insert-command 'delete-selection t)
19413 (put 'orgtbl-self-insert-command 'delete-selection t)
19414 (put 'org-delete-char 'delete-selection 'supersede)
19415 (put 'org-delete-backward-char 'delete-selection 'supersede)
19416 (put 'org-yank 'delete-selection 'yank)
19418 ;; Make `flyspell-mode' delay after some commands
19419 (put 'org-self-insert-command 'flyspell-delayed t)
19420 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19421 (put 'org-delete-char 'flyspell-delayed t)
19422 (put 'org-delete-backward-char 'flyspell-delayed t)
19424 ;; Make pabbrev-mode expand after org-mode commands
19425 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19426 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19428 ;; How to do this: Measure non-white length of current string
19429 ;; If equal to column width, we should realign.
19431 (defun org-remap (map &rest commands)
19432 "In MAP, remap the functions given in COMMANDS.
19433 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19434 (let (new old)
19435 (while commands
19436 (setq old (pop commands) new (pop commands))
19437 (if (fboundp 'command-remapping)
19438 (org-defkey map (vector 'remap old) new)
19439 (substitute-key-definition old new map global-map)))))
19441 (defun org-transpose-words ()
19442 "Transpose words for Org.
19443 This uses the `org-mode-transpose-word-syntax-table' syntax
19444 table, which interprets characters in `org-emphasis-alist' as
19445 word constituants."
19446 (interactive)
19447 (with-syntax-table org-mode-transpose-word-syntax-table
19448 (call-interactively 'transpose-words)))
19449 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19451 (when (eq org-enable-table-editor 'optimized)
19452 ;; If the user wants maximum table support, we need to hijack
19453 ;; some standard editing functions
19454 (org-remap org-mode-map
19455 'self-insert-command 'org-self-insert-command
19456 'delete-char 'org-delete-char
19457 'delete-backward-char 'org-delete-backward-char)
19458 (org-defkey org-mode-map "|" 'org-force-self-insert))
19460 (defvar org-ctrl-c-ctrl-c-hook nil
19461 "Hook for functions attaching themselves to `C-c C-c'.
19463 This can be used to add additional functionality to the C-c C-c
19464 key which executes context-dependent commands. This hook is run
19465 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19466 run after the last test.
19468 Each function will be called with no arguments. The function
19469 must check if the context is appropriate for it to act. If yes,
19470 it should do its thing and then return a non-nil value. If the
19471 context is wrong, just do nothing and return nil.")
19473 (defvar org-ctrl-c-ctrl-c-final-hook nil
19474 "Hook for functions attaching themselves to `C-c C-c'.
19476 This can be used to add additional functionality to the C-c C-c
19477 key which executes context-dependent commands. This hook is run
19478 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19479 before the first test.
19481 Each function will be called with no arguments. The function
19482 must check if the context is appropriate for it to act. If yes,
19483 it should do its thing and then return a non-nil value. If the
19484 context is wrong, just do nothing and return nil.")
19486 (defvar org-tab-first-hook nil
19487 "Hook for functions to attach themselves to TAB.
19488 See `org-ctrl-c-ctrl-c-hook' for more information.
19489 This hook runs as the first action when TAB is pressed, even before
19490 `org-cycle' messes around with the `outline-regexp' to cater for
19491 inline tasks and plain list item folding.
19492 If any function in this hook returns t, any other actions that
19493 would have been caused by TAB (such as table field motion or visibility
19494 cycling) will not occur.")
19496 (defvar org-tab-after-check-for-table-hook nil
19497 "Hook for functions to attach themselves to TAB.
19498 See `org-ctrl-c-ctrl-c-hook' for more information.
19499 This hook runs after it has been established that the cursor is not in a
19500 table, but before checking if the cursor is in a headline or if global cycling
19501 should be done.
19502 If any function in this hook returns t, not other actions like visibility
19503 cycling will be done.")
19505 (defvar org-tab-after-check-for-cycling-hook nil
19506 "Hook for functions to attach themselves to TAB.
19507 See `org-ctrl-c-ctrl-c-hook' for more information.
19508 This hook runs after it has been established that not table field motion and
19509 not visibility should be done because of current context. This is probably
19510 the place where a package like yasnippets can hook in.")
19512 (defvar org-tab-before-tab-emulation-hook nil
19513 "Hook for functions to attach themselves to TAB.
19514 See `org-ctrl-c-ctrl-c-hook' for more information.
19515 This hook runs after every other options for TAB have been exhausted, but
19516 before indentation and \t insertion takes place.")
19518 (defvar org-metaleft-hook nil
19519 "Hook for functions attaching themselves to `M-left'.
19520 See `org-ctrl-c-ctrl-c-hook' for more information.")
19521 (defvar org-metaright-hook nil
19522 "Hook for functions attaching themselves to `M-right'.
19523 See `org-ctrl-c-ctrl-c-hook' for more information.")
19524 (defvar org-metaup-hook nil
19525 "Hook for functions attaching themselves to `M-up'.
19526 See `org-ctrl-c-ctrl-c-hook' for more information.")
19527 (defvar org-metadown-hook nil
19528 "Hook for functions attaching themselves to `M-down'.
19529 See `org-ctrl-c-ctrl-c-hook' for more information.")
19530 (defvar org-shiftmetaleft-hook nil
19531 "Hook for functions attaching themselves to `M-S-left'.
19532 See `org-ctrl-c-ctrl-c-hook' for more information.")
19533 (defvar org-shiftmetaright-hook nil
19534 "Hook for functions attaching themselves to `M-S-right'.
19535 See `org-ctrl-c-ctrl-c-hook' for more information.")
19536 (defvar org-shiftmetaup-hook nil
19537 "Hook for functions attaching themselves to `M-S-up'.
19538 See `org-ctrl-c-ctrl-c-hook' for more information.")
19539 (defvar org-shiftmetadown-hook nil
19540 "Hook for functions attaching themselves to `M-S-down'.
19541 See `org-ctrl-c-ctrl-c-hook' for more information.")
19542 (defvar org-metareturn-hook nil
19543 "Hook for functions attaching themselves to `M-RET'.
19544 See `org-ctrl-c-ctrl-c-hook' for more information.")
19545 (defvar org-shiftup-hook nil
19546 "Hook for functions attaching themselves to `S-up'.
19547 See `org-ctrl-c-ctrl-c-hook' for more information.")
19548 (defvar org-shiftup-final-hook nil
19549 "Hook for functions attaching themselves to `S-up'.
19550 This one runs after all other options except shift-select have been excluded.
19551 See `org-ctrl-c-ctrl-c-hook' for more information.")
19552 (defvar org-shiftdown-hook nil
19553 "Hook for functions attaching themselves to `S-down'.
19554 See `org-ctrl-c-ctrl-c-hook' for more information.")
19555 (defvar org-shiftdown-final-hook nil
19556 "Hook for functions attaching themselves to `S-down'.
19557 This one runs after all other options except shift-select have been excluded.
19558 See `org-ctrl-c-ctrl-c-hook' for more information.")
19559 (defvar org-shiftleft-hook nil
19560 "Hook for functions attaching themselves to `S-left'.
19561 See `org-ctrl-c-ctrl-c-hook' for more information.")
19562 (defvar org-shiftleft-final-hook nil
19563 "Hook for functions attaching themselves to `S-left'.
19564 This one runs after all other options except shift-select have been excluded.
19565 See `org-ctrl-c-ctrl-c-hook' for more information.")
19566 (defvar org-shiftright-hook nil
19567 "Hook for functions attaching themselves to `S-right'.
19568 See `org-ctrl-c-ctrl-c-hook' for more information.")
19569 (defvar org-shiftright-final-hook nil
19570 "Hook for functions attaching themselves to `S-right'.
19571 This one runs after all other options except shift-select have been excluded.
19572 See `org-ctrl-c-ctrl-c-hook' for more information.")
19574 (defun org-modifier-cursor-error ()
19575 "Throw an error, a modified cursor command was applied in wrong context."
19576 (user-error "This command is active in special context like tables, headlines or items"))
19578 (defun org-shiftselect-error ()
19579 "Throw an error because Shift-Cursor command was applied in wrong context."
19580 (if (and (boundp 'shift-select-mode) shift-select-mode)
19581 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19582 (user-error "This command works only in special context like headlines or timestamps")))
19584 (defun org-call-for-shift-select (cmd)
19585 (let ((this-command-keys-shift-translated t))
19586 (call-interactively cmd)))
19588 (defun org-shifttab (&optional arg)
19589 "Global visibility cycling or move to previous table field.
19590 Call `org-table-previous-field' within a table.
19591 When ARG is nil, cycle globally through visibility states.
19592 When ARG is a numeric prefix, show contents of this level."
19593 (interactive "P")
19594 (cond
19595 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19596 ((integerp arg)
19597 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19598 (message "Content view to level: %d" arg)
19599 (org-content (prefix-numeric-value arg2))
19600 (org-cycle-show-empty-lines t)
19601 (setq org-cycle-global-status 'overview)))
19602 (t (call-interactively 'org-global-cycle))))
19604 (defun org-shiftmetaleft ()
19605 "Promote subtree or delete table column.
19606 Calls `org-promote-subtree', `org-outdent-item-tree', or
19607 `org-table-delete-column', depending on context. See the
19608 individual commands for more information."
19609 (interactive)
19610 (cond
19611 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19612 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19613 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19614 ((if (not (org-region-active-p)) (org-at-item-p)
19615 (save-excursion (goto-char (region-beginning))
19616 (org-at-item-p)))
19617 (call-interactively 'org-outdent-item-tree))
19618 (t (org-modifier-cursor-error))))
19620 (defun org-shiftmetaright ()
19621 "Demote subtree or insert table column.
19622 Calls `org-demote-subtree', `org-indent-item-tree', or
19623 `org-table-insert-column', depending on context. See the
19624 individual commands for more information."
19625 (interactive)
19626 (cond
19627 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19628 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19629 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19630 ((if (not (org-region-active-p)) (org-at-item-p)
19631 (save-excursion (goto-char (region-beginning))
19632 (org-at-item-p)))
19633 (call-interactively 'org-indent-item-tree))
19634 (t (org-modifier-cursor-error))))
19636 (defun org-shiftmetaup (&optional arg)
19637 "Move subtree up or kill table row.
19638 Calls `org-move-subtree-up' or `org-table-kill-row' or
19639 `org-move-item-up' or `org-timestamp-up', depending on context.
19640 See the individual commands for more information."
19641 (interactive "P")
19642 (cond
19643 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19644 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19645 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19646 ((org-at-item-p) (call-interactively 'org-move-item-up))
19647 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19648 (call-interactively 'org-timestamp-up)))
19649 (t (call-interactively 'org-drag-line-backward))))
19651 (defun org-shiftmetadown (&optional arg)
19652 "Move subtree down or insert table row.
19653 Calls `org-move-subtree-down' or `org-table-insert-row' or
19654 `org-move-item-down' or `org-timestamp-up', depending on context.
19655 See the individual commands for more information."
19656 (interactive "P")
19657 (cond
19658 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19659 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19660 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19661 ((org-at-item-p) (call-interactively 'org-move-item-down))
19662 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19663 (call-interactively 'org-timestamp-down)))
19664 (t (call-interactively 'org-drag-line-forward))))
19666 (defsubst org-hidden-tree-error ()
19667 (user-error
19668 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19670 (defun org-metaleft (&optional arg)
19671 "Promote heading or move table column to left.
19672 Calls `org-do-promote' or `org-table-move-column', depending on context.
19673 With no specific context, calls the Emacs default `backward-word'.
19674 See the individual commands for more information."
19675 (interactive "P")
19676 (cond
19677 ((run-hook-with-args-until-success 'org-metaleft-hook))
19678 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19679 ((org-with-limited-levels
19680 (or (org-at-heading-p)
19681 (and (org-region-active-p)
19682 (save-excursion
19683 (goto-char (region-beginning))
19684 (org-at-heading-p)))))
19685 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19686 (call-interactively 'org-do-promote))
19687 ;; At an inline task.
19688 ((org-at-heading-p)
19689 (call-interactively 'org-inlinetask-promote))
19690 ((or (org-at-item-p)
19691 (and (org-region-active-p)
19692 (save-excursion
19693 (goto-char (region-beginning))
19694 (org-at-item-p))))
19695 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19696 (call-interactively 'org-outdent-item))
19697 (t (call-interactively 'backward-word))))
19699 (defun org-metaright (&optional arg)
19700 "Demote a subtree, a list item or move table column to right.
19701 In front of a drawer or a block keyword, indent it correctly.
19702 With no specific context, calls the Emacs default `forward-word'.
19703 See the individual commands for more information."
19704 (interactive "P")
19705 (cond
19706 ((run-hook-with-args-until-success 'org-metaright-hook))
19707 ((org-at-table-p) (call-interactively 'org-table-move-column))
19708 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19709 ((org-at-block-p) (call-interactively 'org-indent-block))
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-demote))
19718 ;; At an inline task.
19719 ((org-at-heading-p)
19720 (call-interactively 'org-inlinetask-demote))
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-indent-item))
19728 (t (call-interactively 'forward-word))))
19730 (defun org-check-for-hidden (what)
19731 "Check if there are hidden headlines/items in the current visual line.
19732 WHAT can be either `headlines' or `items'. If the current line is
19733 an outline or item heading and it has a folded subtree below it,
19734 this function returns t, nil otherwise."
19735 (let ((re (cond
19736 ((eq what 'headlines) org-outline-regexp-bol)
19737 ((eq what 'items) (org-item-beginning-re))
19738 (t (error "This should not happen"))))
19739 beg end)
19740 (save-excursion
19741 (catch 'exit
19742 (unless (org-region-active-p)
19743 (setq beg (point-at-bol))
19744 (beginning-of-line 2)
19745 (while (and (not (eobp)) ;; this is like `next-line'
19746 (get-char-property (1- (point)) 'invisible))
19747 (beginning-of-line 2))
19748 (setq end (point))
19749 (goto-char beg)
19750 (goto-char (point-at-eol))
19751 (setq end (max end (point)))
19752 (while (re-search-forward re end t)
19753 (if (get-char-property (match-beginning 0) 'invisible)
19754 (throw 'exit t))))
19755 nil))))
19757 (defun org-metaup (&optional arg)
19758 "Move subtree up or move table row up.
19759 Calls `org-move-subtree-up' or `org-table-move-row' or
19760 `org-move-item-up', depending on context. See the individual commands
19761 for more information."
19762 (interactive "P")
19763 (cond
19764 ((run-hook-with-args-until-success 'org-metaup-hook))
19765 ((org-region-active-p)
19766 (let* ((a (min (region-beginning) (region-end)))
19767 (b (1- (max (region-beginning) (region-end))))
19768 (c (save-excursion (goto-char a)
19769 (move-beginning-of-line 0)))
19770 (d (save-excursion (goto-char a)
19771 (move-end-of-line 0) (point))))
19772 (transpose-regions a b c d)
19773 (goto-char c)))
19774 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19775 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19776 ((org-at-item-p) (call-interactively 'org-move-item-up))
19777 (t (org-drag-element-backward))))
19779 (defun org-metadown (&optional arg)
19780 "Move subtree down or move table row down.
19781 Calls `org-move-subtree-down' or `org-table-move-row' or
19782 `org-move-item-down', depending on context. See the individual
19783 commands for more information."
19784 (interactive "P")
19785 (cond
19786 ((run-hook-with-args-until-success 'org-metadown-hook))
19787 ((org-region-active-p)
19788 (let* ((a (min (region-beginning) (region-end)))
19789 (b (max (region-beginning) (region-end)))
19790 (c (save-excursion (goto-char b)
19791 (move-beginning-of-line 1)))
19792 (d (save-excursion (goto-char b)
19793 (move-end-of-line 1) (1+ (point)))))
19794 (transpose-regions a b c d)
19795 (goto-char d)))
19796 ((org-at-table-p) (call-interactively 'org-table-move-row))
19797 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19798 ((org-at-item-p) (call-interactively 'org-move-item-down))
19799 (t (org-drag-element-forward))))
19801 (defun org-shiftup (&optional arg)
19802 "Increase item in timestamp or increase priority of current headline.
19803 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19804 depending on context. See the individual commands for more information."
19805 (interactive "P")
19806 (cond
19807 ((run-hook-with-args-until-success 'org-shiftup-hook))
19808 ((and org-support-shift-select (org-region-active-p))
19809 (org-call-for-shift-select 'previous-line))
19810 ((org-at-timestamp-p t)
19811 (call-interactively (if org-edit-timestamp-down-means-later
19812 'org-timestamp-down 'org-timestamp-up)))
19813 ((and (not (eq org-support-shift-select 'always))
19814 org-enable-priority-commands
19815 (org-at-heading-p))
19816 (call-interactively 'org-priority-up))
19817 ((and (not org-support-shift-select) (org-at-item-p))
19818 (call-interactively 'org-previous-item))
19819 ((org-clocktable-try-shift 'up arg))
19820 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19821 (org-support-shift-select
19822 (org-call-for-shift-select 'previous-line))
19823 (t (org-shiftselect-error))))
19825 (defun org-shiftdown (&optional arg)
19826 "Decrease item in timestamp or decrease priority of current headline.
19827 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19828 depending on context. See the individual commands for more information."
19829 (interactive "P")
19830 (cond
19831 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19832 ((and org-support-shift-select (org-region-active-p))
19833 (org-call-for-shift-select 'next-line))
19834 ((org-at-timestamp-p t)
19835 (call-interactively (if org-edit-timestamp-down-means-later
19836 'org-timestamp-up 'org-timestamp-down)))
19837 ((and (not (eq org-support-shift-select 'always))
19838 org-enable-priority-commands
19839 (org-at-heading-p))
19840 (call-interactively 'org-priority-down))
19841 ((and (not org-support-shift-select) (org-at-item-p))
19842 (call-interactively 'org-next-item))
19843 ((org-clocktable-try-shift 'down arg))
19844 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19845 (org-support-shift-select
19846 (org-call-for-shift-select 'next-line))
19847 (t (org-shiftselect-error))))
19849 (defun org-shiftright (&optional arg)
19850 "Cycle the thing at point or in the current line, depending on context.
19851 Depending on context, this does one of the following:
19853 - switch a timestamp at point one day into the future
19854 - on a headline, switch to the next TODO keyword.
19855 - on an item, switch entire list to the next bullet type
19856 - on a property line, switch to the next allowed value
19857 - on a clocktable definition line, move time block into the future"
19858 (interactive "P")
19859 (cond
19860 ((run-hook-with-args-until-success 'org-shiftright-hook))
19861 ((and org-support-shift-select (org-region-active-p))
19862 (org-call-for-shift-select 'forward-char))
19863 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19864 ((and (not (eq org-support-shift-select 'always))
19865 (org-at-heading-p))
19866 (let ((org-inhibit-logging
19867 (not org-treat-S-cursor-todo-selection-as-state-change))
19868 (org-inhibit-blocking
19869 (not org-treat-S-cursor-todo-selection-as-state-change)))
19870 (org-call-with-arg 'org-todo 'right)))
19871 ((or (and org-support-shift-select
19872 (not (eq org-support-shift-select 'always))
19873 (org-at-item-bullet-p))
19874 (and (not org-support-shift-select) (org-at-item-p)))
19875 (org-call-with-arg 'org-cycle-list-bullet nil))
19876 ((and (not (eq org-support-shift-select 'always))
19877 (org-at-property-p))
19878 (call-interactively 'org-property-next-allowed-value))
19879 ((org-clocktable-try-shift 'right arg))
19880 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19881 (org-support-shift-select
19882 (org-call-for-shift-select 'forward-char))
19883 (t (org-shiftselect-error))))
19885 (defun org-shiftleft (&optional arg)
19886 "Cycle the thing at point or in the current line, depending on context.
19887 Depending on context, this does one of the following:
19889 - switch a timestamp at point one day into the past
19890 - on a headline, switch to the previous TODO keyword.
19891 - on an item, switch entire list to the previous bullet type
19892 - on a property line, switch to the previous allowed value
19893 - on a clocktable definition line, move time block into the past"
19894 (interactive "P")
19895 (cond
19896 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19897 ((and org-support-shift-select (org-region-active-p))
19898 (org-call-for-shift-select 'backward-char))
19899 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19900 ((and (not (eq org-support-shift-select 'always))
19901 (org-at-heading-p))
19902 (let ((org-inhibit-logging
19903 (not org-treat-S-cursor-todo-selection-as-state-change))
19904 (org-inhibit-blocking
19905 (not org-treat-S-cursor-todo-selection-as-state-change)))
19906 (org-call-with-arg 'org-todo 'left)))
19907 ((or (and org-support-shift-select
19908 (not (eq org-support-shift-select 'always))
19909 (org-at-item-bullet-p))
19910 (and (not org-support-shift-select) (org-at-item-p)))
19911 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19912 ((and (not (eq org-support-shift-select 'always))
19913 (org-at-property-p))
19914 (call-interactively 'org-property-previous-allowed-value))
19915 ((org-clocktable-try-shift 'left arg))
19916 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19917 (org-support-shift-select
19918 (org-call-for-shift-select 'backward-char))
19919 (t (org-shiftselect-error))))
19921 (defun org-shiftcontrolright ()
19922 "Switch to next TODO set."
19923 (interactive)
19924 (cond
19925 ((and org-support-shift-select (org-region-active-p))
19926 (org-call-for-shift-select 'forward-word))
19927 ((and (not (eq org-support-shift-select 'always))
19928 (org-at-heading-p))
19929 (org-call-with-arg 'org-todo 'nextset))
19930 (org-support-shift-select
19931 (org-call-for-shift-select 'forward-word))
19932 (t (org-shiftselect-error))))
19934 (defun org-shiftcontrolleft ()
19935 "Switch to previous TODO set."
19936 (interactive)
19937 (cond
19938 ((and org-support-shift-select (org-region-active-p))
19939 (org-call-for-shift-select 'backward-word))
19940 ((and (not (eq org-support-shift-select 'always))
19941 (org-at-heading-p))
19942 (org-call-with-arg 'org-todo 'previousset))
19943 (org-support-shift-select
19944 (org-call-for-shift-select 'backward-word))
19945 (t (org-shiftselect-error))))
19947 (defun org-shiftcontrolup (&optional n)
19948 "Change timestamps synchronously up in CLOCK log lines.
19949 Optional argument N tells to change by that many units."
19950 (interactive "P")
19951 (cond ((and (not org-support-shift-select)
19952 (org-at-clock-log-p)
19953 (org-at-timestamp-p t))
19954 (org-clock-timestamps-up n))
19955 (t (org-shiftselect-error))))
19957 (defun org-shiftcontroldown (&optional n)
19958 "Change timestamps synchronously down in CLOCK log lines.
19959 Optional argument N tells to change by that many units."
19960 (interactive "P")
19961 (cond ((and (not org-support-shift-select)
19962 (org-at-clock-log-p)
19963 (org-at-timestamp-p t))
19964 (org-clock-timestamps-down n))
19965 (t (org-shiftselect-error))))
19967 (defun org-ctrl-c-ret ()
19968 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19969 (interactive)
19970 (cond
19971 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19972 (t (call-interactively 'org-insert-heading))))
19974 (defun org-find-visible ()
19975 (let ((s (point)))
19976 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19977 (get-char-property s 'invisible)))
19979 (defun org-find-invisible ()
19980 (let ((s (point)))
19981 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19982 (not (get-char-property s 'invisible))))
19985 (defun org-copy-visible (beg end)
19986 "Copy the visible parts of the region."
19987 (interactive "r")
19988 (let (snippets s)
19989 (save-excursion
19990 (save-restriction
19991 (narrow-to-region beg end)
19992 (setq s (goto-char (point-min)))
19993 (while (not (= (point) (point-max)))
19994 (goto-char (org-find-invisible))
19995 (push (buffer-substring s (point)) snippets)
19996 (setq s (goto-char (org-find-visible))))))
19997 (kill-new (apply 'concat (nreverse snippets)))))
19999 (defun org-copy-special ()
20000 "Copy region in table or copy current subtree.
20001 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20002 See the individual commands for more information."
20003 (interactive)
20004 (call-interactively
20005 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20007 (defun org-cut-special ()
20008 "Cut region in table or cut current subtree.
20009 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20010 See the individual commands for more information."
20011 (interactive)
20012 (call-interactively
20013 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20015 (defun org-paste-special (arg)
20016 "Paste rectangular region into table, or past subtree relative to level.
20017 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20018 See the individual commands for more information."
20019 (interactive "P")
20020 (if (org-at-table-p)
20021 (org-table-paste-rectangle)
20022 (org-paste-subtree arg)))
20024 (defsubst org-in-fixed-width-region-p ()
20025 "Is point in a fixed-width region?"
20026 (save-match-data
20027 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20029 (defun org-edit-special (&optional arg)
20030 "Call a special editor for the element at point.
20031 When at a table, call the formula editor with `org-table-edit-formulas'.
20032 When in a source code block, call `org-edit-src-code'.
20033 When in a fixed-width region, call `org-edit-fixed-width-region'.
20034 When at an #+INCLUDE keyword, visit the included file.
20035 On a link, call `ffap' to visit the link at point.
20036 Otherwise, return a user error."
20037 (interactive "P")
20038 (let ((element (org-element-at-point)))
20039 (assert (not buffer-read-only) nil
20040 "Buffer is read-only: %s" (buffer-name))
20041 (case (org-element-type element)
20042 (src-block
20043 (if (not arg) (org-edit-src-code)
20044 (let* ((info (org-babel-get-src-block-info))
20045 (lang (nth 0 info))
20046 (params (nth 2 info))
20047 (session (cdr (assq :session params))))
20048 (if (not session) (org-edit-src-code)
20049 ;; At a src-block with a session and function called with
20050 ;; an ARG: switch to the buffer related to the inferior
20051 ;; process.
20052 (switch-to-buffer
20053 (funcall (intern (concat "org-babel-prep-session:" lang))
20054 session params))))))
20055 (keyword
20056 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20057 (find-file
20058 (org-remove-double-quotes
20059 (car (org-split-string (org-element-property :value element)))))
20060 (user-error "No special environment to edit here")))
20061 (table
20062 (if (eq (org-element-property :type element) 'table.el)
20063 (org-edit-src-code)
20064 (call-interactively 'org-table-edit-formulas)))
20065 ;; Only Org tables contain `table-row' type elements.
20066 (table-row (call-interactively 'org-table-edit-formulas))
20067 ((example-block export-block) (org-edit-src-code))
20068 (fixed-width (org-edit-fixed-width-region))
20069 (otherwise
20070 ;; No notable element at point. Though, we may be at a link,
20071 ;; which is an object. Thus, scan deeper.
20072 (if (eq (org-element-type (org-element-context element)) 'link)
20073 (call-interactively 'ffap)
20074 (user-error "No special environment to edit here"))))))
20076 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20077 (defun org-ctrl-c-ctrl-c (&optional arg)
20078 "Set tags in headline, or update according to changed information at point.
20080 This command does many different things, depending on context:
20082 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20083 this is what we do.
20085 - If the cursor is on a statistics cookie, update it.
20087 - If the cursor is in a headline, prompt for tags and insert them
20088 into the current line, aligned to `org-tags-column'. When called
20089 with prefix arg, realign all tags in the current buffer.
20091 - If the cursor is in one of the special #+KEYWORD lines, this
20092 triggers scanning the buffer for these lines and updating the
20093 information.
20095 - If the cursor is inside a table, realign the table. This command
20096 works even if the automatic table editor has been turned off.
20098 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20099 the entire table.
20101 - If the cursor is at a footnote reference or definition, jump to
20102 the corresponding definition or references, respectively.
20104 - If the cursor is a the beginning of a dynamic block, update it.
20106 - If the current buffer is a capture buffer, close note and file it.
20108 - If the cursor is on a <<<target>>>, update radio targets and
20109 corresponding links in this buffer.
20111 - If the cursor is on a numbered item in a plain list, renumber the
20112 ordered list.
20114 - If the cursor is on a checkbox, toggle it.
20116 - If the cursor is on a code block, evaluate it. The variable
20117 `org-confirm-babel-evaluate' can be used to control prompting
20118 before code block evaluation, by default every code block
20119 evaluation requires confirmation. Code block evaluation can be
20120 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20121 (interactive "P")
20122 (cond
20123 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20124 org-occur-highlights
20125 org-latex-fragment-image-overlays)
20126 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20127 (org-remove-occur-highlights)
20128 (org-remove-latex-fragment-image-overlays)
20129 (message "Temporary highlights/overlays removed from current buffer"))
20130 ((and (local-variable-p 'org-finish-function (current-buffer))
20131 (fboundp org-finish-function))
20132 (funcall org-finish-function))
20133 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20135 (let* ((context (org-element-context)) (type (org-element-type context)))
20136 ;; Test if point is within a blank line.
20137 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20138 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20139 (user-error "C-c C-c can do nothing useful at this location"))
20140 ;; For convenience: at the first line of a paragraph on the
20141 ;; same line as an item, apply function on that item instead.
20142 (when (eq type 'paragraph)
20143 (let ((parent (org-element-property :parent context)))
20144 (when (and (eq (org-element-type parent) 'item)
20145 (= (point-at-bol) (org-element-property :begin parent)))
20146 (setq context parent type 'item))))
20147 ;; Act according to type of element or object at point.
20148 (case type
20149 (clock (org-clock-update-time-maybe))
20150 (dynamic-block
20151 (save-excursion
20152 (goto-char (org-element-property :post-affiliated context))
20153 (org-update-dblock)))
20154 (footnote-definition
20155 (goto-char (org-element-property :post-affiliated context))
20156 (call-interactively 'org-footnote-action))
20157 (footnote-reference (call-interactively 'org-footnote-action))
20158 ((headline inlinetask)
20159 (save-excursion (goto-char (org-element-property :begin context))
20160 (call-interactively 'org-set-tags)))
20161 (item
20162 ;; At an item: a double C-u set checkbox to "[-]"
20163 ;; unconditionally, whereas a single one will toggle its
20164 ;; presence. Without an universal argument, if the item
20165 ;; has a checkbox, toggle it. Otherwise repair the list.
20166 (let* ((box (org-element-property :checkbox context))
20167 (struct (org-element-property :structure context))
20168 (old-struct (copy-tree struct))
20169 (parents (org-list-parents-alist struct))
20170 (prevs (org-list-prevs-alist struct))
20171 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20172 (org-list-set-checkbox
20173 (org-element-property :begin context) struct
20174 (cond ((equal arg '(16)) "[-]")
20175 ((and (not box) (equal arg '(4))) "[ ]")
20176 ((or (not box) (equal arg '(4))) nil)
20177 ((eq box 'on) "[ ]")
20178 (t "[X]")))
20179 ;; Mimic `org-list-write-struct' but with grabbing
20180 ;; a return value from `org-list-struct-fix-box'.
20181 (org-list-struct-fix-ind struct parents 2)
20182 (org-list-struct-fix-item-end struct)
20183 (org-list-struct-fix-bul struct prevs)
20184 (org-list-struct-fix-ind struct parents)
20185 (let ((block-item
20186 (org-list-struct-fix-box struct parents prevs orderedp)))
20187 (if (and box (equal struct old-struct))
20188 (if (equal arg '(16))
20189 (message "Checkboxes already reset")
20190 (user-error "Cannot toggle this checkbox: %s"
20191 (if (eq box 'on)
20192 "all subitems checked"
20193 "unchecked subitems")))
20194 (org-list-struct-apply-struct struct old-struct)
20195 (org-update-checkbox-count-maybe))
20196 (when block-item
20197 (message "Checkboxes were removed due to empty box at line %d"
20198 (org-current-line block-item))))))
20199 (keyword
20200 (let ((org-inhibit-startup-visibility-stuff t)
20201 (org-startup-align-all-tables nil))
20202 (when (boundp 'org-table-coordinate-overlays)
20203 (mapc 'delete-overlay org-table-coordinate-overlays)
20204 (setq org-table-coordinate-overlays nil))
20205 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20206 (message "Local setup has been refreshed"))
20207 (plain-list
20208 ;; At a plain list, with a double C-u argument, set
20209 ;; checkboxes of each item to "[-]", whereas a single one
20210 ;; will toggle their presence according to the state of the
20211 ;; first item in the list. Without an argument, repair the
20212 ;; list.
20213 (let* ((begin (org-element-property :contents-begin context))
20214 (beginm (move-marker (make-marker) begin))
20215 (struct (org-element-property :structure context))
20216 (old-struct (copy-tree struct))
20217 (first-box (save-excursion
20218 (goto-char begin)
20219 (looking-at org-list-full-item-re)
20220 (match-string-no-properties 3)))
20221 (new-box (cond ((equal arg '(16)) "[-]")
20222 ((equal arg '(4)) (unless first-box "[ ]"))
20223 ((equal first-box "[X]") "[ ]")
20224 (t "[X]"))))
20225 (cond
20226 (arg
20227 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20228 (org-list-get-all-items
20229 begin struct (org-list-prevs-alist struct))))
20230 ((and first-box (eq (point) begin))
20231 ;; For convenience, when point is at bol on the first
20232 ;; item of the list and no argument is provided, simply
20233 ;; toggle checkbox of that item, if any.
20234 (org-list-set-checkbox begin struct new-box)))
20235 (org-list-write-struct
20236 struct (org-list-parents-alist struct) old-struct)
20237 (org-update-checkbox-count-maybe)
20238 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20239 ((property-drawer node-property)
20240 (call-interactively 'org-property-action))
20241 ((radio-target target)
20242 (call-interactively 'org-update-radio-target-regexp))
20243 (statistics-cookie
20244 (call-interactively 'org-update-statistics-cookies))
20245 ((table table-cell table-row)
20246 ;; At a table, recalculate every field and align it. Also
20247 ;; send the table if necessary. If the table has
20248 ;; a `table.el' type, just give up. At a table row or
20249 ;; cell, maybe recalculate line but always align table.
20250 (if (eq (org-element-property :type context) 'table.el)
20251 (message "Use C-c ' to edit table.el tables")
20252 (let ((org-enable-table-editor t))
20253 (if (or (eq type 'table)
20254 ;; Check if point is at a TBLFM line.
20255 (and (eq type 'table-row)
20256 (= (point) (org-element-property :end context))))
20257 (save-excursion
20258 (if (org-at-TBLFM-p)
20259 (progn (require 'org-table)
20260 (org-table-calc-current-TBLFM))
20261 (goto-char (org-element-property :contents-begin context))
20262 (org-call-with-arg 'org-table-recalculate (or arg t))
20263 (orgtbl-send-table 'maybe)))
20264 (org-table-maybe-eval-formula)
20265 (cond (arg (call-interactively 'org-table-recalculate))
20266 ((org-table-maybe-recalculate-line))
20267 (t (org-table-align)))))))
20268 (timestamp (org-timestamp-change 0 'day))
20269 (otherwise
20270 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20271 (user-error
20272 "C-c C-c can do nothing useful at this location")))))))))
20274 (defun org-mode-restart ()
20275 "Restart Org-mode, to scan again for special lines.
20276 Also updates the keyword regular expressions."
20277 (interactive)
20278 (org-mode)
20279 (message "Org-mode restarted"))
20281 (defun org-kill-note-or-show-branches ()
20282 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20283 (interactive)
20284 (if (not org-finish-function)
20285 (progn
20286 (hide-subtree)
20287 (call-interactively 'show-branches))
20288 (let ((org-note-abort t))
20289 (funcall org-finish-function))))
20291 (defun org-open-line (n)
20292 "Insert a new row in tables, call `open-line' elsewhere."
20293 (interactive "*p")
20294 (if (org-at-table-p)
20295 (org-table-insert-row)
20296 (open-line n)))
20298 (defun org-return (&optional indent)
20299 "Goto next table row or insert a newline.
20300 Calls `org-table-next-row' or `newline', depending on context.
20301 See the individual commands for more information."
20302 (interactive)
20303 (let (org-ts-what)
20304 (cond
20305 ((or (bobp) (org-in-src-block-p))
20306 (if indent (newline-and-indent) (newline)))
20307 ((org-at-table-p)
20308 (org-table-justify-field-maybe)
20309 (call-interactively 'org-table-next-row))
20310 ;; when `newline-and-indent' is called within a list, make sure
20311 ;; text moved stays inside the item.
20312 ((and (org-in-item-p) indent)
20313 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20314 (progn
20315 (save-match-data (newline))
20316 (org-indent-line-to (length (match-string 0))))
20317 (let ((ind (org-get-indentation)))
20318 (newline)
20319 (if (org-looking-back org-list-end-re)
20320 (org-indent-line)
20321 (org-indent-line-to ind)))))
20322 ((and org-return-follows-link
20323 (org-at-timestamp-p t)
20324 (not (eq org-ts-what 'after)))
20325 (org-follow-timestamp-link))
20326 ((and org-return-follows-link
20327 (let ((tprop (get-text-property (point) 'face)))
20328 (or (eq tprop 'org-link)
20329 (and (listp tprop) (memq 'org-link tprop)))))
20330 (call-interactively 'org-open-at-point))
20331 ((and (org-at-heading-p)
20332 (looking-at
20333 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20334 (org-show-entry)
20335 (end-of-line 1)
20336 (newline))
20337 (t (if indent (newline-and-indent) (newline))))))
20339 (defun org-return-indent ()
20340 "Goto next table row or insert a newline and indent.
20341 Calls `org-table-next-row' or `newline-and-indent', depending on
20342 context. See the individual commands for more information."
20343 (interactive)
20344 (org-return t))
20346 (defun org-ctrl-c-star ()
20347 "Compute table, or change heading status of lines.
20348 Calls `org-table-recalculate' or `org-toggle-heading',
20349 depending on context."
20350 (interactive)
20351 (cond
20352 ((org-at-table-p)
20353 (call-interactively 'org-table-recalculate))
20355 ;; Convert all lines in region to list items
20356 (call-interactively 'org-toggle-heading))))
20358 (defun org-ctrl-c-minus ()
20359 "Insert separator line in table or modify bullet status of line.
20360 Also turns a plain line or a region of lines into list items.
20361 Calls `org-table-insert-hline', `org-toggle-item', or
20362 `org-cycle-list-bullet', depending on context."
20363 (interactive)
20364 (cond
20365 ((org-at-table-p)
20366 (call-interactively 'org-table-insert-hline))
20367 ((org-region-active-p)
20368 (call-interactively 'org-toggle-item))
20369 ((org-in-item-p)
20370 (call-interactively 'org-cycle-list-bullet))
20372 (call-interactively 'org-toggle-item))))
20374 (defun org-toggle-item (arg)
20375 "Convert headings or normal lines to items, items to normal lines.
20376 If there is no active region, only the current line is considered.
20378 If the first non blank line in the region is a headline, convert
20379 all headlines to items, shifting text accordingly.
20381 If it is an item, convert all items to normal lines.
20383 If it is normal text, change region into a list of items.
20384 With a prefix argument ARG, change the region in a single item."
20385 (interactive "P")
20386 (let ((shift-text
20387 (function
20388 ;; Shift text in current section to IND, from point to END.
20389 ;; The function leaves point to END line.
20390 (lambda (ind end)
20391 (let ((min-i 1000) (end (copy-marker end)))
20392 ;; First determine the minimum indentation (MIN-I) of
20393 ;; the text.
20394 (save-excursion
20395 (catch 'exit
20396 (while (< (point) end)
20397 (let ((i (org-get-indentation)))
20398 (cond
20399 ;; Skip blank lines and inline tasks.
20400 ((looking-at "^[ \t]*$"))
20401 ((looking-at org-outline-regexp-bol))
20402 ;; We can't find less than 0 indentation.
20403 ((zerop i) (throw 'exit (setq min-i 0)))
20404 ((< i min-i) (setq min-i i))))
20405 (forward-line))))
20406 ;; Then indent each line so that a line indented to
20407 ;; MIN-I becomes indented to IND. Ignore blank lines
20408 ;; and inline tasks in the process.
20409 (let ((delta (- ind min-i)))
20410 (while (< (point) end)
20411 (unless (or (looking-at "^[ \t]*$")
20412 (looking-at org-outline-regexp-bol))
20413 (org-indent-line-to (+ (org-get-indentation) delta)))
20414 (forward-line)))))))
20415 (skip-blanks
20416 (function
20417 ;; Return beginning of first non-blank line, starting from
20418 ;; line at POS.
20419 (lambda (pos)
20420 (save-excursion
20421 (goto-char pos)
20422 (skip-chars-forward " \r\t\n")
20423 (point-at-bol)))))
20424 beg end)
20425 ;; Determine boundaries of changes.
20426 (if (org-region-active-p)
20427 (setq beg (funcall skip-blanks (region-beginning))
20428 end (copy-marker (region-end)))
20429 (setq beg (funcall skip-blanks (point-at-bol))
20430 end (copy-marker (point-at-eol))))
20431 ;; Depending on the starting line, choose an action on the text
20432 ;; between BEG and END.
20433 (org-with-limited-levels
20434 (save-excursion
20435 (goto-char beg)
20436 (cond
20437 ;; Case 1. Start at an item: de-itemize. Note that it only
20438 ;; happens when a region is active: `org-ctrl-c-minus'
20439 ;; would call `org-cycle-list-bullet' otherwise.
20440 ((org-at-item-p)
20441 (while (< (point) end)
20442 (when (org-at-item-p)
20443 (skip-chars-forward " \t")
20444 (delete-region (point) (match-end 0)))
20445 (forward-line)))
20446 ;; Case 2. Start at an heading: convert to items.
20447 ((org-at-heading-p)
20448 (let* ((bul (org-list-bullet-string "-"))
20449 (bul-len (length bul))
20450 ;; Indentation of the first heading. It should be
20451 ;; relative to the indentation of its parent, if any.
20452 (start-ind (save-excursion
20453 (cond
20454 ((not org-adapt-indentation) 0)
20455 ((not (outline-previous-heading)) 0)
20456 (t (length (match-string 0))))))
20457 ;; Level of first heading. Further headings will be
20458 ;; compared to it to determine hierarchy in the list.
20459 (ref-level (org-reduced-level (org-outline-level))))
20460 (while (< (point) end)
20461 (let* ((level (org-reduced-level (org-outline-level)))
20462 (delta (max 0 (- level ref-level))))
20463 ;; If current headline is less indented than the first
20464 ;; one, set it as reference, in order to preserve
20465 ;; subtrees.
20466 (when (< level ref-level) (setq ref-level level))
20467 (replace-match bul t t)
20468 (org-indent-line-to (+ start-ind (* delta bul-len)))
20469 ;; Ensure all text down to END (or SECTION-END) belongs
20470 ;; to the newly created item.
20471 (let ((section-end (save-excursion
20472 (or (outline-next-heading) (point)))))
20473 (forward-line)
20474 (funcall shift-text
20475 (+ start-ind (* (1+ delta) bul-len))
20476 (min end section-end)))))))
20477 ;; Case 3. Normal line with ARG: make the first line of region
20478 ;; an item, and shift indentation of others lines to
20479 ;; set them as item's body.
20480 (arg (let* ((bul (org-list-bullet-string "-"))
20481 (bul-len (length bul))
20482 (ref-ind (org-get-indentation)))
20483 (skip-chars-forward " \t")
20484 (insert bul)
20485 (forward-line)
20486 (while (< (point) end)
20487 ;; Ensure that lines less indented than first one
20488 ;; still get included in item body.
20489 (funcall shift-text
20490 (+ ref-ind bul-len)
20491 (min end (save-excursion (or (outline-next-heading)
20492 (point)))))
20493 (forward-line))))
20494 ;; Case 4. Normal line without ARG: turn each non-item line
20495 ;; into an item.
20497 (while (< (point) end)
20498 (unless (or (org-at-heading-p) (org-at-item-p))
20499 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20500 (replace-match
20501 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20502 (forward-line))))))))
20504 (defun org-toggle-heading (&optional nstars)
20505 "Convert headings to normal text, or items or text to headings.
20506 If there is no active region, only convert the current line.
20508 With a \\[universal-argument] prefix, convert the whole list at
20509 point into heading.
20511 In a region:
20513 - If the first non blank line is a headline, remove the stars
20514 from all headlines in the region.
20516 - If it is a normal line, turn each and every normal line (i.e.,
20517 not an heading or an item) in the region into headings. If you
20518 want to convert only the first line of this region, use one
20519 universal prefix argument.
20521 - If it is a plain list item, turn all plain list items into headings.
20523 When converting a line into a heading, the number of stars is chosen
20524 such that the lines become children of the current entry. However,
20525 when a numeric prefix argument is given, its value determines the
20526 number of stars to add."
20527 (interactive "P")
20528 (let ((skip-blanks
20529 (function
20530 ;; Return beginning of first non-blank line, starting from
20531 ;; line at POS.
20532 (lambda (pos)
20533 (save-excursion
20534 (goto-char pos)
20535 (while (org-at-comment-p) (forward-line))
20536 (skip-chars-forward " \r\t\n")
20537 (point-at-bol)))))
20538 beg end toggled)
20539 ;; Determine boundaries of changes. If a universal prefix has
20540 ;; been given, put the list in a region. If region ends at a bol,
20541 ;; do not consider the last line to be in the region.
20543 (when (and current-prefix-arg (org-at-item-p))
20544 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20545 (org-mark-element))
20547 (if (org-region-active-p)
20548 (setq beg (funcall skip-blanks (region-beginning))
20549 end (copy-marker (save-excursion
20550 (goto-char (region-end))
20551 (if (bolp) (point) (point-at-eol)))))
20552 (setq beg (funcall skip-blanks (point-at-bol))
20553 end (copy-marker (point-at-eol))))
20554 ;; Ensure inline tasks don't count as headings.
20555 (org-with-limited-levels
20556 (save-excursion
20557 (goto-char beg)
20558 (cond
20559 ;; Case 1. Started at an heading: de-star headings.
20560 ((org-at-heading-p)
20561 (while (< (point) end)
20562 (when (org-at-heading-p t)
20563 (looking-at org-outline-regexp) (replace-match "")
20564 (setq toggled t))
20565 (forward-line)))
20566 ;; Case 2. Started at an item: change items into headlines.
20567 ;; One star will be added by `org-list-to-subtree'.
20568 ((org-at-item-p)
20569 (let* ((stars (make-string
20570 ;; subtract the star that will be added again by
20571 ;; `org-list-to-subtree'
20572 (if (numberp nstars) (1- nstars)
20573 (or (org-current-level) 0))
20574 ?*))
20575 (add-stars
20576 (cond (nstars "") ; stars from prefix only
20577 ((equal stars "") "") ; before first heading
20578 (org-odd-levels-only "*") ; inside heading, odd
20579 (t "")))) ; inside heading, oddeven
20580 (while (< (point) end)
20581 (when (org-at-item-p)
20582 ;; Pay attention to cases when region ends before list.
20583 (let* ((struct (org-list-struct))
20584 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20585 (save-restriction
20586 (narrow-to-region (point) list-end)
20587 (insert
20588 (org-list-to-subtree
20589 (org-list-parse-list t)
20590 '(:istart (concat stars add-stars (funcall get-stars depth))
20591 :icount (concat stars add-stars (funcall get-stars depth)))))))
20592 (setq toggled t))
20593 (forward-line))))
20594 ;; Case 3. Started at normal text: make every line an heading,
20595 ;; skipping headlines and items.
20596 (t (let* ((stars
20597 (make-string
20598 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20599 (add-stars
20600 (cond (nstars "") ; stars from prefix only
20601 ((equal stars "") "*") ; before first heading
20602 (org-odd-levels-only "**") ; inside heading, odd
20603 (t "*"))) ; inside heading, oddeven
20604 (rpl (concat stars add-stars " "))
20605 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20606 (while (< (point) (if (equal nstars '(4)) lend end))
20607 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20608 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20609 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20610 (forward-line)))))))
20611 (unless toggled (message "Cannot toggle heading from here"))))
20613 (defun org-meta-return (&optional arg)
20614 "Insert a new heading or wrap a region in a table.
20615 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20616 See the individual commands for more information."
20617 (interactive "P")
20618 (org-check-before-invisible-edit 'insert)
20619 (cond
20620 ((run-hook-with-args-until-success 'org-metareturn-hook))
20621 ((or (org-at-drawer-p) (org-in-drawer-p) (org-at-property-p))
20622 (newline-and-indent))
20623 ((org-at-table-p)
20624 (call-interactively 'org-table-wrap-region))
20625 (t (call-interactively 'org-insert-heading))))
20627 ;;; Menu entries
20629 (defsubst org-in-subtree-not-table-p ()
20630 "Are we in a subtree and not in a table?"
20631 (and (not (org-before-first-heading-p))
20632 (not (org-at-table-p))))
20634 ;; Define the Org-mode menus
20635 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20636 '("Tbl"
20637 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20638 ["Next Field" org-cycle (org-at-table-p)]
20639 ["Previous Field" org-shifttab (org-at-table-p)]
20640 ["Next Row" org-return (org-at-table-p)]
20641 "--"
20642 ["Blank Field" org-table-blank-field (org-at-table-p)]
20643 ["Edit Field" org-table-edit-field (org-at-table-p)]
20644 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20645 "--"
20646 ("Column"
20647 ["Move Column Left" org-metaleft (org-at-table-p)]
20648 ["Move Column Right" org-metaright (org-at-table-p)]
20649 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20650 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20651 ("Row"
20652 ["Move Row Up" org-metaup (org-at-table-p)]
20653 ["Move Row Down" org-metadown (org-at-table-p)]
20654 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20655 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20656 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20657 "--"
20658 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20659 ("Rectangle"
20660 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20661 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20662 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20663 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20664 "--"
20665 ("Calculate"
20666 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20667 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20668 ["Edit Formulas" org-edit-special (org-at-table-p)]
20669 "--"
20670 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20671 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20672 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20673 "--"
20674 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20675 "--"
20676 ["Sum Column/Rectangle" org-table-sum
20677 (or (org-at-table-p) (org-region-active-p))]
20678 ["Which Column?" org-table-current-column (org-at-table-p)])
20679 ["Debug Formulas"
20680 org-table-toggle-formula-debugger
20681 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20682 ["Show Col/Row Numbers"
20683 org-table-toggle-coordinate-overlays
20684 :style toggle
20685 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20686 "--"
20687 ["Create" org-table-create (and (not (org-at-table-p))
20688 org-enable-table-editor)]
20689 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20690 ["Import from File" org-table-import (not (org-at-table-p))]
20691 ["Export to File" org-table-export (org-at-table-p)]
20692 "--"
20693 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20695 (easy-menu-define org-org-menu org-mode-map "Org menu"
20696 '("Org"
20697 ("Show/Hide"
20698 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20699 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20700 ["Sparse Tree..." org-sparse-tree t]
20701 ["Reveal Context" org-reveal t]
20702 ["Show All" show-all t]
20703 "--"
20704 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20705 "--"
20706 ["New Heading" org-insert-heading t]
20707 ("Navigate Headings"
20708 ["Up" outline-up-heading t]
20709 ["Next" outline-next-visible-heading t]
20710 ["Previous" outline-previous-visible-heading t]
20711 ["Next Same Level" outline-forward-same-level t]
20712 ["Previous Same Level" outline-backward-same-level t]
20713 "--"
20714 ["Jump" org-goto t])
20715 ("Edit Structure"
20716 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20717 "--"
20718 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20719 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20720 "--"
20721 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20722 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20723 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20724 "--"
20725 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20726 "--"
20727 ["Copy visible text" org-copy-visible t]
20728 "--"
20729 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20730 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20731 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20732 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20733 "--"
20734 ["Sort Region/Children" org-sort t]
20735 "--"
20736 ["Convert to odd levels" org-convert-to-odd-levels t]
20737 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20738 ("Editing"
20739 ["Emphasis..." org-emphasize t]
20740 ["Edit Source Example" org-edit-special t]
20741 "--"
20742 ["Footnote new/jump" org-footnote-action t]
20743 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20744 ("Archive"
20745 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20746 "--"
20747 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20748 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20749 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20751 "--"
20752 ("Hyperlinks"
20753 ["Store Link (Global)" org-store-link t]
20754 ["Find existing link to here" org-occur-link-in-agenda-files t]
20755 ["Insert Link" org-insert-link t]
20756 ["Follow Link" org-open-at-point t]
20757 "--"
20758 ["Next link" org-next-link t]
20759 ["Previous link" org-previous-link t]
20760 "--"
20761 ["Descriptive Links"
20762 org-toggle-link-display
20763 :style radio
20764 :selected org-descriptive-links
20766 ["Literal Links"
20767 org-toggle-link-display
20768 :style radio
20769 :selected (not org-descriptive-links)])
20770 "--"
20771 ("TODO Lists"
20772 ["TODO/DONE/-" org-todo t]
20773 ("Select keyword"
20774 ["Next keyword" org-shiftright (org-at-heading-p)]
20775 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20776 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20777 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20778 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20779 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20780 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20781 "--"
20782 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20783 :selected org-enforce-todo-dependencies :style toggle :active t]
20784 "Settings for tree at point"
20785 ["Do Children sequentially" org-toggle-ordered-property :style radio
20786 :selected (org-entry-get nil "ORDERED")
20787 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20788 ["Do Children parallel" org-toggle-ordered-property :style radio
20789 :selected (not (org-entry-get nil "ORDERED"))
20790 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20791 "--"
20792 ["Set Priority" org-priority t]
20793 ["Priority Up" org-shiftup t]
20794 ["Priority Down" org-shiftdown t]
20795 "--"
20796 ["Get news from all feeds" org-feed-update-all t]
20797 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20798 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20799 ("TAGS and Properties"
20800 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20801 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20802 "--"
20803 ["Set property" org-set-property (not (org-before-first-heading-p))]
20804 ["Column view of properties" org-columns t]
20805 ["Insert Column View DBlock" org-insert-columns-dblock t])
20806 ("Dates and Scheduling"
20807 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20808 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20809 ("Change Date"
20810 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20811 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20812 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20813 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20814 ["Compute Time Range" org-evaluate-time-range t]
20815 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20816 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20817 "--"
20818 ["Custom time format" org-toggle-time-stamp-overlays
20819 :style radio :selected org-display-custom-times]
20820 "--"
20821 ["Goto Calendar" org-goto-calendar t]
20822 ["Date from Calendar" org-date-from-calendar t]
20823 "--"
20824 ["Start/Restart Timer" org-timer-start t]
20825 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20826 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20827 ["Insert Timer String" org-timer t]
20828 ["Insert Timer Item" org-timer-item t])
20829 ("Logging work"
20830 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20831 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20832 ["Clock out" org-clock-out t]
20833 ["Clock cancel" org-clock-cancel t]
20834 "--"
20835 ["Mark as default task" org-clock-mark-default-task t]
20836 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20837 ["Goto running clock" org-clock-goto t]
20838 "--"
20839 ["Display times" org-clock-display t]
20840 ["Create clock table" org-clock-report t]
20841 "--"
20842 ["Record DONE time"
20843 (progn (setq org-log-done (not org-log-done))
20844 (message "Switching to %s will %s record a timestamp"
20845 (car org-done-keywords)
20846 (if org-log-done "automatically" "not")))
20847 :style toggle :selected org-log-done])
20848 "--"
20849 ["Agenda Command..." org-agenda t]
20850 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20851 ("File List for Agenda")
20852 ("Special views current file"
20853 ["TODO Tree" org-show-todo-tree t]
20854 ["Check Deadlines" org-check-deadlines t]
20855 ["Timeline" org-timeline t]
20856 ["Tags/Property tree" org-match-sparse-tree t])
20857 "--"
20858 ["Export/Publish..." org-export-dispatch t]
20859 ("LaTeX"
20860 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20861 :selected org-cdlatex-mode]
20862 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20863 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20864 ["Modify math symbol" org-cdlatex-math-modify
20865 (org-inside-LaTeX-fragment-p)]
20866 ["Insert citation" org-reftex-citation t]
20867 "--"
20868 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20869 "--"
20870 ("MobileOrg"
20871 ["Push Files and Views" org-mobile-push t]
20872 ["Get Captured and Flagged" org-mobile-pull t]
20873 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20874 "--"
20875 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20876 "--"
20877 ("Documentation"
20878 ["Show Version" org-version t]
20879 ["Info Documentation" org-info t])
20880 ("Customize"
20881 ["Browse Org Group" org-customize t]
20882 "--"
20883 ["Expand This Menu" org-create-customize-menu
20884 (fboundp 'customize-menu-create)])
20885 ["Send bug report" org-submit-bug-report t]
20886 "--"
20887 ("Refresh/Reload"
20888 ["Refresh setup current buffer" org-mode-restart t]
20889 ["Reload Org (after update)" org-reload t]
20890 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20893 (defun org-info (&optional node)
20894 "Read documentation for Org-mode in the info system.
20895 With optional NODE, go directly to that node."
20896 (interactive)
20897 (info (format "(org)%s" (or node ""))))
20899 ;;;###autoload
20900 (defun org-submit-bug-report ()
20901 "Submit a bug report on Org-mode via mail.
20903 Don't hesitate to report any problems or inaccurate documentation.
20905 If you don't have setup sending mail from (X)Emacs, please copy the
20906 output buffer into your mail program, as it gives us important
20907 information about your Org-mode version and configuration."
20908 (interactive)
20909 (require 'reporter)
20910 (org-load-modules-maybe)
20911 (org-require-autoloaded-modules)
20912 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20913 (reporter-submit-bug-report
20914 "emacs-orgmode@gnu.org"
20915 (org-version nil 'full)
20916 (let (list)
20917 (save-window-excursion
20918 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20919 (delete-other-windows)
20920 (erase-buffer)
20921 (insert "You are about to submit a bug report to the Org-mode mailing list.
20923 We would like to add your full Org-mode and Outline configuration to the
20924 bug report. This greatly simplifies the work of the maintainer and
20925 other experts on the mailing list.
20927 HOWEVER, some variables you have customized may contain private
20928 information. The names of customers, colleagues, or friends, might
20929 appear in the form of file names, tags, todo states, or search strings.
20930 If you answer yes to the prompt, you might want to check and remove
20931 such private information before sending the email.")
20932 (add-text-properties (point-min) (point-max) '(face org-warning))
20933 (when (yes-or-no-p "Include your Org-mode configuration ")
20934 (mapatoms
20935 (lambda (v)
20936 (and (boundp v)
20937 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20938 (or (and (symbol-value v)
20939 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20940 (and
20941 (get v 'custom-type) (get v 'standard-value)
20942 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20943 (push v list)))))
20944 (kill-buffer (get-buffer "*Warn about privacy*"))
20945 list))
20946 nil nil
20947 "Remember to cover the basics, that is, what you expected to happen and
20948 what in fact did happen. You don't know how to make a good report? See
20950 http://orgmode.org/manual/Feedback.html#Feedback
20952 Your bug report will be posted to the Org-mode mailing list.
20953 ------------------------------------------------------------------------")
20954 (save-excursion
20955 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20956 (replace-match "\\1Bug: \\3 [\\2]")))))
20959 (defun org-install-agenda-files-menu ()
20960 (let ((bl (buffer-list)))
20961 (save-excursion
20962 (while bl
20963 (set-buffer (pop bl))
20964 (if (derived-mode-p 'org-mode) (setq bl nil)))
20965 (when (derived-mode-p 'org-mode)
20966 (easy-menu-change
20967 '("Org") "File List for Agenda"
20968 (append
20969 (list
20970 ["Edit File List" (org-edit-agenda-file-list) t]
20971 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20972 ["Remove Current File from List" org-remove-file t]
20973 ["Cycle through agenda files" org-cycle-agenda-files t]
20974 ["Occur in all agenda files" org-occur-in-agenda-files t]
20975 "--")
20976 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20978 ;;;; Documentation
20980 (defun org-require-autoloaded-modules ()
20981 (interactive)
20982 (mapc 'require
20983 '(org-agenda org-archive org-attach org-clock org-colview org-id
20984 org-remember org-table org-timer)))
20986 ;;;###autoload
20987 (defun org-reload (&optional uncompiled)
20988 "Reload all org lisp files.
20989 With prefix arg UNCOMPILED, load the uncompiled versions."
20990 (interactive "P")
20991 (require 'loadhist)
20992 (let* ((org-dir (org-find-library-dir "org"))
20993 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20994 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20995 (remove-re (mapconcat 'identity
20996 (mapcar (lambda (f) (concat "^" f "$"))
20997 (list (if (featurep 'xemacs)
20998 "org-colview"
20999 "org-colview-xemacs")
21000 "org" "org-loaddefs" "org-version"))
21001 "\\|"))
21002 (feats (delete-dups
21003 (mapcar 'file-name-sans-extension
21004 (mapcar 'file-name-nondirectory
21005 (delq nil
21006 (mapcar 'feature-file
21007 features))))))
21008 (lfeat (append
21009 (sort
21010 (setq feats
21011 (delq nil (mapcar
21012 (lambda (f)
21013 (if (and (string-match feature-re f)
21014 (not (string-match remove-re f)))
21015 f nil))
21016 feats)))
21017 'string-lessp)
21018 (list "org-version" "org")))
21019 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21020 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21021 load-uncore load-misses)
21022 (setq load-misses
21023 (delq 't
21024 (mapcar (lambda (f)
21025 (or (org-load-noerror-mustsuffix (concat org-dir f))
21026 (and (string= org-dir contrib-dir)
21027 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21028 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21029 (add-to-list 'load-uncore f 'append)
21032 lfeat)))
21033 (if load-uncore
21034 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21035 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21036 (if load-misses
21037 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21038 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21039 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21041 ;;;###autoload
21042 (defun org-customize ()
21043 "Call the customize function with org as argument."
21044 (interactive)
21045 (org-load-modules-maybe)
21046 (org-require-autoloaded-modules)
21047 (customize-browse 'org))
21049 (defun org-create-customize-menu ()
21050 "Create a full customization menu for Org-mode, insert it into the menu."
21051 (interactive)
21052 (org-load-modules-maybe)
21053 (org-require-autoloaded-modules)
21054 (if (fboundp 'customize-menu-create)
21055 (progn
21056 (easy-menu-change
21057 '("Org") "Customize"
21058 `(["Browse Org group" org-customize t]
21059 "--"
21060 ,(customize-menu-create 'org)
21061 ["Set" Custom-set t]
21062 ["Save" Custom-save t]
21063 ["Reset to Current" Custom-reset-current t]
21064 ["Reset to Saved" Custom-reset-saved t]
21065 ["Reset to Standard Settings" Custom-reset-standard t]))
21066 (message "\"Org\"-menu now contains full customization menu"))
21067 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21069 ;;;; Miscellaneous stuff
21071 ;;; Generally useful functions
21073 (defun org-get-at-bol (property)
21074 "Get text property PROPERTY at beginning of line."
21075 (get-text-property (point-at-bol) property))
21077 (defun org-find-text-property-in-string (prop s)
21078 "Return the first non-nil value of property PROP in string S."
21079 (or (get-text-property 0 prop s)
21080 (get-text-property (or (next-single-property-change 0 prop s) 0)
21081 prop s)))
21083 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21084 "Display the given MESSAGE as a warning."
21085 (if (fboundp 'display-warning)
21086 (display-warning 'org message
21087 (if (featurep 'xemacs) 'warning :warning))
21088 (let ((buf (get-buffer-create "*Org warnings*")))
21089 (with-current-buffer buf
21090 (goto-char (point-max))
21091 (insert "Warning (Org): " message)
21092 (unless (bolp)
21093 (newline)))
21094 (display-buffer buf)
21095 (sit-for 0))))
21097 (defun org-eval (form)
21098 "Eval FORM and return result."
21099 (condition-case error
21100 (eval form)
21101 (error (format "%%![Error: %s]" error))))
21103 (defun org-in-clocktable-p ()
21104 "Check if the cursor is in a clocktable."
21105 (let ((pos (point)) start)
21106 (save-excursion
21107 (end-of-line 1)
21108 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21109 (setq start (match-beginning 0))
21110 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21111 (>= (match-end 0) pos)
21112 start))))
21114 (defun org-in-commented-line ()
21115 "Is point in a line starting with `#'?"
21116 (equal (char-after (point-at-bol)) ?#))
21118 (defun org-in-indented-comment-line ()
21119 "Is point in a line starting with `#' after some white space?"
21120 (save-excursion
21121 (save-match-data
21122 (goto-char (point-at-bol))
21123 (looking-at "[ \t]*#"))))
21125 (defun org-in-verbatim-emphasis ()
21126 (save-match-data
21127 (and (org-in-regexp org-emph-re 2)
21128 (>= (point) (match-beginning 3))
21129 (<= (point) (match-end 4))
21130 (member (match-string 3) '("=" "~")))))
21132 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21133 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21134 (if (and marker (marker-buffer marker)
21135 (buffer-live-p (marker-buffer marker)))
21136 (progn
21137 (org-pop-to-buffer-same-window (marker-buffer marker))
21138 (if (or (> marker (point-max)) (< marker (point-min)))
21139 (widen))
21140 (goto-char marker)
21141 (org-show-context 'org-goto))
21142 (if bookmark
21143 (bookmark-jump bookmark)
21144 (error "Cannot find location"))))
21146 (defun org-quote-csv-field (s)
21147 "Quote field for inclusion in CSV material."
21148 (if (string-match "[\",]" s)
21149 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21152 (defun org-force-self-insert (N)
21153 "Needed to enforce self-insert under remapping."
21154 (interactive "p")
21155 (self-insert-command N))
21157 (defun org-string-width (s)
21158 "Compute width of string, ignoring invisible characters.
21159 This ignores character with invisibility property `org-link', and also
21160 characters with property `org-cwidth', because these will become invisible
21161 upon the next fontification round."
21162 (let (b l)
21163 (when (or (eq t buffer-invisibility-spec)
21164 (assq 'org-link buffer-invisibility-spec))
21165 (while (setq b (text-property-any 0 (length s)
21166 'invisible 'org-link s))
21167 (setq s (concat (substring s 0 b)
21168 (substring s (or (next-single-property-change
21169 b 'invisible s) (length s)))))))
21170 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21171 (setq s (concat (substring s 0 b)
21172 (substring s (or (next-single-property-change
21173 b 'org-cwidth s) (length s))))))
21174 (setq l (string-width s) b -1)
21175 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21176 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21179 (defun org-shorten-string (s maxlength)
21180 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21181 If the string is shorter or has length MAXLENGTH, just return the
21182 original string. If it is longer, the functions finds a space in the
21183 string, breaks this string off at that locations and adds three dots
21184 as ellipsis. Including the ellipsis, the string will not be longer
21185 than MAXLENGTH. If finding a good breaking point in the string does
21186 not work, the string is just chopped off in the middle of a word
21187 if necessary."
21188 (if (<= (length s) maxlength)
21190 (let* ((n (max (- maxlength 4) 1))
21191 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21192 (if (string-match re s)
21193 (concat (match-string 1 s) "...")
21194 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21196 (defun org-get-indentation (&optional line)
21197 "Get the indentation of the current line, interpreting tabs.
21198 When LINE is given, assume it represents a line and compute its indentation."
21199 (if line
21200 (if (string-match "^ *" (org-remove-tabs line))
21201 (match-end 0))
21202 (save-excursion
21203 (beginning-of-line 1)
21204 (skip-chars-forward " \t")
21205 (current-column))))
21207 (defun org-get-string-indentation (s)
21208 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21209 (let ((n -1) (i 0) (w tab-width) c)
21210 (catch 'exit
21211 (while (< (setq n (1+ n)) (length s))
21212 (setq c (aref s n))
21213 (cond ((= c ?\ ) (setq i (1+ i)))
21214 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21215 (t (throw 'exit t)))))
21218 (defun org-remove-tabs (s &optional width)
21219 "Replace tabulators in S with spaces.
21220 Assumes that s is a single line, starting in column 0."
21221 (setq width (or width tab-width))
21222 (while (string-match "\t" s)
21223 (setq s (replace-match
21224 (make-string
21225 (- (* width (/ (+ (match-beginning 0) width) width))
21226 (match-beginning 0)) ?\ )
21227 t t s)))
21230 (defun org-fix-indentation (line ind)
21231 "Fix indentation in LINE.
21232 IND is a cons cell with target and minimum indentation.
21233 If the current indentation in LINE is smaller than the minimum,
21234 leave it alone. If it is larger than ind, set it to the target."
21235 (let* ((l (org-remove-tabs line))
21236 (i (org-get-indentation l))
21237 (i1 (car ind)) (i2 (cdr ind)))
21238 (if (>= i i2) (setq l (substring line i2)))
21239 (if (> i1 0)
21240 (concat (make-string i1 ?\ ) l)
21241 l)))
21243 (defun org-remove-indentation (code &optional n)
21244 "Remove the maximum common indentation from the lines in CODE.
21245 N may optionally be the number of spaces to remove."
21246 (with-temp-buffer
21247 (insert code)
21248 (org-do-remove-indentation n)
21249 (buffer-string)))
21251 (defun org-do-remove-indentation (&optional n)
21252 "Remove the maximum common indentation from the buffer."
21253 (untabify (point-min) (point-max))
21254 (let ((min 10000) re)
21255 (if n
21256 (setq min n)
21257 (goto-char (point-min))
21258 (while (re-search-forward "^ *[^ \n]" nil t)
21259 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21260 (unless (or (= min 0) (= min 10000))
21261 (setq re (format "^ \\{%d\\}" min))
21262 (goto-char (point-min))
21263 (while (re-search-forward re nil t)
21264 (replace-match "")
21265 (end-of-line 1))
21266 min)))
21268 (defun org-fill-template (template alist)
21269 "Find each %key of ALIST in TEMPLATE and replace it."
21270 (let ((case-fold-search nil)
21271 entry key value)
21272 (setq alist (sort (copy-sequence alist)
21273 (lambda (a b) (< (length (car a)) (length (car b))))))
21274 (while (setq entry (pop alist))
21275 (setq template
21276 (replace-regexp-in-string
21277 (concat "%" (regexp-quote (car entry)))
21278 (or (cdr entry) "") template t t)))
21279 template))
21281 (defun org-base-buffer (buffer)
21282 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21283 (if (not buffer)
21284 buffer
21285 (or (buffer-base-buffer buffer)
21286 buffer)))
21288 (defun org-trim (s)
21289 "Remove whitespace at beginning and end of string."
21290 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21291 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21294 (defun org-wrap (string &optional width lines)
21295 "Wrap string to either a number of lines, or a width in characters.
21296 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21297 that costs. If there is a word longer than WIDTH, the text is actually
21298 wrapped to the length of that word.
21299 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21300 many lines, whatever width that takes.
21301 The return value is a list of lines, without newlines at the end."
21302 (let* ((words (org-split-string string "[ \t\n]+"))
21303 (maxword (apply 'max (mapcar 'org-string-width words)))
21304 w ll)
21305 (cond (width
21306 (org-do-wrap words (max maxword width)))
21307 (lines
21308 (setq w maxword)
21309 (setq ll (org-do-wrap words maxword))
21310 (if (<= (length ll) lines)
21312 (setq ll words)
21313 (while (> (length ll) lines)
21314 (setq w (1+ w))
21315 (setq ll (org-do-wrap words w)))
21316 ll))
21317 (t (error "Cannot wrap this")))))
21319 (defun org-do-wrap (words width)
21320 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21321 (let (lines line)
21322 (while words
21323 (setq line (pop words))
21324 (while (and words (< (+ (length line) (length (car words))) width))
21325 (setq line (concat line " " (pop words))))
21326 (setq lines (push line lines)))
21327 (nreverse lines)))
21329 (defun org-split-string (string &optional separators)
21330 "Splits STRING into substrings at SEPARATORS.
21331 No empty strings are returned if there are matches at the beginning
21332 and end of string."
21333 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21334 (start 0)
21335 notfirst
21336 (list nil))
21337 (while (and (string-match rexp string
21338 (if (and notfirst
21339 (= start (match-beginning 0))
21340 (< start (length string)))
21341 (1+ start) start))
21342 (< (match-beginning 0) (length string)))
21343 (setq notfirst t)
21344 (or (eq (match-beginning 0) 0)
21345 (and (eq (match-beginning 0) (match-end 0))
21346 (eq (match-beginning 0) start))
21347 (setq list
21348 (cons (substring string start (match-beginning 0))
21349 list)))
21350 (setq start (match-end 0)))
21351 (or (eq start (length string))
21352 (setq list
21353 (cons (substring string start)
21354 list)))
21355 (nreverse list)))
21357 (defun org-quote-vert (s)
21358 "Replace \"|\" with \"\\vert\"."
21359 (while (string-match "|" s)
21360 (setq s (replace-match "\\vert" t t s)))
21363 (defun org-uuidgen-p (s)
21364 "Is S an ID created by UUIDGEN?"
21365 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21367 (defun org-in-src-block-p (&optional inside)
21368 "Whether point is in a code source block.
21369 When INSIDE is non-nil, don't consider we are within a src block
21370 when point is at #+BEGIN_SRC or #+END_SRC."
21371 (let ((case-fold-search t) ov)
21372 (or (and (setq ov (overlays-at (point)))
21373 (memq 'org-block-background
21374 (overlay-properties (car ov))))
21375 (and (not inside)
21376 (save-match-data
21377 (save-excursion
21378 (beginning-of-line)
21379 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21381 (defun org-context ()
21382 "Return a list of contexts of the current cursor position.
21383 If several contexts apply, all are returned.
21384 Each context entry is a list with a symbol naming the context, and
21385 two positions indicating start and end of the context. Possible
21386 contexts are:
21388 :headline anywhere in a headline
21389 :headline-stars on the leading stars in a headline
21390 :todo-keyword on a TODO keyword (including DONE) in a headline
21391 :tags on the TAGS in a headline
21392 :priority on the priority cookie in a headline
21393 :item on the first line of a plain list item
21394 :item-bullet on the bullet/number of a plain list item
21395 :checkbox on the checkbox in a plain list item
21396 :table in an org-mode table
21397 :table-special on a special filed in a table
21398 :table-table in a table.el table
21399 :clocktable in a clocktable
21400 :src-block in a source block
21401 :link on a hyperlink
21402 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21403 :target on a <<target>>
21404 :radio-target on a <<<radio-target>>>
21405 :latex-fragment on a LaTeX fragment
21406 :latex-preview on a LaTeX fragment with overlaid preview image
21408 This function expects the position to be visible because it uses font-lock
21409 faces as a help to recognize the following contexts: :table-special, :link,
21410 and :keyword."
21411 (let* ((f (get-text-property (point) 'face))
21412 (faces (if (listp f) f (list f)))
21413 (case-fold-search t)
21414 (p (point)) clist o)
21415 ;; First the large context
21416 (cond
21417 ((org-at-heading-p t)
21418 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21419 (when (progn
21420 (beginning-of-line 1)
21421 (looking-at org-todo-line-tags-regexp))
21422 (push (org-point-in-group p 1 :headline-stars) clist)
21423 (push (org-point-in-group p 2 :todo-keyword) clist)
21424 (push (org-point-in-group p 4 :tags) clist))
21425 (goto-char p)
21426 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21427 (if (looking-at "\\[#[A-Z0-9]\\]")
21428 (push (org-point-in-group p 0 :priority) clist)))
21430 ((org-at-item-p)
21431 (push (org-point-in-group p 2 :item-bullet) clist)
21432 (push (list :item (point-at-bol)
21433 (save-excursion (org-end-of-item) (point)))
21434 clist)
21435 (and (org-at-item-checkbox-p)
21436 (push (org-point-in-group p 0 :checkbox) clist)))
21438 ((org-at-table-p)
21439 (push (list :table (org-table-begin) (org-table-end)) clist)
21440 (if (memq 'org-formula faces)
21441 (push (list :table-special
21442 (previous-single-property-change p 'face)
21443 (next-single-property-change p 'face)) clist)))
21444 ((org-at-table-p 'any)
21445 (push (list :table-table) clist)))
21446 (goto-char p)
21448 (let ((case-fold-search t))
21449 ;; New the "medium" contexts: clocktables, source blocks
21450 (cond ((org-in-clocktable-p)
21451 (push (list :clocktable
21452 (and (or (looking-at "#\\+BEGIN: clocktable")
21453 (search-backward "#+BEGIN: clocktable" nil t))
21454 (match-beginning 0))
21455 (and (re-search-forward "#\\+END:?" nil t)
21456 (match-end 0))) clist))
21457 ((org-in-src-block-p)
21458 (push (list :src-block
21459 (and (or (looking-at "#\\+BEGIN_SRC")
21460 (search-backward "#+BEGIN_SRC" nil t))
21461 (match-beginning 0))
21462 (and (search-forward "#+END_SRC" nil t)
21463 (match-beginning 0))) clist))))
21464 (goto-char p)
21466 ;; Now the small context
21467 (cond
21468 ((org-at-timestamp-p)
21469 (push (org-point-in-group p 0 :timestamp) clist))
21470 ((memq 'org-link faces)
21471 (push (list :link
21472 (previous-single-property-change p 'face)
21473 (next-single-property-change p 'face)) clist))
21474 ((memq 'org-special-keyword faces)
21475 (push (list :keyword
21476 (previous-single-property-change p 'face)
21477 (next-single-property-change p 'face)) clist))
21478 ((org-at-target-p)
21479 (push (org-point-in-group p 0 :target) clist)
21480 (goto-char (1- (match-beginning 0)))
21481 (if (looking-at org-radio-target-regexp)
21482 (push (org-point-in-group p 0 :radio-target) clist))
21483 (goto-char p))
21484 ((setq o (car (delq nil
21485 (mapcar
21486 (lambda (x)
21487 (if (memq x org-latex-fragment-image-overlays) x))
21488 (overlays-at (point))))))
21489 (push (list :latex-fragment
21490 (overlay-start o) (overlay-end o)) clist)
21491 (push (list :latex-preview
21492 (overlay-start o) (overlay-end o)) clist))
21493 ((org-inside-LaTeX-fragment-p)
21494 ;; FIXME: positions wrong.
21495 (push (list :latex-fragment (point) (point)) clist)))
21497 (setq clist (nreverse (delq nil clist)))
21498 clist))
21500 ;; FIXME: Compare with at-regexp-p Do we need both?
21501 (defun org-in-regexp (re &optional nlines visually)
21502 "Check if point is inside a match of regexp.
21503 Normally only the current line is checked, but you can include NLINES extra
21504 lines both before and after point into the search.
21505 If VISUALLY is set, require that the cursor is not after the match but
21506 really on, so that the block visually is on the match."
21507 (catch 'exit
21508 (let ((pos (point))
21509 (eol (point-at-eol (+ 1 (or nlines 0))))
21510 (inc (if visually 1 0)))
21511 (save-excursion
21512 (beginning-of-line (- 1 (or nlines 0)))
21513 (while (re-search-forward re eol t)
21514 (if (and (<= (match-beginning 0) pos)
21515 (>= (+ inc (match-end 0)) pos))
21516 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21518 (defun org-at-regexp-p (regexp)
21519 "Is point inside a match of REGEXP in the current line?"
21520 (catch 'exit
21521 (save-excursion
21522 (let ((pos (point)) (end (point-at-eol)))
21523 (beginning-of-line 1)
21524 (while (re-search-forward regexp end t)
21525 (if (and (<= (match-beginning 0) pos)
21526 (>= (match-end 0) pos))
21527 (throw 'exit t)))
21528 nil))))
21530 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21531 "Non-nil when point is between matches of START-RE and END-RE.
21533 Also return a non-nil value when point is on one of the matches.
21535 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21536 buffer positions. Default values are the positions of headlines
21537 surrounding the point.
21539 The functions returns a cons cell whose car (resp. cdr) is the
21540 position before START-RE (resp. after END-RE)."
21541 (save-match-data
21542 (let ((pos (point))
21543 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21544 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21545 beg end)
21546 (save-excursion
21547 ;; Point is on a block when on START-RE or if START-RE can be
21548 ;; found before it...
21549 (and (or (org-at-regexp-p start-re)
21550 (re-search-backward start-re limit-up t))
21551 (setq beg (match-beginning 0))
21552 ;; ... and END-RE after it...
21553 (goto-char (match-end 0))
21554 (re-search-forward end-re limit-down t)
21555 (> (setq end (match-end 0)) pos)
21556 ;; ... without another START-RE in-between.
21557 (goto-char (match-beginning 0))
21558 (not (re-search-backward start-re (1+ beg) t))
21559 ;; Return value.
21560 (cons beg end))))))
21562 (defun org-in-block-p (names)
21563 "Non-nil when point belongs to a block whose name belongs to NAMES.
21565 NAMES is a list of strings containing names of blocks.
21567 Return first block name matched, or nil. Beware that in case of
21568 nested blocks, the returned name may not belong to the closest
21569 block from point."
21570 (save-match-data
21571 (catch 'exit
21572 (let ((case-fold-search t)
21573 (lim-up (save-excursion (outline-previous-heading)))
21574 (lim-down (save-excursion (outline-next-heading))))
21575 (mapc (lambda (name)
21576 (let ((n (regexp-quote name)))
21577 (when (org-between-regexps-p
21578 (concat "^[ \t]*#\\+begin_" n)
21579 (concat "^[ \t]*#\\+end_" n)
21580 lim-up lim-down)
21581 (throw 'exit n))))
21582 names))
21583 nil)))
21585 (defun org-in-drawer-p ()
21586 "Is point within a drawer?"
21587 (save-match-data
21588 (let ((case-fold-search t)
21589 (lim-up (save-excursion (outline-previous-heading)))
21590 (lim-down (save-excursion (outline-next-heading))))
21591 (org-between-regexps-p
21592 (concat "^[ \t]*:" (regexp-opt org-drawers) ":")
21593 "^[ \t]*:end:.*$"
21594 lim-up lim-down))))
21596 (defun org-occur-in-agenda-files (regexp &optional nlines)
21597 "Call `multi-occur' with buffers for all agenda files."
21598 (interactive "sOrg-files matching: \np")
21599 (let* ((files (org-agenda-files))
21600 (tnames (mapcar 'file-truename files))
21601 (extra org-agenda-text-search-extra-files)
21603 (when (eq (car extra) 'agenda-archives)
21604 (setq extra (cdr extra))
21605 (setq files (org-add-archive-files files)))
21606 (while (setq f (pop extra))
21607 (unless (member (file-truename f) tnames)
21608 (add-to-list 'files f 'append)
21609 (add-to-list 'tnames (file-truename f) 'append)))
21610 (multi-occur
21611 (mapcar (lambda (x)
21612 (with-current-buffer
21613 (or (get-file-buffer x) (find-file-noselect x))
21614 (widen)
21615 (current-buffer)))
21616 files)
21617 regexp)))
21619 (if (boundp 'occur-mode-find-occurrence-hook)
21620 ;; Emacs 23
21621 (add-hook 'occur-mode-find-occurrence-hook
21622 (lambda ()
21623 (when (derived-mode-p 'org-mode)
21624 (org-reveal))))
21625 ;; Emacs 22
21626 (defadvice occur-mode-goto-occurrence
21627 (after org-occur-reveal activate)
21628 (and (derived-mode-p 'org-mode) (org-reveal)))
21629 (defadvice occur-mode-goto-occurrence-other-window
21630 (after org-occur-reveal activate)
21631 (and (derived-mode-p 'org-mode) (org-reveal)))
21632 (defadvice occur-mode-display-occurrence
21633 (after org-occur-reveal activate)
21634 (when (derived-mode-p 'org-mode)
21635 (let ((pos (occur-mode-find-occurrence)))
21636 (with-current-buffer (marker-buffer pos)
21637 (save-excursion
21638 (goto-char pos)
21639 (org-reveal)))))))
21641 (defun org-occur-link-in-agenda-files ()
21642 "Create a link and search for it in the agendas.
21643 The link is not stored in `org-stored-links', it is just created
21644 for the search purpose."
21645 (interactive)
21646 (let ((link (condition-case nil
21647 (org-store-link nil)
21648 (error "Unable to create a link to here"))))
21649 (org-occur-in-agenda-files (regexp-quote link))))
21651 (defun org-reverse-string (string)
21652 "Return the reverse of STRING."
21653 (apply 'string (reverse (string-to-list string))))
21655 (defsubst org-uniquify (list)
21656 "Non-destructively remove duplicate elements from LIST."
21657 (let ((res (copy-sequence list))) (delete-dups res)))
21659 (defun org-uniquify-alist (alist)
21660 "Merge elements of ALIST with the same key.
21662 For example, in this alist:
21664 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21665 => '((a 1 3) (b 2))
21667 merge (a 1) and (a 3) into (a 1 3).
21669 The function returns the new ALIST."
21670 (let (rtn)
21671 (mapc
21672 (lambda (e)
21673 (let (n)
21674 (if (not (assoc (car e) rtn))
21675 (push e rtn)
21676 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21677 (setq rtn (assq-delete-all (car e) rtn))
21678 (push n rtn))))
21679 alist)
21680 rtn))
21682 (defun org-delete-all (elts list)
21683 "Remove all elements in ELTS from LIST."
21684 (while elts
21685 (setq list (delete (pop elts) list)))
21686 list)
21688 (defun org-count (cl-item cl-seq)
21689 "Count the number of occurrences of ITEM in SEQ.
21690 Taken from `count' in cl-seq.el with all keyword arguments removed."
21691 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21692 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21693 (while (< cl-start cl-end)
21694 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21695 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21696 (setq cl-start (1+ cl-start)))
21697 cl-count))
21699 (defun org-remove-if (predicate seq)
21700 "Remove everything from SEQ that fulfills PREDICATE."
21701 (let (res e)
21702 (while seq
21703 (setq e (pop seq))
21704 (if (not (funcall predicate e)) (push e res)))
21705 (nreverse res)))
21707 (defun org-remove-if-not (predicate seq)
21708 "Remove everything from SEQ that does not fulfill PREDICATE."
21709 (let (res e)
21710 (while seq
21711 (setq e (pop seq))
21712 (if (funcall predicate e) (push e res)))
21713 (nreverse res)))
21715 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21716 "Reduce two-argument FUNCTION across SEQ.
21717 Taken from `reduce' in cl-seq.el with all keyword arguments but
21718 \":initial-value\" removed."
21719 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21720 (cadr (memq :initial-value cl-keys)))
21721 (cl-seq (pop cl-seq))
21722 (t (funcall cl-func)))))
21723 (while cl-seq
21724 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21725 cl-accum))
21727 (defun org-back-over-empty-lines ()
21728 "Move backwards over whitespace, to the beginning of the first empty line.
21729 Returns the number of empty lines passed."
21730 (let ((pos (point)))
21731 (if (cdr (assoc 'heading org-blank-before-new-entry))
21732 (skip-chars-backward " \t\n\r")
21733 (unless (eobp)
21734 (forward-line -1)))
21735 (beginning-of-line 2)
21736 (goto-char (min (point) pos))
21737 (count-lines (point) pos)))
21739 (defun org-skip-whitespace ()
21740 (skip-chars-forward " \t\n\r"))
21742 (defun org-point-in-group (point group &optional context)
21743 "Check if POINT is in match-group GROUP.
21744 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21745 match. If the match group does not exist or point is not inside it,
21746 return nil."
21747 (and (match-beginning group)
21748 (>= point (match-beginning group))
21749 (<= point (match-end group))
21750 (if context
21751 (list context (match-beginning group) (match-end group))
21752 t)))
21754 (defun org-switch-to-buffer-other-window (&rest args)
21755 "Switch to buffer in a second window on the current frame.
21756 In particular, do not allow pop-up frames.
21757 Returns the newly created buffer."
21758 (org-no-popups
21759 (apply 'switch-to-buffer-other-window args)))
21761 (defun org-combine-plists (&rest plists)
21762 "Create a single property list from all plists in PLISTS.
21763 The process starts by copying the first list, and then setting properties
21764 from the other lists. Settings in the last list are the most significant
21765 ones and overrule settings in the other lists."
21766 (let ((rtn (copy-sequence (pop plists)))
21767 p v ls)
21768 (while plists
21769 (setq ls (pop plists))
21770 (while ls
21771 (setq p (pop ls) v (pop ls))
21772 (setq rtn (plist-put rtn p v))))
21773 rtn))
21775 (defun org-replace-escapes (string table)
21776 "Replace %-escapes in STRING with values in TABLE.
21777 TABLE is an association list with keys like \"%a\" and string values.
21778 The sequences in STRING may contain normal field width and padding information,
21779 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21780 so values can contain further %-escapes if they are define later in TABLE."
21781 (let ((tbl (copy-alist table))
21782 (case-fold-search nil)
21783 (pchg 0)
21784 e re rpl)
21785 (while (setq e (pop tbl))
21786 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21787 (when (and (cdr e) (string-match re (cdr e)))
21788 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21789 (safe "SREF"))
21790 (add-text-properties 0 3 (list 'sref sref) safe)
21791 (setcdr e (replace-match safe t t (cdr e)))))
21792 (while (string-match re string)
21793 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21794 (cdr e)))
21795 (setq string (replace-match rpl t t string))))
21796 (while (setq pchg (next-property-change pchg string))
21797 (let ((sref (get-text-property pchg 'sref string)))
21798 (when (and sref (string-match "SREF" string pchg))
21799 (setq string (replace-match sref t t string)))))
21800 string))
21802 (defun org-sublist (list start end)
21803 "Return a section of LIST, from START to END.
21804 Counting starts at 1."
21805 (let (rtn (c start))
21806 (setq list (nthcdr (1- start) list))
21807 (while (and list (<= c end))
21808 (push (pop list) rtn)
21809 (setq c (1+ c)))
21810 (nreverse rtn)))
21812 (defun org-find-base-buffer-visiting (file)
21813 "Like `find-buffer-visiting' but always return the base buffer and
21814 not an indirect buffer."
21815 (let ((buf (or (get-file-buffer file)
21816 (find-buffer-visiting file))))
21817 (if buf
21818 (or (buffer-base-buffer buf) buf)
21819 nil)))
21821 (defun org-image-file-name-regexp (&optional extensions)
21822 "Return regexp matching the file names of images.
21823 If EXTENSIONS is given, only match these."
21824 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21825 (image-file-name-regexp)
21826 (let ((image-file-name-extensions
21827 (or extensions
21828 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21829 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21830 (concat "\\."
21831 (regexp-opt (nconc (mapcar 'upcase
21832 image-file-name-extensions)
21833 image-file-name-extensions)
21835 "\\'"))))
21837 (defun org-file-image-p (file &optional extensions)
21838 "Return non-nil if FILE is an image."
21839 (save-match-data
21840 (string-match (org-image-file-name-regexp extensions) file)))
21842 (defun org-get-cursor-date (&optional with-time)
21843 "Return the date at cursor in as a time.
21844 This works in the calendar and in the agenda, anywhere else it just
21845 returns the current time.
21846 If WITH-TIME is non-nil, returns the time of the event at point (in
21847 the agenda) or the current time of the day."
21848 (let (date day defd tp tm hod mod)
21849 (when with-time
21850 (setq tp (get-text-property (point) 'time))
21851 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21852 (setq hod (string-to-number (match-string 1 tp))
21853 mod (string-to-number (match-string 2 tp))))
21854 (or tp (setq hod (nth 2 (decode-time (current-time)))
21855 mod (nth 1 (decode-time (current-time))))))
21856 (cond
21857 ((eq major-mode 'calendar-mode)
21858 (setq date (calendar-cursor-to-date)
21859 defd (encode-time 0 (or mod 0) (or hod 0)
21860 (nth 1 date) (nth 0 date) (nth 2 date))))
21861 ((eq major-mode 'org-agenda-mode)
21862 (setq day (get-text-property (point) 'day))
21863 (if day
21864 (setq date (calendar-gregorian-from-absolute day)
21865 defd (encode-time 0 (or mod 0) (or hod 0)
21866 (nth 1 date) (nth 0 date) (nth 2 date))))))
21867 (or defd (current-time))))
21869 (defun org-mark-subtree (&optional up)
21870 "Mark the current subtree.
21871 This puts point at the start of the current subtree, and mark at
21872 the end. If a numeric prefix UP is given, move up into the
21873 hierarchy of headlines by UP levels before marking the subtree."
21874 (interactive "P")
21875 (org-with-limited-levels
21876 (cond ((org-at-heading-p) (beginning-of-line))
21877 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21878 (t (outline-previous-visible-heading 1))))
21879 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21880 (if (org-called-interactively-p 'any)
21881 (call-interactively 'org-mark-element)
21882 (org-mark-element)))
21885 ;;; Indentation
21887 (defun org-indent-line ()
21888 "Indent line depending on context."
21889 (interactive)
21890 (let* ((pos (point))
21891 (itemp (org-at-item-p))
21892 (case-fold-search t)
21893 (org-drawer-regexp (or org-drawer-regexp "\000"))
21894 (inline-task-p (and (featurep 'org-inlinetask)
21895 (org-inlinetask-in-task-p)))
21896 (inline-re (and inline-task-p
21897 (org-inlinetask-outline-regexp)))
21898 column)
21899 (if (and orgstruct-is-++ (eq pos (point)))
21900 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21901 (indent-according-to-mode))
21902 (beginning-of-line 1)
21903 (cond
21904 ;; Headings
21905 ((looking-at org-outline-regexp) (setq column 0))
21906 ;; Footnote definition
21907 ((looking-at org-footnote-definition-re) (setq column 0))
21908 ;; Literal examples
21909 ((looking-at "[ \t]*:\\( \\|$\\)")
21910 (setq column (org-get-indentation))) ; do nothing
21911 ;; Lists
21912 ((ignore-errors (goto-char (org-in-item-p)))
21913 (setq column (if itemp
21914 (org-get-indentation)
21915 (org-list-item-body-column (point))))
21916 (goto-char pos))
21917 ;; Drawers
21918 ((and (looking-at "[ \t]*:END:")
21919 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21920 (save-excursion
21921 (goto-char (1- (match-beginning 1)))
21922 (setq column (current-column))))
21923 ;; Special blocks
21924 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21925 (save-excursion
21926 (re-search-backward
21927 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21928 (setq column (org-get-indentation (match-string 0))))
21929 ((and (not (looking-at "[ \t]*#\\+begin_"))
21930 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21931 (save-excursion
21932 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21933 (setq column
21934 (cond ((equal (downcase (match-string 1)) "src")
21935 ;; src blocks: let `org-edit-src-exit' handle them
21936 (org-get-indentation))
21937 ((equal (downcase (match-string 1)) "example")
21938 (max (org-get-indentation)
21939 (org-get-indentation (match-string 0))))
21941 (org-get-indentation (match-string 0))))))
21942 ;; This line has nothing special, look at the previous relevant
21943 ;; line to compute indentation
21945 (beginning-of-line 0)
21946 (while (and (not (bobp))
21947 (not (looking-at org-table-line-regexp))
21948 (not (looking-at org-drawer-regexp))
21949 ;; When point started in an inline task, do not move
21950 ;; above task starting line.
21951 (not (and inline-task-p (looking-at inline-re)))
21952 ;; Skip drawers, blocks, empty lines, verbatim,
21953 ;; comments, tables, footnotes definitions, lists,
21954 ;; inline tasks.
21955 (or (and (looking-at "[ \t]*:END:")
21956 (re-search-backward org-drawer-regexp nil t))
21957 (and (looking-at "[ \t]*#\\+end_")
21958 (re-search-backward "[ \t]*#\\+begin_"nil t))
21959 (looking-at "[ \t]*[\n:#|]")
21960 (looking-at org-footnote-definition-re)
21961 (and (not inline-task-p)
21962 (featurep 'org-inlinetask)
21963 (org-inlinetask-in-task-p)
21964 (or (org-inlinetask-goto-beginning) t))))
21965 (beginning-of-line 0))
21966 (cond
21967 ;; There was a list item above.
21968 ((save-excursion
21969 (and (ignore-errors (goto-char (org-in-item-p)))
21970 (goto-char
21971 (org-list-get-top-point (org-list-struct)))))
21972 (looking-at org-list-full-item-re)
21973 (setq column (length (match-string 0))))
21974 ;; There was an heading above.
21975 ((looking-at "\\*+[ \t]+")
21976 (if (not org-adapt-indentation)
21977 (setq column 0)
21978 (goto-char (match-end 0))
21979 (setq column (current-column))))
21980 ;; A drawer had started and is unfinished
21981 ((looking-at org-drawer-regexp)
21982 (goto-char (1- (match-beginning 1)))
21983 (setq column (current-column)))
21984 ;; Else, nothing noticeable found: get indentation and go on.
21985 (t (setq column (org-get-indentation))))))
21986 ;; Now apply indentation and move cursor accordingly
21987 (goto-char pos)
21988 (if (<= (current-column) (current-indentation))
21989 (org-indent-line-to column)
21990 (save-excursion (org-indent-line-to column)))
21991 ;; Special polishing for properties, see `org-property-format'
21992 (setq column (current-column))
21993 (beginning-of-line 1)
21994 (if (looking-at
21995 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21996 (replace-match (concat (match-string 1)
21997 (format org-property-format
21998 (match-string 2) (match-string 3)))
21999 t t))
22000 (org-move-to-column column))))
22002 (defun org-indent-drawer ()
22003 "Indent the drawer at point."
22004 (interactive)
22005 (let ((p (point))
22006 (e (and (save-excursion (re-search-forward ":END:" nil t))
22007 (match-end 0)))
22008 (folded
22009 (save-excursion
22010 (end-of-line)
22011 (when (overlays-at (point))
22012 (member 'invisible (overlay-properties
22013 (car (overlays-at (point)))))))))
22014 (when folded (org-cycle))
22015 (indent-for-tab-command)
22016 (while (and (move-beginning-of-line 2) (< (point) e))
22017 (indent-for-tab-command))
22018 (goto-char p)
22019 (when folded (org-cycle)))
22020 (message "Drawer at point indented"))
22022 (defun org-indent-block ()
22023 "Indent the block at point."
22024 (interactive)
22025 (let ((p (point))
22026 (case-fold-search t)
22027 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22028 (match-end 0)))
22029 (folded
22030 (save-excursion
22031 (end-of-line)
22032 (when (overlays-at (point))
22033 (member 'invisible (overlay-properties
22034 (car (overlays-at (point)))))))))
22035 (when folded (org-cycle))
22036 (indent-for-tab-command)
22037 (while (and (move-beginning-of-line 2) (< (point) e))
22038 (indent-for-tab-command))
22039 (goto-char p)
22040 (when folded (org-cycle)))
22041 (message "Block at point indented"))
22043 (defun org-indent-region (start end)
22044 "Indent region."
22045 (interactive "r")
22046 (save-excursion
22047 (let ((line-end (org-current-line end)))
22048 (goto-char start)
22049 (while (< (org-current-line) line-end)
22050 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
22051 (t (call-interactively 'org-indent-line)))
22052 (move-beginning-of-line 2)))))
22055 ;;; Filling
22057 ;; We use our own fill-paragraph and auto-fill functions.
22059 ;; `org-fill-paragraph' relies on adaptive filling and context
22060 ;; checking. Appropriate `fill-prefix' is computed with
22061 ;; `org-adaptive-fill-function'.
22063 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22064 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22065 ;; `org-adaptive-fill-function' value. Internally,
22066 ;; `org-comment-line-break-function' breaks the line.
22068 ;; `org-setup-filling' installs filling and auto-filling related
22069 ;; variables during `org-mode' initialization.
22071 (defun org-setup-filling ()
22072 (interactive)
22073 ;; Prevent auto-fill from inserting unwanted new items.
22074 (when (boundp 'fill-nobreak-predicate)
22075 (org-set-local
22076 'fill-nobreak-predicate
22077 (org-uniquify
22078 (append fill-nobreak-predicate
22079 '(org-fill-paragraph-separate-nobreak-p
22080 org-fill-line-break-nobreak-p
22081 org-fill-paragraph-with-timestamp-nobreak-p)))))
22082 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22083 (org-set-local 'auto-fill-inhibit-regexp nil)
22084 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22085 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22086 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22088 (defvar org-element-paragraph-separate) ; org-element.el
22089 (defun org-fill-paragraph-separate-nobreak-p ()
22090 "Non-nil when a new line at point would end current paragraph."
22091 (looking-at (substring org-element-paragraph-separate 1)))
22093 (defun org-fill-line-break-nobreak-p ()
22094 "Non-nil when a new line at point would create an Org line break."
22095 (save-excursion
22096 (skip-chars-backward "[ \t]")
22097 (skip-chars-backward "\\\\")
22098 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22100 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22101 "Non-nil when a new line at point would split a timestamp."
22102 (and (org-at-timestamp-p t)
22103 (not (looking-at org-ts-regexp-both))))
22105 (declare-function message-in-body-p "message" ())
22106 (defvar orgtbl-line-start-regexp) ; From org-table.el
22107 (defun org-adaptive-fill-function ()
22108 "Compute a fill prefix for the current line.
22109 Return fill prefix, as a string, or nil if current line isn't
22110 meant to be filled."
22111 (let (prefix)
22112 (catch 'exit
22113 (when (derived-mode-p 'message-mode)
22114 (save-excursion
22115 (beginning-of-line)
22116 (cond ((or (not (message-in-body-p))
22117 (looking-at orgtbl-line-start-regexp))
22118 (throw 'exit nil))
22119 ((looking-at message-cite-prefix-regexp)
22120 (throw 'exit (match-string-no-properties 0)))
22121 ((looking-at org-outline-regexp)
22122 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22123 (org-with-wide-buffer
22124 (let* ((p (line-beginning-position))
22125 (element (save-excursion
22126 (beginning-of-line)
22127 (or (ignore-errors (org-element-at-point))
22128 (user-error "An element cannot be parsed line %d"
22129 (line-number-at-pos (point))))))
22130 (type (org-element-type element))
22131 (post-affiliated (org-element-property :post-affiliated element)))
22132 (unless (and post-affiliated (< p post-affiliated))
22133 (case type
22134 (comment (looking-at "[ \t]*# ?") (match-string 0))
22135 (footnote-definition "")
22136 ((item plain-list)
22137 (make-string (org-list-item-body-column
22138 (or post-affiliated
22139 (org-element-property :begin element)))
22140 ? ))
22141 (paragraph
22142 ;; Fill prefix is usually the same as the current line,
22143 ;; except if the paragraph is at the beginning of an item.
22144 (let ((parent (org-element-property :parent element)))
22145 (cond ((eq (org-element-type parent) 'item)
22146 (make-string (org-list-item-body-column
22147 (org-element-property :begin parent))
22148 ? ))
22149 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22150 (match-string 0))
22151 (t ""))))
22152 (comment-block
22153 ;; Only fill contents if P is within block boundaries.
22154 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22155 (forward-line)
22156 (point)))
22157 (cend (save-excursion
22158 (goto-char (org-element-property :end element))
22159 (skip-chars-backward " \r\t\n")
22160 (line-beginning-position))))
22161 (when (and (>= p cbeg) (< p cend))
22162 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22163 (match-string 0)
22164 "")))))))))))
22166 (declare-function message-goto-body "message" ())
22167 (defvar message-cite-prefix-regexp) ; From message.el
22168 (defun org-fill-paragraph (&optional justify)
22169 "Fill element at point, when applicable.
22171 This function only applies to comment blocks, comments, example
22172 blocks and paragraphs. Also, as a special case, re-align table
22173 when point is at one.
22175 If JUSTIFY is non-nil (interactively, with prefix argument),
22176 justify as well. If `sentence-end-double-space' is non-nil, then
22177 period followed by one space does not end a sentence, so don't
22178 break a line there. The variable `fill-column' controls the
22179 width for filling.
22181 For convenience, when point is at a plain list, an item or
22182 a footnote definition, try to fill the first paragraph within."
22183 (interactive)
22184 (if (and (derived-mode-p 'message-mode)
22185 (or (not (message-in-body-p))
22186 (save-excursion (move-beginning-of-line 1)
22187 (looking-at message-cite-prefix-regexp))))
22188 ;; First ensure filling is correct in message-mode.
22189 (let ((fill-paragraph-function
22190 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22191 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22192 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22193 (paragraph-separate
22194 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22195 (fill-paragraph nil))
22196 (with-syntax-table org-mode-transpose-word-syntax-table
22197 ;; Move to end of line in order to get the first paragraph
22198 ;; within a plain list or a footnote definition.
22199 (let ((element (save-excursion
22200 (end-of-line)
22201 (or (ignore-errors (org-element-at-point))
22202 (user-error "An element cannot be parsed line %d"
22203 (line-number-at-pos (point)))))))
22204 ;; First check if point is in a blank line at the beginning of
22205 ;; the buffer. In that case, ignore filling.
22206 (case (org-element-type element)
22207 ;; Use major mode filling function is src blocks.
22208 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22209 ;; Align Org tables, leave table.el tables as-is.
22210 (table-row (org-table-align) t)
22211 (table
22212 (when (eq (org-element-property :type element) 'org)
22213 (save-excursion
22214 (goto-char (org-element-property :post-affiliated element))
22215 (org-table-align)))
22217 (paragraph
22218 ;; Paragraphs may contain `line-break' type objects.
22219 (let ((beg (max (point-min)
22220 (org-element-property :contents-begin element)))
22221 (end (min (point-max)
22222 (org-element-property :contents-end element))))
22223 ;; Do nothing if point is at an affiliated keyword.
22224 (if (< (line-end-position) beg) t
22225 (when (derived-mode-p 'message-mode)
22226 ;; In `message-mode', do not fill following citation
22227 ;; in current paragraph nor text before message body.
22228 (let ((body-start (save-excursion (message-goto-body))))
22229 (when body-start (setq beg (max body-start beg))))
22230 (when (save-excursion
22231 (re-search-forward
22232 (concat "^" message-cite-prefix-regexp) end t))
22233 (setq end (match-beginning 0))))
22234 ;; Fill paragraph, taking line breaks into account.
22235 ;; For that, slice the paragraph using line breaks as
22236 ;; separators, and fill the parts in reverse order to
22237 ;; avoid messing with markers.
22238 (save-excursion
22239 (goto-char end)
22240 (mapc
22241 (lambda (pos)
22242 (fill-region-as-paragraph pos (point) justify)
22243 (goto-char pos))
22244 ;; Find the list of ending positions for line breaks
22245 ;; in the current paragraph. Add paragraph
22246 ;; beginning to include first slice.
22247 (nreverse
22248 (cons beg
22249 (org-element-map
22250 (org-element--parse-objects
22251 beg end nil (org-element-restriction 'paragraph))
22252 'line-break
22253 (lambda (lb) (org-element-property :end lb)))))))
22254 t)))
22255 ;; Contents of `comment-block' type elements should be
22256 ;; filled as plain text, but only if point is within block
22257 ;; markers.
22258 (comment-block
22259 (let* ((case-fold-search t)
22260 (beg (save-excursion
22261 (goto-char (org-element-property :begin element))
22262 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22263 (forward-line)
22264 (point)))
22265 (end (save-excursion
22266 (goto-char (org-element-property :end element))
22267 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22268 (line-beginning-position))))
22269 (when (and (>= (point) beg) (< (point) end))
22270 (fill-region-as-paragraph
22271 (save-excursion
22272 (end-of-line)
22273 (re-search-backward "^[ \t]*$" beg 'move)
22274 (line-beginning-position))
22275 (save-excursion
22276 (beginning-of-line)
22277 (re-search-forward "^[ \t]*$" end 'move)
22278 (line-beginning-position))
22279 justify)))
22281 ;; Fill comments.
22282 (comment (fill-comment-paragraph justify))
22283 ;; Ignore every other element.
22284 (otherwise t))))))
22286 (defun org-auto-fill-function ()
22287 "Auto-fill function."
22288 ;; Check if auto-filling is meaningful.
22289 (let ((fc (current-fill-column)))
22290 (when (and fc (> (current-column) fc))
22291 (let* ((fill-prefix (org-adaptive-fill-function))
22292 ;; Enforce empty fill prefix, if required. Otherwise, it
22293 ;; will be computed again.
22294 (adaptive-fill-mode (not (equal fill-prefix ""))))
22295 (when fill-prefix (do-auto-fill))))))
22297 (defun org-comment-line-break-function (&optional soft)
22298 "Break line at point and indent, continuing comment if within one.
22299 The inserted newline is marked hard if variable
22300 `use-hard-newlines' is true, unless optional argument SOFT is
22301 non-nil."
22302 (if soft (insert-and-inherit ?\n) (newline 1))
22303 (save-excursion (forward-char -1) (delete-horizontal-space))
22304 (delete-horizontal-space)
22305 (indent-to-left-margin)
22306 (insert-before-markers-and-inherit fill-prefix))
22309 ;;; Comments
22311 ;; Org comments syntax is quite complex. It requires the entire line
22312 ;; to be just a comment. Also, even with the right syntax at the
22313 ;; beginning of line, some some elements (i.e. verse-block or
22314 ;; example-block) don't accept comments. Usual Emacs comment commands
22315 ;; cannot cope with those requirements. Therefore, Org replaces them.
22317 ;; Org still relies on `comment-dwim', but cannot trust
22318 ;; `comment-only-p'. So, `comment-region-function' and
22319 ;; `uncomment-region-function' both point
22320 ;; to`org-comment-or-uncomment-region'. Eventually,
22321 ;; `org-insert-comment' takes care of insertion of comments at the
22322 ;; beginning of line.
22324 ;; `org-setup-comments-handling' install comments related variables
22325 ;; during `org-mode' initialization.
22327 (defun org-setup-comments-handling ()
22328 (interactive)
22329 (org-set-local 'comment-use-syntax nil)
22330 (org-set-local 'comment-start "# ")
22331 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22332 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22333 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22334 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22336 (defun org-insert-comment ()
22337 "Insert an empty comment above current line.
22338 If the line is empty, insert comment at its beginning."
22339 (beginning-of-line)
22340 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22341 (org-indent-line)
22342 (insert "# "))
22344 (defvar comment-empty-lines) ; From newcomment.el.
22345 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22346 "Comment or uncomment each non-blank line in the region.
22347 Uncomment each non-blank line between BEG and END if it only
22348 contains commented lines. Otherwise, comment them."
22349 (save-restriction
22350 ;; Restrict region
22351 (narrow-to-region (save-excursion (goto-char beg)
22352 (skip-chars-forward " \r\t\n" end)
22353 (line-beginning-position))
22354 (save-excursion (goto-char end)
22355 (skip-chars-backward " \r\t\n" beg)
22356 (line-end-position)))
22357 (let ((uncommentp
22358 ;; UNCOMMENTP is non-nil when every non blank line between
22359 ;; BEG and END is a comment.
22360 (save-excursion
22361 (goto-char (point-min))
22362 (while (and (not (eobp))
22363 (let ((element (org-element-at-point)))
22364 (and (eq (org-element-type element) 'comment)
22365 (goto-char (min (point-max)
22366 (org-element-property
22367 :end element)))))))
22368 (eobp))))
22369 (if uncommentp
22370 ;; Only blank lines and comments in region: uncomment it.
22371 (save-excursion
22372 (goto-char (point-min))
22373 (while (not (eobp))
22374 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22375 (replace-match "" nil nil nil 1))
22376 (forward-line)))
22377 ;; Comment each line in region.
22378 (let ((min-indent (point-max)))
22379 ;; First find the minimum indentation across all lines.
22380 (save-excursion
22381 (goto-char (point-min))
22382 (while (and (not (eobp)) (not (zerop min-indent)))
22383 (unless (looking-at "[ \t]*$")
22384 (setq min-indent (min min-indent (current-indentation))))
22385 (forward-line)))
22386 ;; Then loop over all lines.
22387 (save-excursion
22388 (goto-char (point-min))
22389 (while (not (eobp))
22390 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22391 ;; Don't get fooled by invisible text (e.g. link path)
22392 ;; when moving to column MIN-INDENT.
22393 (let ((buffer-invisibility-spec nil))
22394 (org-move-to-column min-indent t))
22395 (insert comment-start))
22396 (forward-line))))))))
22399 ;;; Planning
22401 ;; This section contains tools to operate on timestamp objects, as
22402 ;; returned by, e.g. `org-element-context'.
22404 (defun org-timestamp-has-time-p (timestamp)
22405 "Non-nil when TIMESTAMP has a time specified."
22406 (org-element-property :hour-start timestamp))
22408 (defun org-timestamp-format (timestamp format &optional end utc)
22409 "Format a TIMESTAMP element into a string.
22411 FORMAT is a format specifier to be passed to
22412 `format-time-string'.
22414 When optional argument END is non-nil, use end of date-range or
22415 time-range, if possible.
22417 When optional argument UTC is non-nil, time will be expressed as
22418 Universal Time."
22419 (format-time-string
22420 format
22421 (apply 'encode-time
22422 (cons 0
22423 (mapcar
22424 (lambda (prop) (or (org-element-property prop timestamp) 0))
22425 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22426 '(:minute-start :hour-start :day-start :month-start
22427 :year-start)))))
22428 utc))
22430 (defun org-timestamp-split-range (timestamp &optional end)
22431 "Extract a timestamp object from a date or time range.
22433 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22434 the end of the range. Otherwise, extract its start.
22436 Return a new timestamp object sharing the same parent as
22437 TIMESTAMP."
22438 (let ((type (org-element-property :type timestamp)))
22439 (if (memq type '(active inactive diary)) timestamp
22440 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22441 ;; Set new type.
22442 (org-element-put-property
22443 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22444 ;; Copy start properties over end properties if END is
22445 ;; non-nil. Otherwise, copy end properties over `start' ones.
22446 (let ((p-alist '((:minute-start . :minute-end)
22447 (:hour-start . :hour-end)
22448 (:day-start . :day-end)
22449 (:month-start . :month-end)
22450 (:year-start . :year-end))))
22451 (dolist (p-cell p-alist)
22452 (org-element-put-property
22453 split-ts
22454 (funcall (if end 'car 'cdr) p-cell)
22455 (org-element-property
22456 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22457 ;; Eventually refresh `:raw-value'.
22458 (org-element-put-property split-ts :raw-value nil)
22459 (org-element-put-property
22460 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22462 (defun org-timestamp-translate (timestamp &optional boundary)
22463 "Apply `org-translate-time' on a TIMESTAMP object.
22464 When optional argument BOUNDARY is non-nil, it is either the
22465 symbol `start' or `end'. In this case, only translate the
22466 starting or ending part of TIMESTAMP if it is a date or time
22467 range. Otherwise, translate both parts."
22468 (if (and (not boundary)
22469 (memq (org-element-property :type timestamp)
22470 '(active-range inactive-range)))
22471 (concat
22472 (org-translate-time
22473 (org-element-property :raw-value
22474 (org-timestamp-split-range timestamp)))
22475 "--"
22476 (org-translate-time
22477 (org-element-property :raw-value
22478 (org-timestamp-split-range timestamp t))))
22479 (org-translate-time
22480 (org-element-property
22481 :raw-value
22482 (if (not boundary) timestamp
22483 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22487 ;;; Other stuff.
22489 (defun org-toggle-fixed-width-section (arg)
22490 "Toggle the fixed-width export.
22491 If there is no active region, the QUOTE keyword at the current headline is
22492 inserted or removed. When present, it causes the text between this headline
22493 and the next to be exported as fixed-width text, and unmodified.
22494 If there is an active region, this command adds or removes a colon as the
22495 first character of this line. If the first character of a line is a colon,
22496 this line is also exported in fixed-width font."
22497 (interactive "P")
22498 (let* ((cc 0)
22499 (regionp (org-region-active-p))
22500 (beg (if regionp (region-beginning) (point)))
22501 (end (if regionp (region-end)))
22502 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22503 (case-fold-search nil)
22504 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22505 off)
22506 (if regionp
22507 (save-excursion
22508 (goto-char beg)
22509 (setq cc (current-column))
22510 (beginning-of-line 1)
22511 (setq off (looking-at re))
22512 (while (> nlines 0)
22513 (setq nlines (1- nlines))
22514 (beginning-of-line 1)
22515 (cond
22516 (arg
22517 (org-move-to-column cc t)
22518 (insert ": \n")
22519 (forward-line -1))
22520 ((and off (looking-at re))
22521 (replace-match "" t t nil 1))
22522 ((not off) (org-move-to-column cc t) (insert ": ")))
22523 (forward-line 1)))
22524 (save-excursion
22525 (org-back-to-heading)
22526 (cond
22527 ((looking-at (format org-heading-keyword-regexp-format
22528 org-quote-string))
22529 (goto-char (match-end 1))
22530 (looking-at (concat " +" org-quote-string))
22531 (replace-match "" t t)
22532 (when (eolp) (insert " ")))
22533 ((looking-at org-outline-regexp)
22534 (goto-char (match-end 0))
22535 (insert org-quote-string " ")))))))
22537 (defun org-reftex-citation ()
22538 "Use reftex-citation to insert a citation into the buffer.
22539 This looks for a line like
22541 #+BIBLIOGRAPHY: foo plain option:-d
22543 and derives from it that foo.bib is the bibliography file relevant
22544 for this document. It then installs the necessary environment for RefTeX
22545 to work in this buffer and calls `reftex-citation' to insert a citation
22546 into the buffer.
22548 Export of such citations to both LaTeX and HTML is handled by the contributed
22549 package org-exp-bibtex by Taru Karttunen."
22550 (interactive)
22551 (let ((reftex-docstruct-symbol 'rds)
22552 (reftex-cite-format "\\cite{%l}")
22553 rds bib)
22554 (save-excursion
22555 (save-restriction
22556 (widen)
22557 (let ((case-fold-search t)
22558 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22559 (if (not (save-excursion
22560 (or (re-search-forward re nil t)
22561 (re-search-backward re nil t))))
22562 (error "No bibliography defined in file")
22563 (setq bib (concat (match-string 1) ".bib")
22564 rds (list (list 'bib bib)))))))
22565 (call-interactively 'reftex-citation)))
22567 ;;;; Functions extending outline functionality
22569 (defun org-beginning-of-line (&optional arg)
22570 "Go to the beginning of the current line. If that is invisible, continue
22571 to a visible line beginning. This makes the function of C-a more intuitive.
22572 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22573 first attempt, and only move to after the tags when the cursor is already
22574 beyond the end of the headline."
22575 (interactive "P")
22576 (let ((pos (point))
22577 (special (if (consp org-special-ctrl-a/e)
22578 (car org-special-ctrl-a/e)
22579 org-special-ctrl-a/e))
22580 refpos)
22581 (if (org-bound-and-true-p visual-line-mode)
22582 (beginning-of-visual-line 1)
22583 (beginning-of-line 1))
22584 (if (and arg (fboundp 'move-beginning-of-line))
22585 (call-interactively 'move-beginning-of-line)
22586 (if (bobp)
22588 (backward-char 1)
22589 (if (org-truely-invisible-p)
22590 (while (and (not (bobp)) (org-truely-invisible-p))
22591 (backward-char 1)
22592 (beginning-of-line 1))
22593 (forward-char 1))))
22594 (when special
22595 (cond
22596 ((and (looking-at org-complex-heading-regexp)
22597 (= (char-after (match-end 1)) ?\ ))
22598 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22599 (point-at-eol)))
22600 (goto-char
22601 (if (eq special t)
22602 (cond ((> pos refpos) refpos)
22603 ((= pos (point)) refpos)
22604 (t (point)))
22605 (cond ((> pos (point)) (point))
22606 ((not (eq last-command this-command)) (point))
22607 (t refpos)))))
22608 ((org-at-item-p)
22609 ;; Being at an item and not looking at an the item means point
22610 ;; was previously moved to beginning of a visual line, which
22611 ;; doesn't contain the item. Therefore, do nothing special,
22612 ;; just stay here.
22613 (when (looking-at org-list-full-item-re)
22614 ;; Set special position at first white space character after
22615 ;; bullet, and check-box, if any.
22616 (let ((after-bullet
22617 (let ((box (match-end 3)))
22618 (if (not box) (match-end 1)
22619 (let ((after (char-after box)))
22620 (if (and after (= after ? )) (1+ box) box))))))
22621 ;; Special case: Move point to special position when
22622 ;; currently after it or at beginning of line.
22623 (if (eq special t)
22624 (when (or (> pos after-bullet) (= (point) pos))
22625 (goto-char after-bullet))
22626 ;; Reversed case: Move point to special position when
22627 ;; point was already at beginning of line and command is
22628 ;; repeated.
22629 (when (and (= (point) pos) (eq last-command this-command))
22630 (goto-char after-bullet))))))))
22631 (org-no-warnings
22632 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22634 (defun org-end-of-line (&optional arg)
22635 "Go to the end of the line.
22636 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22637 tags on the first attempt, and only move to after the tags when
22638 the cursor is already beyond the end of the headline."
22639 (interactive "P")
22640 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22641 org-special-ctrl-a/e))
22642 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22643 'end-of-visual-line)
22644 ((fboundp 'move-end-of-line) 'move-end-of-line)
22645 (t 'end-of-line))))
22646 (if (or (not special) arg) (call-interactively move-fun)
22647 (let* ((element (save-excursion (beginning-of-line)
22648 (org-element-at-point)))
22649 (type (org-element-type element)))
22650 (cond
22651 ((memq type '(headline inlinetask))
22652 (let ((pos (point)))
22653 (beginning-of-line 1)
22654 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22655 (if (eq special t)
22656 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22657 (goto-char (match-beginning 1))
22658 (goto-char (match-end 0)))
22659 (if (or (< pos (match-end 0))
22660 (not (eq this-command last-command)))
22661 (goto-char (match-end 0))
22662 (goto-char (match-beginning 1))))
22663 (call-interactively move-fun))))
22664 ((org-element-property :hiddenp element)
22665 ;; If element is hidden, `move-end-of-line' would put point
22666 ;; after it. Use `end-of-line' to stay on current line.
22667 (call-interactively 'end-of-line))
22668 (t (call-interactively move-fun)))))
22669 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22671 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22672 (define-key org-mode-map "\C-e" 'org-end-of-line)
22674 (defun org-backward-sentence (&optional arg)
22675 "Go to beginning of sentence, or beginning of table field.
22676 This will call `backward-sentence' or `org-table-beginning-of-field',
22677 depending on context."
22678 (interactive "P")
22679 (cond
22680 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22681 (t (call-interactively 'backward-sentence))))
22683 (defun org-forward-sentence (&optional arg)
22684 "Go to end of sentence, or end of table field.
22685 This will call `forward-sentence' or `org-table-end-of-field',
22686 depending on context."
22687 (interactive "P")
22688 (cond
22689 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22690 (t (call-interactively 'forward-sentence))))
22692 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22693 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22695 (defun org-kill-line (&optional arg)
22696 "Kill line, to tags or end of line."
22697 (interactive "P")
22698 (cond
22699 ((or (not org-special-ctrl-k)
22700 (bolp)
22701 (not (org-at-heading-p)))
22702 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22703 org-ctrl-k-protect-subtree)
22704 (if (or (eq org-ctrl-k-protect-subtree 'error)
22705 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22706 (user-error "C-k aborted as it would kill a hidden subtree")))
22707 (call-interactively
22708 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22709 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22710 (kill-region (point) (match-beginning 1))
22711 (org-set-tags nil t))
22712 (t (kill-region (point) (point-at-eol)))))
22714 (define-key org-mode-map "\C-k" 'org-kill-line)
22716 (defun org-yank (&optional arg)
22717 "Yank. If the kill is a subtree, treat it specially.
22718 This command will look at the current kill and check if is a single
22719 subtree, or a series of subtrees[1]. If it passes the test, and if the
22720 cursor is at the beginning of a line or after the stars of a currently
22721 empty headline, then the yank is handled specially. How exactly depends
22722 on the value of the following variables, both set by default.
22724 org-yank-folded-subtrees
22725 When set, the subtree(s) will be folded after insertion, but only
22726 if doing so would now swallow text after the yanked text.
22728 org-yank-adjusted-subtrees
22729 When set, the subtree will be promoted or demoted in order to
22730 fit into the local outline tree structure, which means that the level
22731 will be adjusted so that it becomes the smaller one of the two
22732 *visible* surrounding headings.
22734 Any prefix to this command will cause `yank' to be called directly with
22735 no special treatment. In particular, a simple \\[universal-argument] prefix \
22736 will just
22737 plainly yank the text as it is.
22739 \[1] The test checks if the first non-white line is a heading
22740 and if there are no other headings with fewer stars."
22741 (interactive "P")
22742 (org-yank-generic 'yank arg))
22744 (defun org-yank-generic (command arg)
22745 "Perform some yank-like command.
22747 This function implements the behavior described in the `org-yank'
22748 documentation. However, it has been generalized to work for any
22749 interactive command with similar behavior."
22751 ;; pretend to be command COMMAND
22752 (setq this-command command)
22754 (if arg
22755 (call-interactively command)
22757 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22758 (and (org-kill-is-subtree-p)
22759 (or (bolp)
22760 (and (looking-at "[ \t]*$")
22761 (string-match
22762 "\\`\\*+\\'"
22763 (buffer-substring (point-at-bol) (point)))))))
22764 swallowp)
22765 (cond
22766 ((and subtreep org-yank-folded-subtrees)
22767 (let ((beg (point))
22768 end)
22769 (if (and subtreep org-yank-adjusted-subtrees)
22770 (org-paste-subtree nil nil 'for-yank)
22771 (call-interactively command))
22773 (setq end (point))
22774 (goto-char beg)
22775 (when (and (bolp) subtreep
22776 (not (setq swallowp
22777 (org-yank-folding-would-swallow-text beg end))))
22778 (org-with-limited-levels
22779 (or (looking-at org-outline-regexp)
22780 (re-search-forward org-outline-regexp-bol end t))
22781 (while (and (< (point) end) (looking-at org-outline-regexp))
22782 (hide-subtree)
22783 (org-cycle-show-empty-lines 'folded)
22784 (condition-case nil
22785 (outline-forward-same-level 1)
22786 (error (goto-char end))))))
22787 (when swallowp
22788 (message
22789 "Inserted text not folded because that would swallow text"))
22791 (goto-char end)
22792 (skip-chars-forward " \t\n\r")
22793 (beginning-of-line 1)
22794 (push-mark beg 'nomsg)))
22795 ((and subtreep org-yank-adjusted-subtrees)
22796 (let ((beg (point-at-bol)))
22797 (org-paste-subtree nil nil 'for-yank)
22798 (push-mark beg 'nomsg)))
22800 (call-interactively command))))))
22802 (defun org-yank-folding-would-swallow-text (beg end)
22803 "Would hide-subtree at BEG swallow any text after END?"
22804 (let (level)
22805 (org-with-limited-levels
22806 (save-excursion
22807 (goto-char beg)
22808 (when (or (looking-at org-outline-regexp)
22809 (re-search-forward org-outline-regexp-bol end t))
22810 (setq level (org-outline-level)))
22811 (goto-char end)
22812 (skip-chars-forward " \t\r\n\v\f")
22813 (if (or (eobp)
22814 (and (bolp) (looking-at org-outline-regexp)
22815 (<= (org-outline-level) level)))
22816 nil ; Nothing would be swallowed
22817 t))))) ; something would swallow
22819 (define-key org-mode-map "\C-y" 'org-yank)
22821 (defun org-truely-invisible-p ()
22822 "Check if point is at a character currently not visible.
22823 This version does not only check the character property, but also
22824 `visible-mode'."
22825 ;; Early versions of noutline don't have `outline-invisible-p'.
22826 (if (org-bound-and-true-p visible-mode)
22828 (outline-invisible-p)))
22830 (defun org-invisible-p2 ()
22831 "Check if point is at a character currently not visible."
22832 (save-excursion
22833 (if (and (eolp) (not (bobp))) (backward-char 1))
22834 ;; Early versions of noutline don't have `outline-invisible-p'.
22835 (outline-invisible-p)))
22837 (defun org-back-to-heading (&optional invisible-ok)
22838 "Call `outline-back-to-heading', but provide a better error message."
22839 (condition-case nil
22840 (outline-back-to-heading invisible-ok)
22841 (error (error "Before first headline at position %d in buffer %s"
22842 (point) (current-buffer)))))
22844 (defun org-before-first-heading-p ()
22845 "Before first heading?"
22846 (save-excursion
22847 (end-of-line)
22848 (null (re-search-backward org-outline-regexp-bol nil t))))
22850 (defun org-at-heading-p (&optional ignored)
22851 (outline-on-heading-p t))
22852 ;; Compatibility alias with Org versions < 7.8.03
22853 (defalias 'org-on-heading-p 'org-at-heading-p)
22855 (defun org-at-comment-p nil
22856 "Is cursor in a line starting with a # character?"
22857 (save-excursion
22858 (beginning-of-line)
22859 (looking-at "^#")))
22861 (defun org-at-drawer-p nil
22862 "Is cursor at a drawer keyword?"
22863 (save-excursion
22864 (move-beginning-of-line 1)
22865 (looking-at org-drawer-regexp)))
22867 (defun org-at-block-p nil
22868 "Is cursor at a block keyword?"
22869 (save-excursion
22870 (move-beginning-of-line 1)
22871 (looking-at org-block-regexp)))
22873 (defun org-point-at-end-of-empty-headline ()
22874 "If point is at the end of an empty headline, return t, else nil.
22875 If the heading only contains a TODO keyword, it is still still considered
22876 empty."
22877 (and (looking-at "[ \t]*$")
22878 (when org-todo-line-regexp
22879 (save-excursion
22880 (beginning-of-line 1)
22881 (let ((case-fold-search nil))
22882 (looking-at org-todo-line-regexp)
22883 (string= (match-string 3) ""))))))
22885 (defun org-at-heading-or-item-p ()
22886 (or (org-at-heading-p) (org-at-item-p)))
22888 (defun org-at-target-p ()
22889 (or (org-in-regexp org-radio-target-regexp)
22890 (org-in-regexp org-target-regexp)))
22891 ;; Compatibility alias with Org versions < 7.8.03
22892 (defalias 'org-on-target-p 'org-at-target-p)
22894 (defun org-up-heading-all (arg)
22895 "Move to the heading line of which the present line is a subheading.
22896 This function considers both visible and invisible heading lines.
22897 With argument, move up ARG levels."
22898 (if (fboundp 'outline-up-heading-all)
22899 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22900 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22902 (defun org-up-heading-safe ()
22903 "Move to the heading line of which the present line is a subheading.
22904 This version will not throw an error. It will return the level of the
22905 headline found, or nil if no higher level is found.
22907 Also, this function will be a lot faster than `outline-up-heading',
22908 because it relies on stars being the outline starters. This can really
22909 make a significant difference in outlines with very many siblings."
22910 (let (start-level re)
22911 (org-back-to-heading t)
22912 (setq start-level (funcall outline-level))
22913 (if (equal start-level 1)
22915 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22916 (if (re-search-backward re nil t)
22917 (funcall outline-level)))))
22919 (defun org-first-sibling-p ()
22920 "Is this heading the first child of its parents?"
22921 (interactive)
22922 (let ((re org-outline-regexp-bol)
22923 level l)
22924 (unless (org-at-heading-p t)
22925 (user-error "Not at a heading"))
22926 (setq level (funcall outline-level))
22927 (save-excursion
22928 (if (not (re-search-backward re nil t))
22930 (setq l (funcall outline-level))
22931 (< l level)))))
22933 (defun org-goto-sibling (&optional previous)
22934 "Goto the next sibling, even if it is invisible.
22935 When PREVIOUS is set, go to the previous sibling instead. Returns t
22936 when a sibling was found. When none is found, return nil and don't
22937 move point."
22938 (let ((fun (if previous 're-search-backward 're-search-forward))
22939 (pos (point))
22940 (re org-outline-regexp-bol)
22941 level l)
22942 (when (condition-case nil (org-back-to-heading t) (error nil))
22943 (setq level (funcall outline-level))
22944 (catch 'exit
22945 (or previous (forward-char 1))
22946 (while (funcall fun re nil t)
22947 (setq l (funcall outline-level))
22948 (when (< l level) (goto-char pos) (throw 'exit nil))
22949 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22950 (goto-char pos)
22951 nil))))
22953 (defun org-show-siblings ()
22954 "Show all siblings of the current headline."
22955 (save-excursion
22956 (while (org-goto-sibling) (org-flag-heading nil)))
22957 (save-excursion
22958 (while (org-goto-sibling 'previous)
22959 (org-flag-heading nil))))
22961 (defun org-goto-first-child ()
22962 "Goto the first child, even if it is invisible.
22963 Return t when a child was found. Otherwise don't move point and
22964 return nil."
22965 (let (level (pos (point)) (re org-outline-regexp-bol))
22966 (when (condition-case nil (org-back-to-heading t) (error nil))
22967 (setq level (outline-level))
22968 (forward-char 1)
22969 (if (and (re-search-forward re nil t) (> (outline-level) level))
22970 (progn (goto-char (match-beginning 0)) t)
22971 (goto-char pos) nil))))
22973 (defun org-show-hidden-entry ()
22974 "Show an entry where even the heading is hidden."
22975 (save-excursion
22976 (org-show-entry)))
22978 (defun org-flag-heading (flag &optional entry)
22979 "Flag the current heading. FLAG non-nil means make invisible.
22980 When ENTRY is non-nil, show the entire entry."
22981 (save-excursion
22982 (org-back-to-heading t)
22983 ;; Check if we should show the entire entry
22984 (if entry
22985 (progn
22986 (org-show-entry)
22987 (save-excursion
22988 (and (outline-next-heading)
22989 (org-flag-heading nil))))
22990 (outline-flag-region (max (point-min) (1- (point)))
22991 (save-excursion (outline-end-of-heading) (point))
22992 flag))))
22994 (defun org-get-next-sibling ()
22995 "Move to next heading of the same level, and return point.
22996 If there is no such heading, return nil.
22997 This is like outline-next-sibling, but invisible headings are ok."
22998 (let ((level (funcall outline-level)))
22999 (outline-next-heading)
23000 (while (and (not (eobp)) (> (funcall outline-level) level))
23001 (outline-next-heading))
23002 (if (or (eobp) (< (funcall outline-level) level))
23004 (point))))
23006 (defun org-get-last-sibling ()
23007 "Move to previous heading of the same level, and return point.
23008 If there is no such heading, return nil."
23009 (let ((opoint (point))
23010 (level (funcall outline-level)))
23011 (outline-previous-heading)
23012 (when (and (/= (point) opoint) (outline-on-heading-p t))
23013 (while (and (> (funcall outline-level) level)
23014 (not (bobp)))
23015 (outline-previous-heading))
23016 (if (< (funcall outline-level) level)
23018 (point)))))
23020 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23021 "Goto to the end of a subtree."
23022 ;; This contains an exact copy of the original function, but it uses
23023 ;; `org-back-to-heading', to make it work also in invisible
23024 ;; trees. And is uses an invisible-ok argument.
23025 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23026 ;; Furthermore, when used inside Org, finding the end of a large subtree
23027 ;; with many children and grandchildren etc, this can be much faster
23028 ;; than the outline version.
23029 (org-back-to-heading invisible-ok)
23030 (let ((first t)
23031 (level (funcall outline-level)))
23032 (if (and (derived-mode-p 'org-mode) (< level 1000))
23033 ;; A true heading (not a plain list item), in Org-mode
23034 ;; This means we can easily find the end by looking
23035 ;; only for the right number of stars. Using a regexp to do
23036 ;; this is so much faster than using a Lisp loop.
23037 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23038 (forward-char 1)
23039 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23040 ;; something else, do it the slow way
23041 (while (and (not (eobp))
23042 (or first (> (funcall outline-level) level)))
23043 (setq first nil)
23044 (outline-next-heading)))
23045 (unless to-heading
23046 (if (memq (preceding-char) '(?\n ?\^M))
23047 (progn
23048 ;; Go to end of line before heading
23049 (forward-char -1)
23050 (if (memq (preceding-char) '(?\n ?\^M))
23051 ;; leave blank line before heading
23052 (forward-char -1))))))
23053 (point))
23055 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23056 "Use Org version in org-mode, for dramatic speed-up."
23057 (if (derived-mode-p 'org-mode)
23058 (progn
23059 (org-end-of-subtree nil t)
23060 (unless (eobp) (backward-char 1)))
23061 ad-do-it))
23063 (defun org-end-of-meta-data-and-drawers ()
23064 "Jump to the first text after meta data and drawers in the current entry.
23065 This will move over empty lines, lines with planning time stamps,
23066 clocking lines, and drawers."
23067 (org-back-to-heading t)
23068 (let ((end (save-excursion (outline-next-heading) (point)))
23069 (re (concat "\\(" org-drawer-regexp "\\)"
23070 "\\|" "[ \t]*" org-keyword-time-regexp)))
23071 (forward-line 1)
23072 (while (re-search-forward re end t)
23073 (if (not (match-end 1))
23074 ;; empty or planning line
23075 (forward-line 1)
23076 ;; a drawer, find the end
23077 (re-search-forward "^[ \t]*:END:" end 'move)
23078 (forward-line 1)))
23079 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23080 (point)))
23082 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23083 "Move forward to the ARG'th subheading at same level as this one.
23084 Stop at the first and last subheadings of a superior heading.
23085 Normally this only looks at visible headings, but when INVISIBLE-OK is
23086 non-nil it will also look at invisible ones."
23087 (interactive "p")
23088 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23089 (if (and arg (< arg 0))
23090 (goto-char (point-min))
23091 (outline-next-heading))
23092 (org-at-heading-p)
23093 (let ((level (- (match-end 0) (match-beginning 0) 1))
23094 (f (if (and arg (< arg 0))
23095 're-search-backward
23096 're-search-forward))
23097 (count (if arg (abs arg) 1))
23098 (result (point)))
23099 (while (and (prog1 (> count 0)
23100 (forward-char (if (and arg (< arg 0)) -1 1)))
23101 (funcall f org-outline-regexp-bol nil 'move))
23102 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23103 (cond ((< l level) (setq count 0))
23104 ((and (= l level)
23105 (or invisible-ok
23106 (progn
23107 (goto-char (line-beginning-position))
23108 (not (outline-invisible-p)))))
23109 (setq count (1- count))
23110 (when (eq l level)
23111 (setq result (point)))))))
23112 (goto-char result))
23113 (beginning-of-line 1)))
23115 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23116 "Move backward to the ARG'th subheading at same level as this one.
23117 Stop at the first and last subheadings of a superior heading."
23118 (interactive "p")
23119 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23121 (defun org-next-block (arg &optional backward block-regexp)
23122 "Jump to the next block.
23123 With a prefix argument ARG, jump forward ARG many source blocks.
23124 When BACKWARD is non-nil, jump to the previous block.
23125 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23126 (interactive "p")
23127 (let ((re (or block-regexp org-block-regexp))
23128 (re-search-fn (or (and backward 're-search-backward)
23129 're-search-forward)))
23130 (if (looking-at re) (forward-char 1))
23131 (condition-case nil
23132 (funcall re-search-fn re nil nil arg)
23133 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23134 (goto-char (match-beginning 0)) (org-show-context)))
23136 (defun org-previous-block (arg &optional block-regexp)
23137 "Jump to the previous block.
23138 With a prefix argument ARG, jump backward ARG many source blocks.
23139 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23140 (interactive "p")
23141 (org-next-block arg t block-regexp))
23143 (defun org-forward-element ()
23144 "Move forward by one element.
23145 Move to the next element at the same level, when possible."
23146 (interactive)
23147 (cond ((eobp) (user-error "Cannot move further down"))
23148 ((org-with-limited-levels (org-at-heading-p))
23149 (let ((origin (point)))
23150 (goto-char (org-end-of-subtree nil t))
23151 (unless (org-with-limited-levels (org-at-heading-p))
23152 (goto-char origin)
23153 (user-error "Cannot move further down"))))
23155 (let* ((elem (org-element-at-point))
23156 (end (org-element-property :end elem))
23157 (parent (org-element-property :parent elem)))
23158 (if (and parent (= (org-element-property :contents-end parent) end))
23159 (goto-char (org-element-property :end parent))
23160 (goto-char end))))))
23162 (defun org-backward-element ()
23163 "Move backward by one element.
23164 Move to the previous element at the same level, when possible."
23165 (interactive)
23166 (cond ((bobp) (user-error "Cannot move further up"))
23167 ((org-with-limited-levels (org-at-heading-p))
23168 ;; At a headline, move to the previous one, if any, or stay
23169 ;; here.
23170 (let ((origin (point)))
23171 (org-with-limited-levels (org-backward-heading-same-level 1))
23172 ;; When current headline has no sibling above, move to its
23173 ;; parent.
23174 (when (= (point) origin)
23175 (or (org-with-limited-levels (org-up-heading-safe))
23176 (progn (goto-char origin)
23177 (user-error "Cannot move further up"))))))
23179 (let* ((trail (org-element-at-point 'keep-trail))
23180 (elem (car trail))
23181 (prev-elem (nth 1 trail))
23182 (beg (org-element-property :begin elem)))
23183 (cond
23184 ;; Move to beginning of current element if point isn't
23185 ;; there already.
23186 ((/= (point) beg) (goto-char beg))
23187 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23188 ((org-before-first-heading-p) (goto-char (point-min)))
23189 (t (org-back-to-heading)))))))
23191 (defun org-up-element ()
23192 "Move to upper element."
23193 (interactive)
23194 (if (org-with-limited-levels (org-at-heading-p))
23195 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23196 (let* ((elem (org-element-at-point))
23197 (parent (org-element-property :parent elem)))
23198 (if parent (goto-char (org-element-property :begin parent))
23199 (if (org-with-limited-levels (org-before-first-heading-p))
23200 (user-error "No surrounding element")
23201 (org-with-limited-levels (org-back-to-heading)))))))
23203 (defvar org-element-greater-elements)
23204 (defun org-down-element ()
23205 "Move to inner element."
23206 (interactive)
23207 (let ((element (org-element-at-point)))
23208 (cond
23209 ((memq (org-element-type element) '(plain-list table))
23210 (goto-char (org-element-property :contents-begin element))
23211 (forward-char))
23212 ((memq (org-element-type element) org-element-greater-elements)
23213 ;; If contents are hidden, first disclose them.
23214 (when (org-element-property :hiddenp element) (org-cycle))
23215 (goto-char (or (org-element-property :contents-begin element)
23216 (user-error "No content for this element"))))
23217 (t (user-error "No inner element")))))
23219 (defun org-drag-element-backward ()
23220 "Move backward element at point."
23221 (interactive)
23222 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23223 (let* ((trail (org-element-at-point 'keep-trail))
23224 (elem (car trail))
23225 (prev-elem (nth 1 trail)))
23226 ;; Error out if no previous element or previous element is
23227 ;; a parent of the current one.
23228 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23229 (user-error "Cannot drag element backward")
23230 (let ((pos (point)))
23231 (org-element-swap-A-B prev-elem elem)
23232 (goto-char (+ (org-element-property :begin prev-elem)
23233 (- pos (org-element-property :begin elem)))))))))
23235 (defun org-drag-element-forward ()
23236 "Move forward element at point."
23237 (interactive)
23238 (let* ((pos (point))
23239 (elem (org-element-at-point)))
23240 (when (= (point-max) (org-element-property :end elem))
23241 (user-error "Cannot drag element forward"))
23242 (goto-char (org-element-property :end elem))
23243 (let ((next-elem (org-element-at-point)))
23244 (when (or (org-element-nested-p elem next-elem)
23245 (and (eq (org-element-type next-elem) 'headline)
23246 (not (eq (org-element-type elem) 'headline))))
23247 (goto-char pos)
23248 (user-error "Cannot drag element forward"))
23249 ;; Compute new position of point: it's shifted by NEXT-ELEM
23250 ;; body's length (without final blanks) and by the length of
23251 ;; blanks between ELEM and NEXT-ELEM.
23252 (let ((size-next (- (save-excursion
23253 (goto-char (org-element-property :end next-elem))
23254 (skip-chars-backward " \r\t\n")
23255 (forward-line)
23256 ;; Small correction if buffer doesn't end
23257 ;; with a newline character.
23258 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23259 (org-element-property :begin next-elem)))
23260 (size-blank (- (org-element-property :end elem)
23261 (save-excursion
23262 (goto-char (org-element-property :end elem))
23263 (skip-chars-backward " \r\t\n")
23264 (forward-line)
23265 (point)))))
23266 (org-element-swap-A-B elem next-elem)
23267 (goto-char (+ pos size-next size-blank))))))
23269 (defun org-drag-line-forward (arg)
23270 "Drag the line at point ARG lines forward."
23271 (interactive "p")
23272 (dotimes (n (abs arg))
23273 (let ((c (current-column)))
23274 (if (< 0 arg)
23275 (progn
23276 (beginning-of-line 2)
23277 (transpose-lines 1)
23278 (beginning-of-line 0))
23279 (transpose-lines 1)
23280 (beginning-of-line -1))
23281 (org-move-to-column c))))
23283 (defun org-drag-line-backward (arg)
23284 "Drag the line at point ARG lines backward."
23285 (interactive "p")
23286 (org-drag-line-forward (- arg)))
23288 (defun org-mark-element ()
23289 "Put point at beginning of this element, mark at end.
23291 Interactively, if this command is repeated or (in Transient Mark
23292 mode) if the mark is active, it marks the next element after the
23293 ones already marked."
23294 (interactive)
23295 (let (deactivate-mark)
23296 (if (and (org-called-interactively-p 'any)
23297 (or (and (eq last-command this-command) (mark t))
23298 (and transient-mark-mode mark-active)))
23299 (set-mark
23300 (save-excursion
23301 (goto-char (mark))
23302 (goto-char (org-element-property :end (org-element-at-point)))))
23303 (let ((element (org-element-at-point)))
23304 (end-of-line)
23305 (push-mark (org-element-property :end element) t t)
23306 (goto-char (org-element-property :begin element))))))
23308 (defun org-narrow-to-element ()
23309 "Narrow buffer to current element."
23310 (interactive)
23311 (let ((elem (org-element-at-point)))
23312 (cond
23313 ((eq (car elem) 'headline)
23314 (narrow-to-region
23315 (org-element-property :begin elem)
23316 (org-element-property :end elem)))
23317 ((memq (car elem) org-element-greater-elements)
23318 (narrow-to-region
23319 (org-element-property :contents-begin elem)
23320 (org-element-property :contents-end elem)))
23322 (narrow-to-region
23323 (org-element-property :begin elem)
23324 (org-element-property :end elem))))))
23326 (defun org-transpose-element ()
23327 "Transpose current and previous elements, keeping blank lines between.
23328 Point is moved after both elements."
23329 (interactive)
23330 (org-skip-whitespace)
23331 (let ((end (org-element-property :end (org-element-at-point))))
23332 (org-drag-element-backward)
23333 (goto-char end)))
23335 (defun org-unindent-buffer ()
23336 "Un-indent the visible part of the buffer.
23337 Relative indentation (between items, inside blocks, etc.) isn't
23338 modified."
23339 (interactive)
23340 (unless (eq major-mode 'org-mode)
23341 (user-error "Cannot un-indent a buffer not in Org mode"))
23342 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23343 unindent-tree ; For byte-compiler.
23344 (unindent-tree
23345 (function
23346 (lambda (contents)
23347 (mapc
23348 (lambda (element)
23349 (if (memq (org-element-type element) '(headline section))
23350 (funcall unindent-tree (org-element-contents element))
23351 (save-excursion
23352 (save-restriction
23353 (narrow-to-region
23354 (org-element-property :begin element)
23355 (org-element-property :end element))
23356 (org-do-remove-indentation)))))
23357 (reverse contents))))))
23358 (funcall unindent-tree (org-element-contents parse-tree))))
23360 (defun org-show-subtree ()
23361 "Show everything after this heading at deeper levels."
23362 (interactive)
23363 (outline-flag-region
23364 (point)
23365 (save-excursion
23366 (org-end-of-subtree t t))
23367 nil))
23369 (defun org-show-entry ()
23370 "Show the body directly following this heading.
23371 Show the heading too, if it is currently invisible."
23372 (interactive)
23373 (save-excursion
23374 (condition-case nil
23375 (progn
23376 (org-back-to-heading t)
23377 (outline-flag-region
23378 (max (point-min) (1- (point)))
23379 (save-excursion
23380 (if (re-search-forward
23381 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23382 (match-beginning 1)
23383 (point-max)))
23384 nil)
23385 (org-cycle-hide-drawers 'children))
23386 (error nil))))
23388 (defun org-make-options-regexp (kwds &optional extra)
23389 "Make a regular expression for keyword lines."
23390 (concat
23391 "^#\\+\\("
23392 (mapconcat 'regexp-quote kwds "\\|")
23393 (if extra (concat "\\|" extra))
23394 "\\):[ \t]*\\(.*\\)"))
23396 ;; Make isearch reveal the necessary context
23397 (defun org-isearch-end ()
23398 "Reveal context after isearch exits."
23399 (when isearch-success ; only if search was successful
23400 (if (featurep 'xemacs)
23401 ;; Under XEmacs, the hook is run in the correct place,
23402 ;; we directly show the context.
23403 (org-show-context 'isearch)
23404 ;; In Emacs the hook runs *before* restoring the overlays.
23405 ;; So we have to use a one-time post-command-hook to do this.
23406 ;; (Emacs 22 has a special variable, see function `org-mode')
23407 (unless (and (boundp 'isearch-mode-end-hook-quit)
23408 isearch-mode-end-hook-quit)
23409 ;; Only when the isearch was not quitted.
23410 (org-add-hook 'post-command-hook 'org-isearch-post-command
23411 'append 'local)))
23412 (org-fix-ellipsis-at-bol)))
23414 (defun org-isearch-post-command ()
23415 "Remove self from hook, and show context."
23416 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23417 (org-show-context 'isearch))
23420 ;;;; Integration with and fixes for other packages
23422 ;;; Imenu support
23424 (defvar org-imenu-markers nil
23425 "All markers currently used by Imenu.")
23426 (make-variable-buffer-local 'org-imenu-markers)
23428 (defun org-imenu-new-marker (&optional pos)
23429 "Return a new marker for use by Imenu, and remember the marker."
23430 (let ((m (make-marker)))
23431 (move-marker m (or pos (point)))
23432 (push m org-imenu-markers)
23435 (defun org-imenu-get-tree ()
23436 "Produce the index for Imenu."
23437 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23438 (setq org-imenu-markers nil)
23439 (let* ((n org-imenu-depth)
23440 (re (concat "^" (org-get-limited-outline-regexp)))
23441 (subs (make-vector (1+ n) nil))
23442 (last-level 0)
23443 m level head0 head)
23444 (save-excursion
23445 (save-restriction
23446 (widen)
23447 (goto-char (point-max))
23448 (while (re-search-backward re nil t)
23449 (setq level (org-reduced-level (funcall outline-level)))
23450 (when (and (<= level n)
23451 (looking-at org-complex-heading-regexp)
23452 (setq head0 (org-match-string-no-properties 4)))
23453 (setq head (org-link-display-format head0)
23454 m (org-imenu-new-marker))
23455 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23456 (if (>= level last-level)
23457 (push (cons head m) (aref subs level))
23458 (push (cons head (aref subs (1+ level))) (aref subs level))
23459 (loop for i from (1+ level) to n do (aset subs i nil)))
23460 (setq last-level level)))))
23461 (aref subs 1)))
23463 (eval-after-load "imenu"
23464 '(progn
23465 (add-hook 'imenu-after-jump-hook
23466 (lambda ()
23467 (if (derived-mode-p 'org-mode)
23468 (org-show-context 'org-goto))))))
23470 (defun org-link-display-format (link)
23471 "Replace a link with its the description.
23472 If there is no description, use the link target."
23473 (save-match-data
23474 (if (string-match org-bracket-link-analytic-regexp link)
23475 (replace-match (if (match-end 5)
23476 (match-string 5 link)
23477 (concat (match-string 1 link)
23478 (match-string 3 link)))
23479 nil t link)
23480 link)))
23482 (defun org-toggle-link-display ()
23483 "Toggle the literal or descriptive display of links."
23484 (interactive)
23485 (if org-descriptive-links
23486 (progn (org-remove-from-invisibility-spec '(org-link))
23487 (org-restart-font-lock)
23488 (setq org-descriptive-links nil))
23489 (progn (add-to-invisibility-spec '(org-link))
23490 (org-restart-font-lock)
23491 (setq org-descriptive-links t))))
23493 ;; Speedbar support
23495 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23496 "Overlay marking the agenda restriction line in speedbar.")
23497 (overlay-put org-speedbar-restriction-lock-overlay
23498 'face 'org-agenda-restriction-lock)
23499 (overlay-put org-speedbar-restriction-lock-overlay
23500 'help-echo "Agendas are currently limited to this item.")
23501 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23503 (defun org-speedbar-set-agenda-restriction ()
23504 "Restrict future agenda commands to the location at point in speedbar.
23505 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23506 (interactive)
23507 (require 'org-agenda)
23508 (let (p m tp np dir txt)
23509 (cond
23510 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23511 'org-imenu t))
23512 (setq m (get-text-property p 'org-imenu-marker))
23513 (with-current-buffer (marker-buffer m)
23514 (goto-char m)
23515 (org-agenda-set-restriction-lock 'subtree)))
23516 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23517 'speedbar-function 'speedbar-find-file))
23518 (setq tp (previous-single-property-change
23519 (1+ p) 'speedbar-function)
23520 np (next-single-property-change
23521 tp 'speedbar-function)
23522 dir (speedbar-line-directory)
23523 txt (buffer-substring-no-properties (or tp (point-min))
23524 (or np (point-max))))
23525 (with-current-buffer (find-file-noselect
23526 (let ((default-directory dir))
23527 (expand-file-name txt)))
23528 (unless (derived-mode-p 'org-mode)
23529 (user-error "Cannot restrict to non-Org-mode file"))
23530 (org-agenda-set-restriction-lock 'file)))
23531 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23532 (move-overlay org-speedbar-restriction-lock-overlay
23533 (point-at-bol) (point-at-eol))
23534 (setq current-prefix-arg nil)
23535 (org-agenda-maybe-redo)))
23537 (eval-after-load "speedbar"
23538 '(progn
23539 (speedbar-add-supported-extension ".org")
23540 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23541 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23542 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23543 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23544 (add-hook 'speedbar-visiting-tag-hook
23545 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23547 ;;; Fixes and Hacks for problems with other packages
23549 ;; Make flyspell not check words in links, to not mess up our keymap
23550 (defvar org-element-affiliated-keywords) ; From org-element.el
23551 (defvar org-element-block-name-alist) ; From org-element.el
23552 (defun org-mode-flyspell-verify ()
23553 "Don't let flyspell put overlays at active buttons, or on
23554 {todo,all-time,additional-option-like}-keywords."
23555 (require 'org-element) ; For `org-element-affiliated-keywords'
23556 (let ((pos (max (1- (point)) (point-min)))
23557 (word (thing-at-point 'word)))
23558 (and (not (get-text-property pos 'keymap))
23559 (not (get-text-property pos 'org-no-flyspell))
23560 (not (member word org-todo-keywords-1))
23561 (not (member word org-all-time-keywords))
23562 (not (member word org-options-keywords))
23563 (not (member word (mapcar 'car org-startup-options)))
23564 (not (member-ignore-case word org-element-affiliated-keywords))
23565 (not (member-ignore-case word (org-get-export-keywords)))
23566 (not (member-ignore-case
23567 word (mapcar 'car org-element-block-name-alist)))
23568 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23570 (defun org-remove-flyspell-overlays-in (beg end)
23571 "Remove flyspell overlays in region."
23572 (and (org-bound-and-true-p flyspell-mode)
23573 (fboundp 'flyspell-delete-region-overlays)
23574 (flyspell-delete-region-overlays beg end))
23575 (add-text-properties beg end '(org-no-flyspell t)))
23577 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23578 (eval-after-load "bookmark"
23579 '(if (boundp 'bookmark-after-jump-hook)
23580 ;; We can use the hook
23581 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23582 ;; Hook not available, use advice
23583 (defadvice bookmark-jump (after org-make-visible activate)
23584 "Make the position visible."
23585 (org-bookmark-jump-unhide))))
23587 ;; Make sure saveplace shows the location if it was hidden
23588 (eval-after-load "saveplace"
23589 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23590 "Make the position visible."
23591 (org-bookmark-jump-unhide)))
23593 ;; Make sure ecb shows the location if it was hidden
23594 (eval-after-load "ecb"
23595 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23596 "Make hierarchy visible when jumping into location from ECB tree buffer."
23597 (if (derived-mode-p 'org-mode)
23598 (org-show-context))))
23600 (defun org-bookmark-jump-unhide ()
23601 "Unhide the current position, to show the bookmark location."
23602 (and (derived-mode-p 'org-mode)
23603 (or (outline-invisible-p)
23604 (save-excursion (goto-char (max (point-min) (1- (point))))
23605 (outline-invisible-p)))
23606 (org-show-context 'bookmark-jump)))
23608 ;; Make session.el ignore our circular variable
23609 (eval-after-load "session"
23610 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23612 ;;;; Finish up
23614 (provide 'org)
23616 (run-hooks 'org-load-hook)
23618 ;;; org.el ends here