Export back-ends: Apply changes to back-end structure
[org-mode/org-tableheadings.git] / lisp / org.el
blobc569a96d2a1c593d5829fa08d4d43eb6dfee1fe7
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 (declare-function org-export-backend-name "ox" (backend))
442 (defcustom org-export-backends '(ascii html icalendar latex)
443 "List of export back-ends that should be always available.
445 If a description starts with <C>, the file is not part of Emacs
446 and loading it will require that you have downloaded and properly
447 installed the Org mode distribution.
449 Unlike to `org-modules', libraries in this list will not be
450 loaded along with Org, but only once the export framework is
451 needed.
453 This variable needs to be set before org.el is loaded. If you
454 need to make a change while Emacs is running, use the customize
455 interface or run the following code, where VAL stands for the new
456 value of the variable, after updating it:
458 \(progn
459 \(setq org-export--registered-backends
460 \(org-remove-if-not
461 \(lambda (backend)
462 \(let ((name (org-export-backend-name backend)))
463 \(or (memq name val)
464 \(catch 'parentp
465 \(dolist (b val)
466 \(and (org-export-derived-backend-p b name)
467 \(throw 'parentp t)))))))
468 org-export--registered-backends))
469 \(let ((new-list (mapcar 'org-export-backend-name
470 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 'org-export-backends 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 (let ((name (org-export-backend-name backend)))
495 (or (memq name val)
496 (catch 'parentp
497 (dolist (b val)
498 (and (org-export-derived-backend-p b name)
499 (throw 'parentp t)))))))
500 org-export--registered-backends))
501 ;; Now build NEW-LIST of both new back-ends and required
502 ;; parents.
503 (let ((new-list (mapcar 'org-export-backend-name
504 org-export--registered-backends)))
505 (dolist (backend val)
506 (cond
507 ((not (load (format "ox-%s" backend) t t))
508 (message "Problems while trying to load export back-end `%s'"
509 backend))
510 ((not (memq backend new-list)) (push backend new-list))))
511 ;; Set VAR to that list with fixed dependencies.
512 (set-default var new-list))))
513 :type '(set :greedy t
514 (const :tag " ascii Export buffer to ASCII format" ascii)
515 (const :tag " beamer Export buffer to Beamer presentation" beamer)
516 (const :tag " html Export buffer to HTML format" html)
517 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
518 (const :tag " latex Export buffer to LaTeX format" latex)
519 (const :tag " man Export buffer to MAN format" man)
520 (const :tag " md Export buffer to Markdown format" md)
521 (const :tag " odt Export buffer to ODT format" odt)
522 (const :tag " org Export buffer to Org format" org)
523 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
524 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
525 (const :tag "C deck Export buffer to deck.js presentations" deck)
526 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
527 (const :tag "C groff Export buffer to Groff format" groff)
528 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
529 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
530 (const :tag "C s5 Export buffer to s5 presentations" s5)
531 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
533 (eval-after-load 'ox
534 '(mapc
535 (lambda (backend)
536 (condition-case nil (require (intern (format "ox-%s" backend)))
537 (error (message "Problems while trying to load export back-end `%s'"
538 backend))))
539 org-export-backends))
541 (defcustom org-support-shift-select nil
542 "Non-nil means make shift-cursor commands select text when possible.
544 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
545 start selecting a region, or enlarge regions started in this way.
546 In Org-mode, in special contexts, these same keys are used for
547 other purposes, important enough to compete with shift selection.
548 Org tries to balance these needs by supporting `shift-select-mode'
549 outside these special contexts, under control of this variable.
551 The default of this variable is nil, to avoid confusing behavior. Shifted
552 cursor keys will then execute Org commands in the following contexts:
553 - on a headline, changing TODO state (left/right) and priority (up/down)
554 - on a time stamp, changing the time
555 - in a plain list item, changing the bullet type
556 - in a property definition line, switching between allowed values
557 - in the BEGIN line of a clock table (changing the time block).
558 Outside these contexts, the commands will throw an error.
560 When this variable is t and the cursor is not in a special
561 context, Org-mode will support shift-selection for making and
562 enlarging regions. To make this more effective, the bullet
563 cycling will no longer happen anywhere in an item line, but only
564 if the cursor is exactly on the bullet.
566 If you set this variable to the symbol `always', then the keys
567 will not be special in headlines, property lines, and item lines,
568 to make shift selection work there as well. If this is what you
569 want, you can use the following alternative commands: `C-c C-t'
570 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
571 can be used to switch TODO sets, `C-c -' to cycle item bullet
572 types, and properties can be edited by hand or in column view.
574 However, when the cursor is on a timestamp, shift-cursor commands
575 will still edit the time stamp - this is just too good to give up.
577 XEmacs user should have this variable set to nil, because
578 `shift-select-mode' is in Emacs 23 or later only."
579 :group 'org
580 :type '(choice
581 (const :tag "Never" nil)
582 (const :tag "When outside special context" t)
583 (const :tag "Everywhere except timestamps" always)))
585 (defcustom org-loop-over-headlines-in-active-region nil
586 "Shall some commands act upon headlines in the active region?
588 When set to `t', some commands will be performed in all headlines
589 within the active region.
591 When set to `start-level', some commands will be performed in all
592 headlines within the active region, provided that these headlines
593 are of the same level than the first one.
595 When set to a string, those commands will be performed on the
596 matching headlines within the active region. Such string must be
597 a tags/property/todo match as it is used in the agenda tags view.
599 The list of commands is: `org-schedule', `org-deadline',
600 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
601 `org-archive-to-archive-sibling'. The archiving commands skip
602 already archived entries."
603 :type '(choice (const :tag "Don't loop" nil)
604 (const :tag "All headlines in active region" t)
605 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
606 (string :tag "Tags/Property/Todo matcher"))
607 :version "24.1"
608 :group 'org-todo
609 :group 'org-archive)
611 (defgroup org-startup nil
612 "Options concerning startup of Org-mode."
613 :tag "Org Startup"
614 :group 'org)
616 (defcustom org-startup-folded t
617 "Non-nil means entering Org-mode will switch to OVERVIEW.
618 This can also be configured on a per-file basis by adding one of
619 the following lines anywhere in the buffer:
621 #+STARTUP: fold (or `overview', this is equivalent)
622 #+STARTUP: nofold (or `showall', this is equivalent)
623 #+STARTUP: content
624 #+STARTUP: showeverything
626 By default, this option is ignored when Org opens agenda files
627 for the first time. If you want the agenda to honor the startup
628 option, set `org-agenda-inhibit-startup' to nil."
629 :group 'org-startup
630 :type '(choice
631 (const :tag "nofold: show all" nil)
632 (const :tag "fold: overview" t)
633 (const :tag "content: all headlines" content)
634 (const :tag "show everything, even drawers" showeverything)))
636 (defcustom org-startup-truncated t
637 "Non-nil means entering Org-mode will set `truncate-lines'.
638 This is useful since some lines containing links can be very long and
639 uninteresting. Also tables look terrible when wrapped."
640 :group 'org-startup
641 :type 'boolean)
643 (defcustom org-startup-indented nil
644 "Non-nil means turn on `org-indent-mode' on startup.
645 This can also be configured on a per-file basis by adding one of
646 the following lines anywhere in the buffer:
648 #+STARTUP: indent
649 #+STARTUP: noindent"
650 :group 'org-structure
651 :type '(choice
652 (const :tag "Not" nil)
653 (const :tag "Globally (slow on startup in large files)" t)))
655 (defcustom org-use-sub-superscripts t
656 "Non-nil means interpret \"_\" and \"^\" for display.
657 When this option is turned on, you can use TeX-like syntax for sub- and
658 superscripts. Several characters after \"_\" or \"^\" will be
659 considered as a single item - so grouping with {} is normally not
660 needed. For example, the following things will be parsed as single
661 sub- or superscripts.
663 10^24 or 10^tau several digits will be considered 1 item.
664 10^-12 or 10^-tau a leading sign with digits or a word
665 x^2-y^3 will be read as x^2 - y^3, because items are
666 terminated by almost any nonword/nondigit char.
667 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
669 Still, ambiguity is possible - so when in doubt use {} to enclose
670 the sub/superscript. If you set this variable to the symbol
671 `{}', the braces are *required* in order to trigger
672 interpretations as sub/superscript. This can be helpful in
673 documents that need \"_\" frequently in plain text."
674 :group 'org-startup
675 :version "24.1"
676 :type '(choice
677 (const :tag "Always interpret" t)
678 (const :tag "Only with braces" {})
679 (const :tag "Never interpret" nil)))
681 (defcustom org-startup-with-beamer-mode nil
682 "Non-nil means turn on `org-beamer-mode' on startup.
683 This can also be configured on a per-file basis by adding one of
684 the following lines anywhere in the buffer:
686 #+STARTUP: beamer"
687 :group 'org-startup
688 :version "24.1"
689 :type 'boolean)
691 (defcustom org-startup-align-all-tables nil
692 "Non-nil means align all tables when visiting a file.
693 This is useful when the column width in tables is forced with <N> cookies
694 in table fields. Such tables will look correct only after the first re-align.
695 This can also be configured on a per-file basis by adding one of
696 the following lines anywhere in the buffer:
697 #+STARTUP: align
698 #+STARTUP: noalign"
699 :group 'org-startup
700 :type 'boolean)
702 (defcustom org-startup-with-inline-images nil
703 "Non-nil means show inline images when loading a new Org file.
704 This can also be configured on a per-file basis by adding one of
705 the following lines anywhere in the buffer:
706 #+STARTUP: inlineimages
707 #+STARTUP: noinlineimages"
708 :group 'org-startup
709 :version "24.1"
710 :type 'boolean)
712 (defcustom org-startup-with-latex-preview nil
713 "Non-nil means preview LaTeX fragments when loading a new Org file.
715 This can also be configured on a per-file basis by adding one of
716 the followinglines anywhere in the buffer:
717 #+STARTUP: latexpreview
718 #+STARTUP: nolatexpreview"
719 :group 'org-startup
720 :version "24.4"
721 :package-version '(Org . "8.0")
722 :type 'boolean)
724 (defcustom org-insert-mode-line-in-empty-file nil
725 "Non-nil means insert the first line setting Org-mode in empty files.
726 When the function `org-mode' is called interactively in an empty file, this
727 normally means that the file name does not automatically trigger Org-mode.
728 To ensure that the file will always be in Org-mode in the future, a
729 line enforcing Org-mode will be inserted into the buffer, if this option
730 has been set."
731 :group 'org-startup
732 :type 'boolean)
734 (defcustom org-replace-disputed-keys nil
735 "Non-nil means use alternative key bindings for some keys.
736 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
737 These keys are also used by other packages like shift-selection-mode'
738 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
739 If you want to use Org-mode together with one of these other modes,
740 or more generally if you would like to move some Org-mode commands to
741 other keys, set this variable and configure the keys with the variable
742 `org-disputed-keys'.
744 This option is only relevant at load-time of Org-mode, and must be set
745 *before* org.el is loaded. Changing it requires a restart of Emacs to
746 become effective."
747 :group 'org-startup
748 :type 'boolean)
750 (defcustom org-use-extra-keys nil
751 "Non-nil means use extra key sequence definitions for certain commands.
752 This happens automatically if you run XEmacs or if `window-system'
753 is nil. This variable lets you do the same manually. You must
754 set it before loading org.
756 Example: on Carbon Emacs 22 running graphically, with an external
757 keyboard on a Powerbook, the default way of setting M-left might
758 not work for either Alt or ESC. Setting this variable will make
759 it work for ESC."
760 :group 'org-startup
761 :type 'boolean)
763 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
765 (defcustom org-disputed-keys
766 '(([(shift up)] . [(meta p)])
767 ([(shift down)] . [(meta n)])
768 ([(shift left)] . [(meta -)])
769 ([(shift right)] . [(meta +)])
770 ([(control shift right)] . [(meta shift +)])
771 ([(control shift left)] . [(meta shift -)]))
772 "Keys for which Org-mode and other modes compete.
773 This is an alist, cars are the default keys, second element specifies
774 the alternative to use when `org-replace-disputed-keys' is t.
776 Keys can be specified in any syntax supported by `define-key'.
777 The value of this option takes effect only at Org-mode's startup,
778 therefore you'll have to restart Emacs to apply it after changing."
779 :group 'org-startup
780 :type 'alist)
782 (defun org-key (key)
783 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
784 Or return the original if not disputed.
785 Also apply the translations defined in `org-xemacs-key-equivalents'."
786 (when org-replace-disputed-keys
787 (let* ((nkey (key-description key))
788 (x (org-find-if (lambda (x)
789 (equal (key-description (car x)) nkey))
790 org-disputed-keys)))
791 (setq key (if x (cdr x) key))))
792 (when (featurep 'xemacs)
793 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
794 key)
796 (defun org-find-if (predicate seq)
797 (catch 'exit
798 (while seq
799 (if (funcall predicate (car seq))
800 (throw 'exit (car seq))
801 (pop seq)))))
803 (defun org-defkey (keymap key def)
804 "Define a key, possibly translated, as returned by `org-key'."
805 (define-key keymap (org-key key) def))
807 (defcustom org-ellipsis nil
808 "The ellipsis to use in the Org-mode outline.
809 When nil, just use the standard three dots. When a string, use that instead,
810 When a face, use the standard 3 dots, but with the specified face.
811 The change affects only Org-mode (which will then use its own display table).
812 Changing this requires executing `M-x org-mode' in a buffer to become
813 effective."
814 :group 'org-startup
815 :type '(choice (const :tag "Default" nil)
816 (face :tag "Face" :value org-warning)
817 (string :tag "String" :value "...#")))
819 (defvar org-display-table nil
820 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
822 (defgroup org-keywords nil
823 "Keywords in Org-mode."
824 :tag "Org Keywords"
825 :group 'org)
827 (defcustom org-deadline-string "DEADLINE:"
828 "String to mark deadline entries.
829 A deadline is this string, followed by a time stamp. Should be a word,
830 terminated by a colon. You can insert a schedule keyword and
831 a timestamp with \\[org-deadline].
832 Changes become only effective after restarting Emacs."
833 :group 'org-keywords
834 :type 'string)
836 (defcustom org-scheduled-string "SCHEDULED:"
837 "String to mark scheduled TODO entries.
838 A schedule is this string, followed by a time stamp. Should be a word,
839 terminated by a colon. You can insert a schedule keyword and
840 a timestamp with \\[org-schedule].
841 Changes become only effective after restarting Emacs."
842 :group 'org-keywords
843 :type 'string)
845 (defcustom org-closed-string "CLOSED:"
846 "String used as the prefix for timestamps logging closing a TODO entry."
847 :group 'org-keywords
848 :type 'string)
850 (defcustom org-clock-string "CLOCK:"
851 "String used as prefix for timestamps clocking work hours on an item."
852 :group 'org-keywords
853 :type 'string)
855 (defcustom org-closed-keep-when-no-todo nil
856 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
857 :group 'org-todo
858 :group 'org-keywords
859 :version "24.4"
860 :package-version '(Org . "8.0")
861 :type 'boolean)
863 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
864 org-scheduled-string "\\|"
865 org-deadline-string "\\|"
866 org-closed-string "\\|"
867 org-clock-string "\\)")
868 "Matches a line with planning or clock info.")
870 (defcustom org-comment-string "COMMENT"
871 "Entries starting with this keyword will never be exported.
872 An entry can be toggled between COMMENT and normal with
873 \\[org-toggle-comment].
874 Changes become only effective after restarting Emacs."
875 :group 'org-keywords
876 :type 'string)
878 (defcustom org-quote-string "QUOTE"
879 "Entries starting with this keyword will be exported in fixed-width font.
880 Quoting applies only to the text in the entry following the headline, and does
881 not extend beyond the next headline, even if that is lower level.
882 An entry can be toggled between QUOTE and normal with
883 \\[org-toggle-fixed-width-section]."
884 :group 'org-keywords
885 :type 'string)
887 (defconst org-repeat-re
888 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
889 "Regular expression for specifying repeated events.
890 After a match, group 1 contains the repeat expression.")
892 (defgroup org-structure nil
893 "Options concerning the general structure of Org-mode files."
894 :tag "Org Structure"
895 :group 'org)
897 (defgroup org-reveal-location nil
898 "Options about how to make context of a location visible."
899 :tag "Org Reveal Location"
900 :group 'org-structure)
902 (defconst org-context-choice
903 '(choice
904 (const :tag "Always" t)
905 (const :tag "Never" nil)
906 (repeat :greedy t :tag "Individual contexts"
907 (cons
908 (choice :tag "Context"
909 (const agenda)
910 (const org-goto)
911 (const occur-tree)
912 (const tags-tree)
913 (const link-search)
914 (const mark-goto)
915 (const bookmark-jump)
916 (const isearch)
917 (const default))
918 (boolean))))
919 "Contexts for the reveal options.")
921 (defcustom org-show-hierarchy-above '((default . t))
922 "Non-nil means show full hierarchy when revealing a location.
923 Org-mode often shows locations in an org-mode file which might have
924 been invisible before. When this is set, the hierarchy of headings
925 above the exposed location is shown.
926 Turning this off for example for sparse trees makes them very compact.
927 Instead of t, this can also be an alist specifying this option for different
928 contexts. Valid contexts are
929 agenda when exposing an entry from the agenda
930 org-goto when using the command `org-goto' on key C-c C-j
931 occur-tree when using the command `org-occur' on key C-c /
932 tags-tree when constructing a sparse tree based on tags matches
933 link-search when exposing search matches associated with a link
934 mark-goto when exposing the jump goal of a mark
935 bookmark-jump when exposing a bookmark location
936 isearch when exiting from an incremental search
937 default default for all contexts not set explicitly"
938 :group 'org-reveal-location
939 :type org-context-choice)
941 (defcustom org-show-following-heading '((default . nil))
942 "Non-nil means show following heading when revealing a location.
943 Org-mode often shows locations in an org-mode file which might have
944 been invisible before. When this is set, the heading following the
945 match is shown.
946 Turning this off for example for sparse trees makes them very compact,
947 but makes it harder to edit the location of the match. In such a case,
948 use the command \\[org-reveal] to show more context.
949 Instead of t, this can also be an alist specifying this option for different
950 contexts. See `org-show-hierarchy-above' for valid contexts."
951 :group 'org-reveal-location
952 :type org-context-choice)
954 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
955 "Non-nil means show all sibling heading when revealing a location.
956 Org-mode often shows locations in an org-mode file which might have
957 been invisible before. When this is set, the sibling of the current entry
958 heading are all made visible. If `org-show-hierarchy-above' is t,
959 the same happens on each level of the hierarchy above the current entry.
961 By default this is on for the isearch context, off for all other contexts.
962 Turning this off for example for sparse trees makes them very compact,
963 but makes it harder to edit the location of the match. In such a case,
964 use the command \\[org-reveal] to show more context.
965 Instead of t, this can also be an alist specifying this option for different
966 contexts. See `org-show-hierarchy-above' for valid contexts."
967 :group 'org-reveal-location
968 :type org-context-choice
969 :version "24.4"
970 :package-version '(Org . "8.0"))
972 (defcustom org-show-entry-below '((default . nil))
973 "Non-nil means show the entry below a headline when revealing a location.
974 Org-mode often shows locations in an org-mode file which might have
975 been invisible before. When this is set, the text below the headline that is
976 exposed is also shown.
978 By default this is off for all contexts.
979 Instead of t, this can also be an alist specifying this option for different
980 contexts. See `org-show-hierarchy-above' for valid contexts."
981 :group 'org-reveal-location
982 :type org-context-choice)
984 (defcustom org-indirect-buffer-display 'other-window
985 "How should indirect tree buffers be displayed?
986 This applies to indirect buffers created with the commands
987 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
988 Valid values are:
989 current-window Display in the current window
990 other-window Just display in another window.
991 dedicated-frame Create one new frame, and re-use it each time.
992 new-frame Make a new frame each time. Note that in this case
993 previously-made indirect buffers are kept, and you need to
994 kill these buffers yourself."
995 :group 'org-structure
996 :group 'org-agenda-windows
997 :type '(choice
998 (const :tag "In current window" current-window)
999 (const :tag "In current frame, other window" other-window)
1000 (const :tag "Each time a new frame" new-frame)
1001 (const :tag "One dedicated frame" dedicated-frame)))
1003 (defcustom org-use-speed-commands nil
1004 "Non-nil means activate single letter commands at beginning of a headline.
1005 This may also be a function to test for appropriate locations where speed
1006 commands should be active."
1007 :group 'org-structure
1008 :type '(choice
1009 (const :tag "Never" nil)
1010 (const :tag "At beginning of headline stars" t)
1011 (function)))
1013 (defcustom org-speed-commands-user nil
1014 "Alist of additional speed commands.
1015 This list will be checked before `org-speed-commands-default'
1016 when the variable `org-use-speed-commands' is non-nil
1017 and when the cursor is at the beginning of a headline.
1018 The car if each entry is a string with a single letter, which must
1019 be assigned to `self-insert-command' in the global map.
1020 The cdr is either a command to be called interactively, a function
1021 to be called, or a form to be evaluated.
1022 An entry that is just a list with a single string will be interpreted
1023 as a descriptive headline that will be added when listing the speed
1024 commands in the Help buffer using the `?' speed command."
1025 :group 'org-structure
1026 :type '(repeat :value ("k" . ignore)
1027 (choice :value ("k" . ignore)
1028 (list :tag "Descriptive Headline" (string :tag "Headline"))
1029 (cons :tag "Letter and Command"
1030 (string :tag "Command letter")
1031 (choice
1032 (function)
1033 (sexp))))))
1035 (defgroup org-cycle nil
1036 "Options concerning visibility cycling in Org-mode."
1037 :tag "Org Cycle"
1038 :group 'org-structure)
1040 (defcustom org-cycle-skip-children-state-if-no-children t
1041 "Non-nil means skip CHILDREN state in entries that don't have any."
1042 :group 'org-cycle
1043 :type 'boolean)
1045 (defcustom org-cycle-max-level nil
1046 "Maximum level which should still be subject to visibility cycling.
1047 Levels higher than this will, for cycling, be treated as text, not a headline.
1048 When `org-odd-levels-only' is set, a value of N in this variable actually
1049 means 2N-1 stars as the limiting headline.
1050 When nil, cycle all levels.
1051 Note that the limiting level of cycling is also influenced by
1052 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1053 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1054 than its value."
1055 :group 'org-cycle
1056 :type '(choice
1057 (const :tag "No limit" nil)
1058 (integer :tag "Maximum level")))
1060 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1061 "Names of drawers. Drawers are not opened by cycling on the headline above.
1062 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1063 this:
1064 :DRAWERNAME:
1065 .....
1066 :END:
1067 The drawer \"PROPERTIES\" is special for capturing properties through
1068 the property API.
1070 Drawers can be defined on the per-file basis with a line like:
1072 #+DRAWERS: HIDDEN STATE PROPERTIES"
1073 :group 'org-structure
1074 :group 'org-cycle
1075 :type '(repeat (string :tag "Drawer Name")))
1077 (defcustom org-hide-block-startup nil
1078 "Non-nil means entering Org-mode will fold all blocks.
1079 This can also be set in on a per-file basis with
1081 #+STARTUP: hideblocks
1082 #+STARTUP: showblocks"
1083 :group 'org-startup
1084 :group 'org-cycle
1085 :type 'boolean)
1087 (defcustom org-cycle-global-at-bob nil
1088 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1089 This makes it possible to do global cycling without having to use S-TAB or
1090 \\[universal-argument] TAB. For this special case to work, the first line
1091 of the buffer must not be a headline -- it may be empty or some other text.
1092 When used in this way, `org-cycle-hook' is disabled temporarily to make
1093 sure the cursor stays at the beginning of the buffer. When this option is
1094 nil, don't do anything special at the beginning of the buffer."
1095 :group 'org-cycle
1096 :type 'boolean)
1098 (defcustom org-cycle-level-after-item/entry-creation t
1099 "Non-nil means cycle entry level or item indentation in new empty entries.
1101 When the cursor is at the end of an empty headline, i.e., with only stars
1102 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1103 and then all possible ancestor states, before returning to the original state.
1104 This makes data entry extremely fast: M-RET to create a new headline,
1105 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1107 When the cursor is at the end of an empty plain list item, one TAB will
1108 make it a subitem, two or more tabs will back up to make this an item
1109 higher up in the item hierarchy."
1110 :group 'org-cycle
1111 :type 'boolean)
1113 (defcustom org-cycle-emulate-tab t
1114 "Where should `org-cycle' emulate TAB.
1115 nil Never
1116 white Only in completely white lines
1117 whitestart Only at the beginning of lines, before the first non-white char
1118 t Everywhere except in headlines
1119 exc-hl-bol Everywhere except at the start of a headline
1120 If TAB is used in a place where it does not emulate TAB, the current subtree
1121 visibility is cycled."
1122 :group 'org-cycle
1123 :type '(choice (const :tag "Never" nil)
1124 (const :tag "Only in completely white lines" white)
1125 (const :tag "Before first char in a line" whitestart)
1126 (const :tag "Everywhere except in headlines" t)
1127 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1129 (defcustom org-cycle-separator-lines 2
1130 "Number of empty lines needed to keep an empty line between collapsed trees.
1131 If you leave an empty line between the end of a subtree and the following
1132 headline, this empty line is hidden when the subtree is folded.
1133 Org-mode will leave (exactly) one empty line visible if the number of
1134 empty lines is equal or larger to the number given in this variable.
1135 So the default 2 means at least 2 empty lines after the end of a subtree
1136 are needed to produce free space between a collapsed subtree and the
1137 following headline.
1139 If the number is negative, and the number of empty lines is at least -N,
1140 all empty lines are shown.
1142 Special case: when 0, never leave empty lines in collapsed view."
1143 :group 'org-cycle
1144 :type 'integer)
1145 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1147 (defcustom org-pre-cycle-hook nil
1148 "Hook that is run before visibility cycling is happening.
1149 The function(s) in this hook must accept a single argument which indicates
1150 the new state that will be set right after running this hook. The
1151 argument is a symbol. Before a global state change, it can have the values
1152 `overview', `content', or `all'. Before a local state change, it can have
1153 the values `folded', `children', or `subtree'."
1154 :group 'org-cycle
1155 :type 'hook)
1157 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1158 org-cycle-hide-drawers
1159 org-cycle-hide-inline-tasks
1160 org-cycle-show-empty-lines
1161 org-optimize-window-after-visibility-change)
1162 "Hook that is run after `org-cycle' has changed the buffer visibility.
1163 The function(s) in this hook must accept a single argument which indicates
1164 the new state that was set by the most recent `org-cycle' command. The
1165 argument is a symbol. After a global state change, it can have the values
1166 `overview', `contents', or `all'. After a local state change, it can have
1167 the values `folded', `children', or `subtree'."
1168 :group 'org-cycle
1169 :type 'hook)
1171 (defgroup org-edit-structure nil
1172 "Options concerning structure editing in Org-mode."
1173 :tag "Org Edit Structure"
1174 :group 'org-structure)
1176 (defcustom org-odd-levels-only nil
1177 "Non-nil means skip even levels and only use odd levels for the outline.
1178 This has the effect that two stars are being added/taken away in
1179 promotion/demotion commands. It also influences how levels are
1180 handled by the exporters.
1181 Changing it requires restart of `font-lock-mode' to become effective
1182 for fontification also in regions already fontified.
1183 You may also set this on a per-file basis by adding one of the following
1184 lines to the buffer:
1186 #+STARTUP: odd
1187 #+STARTUP: oddeven"
1188 :group 'org-edit-structure
1189 :group 'org-appearance
1190 :type 'boolean)
1192 (defcustom org-adapt-indentation t
1193 "Non-nil means adapt indentation to outline node level.
1195 When this variable is set, Org assumes that you write outlines by
1196 indenting text in each node to align with the headline (after the stars).
1197 The following issues are influenced by this variable:
1199 - When this is set and the *entire* text in an entry is indented, the
1200 indentation is increased by one space in a demotion command, and
1201 decreased by one in a promotion command. If any line in the entry
1202 body starts with text at column 0, indentation is not changed at all.
1204 - Property drawers and planning information is inserted indented when
1205 this variable s set. When nil, they will not be indented.
1207 - TAB indents a line relative to context. The lines below a headline
1208 will be indented when this variable is set.
1210 Note that this is all about true indentation, by adding and removing
1211 space characters. See also `org-indent.el' which does level-dependent
1212 indentation in a virtual way, i.e. at display time in Emacs."
1213 :group 'org-edit-structure
1214 :type 'boolean)
1216 (defcustom org-special-ctrl-a/e nil
1217 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1219 When t, `C-a' will bring back the cursor to the beginning of the
1220 headline text, i.e. after the stars and after a possible TODO
1221 keyword. In an item, this will be the position after bullet and
1222 check-box, if any. When the cursor is already at that position,
1223 another `C-a' will bring it to the beginning of the line.
1225 `C-e' will jump to the end of the headline, ignoring the presence
1226 of tags in the headline. A second `C-e' will then jump to the
1227 true end of the line, after any tags. This also means that, when
1228 this variable is non-nil, `C-e' also will never jump beyond the
1229 end of the heading of a folded section, i.e. not after the
1230 ellipses.
1232 When set to the symbol `reversed', the first `C-a' or `C-e' works
1233 normally, going to the true line boundary first. Only a directly
1234 following, identical keypress will bring the cursor to the
1235 special positions.
1237 This may also be a cons cell where the behavior for `C-a' and
1238 `C-e' is set separately."
1239 :group 'org-edit-structure
1240 :type '(choice
1241 (const :tag "off" nil)
1242 (const :tag "on: after stars/bullet and before tags first" t)
1243 (const :tag "reversed: true line boundary first" reversed)
1244 (cons :tag "Set C-a and C-e separately"
1245 (choice :tag "Special C-a"
1246 (const :tag "off" nil)
1247 (const :tag "on: after stars/bullet first" t)
1248 (const :tag "reversed: before stars/bullet first" reversed))
1249 (choice :tag "Special C-e"
1250 (const :tag "off" nil)
1251 (const :tag "on: before tags first" t)
1252 (const :tag "reversed: after tags first" reversed)))))
1253 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1255 (defcustom org-special-ctrl-k nil
1256 "Non-nil means `C-k' will behave specially in headlines.
1257 When nil, `C-k' will call the default `kill-line' command.
1258 When t, the following will happen while the cursor is in the headline:
1260 - When the cursor is at the beginning of a headline, kill the entire
1261 line and possible the folded subtree below the line.
1262 - When in the middle of the headline text, kill the headline up to the tags.
1263 - When after the headline text, kill the tags."
1264 :group 'org-edit-structure
1265 :type 'boolean)
1267 (defcustom org-ctrl-k-protect-subtree nil
1268 "Non-nil means, do not delete a hidden subtree with C-k.
1269 When set to the symbol `error', simply throw an error when C-k is
1270 used to kill (part-of) a headline that has hidden text behind it.
1271 Any other non-nil value will result in a query to the user, if it is
1272 OK to kill that hidden subtree. When nil, kill without remorse."
1273 :group 'org-edit-structure
1274 :version "24.1"
1275 :type '(choice
1276 (const :tag "Do not protect hidden subtrees" nil)
1277 (const :tag "Protect hidden subtrees with a security query" t)
1278 (const :tag "Never kill a hidden subtree with C-k" error)))
1280 (defcustom org-catch-invisible-edits nil
1281 "Check if in invisible region before inserting or deleting a character.
1282 Valid values are:
1284 nil Do not check, so just do invisible edits.
1285 error Throw an error and do nothing.
1286 show Make point visible, and do the requested edit.
1287 show-and-error Make point visible, then throw an error and abort the edit.
1288 smart Make point visible, and do insertion/deletion if it is
1289 adjacent to visible text and the change feels predictable.
1290 Never delete a previously invisible character or add in the
1291 middle or right after an invisible region. Basically, this
1292 allows insertion and backward-delete right before ellipses.
1293 FIXME: maybe in this case we should not even show?"
1294 :group 'org-edit-structure
1295 :version "24.1"
1296 :type '(choice
1297 (const :tag "Do not check" nil)
1298 (const :tag "Throw error when trying to edit" error)
1299 (const :tag "Unhide, but do not do the edit" show-and-error)
1300 (const :tag "Show invisible part and do the edit" show)
1301 (const :tag "Be smart and do the right thing" smart)))
1303 (defcustom org-yank-folded-subtrees t
1304 "Non-nil means when yanking subtrees, fold them.
1305 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1306 it starts with a heading and all other headings in it are either children
1307 or siblings, then fold all the subtrees. However, do this only if no
1308 text after the yank would be swallowed into a folded tree by this action."
1309 :group 'org-edit-structure
1310 :type 'boolean)
1312 (defcustom org-yank-adjusted-subtrees nil
1313 "Non-nil means when yanking subtrees, adjust the level.
1314 With this setting, `org-paste-subtree' is used to insert the subtree, see
1315 this function for details."
1316 :group 'org-edit-structure
1317 :type 'boolean)
1319 (defcustom org-M-RET-may-split-line '((default . t))
1320 "Non-nil means M-RET will split the line at the cursor position.
1321 When nil, it will go to the end of the line before making a
1322 new line.
1323 You may also set this option in a different way for different
1324 contexts. Valid contexts are:
1326 headline when creating a new headline
1327 item when creating a new item
1328 table in a table field
1329 default the value to be used for all contexts not explicitly
1330 customized"
1331 :group 'org-structure
1332 :group 'org-table
1333 :type '(choice
1334 (const :tag "Always" t)
1335 (const :tag "Never" nil)
1336 (repeat :greedy t :tag "Individual contexts"
1337 (cons
1338 (choice :tag "Context"
1339 (const headline)
1340 (const item)
1341 (const table)
1342 (const default))
1343 (boolean)))))
1346 (defcustom org-insert-heading-respect-content nil
1347 "Non-nil means insert new headings after the current subtree.
1348 When nil, the new heading is created directly after the current line.
1349 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1350 this variable on for the duration of the command."
1351 :group 'org-structure
1352 :type 'boolean)
1354 (defcustom org-blank-before-new-entry '((heading . auto)
1355 (plain-list-item . auto))
1356 "Should `org-insert-heading' leave a blank line before new heading/item?
1357 The value is an alist, with `heading' and `plain-list-item' as CAR,
1358 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1359 which case Org will look at the surrounding headings/items and try to
1360 make an intelligent decision whether to insert a blank line or not.
1362 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1363 the setting here is ignored and no empty line is inserted to avoid breaking
1364 the list structure."
1365 :group 'org-edit-structure
1366 :type '(list
1367 (cons (const heading)
1368 (choice (const :tag "Never" nil)
1369 (const :tag "Always" t)
1370 (const :tag "Auto" auto)))
1371 (cons (const plain-list-item)
1372 (choice (const :tag "Never" nil)
1373 (const :tag "Always" t)
1374 (const :tag "Auto" auto)))))
1376 (defcustom org-insert-heading-hook nil
1377 "Hook being run after inserting a new heading."
1378 :group 'org-edit-structure
1379 :type 'hook)
1381 (defcustom org-enable-fixed-width-editor t
1382 "Non-nil means lines starting with \":\" are treated as fixed-width.
1383 This currently only means they are never auto-wrapped.
1384 When nil, such lines will be treated like ordinary lines.
1385 See also the QUOTE keyword."
1386 :group 'org-edit-structure
1387 :type 'boolean)
1389 (defcustom org-goto-auto-isearch t
1390 "Non-nil means typing characters in `org-goto' starts incremental search.
1391 When nil, you can use these keybindings to navigate the buffer:
1393 q Quit the org-goto interface
1394 n Go to the next visible heading
1395 p Go to the previous visible heading
1396 f Go one heading forward on same level
1397 b Go one heading backward on same level
1398 u Go one heading up"
1399 :group 'org-edit-structure
1400 :type 'boolean)
1402 (defgroup org-sparse-trees nil
1403 "Options concerning sparse trees in Org-mode."
1404 :tag "Org Sparse Trees"
1405 :group 'org-structure)
1407 (defcustom org-highlight-sparse-tree-matches t
1408 "Non-nil means highlight all matches that define a sparse tree.
1409 The highlights will automatically disappear the next time the buffer is
1410 changed by an edit command."
1411 :group 'org-sparse-trees
1412 :type 'boolean)
1414 (defcustom org-remove-highlights-with-change t
1415 "Non-nil means any change to the buffer will remove temporary highlights.
1416 Such highlights are created by `org-occur' and `org-clock-display'.
1417 When nil, `C-c C-c needs to be used to get rid of the highlights.
1418 The highlights created by `org-preview-latex-fragment' always need
1419 `C-c C-c' to be removed."
1420 :group 'org-sparse-trees
1421 :group 'org-time
1422 :type 'boolean)
1425 (defcustom org-occur-hook '(org-first-headline-recenter)
1426 "Hook that is run after `org-occur' has constructed a sparse tree.
1427 This can be used to recenter the window to show as much of the structure
1428 as possible."
1429 :group 'org-sparse-trees
1430 :type 'hook)
1432 (defgroup org-imenu-and-speedbar nil
1433 "Options concerning imenu and speedbar in Org-mode."
1434 :tag "Org Imenu and Speedbar"
1435 :group 'org-structure)
1437 (defcustom org-imenu-depth 2
1438 "The maximum level for Imenu access to Org-mode headlines.
1439 This also applied for speedbar access."
1440 :group 'org-imenu-and-speedbar
1441 :type 'integer)
1443 (defgroup org-table nil
1444 "Options concerning tables in Org-mode."
1445 :tag "Org Table"
1446 :group 'org)
1448 (defcustom org-enable-table-editor 'optimized
1449 "Non-nil means lines starting with \"|\" are handled by the table editor.
1450 When nil, such lines will be treated like ordinary lines.
1452 When equal to the symbol `optimized', the table editor will be optimized to
1453 do the following:
1454 - Automatic overwrite mode in front of whitespace in table fields.
1455 This makes the structure of the table stay in tact as long as the edited
1456 field does not exceed the column width.
1457 - Minimize the number of realigns. Normally, the table is aligned each time
1458 TAB or RET are pressed to move to another field. With optimization this
1459 happens only if changes to a field might have changed the column width.
1460 Optimization requires replacing the functions `self-insert-command',
1461 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1462 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1463 very good at guessing when a re-align will be necessary, but you can always
1464 force one with \\[org-ctrl-c-ctrl-c].
1466 If you would like to use the optimized version in Org-mode, but the
1467 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1469 This variable can be used to turn on and off the table editor during a session,
1470 but in order to toggle optimization, a restart is required.
1472 See also the variable `org-table-auto-blank-field'."
1473 :group 'org-table
1474 :type '(choice
1475 (const :tag "off" nil)
1476 (const :tag "on" t)
1477 (const :tag "on, optimized" optimized)))
1479 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1480 (version<= emacs-version "24.1"))
1481 "Non-nil means cluster self-insert commands for undo when possible.
1482 If this is set, then, like in the Emacs command loop, 20 consecutive
1483 characters will be undone together.
1484 This is configurable, because there is some impact on typing performance."
1485 :group 'org-table
1486 :type 'boolean)
1488 (defcustom org-table-tab-recognizes-table.el t
1489 "Non-nil means TAB will automatically notice a table.el table.
1490 When it sees such a table, it moves point into it and - if necessary -
1491 calls `table-recognize-table'."
1492 :group 'org-table-editing
1493 :type 'boolean)
1495 (defgroup org-link nil
1496 "Options concerning links in Org-mode."
1497 :tag "Org Link"
1498 :group 'org)
1500 (defvar org-link-abbrev-alist-local nil
1501 "Buffer-local version of `org-link-abbrev-alist', which see.
1502 The value of this is taken from the #+LINK lines.")
1503 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1505 (defcustom org-link-abbrev-alist nil
1506 "Alist of link abbreviations.
1507 The car of each element is a string, to be replaced at the start of a link.
1508 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1509 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1511 [[linkkey:tag][description]]
1513 The 'linkkey' must be a word word, starting with a letter, followed
1514 by letters, numbers, '-' or '_'.
1516 If REPLACE is a string, the tag will simply be appended to create the link.
1517 If the string contains \"%s\", the tag will be inserted there. If the string
1518 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1519 at that point (see the function `url-hexify-string'). If the string contains
1520 the specifier \"%(my-function)\", then the custom function `my-function' will
1521 be invoked: this function takes the tag as its only argument and must return
1522 a string.
1524 REPLACE may also be a function that will be called with the tag as the
1525 only argument to create the link, which should be returned as a string.
1527 See the manual for examples."
1528 :group 'org-link
1529 :type '(repeat
1530 (cons
1531 (string :tag "Protocol")
1532 (choice
1533 (string :tag "Format")
1534 (function)))))
1536 (defcustom org-descriptive-links t
1537 "Non-nil means Org will display descriptive links.
1538 E.g. [[http://orgmode.org][Org website]] will be displayed as
1539 \"Org Website\", hiding the link itself and just displaying its
1540 description. When set to `nil', Org will display the full links
1541 literally.
1543 You can interactively set the value of this variable by calling
1544 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1545 :group 'org-link
1546 :type 'boolean)
1548 (defcustom org-link-file-path-type 'adaptive
1549 "How the path name in file links should be stored.
1550 Valid values are:
1552 relative Relative to the current directory, i.e. the directory of the file
1553 into which the link is being inserted.
1554 absolute Absolute path, if possible with ~ for home directory.
1555 noabbrev Absolute path, no abbreviation of home directory.
1556 adaptive Use relative path for files in the current directory and sub-
1557 directories of it. For other files, use an absolute path."
1558 :group 'org-link
1559 :type '(choice
1560 (const relative)
1561 (const absolute)
1562 (const noabbrev)
1563 (const adaptive)))
1565 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1566 "Types of links that should be activated in Org-mode files.
1567 This is a list of symbols, each leading to the activation of a certain link
1568 type. In principle, it does not hurt to turn on most link types - there may
1569 be a small gain when turning off unused link types. The types are:
1571 bracket The recommended [[link][description]] or [[link]] links with hiding.
1572 angle Links in angular brackets that may contain whitespace like
1573 <bbdb:Carsten Dominik>.
1574 plain Plain links in normal text, no whitespace, like http://google.com.
1575 radio Text that is matched by a radio target, see manual for details.
1576 tag Tag settings in a headline (link to tag search).
1577 date Time stamps (link to calendar).
1578 footnote Footnote labels.
1580 Changing this variable requires a restart of Emacs to become effective."
1581 :group 'org-link
1582 :type '(set :greedy t
1583 (const :tag "Double bracket links" bracket)
1584 (const :tag "Angular bracket links" angle)
1585 (const :tag "Plain text links" plain)
1586 (const :tag "Radio target matches" radio)
1587 (const :tag "Tags" tag)
1588 (const :tag "Timestamps" date)
1589 (const :tag "Footnotes" footnote)))
1591 (defcustom org-make-link-description-function nil
1592 "Function to use for generating link descriptions from links.
1593 When nil, the link location will be used. This function must take
1594 two parameters: the first one is the link, the second one is the
1595 description generated by `org-insert-link'. The function should
1596 return the description to use."
1597 :group 'org-link
1598 :type '(choice (const nil) (function)))
1600 (defgroup org-link-store nil
1601 "Options concerning storing links in Org-mode."
1602 :tag "Org Store Link"
1603 :group 'org-link)
1605 (defcustom org-url-hexify-p t
1606 "When non-nil, hexify URL when creating a link."
1607 :type 'boolean
1608 :version "24.3"
1609 :group 'org-link-store)
1611 (defcustom org-email-link-description-format "Email %c: %.30s"
1612 "Format of the description part of a link to an email or usenet message.
1613 The following %-escapes will be replaced by corresponding information:
1615 %F full \"From\" field
1616 %f name, taken from \"From\" field, address if no name
1617 %T full \"To\" field
1618 %t first name in \"To\" field, address if no name
1619 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1620 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1621 %s subject
1622 %d date
1623 %m message-id.
1625 You may use normal field width specification between the % and the letter.
1626 This is for example useful to limit the length of the subject.
1628 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1629 :group 'org-link-store
1630 :type 'string)
1632 (defcustom org-from-is-user-regexp
1633 (let (r1 r2)
1634 (when (and user-mail-address (not (string= user-mail-address "")))
1635 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1636 (when (and user-full-name (not (string= user-full-name "")))
1637 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1638 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1639 "Regexp matched against the \"From:\" header of an email or usenet message.
1640 It should match if the message is from the user him/herself."
1641 :group 'org-link-store
1642 :type 'regexp)
1644 (defcustom org-context-in-file-links t
1645 "Non-nil means file links from `org-store-link' contain context.
1646 A search string will be added to the file name with :: as separator and
1647 used to find the context when the link is activated by the command
1648 `org-open-at-point'. When this option is t, the entire active region
1649 will be placed in the search string of the file link. If set to a
1650 positive integer, only the first n lines of context will be stored.
1652 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1653 negates this setting for the duration of the command."
1654 :group 'org-link-store
1655 :type '(choice boolean integer))
1657 (defcustom org-keep-stored-link-after-insertion nil
1658 "Non-nil means keep link in list for entire session.
1660 The command `org-store-link' adds a link pointing to the current
1661 location to an internal list. These links accumulate during a session.
1662 The command `org-insert-link' can be used to insert links into any
1663 Org-mode file (offering completion for all stored links). When this
1664 option is nil, every link which has been inserted once using \\[org-insert-link]
1665 will be removed from the list, to make completing the unused links
1666 more efficient."
1667 :group 'org-link-store
1668 :type 'boolean)
1670 (defgroup org-link-follow nil
1671 "Options concerning following links in Org-mode."
1672 :tag "Org Follow Link"
1673 :group 'org-link)
1675 (defcustom org-link-translation-function nil
1676 "Function to translate links with different syntax to Org syntax.
1677 This can be used to translate links created for example by the Planner
1678 or emacs-wiki packages to Org syntax.
1679 The function must accept two parameters, a TYPE containing the link
1680 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1681 which is everything after the link protocol. It should return a cons
1682 with possibly modified values of type and path.
1683 Org contains a function for this, so if you set this variable to
1684 `org-translate-link-from-planner', you should be able follow many
1685 links created by planner."
1686 :group 'org-link-follow
1687 :type '(choice (const nil) (function)))
1689 (defcustom org-follow-link-hook nil
1690 "Hook that is run after a link has been followed."
1691 :group 'org-link-follow
1692 :type 'hook)
1694 (defcustom org-tab-follows-link nil
1695 "Non-nil means on links TAB will follow the link.
1696 Needs to be set before org.el is loaded.
1697 This really should not be used, it does not make sense, and the
1698 implementation is bad."
1699 :group 'org-link-follow
1700 :type 'boolean)
1702 (defcustom org-return-follows-link nil
1703 "Non-nil means on links RET will follow the link.
1704 In tables, the special behavior of RET has precedence."
1705 :group 'org-link-follow
1706 :type 'boolean)
1708 (defcustom org-mouse-1-follows-link
1709 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1710 "Non-nil means mouse-1 on a link will follow the link.
1711 A longer mouse click will still set point. Does not work on XEmacs.
1712 Needs to be set before org.el is loaded."
1713 :group 'org-link-follow
1714 :type 'boolean)
1716 (defcustom org-mark-ring-length 4
1717 "Number of different positions to be recorded in the ring.
1718 Changing this requires a restart of Emacs to work correctly."
1719 :group 'org-link-follow
1720 :type 'integer)
1722 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1723 "Non-nil means internal links in Org files must exactly match a headline.
1724 When nil, the link search tries to match a phrase with all words
1725 in the search text."
1726 :group 'org-link-follow
1727 :version "24.1"
1728 :type '(choice
1729 (const :tag "Use fuzzy text search" nil)
1730 (const :tag "Match only exact headline" t)
1731 (const :tag "Match exact headline or query to create it"
1732 query-to-create)))
1734 (defcustom org-link-frame-setup
1735 '((vm . vm-visit-folder-other-frame)
1736 (vm-imap . vm-visit-imap-folder-other-frame)
1737 (gnus . org-gnus-no-new-news)
1738 (file . find-file-other-window)
1739 (wl . wl-other-frame))
1740 "Setup the frame configuration for following links.
1741 When following a link with Emacs, it may often be useful to display
1742 this link in another window or frame. This variable can be used to
1743 set this up for the different types of links.
1744 For VM, use any of
1745 `vm-visit-folder'
1746 `vm-visit-folder-other-window'
1747 `vm-visit-folder-other-frame'
1748 For Gnus, use any of
1749 `gnus'
1750 `gnus-other-frame'
1751 `org-gnus-no-new-news'
1752 For FILE, use any of
1753 `find-file'
1754 `find-file-other-window'
1755 `find-file-other-frame'
1756 For Wanderlust use any of
1757 `wl'
1758 `wl-other-frame'
1759 For the calendar, use the variable `calendar-setup'.
1760 For BBDB, it is currently only possible to display the matches in
1761 another window."
1762 :group 'org-link-follow
1763 :type '(list
1764 (cons (const vm)
1765 (choice
1766 (const vm-visit-folder)
1767 (const vm-visit-folder-other-window)
1768 (const vm-visit-folder-other-frame)))
1769 (cons (const vm-imap)
1770 (choice
1771 (const vm-visit-imap-folder)
1772 (const vm-visit-imap-folder-other-window)
1773 (const vm-visit-imap-folder-other-frame)))
1774 (cons (const gnus)
1775 (choice
1776 (const gnus)
1777 (const gnus-other-frame)
1778 (const org-gnus-no-new-news)))
1779 (cons (const file)
1780 (choice
1781 (const find-file)
1782 (const find-file-other-window)
1783 (const find-file-other-frame)))
1784 (cons (const wl)
1785 (choice
1786 (const wl)
1787 (const wl-other-frame)))))
1789 (defcustom org-display-internal-link-with-indirect-buffer nil
1790 "Non-nil means use indirect buffer to display infile links.
1791 Activating internal links (from one location in a file to another location
1792 in the same file) normally just jumps to the location. When the link is
1793 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1794 is displayed in
1795 another window. When this option is set, the other window actually displays
1796 an indirect buffer clone of the current buffer, to avoid any visibility
1797 changes to the current buffer."
1798 :group 'org-link-follow
1799 :type 'boolean)
1801 (defcustom org-open-non-existing-files nil
1802 "Non-nil means `org-open-file' will open non-existing files.
1803 When nil, an error will be generated.
1804 This variable applies only to external applications because they
1805 might choke on non-existing files. If the link is to a file that
1806 will be opened in Emacs, the variable is ignored."
1807 :group 'org-link-follow
1808 :type 'boolean)
1810 (defcustom org-open-directory-means-index-dot-org nil
1811 "Non-nil means a link to a directory really means to index.org.
1812 When nil, following a directory link will run dired or open a finder/explorer
1813 window on that directory."
1814 :group 'org-link-follow
1815 :type 'boolean)
1817 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1818 "Function and arguments to call for following mailto links.
1819 This is a list with the first element being a Lisp function, and the
1820 remaining elements being arguments to the function. In string arguments,
1821 %a will be replaced by the address, and %s will be replaced by the subject
1822 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1823 :group 'org-link-follow
1824 :type '(choice
1825 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1826 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1827 (const :tag "message-mail" (message-mail "%a" "%s"))
1828 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1830 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1831 "Non-nil means ask for confirmation before executing shell links.
1832 Shell links can be dangerous: just think about a link
1834 [[shell:rm -rf ~/*][Google Search]]
1836 This link would show up in your Org-mode document as \"Google Search\",
1837 but really it would remove your entire home directory.
1838 Therefore we advise against setting this variable to nil.
1839 Just change it to `y-or-n-p' if you want to confirm with a
1840 single keystroke rather than having to type \"yes\"."
1841 :group 'org-link-follow
1842 :type '(choice
1843 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1844 (const :tag "with y-or-n (faster)" y-or-n-p)
1845 (const :tag "no confirmation (dangerous)" nil)))
1846 (put 'org-confirm-shell-link-function
1847 'safe-local-variable
1848 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1850 (defcustom org-confirm-shell-link-not-regexp ""
1851 "A regexp to skip confirmation for shell links."
1852 :group 'org-link-follow
1853 :version "24.1"
1854 :type 'regexp)
1856 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1857 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1858 Elisp links can be dangerous: just think about a link
1860 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1862 This link would show up in your Org-mode document as \"Google Search\",
1863 but really it would remove your entire home directory.
1864 Therefore we advise against setting this variable to nil.
1865 Just change it to `y-or-n-p' if you want to confirm with a
1866 single keystroke rather than having to type \"yes\"."
1867 :group 'org-link-follow
1868 :type '(choice
1869 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1870 (const :tag "with y-or-n (faster)" y-or-n-p)
1871 (const :tag "no confirmation (dangerous)" nil)))
1872 (put 'org-confirm-shell-link-function
1873 'safe-local-variable
1874 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1876 (defcustom org-confirm-elisp-link-not-regexp ""
1877 "A regexp to skip confirmation for Elisp links."
1878 :group 'org-link-follow
1879 :version "24.1"
1880 :type 'regexp)
1882 (defconst org-file-apps-defaults-gnu
1883 '((remote . emacs)
1884 (system . mailcap)
1885 (t . mailcap))
1886 "Default file applications on a UNIX or GNU/Linux system.
1887 See `org-file-apps'.")
1889 (defconst org-file-apps-defaults-macosx
1890 '((remote . emacs)
1891 (t . "open %s")
1892 (system . "open %s")
1893 ("ps.gz" . "gv %s")
1894 ("eps.gz" . "gv %s")
1895 ("dvi" . "xdvi %s")
1896 ("fig" . "xfig %s"))
1897 "Default file applications on a MacOS X system.
1898 The system \"open\" is known as a default, but we use X11 applications
1899 for some files for which the OS does not have a good default.
1900 See `org-file-apps'.")
1902 (defconst org-file-apps-defaults-windowsnt
1903 (list
1904 '(remote . emacs)
1905 (cons t
1906 (list (if (featurep 'xemacs)
1907 'mswindows-shell-execute
1908 'w32-shell-execute)
1909 "open" 'file))
1910 (cons 'system
1911 (list (if (featurep 'xemacs)
1912 'mswindows-shell-execute
1913 'w32-shell-execute)
1914 "open" 'file)))
1915 "Default file applications on a Windows NT system.
1916 The system \"open\" is used for most files.
1917 See `org-file-apps'.")
1919 (defcustom org-file-apps
1920 '((auto-mode . emacs)
1921 ("\\.mm\\'" . default)
1922 ("\\.x?html?\\'" . default)
1923 ("\\.pdf\\'" . default))
1924 "External applications for opening `file:path' items in a document.
1925 Org-mode uses system defaults for different file types, but
1926 you can use this variable to set the application for a given file
1927 extension. The entries in this list are cons cells where the car identifies
1928 files and the cdr the corresponding command. Possible values for the
1929 file identifier are
1930 \"string\" A string as a file identifier can be interpreted in different
1931 ways, depending on its contents:
1933 - Alphanumeric characters only:
1934 Match links with this file extension.
1935 Example: (\"pdf\" . \"evince %s\")
1936 to open PDFs with evince.
1938 - Regular expression: Match links where the
1939 filename matches the regexp. If you want to
1940 use groups here, use shy groups.
1942 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1943 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1944 to open *.html and *.xhtml with firefox.
1946 - Regular expression which contains (non-shy) groups:
1947 Match links where the whole link, including \"::\", and
1948 anything after that, matches the regexp.
1949 In a custom command string, %1, %2, etc. are replaced with
1950 the parts of the link that were matched by the groups.
1951 For backwards compatibility, if a command string is given
1952 that does not use any of the group matches, this case is
1953 handled identically to the second one (i.e. match against
1954 file name only).
1955 In a custom lisp form, you can access the group matches with
1956 (match-string n link).
1958 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1959 to open [[file:document.pdf::5]] with evince at page 5.
1961 `directory' Matches a directory
1962 `remote' Matches a remote file, accessible through tramp or efs.
1963 Remote files most likely should be visited through Emacs
1964 because external applications cannot handle such paths.
1965 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1966 so all files Emacs knows how to handle. Using this with
1967 command `emacs' will open most files in Emacs. Beware that this
1968 will also open html files inside Emacs, unless you add
1969 (\"html\" . default) to the list as well.
1970 t Default for files not matched by any of the other options.
1971 `system' The system command to open files, like `open' on Windows
1972 and Mac OS X, and mailcap under GNU/Linux. This is the command
1973 that will be selected if you call `C-c C-o' with a double
1974 \\[universal-argument] \\[universal-argument] prefix.
1976 Possible values for the command are:
1977 `emacs' The file will be visited by the current Emacs process.
1978 `default' Use the default application for this file type, which is the
1979 association for t in the list, most likely in the system-specific
1980 part.
1981 This can be used to overrule an unwanted setting in the
1982 system-specific variable.
1983 `system' Use the system command for opening files, like \"open\".
1984 This command is specified by the entry whose car is `system'.
1985 Most likely, the system-specific version of this variable
1986 does define this command, but you can overrule/replace it
1987 here.
1988 string A command to be executed by a shell; %s will be replaced
1989 by the path to the file.
1990 sexp A Lisp form which will be evaluated. The file path will
1991 be available in the Lisp variable `file'.
1992 For more examples, see the system specific constants
1993 `org-file-apps-defaults-macosx'
1994 `org-file-apps-defaults-windowsnt'
1995 `org-file-apps-defaults-gnu'."
1996 :group 'org-link-follow
1997 :type '(repeat
1998 (cons (choice :value ""
1999 (string :tag "Extension")
2000 (const :tag "System command to open files" system)
2001 (const :tag "Default for unrecognized files" t)
2002 (const :tag "Remote file" remote)
2003 (const :tag "Links to a directory" directory)
2004 (const :tag "Any files that have Emacs modes"
2005 auto-mode))
2006 (choice :value ""
2007 (const :tag "Visit with Emacs" emacs)
2008 (const :tag "Use default" default)
2009 (const :tag "Use the system command" system)
2010 (string :tag "Command")
2011 (sexp :tag "Lisp form")))))
2013 (defcustom org-doi-server-url "http://dx.doi.org/"
2014 "The URL of the DOI server."
2015 :type 'string
2016 :version "24.3"
2017 :group 'org-link-follow)
2019 (defgroup org-refile nil
2020 "Options concerning refiling entries in Org-mode."
2021 :tag "Org Refile"
2022 :group 'org)
2024 (defcustom org-directory "~/org"
2025 "Directory with org files.
2026 This is just a default location to look for Org files. There is no need
2027 at all to put your files into this directory. It is only used in the
2028 following situations:
2030 1. When a capture template specifies a target file that is not an
2031 absolute path. The path will then be interpreted relative to
2032 `org-directory'
2033 2. When a capture note is filed away in an interactive way (when exiting the
2034 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2035 with `org-directory' as the default path."
2036 :group 'org-refile
2037 :group 'org-remember
2038 :group 'org-capture
2039 :type 'directory)
2041 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2042 "Default target for storing notes.
2043 Used as a fall back file for org-remember.el and org-capture.el, for
2044 templates that do not specify a target file."
2045 :group 'org-refile
2046 :group 'org-remember
2047 :group 'org-capture
2048 :type '(choice
2049 (const :tag "Default from remember-data-file" nil)
2050 file))
2052 (defcustom org-goto-interface 'outline
2053 "The default interface to be used for `org-goto'.
2054 Allowed values are:
2055 outline The interface shows an outline of the relevant file
2056 and the correct heading is found by moving through
2057 the outline or by searching with incremental search.
2058 outline-path-completion Headlines in the current buffer are offered via
2059 completion. This is the interface also used by
2060 the refile command."
2061 :group 'org-refile
2062 :type '(choice
2063 (const :tag "Outline" outline)
2064 (const :tag "Outline-path-completion" outline-path-completion)))
2066 (defcustom org-goto-max-level 5
2067 "Maximum target level when running `org-goto' with refile interface."
2068 :group 'org-refile
2069 :type 'integer)
2071 (defcustom org-reverse-note-order nil
2072 "Non-nil means store new notes at the beginning of a file or entry.
2073 When nil, new notes will be filed to the end of a file or entry.
2074 This can also be a list with cons cells of regular expressions that
2075 are matched against file names, and values."
2076 :group 'org-remember
2077 :group 'org-capture
2078 :group 'org-refile
2079 :type '(choice
2080 (const :tag "Reverse always" t)
2081 (const :tag "Reverse never" nil)
2082 (repeat :tag "By file name regexp"
2083 (cons regexp boolean))))
2085 (defcustom org-log-refile nil
2086 "Information to record when a task is refiled.
2088 Possible values are:
2090 nil Don't add anything
2091 time Add a time stamp to the task
2092 note Prompt for a note and add it with template `org-log-note-headings'
2094 This option can also be set with on a per-file-basis with
2096 #+STARTUP: nologrefile
2097 #+STARTUP: logrefile
2098 #+STARTUP: lognoterefile
2100 You can have local logging settings for a subtree by setting the LOGGING
2101 property to one or more of these keywords.
2103 When bulk-refiling from the agenda, the value `note' is forbidden and
2104 will temporarily be changed to `time'."
2105 :group 'org-refile
2106 :group 'org-progress
2107 :version "24.1"
2108 :type '(choice
2109 (const :tag "No logging" nil)
2110 (const :tag "Record timestamp" time)
2111 (const :tag "Record timestamp with note." note)))
2113 (defcustom org-refile-targets nil
2114 "Targets for refiling entries with \\[org-refile].
2115 This is a list of cons cells. Each cell contains:
2116 - a specification of the files to be considered, either a list of files,
2117 or a symbol whose function or variable value will be used to retrieve
2118 a file name or a list of file names. If you use `org-agenda-files' for
2119 that, all agenda files will be scanned for targets. Nil means consider
2120 headings in the current buffer.
2121 - A specification of how to find candidate refile targets. This may be
2122 any of:
2123 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2124 This tag has to be present in all target headlines, inheritance will
2125 not be considered.
2126 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2127 todo keyword.
2128 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2129 headlines that are refiling targets.
2130 - a cons cell (:level . N). Any headline of level N is considered a target.
2131 Note that, when `org-odd-levels-only' is set, level corresponds to
2132 order in hierarchy, not to the number of stars.
2133 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2134 Note that, when `org-odd-levels-only' is set, level corresponds to
2135 order in hierarchy, not to the number of stars.
2137 Each element of this list generates a set of possible targets.
2138 The union of these sets is presented (with completion) to
2139 the user by `org-refile'.
2141 You can set the variable `org-refile-target-verify-function' to a function
2142 to verify each headline found by the simple criteria above.
2144 When this variable is nil, all top-level headlines in the current buffer
2145 are used, equivalent to the value `((nil . (:level . 1))'."
2146 :group 'org-refile
2147 :type '(repeat
2148 (cons
2149 (choice :value org-agenda-files
2150 (const :tag "All agenda files" org-agenda-files)
2151 (const :tag "Current buffer" nil)
2152 (function) (variable) (file))
2153 (choice :tag "Identify target headline by"
2154 (cons :tag "Specific tag" (const :value :tag) (string))
2155 (cons :tag "TODO keyword" (const :value :todo) (string))
2156 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2157 (cons :tag "Level number" (const :value :level) (integer))
2158 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2160 (defcustom org-refile-target-verify-function nil
2161 "Function to verify if the headline at point should be a refile target.
2162 The function will be called without arguments, with point at the
2163 beginning of the headline. It should return t and leave point
2164 where it is if the headline is a valid target for refiling.
2166 If the target should not be selected, the function must return nil.
2167 In addition to this, it may move point to a place from where the search
2168 should be continued. For example, the function may decide that the entire
2169 subtree of the current entry should be excluded and move point to the end
2170 of the subtree."
2171 :group 'org-refile
2172 :type '(choice
2173 (const nil)
2174 (function)))
2176 (defcustom org-refile-use-cache nil
2177 "Non-nil means cache refile targets to speed up the process.
2178 The cache for a particular file will be updated automatically when
2179 the buffer has been killed, or when any of the marker used for flagging
2180 refile targets no longer points at a live buffer.
2181 If you have added new entries to a buffer that might themselves be targets,
2182 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2183 find that easier, `C-u C-u C-u C-c C-w'."
2184 :group 'org-refile
2185 :version "24.1"
2186 :type 'boolean)
2188 (defcustom org-refile-use-outline-path nil
2189 "Non-nil means provide refile targets as paths.
2190 So a level 3 headline will be available as level1/level2/level3.
2192 When the value is `file', also include the file name (without directory)
2193 into the path. In this case, you can also stop the completion after
2194 the file name, to get entries inserted as top level in the file.
2196 When `full-file-path', include the full file path."
2197 :group 'org-refile
2198 :type '(choice
2199 (const :tag "Not" nil)
2200 (const :tag "Yes" t)
2201 (const :tag "Start with file name" file)
2202 (const :tag "Start with full file path" full-file-path)))
2204 (defcustom org-outline-path-complete-in-steps t
2205 "Non-nil means complete the outline path in hierarchical steps.
2206 When Org-mode uses the refile interface to select an outline path
2207 \(see variable `org-refile-use-outline-path'), the completion of
2208 the path can be done is a single go, or if can be done in steps down
2209 the headline hierarchy. Going in steps is probably the best if you
2210 do not use a special completion package like `ido' or `icicles'.
2211 However, when using these packages, going in one step can be very
2212 fast, while still showing the whole path to the entry."
2213 :group 'org-refile
2214 :type 'boolean)
2216 (defcustom org-refile-allow-creating-parent-nodes nil
2217 "Non-nil means allow to create new nodes as refile targets.
2218 New nodes are then created by adding \"/new node name\" to the completion
2219 of an existing node. When the value of this variable is `confirm',
2220 new node creation must be confirmed by the user (recommended)
2221 When nil, the completion must match an existing entry.
2223 Note that, if the new heading is not seen by the criteria
2224 listed in `org-refile-targets', multiple instances of the same
2225 heading would be created by trying again to file under the new
2226 heading."
2227 :group 'org-refile
2228 :type '(choice
2229 (const :tag "Never" nil)
2230 (const :tag "Always" t)
2231 (const :tag "Prompt for confirmation" confirm)))
2233 (defcustom org-refile-active-region-within-subtree nil
2234 "Non-nil means also refile active region within a subtree.
2236 By default `org-refile' doesn't allow refiling regions if they
2237 don't contain a set of subtrees, but it might be convenient to
2238 do so sometimes: in that case, the first line of the region is
2239 converted to a headline before refiling."
2240 :group 'org-refile
2241 :version "24.1"
2242 :type 'boolean)
2244 (defgroup org-todo nil
2245 "Options concerning TODO items in Org-mode."
2246 :tag "Org TODO"
2247 :group 'org)
2249 (defgroup org-progress nil
2250 "Options concerning Progress logging in Org-mode."
2251 :tag "Org Progress"
2252 :group 'org-time)
2254 (defvar org-todo-interpretation-widgets
2255 '((:tag "Sequence (cycling hits every state)" sequence)
2256 (:tag "Type (cycling directly to DONE)" type))
2257 "The available interpretation symbols for customizing `org-todo-keywords'.
2258 Interested libraries should add to this list.")
2260 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2261 "List of TODO entry keyword sequences and their interpretation.
2262 \\<org-mode-map>This is a list of sequences.
2264 Each sequence starts with a symbol, either `sequence' or `type',
2265 indicating if the keywords should be interpreted as a sequence of
2266 action steps, or as different types of TODO items. The first
2267 keywords are states requiring action - these states will select a headline
2268 for inclusion into the global TODO list Org-mode produces. If one of
2269 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2270 signify that no further action is necessary. If \"|\" is not found,
2271 the last keyword is treated as the only DONE state of the sequence.
2273 The command \\[org-todo] cycles an entry through these states, and one
2274 additional state where no keyword is present. For details about this
2275 cycling, see the manual.
2277 TODO keywords and interpretation can also be set on a per-file basis with
2278 the special #+SEQ_TODO and #+TYP_TODO lines.
2280 Each keyword can optionally specify a character for fast state selection
2281 \(in combination with the variable `org-use-fast-todo-selection')
2282 and specifiers for state change logging, using the same syntax that
2283 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2284 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2285 indicates to record a time stamp each time this state is selected.
2287 Each keyword may also specify if a timestamp or a note should be
2288 recorded when entering or leaving the state, by adding additional
2289 characters in the parenthesis after the keyword. This looks like this:
2290 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2291 record only the time of the state change. With X and Y being either
2292 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2293 Y when leaving the state if and only if the *target* state does not
2294 define X. You may omit any of the fast-selection key or X or /Y,
2295 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2297 For backward compatibility, this variable may also be just a list
2298 of keywords. In this case the interpretation (sequence or type) will be
2299 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2300 :group 'org-todo
2301 :group 'org-keywords
2302 :type '(choice
2303 (repeat :tag "Old syntax, just keywords"
2304 (string :tag "Keyword"))
2305 (repeat :tag "New syntax"
2306 (cons
2307 (choice
2308 :tag "Interpretation"
2309 ;;Quick and dirty way to see
2310 ;;`org-todo-interpretations'. This takes the
2311 ;;place of item arguments
2312 :convert-widget
2313 (lambda (widget)
2314 (widget-put widget
2315 :args (mapcar
2316 #'(lambda (x)
2317 (widget-convert
2318 (cons 'const x)))
2319 org-todo-interpretation-widgets))
2320 widget))
2321 (repeat
2322 (string :tag "Keyword"))))))
2324 (defvar org-todo-keywords-1 nil
2325 "All TODO and DONE keywords active in a buffer.")
2326 (make-variable-buffer-local 'org-todo-keywords-1)
2327 (defvar org-todo-keywords-for-agenda nil)
2328 (defvar org-done-keywords-for-agenda nil)
2329 (defvar org-drawers-for-agenda nil)
2330 (defvar org-todo-keyword-alist-for-agenda nil)
2331 (defvar org-tag-alist-for-agenda nil
2332 "Alist of all tags from all agenda files.")
2333 (defvar org-tag-groups-alist-for-agenda nil
2334 "Alist of all groups tags from all current agenda files.")
2335 (defvar org-tag-groups-alist nil)
2336 (make-variable-buffer-local 'org-tag-groups-alist)
2337 (defvar org-agenda-contributing-files nil)
2338 (defvar org-not-done-keywords nil)
2339 (make-variable-buffer-local 'org-not-done-keywords)
2340 (defvar org-done-keywords nil)
2341 (make-variable-buffer-local 'org-done-keywords)
2342 (defvar org-todo-heads nil)
2343 (make-variable-buffer-local 'org-todo-heads)
2344 (defvar org-todo-sets nil)
2345 (make-variable-buffer-local 'org-todo-sets)
2346 (defvar org-todo-log-states nil)
2347 (make-variable-buffer-local 'org-todo-log-states)
2348 (defvar org-todo-kwd-alist nil)
2349 (make-variable-buffer-local 'org-todo-kwd-alist)
2350 (defvar org-todo-key-alist nil)
2351 (make-variable-buffer-local 'org-todo-key-alist)
2352 (defvar org-todo-key-trigger nil)
2353 (make-variable-buffer-local 'org-todo-key-trigger)
2355 (defcustom org-todo-interpretation 'sequence
2356 "Controls how TODO keywords are interpreted.
2357 This variable is in principle obsolete and is only used for
2358 backward compatibility, if the interpretation of todo keywords is
2359 not given already in `org-todo-keywords'. See that variable for
2360 more information."
2361 :group 'org-todo
2362 :group 'org-keywords
2363 :type '(choice (const sequence)
2364 (const type)))
2366 (defcustom org-use-fast-todo-selection t
2367 "Non-nil means use the fast todo selection scheme with C-c C-t.
2368 This variable describes if and under what circumstances the cycling
2369 mechanism for TODO keywords will be replaced by a single-key, direct
2370 selection scheme.
2372 When nil, fast selection is never used.
2374 When the symbol `prefix', it will be used when `org-todo' is called
2375 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2376 `C-u t' in an agenda buffer.
2378 When t, fast selection is used by default. In this case, the prefix
2379 argument forces cycling instead.
2381 In all cases, the special interface is only used if access keys have
2382 actually been assigned by the user, i.e. if keywords in the configuration
2383 are followed by a letter in parenthesis, like TODO(t)."
2384 :group 'org-todo
2385 :type '(choice
2386 (const :tag "Never" nil)
2387 (const :tag "By default" t)
2388 (const :tag "Only with C-u C-c C-t" prefix)))
2390 (defcustom org-provide-todo-statistics t
2391 "Non-nil means update todo statistics after insert and toggle.
2392 ALL-HEADLINES means update todo statistics by including headlines
2393 with no TODO keyword as well, counting them as not done.
2394 A list of TODO keywords means the same, but skip keywords that are
2395 not in this list.
2397 When this is set, todo statistics is updated in the parent of the
2398 current entry each time a todo state is changed."
2399 :group 'org-todo
2400 :type '(choice
2401 (const :tag "Yes, only for TODO entries" t)
2402 (const :tag "Yes, including all entries" 'all-headlines)
2403 (repeat :tag "Yes, for TODOs in this list"
2404 (string :tag "TODO keyword"))
2405 (other :tag "No TODO statistics" nil)))
2407 (defcustom org-hierarchical-todo-statistics t
2408 "Non-nil means TODO statistics covers just direct children.
2409 When nil, all entries in the subtree are considered.
2410 This has only an effect if `org-provide-todo-statistics' is set.
2411 To set this to nil for only a single subtree, use a COOKIE_DATA
2412 property and include the word \"recursive\" into the value."
2413 :group 'org-todo
2414 :type 'boolean)
2416 (defcustom org-after-todo-state-change-hook nil
2417 "Hook which is run after the state of a TODO item was changed.
2418 The new state (a string with a TODO keyword, or nil) is available in the
2419 Lisp variable `org-state'."
2420 :group 'org-todo
2421 :type 'hook)
2423 (defvar org-blocker-hook nil
2424 "Hook for functions that are allowed to block a state change.
2426 Functions in this hook should not modify the buffer.
2427 Each function gets as its single argument a property list,
2428 see `org-trigger-hook' for more information about this list.
2430 If any of the functions in this hook returns nil, the state change
2431 is blocked.")
2433 (defvar org-trigger-hook nil
2434 "Hook for functions that are triggered by a state change.
2436 Each function gets as its single argument a property list with at
2437 least the following elements:
2439 (:type type-of-change :position pos-at-entry-start
2440 :from old-state :to new-state)
2442 Depending on the type, more properties may be present.
2444 This mechanism is currently implemented for:
2446 TODO state changes
2447 ------------------
2448 :type todo-state-change
2449 :from previous state (keyword as a string), or nil, or a symbol
2450 'todo' or 'done', to indicate the general type of state.
2451 :to new state, like in :from")
2453 (defcustom org-enforce-todo-dependencies nil
2454 "Non-nil means undone TODO entries will block switching the parent to DONE.
2455 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2456 be blocked if any prior sibling is not yet done.
2457 Finally, if the parent is blocked because of ordered siblings of its own,
2458 the child will also be blocked."
2459 :set (lambda (var val)
2460 (set var val)
2461 (if val
2462 (add-hook 'org-blocker-hook
2463 'org-block-todo-from-children-or-siblings-or-parent)
2464 (remove-hook 'org-blocker-hook
2465 'org-block-todo-from-children-or-siblings-or-parent)))
2466 :group 'org-todo
2467 :type 'boolean)
2469 (defcustom org-enforce-todo-checkbox-dependencies nil
2470 "Non-nil means unchecked boxes will block switching the parent to DONE.
2471 When this is nil, checkboxes have no influence on switching TODO states.
2472 When non-nil, you first need to check off all check boxes before the TODO
2473 entry can be switched to DONE.
2474 This variable needs to be set before org.el is loaded, and you need to
2475 restart Emacs after a change to make the change effective. The only way
2476 to change is while Emacs is running is through the customize interface."
2477 :set (lambda (var val)
2478 (set var val)
2479 (if val
2480 (add-hook 'org-blocker-hook
2481 'org-block-todo-from-checkboxes)
2482 (remove-hook 'org-blocker-hook
2483 'org-block-todo-from-checkboxes)))
2484 :group 'org-todo
2485 :type 'boolean)
2487 (defcustom org-treat-insert-todo-heading-as-state-change nil
2488 "Non-nil means inserting a TODO heading is treated as state change.
2489 So when the command \\[org-insert-todo-heading] is used, state change
2490 logging will apply if appropriate. When nil, the new TODO item will
2491 be inserted directly, and no logging will take place."
2492 :group 'org-todo
2493 :type 'boolean)
2495 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2496 "Non-nil means switching TODO states with S-cursor counts as state change.
2497 This is the default behavior. However, setting this to nil allows a
2498 convenient way to select a TODO state and bypass any logging associated
2499 with that."
2500 :group 'org-todo
2501 :type 'boolean)
2503 (defcustom org-todo-state-tags-triggers nil
2504 "Tag changes that should be triggered by TODO state changes.
2505 This is a list. Each entry is
2507 (state-change (tag . flag) .......)
2509 State-change can be a string with a state, and empty string to indicate the
2510 state that has no TODO keyword, or it can be one of the symbols `todo'
2511 or `done', meaning any not-done or done state, respectively."
2512 :group 'org-todo
2513 :group 'org-tags
2514 :type '(repeat
2515 (cons (choice :tag "When changing to"
2516 (const :tag "Not-done state" todo)
2517 (const :tag "Done state" done)
2518 (string :tag "State"))
2519 (repeat
2520 (cons :tag "Tag action"
2521 (string :tag "Tag")
2522 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2524 (defcustom org-log-done nil
2525 "Information to record when a task moves to the DONE state.
2527 Possible values are:
2529 nil Don't add anything, just change the keyword
2530 time Add a time stamp to the task
2531 note Prompt for a note and add it with template `org-log-note-headings'
2533 This option can also be set with on a per-file-basis with
2535 #+STARTUP: nologdone
2536 #+STARTUP: logdone
2537 #+STARTUP: lognotedone
2539 You can have local logging settings for a subtree by setting the LOGGING
2540 property to one or more of these keywords."
2541 :group 'org-todo
2542 :group 'org-progress
2543 :type '(choice
2544 (const :tag "No logging" nil)
2545 (const :tag "Record CLOSED timestamp" time)
2546 (const :tag "Record CLOSED timestamp with note." note)))
2548 ;; Normalize old uses of org-log-done.
2549 (cond
2550 ((eq org-log-done t) (setq org-log-done 'time))
2551 ((and (listp org-log-done) (memq 'done org-log-done))
2552 (setq org-log-done 'note)))
2554 (defcustom org-log-reschedule nil
2555 "Information to record when the scheduling date of a tasks is modified.
2557 Possible values are:
2559 nil Don't add anything, just change the date
2560 time Add a time stamp to the task
2561 note Prompt for a note and add it with template `org-log-note-headings'
2563 This option can also be set with on a per-file-basis with
2565 #+STARTUP: nologreschedule
2566 #+STARTUP: logreschedule
2567 #+STARTUP: lognotereschedule"
2568 :group 'org-todo
2569 :group 'org-progress
2570 :type '(choice
2571 (const :tag "No logging" nil)
2572 (const :tag "Record timestamp" time)
2573 (const :tag "Record timestamp with note." note)))
2575 (defcustom org-log-redeadline nil
2576 "Information to record when the deadline date of a tasks is modified.
2578 Possible values are:
2580 nil Don't add anything, just change the date
2581 time Add a time stamp to the task
2582 note Prompt for a note and add it with template `org-log-note-headings'
2584 This option can also be set with on a per-file-basis with
2586 #+STARTUP: nologredeadline
2587 #+STARTUP: logredeadline
2588 #+STARTUP: lognoteredeadline
2590 You can have local logging settings for a subtree by setting the LOGGING
2591 property to one or more of these keywords."
2592 :group 'org-todo
2593 :group 'org-progress
2594 :type '(choice
2595 (const :tag "No logging" nil)
2596 (const :tag "Record timestamp" time)
2597 (const :tag "Record timestamp with note." note)))
2599 (defcustom org-log-note-clock-out nil
2600 "Non-nil means record a note when clocking out of an item.
2601 This can also be configured on a per-file basis by adding one of
2602 the following lines anywhere in the buffer:
2604 #+STARTUP: lognoteclock-out
2605 #+STARTUP: nolognoteclock-out"
2606 :group 'org-todo
2607 :group 'org-progress
2608 :type 'boolean)
2610 (defcustom org-log-done-with-time t
2611 "Non-nil means the CLOSED time stamp will contain date and time.
2612 When nil, only the date will be recorded."
2613 :group 'org-progress
2614 :type 'boolean)
2616 (defcustom org-log-note-headings
2617 '((done . "CLOSING NOTE %t")
2618 (state . "State %-12s from %-12S %t")
2619 (note . "Note taken on %t")
2620 (reschedule . "Rescheduled from %S on %t")
2621 (delschedule . "Not scheduled, was %S on %t")
2622 (redeadline . "New deadline from %S on %t")
2623 (deldeadline . "Removed deadline, was %S on %t")
2624 (refile . "Refiled on %t")
2625 (clock-out . ""))
2626 "Headings for notes added to entries.
2627 The value is an alist, with the car being a symbol indicating the note
2628 context, and the cdr is the heading to be used. The heading may also be the
2629 empty string.
2630 %t in the heading will be replaced by a time stamp.
2631 %T will be an active time stamp instead the default inactive one
2632 %d will be replaced by a short-format time stamp.
2633 %D will be replaced by an active short-format time stamp.
2634 %s will be replaced by the new TODO state, in double quotes.
2635 %S will be replaced by the old TODO state, in double quotes.
2636 %u will be replaced by the user name.
2637 %U will be replaced by the full user name.
2639 In fact, it is not a good idea to change the `state' entry, because
2640 agenda log mode depends on the format of these entries."
2641 :group 'org-todo
2642 :group 'org-progress
2643 :type '(list :greedy t
2644 (cons (const :tag "Heading when closing an item" done) string)
2645 (cons (const :tag
2646 "Heading when changing todo state (todo sequence only)"
2647 state) string)
2648 (cons (const :tag "Heading when just taking a note" note) string)
2649 (cons (const :tag "Heading when clocking out" clock-out) string)
2650 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2651 (cons (const :tag "Heading when rescheduling" reschedule) string)
2652 (cons (const :tag "Heading when changing deadline" redeadline) string)
2653 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2654 (cons (const :tag "Heading when refiling" refile) string)))
2656 (unless (assq 'note org-log-note-headings)
2657 (push '(note . "%t") org-log-note-headings))
2659 (defcustom org-log-into-drawer nil
2660 "Non-nil means insert state change notes and time stamps into a drawer.
2661 When nil, state changes notes will be inserted after the headline and
2662 any scheduling and clock lines, but not inside a drawer.
2664 The value of this variable should be the name of the drawer to use.
2665 LOGBOOK is proposed as the default drawer for this purpose, you can
2666 also set this to a string to define the drawer of your choice.
2668 A value of t is also allowed, representing \"LOGBOOK\".
2670 A value of t or nil can also be set with on a per-file-basis with
2672 #+STARTUP: logdrawer
2673 #+STARTUP: nologdrawer
2675 If this variable is set, `org-log-state-notes-insert-after-drawers'
2676 will be ignored.
2678 You can set the property LOG_INTO_DRAWER to overrule this setting for
2679 a subtree."
2680 :group 'org-todo
2681 :group 'org-progress
2682 :type '(choice
2683 (const :tag "Not into a drawer" nil)
2684 (const :tag "LOGBOOK" t)
2685 (string :tag "Other")))
2687 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2689 (defun org-log-into-drawer ()
2690 "Return the value of `org-log-into-drawer', but let properties overrule.
2691 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2692 used instead of the default value."
2693 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2694 (cond
2695 ((not p) org-log-into-drawer)
2696 ((equal p "nil") nil)
2697 ((equal p "t") "LOGBOOK")
2698 (t p))))
2700 (defcustom org-log-state-notes-insert-after-drawers nil
2701 "Non-nil means insert state change notes after any drawers in entry.
2702 Only the drawers that *immediately* follow the headline and the
2703 deadline/scheduled line are skipped.
2704 When nil, insert notes right after the heading and perhaps the line
2705 with deadline/scheduling if present.
2707 This variable will have no effect if `org-log-into-drawer' is
2708 set."
2709 :group 'org-todo
2710 :group 'org-progress
2711 :type 'boolean)
2713 (defcustom org-log-states-order-reversed t
2714 "Non-nil means the latest state note will be directly after heading.
2715 When nil, the state change notes will be ordered according to time.
2717 This option can also be set with on a per-file-basis with
2719 #+STARTUP: logstatesreversed
2720 #+STARTUP: nologstatesreversed"
2721 :group 'org-todo
2722 :group 'org-progress
2723 :type 'boolean)
2725 (defcustom org-todo-repeat-to-state nil
2726 "The TODO state to which a repeater should return the repeating task.
2727 By default this is the first task in a TODO sequence, or the previous state
2728 in a TODO_TYP set. But you can specify another task here.
2729 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2730 :group 'org-todo
2731 :version "24.1"
2732 :type '(choice (const :tag "Head of sequence" nil)
2733 (string :tag "Specific state")))
2735 (defcustom org-log-repeat 'time
2736 "Non-nil means record moving through the DONE state when triggering repeat.
2737 An auto-repeating task is immediately switched back to TODO when
2738 marked DONE. If you are not logging state changes (by adding \"@\"
2739 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2740 record a closing note, there will be no record of the task moving
2741 through DONE. This variable forces taking a note anyway.
2743 nil Don't force a record
2744 time Record a time stamp
2745 note Prompt for a note and add it with template `org-log-note-headings'
2747 This option can also be set with on a per-file-basis with
2749 #+STARTUP: nologrepeat
2750 #+STARTUP: logrepeat
2751 #+STARTUP: lognoterepeat
2753 You can have local logging settings for a subtree by setting the LOGGING
2754 property to one or more of these keywords."
2755 :group 'org-todo
2756 :group 'org-progress
2757 :type '(choice
2758 (const :tag "Don't force a record" nil)
2759 (const :tag "Force recording the DONE state" time)
2760 (const :tag "Force recording a note with the DONE state" note)))
2763 (defgroup org-priorities nil
2764 "Priorities in Org-mode."
2765 :tag "Org Priorities"
2766 :group 'org-todo)
2768 (defcustom org-enable-priority-commands t
2769 "Non-nil means priority commands are active.
2770 When nil, these commands will be disabled, so that you never accidentally
2771 set a priority."
2772 :group 'org-priorities
2773 :type 'boolean)
2775 (defcustom org-highest-priority ?A
2776 "The highest priority of TODO items. A character like ?A, ?B etc.
2777 Must have a smaller ASCII number than `org-lowest-priority'."
2778 :group 'org-priorities
2779 :type 'character)
2781 (defcustom org-lowest-priority ?C
2782 "The lowest priority of TODO items. A character like ?A, ?B etc.
2783 Must have a larger ASCII number than `org-highest-priority'."
2784 :group 'org-priorities
2785 :type 'character)
2787 (defcustom org-default-priority ?B
2788 "The default priority of TODO items.
2789 This is the priority an item gets if no explicit priority is given.
2790 When starting to cycle on an empty priority the first step in the cycle
2791 depends on `org-priority-start-cycle-with-default'. The resulting first
2792 step priority must not exceed the range from `org-highest-priority' to
2793 `org-lowest-priority' which means that `org-default-priority' has to be
2794 in this range exclusive or inclusive the range boundaries. Else the
2795 first step refuses to set the default and the second will fall back
2796 to (depending on the command used) the highest or lowest priority."
2797 :group 'org-priorities
2798 :type 'character)
2800 (defcustom org-priority-start-cycle-with-default t
2801 "Non-nil means start with default priority when starting to cycle.
2802 When this is nil, the first step in the cycle will be (depending on the
2803 command used) one higher or lower than the default priority.
2804 See also `org-default-priority'."
2805 :group 'org-priorities
2806 :type 'boolean)
2808 (defcustom org-get-priority-function nil
2809 "Function to extract the priority from a string.
2810 The string is normally the headline. If this is nil Org computes the
2811 priority from the priority cookie like [#A] in the headline. It returns
2812 an integer, increasing by 1000 for each priority level.
2813 The user can set a different function here, which should take a string
2814 as an argument and return the numeric priority."
2815 :group 'org-priorities
2816 :version "24.1"
2817 :type '(choice
2818 (const nil)
2819 (function)))
2821 (defgroup org-time nil
2822 "Options concerning time stamps and deadlines in Org-mode."
2823 :tag "Org Time"
2824 :group 'org)
2826 (defcustom org-insert-labeled-timestamps-at-point nil
2827 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2828 When nil, these labeled time stamps are forces into the second line of an
2829 entry, just after the headline. When scheduling from the global TODO list,
2830 the time stamp will always be forced into the second line."
2831 :group 'org-time
2832 :type 'boolean)
2834 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2835 "Formats for `format-time-string' which are used for time stamps.
2836 It is not recommended to change this constant.")
2838 (defcustom org-time-stamp-rounding-minutes '(0 5)
2839 "Number of minutes to round time stamps to.
2840 These are two values, the first applies when first creating a time stamp.
2841 The second applies when changing it with the commands `S-up' and `S-down'.
2842 When changing the time stamp, this means that it will change in steps
2843 of N minutes, as given by the second value.
2845 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2846 numbers should be factors of 60, so for example 5, 10, 15.
2848 When this is larger than 1, you can still force an exact time stamp by using
2849 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2850 and by using a prefix arg to `S-up/down' to specify the exact number
2851 of minutes to shift."
2852 :group 'org-time
2853 :get #'(lambda (var) ; Make sure both elements are there
2854 (if (integerp (default-value var))
2855 (list (default-value var) 5)
2856 (default-value var)))
2857 :type '(list
2858 (integer :tag "when inserting times")
2859 (integer :tag "when modifying times")))
2861 ;; Normalize old customizations of this variable.
2862 (when (integerp org-time-stamp-rounding-minutes)
2863 (setq org-time-stamp-rounding-minutes
2864 (list org-time-stamp-rounding-minutes
2865 org-time-stamp-rounding-minutes)))
2867 (defcustom org-display-custom-times nil
2868 "Non-nil means overlay custom formats over all time stamps.
2869 The formats are defined through the variable `org-time-stamp-custom-formats'.
2870 To turn this on on a per-file basis, insert anywhere in the file:
2871 #+STARTUP: customtime"
2872 :group 'org-time
2873 :set 'set-default
2874 :type 'sexp)
2875 (make-variable-buffer-local 'org-display-custom-times)
2877 (defcustom org-time-stamp-custom-formats
2878 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2879 "Custom formats for time stamps. See `format-time-string' for the syntax.
2880 These are overlaid over the default ISO format if the variable
2881 `org-display-custom-times' is set. Time like %H:%M should be at the
2882 end of the second format. The custom formats are also honored by export
2883 commands, if custom time display is turned on at the time of export."
2884 :group 'org-time
2885 :type 'sexp)
2887 (defun org-time-stamp-format (&optional long inactive)
2888 "Get the right format for a time string."
2889 (let ((f (if long (cdr org-time-stamp-formats)
2890 (car org-time-stamp-formats))))
2891 (if inactive
2892 (concat "[" (substring f 1 -1) "]")
2893 f)))
2895 (defcustom org-time-clocksum-format
2896 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2897 "The format string used when creating CLOCKSUM lines.
2898 This is also used when Org mode generates a time duration.
2900 The value can be a single format string containing two
2901 %-sequences, which will be filled with the number of hours and
2902 minutes in that order.
2904 Alternatively, the value can be a plist associating any of the
2905 keys :years, :months, :weeks, :days, :hours or :minutes with
2906 format strings. The time duration is formatted using only the
2907 time components that are needed and concatenating the results.
2908 If a time unit in absent, it falls back to the next smallest
2909 unit.
2911 The keys :require-years, :require-months, :require-days,
2912 :require-weeks, :require-hours, :require-minutes are also
2913 meaningful. A non-nil value for these keys indicates that the
2914 corresponding time component should always be included, even if
2915 its value is 0.
2918 For example,
2920 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2921 :require-minutes t)
2923 means durations longer than a day will be expressed in days,
2924 hours and minutes, and durations less than a day will always be
2925 expressed in hours and minutes (even for durations less than an
2926 hour).
2928 The value
2930 \(:days \"%dd\" :minutes \"%dm\")
2932 means durations longer than a day will be expressed in days and
2933 minutes, and durations less than a day will be expressed entirely
2934 in minutes (even for durations longer than an hour)."
2935 :group 'org-time
2936 :group 'org-clock
2937 :version "24.4"
2938 :package-version '(Org . "8.0")
2939 :type '(choice (string :tag "Format string")
2940 (set :tag "Plist"
2941 (group :inline t (const :tag "Years" :years)
2942 (string :tag "Format string"))
2943 (group :inline t
2944 (const :tag "Always show years" :require-years)
2945 (const t))
2946 (group :inline t (const :tag "Months" :months)
2947 (string :tag "Format string"))
2948 (group :inline t
2949 (const :tag "Always show months" :require-months)
2950 (const t))
2951 (group :inline t (const :tag "Weeks" :weeks)
2952 (string :tag "Format string"))
2953 (group :inline t
2954 (const :tag "Always show weeks" :require-weeks)
2955 (const t))
2956 (group :inline t (const :tag "Days" :days)
2957 (string :tag "Format string"))
2958 (group :inline t
2959 (const :tag "Always show days" :require-days)
2960 (const t))
2961 (group :inline t (const :tag "Hours" :hours)
2962 (string :tag "Format string"))
2963 (group :inline t
2964 (const :tag "Always show hours" :require-hours)
2965 (const t))
2966 (group :inline t (const :tag "Minutes" :minutes)
2967 (string :tag "Format string"))
2968 (group :inline t
2969 (const :tag "Always show minutes" :require-minutes)
2970 (const t)))))
2972 (defcustom org-time-clocksum-use-fractional nil
2973 "When non-nil, \\[org-clock-display] uses fractional times.
2974 See `org-time-clocksum-format' for more on time clock formats."
2975 :group 'org-time
2976 :group 'org-clock
2977 :version "24.3"
2978 :type 'boolean)
2980 (defcustom org-time-clocksum-use-effort-durations nil
2981 "When non-nil, \\[org-clock-display] uses effort durations.
2982 E.g. by default, one day is considered to be a 8 hours effort,
2983 so a task that has been clocked for 16 hours will be displayed
2984 as during 2 days in the clock display or in the clocktable.
2986 See `org-effort-durations' on how to set effort durations
2987 and `org-time-clocksum-format' for more on time clock formats."
2988 :group 'org-time
2989 :group 'org-clock
2990 :version "24.4"
2991 :package-version '(Org . "8.0")
2992 :type 'boolean)
2994 (defcustom org-time-clocksum-fractional-format "%.2f"
2995 "The format string used when creating CLOCKSUM lines,
2996 or when Org mode generates a time duration, if
2997 `org-time-clocksum-use-fractional' is enabled.
2999 The value can be a single format string containing one
3000 %-sequence, which will be filled with the number of hours as
3001 a float.
3003 Alternatively, the value can be a plist associating any of the
3004 keys :years, :months, :weeks, :days, :hours or :minutes with
3005 a format string. The time duration is formatted using the
3006 largest time unit which gives a non-zero integer part. If all
3007 specified formats have zero integer part, the smallest time unit
3008 is used."
3009 :group 'org-time
3010 :type '(choice (string :tag "Format string")
3011 (set (group :inline t (const :tag "Years" :years)
3012 (string :tag "Format string"))
3013 (group :inline t (const :tag "Months" :months)
3014 (string :tag "Format string"))
3015 (group :inline t (const :tag "Weeks" :weeks)
3016 (string :tag "Format string"))
3017 (group :inline t (const :tag "Days" :days)
3018 (string :tag "Format string"))
3019 (group :inline t (const :tag "Hours" :hours)
3020 (string :tag "Format string"))
3021 (group :inline t (const :tag "Minutes" :minutes)
3022 (string :tag "Format string")))))
3024 (defcustom org-deadline-warning-days 14
3025 "Number of days before expiration during which a deadline becomes active.
3026 This variable governs the display in sparse trees and in the agenda.
3027 When 0 or negative, it means use this number (the absolute value of it)
3028 even if a deadline has a different individual lead time specified.
3030 Custom commands can set this variable in the options section."
3031 :group 'org-time
3032 :group 'org-agenda-daily/weekly
3033 :type 'integer)
3035 (defcustom org-scheduled-delay-days 0
3036 "Number of days before a scheduled item becomes active.
3037 This variable governs the display in sparse trees and in the agenda.
3038 The default value (i.e. 0) means: don't delay scheduled item.
3039 When negative, it means use this number (the absolute value of it)
3040 even if a scheduled item has a different individual delay time
3041 specified.
3043 Custom commands can set this variable in the options section."
3044 :group 'org-time
3045 :group 'org-agenda-daily/weekly
3046 :version "24.4"
3047 :package-version '(Org . "8.0")
3048 :type 'integer)
3050 (defcustom org-read-date-prefer-future t
3051 "Non-nil means assume future for incomplete date input from user.
3052 This affects the following situations:
3053 1. The user gives a month but not a year.
3054 For example, if it is April and you enter \"feb 2\", this will be read
3055 as Feb 2, *next* year. \"May 5\", however, will be this year.
3056 2. The user gives a day, but no month.
3057 For example, if today is the 15th, and you enter \"3\", Org-mode will
3058 read this as the third of *next* month. However, if you enter \"17\",
3059 it will be considered as *this* month.
3061 If you set this variable to the symbol `time', then also the following
3062 will work:
3064 3. If the user gives a time.
3065 If the time is before now, it will be interpreted as tomorrow.
3067 Currently none of this works for ISO week specifications.
3069 When this option is nil, the current day, month and year will always be
3070 used as defaults.
3072 See also `org-agenda-jump-prefer-future'."
3073 :group 'org-time
3074 :type '(choice
3075 (const :tag "Never" nil)
3076 (const :tag "Check month and day" t)
3077 (const :tag "Check month, day, and time" time)))
3079 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3080 "Should the agenda jump command prefer the future for incomplete dates?
3081 The default is to do the same as configured in `org-read-date-prefer-future'.
3082 But you can also set a deviating value here.
3083 This may t or nil, or the symbol `org-read-date-prefer-future'."
3084 :group 'org-agenda
3085 :group 'org-time
3086 :version "24.1"
3087 :type '(choice
3088 (const :tag "Use org-read-date-prefer-future"
3089 org-read-date-prefer-future)
3090 (const :tag "Never" nil)
3091 (const :tag "Always" t)))
3093 (defcustom org-read-date-force-compatible-dates t
3094 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3096 Depending on the system Emacs is running on, certain dates cannot
3097 be represented with the type used internally to represent time.
3098 Dates between 1970-1-1 and 2038-1-1 can always be represented
3099 correctly. Some systems allow for earlier dates, some for later,
3100 some for both. One way to find out it to insert any date into an
3101 Org buffer, putting the cursor on the year and hitting S-up and
3102 S-down to test the range.
3104 When this variable is set to t, the date/time prompt will not let
3105 you specify dates outside the 1970-2037 range, so it is certain that
3106 these dates will work in whatever version of Emacs you are
3107 running, and also that you can move a file from one Emacs implementation
3108 to another. WHenever Org is forcing the year for you, it will display
3109 a message and beep.
3111 When this variable is nil, Org will check if the date is
3112 representable in the specific Emacs implementation you are using.
3113 If not, it will force a year, usually the current year, and beep
3114 to remind you. Currently this setting is not recommended because
3115 the likelihood that you will open your Org files in an Emacs that
3116 has limited date range is not negligible.
3118 A workaround for this problem is to use diary sexp dates for time
3119 stamps outside of this range."
3120 :group 'org-time
3121 :version "24.1"
3122 :type 'boolean)
3124 (defcustom org-read-date-display-live t
3125 "Non-nil means display current interpretation of date prompt live.
3126 This display will be in an overlay, in the minibuffer."
3127 :group 'org-time
3128 :type 'boolean)
3130 (defcustom org-read-date-popup-calendar t
3131 "Non-nil means pop up a calendar when prompting for a date.
3132 In the calendar, the date can be selected with mouse-1. However, the
3133 minibuffer will also be active, and you can simply enter the date as well.
3134 When nil, only the minibuffer will be available."
3135 :group 'org-time
3136 :type 'boolean)
3137 (org-defvaralias 'org-popup-calendar-for-date-prompt
3138 'org-read-date-popup-calendar)
3140 (make-obsolete-variable
3141 'org-read-date-minibuffer-setup-hook
3142 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3143 (defcustom org-read-date-minibuffer-setup-hook nil
3144 "Hook to be used to set up keys for the date/time interface.
3145 Add key definitions to `minibuffer-local-map', which will be a
3146 temporary copy.
3148 WARNING: This option is obsolete, you should use
3149 `org-read-date-minibuffer-local-map' to set up keys."
3150 :group 'org-time
3151 :type 'hook)
3153 (defcustom org-extend-today-until 0
3154 "The hour when your day really ends. Must be an integer.
3155 This has influence for the following applications:
3156 - When switching the agenda to \"today\". It it is still earlier than
3157 the time given here, the day recognized as TODAY is actually yesterday.
3158 - When a date is read from the user and it is still before the time given
3159 here, the current date and time will be assumed to be yesterday, 23:59.
3160 Also, timestamps inserted in capture templates follow this rule.
3162 IMPORTANT: This is a feature whose implementation is and likely will
3163 remain incomplete. Really, it is only here because past midnight seems to
3164 be the favorite working time of John Wiegley :-)"
3165 :group 'org-time
3166 :type 'integer)
3168 (defcustom org-use-effective-time nil
3169 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3170 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3171 \"effective time\" of any timestamps between midnight and 8am will be
3172 23:59 of the previous day."
3173 :group 'org-time
3174 :version "24.1"
3175 :type 'boolean)
3177 (defcustom org-use-last-clock-out-time-as-effective-time nil
3178 "When non-nil, use the last clock out time for `org-todo'.
3179 Note that this option has precedence over the combined use of
3180 `org-use-effective-time' and `org-extend-today-until'."
3181 :group 'org-time
3182 :version "24.4"
3183 :package-version '(Org . "8.0")
3184 :type 'boolean)
3186 (defcustom org-edit-timestamp-down-means-later nil
3187 "Non-nil means S-down will increase the time in a time stamp.
3188 When nil, S-up will increase."
3189 :group 'org-time
3190 :type 'boolean)
3192 (defcustom org-calendar-follow-timestamp-change t
3193 "Non-nil means make the calendar window follow timestamp changes.
3194 When a timestamp is modified and the calendar window is visible, it will be
3195 moved to the new date."
3196 :group 'org-time
3197 :type 'boolean)
3199 (defgroup org-tags nil
3200 "Options concerning tags in Org-mode."
3201 :tag "Org Tags"
3202 :group 'org)
3204 (defcustom org-tag-alist nil
3205 "List of tags allowed in Org-mode files.
3206 When this list is nil, Org-mode will base TAG input on what is already in the
3207 buffer.
3208 The value of this variable is an alist, the car of each entry must be a
3209 keyword as a string, the cdr may be a character that is used to select
3210 that tag through the fast-tag-selection interface.
3211 See the manual for details."
3212 :group 'org-tags
3213 :type '(repeat
3214 (choice
3215 (cons (string :tag "Tag name")
3216 (character :tag "Access char"))
3217 (list :tag "Start radio group"
3218 (const :startgroup)
3219 (option (string :tag "Group description")))
3220 (list :tag "Group tags delimiter"
3221 (const :grouptags))
3222 (list :tag "End radio group"
3223 (const :endgroup)
3224 (option (string :tag "Group description")))
3225 (const :tag "New line" (:newline)))))
3227 (defcustom org-tag-persistent-alist nil
3228 "List of tags that will always appear in all Org-mode files.
3229 This is in addition to any in buffer settings or customizations
3230 of `org-tag-alist'.
3231 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3232 The value of this variable is an alist, the car of each entry must be a
3233 keyword as a string, the cdr may be a character that is used to select
3234 that tag through the fast-tag-selection interface.
3235 See the manual for details.
3236 To disable these tags on a per-file basis, insert anywhere in the file:
3237 #+STARTUP: noptag"
3238 :group 'org-tags
3239 :type '(repeat
3240 (choice
3241 (cons (string :tag "Tag name")
3242 (character :tag "Access char"))
3243 (const :tag "Start radio group" (:startgroup))
3244 (const :tag "Group tags delimiter" (:grouptags))
3245 (const :tag "End radio group" (:endgroup))
3246 (const :tag "New line" (:newline)))))
3248 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3249 "If non-nil, always offer completion for all tags of all agenda files.
3250 Instead of customizing this variable directly, you might want to
3251 set it locally for capture buffers, because there no list of
3252 tags in that file can be created dynamically (there are none).
3254 (add-hook 'org-capture-mode-hook
3255 (lambda ()
3256 (set (make-local-variable
3257 'org-complete-tags-always-offer-all-agenda-tags)
3258 t)))"
3259 :group 'org-tags
3260 :version "24.1"
3261 :type 'boolean)
3263 (defvar org-file-tags nil
3264 "List of tags that can be inherited by all entries in the file.
3265 The tags will be inherited if the variable `org-use-tag-inheritance'
3266 says they should be.
3267 This variable is populated from #+FILETAGS lines.")
3269 (defcustom org-use-fast-tag-selection 'auto
3270 "Non-nil means use fast tag selection scheme.
3271 This is a special interface to select and deselect tags with single keys.
3272 When nil, fast selection is never used.
3273 When the symbol `auto', fast selection is used if and only if selection
3274 characters for tags have been configured, either through the variable
3275 `org-tag-alist' or through a #+TAGS line in the buffer.
3276 When t, fast selection is always used and selection keys are assigned
3277 automatically if necessary."
3278 :group 'org-tags
3279 :type '(choice
3280 (const :tag "Always" t)
3281 (const :tag "Never" nil)
3282 (const :tag "When selection characters are configured" auto)))
3284 (defcustom org-fast-tag-selection-single-key nil
3285 "Non-nil means fast tag selection exits after first change.
3286 When nil, you have to press RET to exit it.
3287 During fast tag selection, you can toggle this flag with `C-c'.
3288 This variable can also have the value `expert'. In this case, the window
3289 displaying the tags menu is not even shown, until you press C-c again."
3290 :group 'org-tags
3291 :type '(choice
3292 (const :tag "No" nil)
3293 (const :tag "Yes" t)
3294 (const :tag "Expert" expert)))
3296 (defvar org-fast-tag-selection-include-todo nil
3297 "Non-nil means fast tags selection interface will also offer TODO states.
3298 This is an undocumented feature, you should not rely on it.")
3300 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3301 "The column to which tags should be indented in a headline.
3302 If this number is positive, it specifies the column. If it is negative,
3303 it means that the tags should be flushright to that column. For example,
3304 -80 works well for a normal 80 character screen.
3305 When 0, place tags directly after headline text, with only one space in
3306 between."
3307 :group 'org-tags
3308 :type 'integer)
3310 (defcustom org-auto-align-tags t
3311 "Non-nil keeps tags aligned when modifying headlines.
3312 Some operations (i.e. demoting) change the length of a headline and
3313 therefore shift the tags around. With this option turned on, after
3314 each such operation the tags are again aligned to `org-tags-column'."
3315 :group 'org-tags
3316 :type 'boolean)
3318 (defcustom org-use-tag-inheritance t
3319 "Non-nil means tags in levels apply also for sublevels.
3320 When nil, only the tags directly given in a specific line apply there.
3321 This may also be a list of tags that should be inherited, or a regexp that
3322 matches tags that should be inherited. Additional control is possible
3323 with the variable `org-tags-exclude-from-inheritance' which gives an
3324 explicit list of tags to be excluded from inheritance, even if the value of
3325 `org-use-tag-inheritance' would select it for inheritance.
3327 If this option is t, a match early-on in a tree can lead to a large
3328 number of matches in the subtree when constructing the agenda or creating
3329 a sparse tree. If you only want to see the first match in a tree during
3330 a search, check out the variable `org-tags-match-list-sublevels'."
3331 :group 'org-tags
3332 :type '(choice
3333 (const :tag "Not" nil)
3334 (const :tag "Always" t)
3335 (repeat :tag "Specific tags" (string :tag "Tag"))
3336 (regexp :tag "Tags matched by regexp")))
3338 (defcustom org-tags-exclude-from-inheritance nil
3339 "List of tags that should never be inherited.
3340 This is a way to exclude a few tags from inheritance. For way to do
3341 the opposite, to actively allow inheritance for selected tags,
3342 see the variable `org-use-tag-inheritance'."
3343 :group 'org-tags
3344 :type '(repeat (string :tag "Tag")))
3346 (defun org-tag-inherit-p (tag)
3347 "Check if TAG is one that should be inherited."
3348 (cond
3349 ((member tag org-tags-exclude-from-inheritance) nil)
3350 ((eq org-use-tag-inheritance t) t)
3351 ((not org-use-tag-inheritance) nil)
3352 ((stringp org-use-tag-inheritance)
3353 (string-match org-use-tag-inheritance tag))
3354 ((listp org-use-tag-inheritance)
3355 (member tag org-use-tag-inheritance))
3356 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3358 (defcustom org-tags-match-list-sublevels t
3359 "Non-nil means list also sublevels of headlines matching a search.
3360 This variable applies to tags/property searches, and also to stuck
3361 projects because this search is based on a tags match as well.
3363 When set to the symbol `indented', sublevels are indented with
3364 leading dots.
3366 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3367 the sublevels of a headline matching a tag search often also match
3368 the same search. Listing all of them can create very long lists.
3369 Setting this variable to nil causes subtrees of a match to be skipped.
3371 This variable is semi-obsolete and probably should always be true. It
3372 is better to limit inheritance to certain tags using the variables
3373 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3374 :group 'org-tags
3375 :type '(choice
3376 (const :tag "No, don't list them" nil)
3377 (const :tag "Yes, do list them" t)
3378 (const :tag "List them, indented with leading dots" indented)))
3380 (defcustom org-tags-sort-function nil
3381 "When set, tags are sorted using this function as a comparator."
3382 :group 'org-tags
3383 :type '(choice
3384 (const :tag "No sorting" nil)
3385 (const :tag "Alphabetical" string<)
3386 (const :tag "Reverse alphabetical" string>)
3387 (function :tag "Custom function" nil)))
3389 (defvar org-tags-history nil
3390 "History of minibuffer reads for tags.")
3391 (defvar org-last-tags-completion-table nil
3392 "The last used completion table for tags.")
3393 (defvar org-after-tags-change-hook nil
3394 "Hook that is run after the tags in a line have changed.")
3396 (defgroup org-properties nil
3397 "Options concerning properties in Org-mode."
3398 :tag "Org Properties"
3399 :group 'org)
3401 (defcustom org-property-format "%-10s %s"
3402 "How property key/value pairs should be formatted by `indent-line'.
3403 When `indent-line' hits a property definition, it will format the line
3404 according to this format, mainly to make sure that the values are
3405 lined-up with respect to each other."
3406 :group 'org-properties
3407 :type 'string)
3409 (defcustom org-properties-postprocess-alist nil
3410 "Alist of properties and functions to adjust inserted values.
3411 Elements of this alist must be of the form
3413 ([string] [function])
3415 where [string] must be a property name and [function] must be a
3416 lambda expression: this lambda expression must take one argument,
3417 the value to adjust, and return the new value as a string.
3419 For example, this element will allow the property \"Remaining\"
3420 to be updated wrt the relation between the \"Effort\" property
3421 and the clock summary:
3423 ((\"Remaining\" (lambda(value)
3424 (let ((clocksum (org-clock-sum-current-item))
3425 (effort (org-duration-string-to-minutes
3426 (org-entry-get (point) \"Effort\"))))
3427 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3428 :group 'org-properties
3429 :version "24.1"
3430 :type '(alist :key-type (string :tag "Property")
3431 :value-type (function :tag "Function")))
3433 (defcustom org-use-property-inheritance nil
3434 "Non-nil means properties apply also for sublevels.
3436 This setting is chiefly used during property searches. Turning it on can
3437 cause significant overhead when doing a search, which is why it is not
3438 on by default.
3440 When nil, only the properties directly given in the current entry count.
3441 When t, every property is inherited. The value may also be a list of
3442 properties that should have inheritance, or a regular expression matching
3443 properties that should be inherited.
3445 However, note that some special properties use inheritance under special
3446 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3447 and the properties ending in \"_ALL\" when they are used as descriptor
3448 for valid values of a property.
3450 Note for programmers:
3451 When querying an entry with `org-entry-get', you can control if inheritance
3452 should be used. By default, `org-entry-get' looks only at the local
3453 properties. You can request inheritance by setting the inherit argument
3454 to t (to force inheritance) or to `selective' (to respect the setting
3455 in this variable)."
3456 :group 'org-properties
3457 :type '(choice
3458 (const :tag "Not" nil)
3459 (const :tag "Always" t)
3460 (repeat :tag "Specific properties" (string :tag "Property"))
3461 (regexp :tag "Properties matched by regexp")))
3463 (defun org-property-inherit-p (property)
3464 "Check if PROPERTY is one that should be inherited."
3465 (cond
3466 ((eq org-use-property-inheritance t) t)
3467 ((not org-use-property-inheritance) nil)
3468 ((stringp org-use-property-inheritance)
3469 (string-match org-use-property-inheritance property))
3470 ((listp org-use-property-inheritance)
3471 (member property org-use-property-inheritance))
3472 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3474 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3475 "The default column format, if no other format has been defined.
3476 This variable can be set on the per-file basis by inserting a line
3478 #+COLUMNS: %25ITEM ....."
3479 :group 'org-properties
3480 :type 'string)
3482 (defcustom org-columns-ellipses ".."
3483 "The ellipses to be used when a field in column view is truncated.
3484 When this is the empty string, as many characters as possible are shown,
3485 but then there will be no visual indication that the field has been truncated.
3486 When this is a string of length N, the last N characters of a truncated
3487 field are replaced by this string. If the column is narrower than the
3488 ellipses string, only part of the ellipses string will be shown."
3489 :group 'org-properties
3490 :type 'string)
3492 (defcustom org-columns-modify-value-for-display-function nil
3493 "Function that modifies values for display in column view.
3494 For example, it can be used to cut out a certain part from a time stamp.
3495 The function must take 2 arguments:
3497 column-title The title of the column (*not* the property name)
3498 value The value that should be modified.
3500 The function should return the value that should be displayed,
3501 or nil if the normal value should be used."
3502 :group 'org-properties
3503 :type '(choice (const nil) (function)))
3505 (defcustom org-effort-property "Effort"
3506 "The property that is being used to keep track of effort estimates.
3507 Effort estimates given in this property need to have the format H:MM."
3508 :group 'org-properties
3509 :group 'org-progress
3510 :type '(string :tag "Property"))
3512 (defconst org-global-properties-fixed
3513 '(("VISIBILITY_ALL" . "folded children content all")
3514 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3515 "List of property/value pairs that can be inherited by any entry.
3517 These are fixed values, for the preset properties. The user variable
3518 that can be used to add to this list is `org-global-properties'.
3520 The entries in this list are cons cells where the car is a property
3521 name and cdr is a string with the value. If the value represents
3522 multiple items like an \"_ALL\" property, separate the items by
3523 spaces.")
3525 (defcustom org-global-properties nil
3526 "List of property/value pairs that can be inherited by any entry.
3528 This list will be combined with the constant `org-global-properties-fixed'.
3530 The entries in this list are cons cells where the car is a property
3531 name and cdr is a string with the value.
3533 You can set buffer-local values for the same purpose in the variable
3534 `org-file-properties' this by adding lines like
3536 #+PROPERTY: NAME VALUE"
3537 :group 'org-properties
3538 :type '(repeat
3539 (cons (string :tag "Property")
3540 (string :tag "Value"))))
3542 (defvar org-file-properties nil
3543 "List of property/value pairs that can be inherited by any entry.
3544 Valid for the current buffer.
3545 This variable is populated from #+PROPERTY lines.")
3546 (make-variable-buffer-local 'org-file-properties)
3548 (defgroup org-agenda nil
3549 "Options concerning agenda views in Org-mode."
3550 :tag "Org Agenda"
3551 :group 'org)
3553 (defvar org-category nil
3554 "Variable used by org files to set a category for agenda display.
3555 Such files should use a file variable to set it, for example
3557 # -*- mode: org; org-category: \"ELisp\"
3559 or contain a special line
3561 #+CATEGORY: ELisp
3563 If the file does not specify a category, then file's base name
3564 is used instead.")
3565 (make-variable-buffer-local 'org-category)
3566 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3568 (defcustom org-agenda-files nil
3569 "The files to be used for agenda display.
3570 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3571 \\[org-remove-file]. You can also use customize to edit the list.
3573 If an entry is a directory, all files in that directory that are matched by
3574 `org-agenda-file-regexp' will be part of the file list.
3576 If the value of the variable is not a list but a single file name, then
3577 the list of agenda files is actually stored and maintained in that file, one
3578 agenda file per line. In this file paths can be given relative to
3579 `org-directory'. Tilde expansion and environment variable substitution
3580 are also made."
3581 :group 'org-agenda
3582 :type '(choice
3583 (repeat :tag "List of files and directories" file)
3584 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3586 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3587 "Regular expression to match files for `org-agenda-files'.
3588 If any element in the list in that variable contains a directory instead
3589 of a normal file, all files in that directory that are matched by this
3590 regular expression will be included."
3591 :group 'org-agenda
3592 :type 'regexp)
3594 (defcustom org-agenda-text-search-extra-files nil
3595 "List of extra files to be searched by text search commands.
3596 These files will be searched in addition to the agenda files by the
3597 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3598 Note that these files will only be searched for text search commands,
3599 not for the other agenda views like todo lists, tag searches or the weekly
3600 agenda. This variable is intended to list notes and possibly archive files
3601 that should also be searched by these two commands.
3602 In fact, if the first element in the list is the symbol `agenda-archives',
3603 then all archive files of all agenda files will be added to the search
3604 scope."
3605 :group 'org-agenda
3606 :type '(set :greedy t
3607 (const :tag "Agenda Archives" agenda-archives)
3608 (repeat :inline t (file))))
3610 (org-defvaralias 'org-agenda-multi-occur-extra-files
3611 'org-agenda-text-search-extra-files)
3613 (defcustom org-agenda-skip-unavailable-files nil
3614 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3615 A nil value means to remove them, after a query, from the list."
3616 :group 'org-agenda
3617 :type 'boolean)
3619 (defcustom org-calendar-to-agenda-key [?c]
3620 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3621 The command `org-calendar-goto-agenda' will be bound to this key. The
3622 default is the character `c' because then `c' can be used to switch back and
3623 forth between agenda and calendar."
3624 :group 'org-agenda
3625 :type 'sexp)
3627 (defcustom org-calendar-insert-diary-entry-key [?i]
3628 "The key to be installed in `calendar-mode-map' for adding diary entries.
3629 This option is irrelevant until `org-agenda-diary-file' has been configured
3630 to point to an Org-mode file. When that is the case, the command
3631 `org-agenda-diary-entry' will be bound to the key given here, by default
3632 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3633 if you want to continue doing this, you need to change this to a different
3634 key."
3635 :group 'org-agenda
3636 :type 'sexp)
3638 (defcustom org-agenda-diary-file 'diary-file
3639 "File to which to add new entries with the `i' key in agenda and calendar.
3640 When this is the symbol `diary-file', the functionality in the Emacs
3641 calendar will be used to add entries to the `diary-file'. But when this
3642 points to a file, `org-agenda-diary-entry' will be used instead."
3643 :group 'org-agenda
3644 :type '(choice
3645 (const :tag "The standard Emacs diary file" diary-file)
3646 (file :tag "Special Org file diary entries")))
3648 (eval-after-load "calendar"
3649 '(progn
3650 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3651 'org-calendar-goto-agenda)
3652 (add-hook 'calendar-mode-hook
3653 (lambda ()
3654 (unless (eq org-agenda-diary-file 'diary-file)
3655 (define-key calendar-mode-map
3656 org-calendar-insert-diary-entry-key
3657 'org-agenda-diary-entry))))))
3659 (defgroup org-latex nil
3660 "Options for embedding LaTeX code into Org-mode."
3661 :tag "Org LaTeX"
3662 :group 'org)
3664 (defcustom org-format-latex-options
3665 '(:foreground default :background default :scale 1.0
3666 :html-foreground "Black" :html-background "Transparent"
3667 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3668 "Options for creating images from LaTeX fragments.
3669 This is a property list with the following properties:
3670 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3671 `default' means use the foreground of the default face.
3672 `auto' means use the foreground from the text face.
3673 :background the background color, or \"Transparent\".
3674 `default' means use the background of the default face.
3675 `auto' means use the background from the text face.
3676 :scale a scaling factor for the size of the images, to get more pixels
3677 :html-foreground, :html-background, :html-scale
3678 the same numbers for HTML export.
3679 :matchers a list indicating which matchers should be used to
3680 find LaTeX fragments. Valid members of this list are:
3681 \"begin\" find environments
3682 \"$1\" find single characters surrounded by $.$
3683 \"$\" find math expressions surrounded by $...$
3684 \"$$\" find math expressions surrounded by $$....$$
3685 \"\\(\" find math expressions surrounded by \\(...\\)
3686 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3687 :group 'org-latex
3688 :type 'plist)
3690 (defcustom org-format-latex-signal-error t
3691 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3692 When nil, just push out a message."
3693 :group 'org-latex
3694 :version "24.1"
3695 :type 'boolean)
3697 (defcustom org-latex-to-mathml-jar-file nil
3698 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3699 Use this to specify additional executable file say a jar file.
3701 When using MathToWeb as the converter, specify the full-path to
3702 your mathtoweb.jar file."
3703 :group 'org-latex
3704 :version "24.1"
3705 :type '(choice
3706 (const :tag "None" nil)
3707 (file :tag "JAR file" :must-match t)))
3709 (defcustom org-latex-to-mathml-convert-command nil
3710 "Command to convert LaTeX fragments to MathML.
3711 Replace format-specifiers in the command as noted below and use
3712 `shell-command' to convert LaTeX to MathML.
3713 %j: Executable file in fully expanded form as specified by
3714 `org-latex-to-mathml-jar-file'.
3715 %I: Input LaTeX file in fully expanded form
3716 %o: Output MathML file
3717 This command is used by `org-create-math-formula'.
3719 When using MathToWeb as the converter, set this to
3720 \"java -jar %j -unicode -force -df %o %I\"."
3721 :group 'org-latex
3722 :version "24.1"
3723 :type '(choice
3724 (const :tag "None" nil)
3725 (string :tag "\nShell command")))
3727 (defcustom org-latex-create-formula-image-program 'dvipng
3728 "Program to convert LaTeX fragments with.
3730 dvipng Process the LaTeX fragments to dvi file, then convert
3731 dvi files to png files using dvipng.
3732 This will also include processing of non-math environments.
3733 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3734 to convert pdf files to png files"
3735 :group 'org-latex
3736 :version "24.1"
3737 :type '(choice
3738 (const :tag "dvipng" dvipng)
3739 (const :tag "imagemagick" imagemagick)))
3741 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3742 "Path to store latex preview images.
3743 A relative path here creates many directories relative to the
3744 processed org files paths. An absolute path puts all preview
3745 images at the same place."
3746 :group 'org-latex
3747 :version "24.3"
3748 :type 'string)
3750 (defun org-format-latex-mathml-available-p ()
3751 "Return t if `org-latex-to-mathml-convert-command' is usable."
3752 (save-match-data
3753 (when (and (boundp 'org-latex-to-mathml-convert-command)
3754 org-latex-to-mathml-convert-command)
3755 (let ((executable (car (split-string
3756 org-latex-to-mathml-convert-command))))
3757 (when (executable-find executable)
3758 (if (string-match
3759 "%j" org-latex-to-mathml-convert-command)
3760 (file-readable-p org-latex-to-mathml-jar-file)
3761 t))))))
3763 (defcustom org-format-latex-header "\\documentclass{article}
3764 \\usepackage[usenames]{color}
3765 \\usepackage{amsmath}
3766 \\usepackage[mathscr]{eucal}
3767 \\pagestyle{empty} % do not remove
3768 \[PACKAGES]
3769 \[DEFAULT-PACKAGES]
3770 % The settings below are copied from fullpage.sty
3771 \\setlength{\\textwidth}{\\paperwidth}
3772 \\addtolength{\\textwidth}{-3cm}
3773 \\setlength{\\oddsidemargin}{1.5cm}
3774 \\addtolength{\\oddsidemargin}{-2.54cm}
3775 \\setlength{\\evensidemargin}{\\oddsidemargin}
3776 \\setlength{\\textheight}{\\paperheight}
3777 \\addtolength{\\textheight}{-\\headheight}
3778 \\addtolength{\\textheight}{-\\headsep}
3779 \\addtolength{\\textheight}{-\\footskip}
3780 \\addtolength{\\textheight}{-3cm}
3781 \\setlength{\\topmargin}{1.5cm}
3782 \\addtolength{\\topmargin}{-2.54cm}"
3783 "The document header used for processing LaTeX fragments.
3784 It is imperative that this header make sure that no page number
3785 appears on the page. The package defined in the variables
3786 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3787 will either replace the placeholder \"[PACKAGES]\" in this
3788 header, or they will be appended."
3789 :group 'org-latex
3790 :type 'string)
3792 (defun org-set-packages-alist (var val)
3793 "Set the packages alist and make sure it has 3 elements per entry."
3794 (set var (mapcar (lambda (x)
3795 (if (and (consp x) (= (length x) 2))
3796 (list (car x) (nth 1 x) t)
3798 val)))
3800 (defun org-get-packages-alist (var)
3801 "Get the packages alist and make sure it has 3 elements per entry."
3802 (mapcar (lambda (x)
3803 (if (and (consp x) (= (length x) 2))
3804 (list (car x) (nth 1 x) t)
3806 (default-value var)))
3808 (defcustom org-latex-default-packages-alist
3809 '(("AUTO" "inputenc" t)
3810 ("T1" "fontenc" t)
3811 ("" "fixltx2e" nil)
3812 ("" "graphicx" t)
3813 ("" "longtable" nil)
3814 ("" "float" nil)
3815 ("" "wrapfig" nil)
3816 ("normalem" "ulem" t)
3817 ("" "textcomp" t)
3818 ("" "marvosym" t)
3819 ("" "wasysym" t)
3820 ("" "latexsym" t)
3821 ("" "amssymb" t)
3822 ("" "amstext" nil)
3823 ("" "hyperref" nil)
3824 "\\tolerance=1000")
3825 "Alist of default packages to be inserted in the header.
3827 Change this only if one of the packages here causes an
3828 incompatibility with another package you are using.
3830 The packages in this list are needed by one part or another of
3831 Org mode to function properly:
3833 - inputenc, fontenc: for basic font and character selection
3834 - amstext: for subscript and superscript
3835 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3836 symbols used for interpreting the entities in `org-entities'.
3837 You can skip some of these packages if you don't use any of the
3838 symbols in it.
3839 - ulem: for underline and strike-through
3840 - graphicx: for including images
3841 - float, wrapfig: for figure placement
3842 - longtable: for long tables
3843 - hyperref: for cross references
3845 Therefore you should not modify this variable unless you know
3846 what you are doing. The one reason to change it anyway is that
3847 you might be loading some other package that conflicts with one
3848 of the default packages. Each cell is of the format
3849 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3850 the package also needs to be included when compiling LaTeX
3851 snippets into images for inclusion into non-LaTeX output."
3852 :group 'org-latex
3853 :group 'org-export-latex
3854 :set 'org-set-packages-alist
3855 :get 'org-get-packages-alist
3856 :version "24.1"
3857 :type '(repeat
3858 (choice
3859 (list :tag "options/package pair"
3860 (string :tag "options")
3861 (string :tag "package")
3862 (boolean :tag "Snippet"))
3863 (string :tag "A line of LaTeX"))))
3865 (defcustom org-latex-packages-alist nil
3866 "Alist of packages to be inserted in every LaTeX header.
3868 These will be inserted after `org-latex-default-packages-alist'.
3869 Each cell is of the format:
3871 \(\"options\" \"package\" snippet-flag)
3873 SNIPPET-FLAG, when t, indicates that this package is also needed
3874 when turning LaTeX snippets into images for inclusion into
3875 non-LaTeX output.
3877 Make sure that you only list packages here which:
3879 - you want in every file
3880 - do not conflict with the setup in `org-format-latex-header'.
3881 - do not conflict with the default packages in
3882 `org-latex-default-packages-alist'."
3883 :group 'org-latex
3884 :group 'org-export-latex
3885 :set 'org-set-packages-alist
3886 :get 'org-get-packages-alist
3887 :type '(repeat
3888 (choice
3889 (list :tag "options/package pair"
3890 (string :tag "options")
3891 (string :tag "package")
3892 (boolean :tag "Snippet"))
3893 (string :tag "A line of LaTeX"))))
3895 (defgroup org-appearance nil
3896 "Settings for Org-mode appearance."
3897 :tag "Org Appearance"
3898 :group 'org)
3900 (defcustom org-level-color-stars-only nil
3901 "Non-nil means fontify only the stars in each headline.
3902 When nil, the entire headline is fontified.
3903 Changing it requires restart of `font-lock-mode' to become effective
3904 also in regions already fontified."
3905 :group 'org-appearance
3906 :type 'boolean)
3908 (defcustom org-hide-leading-stars nil
3909 "Non-nil means hide the first N-1 stars in a headline.
3910 This works by using the face `org-hide' for these stars. This
3911 face is white for a light background, and black for a dark
3912 background. You may have to customize the face `org-hide' to
3913 make this work.
3914 Changing it requires restart of `font-lock-mode' to become effective
3915 also in regions already fontified.
3916 You may also set this on a per-file basis by adding one of the following
3917 lines to the buffer:
3919 #+STARTUP: hidestars
3920 #+STARTUP: showstars"
3921 :group 'org-appearance
3922 :type 'boolean)
3924 (defcustom org-hidden-keywords nil
3925 "List of symbols corresponding to keywords to be hidden the org buffer.
3926 For example, a value '(title) for this list will make the document's title
3927 appear in the buffer without the initial #+TITLE: keyword."
3928 :group 'org-appearance
3929 :version "24.1"
3930 :type '(set (const :tag "#+AUTHOR" author)
3931 (const :tag "#+DATE" date)
3932 (const :tag "#+EMAIL" email)
3933 (const :tag "#+TITLE" title)))
3935 (defcustom org-custom-properties nil
3936 "List of properties (as strings) with a special meaning.
3937 The default use of these custom properties is to let the user
3938 hide them with `org-toggle-custom-properties-visibility'."
3939 :group 'org-properties
3940 :group 'org-appearance
3941 :version "24.3"
3942 :type '(repeat (string :tag "Property Name")))
3944 (defcustom org-fontify-done-headline nil
3945 "Non-nil means change the face of a headline if it is marked DONE.
3946 Normally, only the TODO/DONE keyword indicates the state of a headline.
3947 When this is non-nil, the headline after the keyword is set to the
3948 `org-headline-done' as an additional indication."
3949 :group 'org-appearance
3950 :type 'boolean)
3952 (defcustom org-fontify-emphasized-text t
3953 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3954 Changing this variable requires a restart of Emacs to take effect."
3955 :group 'org-appearance
3956 :type 'boolean)
3958 (defcustom org-fontify-whole-heading-line nil
3959 "Non-nil means fontify the whole line for headings.
3960 This is useful when setting a background color for the
3961 org-level-* faces."
3962 :group 'org-appearance
3963 :type 'boolean)
3965 (defcustom org-highlight-latex-and-related nil
3966 "Non-nil means highlight LaTeX related syntax in the buffer.
3967 When non nil, the value should be a list containing any of the
3968 following symbols:
3969 `latex' Highlight LaTeX snippets and environments.
3970 `script' Highlight subscript and superscript.
3971 `entities' Highlight entities."
3972 :group 'org-appearance
3973 :version "24.4"
3974 :package-version '(Org . "8.0")
3975 :type '(choice
3976 (const :tag "No highlighting" nil)
3977 (set :greedy t :tag "Highlight"
3978 (const :tag "LaTeX snippets and environments" latex)
3979 (const :tag "Subscript and superscript" script)
3980 (const :tag "Entities" entities))))
3982 (defcustom org-hide-emphasis-markers nil
3983 "Non-nil mean font-lock should hide the emphasis marker characters."
3984 :group 'org-appearance
3985 :type 'boolean)
3987 (defcustom org-pretty-entities nil
3988 "Non-nil means show entities as UTF8 characters.
3989 When nil, the \\name form remains in the buffer."
3990 :group 'org-appearance
3991 :version "24.1"
3992 :type 'boolean)
3994 (defcustom org-pretty-entities-include-sub-superscripts t
3995 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3996 :group 'org-appearance
3997 :version "24.1"
3998 :type 'boolean)
4000 (defvar org-emph-re nil
4001 "Regular expression for matching emphasis.
4002 After a match, the match groups contain these elements:
4003 0 The match of the full regular expression, including the characters
4004 before and after the proper match
4005 1 The character before the proper match, or empty at beginning of line
4006 2 The proper match, including the leading and trailing markers
4007 3 The leading marker like * or /, indicating the type of highlighting
4008 4 The text between the emphasis markers, not including the markers
4009 5 The character after the match, empty at the end of a line")
4010 (defvar org-verbatim-re nil
4011 "Regular expression for matching verbatim text.")
4012 (defvar org-emphasis-regexp-components) ; defined just below
4013 (defvar org-emphasis-alist) ; defined just below
4014 (defun org-set-emph-re (var val)
4015 "Set variable and compute the emphasis regular expression."
4016 (set var val)
4017 (when (and (boundp 'org-emphasis-alist)
4018 (boundp 'org-emphasis-regexp-components)
4019 org-emphasis-alist org-emphasis-regexp-components)
4020 (let* ((e org-emphasis-regexp-components)
4021 (pre (car e))
4022 (post (nth 1 e))
4023 (border (nth 2 e))
4024 (body (nth 3 e))
4025 (nl (nth 4 e))
4026 (body1 (concat body "*?"))
4027 (markers (mapconcat 'car org-emphasis-alist ""))
4028 (vmarkers (mapconcat
4029 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4030 org-emphasis-alist "")))
4031 ;; make sure special characters appear at the right position in the class
4032 (if (string-match "\\^" markers)
4033 (setq markers (concat (replace-match "" t t markers) "^")))
4034 (if (string-match "-" markers)
4035 (setq markers (concat (replace-match "" t t markers) "-")))
4036 (if (string-match "\\^" vmarkers)
4037 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4038 (if (string-match "-" vmarkers)
4039 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4040 (if (> nl 0)
4041 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4042 (int-to-string nl) "\\}")))
4043 ;; Make the regexp
4044 (setq org-emph-re
4045 (concat "\\([" pre "]\\|^\\)"
4046 "\\("
4047 "\\([" markers "]\\)"
4048 "\\("
4049 "[^" border "]\\|"
4050 "[^" border "]"
4051 body1
4052 "[^" border "]"
4053 "\\)"
4054 "\\3\\)"
4055 "\\([" post "]\\|$\\)"))
4056 (setq org-verbatim-re
4057 (concat "\\([" pre "]\\|^\\)"
4058 "\\("
4059 "\\([" vmarkers "]\\)"
4060 "\\("
4061 "[^" border "]\\|"
4062 "[^" border "]"
4063 body1
4064 "[^" border "]"
4065 "\\)"
4066 "\\3\\)"
4067 "\\([" post "]\\|$\\)")))))
4069 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4070 ;; set this option proved cumbersome. See this message/thread:
4071 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4072 (defvar org-emphasis-regexp-components
4073 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4074 "Components used to build the regular expression for emphasis.
4075 This is a list with five entries. Terminology: In an emphasis string
4076 like \" *strong word* \", we call the initial space PREMATCH, the final
4077 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4078 and \"trong wor\" is the body. The different components in this variable
4079 specify what is allowed/forbidden in each part:
4081 pre Chars allowed as prematch. Beginning of line will be allowed too.
4082 post Chars allowed as postmatch. End of line will be allowed too.
4083 border The chars *forbidden* as border characters.
4084 body-regexp A regexp like \".\" to match a body character. Don't use
4085 non-shy groups here, and don't allow newline here.
4086 newline The maximum number of newlines allowed in an emphasis exp.
4088 You need to reload Org or to restart Emacs after customizing this.")
4090 (defcustom org-emphasis-alist
4091 `(("*" bold)
4092 ("/" italic)
4093 ("_" underline)
4094 ("=" org-code verbatim)
4095 ("~" org-verbatim verbatim)
4096 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4097 "Alist of characters and faces to emphasize text.
4098 Text starting and ending with a special character will be emphasized,
4099 for example *bold*, _underlined_ and /italic/. This variable sets the
4100 marker characters and the face to be used by font-lock for highlighting
4101 in Org-mode Emacs buffers.
4103 You need to reload Org or to restart Emacs after customizing this."
4104 :group 'org-appearance
4105 :set 'org-set-emph-re
4106 :version "24.4"
4107 :package-version '(Org . "8.0")
4108 :type '(repeat
4109 (list
4110 (string :tag "Marker character")
4111 (choice
4112 (face :tag "Font-lock-face")
4113 (plist :tag "Face property list"))
4114 (option (const verbatim)))))
4116 (defvar org-protecting-blocks
4117 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4118 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4119 This is needed for font-lock setup.")
4121 ;;; Miscellaneous options
4123 (defgroup org-completion nil
4124 "Completion in Org-mode."
4125 :tag "Org Completion"
4126 :group 'org)
4128 (defcustom org-completion-use-ido nil
4129 "Non-nil means use ido completion wherever possible.
4130 Note that `ido-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 See also `org-completion-use-iswitchb'."
4134 :group 'org-completion
4135 :type 'boolean)
4137 (defcustom org-completion-use-iswitchb nil
4138 "Non-nil means use iswitchb completion wherever possible.
4139 Note that `iswitchb-mode' must be active for this variable to be relevant.
4140 If you decide to turn this variable on, you might well want to turn off
4141 `org-outline-path-complete-in-steps'.
4142 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4143 :group 'org-completion
4144 :type 'boolean)
4146 (defcustom org-completion-fallback-command 'hippie-expand
4147 "The expansion command called by \\[pcomplete] in normal context.
4148 Normal means, no org-mode-specific context."
4149 :group 'org-completion
4150 :type 'function)
4152 ;;; Functions and variables from their packages
4153 ;; Declared here to avoid compiler warnings
4155 ;; XEmacs only
4156 (defvar outline-mode-menu-heading)
4157 (defvar outline-mode-menu-show)
4158 (defvar outline-mode-menu-hide)
4159 (defvar zmacs-regions) ; XEmacs regions
4161 ;; Emacs only
4162 (defvar mark-active)
4164 ;; Various packages
4165 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4166 (declare-function calendar-forward-day "cal-move" (arg))
4167 (declare-function calendar-goto-date "cal-move" (date))
4168 (declare-function calendar-goto-today "cal-move" ())
4169 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4170 (defvar calc-embedded-close-formula)
4171 (defvar calc-embedded-open-formula)
4172 (declare-function cdlatex-tab "ext:cdlatex" ())
4173 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4174 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4175 (defvar font-lock-unfontify-region-function)
4176 (declare-function iswitchb-read-buffer "iswitchb"
4177 (prompt &optional default require-match start matches-set))
4178 (defvar iswitchb-temp-buflist)
4179 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4180 (defvar org-agenda-tags-todo-honor-ignore-options)
4181 (declare-function org-agenda-skip "org-agenda" ())
4182 (declare-function
4183 org-agenda-format-item "org-agenda"
4184 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4185 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4186 (declare-function org-agenda-change-all-lines "org-agenda"
4187 (newhead hdmarker &optional fixface just-this))
4188 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4189 (declare-function org-agenda-maybe-redo "org-agenda" ())
4190 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4191 (beg end))
4192 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4193 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4194 "org-agenda" (&optional end))
4195 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4196 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4197 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4198 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4199 (declare-function org-indent-mode "org-indent" (&optional arg))
4200 (declare-function parse-time-string "parse-time" (string))
4201 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4202 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4203 (defvar remember-data-file)
4204 (defvar texmathp-why)
4205 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4206 (declare-function table--at-cell-p "table" (position &optional object at-column))
4208 (defvar org-latex-regexps)
4210 ;;; Autoload and prepare some org modules
4212 ;; Some table stuff that needs to be defined here, because it is used
4213 ;; by the functions setting up org-mode or checking for table context.
4215 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4216 "Detect an org-type or table-type table.")
4217 (defconst org-table-line-regexp "^[ \t]*|"
4218 "Detect an org-type table line.")
4219 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4220 "Detect an org-type table line.")
4221 (defconst org-table-hline-regexp "^[ \t]*|-"
4222 "Detect an org-type table hline.")
4223 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4224 "Detect a table-type table hline.")
4225 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4226 "Detect the first line outside a table when searching from within it.
4227 This works for both table types.")
4229 ;; Autoload the functions in org-table.el that are needed by functions here.
4231 (eval-and-compile
4232 (org-autoload "org-table"
4233 '(org-table-begin org-table-blank-field org-table-end)))
4235 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
4236 "Detect a #+TBLFM line.")
4238 ;;;###autoload
4239 (defun turn-on-orgtbl ()
4240 "Unconditionally turn on `orgtbl-mode'."
4241 (require 'org-table)
4242 (orgtbl-mode 1))
4244 (defun org-at-table-p (&optional table-type)
4245 "Return t if the cursor is inside an org-type table.
4246 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4247 (if org-enable-table-editor
4248 (save-excursion
4249 (beginning-of-line 1)
4250 (looking-at (if table-type org-table-any-line-regexp
4251 org-table-line-regexp)))
4252 nil))
4253 (defsubst org-table-p () (org-at-table-p))
4255 (defun org-at-table.el-p ()
4256 "Return t if and only if we are at a table.el table."
4257 (and (org-at-table-p 'any)
4258 (save-excursion
4259 (goto-char (org-table-begin 'any))
4260 (looking-at org-table1-hline-regexp))))
4262 (defun org-table-recognize-table.el ()
4263 "If there is a table.el table nearby, recognize it and move into it."
4264 (if org-table-tab-recognizes-table.el
4265 (if (org-at-table.el-p)
4266 (progn
4267 (beginning-of-line 1)
4268 (if (looking-at org-table-dataline-regexp)
4270 (if (looking-at org-table1-hline-regexp)
4271 (progn
4272 (beginning-of-line 2)
4273 (if (looking-at org-table-any-border-regexp)
4274 (beginning-of-line -1)))))
4275 (if (re-search-forward "|" (org-table-end t) t)
4276 (progn
4277 (require 'table)
4278 (if (table--at-cell-p (point))
4280 (message "recognizing table.el table...")
4281 (table-recognize-table)
4282 (message "recognizing table.el table...done")))
4283 (error "This should not happen"))
4285 nil)
4286 nil))
4288 (defun org-at-table-hline-p ()
4289 "Return t if the cursor is inside a hline in a table."
4290 (if org-enable-table-editor
4291 (save-excursion
4292 (beginning-of-line 1)
4293 (looking-at org-table-hline-regexp))
4294 nil))
4296 (defun org-table-map-tables (function &optional quietly)
4297 "Apply FUNCTION to the start of all tables in the buffer."
4298 (save-excursion
4299 (save-restriction
4300 (widen)
4301 (goto-char (point-min))
4302 (while (re-search-forward org-table-any-line-regexp nil t)
4303 (unless quietly
4304 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4305 (beginning-of-line 1)
4306 (when (and (looking-at org-table-line-regexp)
4307 ;; Exclude tables in src/example/verbatim/clocktable blocks
4308 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4309 (save-excursion (funcall function))
4310 (or (looking-at org-table-line-regexp)
4311 (forward-char 1)))
4312 (re-search-forward org-table-any-border-regexp nil 1))))
4313 (unless quietly (message "Mapping tables: done")))
4315 ;; Declare and autoload functions from org-agenda.el
4317 (eval-and-compile
4318 (org-autoload "org-agenda"
4319 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4321 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4322 (declare-function org-clock-update-mode-line "org-clock" ())
4323 (declare-function org-resolve-clocks "org-clock"
4324 (&optional also-non-dangling-p prompt last-valid))
4326 (defun org-at-TBLFM-p (&optional pos)
4327 "Return t when point (or POS) is in #+TBLFM line."
4328 (save-excursion
4329 (let ((pos pos)))
4330 (goto-char (or pos (point)))
4331 (beginning-of-line 1)
4332 (looking-at org-TBLFM-regexp)))
4334 (defvar org-clock-start-time)
4335 (defvar org-clock-marker (make-marker)
4336 "Marker recording the last clock-in.")
4337 (defvar org-clock-hd-marker (make-marker)
4338 "Marker recording the last clock-in, but the headline position.")
4339 (defvar org-clock-heading ""
4340 "The heading of the current clock entry.")
4341 (defun org-clock-is-active ()
4342 "Return the buffer where the clock is currently running.
4343 Return nil if no clock is running."
4344 (marker-buffer org-clock-marker))
4346 (eval-and-compile
4347 (org-autoload "org-clock" '(org-clock-remove-overlays
4348 org-clock-update-time-maybe
4349 org-clocktable-shift)))
4351 (defun org-check-running-clock ()
4352 "Check if the current buffer contains the running clock.
4353 If yes, offer to stop it and to save the buffer with the changes."
4354 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4355 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4356 (buffer-name))))
4357 (org-clock-out)
4358 (when (y-or-n-p "Save changed buffer?")
4359 (save-buffer))))
4361 (defun org-clocktable-try-shift (dir n)
4362 "Check if this line starts a clock table, if yes, shift the time block."
4363 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4364 (org-clocktable-shift dir n)))
4366 ;;;###autoload
4367 (defun org-clock-persistence-insinuate ()
4368 "Set up hooks for clock persistence."
4369 (require 'org-clock)
4370 (add-hook 'org-mode-hook 'org-clock-load)
4371 (add-hook 'kill-emacs-hook 'org-clock-save))
4373 ;; Define the variable already here, to make sure we have it.
4374 (defvar org-indent-mode nil
4375 "Non-nil if Org-Indent mode is enabled.
4376 Use the command `org-indent-mode' to change this variable.")
4378 ;; Autoload archiving code
4379 ;; The stuff that is needed for cycling and tags has to be defined here.
4381 (defgroup org-archive nil
4382 "Options concerning archiving in Org-mode."
4383 :tag "Org Archive"
4384 :group 'org-structure)
4386 (defcustom org-archive-location "%s_archive::"
4387 "The location where subtrees should be archived.
4389 The value of this variable is a string, consisting of two parts,
4390 separated by a double-colon. The first part is a filename and
4391 the second part is a headline.
4393 When the filename is omitted, archiving happens in the same file.
4394 %s in the filename will be replaced by the current file
4395 name (without the directory part). Archiving to a different file
4396 is useful to keep archived entries from contributing to the
4397 Org-mode Agenda.
4399 The archived entries will be filed as subtrees of the specified
4400 headline. When the headline is omitted, the subtrees are simply
4401 filed away at the end of the file, as top-level entries. Also in
4402 the heading you can use %s to represent the file name, this can be
4403 useful when using the same archive for a number of different files.
4405 Here are a few examples:
4406 \"%s_archive::\"
4407 If the current file is Projects.org, archive in file
4408 Projects.org_archive, as top-level trees. This is the default.
4410 \"::* Archived Tasks\"
4411 Archive in the current file, under the top-level headline
4412 \"* Archived Tasks\".
4414 \"~/org/archive.org::\"
4415 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4417 \"~/org/archive.org::* From %s\"
4418 Archive in file ~/org/archive.org (absolute path), under headlines
4419 \"From FILENAME\" where file name is the current file name.
4421 \"~/org/datetree.org::datetree/* Finished Tasks\"
4422 The \"datetree/\" string is special, signifying to archive
4423 items to the datetree. Items are placed in either the CLOSED
4424 date of the item, or the current date if there is no CLOSED date.
4425 The heading will be a subentry to the current date. There doesn't
4426 need to be a heading, but there always needs to be a slash after
4427 datetree. For example, to store archived items directly in the
4428 datetree, use \"~/org/datetree.org::datetree/\".
4430 \"basement::** Finished Tasks\"
4431 Archive in file ./basement (relative path), as level 3 trees
4432 below the level 2 heading \"** Finished Tasks\".
4434 You may set this option on a per-file basis by adding to the buffer a
4435 line like
4437 #+ARCHIVE: basement::** Finished Tasks
4439 You may also define it locally for a subtree by setting an ARCHIVE property
4440 in the entry. If such a property is found in an entry, or anywhere up
4441 the hierarchy, it will be used."
4442 :group 'org-archive
4443 :type 'string)
4445 (defcustom org-archive-tag "ARCHIVE"
4446 "The tag that marks a subtree as archived.
4447 An archived subtree does not open during visibility cycling, and does
4448 not contribute to the agenda listings.
4449 After changing this, font-lock must be restarted in the relevant buffers to
4450 get the proper fontification."
4451 :group 'org-archive
4452 :group 'org-keywords
4453 :type 'string)
4455 (defcustom org-agenda-skip-archived-trees t
4456 "Non-nil means the agenda will skip any items located in archived trees.
4457 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4458 variable is no longer recommended, you should leave it at the value t.
4459 Instead, use the key `v' to cycle the archives-mode in the agenda."
4460 :group 'org-archive
4461 :group 'org-agenda-skip
4462 :type 'boolean)
4464 (defcustom org-columns-skip-archived-trees t
4465 "Non-nil means ignore archived trees when creating column view."
4466 :group 'org-archive
4467 :group 'org-properties
4468 :type 'boolean)
4470 (defcustom org-cycle-open-archived-trees nil
4471 "Non-nil means `org-cycle' will open archived trees.
4472 An archived tree is a tree marked with the tag ARCHIVE.
4473 When nil, archived trees will stay folded. You can still open them with
4474 normal outline commands like `show-all', but not with the cycling commands."
4475 :group 'org-archive
4476 :group 'org-cycle
4477 :type 'boolean)
4479 (defcustom org-sparse-tree-open-archived-trees nil
4480 "Non-nil means sparse tree construction shows matches in archived trees.
4481 When nil, matches in these trees are highlighted, but the trees are kept in
4482 collapsed state."
4483 :group 'org-archive
4484 :group 'org-sparse-trees
4485 :type 'boolean)
4487 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4488 "The default date type when building a sparse tree.
4489 When this is nil, a date is a scheduled or a deadline timestamp.
4490 Otherwise, these types are allowed:
4492 all: all timestamps
4493 active: only active timestamps (<...>)
4494 inactive: only inactive timestamps (<...)
4495 scheduled: only scheduled timestamps
4496 deadline: only deadline timestamps"
4497 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4498 (const :tag "All timestamps" all)
4499 (const :tag "Only active timestamps" active)
4500 (const :tag "Only inactive timestamps" inactive)
4501 (const :tag "Only scheduled timestamps" scheduled)
4502 (const :tag "Only deadline timestamps" deadline)
4503 (const :tag "Only closed timestamps" closed))
4504 :version "24.3"
4505 :group 'org-sparse-trees)
4507 (defun org-cycle-hide-archived-subtrees (state)
4508 "Re-hide all archived subtrees after a visibility state change."
4509 (when (and (not org-cycle-open-archived-trees)
4510 (not (memq state '(overview folded))))
4511 (save-excursion
4512 (let* ((globalp (memq state '(contents all)))
4513 (beg (if globalp (point-min) (point)))
4514 (end (if globalp (point-max) (org-end-of-subtree t))))
4515 (org-hide-archived-subtrees beg end)
4516 (goto-char beg)
4517 (if (looking-at (concat ".*:" org-archive-tag ":"))
4518 (message "%s" (substitute-command-keys
4519 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4521 (defun org-force-cycle-archived ()
4522 "Cycle subtree even if it is archived."
4523 (interactive)
4524 (setq this-command 'org-cycle)
4525 (let ((org-cycle-open-archived-trees t))
4526 (call-interactively 'org-cycle)))
4528 (defun org-hide-archived-subtrees (beg end)
4529 "Re-hide all archived subtrees after a visibility state change."
4530 (save-excursion
4531 (let* ((re (concat ":" org-archive-tag ":")))
4532 (goto-char beg)
4533 (while (re-search-forward re end t)
4534 (when (org-at-heading-p)
4535 (org-flag-subtree t)
4536 (org-end-of-subtree t))))))
4538 (declare-function outline-end-of-heading "outline" ())
4539 (declare-function outline-flag-region "outline" (from to flag))
4540 (defun org-flag-subtree (flag)
4541 (save-excursion
4542 (org-back-to-heading t)
4543 (outline-end-of-heading)
4544 (outline-flag-region (point)
4545 (progn (org-end-of-subtree t) (point))
4546 flag)))
4548 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4550 (eval-and-compile
4551 (org-autoload "org-archive"
4552 '(org-add-archive-files)))
4554 ;; Autoload Column View Code
4556 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4557 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4558 (declare-function org-columns-compute "org-colview" (property))
4560 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4561 '(org-columns-number-to-string
4562 org-columns-get-format-and-top-level
4563 org-columns-compute
4564 org-columns-remove-overlays))
4566 ;; Autoload ID code
4568 (declare-function org-id-store-link "org-id")
4569 (declare-function org-id-locations-load "org-id")
4570 (declare-function org-id-locations-save "org-id")
4571 (defvar org-id-track-globally)
4572 (org-autoload "org-id"
4573 '(org-id-new
4574 org-id-copy
4575 org-id-get-with-outline-path-completion
4576 org-id-get-with-outline-drilling))
4578 ;;; Variables for pre-computed regular expressions, all buffer local
4580 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4581 "Matches first line of a hidden block.")
4582 (make-variable-buffer-local 'org-drawer-regexp)
4583 (defvar org-todo-regexp nil
4584 "Matches any of the TODO state keywords.")
4585 (make-variable-buffer-local 'org-todo-regexp)
4586 (defvar org-not-done-regexp nil
4587 "Matches any of the TODO state keywords except the last one.")
4588 (make-variable-buffer-local 'org-not-done-regexp)
4589 (defvar org-not-done-heading-regexp nil
4590 "Matches a TODO headline that is not done.")
4591 (make-variable-buffer-local 'org-not-done-regexp)
4592 (defvar org-todo-line-regexp nil
4593 "Matches a headline and puts TODO state into group 2 if present.")
4594 (make-variable-buffer-local 'org-todo-line-regexp)
4595 (defvar org-complex-heading-regexp nil
4596 "Matches a headline and puts everything into groups:
4597 group 1: the stars
4598 group 2: The todo keyword, maybe
4599 group 3: Priority cookie
4600 group 4: True headline
4601 group 5: Tags")
4602 (make-variable-buffer-local 'org-complex-heading-regexp)
4603 (defvar org-complex-heading-regexp-format nil
4604 "Printf format to make regexp to match an exact headline.
4605 This regexp will match the headline of any node which has the
4606 exact headline text that is put into the format, but may have any
4607 TODO state, priority and tags.")
4608 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4609 (defvar org-todo-line-tags-regexp nil
4610 "Matches a headline and puts TODO state into group 2 if present.
4611 Also put tags into group 4 if tags are present.")
4612 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4613 (defvar org-ds-keyword-length 12
4614 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4615 (make-variable-buffer-local 'org-ds-keyword-length)
4616 (defvar org-deadline-regexp nil
4617 "Matches the DEADLINE keyword.")
4618 (make-variable-buffer-local 'org-deadline-regexp)
4619 (defvar org-deadline-time-regexp nil
4620 "Matches the DEADLINE keyword together with a time stamp.")
4621 (make-variable-buffer-local 'org-deadline-time-regexp)
4622 (defvar org-deadline-time-hour-regexp nil
4623 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4624 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4625 (defvar org-deadline-line-regexp nil
4626 "Matches the DEADLINE keyword and the rest of the line.")
4627 (make-variable-buffer-local 'org-deadline-line-regexp)
4628 (defvar org-scheduled-regexp nil
4629 "Matches the SCHEDULED keyword.")
4630 (make-variable-buffer-local 'org-scheduled-regexp)
4631 (defvar org-scheduled-time-regexp nil
4632 "Matches the SCHEDULED keyword together with a time stamp.")
4633 (make-variable-buffer-local 'org-scheduled-time-regexp)
4634 (defvar org-scheduled-time-hour-regexp nil
4635 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4636 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4637 (defvar org-closed-time-regexp nil
4638 "Matches the CLOSED keyword together with a time stamp.")
4639 (make-variable-buffer-local 'org-closed-time-regexp)
4641 (defvar org-keyword-time-regexp nil
4642 "Matches any of the 4 keywords, together with the time stamp.")
4643 (make-variable-buffer-local 'org-keyword-time-regexp)
4644 (defvar org-keyword-time-not-clock-regexp nil
4645 "Matches any of the 3 keywords, together with the time stamp.")
4646 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4647 (defvar org-maybe-keyword-time-regexp nil
4648 "Matches a timestamp, possibly preceded by a keyword.")
4649 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4650 (defvar org-all-time-keywords nil
4651 "List of time keywords.")
4652 (make-variable-buffer-local 'org-all-time-keywords)
4654 (defconst org-plain-time-of-day-regexp
4655 (concat
4656 "\\(\\<[012]?[0-9]"
4657 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4658 "\\(--?"
4659 "\\(\\<[012]?[0-9]"
4660 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4661 "\\)?")
4662 "Regular expression to match a plain time or time range.
4663 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4664 groups carry important information:
4665 0 the full match
4666 1 the first time, range or not
4667 8 the second time, if it is a range.")
4669 (defconst org-plain-time-extension-regexp
4670 (concat
4671 "\\(\\<[012]?[0-9]"
4672 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4673 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4674 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4675 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4676 groups carry important information:
4677 0 the full match
4678 7 hours of duration
4679 9 minutes of duration")
4681 (defconst org-stamp-time-of-day-regexp
4682 (concat
4683 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4684 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4685 "\\(--?"
4686 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4687 "Regular expression to match a timestamp time or time range.
4688 After a match, the following groups carry important information:
4689 0 the full match
4690 1 date plus weekday, for back referencing to make sure both times are on the same day
4691 2 the first time, range or not
4692 4 the second time, if it is a range.")
4694 (defconst org-startup-options
4695 '(("fold" org-startup-folded t)
4696 ("overview" org-startup-folded t)
4697 ("nofold" org-startup-folded nil)
4698 ("showall" org-startup-folded nil)
4699 ("showeverything" org-startup-folded showeverything)
4700 ("content" org-startup-folded content)
4701 ("indent" org-startup-indented t)
4702 ("noindent" org-startup-indented nil)
4703 ("hidestars" org-hide-leading-stars t)
4704 ("showstars" org-hide-leading-stars nil)
4705 ("odd" org-odd-levels-only t)
4706 ("oddeven" org-odd-levels-only nil)
4707 ("align" org-startup-align-all-tables t)
4708 ("noalign" org-startup-align-all-tables nil)
4709 ("inlineimages" org-startup-with-inline-images t)
4710 ("noinlineimages" org-startup-with-inline-images nil)
4711 ("latexpreview" org-startup-with-latex-preview t)
4712 ("nolatexpreview" org-startup-with-latex-preview nil)
4713 ("customtime" org-display-custom-times t)
4714 ("logdone" org-log-done time)
4715 ("lognotedone" org-log-done note)
4716 ("nologdone" org-log-done nil)
4717 ("lognoteclock-out" org-log-note-clock-out t)
4718 ("nolognoteclock-out" org-log-note-clock-out nil)
4719 ("logrepeat" org-log-repeat state)
4720 ("lognoterepeat" org-log-repeat note)
4721 ("logdrawer" org-log-into-drawer t)
4722 ("nologdrawer" org-log-into-drawer nil)
4723 ("logstatesreversed" org-log-states-order-reversed t)
4724 ("nologstatesreversed" org-log-states-order-reversed nil)
4725 ("nologrepeat" org-log-repeat nil)
4726 ("logreschedule" org-log-reschedule time)
4727 ("lognotereschedule" org-log-reschedule note)
4728 ("nologreschedule" org-log-reschedule nil)
4729 ("logredeadline" org-log-redeadline time)
4730 ("lognoteredeadline" org-log-redeadline note)
4731 ("nologredeadline" org-log-redeadline nil)
4732 ("logrefile" org-log-refile time)
4733 ("lognoterefile" org-log-refile note)
4734 ("nologrefile" org-log-refile nil)
4735 ("fninline" org-footnote-define-inline t)
4736 ("nofninline" org-footnote-define-inline nil)
4737 ("fnlocal" org-footnote-section nil)
4738 ("fnauto" org-footnote-auto-label t)
4739 ("fnprompt" org-footnote-auto-label nil)
4740 ("fnconfirm" org-footnote-auto-label confirm)
4741 ("fnplain" org-footnote-auto-label plain)
4742 ("fnadjust" org-footnote-auto-adjust t)
4743 ("nofnadjust" org-footnote-auto-adjust nil)
4744 ("constcgs" constants-unit-system cgs)
4745 ("constSI" constants-unit-system SI)
4746 ("noptag" org-tag-persistent-alist nil)
4747 ("hideblocks" org-hide-block-startup t)
4748 ("nohideblocks" org-hide-block-startup nil)
4749 ("beamer" org-startup-with-beamer-mode t)
4750 ("entitiespretty" org-pretty-entities t)
4751 ("entitiesplain" org-pretty-entities nil))
4752 "Variable associated with STARTUP options for org-mode.
4753 Each element is a list of three items: the startup options (as written
4754 in the #+STARTUP line), the corresponding variable, and the value to set
4755 this variable to if the option is found. An optional forth element PUSH
4756 means to push this value onto the list in the variable.")
4758 (defun org-update-property-plist (key val props)
4759 "Update PROPS with KEY and VAL."
4760 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4761 (key (if appending (substring key 0 (- (length key) 1)) key))
4762 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4763 (previous (cdr (assoc key props))))
4764 (if appending
4765 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4766 (cons (cons key val) remainder))))
4768 (defconst org-block-regexp
4769 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4770 "Regular expression for hiding blocks.")
4771 (defconst org-heading-keyword-regexp-format
4772 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4773 "Printf format for a regexp matching a headline with some keyword.
4774 This regexp will match the headline of any node which has the
4775 exact keyword that is put into the format. The keyword isn't in
4776 any group by default, but the stars and the body are.")
4777 (defconst org-heading-keyword-maybe-regexp-format
4778 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4779 "Printf format for a regexp matching a headline, possibly with some keyword.
4780 This regexp can match any headline with the specified keyword, or
4781 without a keyword. The keyword isn't in any group by default,
4782 but the stars and the body are.")
4784 (defcustom org-group-tags t
4785 "When non-nil (the default), use group tags.
4786 This can be turned on/off through `org-toggle-tags-groups'."
4787 :group 'org-tags
4788 :group 'org-startup
4789 :type 'boolean)
4791 (defun org-toggle-tags-groups ()
4792 "Toggle support for group tags.
4793 Support for group tags is controlled by the option
4794 `org-group-tags', which is non-nil by default."
4795 (interactive)
4796 (setq org-group-tags (not org-group-tags))
4797 (cond ((and (derived-mode-p 'org-agenda-mode)
4798 org-group-tags)
4799 (org-agenda-redo))
4800 ((derived-mode-p 'org-mode)
4801 (let ((org-inhibit-startup t)) (org-mode))))
4802 (message "Groups tags support has been turned %s"
4803 (if org-group-tags "on" "off")))
4805 (defun org-set-regexps-and-options-for-tags ()
4806 "Precompute variables used for tags."
4807 (when (derived-mode-p 'org-mode)
4808 (org-set-local 'org-file-tags nil)
4809 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4810 (splitre "[ \t]+")
4811 (start 0)
4812 tags ftags key value)
4813 (save-excursion
4814 (save-restriction
4815 (widen)
4816 (goto-char (point-min))
4817 (while (re-search-forward re nil t)
4818 (setq key (upcase (org-match-string-no-properties 1))
4819 value (org-match-string-no-properties 2))
4820 (if (stringp value) (setq value (org-trim value)))
4821 (cond
4822 ((equal key "TAGS")
4823 (setq tags (append tags (if tags '("\\n") nil)
4824 (org-split-string value splitre))))
4825 ((equal key "FILETAGS")
4826 (when (string-match "\\S-" value)
4827 (setq ftags
4828 (append
4829 ftags
4830 (apply 'append
4831 (mapcar (lambda (x) (org-split-string x ":"))
4832 (org-split-string value)))))))))))
4833 ;; Process the file tags.
4834 (and ftags (org-set-local 'org-file-tags
4835 (mapcar 'org-add-prop-inherited ftags)))
4836 (org-set-local 'org-tag-groups-alist nil)
4837 ;; Process the tags.
4838 ;; FIXME
4839 (when tags
4840 (let (e tgs g)
4841 (while (setq e (pop tags))
4842 (cond
4843 ((equal e "{")
4844 (progn (push '(:startgroup) tgs)
4845 (when (equal (nth 1 tags) ":")
4846 (push (list (replace-regexp-in-string
4847 "(.+)$" "" (nth 0 tags)))
4848 org-tag-groups-alist)
4849 (setq g 0))))
4850 ((equal e ":") (push '(:grouptags) tgs))
4851 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4852 ((equal e "\\n") (push '(:newline) tgs))
4853 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4854 (push (cons (match-string 1 e)
4855 (string-to-char (match-string 2 e))) tgs)
4856 (if (and g (> g 0))
4857 (setcar org-tag-groups-alist
4858 (append (car org-tag-groups-alist)
4859 (list (match-string 1 e)))))
4860 (if g (setq g (1+ g))))
4861 (t (push (list e) tgs)
4862 (if (and g (> g 0))
4863 (setcar org-tag-groups-alist
4864 (append (car org-tag-groups-alist) (list e))))
4865 (if g (setq g (1+ g))))))
4866 (org-set-local 'org-tag-alist nil)
4867 (while (setq e (pop tgs))
4868 (or (and (stringp (car e))
4869 (assoc (car e) org-tag-alist))
4870 (push e org-tag-alist)))
4871 ;; Return a list with tag variables
4872 (list org-file-tags org-tag-alist org-tag-groups-alist))))))
4874 (defvar org-ota nil)
4875 (defun org-set-regexps-and-options ()
4876 "Precompute regular expressions used in the current buffer."
4877 (when (derived-mode-p 'org-mode)
4878 (org-set-local 'org-todo-kwd-alist nil)
4879 (org-set-local 'org-todo-key-alist nil)
4880 (org-set-local 'org-todo-key-trigger nil)
4881 (org-set-local 'org-todo-keywords-1 nil)
4882 (org-set-local 'org-done-keywords nil)
4883 (org-set-local 'org-todo-heads nil)
4884 (org-set-local 'org-todo-sets nil)
4885 (org-set-local 'org-todo-log-states nil)
4886 (org-set-local 'org-file-properties nil)
4887 (let ((re (org-make-options-regexp
4888 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4889 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4890 "SETUPFILE" "OPTIONS")
4891 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4892 (splitre "[ \t]+")
4893 (scripts org-use-sub-superscripts)
4894 kwds kws0 kwsa key log value cat arch const links hw dws
4895 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4896 (start 0))
4897 (save-excursion
4898 (save-restriction
4899 (widen)
4900 (goto-char (point-min))
4901 (while
4902 (or (and
4903 ext-setup-or-nil
4904 (not org-ota)
4905 (let (ret)
4906 (with-temp-buffer
4907 (insert ext-setup-or-nil)
4908 (let ((major-mode 'org-mode) org-ota)
4909 (setq ret (save-match-data
4910 (org-set-regexps-and-options-for-tags)))))
4911 ;; Append setupfile tags to existing tags
4912 (setq org-file-tags
4913 (delq nil (append org-file-tags (nth 0 ret)))
4914 org-tag-alist
4915 (delq nil (append org-tag-alist (nth 1 ret)))
4916 org-tag-groups-alist
4917 (delq nil (append org-tag-groups-alist (nth 2 ret)))
4918 org-ota t)))
4919 (and ext-setup-or-nil
4920 (string-match re ext-setup-or-nil start)
4921 (setq start (match-end 0)))
4922 (and (setq ext-setup-or-nil nil start 0)
4923 (re-search-forward re nil t)))
4924 (setq key (upcase (match-string 1 ext-setup-or-nil))
4925 value (org-match-string-no-properties 2 ext-setup-or-nil))
4926 (if (stringp value) (setq value (org-trim value)))
4927 (cond
4928 ((equal key "CATEGORY")
4929 (setq cat value))
4930 ((member key '("SEQ_TODO" "TODO"))
4931 (push (cons 'sequence (org-split-string value splitre)) kwds))
4932 ((equal key "TYP_TODO")
4933 (push (cons 'type (org-split-string value splitre)) kwds))
4934 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4935 ;; general TODO-like setup
4936 (push (cons (intern (downcase (match-string 1 key)))
4937 (org-split-string value splitre)) kwds))
4938 ((equal key "COLUMNS")
4939 (org-set-local 'org-columns-default-format value))
4940 ((equal key "LINK")
4941 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4942 (push (cons (match-string 1 value)
4943 (org-trim (match-string 2 value)))
4944 links)))
4945 ((equal key "PRIORITIES")
4946 (setq prio (org-split-string value " +")))
4947 ((equal key "PROPERTY")
4948 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4949 (setq props (org-update-property-plist (match-string 1 value)
4950 (match-string 2 value)
4951 props))))
4952 ((equal key "DRAWERS")
4953 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4954 ((equal key "CONSTANTS")
4955 (org-table-set-constants))
4956 ((equal key "STARTUP")
4957 (let ((opts (org-split-string value splitre))
4958 l var val)
4959 (while (setq l (pop opts))
4960 (when (setq l (assoc l org-startup-options))
4961 (setq var (nth 1 l) val (nth 2 l))
4962 (if (not (nth 3 l))
4963 (set (make-local-variable var) val)
4964 (if (not (listp (symbol-value var)))
4965 (set (make-local-variable var) nil))
4966 (set (make-local-variable var) (symbol-value var))
4967 (add-to-list var val))))))
4968 ((equal key "ARCHIVE")
4969 (setq arch value)
4970 (remove-text-properties 0 (length arch)
4971 '(face t fontified t) arch))
4972 ((equal key "OPTIONS")
4973 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4974 (setq scripts (read (match-string 2 value)))))
4975 ((and (equal key "SETUPFILE")
4976 ;; Prevent checking in Gnus messages
4977 (not buffer-read-only))
4978 (setq setup-contents (org-file-contents
4979 (expand-file-name
4980 (org-remove-double-quotes value))
4981 'noerror))
4982 (if (not ext-setup-or-nil)
4983 (setq ext-setup-or-nil setup-contents start 0)
4984 (setq ext-setup-or-nil
4985 (concat (substring ext-setup-or-nil 0 start)
4986 "\n" setup-contents "\n"
4987 (substring ext-setup-or-nil start)))))))
4988 ;; search for property blocks
4989 (goto-char (point-min))
4990 (while (re-search-forward org-block-regexp nil t)
4991 (when (equal "PROPERTY" (upcase (match-string 1)))
4992 (setq value (replace-regexp-in-string
4993 "[\n\r]" " " (match-string 4)))
4994 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4995 (setq props (org-update-property-plist (match-string 1 value)
4996 (match-string 2 value)
4997 props)))))))
4998 (org-set-local 'org-use-sub-superscripts scripts)
4999 (when cat
5000 (org-set-local 'org-category (intern cat))
5001 (push (cons "CATEGORY" cat) props))
5002 (when prio
5003 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5004 (setq prio (mapcar 'string-to-char prio))
5005 (org-set-local 'org-highest-priority (nth 0 prio))
5006 (org-set-local 'org-lowest-priority (nth 1 prio))
5007 (org-set-local 'org-default-priority (nth 2 prio)))
5008 (and props (org-set-local 'org-file-properties (nreverse props)))
5009 (and drawers (org-set-local 'org-drawers drawers))
5010 (and arch (org-set-local 'org-archive-location arch))
5011 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5012 ;; Process the TODO keywords
5013 (unless kwds
5014 ;; Use the global values as if they had been given locally.
5015 (setq kwds (default-value 'org-todo-keywords))
5016 (if (stringp (car kwds))
5017 (setq kwds (list (cons org-todo-interpretation
5018 (default-value 'org-todo-keywords)))))
5019 (setq kwds (reverse kwds)))
5020 (setq kwds (nreverse kwds))
5021 (let (inter kws kw)
5022 (while (setq kws (pop kwds))
5023 (let ((kws (or
5024 (run-hook-with-args-until-success
5025 'org-todo-setup-filter-hook kws)
5026 kws)))
5027 (setq inter (pop kws) sep (member "|" kws)
5028 kws0 (delete "|" (copy-sequence kws))
5029 kwsa nil
5030 kws1 (mapcar
5031 (lambda (x)
5032 ;; 1 2
5033 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5034 (progn
5035 (setq kw (match-string 1 x)
5036 key (and (match-end 2) (match-string 2 x))
5037 log (org-extract-log-state-settings x))
5038 (push (cons kw (and key (string-to-char key))) kwsa)
5039 (and log (push log org-todo-log-states))
5041 (error "Invalid TODO keyword %s" x)))
5042 kws0)
5043 kwsa (if kwsa (append '((:startgroup))
5044 (nreverse kwsa)
5045 '((:endgroup))))
5046 hw (car kws1)
5047 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5048 tail (list inter hw (car dws) (org-last dws))))
5049 (add-to-list 'org-todo-heads hw 'append)
5050 (push kws1 org-todo-sets)
5051 (setq org-done-keywords (append org-done-keywords dws nil))
5052 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5053 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5054 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5055 (setq org-todo-sets (nreverse org-todo-sets)
5056 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5057 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5058 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5059 ;; Compute the regular expressions and other local variables.
5060 ;; Using `org-outline-regexp-bol' would complicate them much,
5061 ;; because of the fixed white space at the end of that string.
5062 (if (not org-done-keywords)
5063 (setq org-done-keywords (and org-todo-keywords-1
5064 (list (org-last org-todo-keywords-1)))))
5065 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5066 (length org-scheduled-string)
5067 (length org-clock-string)
5068 (length org-closed-string)))
5069 org-drawer-regexp
5070 (concat "^[ \t]*:\\("
5071 (mapconcat 'regexp-quote org-drawers "\\|")
5072 "\\):[ \t]*$")
5073 org-not-done-keywords
5074 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5075 org-todo-regexp
5076 (concat "\\("
5077 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5078 "\\)")
5079 org-not-done-regexp
5080 (concat "\\("
5081 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5082 "\\)")
5083 org-not-done-heading-regexp
5084 (format org-heading-keyword-regexp-format org-not-done-regexp)
5085 org-todo-line-regexp
5086 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5087 org-complex-heading-regexp
5088 (concat "^\\(\\*+\\)"
5089 "\\(?: +" org-todo-regexp "\\)?"
5090 "\\(?: +\\(\\[#.\\]\\)\\)?"
5091 "\\(?: +\\(.*?\\)\\)??"
5092 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5093 "[ \t]*$")
5094 org-complex-heading-regexp-format
5095 (concat "^\\(\\*+\\)"
5096 "\\(?: +" org-todo-regexp "\\)?"
5097 "\\(?: +\\(\\[#.\\]\\)\\)?"
5098 "\\(?: +"
5099 ;; Stats cookies can be stuck to body.
5100 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5101 "\\(%s\\)"
5102 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5103 "\\)"
5104 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5105 "[ \t]*$")
5106 org-todo-line-tags-regexp
5107 (concat "^\\(\\*+\\)"
5108 "\\(?: +" org-todo-regexp "\\)?"
5109 "\\(?: +\\(.*?\\)\\)??"
5110 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5111 "[ \t]*$")
5112 org-deadline-regexp (concat "\\<" org-deadline-string)
5113 org-deadline-time-regexp
5114 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5115 org-deadline-time-hour-regexp
5116 (concat "\\<" org-deadline-string
5117 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5118 org-deadline-line-regexp
5119 (concat "\\<\\(" org-deadline-string "\\).*")
5120 org-scheduled-regexp
5121 (concat "\\<" org-scheduled-string)
5122 org-scheduled-time-regexp
5123 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5124 org-scheduled-time-hour-regexp
5125 (concat "\\<" org-scheduled-string
5126 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5127 org-closed-time-regexp
5128 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5129 org-keyword-time-regexp
5130 (concat "\\<\\(" org-scheduled-string
5131 "\\|" org-deadline-string
5132 "\\|" org-closed-string
5133 "\\|" org-clock-string "\\)"
5134 " *[[<]\\([^]>]+\\)[]>]")
5135 org-keyword-time-not-clock-regexp
5136 (concat "\\<\\(" org-scheduled-string
5137 "\\|" org-deadline-string
5138 "\\|" org-closed-string
5139 "\\)"
5140 " *[[<]\\([^]>]+\\)[]>]")
5141 org-maybe-keyword-time-regexp
5142 (concat "\\(\\<\\(" org-scheduled-string
5143 "\\|" org-deadline-string
5144 "\\|" org-closed-string
5145 "\\|" org-clock-string "\\)\\)?"
5146 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5147 org-all-time-keywords
5148 (mapcar (lambda (w) (substring w 0 -1))
5149 (list org-scheduled-string org-deadline-string
5150 org-clock-string org-closed-string)))
5151 (setq org-ota nil)
5152 (org-compute-latex-and-related-regexp))))
5154 (defun org-file-contents (file &optional noerror)
5155 "Return the contents of FILE, as a string."
5156 (if (or (not file)
5157 (not (file-readable-p file)))
5158 (if noerror
5159 (message "Cannot read file \"%s\"" file)
5160 (error "Cannot read file \"%s\"" file))
5161 (with-temp-buffer
5162 (insert-file-contents file)
5163 (buffer-string))))
5165 (defun org-extract-log-state-settings (x)
5166 "Extract the log state setting from a TODO keyword string.
5167 This will extract info from a string like \"WAIT(w@/!)\"."
5168 (let (kw key log1 log2)
5169 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5170 (setq kw (match-string 1 x)
5171 key (and (match-end 2) (match-string 2 x))
5172 log1 (and (match-end 3) (match-string 3 x))
5173 log2 (and (match-end 4) (match-string 4 x)))
5174 (and (or log1 log2)
5175 (list kw
5176 (and log1 (if (equal log1 "!") 'time 'note))
5177 (and log2 (if (equal log2 "!") 'time 'note)))))))
5179 (defun org-remove-keyword-keys (list)
5180 "Remove a pair of parenthesis at the end of each string in LIST."
5181 (mapcar (lambda (x)
5182 (if (string-match "(.*)$" x)
5183 (substring x 0 (match-beginning 0))
5185 list))
5187 (defun org-assign-fast-keys (alist)
5188 "Assign fast keys to a keyword-key alist.
5189 Respect keys that are already there."
5190 (let (new e (alt ?0))
5191 (while (setq e (pop alist))
5192 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5193 (cdr e)) ;; Key already assigned.
5194 (push e new)
5195 (let ((clist (string-to-list (downcase (car e))))
5196 (used (append new alist)))
5197 (when (= (car clist) ?@)
5198 (pop clist))
5199 (while (and clist (rassoc (car clist) used))
5200 (pop clist))
5201 (unless clist
5202 (while (rassoc alt used)
5203 (incf alt)))
5204 (push (cons (car e) (or (car clist) alt)) new))))
5205 (nreverse new)))
5207 ;;; Some variables used in various places
5209 (defvar org-window-configuration nil
5210 "Used in various places to store a window configuration.")
5211 (defvar org-selected-window nil
5212 "Used in various places to store a window configuration.")
5213 (defvar org-finish-function nil
5214 "Function to be called when `C-c C-c' is used.
5215 This is for getting out of special buffers like capture.")
5218 ;; FIXME: Occasionally check by commenting these, to make sure
5219 ;; no other functions uses these, forgetting to let-bind them.
5220 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5221 (defvar org-last-state)
5222 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5224 ;; Defined somewhere in this file, but used before definition.
5225 (defvar org-entities) ;; defined in org-entities.el
5226 (defvar org-struct-menu)
5227 (defvar org-org-menu)
5228 (defvar org-tbl-menu)
5230 ;;;; Define the Org-mode
5232 ;; We use a before-change function to check if a table might need
5233 ;; an update.
5234 (defvar org-table-may-need-update t
5235 "Indicates that a table might need an update.
5236 This variable is set by `org-before-change-function'.
5237 `org-table-align' sets it back to nil.")
5238 (defun org-before-change-function (beg end)
5239 "Every change indicates that a table might need an update."
5240 (setq org-table-may-need-update t))
5241 (defvar org-mode-map)
5242 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5243 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5244 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5245 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5246 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5247 (defvar org-table-buffer-is-an nil)
5249 (defvar bidi-paragraph-direction)
5250 (defvar buffer-face-mode-face)
5252 (require 'outline)
5253 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5254 (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"))
5255 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5257 ;; Other stuff we need.
5258 (require 'time-date)
5259 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5260 (require 'easymenu)
5261 (require 'overlay)
5263 ;; (require 'org-macs) moved higher up in the file before it is first used
5264 (require 'org-entities)
5265 ;; (require 'org-compat) moved higher up in the file before it is first used
5266 (require 'org-faces)
5267 (require 'org-list)
5268 (require 'org-pcomplete)
5269 (require 'org-src)
5270 (require 'org-footnote)
5271 (require 'org-macro)
5273 ;; babel
5274 (require 'ob)
5276 ;;;###autoload
5277 (define-derived-mode org-mode outline-mode "Org"
5278 "Outline-based notes management and organizer, alias
5279 \"Carsten's outline-mode for keeping track of everything.\"
5281 Org-mode develops organizational tasks around a NOTES file which
5282 contains information about projects as plain text. Org-mode is
5283 implemented on top of outline-mode, which is ideal to keep the content
5284 of large files well structured. It supports ToDo items, deadlines and
5285 time stamps, which magically appear in the diary listing of the Emacs
5286 calendar. Tables are easily created with a built-in table editor.
5287 Plain text URL-like links connect to websites, emails (VM), Usenet
5288 messages (Gnus), BBDB entries, and any files related to the project.
5289 For printing and sharing of notes, an Org-mode file (or a part of it)
5290 can be exported as a structured ASCII or HTML file.
5292 The following commands are available:
5294 \\{org-mode-map}"
5296 ;; Get rid of Outline menus, they are not needed
5297 ;; Need to do this here because define-derived-mode sets up
5298 ;; the keymap so late. Still, it is a waste to call this each time
5299 ;; we switch another buffer into org-mode.
5300 (if (featurep 'xemacs)
5301 (when (boundp 'outline-mode-menu-heading)
5302 ;; Assume this is Greg's port, it uses easymenu
5303 (easy-menu-remove outline-mode-menu-heading)
5304 (easy-menu-remove outline-mode-menu-show)
5305 (easy-menu-remove outline-mode-menu-hide))
5306 (define-key org-mode-map [menu-bar headings] 'undefined)
5307 (define-key org-mode-map [menu-bar hide] 'undefined)
5308 (define-key org-mode-map [menu-bar show] 'undefined))
5310 (org-load-modules-maybe)
5311 (easy-menu-add org-org-menu)
5312 (easy-menu-add org-tbl-menu)
5313 (org-install-agenda-files-menu)
5314 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5315 (add-to-invisibility-spec '(org-cwidth))
5316 (add-to-invisibility-spec '(org-hide-block . t))
5317 (when (featurep 'xemacs)
5318 (org-set-local 'line-move-ignore-invisible t))
5319 (org-set-local 'outline-regexp org-outline-regexp)
5320 (org-set-local 'outline-level 'org-outline-level)
5321 (setq bidi-paragraph-direction 'left-to-right)
5322 (when (and org-ellipsis
5323 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5324 (fboundp 'make-glyph-code))
5325 (unless org-display-table
5326 (setq org-display-table (make-display-table)))
5327 (set-display-table-slot
5328 org-display-table 4
5329 (vconcat (mapcar
5330 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5331 org-ellipsis)))
5332 (if (stringp org-ellipsis) org-ellipsis "..."))))
5333 (setq buffer-display-table org-display-table))
5334 (org-set-regexps-and-options-for-tags)
5335 (org-set-regexps-and-options)
5336 (org-set-font-lock-defaults)
5337 (when (and org-tag-faces (not org-tags-special-faces-re))
5338 ;; tag faces set outside customize.... force initialization.
5339 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5340 ;; Calc embedded
5341 (org-set-local 'calc-embedded-open-mode "# ")
5342 ;; Modify a few syntax entries
5343 (modify-syntax-entry ?@ "w")
5344 (modify-syntax-entry ?\" "\"")
5345 (if org-startup-truncated (setq truncate-lines t))
5346 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5347 (org-set-local 'font-lock-unfontify-region-function
5348 'org-unfontify-region)
5349 ;; Activate before-change-function
5350 (org-set-local 'org-table-may-need-update t)
5351 (org-add-hook 'before-change-functions 'org-before-change-function nil
5352 'local)
5353 ;; Check for running clock before killing a buffer
5354 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5355 ;; Initialize macros templates.
5356 (org-macro-initialize-templates)
5357 ;; Initialize radio targets.
5358 (org-update-radio-target-regexp)
5359 ;; Indentation.
5360 (org-set-local 'indent-line-function 'org-indent-line)
5361 (org-set-local 'indent-region-function 'org-indent-region)
5362 ;; Filling and auto-filling.
5363 (org-setup-filling)
5364 ;; Comments.
5365 (org-setup-comments-handling)
5366 ;; Beginning/end of defun
5367 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5368 (org-set-local 'end-of-defun-function 'org-forward-element)
5369 ;; Next error for sparse trees
5370 (org-set-local 'next-error-function 'org-occur-next-match)
5371 ;; Make sure dependence stuff works reliably, even for users who set it
5372 ;; too late :-(
5373 (if org-enforce-todo-dependencies
5374 (add-hook 'org-blocker-hook
5375 'org-block-todo-from-children-or-siblings-or-parent)
5376 (remove-hook 'org-blocker-hook
5377 'org-block-todo-from-children-or-siblings-or-parent))
5378 (if org-enforce-todo-checkbox-dependencies
5379 (add-hook 'org-blocker-hook
5380 'org-block-todo-from-checkboxes)
5381 (remove-hook 'org-blocker-hook
5382 'org-block-todo-from-checkboxes))
5384 ;; Align options lines
5385 (org-set-local
5386 'align-mode-rules-list
5387 '((org-in-buffer-settings
5388 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5389 (modes . '(org-mode)))))
5391 ;; Imenu
5392 (org-set-local 'imenu-create-index-function
5393 'org-imenu-get-tree)
5395 ;; Make isearch reveal context
5396 (if (or (featurep 'xemacs)
5397 (not (boundp 'outline-isearch-open-invisible-function)))
5398 ;; Emacs 21 and XEmacs make use of the hook
5399 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5400 ;; Emacs 22 deals with this through a special variable
5401 (org-set-local 'outline-isearch-open-invisible-function
5402 (lambda (&rest ignore) (org-show-context 'isearch)))
5403 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5405 ;; Setup the pcomplete hooks
5406 (set (make-local-variable 'pcomplete-command-completion-function)
5407 'org-pcomplete-initial)
5408 (set (make-local-variable 'pcomplete-command-name-function)
5409 'org-command-at-point)
5410 (set (make-local-variable 'pcomplete-default-completion-function)
5411 'ignore)
5412 (set (make-local-variable 'pcomplete-parse-arguments-function)
5413 'org-parse-arguments)
5414 (set (make-local-variable 'pcomplete-termination-string) "")
5415 (when (>= emacs-major-version 23)
5416 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5418 ;; If empty file that did not turn on org-mode automatically, make it to.
5419 (if (and org-insert-mode-line-in-empty-file
5420 (org-called-interactively-p 'any)
5421 (= (point-min) (point-max)))
5422 (insert "# -*- mode: org -*-\n\n"))
5423 (unless org-inhibit-startup
5424 (org-unmodified
5425 (and org-startup-with-beamer-mode (org-beamer-mode))
5426 (when org-startup-align-all-tables
5427 (org-table-map-tables 'org-table-align 'quietly))
5428 (when org-startup-with-inline-images
5429 (org-display-inline-images))
5430 (when org-startup-with-latex-preview
5431 (org-preview-latex-fragment))
5432 (unless org-inhibit-startup-visibility-stuff
5433 (org-set-startup-visibility))))
5434 ;; Try to set org-hide correctly
5435 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5437 ;; Update `customize-package-emacs-version-alist'
5438 (add-to-list 'customize-package-emacs-version-alist
5439 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5440 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5441 ("8.0" . "24.4")))
5443 (defvar org-mode-transpose-word-syntax-table
5444 (let ((st (make-syntax-table)))
5445 (mapc (lambda(c) (modify-syntax-entry
5446 (string-to-char (car c)) "w p" st))
5447 org-emphasis-alist)
5448 st))
5450 (when (fboundp 'abbrev-table-put)
5451 (abbrev-table-put org-mode-abbrev-table
5452 :parents (list text-mode-abbrev-table)))
5454 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5456 (defsubst org-fix-ellipsis-at-bol ()
5457 (save-excursion (goto-char (window-start)) (recenter 0)))
5459 (defun org-find-invisible-foreground ()
5460 (let ((candidates (remove
5461 "unspecified-bg"
5462 (nconc
5463 (list (face-background 'default)
5464 (face-background 'org-default))
5465 (mapcar
5466 (lambda (alist)
5467 (when (boundp alist)
5468 (cdr (assoc 'background-color (symbol-value alist)))))
5469 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5470 (list (face-foreground 'org-hide))))))
5471 (car (remove nil candidates))))
5473 (defun org-current-time (&optional rounding-minutes past)
5474 "Current time, possibly rounded to ROUNDING-MINUTES.
5475 When ROUNDING-MINUTES is not an integer, fall back on the car of
5476 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5477 the rounding returns a past time."
5478 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5479 (car org-time-stamp-rounding-minutes)))
5480 (time (decode-time)) res)
5481 (if (< r 1)
5482 (current-time)
5483 (setq res
5484 (apply 'encode-time
5485 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5486 (nthcdr 2 time))))
5487 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5488 (seconds-to-time (- (org-float-time res) (* r 60)))
5489 res))))
5491 (defun org-today ()
5492 "Return today date, considering `org-extend-today-until'."
5493 (time-to-days
5494 (time-subtract (current-time)
5495 (list 0 (* 3600 org-extend-today-until) 0))))
5497 ;;;; Font-Lock stuff, including the activators
5499 (defvar org-mouse-map (make-sparse-keymap))
5500 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5501 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5502 (when org-mouse-1-follows-link
5503 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5504 (when org-tab-follows-link
5505 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5506 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5508 (require 'font-lock)
5510 (defconst org-non-link-chars "]\t\n\r<>")
5511 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5512 "shell" "elisp" "doi" "message"))
5513 (defvar org-link-types-re nil
5514 "Matches a link that has a url-like prefix like \"http:\"")
5515 (defvar org-link-re-with-space nil
5516 "Matches a link with spaces, optional angular brackets around it.")
5517 (defvar org-link-re-with-space2 nil
5518 "Matches a link with spaces, optional angular brackets around it.")
5519 (defvar org-link-re-with-space3 nil
5520 "Matches a link with spaces, only for internal part in bracket links.")
5521 (defvar org-angle-link-re nil
5522 "Matches link with angular brackets, spaces are allowed.")
5523 (defvar org-plain-link-re nil
5524 "Matches plain link, without spaces.")
5525 (defvar org-bracket-link-regexp nil
5526 "Matches a link in double brackets.")
5527 (defvar org-bracket-link-analytic-regexp nil
5528 "Regular expression used to analyze links.
5529 Here is what the match groups contain after a match:
5530 1: http:
5531 2: http
5532 3: path
5533 4: [desc]
5534 5: desc")
5535 (defvar org-bracket-link-analytic-regexp++ nil
5536 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5537 (defvar org-any-link-re nil
5538 "Regular expression matching any link.")
5540 (defconst org-match-sexp-depth 3
5541 "Number of stacked braces for sub/superscript matching.")
5543 (defun org-create-multibrace-regexp (left right n)
5544 "Create a regular expression which will match a balanced sexp.
5545 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5546 as single character strings.
5547 The regexp returned will match the entire expression including the
5548 delimiters. It will also define a single group which contains the
5549 match except for the outermost delimiters. The maximum depth of
5550 stacked delimiters is N. Escaping delimiters is not possible."
5551 (let* ((nothing (concat "[^" left right "]*?"))
5552 (or "\\|")
5553 (re nothing)
5554 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5555 (while (> n 1)
5556 (setq n (1- n)
5557 re (concat re or next)
5558 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5559 (concat left "\\(" re "\\)" right)))
5561 (defvar org-match-substring-regexp
5562 (concat
5563 "\\(\\S-\\)\\([_^]\\)\\("
5564 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5565 "\\|"
5566 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5567 "\\|"
5568 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5569 "The regular expression matching a sub- or superscript.")
5571 (defvar org-match-substring-with-braces-regexp
5572 (concat
5573 "\\(\\S-\\)\\([_^]\\)\\("
5574 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5575 "\\)")
5576 "The regular expression matching a sub- or superscript, forcing braces.")
5578 (defun org-make-link-regexps ()
5579 "Update the link regular expressions.
5580 This should be called after the variable `org-link-types' has changed."
5581 (setq org-link-types-re
5582 (concat
5583 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5584 org-link-re-with-space
5585 (concat
5586 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5587 "\\([^" org-non-link-chars " ]"
5588 "[^" org-non-link-chars "]*"
5589 "[^" org-non-link-chars " ]\\)>?")
5590 org-link-re-with-space2
5591 (concat
5592 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5593 "\\([^" org-non-link-chars " ]"
5594 "[^\t\n\r]*"
5595 "[^" org-non-link-chars " ]\\)>?")
5596 org-link-re-with-space3
5597 (concat
5598 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5599 "\\([^" org-non-link-chars " ]"
5600 "[^\t\n\r]*\\)")
5601 org-angle-link-re
5602 (concat
5603 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5604 "\\([^" org-non-link-chars " ]"
5605 "[^" org-non-link-chars "]*"
5606 "\\)>")
5607 org-plain-link-re
5608 (concat
5609 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5610 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5611 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5612 org-bracket-link-regexp
5613 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5614 org-bracket-link-analytic-regexp
5615 (concat
5616 "\\[\\["
5617 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5618 "\\([^]]+\\)"
5619 "\\]"
5620 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5621 "\\]")
5622 org-bracket-link-analytic-regexp++
5623 (concat
5624 "\\[\\["
5625 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5626 "\\([^]]+\\)"
5627 "\\]"
5628 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5629 "\\]")
5630 org-any-link-re
5631 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5632 org-angle-link-re "\\)\\|\\("
5633 org-plain-link-re "\\)")))
5635 (org-make-link-regexps)
5637 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5638 "Regular expression for fast time stamp matching.")
5639 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5640 "Regular expression for fast time stamp matching.")
5641 (defconst org-ts-regexp0
5642 "\\(\\([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 This one does not require the space after the date, so it can be used
5645 on a string that terminates immediately after the date.")
5646 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5647 "Regular expression matching time strings for analysis.")
5648 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5649 "Regular expression matching time stamps, with groups.")
5650 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5651 "Regular expression matching time stamps (also [..]), with groups.")
5652 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5653 "Regular expression matching a time stamp range.")
5654 (defconst org-tr-regexp-both
5655 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5656 "Regular expression matching a time stamp range.")
5657 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5658 org-ts-regexp "\\)?")
5659 "Regular expression matching a time stamp or time stamp range.")
5660 (defconst org-tsr-regexp-both
5661 (concat org-ts-regexp-both "\\(--?-?"
5662 org-ts-regexp-both "\\)?")
5663 "Regular expression matching a time stamp or time stamp range.
5664 The time stamps may be either active or inactive.")
5666 (defvar org-emph-face nil)
5668 (defun org-do-emphasis-faces (limit)
5669 "Run through the buffer and add overlays to emphasized strings."
5670 (let (rtn a)
5671 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5672 (if (not (= (char-after (match-beginning 3))
5673 (char-after (match-beginning 4))))
5674 (progn
5675 (setq rtn t)
5676 (setq a (assoc (match-string 3) org-emphasis-alist))
5677 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5678 'face
5679 (nth 1 a))
5680 (and (nth 4 a)
5681 (org-remove-flyspell-overlays-in
5682 (match-beginning 0) (match-end 0)))
5683 (add-text-properties (match-beginning 2) (match-end 2)
5684 '(font-lock-multiline t org-emphasis t))
5685 (when org-hide-emphasis-markers
5686 (add-text-properties (match-end 4) (match-beginning 5)
5687 '(invisible org-link))
5688 (add-text-properties (match-beginning 3) (match-end 3)
5689 '(invisible org-link)))))
5690 (backward-char 1))
5691 rtn))
5693 (defun org-emphasize (&optional char)
5694 "Insert or change an emphasis, i.e. a font like bold or italic.
5695 If there is an active region, change that region to a new emphasis.
5696 If there is no region, just insert the marker characters and position
5697 the cursor between them.
5698 CHAR should be the marker character. If it is a space, it means to
5699 remove the emphasis of the selected region.
5700 If CHAR is not given (for example in an interactive call) it will be
5701 prompted for."
5702 (interactive)
5703 (let ((erc org-emphasis-regexp-components)
5704 (prompt "")
5705 (string "") beg end move c s)
5706 (if (org-region-active-p)
5707 (setq beg (region-beginning) end (region-end)
5708 string (buffer-substring beg end))
5709 (setq move t))
5711 (unless char
5712 (message "Emphasis marker or tag: [%s]"
5713 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5714 (setq char (read-char-exclusive)))
5715 (if (equal char ?\ )
5716 (setq s "" move nil)
5717 (unless (assoc (char-to-string char) org-emphasis-alist)
5718 (user-error "No such emphasis marker: \"%c\"" char))
5719 (setq s (char-to-string char)))
5720 (while (and (> (length string) 1)
5721 (equal (substring string 0 1) (substring string -1))
5722 (assoc (substring string 0 1) org-emphasis-alist))
5723 (setq string (substring string 1 -1)))
5724 (setq string (concat s string s))
5725 (if beg (delete-region beg end))
5726 (unless (or (bolp)
5727 (string-match (concat "[" (nth 0 erc) "\n]")
5728 (char-to-string (char-before (point)))))
5729 (insert " "))
5730 (unless (or (eobp)
5731 (string-match (concat "[" (nth 1 erc) "\n]")
5732 (char-to-string (char-after (point)))))
5733 (insert " ") (backward-char 1))
5734 (insert string)
5735 (and move (backward-char 1))))
5737 (defconst org-nonsticky-props
5738 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5740 (defsubst org-rear-nonsticky-at (pos)
5741 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5743 (defun org-activate-plain-links (limit)
5744 "Run through the buffer and add overlays to links."
5745 (let (f hl)
5746 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5747 (not (org-in-src-block-p)))
5748 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5749 (setq f (get-text-property (match-beginning 0) 'face))
5750 (setq hl (org-match-string-no-properties 0))
5751 (if (or (eq f 'org-tag)
5752 (and (listp f) (memq 'org-tag f)))
5754 (add-text-properties (match-beginning 0) (match-end 0)
5755 (list 'mouse-face 'highlight
5756 'face 'org-link
5757 'htmlize-link `(:uri ,hl)
5758 'keymap org-mouse-map))
5759 (org-rear-nonsticky-at (match-end 0)))
5760 t)))
5762 (defun org-activate-code (limit)
5763 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5764 (progn
5765 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5766 (remove-text-properties (match-beginning 0) (match-end 0)
5767 '(display t invisible t intangible t))
5768 t)))
5770 (defcustom org-src-fontify-natively nil
5771 "When non-nil, fontify code in code blocks."
5772 :type 'boolean
5773 :version "24.1"
5774 :group 'org-appearance
5775 :group 'org-babel)
5777 (defcustom org-allow-promoting-top-level-subtree nil
5778 "When non-nil, allow promoting a top level subtree.
5779 The leading star of the top level headline will be replaced
5780 by a #."
5781 :type 'boolean
5782 :version "24.1"
5783 :group 'org-appearance)
5785 (defun org-fontify-meta-lines-and-blocks (limit)
5786 (condition-case nil
5787 (org-fontify-meta-lines-and-blocks-1 limit)
5788 (error (message "org-mode fontification error"))))
5790 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5791 "Fontify #+ lines and blocks."
5792 (let ((case-fold-search t))
5793 (if (re-search-forward
5794 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5795 limit t)
5796 (let ((beg (match-beginning 0))
5797 (block-start (match-end 0))
5798 (block-end nil)
5799 (lang (match-string 7))
5800 (beg1 (line-beginning-position 2))
5801 (dc1 (downcase (match-string 2)))
5802 (dc3 (downcase (match-string 3)))
5803 end end1 quoting block-type ovl)
5804 (cond
5805 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5806 ;; a single line of backend-specific content
5807 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5808 (remove-text-properties (match-beginning 0) (match-end 0)
5809 '(display t invisible t intangible t))
5810 (add-text-properties (match-beginning 1) (match-end 3)
5811 '(font-lock-fontified t face org-meta-line))
5812 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5813 '(font-lock-fontified t face org-block))
5814 ; for backend-specific code
5816 ((and (match-end 4) (equal dc3 "+begin"))
5817 ;; Truly a block
5818 (setq block-type (downcase (match-string 5))
5819 quoting (member block-type org-protecting-blocks))
5820 (when (re-search-forward
5821 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5822 nil t) ;; on purpose, we look further than LIMIT
5823 (setq end (min (point-max) (match-end 0))
5824 end1 (min (point-max) (1- (match-beginning 0))))
5825 (setq block-end (match-beginning 0))
5826 (when quoting
5827 (remove-text-properties beg end
5828 '(display t invisible t intangible t)))
5829 (add-text-properties
5830 beg end
5831 '(font-lock-fontified t font-lock-multiline t))
5832 (add-text-properties beg beg1 '(face org-meta-line))
5833 (add-text-properties end1 (min (point-max) (1+ end))
5834 '(face org-meta-line)) ; for end_src
5835 (cond
5836 ((and lang (not (string= lang "")) org-src-fontify-natively)
5837 (org-src-font-lock-fontify-block lang block-start block-end)
5838 ;; remove old background overlays
5839 (mapc (lambda (ov)
5840 (if (eq (overlay-get ov 'face) 'org-block-background)
5841 (delete-overlay ov)))
5842 (overlays-at (/ (+ beg1 block-end) 2)))
5843 ;; add a background overlay
5844 (setq ovl (make-overlay beg1 block-end))
5845 (overlay-put ovl 'face 'org-block-background)
5846 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5847 (quoting
5848 (add-text-properties beg1 (min (point-max) (1+ end1))
5849 '(face org-block))) ; end of source block
5850 ((not org-fontify-quote-and-verse-blocks))
5851 ((string= block-type "quote")
5852 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5853 ((string= block-type "verse")
5854 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5855 (add-text-properties beg beg1 '(face org-block-begin-line))
5856 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5857 '(face org-block-end-line))
5859 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5860 (add-text-properties
5861 beg (match-end 3)
5862 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5863 '(font-lock-fontified t invisible t)
5864 '(font-lock-fontified t face org-document-info-keyword)))
5865 (add-text-properties
5866 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5867 (if (string-equal dc1 "+title:")
5868 '(font-lock-fontified t face org-document-title)
5869 '(font-lock-fontified t face org-document-info))))
5870 ((or (equal dc1 "+results")
5871 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5872 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5873 "+call:" "+header:" "+headers:" "+name:"))
5874 (and (match-end 4) (equal dc3 "+attr")))
5875 (add-text-properties
5876 beg (match-end 0)
5877 '(font-lock-fontified t face org-meta-line))
5879 ((member dc3 '(" " ""))
5880 (add-text-properties
5881 beg (match-end 0)
5882 '(font-lock-fontified t face font-lock-comment-face)))
5883 ((not (member (char-after beg) '(?\ ?\t)))
5884 ;; just any other in-buffer setting, but not indented
5885 (add-text-properties
5886 beg (match-end 0)
5887 '(font-lock-fontified t face org-meta-line))
5889 (t nil))))))
5891 (defun org-activate-angle-links (limit)
5892 "Run through the buffer and add overlays to links."
5893 (if (and (re-search-forward org-angle-link-re limit t)
5894 (not (org-in-src-block-p)))
5895 (progn
5896 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5897 (add-text-properties (match-beginning 0) (match-end 0)
5898 (list 'mouse-face 'highlight
5899 'keymap org-mouse-map))
5900 (org-rear-nonsticky-at (match-end 0))
5901 t)))
5903 (defun org-activate-footnote-links (limit)
5904 "Run through the buffer and add overlays to footnotes."
5905 (let ((fn (org-footnote-next-reference-or-definition limit)))
5906 (when fn
5907 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5908 (org-remove-flyspell-overlays-in beg end)
5909 (add-text-properties beg end
5910 (list 'mouse-face 'highlight
5911 'keymap org-mouse-map
5912 'help-echo
5913 (if (= (point-at-bol) beg)
5914 "Footnote definition"
5915 "Footnote reference")
5916 'font-lock-fontified t
5917 'font-lock-multiline t
5918 'face 'org-footnote))))))
5920 (defun org-activate-bracket-links (limit)
5921 "Run through the buffer and add overlays to bracketed links."
5922 (if (and (re-search-forward org-bracket-link-regexp limit t)
5923 (not (org-in-src-block-p)))
5924 (let* ((hl (org-match-string-no-properties 1))
5925 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5926 (ip (org-maybe-intangible
5927 (list 'invisible 'org-link
5928 'keymap org-mouse-map 'mouse-face 'highlight
5929 'font-lock-multiline t 'help-echo help
5930 'htmlize-link `(:uri ,hl))))
5931 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5932 'font-lock-multiline t 'help-echo help
5933 'htmlize-link `(:uri ,hl))))
5934 ;; We need to remove the invisible property here. Table narrowing
5935 ;; may have made some of this invisible.
5936 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5937 (remove-text-properties (match-beginning 0) (match-end 0)
5938 '(invisible nil))
5939 (if (match-end 3)
5940 (progn
5941 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5942 (org-rear-nonsticky-at (match-beginning 3))
5943 (add-text-properties (match-beginning 3) (match-end 3) vp)
5944 (org-rear-nonsticky-at (match-end 3))
5945 (add-text-properties (match-end 3) (match-end 0) ip)
5946 (org-rear-nonsticky-at (match-end 0)))
5947 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5948 (org-rear-nonsticky-at (match-beginning 1))
5949 (add-text-properties (match-beginning 1) (match-end 1) vp)
5950 (org-rear-nonsticky-at (match-end 1))
5951 (add-text-properties (match-end 1) (match-end 0) ip)
5952 (org-rear-nonsticky-at (match-end 0)))
5953 t)))
5955 (defun org-activate-dates (limit)
5956 "Run through the buffer and add overlays to dates."
5957 (if (and (re-search-forward org-tsr-regexp-both limit t)
5958 (not (equal (char-before (match-beginning 0)) 91)))
5959 (progn
5960 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5961 (add-text-properties (match-beginning 0) (match-end 0)
5962 (list 'mouse-face 'highlight
5963 'keymap org-mouse-map))
5964 (org-rear-nonsticky-at (match-end 0))
5965 (when org-display-custom-times
5966 (if (match-end 3)
5967 (org-display-custom-time (match-beginning 3) (match-end 3)))
5968 (org-display-custom-time (match-beginning 1) (match-end 1)))
5969 t)))
5971 (defvar org-target-link-regexp nil
5972 "Regular expression matching radio targets in plain text.")
5973 (make-variable-buffer-local 'org-target-link-regexp)
5974 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5975 "Regular expression matching a link target.")
5976 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5977 "Regular expression matching a radio target.")
5978 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5979 "Regular expression matching any target.")
5981 (defun org-activate-target-links (limit)
5982 "Run through the buffer and add overlays to target matches."
5983 (when org-target-link-regexp
5984 (let ((case-fold-search t))
5985 (if (re-search-forward org-target-link-regexp limit t)
5986 (progn
5987 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5988 (add-text-properties (match-beginning 0) (match-end 0)
5989 (list 'mouse-face 'highlight
5990 'keymap org-mouse-map
5991 'help-echo "Radio target link"
5992 'org-linked-text t))
5993 (org-rear-nonsticky-at (match-end 0))
5994 t)))))
5996 (defun org-update-radio-target-regexp ()
5997 "Find all radio targets in this file and update the regular expression."
5998 (interactive)
5999 (when (memq 'radio org-activate-links)
6000 (setq org-target-link-regexp
6001 (org-make-target-link-regexp (org-all-targets 'radio)))
6002 (org-restart-font-lock)))
6004 (defun org-hide-wide-columns (limit)
6005 (let (s e)
6006 (setq s (text-property-any (point) (or limit (point-max))
6007 'org-cwidth t))
6008 (when s
6009 (setq e (next-single-property-change s 'org-cwidth))
6010 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6011 (goto-char e)
6012 t)))
6014 (defvar org-latex-and-related-regexp nil
6015 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6016 (defvar org-match-substring-regexp)
6017 (defvar org-match-substring-with-braces-regexp)
6019 (defun org-compute-latex-and-related-regexp ()
6020 "Compute regular expression for LaTeX, entities and sub/superscript.
6021 Result depends on variable `org-highlight-latex-and-related'."
6022 (org-set-local
6023 'org-latex-and-related-regexp
6024 (let* ((re-sub
6025 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6026 ((eq org-use-sub-superscripts '{})
6027 (list org-match-substring-with-braces-regexp))
6028 (org-use-sub-superscripts (list org-match-substring-regexp))))
6029 (re-latex
6030 (when (memq 'latex org-highlight-latex-and-related)
6031 (let ((matchers (plist-get org-format-latex-options :matchers)))
6032 (delq nil
6033 (mapcar (lambda (x)
6034 (and (member (car x) matchers) (nth 1 x)))
6035 org-latex-regexps)))))
6036 (re-entities
6037 (when (memq 'entities org-highlight-latex-and-related)
6038 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6039 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6041 (defun org-do-latex-and-related (limit)
6042 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6043 LIMIT bounds the search for syntax to highlight. Stop at first
6044 highlighted object, if any. Return t if some highlighting was
6045 done, nil otherwise."
6046 (when (org-string-nw-p org-latex-and-related-regexp)
6047 (catch 'found
6048 (while (re-search-forward org-latex-and-related-regexp limit t)
6049 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6050 'face))
6051 '(org-code org-verbatim underline))
6052 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6053 '(?_ ?^))
6055 0)))
6056 (font-lock-prepend-text-property
6057 (+ offset (match-beginning 0)) (match-end 0)
6058 'face 'org-latex-and-related)
6059 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6060 '(font-lock-multiline t)))
6061 (throw 'found t)))
6062 nil)))
6064 (defun org-restart-font-lock ()
6065 "Restart `font-lock-mode', to force refontification."
6066 (when (and (boundp 'font-lock-mode) font-lock-mode)
6067 (font-lock-mode -1)
6068 (font-lock-mode 1)))
6070 (defun org-all-targets (&optional radio)
6071 "Return a list of all targets in this file.
6072 When optional argument RADIO is non-nil, only find radio
6073 targets."
6074 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6075 (save-excursion
6076 (goto-char (point-min))
6077 (while (re-search-forward re nil t)
6078 ;; Make sure point is really within the object.
6079 (backward-char)
6080 (let ((obj (org-element-context)))
6081 (when (memq (org-element-type obj) '(radio-target target))
6082 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6083 rtn)))
6085 (defun org-make-target-link-regexp (targets)
6086 "Make regular expression matching all strings in TARGETS.
6087 The regular expression finds the targets also if there is a line break
6088 between words."
6089 (and targets
6090 (concat
6091 "\\<\\("
6092 (mapconcat
6093 (lambda (x)
6094 (setq x (regexp-quote x))
6095 (while (string-match " +" x)
6096 (setq x (replace-match "\\s-+" t t x)))
6098 targets
6099 "\\|")
6100 "\\)\\>")))
6102 (defun org-activate-tags (limit)
6103 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6104 (progn
6105 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6106 (add-text-properties (match-beginning 1) (match-end 1)
6107 (list 'mouse-face 'highlight
6108 'keymap org-mouse-map))
6109 (org-rear-nonsticky-at (match-end 1))
6110 t)))
6112 (defun org-outline-level ()
6113 "Compute the outline level of the heading at point.
6114 If this is called at a normal headline, the level is the number of stars.
6115 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6116 (save-excursion
6117 (if (not (condition-case nil
6118 (org-back-to-heading t)
6119 (error nil)))
6121 (looking-at org-outline-regexp)
6122 (1- (- (match-end 0) (match-beginning 0))))))
6124 (defvar org-font-lock-keywords nil)
6126 (defsubst org-re-property (property &optional literal)
6127 "Return a regexp matching a PROPERTY line.
6128 Match group 3 will be set to the value if it exists."
6129 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6130 (if literal property (regexp-quote property))
6131 "\\):\\)[ \t]+\\(?3:[^ \t\r\n].*?\\)\\(?5:[ \t]*\\)$"))
6133 (defconst org-property-re
6134 (org-re-property ".*?" 'literal)
6135 "Regular expression matching a property line.
6136 There are four matching groups:
6137 1: :PROPKEY: including the leading and trailing colon,
6138 2: PROPKEY without the leading and trailing colon,
6139 3: PROPVAL without leading or trailing spaces,
6140 4: the indentation of the current line,
6141 5: trailing whitespace.")
6143 (defvar org-font-lock-hook nil
6144 "Functions to be called for special font lock stuff.")
6146 (defvar org-font-lock-set-keywords-hook nil
6147 "Functions that can manipulate `org-font-lock-extra-keywords'.
6148 This is called after `org-font-lock-extra-keywords' is defined, but before
6149 it is installed to be used by font lock. This can be useful if something
6150 needs to be inserted at a specific position in the font-lock sequence.")
6152 (defun org-font-lock-hook (limit)
6153 "Run `org-font-lock-hook' within LIMIT."
6154 (run-hook-with-args 'org-font-lock-hook limit))
6156 (defun org-set-font-lock-defaults ()
6157 "Set font lock defaults for the current buffer."
6158 (let* ((em org-fontify-emphasized-text)
6159 (lk org-activate-links)
6160 (org-font-lock-extra-keywords
6161 (list
6162 ;; Call the hook
6163 '(org-font-lock-hook)
6164 ;; Headlines
6165 `(,(if org-fontify-whole-heading-line
6166 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6167 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6168 (1 (org-get-level-face 1))
6169 (2 (org-get-level-face 2))
6170 (3 (org-get-level-face 3)))
6171 ;; Table lines
6172 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6173 (1 'org-table t))
6174 ;; Table internals
6175 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6176 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6177 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6178 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6179 ;; Drawers
6180 (list org-drawer-regexp '(0 'org-special-keyword t))
6181 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6182 ;; Properties
6183 (list org-property-re
6184 '(1 'org-special-keyword t)
6185 '(3 'org-property-value t))
6186 ;; Links
6187 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6188 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6189 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6190 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6191 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6192 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6193 (if (memq 'footnote lk) '(org-activate-footnote-links))
6194 ;; Targets.
6195 (list org-any-target-regexp '(0 'org-target t))
6196 ;; Diary sexps.
6197 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6198 ;; Macro
6199 '("{{{.+}}}" (0 'org-macro t))
6200 '(org-hide-wide-columns (0 nil append))
6201 ;; TODO keyword
6202 (list (format org-heading-keyword-regexp-format
6203 org-todo-regexp)
6204 '(2 (org-get-todo-face 2) t))
6205 ;; DONE
6206 (if org-fontify-done-headline
6207 (list (format org-heading-keyword-regexp-format
6208 (concat
6209 "\\(?:"
6210 (mapconcat 'regexp-quote org-done-keywords "\\|")
6211 "\\)"))
6212 '(2 'org-headline-done t))
6213 nil)
6214 ;; Priorities
6215 '(org-font-lock-add-priority-faces)
6216 ;; Tags
6217 '(org-font-lock-add-tag-faces)
6218 ;; Tags groups
6219 (if (and org-group-tags org-tag-groups-alist)
6220 (list (concat org-outline-regexp-bol ".+\\(:"
6221 (regexp-opt (mapcar 'car org-tag-groups-alist))
6222 ":\\).*$")
6223 '(1 'org-tag-group prepend)))
6224 ;; Special keywords
6225 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6226 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6227 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6228 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6229 ;; Emphasis
6230 (if em
6231 (if (featurep 'xemacs)
6232 '(org-do-emphasis-faces (0 nil append))
6233 '(org-do-emphasis-faces)))
6234 ;; Checkboxes
6235 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6236 1 'org-checkbox prepend)
6237 (if (cdr (assq 'checkbox org-list-automatic-rules))
6238 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6239 (0 (org-get-checkbox-statistics-face) t)))
6240 ;; Description list items
6241 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6242 1 'org-list-dt prepend)
6243 ;; ARCHIVEd headings
6244 (list (concat
6245 org-outline-regexp-bol
6246 "\\(.*:" org-archive-tag ":.*\\)")
6247 '(1 'org-archived prepend))
6248 ;; Specials
6249 '(org-do-latex-and-related)
6250 '(org-fontify-entities)
6251 '(org-raise-scripts)
6252 ;; Code
6253 '(org-activate-code (1 'org-code t))
6254 ;; COMMENT
6255 (list (format org-heading-keyword-regexp-format
6256 (concat "\\("
6257 org-comment-string "\\|" org-quote-string
6258 "\\)"))
6259 '(2 'org-special-keyword t))
6260 ;; Blocks and meta lines
6261 '(org-fontify-meta-lines-and-blocks))))
6262 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6263 (run-hooks 'org-font-lock-set-keywords-hook)
6264 ;; Now set the full font-lock-keywords
6265 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6266 (org-set-local 'font-lock-defaults
6267 '(org-font-lock-keywords t nil nil backward-paragraph))
6268 (kill-local-variable 'font-lock-keywords) nil))
6270 (defun org-toggle-pretty-entities ()
6271 "Toggle the composition display of entities as UTF8 characters."
6272 (interactive)
6273 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6274 (org-restart-font-lock)
6275 (if org-pretty-entities
6276 (message "Entities are now displayed as UTF8 characters")
6277 (save-restriction
6278 (widen)
6279 (org-decompose-region (point-min) (point-max))
6280 (message "Entities are now displayed as plain text"))))
6282 (defvar org-custom-properties-overlays nil
6283 "List of overlays used for custom properties.")
6284 (make-variable-buffer-local 'org-custom-properties-overlays)
6286 (defun org-toggle-custom-properties-visibility ()
6287 "Display or hide properties in `org-custom-properties'."
6288 (interactive)
6289 (if org-custom-properties-overlays
6290 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6291 (setq org-custom-properties-overlays nil))
6292 (unless (not org-custom-properties)
6293 (save-excursion
6294 (save-restriction
6295 (widen)
6296 (goto-char (point-min))
6297 (while (re-search-forward org-property-re nil t)
6298 (mapc (lambda(p)
6299 (when (equal p (substring (match-string 1) 1 -1))
6300 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6301 (overlay-put o 'invisible t)
6302 (overlay-put o 'org-custom-property t)
6303 (push o org-custom-properties-overlays))))
6304 org-custom-properties)))))))
6306 (defun org-fontify-entities (limit)
6307 "Find an entity to fontify."
6308 (let (ee)
6309 (when org-pretty-entities
6310 (catch 'match
6311 (while (re-search-forward
6312 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6313 limit t)
6314 (if (and (not (org-in-indented-comment-line))
6315 (setq ee (org-entity-get (match-string 1)))
6316 (= (length (nth 6 ee)) 1))
6317 (let*
6318 ((end (if (equal (match-string 2) "{}")
6319 (match-end 2)
6320 (match-end 1))))
6321 (add-text-properties
6322 (match-beginning 0) end
6323 (list 'font-lock-fontified t))
6324 (compose-region (match-beginning 0) end
6325 (nth 6 ee) nil)
6326 (backward-char 1)
6327 (throw 'match t))))
6328 nil))))
6330 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6331 "Fontify string S like in Org-mode."
6332 (with-temp-buffer
6333 (insert s)
6334 (let ((org-odd-levels-only odd-levels))
6335 (org-mode)
6336 (font-lock-fontify-buffer)
6337 (buffer-string))))
6339 (defvar org-m nil)
6340 (defvar org-l nil)
6341 (defvar org-f nil)
6342 (defun org-get-level-face (n)
6343 "Get the right face for match N in font-lock matching of headlines."
6344 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6345 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6346 (if org-cycle-level-faces
6347 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6348 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6349 (cond
6350 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6351 ((eq n 2) org-f)
6352 (t (if org-level-color-stars-only nil org-f))))
6355 (defun org-get-todo-face (kwd)
6356 "Get the right face for a TODO keyword KWD.
6357 If KWD is a number, get the corresponding match group."
6358 (if (numberp kwd) (setq kwd (match-string kwd)))
6359 (or (org-face-from-face-or-color
6360 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6361 (and (member kwd org-done-keywords) 'org-done)
6362 'org-todo))
6364 (defun org-face-from-face-or-color (context inherit face-or-color)
6365 "Create a face list that inherits INHERIT, but sets the foreground color.
6366 When FACE-OR-COLOR is not a string, just return it."
6367 (if (stringp face-or-color)
6368 (list :inherit inherit
6369 (cdr (assoc context org-faces-easy-properties))
6370 face-or-color)
6371 face-or-color))
6373 (defun org-font-lock-add-tag-faces (limit)
6374 "Add the special tag faces."
6375 (when (and org-tag-faces org-tags-special-faces-re)
6376 (while (re-search-forward org-tags-special-faces-re limit t)
6377 (add-text-properties (match-beginning 1) (match-end 1)
6378 (list 'face (org-get-tag-face 1)
6379 'font-lock-fontified t))
6380 (backward-char 1))))
6382 (defun org-font-lock-add-priority-faces (limit)
6383 "Add the special priority faces."
6384 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6385 (when (save-match-data (org-at-heading-p))
6386 (add-text-properties
6387 (match-beginning 0) (match-end 0)
6388 (list 'face (or (org-face-from-face-or-color
6389 'priority 'org-priority
6390 (cdr (assoc (char-after (match-beginning 1))
6391 org-priority-faces)))
6392 'org-priority)
6393 'font-lock-fontified t)))))
6395 (defun org-get-tag-face (kwd)
6396 "Get the right face for a TODO keyword KWD.
6397 If KWD is a number, get the corresponding match group."
6398 (if (numberp kwd) (setq kwd (match-string kwd)))
6399 (or (org-face-from-face-or-color
6400 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6401 'org-tag))
6403 (defun org-unfontify-region (beg end &optional maybe_loudly)
6404 "Remove fontification and activation overlays from links."
6405 (font-lock-default-unfontify-region beg end)
6406 (let* ((buffer-undo-list t)
6407 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6408 (inhibit-modification-hooks t)
6409 deactivate-mark buffer-file-name buffer-file-truename)
6410 (org-decompose-region beg end)
6411 (remove-text-properties beg end
6412 '(mouse-face t keymap t org-linked-text t
6413 invisible t intangible t
6414 org-no-flyspell t org-emphasis t))
6415 (org-remove-font-lock-display-properties beg end)))
6417 (defconst org-script-display '(((raise -0.3) (height 0.7))
6418 ((raise 0.3) (height 0.7))
6419 ((raise -0.5))
6420 ((raise 0.5)))
6421 "Display properties for showing superscripts and subscripts.")
6423 (defun org-remove-font-lock-display-properties (beg end)
6424 "Remove specific display properties that have been added by font lock.
6425 The will remove the raise properties that are used to show superscripts
6426 and subscripts."
6427 (let (next prop)
6428 (while (< beg end)
6429 (setq next (next-single-property-change beg 'display nil end)
6430 prop (get-text-property beg 'display))
6431 (if (member prop org-script-display)
6432 (put-text-property beg next 'display nil))
6433 (setq beg next))))
6435 (defun org-raise-scripts (limit)
6436 "Add raise properties to sub/superscripts."
6437 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6438 (if (re-search-forward
6439 (if (eq org-use-sub-superscripts t)
6440 org-match-substring-regexp
6441 org-match-substring-with-braces-regexp)
6442 limit t)
6443 (let* ((pos (point)) table-p comment-p
6444 (mpos (match-beginning 3))
6445 (emph-p (get-text-property mpos 'org-emphasis))
6446 (link-p (get-text-property mpos 'mouse-face))
6447 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6448 (goto-char (point-at-bol))
6449 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6450 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6451 (goto-char pos)
6452 ;; Handle a_b^c
6453 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6454 (if (or comment-p emph-p link-p keyw-p)
6456 (put-text-property (match-beginning 3) (match-end 0)
6457 'display
6458 (if (equal (char-after (match-beginning 2)) ?^)
6459 (nth (if table-p 3 1) org-script-display)
6460 (nth (if table-p 2 0) org-script-display)))
6461 (add-text-properties (match-beginning 2) (match-end 2)
6462 (list 'invisible t
6463 'org-dwidth t 'org-dwidth-n 1))
6464 (if (and (eq (char-after (match-beginning 3)) ?{)
6465 (eq (char-before (match-end 3)) ?}))
6466 (progn
6467 (add-text-properties
6468 (match-beginning 3) (1+ (match-beginning 3))
6469 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6470 (add-text-properties
6471 (1- (match-end 3)) (match-end 3)
6472 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6473 t)))))
6475 ;;;; Visibility cycling, including org-goto and indirect buffer
6477 ;;; Cycling
6479 (defvar org-cycle-global-status nil)
6480 (make-variable-buffer-local 'org-cycle-global-status)
6481 (put 'org-cycle-global-status 'org-state t)
6482 (defvar org-cycle-subtree-status nil)
6483 (make-variable-buffer-local 'org-cycle-subtree-status)
6484 (put 'org-cycle-subtree-status 'org-state t)
6486 (defvar org-inlinetask-min-level)
6488 ;;;###autoload
6489 (defun org-cycle (&optional arg)
6490 "TAB-action and visibility cycling for Org-mode.
6492 This is the command invoked in Org-mode by the TAB key. Its main purpose
6493 is outline visibility cycling, but it also invokes other actions
6494 in special contexts.
6496 - When this function is called with a prefix argument, rotate the entire
6497 buffer through 3 states (global cycling)
6498 1. OVERVIEW: Show only top-level headlines.
6499 2. CONTENTS: Show all headlines of all levels, but no body text.
6500 3. SHOW ALL: Show everything.
6501 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6502 determined by the variable `org-startup-folded', and by any VISIBILITY
6503 properties in the buffer.
6504 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6505 including any drawers.
6507 - When inside a table, re-align the table and move to the next field.
6509 - When point is at the beginning of a headline, rotate the subtree started
6510 by this line through 3 different states (local cycling)
6511 1. FOLDED: Only the main headline is shown.
6512 2. CHILDREN: The main headline and the direct children are shown.
6513 From this state, you can move to one of the children
6514 and zoom in further.
6515 3. SUBTREE: Show the entire subtree, including body text.
6516 If there is no subtree, switch directly from CHILDREN to FOLDED.
6518 - When point is at the beginning of an empty headline and the variable
6519 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6520 of the headline by demoting and promoting it to likely levels. This
6521 speeds up creation document structure by pressing TAB once or several
6522 times right after creating a new headline.
6524 - When there is a numeric prefix, go up to a heading with level ARG, do
6525 a `show-subtree' and return to the previous cursor position. If ARG
6526 is negative, go up that many levels.
6528 - When point is not at the beginning of a headline, execute the global
6529 binding for TAB, which is re-indenting the line. See the option
6530 `org-cycle-emulate-tab' for details.
6532 - Special case: if point is at the beginning of the buffer and there is
6533 no headline in line 1, this function will act as if called with prefix arg
6534 (C-u TAB, same as S-TAB) also when called without prefix arg.
6535 But only if also the variable `org-cycle-global-at-bob' is t."
6536 (interactive "P")
6537 (org-load-modules-maybe)
6538 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6539 (and org-cycle-level-after-item/entry-creation
6540 (or (org-cycle-level)
6541 (org-cycle-item-indentation))))
6542 (let* (message-log-max ; Don't populate the *Messages* buffer
6543 (limit-level
6544 (or org-cycle-max-level
6545 (and (boundp 'org-inlinetask-min-level)
6546 org-inlinetask-min-level
6547 (1- org-inlinetask-min-level))))
6548 (nstars (and limit-level
6549 (if org-odd-levels-only
6550 (and limit-level (1- (* limit-level 2)))
6551 limit-level)))
6552 (org-outline-regexp
6553 (if (not (derived-mode-p 'org-mode))
6554 outline-regexp
6555 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6556 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6557 (not (looking-at org-outline-regexp))))
6558 (org-cycle-hook
6559 (if bob-special
6560 (delq 'org-optimize-window-after-visibility-change
6561 (copy-sequence org-cycle-hook))
6562 org-cycle-hook))
6563 (pos (point)))
6565 (if (or bob-special (equal arg '(4)))
6566 ;; special case: use global cycling
6567 (setq arg t))
6569 (cond
6571 ((equal arg '(16))
6572 (setq last-command 'dummy)
6573 (org-set-startup-visibility)
6574 (message "Startup visibility, plus VISIBILITY properties"))
6576 ((equal arg '(64))
6577 (show-all)
6578 (message "Entire buffer visible, including drawers"))
6580 ;; Table: enter it or move to the next field.
6581 ((org-at-table-p 'any)
6582 (if (org-at-table.el-p)
6583 (message "Use C-c ' to edit table.el tables")
6584 (if arg (org-table-edit-field t)
6585 (org-table-justify-field-maybe)
6586 (call-interactively 'org-table-next-field))))
6588 ((run-hook-with-args-until-success
6589 'org-tab-after-check-for-table-hook))
6591 ;; Global cycling: delegate to `org-cycle-internal-global'.
6592 ((eq arg t) (org-cycle-internal-global))
6594 ;; Drawers: delegate to `org-flag-drawer'.
6595 ((and org-drawers org-drawer-regexp
6596 (save-excursion
6597 (beginning-of-line 1)
6598 (looking-at org-drawer-regexp)))
6599 (org-flag-drawer ; toggle block visibility
6600 (not (get-char-property (match-end 0) 'invisible))))
6602 ;; Show-subtree, ARG levels up from here.
6603 ((integerp arg)
6604 (save-excursion
6605 (org-back-to-heading)
6606 (outline-up-heading (if (< arg 0) (- arg)
6607 (- (funcall outline-level) arg)))
6608 (org-show-subtree)))
6610 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6611 ((and (featurep 'org-inlinetask)
6612 (org-inlinetask-at-task-p)
6613 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6614 (org-inlinetask-toggle-visibility))
6616 ((org-try-cdlatex-tab))
6618 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6619 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6620 (save-excursion (beginning-of-line 1)
6621 (looking-at org-outline-regexp)))
6622 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6623 (org-cycle-internal-local))
6625 ;; From there: TAB emulation and template completion.
6626 (buffer-read-only (org-back-to-heading))
6628 ((run-hook-with-args-until-success
6629 'org-tab-after-check-for-cycling-hook))
6631 ((org-try-structure-completion))
6633 ((run-hook-with-args-until-success
6634 'org-tab-before-tab-emulation-hook))
6636 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6637 (or (not (bolp))
6638 (not (looking-at org-outline-regexp))))
6639 (call-interactively (global-key-binding "\t")))
6641 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6642 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6643 (or (and (eq org-cycle-emulate-tab 'white)
6644 (= (match-end 0) (point-at-eol)))
6645 (and (eq org-cycle-emulate-tab 'whitestart)
6646 (>= (match-end 0) pos))))
6648 (eq org-cycle-emulate-tab t))
6649 (call-interactively (global-key-binding "\t")))
6651 (t (save-excursion
6652 (org-back-to-heading)
6653 (org-cycle)))))))
6655 (defun org-cycle-internal-global ()
6656 "Do the global cycling action."
6657 ;; Hack to avoid display of messages for .org attachments in Gnus
6658 (let (message-log-max ; Don't populate the *Messages* buffer
6659 (ga (string-match "\\*fontification" (buffer-name))))
6660 (cond
6661 ((and (eq last-command this-command)
6662 (eq org-cycle-global-status 'overview))
6663 ;; We just created the overview - now do table of contents
6664 ;; This can be slow in very large buffers, so indicate action
6665 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6666 (unless ga (message "CONTENTS..."))
6667 (org-content)
6668 (unless ga (message "CONTENTS...done"))
6669 (setq org-cycle-global-status 'contents)
6670 (run-hook-with-args 'org-cycle-hook 'contents))
6672 ((and (eq last-command this-command)
6673 (eq org-cycle-global-status 'contents))
6674 ;; We just showed the table of contents - now show everything
6675 (run-hook-with-args 'org-pre-cycle-hook 'all)
6676 (show-all)
6677 (unless ga (message "SHOW ALL"))
6678 (setq org-cycle-global-status 'all)
6679 (run-hook-with-args 'org-cycle-hook 'all))
6682 ;; Default action: go to overview
6683 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6684 (org-overview)
6685 (unless ga (message "OVERVIEW"))
6686 (setq org-cycle-global-status 'overview)
6687 (run-hook-with-args 'org-cycle-hook 'overview)))))
6689 (defun org-cycle-internal-local ()
6690 "Do the local cycling action."
6691 (let (message-log-max ; Don't populate the *Messages* buffer
6692 (goal-column 0) eoh eol eos has-children children-skipped struct)
6693 ;; First, determine end of headline (EOH), end of subtree or item
6694 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6695 (save-excursion
6696 (if (org-at-item-p)
6697 (progn
6698 (beginning-of-line)
6699 (setq struct (org-list-struct))
6700 (setq eoh (point-at-eol))
6701 (setq eos (org-list-get-item-end-before-blank (point) struct))
6702 (setq has-children (org-list-has-child-p (point) struct)))
6703 (org-back-to-heading)
6704 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6705 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6706 (setq has-children
6707 (or (save-excursion
6708 (let ((level (funcall outline-level)))
6709 (outline-next-heading)
6710 (and (org-at-heading-p t)
6711 (> (funcall outline-level) level))))
6712 (save-excursion
6713 (org-list-search-forward (org-item-beginning-re) eos t)))))
6714 ;; Determine end invisible part of buffer (EOL)
6715 (beginning-of-line 2)
6716 ;; XEmacs doesn't have `next-single-char-property-change'
6717 (if (featurep 'xemacs)
6718 (while (and (not (eobp)) ;; this is like `next-line'
6719 (get-char-property (1- (point)) 'invisible))
6720 (beginning-of-line 2))
6721 (while (and (not (eobp)) ;; this is like `next-line'
6722 (get-char-property (1- (point)) 'invisible))
6723 (goto-char (next-single-char-property-change (point) 'invisible))
6724 (and (eolp) (beginning-of-line 2))))
6725 (setq eol (point)))
6726 ;; Find out what to do next and set `this-command'
6727 (cond
6728 ((= eos eoh)
6729 ;; Nothing is hidden behind this heading
6730 (unless (org-before-first-heading-p)
6731 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6732 (message "EMPTY ENTRY")
6733 (setq org-cycle-subtree-status nil)
6734 (save-excursion
6735 (goto-char eos)
6736 (outline-next-heading)
6737 (if (outline-invisible-p) (org-flag-heading nil))))
6738 ((and (or (>= eol eos)
6739 (not (string-match "\\S-" (buffer-substring eol eos))))
6740 (or has-children
6741 (not (setq children-skipped
6742 org-cycle-skip-children-state-if-no-children))))
6743 ;; Entire subtree is hidden in one line: children view
6744 (unless (org-before-first-heading-p)
6745 (run-hook-with-args 'org-pre-cycle-hook 'children))
6746 (if (org-at-item-p)
6747 (org-list-set-item-visibility (point-at-bol) struct 'children)
6748 (org-show-entry)
6749 (org-with-limited-levels (show-children))
6750 ;; FIXME: This slows down the func way too much.
6751 ;; How keep drawers hidden in subtree anyway?
6752 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6753 ;; (org-cycle-hide-drawers 'subtree))
6755 ;; Fold every list in subtree to top-level items.
6756 (when (eq org-cycle-include-plain-lists 'integrate)
6757 (save-excursion
6758 (org-back-to-heading)
6759 (while (org-list-search-forward (org-item-beginning-re) eos t)
6760 (beginning-of-line 1)
6761 (let* ((struct (org-list-struct))
6762 (prevs (org-list-prevs-alist struct))
6763 (end (org-list-get-bottom-point struct)))
6764 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6765 (org-list-get-all-items (point) struct prevs))
6766 (goto-char (if (< end eos) end eos)))))))
6767 (message "CHILDREN")
6768 (save-excursion
6769 (goto-char eos)
6770 (outline-next-heading)
6771 (if (outline-invisible-p) (org-flag-heading nil)))
6772 (setq org-cycle-subtree-status 'children)
6773 (unless (org-before-first-heading-p)
6774 (run-hook-with-args 'org-cycle-hook 'children)))
6775 ((or children-skipped
6776 (and (eq last-command this-command)
6777 (eq org-cycle-subtree-status 'children)))
6778 ;; We just showed the children, or no children are there,
6779 ;; now show everything.
6780 (unless (org-before-first-heading-p)
6781 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6782 (outline-flag-region eoh eos nil)
6783 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6784 (setq org-cycle-subtree-status 'subtree)
6785 (unless (org-before-first-heading-p)
6786 (run-hook-with-args 'org-cycle-hook 'subtree)))
6788 ;; Default action: hide the subtree.
6789 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6790 (outline-flag-region eoh eos t)
6791 (message "FOLDED")
6792 (setq org-cycle-subtree-status 'folded)
6793 (unless (org-before-first-heading-p)
6794 (run-hook-with-args 'org-cycle-hook 'folded))))))
6796 ;;;###autoload
6797 (defun org-global-cycle (&optional arg)
6798 "Cycle the global visibility. For details see `org-cycle'.
6799 With \\[universal-argument] prefix arg, switch to startup visibility.
6800 With a numeric prefix, show all headlines up to that level."
6801 (interactive "P")
6802 (let ((org-cycle-include-plain-lists
6803 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6804 (cond
6805 ((integerp arg)
6806 (show-all)
6807 (hide-sublevels arg)
6808 (setq org-cycle-global-status 'contents))
6809 ((equal arg '(4))
6810 (org-set-startup-visibility)
6811 (message "Startup visibility, plus VISIBILITY properties."))
6813 (org-cycle '(4))))))
6815 (defun org-set-startup-visibility ()
6816 "Set the visibility required by startup options and properties."
6817 (cond
6818 ((eq org-startup-folded t)
6819 (org-cycle '(4)))
6820 ((eq org-startup-folded 'content)
6821 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6822 (org-cycle '(4)) (org-cycle '(4)))))
6823 (unless (eq org-startup-folded 'showeverything)
6824 (if org-hide-block-startup (org-hide-block-all))
6825 (org-set-visibility-according-to-property 'no-cleanup)
6826 (org-cycle-hide-archived-subtrees 'all)
6827 (org-cycle-hide-drawers 'all)
6828 (org-cycle-show-empty-lines t)))
6830 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6831 "Switch subtree visibilities according to :VISIBILITY: property."
6832 (interactive)
6833 (let (org-show-entry-below state)
6834 (save-excursion
6835 (goto-char (point-min))
6836 (while (re-search-forward
6837 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6838 nil t)
6839 (setq state (match-string 1))
6840 (save-excursion
6841 (org-back-to-heading t)
6842 (hide-subtree)
6843 (org-reveal)
6844 (cond
6845 ((equal state '("fold" "folded"))
6846 (hide-subtree))
6847 ((equal state "children")
6848 (org-show-hidden-entry)
6849 (show-children))
6850 ((equal state "content")
6851 (save-excursion
6852 (save-restriction
6853 (org-narrow-to-subtree)
6854 (org-content))))
6855 ((member state '("all" "showall"))
6856 (show-subtree)))))
6857 (unless no-cleanup
6858 (org-cycle-hide-archived-subtrees 'all)
6859 (org-cycle-hide-drawers 'all)
6860 (org-cycle-show-empty-lines 'all)))))
6862 ;; This function uses outline-regexp instead of the more fundamental
6863 ;; org-outline-regexp so that org-cycle-global works outside of Org
6864 ;; buffers, where outline-regexp is needed.
6865 (defun org-overview ()
6866 "Switch to overview mode, showing only top-level headlines.
6867 Really, this shows all headlines with level equal or greater than the level
6868 of the first headline in the buffer. This is important, because if the
6869 first headline is not level one, then (hide-sublevels 1) gives confusing
6870 results."
6871 (interactive)
6872 (let ((l (org-current-line))
6873 (level (save-excursion
6874 (goto-char (point-min))
6875 (if (re-search-forward (concat "^" outline-regexp) nil t)
6876 (progn
6877 (goto-char (match-beginning 0))
6878 (funcall outline-level))))))
6879 (and level (hide-sublevels level))
6880 (recenter '(4))
6881 (org-goto-line l)))
6883 (defun org-content (&optional arg)
6884 "Show all headlines in the buffer, like a table of contents.
6885 With numerical argument N, show content up to level N."
6886 (interactive "P")
6887 (save-excursion
6888 ;; Visit all headings and show their offspring
6889 (and (integerp arg) (org-overview))
6890 (goto-char (point-max))
6891 (catch 'exit
6892 (while (and (progn (condition-case nil
6893 (outline-previous-visible-heading 1)
6894 (error (goto-char (point-min))))
6896 (looking-at org-outline-regexp))
6897 (if (integerp arg)
6898 (show-children (1- arg))
6899 (show-branches))
6900 (if (bobp) (throw 'exit nil))))))
6903 (defun org-optimize-window-after-visibility-change (state)
6904 "Adjust the window after a change in outline visibility.
6905 This function is the default value of the hook `org-cycle-hook'."
6906 (when (get-buffer-window (current-buffer))
6907 (cond
6908 ((eq state 'content) nil)
6909 ((eq state 'all) nil)
6910 ((eq state 'folded) nil)
6911 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6912 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6914 (defun org-remove-empty-overlays-at (pos)
6915 "Remove outline overlays that do not contain non-white stuff."
6916 (mapc
6917 (lambda (o)
6918 (and (eq 'outline (overlay-get o 'invisible))
6919 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6920 (overlay-end o))))
6921 (delete-overlay o)))
6922 (overlays-at pos)))
6924 (defun org-clean-visibility-after-subtree-move ()
6925 "Fix visibility issues after moving a subtree."
6926 ;; First, find a reasonable region to look at:
6927 ;; Start two siblings above, end three below
6928 (let* ((beg (save-excursion
6929 (and (org-get-last-sibling)
6930 (org-get-last-sibling))
6931 (point)))
6932 (end (save-excursion
6933 (and (org-get-next-sibling)
6934 (org-get-next-sibling)
6935 (org-get-next-sibling))
6936 (if (org-at-heading-p)
6937 (point-at-eol)
6938 (point))))
6939 (level (looking-at "\\*+"))
6940 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6941 (save-excursion
6942 (save-restriction
6943 (narrow-to-region beg end)
6944 (when re
6945 ;; Properly fold already folded siblings
6946 (goto-char (point-min))
6947 (while (re-search-forward re nil t)
6948 (if (and (not (outline-invisible-p))
6949 (save-excursion
6950 (goto-char (point-at-eol)) (outline-invisible-p)))
6951 (hide-entry))))
6952 (org-cycle-show-empty-lines 'overview)
6953 (org-cycle-hide-drawers 'overview)))))
6955 (defun org-cycle-show-empty-lines (state)
6956 "Show empty lines above all visible headlines.
6957 The region to be covered depends on STATE when called through
6958 `org-cycle-hook'. Lisp program can use t for STATE to get the
6959 entire buffer covered. Note that an empty line is only shown if there
6960 are at least `org-cycle-separator-lines' empty lines before the headline."
6961 (when (not (= org-cycle-separator-lines 0))
6962 (save-excursion
6963 (let* ((n (abs org-cycle-separator-lines))
6964 (re (cond
6965 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6966 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6967 (t (let ((ns (number-to-string (- n 2))))
6968 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6969 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6970 beg end b e)
6971 (cond
6972 ((memq state '(overview contents t))
6973 (setq beg (point-min) end (point-max)))
6974 ((memq state '(children folded))
6975 (setq beg (point) end (progn (org-end-of-subtree t t)
6976 (beginning-of-line 2)
6977 (point)))))
6978 (when beg
6979 (goto-char beg)
6980 (while (re-search-forward re end t)
6981 (unless (get-char-property (match-end 1) 'invisible)
6982 (setq e (match-end 1))
6983 (if (< org-cycle-separator-lines 0)
6984 (setq b (save-excursion
6985 (goto-char (match-beginning 0))
6986 (org-back-over-empty-lines)
6987 (if (save-excursion
6988 (goto-char (max (point-min) (1- (point))))
6989 (org-at-heading-p))
6990 (1- (point))
6991 (point))))
6992 (setq b (match-beginning 1)))
6993 (outline-flag-region b e nil)))))))
6994 ;; Never hide empty lines at the end of the file.
6995 (save-excursion
6996 (goto-char (point-max))
6997 (outline-previous-heading)
6998 (outline-end-of-heading)
6999 (if (and (looking-at "[ \t\n]+")
7000 (= (match-end 0) (point-max)))
7001 (outline-flag-region (point) (match-end 0) nil))))
7003 (defun org-show-empty-lines-in-parent ()
7004 "Move to the parent and re-show empty lines before visible headlines."
7005 (save-excursion
7006 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7007 (org-cycle-show-empty-lines context))))
7009 (defun org-files-list ()
7010 "Return `org-agenda-files' list, plus all open org-mode files.
7011 This is useful for operations that need to scan all of a user's
7012 open and agenda-wise Org files."
7013 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7014 (dolist (buf (buffer-list))
7015 (with-current-buffer buf
7016 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7017 (let ((file (expand-file-name (buffer-file-name))))
7018 (unless (member file files)
7019 (push file files))))))
7020 files))
7022 (defsubst org-entry-beginning-position ()
7023 "Return the beginning position of the current entry."
7024 (save-excursion (outline-back-to-heading t) (point)))
7026 (defsubst org-entry-end-position ()
7027 "Return the end position of the current entry."
7028 (save-excursion (outline-next-heading) (point)))
7030 (defun org-cycle-hide-drawers (state)
7031 "Re-hide all drawers after a visibility state change."
7032 (when (and (derived-mode-p 'org-mode)
7033 (not (memq state '(overview folded contents))))
7034 (save-excursion
7035 (let* ((globalp (memq state '(contents all)))
7036 (beg (if globalp (point-min) (point)))
7037 (end (if globalp (point-max)
7038 (if (eq state 'children)
7039 (save-excursion (outline-next-heading) (point))
7040 (org-end-of-subtree t)))))
7041 (goto-char beg)
7042 (while (re-search-forward org-drawer-regexp end t)
7043 (org-flag-drawer t))))))
7045 (defun org-cycle-hide-inline-tasks (state)
7046 "Re-hide inline task when switching to 'contents visibility state."
7047 (when (and (eq state 'contents)
7048 (boundp 'org-inlinetask-min-level)
7049 org-inlinetask-min-level)
7050 (hide-sublevels (1- org-inlinetask-min-level))))
7052 (defun org-flag-drawer (flag)
7053 "When FLAG is non-nil, hide the drawer we are within.
7054 Otherwise make it visible."
7055 (save-excursion
7056 (beginning-of-line 1)
7057 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7058 (let ((b (match-end 0)))
7059 (if (re-search-forward
7060 "^[ \t]*:END:"
7061 (save-excursion (outline-next-heading) (point)) t)
7062 (outline-flag-region b (point-at-eol) flag)
7063 (user-error ":END: line missing at position %s" b))))))
7065 (defun org-subtree-end-visible-p ()
7066 "Is the end of the current subtree visible?"
7067 (pos-visible-in-window-p
7068 (save-excursion (org-end-of-subtree t) (point))))
7070 (defun org-first-headline-recenter (&optional N)
7071 "Move cursor to the first headline and recenter the headline.
7072 Optional argument N means put the headline into the Nth line of the window."
7073 (goto-char (point-min))
7074 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7075 (beginning-of-line)
7076 (recenter (prefix-numeric-value N))))
7078 ;;; Saving and restoring visibility
7080 (defun org-outline-overlay-data (&optional use-markers)
7081 "Return a list of the locations of all outline overlays.
7082 These are overlays with the `invisible' property value `outline'.
7083 The return value is a list of cons cells, with start and stop
7084 positions for each overlay.
7085 If USE-MARKERS is set, return the positions as markers."
7086 (let (beg end)
7087 (save-excursion
7088 (save-restriction
7089 (widen)
7090 (delq nil
7091 (mapcar (lambda (o)
7092 (when (eq (overlay-get o 'invisible) 'outline)
7093 (setq beg (overlay-start o)
7094 end (overlay-end o))
7095 (and beg end (> end beg)
7096 (if use-markers
7097 (cons (move-marker (make-marker) beg)
7098 (move-marker (make-marker) end))
7099 (cons beg end)))))
7100 (overlays-in (point-min) (point-max))))))))
7102 (defun org-set-outline-overlay-data (data)
7103 "Create visibility overlays for all positions in DATA.
7104 DATA should have been made by `org-outline-overlay-data'."
7105 (let (o)
7106 (save-excursion
7107 (save-restriction
7108 (widen)
7109 (show-all)
7110 (mapc (lambda (c)
7111 (outline-flag-region (car c) (cdr c) t))
7112 data)))))
7114 ;;; Folding of blocks
7116 (defvar org-hide-block-overlays nil
7117 "Overlays hiding blocks.")
7118 (make-variable-buffer-local 'org-hide-block-overlays)
7120 (defun org-block-map (function &optional start end)
7121 "Call FUNCTION at the head of all source blocks in the current buffer.
7122 Optional arguments START and END can be used to limit the range."
7123 (let ((start (or start (point-min)))
7124 (end (or end (point-max))))
7125 (save-excursion
7126 (goto-char start)
7127 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7128 (save-excursion
7129 (save-match-data
7130 (goto-char (match-beginning 0))
7131 (funcall function)))))))
7133 (defun org-hide-block-toggle-all ()
7134 "Toggle the visibility of all blocks in the current buffer."
7135 (org-block-map #'org-hide-block-toggle))
7137 (defun org-hide-block-all ()
7138 "Fold all blocks in the current buffer."
7139 (interactive)
7140 (org-show-block-all)
7141 (org-block-map #'org-hide-block-toggle-maybe))
7143 (defun org-show-block-all ()
7144 "Unfold all blocks in the current buffer."
7145 (interactive)
7146 (mapc 'delete-overlay org-hide-block-overlays)
7147 (setq org-hide-block-overlays nil))
7149 (defun org-hide-block-toggle-maybe ()
7150 "Toggle visibility of block at point."
7151 (interactive)
7152 (let ((case-fold-search t))
7153 (if (save-excursion
7154 (beginning-of-line 1)
7155 (looking-at org-block-regexp))
7156 (progn (org-hide-block-toggle)
7157 t) ;; to signal that we took action
7158 nil))) ;; to signal that we did not
7160 (defun org-hide-block-toggle (&optional force)
7161 "Toggle the visibility of the current block."
7162 (interactive)
7163 (save-excursion
7164 (beginning-of-line)
7165 (if (re-search-forward org-block-regexp nil t)
7166 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7167 (end (match-end 0)) ;; end of entire body
7169 (if (memq t (mapcar (lambda (overlay)
7170 (eq (overlay-get overlay 'invisible)
7171 'org-hide-block))
7172 (overlays-at start)))
7173 (if (or (not force) (eq force 'off))
7174 (mapc (lambda (ov)
7175 (when (member ov org-hide-block-overlays)
7176 (setq org-hide-block-overlays
7177 (delq ov org-hide-block-overlays)))
7178 (when (eq (overlay-get ov 'invisible)
7179 'org-hide-block)
7180 (delete-overlay ov)))
7181 (overlays-at start)))
7182 (setq ov (make-overlay start end))
7183 (overlay-put ov 'invisible 'org-hide-block)
7184 ;; make the block accessible to isearch
7185 (overlay-put
7186 ov 'isearch-open-invisible
7187 (lambda (ov)
7188 (when (member ov org-hide-block-overlays)
7189 (setq org-hide-block-overlays
7190 (delq ov org-hide-block-overlays)))
7191 (when (eq (overlay-get ov 'invisible)
7192 'org-hide-block)
7193 (delete-overlay ov))))
7194 (push ov org-hide-block-overlays)))
7195 (user-error "Not looking at a source block"))))
7197 ;; org-tab-after-check-for-cycling-hook
7198 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7199 ;; Remove overlays when changing major mode
7200 (add-hook 'org-mode-hook
7201 (lambda () (org-add-hook 'change-major-mode-hook
7202 'org-show-block-all 'append 'local)))
7204 ;;; Org-goto
7206 (defvar org-goto-window-configuration nil)
7207 (defvar org-goto-marker nil)
7208 (defvar org-goto-map)
7209 (defun org-goto-map ()
7210 "Set the keymap `org-goto'."
7211 (setq org-goto-map
7212 (let ((map (make-sparse-keymap)))
7213 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7214 mouse-drag-region universal-argument org-occur))
7215 cmd)
7216 (while (setq cmd (pop cmds))
7217 (substitute-key-definition cmd cmd map global-map)))
7218 (suppress-keymap map)
7219 (org-defkey map "\C-m" 'org-goto-ret)
7220 (org-defkey map [(return)] 'org-goto-ret)
7221 (org-defkey map [(left)] 'org-goto-left)
7222 (org-defkey map [(right)] 'org-goto-right)
7223 (org-defkey map [(control ?g)] 'org-goto-quit)
7224 (org-defkey map "\C-i" 'org-cycle)
7225 (org-defkey map [(tab)] 'org-cycle)
7226 (org-defkey map [(down)] 'outline-next-visible-heading)
7227 (org-defkey map [(up)] 'outline-previous-visible-heading)
7228 (if org-goto-auto-isearch
7229 (if (fboundp 'define-key-after)
7230 (define-key-after map [t] 'org-goto-local-auto-isearch)
7231 nil)
7232 (org-defkey map "q" 'org-goto-quit)
7233 (org-defkey map "n" 'outline-next-visible-heading)
7234 (org-defkey map "p" 'outline-previous-visible-heading)
7235 (org-defkey map "f" 'outline-forward-same-level)
7236 (org-defkey map "b" 'outline-backward-same-level)
7237 (org-defkey map "u" 'outline-up-heading))
7238 (org-defkey map "/" 'org-occur)
7239 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7240 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7241 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7242 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7243 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7244 map)))
7246 (defconst org-goto-help
7247 "Browse buffer copy, to find location or copy text.%s
7248 RET=jump to location C-g=quit and return to previous location
7249 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7251 (defvar org-goto-start-pos) ; dynamically scoped parameter
7253 (defun org-goto (&optional alternative-interface)
7254 "Look up a different location in the current file, keeping current visibility.
7256 When you want look-up or go to a different location in a
7257 document, the fastest way is often to fold the entire buffer and
7258 then dive into the tree. This method has the disadvantage, that
7259 the previous location will be folded, which may not be what you
7260 want.
7262 This command works around this by showing a copy of the current
7263 buffer in an indirect buffer, in overview mode. You can dive
7264 into the tree in that copy, use org-occur and incremental search
7265 to find a location. When pressing RET or `Q', the command
7266 returns to the original buffer in which the visibility is still
7267 unchanged. After RET it will also jump to the location selected
7268 in the indirect buffer and expose the headline hierarchy above.
7270 With a prefix argument, use the alternative interface: e.g. if
7271 `org-goto-interface' is 'outline use 'outline-path-completion."
7272 (interactive "P")
7273 (org-goto-map)
7274 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7275 (org-refile-use-outline-path t)
7276 (org-refile-target-verify-function nil)
7277 (interface
7278 (if (not alternative-interface)
7279 org-goto-interface
7280 (if (eq org-goto-interface 'outline)
7281 'outline-path-completion
7282 'outline)))
7283 (org-goto-start-pos (point))
7284 (selected-point
7285 (if (eq interface 'outline)
7286 (car (org-get-location (current-buffer) org-goto-help))
7287 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7288 (org-refile-check-position pa)
7289 (nth 3 pa)))))
7290 (if selected-point
7291 (progn
7292 (org-mark-ring-push org-goto-start-pos)
7293 (goto-char selected-point)
7294 (if (or (outline-invisible-p) (org-invisible-p2))
7295 (org-show-context 'org-goto)))
7296 (message "Quit"))))
7298 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7299 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7300 (defvar org-goto-local-auto-isearch-map) ; defined below
7302 (defun org-get-location (buf help)
7303 "Let the user select a location in the Org-mode buffer BUF.
7304 This function uses a recursive edit. It returns the selected position
7305 or nil."
7306 (org-no-popups
7307 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7308 (isearch-hide-immediately nil)
7309 (isearch-search-fun-function
7310 (lambda () 'org-goto-local-search-headings))
7311 (org-goto-selected-point org-goto-exit-command))
7312 (save-excursion
7313 (save-window-excursion
7314 (delete-other-windows)
7315 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7316 (org-pop-to-buffer-same-window
7317 (condition-case nil
7318 (make-indirect-buffer (current-buffer) "*org-goto*")
7319 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7320 (with-output-to-temp-buffer "*Org Help*"
7321 (princ (format help (if org-goto-auto-isearch
7322 " Just type for auto-isearch."
7323 " n/p/f/b/u to navigate, q to quit."))))
7324 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7325 (setq buffer-read-only nil)
7326 (let ((org-startup-truncated t)
7327 (org-startup-folded nil)
7328 (org-startup-align-all-tables nil))
7329 (org-mode)
7330 (org-overview))
7331 (setq buffer-read-only t)
7332 (if (and (boundp 'org-goto-start-pos)
7333 (integer-or-marker-p org-goto-start-pos))
7334 (let ((org-show-hierarchy-above t)
7335 (org-show-siblings t)
7336 (org-show-following-heading t))
7337 (goto-char org-goto-start-pos)
7338 (and (outline-invisible-p) (org-show-context)))
7339 (goto-char (point-min)))
7340 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7341 (message "Select location and press RET")
7342 (use-local-map org-goto-map)
7343 (recursive-edit)))
7344 (kill-buffer "*org-goto*")
7345 (cons org-goto-selected-point org-goto-exit-command))))
7347 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7348 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7349 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7350 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7352 (defun org-goto-local-search-headings (string bound noerror)
7353 "Search and make sure that any matches are in headlines."
7354 (catch 'return
7355 (while (if isearch-forward
7356 (search-forward string bound noerror)
7357 (search-backward string bound noerror))
7358 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7359 (and (member :headline context)
7360 (not (member :tags context))))
7361 (throw 'return (point))))))
7363 (defun org-goto-local-auto-isearch ()
7364 "Start isearch."
7365 (interactive)
7366 (goto-char (point-min))
7367 (let ((keys (this-command-keys)))
7368 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7369 (isearch-mode t)
7370 (isearch-process-search-char (string-to-char keys)))))
7372 (defun org-goto-ret (&optional arg)
7373 "Finish `org-goto' by going to the new location."
7374 (interactive "P")
7375 (setq org-goto-selected-point (point)
7376 org-goto-exit-command 'return)
7377 (throw 'exit nil))
7379 (defun org-goto-left ()
7380 "Finish `org-goto' by going to the new location."
7381 (interactive)
7382 (if (org-at-heading-p)
7383 (progn
7384 (beginning-of-line 1)
7385 (setq org-goto-selected-point (point)
7386 org-goto-exit-command 'left)
7387 (throw 'exit nil))
7388 (user-error "Not on a heading")))
7390 (defun org-goto-right ()
7391 "Finish `org-goto' by going to the new location."
7392 (interactive)
7393 (if (org-at-heading-p)
7394 (progn
7395 (setq org-goto-selected-point (point)
7396 org-goto-exit-command 'right)
7397 (throw 'exit nil))
7398 (user-error "Not on a heading")))
7400 (defun org-goto-quit ()
7401 "Finish `org-goto' without cursor motion."
7402 (interactive)
7403 (setq org-goto-selected-point nil)
7404 (setq org-goto-exit-command 'quit)
7405 (throw 'exit nil))
7407 ;;; Indirect buffer display of subtrees
7409 (defvar org-indirect-dedicated-frame nil
7410 "This is the frame being used for indirect tree display.")
7411 (defvar org-last-indirect-buffer nil)
7413 (defun org-tree-to-indirect-buffer (&optional arg)
7414 "Create indirect buffer and narrow it to current subtree.
7415 With a numerical prefix ARG, go up to this level and then take that tree.
7416 If ARG is negative, go up that many levels.
7418 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7419 indirect buffer previously made with this command, to avoid proliferation of
7420 indirect buffers. However, when you call the command with a \
7421 \\[universal-argument] prefix, or
7422 when `org-indirect-buffer-display' is `new-frame', the last buffer
7423 is kept so that you can work with several indirect buffers at the same time.
7424 If `org-indirect-buffer-display' is `dedicated-frame', the \
7425 \\[universal-argument] prefix also
7426 requests that a new frame be made for the new buffer, so that the dedicated
7427 frame is not changed."
7428 (interactive "P")
7429 (let ((cbuf (current-buffer))
7430 (cwin (selected-window))
7431 (pos (point))
7432 beg end level heading ibuf)
7433 (save-excursion
7434 (org-back-to-heading t)
7435 (when (numberp arg)
7436 (setq level (org-outline-level))
7437 (if (< arg 0) (setq arg (+ level arg)))
7438 (while (> (setq level (org-outline-level)) arg)
7439 (org-up-heading-safe)))
7440 (setq beg (point)
7441 heading (org-get-heading))
7442 (org-end-of-subtree t t)
7443 (if (org-at-heading-p) (backward-char 1))
7444 (setq end (point)))
7445 (if (and (buffer-live-p org-last-indirect-buffer)
7446 (not (eq org-indirect-buffer-display 'new-frame))
7447 (not arg))
7448 (kill-buffer org-last-indirect-buffer))
7449 (setq ibuf (org-get-indirect-buffer cbuf)
7450 org-last-indirect-buffer ibuf)
7451 (cond
7452 ((or (eq org-indirect-buffer-display 'new-frame)
7453 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7454 (select-frame (make-frame))
7455 (delete-other-windows)
7456 (org-pop-to-buffer-same-window ibuf)
7457 (org-set-frame-title heading))
7458 ((eq org-indirect-buffer-display 'dedicated-frame)
7459 (raise-frame
7460 (select-frame (or (and org-indirect-dedicated-frame
7461 (frame-live-p org-indirect-dedicated-frame)
7462 org-indirect-dedicated-frame)
7463 (setq org-indirect-dedicated-frame (make-frame)))))
7464 (delete-other-windows)
7465 (org-pop-to-buffer-same-window ibuf)
7466 (org-set-frame-title (concat "Indirect: " heading)))
7467 ((eq org-indirect-buffer-display 'current-window)
7468 (org-pop-to-buffer-same-window ibuf))
7469 ((eq org-indirect-buffer-display 'other-window)
7470 (pop-to-buffer ibuf))
7471 (t (error "Invalid value")))
7472 (if (featurep 'xemacs)
7473 (save-excursion (org-mode) (turn-on-font-lock)))
7474 (narrow-to-region beg end)
7475 (show-all)
7476 (goto-char pos)
7477 (run-hook-with-args 'org-cycle-hook 'all)
7478 (and (window-live-p cwin) (select-window cwin))))
7480 (defun org-get-indirect-buffer (&optional buffer)
7481 (setq buffer (or buffer (current-buffer)))
7482 (let ((n 1) (base (buffer-name buffer)) bname)
7483 (while (buffer-live-p
7484 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7485 (setq n (1+ n)))
7486 (condition-case nil
7487 (make-indirect-buffer buffer bname 'clone)
7488 (error (make-indirect-buffer buffer bname)))))
7490 (defun org-set-frame-title (title)
7491 "Set the title of the current frame to the string TITLE."
7492 ;; FIXME: how to name a single frame in XEmacs???
7493 (unless (featurep 'xemacs)
7494 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7496 ;;;; Structure editing
7498 ;;; Inserting headlines
7500 (defun org-previous-line-empty-p (&optional next)
7501 "Is the previous line a blank line?
7502 When NEXT is non-nil, check the next line instead."
7503 (save-excursion
7504 (and (not (bobp))
7505 (or (beginning-of-line (if next 2 0)) t)
7506 (save-match-data
7507 (looking-at "[ \t]*$")))))
7509 (defun org-insert-heading (&optional arg invisible-ok)
7510 "Insert a new heading or item with same depth at point.
7511 If point is in a plain list and ARG is nil, create a new list item.
7512 With one universal prefix argument, insert a heading even in lists.
7513 With two universal prefix arguments, insert the heading at the end
7514 of the parent subtree.
7516 If point is at the beginning of a headline, insert a sibling before
7517 the current headline. If point is not at the beginning, split the line
7518 and create a new headline with the text in the current line after point
7519 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7521 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7522 This is important for non-interactive uses of the command."
7523 (interactive "P")
7524 (if (org-called-interactively-p 'any) (org-reveal))
7525 (let ((itemp (org-in-item-p)))
7526 (cond
7527 ((or (= (buffer-size) 0)
7528 (and (not (save-excursion
7529 (and (ignore-errors (org-back-to-heading invisible-ok))
7530 (org-at-heading-p))))
7531 (or arg (not itemp))))
7532 (insert
7533 (if (org-previous-line-empty-p) "" "\n")
7534 (if (org-in-src-block-p) ",* " "* "))
7535 (run-hooks 'org-insert-heading-hook))
7536 ((or arg
7537 (and (not itemp) org-insert-heading-respect-content)
7538 (not (org-insert-item
7539 (save-excursion
7540 (and itemp
7541 (goto-char itemp)
7542 (looking-at org-list-full-item-re)
7543 (match-string 3))))))
7544 (let (begn endn)
7545 (when (org-buffer-narrowed-p)
7546 (setq begn (point-min) endn (point-max))
7547 (widen))
7548 (let* ((empty-line-p nil)
7549 (eops (equal arg '(16))) ; insert at end of parent subtree
7550 (org-insert-heading-respect-content
7551 (or (not (null arg)) org-insert-heading-respect-content))
7552 (level nil)
7553 (on-heading (org-at-heading-p))
7554 ;; Get a level to fall back on
7555 (fix-level
7556 (save-excursion
7557 (org-back-to-heading t)
7558 (looking-at org-outline-regexp)
7559 (make-string (1- (length (match-string 0))) ?*)))
7560 (on-empty-line
7561 (save-excursion (beginning-of-line 1) (looking-at "^\\s-*$")))
7562 (head (save-excursion
7563 (condition-case nil
7564 (progn
7565 (org-back-to-heading invisible-ok)
7566 (when (and (not on-heading)
7567 (featurep 'org-inlinetask)
7568 (integerp org-inlinetask-min-level)
7569 (>= (length (match-string 0))
7570 org-inlinetask-min-level))
7571 ;; Find a heading level before the inline task
7572 (while (and (setq level (org-up-heading-safe))
7573 (>= level org-inlinetask-min-level)))
7574 (if (org-at-heading-p)
7575 (org-back-to-heading invisible-ok)
7576 (error "This should not happen")))
7577 (unless (and (save-excursion
7578 (save-match-data
7579 (org-backward-heading-same-level 1 invisible-ok))
7580 (= (point) (match-beginning 0)))
7581 (not (org-previous-line-empty-p t)))
7582 (setq empty-line-p (org-previous-line-empty-p)))
7583 (match-string 0))
7584 (error (or fix-level "* ")))))
7585 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7586 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7587 pos hide-previous previous-pos)
7588 (if ;; At the beginning of a heading, open a new line for insertion
7589 (and (bolp) (org-at-heading-p)
7590 (not eops)
7591 (or (bobp)
7592 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7593 (open-line (if blank 2 1))
7594 (save-excursion
7595 (setq previous-pos (point-at-bol))
7596 (end-of-line)
7597 (setq hide-previous (outline-invisible-p)))
7598 (and org-insert-heading-respect-content
7599 (save-excursion
7600 (while (outline-invisible-p)
7601 (org-show-subtree)
7602 (org-up-heading-safe))))
7603 (let ((split
7604 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7605 (save-excursion
7606 (let ((p (point)))
7607 (goto-char (point-at-bol))
7608 (and (looking-at org-complex-heading-regexp)
7609 (match-beginning 4)
7610 (> p (match-beginning 4)))))))
7611 tags pos)
7612 (cond
7613 ;; Insert a new line, possibly at end of parent subtree
7614 ((and (not arg) (not on-heading) (not on-empty-line)
7615 (not (save-excursion
7616 (beginning-of-line 1)
7617 (or (looking-at org-list-full-item-re)
7618 ;; Don't convert :end: lines to headline
7619 (looking-at "^\\s-*:end:")
7620 (looking-at "^\\s-*#\\+end_?")))))
7621 (beginning-of-line 1))
7622 (org-insert-heading-respect-content
7623 (if (not eops)
7624 (progn
7625 (org-end-of-subtree nil t)
7626 (and (looking-at "^\\*") (backward-char 1))
7627 (while (and (not (bobp))
7628 ;; Don't delete spaces in empty headlines
7629 (not (looking-back org-outline-regexp))
7630 (member (char-before) '(?\ ?\t ?\n)))
7631 (backward-delete-char 1)))
7632 (let ((p (point)))
7633 (org-up-heading-safe)
7634 (if (= p (point))
7635 (goto-char (point-max))
7636 (org-end-of-subtree nil t))))
7637 (when (featurep 'org-inlinetask)
7638 (while (and (not (eobp))
7639 (looking-at "\\(\\*+\\)[ \t]+")
7640 (>= (length (match-string 1))
7641 org-inlinetask-min-level))
7642 (org-end-of-subtree nil t)))
7643 (or (bolp) (newline))
7644 (or (org-previous-line-empty-p)
7645 (and blank (newline)))
7646 (if (or empty-line-p eops) (open-line 1)))
7647 ;; Insert a headling containing text after point
7648 ((org-at-heading-p)
7649 (when hide-previous
7650 (show-children)
7651 (org-show-entry))
7652 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7653 (setq tags (and (match-end 2) (match-string 2)))
7654 (and (match-end 1)
7655 (delete-region (match-beginning 1) (match-end 1)))
7656 (setq pos (point-at-bol))
7657 (or split (end-of-line 1))
7658 (delete-horizontal-space)
7659 (if (string-match "\\`\\*+\\'"
7660 (buffer-substring (point-at-bol) (point)))
7661 (insert " "))
7662 (newline (if blank 2 1))
7663 (when tags
7664 (save-excursion
7665 (goto-char pos)
7666 (end-of-line 1)
7667 (insert " " tags)
7668 (org-set-tags nil 'align))))
7670 (or split (end-of-line 1))
7671 (newline (cond ((and blank (not on-empty-line)) 2)
7672 (blank 1)
7673 (on-empty-line 0) (t 1)))))))
7674 (insert head) (just-one-space)
7675 (setq pos (point))
7676 (end-of-line 1)
7677 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7678 (when (and org-insert-heading-respect-content hide-previous)
7679 (save-excursion
7680 (goto-char previous-pos)
7681 (hide-subtree)))
7682 (when (and begn endn)
7683 (narrow-to-region (min (point) begn) (max (point) endn)))
7684 (run-hooks 'org-insert-heading-hook)))))))
7686 (defun org-get-heading (&optional no-tags no-todo)
7687 "Return the heading of the current entry, without the stars.
7688 When NO-TAGS is non-nil, don't include tags.
7689 When NO-TODO is non-nil, don't include TODO keywords."
7690 (save-excursion
7691 (org-back-to-heading t)
7692 (cond
7693 ((and no-tags no-todo)
7694 (looking-at org-complex-heading-regexp)
7695 (match-string 4))
7696 (no-tags
7697 (looking-at (concat org-outline-regexp
7698 "\\(.*?\\)"
7699 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7700 (match-string 1))
7701 (no-todo
7702 (looking-at org-todo-line-regexp)
7703 (match-string 3))
7704 (t (looking-at org-heading-regexp)
7705 (match-string 2)))))
7707 (defvar orgstruct-mode) ; defined below
7709 (defun org-heading-components ()
7710 "Return the components of the current heading.
7711 This is a list with the following elements:
7712 - the level as an integer
7713 - the reduced level, different if `org-odd-levels-only' is set.
7714 - the TODO keyword, or nil
7715 - the priority character, like ?A, or nil if no priority is given
7716 - the headline text itself, or the tags string if no headline text
7717 - the tags string, or nil."
7718 (save-excursion
7719 (org-back-to-heading t)
7720 (if (let (case-fold-search)
7721 (looking-at
7722 (if orgstruct-mode
7723 org-heading-regexp
7724 org-complex-heading-regexp)))
7725 (if orgstruct-mode
7726 (list (length (match-string 1))
7727 (org-reduced-level (length (match-string 1)))
7730 (match-string 2)
7731 nil)
7732 (list (length (match-string 1))
7733 (org-reduced-level (length (match-string 1)))
7734 (org-match-string-no-properties 2)
7735 (and (match-end 3) (aref (match-string 3) 2))
7736 (org-match-string-no-properties 4)
7737 (org-match-string-no-properties 5))))))
7739 (defun org-get-entry ()
7740 "Get the entry text, after heading, entire subtree."
7741 (save-excursion
7742 (org-back-to-heading t)
7743 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7745 (defun org-insert-heading-after-current ()
7746 "Insert a new heading with same level as current, after current subtree."
7747 (interactive)
7748 (org-back-to-heading)
7749 (org-insert-heading)
7750 (org-move-subtree-down)
7751 (end-of-line 1))
7753 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7754 "Insert heading with `org-insert-heading-respect-content' set to t."
7755 (interactive "P")
7756 (let ((org-insert-heading-respect-content t))
7757 (org-insert-heading arg invisible-ok)))
7759 (defun org-insert-todo-heading-respect-content (&optional force-state)
7760 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7761 (interactive "P")
7762 (let ((org-insert-heading-respect-content t))
7763 (org-insert-todo-heading force-state t)))
7765 (defun org-insert-todo-heading (arg &optional force-heading)
7766 "Insert a new heading with the same level and TODO state as current heading.
7767 If the heading has no TODO state, or if the state is DONE, use the first
7768 state (TODO by default). Also one prefix arg, force first state. With two
7769 prefix args, force inserting at the end of the parent subtree."
7770 (interactive "P")
7771 (when (or force-heading (not (org-insert-item 'checkbox)))
7772 (org-insert-heading (or (and (equal arg '(16)) '(16))
7773 force-heading))
7774 (save-excursion
7775 (org-back-to-heading)
7776 (outline-previous-heading)
7777 (looking-at org-todo-line-regexp))
7778 (let*
7779 ((new-mark-x
7780 (if (or arg
7781 (not (match-beginning 2))
7782 (member (match-string 2) org-done-keywords))
7783 (car org-todo-keywords-1)
7784 (match-string 2)))
7785 (new-mark
7787 (run-hook-with-args-until-success
7788 'org-todo-get-default-hook new-mark-x nil)
7789 new-mark-x)))
7790 (beginning-of-line 1)
7791 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7792 (if org-treat-insert-todo-heading-as-state-change
7793 (org-todo new-mark)
7794 (insert new-mark " "))))
7795 (when org-provide-todo-statistics
7796 (org-update-parent-todo-statistics))))
7798 (defun org-insert-subheading (arg)
7799 "Insert a new subheading and demote it.
7800 Works for outline headings and for plain lists alike."
7801 (interactive "P")
7802 (org-insert-heading arg)
7803 (cond
7804 ((org-at-heading-p) (org-do-demote))
7805 ((org-at-item-p) (org-indent-item))))
7807 (defun org-insert-todo-subheading (arg)
7808 "Insert a new subheading with TODO keyword or checkbox and demote it.
7809 Works for outline headings and for plain lists alike."
7810 (interactive "P")
7811 (org-insert-todo-heading arg)
7812 (cond
7813 ((org-at-heading-p) (org-do-demote))
7814 ((org-at-item-p) (org-indent-item))))
7816 ;;; Promotion and Demotion
7818 (defvar org-after-demote-entry-hook nil
7819 "Hook run after an entry has been demoted.
7820 The cursor will be at the beginning of the entry.
7821 When a subtree is being demoted, the hook will be called for each node.")
7823 (defvar org-after-promote-entry-hook nil
7824 "Hook run after an entry has been promoted.
7825 The cursor will be at the beginning of the entry.
7826 When a subtree is being promoted, the hook will be called for each node.")
7828 (defun org-promote-subtree ()
7829 "Promote the entire subtree.
7830 See also `org-promote'."
7831 (interactive)
7832 (save-excursion
7833 (org-with-limited-levels (org-map-tree 'org-promote)))
7834 (org-fix-position-after-promote))
7836 (defun org-demote-subtree ()
7837 "Demote the entire subtree. See `org-demote'.
7838 See also `org-promote'."
7839 (interactive)
7840 (save-excursion
7841 (org-with-limited-levels (org-map-tree 'org-demote)))
7842 (org-fix-position-after-promote))
7845 (defun org-do-promote ()
7846 "Promote the current heading higher up the tree.
7847 If the region is active in `transient-mark-mode', promote all headings
7848 in the region."
7849 (interactive)
7850 (save-excursion
7851 (if (org-region-active-p)
7852 (org-map-region 'org-promote (region-beginning) (region-end))
7853 (org-promote)))
7854 (org-fix-position-after-promote))
7856 (defun org-do-demote ()
7857 "Demote the current heading lower down the tree.
7858 If the region is active in `transient-mark-mode', demote all headings
7859 in the region."
7860 (interactive)
7861 (save-excursion
7862 (if (org-region-active-p)
7863 (org-map-region 'org-demote (region-beginning) (region-end))
7864 (org-demote)))
7865 (org-fix-position-after-promote))
7867 (defun org-fix-position-after-promote ()
7868 "Make sure that after pro/demotion cursor position is right."
7869 (let ((pos (point)))
7870 (when (save-excursion
7871 (beginning-of-line 1)
7872 (looking-at org-todo-line-regexp)
7873 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7874 (cond ((eobp) (insert " "))
7875 ((eolp) (insert " "))
7876 ((equal (char-after) ?\ ) (forward-char 1))))))
7878 (defun org-current-level ()
7879 "Return the level of the current entry, or nil if before the first headline.
7880 The level is the number of stars at the beginning of the headline."
7881 (save-excursion
7882 (org-with-limited-levels
7883 (if (ignore-errors (org-back-to-heading t))
7884 (funcall outline-level)))))
7886 (defun org-get-previous-line-level ()
7887 "Return the outline depth of the last headline before the current line.
7888 Returns 0 for the first headline in the buffer, and nil if before the
7889 first headline."
7890 (let ((current-level (org-current-level))
7891 (prev-level (when (> (line-number-at-pos) 1)
7892 (save-excursion
7893 (beginning-of-line 0)
7894 (org-current-level)))))
7895 (cond ((null current-level) nil) ; Before first headline
7896 ((null prev-level) 0) ; At first headline
7897 (prev-level))))
7899 (defun org-reduced-level (l)
7900 "Compute the effective level of a heading.
7901 This takes into account the setting of `org-odd-levels-only'."
7902 (cond
7903 ((zerop l) 0)
7904 (org-odd-levels-only (1+ (floor (/ l 2))))
7905 (t l)))
7907 (defun org-level-increment ()
7908 "Return the number of stars that will be added or removed at a
7909 time to headlines when structure editing, based on the value of
7910 `org-odd-levels-only'."
7911 (if org-odd-levels-only 2 1))
7913 (defun org-get-valid-level (level &optional change)
7914 "Rectify a level change under the influence of `org-odd-levels-only'
7915 LEVEL is a current level, CHANGE is by how much the level should be
7916 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7917 even level numbers will become the next higher odd number."
7918 (if org-odd-levels-only
7919 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7920 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7921 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7922 (max 1 (+ level (or change 0)))))
7924 (if (boundp 'define-obsolete-function-alias)
7925 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7926 (define-obsolete-function-alias 'org-get-legal-level
7927 'org-get-valid-level)
7928 (define-obsolete-function-alias 'org-get-legal-level
7929 'org-get-valid-level "23.1")))
7931 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7932 ;; ̀org-with-limited-levels'
7933 (defun org-promote ()
7934 "Promote the current heading higher up the tree.
7935 If the region is active in `transient-mark-mode', promote all headings
7936 in the region."
7937 (org-back-to-heading t)
7938 (let* ((level (save-match-data (funcall outline-level)))
7939 (after-change-functions (remove 'flyspell-after-change-function
7940 after-change-functions))
7941 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7942 (diff (abs (- level (length up-head) -1))))
7943 (cond ((and (= level 1) org-called-with-limited-levels
7944 org-allow-promoting-top-level-subtree)
7945 (replace-match "# " nil t))
7946 ((= level 1)
7947 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7948 (t (replace-match up-head nil t)))
7949 ;; Fixup tag positioning
7950 (unless (= level 1)
7951 (and org-auto-align-tags (org-set-tags nil t))
7952 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7953 (run-hooks 'org-after-promote-entry-hook)))
7955 (defun org-demote ()
7956 "Demote the current heading lower down the tree.
7957 If the region is active in `transient-mark-mode', demote all headings
7958 in the region."
7959 (org-back-to-heading t)
7960 (let* ((level (save-match-data (funcall outline-level)))
7961 (after-change-functions (remove 'flyspell-after-change-function
7962 after-change-functions))
7963 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7964 (diff (abs (- level (length down-head) -1))))
7965 (replace-match down-head nil t)
7966 ;; Fixup tag positioning
7967 (and org-auto-align-tags (org-set-tags nil t))
7968 (if org-adapt-indentation (org-fixup-indentation diff))
7969 (run-hooks 'org-after-demote-entry-hook)))
7971 (defun org-cycle-level ()
7972 "Cycle the level of an empty headline through possible states.
7973 This goes first to child, then to parent, level, then up the hierarchy.
7974 After top level, it switches back to sibling level."
7975 (interactive)
7976 (let ((org-adapt-indentation nil))
7977 (when (org-point-at-end-of-empty-headline)
7978 (setq this-command 'org-cycle-level) ; Only needed for caching
7979 (let ((cur-level (org-current-level))
7980 (prev-level (org-get-previous-line-level)))
7981 (cond
7982 ;; If first headline in file, promote to top-level.
7983 ((= prev-level 0)
7984 (loop repeat (/ (- cur-level 1) (org-level-increment))
7985 do (org-do-promote)))
7986 ;; If same level as prev, demote one.
7987 ((= prev-level cur-level)
7988 (org-do-demote))
7989 ;; If parent is top-level, promote to top level if not already.
7990 ((= prev-level 1)
7991 (loop repeat (/ (- cur-level 1) (org-level-increment))
7992 do (org-do-promote)))
7993 ;; If top-level, return to prev-level.
7994 ((= cur-level 1)
7995 (loop repeat (/ (- prev-level 1) (org-level-increment))
7996 do (org-do-demote)))
7997 ;; If less than prev-level, promote one.
7998 ((< cur-level prev-level)
7999 (org-do-promote))
8000 ;; If deeper than prev-level, promote until higher than
8001 ;; prev-level.
8002 ((> cur-level prev-level)
8003 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8004 do (org-do-promote))))
8005 t))))
8007 (defun org-map-tree (fun)
8008 "Call FUN for every heading underneath the current one."
8009 (org-back-to-heading)
8010 (let ((level (funcall outline-level)))
8011 (save-excursion
8012 (funcall fun)
8013 (while (and (progn
8014 (outline-next-heading)
8015 (> (funcall outline-level) level))
8016 (not (eobp)))
8017 (funcall fun)))))
8019 (defun org-map-region (fun beg end)
8020 "Call FUN for every heading between BEG and END."
8021 (let ((org-ignore-region t))
8022 (save-excursion
8023 (setq end (copy-marker end))
8024 (goto-char beg)
8025 (if (and (re-search-forward org-outline-regexp-bol nil t)
8026 (< (point) end))
8027 (funcall fun))
8028 (while (and (progn
8029 (outline-next-heading)
8030 (< (point) end))
8031 (not (eobp)))
8032 (funcall fun)))))
8034 (defvar org-property-end-re) ; silence byte-compiler
8035 (defun org-fixup-indentation (diff)
8036 "Change the indentation in the current entry by DIFF.
8037 However, if any line in the current entry has no indentation, or if it
8038 would end up with no indentation after the change, nothing at all is done."
8039 (save-excursion
8040 (let ((end (save-excursion (outline-next-heading)
8041 (point-marker)))
8042 (prohibit (if (> diff 0)
8043 "^\\S-"
8044 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8045 col)
8046 (unless (save-excursion (end-of-line 1)
8047 (re-search-forward prohibit end t))
8048 (while (and (< (point) end)
8049 (re-search-forward "^[ \t]+" end t))
8050 (goto-char (match-end 0))
8051 (setq col (current-column))
8052 (if (< diff 0) (replace-match ""))
8053 (org-indent-to-column (+ diff col))))
8054 (move-marker end nil))))
8056 (defun org-convert-to-odd-levels ()
8057 "Convert an org-mode file with all levels allowed to one with odd levels.
8058 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8059 level 5 etc."
8060 (interactive)
8061 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8062 (let ((outline-level 'org-outline-level)
8063 (org-odd-levels-only nil) n)
8064 (save-excursion
8065 (goto-char (point-min))
8066 (while (re-search-forward "^\\*\\*+ " nil t)
8067 (setq n (- (length (match-string 0)) 2))
8068 (while (>= (setq n (1- n)) 0)
8069 (org-demote))
8070 (end-of-line 1))))))
8072 (defun org-convert-to-oddeven-levels ()
8073 "Convert an org-mode file with only odd levels to one with odd/even levels.
8074 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8075 file contains a section with an even level, conversion would
8076 destroy the structure of the file. An error is signaled in this
8077 case."
8078 (interactive)
8079 (goto-char (point-min))
8080 ;; First check if there are no even levels
8081 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8082 (org-show-context t)
8083 (error "Not all levels are odd in this file. Conversion not possible"))
8084 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8085 (let ((outline-regexp org-outline-regexp)
8086 (outline-level 'org-outline-level)
8087 (org-odd-levels-only nil) n)
8088 (save-excursion
8089 (goto-char (point-min))
8090 (while (re-search-forward "^\\*\\*+ " nil t)
8091 (setq n (/ (1- (length (match-string 0))) 2))
8092 (while (>= (setq n (1- n)) 0)
8093 (org-promote))
8094 (end-of-line 1))))))
8096 (defun org-tr-level (n)
8097 "Make N odd if required."
8098 (if org-odd-levels-only (1+ (/ n 2)) n))
8100 ;;; Vertical tree motion, cutting and pasting of subtrees
8102 (defun org-move-subtree-up (&optional arg)
8103 "Move the current subtree up past ARG headlines of the same level."
8104 (interactive "p")
8105 (org-move-subtree-down (- (prefix-numeric-value arg))))
8107 (defun org-move-subtree-down (&optional arg)
8108 "Move the current subtree down past ARG headlines of the same level."
8109 (interactive "p")
8110 (setq arg (prefix-numeric-value arg))
8111 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8112 'org-get-last-sibling))
8113 (ins-point (make-marker))
8114 (cnt (abs arg))
8115 (col (current-column))
8116 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8117 ;; Select the tree
8118 (org-back-to-heading)
8119 (setq beg0 (point))
8120 (save-excursion
8121 (setq ne-beg (org-back-over-empty-lines))
8122 (setq beg (point)))
8123 (save-match-data
8124 (save-excursion (outline-end-of-heading)
8125 (setq folded (outline-invisible-p)))
8126 (outline-end-of-subtree))
8127 (outline-next-heading)
8128 (setq ne-end (org-back-over-empty-lines))
8129 (setq end (point))
8130 (goto-char beg0)
8131 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8132 ;; include less whitespace
8133 (save-excursion
8134 (goto-char beg)
8135 (forward-line (- ne-beg ne-end))
8136 (setq beg (point))))
8137 ;; Find insertion point, with error handling
8138 (while (> cnt 0)
8139 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8140 (progn (goto-char beg0)
8141 (user-error "Cannot move past superior level or buffer limit")))
8142 (setq cnt (1- cnt)))
8143 (if (> arg 0)
8144 ;; Moving forward - still need to move over subtree
8145 (progn (org-end-of-subtree t t)
8146 (save-excursion
8147 (org-back-over-empty-lines)
8148 (or (bolp) (newline)))))
8149 (setq ne-ins (org-back-over-empty-lines))
8150 (move-marker ins-point (point))
8151 (setq txt (buffer-substring beg end))
8152 (org-save-markers-in-region beg end)
8153 (delete-region beg end)
8154 (org-remove-empty-overlays-at beg)
8155 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8156 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8157 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8158 (let ((bbb (point)))
8159 (insert-before-markers txt)
8160 (org-reinstall-markers-in-region bbb)
8161 (move-marker ins-point bbb))
8162 (or (bolp) (insert "\n"))
8163 (setq ins-end (point))
8164 (goto-char ins-point)
8165 (org-skip-whitespace)
8166 (when (and (< arg 0)
8167 (org-first-sibling-p)
8168 (> ne-ins ne-beg))
8169 ;; Move whitespace back to beginning
8170 (save-excursion
8171 (goto-char ins-end)
8172 (let ((kill-whole-line t))
8173 (kill-line (- ne-ins ne-beg)) (point)))
8174 (insert (make-string (- ne-ins ne-beg) ?\n)))
8175 (move-marker ins-point nil)
8176 (if folded
8177 (hide-subtree)
8178 (org-show-entry)
8179 (show-children)
8180 (org-cycle-hide-drawers 'children))
8181 (org-clean-visibility-after-subtree-move)
8182 ;; move back to the initial column we were at
8183 (move-to-column col)))
8185 (defvar org-subtree-clip ""
8186 "Clipboard for cut and paste of subtrees.
8187 This is actually only a copy of the kill, because we use the normal kill
8188 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8190 (defvar org-subtree-clip-folded nil
8191 "Was the last copied subtree folded?
8192 This is used to fold the tree back after pasting.")
8194 (defun org-cut-subtree (&optional n)
8195 "Cut the current subtree into the clipboard.
8196 With prefix arg N, cut this many sequential subtrees.
8197 This is a short-hand for marking the subtree and then cutting it."
8198 (interactive "p")
8199 (org-copy-subtree n 'cut))
8201 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8202 "Copy the current subtree it in the clipboard.
8203 With prefix arg N, copy this many sequential subtrees.
8204 This is a short-hand for marking the subtree and then copying it.
8205 If CUT is non-nil, actually cut the subtree.
8206 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8207 of some markers in the region, even if CUT is non-nil. This is
8208 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8209 (interactive "p")
8210 (let (beg end folded (beg0 (point)))
8211 (if (org-called-interactively-p 'any)
8212 (org-back-to-heading nil) ; take what looks like a subtree
8213 (org-back-to-heading t)) ; take what is really there
8214 (setq beg (point))
8215 (skip-chars-forward " \t\r\n")
8216 (save-match-data
8217 (if nosubtrees
8218 (outline-next-heading)
8219 (save-excursion (outline-end-of-heading)
8220 (setq folded (outline-invisible-p)))
8221 (condition-case nil
8222 (org-forward-heading-same-level (1- n) t)
8223 (error nil))
8224 (org-end-of-subtree t t)))
8225 (setq end (point))
8226 (goto-char beg0)
8227 (when (> end beg)
8228 (setq org-subtree-clip-folded folded)
8229 (when (or cut force-store-markers)
8230 (org-save-markers-in-region beg end))
8231 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8232 (setq org-subtree-clip (current-kill 0))
8233 (message "%s: Subtree(s) with %d characters"
8234 (if cut "Cut" "Copied")
8235 (length org-subtree-clip)))))
8237 (defun org-paste-subtree (&optional level tree for-yank)
8238 "Paste the clipboard as a subtree, with modification of headline level.
8239 The entire subtree is promoted or demoted in order to match a new headline
8240 level.
8242 If the cursor is at the beginning of a headline, the same level as
8243 that headline is used to paste the tree.
8245 If not, the new level is derived from the *visible* headings
8246 before and after the insertion point, and taken to be the inferior headline
8247 level of the two. So if the previous visible heading is level 3 and the
8248 next is level 4 (or vice versa), level 4 will be used for insertion.
8249 This makes sure that the subtree remains an independent subtree and does
8250 not swallow low level entries.
8252 You can also force a different level, either by using a numeric prefix
8253 argument, or by inserting the heading marker by hand. For example, if the
8254 cursor is after \"*****\", then the tree will be shifted to level 5.
8256 If optional TREE is given, use this text instead of the kill ring.
8258 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8259 move back over whitespace before inserting, and move point to the end of
8260 the inserted text when done."
8261 (interactive "P")
8262 (setq tree (or tree (and kill-ring (current-kill 0))))
8263 (unless (org-kill-is-subtree-p tree)
8264 (user-error "%s"
8265 (substitute-command-keys
8266 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8267 (org-with-limited-levels
8268 (let* ((visp (not (outline-invisible-p)))
8269 (txt tree)
8270 (^re_ "\\(\\*+\\)[ \t]*")
8271 (old-level (if (string-match org-outline-regexp-bol txt)
8272 (- (match-end 0) (match-beginning 0) 1)
8273 -1))
8274 (force-level (cond (level (prefix-numeric-value level))
8275 ((and (looking-at "[ \t]*$")
8276 (string-match
8277 "^\\*+$" (buffer-substring
8278 (point-at-bol) (point))))
8279 (- (match-end 1) (match-beginning 1)))
8280 ((and (bolp)
8281 (looking-at org-outline-regexp))
8282 (- (match-end 0) (point) 1))))
8283 (previous-level (save-excursion
8284 (condition-case nil
8285 (progn
8286 (outline-previous-visible-heading 1)
8287 (if (looking-at ^re_)
8288 (- (match-end 0) (match-beginning 0) 1)
8290 (error 1))))
8291 (next-level (save-excursion
8292 (condition-case nil
8293 (progn
8294 (or (looking-at org-outline-regexp)
8295 (outline-next-visible-heading 1))
8296 (if (looking-at ^re_)
8297 (- (match-end 0) (match-beginning 0) 1)
8299 (error 1))))
8300 (new-level (or force-level (max previous-level next-level)))
8301 (shift (if (or (= old-level -1)
8302 (= new-level -1)
8303 (= old-level new-level))
8305 (- new-level old-level)))
8306 (delta (if (> shift 0) -1 1))
8307 (func (if (> shift 0) 'org-demote 'org-promote))
8308 (org-odd-levels-only nil)
8309 beg end newend)
8310 ;; Remove the forced level indicator
8311 (if force-level
8312 (delete-region (point-at-bol) (point)))
8313 ;; Paste
8314 (beginning-of-line (if (bolp) 1 2))
8315 (setq beg (point))
8316 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8317 (insert-before-markers txt)
8318 (unless (string-match "\n\\'" txt) (insert "\n"))
8319 (setq newend (point))
8320 (org-reinstall-markers-in-region beg)
8321 (setq end (point))
8322 (goto-char beg)
8323 (skip-chars-forward " \t\n\r")
8324 (setq beg (point))
8325 (if (and (outline-invisible-p) visp)
8326 (save-excursion (outline-show-heading)))
8327 ;; Shift if necessary
8328 (unless (= shift 0)
8329 (save-restriction
8330 (narrow-to-region beg end)
8331 (while (not (= shift 0))
8332 (org-map-region func (point-min) (point-max))
8333 (setq shift (+ delta shift)))
8334 (goto-char (point-min))
8335 (setq newend (point-max))))
8336 (when (or (org-called-interactively-p 'interactive) for-yank)
8337 (message "Clipboard pasted as level %d subtree" new-level))
8338 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8339 kill-ring
8340 (eq org-subtree-clip (current-kill 0))
8341 org-subtree-clip-folded)
8342 ;; The tree was folded before it was killed/copied
8343 (hide-subtree))
8344 (and for-yank (goto-char newend)))))
8346 (defun org-kill-is-subtree-p (&optional txt)
8347 "Check if the current kill is an outline subtree, or a set of trees.
8348 Returns nil if kill does not start with a headline, or if the first
8349 headline level is not the largest headline level in the tree.
8350 So this will actually accept several entries of equal levels as well,
8351 which is OK for `org-paste-subtree'.
8352 If optional TXT is given, check this string instead of the current kill."
8353 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8354 (re (org-get-limited-outline-regexp))
8355 (^re (concat "^" re))
8356 (start-level (and kill
8357 (string-match
8358 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8359 kill)
8360 (- (match-end 2) (match-beginning 2) 1)))
8361 (start (1+ (or (match-beginning 2) -1))))
8362 (if (not start-level)
8363 (progn
8364 nil) ;; does not even start with a heading
8365 (catch 'exit
8366 (while (setq start (string-match ^re kill (1+ start)))
8367 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8368 (throw 'exit nil)))
8369 t))))
8371 (defvar org-markers-to-move nil
8372 "Markers that should be moved with a cut-and-paste operation.
8373 Those markers are stored together with their positions relative to
8374 the start of the region.")
8376 (defun org-save-markers-in-region (beg end)
8377 "Check markers in region.
8378 If these markers are between BEG and END, record their position relative
8379 to BEG, so that after moving the block of text, we can put the markers back
8380 into place.
8381 This function gets called just before an entry or tree gets cut from the
8382 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8383 called immediately, to move the markers with the entries."
8384 (setq org-markers-to-move nil)
8385 (when (featurep 'org-clock)
8386 (org-clock-save-markers-for-cut-and-paste beg end))
8387 (when (featurep 'org-agenda)
8388 (org-agenda-save-markers-for-cut-and-paste beg end)))
8390 (defun org-check-and-save-marker (marker beg end)
8391 "Check if MARKER is between BEG and END.
8392 If yes, remember the marker and the distance to BEG."
8393 (when (and (marker-buffer marker)
8394 (equal (marker-buffer marker) (current-buffer)))
8395 (if (and (>= marker beg) (< marker end))
8396 (push (cons marker (- marker beg)) org-markers-to-move))))
8398 (defun org-reinstall-markers-in-region (beg)
8399 "Move all remembered markers to their position relative to BEG."
8400 (mapc (lambda (x)
8401 (move-marker (car x) (+ beg (cdr x))))
8402 org-markers-to-move)
8403 (setq org-markers-to-move nil))
8405 (defun org-narrow-to-subtree ()
8406 "Narrow buffer to the current subtree."
8407 (interactive)
8408 (save-excursion
8409 (save-match-data
8410 (org-with-limited-levels
8411 (narrow-to-region
8412 (progn (org-back-to-heading t) (point))
8413 (progn (org-end-of-subtree t t)
8414 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8415 (point)))))))
8417 (defun org-narrow-to-block ()
8418 "Narrow buffer to the current block."
8419 (interactive)
8420 (let* ((case-fold-search t)
8421 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8422 "^[ \t]*#\\+end_.*")))
8423 (if blockp
8424 (narrow-to-region (car blockp) (cdr blockp))
8425 (user-error "Not in a block"))))
8427 (eval-when-compile
8428 (defvar org-property-drawer-re))
8430 (defvar org-property-start-re) ;; defined below
8431 (defun org-clone-subtree-with-time-shift (n &optional shift)
8432 "Clone the task (subtree) at point N times.
8433 The clones will be inserted as siblings.
8435 In interactive use, the user will be prompted for the number of
8436 clones to be produced. If the entry has a timestamp, the user
8437 will also be prompted for a time shift, which may be a repeater
8438 as used in time stamps, for example `+3d'. To disable this,
8439 you can call the function with a universal prefix argument.
8441 When a valid repeater is given and the entry contains any time
8442 stamps, the clones will become a sequence in time, with time
8443 stamps in the subtree shifted for each clone produced. If SHIFT
8444 is nil or the empty string, time stamps will be left alone. The
8445 ID property of the original subtree is removed.
8447 If the original subtree did contain time stamps with a repeater,
8448 the following will happen:
8449 - the repeater will be removed in each clone
8450 - an additional clone will be produced, with the current, unshifted
8451 date(s) in the entry.
8452 - the original entry will be placed *after* all the clones, with
8453 repeater intact.
8454 - the start days in the repeater in the original entry will be shifted
8455 to past the last clone.
8456 In this way you can spell out a number of instances of a repeating task,
8457 and still retain the repeater to cover future instances of the task."
8458 (interactive "nNumber of clones to produce: ")
8459 (let ((shift
8460 (or shift
8461 (if (and (not (equal current-prefix-arg '(4)))
8462 (save-excursion
8463 (re-search-forward org-ts-regexp-both
8464 (save-excursion
8465 (org-end-of-subtree t)
8466 (point)) t)))
8467 (read-from-minibuffer
8468 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8469 ""))) ;; No time shift
8470 (n-no-remove -1)
8471 (drawer-re org-drawer-regexp)
8472 beg end template task idprop
8473 shift-n shift-what doshift nmin nmax)
8474 (if (not (and (integerp n) (> n 0)))
8475 (error "Invalid number of replications %s" n))
8476 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8477 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8478 shift)))
8479 (error "Invalid shift specification %s" shift))
8480 (when doshift
8481 (setq shift-n (string-to-number (match-string 1 shift))
8482 shift-what (cdr (assoc (match-string 2 shift)
8483 '(("d" . day) ("w" . week)
8484 ("m" . month) ("y" . year))))))
8485 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8486 (setq nmin 1 nmax n)
8487 (org-back-to-heading t)
8488 (setq beg (point))
8489 (setq idprop (org-entry-get nil "ID"))
8490 (org-end-of-subtree t t)
8491 (or (bolp) (insert "\n"))
8492 (setq end (point))
8493 (setq template (buffer-substring beg end))
8494 (when (and doshift
8495 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8496 (delete-region beg end)
8497 (setq end beg)
8498 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8499 (goto-char end)
8500 (loop for n from nmin to nmax do
8501 ;; prepare clone
8502 (with-temp-buffer
8503 (insert template)
8504 (org-mode)
8505 (goto-char (point-min))
8506 (org-show-subtree)
8507 (and idprop (if org-clone-delete-id
8508 (org-entry-delete nil "ID")
8509 (org-id-get-create t)))
8510 (unless (= n 0)
8511 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8512 (kill-whole-line))
8513 (goto-char (point-min))
8514 (while (re-search-forward drawer-re nil t)
8515 (mapc (lambda (d)
8516 (org-remove-empty-drawer-at d (point))) org-drawers)))
8517 (goto-char (point-min))
8518 (when doshift
8519 (while (re-search-forward org-ts-regexp-both nil t)
8520 (org-timestamp-change (* n shift-n) shift-what))
8521 (unless (= n n-no-remove)
8522 (goto-char (point-min))
8523 (while (re-search-forward org-ts-regexp nil t)
8524 (save-excursion
8525 (goto-char (match-beginning 0))
8526 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8527 (delete-region (match-beginning 1) (match-end 1)))))))
8528 (setq task (buffer-string)))
8529 (insert task))
8530 (goto-char beg)))
8532 ;;; Outline Sorting
8534 (defun org-sort (with-case)
8535 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8536 Optional argument WITH-CASE means sort case-sensitively."
8537 (interactive "P")
8538 (cond
8539 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8540 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8542 (org-call-with-arg 'org-sort-entries with-case))))
8544 (defun org-sort-remove-invisible (s)
8545 "Remove invisible links from string S."
8546 (remove-text-properties 0 (length s) org-rm-props s)
8547 (while (string-match org-bracket-link-regexp s)
8548 (setq s (replace-match (if (match-end 2)
8549 (match-string 3 s)
8550 (match-string 1 s)) t t s)))
8551 (let ((st (format " %s " s)))
8552 (while (string-match org-emph-re st)
8553 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8554 (setq s (substring st 1 -1)))
8557 (defvar org-priority-regexp) ; defined later in the file
8559 (defvar org-after-sorting-entries-or-items-hook nil
8560 "Hook that is run after a bunch of entries or items have been sorted.
8561 When children are sorted, the cursor is in the parent line when this
8562 hook gets called. When a region or a plain list is sorted, the cursor
8563 will be in the first entry of the sorted region/list.")
8565 (defun org-sort-entries
8566 (&optional with-case sorting-type getkey-func compare-func property)
8567 "Sort entries on a certain level of an outline tree.
8568 If there is an active region, the entries in the region are sorted.
8569 Else, if the cursor is before the first entry, sort the top-level items.
8570 Else, the children of the entry at point are sorted.
8572 Sorting can be alphabetically, numerically, by date/time as given by
8573 a time stamp, by a property, by priority order, or by a custom function.
8575 The command prompts for the sorting type unless it has been given to the
8576 function through the SORTING-TYPE argument, which needs to be a character,
8577 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8578 precise meaning of each character:
8580 n Numerically, by converting the beginning of the entry/item to a number.
8581 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8582 o By order of TODO keywords.
8583 t By date/time, either the first active time stamp in the entry, or, if
8584 none exist, by the first inactive one.
8585 s By the scheduled date/time.
8586 d By deadline date/time.
8587 c By creation time, which is assumed to be the first inactive time stamp
8588 at the beginning of a line.
8589 p By priority according to the cookie.
8590 r By the value of a property.
8592 Capital letters will reverse the sort order.
8594 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8595 called with point at the beginning of the record. It must return either
8596 a string or a number that should serve as the sorting key for that record.
8598 Comparing entries ignores case by default. However, with an optional argument
8599 WITH-CASE, the sorting considers case as well.
8601 Sorting is done against the visible part of the headlines, it ignores hidden
8602 links."
8603 (interactive "P")
8604 (let ((case-func (if with-case 'identity 'downcase))
8605 (cmstr
8606 ;; The clock marker is lost when using `sort-subr', let's
8607 ;; store the clocking string.
8608 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8609 (save-excursion
8610 (goto-char org-clock-marker)
8611 (looking-back "^.*") (match-string-no-properties 0))))
8612 start beg end stars re re2
8613 txt what tmp)
8614 ;; Find beginning and end of region to sort
8615 (cond
8616 ((org-region-active-p)
8617 ;; we will sort the region
8618 (setq end (region-end)
8619 what "region")
8620 (goto-char (region-beginning))
8621 (if (not (org-at-heading-p)) (outline-next-heading))
8622 (setq start (point)))
8623 ((or (org-at-heading-p)
8624 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8625 ;; we will sort the children of the current headline
8626 (org-back-to-heading)
8627 (setq start (point)
8628 end (progn (org-end-of-subtree t t)
8629 (or (bolp) (insert "\n"))
8630 (org-back-over-empty-lines)
8631 (point))
8632 what "children")
8633 (goto-char start)
8634 (show-subtree)
8635 (outline-next-heading))
8637 ;; we will sort the top-level entries in this file
8638 (goto-char (point-min))
8639 (or (org-at-heading-p) (outline-next-heading))
8640 (setq start (point))
8641 (goto-char (point-max))
8642 (beginning-of-line 1)
8643 (when (looking-at ".*?\\S-")
8644 ;; File ends in a non-white line
8645 (end-of-line 1)
8646 (insert "\n"))
8647 (setq end (point-max))
8648 (setq what "top-level")
8649 (goto-char start)
8650 (show-all)))
8652 (setq beg (point))
8653 (if (>= beg end) (user-error "Nothing to sort"))
8655 (looking-at "\\(\\*+\\)")
8656 (setq stars (match-string 1)
8657 re (concat "^" (regexp-quote stars) " +")
8658 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8659 txt (buffer-substring beg end))
8660 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8661 (if (and (not (equal stars "*")) (string-match re2 txt))
8662 (user-error "Region to sort contains a level above the first entry"))
8664 (unless sorting-type
8665 (message
8666 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8667 [t]ime [s]cheduled [d]eadline [c]reated
8668 A/N/P/R/O/F/T/S/D/C means reversed:"
8669 what)
8670 (setq sorting-type (read-char-exclusive))
8672 (unless getkey-func
8673 (and (= (downcase sorting-type) ?f)
8674 (setq getkey-func
8675 (org-icompleting-read "Sort using function: "
8676 obarray 'fboundp t nil nil))
8677 (setq getkey-func (intern getkey-func))))
8679 (and (= (downcase sorting-type) ?r)
8680 (not property)
8681 (setq property
8682 (org-icompleting-read "Property: "
8683 (mapcar 'list (org-buffer-property-keys t))
8684 nil t))))
8686 (message "Sorting entries...")
8688 (save-restriction
8689 (narrow-to-region start end)
8690 (let ((dcst (downcase sorting-type))
8691 (case-fold-search nil)
8692 (now (current-time)))
8693 (sort-subr
8694 (/= dcst sorting-type)
8695 ;; This function moves to the beginning character of the "record" to
8696 ;; be sorted.
8697 (lambda nil
8698 (if (re-search-forward re nil t)
8699 (goto-char (match-beginning 0))
8700 (goto-char (point-max))))
8701 ;; This function moves to the last character of the "record" being
8702 ;; sorted.
8703 (lambda nil
8704 (save-match-data
8705 (condition-case nil
8706 (outline-forward-same-level 1)
8707 (error
8708 (goto-char (point-max))))))
8709 ;; This function returns the value that gets sorted against.
8710 (lambda nil
8711 (cond
8712 ((= dcst ?n)
8713 (if (looking-at org-complex-heading-regexp)
8714 (string-to-number (org-sort-remove-invisible (match-string 4)))
8715 nil))
8716 ((= dcst ?a)
8717 (if (looking-at org-complex-heading-regexp)
8718 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8719 nil))
8720 ((= dcst ?t)
8721 (let ((end (save-excursion (outline-next-heading) (point))))
8722 (if (or (re-search-forward org-ts-regexp end t)
8723 (re-search-forward org-ts-regexp-both end t))
8724 (org-time-string-to-seconds (match-string 0))
8725 (org-float-time now))))
8726 ((= dcst ?c)
8727 (let ((end (save-excursion (outline-next-heading) (point))))
8728 (if (re-search-forward
8729 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8730 end t)
8731 (org-time-string-to-seconds (match-string 0))
8732 (org-float-time now))))
8733 ((= dcst ?s)
8734 (let ((end (save-excursion (outline-next-heading) (point))))
8735 (if (re-search-forward org-scheduled-time-regexp end t)
8736 (org-time-string-to-seconds (match-string 1))
8737 (org-float-time now))))
8738 ((= dcst ?d)
8739 (let ((end (save-excursion (outline-next-heading) (point))))
8740 (if (re-search-forward org-deadline-time-regexp end t)
8741 (org-time-string-to-seconds (match-string 1))
8742 (org-float-time now))))
8743 ((= dcst ?p)
8744 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8745 (string-to-char (match-string 2))
8746 org-default-priority))
8747 ((= dcst ?r)
8748 (or (org-entry-get nil property) ""))
8749 ((= dcst ?o)
8750 (if (looking-at org-complex-heading-regexp)
8751 (- 9999 (length (member (match-string 2)
8752 org-todo-keywords-1)))))
8753 ((= dcst ?f)
8754 (if getkey-func
8755 (progn
8756 (setq tmp (funcall getkey-func))
8757 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8758 tmp)
8759 (error "Invalid key function `%s'" getkey-func)))
8760 (t (error "Invalid sorting type `%c'" sorting-type))))
8762 (cond
8763 ((= dcst ?a) 'string<)
8764 ((= dcst ?f) compare-func)
8765 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8766 (run-hooks 'org-after-sorting-entries-or-items-hook)
8767 ;; Reset the clock marker if needed
8768 (when cmstr
8769 (save-excursion
8770 (goto-char start)
8771 (search-forward cmstr nil t)
8772 (move-marker org-clock-marker (point))))
8773 (message "Sorting entries...done")))
8775 (defun org-do-sort (table what &optional with-case sorting-type)
8776 "Sort TABLE of WHAT according to SORTING-TYPE.
8777 The user will be prompted for the SORTING-TYPE if the call to this
8778 function does not specify it. WHAT is only for the prompt, to indicate
8779 what is being sorted. The sorting key will be extracted from
8780 the car of the elements of the table.
8781 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8782 (unless sorting-type
8783 (message
8784 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8785 what)
8786 (setq sorting-type (read-char-exclusive)))
8787 (let ((dcst (downcase sorting-type))
8788 extractfun comparefun)
8789 ;; Define the appropriate functions
8790 (cond
8791 ((= dcst ?n)
8792 (setq extractfun 'string-to-number
8793 comparefun (if (= dcst sorting-type) '< '>)))
8794 ((= dcst ?a)
8795 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8796 (lambda(x) (downcase (org-sort-remove-invisible x))))
8797 comparefun (if (= dcst sorting-type)
8798 'string<
8799 (lambda (a b) (and (not (string< a b))
8800 (not (string= a b)))))))
8801 ((= dcst ?t)
8802 (setq extractfun
8803 (lambda (x)
8804 (if (or (string-match org-ts-regexp x)
8805 (string-match org-ts-regexp-both x))
8806 (org-float-time
8807 (org-time-string-to-time (match-string 0 x)))
8809 comparefun (if (= dcst sorting-type) '< '>)))
8810 (t (error "Invalid sorting type `%c'" sorting-type)))
8812 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8813 table)
8814 (lambda (a b) (funcall comparefun (car a) (car b))))))
8817 ;;; The orgstruct minor mode
8819 ;; Define a minor mode which can be used in other modes in order to
8820 ;; integrate the org-mode structure editing commands.
8822 ;; This is really a hack, because the org-mode structure commands use
8823 ;; keys which normally belong to the major mode. Here is how it
8824 ;; works: The minor mode defines all the keys necessary to operate the
8825 ;; structure commands, but wraps the commands into a function which
8826 ;; tests if the cursor is currently at a headline or a plain list
8827 ;; item. If that is the case, the structure command is used,
8828 ;; temporarily setting many Org-mode variables like regular
8829 ;; expressions for filling etc. However, when any of those keys is
8830 ;; used at a different location, function uses `key-binding' to look
8831 ;; up if the key has an associated command in another currently active
8832 ;; keymap (minor modes, major mode, global), and executes that
8833 ;; command. There might be problems if any of the keys is otherwise
8834 ;; used as a prefix key.
8836 (defcustom orgstruct-heading-prefix-regexp nil
8837 "Regexp that matches the custom prefix of Org headlines in
8838 orgstruct(++)-mode."
8839 :group 'org
8840 :version "24.4"
8841 :package-version '(Org . "8.0")
8842 :type 'string)
8843 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8845 (defcustom orgstruct-setup-hook nil
8846 "Hook run after orgstruct-mode-map is filled."
8847 :group 'org
8848 :version "24.4"
8849 :package-version '(Org . "8.0")
8850 :type 'hook)
8852 (defvar orgstruct-initialized nil)
8854 (defvar org-local-vars nil
8855 "List of local variables, for use by `orgstruct-mode'.")
8857 ;;;###autoload
8858 (define-minor-mode orgstruct-mode
8859 "Toggle the minor mode `orgstruct-mode'.
8860 This mode is for using Org-mode structure commands in other
8861 modes. The following keys behave as if Org-mode were active, if
8862 the cursor is on a headline, or on a plain list item (both as
8863 defined by Org-mode)."
8864 nil " OrgStruct" (make-sparse-keymap)
8865 (funcall (if orgstruct-mode
8866 'add-to-invisibility-spec
8867 'remove-from-invisibility-spec)
8868 '(outline . t))
8869 (when orgstruct-mode
8870 (org-load-modules-maybe)
8871 (unless orgstruct-initialized
8872 (orgstruct-setup)
8873 (setq orgstruct-initialized t))))
8875 ;;;###autoload
8876 (defun turn-on-orgstruct ()
8877 "Unconditionally turn on `orgstruct-mode'."
8878 (orgstruct-mode 1))
8880 (defvar org-fb-vars nil)
8881 (make-variable-buffer-local 'org-fb-vars)
8882 (defun orgstruct++-mode (&optional arg)
8883 "Toggle `orgstruct-mode', the enhanced version of it.
8884 In addition to setting orgstruct-mode, this also exports all
8885 indentation and autofilling variables from org-mode into the
8886 buffer. It will also recognize item context in multiline items."
8887 (interactive "P")
8888 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8889 (if (< arg 1)
8890 (progn (orgstruct-mode -1)
8891 (mapc (lambda(v)
8892 (org-set-local (car v)
8893 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8894 org-fb-vars))
8895 (orgstruct-mode 1)
8896 (setq org-fb-vars nil)
8897 (unless org-local-vars
8898 (setq org-local-vars (org-get-local-variables)))
8899 (let (var val)
8900 (mapc
8901 (lambda (x)
8902 (when (string-match
8903 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8904 (symbol-name (car x)))
8905 (setq var (car x) val (nth 1 x))
8906 (push (list var `(quote ,(eval var))) org-fb-vars)
8907 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8908 org-local-vars)
8909 (org-set-local 'orgstruct-is-++ t))))
8911 (defvar orgstruct-is-++ nil
8912 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8913 (make-variable-buffer-local 'orgstruct-is-++)
8915 ;;;###autoload
8916 (defun turn-on-orgstruct++ ()
8917 "Unconditionally turn on `orgstruct++-mode'."
8918 (orgstruct++-mode 1))
8920 (defun orgstruct-error ()
8921 "Error when there is no default binding for a structure key."
8922 (interactive)
8923 (funcall (if (fboundp 'user-error)
8924 'user-error
8925 'error)
8926 "This key has no function outside structure elements"))
8928 (defun orgstruct-setup ()
8929 "Setup orgstruct keymap."
8930 (dolist (cell '((org-demote . t)
8931 (org-metaleft . t)
8932 (org-metaright . t)
8933 (org-promote . t)
8934 (org-shiftmetaleft . t)
8935 (org-shiftmetaright . t)
8936 org-backward-element
8937 org-backward-heading-same-level
8938 org-ctrl-c-ret
8939 org-ctrl-c-minus
8940 org-ctrl-c-star
8941 org-cycle
8942 org-forward-heading-same-level
8943 org-insert-heading
8944 org-insert-heading-respect-content
8945 org-kill-note-or-show-branches
8946 org-mark-subtree
8947 org-meta-return
8948 org-metadown
8949 org-metaup
8950 org-narrow-to-subtree
8951 org-promote-subtree
8952 org-reveal
8953 org-shiftdown
8954 org-shiftleft
8955 org-shiftmetadown
8956 org-shiftmetaup
8957 org-shiftright
8958 org-shifttab
8959 org-shifttab
8960 org-shiftup
8961 org-show-subtree
8962 org-sort
8963 org-up-element
8964 outline-demote
8965 outline-next-visible-heading
8966 outline-previous-visible-heading
8967 outline-promote
8968 outline-up-heading
8969 show-children))
8970 (let ((f (or (car-safe cell) cell))
8971 (disable-when-heading-prefix (cdr-safe cell)))
8972 (when (fboundp f)
8973 (let ((new-bindings))
8974 (dolist (binding (nconc (where-is-internal f org-mode-map)
8975 (where-is-internal f outline-mode-map)))
8976 (push binding new-bindings)
8977 ;; TODO use local-function-key-map
8978 (dolist (rep '(("<tab>" . "TAB")
8979 ("<return>" . "RET")
8980 ("<escape>" . "ESC")
8981 ("<delete>" . "DEL")))
8982 (setq binding (read-kbd-macro
8983 (let ((case-fold-search))
8984 (replace-regexp-in-string
8985 (regexp-quote (cdr rep))
8986 (car rep)
8987 (key-description binding)))))
8988 (pushnew binding new-bindings :test 'equal)))
8989 (dolist (binding new-bindings)
8990 (let ((key (lookup-key orgstruct-mode-map binding)))
8991 (when (or (not key) (numberp key))
8992 (condition-case nil
8993 (org-defkey orgstruct-mode-map
8994 binding
8995 (orgstruct-make-binding f binding disable-when-heading-prefix))
8996 (error nil)))))))))
8997 (run-hooks 'orgstruct-setup-hook))
8999 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9000 "Create a function for binding in the structure minor mode.
9001 FUN is the command to call inside a table. KEY is the key that
9002 should be checked in for a command to execute outside of tables.
9003 Non-nil DISABLE-WHEN-HEADING-PREFIX means to disable the command
9004 if `orgstruct-heading-prefix-regexp' is non-nil."
9005 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9006 (let ((nname name)
9007 (i 0))
9008 (while (fboundp (intern nname))
9009 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9010 (setq name (intern nname)))
9011 (eval
9012 (let ((bindings '((org-heading-regexp
9013 (concat "^"
9014 orgstruct-heading-prefix-regexp
9015 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9016 (org-outline-regexp
9017 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9018 (org-outline-regexp-bol
9019 (concat "^" org-outline-regexp))
9020 (outline-regexp org-outline-regexp)
9021 (outline-heading-end-regexp "\n")
9022 (outline-level 'org-outline-level)
9023 (outline-heading-alist))))
9024 `(defun ,name (arg)
9025 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9026 "Outside of structure, run the binding of `"
9027 (key-description key) "'."
9028 (when disable-when-heading-prefix
9029 (concat
9030 "\nIf `orgstruct-heading-prefix-regexp' is non-nil, this command will always fall\n"
9031 "back to the default binding due to limitations of Org's implementation of\n"
9032 "`" (symbol-name fun) "'.")))
9033 (interactive "p")
9034 (let* ((disable
9035 ,(when disable-when-heading-prefix
9036 '(and orgstruct-heading-prefix-regexp
9037 (not (string= orgstruct-heading-prefix-regexp "")))))
9038 (fallback
9039 (or disable
9040 (not
9041 (let* ,bindings
9042 (org-context-p 'headline 'item
9043 ,(when (memq fun
9044 '(org-insert-heading
9045 org-insert-heading-respect-content
9046 org-meta-return))
9047 '(when orgstruct-is-++
9048 'item-body))))))))
9049 (if fallback
9050 (let* ((orgstruct-mode)
9051 (binding
9052 (loop with key = ,key
9053 for rep in
9054 '(nil
9055 ("<\\([^>]*\\)tab>" . "\\1TAB")
9056 ("<\\([^>]*\\)return>" . "\\1RET")
9057 ("<\\([^>]*\\)escape>" . "\\1ESC")
9058 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9060 (when rep
9061 (setq key (read-kbd-macro
9062 (let ((case-fold-search))
9063 (replace-regexp-in-string
9064 (car rep)
9065 (cdr rep)
9066 (key-description key))))))
9067 thereis (key-binding key))))
9068 (if (keymapp binding)
9069 (set-temporary-overlay-map binding)
9070 (let ((func (or binding
9071 (unless disable
9072 'orgstruct-error))))
9073 (when func
9074 (call-interactively func)))))
9075 (org-run-like-in-org-mode
9076 (lambda ()
9077 (interactive)
9078 (let* ,bindings
9079 (call-interactively ',fun)))))))))
9080 name))
9082 (defun org-contextualize-keys (alist contexts)
9083 "Return valid elements in ALIST depending on CONTEXTS.
9085 `org-agenda-custom-commands' or `org-capture-templates' are the
9086 values used for ALIST, and `org-agenda-custom-commands-contexts'
9087 or `org-capture-templates-contexts' are the associated contexts
9088 definitions."
9089 (let ((contexts
9090 ;; normalize contexts
9091 (mapcar
9092 (lambda(c) (cond ((listp (cadr c))
9093 (list (car c) (car c) (cadr c)))
9094 ((string= "" (cadr c))
9095 (list (car c) (car c) (caddr c)))
9096 (t c))) contexts))
9097 (a alist) c r s)
9098 ;; loop over all commands or templates
9099 (while (setq c (pop a))
9100 (let (vrules repl)
9101 (cond
9102 ((not (assoc (car c) contexts))
9103 (push c r))
9104 ((and (assoc (car c) contexts)
9105 (setq vrules (org-contextualize-validate-key
9106 (car c) contexts)))
9107 (mapc (lambda (vr)
9108 (when (not (equal (car vr) (cadr vr)))
9109 (setq repl vr))) vrules)
9110 (if (not repl) (push c r)
9111 (push (cadr repl) s)
9112 (push
9113 (cons (car c)
9114 (cdr (or (assoc (cadr repl) alist)
9115 (error "Undefined key `%s' as contextual replacement for `%s'"
9116 (cadr repl) (car c)))))
9117 r))))))
9118 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9119 (delq
9121 (delete-dups
9122 (mapcar (lambda (x)
9123 (let ((tpl (car x)))
9124 (when (not (delq
9126 (mapcar (lambda(y)
9127 (equal y tpl)) s))) x)))
9128 (reverse r))))))
9130 (defun org-contextualize-validate-key (key contexts)
9131 "Check CONTEXTS for agenda or capture KEY."
9132 (let (r rr res)
9133 (while (setq r (pop contexts))
9134 (mapc
9135 (lambda (rr)
9136 (when
9137 (and (equal key (car r))
9138 (if (functionp rr) (funcall rr)
9139 (or (and (eq (car rr) 'in-file)
9140 (buffer-file-name)
9141 (string-match (cdr rr) (buffer-file-name)))
9142 (and (eq (car rr) 'in-mode)
9143 (string-match (cdr rr) (symbol-name major-mode)))
9144 (and (eq (car rr) 'in-buffer)
9145 (string-match (cdr rr) (buffer-name)))
9146 (when (and (eq (car rr) 'not-in-file)
9147 (buffer-file-name))
9148 (not (string-match (cdr rr) (buffer-file-name))))
9149 (when (eq (car rr) 'not-in-mode)
9150 (not (string-match (cdr rr) (symbol-name major-mode))))
9151 (when (eq (car rr) 'not-in-buffer)
9152 (not (string-match (cdr rr) (buffer-name)))))))
9153 (push r res)))
9154 (car (last r))))
9155 (delete-dups (delq nil res))))
9157 (defun org-context-p (&rest contexts)
9158 "Check if local context is any of CONTEXTS.
9159 Possible values in the list of contexts are `table', `headline', and `item'."
9160 (let ((pos (point)))
9161 (goto-char (point-at-bol))
9162 (prog1 (or (and (memq 'table contexts)
9163 (looking-at "[ \t]*|"))
9164 (and (memq 'headline contexts)
9165 (looking-at org-outline-regexp))
9166 (and (memq 'item contexts)
9167 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9168 (and (memq 'item-body contexts)
9169 (org-in-item-p)))
9170 (goto-char pos))))
9172 (defun org-get-local-variables ()
9173 "Return a list of all local variables in an Org mode buffer."
9174 (let (varlist)
9175 (with-current-buffer (get-buffer-create "*Org tmp*")
9176 (erase-buffer)
9177 (org-mode)
9178 (setq varlist (buffer-local-variables)))
9179 (kill-buffer "*Org tmp*")
9180 (delq nil
9181 (mapcar
9182 (lambda (x)
9183 (setq x
9184 (if (symbolp x)
9185 (list x)
9186 (list (car x) (cdr x))))
9187 (if (and (not (get (car x) 'org-state))
9188 (string-match
9189 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9190 (symbol-name (car x))))
9191 x nil))
9192 varlist))))
9194 (defun org-clone-local-variables (from-buffer &optional regexp)
9195 "Clone local variables from FROM-BUFFER.
9196 Optional argument REGEXP selects variables to clone."
9197 (mapc
9198 (lambda (pair)
9199 (and (symbolp (car pair))
9200 (or (null regexp)
9201 (string-match regexp (symbol-name (car pair))))
9202 (set (make-local-variable (car pair))
9203 (cdr pair))))
9204 (buffer-local-variables from-buffer)))
9206 ;;;###autoload
9207 (defun org-run-like-in-org-mode (cmd)
9208 "Run a command, pretending that the current buffer is in Org-mode.
9209 This will temporarily bind local variables that are typically bound in
9210 Org-mode to the values they have in Org-mode, and then interactively
9211 call CMD."
9212 (org-load-modules-maybe)
9213 (unless org-local-vars
9214 (setq org-local-vars (org-get-local-variables)))
9215 (let (binds)
9216 (dolist (var org-local-vars)
9217 (when (or (not (boundp (car var)))
9218 (eq (symbol-value (car var))
9219 (default-value (car var))))
9220 (push (list (car var) `(quote ,(cadr var))) binds)))
9221 (eval `(let ,binds
9222 (call-interactively (quote ,cmd))))))
9224 ;;;; Archiving
9226 (defun org-get-category (&optional pos force-refresh)
9227 "Get the category applying to position POS."
9228 (save-match-data
9229 (if force-refresh (org-refresh-category-properties))
9230 (let ((pos (or pos (point))))
9231 (or (get-text-property pos 'org-category)
9232 (progn (org-refresh-category-properties)
9233 (get-text-property pos 'org-category))))))
9235 (defun org-refresh-category-properties ()
9236 "Refresh category text properties in the buffer."
9237 (let ((case-fold-search t)
9238 (inhibit-read-only t)
9239 (def-cat (cond
9240 ((null org-category)
9241 (if buffer-file-name
9242 (file-name-sans-extension
9243 (file-name-nondirectory buffer-file-name))
9244 "???"))
9245 ((symbolp org-category) (symbol-name org-category))
9246 (t org-category)))
9247 beg end cat pos optionp)
9248 (org-with-silent-modifications
9249 (save-excursion
9250 (save-restriction
9251 (widen)
9252 (goto-char (point-min))
9253 (put-text-property (point) (point-max) 'org-category def-cat)
9254 (while (re-search-forward
9255 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9256 (setq pos (match-end 0)
9257 optionp (equal (char-after (match-beginning 0)) ?#)
9258 cat (org-trim (match-string 2)))
9259 (if optionp
9260 (setq beg (point-at-bol) end (point-max))
9261 (org-back-to-heading t)
9262 (setq beg (point) end (org-end-of-subtree t t)))
9263 (put-text-property beg end 'org-category cat)
9264 (put-text-property beg end 'org-category-position beg)
9265 (goto-char pos)))))))
9267 (defun org-refresh-properties (dprop tprop)
9268 "Refresh buffer text properties.
9269 DPROP is the drawer property and TPROP is the corresponding text
9270 property to set."
9271 (let ((case-fold-search t)
9272 (inhibit-read-only t) p)
9273 (org-with-silent-modifications
9274 (save-excursion
9275 (save-restriction
9276 (widen)
9277 (goto-char (point-min))
9278 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9279 (setq p (org-match-string-no-properties 1))
9280 (save-excursion
9281 (org-back-to-heading t)
9282 (put-text-property
9283 (point-at-bol) (org-end-of-subtree t t) tprop p))))))))
9286 ;;;; Link Stuff
9288 ;;; Link abbreviations
9290 (defun org-link-expand-abbrev (link)
9291 "Apply replacements as defined in `org-link-abbrev-alist'."
9292 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9293 (let* ((key (match-string 1 link))
9294 (as (or (assoc key org-link-abbrev-alist-local)
9295 (assoc key org-link-abbrev-alist)))
9296 (tag (and (match-end 2) (match-string 3 link)))
9297 rpl)
9298 (if (not as)
9299 link
9300 (setq rpl (cdr as))
9301 (cond
9302 ((symbolp rpl) (funcall rpl tag))
9303 ((string-match "%(\\([^)]+\\))" rpl)
9304 (replace-match
9305 (save-match-data
9306 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9307 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9308 ((string-match "%h" rpl)
9309 (replace-match (url-hexify-string (or tag "")) t t rpl))
9310 (t (concat rpl tag)))))
9311 link))
9313 ;;; Storing and inserting links
9315 (defvar org-insert-link-history nil
9316 "Minibuffer history for links inserted with `org-insert-link'.")
9318 (defvar org-stored-links nil
9319 "Contains the links stored with `org-store-link'.")
9321 (defvar org-store-link-plist nil
9322 "Plist with info about the most recently link created with `org-store-link'.")
9324 (defvar org-link-protocols nil
9325 "Link protocols added to Org-mode using `org-add-link-type'.")
9327 (defvar org-store-link-functions nil
9328 "List of functions that are called to create and store a link.
9329 Each function will be called in turn until one returns a non-nil
9330 value. Each function should check if it is responsible for creating
9331 this link (for example by looking at the major mode).
9332 If not, it must exit and return nil.
9333 If yes, it should return a non-nil value after a calling
9334 `org-store-link-props' with a list of properties and values.
9335 Special properties are:
9337 :type The link prefix, like \"http\". This must be given.
9338 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9339 This is obligatory as well.
9340 :description Optional default description for the second pair
9341 of brackets in an Org-mode link. The user can still change
9342 this when inserting this link into an Org-mode buffer.
9344 In addition to these, any additional properties can be specified
9345 and then used in capture templates.")
9347 (defun org-add-link-type (type &optional follow export)
9348 "Add TYPE to the list of `org-link-types'.
9349 Re-compute all regular expressions depending on `org-link-types'
9351 FOLLOW and EXPORT are two functions.
9353 FOLLOW should take the link path as the single argument and do whatever
9354 is necessary to follow the link, for example find a file or display
9355 a mail message.
9357 EXPORT should format the link path for export to one of the export formats.
9358 It should be a function accepting three arguments:
9360 path the path of the link, the text after the prefix (like \"http:\")
9361 desc the description of the link, if any, or a description added by
9362 org-export-normalize-links if there is none
9363 format the export format, a symbol like `html' or `latex' or `ascii'..
9365 The function may use the FORMAT information to return different values
9366 depending on the format. The return value will be put literally into
9367 the exported file. If the return value is nil, this means Org should
9368 do what it normally does with links which do not have EXPORT defined.
9370 Org-mode has a built-in default for exporting links. If you are happy with
9371 this default, there is no need to define an export function for the link
9372 type. For a simple example of an export function, see `org-bbdb.el'."
9373 (add-to-list 'org-link-types type t)
9374 (org-make-link-regexps)
9375 (if (assoc type org-link-protocols)
9376 (setcdr (assoc type org-link-protocols) (list follow export))
9377 (push (list type follow export) org-link-protocols)))
9379 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9380 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9382 ;;;###autoload
9383 (defun org-store-link (arg)
9384 "\\<org-mode-map>Store an org-link to the current location.
9385 This link is added to `org-stored-links' and can later be inserted
9386 into an org-buffer with \\[org-insert-link].
9388 For some link types, a prefix arg is interpreted.
9389 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9390 For file links, arg negates `org-context-in-file-links'.
9392 A double prefix arg force skipping storing functions that are not
9393 part of Org's core.
9395 A triple prefix arg force storing a link for each line in the
9396 active region."
9397 (interactive "P")
9398 (org-load-modules-maybe)
9399 (if (and (equal arg '(64)) (org-region-active-p))
9400 (save-excursion
9401 (let ((end (region-end)))
9402 (goto-char (region-beginning))
9403 (set-mark (point))
9404 (while (< (point-at-eol) end)
9405 (move-end-of-line 1) (activate-mark)
9406 (let (current-prefix-arg)
9407 (call-interactively 'org-store-link))
9408 (move-beginning-of-line 2)
9409 (set-mark (point)))))
9410 (org-with-limited-levels
9411 (setq org-store-link-plist nil)
9412 (let (link cpltxt desc description search
9413 txt custom-id agenda-link sfuns sfunsn)
9414 (cond
9416 ;; Store a link using an external link type
9417 ((and (not (equal arg '(16)))
9418 (setq sfuns
9419 (delq
9420 nil (mapcar (lambda (f)
9421 (let (fs) (if (funcall f) (push f fs))))
9422 org-store-link-functions))
9423 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9424 (or (and (cdr sfuns)
9425 (funcall (intern
9426 (completing-read
9427 "Which function for creating the link? "
9428 sfunsn t (car sfunsn)))))
9429 (funcall (caar sfuns)))
9430 (setq link (plist-get org-store-link-plist :link)
9431 desc (or (plist-get org-store-link-plist
9432 :description) link))))
9434 ;; Store a link from a source code buffer
9435 ((org-src-edit-buffer-p)
9436 (let (label gc)
9437 (while (or (not label)
9438 (save-excursion
9439 (save-restriction
9440 (widen)
9441 (goto-char (point-min))
9442 (re-search-forward
9443 (regexp-quote (format org-coderef-label-format label))
9444 nil t))))
9445 (when label (message "Label exists already") (sit-for 2))
9446 (setq label (read-string "Code line label: " label)))
9447 (end-of-line 1)
9448 (setq link (format org-coderef-label-format label))
9449 (setq gc (- 79 (length link)))
9450 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9451 (insert link)
9452 (setq link (concat "(" label ")") desc nil)))
9454 ;; We are in the agenda, link to referenced location
9455 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9456 (let ((m (or (get-text-property (point) 'org-hd-marker)
9457 (get-text-property (point) 'org-marker))))
9458 (when m
9459 (org-with-point-at m
9460 (setq agenda-link
9461 (if (org-called-interactively-p 'any)
9462 (call-interactively 'org-store-link)
9463 (org-store-link nil)))))))
9465 ((eq major-mode 'calendar-mode)
9466 (let ((cd (calendar-cursor-to-date)))
9467 (setq link
9468 (format-time-string
9469 (car org-time-stamp-formats)
9470 (apply 'encode-time
9471 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9472 nil nil nil))))
9473 (org-store-link-props :type "calendar" :date cd)))
9475 ((eq major-mode 'help-mode)
9476 (setq link (concat "help:" (save-excursion
9477 (goto-char (point-min))
9478 (looking-at "^[^ ]+")
9479 (match-string 0))))
9480 (org-store-link-props :type "help"))
9482 ((eq major-mode 'w3-mode)
9483 (setq cpltxt (if (and (buffer-name)
9484 (not (string-match "Untitled" (buffer-name))))
9485 (buffer-name)
9486 (url-view-url t))
9487 link (url-view-url t))
9488 (org-store-link-props :type "w3" :url (url-view-url t)))
9490 ((eq major-mode 'image-mode)
9491 (setq cpltxt (concat "file:"
9492 (abbreviate-file-name buffer-file-name))
9493 link cpltxt)
9494 (org-store-link-props :type "image" :file buffer-file-name))
9496 ;; In dired, store a link to the file of the current line
9497 ((eq major-mode 'dired-mode)
9498 (let ((file (dired-get-filename nil t)))
9499 (setq file (if file
9500 (abbreviate-file-name
9501 (expand-file-name (dired-get-filename nil t)))
9502 ;; otherwise, no file so use current directory.
9503 default-directory))
9504 (setq cpltxt (concat "file:" file)
9505 link cpltxt)))
9507 ((setq search (run-hook-with-args-until-success
9508 'org-create-file-search-functions))
9509 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9510 "::" search))
9511 (setq cpltxt (or description link)))
9513 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9514 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9515 (cond
9516 ;; Store a link using the target at point
9517 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9518 (setq cpltxt
9519 (concat "file:"
9520 (abbreviate-file-name
9521 (buffer-file-name (buffer-base-buffer)))
9522 "::" (match-string 1))
9523 link cpltxt))
9524 ((and (featurep 'org-id)
9525 (or (eq org-id-link-to-org-use-id t)
9526 (and (org-called-interactively-p 'any)
9527 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9528 (and (eq org-id-link-to-org-use-id
9529 'create-if-interactive-and-no-custom-id)
9530 (not custom-id))))
9531 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9532 ;; Store a link using the ID at point
9533 (setq link (condition-case nil
9534 (prog1 (org-id-store-link)
9535 (setq desc (plist-get org-store-link-plist
9536 :description)))
9537 (error
9538 ;; Probably before first headline, link only to file
9539 (concat "file:"
9540 (abbreviate-file-name
9541 (buffer-file-name (buffer-base-buffer))))))))
9543 ;; Just link to current headline
9544 (setq cpltxt (concat "file:"
9545 (abbreviate-file-name
9546 (buffer-file-name (buffer-base-buffer)))))
9547 ;; Add a context search string
9548 (when (org-xor org-context-in-file-links arg)
9549 (let* ((ee (org-element-at-point))
9550 (et (org-element-type ee))
9551 (ev (plist-get (cadr ee) :value))
9552 (ek (plist-get (cadr ee) :key))
9553 (eok (and (stringp ek) (string-match "name" ek))))
9554 (setq txt (cond
9555 ((org-at-heading-p) nil)
9556 ((and (eq et 'keyword) eok) ev)
9557 ((org-region-active-p)
9558 (buffer-substring (region-beginning) (region-end)))))
9559 (when (or (null txt) (string-match "\\S-" txt))
9560 (setq cpltxt
9561 (concat cpltxt "::"
9562 (condition-case nil
9563 (org-make-org-heading-search-string txt)
9564 (error "")))
9565 desc (or (and (eq et 'keyword) eok ev)
9566 (nth 4 (ignore-errors (org-heading-components)))
9567 "NONE")))))
9568 (if (string-match "::\\'" cpltxt)
9569 (setq cpltxt (substring cpltxt 0 -2)))
9570 (setq link cpltxt))))
9572 ((buffer-file-name (buffer-base-buffer))
9573 ;; Just link to this file here.
9574 (setq cpltxt (concat "file:"
9575 (abbreviate-file-name
9576 (buffer-file-name (buffer-base-buffer)))))
9577 ;; Add a context string.
9578 (when (org-xor org-context-in-file-links arg)
9579 (setq txt (if (org-region-active-p)
9580 (buffer-substring (region-beginning) (region-end))
9581 (buffer-substring (point-at-bol) (point-at-eol))))
9582 ;; Only use search option if there is some text.
9583 (when (string-match "\\S-" txt)
9584 (setq cpltxt
9585 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9586 desc "NONE")))
9587 (setq link cpltxt))
9589 ((org-called-interactively-p 'interactive)
9590 (user-error "No method for storing a link from this buffer"))
9592 (t (setq link nil)))
9594 ;; We're done setting link and desc, clean up
9595 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9596 (setq link (or link cpltxt)
9597 desc (or desc cpltxt))
9598 (cond ((equal desc "NONE") (setq desc nil))
9599 ((string-match org-bracket-link-analytic-regexp desc)
9600 (let ((d0 (match-string 3 desc))
9601 (p0 (match-string 5 desc)))
9602 (setq desc
9603 (replace-regexp-in-string
9604 org-bracket-link-regexp
9605 (concat (or p0 d0)
9606 (if (equal (length (match-string 0 desc))
9607 (length desc)) "*" "")) desc)))))
9609 ;; Return the link
9610 (if (not (and (or (org-called-interactively-p 'any)
9611 executing-kbd-macro) link))
9612 (or agenda-link (and link (org-make-link-string link desc)))
9613 (push (list link desc) org-stored-links)
9614 (message "Stored: %s" (or desc link))
9615 (when custom-id
9616 (setq link (concat "file:" (abbreviate-file-name
9617 (buffer-file-name)) "::#" custom-id))
9618 (push (list link desc) org-stored-links)))))))
9620 (defun org-store-link-props (&rest plist)
9621 "Store link properties, extract names and addresses."
9622 (let (x adr)
9623 (when (setq x (plist-get plist :from))
9624 (setq adr (mail-extract-address-components x))
9625 (setq plist (plist-put plist :fromname (car adr)))
9626 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9627 (when (setq x (plist-get plist :to))
9628 (setq adr (mail-extract-address-components x))
9629 (setq plist (plist-put plist :toname (car adr)))
9630 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9631 (let ((from (plist-get plist :from))
9632 (to (plist-get plist :to)))
9633 (when (and from to org-from-is-user-regexp)
9634 (setq plist
9635 (plist-put plist :fromto
9636 (if (string-match org-from-is-user-regexp from)
9637 (concat "to %t")
9638 (concat "from %f"))))))
9639 (setq org-store-link-plist plist))
9641 (defun org-add-link-props (&rest plist)
9642 "Add these properties to the link property list."
9643 (let (key value)
9644 (while plist
9645 (setq key (pop plist) value (pop plist))
9646 (setq org-store-link-plist
9647 (plist-put org-store-link-plist key value)))))
9649 (defun org-email-link-description (&optional fmt)
9650 "Return the description part of an email link.
9651 This takes information from `org-store-link-plist' and formats it
9652 according to FMT (default from `org-email-link-description-format')."
9653 (setq fmt (or fmt org-email-link-description-format))
9654 (let* ((p org-store-link-plist)
9655 (to (plist-get p :toaddress))
9656 (from (plist-get p :fromaddress))
9657 (table
9658 (list
9659 (cons "%c" (plist-get p :fromto))
9660 (cons "%F" (plist-get p :from))
9661 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9662 (cons "%T" (plist-get p :to))
9663 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9664 (cons "%s" (plist-get p :subject))
9665 (cons "%d" (plist-get p :date))
9666 (cons "%m" (plist-get p :message-id)))))
9667 (when (string-match "%c" fmt)
9668 ;; Check if the user wrote this message
9669 (if (and org-from-is-user-regexp from to
9670 (save-match-data (string-match org-from-is-user-regexp from)))
9671 (setq fmt (replace-match "to %t" t t fmt))
9672 (setq fmt (replace-match "from %f" t t fmt))))
9673 (org-replace-escapes fmt table)))
9675 (defun org-make-org-heading-search-string (&optional string)
9676 "Make search string for the current headline or STRING."
9677 (let ((s (or string
9678 (and (derived-mode-p 'org-mode)
9679 (save-excursion
9680 (org-back-to-heading t)
9681 (org-element-property :raw-value (org-element-at-point))))))
9682 (lines org-context-in-file-links))
9683 (or string (setq s (concat "*" s))) ; Add * for headlines
9684 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9685 (when (and string (integerp lines) (> lines 0))
9686 (let ((slines (org-split-string s "\n")))
9687 (when (< lines (length slines))
9688 (setq s (mapconcat
9689 'identity
9690 (reverse (nthcdr (- (length slines) lines)
9691 (reverse slines))) "\n")))))
9692 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9694 (defun org-make-link-string (link &optional description)
9695 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9696 (unless (string-match "\\S-" link)
9697 (error "Empty link"))
9698 (when (and description
9699 (stringp description)
9700 (not (string-match "\\S-" description)))
9701 (setq description nil))
9702 (when (stringp description)
9703 ;; Remove brackets from the description, they are fatal.
9704 (while (string-match "\\[" description)
9705 (setq description (replace-match "{" t t description)))
9706 (while (string-match "\\]" description)
9707 (setq description (replace-match "}" t t description))))
9708 (when (equal link description)
9709 ;; No description needed, it is identical
9710 (setq description nil))
9711 (when (and (not description)
9712 (not (string-match (org-image-file-name-regexp) link))
9713 (not (equal link (org-link-escape link))))
9714 (setq description (org-extract-attributes link)))
9715 (setq link
9716 (cond ((string-match (org-image-file-name-regexp) link) link)
9717 ((string-match org-link-types-re link)
9718 (concat (match-string 1 link)
9719 (org-link-escape (substring link (match-end 1)))))
9720 (t (org-link-escape link))))
9721 (concat "[[" link "]"
9722 (if description (concat "[" description "]") "")
9723 "]"))
9725 (defconst org-link-escape-chars
9726 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9727 "List of characters that should be escaped in link.
9728 This is the list that is used for internal purposes.")
9730 (defconst org-link-escape-chars-browser
9731 '(?\ ?\")
9732 "List of escapes for characters that are problematic in links.
9733 This is the list that is used before handing over to the browser.")
9735 (defun org-link-escape (text &optional table merge)
9736 "Return percent escaped representation of TEXT.
9737 TEXT is a string with the text to escape.
9738 Optional argument TABLE is a list with characters that should be
9739 escaped. When nil, `org-link-escape-chars' is used.
9740 If optional argument MERGE is set, merge TABLE into
9741 `org-link-escape-chars'."
9742 (cond
9743 ((and table merge)
9744 (mapc (lambda (defchr)
9745 (unless (member defchr table)
9746 (setq table (cons defchr table)))) org-link-escape-chars))
9747 ((null table)
9748 (setq table org-link-escape-chars)))
9749 (mapconcat
9750 (lambda (char)
9751 (if (or (member char table)
9752 (and (or (< char 32) (= char 37) (> char 126))
9753 org-url-hexify-p))
9754 (mapconcat (lambda (sequence-element)
9755 (format "%%%.2X" sequence-element))
9756 (or (encode-coding-char char 'utf-8)
9757 (error "Unable to percent escape character: %s"
9758 (char-to-string char))) "")
9759 (char-to-string char))) text ""))
9761 (defun org-link-unescape (str)
9762 "Unhex hexified Unicode strings as returned from the JavaScript function
9763 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9764 (unless (and (null str) (string= "" str))
9765 (let ((pos 0) (case-fold-search t) unhexed)
9766 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9767 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9768 (setq str (replace-match unhexed t t str))
9769 (setq pos (+ pos (length unhexed))))))
9770 str)
9772 (defun org-link-unescape-compound (hex)
9773 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9774 Note: this function also decodes single byte encodings like
9775 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9776 (save-match-data
9777 (let* ((bytes (cdr (split-string hex "%")))
9778 (ret "")
9779 (eat 0)
9780 (sum 0))
9781 (while bytes
9782 (let* ((val (string-to-number (pop bytes) 16))
9783 (shift-xor
9784 (if (= 0 eat)
9785 (cond
9786 ((>= val 252) (cons 6 252))
9787 ((>= val 248) (cons 5 248))
9788 ((>= val 240) (cons 4 240))
9789 ((>= val 224) (cons 3 224))
9790 ((>= val 192) (cons 2 192))
9791 (t (cons 0 0)))
9792 (cons 6 128))))
9793 (if (>= val 192) (setq eat (car shift-xor)))
9794 (setq val (logxor val (cdr shift-xor)))
9795 (setq sum (+ (lsh sum (car shift-xor)) val))
9796 (if (> eat 0) (setq eat (- eat 1)))
9797 (cond
9798 ((= 0 eat) ;multi byte
9799 (setq ret (concat ret (org-char-to-string sum)))
9800 (setq sum 0))
9801 ((not bytes) ; single byte(s)
9802 (setq ret (org-link-unescape-single-byte-sequence hex))))
9803 )) ;; end (while bytes
9804 ret )))
9806 (defun org-link-unescape-single-byte-sequence (hex)
9807 "Unhexify hex-encoded single byte character sequences."
9808 (mapconcat (lambda (byte)
9809 (char-to-string (string-to-number byte 16)))
9810 (cdr (split-string hex "%")) ""))
9812 (defun org-xor (a b)
9813 "Exclusive or."
9814 (if a (not b) b))
9816 (defun org-fixup-message-id-for-http (s)
9817 "Replace special characters in a message id, so it can be used in an http query."
9818 (when (string-match "%" s)
9819 (setq s (mapconcat (lambda (c)
9820 (if (eq c ?%)
9821 "%25"
9822 (char-to-string c)))
9823 s "")))
9824 (while (string-match "<" s)
9825 (setq s (replace-match "%3C" t t s)))
9826 (while (string-match ">" s)
9827 (setq s (replace-match "%3E" t t s)))
9828 (while (string-match "@" s)
9829 (setq s (replace-match "%40" t t s)))
9832 (defun org-link-prettify (link)
9833 "Return a human-readable representation of LINK.
9834 The car of LINK must be a raw link the cdr of LINK must be either
9835 a link description or nil."
9836 (let ((desc (or (cadr link) "<no description>")))
9837 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9838 "<" (car link) ">")))
9840 ;;;###autoload
9841 (defun org-insert-link-global ()
9842 "Insert a link like Org-mode does.
9843 This command can be called in any mode to insert a link in Org-mode syntax."
9844 (interactive)
9845 (org-load-modules-maybe)
9846 (org-run-like-in-org-mode 'org-insert-link))
9848 (defun org-insert-all-links (&optional keep)
9849 "Insert all links in `org-stored-links'."
9850 (interactive "P")
9851 (let ((links (copy-sequence org-stored-links)) l)
9852 (while (setq l (if keep (pop links) (pop org-stored-links)))
9853 (insert "- ")
9854 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9855 (insert "\n"))))
9857 (defun org-link-fontify-links-to-this-file ()
9858 "Fontify links to the current file in `org-stored-links'."
9859 (let ((f (buffer-file-name)) a b)
9860 (setq a (mapcar (lambda(l)
9861 (let ((ll (car l)))
9862 (when (and (string-match "^file:\\(.+\\)::" ll)
9863 (equal f (expand-file-name (match-string 1 ll))))
9864 ll)))
9865 org-stored-links))
9866 (when (featurep 'org-id)
9867 (setq b (mapcar (lambda(l)
9868 (let ((ll (car l)))
9869 (when (and (string-match "^id:\\(.+\\)$" ll)
9870 (equal f (expand-file-name
9871 (or (org-id-find-id-file
9872 (match-string 1 ll)) ""))))
9873 ll)))
9874 org-stored-links)))
9875 (mapcar (lambda(l)
9876 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9877 (delq nil (append a b)))))
9879 (defvar org-link-links-in-this-file nil)
9880 (defun org-insert-link (&optional complete-file link-location default-description)
9881 "Insert a link. At the prompt, enter the link.
9883 Completion can be used to insert any of the link protocol prefixes like
9884 http or ftp in use.
9886 The history can be used to select a link previously stored with
9887 `org-store-link'. When the empty string is entered (i.e. if you just
9888 press RET at the prompt), the link defaults to the most recently
9889 stored link. As SPC triggers completion in the minibuffer, you need to
9890 use M-SPC or C-q SPC to force the insertion of a space character.
9892 You will also be prompted for a description, and if one is given, it will
9893 be displayed in the buffer instead of the link.
9895 If there is already a link at point, this command will allow you to edit link
9896 and description parts.
9898 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9899 be selected using completion. The path to the file will be relative to the
9900 current directory if the file is in the current directory or a subdirectory.
9901 Otherwise, the link will be the absolute path as completed in the minibuffer
9902 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9903 option `org-link-file-path-type'.
9905 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9906 the current directory or below.
9908 With three \\[universal-argument] prefixes, negate the meaning of
9909 `org-keep-stored-link-after-insertion'.
9911 If `org-make-link-description-function' is non-nil, this function will be
9912 called with the link target, and the result will be the default
9913 link description.
9915 If the LINK-LOCATION parameter is non-nil, this value will be
9916 used as the link location instead of reading one interactively.
9918 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9919 be used as the default description."
9920 (interactive "P")
9921 (let* ((wcf (current-window-configuration))
9922 (origbuf (current-buffer))
9923 (region (if (org-region-active-p)
9924 (buffer-substring (region-beginning) (region-end))))
9925 (remove (and region (list (region-beginning) (region-end))))
9926 (desc region)
9927 tmphist ; byte-compile incorrectly complains about this
9928 (link link-location)
9929 (abbrevs org-link-abbrev-alist-local)
9930 entry file all-prefixes auto-desc)
9931 (cond
9932 (link-location) ; specified by arg, just use it.
9933 ((org-in-regexp org-bracket-link-regexp 1)
9934 ;; We do have a link at point, and we are going to edit it.
9935 (setq remove (list (match-beginning 0) (match-end 0)))
9936 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9937 (setq link (read-string "Link: "
9938 (org-link-unescape
9939 (org-match-string-no-properties 1)))))
9940 ((or (org-in-regexp org-angle-link-re)
9941 (org-in-regexp org-plain-link-re))
9942 ;; Convert to bracket link
9943 (setq remove (list (match-beginning 0) (match-end 0))
9944 link (read-string "Link: "
9945 (org-remove-angle-brackets (match-string 0)))))
9946 ((member complete-file '((4) (16)))
9947 ;; Completing read for file names.
9948 (setq link (org-file-complete-link complete-file)))
9950 ;; Read link, with completion for stored links.
9951 (org-link-fontify-links-to-this-file)
9952 (org-switch-to-buffer-other-window "*Org Links*")
9953 (with-current-buffer "*Org Links*"
9954 (erase-buffer)
9955 (insert "Insert a link.
9956 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9957 (when org-stored-links
9958 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9959 (insert (mapconcat 'org-link-prettify
9960 (reverse org-stored-links) "\n")))
9961 (goto-char (point-min)))
9962 (let ((cw (selected-window)))
9963 (select-window (get-buffer-window "*Org Links*" 'visible))
9964 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9965 (unless (pos-visible-in-window-p (point-max))
9966 (org-fit-window-to-buffer))
9967 (and (window-live-p cw) (select-window cw)))
9968 ;; Fake a link history, containing the stored links.
9969 (setq tmphist (append (mapcar 'car org-stored-links)
9970 org-insert-link-history))
9971 (setq all-prefixes (append (mapcar 'car abbrevs)
9972 (mapcar 'car org-link-abbrev-alist)
9973 org-link-types))
9974 (unwind-protect
9975 (progn
9976 (setq link
9977 (org-completing-read
9978 "Link: "
9979 (append
9980 (mapcar (lambda (x) (concat x ":"))
9981 all-prefixes)
9982 (mapcar 'car org-stored-links))
9983 nil nil nil
9984 'tmphist
9985 (caar org-stored-links)))
9986 (if (not (string-match "\\S-" link))
9987 (user-error "No link selected"))
9988 (mapc (lambda(l)
9989 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9990 org-stored-links)
9991 (if (or (member link all-prefixes)
9992 (and (equal ":" (substring link -1))
9993 (member (substring link 0 -1) all-prefixes)
9994 (setq link (substring link 0 -1))))
9995 (setq link (with-current-buffer origbuf
9996 (org-link-try-special-completion link)))))
9997 (set-window-configuration wcf)
9998 (kill-buffer "*Org Links*"))
9999 (setq entry (assoc link org-stored-links))
10000 (or entry (push link org-insert-link-history))
10001 (setq desc (or desc (nth 1 entry)))))
10003 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10004 (not org-keep-stored-link-after-insertion))
10005 (setq org-stored-links (delq (assoc link org-stored-links)
10006 org-stored-links)))
10008 (if (string-match org-plain-link-re link)
10009 ;; URL-like link, normalize the use of angular brackets.
10010 (setq link (org-remove-angle-brackets link)))
10012 ;; Check if we are linking to the current file with a search
10013 ;; option If yes, simplify the link by using only the search
10014 ;; option.
10015 (when (and buffer-file-name
10016 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10017 (let* ((path (match-string 1 link))
10018 (case-fold-search nil)
10019 (search (match-string 2 link)))
10020 (save-match-data
10021 (if (equal (file-truename buffer-file-name) (file-truename path))
10022 ;; We are linking to this same file, with a search option
10023 (setq link search)))))
10025 ;; Check if we can/should use a relative path. If yes, simplify the link
10026 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10027 (let* ((type (match-string 1 link))
10028 (path (match-string 2 link))
10029 (origpath path)
10030 (case-fold-search nil))
10031 (cond
10032 ((or (eq org-link-file-path-type 'absolute)
10033 (equal complete-file '(16)))
10034 (setq path (abbreviate-file-name (expand-file-name path))))
10035 ((eq org-link-file-path-type 'noabbrev)
10036 (setq path (expand-file-name path)))
10037 ((eq org-link-file-path-type 'relative)
10038 (setq path (file-relative-name path)))
10040 (save-match-data
10041 (if (string-match (concat "^" (regexp-quote
10042 (expand-file-name
10043 (file-name-as-directory
10044 default-directory))))
10045 (expand-file-name path))
10046 ;; We are linking a file with relative path name.
10047 (setq path (substring (expand-file-name path)
10048 (match-end 0)))
10049 (setq path (abbreviate-file-name (expand-file-name path)))))))
10050 (setq link (concat type path))
10051 (if (equal desc origpath)
10052 (setq desc path))))
10054 (if org-make-link-description-function
10055 (setq desc
10056 (or (condition-case nil
10057 (funcall org-make-link-description-function link desc)
10058 (error (progn (message "Can't get link description from `%s'"
10059 (symbol-name org-make-link-description-function))
10060 (sit-for 2) nil)))
10061 (read-string "Description: " default-description)))
10062 (if default-description (setq desc default-description)
10063 (setq desc (or (and auto-desc desc)
10064 (read-string "Description: " desc)))))
10066 (unless (string-match "\\S-" desc) (setq desc nil))
10067 (if remove (apply 'delete-region remove))
10068 (insert (org-make-link-string link desc))))
10070 (defun org-link-try-special-completion (type)
10071 "If there is completion support for link type TYPE, offer it."
10072 (let ((fun (intern (concat "org-" type "-complete-link"))))
10073 (if (functionp fun)
10074 (funcall fun)
10075 (read-string "Link (no completion support): " (concat type ":")))))
10077 (defun org-file-complete-link (&optional arg)
10078 "Create a file link using completion."
10079 (let (file link)
10080 (setq file (org-iread-file-name "File: "))
10081 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10082 (pwd1 (file-name-as-directory (abbreviate-file-name
10083 (expand-file-name ".")))))
10084 (cond
10085 ((equal arg '(16))
10086 (setq link (concat
10087 "file:"
10088 (abbreviate-file-name (expand-file-name file)))))
10089 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10090 (setq link (concat "file:" (match-string 1 file))))
10091 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10092 (expand-file-name file))
10093 (setq link (concat
10094 "file:" (match-string 1 (expand-file-name file)))))
10095 (t (setq link (concat "file:" file)))))
10096 link))
10098 (defun org-iread-file-name (&rest args)
10099 "Read-file-name using `ido-mode' speedup if available.
10100 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10101 See `read-file-name' for a description of parameters."
10102 (org-without-partial-completion
10103 (if (and org-completion-use-ido
10104 (fboundp 'ido-read-file-name)
10105 (boundp 'ido-mode) ido-mode
10106 (listp (second args)))
10107 (let ((ido-enter-matching-directory nil))
10108 (apply 'ido-read-file-name args))
10109 (apply 'read-file-name args))))
10111 (defun org-completing-read (&rest args)
10112 "Completing-read with SPACE being a normal character."
10113 (let ((enable-recursive-minibuffers t)
10114 (minibuffer-local-completion-map
10115 (copy-keymap minibuffer-local-completion-map)))
10116 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10117 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10118 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10119 (apply 'org-icompleting-read args)))
10121 (defun org-completing-read-no-i (&rest args)
10122 (let (org-completion-use-ido org-completion-use-iswitchb)
10123 (apply 'org-completing-read args)))
10125 (defun org-iswitchb-completing-read (prompt choices &rest args)
10126 "Use iswitch as a completing-read replacement to choose from choices.
10127 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10128 from."
10129 (let* ((iswitchb-use-virtual-buffers nil)
10130 (iswitchb-make-buflist-hook
10131 (lambda ()
10132 (setq iswitchb-temp-buflist choices))))
10133 (iswitchb-read-buffer prompt)))
10135 (defun org-icompleting-read (&rest args)
10136 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10137 (org-without-partial-completion
10138 (if (and org-completion-use-ido
10139 (fboundp 'ido-completing-read)
10140 (boundp 'ido-mode) ido-mode
10141 (listp (second args)))
10142 (let ((ido-enter-matching-directory nil))
10143 (apply 'ido-completing-read (concat (car args))
10144 (if (consp (car (nth 1 args)))
10145 (mapcar 'car (nth 1 args))
10146 (nth 1 args))
10147 (cddr args)))
10148 (if (and org-completion-use-iswitchb
10149 (boundp 'iswitchb-mode) iswitchb-mode
10150 (listp (second args)))
10151 (apply 'org-iswitchb-completing-read (concat (car args))
10152 (if (consp (car (nth 1 args)))
10153 (mapcar 'car (nth 1 args))
10154 (nth 1 args))
10155 (cddr args))
10156 (apply 'completing-read args)))))
10158 (defun org-extract-attributes (s)
10159 "Extract the attributes cookie from a string and set as text property."
10160 (let (a attr (start 0) key value)
10161 (save-match-data
10162 (when (string-match "{{\\([^}]+\\)}}$" s)
10163 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10164 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10165 (setq key (match-string 1 a) value (match-string 2 a)
10166 start (match-end 0)
10167 attr (plist-put attr (intern key) value))))
10168 (org-add-props s nil 'org-attr attr))
10171 ;;; Opening/following a link
10173 (defvar org-link-search-failed nil)
10175 (defvar org-open-link-functions nil
10176 "Hook for functions finding a plain text link.
10177 These functions must take a single argument, the link content.
10178 They will be called for links that look like [[link text][description]]
10179 when LINK TEXT does not have a protocol like \"http:\" and does not look
10180 like a filename (e.g. \"./blue.png\").
10182 These functions will be called *before* Org attempts to resolve the
10183 link by doing text searches in the current buffer - so if you want a
10184 link \"[[target]]\" to still find \"<<target>>\", your function should
10185 handle this as a special case.
10187 When the function does handle the link, it must return a non-nil value.
10188 If it decides that it is not responsible for this link, it must return
10189 nil to indicate that that Org-mode can continue with other options
10190 like exact and fuzzy text search.")
10192 (defun org-next-link (&optional search-backward)
10193 "Move forward to the next link.
10194 If the link is in hidden text, expose it."
10195 (interactive "P")
10196 (when (and org-link-search-failed (eq this-command last-command))
10197 (goto-char (point-min))
10198 (message "Link search wrapped back to beginning of buffer"))
10199 (setq org-link-search-failed nil)
10200 (let* ((pos (point))
10201 (ct (org-context))
10202 (a (assoc :link ct))
10203 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10204 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10205 ((looking-at org-any-link-re)
10206 ;; Don't stay stuck at link without an org-link face
10207 (forward-char (if search-backward -1 1))))
10208 (if (funcall srch-fun org-any-link-re nil t)
10209 (progn
10210 (goto-char (match-beginning 0))
10211 (if (outline-invisible-p) (org-show-context)))
10212 (goto-char pos)
10213 (setq org-link-search-failed t)
10214 (message "No further link found"))))
10216 (defun org-previous-link ()
10217 "Move backward to the previous link.
10218 If the link is in hidden text, expose it."
10219 (interactive)
10220 (funcall 'org-next-link t))
10222 (defun org-translate-link (s)
10223 "Translate a link string if a translation function has been defined."
10224 (if (and org-link-translation-function
10225 (fboundp org-link-translation-function)
10226 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10227 (progn
10228 (setq s (funcall org-link-translation-function
10229 (match-string 1 s) (match-string 2 s)))
10230 (concat (car s) ":" (cdr s)))
10233 (defun org-translate-link-from-planner (type path)
10234 "Translate a link from Emacs Planner syntax so that Org can follow it.
10235 This is still an experimental function, your mileage may vary."
10236 (cond
10237 ((member type '("http" "https" "news" "ftp"))
10238 ;; standard Internet links are the same.
10239 nil)
10240 ((and (equal type "irc") (string-match "^//" path))
10241 ;; Planner has two / at the beginning of an irc link, we have 1.
10242 ;; We should have zero, actually....
10243 (setq path (substring path 1)))
10244 ((and (equal type "lisp") (string-match "^/" path))
10245 ;; Planner has a slash, we do not.
10246 (setq type "elisp" path (substring path 1)))
10247 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10248 ;; A typical message link. Planner has the id after the final slash,
10249 ;; we separate it with a hash mark
10250 (setq path (concat (match-string 1 path) "#"
10251 (org-remove-angle-brackets (match-string 2 path))))))
10252 (cons type path))
10254 (defun org-find-file-at-mouse (ev)
10255 "Open file link or URL at mouse."
10256 (interactive "e")
10257 (mouse-set-point ev)
10258 (org-open-at-point 'in-emacs))
10260 (defun org-open-at-mouse (ev)
10261 "Open file link or URL at mouse.
10262 See the docstring of `org-open-file' for details."
10263 (interactive "e")
10264 (mouse-set-point ev)
10265 (if (eq major-mode 'org-agenda-mode)
10266 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10267 (org-open-at-point))
10269 (defvar org-window-config-before-follow-link nil
10270 "The window configuration before following a link.
10271 This is saved in case the need arises to restore it.")
10273 (defvar org-open-link-marker (make-marker)
10274 "Marker pointing to the location where `org-open-at-point; was called.")
10276 ;;;###autoload
10277 (defun org-open-at-point-global ()
10278 "Follow a link like Org-mode does.
10279 This command can be called in any mode to follow a link that has
10280 Org-mode syntax."
10281 (interactive)
10282 (org-run-like-in-org-mode 'org-open-at-point))
10284 ;;;###autoload
10285 (defun org-open-link-from-string (s &optional arg reference-buffer)
10286 "Open a link in the string S, as if it was in Org-mode."
10287 (interactive "sLink: \nP")
10288 (let ((reference-buffer (or reference-buffer (current-buffer))))
10289 (with-temp-buffer
10290 (let ((org-inhibit-startup (not reference-buffer)))
10291 (org-mode)
10292 (insert s)
10293 (goto-char (point-min))
10294 (when reference-buffer
10295 (setq org-link-abbrev-alist-local
10296 (with-current-buffer reference-buffer
10297 org-link-abbrev-alist-local)))
10298 (org-open-at-point arg reference-buffer)))))
10300 (defvar org-open-at-point-functions nil
10301 "Hook that is run when following a link at point.
10303 Functions in this hook must return t if they identify and follow
10304 a link at point. If they don't find anything interesting at point,
10305 they must return nil.")
10307 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10308 (defun org-open-at-point (&optional arg reference-buffer)
10309 "Open link at or after point.
10310 If there is no link at point, this function will search forward up to
10311 the end of the current line.
10312 Normally, files will be opened by an appropriate application. If the
10313 optional prefix argument ARG is non-nil, Emacs will visit the file.
10314 With a double prefix argument, try to open outside of Emacs, in the
10315 application the system uses for this file type."
10316 (interactive "P")
10317 ;; if in a code block, then open the block's results
10318 (unless (call-interactively #'org-babel-open-src-block-result)
10319 (org-load-modules-maybe)
10320 (move-marker org-open-link-marker (point))
10321 (setq org-window-config-before-follow-link (current-window-configuration))
10322 (org-remove-occur-highlights nil nil t)
10323 (cond
10324 ((and (org-at-heading-p)
10325 (not (org-at-timestamp-p t))
10326 (not (org-in-regexp
10327 (concat org-plain-link-re "\\|"
10328 org-bracket-link-regexp "\\|"
10329 org-angle-link-re "\\|"
10330 "[ \t]:[^ \t\n]+:[ \t]*$")))
10331 (not (get-text-property (point) 'org-linked-text)))
10332 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10333 (lk0 (car lkall))
10334 (lk (if (stringp lk0) (list lk0) lk0))
10335 (lkend (cdr lkall)))
10336 (mapcar (lambda(l)
10337 (search-forward l nil lkend)
10338 (goto-char (match-beginning 0))
10339 (org-open-at-point))
10340 lk))
10341 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10342 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10343 ((and (org-at-timestamp-p t)
10344 (not (org-in-regexp org-bracket-link-regexp)))
10345 (org-follow-timestamp-link))
10346 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10347 (not (org-in-regexp org-any-link-re)))
10348 (org-footnote-action))
10350 (let (type path link line search (pos (point)))
10351 (catch 'match
10352 (save-excursion
10353 (skip-chars-forward "^]\n\r")
10354 (when (org-in-regexp org-bracket-link-regexp 1)
10355 (setq link (org-extract-attributes
10356 (org-link-unescape (org-match-string-no-properties 1))))
10357 (while (string-match " *\n *" link)
10358 (setq link (replace-match " " t t link)))
10359 (setq link (org-link-expand-abbrev link))
10360 (cond
10361 ((or (file-name-absolute-p link)
10362 (string-match "^\\.\\.?/" link))
10363 (setq type "file" path link))
10364 ((string-match org-link-re-with-space3 link)
10365 (setq type (match-string 1 link) path (match-string 2 link)))
10366 ((string-match "^help:+\\(.+\\)" link)
10367 (setq type "help" path (match-string 1 link)))
10368 (t (setq type "thisfile" path link)))
10369 (throw 'match t)))
10371 (when (get-text-property (point) 'org-linked-text)
10372 (setq type "thisfile"
10373 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10374 (1+ (point)) (point))
10375 path (buffer-substring
10376 (or (previous-single-property-change pos 'org-linked-text)
10377 (point-min))
10378 (or (next-single-property-change pos 'org-linked-text)
10379 (point-max)))
10380 ;; Ensure we will search for a <<<radio>>> link, not
10381 ;; a simple reference like <<ref>>
10382 path (concat "<" path))
10383 (throw 'match t))
10385 (save-excursion
10386 (when (or (org-in-regexp org-angle-link-re)
10387 (let ((match (org-in-regexp org-plain-link-re)))
10388 ;; Check a plain link is not within a bracket link
10389 (and match
10390 (save-excursion
10391 (progn
10392 (goto-char (car match))
10393 (not (org-in-regexp org-bracket-link-regexp))))))
10394 (let ((line_ending (save-excursion (end-of-line) (point))))
10395 ;; We are in a line before a plain or bracket link
10396 (or (re-search-forward org-plain-link-re line_ending t)
10397 (re-search-forward org-bracket-link-regexp line_ending t))))
10398 (setq type (match-string 1)
10399 path (org-link-unescape (match-string 2)))
10400 (throw 'match t)))
10401 (save-excursion
10402 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10403 (setq type "tags"
10404 path (match-string 1))
10405 (while (string-match ":" path)
10406 (setq path (replace-match "+" t t path)))
10407 (throw 'match t)))
10408 (when (org-in-regexp "<\\([^><\n]+\\)>")
10409 (setq type "tree-match"
10410 path (match-string 1))
10411 (throw 'match t)))
10412 (unless path
10413 (user-error "No link found"))
10415 ;; switch back to reference buffer
10416 ;; needed when if called in a temporary buffer through
10417 ;; org-open-link-from-string
10418 (with-current-buffer (or reference-buffer (current-buffer))
10420 ;; Remove any trailing spaces in path
10421 (if (string-match " +\\'" path)
10422 (setq path (replace-match "" t t path)))
10423 (if (and org-link-translation-function
10424 (fboundp org-link-translation-function))
10425 ;; Check if we need to translate the link
10426 (let ((tmp (funcall org-link-translation-function type path)))
10427 (setq type (car tmp) path (cdr tmp))))
10429 (cond
10431 ((assoc type org-link-protocols)
10432 (funcall (nth 1 (assoc type org-link-protocols)) path))
10434 ((equal type "help")
10435 (let ((f-or-v (intern path)))
10436 (cond ((fboundp f-or-v)
10437 (describe-function f-or-v))
10438 ((boundp f-or-v)
10439 (describe-variable f-or-v))
10440 (t (error "Not a known function or variable")))))
10442 ((equal type "mailto")
10443 (let ((cmd (car org-link-mailto-program))
10444 (args (cdr org-link-mailto-program)) args1
10445 (address path) (subject "") a)
10446 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10447 (setq address (match-string 1 path)
10448 subject (org-link-escape (match-string 2 path))))
10449 (while args
10450 (cond
10451 ((not (stringp (car args))) (push (pop args) args1))
10452 (t (setq a (pop args))
10453 (if (string-match "%a" a)
10454 (setq a (replace-match address t t a)))
10455 (if (string-match "%s" a)
10456 (setq a (replace-match subject t t a)))
10457 (push a args1))))
10458 (apply cmd (nreverse args1))))
10460 ((member type '("http" "https" "ftp" "news"))
10461 (browse-url
10462 (concat type ":"
10463 (if (org-string-match-p
10464 (concat "[[:nonascii:]"
10465 org-link-escape-chars-browser "]")
10466 path)
10467 (org-link-escape path org-link-escape-chars-browser)
10468 path))))
10470 ((string= type "doi")
10471 (browse-url
10472 (concat org-doi-server-url
10473 (if (org-string-match-p
10474 (concat "[[:nonascii:]"
10475 org-link-escape-chars-browser "]")
10476 path)
10477 (org-link-escape path org-link-escape-chars-browser)
10478 path))))
10480 ((member type '("message"))
10481 (browse-url (concat type ":" path)))
10483 ((string= type "tags")
10484 (org-tags-view arg path))
10486 ((string= type "tree-match")
10487 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10489 ((string= type "file")
10490 (if (string-match "::\\([0-9]+\\)\\'" path)
10491 (setq line (string-to-number (match-string 1 path))
10492 path (substring path 0 (match-beginning 0)))
10493 (if (string-match "::\\(.+\\)\\'" path)
10494 (setq search (match-string 1 path)
10495 path (substring path 0 (match-beginning 0)))))
10496 (if (string-match "[*?{]" (file-name-nondirectory path))
10497 (dired path)
10498 (org-open-file path arg line search)))
10500 ((string= type "shell")
10501 (let ((buf (generate-new-buffer "*Org Shell Output"))
10502 (cmd path))
10503 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10504 (string-match org-confirm-shell-link-not-regexp cmd))
10505 (not org-confirm-shell-link-function)
10506 (funcall org-confirm-shell-link-function
10507 (format "Execute \"%s\" in shell? "
10508 (org-add-props cmd nil
10509 'face 'org-warning))))
10510 (progn
10511 (message "Executing %s" cmd)
10512 (shell-command cmd buf)
10513 (if (featurep 'midnight)
10514 (setq clean-buffer-list-kill-buffer-names
10515 (cons buf clean-buffer-list-kill-buffer-names))))
10516 (error "Abort"))))
10518 ((string= type "elisp")
10519 (let ((cmd path))
10520 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10521 (string-match org-confirm-elisp-link-not-regexp cmd))
10522 (not org-confirm-elisp-link-function)
10523 (funcall org-confirm-elisp-link-function
10524 (format "Execute \"%s\" as elisp? "
10525 (org-add-props cmd nil
10526 'face 'org-warning))))
10527 (message "%s => %s" cmd
10528 (if (equal (string-to-char cmd) ?\()
10529 (eval (read cmd))
10530 (call-interactively (read cmd))))
10531 (error "Abort"))))
10533 ((and (string= type "thisfile")
10534 (run-hook-with-args-until-success
10535 'org-open-link-functions path)))
10537 ((string= type "thisfile")
10538 (if arg
10539 (switch-to-buffer-other-window
10540 (org-get-buffer-for-internal-link (current-buffer)))
10541 (org-mark-ring-push))
10542 (let ((cmd `(org-link-search
10543 ,path
10544 ,(cond ((equal arg '(4)) ''occur)
10545 ((equal arg '(16)) ''org-occur))
10546 ,pos)))
10547 (condition-case nil (let ((org-link-search-inhibit-query t))
10548 (eval cmd))
10549 (error (progn (widen) (eval cmd))))))
10551 (t (browse-url-at-point)))))))
10552 (move-marker org-open-link-marker nil)
10553 (run-hook-with-args 'org-follow-link-hook)))
10555 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10556 "Offer links in the current entry and return the selected link.
10557 If there is only one link, return it.
10558 If NTH is an integer, return the NTH link found.
10559 If ZERO is a string, check also this string for a link, and if
10560 there is one, return it."
10561 (with-current-buffer buffer
10562 (save-excursion
10563 (save-restriction
10564 (widen)
10565 (goto-char marker)
10566 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10567 "\\(" org-angle-link-re "\\)\\|"
10568 "\\(" org-plain-link-re "\\)"))
10569 (cnt ?0)
10570 (in-emacs (if (integerp nth) nil nth))
10571 have-zero end links link c)
10572 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10573 (push (match-string 0 zero) links)
10574 (setq cnt (1- cnt) have-zero t))
10575 (save-excursion
10576 (org-back-to-heading t)
10577 (setq end (save-excursion (outline-next-heading) (point)))
10578 (while (re-search-forward re end t)
10579 (push (match-string 0) links))
10580 (setq links (org-uniquify (reverse links))))
10581 (cond
10582 ((null links)
10583 (message "No links"))
10584 ((equal (length links) 1)
10585 (setq link (car links)))
10586 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10587 (setq link (nth (if have-zero nth (1- nth)) links)))
10588 (t ; we have to select a link
10589 (save-excursion
10590 (save-window-excursion
10591 (delete-other-windows)
10592 (with-output-to-temp-buffer "*Select Link*"
10593 (mapc (lambda (l)
10594 (if (not (string-match org-bracket-link-regexp l))
10595 (princ (format "[%c] %s\n" (incf cnt)
10596 (org-remove-angle-brackets l)))
10597 (if (match-end 3)
10598 (princ (format "[%c] %s (%s)\n" (incf cnt)
10599 (match-string 3 l) (match-string 1 l)))
10600 (princ (format "[%c] %s\n" (incf cnt)
10601 (match-string 1 l))))))
10602 links))
10603 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10604 (message "Select link to open, RET to open all:")
10605 (setq c (read-char-exclusive))
10606 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10607 (when (equal c ?q) (error "Abort"))
10608 (if (equal c ?\C-m)
10609 (setq link links)
10610 (setq nth (- c ?0))
10611 (if have-zero (setq nth (1+ nth)))
10612 (unless (and (integerp nth) (>= (length links) nth))
10613 (user-error "Invalid link selection"))
10614 (setq link (nth (1- nth) links)))))
10615 (cons link end))))))
10617 ;; Add special file links that specify the way of opening
10619 (org-add-link-type "file+sys" 'org-open-file-with-system)
10620 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10621 (defun org-open-file-with-system (path)
10622 "Open file at PATH using the system way of opening it."
10623 (org-open-file path 'system))
10624 (defun org-open-file-with-emacs (path)
10625 "Open file at PATH in Emacs."
10626 (org-open-file path 'emacs))
10629 ;;; File search
10631 (defvar org-create-file-search-functions nil
10632 "List of functions to construct the right search string for a file link.
10633 These functions are called in turn with point at the location to
10634 which the link should point.
10636 A function in the hook should first test if it would like to
10637 handle this file type, for example by checking the `major-mode'
10638 or the file extension. If it decides not to handle this file, it
10639 should just return nil to give other functions a chance. If it
10640 does handle the file, it must return the search string to be used
10641 when following the link. The search string will be part of the
10642 file link, given after a double colon, and `org-open-at-point'
10643 will automatically search for it. If special measures must be
10644 taken to make the search successful, another function should be
10645 added to the companion hook `org-execute-file-search-functions',
10646 which see.
10648 A function in this hook may also use `setq' to set the variable
10649 `description' to provide a suggestion for the descriptive text to
10650 be used for this link when it gets inserted into an Org-mode
10651 buffer with \\[org-insert-link].")
10653 (defvar org-execute-file-search-functions nil
10654 "List of functions to execute a file search triggered by a link.
10656 Functions added to this hook must accept a single argument, the
10657 search string that was part of the file link, the part after the
10658 double colon. The function must first check if it would like to
10659 handle this search, for example by checking the `major-mode' or
10660 the file extension. If it decides not to handle this search, it
10661 should just return nil to give other functions a chance. If it
10662 does handle the search, it must return a non-nil value to keep
10663 other functions from trying.
10665 Each function can access the current prefix argument through the
10666 variable `current-prefix-arg'. Note that a single prefix is used
10667 to force opening a link in Emacs, so it may be good to only use a
10668 numeric or double prefix to guide the search function.
10670 In case this is needed, a function in this hook can also restore
10671 the window configuration before `org-open-at-point' was called using:
10673 (set-window-configuration org-window-config-before-follow-link)")
10675 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10676 (defun org-link-search (s &optional type avoid-pos stealth)
10677 "Search for a link search option.
10678 If S is surrounded by forward slashes, it is interpreted as a
10679 regular expression. In org-mode files, this will create an `org-occur'
10680 sparse tree. In ordinary files, `occur' will be used to list matches.
10681 If the current buffer is in `dired-mode', grep will be used to search
10682 in all files. If AVOID-POS is given, ignore matches near that position.
10684 When optional argument STEALTH is non-nil, do not modify
10685 visibility around point, thus ignoring
10686 `org-show-hierarchy-above', `org-show-following-heading' and
10687 `org-show-siblings' variables."
10688 (let ((case-fold-search t)
10689 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10690 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10691 (append '(("") (" ") ("\t") ("\n"))
10692 org-emphasis-alist)
10693 "\\|") "\\)"))
10694 (pos (point))
10695 (pre nil) (post nil)
10696 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10697 (cond
10698 ;; First check if there are any special search functions
10699 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10700 ;; Now try the builtin stuff
10701 ((and (equal (string-to-char s0) ?#)
10702 (> (length s0) 1)
10703 (save-excursion
10704 (goto-char (point-min))
10705 (and
10706 (re-search-forward
10707 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10708 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10709 (setq type 'dedicated
10710 pos (match-beginning 0))))
10711 ;; There is an exact target for this
10712 (goto-char pos)
10713 (org-back-to-heading t)))
10714 ((save-excursion
10715 (goto-char (point-min))
10716 (and
10717 (re-search-forward
10718 (concat "<<" (regexp-quote s0) ">>") nil t)
10719 (setq type 'dedicated
10720 pos (match-beginning 0))))
10721 ;; There is an exact target for this
10722 (goto-char pos))
10723 ((save-excursion
10724 (goto-char (point-min))
10725 (and
10726 (re-search-forward
10727 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10728 (setq type 'dedicated pos (match-beginning 0))))
10729 ;; Found an element with a matching #+name affiliated keyword.
10730 (goto-char pos))
10731 ((and (string-match "^(\\(.*\\))$" s0)
10732 (save-excursion
10733 (goto-char (point-min))
10734 (and
10735 (re-search-forward
10736 (concat "[^[]" (regexp-quote
10737 (format org-coderef-label-format
10738 (match-string 1 s0))))
10739 nil t)
10740 (setq type 'dedicated
10741 pos (1+ (match-beginning 0))))))
10742 ;; There is a coderef target for this
10743 (goto-char pos))
10744 ((string-match "^/\\(.*\\)/$" s)
10745 ;; A regular expression
10746 (cond
10747 ((derived-mode-p 'org-mode)
10748 (org-occur (match-string 1 s)))
10749 (t (org-do-occur (match-string 1 s)))))
10750 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10751 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10752 (goto-char (point-min))
10753 (cond
10754 ((let (case-fold-search)
10755 (re-search-forward (format org-complex-heading-regexp-format
10756 (regexp-quote s))
10757 nil t))
10758 ;; OK, found a match
10759 (setq type 'dedicated)
10760 (goto-char (match-beginning 0)))
10761 ((and (not org-link-search-inhibit-query)
10762 (eq org-link-search-must-match-exact-headline 'query-to-create)
10763 (y-or-n-p "No match - create this as a new heading? "))
10764 (goto-char (point-max))
10765 (or (bolp) (newline))
10766 (insert "* " s "\n")
10767 (beginning-of-line 0))
10769 (goto-char pos)
10770 (error "No match"))))
10772 ;; A normal search string
10773 (when (equal (string-to-char s) ?*)
10774 ;; Anchor on headlines, post may include tags.
10775 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10776 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10777 s (substring s 1)))
10778 (remove-text-properties
10779 0 (length s)
10780 '(face nil mouse-face nil keymap nil fontified nil) s)
10781 ;; Make a series of regular expressions to find a match
10782 (setq words (org-split-string s "[ \n\r\t]+")
10784 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10785 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10786 "\\)" markers)
10787 re2a_ (concat "\\(" (mapconcat 'downcase words
10788 "[ \t\r\n]+") "\\)[ \t\r\n]")
10789 re2a (concat "[ \t\r\n]" re2a_)
10790 re4_ (concat "\\(" (mapconcat 'downcase words
10791 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10792 re4 (concat "[^a-zA-Z_]" re4_)
10794 re1 (concat pre re2 post)
10795 re3 (concat pre (if pre re4_ re4) post)
10796 re5 (concat pre ".*" re4)
10797 re2 (concat pre re2)
10798 re2a (concat pre (if pre re2a_ re2a))
10799 re4 (concat pre (if pre re4_ re4))
10800 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10801 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10802 re5 "\\)"))
10803 (cond
10804 ((eq type 'org-occur) (org-occur reall))
10805 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10806 (t (goto-char (point-min))
10807 (setq type 'fuzzy)
10808 (if (or (and (org-search-not-self 1 re0 nil t)
10809 (setq type 'dedicated))
10810 (org-search-not-self 1 re1 nil t)
10811 (org-search-not-self 1 re2 nil t)
10812 (org-search-not-self 1 re2a nil t)
10813 (org-search-not-self 1 re3 nil t)
10814 (org-search-not-self 1 re4 nil t)
10815 (org-search-not-self 1 re5 nil t))
10816 (goto-char (match-beginning 1))
10817 (goto-char pos)
10818 (error "No match"))))))
10819 (and (derived-mode-p 'org-mode)
10820 (not stealth)
10821 (org-show-context 'link-search))
10822 type))
10824 (defun org-search-not-self (group &rest args)
10825 "Execute `re-search-forward', but only accept matches that do not
10826 enclose the position of `org-open-link-marker'."
10827 (let ((m org-open-link-marker))
10828 (catch 'exit
10829 (while (apply 're-search-forward args)
10830 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10831 (goto-char (match-end group))
10832 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10833 (> (match-beginning 0) (marker-position m))
10834 (< (match-end 0) (marker-position m)))
10835 (save-match-data
10836 (or (not (org-in-regexp
10837 org-bracket-link-analytic-regexp 1))
10838 (not (match-end 4)) ; no description
10839 (and (<= (match-beginning 4) (point))
10840 (>= (match-end 4) (point))))))
10841 (throw 'exit (point))))))))
10843 (defun org-get-buffer-for-internal-link (buffer)
10844 "Return a buffer to be used for displaying the link target of internal links."
10845 (cond
10846 ((not org-display-internal-link-with-indirect-buffer)
10847 buffer)
10848 ((string-match "(Clone)$" (buffer-name buffer))
10849 (message "Buffer is already a clone, not making another one")
10850 ;; we also do not modify visibility in this case
10851 buffer)
10852 (t ; make a new indirect buffer for displaying the link
10853 (let* ((bn (buffer-name buffer))
10854 (ibn (concat bn "(Clone)"))
10855 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10856 (with-current-buffer ib (org-overview))
10857 ib))))
10859 (defun org-do-occur (regexp &optional cleanup)
10860 "Call the Emacs command `occur'.
10861 If CLEANUP is non-nil, remove the printout of the regular expression
10862 in the *Occur* buffer. This is useful if the regex is long and not useful
10863 to read."
10864 (occur regexp)
10865 (when cleanup
10866 (let ((cwin (selected-window)) win beg end)
10867 (when (setq win (get-buffer-window "*Occur*"))
10868 (select-window win))
10869 (goto-char (point-min))
10870 (when (re-search-forward "match[a-z]+" nil t)
10871 (setq beg (match-end 0))
10872 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10873 (setq end (1- (match-beginning 0)))))
10874 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10875 (goto-char (point-min))
10876 (select-window cwin))))
10878 ;;; The mark ring for links jumps
10880 (defvar org-mark-ring nil
10881 "Mark ring for positions before jumps in Org-mode.")
10882 (defvar org-mark-ring-last-goto nil
10883 "Last position in the mark ring used to go back.")
10884 ;; Fill and close the ring
10885 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10886 (loop for i from 1 to org-mark-ring-length do
10887 (push (make-marker) org-mark-ring))
10888 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10889 org-mark-ring)
10891 (defun org-mark-ring-push (&optional pos buffer)
10892 "Put the current position or POS into the mark ring and rotate it."
10893 (interactive)
10894 (setq pos (or pos (point)))
10895 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10896 (move-marker (car org-mark-ring)
10897 (or pos (point))
10898 (or buffer (current-buffer)))
10899 (message "%s"
10900 (substitute-command-keys
10901 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10903 (defun org-mark-ring-goto (&optional n)
10904 "Jump to the previous position in the mark ring.
10905 With prefix arg N, jump back that many stored positions. When
10906 called several times in succession, walk through the entire ring.
10907 Org-mode commands jumping to a different position in the current file,
10908 or to another Org-mode file, automatically push the old position
10909 onto the ring."
10910 (interactive "p")
10911 (let (p m)
10912 (if (eq last-command this-command)
10913 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10914 (setq p org-mark-ring))
10915 (setq org-mark-ring-last-goto p)
10916 (setq m (car p))
10917 (org-pop-to-buffer-same-window (marker-buffer m))
10918 (goto-char m)
10919 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10921 (defun org-remove-angle-brackets (s)
10922 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10923 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10925 (defun org-add-angle-brackets (s)
10926 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10927 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10929 (defun org-remove-double-quotes (s)
10930 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10931 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10934 ;;; Following specific links
10936 (defun org-follow-timestamp-link ()
10937 "Open an agenda view for the time-stamp date/range at point."
10938 (cond
10939 ((org-at-date-range-p t)
10940 (let ((org-agenda-start-on-weekday)
10941 (t1 (match-string 1))
10942 (t2 (match-string 2)) tt1 tt2)
10943 (setq tt1 (time-to-days (org-time-string-to-time t1))
10944 tt2 (time-to-days (org-time-string-to-time t2)))
10945 (let ((org-agenda-buffer-tmp-name
10946 (format "*Org Agenda(a:%s)"
10947 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10948 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10949 ((org-at-timestamp-p t)
10950 (let ((org-agenda-buffer-tmp-name
10951 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10952 (org-agenda-list nil (time-to-days (org-time-string-to-time
10953 (substring (match-string 1) 0 10)))
10954 1)))
10955 (t (error "This should not happen"))))
10958 ;;; Following file links
10959 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10960 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10961 (declare-function mailcap-mime-info
10962 "mailcap" (string &optional request no-decode))
10963 (defvar org-wait nil)
10964 (defun org-open-file (path &optional in-emacs line search)
10965 "Open the file at PATH.
10966 First, this expands any special file name abbreviations. Then the
10967 configuration variable `org-file-apps' is checked if it contains an
10968 entry for this file type, and if yes, the corresponding command is launched.
10970 If no application is found, Emacs simply visits the file.
10972 With optional prefix argument IN-EMACS, Emacs will visit the file.
10973 With a double \\[universal-argument] \\[universal-argument] \
10974 prefix arg, Org tries to avoid opening in Emacs
10975 and to use an external application to visit the file.
10977 Optional LINE specifies a line to go to, optional SEARCH a string
10978 to search for. If LINE or SEARCH is given, the file will be
10979 opened in Emacs, unless an entry from org-file-apps that makes
10980 use of groups in a regexp matches.
10982 If you want to change the way frames are used when following a
10983 link, please customize `org-link-frame-setup'.
10985 If the file does not exist, an error is thrown."
10986 (let* ((file (if (equal path "")
10987 buffer-file-name
10988 (substitute-in-file-name (expand-file-name path))))
10989 (file-apps (append org-file-apps (org-default-apps)))
10990 (apps (org-remove-if
10991 'org-file-apps-entry-match-against-dlink-p file-apps))
10992 (apps-dlink (org-remove-if-not
10993 'org-file-apps-entry-match-against-dlink-p file-apps))
10994 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10995 (dirp (if remp nil (file-directory-p file)))
10996 (file (if (and dirp org-open-directory-means-index-dot-org)
10997 (concat (file-name-as-directory file) "index.org")
10998 file))
10999 (a-m-a-p (assq 'auto-mode apps))
11000 (dfile (downcase file))
11001 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11002 (link (cond ((and (eq line nil)
11003 (eq search nil))
11004 file)
11005 (line
11006 (concat file "::" (number-to-string line)))
11007 (search
11008 (concat file "::" search))))
11009 (dlink (downcase link))
11010 (old-buffer (current-buffer))
11011 (old-pos (point))
11012 (old-mode major-mode)
11013 ext cmd link-match-data)
11014 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11015 (setq ext (match-string 1 dfile))
11016 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11017 (setq ext (match-string 1 dfile))))
11018 (cond
11019 ((member in-emacs '((16) system))
11020 (setq cmd (cdr (assoc 'system apps))))
11021 (in-emacs (setq cmd 'emacs))
11023 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11024 (and dirp (cdr (assoc 'directory apps)))
11025 ; first, try matching against apps-dlink
11026 ; if we get a match here, store the match data for later
11027 (let ((match (assoc-default dlink apps-dlink
11028 'string-match)))
11029 (if match
11030 (progn (setq link-match-data (match-data))
11031 match)
11032 (progn (setq in-emacs (or in-emacs line search))
11033 nil))) ; if we have no match in apps-dlink,
11034 ; always open the file in emacs if line or search
11035 ; is given (for backwards compatibility)
11036 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11037 'string-match)
11038 (cdr (assoc ext apps))
11039 (cdr (assoc t apps))))))
11040 (when (eq cmd 'system)
11041 (setq cmd (cdr (assoc 'system apps))))
11042 (when (eq cmd 'default)
11043 (setq cmd (cdr (assoc t apps))))
11044 (when (eq cmd 'mailcap)
11045 (require 'mailcap)
11046 (mailcap-parse-mailcaps)
11047 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11048 (command (mailcap-mime-info mime-type)))
11049 (if (stringp command)
11050 (setq cmd command)
11051 (setq cmd 'emacs))))
11052 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11053 (not (file-exists-p file))
11054 (not org-open-non-existing-files))
11055 (user-error "No such file: %s" file))
11056 (cond
11057 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11058 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11059 (while (string-match "['\"]%s['\"]" cmd)
11060 (setq cmd (replace-match "%s" t t cmd)))
11061 (while (string-match "%s" cmd)
11062 (setq cmd (replace-match
11063 (save-match-data
11064 (shell-quote-argument
11065 (convert-standard-filename file)))
11066 t t cmd)))
11068 ;; Replace "%1", "%2" etc. in command with group matches from regex
11069 (save-match-data
11070 (let ((match-index 1)
11071 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11072 (set-match-data link-match-data)
11073 (while (<= match-index number-of-groups)
11074 (let ((regex (concat "%" (number-to-string match-index)))
11075 (replace-with (match-string match-index dlink)))
11076 (while (string-match regex cmd)
11077 (setq cmd (replace-match replace-with t t cmd))))
11078 (setq match-index (+ match-index 1)))))
11080 (save-window-excursion
11081 (message "Running %s...done" cmd)
11082 (start-process-shell-command cmd nil cmd)
11083 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11084 ((or (stringp cmd)
11085 (eq cmd 'emacs))
11086 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11087 (widen)
11088 (if line (org-goto-line line)
11089 (if search (org-link-search search))))
11090 ((consp cmd)
11091 (let ((file (convert-standard-filename file)))
11092 (save-match-data
11093 (set-match-data link-match-data)
11094 (eval cmd))))
11095 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11096 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11097 (or (not (equal old-buffer (current-buffer)))
11098 (not (equal old-pos (point))))
11099 (org-mark-ring-push old-pos old-buffer))))
11101 (defun org-file-apps-entry-match-against-dlink-p (entry)
11102 "This function returns non-nil if `entry' uses a regular
11103 expression which should be matched against the whole link by
11104 org-open-file.
11106 It assumes that is the case when the entry uses a regular
11107 expression which has at least one grouping construct and the
11108 action is either a lisp form or a command string containing
11109 '%1', i.e. using at least one subexpression match as a
11110 parameter."
11111 (let ((selector (car entry))
11112 (action (cdr entry)))
11113 (if (stringp selector)
11114 (and (> (regexp-opt-depth selector) 0)
11115 (or (and (stringp action)
11116 (string-match "%[0-9]" action))
11117 (consp action)))
11118 nil)))
11120 (defun org-default-apps ()
11121 "Return the default applications for this operating system."
11122 (cond
11123 ((eq system-type 'darwin)
11124 org-file-apps-defaults-macosx)
11125 ((eq system-type 'windows-nt)
11126 org-file-apps-defaults-windowsnt)
11127 (t org-file-apps-defaults-gnu)))
11129 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11130 "Convert extensions to regular expressions in the cars of LIST.
11131 Also, weed out any non-string entries, because the return value is used
11132 only for regexp matching.
11133 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11134 point to the symbol `emacs', indicating that the file should
11135 be opened in Emacs."
11136 (append
11137 (delq nil
11138 (mapcar (lambda (x)
11139 (if (not (stringp (car x)))
11141 (if (string-match "\\W" (car x))
11143 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11144 list))
11145 (if add-auto-mode
11146 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11148 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11149 (defun org-file-remote-p (file)
11150 "Test whether FILE specifies a location on a remote system.
11151 Return non-nil if the location is indeed remote.
11153 For example, the filename \"/user@host:/foo\" specifies a location
11154 on the system \"/user@host:\"."
11155 (cond ((fboundp 'file-remote-p)
11156 (file-remote-p file))
11157 ((fboundp 'tramp-handle-file-remote-p)
11158 (tramp-handle-file-remote-p file))
11159 ((and (boundp 'ange-ftp-name-format)
11160 (string-match (car ange-ftp-name-format) file))
11161 t)))
11164 ;;;; Refiling
11166 (defun org-get-org-file ()
11167 "Read a filename, with default directory `org-directory'."
11168 (let ((default (or org-default-notes-file remember-data-file)))
11169 (read-file-name (format "File name [%s]: " default)
11170 (file-name-as-directory org-directory)
11171 default)))
11173 (defun org-notes-order-reversed-p ()
11174 "Check if the current file should receive notes in reversed order."
11175 (cond
11176 ((not org-reverse-note-order) nil)
11177 ((eq t org-reverse-note-order) t)
11178 ((not (listp org-reverse-note-order)) nil)
11179 (t (catch 'exit
11180 (let ((all org-reverse-note-order)
11181 entry)
11182 (while (setq entry (pop all))
11183 (if (string-match (car entry) buffer-file-name)
11184 (throw 'exit (cdr entry))))
11185 nil)))))
11187 (defvar org-refile-target-table nil
11188 "The list of refile targets, created by `org-refile'.")
11190 (defvar org-agenda-new-buffers nil
11191 "Buffers created to visit agenda files.")
11193 (defvar org-refile-cache nil
11194 "Cache for refile targets.")
11196 (defvar org-refile-markers nil
11197 "All the markers used for caching refile locations.")
11199 (defun org-refile-marker (pos)
11200 "Get a new refile marker, but only if caching is in use."
11201 (if (not org-refile-use-cache)
11203 (let ((m (make-marker)))
11204 (move-marker m pos)
11205 (push m org-refile-markers)
11206 m)))
11208 (defun org-refile-cache-clear ()
11209 "Clear the refile cache and disable all the markers."
11210 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11211 (setq org-refile-markers nil)
11212 (setq org-refile-cache nil)
11213 (message "Refile cache has been cleared"))
11215 (defun org-refile-cache-check-set (set)
11216 "Check if all the markers in the cache still have live buffers."
11217 (let (marker)
11218 (catch 'exit
11219 (while (and set (setq marker (nth 3 (pop set))))
11220 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11221 (when (and marker (null (marker-buffer marker)))
11222 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11223 (sit-for 3)
11224 (throw 'exit nil)))
11225 t)))
11227 (defun org-refile-cache-put (set &rest identifiers)
11228 "Push the refile targets SET into the cache, under IDENTIFIERS."
11229 (let* ((key (sha1 (prin1-to-string identifiers)))
11230 (entry (assoc key org-refile-cache)))
11231 (if entry
11232 (setcdr entry set)
11233 (push (cons key set) org-refile-cache))))
11235 (defun org-refile-cache-get (&rest identifiers)
11236 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11237 (cond
11238 ((not org-refile-cache) nil)
11239 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11241 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11242 org-refile-cache))))
11243 (and set (org-refile-cache-check-set set) set)))))
11245 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11246 "Produce a table with refile targets."
11247 (let ((case-fold-search nil)
11248 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11249 (entries (or org-refile-targets '((nil . (:level . 1)))))
11250 targets tgs txt re files f desc descre fast-path-p level pos0)
11251 (message "Getting targets...")
11252 (with-current-buffer (or default-buffer (current-buffer))
11253 (while (setq entry (pop entries))
11254 (setq files (car entry) desc (cdr entry))
11255 (setq fast-path-p nil)
11256 (cond
11257 ((null files) (setq files (list (current-buffer))))
11258 ((eq files 'org-agenda-files)
11259 (setq files (org-agenda-files 'unrestricted)))
11260 ((and (symbolp files) (fboundp files))
11261 (setq files (funcall files)))
11262 ((and (symbolp files) (boundp files))
11263 (setq files (symbol-value files))))
11264 (if (stringp files) (setq files (list files)))
11265 (cond
11266 ((eq (car desc) :tag)
11267 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11268 ((eq (car desc) :todo)
11269 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11270 ((eq (car desc) :regexp)
11271 (setq descre (cdr desc)))
11272 ((eq (car desc) :level)
11273 (setq descre (concat "^\\*\\{" (number-to-string
11274 (if org-odd-levels-only
11275 (1- (* 2 (cdr desc)))
11276 (cdr desc)))
11277 "\\}[ \t]")))
11278 ((eq (car desc) :maxlevel)
11279 (setq fast-path-p t)
11280 (setq descre (concat "^\\*\\{1," (number-to-string
11281 (if org-odd-levels-only
11282 (1- (* 2 (cdr desc)))
11283 (cdr desc)))
11284 "\\}[ \t]")))
11285 (t (error "Bad refiling target description %s" desc)))
11286 (while (setq f (pop files))
11287 (with-current-buffer
11288 (if (bufferp f) f (org-get-agenda-file-buffer f))
11290 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11291 (progn
11292 (if (bufferp f) (setq f (buffer-file-name
11293 (buffer-base-buffer f))))
11294 (setq f (and f (expand-file-name f)))
11295 (if (eq org-refile-use-outline-path 'file)
11296 (push (list (file-name-nondirectory f) f nil nil) tgs))
11297 (save-excursion
11298 (save-restriction
11299 (widen)
11300 (goto-char (point-min))
11301 (while (re-search-forward descre nil t)
11302 (goto-char (setq pos0 (point-at-bol)))
11303 (catch 'next
11304 (when org-refile-target-verify-function
11305 (save-match-data
11306 (or (funcall org-refile-target-verify-function)
11307 (throw 'next t))))
11308 (when (and (looking-at org-complex-heading-regexp)
11309 (not (member (match-string 4) excluded-entries))
11310 (match-string 4))
11311 (setq level (org-reduced-level
11312 (- (match-end 1) (match-beginning 1)))
11313 txt (org-link-display-format (match-string 4))
11314 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11315 re (format org-complex-heading-regexp-format
11316 (regexp-quote (match-string 4))))
11317 (when org-refile-use-outline-path
11318 (setq txt (mapconcat
11319 'org-protect-slash
11320 (append
11321 (if (eq org-refile-use-outline-path
11322 'file)
11323 (list (file-name-nondirectory
11324 (buffer-file-name
11325 (buffer-base-buffer))))
11326 (if (eq org-refile-use-outline-path
11327 'full-file-path)
11328 (list (buffer-file-name
11329 (buffer-base-buffer)))))
11330 (org-get-outline-path fast-path-p
11331 level txt)
11332 (list txt))
11333 "/")))
11334 (push (list txt f re (org-refile-marker (point)))
11335 tgs)))
11336 (when (= (point) pos0)
11337 ;; verification function has not moved point
11338 (goto-char (point-at-eol))))))))
11339 (when org-refile-use-cache
11340 (org-refile-cache-put tgs (buffer-file-name) descre))
11341 (setq targets (append tgs targets))))))
11342 (message "Getting targets...done")
11343 (nreverse targets)))
11345 (defun org-protect-slash (s)
11346 (while (string-match "/" s)
11347 (setq s (replace-match "\\" t t s)))
11350 (defvar org-olpa (make-vector 20 nil))
11352 (defun org-get-outline-path (&optional fastp level heading)
11353 "Return the outline path to the current entry, as a list.
11355 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11356 routine which makes outline path derivations for an entire file,
11357 avoiding backtracing. Refile target collection makes use of that."
11358 (if fastp
11359 (progn
11360 (if (> level 19)
11361 (error "Outline path failure, more than 19 levels"))
11362 (loop for i from level upto 19 do
11363 (aset org-olpa i nil))
11364 (prog1
11365 (delq nil (append org-olpa nil))
11366 (aset org-olpa level heading)))
11367 (let (rtn case-fold-search)
11368 (save-excursion
11369 (save-restriction
11370 (widen)
11371 (while (org-up-heading-safe)
11372 (when (looking-at org-complex-heading-regexp)
11373 (push (org-trim
11374 (replace-regexp-in-string
11375 ;; Remove statistical/checkboxes cookies
11376 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11377 (org-match-string-no-properties 4)))
11378 rtn)))
11379 rtn)))))
11381 (defun org-format-outline-path (path &optional width prefix separator)
11382 "Format the outline path PATH for display.
11383 WIDTH is the maximum number of characters that is available.
11384 PREFIX is a prefix to be included in the returned string,
11385 such as the file name.
11386 SEPARATOR is inserted between the different parts of the path,
11387 the default is \"/\"."
11388 (setq width (or width 79))
11389 (if prefix (setq width (- width (length prefix))))
11390 (if (not path)
11391 (or prefix "")
11392 (let* ((nsteps (length path))
11393 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11394 (maxwidth (if (<= total-width width)
11395 10000 ;; everything fits
11396 ;; we need to shorten the level headings
11397 (/ (- width nsteps) nsteps)))
11398 (org-odd-levels-only nil)
11399 (n 0)
11400 (total (1+ (length prefix))))
11401 (setq maxwidth (max maxwidth 10))
11402 (concat prefix
11403 (if prefix (or separator "/"))
11404 (mapconcat
11405 (lambda (h)
11406 (setq n (1+ n))
11407 (if (and (= n nsteps) (< maxwidth 10000))
11408 (setq maxwidth (- total-width total)))
11409 (if (< (length h) maxwidth)
11410 (progn (setq total (+ total (length h) 1)) h)
11411 (setq h (substring h 0 (- maxwidth 2))
11412 total (+ total maxwidth 1))
11413 (if (string-match "[ \t]+\\'" h)
11414 (setq h (substring h 0 (match-beginning 0))))
11415 (setq h (concat h "..")))
11416 (org-add-props h nil 'face
11417 (nth (% (1- n) org-n-level-faces)
11418 org-level-faces))
11420 path (or separator "/"))))))
11422 (defun org-display-outline-path (&optional file current separator just-return-string)
11423 "Display the current outline path in the echo area.
11425 If FILE is non-nil, prepend the output with the file name.
11426 If CURRENT is non-nil, append the current heading to the output.
11427 SEPARATOR is passed through to `org-format-outline-path'. It separates
11428 the different parts of the path and defaults to \"/\".
11429 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11430 (interactive "P")
11431 (let* (case-fold-search
11432 message-log-max ; Don't populate the *Messages* buffer
11433 (bfn (buffer-file-name (buffer-base-buffer)))
11434 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11435 res)
11436 (if current (setq path (append path
11437 (save-excursion
11438 (org-back-to-heading t)
11439 (if (looking-at org-complex-heading-regexp)
11440 (list (match-string 4)))))))
11441 (setq res
11442 (org-format-outline-path
11443 path
11444 (1- (frame-width))
11445 (and file bfn (concat (file-name-nondirectory bfn) separator))
11446 separator))
11447 (if just-return-string
11448 (org-no-properties res)
11449 (message "%s" res))))
11451 (defvar org-refile-history nil
11452 "History for refiling operations.")
11454 (defvar org-after-refile-insert-hook nil
11455 "Hook run after `org-refile' has inserted its stuff at the new location.
11456 Note that this is still *before* the stuff will be removed from
11457 the *old* location.")
11459 (defvar org-capture-last-stored-marker)
11460 (defvar org-refile-keep nil
11461 "Non-nil means `org-refile' will copy instead of refile.")
11463 (defun org-copy ()
11464 "Like `org-refile', but copy."
11465 (interactive)
11466 (let ((org-refile-keep t))
11467 (funcall 'org-refile nil nil nil "Copy")))
11469 (defun org-refile (&optional goto default-buffer rfloc msg)
11470 "Move the entry or entries at point to another heading.
11471 The list of target headings is compiled using the information in
11472 `org-refile-targets', which see.
11474 At the target location, the entry is filed as a subitem of the target
11475 heading. Depending on `org-reverse-note-order', the new subitem will
11476 either be the first or the last subitem.
11478 If there is an active region, all entries in that region will be moved.
11479 However, the region must fulfill the requirement that the first heading
11480 is the first one sets the top-level of the moved text - at most siblings
11481 below it are allowed.
11483 With prefix arg GOTO, the command will only visit the target location
11484 and not actually move anything.
11486 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11487 go to the location where the last refiling operation has put the subtree.
11488 With a prefix argument of `2', refile to the running clock.
11490 RFLOC can be a refile location obtained in a different way.
11492 MSG is a string to replace \"Refile\" in the default prompt with
11493 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11495 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11497 If you are using target caching (see `org-refile-use-cache'),
11498 you have to clear the target cache in order to find new targets.
11499 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11500 prefix argument (`C-u C-u C-u C-c C-w')."
11502 (interactive "P")
11503 (if (member goto '(0 (64)))
11504 (org-refile-cache-clear)
11505 (let* ((actionmsg (or msg "Refile"))
11506 (cbuf (current-buffer))
11507 (regionp (org-region-active-p))
11508 (region-start (and regionp (region-beginning)))
11509 (region-end (and regionp (region-end)))
11510 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11511 pos it nbuf file re level reversed)
11512 (setq last-command nil)
11513 (when regionp
11514 (goto-char region-start)
11515 (or (bolp) (goto-char (point-at-bol)))
11516 (setq region-start (point))
11517 (unless (or (org-kill-is-subtree-p
11518 (buffer-substring region-start region-end))
11519 (prog1 org-refile-active-region-within-subtree
11520 (let ((s (point-at-eol)))
11521 (org-toggle-heading)
11522 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11523 (user-error "The region is not a (sequence of) subtree(s)")))
11524 (if (equal goto '(16))
11525 (org-refile-goto-last-stored)
11526 (when (or
11527 (and (equal goto 2)
11528 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11529 (prog1
11530 (setq it (list (or org-clock-heading "running clock")
11531 (buffer-file-name
11532 (marker-buffer org-clock-hd-marker))
11534 (marker-position org-clock-hd-marker)))
11535 (setq goto nil)))
11536 (setq it (or rfloc
11537 (let (heading-text)
11538 (save-excursion
11539 (unless goto
11540 (org-back-to-heading t)
11541 (setq heading-text
11542 (nth 4 (org-heading-components))))
11544 (org-refile-get-location
11545 (cond (goto "Goto")
11546 (regionp (concat actionmsg " region to"))
11547 (t (concat actionmsg " subtree \""
11548 heading-text "\" to")))
11549 default-buffer
11550 (and (not (equal '(4) goto))
11551 org-refile-allow-creating-parent-nodes)
11552 goto))))))
11553 (setq file (nth 1 it)
11554 re (nth 2 it)
11555 pos (nth 3 it))
11556 (if (and (not goto)
11558 (equal (buffer-file-name) file)
11559 (if regionp
11560 (and (>= pos region-start)
11561 (<= pos region-end))
11562 (and (>= pos (point))
11563 (< pos (save-excursion
11564 (org-end-of-subtree t t))))))
11565 (error "Cannot refile to position inside the tree or region"))
11567 (setq nbuf (or (find-buffer-visiting file)
11568 (find-file-noselect file)))
11569 (if goto
11570 (progn
11571 (org-pop-to-buffer-same-window nbuf)
11572 (goto-char pos)
11573 (org-show-context 'org-goto))
11574 (if regionp
11575 (progn
11576 (org-kill-new (buffer-substring region-start region-end))
11577 (org-save-markers-in-region region-start region-end))
11578 (org-copy-subtree 1 nil t))
11579 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11580 (find-file-noselect file)))
11581 (setq reversed (org-notes-order-reversed-p))
11582 (save-excursion
11583 (save-restriction
11584 (widen)
11585 (if pos
11586 (progn
11587 (goto-char pos)
11588 (looking-at org-outline-regexp)
11589 (setq level (org-get-valid-level (funcall outline-level) 1))
11590 (goto-char
11591 (if reversed
11592 (or (outline-next-heading) (point-max))
11593 (or (save-excursion (org-get-next-sibling))
11594 (org-end-of-subtree t t)
11595 (point-max)))))
11596 (setq level 1)
11597 (if (not reversed)
11598 (goto-char (point-max))
11599 (goto-char (point-min))
11600 (or (outline-next-heading) (goto-char (point-max)))))
11601 (if (not (bolp)) (newline))
11602 (org-paste-subtree level)
11603 (when org-log-refile
11604 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11605 (unless (eq org-log-refile 'note)
11606 (save-excursion (org-add-log-note))))
11607 (and org-auto-align-tags
11608 (let ((org-loop-over-headlines-in-active-region nil))
11609 (org-set-tags nil t)))
11610 (with-demoted-errors
11611 (bookmark-set "org-refile-last-stored"))
11612 ;; If we are refiling for capture, make sure that the
11613 ;; last-capture pointers point here
11614 (when (org-bound-and-true-p org-refile-for-capture)
11615 (with-demoted-errors
11616 (bookmark-set "org-capture-last-stored-marker"))
11617 (move-marker org-capture-last-stored-marker (point)))
11618 (if (fboundp 'deactivate-mark) (deactivate-mark))
11619 (run-hooks 'org-after-refile-insert-hook))))
11620 (unless org-refile-keep
11621 (if regionp
11622 (delete-region (point) (+ (point) (- region-end region-start)))
11623 (delete-region
11624 (and (org-back-to-heading t) (point))
11625 (min (buffer-size) (org-end-of-subtree t t) (point)))))
11626 (when (featurep 'org-inlinetask)
11627 (org-inlinetask-remove-END-maybe))
11628 (setq org-markers-to-move nil)
11629 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11631 (defun org-refile-goto-last-stored ()
11632 "Go to the location where the last refile was stored."
11633 (interactive)
11634 (bookmark-jump "org-refile-last-stored")
11635 (message "This is the location of the last refile"))
11637 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11638 no-exclude)
11639 "Prompt the user for a refile location, using PROMPT.
11640 PROMPT should not be suffixed with a colon and a space, because
11641 this function appends the default value from
11642 `org-refile-history' automatically, if that is not empty.
11643 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11644 this is used for the GOTO interface."
11645 (let ((org-refile-targets org-refile-targets)
11646 (org-refile-use-outline-path org-refile-use-outline-path)
11647 excluded-entries)
11648 (when (and (derived-mode-p 'org-mode)
11649 (not org-refile-use-cache)
11650 (not no-exclude))
11651 (org-map-tree
11652 (lambda()
11653 (setq excluded-entries
11654 (append excluded-entries (list (org-get-heading t t)))))))
11655 (setq org-refile-target-table
11656 (org-refile-get-targets default-buffer excluded-entries)))
11657 (unless org-refile-target-table
11658 (user-error "No refile targets"))
11659 (let* ((cbuf (current-buffer))
11660 (partial-completion-mode nil)
11661 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11662 (cfunc (if (and org-refile-use-outline-path
11663 org-outline-path-complete-in-steps)
11664 'org-olpath-completing-read
11665 'org-icompleting-read))
11666 (extra (if org-refile-use-outline-path "/" ""))
11667 (cbnex (concat (buffer-name) extra))
11668 (filename (and cfn (expand-file-name cfn)))
11669 (tbl (mapcar
11670 (lambda (x)
11671 (if (and (not (member org-refile-use-outline-path
11672 '(file full-file-path)))
11673 (not (equal filename (nth 1 x))))
11674 (cons (concat (car x) extra " ("
11675 (file-name-nondirectory (nth 1 x)) ")")
11676 (cdr x))
11677 (cons (concat (car x) extra) (cdr x))))
11678 org-refile-target-table))
11679 (completion-ignore-case t)
11680 cdef
11681 (prompt (concat prompt
11682 (or (and (car org-refile-history)
11683 (concat " (default " (car org-refile-history) ")"))
11684 (and (assoc cbnex tbl) (setq cdef cbnex)
11685 (concat " (default " cbnex ")"))) ": "))
11686 pa answ parent-target child parent old-hist)
11687 (setq old-hist org-refile-history)
11688 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11689 nil 'org-refile-history (or cdef (car org-refile-history))))
11690 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11691 (org-refile-check-position pa)
11692 (if pa
11693 (progn
11694 (when (or (not org-refile-history)
11695 (not (eq old-hist org-refile-history))
11696 (not (equal (car pa) (car org-refile-history))))
11697 (setq org-refile-history
11698 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11699 org-refile-history
11700 (cdr org-refile-history))))
11701 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11702 (pop org-refile-history)))
11704 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11705 (progn
11706 (setq parent (match-string 1 answ)
11707 child (match-string 2 answ))
11708 (setq parent-target (or (assoc parent tbl)
11709 (assoc (concat parent "/") tbl)))
11710 (when (and parent-target
11711 (or (eq new-nodes t)
11712 (and (eq new-nodes 'confirm)
11713 (y-or-n-p (format "Create new node \"%s\"? "
11714 child)))))
11715 (org-refile-new-child parent-target child)))
11716 (user-error "Invalid target location")))))
11718 (declare-function org-string-nw-p "org-macs" (s))
11719 (defun org-refile-check-position (refile-pointer)
11720 "Check if the refile pointer matches the headline to which it points."
11721 (let* ((file (nth 1 refile-pointer))
11722 (re (nth 2 refile-pointer))
11723 (pos (nth 3 refile-pointer))
11724 buffer)
11725 (if (and (not (markerp pos)) (not file))
11726 (user-error "Please save the buffer to a file before refiling")
11727 (when (org-string-nw-p re)
11728 (setq buffer (if (markerp pos)
11729 (marker-buffer pos)
11730 (or (find-buffer-visiting file)
11731 (find-file-noselect file))))
11732 (with-current-buffer buffer
11733 (save-excursion
11734 (save-restriction
11735 (widen)
11736 (goto-char pos)
11737 (beginning-of-line 1)
11738 (unless (org-looking-at-p re)
11739 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11741 (defun org-refile-new-child (parent-target child)
11742 "Use refile target PARENT-TARGET to add new CHILD below it."
11743 (unless parent-target
11744 (error "Cannot find parent for new node"))
11745 (let ((file (nth 1 parent-target))
11746 (pos (nth 3 parent-target))
11747 level)
11748 (with-current-buffer (or (find-buffer-visiting file)
11749 (find-file-noselect file))
11750 (save-excursion
11751 (save-restriction
11752 (widen)
11753 (if pos
11754 (goto-char pos)
11755 (goto-char (point-max))
11756 (if (not (bolp)) (newline)))
11757 (when (looking-at org-outline-regexp)
11758 (setq level (funcall outline-level))
11759 (org-end-of-subtree t t))
11760 (org-back-over-empty-lines)
11761 (insert "\n" (make-string
11762 (if pos (org-get-valid-level level 1) 1) ?*)
11763 " " child "\n")
11764 (beginning-of-line 0)
11765 (list (concat (car parent-target) "/" child) file "" (point)))))))
11767 (defun org-olpath-completing-read (prompt collection &rest args)
11768 "Read an outline path like a file name."
11769 (let ((thetable collection)
11770 (org-completion-use-ido nil) ; does not work with ido.
11771 (org-completion-use-iswitchb nil)) ; or iswitchb
11772 (apply
11773 'org-icompleting-read prompt
11774 (lambda (string predicate &optional flag)
11775 (let (rtn r f (l (length string)))
11776 (cond
11777 ((eq flag nil)
11778 ;; try completion
11779 (try-completion string thetable))
11780 ((eq flag t)
11781 ;; all-completions
11782 (setq rtn (all-completions string thetable predicate))
11783 (mapcar
11784 (lambda (x)
11785 (setq r (substring x l))
11786 (if (string-match " ([^)]*)$" x)
11787 (setq f (match-string 0 x))
11788 (setq f ""))
11789 (if (string-match "/" r)
11790 (concat string (substring r 0 (match-end 0)) f)
11792 rtn))
11793 ((eq flag 'lambda)
11794 ;; exact match?
11795 (assoc string thetable)))))
11796 args)))
11798 ;;;; Dynamic blocks
11800 (defun org-find-dblock (name)
11801 "Find the first dynamic block with name NAME in the buffer.
11802 If not found, stay at current position and return nil."
11803 (let ((case-fold-search t) pos)
11804 (save-excursion
11805 (goto-char (point-min))
11806 (setq pos (and (re-search-forward
11807 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11808 (match-beginning 0))))
11809 (if pos (goto-char pos))
11810 pos))
11812 (defconst org-dblock-start-re
11813 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11814 "Matches the start line of a dynamic block, with parameters.")
11816 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11817 "Matches the end of a dynamic block.")
11819 (defun org-create-dblock (plist)
11820 "Create a dynamic block section, with parameters taken from PLIST.
11821 PLIST must contain a :name entry which is used as name of the block."
11822 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11823 (end-of-line 1)
11824 (newline))
11825 (let ((col (current-column))
11826 (name (plist-get plist :name)))
11827 (insert "#+BEGIN: " name)
11828 (while plist
11829 (if (eq (car plist) :name)
11830 (setq plist (cddr plist))
11831 (insert " " (prin1-to-string (pop plist)))))
11832 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11833 (beginning-of-line -2)))
11835 (defun org-prepare-dblock ()
11836 "Prepare dynamic block for refresh.
11837 This empties the block, puts the cursor at the insert position and returns
11838 the property list including an extra property :name with the block name."
11839 (unless (looking-at org-dblock-start-re)
11840 (user-error "Not at a dynamic block"))
11841 (let* ((begdel (1+ (match-end 0)))
11842 (name (org-no-properties (match-string 1)))
11843 (params (append (list :name name)
11844 (read (concat "(" (match-string 3) ")")))))
11845 (save-excursion
11846 (beginning-of-line 1)
11847 (skip-chars-forward " \t")
11848 (setq params (plist-put params :indentation-column (current-column))))
11849 (unless (re-search-forward org-dblock-end-re nil t)
11850 (error "Dynamic block not terminated"))
11851 (setq params
11852 (append params
11853 (list :content (buffer-substring
11854 begdel (match-beginning 0)))))
11855 (delete-region begdel (match-beginning 0))
11856 (goto-char begdel)
11857 (open-line 1)
11858 params))
11860 (defun org-map-dblocks (&optional command)
11861 "Apply COMMAND to all dynamic blocks in the current buffer.
11862 If COMMAND is not given, use `org-update-dblock'."
11863 (let ((cmd (or command 'org-update-dblock)))
11864 (save-excursion
11865 (goto-char (point-min))
11866 (while (re-search-forward org-dblock-start-re nil t)
11867 (goto-char (match-beginning 0))
11868 (save-excursion
11869 (condition-case nil
11870 (funcall cmd)
11871 (error (message "Error during update of dynamic block"))))
11872 (unless (re-search-forward org-dblock-end-re nil t)
11873 (error "Dynamic block not terminated"))))))
11875 (defun org-dblock-update (&optional arg)
11876 "User command for updating dynamic blocks.
11877 Update the dynamic block at point. With prefix ARG, update all dynamic
11878 blocks in the buffer."
11879 (interactive "P")
11880 (if arg
11881 (org-update-all-dblocks)
11882 (or (looking-at org-dblock-start-re)
11883 (org-beginning-of-dblock))
11884 (org-update-dblock)))
11886 (defun org-update-dblock ()
11887 "Update the dynamic block at point.
11888 This means to empty the block, parse for parameters and then call
11889 the correct writing function."
11890 (interactive)
11891 (save-window-excursion
11892 (let* ((pos (point))
11893 (line (org-current-line))
11894 (params (org-prepare-dblock))
11895 (name (plist-get params :name))
11896 (indent (plist-get params :indentation-column))
11897 (cmd (intern (concat "org-dblock-write:" name))))
11898 (message "Updating dynamic block `%s' at line %d..." name line)
11899 (funcall cmd params)
11900 (message "Updating dynamic block `%s' at line %d...done" name line)
11901 (goto-char pos)
11902 (when (and indent (> indent 0))
11903 (setq indent (make-string indent ?\ ))
11904 (save-excursion
11905 (org-beginning-of-dblock)
11906 (forward-line 1)
11907 (while (not (looking-at org-dblock-end-re))
11908 (insert indent)
11909 (beginning-of-line 2))
11910 (when (looking-at org-dblock-end-re)
11911 (and (looking-at "[ \t]+")
11912 (replace-match ""))
11913 (insert indent)))))))
11915 (defun org-beginning-of-dblock ()
11916 "Find the beginning of the dynamic block at point.
11917 Error if there is no such block at point."
11918 (let ((pos (point))
11919 beg)
11920 (end-of-line 1)
11921 (if (and (re-search-backward org-dblock-start-re nil t)
11922 (setq beg (match-beginning 0))
11923 (re-search-forward org-dblock-end-re nil t)
11924 (> (match-end 0) pos))
11925 (goto-char beg)
11926 (goto-char pos)
11927 (error "Not in a dynamic block"))))
11929 (defun org-update-all-dblocks ()
11930 "Update all dynamic blocks in the buffer.
11931 This function can be used in a hook."
11932 (interactive)
11933 (when (derived-mode-p 'org-mode)
11934 (org-map-dblocks 'org-update-dblock)))
11937 ;;;; Completion
11939 (defun org-get-export-keywords ()
11940 "Return a list of all currently understood export keywords.
11941 Export keywords include options, block names, attributes and
11942 keywords relative to each registered export back-end."
11943 (delq nil
11944 (let (keywords)
11945 (mapc
11946 (lambda (back-end)
11947 (let ((props (cdr back-end)))
11948 ;; Back-end name (for keywords, like #+LATEX:)
11949 (push (upcase (symbol-name (car back-end))) keywords)
11950 ;; Back-end options.
11951 (mapc (lambda (option) (push (cadr option) keywords))
11952 (plist-get (cdr back-end) :options-alist))))
11953 (org-bound-and-true-p org-export-registered-backends))
11954 keywords)))
11956 (defconst org-options-keywords
11957 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11958 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11959 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11960 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11961 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11963 (defcustom org-structure-template-alist
11964 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
11965 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
11966 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
11967 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
11968 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
11969 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
11970 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11971 "<literal style=\"latex\">\n?\n</literal>")
11972 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
11973 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11974 "<literal style=\"html\">\n?\n</literal>")
11975 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
11976 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
11977 ("A" "#+ASCII: " "")
11978 ("i" "#+INDEX: ?" "#+INDEX: ?")
11979 ("I" "#+INCLUDE: %file ?"
11980 "<include file=%file markup=\"?\">"))
11981 "Structure completion elements.
11982 This is a list of abbreviation keys and values. The value gets inserted
11983 if you type `<' followed by the key and then press the completion key,
11984 usually `M-TAB'. %file will be replaced by a file name after prompting
11985 for the file using completion. The cursor will be placed at the position
11986 of the `?` in the template.
11987 There are two templates for each key, the first uses the original Org syntax,
11988 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11989 the default when the /org-mtags.el/ module has been loaded. See also the
11990 variable `org-mtags-prefer-muse-templates'."
11991 :group 'org-completion
11992 :type '(repeat
11993 (list
11994 (string :tag "Key")
11995 (string :tag "Template")
11996 (string :tag "Muse Template"))))
11998 (defun org-try-structure-completion ()
11999 "Try to complete a structure template before point.
12000 This looks for strings like \"<e\" on an otherwise empty line and
12001 expands them."
12002 (let ((l (buffer-substring (point-at-bol) (point)))
12004 (when (and (looking-at "[ \t]*$")
12005 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12006 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12007 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12008 (match-beginning 1)) a)
12009 t)))
12011 (defun org-complete-expand-structure-template (start cell)
12012 "Expand a structure template."
12013 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12014 (rpl (nth (if musep 2 1) cell))
12015 (ind ""))
12016 (delete-region start (point))
12017 (when (string-match "\\`#\\+" rpl)
12018 (cond
12019 ((bolp))
12020 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12021 (setq ind (buffer-substring (point-at-bol) (point))))
12022 (t (newline))))
12023 (setq start (point))
12024 (if (string-match "%file" rpl)
12025 (setq rpl (replace-match
12026 (concat
12027 "\""
12028 (save-match-data
12029 (abbreviate-file-name (read-file-name "Include file: ")))
12030 "\"")
12031 t t rpl)))
12032 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12033 (concat "\n" ind)))
12034 (insert rpl)
12035 (if (re-search-backward "\\?" start t) (delete-char 1))))
12037 ;;;; TODO, DEADLINE, Comments
12039 (defun org-toggle-comment ()
12040 "Change the COMMENT state of an entry."
12041 (interactive)
12042 (save-excursion
12043 (org-back-to-heading)
12044 (let (case-fold-search)
12045 (cond
12046 ((looking-at (format org-heading-keyword-regexp-format
12047 org-comment-string))
12048 (goto-char (match-end 1))
12049 (looking-at (concat " +" org-comment-string))
12050 (replace-match "" t t)
12051 (when (eolp) (insert " ")))
12052 ((looking-at org-outline-regexp)
12053 (goto-char (match-end 0))
12054 (insert org-comment-string " "))))))
12056 (defvar org-last-todo-state-is-todo nil
12057 "This is non-nil when the last TODO state change led to a TODO state.
12058 If the last change removed the TODO tag or switched to DONE, then
12059 this is nil.")
12061 (defvar org-setting-tags nil) ; dynamically skipped
12063 (defvar org-todo-setup-filter-hook nil
12064 "Hook for functions that pre-filter todo specs.
12065 Each function takes a todo spec and returns either nil or the spec
12066 transformed into canonical form." )
12068 (defvar org-todo-get-default-hook nil
12069 "Hook for functions that get a default item for todo.
12070 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12071 nil or a string to be used for the todo mark." )
12073 (defvar org-agenda-headline-snapshot-before-repeat)
12075 (defun org-current-effective-time ()
12076 "Return current time adjusted for `org-extend-today-until' variable."
12077 (let* ((ct (org-current-time))
12078 (dct (decode-time ct))
12079 (ct1
12080 (cond
12081 (org-use-last-clock-out-time-as-effective-time
12082 (or (org-clock-get-last-clock-out-time) ct))
12083 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12084 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12085 (t ct))))
12086 ct1))
12088 (defun org-todo-yesterday (&optional arg)
12089 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12090 (interactive "P")
12091 (if (eq major-mode 'org-agenda-mode)
12092 (apply 'org-agenda-todo-yesterday arg)
12093 (let* ((hour (third (decode-time
12094 (org-current-time))))
12095 (org-extend-today-until (1+ hour)))
12096 (org-todo arg))))
12098 (defvar org-block-entry-blocking ""
12099 "First entry preventing the TODO state change.")
12101 (defun org-todo (&optional arg)
12102 "Change the TODO state of an item.
12103 The state of an item is given by a keyword at the start of the heading,
12104 like
12105 *** TODO Write paper
12106 *** DONE Call mom
12108 The different keywords are specified in the variable `org-todo-keywords'.
12109 By default the available states are \"TODO\" and \"DONE\".
12110 So for this example: when the item starts with TODO, it is changed to DONE.
12111 When it starts with DONE, the DONE is removed. And when neither TODO nor
12112 DONE are present, add TODO at the beginning of the heading.
12114 With \\[universal-argument] prefix arg, use completion to determine the new \
12115 state.
12116 With numeric prefix arg, switch to that state.
12117 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12118 keywords (nextset).
12119 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12120 With a numeric prefix arg of 0, inhibit note taking for the change.
12122 For calling through lisp, arg is also interpreted in the following way:
12123 'none -> empty state
12124 \"\"(empty string) -> switch to empty state
12125 'done -> switch to DONE
12126 'nextset -> switch to the next set of keywords
12127 'previousset -> switch to the previous set of keywords
12128 \"WAITING\" -> switch to the specified keyword, but only if it
12129 really is a member of `org-todo-keywords'."
12130 (interactive "P")
12131 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12132 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12133 'region-start-level 'region))
12134 org-loop-over-headlines-in-active-region)
12135 (org-map-entries
12136 `(org-todo ,arg)
12137 org-loop-over-headlines-in-active-region
12138 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12139 (if (equal arg '(16)) (setq arg 'nextset))
12140 (let ((org-blocker-hook org-blocker-hook)
12141 commentp
12142 case-fold-search)
12143 (when (equal arg '(64))
12144 (setq arg nil org-blocker-hook nil))
12145 (when (and org-blocker-hook
12146 (or org-inhibit-blocking
12147 (org-entry-get nil "NOBLOCKING")))
12148 (setq org-blocker-hook nil))
12149 (save-excursion
12150 (catch 'exit
12151 (org-back-to-heading t)
12152 (when (looking-at (concat "^\\*+ " org-comment-string))
12153 (org-toggle-comment)
12154 (setq commentp t))
12155 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12156 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12157 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12158 (let* ((match-data (match-data))
12159 (startpos (point-at-bol))
12160 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12161 (org-log-done org-log-done)
12162 (org-log-repeat org-log-repeat)
12163 (org-todo-log-states org-todo-log-states)
12164 (org-inhibit-logging
12165 (if (equal arg 0)
12166 (progn (setq arg nil) 'note) org-inhibit-logging))
12167 (this (match-string 1))
12168 (hl-pos (match-beginning 0))
12169 (head (org-get-todo-sequence-head this))
12170 (ass (assoc head org-todo-kwd-alist))
12171 (interpret (nth 1 ass))
12172 (done-word (nth 3 ass))
12173 (final-done-word (nth 4 ass))
12174 (org-last-state (or this ""))
12175 (completion-ignore-case t)
12176 (member (member this org-todo-keywords-1))
12177 (tail (cdr member))
12178 (org-state (cond
12179 ((and org-todo-key-trigger
12180 (or (and (equal arg '(4))
12181 (eq org-use-fast-todo-selection 'prefix))
12182 (and (not arg) org-use-fast-todo-selection
12183 (not (eq org-use-fast-todo-selection
12184 'prefix)))))
12185 ;; Use fast selection
12186 (org-fast-todo-selection))
12187 ((and (equal arg '(4))
12188 (or (not org-use-fast-todo-selection)
12189 (not org-todo-key-trigger)))
12190 ;; Read a state with completion
12191 (org-icompleting-read
12192 "State: " (mapcar 'list org-todo-keywords-1)
12193 nil t))
12194 ((eq arg 'right)
12195 (if this
12196 (if tail (car tail) nil)
12197 (car org-todo-keywords-1)))
12198 ((eq arg 'left)
12199 (if (equal member org-todo-keywords-1)
12201 (if this
12202 (nth (- (length org-todo-keywords-1)
12203 (length tail) 2)
12204 org-todo-keywords-1)
12205 (org-last org-todo-keywords-1))))
12206 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12207 (setq arg nil))) ; hack to fall back to cycling
12208 (arg
12209 ;; user or caller requests a specific state
12210 (cond
12211 ((equal arg "") nil)
12212 ((eq arg 'none) nil)
12213 ((eq arg 'done) (or done-word (car org-done-keywords)))
12214 ((eq arg 'nextset)
12215 (or (car (cdr (member head org-todo-heads)))
12216 (car org-todo-heads)))
12217 ((eq arg 'previousset)
12218 (let ((org-todo-heads (reverse org-todo-heads)))
12219 (or (car (cdr (member head org-todo-heads)))
12220 (car org-todo-heads))))
12221 ((car (member arg org-todo-keywords-1)))
12222 ((stringp arg)
12223 (user-error "State `%s' not valid in this file" arg))
12224 ((nth (1- (prefix-numeric-value arg))
12225 org-todo-keywords-1))))
12226 ((null member) (or head (car org-todo-keywords-1)))
12227 ((equal this final-done-word) nil) ;; -> make empty
12228 ((null tail) nil) ;; -> first entry
12229 ((memq interpret '(type priority))
12230 (if (eq this-command last-command)
12231 (car tail)
12232 (if (> (length tail) 0)
12233 (or done-word (car org-done-keywords))
12234 nil)))
12236 (car tail))))
12237 (org-state (or
12238 (run-hook-with-args-until-success
12239 'org-todo-get-default-hook org-state org-last-state)
12240 org-state))
12241 (next (if org-state (concat " " org-state " ") " "))
12242 (change-plist (list :type 'todo-state-change :from this :to org-state
12243 :position startpos))
12244 dolog now-done-p)
12245 (when org-blocker-hook
12246 (setq org-last-todo-state-is-todo
12247 (not (member this org-done-keywords)))
12248 (unless (save-excursion
12249 (save-match-data
12250 (org-with-wide-buffer
12251 (run-hook-with-args-until-failure
12252 'org-blocker-hook change-plist))))
12253 (if (org-called-interactively-p 'interactive)
12254 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12255 this org-state org-block-entry-blocking)
12256 ;; fail silently
12257 (message "TODO state change from %s to %s blocked (by \"%s\")"
12258 this org-state org-block-entry-blocking)
12259 (throw 'exit nil))))
12260 (store-match-data match-data)
12261 (replace-match next t t)
12262 (unless (pos-visible-in-window-p hl-pos)
12263 (message "TODO state changed to %s" (org-trim next)))
12264 (unless head
12265 (setq head (org-get-todo-sequence-head org-state)
12266 ass (assoc head org-todo-kwd-alist)
12267 interpret (nth 1 ass)
12268 done-word (nth 3 ass)
12269 final-done-word (nth 4 ass)))
12270 (when (memq arg '(nextset previousset))
12271 (message "Keyword-Set %d/%d: %s"
12272 (- (length org-todo-sets) -1
12273 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12274 (length org-todo-sets)
12275 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12276 (setq org-last-todo-state-is-todo
12277 (not (member org-state org-done-keywords)))
12278 (setq now-done-p (and (member org-state org-done-keywords)
12279 (not (member this org-done-keywords))))
12280 (and logging (org-local-logging logging))
12281 (when (and (or org-todo-log-states org-log-done)
12282 (not (eq org-inhibit-logging t))
12283 (not (memq arg '(nextset previousset))))
12284 ;; we need to look at recording a time and note
12285 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12286 (nth 2 (assoc this org-todo-log-states))))
12287 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12288 (setq dolog 'time))
12289 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12290 (and org-state
12291 (member org-state org-not-done-keywords)
12292 (not (member this org-not-done-keywords))))
12293 ;; This is now a todo state and was not one before
12294 ;; If there was a CLOSED time stamp, get rid of it.
12295 (org-add-planning-info nil nil 'closed))
12296 (when (and now-done-p org-log-done)
12297 ;; It is now done, and it was not done before
12298 (org-add-planning-info 'closed (org-current-effective-time))
12299 (if (and (not dolog) (eq 'note org-log-done))
12300 (org-add-log-setup 'done org-state this 'findpos 'note)))
12301 (when (and org-state dolog)
12302 ;; This is a non-nil state, and we need to log it
12303 (org-add-log-setup 'state org-state this 'findpos dolog)))
12304 ;; Fixup tag positioning
12305 (org-todo-trigger-tag-changes org-state)
12306 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12307 (when org-provide-todo-statistics
12308 (org-update-parent-todo-statistics))
12309 (run-hooks 'org-after-todo-state-change-hook)
12310 (if (and arg (not (member org-state org-done-keywords)))
12311 (setq head (org-get-todo-sequence-head org-state)))
12312 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12313 ;; Do we need to trigger a repeat?
12314 (when now-done-p
12315 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12316 ;; This is for the agenda, take a snapshot of the headline.
12317 (save-match-data
12318 (setq org-agenda-headline-snapshot-before-repeat
12319 (org-get-heading))))
12320 (org-auto-repeat-maybe org-state))
12321 ;; Fixup cursor location if close to the keyword
12322 (if (and (outline-on-heading-p)
12323 (not (bolp))
12324 (save-excursion (beginning-of-line 1)
12325 (looking-at org-todo-line-regexp))
12326 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12327 (progn
12328 (goto-char (or (match-end 2) (match-end 1)))
12329 (and (looking-at " ") (just-one-space))))
12330 (when org-trigger-hook
12331 (save-excursion
12332 (run-hook-with-args 'org-trigger-hook change-plist)))
12333 (when commentp (org-toggle-comment))))))))
12335 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12336 "Block turning an entry into a TODO, using the hierarchy.
12337 This checks whether the current task should be blocked from state
12338 changes. Such blocking occurs when:
12340 1. The task has children which are not all in a completed state.
12342 2. A task has a parent with the property :ORDERED:, and there
12343 are siblings prior to the current task with incomplete
12344 status.
12346 3. The parent of the task is blocked because it has siblings that should
12347 be done first, or is child of a block grandparent TODO entry."
12349 (if (not org-enforce-todo-dependencies)
12350 t ; if locally turned off don't block
12351 (catch 'dont-block
12352 ;; If this is not a todo state change, or if this entry is already DONE,
12353 ;; do not block
12354 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12355 (member (plist-get change-plist :from)
12356 (cons 'done org-done-keywords))
12357 (member (plist-get change-plist :to)
12358 (cons 'todo org-not-done-keywords))
12359 (not (plist-get change-plist :to)))
12360 (throw 'dont-block t))
12361 ;; If this task has children, and any are undone, it's blocked
12362 (save-excursion
12363 (org-back-to-heading t)
12364 (let ((this-level (funcall outline-level)))
12365 (outline-next-heading)
12366 (let ((child-level (funcall outline-level)))
12367 (while (and (not (eobp))
12368 (> child-level this-level))
12369 ;; this todo has children, check whether they are all
12370 ;; completed
12371 (if (and (not (org-entry-is-done-p))
12372 (org-entry-is-todo-p))
12373 (progn (setq org-block-entry-blocking (org-get-heading))
12374 (throw 'dont-block nil)))
12375 (outline-next-heading)
12376 (setq child-level (funcall outline-level))))))
12377 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12378 ;; any previous siblings are undone, it's blocked
12379 (save-excursion
12380 (org-back-to-heading t)
12381 (let* ((pos (point))
12382 (parent-pos (and (org-up-heading-safe) (point))))
12383 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12384 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12385 (forward-line 1)
12386 (re-search-forward org-not-done-heading-regexp pos t))
12387 (setq org-block-entry-blocking (match-string 0))
12388 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12389 ;; Search further up the hierarchy, to see if an ancestor is blocked
12390 (while t
12391 (goto-char parent-pos)
12392 (if (not (looking-at org-not-done-heading-regexp))
12393 (throw 'dont-block t)) ; do not block, parent is not a TODO
12394 (setq pos (point))
12395 (setq parent-pos (and (org-up-heading-safe) (point)))
12396 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12397 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12398 (forward-line 1)
12399 (re-search-forward org-not-done-heading-regexp pos t)
12400 (setq org-block-entry-blocking (org-get-heading)))
12401 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12403 (defcustom org-track-ordered-property-with-tag nil
12404 "Should the ORDERED property also be shown as a tag?
12405 The ORDERED property decides if an entry should require subtasks to be
12406 completed in sequence. Since a property is not very visible, setting
12407 this option means that toggling the ORDERED property with the command
12408 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12409 not relevant for the behavior, but it makes things more visible.
12411 Note that toggling the tag with tags commands will not change the property
12412 and therefore not influence behavior!
12414 This can be t, meaning the tag ORDERED should be used, It can also be a
12415 string to select a different tag for this task."
12416 :group 'org-todo
12417 :type '(choice
12418 (const :tag "No tracking" nil)
12419 (const :tag "Track with ORDERED tag" t)
12420 (string :tag "Use other tag")))
12422 (defun org-toggle-ordered-property ()
12423 "Toggle the ORDERED property of the current entry.
12424 For better visibility, you can track the value of this property with a tag.
12425 See variable `org-track-ordered-property-with-tag'."
12426 (interactive)
12427 (let* ((t1 org-track-ordered-property-with-tag)
12428 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12429 (save-excursion
12430 (org-back-to-heading)
12431 (if (org-entry-get nil "ORDERED")
12432 (progn
12433 (org-delete-property "ORDERED" "PROPERTIES")
12434 (and tag (org-toggle-tag tag 'off))
12435 (message "Subtasks can be completed in arbitrary order"))
12436 (org-entry-put nil "ORDERED" "t")
12437 (and tag (org-toggle-tag tag 'on))
12438 (message "Subtasks must be completed in sequence")))))
12440 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12441 (defun org-block-todo-from-checkboxes (change-plist)
12442 "Block turning an entry into a TODO, using checkboxes.
12443 This checks whether the current task should be blocked from state
12444 changes because there are unchecked boxes in this entry."
12445 (if (not org-enforce-todo-checkbox-dependencies)
12446 t ; if locally turned off don't block
12447 (catch 'dont-block
12448 ;; If this is not a todo state change, or if this entry is already DONE,
12449 ;; do not block
12450 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12451 (member (plist-get change-plist :from)
12452 (cons 'done org-done-keywords))
12453 (member (plist-get change-plist :to)
12454 (cons 'todo org-not-done-keywords))
12455 (not (plist-get change-plist :to)))
12456 (throw 'dont-block t))
12457 ;; If this task has checkboxes that are not checked, it's blocked
12458 (save-excursion
12459 (org-back-to-heading t)
12460 (let ((beg (point)) end)
12461 (outline-next-heading)
12462 (setq end (point))
12463 (goto-char beg)
12464 (if (org-list-search-forward
12465 (concat (org-item-beginning-re)
12466 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12467 "\\[[- ]\\]")
12468 end t)
12469 (progn
12470 (if (boundp 'org-blocked-by-checkboxes)
12471 (setq org-blocked-by-checkboxes t))
12472 (throw 'dont-block nil)))))
12473 t))) ; do not block
12475 (defun org-entry-blocked-p ()
12476 "Is the current entry blocked?"
12477 (org-with-silent-modifications
12478 (if (org-entry-get nil "NOBLOCKING")
12479 nil ;; Never block this entry
12480 (not (run-hook-with-args-until-failure
12481 'org-blocker-hook
12482 (list :type 'todo-state-change
12483 :position (point)
12484 :from 'todo
12485 :to 'done))))))
12487 (defun org-update-statistics-cookies (all)
12488 "Update the statistics cookie, either from TODO or from checkboxes.
12489 This should be called with the cursor in a line with a statistics cookie."
12490 (interactive "P")
12491 (if all
12492 (progn
12493 (org-update-checkbox-count 'all)
12494 (org-map-entries 'org-update-parent-todo-statistics))
12495 (if (not (org-at-heading-p))
12496 (org-update-checkbox-count)
12497 (let ((pos (point-marker))
12498 end l1 l2)
12499 (ignore-errors (org-back-to-heading t))
12500 (if (not (org-at-heading-p))
12501 (org-update-checkbox-count)
12502 (setq l1 (org-outline-level))
12503 (setq end (save-excursion
12504 (outline-next-heading)
12505 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12506 (point)))
12507 (if (and (save-excursion
12508 (re-search-forward
12509 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12510 (not (save-excursion (re-search-forward
12511 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12512 (org-update-checkbox-count)
12513 (if (and l2 (> l2 l1))
12514 (progn
12515 (goto-char end)
12516 (org-update-parent-todo-statistics))
12517 (goto-char pos)
12518 (beginning-of-line 1)
12519 (while (re-search-forward
12520 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12521 (point-at-eol) t)
12522 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12523 (goto-char pos)
12524 (move-marker pos nil)))))
12526 (defvar org-entry-property-inherited-from) ;; defined below
12527 (defun org-update-parent-todo-statistics ()
12528 "Update any statistics cookie in the parent of the current headline.
12529 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12530 the entire subtree and this will travel up the hierarchy and update
12531 statistics everywhere."
12532 (let* ((prop (save-excursion (org-up-heading-safe)
12533 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12534 (recursive (or (not org-hierarchical-todo-statistics)
12535 (and prop (string-match "\\<recursive\\>" prop))))
12536 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12538 (first t)
12539 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12540 level ltoggle l1 new ndel
12541 (cnt-all 0) (cnt-done 0) is-percent kwd
12542 checkbox-beg ov ovs ove cookie-present)
12543 (catch 'exit
12544 (save-excursion
12545 (beginning-of-line 1)
12546 (setq ltoggle (funcall outline-level))
12547 ;; Three situations are to consider:
12549 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12550 ;; to the top-level ancestor on the headline;
12552 ;; 2. If parent has "recursive" property, repeat up to the
12553 ;; headline setting that property, taking inheritance into
12554 ;; account;
12556 ;; 3. Else, move up to direct parent and proceed only once.
12557 (while (and (setq level (org-up-heading-safe))
12558 (or recursive first)
12559 (>= (point) lim))
12560 (setq first nil cookie-present nil)
12561 (unless (and level
12562 (not (string-match
12563 "\\<checkbox\\>"
12564 (downcase (or (org-entry-get nil "COOKIE_DATA")
12565 "")))))
12566 (throw 'exit nil))
12567 (while (re-search-forward box-re (point-at-eol) t)
12568 (setq cnt-all 0 cnt-done 0 cookie-present t)
12569 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12570 (save-match-data
12571 (unless (outline-next-heading) (throw 'exit nil))
12572 (while (and (looking-at org-complex-heading-regexp)
12573 (> (setq l1 (length (match-string 1))) level))
12574 (setq kwd (and (or recursive (= l1 ltoggle))
12575 (match-string 2)))
12576 (if (or (eq org-provide-todo-statistics 'all-headlines)
12577 (and (listp org-provide-todo-statistics)
12578 (or (member kwd org-provide-todo-statistics)
12579 (member kwd org-done-keywords))))
12580 (setq cnt-all (1+ cnt-all))
12581 (if (eq org-provide-todo-statistics t)
12582 (and kwd (setq cnt-all (1+ cnt-all)))))
12583 (and (member kwd org-done-keywords)
12584 (setq cnt-done (1+ cnt-done)))
12585 (outline-next-heading)))
12586 (setq new
12587 (if is-percent
12588 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12589 (format "[%d/%d]" cnt-done cnt-all))
12590 ndel (- (match-end 0) checkbox-beg))
12591 ;; handle overlays when updating cookie from column view
12592 (when (setq ov (car (overlays-at checkbox-beg)))
12593 (setq ovs (overlay-start ov) ove (overlay-end ov))
12594 (delete-overlay ov))
12595 (goto-char checkbox-beg)
12596 (insert new)
12597 (delete-region (point) (+ (point) ndel))
12598 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12599 (when ov (move-overlay ov ovs ove)))
12600 (when cookie-present
12601 (run-hook-with-args 'org-after-todo-statistics-hook
12602 cnt-done (- cnt-all cnt-done))))))
12603 (run-hooks 'org-todo-statistics-hook)))
12605 (defvar org-after-todo-statistics-hook nil
12606 "Hook that is called after a TODO statistics cookie has been updated.
12607 Each function is called with two arguments: the number of not-done entries
12608 and the number of done entries.
12610 For example, the following function, when added to this hook, will switch
12611 an entry to DONE when all children are done, and back to TODO when new
12612 entries are set to a TODO status. Note that this hook is only called
12613 when there is a statistics cookie in the headline!
12615 (defun org-summary-todo (n-done n-not-done)
12616 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12617 (let (org-log-done org-log-states) ; turn off logging
12618 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12621 (defvar org-todo-statistics-hook nil
12622 "Hook that is run whenever Org thinks TODO statistics should be updated.
12623 This hook runs even if there is no statistics cookie present, in which case
12624 `org-after-todo-statistics-hook' would not run.")
12626 (defun org-todo-trigger-tag-changes (state)
12627 "Apply the changes defined in `org-todo-state-tags-triggers'."
12628 (let ((l org-todo-state-tags-triggers)
12629 changes)
12630 (when (or (not state) (equal state ""))
12631 (setq changes (append changes (cdr (assoc "" l)))))
12632 (when (and (stringp state) (> (length state) 0))
12633 (setq changes (append changes (cdr (assoc state l)))))
12634 (when (member state org-not-done-keywords)
12635 (setq changes (append changes (cdr (assoc 'todo l)))))
12636 (when (member state org-done-keywords)
12637 (setq changes (append changes (cdr (assoc 'done l)))))
12638 (dolist (c changes)
12639 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12641 (defun org-local-logging (value)
12642 "Get logging settings from a property VALUE."
12643 (let* (words w a)
12644 ;; directly set the variables, they are already local.
12645 (setq org-log-done nil
12646 org-log-repeat nil
12647 org-todo-log-states nil)
12648 (setq words (org-split-string value))
12649 (while (setq w (pop words))
12650 (cond
12651 ((setq a (assoc w org-startup-options))
12652 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12653 (set (nth 1 a) (nth 2 a))))
12654 ((setq a (org-extract-log-state-settings w))
12655 (and (member (car a) org-todo-keywords-1)
12656 (push a org-todo-log-states)))))))
12658 (defun org-get-todo-sequence-head (kwd)
12659 "Return the head of the TODO sequence to which KWD belongs.
12660 If KWD is not set, check if there is a text property remembering the
12661 right sequence."
12662 (let (p)
12663 (cond
12664 ((not kwd)
12665 (or (get-text-property (point-at-bol) 'org-todo-head)
12666 (progn
12667 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12668 nil (point-at-eol)))
12669 (get-text-property p 'org-todo-head))))
12670 ((not (member kwd org-todo-keywords-1))
12671 (car org-todo-keywords-1))
12672 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12674 (defun org-fast-todo-selection ()
12675 "Fast TODO keyword selection with single keys.
12676 Returns the new TODO keyword, or nil if no state change should occur."
12677 (let* ((fulltable org-todo-key-alist)
12678 (done-keywords org-done-keywords) ;; needed for the faces.
12679 (maxlen (apply 'max (mapcar
12680 (lambda (x)
12681 (if (stringp (car x)) (string-width (car x)) 0))
12682 fulltable)))
12683 (expert nil)
12684 (fwidth (+ maxlen 3 1 3))
12685 (ncol (/ (- (window-width) 4) fwidth))
12686 tg cnt e c tbl
12687 groups ingroup)
12688 (save-excursion
12689 (save-window-excursion
12690 (if expert
12691 (set-buffer (get-buffer-create " *Org todo*"))
12692 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12693 (erase-buffer)
12694 (org-set-local 'org-done-keywords done-keywords)
12695 (setq tbl fulltable cnt 0)
12696 (while (setq e (pop tbl))
12697 (cond
12698 ((equal e '(:startgroup))
12699 (push '() groups) (setq ingroup t)
12700 (when (not (= cnt 0))
12701 (setq cnt 0)
12702 (insert "\n"))
12703 (insert "{ "))
12704 ((equal e '(:endgroup))
12705 (setq ingroup nil cnt 0)
12706 (insert "}\n"))
12707 ((equal e '(:newline))
12708 (when (not (= cnt 0))
12709 (setq cnt 0)
12710 (insert "\n")
12711 (setq e (car tbl))
12712 (while (equal (car tbl) '(:newline))
12713 (insert "\n")
12714 (setq tbl (cdr tbl)))))
12716 (setq tg (car e) c (cdr e))
12717 (if ingroup (push tg (car groups)))
12718 (setq tg (org-add-props tg nil 'face
12719 (org-get-todo-face tg)))
12720 (if (and (= cnt 0) (not ingroup)) (insert " "))
12721 (insert "[" c "] " tg (make-string
12722 (- fwidth 4 (length tg)) ?\ ))
12723 (when (= (setq cnt (1+ cnt)) ncol)
12724 (insert "\n")
12725 (if ingroup (insert " "))
12726 (setq cnt 0)))))
12727 (insert "\n")
12728 (goto-char (point-min))
12729 (if (not expert) (org-fit-window-to-buffer))
12730 (message "[a-z..]:Set [SPC]:clear")
12731 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12732 (cond
12733 ((or (= c ?\C-g)
12734 (and (= c ?q) (not (rassoc c fulltable))))
12735 (setq quit-flag t))
12736 ((= c ?\ ) nil)
12737 ((setq e (rassoc c fulltable) tg (car e))
12739 (t (setq quit-flag t)))))))
12741 (defun org-entry-is-todo-p ()
12742 (member (org-get-todo-state) org-not-done-keywords))
12744 (defun org-entry-is-done-p ()
12745 (member (org-get-todo-state) org-done-keywords))
12747 (defun org-get-todo-state ()
12748 "Return the TODO keyword of the current subtree."
12749 (save-excursion
12750 (org-back-to-heading t)
12751 (and (looking-at org-todo-line-regexp)
12752 (match-end 2)
12753 (match-string 2))))
12755 (defun org-at-date-range-p (&optional inactive-ok)
12756 "Is the cursor inside a date range?"
12757 (interactive)
12758 (save-excursion
12759 (catch 'exit
12760 (let ((pos (point)))
12761 (skip-chars-backward "^[<\r\n")
12762 (skip-chars-backward "<[")
12763 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12764 (>= (match-end 0) pos)
12765 (throw 'exit t))
12766 (skip-chars-backward "^<[\r\n")
12767 (skip-chars-backward "<[")
12768 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12769 (>= (match-end 0) pos)
12770 (throw 'exit t)))
12771 nil)))
12773 (defun org-get-repeat (&optional tagline)
12774 "Check if there is a deadline/schedule with repeater in this entry."
12775 (save-match-data
12776 (save-excursion
12777 (org-back-to-heading t)
12778 (and (re-search-forward (if tagline
12779 (concat tagline "\\s-*" org-repeat-re)
12780 org-repeat-re)
12781 (org-entry-end-position) t)
12782 (match-string-no-properties 1)))))
12784 (defvar org-last-changed-timestamp)
12785 (defvar org-last-inserted-timestamp)
12786 (defvar org-log-post-message)
12787 (defvar org-log-note-purpose)
12788 (defvar org-log-note-how)
12789 (defvar org-log-note-extra)
12790 (defun org-auto-repeat-maybe (done-word)
12791 "Check if the current headline contains a repeated deadline/schedule.
12792 If yes, set TODO state back to what it was and change the base date
12793 of repeating deadline/scheduled time stamps to new date.
12794 This function is run automatically after each state change to a DONE state."
12795 ;; last-state is dynamically scoped into this function
12796 (let* ((repeat (org-get-repeat))
12797 (aa (assoc org-last-state org-todo-kwd-alist))
12798 (interpret (nth 1 aa))
12799 (head (nth 2 aa))
12800 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12801 (msg "Entry repeats: ")
12802 (org-log-done nil)
12803 (org-todo-log-states nil)
12804 re type n what ts time to-state)
12805 (when repeat
12806 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12807 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12808 org-todo-repeat-to-state))
12809 (unless (and to-state (member to-state org-todo-keywords-1))
12810 (setq to-state (if (eq interpret 'type) org-last-state head)))
12811 (org-todo to-state)
12812 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12813 (org-entry-put nil "LAST_REPEAT" (format-time-string
12814 (org-time-stamp-format t t))))
12815 (when org-log-repeat
12816 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12817 (memq 'org-add-log-note post-command-hook))
12818 ;; OK, we are already setup for some record
12819 (if (eq org-log-repeat 'note)
12820 ;; make sure we take a note, not only a time stamp
12821 (setq org-log-note-how 'note))
12822 ;; Set up for taking a record
12823 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12824 org-last-state
12825 'findpos org-log-repeat)))
12826 (org-back-to-heading t)
12827 (org-add-planning-info nil nil 'closed)
12828 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12829 org-deadline-time-regexp "\\)\\|\\("
12830 org-ts-regexp "\\)"))
12831 (while (re-search-forward
12832 re (save-excursion (outline-next-heading) (point)) t)
12833 (setq type (if (match-end 1) org-scheduled-string
12834 (if (match-end 3) org-deadline-string "Plain:"))
12835 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12836 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12837 (setq n (string-to-number (match-string 2 ts))
12838 what (match-string 3 ts))
12839 (if (equal what "w") (setq n (* n 7) what "d"))
12840 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12841 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12842 ;; Preparation, see if we need to modify the start date for the change
12843 (when (match-end 1)
12844 (setq time (save-match-data (org-time-string-to-time ts)))
12845 (cond
12846 ((equal (match-string 1 ts) ".")
12847 ;; Shift starting date to today
12848 (org-timestamp-change
12849 (- (org-today) (time-to-days time))
12850 'day))
12851 ((equal (match-string 1 ts) "+")
12852 (let ((nshiftmax 10) (nshift 0))
12853 (while (or (= nshift 0)
12854 (<= (time-to-days time)
12855 (time-to-days (current-time))))
12856 (when (= (incf nshift) nshiftmax)
12857 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12858 (error "Abort")))
12859 (org-timestamp-change n (cdr (assoc what whata)))
12860 (org-at-timestamp-p t)
12861 (setq ts (match-string 1))
12862 (setq time (save-match-data (org-time-string-to-time ts)))))
12863 (org-timestamp-change (- n) (cdr (assoc what whata)))
12864 ;; rematch, so that we have everything in place for the real shift
12865 (org-at-timestamp-p t)
12866 (setq ts (match-string 1))
12867 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12868 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12869 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12870 (setq org-log-post-message msg)
12871 (message "%s" msg))))
12873 (defun org-show-todo-tree (arg)
12874 "Make a compact tree which shows all headlines marked with TODO.
12875 The tree will show the lines where the regexp matches, and all higher
12876 headlines above the match.
12877 With a \\[universal-argument] prefix, prompt for a regexp to match.
12878 With a numeric prefix N, construct a sparse tree for the Nth element
12879 of `org-todo-keywords-1'."
12880 (interactive "P")
12881 (let ((case-fold-search nil)
12882 (kwd-re
12883 (cond ((null arg) org-not-done-regexp)
12884 ((equal arg '(4))
12885 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12886 (mapcar 'list org-todo-keywords-1))))
12887 (concat "\\("
12888 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12889 "\\)\\>")))
12890 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12891 (regexp-quote (nth (1- (prefix-numeric-value arg))
12892 org-todo-keywords-1)))
12893 (t (user-error "Invalid prefix argument: %s" arg)))))
12894 (message "%d TODO entries found"
12895 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12897 (defun org-deadline (arg &optional time)
12898 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12899 With one universal prefix argument, remove any deadline from the item.
12900 With two universal prefix arguments, prompt for a warning delay.
12901 With argument TIME, set the deadline at the corresponding date. TIME
12902 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12903 (interactive "P")
12904 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12905 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12906 'region-start-level 'region))
12907 org-loop-over-headlines-in-active-region)
12908 (org-map-entries
12909 `(org-deadline ',arg ,time)
12910 org-loop-over-headlines-in-active-region
12911 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12912 (let* ((old-date (org-entry-get nil "DEADLINE"))
12913 (old-date-time (if old-date (org-time-string-to-time old-date)))
12914 (repeater (and old-date
12915 (string-match
12916 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12917 old-date)
12918 (match-string 1 old-date))))
12919 (cond
12920 ((equal arg '(4))
12921 (when (and old-date org-log-redeadline)
12922 (org-add-log-setup 'deldeadline nil old-date 'findpos
12923 org-log-redeadline))
12924 (org-remove-timestamp-with-keyword org-deadline-string)
12925 (message "Item no longer has a deadline."))
12926 ((equal arg '(16))
12927 (save-excursion
12928 (if (re-search-forward
12929 org-deadline-time-regexp
12930 (save-excursion (outline-next-heading) (point)) t)
12931 (let* ((rpl0 (match-string 1))
12932 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12933 (replace-match
12934 (concat org-deadline-string
12935 " <" rpl
12936 (format " -%dd"
12937 (abs
12938 (- (time-to-days
12939 (save-match-data
12940 (org-read-date nil t nil "Warn starting from" old-date-time)))
12941 (time-to-days old-date-time))))
12942 ">") t t))
12943 (user-error "No deadline information to update"))))
12945 (org-add-planning-info 'deadline time 'closed)
12946 (when (and old-date org-log-redeadline
12947 (not (equal old-date
12948 (substring org-last-inserted-timestamp 1 -1))))
12949 (org-add-log-setup 'redeadline nil old-date 'findpos
12950 org-log-redeadline))
12951 (when repeater
12952 (save-excursion
12953 (org-back-to-heading t)
12954 (when (re-search-forward (concat org-deadline-string " "
12955 org-last-inserted-timestamp)
12956 (save-excursion
12957 (outline-next-heading) (point)) t)
12958 (goto-char (1- (match-end 0)))
12959 (insert " " repeater)
12960 (setq org-last-inserted-timestamp
12961 (concat (substring org-last-inserted-timestamp 0 -1)
12962 " " repeater
12963 (substring org-last-inserted-timestamp -1))))))
12964 (message "Deadline on %s" org-last-inserted-timestamp))))))
12966 (defun org-schedule (arg &optional time)
12967 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12968 With one universal prefix argument, remove any scheduling date from the item.
12969 With two universal prefix arguments, prompt for a delay cookie.
12970 With argument TIME, scheduled at the corresponding date. TIME can
12971 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12972 (interactive "P")
12973 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12974 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12975 'region-start-level 'region))
12976 org-loop-over-headlines-in-active-region)
12977 (org-map-entries
12978 `(org-schedule ',arg ,time)
12979 org-loop-over-headlines-in-active-region
12980 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12981 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12982 (old-date-time (if old-date (org-time-string-to-time old-date)))
12983 (repeater (and old-date
12984 (string-match
12985 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12986 old-date)
12987 (match-string 1 old-date))))
12988 (cond
12989 ((equal arg '(4))
12990 (progn
12991 (when (and old-date org-log-reschedule)
12992 (org-add-log-setup 'delschedule nil old-date 'findpos
12993 org-log-reschedule))
12994 (org-remove-timestamp-with-keyword org-scheduled-string)
12995 (message "Item is no longer scheduled.")))
12996 ((equal arg '(16))
12997 (save-excursion
12998 (if (re-search-forward
12999 org-scheduled-time-regexp
13000 (save-excursion (outline-next-heading) (point)) t)
13001 (let* ((rpl0 (match-string 1))
13002 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13003 (replace-match
13004 (concat org-scheduled-string
13005 " <" rpl
13006 (format " -%dd"
13007 (abs
13008 (- (time-to-days
13009 (save-match-data
13010 (org-read-date nil t nil "Delay until" old-date-time)))
13011 (time-to-days old-date-time))))
13012 ">") t t))
13013 (user-error "No scheduled information to update"))))
13015 (org-add-planning-info 'scheduled time 'closed)
13016 (when (and old-date org-log-reschedule
13017 (not (equal old-date
13018 (substring org-last-inserted-timestamp 1 -1))))
13019 (org-add-log-setup 'reschedule nil old-date 'findpos
13020 org-log-reschedule))
13021 (when repeater
13022 (save-excursion
13023 (org-back-to-heading t)
13024 (when (re-search-forward (concat org-scheduled-string " "
13025 org-last-inserted-timestamp)
13026 (save-excursion
13027 (outline-next-heading) (point)) t)
13028 (goto-char (1- (match-end 0)))
13029 (insert " " repeater)
13030 (setq org-last-inserted-timestamp
13031 (concat (substring org-last-inserted-timestamp 0 -1)
13032 " " repeater
13033 (substring org-last-inserted-timestamp -1))))))
13034 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13036 (defun org-get-scheduled-time (pom &optional inherit)
13037 "Get the scheduled time as a time tuple, of a format suitable
13038 for calling org-schedule with, or if there is no scheduling,
13039 returns nil."
13040 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13041 (when time
13042 (apply 'encode-time (org-parse-time-string time)))))
13044 (defun org-get-deadline-time (pom &optional inherit)
13045 "Get the deadline as a time tuple, of a format suitable for
13046 calling org-deadline with, or if there is no scheduling, returns
13047 nil."
13048 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13049 (when time
13050 (apply 'encode-time (org-parse-time-string time)))))
13052 (defun org-remove-timestamp-with-keyword (keyword)
13053 "Remove all time stamps with KEYWORD in the current entry."
13054 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13055 beg)
13056 (save-excursion
13057 (org-back-to-heading t)
13058 (setq beg (point))
13059 (outline-next-heading)
13060 (while (re-search-backward re beg t)
13061 (replace-match "")
13062 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13063 (equal (char-before) ?\ ))
13064 (backward-delete-char 1)
13065 (if (string-match "^[ \t]*$" (buffer-substring
13066 (point-at-bol) (point-at-eol)))
13067 (delete-region (point-at-bol)
13068 (min (point-max) (1+ (point-at-eol))))))))))
13070 (defun org-add-planning-info (what &optional time &rest remove)
13071 "Insert new timestamp with keyword in the line directly after the headline.
13072 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13073 If non is given, the user is prompted for a date.
13074 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13075 be removed."
13076 (interactive)
13077 (let (org-time-was-given org-end-time-was-given ts
13078 end default-time default-input)
13080 (catch 'exit
13081 (when (and (memq what '(scheduled deadline))
13082 (or (not time)
13083 (and (stringp time)
13084 (string-match "^[-+]+[0-9]" time))))
13085 ;; Try to get a default date/time from existing timestamp
13086 (save-excursion
13087 (org-back-to-heading t)
13088 (setq end (save-excursion (outline-next-heading) (point)))
13089 (when (re-search-forward (if (eq what 'scheduled)
13090 org-scheduled-time-regexp
13091 org-deadline-time-regexp)
13092 end t)
13093 (setq ts (match-string 1)
13094 default-time
13095 (apply 'encode-time (org-parse-time-string ts))
13096 default-input (and ts (org-get-compact-tod ts))))))
13097 (when what
13098 (setq time
13099 (if (stringp time)
13100 ;; This is a string (relative or absolute), set proper date
13101 (apply 'encode-time
13102 (org-read-date-analyze
13103 time default-time (decode-time default-time)))
13104 ;; If necessary, get the time from the user
13105 (or time (org-read-date nil 'to-time nil nil
13106 default-time default-input)))))
13108 (when (and org-insert-labeled-timestamps-at-point
13109 (member what '(scheduled deadline)))
13110 (insert
13111 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13112 (org-insert-time-stamp time org-time-was-given
13113 nil nil nil (list org-end-time-was-given))
13114 (setq what nil))
13115 (save-excursion
13116 (save-restriction
13117 (let (col list elt ts buffer-invisibility-spec)
13118 (org-back-to-heading t)
13119 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13120 (goto-char (match-end 1))
13121 (setq col (current-column))
13122 (goto-char (match-end 0))
13123 (if (eobp) (insert "\n") (forward-char 1))
13124 (when (and (not what)
13125 (not (looking-at
13126 (concat "[ \t]*"
13127 org-keyword-time-not-clock-regexp))))
13128 ;; Nothing to add, nothing to remove...... :-)
13129 (throw 'exit nil))
13130 (if (and (not (looking-at org-outline-regexp))
13131 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13132 "[^\r\n]*"))
13133 (not (equal (match-string 1) org-clock-string)))
13134 (narrow-to-region (match-beginning 0) (match-end 0))
13135 (insert-before-markers "\n")
13136 (backward-char 1)
13137 (narrow-to-region (point) (point))
13138 (and org-adapt-indentation (org-indent-to-column col)))
13139 ;; Check if we have to remove something.
13140 (setq list (cons what remove))
13141 (while list
13142 (setq elt (pop list))
13143 (when (or (and (eq elt 'scheduled)
13144 (re-search-forward org-scheduled-time-regexp nil t))
13145 (and (eq elt 'deadline)
13146 (re-search-forward org-deadline-time-regexp nil t))
13147 (and (eq elt 'closed)
13148 (re-search-forward org-closed-time-regexp nil t)))
13149 (replace-match "")
13150 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13151 (and (looking-at "[ \t]+") (replace-match ""))
13152 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13153 (when what
13154 (insert
13155 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13156 (cond ((eq what 'scheduled) org-scheduled-string)
13157 ((eq what 'deadline) org-deadline-string)
13158 ((eq what 'closed) org-closed-string))
13159 " ")
13160 (setq ts (org-insert-time-stamp
13161 time
13162 (or org-time-was-given
13163 (and (eq what 'closed) org-log-done-with-time))
13164 (eq what 'closed)
13165 nil nil (list org-end-time-was-given)))
13166 (insert
13167 (if (not (or (bolp) (eq (char-before) ?\ )
13168 (memq (char-after) '(32 10))
13169 (eobp))) " " ""))
13170 (end-of-line 1))
13171 (goto-char (point-min))
13172 (widen)
13173 (if (and (looking-at "[ \t]*\n")
13174 (equal (char-before) ?\n))
13175 (delete-region (1- (point)) (point-at-eol)))
13176 ts))))))
13178 (defvar org-log-note-marker (make-marker))
13179 (defvar org-log-note-purpose nil)
13180 (defvar org-log-note-state nil)
13181 (defvar org-log-note-previous-state nil)
13182 (defvar org-log-note-how nil)
13183 (defvar org-log-note-extra nil)
13184 (defvar org-log-note-window-configuration nil)
13185 (defvar org-log-note-return-to (make-marker))
13186 (defvar org-log-note-effective-time nil
13187 "Remembered current time so that dynamically scoped
13188 `org-extend-today-until' affects tha timestamps in state change
13189 log")
13191 (defvar org-log-post-message nil
13192 "Message to be displayed after a log note has been stored.
13193 The auto-repeater uses this.")
13195 (defun org-add-note ()
13196 "Add a note to the current entry.
13197 This is done in the same way as adding a state change note."
13198 (interactive)
13199 (org-add-log-setup 'note nil nil 'findpos nil))
13201 (defvar org-property-end-re)
13202 (defun org-add-log-setup (&optional purpose state prev-state
13203 findpos how extra)
13204 "Set up the post command hook to take a note.
13205 If this is about to TODO state change, the new state is expected in STATE.
13206 When FINDPOS is non-nil, find the correct position for the note in
13207 the current entry. If not, assume that it can be inserted at point.
13208 HOW is an indicator what kind of note should be created.
13209 EXTRA is additional text that will be inserted into the notes buffer."
13210 (let* ((org-log-into-drawer (org-log-into-drawer))
13211 (drawer (cond ((stringp org-log-into-drawer)
13212 org-log-into-drawer)
13213 (org-log-into-drawer "LOGBOOK"))))
13214 (save-restriction
13215 (save-excursion
13216 (when findpos
13217 (org-back-to-heading t)
13218 (narrow-to-region (point) (save-excursion
13219 (outline-next-heading) (point)))
13220 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13221 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13222 "[^\r\n]*\\)?"))
13223 (goto-char (match-end 0))
13224 (cond
13225 (drawer
13226 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13227 nil t)
13228 (progn
13229 (goto-char (match-end 0))
13230 (or org-log-states-order-reversed
13231 (and (re-search-forward org-property-end-re nil t)
13232 (goto-char (1- (match-beginning 0))))))
13233 (insert "\n:" drawer ":\n:END:")
13234 (beginning-of-line 0)
13235 (org-indent-line)
13236 (beginning-of-line 2)
13237 (org-indent-line)
13238 (end-of-line 0)))
13239 ((and org-log-state-notes-insert-after-drawers
13240 (save-excursion
13241 (forward-line) (looking-at org-drawer-regexp)))
13242 (forward-line)
13243 (while (looking-at org-drawer-regexp)
13244 (goto-char (match-end 0))
13245 (re-search-forward org-property-end-re (point-max) t)
13246 (forward-line))
13247 (forward-line -1)))
13248 (unless org-log-states-order-reversed
13249 (and (= (char-after) ?\n) (forward-char 1))
13250 (org-skip-over-state-notes)
13251 (skip-chars-backward " \t\n\r")))
13252 (move-marker org-log-note-marker (point))
13253 (setq org-log-note-purpose purpose
13254 org-log-note-state state
13255 org-log-note-previous-state prev-state
13256 org-log-note-how how
13257 org-log-note-extra extra
13258 org-log-note-effective-time (org-current-effective-time))
13259 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13261 (defun org-skip-over-state-notes ()
13262 "Skip past the list of State notes in an entry."
13263 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13264 (when (ignore-errors (goto-char (org-in-item-p)))
13265 (let* ((struct (org-list-struct))
13266 (prevs (org-list-prevs-alist struct)))
13267 (while (looking-at "[ \t]*- State")
13268 (goto-char (or (org-list-get-next-item (point) struct prevs)
13269 (org-list-get-item-end (point) struct)))))))
13271 (defun org-add-log-note (&optional purpose)
13272 "Pop up a window for taking a note, and add this note later at point."
13273 (remove-hook 'post-command-hook 'org-add-log-note)
13274 (setq org-log-note-window-configuration (current-window-configuration))
13275 (delete-other-windows)
13276 (move-marker org-log-note-return-to (point))
13277 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13278 (goto-char org-log-note-marker)
13279 (org-switch-to-buffer-other-window "*Org Note*")
13280 (erase-buffer)
13281 (if (memq org-log-note-how '(time state))
13282 (let (current-prefix-arg) (org-store-log-note))
13283 (let ((org-inhibit-startup t)) (org-mode))
13284 (insert (format "# Insert note for %s.
13285 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13286 (cond
13287 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13288 ((eq org-log-note-purpose 'done) "closed todo item")
13289 ((eq org-log-note-purpose 'state)
13290 (format "state change from \"%s\" to \"%s\""
13291 (or org-log-note-previous-state "")
13292 (or org-log-note-state "")))
13293 ((eq org-log-note-purpose 'reschedule)
13294 "rescheduling")
13295 ((eq org-log-note-purpose 'delschedule)
13296 "no longer scheduled")
13297 ((eq org-log-note-purpose 'redeadline)
13298 "changing deadline")
13299 ((eq org-log-note-purpose 'deldeadline)
13300 "removing deadline")
13301 ((eq org-log-note-purpose 'refile)
13302 "refiling")
13303 ((eq org-log-note-purpose 'note)
13304 "this entry")
13305 (t (error "This should not happen")))))
13306 (if org-log-note-extra (insert org-log-note-extra))
13307 (org-set-local 'org-finish-function 'org-store-log-note)
13308 (run-hooks 'org-log-buffer-setup-hook)))
13310 (defvar org-note-abort nil) ; dynamically scoped
13311 (defun org-store-log-note ()
13312 "Finish taking a log note, and insert it to where it belongs."
13313 (let ((txt (buffer-string)))
13314 (kill-buffer (current-buffer))
13315 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13316 lines ind bul)
13317 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13318 (setq txt (replace-match "" t t txt)))
13319 (if (string-match "\\s-+\\'" txt)
13320 (setq txt (replace-match "" t t txt)))
13321 (setq lines (org-split-string txt "\n"))
13322 (when (and note (string-match "\\S-" note))
13323 (setq note
13324 (org-replace-escapes
13325 note
13326 (list (cons "%u" (user-login-name))
13327 (cons "%U" user-full-name)
13328 (cons "%t" (format-time-string
13329 (org-time-stamp-format 'long 'inactive)
13330 org-log-note-effective-time))
13331 (cons "%T" (format-time-string
13332 (org-time-stamp-format 'long nil)
13333 org-log-note-effective-time))
13334 (cons "%d" (format-time-string
13335 (org-time-stamp-format nil 'inactive)
13336 org-log-note-effective-time))
13337 (cons "%D" (format-time-string
13338 (org-time-stamp-format nil nil)
13339 org-log-note-effective-time))
13340 (cons "%s" (if org-log-note-state
13341 (concat "\"" org-log-note-state "\"")
13342 ""))
13343 (cons "%S" (if org-log-note-previous-state
13344 (concat "\"" org-log-note-previous-state "\"")
13345 "\"\"")))))
13346 (if lines (setq note (concat note " \\\\")))
13347 (push note lines))
13348 (when (or current-prefix-arg org-note-abort)
13349 (when org-log-into-drawer
13350 (org-remove-empty-drawer-at
13351 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13352 org-log-note-marker))
13353 (setq lines nil))
13354 (when lines
13355 (with-current-buffer (marker-buffer org-log-note-marker)
13356 (save-excursion
13357 (goto-char org-log-note-marker)
13358 (move-marker org-log-note-marker nil)
13359 (end-of-line 1)
13360 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13361 (setq ind (save-excursion
13362 (if (ignore-errors (goto-char (org-in-item-p)))
13363 (let ((struct (org-list-struct)))
13364 (org-list-get-ind
13365 (org-list-get-top-point struct) struct))
13366 (skip-chars-backward " \r\t\n")
13367 (cond
13368 ((and (org-at-heading-p)
13369 org-adapt-indentation)
13370 (1+ (org-current-level)))
13371 ((org-at-heading-p) 0)
13372 (t (org-get-indentation))))))
13373 (setq bul (org-list-bullet-string "-"))
13374 (org-indent-line-to ind)
13375 (insert bul (pop lines))
13376 (let ((ind-body (+ (length bul) ind)))
13377 (while lines
13378 (insert "\n")
13379 (org-indent-line-to ind-body)
13380 (insert (pop lines))))
13381 (message "Note stored")
13382 (org-back-to-heading t)
13383 (org-cycle-hide-drawers 'children))
13384 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13385 ;; from within `org-add-log-note' because `buffer-undo-list'
13386 ;; is then modified outside of `org-with-remote-undo'.
13387 (when (eq this-command 'org-agenda-todo)
13388 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13389 ;; Don't add undo information when called from `org-agenda-todo'
13390 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13391 (set-window-configuration org-log-note-window-configuration)
13392 (with-current-buffer (marker-buffer org-log-note-return-to)
13393 (goto-char org-log-note-return-to))
13394 (move-marker org-log-note-return-to nil)
13395 (and org-log-post-message (message "%s" org-log-post-message))))
13397 (defun org-remove-empty-drawer-at (drawer pos)
13398 "Remove an empty drawer DRAWER at position POS.
13399 POS may also be a marker."
13400 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13401 (save-excursion
13402 (save-restriction
13403 (widen)
13404 (goto-char pos)
13405 (if (org-in-regexp
13406 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13407 (replace-match ""))))))
13409 (defvar org-ts-type nil)
13410 (defun org-sparse-tree (&optional arg type)
13411 "Create a sparse tree, prompt for the details.
13412 This command can create sparse trees. You first need to select the type
13413 of match used to create the tree:
13415 t Show all TODO entries.
13416 T Show entries with a specific TODO keyword.
13417 m Show entries selected by a tags/property match.
13418 p Enter a property name and its value (both with completion on existing
13419 names/values) and show entries with that property.
13420 r Show entries matching a regular expression (`/' can be used as well).
13421 b Show deadlines and scheduled items before a date.
13422 a Show deadlines and scheduled items after a date.
13423 d Show deadlines due within `org-deadline-warning-days'.
13424 D Show deadlines and scheduled items between a date range."
13425 (interactive "P")
13426 (let (ans kwd value ts-type)
13427 (setq type (or type org-sparse-tree-default-date-type))
13428 (setq org-ts-type type)
13429 (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"
13430 (cond ((eq type 'all) "all timestamps")
13431 ((eq type 'scheduled) "only scheduled")
13432 ((eq type 'deadline) "only deadline")
13433 ((eq type 'active) "only active timestamps")
13434 ((eq type 'inactive) "only inactive timestamps")
13435 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13436 ((eq type 'closed) "with a closed time-stamp")
13437 (t "scheduled/deadline")))
13438 (setq ans (read-char-exclusive))
13439 (cond
13440 ((equal ans ?c)
13441 (org-sparse-tree
13442 arg (cadr (member type '(scheduled-or-deadline
13443 all scheduled deadline active inactive closed)))))
13444 ((equal ans ?d)
13445 (call-interactively 'org-check-deadlines))
13446 ((equal ans ?b)
13447 (call-interactively 'org-check-before-date))
13448 ((equal ans ?a)
13449 (call-interactively 'org-check-after-date))
13450 ((equal ans ?D)
13451 (call-interactively 'org-check-dates-range))
13452 ((equal ans ?t)
13453 (call-interactively 'org-show-todo-tree))
13454 ((equal ans ?T)
13455 (org-show-todo-tree '(4)))
13456 ((member ans '(?T ?m))
13457 (call-interactively 'org-match-sparse-tree))
13458 ((member ans '(?p ?P))
13459 (setq kwd (org-icompleting-read "Property: "
13460 (mapcar 'list (org-buffer-property-keys))))
13461 (setq value (org-icompleting-read "Value: "
13462 (mapcar 'list (org-property-values kwd))))
13463 (unless (string-match "\\`{.*}\\'" value)
13464 (setq value (concat "\"" value "\"")))
13465 (org-match-sparse-tree arg (concat kwd "=" value)))
13466 ((member ans '(?r ?R ?/))
13467 (call-interactively 'org-occur))
13468 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13470 (defvar org-occur-highlights nil
13471 "List of overlays used for occur matches.")
13472 (make-variable-buffer-local 'org-occur-highlights)
13473 (defvar org-occur-parameters nil
13474 "Parameters of the active org-occur calls.
13475 This is a list, each call to org-occur pushes as cons cell,
13476 containing the regular expression and the callback, onto the list.
13477 The list can contain several entries if `org-occur' has been called
13478 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13479 will only contain one set of parameters. When the highlights are
13480 removed (for example with `C-c C-c', or with the next edit (depending
13481 on `org-remove-highlights-with-change'), this variable is emptied
13482 as well.")
13483 (make-variable-buffer-local 'org-occur-parameters)
13485 (defun org-occur (regexp &optional keep-previous callback)
13486 "Make a compact tree which shows all matches of REGEXP.
13487 The tree will show the lines where the regexp matches, and all higher
13488 headlines above the match. It will also show the heading after the match,
13489 to make sure editing the matching entry is easy.
13490 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13491 call to `org-occur' will be kept, to allow stacking of calls to this
13492 command.
13493 If CALLBACK is non-nil, it is a function which is called to confirm
13494 that the match should indeed be shown."
13495 (interactive "sRegexp: \nP")
13496 (when (equal regexp "")
13497 (user-error "Regexp cannot be empty"))
13498 (unless keep-previous
13499 (org-remove-occur-highlights nil nil t))
13500 (push (cons regexp callback) org-occur-parameters)
13501 (let ((cnt 0))
13502 (save-excursion
13503 (goto-char (point-min))
13504 (if (or (not keep-previous) ; do not want to keep
13505 (not org-occur-highlights)) ; no previous matches
13506 ;; hide everything
13507 (org-overview))
13508 (while (re-search-forward regexp nil t)
13509 (when (or (not callback)
13510 (save-match-data (funcall callback)))
13511 (setq cnt (1+ cnt))
13512 (when org-highlight-sparse-tree-matches
13513 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13514 (org-show-context 'occur-tree))))
13515 (when org-remove-highlights-with-change
13516 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13517 nil 'local))
13518 (unless org-sparse-tree-open-archived-trees
13519 (org-hide-archived-subtrees (point-min) (point-max)))
13520 (run-hooks 'org-occur-hook)
13521 (if (org-called-interactively-p 'interactive)
13522 (message "%d match(es) for regexp %s" cnt regexp))
13523 cnt))
13525 (defun org-occur-next-match (&optional n reset)
13526 "Function for `next-error-function' to find sparse tree matches.
13527 N is the number of matches to move, when negative move backwards.
13528 RESET is entirely ignored - this function always goes back to the
13529 starting point when no match is found."
13530 (let* ((limit (if (< n 0) (point-min) (point-max)))
13531 (search-func (if (< n 0)
13532 'previous-single-char-property-change
13533 'next-single-char-property-change))
13534 (n (abs n))
13535 (pos (point))
13537 (catch 'exit
13538 (while (setq p1 (funcall search-func (point) 'org-type))
13539 (when (equal p1 limit)
13540 (goto-char pos)
13541 (error "No more matches"))
13542 (when (equal (get-char-property p1 'org-type) 'org-occur)
13543 (setq n (1- n))
13544 (when (= n 0)
13545 (goto-char p1)
13546 (throw 'exit (point))))
13547 (goto-char p1))
13548 (goto-char p1)
13549 (error "No more matches"))))
13551 (defun org-show-context (&optional key)
13552 "Make sure point and context are visible.
13553 How much context is shown depends upon the variables
13554 `org-show-hierarchy-above', `org-show-following-heading',
13555 `org-show-entry-below' and `org-show-siblings'."
13556 (let ((heading-p (org-at-heading-p t))
13557 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13558 (following-p (org-get-alist-option org-show-following-heading key))
13559 (entry-p (org-get-alist-option org-show-entry-below key))
13560 (siblings-p (org-get-alist-option org-show-siblings key)))
13561 ;; Show heading or entry text
13562 (if (and heading-p (not entry-p))
13563 (org-flag-heading nil) ; only show the heading
13564 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13565 (org-show-hidden-entry))) ; show entire entry
13566 (when following-p
13567 ;; Show next sibling, or heading below text
13568 (save-excursion
13569 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13570 (org-flag-heading nil))))
13571 (when siblings-p (org-show-siblings))
13572 (when hierarchy-p
13573 ;; show all higher headings, possibly with siblings
13574 (save-excursion
13575 (while (and (condition-case nil
13576 (progn (org-up-heading-all 1) t)
13577 (error nil))
13578 (not (bobp)))
13579 (org-flag-heading nil)
13580 (when siblings-p (org-show-siblings)))))
13581 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13583 (defvar org-reveal-start-hook nil
13584 "Hook run before revealing a location.")
13586 (defun org-reveal (&optional siblings)
13587 "Show current entry, hierarchy above it, and the following headline.
13588 This can be used to show a consistent set of context around locations
13589 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13590 not t for the search context.
13592 With optional argument SIBLINGS, on each level of the hierarchy all
13593 siblings are shown. This repairs the tree structure to what it would
13594 look like when opened with hierarchical calls to `org-cycle'.
13595 With double optional argument \\[universal-argument] \\[universal-argument], \
13596 go to the parent and show the
13597 entire tree."
13598 (interactive "P")
13599 (run-hooks 'org-reveal-start-hook)
13600 (let ((org-show-hierarchy-above t)
13601 (org-show-following-heading t)
13602 (org-show-siblings (if siblings t org-show-siblings)))
13603 (org-show-context nil))
13604 (when (equal siblings '(16))
13605 (save-excursion
13606 (when (org-up-heading-safe)
13607 (org-show-subtree)
13608 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13610 (defun org-highlight-new-match (beg end)
13611 "Highlight from BEG to END and mark the highlight is an occur headline."
13612 (let ((ov (make-overlay beg end)))
13613 (overlay-put ov 'face 'secondary-selection)
13614 (overlay-put ov 'org-type 'org-occur)
13615 (push ov org-occur-highlights)))
13617 (defun org-remove-occur-highlights (&optional beg end noremove)
13618 "Remove the occur highlights from the buffer.
13619 BEG and END are ignored. If NOREMOVE is nil, remove this function
13620 from the `before-change-functions' in the current buffer."
13621 (interactive)
13622 (unless org-inhibit-highlight-removal
13623 (mapc 'delete-overlay org-occur-highlights)
13624 (setq org-occur-highlights nil)
13625 (setq org-occur-parameters nil)
13626 (unless noremove
13627 (remove-hook 'before-change-functions
13628 'org-remove-occur-highlights 'local))))
13630 ;;;; Priorities
13632 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13633 "Regular expression matching the priority indicator.")
13635 (defvar org-remove-priority-next-time nil)
13637 (defun org-priority-up ()
13638 "Increase the priority of the current item."
13639 (interactive)
13640 (org-priority 'up))
13642 (defun org-priority-down ()
13643 "Decrease the priority of the current item."
13644 (interactive)
13645 (org-priority 'down))
13647 (defun org-priority (&optional action show)
13648 "Change the priority of an item.
13649 ACTION can be `set', `up', `down', or a character."
13650 (interactive "P")
13651 (if (equal action '(4))
13652 (org-show-priority)
13653 (unless org-enable-priority-commands
13654 (user-error "Priority commands are disabled"))
13655 (setq action (or action 'set))
13656 (let (current new news have remove)
13657 (save-excursion
13658 (org-back-to-heading t)
13659 (if (looking-at org-priority-regexp)
13660 (setq current (string-to-char (match-string 2))
13661 have t))
13662 (cond
13663 ((eq action 'remove)
13664 (setq remove t new ?\ ))
13665 ((or (eq action 'set)
13666 (if (featurep 'xemacs) (characterp action) (integerp action)))
13667 (if (not (eq action 'set))
13668 (setq new action)
13669 (message "Priority %c-%c, SPC to remove: "
13670 org-highest-priority org-lowest-priority)
13671 (save-match-data
13672 (setq new (read-char-exclusive))))
13673 (if (and (= (upcase org-highest-priority) org-highest-priority)
13674 (= (upcase org-lowest-priority) org-lowest-priority))
13675 (setq new (upcase new)))
13676 (cond ((equal new ?\ ) (setq remove t))
13677 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13678 (user-error "Priority must be between `%c' and `%c'"
13679 org-highest-priority org-lowest-priority))))
13680 ((eq action 'up)
13681 (setq new (if have
13682 (1- current) ; normal cycling
13683 ;; last priority was empty
13684 (if (eq last-command this-command)
13685 org-lowest-priority ; wrap around empty to lowest
13686 ;; default
13687 (if org-priority-start-cycle-with-default
13688 org-default-priority
13689 (1- org-default-priority))))))
13690 ((eq action 'down)
13691 (setq new (if have
13692 (1+ current) ; normal cycling
13693 ;; last priority was empty
13694 (if (eq last-command this-command)
13695 org-highest-priority ; wrap around empty to highest
13696 ;; default
13697 (if org-priority-start-cycle-with-default
13698 org-default-priority
13699 (1+ org-default-priority))))))
13700 (t (user-error "Invalid action")))
13701 (if (or (< (upcase new) org-highest-priority)
13702 (> (upcase new) org-lowest-priority))
13703 (if (and (memq action '(up down))
13704 (not have) (not (eq last-command this-command)))
13705 ;; `new' is from default priority
13706 (error
13707 "The default can not be set, see `org-default-priority' why")
13708 ;; normal cycling: `new' is beyond highest/lowest priority
13709 ;; and is wrapped around to the empty priority
13710 (setq remove t)))
13711 (setq news (format "%c" new))
13712 (if have
13713 (if remove
13714 (replace-match "" t t nil 1)
13715 (replace-match news t t nil 2))
13716 (if remove
13717 (user-error "No priority cookie found in line")
13718 (let ((case-fold-search nil))
13719 (looking-at org-todo-line-regexp))
13720 (if (match-end 2)
13721 (progn
13722 (goto-char (match-end 2))
13723 (insert " [#" news "]"))
13724 (goto-char (match-beginning 3))
13725 (insert "[#" news "] "))))
13726 (org-preserve-lc (org-set-tags nil 'align)))
13727 (if remove
13728 (message "Priority removed")
13729 (message "Priority of current item set to %s" news)))))
13731 (defun org-show-priority ()
13732 "Show the priority of the current item.
13733 This priority is composed of the main priority given with the [#A] cookies,
13734 and by additional input from the age of a schedules or deadline entry."
13735 (interactive)
13736 (let ((pri (if (eq major-mode 'org-agenda-mode)
13737 (org-get-at-bol 'priority)
13738 (save-excursion
13739 (save-match-data
13740 (beginning-of-line)
13741 (and (looking-at org-heading-regexp)
13742 (org-get-priority (match-string 0))))))))
13743 (message "Priority is %d" (if pri pri -1000))))
13745 (defun org-get-priority (s)
13746 "Find priority cookie and return priority."
13747 (save-match-data
13748 (if (functionp org-get-priority-function)
13749 (funcall org-get-priority-function)
13750 (if (not (string-match org-priority-regexp s))
13751 (* 1000 (- org-lowest-priority org-default-priority))
13752 (* 1000 (- org-lowest-priority
13753 (string-to-char (match-string 2 s))))))))
13755 ;;;; Tags
13757 (defvar org-agenda-archives-mode)
13758 (defvar org-map-continue-from nil
13759 "Position from where mapping should continue.
13760 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13762 (defvar org-scanner-tags nil
13763 "The current tag list while the tags scanner is running.")
13764 (defvar org-trust-scanner-tags nil
13765 "Should `org-get-tags-at' use the tags for the scanner.
13766 This is for internal dynamical scoping only.
13767 When this is non-nil, the function `org-get-tags-at' will return the value
13768 of `org-scanner-tags' instead of building the list by itself. This
13769 can lead to large speed-ups when the tags scanner is used in a file with
13770 many entries, and when the list of tags is retrieved, for example to
13771 obtain a list of properties. Building the tags list for each entry in such
13772 a file becomes an N^2 operation - but with this variable set, it scales
13773 as N.")
13775 (defun org-scan-tags (action matcher todo-only &optional start-level)
13776 "Sca headline tags with inheritance and produce output ACTION.
13778 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13779 or `agenda' to produce an entry list for an agenda view. It can also be
13780 a Lisp form or a function that should be called at each matched headline, in
13781 this case the return value is a list of all return values from these calls.
13783 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13784 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13785 only lines with a not-done TODO keyword are included in the output.
13786 This should be the same variable that was scoped into
13787 and set by `org-make-tags-matcher' when it constructed MATCHER.
13789 START-LEVEL can be a string with asterisks, reducing the scope to
13790 headlines matching this string."
13791 (require 'org-agenda)
13792 (let* ((re (concat "^"
13793 (if start-level
13794 ;; Get the correct level to match
13795 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13796 org-outline-regexp)
13797 " *\\(\\<\\("
13798 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13799 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13800 (props (list 'face 'default
13801 'done-face 'org-agenda-done
13802 'undone-face 'default
13803 'mouse-face 'highlight
13804 'org-not-done-regexp org-not-done-regexp
13805 'org-todo-regexp org-todo-regexp
13806 'org-complex-heading-regexp org-complex-heading-regexp
13807 'help-echo
13808 (format "mouse-2 or RET jump to org file %s"
13809 (abbreviate-file-name
13810 (or (buffer-file-name (buffer-base-buffer))
13811 (buffer-name (buffer-base-buffer)))))))
13812 (org-map-continue-from nil)
13813 lspos tags tags-list
13814 (tags-alist (list (cons 0 org-file-tags)))
13815 (llast 0) rtn rtn1 level category i txt
13816 todo marker entry priority)
13817 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13818 (setq action (list 'lambda nil action)))
13819 (save-excursion
13820 (goto-char (point-min))
13821 (when (eq action 'sparse-tree)
13822 (org-overview)
13823 (org-remove-occur-highlights))
13824 (while (let (case-fold-search)
13825 (re-search-forward re nil t))
13826 (setq org-map-continue-from nil)
13827 (catch :skip
13828 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13829 tags (if (match-end 4) (org-match-string-no-properties 4)))
13830 (goto-char (setq lspos (match-beginning 0)))
13831 (setq level (org-reduced-level (org-outline-level))
13832 category (org-get-category))
13833 (setq i llast llast level)
13834 ;; remove tag lists from same and sublevels
13835 (while (>= i level)
13836 (when (setq entry (assoc i tags-alist))
13837 (setq tags-alist (delete entry tags-alist)))
13838 (setq i (1- i)))
13839 ;; add the next tags
13840 (when tags
13841 (setq tags (org-split-string tags ":")
13842 tags-alist
13843 (cons (cons level tags) tags-alist)))
13844 ;; compile tags for current headline
13845 (setq tags-list
13846 (if org-use-tag-inheritance
13847 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13848 tags)
13849 org-scanner-tags tags-list)
13850 (when org-use-tag-inheritance
13851 (setcdr (car tags-alist)
13852 (mapcar (lambda (x)
13853 (setq x (copy-sequence x))
13854 (org-add-prop-inherited x))
13855 (cdar tags-alist))))
13856 (when (and tags org-use-tag-inheritance
13857 (or (not (eq t org-use-tag-inheritance))
13858 org-tags-exclude-from-inheritance))
13859 ;; selective inheritance, remove uninherited ones
13860 (setcdr (car tags-alist)
13861 (org-remove-uninherited-tags (cdar tags-alist))))
13862 (when (and
13864 ;; eval matcher only when the todo condition is OK
13865 (and (or (not todo-only) (member todo org-not-done-keywords))
13866 (let ((case-fold-search t) (org-trust-scanner-tags t))
13867 (eval matcher)))
13869 ;; Call the skipper, but return t if it does not skip,
13870 ;; so that the `and' form continues evaluating
13871 (progn
13872 (unless (eq action 'sparse-tree) (org-agenda-skip))
13875 ;; Check if timestamps are deselecting this entry
13876 (or (not todo-only)
13877 (and (member todo org-not-done-keywords)
13878 (or (not org-agenda-tags-todo-honor-ignore-options)
13879 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13881 ;; select this headline
13882 (cond
13883 ((eq action 'sparse-tree)
13884 (and org-highlight-sparse-tree-matches
13885 (org-get-heading) (match-end 0)
13886 (org-highlight-new-match
13887 (match-beginning 1) (match-end 1)))
13888 (org-show-context 'tags-tree))
13889 ((eq action 'agenda)
13890 (setq txt (org-agenda-format-item
13892 (concat
13893 (if (eq org-tags-match-list-sublevels 'indented)
13894 (make-string (1- level) ?.) "")
13895 (org-get-heading))
13896 level category
13897 tags-list)
13898 priority (org-get-priority txt))
13899 (goto-char lspos)
13900 (setq marker (org-agenda-new-marker))
13901 (org-add-props txt props
13902 'org-marker marker 'org-hd-marker marker 'org-category category
13903 'todo-state todo
13904 'priority priority 'type "tagsmatch")
13905 (push txt rtn))
13906 ((functionp action)
13907 (setq org-map-continue-from nil)
13908 (save-excursion
13909 (setq rtn1 (funcall action))
13910 (push rtn1 rtn)))
13911 (t (user-error "Invalid action")))
13913 ;; if we are to skip sublevels, jump to end of subtree
13914 (unless org-tags-match-list-sublevels
13915 (org-end-of-subtree t)
13916 (backward-char 1))))
13917 ;; Get the correct position from where to continue
13918 (if org-map-continue-from
13919 (goto-char org-map-continue-from)
13920 (and (= (point) lspos) (end-of-line 1)))))
13921 (when (and (eq action 'sparse-tree)
13922 (not org-sparse-tree-open-archived-trees))
13923 (org-hide-archived-subtrees (point-min) (point-max)))
13924 (nreverse rtn)))
13926 (defun org-remove-uninherited-tags (tags)
13927 "Remove all tags that are not inherited from the list TAGS."
13928 (cond
13929 ((eq org-use-tag-inheritance t)
13930 (if org-tags-exclude-from-inheritance
13931 (org-delete-all org-tags-exclude-from-inheritance tags)
13932 tags))
13933 ((not org-use-tag-inheritance) nil)
13934 ((stringp org-use-tag-inheritance)
13935 (delq nil (mapcar
13936 (lambda (x)
13937 (if (and (string-match org-use-tag-inheritance x)
13938 (not (member x org-tags-exclude-from-inheritance)))
13939 x nil))
13940 tags)))
13941 ((listp org-use-tag-inheritance)
13942 (delq nil (mapcar
13943 (lambda (x)
13944 (if (member x org-use-tag-inheritance) x nil))
13945 tags)))))
13947 (defun org-match-sparse-tree (&optional todo-only match)
13948 "Create a sparse tree according to tags string MATCH.
13949 MATCH can contain positive and negative selection of tags, like
13950 \"+WORK+URGENT-WITHBOSS\".
13951 If optional argument TODO-ONLY is non-nil, only select lines that are
13952 also TODO lines."
13953 (interactive "P")
13954 (org-agenda-prepare-buffers (list (current-buffer)))
13955 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13957 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13959 (defvar org-cached-props nil)
13960 (defun org-cached-entry-get (pom property)
13961 (if (or (eq t org-use-property-inheritance)
13962 (and (stringp org-use-property-inheritance)
13963 (string-match org-use-property-inheritance property))
13964 (and (listp org-use-property-inheritance)
13965 (member property org-use-property-inheritance)))
13966 ;; Caching is not possible, check it directly
13967 (org-entry-get pom property 'inherit)
13968 ;; Get all properties, so that we can do complicated checks easily
13969 (cdr (assoc property (or org-cached-props
13970 (setq org-cached-props
13971 (org-entry-properties pom)))))))
13973 (defun org-global-tags-completion-table (&optional files)
13974 "Return the list of all tags in all agenda buffer/files.
13975 Optional FILES argument is a list of files which can be used
13976 instead of the agenda files."
13977 (save-excursion
13978 (org-uniquify
13979 (delq nil
13980 (apply 'append
13981 (mapcar
13982 (lambda (file)
13983 (set-buffer (find-file-noselect file))
13984 (append (org-get-buffer-tags)
13985 (mapcar (lambda (x) (if (stringp (car-safe x))
13986 (list (car-safe x)) nil))
13987 org-tag-alist)))
13988 (if (and files (car files))
13989 files
13990 (org-agenda-files))))))))
13992 (defun org-make-tags-matcher (match)
13993 "Create the TAGS/TODO matcher form for the selection string MATCH.
13995 The variable `todo-only' is scoped dynamically into this function.
13996 It will be set to t if the matcher restricts matching to TODO entries,
13997 otherwise will not be touched.
13999 Returns a cons of the selection string MATCH and the constructed
14000 lisp form implementing the matcher. The matcher is to be evaluated
14001 at an Org entry, with point on the headline, and returns t if the
14002 entry matches the selection string MATCH. The returned lisp form
14003 references two variables with information about the entry, which
14004 must be bound around the form's evaluation: todo, the TODO keyword
14005 at the entry (or nil of none); and tags-list, the list of all tags
14006 at the entry including inherited ones. Additionally, the category
14007 of the entry (if any) must be specified as the text property
14008 'org-category on the headline.
14010 See also `org-scan-tags'.
14012 (declare (special todo-only))
14013 (unless (boundp 'todo-only)
14014 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14015 (unless match
14016 ;; Get a new match request, with completion against the global
14017 ;; tags table and the local tags in current buffer
14018 (let ((org-last-tags-completion-table
14019 (org-uniquify
14020 (delq nil (append (org-get-buffer-tags)
14021 (org-global-tags-completion-table))))))
14022 (setq match (org-completing-read-no-i
14023 "Match: " 'org-tags-completion-function nil nil nil
14024 'org-tags-history))))
14026 ;; Parse the string and create a lisp form
14027 (let ((match0 match)
14028 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14029 minus tag mm
14030 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14031 orterms term orlist re-p str-p level-p level-op time-p
14032 prop-p pn pv po gv rest)
14033 ;; Expand group tags
14034 (setq match (org-tags-expand match))
14035 (if (string-match "/+" match)
14036 ;; match contains also a todo-matching request
14037 (progn
14038 (setq tagsmatch (substring match 0 (match-beginning 0))
14039 todomatch (substring match (match-end 0)))
14040 (if (string-match "^!" todomatch)
14041 (setq todo-only t todomatch (substring todomatch 1)))
14042 (if (string-match "^\\s-*$" todomatch)
14043 (setq todomatch nil)))
14044 ;; only matching tags
14045 (setq tagsmatch match todomatch nil))
14047 ;; Make the tags matcher
14048 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14049 (setq tagsmatcher t)
14050 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14051 (while (setq term (pop orterms))
14052 (while (and (equal (substring term -1) "\\") orterms)
14053 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14054 (while (string-match re term)
14055 (setq rest (substring term (match-end 0))
14056 minus (and (match-end 1)
14057 (equal (match-string 1 term) "-"))
14058 tag (save-match-data (replace-regexp-in-string
14059 "\\\\-" "-"
14060 (match-string 2 term)))
14061 re-p (equal (string-to-char tag) ?{)
14062 level-p (match-end 4)
14063 prop-p (match-end 5)
14064 mm (cond
14065 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14066 (level-p
14067 (setq level-op (org-op-to-function (match-string 3 term)))
14068 `(,level-op level ,(string-to-number
14069 (match-string 4 term))))
14070 (prop-p
14071 (setq pn (match-string 5 term)
14072 po (match-string 6 term)
14073 pv (match-string 7 term)
14074 re-p (equal (string-to-char pv) ?{)
14075 str-p (equal (string-to-char pv) ?\")
14076 time-p (save-match-data
14077 (string-match "^\"[[<].*[]>]\"$" pv))
14078 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14079 (if time-p (setq pv (org-matcher-time pv)))
14080 (setq po (org-op-to-function po (if time-p 'time str-p)))
14081 (cond
14082 ((equal pn "CATEGORY")
14083 (setq gv '(get-text-property (point) 'org-category)))
14084 ((equal pn "TODO")
14085 (setq gv 'todo))
14087 (setq gv `(org-cached-entry-get nil ,pn))))
14088 (if re-p
14089 (if (eq po 'org<>)
14090 `(not (string-match ,pv (or ,gv "")))
14091 `(string-match ,pv (or ,gv "")))
14092 (if str-p
14093 `(,po (or ,gv "") ,pv)
14094 `(,po (string-to-number (or ,gv ""))
14095 ,(string-to-number pv) ))))
14096 (t `(member ,tag tags-list)))
14097 mm (if minus (list 'not mm) mm)
14098 term rest)
14099 (push mm tagsmatcher))
14100 (push (if (> (length tagsmatcher) 1)
14101 (cons 'and tagsmatcher)
14102 (car tagsmatcher))
14103 orlist)
14104 (setq tagsmatcher nil))
14105 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14106 (setq tagsmatcher
14107 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14108 ;; Make the todo matcher
14109 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14110 (setq todomatcher t)
14111 (setq orterms (org-split-string todomatch "|") orlist nil)
14112 (while (setq term (pop orterms))
14113 (while (string-match re term)
14114 (setq minus (and (match-end 1)
14115 (equal (match-string 1 term) "-"))
14116 kwd (match-string 2 term)
14117 re-p (equal (string-to-char kwd) ?{)
14118 term (substring term (match-end 0))
14119 mm (if re-p
14120 `(string-match ,(substring kwd 1 -1) todo)
14121 (list 'equal 'todo kwd))
14122 mm (if minus (list 'not mm) mm))
14123 (push mm todomatcher))
14124 (push (if (> (length todomatcher) 1)
14125 (cons 'and todomatcher)
14126 (car todomatcher))
14127 orlist)
14128 (setq todomatcher nil))
14129 (setq todomatcher (if (> (length orlist) 1)
14130 (cons 'or orlist) (car orlist))))
14132 ;; Return the string and lisp forms of the matcher
14133 (setq matcher (if todomatcher
14134 (list 'and tagsmatcher todomatcher)
14135 tagsmatcher))
14136 (when todo-only
14137 (setq matcher (list 'and '(member todo org-not-done-keywords)
14138 matcher)))
14139 (cons match0 matcher)))
14141 (defun org-tags-expand (match &optional single-as-list downcased)
14142 "Expand group tags in MATCH.
14144 This replaces every group tag in MATCH with a regexp tag search.
14145 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14146 will be replaced like this:
14148 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14149 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14150 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14152 Replacing by a regexp preserves the structure of the match.
14153 E.g., this expansion
14155 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14157 will match anything tagged with \"Lab\" and \"Home\", or tagged
14158 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14160 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14161 assumed to be a single group tag, and the function will return
14162 the list of tags in this group.
14164 When DOWNCASE is non-nil, expand downcased TAGS."
14165 (if org-group-tags
14166 (let* ((case-fold-search t)
14167 (stable org-mode-syntax-table)
14168 (tal (or org-tag-groups-alist-for-agenda
14169 org-tag-groups-alist))
14170 (tal (if downcased
14171 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14172 (tml (mapcar 'car tal))
14173 (rtnmatch match) rpl)
14174 ;; @ and _ are allowed as word-components in tags
14175 (modify-syntax-entry ?@ "w" stable)
14176 (modify-syntax-entry ?_ "w" stable)
14177 (while (and tml
14178 (with-syntax-table stable
14179 (string-match
14180 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14181 (regexp-opt tml) "\\>\\)") rtnmatch)))
14182 (let* ((dir (match-string 1 rtnmatch))
14183 (tag (match-string 2 rtnmatch))
14184 (tag (if downcased (downcase tag) tag)))
14185 (setq tml (delete tag tml))
14186 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14187 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14188 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14189 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14190 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14191 (if single-as-list
14192 (or (reverse rpl) (list rtnmatch))
14193 rtnmatch))
14194 (if single-as-list (list (if downcased (downcase match) match))
14195 match)))
14197 (defun org-op-to-function (op &optional stringp)
14198 "Turn an operator into the appropriate function."
14199 (setq op
14200 (cond
14201 ((equal op "<" ) '(< string< org-time<))
14202 ((equal op ">" ) '(> org-string> org-time>))
14203 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14204 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14205 ((member op '("=" "==")) '(= string= org-time=))
14206 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14207 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14209 (defun org<> (a b) (not (= a b)))
14210 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14211 (defun org-string>= (a b) (not (string< a b)))
14212 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14213 (defun org-string<> (a b) (not (string= a b)))
14214 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14215 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14216 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14217 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14218 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14219 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14220 (defun org-2ft (s)
14221 "Convert S to a floating point time.
14222 If S is already a number, just return it. If it is a string, parse
14223 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14224 (cond
14225 ((numberp s) s)
14226 ((stringp s)
14227 (condition-case nil
14228 (float-time (apply 'encode-time (org-parse-time-string s)))
14229 (error 0.)))
14230 (t 0.)))
14232 (defun org-time-today ()
14233 "Time in seconds today at 0:00.
14234 Returns the float number of seconds since the beginning of the
14235 epoch to the beginning of today (00:00)."
14236 (float-time (apply 'encode-time
14237 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14239 (defun org-matcher-time (s)
14240 "Interpret a time comparison value."
14241 (save-match-data
14242 (cond
14243 ((string= s "<now>") (float-time))
14244 ((string= s "<today>") (org-time-today))
14245 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14246 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14247 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14248 (+ (org-time-today)
14249 (* (string-to-number (match-string 1 s))
14250 (cdr (assoc (match-string 2 s)
14251 '(("d" . 86400.0) ("w" . 604800.0)
14252 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14253 (t (org-2ft s)))))
14255 (defun org-match-any-p (re list)
14256 "Does re match any element of list?"
14257 (setq list (mapcar (lambda (x) (string-match re x)) list))
14258 (delq nil list))
14260 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14261 (defvar org-tags-overlay (make-overlay 1 1))
14262 (org-detach-overlay org-tags-overlay)
14264 (defun org-get-local-tags-at (&optional pos)
14265 "Get a list of tags defined in the current headline."
14266 (org-get-tags-at pos 'local))
14268 (defun org-get-local-tags ()
14269 "Get a list of tags defined in the current headline."
14270 (org-get-tags-at nil 'local))
14272 (defun org-get-tags-at (&optional pos local)
14273 "Get a list of all headline tags applicable at POS.
14274 POS defaults to point. If tags are inherited, the list contains
14275 the targets in the same sequence as the headlines appear, i.e.
14276 the tags of the current headline come last.
14277 When LOCAL is non-nil, only return tags from the current headline,
14278 ignore inherited ones."
14279 (interactive)
14280 (if (and org-trust-scanner-tags
14281 (or (not pos) (equal pos (point)))
14282 (not local))
14283 org-scanner-tags
14284 (let (tags ltags lastpos parent)
14285 (save-excursion
14286 (save-restriction
14287 (widen)
14288 (goto-char (or pos (point)))
14289 (save-match-data
14290 (catch 'done
14291 (condition-case nil
14292 (progn
14293 (org-back-to-heading t)
14294 (while (not (equal lastpos (point)))
14295 (setq lastpos (point))
14296 (when (looking-at
14297 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14298 (setq ltags (org-split-string
14299 (org-match-string-no-properties 1) ":"))
14300 (when parent
14301 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14302 (setq tags (append
14303 (if parent
14304 (org-remove-uninherited-tags ltags)
14305 ltags)
14306 tags)))
14307 (or org-use-tag-inheritance (throw 'done t))
14308 (if local (throw 'done t))
14309 (or (org-up-heading-safe) (error nil))
14310 (setq parent t)))
14311 (error nil)))))
14312 (if local
14313 tags
14314 (reverse (delete-dups
14315 (reverse (append
14316 (org-remove-uninherited-tags
14317 org-file-tags) tags)))))))))
14319 (defun org-add-prop-inherited (s)
14320 (add-text-properties 0 (length s) '(inherited t) s)
14323 (defun org-toggle-tag (tag &optional onoff)
14324 "Toggle the tag TAG for the current line.
14325 If ONOFF is `on' or `off', don't toggle but set to this state."
14326 (let (res current)
14327 (save-excursion
14328 (org-back-to-heading t)
14329 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14330 (point-at-eol) t)
14331 (progn
14332 (setq current (match-string 1))
14333 (replace-match ""))
14334 (setq current ""))
14335 (setq current (nreverse (org-split-string current ":")))
14336 (cond
14337 ((eq onoff 'on)
14338 (setq res t)
14339 (or (member tag current) (push tag current)))
14340 ((eq onoff 'off)
14341 (or (not (member tag current)) (setq current (delete tag current))))
14342 (t (if (member tag current)
14343 (setq current (delete tag current))
14344 (setq res t)
14345 (push tag current))))
14346 (end-of-line 1)
14347 (if current
14348 (progn
14349 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14350 (org-set-tags nil t))
14351 (delete-horizontal-space))
14352 (run-hooks 'org-after-tags-change-hook))
14353 res))
14355 (defun org-align-tags-here (to-col)
14356 ;; Assumes that this is a headline
14357 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14358 (beginning-of-line 1)
14359 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14360 (< pos (match-beginning 2)))
14361 (progn
14362 (setq tags-l (- (match-end 2) (match-beginning 2)))
14363 (goto-char (match-beginning 1))
14364 (insert " ")
14365 (delete-region (point) (1+ (match-beginning 2)))
14366 (setq ncol (max (current-column)
14367 (1+ col)
14368 (if (> to-col 0)
14369 to-col
14370 (- (abs to-col) tags-l))))
14371 (setq p (point))
14372 (insert (make-string (- ncol (current-column)) ?\ ))
14373 (setq ncol (current-column))
14374 (when indent-tabs-mode (tabify p (point-at-eol)))
14375 (org-move-to-column (min ncol col) t))
14376 (goto-char pos))))
14378 (defun org-set-tags-command (&optional arg just-align)
14379 "Call the set-tags command for the current entry."
14380 (interactive "P")
14381 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14382 (org-set-tags arg just-align)
14383 (save-excursion
14384 (unless (and (org-region-active-p)
14385 org-loop-over-headlines-in-active-region)
14386 (org-back-to-heading t))
14387 (org-set-tags arg just-align))))
14389 (defun org-set-tags-to (data)
14390 "Set the tags of the current entry to DATA, replacing the current tags.
14391 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14392 If DATA is nil or the empty string, any tags will be removed."
14393 (interactive "sTags: ")
14394 (setq data
14395 (cond
14396 ((eq data nil) "")
14397 ((equal data "") "")
14398 ((stringp data)
14399 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14400 ":"))
14401 ((listp data)
14402 (concat ":" (mapconcat 'identity data ":") ":"))))
14403 (when data
14404 (save-excursion
14405 (org-back-to-heading t)
14406 (when (looking-at org-complex-heading-regexp)
14407 (if (match-end 5)
14408 (progn
14409 (goto-char (match-beginning 5))
14410 (insert data)
14411 (delete-region (point) (point-at-eol))
14412 (org-set-tags nil 'align))
14413 (goto-char (point-at-eol))
14414 (insert " " data)
14415 (org-set-tags nil 'align)))
14416 (beginning-of-line 1)
14417 (if (looking-at ".*?\\([ \t]+\\)$")
14418 (delete-region (match-beginning 1) (match-end 1))))))
14420 (defun org-align-all-tags ()
14421 "Align the tags i all headings."
14422 (interactive)
14423 (save-excursion
14424 (or (ignore-errors (org-back-to-heading t))
14425 (outline-next-heading))
14426 (if (org-at-heading-p)
14427 (org-set-tags t)
14428 (message "No headings"))))
14430 (defvar org-indent-indentation-per-level)
14431 (defun org-set-tags (&optional arg just-align)
14432 "Set the tags for the current headline.
14433 With prefix ARG, realign all tags in headings in the current buffer."
14434 (interactive "P")
14435 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14436 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14437 'region-start-level 'region))
14438 org-loop-over-headlines-in-active-region)
14439 (org-map-entries
14440 ;; We don't use ARG and JUST-ALIGN here these args are not
14441 ;; useful when looping over headlines
14442 `(org-set-tags)
14443 org-loop-over-headlines-in-active-region
14444 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14445 (let* ((re org-outline-regexp-bol)
14446 (current (unless arg (org-get-tags-string)))
14447 (col (current-column))
14448 (org-setting-tags t)
14449 table current-tags inherited-tags ; computed below when needed
14450 tags p0 c0 c1 rpl di tc level)
14451 (if arg
14452 (save-excursion
14453 (goto-char (point-min))
14454 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14455 (while (re-search-forward re nil t)
14456 (org-set-tags nil t)
14457 (end-of-line 1)))
14458 (message "All tags realigned to column %d" org-tags-column))
14459 (if just-align
14460 (setq tags current)
14461 ;; Get a new set of tags from the user
14462 (save-excursion
14463 (setq table (append org-tag-persistent-alist
14464 (or org-tag-alist (org-get-buffer-tags))
14465 (and
14466 org-complete-tags-always-offer-all-agenda-tags
14467 (org-global-tags-completion-table
14468 (org-agenda-files))))
14469 org-last-tags-completion-table table
14470 current-tags (org-split-string current ":")
14471 inherited-tags (nreverse
14472 (nthcdr (length current-tags)
14473 (nreverse (org-get-tags-at))))
14474 tags
14475 (if (or (eq t org-use-fast-tag-selection)
14476 (and org-use-fast-tag-selection
14477 (delq nil (mapcar 'cdr table))))
14478 (org-fast-tag-selection
14479 current-tags inherited-tags table
14480 (if org-fast-tag-selection-include-todo
14481 org-todo-key-alist))
14482 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14483 (org-trim
14484 (org-icompleting-read "Tags: "
14485 'org-tags-completion-function
14486 nil nil current 'org-tags-history))))))
14487 (while (string-match "[-+&]+" tags)
14488 ;; No boolean logic, just a list
14489 (setq tags (replace-match ":" t t tags))))
14491 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14493 (if org-tags-sort-function
14494 (setq tags (mapconcat 'identity
14495 (sort (org-split-string
14496 tags (org-re "[^[:alnum:]_@#%]+"))
14497 org-tags-sort-function) ":")))
14499 (if (string-match "\\`[\t ]*\\'" tags)
14500 (setq tags "")
14501 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14502 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14504 ;; Insert new tags at the correct column
14505 (beginning-of-line 1)
14506 (setq level (or (and (looking-at org-outline-regexp)
14507 (- (match-end 0) (point) 1))
14509 (cond
14510 ((and (equal current "") (equal tags "")))
14511 ((re-search-forward
14512 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14513 (point-at-eol) t)
14514 (if (equal tags "")
14515 (setq rpl "")
14516 (goto-char (match-beginning 0))
14517 (setq c0 (current-column)
14518 ;; compute offset for the case of org-indent-mode active
14519 di (if org-indent-mode
14520 (* (1- org-indent-indentation-per-level) (1- level))
14522 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14523 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14524 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14525 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14526 (replace-match rpl t t)
14527 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14528 tags)
14529 (t (error "Tags alignment failed")))
14530 (org-move-to-column col)
14531 (unless just-align
14532 (run-hooks 'org-after-tags-change-hook))))))
14534 (defun org-change-tag-in-region (beg end tag off)
14535 "Add or remove TAG for each entry in the region.
14536 This works in the agenda, and also in an org-mode buffer."
14537 (interactive
14538 (list (region-beginning) (region-end)
14539 (let ((org-last-tags-completion-table
14540 (if (derived-mode-p 'org-mode)
14541 (org-uniquify
14542 (delq nil (append (org-get-buffer-tags)
14543 (org-global-tags-completion-table))))
14544 (org-global-tags-completion-table))))
14545 (org-icompleting-read
14546 "Tag: " 'org-tags-completion-function nil nil nil
14547 'org-tags-history))
14548 (progn
14549 (message "[s]et or [r]emove? ")
14550 (equal (read-char-exclusive) ?r))))
14551 (if (fboundp 'deactivate-mark) (deactivate-mark))
14552 (let ((agendap (equal major-mode 'org-agenda-mode))
14553 l1 l2 m buf pos newhead (cnt 0))
14554 (goto-char end)
14555 (setq l2 (1- (org-current-line)))
14556 (goto-char beg)
14557 (setq l1 (org-current-line))
14558 (loop for l from l1 to l2 do
14559 (org-goto-line l)
14560 (setq m (get-text-property (point) 'org-hd-marker))
14561 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14562 (and agendap m))
14563 (setq buf (if agendap (marker-buffer m) (current-buffer))
14564 pos (if agendap m (point)))
14565 (with-current-buffer buf
14566 (save-excursion
14567 (save-restriction
14568 (goto-char pos)
14569 (setq cnt (1+ cnt))
14570 (org-toggle-tag tag (if off 'off 'on))
14571 (setq newhead (org-get-heading)))))
14572 (and agendap (org-agenda-change-all-lines newhead m))))
14573 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14575 (defun org-tags-completion-function (string predicate &optional flag)
14576 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14577 (confirm (lambda (x) (stringp (car x)))))
14578 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14579 (setq s1 (match-string 1 string)
14580 s2 (match-string 2 string))
14581 (setq s1 "" s2 string))
14582 (cond
14583 ((eq flag nil)
14584 ;; try completion
14585 (setq rtn (try-completion s2 ctable confirm))
14586 (if (stringp rtn)
14587 (setq rtn
14588 (concat s1 s2 (substring rtn (length s2))
14589 (if (and org-add-colon-after-tag-completion
14590 (assoc rtn ctable))
14591 ":" ""))))
14592 rtn)
14593 ((eq flag t)
14594 ;; all-completions
14595 (all-completions s2 ctable confirm))
14596 ((eq flag 'lambda)
14597 ;; exact match?
14598 (assoc s2 ctable)))))
14600 (defun org-fast-tag-insert (kwd tags face &optional end)
14601 "Insert KDW, and the TAGS, the latter with face FACE.
14602 Also insert END."
14603 (insert (format "%-12s" (concat kwd ":"))
14604 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14605 (or end "")))
14607 (defun org-fast-tag-show-exit (flag)
14608 (save-excursion
14609 (org-goto-line 3)
14610 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14611 (replace-match ""))
14612 (when flag
14613 (end-of-line 1)
14614 (org-move-to-column (- (window-width) 19) t)
14615 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14617 (defun org-set-current-tags-overlay (current prefix)
14618 "Add an overlay to CURRENT tag with PREFIX."
14619 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14620 (if (featurep 'xemacs)
14621 (org-overlay-display org-tags-overlay (concat prefix s)
14622 'secondary-selection)
14623 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14624 (org-overlay-display org-tags-overlay (concat prefix s)))))
14626 (defvar org-last-tag-selection-key nil)
14627 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14628 "Fast tag selection with single keys.
14629 CURRENT is the current list of tags in the headline, INHERITED is the
14630 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14631 possibly with grouping information. TODO-TABLE is a similar table with
14632 TODO keywords, should these have keys assigned to them.
14633 If the keys are nil, a-z are automatically assigned.
14634 Returns the new tags string, or nil to not change the current settings."
14635 (let* ((fulltable (append table todo-table))
14636 (maxlen (apply 'max (mapcar
14637 (lambda (x)
14638 (if (stringp (car x)) (string-width (car x)) 0))
14639 fulltable)))
14640 (buf (current-buffer))
14641 (expert (eq org-fast-tag-selection-single-key 'expert))
14642 (buffer-tags nil)
14643 (fwidth (+ maxlen 3 1 3))
14644 (ncol (/ (- (window-width) 4) fwidth))
14645 (i-face 'org-done)
14646 (c-face 'org-todo)
14647 tg cnt e c char c1 c2 ntable tbl rtn
14648 ov-start ov-end ov-prefix
14649 (exit-after-next org-fast-tag-selection-single-key)
14650 (done-keywords org-done-keywords)
14651 groups ingroup)
14652 (save-excursion
14653 (beginning-of-line 1)
14654 (if (looking-at
14655 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14656 (setq ov-start (match-beginning 1)
14657 ov-end (match-end 1)
14658 ov-prefix "")
14659 (setq ov-start (1- (point-at-eol))
14660 ov-end (1+ ov-start))
14661 (skip-chars-forward "^\n\r")
14662 (setq ov-prefix
14663 (concat
14664 (buffer-substring (1- (point)) (point))
14665 (if (> (current-column) org-tags-column)
14667 (make-string (- org-tags-column (current-column)) ?\ ))))))
14668 (move-overlay org-tags-overlay ov-start ov-end)
14669 (save-window-excursion
14670 (if expert
14671 (set-buffer (get-buffer-create " *Org tags*"))
14672 (delete-other-windows)
14673 (split-window-vertically)
14674 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14675 (erase-buffer)
14676 (org-set-local 'org-done-keywords done-keywords)
14677 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14678 (org-fast-tag-insert "Current" current c-face "\n\n")
14679 (org-fast-tag-show-exit exit-after-next)
14680 (org-set-current-tags-overlay current ov-prefix)
14681 (setq tbl fulltable char ?a cnt 0)
14682 (while (setq e (pop tbl))
14683 (cond
14684 ((equal (car e) :startgroup)
14685 (push '() groups) (setq ingroup t)
14686 (when (not (= cnt 0))
14687 (setq cnt 0)
14688 (insert "\n"))
14689 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14690 ((equal (car e) :endgroup)
14691 (setq ingroup nil cnt 0)
14692 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14693 ((equal e '(:newline))
14694 (when (not (= cnt 0))
14695 (setq cnt 0)
14696 (insert "\n")
14697 (setq e (car tbl))
14698 (while (equal (car tbl) '(:newline))
14699 (insert "\n")
14700 (setq tbl (cdr tbl)))))
14701 ((equal e '(:grouptags)) nil)
14703 (setq tg (copy-sequence (car e)) c2 nil)
14704 (if (cdr e)
14705 (setq c (cdr e))
14706 ;; automatically assign a character.
14707 (setq c1 (string-to-char
14708 (downcase (substring
14709 tg (if (= (string-to-char tg) ?@) 1 0)))))
14710 (if (or (rassoc c1 ntable) (rassoc c1 table))
14711 (while (or (rassoc char ntable) (rassoc char table))
14712 (setq char (1+ char)))
14713 (setq c2 c1))
14714 (setq c (or c2 char)))
14715 (if ingroup (push tg (car groups)))
14716 (setq tg (org-add-props tg nil 'face
14717 (cond
14718 ((not (assoc tg table))
14719 (org-get-todo-face tg))
14720 ((member tg current) c-face)
14721 ((member tg inherited) i-face))))
14722 (if (equal (caar tbl) :grouptags)
14723 (org-add-props tg nil 'face 'org-tag-group))
14724 (if (and (= cnt 0) (not ingroup)) (insert " "))
14725 (insert "[" c "] " tg (make-string
14726 (- fwidth 4 (length tg)) ?\ ))
14727 (push (cons tg c) ntable)
14728 (when (= (setq cnt (1+ cnt)) ncol)
14729 (insert "\n")
14730 (if ingroup (insert " "))
14731 (setq cnt 0)))))
14732 (setq ntable (nreverse ntable))
14733 (insert "\n")
14734 (goto-char (point-min))
14735 (if (not expert) (org-fit-window-to-buffer))
14736 (setq rtn
14737 (catch 'exit
14738 (while t
14739 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14740 (if (not groups) "no " "")
14741 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14742 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14743 (setq org-last-tag-selection-key c)
14744 (cond
14745 ((= c ?\r) (throw 'exit t))
14746 ((= c ?!)
14747 (setq groups (not groups))
14748 (goto-char (point-min))
14749 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14750 ((= c ?\C-c)
14751 (if (not expert)
14752 (org-fast-tag-show-exit
14753 (setq exit-after-next (not exit-after-next)))
14754 (setq expert nil)
14755 (delete-other-windows)
14756 (set-window-buffer (split-window-vertically) " *Org tags*")
14757 (org-switch-to-buffer-other-window " *Org tags*")
14758 (org-fit-window-to-buffer)))
14759 ((or (= c ?\C-g)
14760 (and (= c ?q) (not (rassoc c ntable))))
14761 (org-detach-overlay org-tags-overlay)
14762 (setq quit-flag t))
14763 ((= c ?\ )
14764 (setq current nil)
14765 (if exit-after-next (setq exit-after-next 'now)))
14766 ((= c ?\t)
14767 (condition-case nil
14768 (setq tg (org-icompleting-read
14769 "Tag: "
14770 (or buffer-tags
14771 (with-current-buffer buf
14772 (org-get-buffer-tags)))))
14773 (quit (setq tg "")))
14774 (when (string-match "\\S-" tg)
14775 (add-to-list 'buffer-tags (list tg))
14776 (if (member tg current)
14777 (setq current (delete tg current))
14778 (push tg current)))
14779 (if exit-after-next (setq exit-after-next 'now)))
14780 ((setq e (rassoc c todo-table) tg (car e))
14781 (with-current-buffer buf
14782 (save-excursion (org-todo tg)))
14783 (if exit-after-next (setq exit-after-next 'now)))
14784 ((setq e (rassoc c ntable) tg (car e))
14785 (if (member tg current)
14786 (setq current (delete tg current))
14787 (loop for g in groups do
14788 (if (member tg g)
14789 (mapc (lambda (x)
14790 (setq current (delete x current)))
14791 g)))
14792 (push tg current))
14793 (if exit-after-next (setq exit-after-next 'now))))
14795 ;; Create a sorted list
14796 (setq current
14797 (sort current
14798 (lambda (a b)
14799 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14800 (if (eq exit-after-next 'now) (throw 'exit t))
14801 (goto-char (point-min))
14802 (beginning-of-line 2)
14803 (delete-region (point) (point-at-eol))
14804 (org-fast-tag-insert "Current" current c-face)
14805 (org-set-current-tags-overlay current ov-prefix)
14806 (while (re-search-forward
14807 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14808 (setq tg (match-string 1))
14809 (add-text-properties
14810 (match-beginning 1) (match-end 1)
14811 (list 'face
14812 (cond
14813 ((member tg current) c-face)
14814 ((member tg inherited) i-face)
14815 (t (get-text-property (match-beginning 1) 'face))))))
14816 (goto-char (point-min)))))
14817 (org-detach-overlay org-tags-overlay)
14818 (if rtn
14819 (mapconcat 'identity current ":")
14820 nil))))
14822 (defun org-get-tags-string ()
14823 "Get the TAGS string in the current headline."
14824 (unless (org-at-heading-p t)
14825 (user-error "Not on a heading"))
14826 (save-excursion
14827 (beginning-of-line 1)
14828 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14829 (org-match-string-no-properties 1)
14830 "")))
14832 (defun org-get-tags ()
14833 "Get the list of tags specified in the current headline."
14834 (org-split-string (org-get-tags-string) ":"))
14836 (defun org-get-buffer-tags ()
14837 "Get a table of all tags used in the buffer, for completion."
14838 (let (tags)
14839 (save-excursion
14840 (goto-char (point-min))
14841 (while (re-search-forward
14842 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14843 (when (equal (char-after (point-at-bol 0)) ?*)
14844 (mapc (lambda (x) (add-to-list 'tags x))
14845 (org-split-string (org-match-string-no-properties 1) ":")))))
14846 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14847 (mapcar 'list tags)))
14849 ;;;; The mapping API
14851 (defun org-map-entries (func &optional match scope &rest skip)
14852 "Call FUNC at each headline selected by MATCH in SCOPE.
14854 FUNC is a function or a lisp form. The function will be called without
14855 arguments, with the cursor positioned at the beginning of the headline.
14856 The return values of all calls to the function will be collected and
14857 returned as a list.
14859 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14860 does not need to preserve point. After evaluation, the cursor will be
14861 moved to the end of the line (presumably of the headline of the
14862 processed entry) and search continues from there. Under some
14863 circumstances, this may not produce the wanted results. For example,
14864 if you have removed (e.g. archived) the current (sub)tree it could
14865 mean that the next entry will be skipped entirely. In such cases, you
14866 can specify the position from where search should continue by making
14867 FUNC set the variable `org-map-continue-from' to the desired buffer
14868 position.
14870 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14871 Only headlines that are matched by this query will be considered during
14872 the iteration. When MATCH is nil or t, all headlines will be
14873 visited by the iteration.
14875 SCOPE determines the scope of this command. It can be any of:
14877 nil The current buffer, respecting the restriction if any
14878 tree The subtree started with the entry at point
14879 region The entries within the active region, if any
14880 region-start-level
14881 The entries within the active region, but only those at
14882 the same level than the first one.
14883 file The current buffer, without restriction
14884 file-with-archives
14885 The current buffer, and any archives associated with it
14886 agenda All agenda files
14887 agenda-with-archives
14888 All agenda files with any archive files associated with them
14889 \(file1 file2 ...)
14890 If this is a list, all files in the list will be scanned
14892 The remaining args are treated as settings for the skipping facilities of
14893 the scanner. The following items can be given here:
14895 archive skip trees with the archive tag
14896 comment skip trees with the COMMENT keyword
14897 function or Emacs Lisp form:
14898 will be used as value for `org-agenda-skip-function', so
14899 whenever the function returns a position, FUNC will not be
14900 called for that entry and search will continue from the
14901 position returned
14903 If your function needs to retrieve the tags including inherited tags
14904 at the *current* entry, you can use the value of the variable
14905 `org-scanner-tags' which will be much faster than getting the value
14906 with `org-get-tags-at'. If your function gets properties with
14907 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14908 to t around the call to `org-entry-properties' to get the same speedup.
14909 Note that if your function moves around to retrieve tags and properties at
14910 a *different* entry, you cannot use these techniques."
14911 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14912 (not (org-region-active-p)))
14913 (let* ((org-agenda-archives-mode nil) ; just to make sure
14914 (org-agenda-skip-archived-trees (memq 'archive skip))
14915 (org-agenda-skip-comment-trees (memq 'comment skip))
14916 (org-agenda-skip-function
14917 (car (org-delete-all '(comment archive) skip)))
14918 (org-tags-match-list-sublevels t)
14919 (start-level (eq scope 'region-start-level))
14920 matcher file res
14921 org-todo-keywords-for-agenda
14922 org-done-keywords-for-agenda
14923 org-todo-keyword-alist-for-agenda
14924 org-drawers-for-agenda
14925 org-tag-alist-for-agenda
14926 todo-only)
14928 (cond
14929 ((eq match t) (setq matcher t))
14930 ((eq match nil) (setq matcher t))
14931 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14933 (save-window-excursion
14934 (save-restriction
14935 (cond ((eq scope 'tree)
14936 (org-back-to-heading t)
14937 (org-narrow-to-subtree)
14938 (setq scope nil))
14939 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14940 (org-region-active-p))
14941 ;; If needed, set start-level to a string like "2"
14942 (when start-level
14943 (save-excursion
14944 (goto-char (region-beginning))
14945 (unless (org-at-heading-p) (outline-next-heading))
14946 (setq start-level (org-current-level))))
14947 (narrow-to-region (region-beginning)
14948 (save-excursion
14949 (goto-char (region-end))
14950 (unless (and (bolp) (org-at-heading-p))
14951 (outline-next-heading))
14952 (point)))
14953 (setq scope nil)))
14955 (if (not scope)
14956 (progn
14957 (org-agenda-prepare-buffers
14958 (list (buffer-file-name (current-buffer))))
14959 (setq res (org-scan-tags func matcher todo-only start-level)))
14960 ;; Get the right scope
14961 (cond
14962 ((and scope (listp scope) (symbolp (car scope)))
14963 (setq scope (eval scope)))
14964 ((eq scope 'agenda)
14965 (setq scope (org-agenda-files t)))
14966 ((eq scope 'agenda-with-archives)
14967 (setq scope (org-agenda-files t))
14968 (setq scope (org-add-archive-files scope)))
14969 ((eq scope 'file)
14970 (setq scope (list (buffer-file-name))))
14971 ((eq scope 'file-with-archives)
14972 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14973 (org-agenda-prepare-buffers scope)
14974 (while (setq file (pop scope))
14975 (with-current-buffer (org-find-base-buffer-visiting file)
14976 (save-excursion
14977 (save-restriction
14978 (widen)
14979 (goto-char (point-min))
14980 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14981 res)))
14983 ;;;; Properties
14985 ;;; Setting and retrieving properties
14987 (defconst org-special-properties
14988 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14989 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14990 "The special properties valid in Org-mode.
14992 These are properties that are not defined in the property drawer,
14993 but in some other way.")
14995 (defconst org-default-properties
14996 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14997 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14998 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14999 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15000 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15001 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15002 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15003 "Some properties that are used by Org-mode for various purposes.
15004 Being in this list makes sure that they are offered for completion.")
15006 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15007 "Regular expression matching the first line of a property drawer.")
15009 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15010 "Regular expression matching the last line of a property drawer.")
15012 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
15013 "Regular expression matching the first line of a property drawer.")
15015 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
15016 "Regular expression matching the first line of a property drawer.")
15018 (defconst org-property-drawer-re
15019 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
15020 org-property-end-re "\\)\n?")
15021 "Matches an entire property drawer.")
15023 (defconst org-clock-drawer-re
15024 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
15025 org-property-end-re "\\)\n?")
15026 "Matches an entire clock drawer.")
15028 (defun org-property-action ()
15029 "Do an action on properties."
15030 (interactive)
15031 (let (c)
15032 (org-at-property-p)
15033 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15034 (setq c (read-char-exclusive))
15035 (cond
15036 ((equal c ?s)
15037 (call-interactively 'org-set-property))
15038 ((equal c ?d)
15039 (call-interactively 'org-delete-property))
15040 ((equal c ?D)
15041 (call-interactively 'org-delete-property-globally))
15042 ((equal c ?c)
15043 (call-interactively 'org-compute-property-at-point))
15044 (t (user-error "No such property action %c" c)))))
15046 (defun org-inc-effort ()
15047 "Increment the value of the effort property in the current entry."
15048 (interactive)
15049 (org-set-effort nil t))
15051 (defvar org-clock-effort) ;; Defined in org-clock.el
15052 (defvar org-clock-current-task) ;; Defined in org-clock.el
15053 (defun org-set-effort (&optional value increment)
15054 "Set the effort property of the current entry.
15055 With numerical prefix arg, use the nth allowed value, 0 stands for the
15056 10th allowed value.
15058 When INCREMENT is non-nil, set the property to the next allowed value."
15059 (interactive "P")
15060 (if (equal value 0) (setq value 10))
15061 (let* ((completion-ignore-case t)
15062 (prop org-effort-property)
15063 (cur (org-entry-get nil prop))
15064 (allowed (org-property-get-allowed-values nil prop 'table))
15065 (existing (mapcar 'list (org-property-values prop)))
15066 (heading (nth 4 (org-heading-components)))
15068 (val (cond
15069 ((stringp value) value)
15070 ((and allowed (integerp value))
15071 (or (car (nth (1- value) allowed))
15072 (car (org-last allowed))))
15073 ((and allowed increment)
15074 (or (caadr (member (list cur) allowed))
15075 (user-error "Allowed effort values are not set")))
15076 (allowed
15077 (message "Select 1-9,0, [RET%s]: %s"
15078 (if cur (concat "=" cur) "")
15079 (mapconcat 'car allowed " "))
15080 (setq rpl (read-char-exclusive))
15081 (if (equal rpl ?\r)
15083 (setq rpl (- rpl ?0))
15084 (if (equal rpl 0) (setq rpl 10))
15085 (if (and (> rpl 0) (<= rpl (length allowed)))
15086 (car (nth (1- rpl) allowed))
15087 (org-completing-read "Effort: " allowed nil))))
15089 (let (org-completion-use-ido org-completion-use-iswitchb)
15090 (org-completing-read
15091 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15092 (concat "[" cur "]") "")
15093 ": ")
15094 existing nil nil "" nil cur))))))
15095 (unless (equal (org-entry-get nil prop) val)
15096 (org-entry-put nil prop val))
15097 (save-excursion
15098 (org-back-to-heading t)
15099 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15100 (when (string= heading org-clock-current-task)
15101 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15102 (org-clock-update-mode-line))
15103 (message "%s is now %s" prop val)))
15105 (defun org-at-property-p ()
15106 "Is cursor inside a property drawer?"
15107 (save-excursion
15108 (when (equal 'node-property (car (org-element-at-point)))
15109 (beginning-of-line 1)
15110 (looking-at org-property-re))))
15112 (defun org-get-property-block (&optional beg end force)
15113 "Return the (beg . end) range of the body of the property drawer.
15114 BEG and END are the beginning and end of the current subtree, or of
15115 the part before the first headline. If they are not given, they will
15116 be found. If the drawer does not exist and FORCE is non-nil, create
15117 the drawer."
15118 (catch 'exit
15119 (save-excursion
15120 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15121 (progn (org-back-to-heading t) (point))))
15122 (end (or end (and (not (outline-next-heading)) (point-max))
15123 (point))))
15124 (goto-char beg)
15125 (if (re-search-forward org-property-start-re end t)
15126 (setq beg (1+ (match-end 0)))
15127 (if force
15128 (save-excursion
15129 (org-insert-property-drawer)
15130 (setq end (progn (outline-next-heading) (point))))
15131 (throw 'exit nil))
15132 (goto-char beg)
15133 (if (re-search-forward org-property-start-re end t)
15134 (setq beg (1+ (match-end 0)))))
15135 (if (re-search-forward org-property-end-re end t)
15136 (setq end (match-beginning 0))
15137 (or force (throw 'exit nil))
15138 (goto-char beg)
15139 (setq end beg)
15140 (org-indent-line)
15141 (insert ":END:\n"))
15142 (cons beg end)))))
15144 (defun org-entry-properties (&optional pom which specific)
15145 "Get all properties of the entry at point-or-marker POM.
15146 This includes the TODO keyword, the tags, time strings for deadline,
15147 scheduled, and clocking, and any additional properties defined in the
15148 entry. The return value is an alist, keys may occur multiple times
15149 if the property key was used several times.
15150 POM may also be nil, in which case the current entry is used.
15151 If WHICH is nil or `all', get all properties. If WHICH is
15152 `special' or `standard', only get that subclass. If WHICH
15153 is a string only get exactly this property. SPECIFIC can be a string, the
15154 specific property we are interested in. Specifying it can speed
15155 things up because then unnecessary parsing is avoided."
15156 (setq which (or which 'all))
15157 (org-with-point-at pom
15158 (let ((clockstr (substring org-clock-string 0 -1))
15159 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15160 (case-fold-search nil)
15161 beg end range props sum-props key key1 value string clocksum clocksumt)
15162 (save-excursion
15163 (when (condition-case nil
15164 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
15165 (error nil))
15166 (setq beg (point))
15167 (setq sum-props (get-text-property (point) 'org-summaries))
15168 (setq clocksum (get-text-property (point) :org-clock-minutes)
15169 clocksumt (get-text-property (point) :org-clock-minutes-today))
15170 (outline-next-heading)
15171 (setq end (point))
15172 (when (memq which '(all special))
15173 ;; Get the special properties, like TODO and tags
15174 (goto-char beg)
15175 (when (and (or (not specific) (string= specific "TODO"))
15176 (looking-at org-todo-line-regexp) (match-end 2))
15177 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15178 (when (and (or (not specific) (string= specific "PRIORITY"))
15179 (looking-at org-priority-regexp))
15180 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15181 (when (or (not specific) (string= specific "FILE"))
15182 (push (cons "FILE" buffer-file-name) props))
15183 (when (and (or (not specific) (string= specific "TAGS"))
15184 (setq value (org-get-tags-string))
15185 (string-match "\\S-" value))
15186 (push (cons "TAGS" value) props))
15187 (when (and (or (not specific) (string= specific "ALLTAGS"))
15188 (setq value (org-get-tags-at)))
15189 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15190 ":"))
15191 props))
15192 (when (or (not specific) (string= specific "BLOCKED"))
15193 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15194 (when (or (not specific)
15195 (member specific
15196 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15197 "TIMESTAMP" "TIMESTAMP_IA")))
15198 (catch 'match
15199 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15200 (setq key (if (match-end 1)
15201 (substring (org-match-string-no-properties 1)
15202 0 -1))
15203 string (if (equal key clockstr)
15204 (org-trim
15205 (buffer-substring-no-properties
15206 (match-beginning 3) (goto-char
15207 (point-at-eol))))
15208 (substring (org-match-string-no-properties 3)
15209 1 -1)))
15210 ;; Get the correct property name from the key. This is
15211 ;; necessary if the user has configured time keywords.
15212 (setq key1 (concat key ":"))
15213 (cond
15214 ((not key)
15215 (setq key
15216 (if (= (char-after (match-beginning 3)) ?\[)
15217 "TIMESTAMP_IA" "TIMESTAMP")))
15218 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15219 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15220 ((equal key1 org-closed-string) (setq key "CLOSED"))
15221 ((equal key1 org-clock-string) (setq key "CLOCK")))
15222 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15223 (progn
15224 (push (cons key string) props)
15225 ;; no need to search further if match is found
15226 (throw 'match t))
15227 (when (or (equal key "CLOCK") (not (assoc key props)))
15228 (push (cons key string) props)))))))
15230 (when (memq which '(all standard))
15231 ;; Get the standard properties, like :PROP: ...
15232 (setq range (org-get-property-block beg end))
15233 (when range
15234 (goto-char (car range))
15235 (while (re-search-forward org-property-re
15236 (cdr range) t)
15237 (setq key (org-match-string-no-properties 2)
15238 value (org-trim (or (org-match-string-no-properties 3) "")))
15239 (unless (member key excluded)
15240 (push (cons key (or value "")) props)))))
15241 (if clocksum
15242 (push (cons "CLOCKSUM"
15243 (org-columns-number-to-string (/ (float clocksum) 60.)
15244 'add_times))
15245 props))
15246 (if clocksumt
15247 (push (cons "CLOCKSUM_T"
15248 (org-columns-number-to-string (/ (float clocksumt) 60.)
15249 'add_times))
15250 props))
15251 (unless (assoc "CATEGORY" props)
15252 (push (cons "CATEGORY" (org-get-category)) props))
15253 (append sum-props (nreverse props)))))))
15255 (defun org-entry-get (pom property &optional inherit literal-nil)
15256 "Get value of PROPERTY for entry or content at point-or-marker POM.
15257 If INHERIT is non-nil and the entry does not have the property,
15258 then also check higher levels of the hierarchy.
15259 If INHERIT is the symbol `selective', use inheritance only if the setting
15260 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15261 If the property is present but empty, the return value is the empty string.
15262 If the property is not present at all, nil is returned.
15264 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15265 do not interpret it as the list atom nil. This is used for inheritance
15266 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15267 (org-with-point-at pom
15268 (if (and inherit (if (eq inherit 'selective)
15269 (org-property-inherit-p property)
15271 (org-entry-get-with-inheritance property literal-nil)
15272 (if (member property org-special-properties)
15273 ;; We need a special property. Use `org-entry-properties' to
15274 ;; retrieve it, but specify the wanted property
15275 (cdr (assoc property (org-entry-properties nil 'special property)))
15276 (let ((range (org-get-property-block)))
15277 (when (and range (not (eq (car range) (cdr range))))
15278 (let* ((props (list (or (assoc property org-file-properties)
15279 (assoc property org-global-properties)
15280 (assoc property org-global-properties-fixed))))
15281 (ap (lambda (key)
15282 (when (re-search-forward
15283 (org-re-property key) (cdr range) t)
15284 (setq props
15285 (org-update-property-plist
15287 (if (match-end 3)
15288 (org-match-string-no-properties 3) "")
15289 props)))))
15290 val)
15291 (goto-char (car range))
15292 (funcall ap property)
15293 (goto-char (car range))
15294 (while (funcall ap (concat property "+")))
15295 (setq val (cdr (assoc property props)))
15296 (when val (if literal-nil val (org-not-nil val))))))))))
15298 (defun org-property-or-variable-value (var &optional inherit)
15299 "Check if there is a property fixing the value of VAR.
15300 If yes, return this value. If not, return the current value of the variable."
15301 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15302 (if (and prop (stringp prop) (string-match "\\S-" prop))
15303 (read prop)
15304 (symbol-value var))))
15306 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15307 "Delete the property PROPERTY from entry at point-or-marker POM.
15308 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15309 an empty drawer to delete."
15310 (org-with-point-at pom
15311 (if (member property org-special-properties)
15312 nil ; cannot delete these properties.
15313 (let ((range (org-get-property-block)))
15314 (if (and range
15315 (goto-char (car range))
15316 (re-search-forward
15317 (org-re-property property)
15318 (cdr range) t))
15319 (progn
15320 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15321 (and delete-empty-drawer
15322 (org-remove-empty-drawer-at
15323 delete-empty-drawer (car range)))
15325 nil)))))
15327 ;; Multi-values properties are properties that contain multiple values
15328 ;; These values are assumed to be single words, separated by whitespace.
15329 (defun org-entry-add-to-multivalued-property (pom property value)
15330 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15331 (let* ((old (org-entry-get pom property))
15332 (values (and old (org-split-string old "[ \t]"))))
15333 (setq value (org-entry-protect-space value))
15334 (unless (member value values)
15335 (setq values (append values (list value)))
15336 (org-entry-put pom property
15337 (mapconcat 'identity values " ")))))
15339 (defun org-entry-remove-from-multivalued-property (pom property value)
15340 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15341 (let* ((old (org-entry-get pom property))
15342 (values (and old (org-split-string old "[ \t]"))))
15343 (setq value (org-entry-protect-space value))
15344 (when (member value values)
15345 (setq values (delete value values))
15346 (org-entry-put pom property
15347 (mapconcat 'identity values " ")))))
15349 (defun org-entry-member-in-multivalued-property (pom property value)
15350 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15351 (let* ((old (org-entry-get pom property))
15352 (values (and old (org-split-string old "[ \t]"))))
15353 (setq value (org-entry-protect-space value))
15354 (member value values)))
15356 (defun org-entry-get-multivalued-property (pom property)
15357 "Return a list of values in a multivalued property."
15358 (let* ((value (org-entry-get pom property))
15359 (values (and value (org-split-string value "[ \t]"))))
15360 (mapcar 'org-entry-restore-space values)))
15362 (defun org-entry-put-multivalued-property (pom property &rest values)
15363 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15364 VALUES should be a list of strings. Spaces will be protected."
15365 (org-entry-put pom property
15366 (mapconcat 'org-entry-protect-space values " "))
15367 (let* ((value (org-entry-get pom property))
15368 (values (and value (org-split-string value "[ \t]"))))
15369 (mapcar 'org-entry-restore-space values)))
15371 (defun org-entry-protect-space (s)
15372 "Protect spaces and newline in string S."
15373 (while (string-match " " s)
15374 (setq s (replace-match "%20" t t s)))
15375 (while (string-match "\n" s)
15376 (setq s (replace-match "%0A" t t s)))
15379 (defun org-entry-restore-space (s)
15380 "Restore spaces and newline in string S."
15381 (while (string-match "%20" s)
15382 (setq s (replace-match " " t t s)))
15383 (while (string-match "%0A" s)
15384 (setq s (replace-match "\n" t t s)))
15387 (defvar org-entry-property-inherited-from (make-marker)
15388 "Marker pointing to the entry from where a property was inherited.
15389 Each call to `org-entry-get-with-inheritance' will set this marker to the
15390 location of the entry where the inheritance search matched. If there was
15391 no match, the marker will point nowhere.
15392 Note that also `org-entry-get' calls this function, if the INHERIT flag
15393 is set.")
15395 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15396 "Get PROPERTY of entry or content at point, search higher levels if needed.
15397 The search will stop at the first ancestor which has the property defined.
15398 If the value found is \"nil\", return nil to show that the property
15399 should be considered as undefined (this is the meaning of nil here).
15400 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15401 (move-marker org-entry-property-inherited-from nil)
15402 (let (tmp)
15403 (save-excursion
15404 (save-restriction
15405 (widen)
15406 (catch 'ex
15407 (while t
15408 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15409 (or (ignore-errors (org-back-to-heading t))
15410 (goto-char (point-min)))
15411 (move-marker org-entry-property-inherited-from (point))
15412 (throw 'ex tmp))
15413 (or (ignore-errors (org-up-heading-safe))
15414 (throw 'ex nil))))))
15415 (setq tmp (or tmp
15416 (cdr (assoc property org-file-properties))
15417 (cdr (assoc property org-global-properties))
15418 (cdr (assoc property org-global-properties-fixed))))
15419 (if literal-nil tmp (org-not-nil tmp))))
15421 (defvar org-property-changed-functions nil
15422 "Hook called when the value of a property has changed.
15423 Each hook function should accept two arguments, the name of the property
15424 and the new value.")
15426 (defun org-entry-put (pom property value)
15427 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15428 (org-with-point-at pom
15429 (org-back-to-heading t)
15430 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15431 range)
15432 (cond
15433 ((equal property "TODO")
15434 (when (and (stringp value) (string-match "\\S-" value)
15435 (not (member value org-todo-keywords-1)))
15436 (user-error "\"%s\" is not a valid TODO state" value))
15437 (if (or (not value)
15438 (not (string-match "\\S-" value)))
15439 (setq value 'none))
15440 (org-todo value)
15441 (org-set-tags nil 'align))
15442 ((equal property "PRIORITY")
15443 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15444 (string-to-char value) ?\ ))
15445 (org-set-tags nil 'align))
15446 ((equal property "CLOCKSUM")
15447 (if (not (re-search-forward
15448 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15449 (error "Cannot find a clock log")
15450 (goto-char (- (match-end 1) 2))
15451 (cond
15452 ((eq value 'earlier) (org-timestamp-down))
15453 ((eq value 'later) (org-timestamp-up)))
15454 (org-clock-sum-current-item)))
15455 ((equal property "SCHEDULED")
15456 (if (re-search-forward org-scheduled-time-regexp end t)
15457 (cond
15458 ((eq value 'earlier) (org-timestamp-change -1 'day))
15459 ((eq value 'later) (org-timestamp-change 1 'day))
15460 (t (call-interactively 'org-schedule)))
15461 (call-interactively 'org-schedule)))
15462 ((equal property "DEADLINE")
15463 (if (re-search-forward org-deadline-time-regexp end t)
15464 (cond
15465 ((eq value 'earlier) (org-timestamp-change -1 'day))
15466 ((eq value 'later) (org-timestamp-change 1 'day))
15467 (t (call-interactively 'org-deadline)))
15468 (call-interactively 'org-deadline)))
15469 ((member property org-special-properties)
15470 (error "The %s property can not yet be set with `org-entry-put'"
15471 property))
15472 (t ; a non-special property
15473 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15474 (setq range (org-get-property-block beg end 'force))
15475 (goto-char (car range))
15476 (if (re-search-forward
15477 (org-re-property property) (cdr range) t)
15478 (progn
15479 (delete-region (match-beginning 0) (match-end 0))
15480 (goto-char (match-beginning 0)))
15481 (goto-char (cdr range))
15482 (insert "\n")
15483 (backward-char 1)
15484 (org-indent-line))
15485 (insert ":" property ":")
15486 (and value (insert " " value))
15487 (org-indent-line)))))
15488 (run-hook-with-args 'org-property-changed-functions property value)))
15490 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15491 "Get all property keys in the current buffer.
15492 With INCLUDE-SPECIALS, also list the special properties that reflect things
15493 like tags and TODO state.
15494 With INCLUDE-DEFAULTS, also include properties that has special meaning
15495 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15496 and others.
15497 With INCLUDE-COLUMNS, also include property names given in COLUMN
15498 formats in the current buffer."
15499 (let (rtn range cfmt s p)
15500 (save-excursion
15501 (save-restriction
15502 (widen)
15503 (goto-char (point-min))
15504 (while (re-search-forward org-property-start-re nil t)
15505 (setq range (org-get-property-block))
15506 (goto-char (car range))
15507 (while (re-search-forward org-property-re
15508 (cdr range) t)
15509 (add-to-list 'rtn (org-match-string-no-properties 2)))
15510 (outline-next-heading))))
15512 (when include-specials
15513 (setq rtn (append org-special-properties rtn)))
15515 (when include-defaults
15516 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15517 (add-to-list 'rtn org-effort-property))
15519 (when include-columns
15520 (save-excursion
15521 (save-restriction
15522 (widen)
15523 (goto-char (point-min))
15524 (while (re-search-forward
15525 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15526 nil t)
15527 (setq cfmt (match-string 2) s 0)
15528 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15529 cfmt s)
15530 (setq s (match-end 0)
15531 p (match-string 1 cfmt))
15532 (unless (or (equal p "ITEM")
15533 (member p org-special-properties))
15534 (add-to-list 'rtn (match-string 1 cfmt))))))))
15536 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15538 (defun org-property-values (key)
15539 "Return a list of all values of property KEY in the current buffer."
15540 (save-excursion
15541 (save-restriction
15542 (widen)
15543 (goto-char (point-min))
15544 (let ((re (org-re-property key))
15545 values)
15546 (while (re-search-forward re nil t)
15547 (add-to-list 'values (org-trim (match-string 3))))
15548 (delete "" values)))))
15550 (defun org-insert-property-drawer ()
15551 "Insert a property drawer into the current entry."
15552 (org-back-to-heading t)
15553 (looking-at org-outline-regexp)
15554 (let ((indent (if org-adapt-indentation
15555 (- (match-end 0) (match-beginning 0))
15557 (beg (point))
15558 (re (concat "^[ \t]*" org-keyword-time-regexp))
15559 end hiddenp)
15560 (outline-next-heading)
15561 (setq end (point))
15562 (goto-char beg)
15563 (while (re-search-forward re end t))
15564 (setq hiddenp (outline-invisible-p))
15565 (end-of-line 1)
15566 (and (equal (char-after) ?\n) (forward-char 1))
15567 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15568 (if (member (match-string 1) '("CLOCK:" ":END:"))
15569 ;; just skip this line
15570 (beginning-of-line 2)
15571 ;; Drawer start, find the end
15572 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15573 (beginning-of-line 1)))
15574 (org-skip-over-state-notes)
15575 (skip-chars-backward " \t\n\r")
15576 (if (eq (char-before) ?*) (forward-char 1))
15577 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15578 (beginning-of-line 0)
15579 (org-indent-to-column indent)
15580 (beginning-of-line 2)
15581 (org-indent-to-column indent)
15582 (beginning-of-line 0)
15583 (if hiddenp
15584 (save-excursion
15585 (org-back-to-heading t)
15586 (hide-entry))
15587 (org-flag-drawer t))))
15589 (defun org-insert-drawer (&optional arg drawer)
15590 "Insert a drawer at point.
15592 Optional argument DRAWER, when non-nil, is a string representing
15593 drawer's name. Otherwise, the user is prompted for a name.
15595 If a region is active, insert the drawer around that region
15596 instead.
15598 Point is left between drawer's boundaries."
15599 (interactive "P")
15600 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15601 "LOGBOOK"))
15602 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15603 ;; internally by Org. They are meant to be inserted
15604 ;; automatically.
15605 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15606 ;; Remove system drawers from list. Note: For some reason,
15607 ;; `org-completing-read' ignores the predicate while
15608 ;; `completing-read' handles it fine.
15609 (drawer (if arg "PROPERTIES"
15610 (or drawer
15611 (completing-read
15612 "Drawer: " org-drawers
15613 (lambda (d) (not (member d system-drawers))))))))
15614 (cond
15615 ;; With C-u, fall back on `org-insert-property-drawer'
15616 (arg (org-insert-property-drawer))
15617 ;; With an active region, insert a drawer at point.
15618 ((not (org-region-active-p))
15619 (progn
15620 (unless (bolp) (insert "\n"))
15621 (insert (format ":%s:\n\n:END:\n" drawer))
15622 (forward-line -2)))
15623 ;; Otherwise, insert the drawer at point
15625 (let ((rbeg (region-beginning))
15626 (rend (copy-marker (region-end))))
15627 (unwind-protect
15628 (progn
15629 (goto-char rbeg)
15630 (beginning-of-line)
15631 (when (save-excursion
15632 (re-search-forward org-outline-regexp-bol rend t))
15633 (user-error "Drawers cannot contain headlines"))
15634 ;; Position point at the beginning of the first
15635 ;; non-blank line in region. Insert drawer's opening
15636 ;; there, then indent it.
15637 (org-skip-whitespace)
15638 (beginning-of-line)
15639 (insert ":" drawer ":\n")
15640 (forward-line -1)
15641 (indent-for-tab-command)
15642 ;; Move point to the beginning of the first blank line
15643 ;; after the last non-blank line in region. Insert
15644 ;; drawer's closing, then indent it.
15645 (goto-char rend)
15646 (skip-chars-backward " \r\t\n")
15647 (insert "\n:END:")
15648 (deactivate-mark t)
15649 (indent-for-tab-command)
15650 (unless (eolp) (insert "\n")))
15651 ;; Clear marker, whatever the outcome of insertion is.
15652 (set-marker rend nil)))))))
15654 (defvar org-property-set-functions-alist nil
15655 "Property set function alist.
15656 Each entry should have the following format:
15658 (PROPERTY . READ-FUNCTION)
15660 The read function will be called with the same argument as
15661 `org-completing-read'.")
15663 (defun org-set-property-function (property)
15664 "Get the function that should be used to set PROPERTY.
15665 This is computed according to `org-property-set-functions-alist'."
15666 (or (cdr (assoc property org-property-set-functions-alist))
15667 'org-completing-read))
15669 (defun org-read-property-value (property)
15670 "Read PROPERTY value from user."
15671 (let* ((completion-ignore-case t)
15672 (allowed (org-property-get-allowed-values nil property 'table))
15673 (cur (org-entry-get nil property))
15674 (prompt (concat property " value"
15675 (if (and cur (string-match "\\S-" cur))
15676 (concat " [" cur "]") "") ": "))
15677 (set-function (org-set-property-function property))
15678 (val (if allowed
15679 (funcall set-function prompt allowed nil
15680 (not (get-text-property 0 'org-unrestricted
15681 (caar allowed))))
15682 (let (org-completion-use-ido org-completion-use-iswitchb)
15683 (funcall set-function prompt
15684 (mapcar 'list (org-property-values property))
15685 nil nil "" nil cur)))))
15686 (if (equal val "")
15688 val)))
15690 (defvar org-last-set-property nil)
15691 (defvar org-last-set-property-value nil)
15692 (defun org-read-property-name ()
15693 "Read a property name."
15694 (let* ((completion-ignore-case t)
15695 (keys (org-buffer-property-keys nil t t))
15696 (default-prop (or (save-excursion
15697 (save-match-data
15698 (beginning-of-line)
15699 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15700 (null (string= (match-string 1) "END"))
15701 (match-string 1))))
15702 org-last-set-property))
15703 (property (org-icompleting-read
15704 (concat "Property"
15705 (if default-prop (concat " [" default-prop "]") "")
15706 ": ")
15707 (mapcar 'list keys)
15708 nil nil nil nil
15709 default-prop)))
15710 (if (member property keys)
15711 property
15712 (or (cdr (assoc (downcase property)
15713 (mapcar (lambda (x) (cons (downcase x) x))
15714 keys)))
15715 property))))
15717 (defun org-set-property-and-value (use-last)
15718 "Allow to set [PROPERTY]: [value] direction from prompt.
15719 When use-default, don't even ask, just use the last
15720 \"[PROPERTY]: [value]\" string from the history."
15721 (interactive "P")
15722 (let* ((completion-ignore-case t)
15723 (pv (or (and use-last org-last-set-property-value)
15724 (org-completing-read
15725 "Enter a \"[Property]: [value]\" pair: "
15726 nil nil nil nil nil
15727 org-last-set-property-value)))
15728 prop val)
15729 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15730 (setq prop (match-string 1 pv)
15731 val (match-string 2 pv))
15732 (org-set-property prop val))))
15734 (defun org-set-property (property value)
15735 "In the current entry, set PROPERTY to VALUE.
15736 When called interactively, this will prompt for a property name, offering
15737 completion on existing and default properties. And then it will prompt
15738 for a value, offering completion either on allowed values (via an inherited
15739 xxx_ALL property) or on existing values in other instances of this property
15740 in the current file."
15741 (interactive (list nil nil))
15742 (let* ((property (or property (org-read-property-name)))
15743 (value (or value (org-read-property-value property)))
15744 (fn (cdr (assoc property org-properties-postprocess-alist))))
15745 (setq org-last-set-property property)
15746 (setq org-last-set-property-value (concat property ": " value))
15747 ;; Possibly postprocess the inserted value:
15748 (when fn (setq value (funcall fn value)))
15749 (unless (equal (org-entry-get nil property) value)
15750 (org-entry-put nil property value))))
15752 (defun org-delete-property (property &optional delete-empty-drawer)
15753 "In the current entry, delete PROPERTY.
15754 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15755 an empty drawer to delete."
15756 (interactive
15757 (let* ((completion-ignore-case t)
15758 (prop (org-icompleting-read "Property: "
15759 (org-entry-properties nil 'standard))))
15760 (list prop)))
15761 (message "Property %s %s" property
15762 (if (org-entry-delete nil property delete-empty-drawer)
15763 "deleted"
15764 "was not present in the entry")))
15766 (defun org-delete-property-globally (property)
15767 "Remove PROPERTY globally, from all entries."
15768 (interactive
15769 (let* ((completion-ignore-case t)
15770 (prop (org-icompleting-read
15771 "Globally remove property: "
15772 (mapcar 'list (org-buffer-property-keys)))))
15773 (list prop)))
15774 (save-excursion
15775 (save-restriction
15776 (widen)
15777 (goto-char (point-min))
15778 (let ((cnt 0))
15779 (while (re-search-forward
15780 (org-re-property property)
15781 nil t)
15782 (setq cnt (1+ cnt))
15783 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15784 (message "Property \"%s\" removed from %d entries" property cnt)))))
15786 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15788 (defun org-compute-property-at-point ()
15789 "Compute the property at point.
15790 This looks for an enclosing column format, extracts the operator and
15791 then applies it to the property in the column format's scope."
15792 (interactive)
15793 (unless (org-at-property-p)
15794 (user-error "Not at a property"))
15795 (let ((prop (org-match-string-no-properties 2)))
15796 (org-columns-get-format-and-top-level)
15797 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15798 (user-error "No operator defined for property %s" prop))
15799 (org-columns-compute prop)))
15801 (defvar org-property-allowed-value-functions nil
15802 "Hook for functions supplying allowed values for a specific property.
15803 The functions must take a single argument, the name of the property, and
15804 return a flat list of allowed values. If \":ETC\" is one of
15805 the values, this means that these values are intended as defaults for
15806 completion, but that other values should be allowed too.
15807 The functions must return nil if they are not responsible for this
15808 property.")
15810 (defun org-property-get-allowed-values (pom property &optional table)
15811 "Get allowed values for the property PROPERTY.
15812 When TABLE is non-nil, return an alist that can directly be used for
15813 completion."
15814 (let (vals)
15815 (cond
15816 ((equal property "TODO")
15817 (setq vals (org-with-point-at pom
15818 (append org-todo-keywords-1 '("")))))
15819 ((equal property "PRIORITY")
15820 (let ((n org-lowest-priority))
15821 (while (>= n org-highest-priority)
15822 (push (char-to-string n) vals)
15823 (setq n (1- n)))))
15824 ((member property org-special-properties))
15825 ((setq vals (run-hook-with-args-until-success
15826 'org-property-allowed-value-functions property)))
15828 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15829 (when (and vals (string-match "\\S-" vals))
15830 (setq vals (car (read-from-string (concat "(" vals ")"))))
15831 (setq vals (mapcar (lambda (x)
15832 (cond ((stringp x) x)
15833 ((numberp x) (number-to-string x))
15834 ((symbolp x) (symbol-name x))
15835 (t "???")))
15836 vals)))))
15837 (when (member ":ETC" vals)
15838 (setq vals (remove ":ETC" vals))
15839 (org-add-props (car vals) '(org-unrestricted t)))
15840 (if table (mapcar 'list vals) vals)))
15842 (defun org-property-previous-allowed-value (&optional previous)
15843 "Switch to the next allowed value for this property."
15844 (interactive)
15845 (org-property-next-allowed-value t))
15847 (defun org-property-next-allowed-value (&optional previous)
15848 "Switch to the next allowed value for this property."
15849 (interactive)
15850 (unless (org-at-property-p)
15851 (user-error "Not at a property"))
15852 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15853 (key (match-string 2))
15854 (value (match-string 3))
15855 (allowed (or (org-property-get-allowed-values (point) key)
15856 (and (member value '("[ ]" "[-]" "[X]"))
15857 '("[ ]" "[X]"))))
15858 (heading (save-match-data (nth 4 (org-heading-components))))
15859 nval)
15860 (unless allowed
15861 (user-error "Allowed values for this property have not been defined"))
15862 (if previous (setq allowed (reverse allowed)))
15863 (if (member value allowed)
15864 (setq nval (car (cdr (member value allowed)))))
15865 (setq nval (or nval (car allowed)))
15866 (if (equal nval value)
15867 (user-error "Only one allowed value for this property"))
15868 (org-at-property-p)
15869 (replace-match (concat " :" key ": " nval) t t)
15870 (org-indent-line)
15871 (beginning-of-line 1)
15872 (skip-chars-forward " \t")
15873 (when (equal prop org-effort-property)
15874 (save-excursion
15875 (org-back-to-heading t)
15876 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15877 (when (string= org-clock-current-task heading)
15878 (setq org-clock-effort nval)
15879 (org-clock-update-mode-line)))
15880 (run-hook-with-args 'org-property-changed-functions key nval)))
15882 (defun org-find-olp (path &optional this-buffer)
15883 "Return a marker pointing to the entry at outline path OLP.
15884 If anything goes wrong, throw an error.
15885 You can wrap this call to catch the error like this:
15887 (condition-case msg
15888 (org-mobile-locate-entry (match-string 4))
15889 (error (nth 1 msg)))
15891 The return value will then be either a string with the error message,
15892 or a marker if everything is OK.
15894 If THIS-BUFFER is set, the outline path does not contain a file,
15895 only headings."
15896 (let* ((file (if this-buffer buffer-file-name (pop path)))
15897 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15898 (level 1)
15899 (lmin 1)
15900 (lmax 1)
15901 limit re end found pos heading cnt flevel)
15902 (unless buffer (error "File not found :%s" file))
15903 (with-current-buffer buffer
15904 (save-excursion
15905 (save-restriction
15906 (widen)
15907 (setq limit (point-max))
15908 (goto-char (point-min))
15909 (while (setq heading (pop path))
15910 (setq re (format org-complex-heading-regexp-format
15911 (regexp-quote heading)))
15912 (setq cnt 0 pos (point))
15913 (while (re-search-forward re end t)
15914 (setq level (- (match-end 1) (match-beginning 1)))
15915 (if (and (>= level lmin) (<= level lmax))
15916 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15917 (when (= cnt 0) (error "Heading not found on level %d: %s"
15918 lmax heading))
15919 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15920 lmax heading))
15921 (goto-char found)
15922 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15923 (setq end (save-excursion (org-end-of-subtree t t))))
15924 (when (org-at-heading-p)
15925 (point-marker)))))))
15927 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15928 "Find node HEADING in BUFFER.
15929 Return a marker to the heading if it was found, or nil if not.
15930 If POS-ONLY is set, return just the position instead of a marker.
15932 The heading text must match exact, but it may have a TODO keyword,
15933 a priority cookie and tags in the standard locations."
15934 (with-current-buffer (or buffer (current-buffer))
15935 (save-excursion
15936 (save-restriction
15937 (widen)
15938 (goto-char (point-min))
15939 (let (case-fold-search)
15940 (if (re-search-forward
15941 (format org-complex-heading-regexp-format
15942 (regexp-quote heading)) nil t)
15943 (if pos-only
15944 (match-beginning 0)
15945 (move-marker (make-marker) (match-beginning 0)))))))))
15947 (defun org-find-exact-heading-in-directory (heading &optional dir)
15948 "Find Org node headline HEADING in all .org files in directory DIR.
15949 When the target headline is found, return a marker to this location."
15950 (let ((files (directory-files (or dir default-directory)
15951 nil "\\`[^.#].*\\.org\\'"))
15952 file visiting m buffer)
15953 (catch 'found
15954 (while (setq file (pop files))
15955 (message "trying %s" file)
15956 (setq visiting (org-find-base-buffer-visiting file))
15957 (setq buffer (or visiting (find-file-noselect file)))
15958 (setq m (org-find-exact-headline-in-buffer
15959 heading buffer))
15960 (when (and (not m) (not visiting)) (kill-buffer buffer))
15961 (and m (throw 'found m))))))
15963 (defun org-find-entry-with-id (ident)
15964 "Locate the entry that contains the ID property with exact value IDENT.
15965 IDENT can be a string, a symbol or a number, this function will search for
15966 the string representation of it.
15967 Return the position where this entry starts, or nil if there is no such entry."
15968 (interactive "sID: ")
15969 (let ((id (cond
15970 ((stringp ident) ident)
15971 ((symbol-name ident) (symbol-name ident))
15972 ((numberp ident) (number-to-string ident))
15973 (t (error "IDENT %s must be a string, symbol or number" ident))))
15974 (case-fold-search nil))
15975 (save-excursion
15976 (save-restriction
15977 (widen)
15978 (goto-char (point-min))
15979 (when (re-search-forward
15980 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15981 nil t)
15982 (org-back-to-heading t)
15983 (point))))))
15985 ;;;; Timestamps
15987 (defvar org-last-changed-timestamp nil)
15988 (defvar org-last-inserted-timestamp nil
15989 "The last time stamp inserted with `org-insert-time-stamp'.")
15990 (defvar org-time-was-given) ; dynamically scoped parameter
15991 (defvar org-end-time-was-given) ; dynamically scoped parameter
15992 (defvar org-ts-what) ; dynamically scoped parameter
15994 (defun org-time-stamp (arg &optional inactive)
15995 "Prompt for a date/time and insert a time stamp.
15996 If the user specifies a time like HH:MM or if this command is
15997 called with at least one prefix argument, the time stamp contains
15998 the date and the time. Otherwise, only the date is be included.
16000 All parts of a date not specified by the user is filled in from
16001 the current date/time. So if you just press return without
16002 typing anything, the time stamp will represent the current
16003 date/time.
16005 If there is already a timestamp at the cursor, it will be
16006 modified.
16008 With two universal prefix arguments, insert an active timestamp
16009 with the current time without prompting the user."
16010 (interactive "P")
16011 (let* ((ts nil)
16012 (default-time
16013 ;; Default time is either today, or, when entering a range,
16014 ;; the range start.
16015 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16016 (save-excursion
16017 (re-search-backward
16018 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16019 (- (point) 20) t)))
16020 (apply 'encode-time (org-parse-time-string (match-string 1)))
16021 (current-time)))
16022 (default-input (and ts (org-get-compact-tod ts)))
16023 (repeater (save-excursion
16024 (save-match-data
16025 (beginning-of-line)
16026 (when (re-search-forward
16027 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16028 (save-excursion (progn (end-of-line) (point))) t)
16029 (match-string 0)))))
16030 org-time-was-given org-end-time-was-given time)
16031 (cond
16032 ((and (org-at-timestamp-p t)
16033 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16034 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16035 (insert "--")
16036 (setq time (let ((this-command this-command))
16037 (org-read-date arg 'totime nil nil
16038 default-time default-input inactive)))
16039 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16040 ((org-at-timestamp-p t)
16041 (setq time (let ((this-command this-command))
16042 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16043 (when (org-at-timestamp-p t) ; just to get the match data
16044 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16045 (replace-match "")
16046 (setq org-last-changed-timestamp
16047 (org-insert-time-stamp
16048 time (or org-time-was-given arg)
16049 inactive nil nil (list org-end-time-was-given)))
16050 (when repeater (goto-char (1- (point))) (insert " " repeater)
16051 (setq org-last-changed-timestamp
16052 (concat (substring org-last-inserted-timestamp 0 -1)
16053 " " repeater ">"))))
16054 (message "Timestamp updated"))
16055 ((equal arg '(16))
16056 (org-insert-time-stamp (current-time) t))
16058 (setq time (let ((this-command this-command))
16059 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16060 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16061 nil nil (list org-end-time-was-given))))))
16063 ;; FIXME: can we use this for something else, like computing time differences?
16064 (defun org-get-compact-tod (s)
16065 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16066 (let* ((t1 (match-string 1 s))
16067 (h1 (string-to-number (match-string 2 s)))
16068 (m1 (string-to-number (match-string 3 s)))
16069 (t2 (and (match-end 4) (match-string 5 s)))
16070 (h2 (and t2 (string-to-number (match-string 6 s))))
16071 (m2 (and t2 (string-to-number (match-string 7 s))))
16072 dh dm)
16073 (if (not t2)
16075 (setq dh (- h2 h1) dm (- m2 m1))
16076 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16077 (concat t1 "+" (number-to-string dh)
16078 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
16080 (defun org-time-stamp-inactive (&optional arg)
16081 "Insert an inactive time stamp.
16082 An inactive time stamp is enclosed in square brackets instead of angle
16083 brackets. It is inactive in the sense that it does not trigger agenda entries,
16084 does not link to the calendar and cannot be changed with the S-cursor keys.
16085 So these are more for recording a certain time/date."
16086 (interactive "P")
16087 (org-time-stamp arg 'inactive))
16089 (defvar org-date-ovl (make-overlay 1 1))
16090 (overlay-put org-date-ovl 'face 'org-date-selected)
16091 (org-detach-overlay org-date-ovl)
16093 (defvar org-ans1) ; dynamically scoped parameter
16094 (defvar org-ans2) ; dynamically scoped parameter
16096 (defvar org-plain-time-of-day-regexp) ; defined below
16098 (defvar org-overriding-default-time nil) ; dynamically scoped
16099 (defvar org-read-date-overlay nil)
16100 (defvar org-dcst nil) ; dynamically scoped
16101 (defvar org-read-date-history nil)
16102 (defvar org-read-date-final-answer nil)
16103 (defvar org-read-date-analyze-futurep nil)
16104 (defvar org-read-date-analyze-forced-year nil)
16105 (defvar org-read-date-inactive)
16107 (defvar org-read-date-minibuffer-local-map
16108 (let ((map (make-sparse-keymap)))
16109 (set-keymap-parent map minibuffer-local-map)
16110 (org-defkey map (kbd ".")
16111 (lambda () (interactive)
16112 ;; Are we at the beginning of the prompt?
16113 (if (looking-back "^[^:]+: ")
16114 (org-eval-in-calendar '(calendar-goto-today))
16115 (insert "."))))
16116 (org-defkey map (kbd "C-.")
16117 (lambda () (interactive)
16118 (org-eval-in-calendar '(calendar-goto-today))))
16119 (org-defkey map [(meta shift left)]
16120 (lambda () (interactive)
16121 (org-eval-in-calendar '(calendar-backward-month 1))))
16122 (org-defkey map [(meta shift right)]
16123 (lambda () (interactive)
16124 (org-eval-in-calendar '(calendar-forward-month 1))))
16125 (org-defkey map [(meta shift up)]
16126 (lambda () (interactive)
16127 (org-eval-in-calendar '(calendar-backward-year 1))))
16128 (org-defkey map [(meta shift down)]
16129 (lambda () (interactive)
16130 (org-eval-in-calendar '(calendar-forward-year 1))))
16131 (org-defkey map [?\e (shift left)]
16132 (lambda () (interactive)
16133 (org-eval-in-calendar '(calendar-backward-month 1))))
16134 (org-defkey map [?\e (shift right)]
16135 (lambda () (interactive)
16136 (org-eval-in-calendar '(calendar-forward-month 1))))
16137 (org-defkey map [?\e (shift up)]
16138 (lambda () (interactive)
16139 (org-eval-in-calendar '(calendar-backward-year 1))))
16140 (org-defkey map [?\e (shift down)]
16141 (lambda () (interactive)
16142 (org-eval-in-calendar '(calendar-forward-year 1))))
16143 (org-defkey map [(shift up)]
16144 (lambda () (interactive)
16145 (org-eval-in-calendar '(calendar-backward-week 1))))
16146 (org-defkey map [(shift down)]
16147 (lambda () (interactive)
16148 (org-eval-in-calendar '(calendar-forward-week 1))))
16149 (org-defkey map [(shift left)]
16150 (lambda () (interactive)
16151 (org-eval-in-calendar '(calendar-backward-day 1))))
16152 (org-defkey map [(shift right)]
16153 (lambda () (interactive)
16154 (org-eval-in-calendar '(calendar-forward-day 1))))
16155 (org-defkey map "!"
16156 (lambda () (interactive)
16157 (org-eval-in-calendar '(diary-view-entries))
16158 (message "")))
16159 (org-defkey map ">"
16160 (lambda () (interactive)
16161 (org-eval-in-calendar '(scroll-calendar-left 1))))
16162 (org-defkey map "<"
16163 (lambda () (interactive)
16164 (org-eval-in-calendar '(scroll-calendar-right 1))))
16165 (org-defkey map "\C-v"
16166 (lambda () (interactive)
16167 (org-eval-in-calendar
16168 '(calendar-scroll-left-three-months 1))))
16169 (org-defkey map "\M-v"
16170 (lambda () (interactive)
16171 (org-eval-in-calendar
16172 '(calendar-scroll-right-three-months 1))))
16173 map)
16174 "Keymap for minibuffer commands when using `org-read-date'.")
16176 (defun org-read-date (&optional org-with-time to-time from-string prompt
16177 default-time default-input inactive)
16178 "Read a date, possibly a time, and make things smooth for the user.
16179 The prompt will suggest to enter an ISO date, but you can also enter anything
16180 which will at least partially be understood by `parse-time-string'.
16181 Unrecognized parts of the date will default to the current day, month, year,
16182 hour and minute. If this command is called to replace a timestamp at point,
16183 or to enter the second timestamp of a range, the default time is taken
16184 from the existing stamp. Furthermore, the command prefers the future,
16185 so if you are giving a date where the year is not given, and the day-month
16186 combination is already past in the current year, it will assume you
16187 mean next year. For details, see the manual. A few examples:
16189 3-2-5 --> 2003-02-05
16190 feb 15 --> currentyear-02-15
16191 2/15 --> currentyear-02-15
16192 sep 12 9 --> 2009-09-12
16193 12:45 --> today 12:45
16194 22 sept 0:34 --> currentyear-09-22 0:34
16195 12 --> currentyear-currentmonth-12
16196 Fri --> nearest Friday after today
16197 -Tue --> last Tuesday
16198 etc.
16200 Furthermore you can specify a relative date by giving, as the *first* thing
16201 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16202 change in days weeks, months, years.
16203 With a single plus or minus, the date is relative to today. With a double
16204 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16205 +4d --> four days from today
16206 +4 --> same as above
16207 +2w --> two weeks from today
16208 ++5 --> five days from default date
16210 The function understands only English month and weekday abbreviations.
16212 While prompting, a calendar is popped up - you can also select the
16213 date with the mouse (button 1). The calendar shows a period of three
16214 months. To scroll it to other months, use the keys `>' and `<'.
16215 If you don't like the calendar, turn it off with
16216 \(setq org-read-date-popup-calendar nil)
16218 With optional argument TO-TIME, the date will immediately be converted
16219 to an internal time.
16220 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16221 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16222 still enter a time, and this function will inform the calling routine
16223 about this change. The calling routine may then choose to change the
16224 format used to insert the time stamp into the buffer to include the time.
16225 With optional argument FROM-STRING, read from this string instead from
16226 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16227 the time/date that is used for everything that is not specified by the
16228 user."
16229 (require 'parse-time)
16230 (let* ((org-time-stamp-rounding-minutes
16231 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16232 (org-dcst org-display-custom-times)
16233 (ct (org-current-time))
16234 (org-def (or org-overriding-default-time default-time ct))
16235 (org-defdecode (decode-time org-def))
16236 (dummy (progn
16237 (when (< (nth 2 org-defdecode) org-extend-today-until)
16238 (setcar (nthcdr 2 org-defdecode) -1)
16239 (setcar (nthcdr 1 org-defdecode) 59)
16240 (setq org-def (apply 'encode-time org-defdecode)
16241 org-defdecode (decode-time org-def)))))
16242 (mouse-autoselect-window nil) ; Don't let the mouse jump
16243 (calendar-frame-setup nil)
16244 (calendar-setup nil)
16245 (calendar-move-hook nil)
16246 (calendar-view-diary-initially-flag nil)
16247 (calendar-view-holidays-initially-flag nil)
16248 (timestr (format-time-string
16249 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16250 (prompt (concat (if prompt (concat prompt " ") "")
16251 (format "Date+time [%s]: " timestr)))
16252 ans (org-ans0 "") org-ans1 org-ans2 final)
16254 (cond
16255 (from-string (setq ans from-string))
16256 (org-read-date-popup-calendar
16257 (save-excursion
16258 (save-window-excursion
16259 (calendar)
16260 (org-eval-in-calendar '(setq cursor-type nil) t)
16261 (unwind-protect
16262 (progn
16263 (calendar-forward-day (- (time-to-days org-def)
16264 (calendar-absolute-from-gregorian
16265 (calendar-current-date))))
16266 (org-eval-in-calendar nil t)
16267 (let* ((old-map (current-local-map))
16268 (map (copy-keymap calendar-mode-map))
16269 (minibuffer-local-map
16270 (copy-keymap org-read-date-minibuffer-local-map)))
16271 (org-defkey map (kbd "RET") 'org-calendar-select)
16272 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16273 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16274 (unwind-protect
16275 (progn
16276 (use-local-map map)
16277 (setq org-read-date-inactive inactive)
16278 (add-hook 'post-command-hook 'org-read-date-display)
16279 (setq org-ans0 (read-string prompt default-input
16280 'org-read-date-history nil))
16281 ;; org-ans0: from prompt
16282 ;; org-ans1: from mouse click
16283 ;; org-ans2: from calendar motion
16284 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16285 (remove-hook 'post-command-hook 'org-read-date-display)
16286 (use-local-map old-map)
16287 (when org-read-date-overlay
16288 (delete-overlay org-read-date-overlay)
16289 (setq org-read-date-overlay nil)))))
16290 (bury-buffer "*Calendar*")))))
16292 (t ; Naked prompt only
16293 (unwind-protect
16294 (setq ans (read-string prompt default-input
16295 'org-read-date-history timestr))
16296 (when org-read-date-overlay
16297 (delete-overlay org-read-date-overlay)
16298 (setq org-read-date-overlay nil)))))
16300 (setq final (org-read-date-analyze ans org-def org-defdecode))
16302 (when org-read-date-analyze-forced-year
16303 (message "Year was forced into %s"
16304 (if org-read-date-force-compatible-dates
16305 "compatible range (1970-2037)"
16306 "range representable on this machine"))
16307 (ding))
16309 ;; One round trip to get rid of 34th of August and stuff like that....
16310 (setq final (decode-time (apply 'encode-time final)))
16312 (setq org-read-date-final-answer ans)
16314 (if to-time
16315 (apply 'encode-time final)
16316 (if (and (boundp 'org-time-was-given) org-time-was-given)
16317 (format "%04d-%02d-%02d %02d:%02d"
16318 (nth 5 final) (nth 4 final) (nth 3 final)
16319 (nth 2 final) (nth 1 final))
16320 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16322 (defvar org-def)
16323 (defvar org-defdecode)
16324 (defvar org-with-time)
16325 (defun org-read-date-display ()
16326 "Display the current date prompt interpretation in the minibuffer."
16327 (when org-read-date-display-live
16328 (when org-read-date-overlay
16329 (delete-overlay org-read-date-overlay))
16330 (when (minibufferp (current-buffer))
16331 (save-excursion
16332 (end-of-line 1)
16333 (while (not (equal (buffer-substring
16334 (max (point-min) (- (point) 4)) (point))
16335 " "))
16336 (insert " ")))
16337 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16338 " " (or org-ans1 org-ans2)))
16339 (org-end-time-was-given nil)
16340 (f (org-read-date-analyze ans org-def org-defdecode))
16341 (fmts (if org-dcst
16342 org-time-stamp-custom-formats
16343 org-time-stamp-formats))
16344 (fmt (if (or org-with-time
16345 (and (boundp 'org-time-was-given) org-time-was-given))
16346 (cdr fmts)
16347 (car fmts)))
16348 (txt (format-time-string fmt (apply 'encode-time f)))
16349 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16350 (txt (concat "=> " txt)))
16351 (when (and org-end-time-was-given
16352 (string-match org-plain-time-of-day-regexp txt))
16353 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16354 org-end-time-was-given
16355 (substring txt (match-end 0)))))
16356 (when org-read-date-analyze-futurep
16357 (setq txt (concat txt " (=>F)")))
16358 (setq org-read-date-overlay
16359 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16360 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16362 (defun org-read-date-analyze (ans org-def org-defdecode)
16363 "Analyze the combined answer of the date prompt."
16364 ;; FIXME: cleanup and comment
16365 (let ((nowdecode (decode-time (current-time)))
16366 delta deltan deltaw deltadef year month day
16367 hour minute second wday pm h2 m2 tl wday1
16368 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16369 (setq org-read-date-analyze-futurep nil
16370 org-read-date-analyze-forced-year nil)
16371 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16372 (setq ans "+0"))
16374 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16375 (setq ans (replace-match "" t t ans)
16376 deltan (car delta)
16377 deltaw (nth 1 delta)
16378 deltadef (nth 2 delta)))
16380 ;; Check if there is an iso week date in there. If yes, store the
16381 ;; info and postpone interpreting it until the rest of the parsing
16382 ;; is done.
16383 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16384 (setq iso-year (if (match-end 1)
16385 (org-small-year-to-year
16386 (string-to-number (match-string 1 ans))))
16387 iso-weekday (if (match-end 3)
16388 (string-to-number (match-string 3 ans)))
16389 iso-week (string-to-number (match-string 2 ans)))
16390 (setq ans (replace-match "" t t ans)))
16392 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16393 (when (string-match
16394 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16395 (setq year (if (match-end 2)
16396 (string-to-number (match-string 2 ans))
16397 (progn (setq kill-year t)
16398 (string-to-number (format-time-string "%Y"))))
16399 month (string-to-number (match-string 3 ans))
16400 day (string-to-number (match-string 4 ans)))
16401 (if (< year 100) (setq year (+ 2000 year)))
16402 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16403 t nil ans)))
16405 ;; Help matching dotted european dates
16406 (when (string-match
16407 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16408 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16409 (setq kill-year t)
16410 (string-to-number (format-time-string "%Y")))
16411 day (string-to-number (match-string 1 ans))
16412 month (string-to-number (match-string 2 ans))
16413 ans (replace-match (format "%04d-%02d-%02d" year month day)
16414 t nil ans)))
16416 ;; Help matching american dates, like 5/30 or 5/30/7
16417 (when (string-match
16418 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16419 (setq year (if (match-end 4)
16420 (string-to-number (match-string 4 ans))
16421 (progn (setq kill-year t)
16422 (string-to-number (format-time-string "%Y"))))
16423 month (string-to-number (match-string 1 ans))
16424 day (string-to-number (match-string 2 ans)))
16425 (if (< year 100) (setq year (+ 2000 year)))
16426 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16427 t nil ans)))
16428 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16429 ;; If there is a time with am/pm, and *no* time without it, we convert
16430 ;; so that matching will be successful.
16431 (loop for i from 1 to 2 do ; twice, for end time as well
16432 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16433 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16434 (setq hour (string-to-number (match-string 1 ans))
16435 minute (if (match-end 3)
16436 (string-to-number (match-string 3 ans))
16438 pm (equal ?p
16439 (string-to-char (downcase (match-string 4 ans)))))
16440 (if (and (= hour 12) (not pm))
16441 (setq hour 0)
16442 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16443 (setq ans (replace-match (format "%02d:%02d" hour minute)
16444 t t ans))))
16446 ;; Check if a time range is given as a duration
16447 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16448 (setq hour (string-to-number (match-string 1 ans))
16449 h2 (+ hour (string-to-number (match-string 3 ans)))
16450 minute (string-to-number (match-string 2 ans))
16451 m2 (+ minute (if (match-end 5) (string-to-number
16452 (match-string 5 ans))0)))
16453 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16454 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16455 t t ans)))
16457 ;; Check if there is a time range
16458 (when (boundp 'org-end-time-was-given)
16459 (setq org-time-was-given nil)
16460 (when (and (string-match org-plain-time-of-day-regexp ans)
16461 (match-end 8))
16462 (setq org-end-time-was-given (match-string 8 ans))
16463 (setq ans (concat (substring ans 0 (match-beginning 7))
16464 (substring ans (match-end 7))))))
16466 (setq tl (parse-time-string ans)
16467 day (or (nth 3 tl) (nth 3 org-defdecode))
16468 month (or (nth 4 tl)
16469 (if (and org-read-date-prefer-future
16470 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16471 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16472 (nth 4 org-defdecode)))
16473 year (or (and (not kill-year) (nth 5 tl))
16474 (if (and org-read-date-prefer-future
16475 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16476 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16477 (nth 5 org-defdecode)))
16478 hour (or (nth 2 tl) (nth 2 org-defdecode))
16479 minute (or (nth 1 tl) (nth 1 org-defdecode))
16480 second (or (nth 0 tl) 0)
16481 wday (nth 6 tl))
16483 (when (and (eq org-read-date-prefer-future 'time)
16484 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16485 (equal day (nth 3 nowdecode))
16486 (equal month (nth 4 nowdecode))
16487 (equal year (nth 5 nowdecode))
16488 (nth 2 tl)
16489 (or (< (nth 2 tl) (nth 2 nowdecode))
16490 (and (= (nth 2 tl) (nth 2 nowdecode))
16491 (nth 1 tl)
16492 (< (nth 1 tl) (nth 1 nowdecode)))))
16493 (setq day (1+ day)
16494 futurep t))
16496 ;; Special date definitions below
16497 (cond
16498 (iso-week
16499 ;; There was an iso week
16500 (require 'cal-iso)
16501 (setq futurep nil)
16502 (setq year (or iso-year year)
16503 day (or iso-weekday wday 1)
16504 wday nil ; to make sure that the trigger below does not match
16505 iso-date (calendar-gregorian-from-absolute
16506 (calendar-absolute-from-iso
16507 (list iso-week day year))))
16508 ; FIXME: Should we also push ISO weeks into the future?
16509 ; (when (and org-read-date-prefer-future
16510 ; (not iso-year)
16511 ; (< (calendar-absolute-from-gregorian iso-date)
16512 ; (time-to-days (current-time))))
16513 ; (setq year (1+ year)
16514 ; iso-date (calendar-gregorian-from-absolute
16515 ; (calendar-absolute-from-iso
16516 ; (list iso-week day year)))))
16517 (setq month (car iso-date)
16518 year (nth 2 iso-date)
16519 day (nth 1 iso-date)))
16520 (deltan
16521 (setq futurep nil)
16522 (unless deltadef
16523 (let ((now (decode-time (current-time))))
16524 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16525 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16526 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16527 ((equal deltaw "m") (setq month (+ month deltan)))
16528 ((equal deltaw "y") (setq year (+ year deltan)))))
16529 ((and wday (not (nth 3 tl)))
16530 ;; Weekday was given, but no day, so pick that day in the week
16531 ;; on or after the derived date.
16532 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16533 (unless (equal wday wday1)
16534 (setq day (+ day (% (- wday wday1 -7) 7))))))
16535 (if (and (boundp 'org-time-was-given)
16536 (nth 2 tl))
16537 (setq org-time-was-given t))
16538 (if (< year 100) (setq year (+ 2000 year)))
16539 ;; Check of the date is representable
16540 (if org-read-date-force-compatible-dates
16541 (progn
16542 (if (< year 1970)
16543 (setq year 1970 org-read-date-analyze-forced-year t))
16544 (if (> year 2037)
16545 (setq year 2037 org-read-date-analyze-forced-year t)))
16546 (condition-case nil
16547 (ignore (encode-time second minute hour day month year))
16548 (error
16549 (setq year (nth 5 org-defdecode))
16550 (setq org-read-date-analyze-forced-year t))))
16551 (setq org-read-date-analyze-futurep futurep)
16552 (list second minute hour day month year)))
16554 (defvar parse-time-weekdays)
16555 (defun org-read-date-get-relative (s today default)
16556 "Check string S for special relative date string.
16557 TODAY and DEFAULT are internal times, for today and for a default.
16558 Return shift list (N what def-flag)
16559 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16560 N is the number of WHATs to shift.
16561 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16562 the DEFAULT date rather than TODAY."
16563 (require 'parse-time)
16564 (when (and
16565 (string-match
16566 (concat
16567 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16568 "\\([0-9]+\\)?"
16569 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16570 "\\([ \t]\\|$\\)") s)
16571 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16572 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16573 (string-to-char (substring (match-string 1 s) -1))
16574 ?+))
16575 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16576 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16577 (what (if (match-end 3) (match-string 3 s) "d"))
16578 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16579 (date (if rel default today))
16580 (wday (nth 6 (decode-time date)))
16581 delta)
16582 (if wday1
16583 (progn
16584 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16585 (if (= delta 0) (setq delta 7))
16586 (if (= dir ?-)
16587 (progn
16588 (setq delta (- delta 7))
16589 (if (= delta 0) (setq delta -7))))
16590 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16591 (list delta "d" rel))
16592 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16594 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16595 "Turn a user-specified date into the internal representation.
16596 The internal representation needed by the calendar is (month day year).
16597 This is a wrapper to handle the brain-dead convention in calendar that
16598 user function argument order change dependent on argument order."
16599 (if (boundp 'calendar-date-style)
16600 (cond
16601 ((eq calendar-date-style 'american)
16602 (list arg1 arg2 arg3))
16603 ((eq calendar-date-style 'european)
16604 (list arg2 arg1 arg3))
16605 ((eq calendar-date-style 'iso)
16606 (list arg2 arg3 arg1)))
16607 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16608 (if (org-bound-and-true-p european-calendar-style)
16609 (list arg2 arg1 arg3)
16610 (list arg1 arg2 arg3)))))
16612 (defun org-eval-in-calendar (form &optional keepdate)
16613 "Eval FORM in the calendar window and return to current window.
16614 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16615 otherwise stick to the current value of `org-ans2'."
16616 (let ((sf (selected-frame))
16617 (sw (selected-window)))
16618 (select-window (get-buffer-window "*Calendar*" t))
16619 (eval form)
16620 (when (and (not keepdate) (calendar-cursor-to-date))
16621 (let* ((date (calendar-cursor-to-date))
16622 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16623 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16624 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16625 (select-window sw)
16626 (org-select-frame-set-input-focus sf)))
16628 (defun org-calendar-select ()
16629 "Return to `org-read-date' with the date currently selected.
16630 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16631 (interactive)
16632 (when (calendar-cursor-to-date)
16633 (let* ((date (calendar-cursor-to-date))
16634 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16635 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16636 (if (active-minibuffer-window) (exit-minibuffer))))
16638 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16639 "Insert a date stamp for the date given by the internal TIME.
16640 WITH-HM means use the stamp format that includes the time of the day.
16641 INACTIVE means use square brackets instead of angular ones, so that the
16642 stamp will not contribute to the agenda.
16643 PRE and POST are optional strings to be inserted before and after the
16644 stamp.
16645 The command returns the inserted time stamp."
16646 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16647 stamp)
16648 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16649 (insert-before-markers (or pre ""))
16650 (when (listp extra)
16651 (setq extra (car extra))
16652 (if (and (stringp extra)
16653 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16654 (setq extra (format "-%02d:%02d"
16655 (string-to-number (match-string 1 extra))
16656 (string-to-number (match-string 2 extra))))
16657 (setq extra nil)))
16658 (when extra
16659 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16660 (insert-before-markers (setq stamp (format-time-string fmt time)))
16661 (insert-before-markers (or post ""))
16662 (setq org-last-inserted-timestamp stamp)))
16664 (defun org-toggle-time-stamp-overlays ()
16665 "Toggle the use of custom time stamp formats."
16666 (interactive)
16667 (setq org-display-custom-times (not org-display-custom-times))
16668 (unless org-display-custom-times
16669 (let ((p (point-min)) (bmp (buffer-modified-p)))
16670 (while (setq p (next-single-property-change p 'display))
16671 (if (and (get-text-property p 'display)
16672 (eq (get-text-property p 'face) 'org-date))
16673 (remove-text-properties
16674 p (setq p (next-single-property-change p 'display))
16675 '(display t))))
16676 (set-buffer-modified-p bmp)))
16677 (if (featurep 'xemacs)
16678 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16679 (org-restart-font-lock)
16680 (setq org-table-may-need-update t)
16681 (if org-display-custom-times
16682 (message "Time stamps are overlaid with custom format")
16683 (message "Time stamp overlays removed")))
16685 (defun org-display-custom-time (beg end)
16686 "Overlay modified time stamp format over timestamp between BEG and END."
16687 (let* ((ts (buffer-substring beg end))
16688 t1 w1 with-hm tf time str w2 (off 0))
16689 (save-match-data
16690 (setq t1 (org-parse-time-string ts t))
16691 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16692 (setq off (- (match-end 0) (match-beginning 0)))))
16693 (setq end (- end off))
16694 (setq w1 (- end beg)
16695 with-hm (and (nth 1 t1) (nth 2 t1))
16696 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16697 time (org-fix-decoded-time t1)
16698 str (org-add-props
16699 (format-time-string
16700 (substring tf 1 -1) (apply 'encode-time time))
16701 nil 'mouse-face 'highlight)
16702 w2 (length str))
16703 (if (not (= w2 w1))
16704 (add-text-properties (1+ beg) (+ 2 beg)
16705 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16706 (if (featurep 'xemacs)
16707 (progn
16708 (put-text-property beg end 'invisible t)
16709 (put-text-property beg end 'end-glyph (make-glyph str)))
16710 (put-text-property beg end 'display str))))
16712 (defun org-translate-time (string)
16713 "Translate all timestamps in STRING to custom format.
16714 But do this only if the variable `org-display-custom-times' is set."
16715 (when org-display-custom-times
16716 (save-match-data
16717 (let* ((start 0)
16718 (re org-ts-regexp-both)
16719 t1 with-hm inactive tf time str beg end)
16720 (while (setq start (string-match re string start))
16721 (setq beg (match-beginning 0)
16722 end (match-end 0)
16723 t1 (save-match-data
16724 (org-parse-time-string (substring string beg end) t))
16725 with-hm (and (nth 1 t1) (nth 2 t1))
16726 inactive (equal (substring string beg (1+ beg)) "[")
16727 tf (funcall (if with-hm 'cdr 'car)
16728 org-time-stamp-custom-formats)
16729 time (org-fix-decoded-time t1)
16730 str (format-time-string
16731 (concat
16732 (if inactive "[" "<") (substring tf 1 -1)
16733 (if inactive "]" ">"))
16734 (apply 'encode-time time))
16735 string (replace-match str t t string)
16736 start (+ start (length str)))))))
16737 string)
16739 (defun org-fix-decoded-time (time)
16740 "Set 0 instead of nil for the first 6 elements of time.
16741 Don't touch the rest."
16742 (let ((n 0))
16743 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16745 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16747 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16748 "Difference between TIMESTAMP-STRING and now in days.
16749 If SECONDS is non-nil, return the difference in seconds."
16750 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16751 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16752 (funcall fdiff (current-time)))))
16754 (defun org-deadline-close (timestamp-string &optional ndays)
16755 "Is the time in TIMESTAMP-STRING close to the current date?"
16756 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16757 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16758 (not (org-entry-is-done-p))))
16760 (defun org-get-wdays (ts &optional delay zero-delay)
16761 "Get the deadline lead time appropriate for timestring TS.
16762 When DELAY is non-nil, get the delay time for scheduled items
16763 instead of the deadline lead time. When ZERO-DELAY is non-nil
16764 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16765 don't try to find the delay cookie in the scheduled timestamp."
16766 (let ((tv (if delay org-scheduled-delay-days
16767 org-deadline-warning-days)))
16768 (cond
16769 ((or (and delay (< tv 0))
16770 (and delay zero-delay (<= tv 0))
16771 (and (not delay) (<= tv 0)))
16772 ;; Enforce this value no matter what
16773 (- tv))
16774 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16775 ;; lead time is specified.
16776 (floor (* (string-to-number (match-string 1 ts))
16777 (cdr (assoc (match-string 2 ts)
16778 '(("d" . 1) ("w" . 7)
16779 ("m" . 30.4) ("y" . 365.25)
16780 ("h" . 0.041667)))))))
16781 ;; go for the default.
16782 (t tv))))
16784 (defun org-calendar-select-mouse (ev)
16785 "Return to `org-read-date' with the date currently selected.
16786 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16787 (interactive "e")
16788 (mouse-set-point ev)
16789 (when (calendar-cursor-to-date)
16790 (let* ((date (calendar-cursor-to-date))
16791 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16792 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16793 (if (active-minibuffer-window) (exit-minibuffer))))
16795 (defun org-check-deadlines (ndays)
16796 "Check if there are any deadlines due or past due.
16797 A deadline is considered due if it happens within `org-deadline-warning-days'
16798 days from today's date. If the deadline appears in an entry marked DONE,
16799 it is not shown. The prefix arg NDAYS can be used to test that many
16800 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16801 (interactive "P")
16802 (let* ((org-warn-days
16803 (cond
16804 ((equal ndays '(4)) 100000)
16805 (ndays (prefix-numeric-value ndays))
16806 (t (abs org-deadline-warning-days))))
16807 (case-fold-search nil)
16808 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16809 (callback
16810 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16812 (message "%d deadlines past-due or due within %d days"
16813 (org-occur regexp nil callback)
16814 org-warn-days)))
16816 (defsubst org-re-timestamp (type)
16817 "Return a regexp for timestamp TYPE.
16818 Allowed values for TYPE are:
16820 all: all timestamps
16821 active: only active timestamps (<...>)
16822 inactive: only inactive timestamps ([...])
16823 scheduled: only scheduled timestamps
16824 deadline: only deadline timestamps
16825 closed: only closed time-stamps
16827 When TYPE is nil, fall back on returning a regexp that matches
16828 both scheduled and deadline timestamps."
16829 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16830 ((eq type 'active) org-ts-regexp)
16831 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16832 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16833 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16834 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16835 ((eq type 'scheduled-or-deadline)
16836 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16838 (defun org-check-before-date (date)
16839 "Check if there are deadlines or scheduled entries before DATE."
16840 (interactive (list (org-read-date)))
16841 (let ((case-fold-search nil)
16842 (regexp (org-re-timestamp org-ts-type))
16843 (callback
16844 (lambda () (time-less-p
16845 (org-time-string-to-time (match-string 1))
16846 (org-time-string-to-time date)))))
16847 (message "%d entries before %s"
16848 (org-occur regexp nil callback) date)))
16850 (defun org-check-after-date (date)
16851 "Check if there are deadlines or scheduled entries after DATE."
16852 (interactive (list (org-read-date)))
16853 (let ((case-fold-search nil)
16854 (regexp (org-re-timestamp org-ts-type))
16855 (callback
16856 (lambda () (not
16857 (time-less-p
16858 (org-time-string-to-time (match-string 1))
16859 (org-time-string-to-time date))))))
16860 (message "%d entries after %s"
16861 (org-occur regexp nil callback) date)))
16863 (defun org-check-dates-range (start-date end-date)
16864 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16865 (interactive (list (org-read-date nil nil nil "Range starts")
16866 (org-read-date nil nil nil "Range end")))
16867 (let ((case-fold-search nil)
16868 (regexp (org-re-timestamp org-ts-type))
16869 (callback
16870 (lambda ()
16871 (let ((match (match-string 1)))
16872 (and
16873 (not (time-less-p
16874 (org-time-string-to-time match)
16875 (org-time-string-to-time start-date)))
16876 (time-less-p
16877 (org-time-string-to-time match)
16878 (org-time-string-to-time end-date)))))))
16879 (message "%d entries between %s and %s"
16880 (org-occur regexp nil callback) start-date end-date)))
16882 (defun org-evaluate-time-range (&optional to-buffer)
16883 "Evaluate a time range by computing the difference between start and end.
16884 Normally the result is just printed in the echo area, but with prefix arg
16885 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16886 If the time range is actually in a table, the result is inserted into the
16887 next column.
16888 For time difference computation, a year is assumed to be exactly 365
16889 days in order to avoid rounding problems."
16890 (interactive "P")
16892 (org-clock-update-time-maybe)
16893 (save-excursion
16894 (unless (org-at-date-range-p t)
16895 (goto-char (point-at-bol))
16896 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16897 (if (not (org-at-date-range-p t))
16898 (user-error "Not at a time-stamp range, and none found in current line")))
16899 (let* ((ts1 (match-string 1))
16900 (ts2 (match-string 2))
16901 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16902 (match-end (match-end 0))
16903 (time1 (org-time-string-to-time ts1))
16904 (time2 (org-time-string-to-time ts2))
16905 (t1 (org-float-time time1))
16906 (t2 (org-float-time time2))
16907 (diff (abs (- t2 t1)))
16908 (negative (< (- t2 t1) 0))
16909 ;; (ys (floor (* 365 24 60 60)))
16910 (ds (* 24 60 60))
16911 (hs (* 60 60))
16912 (fy "%dy %dd %02d:%02d")
16913 (fy1 "%dy %dd")
16914 (fd "%dd %02d:%02d")
16915 (fd1 "%dd")
16916 (fh "%02d:%02d")
16917 y d h m align)
16918 (if havetime
16919 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16921 d (floor (/ diff ds)) diff (mod diff ds)
16922 h (floor (/ diff hs)) diff (mod diff hs)
16923 m (floor (/ diff 60)))
16924 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16926 d (floor (+ (/ diff ds) 0.5))
16927 h 0 m 0))
16928 (if (not to-buffer)
16929 (message "%s" (org-make-tdiff-string y d h m))
16930 (if (org-at-table-p)
16931 (progn
16932 (goto-char match-end)
16933 (setq align t)
16934 (and (looking-at " *|") (goto-char (match-end 0))))
16935 (goto-char match-end))
16936 (if (looking-at
16937 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16938 (replace-match ""))
16939 (if negative (insert " -"))
16940 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16941 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16942 (insert " " (format fh h m))))
16943 (if align (org-table-align))
16944 (message "Time difference inserted")))))
16946 (defun org-make-tdiff-string (y d h m)
16947 (let ((fmt "")
16948 (l nil))
16949 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16950 l (push y l)))
16951 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16952 l (push d l)))
16953 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16954 l (push h l)))
16955 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16956 l (push m l)))
16957 (apply 'format fmt (nreverse l))))
16959 (defun org-time-string-to-time (s &optional buffer pos)
16960 "Convert a timestamp string into internal time."
16961 (condition-case errdata
16962 (apply 'encode-time (org-parse-time-string s))
16963 (error (error "Bad timestamp `%s'%s\nError was: %s"
16964 s (if (not (and buffer pos))
16966 (format " at %d in buffer `%s'" pos buffer))
16967 (cdr errdata)))))
16969 (defun org-time-string-to-seconds (s)
16970 "Convert a timestamp string to a number of seconds."
16971 (org-float-time (org-time-string-to-time s)))
16973 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16974 "Convert a time stamp to an absolute day number.
16975 If there is a specifier for a cyclic time stamp, get the closest
16976 date to DAYNR.
16977 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16978 The variable `date' is bound by the calendar when this is called."
16979 (cond
16980 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16981 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16982 daynr
16983 (+ daynr 1000)))
16984 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16985 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16986 (time-to-days (current-time))) (match-string 0 s)
16987 prefer show-all))
16988 (t (time-to-days
16989 (condition-case errdata
16990 (apply 'encode-time (org-parse-time-string s))
16991 (error (error "Bad timestamp `%s'%s\nError was: %s"
16992 s (if (not (and buffer pos))
16994 (format " at %d in buffer `%s'" pos buffer))
16995 (cdr errdata))))))))
16997 (defun org-days-to-iso-week (days)
16998 "Return the iso week number."
16999 (require 'cal-iso)
17000 (car (calendar-iso-from-absolute days)))
17002 (defun org-small-year-to-year (year)
17003 "Convert 2-digit years into 4-digit years.
17004 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17005 The year 2000 cannot be abbreviated. Any year larger than 99
17006 is returned unchanged."
17007 (if (< year 38)
17008 (setq year (+ 2000 year))
17009 (if (< year 100)
17010 (setq year (+ 1900 year))))
17011 year)
17013 (defun org-time-from-absolute (d)
17014 "Return the time corresponding to date D.
17015 D may be an absolute day number, or a calendar-type list (month day year)."
17016 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17017 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17019 (defun org-calendar-holiday ()
17020 "List of holidays, for Diary display in Org-mode."
17021 (require 'holidays)
17022 (let ((hl (funcall
17023 (if (fboundp 'calendar-check-holidays)
17024 'calendar-check-holidays 'check-calendar-holidays) date)))
17025 (if hl (mapconcat 'identity hl "; "))))
17027 (defun org-diary-sexp-entry (sexp entry date)
17028 "Process a SEXP diary ENTRY for DATE."
17029 (require 'diary-lib)
17030 (let ((result (if calendar-debug-sexp
17031 (let ((stack-trace-on-error t))
17032 (eval (car (read-from-string sexp))))
17033 (condition-case nil
17034 (eval (car (read-from-string sexp)))
17035 (error
17036 (beep)
17037 (message "Bad sexp at line %d in %s: %s"
17038 (org-current-line)
17039 (buffer-file-name) sexp)
17040 (sleep-for 2))))))
17041 (cond ((stringp result) (split-string result "; "))
17042 ((and (consp result)
17043 (not (consp (cdr result)))
17044 (stringp (cdr result))) (cdr result))
17045 ((and (consp result)
17046 (stringp (car result))) result)
17047 (result entry))))
17049 (defun org-diary-to-ical-string (frombuf)
17050 "Get iCalendar entries from diary entries in buffer FROMBUF.
17051 This uses the icalendar.el library."
17052 (let* ((tmpdir (if (featurep 'xemacs)
17053 (temp-directory)
17054 temporary-file-directory))
17055 (tmpfile (make-temp-name
17056 (expand-file-name "orgics" tmpdir)))
17057 buf rtn b e)
17058 (with-current-buffer frombuf
17059 (icalendar-export-region (point-min) (point-max) tmpfile)
17060 (setq buf (find-buffer-visiting tmpfile))
17061 (set-buffer buf)
17062 (goto-char (point-min))
17063 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17064 (setq b (match-beginning 0)))
17065 (goto-char (point-max))
17066 (if (re-search-backward "^END:VEVENT" nil t)
17067 (setq e (match-end 0)))
17068 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17069 (kill-buffer buf)
17070 (delete-file tmpfile)
17071 rtn))
17073 (defun org-closest-date (start current change prefer show-all)
17074 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17075 When PREFER is `past', return a date that is either CURRENT or past.
17076 When PREFER is `future', return a date that is either CURRENT or future.
17077 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17078 ;; Make the proper lists from the dates
17079 (catch 'exit
17080 (let ((a1 '(("h" . hour)
17081 ("d" . day)
17082 ("w" . week)
17083 ("m" . month)
17084 ("y" . year)))
17085 (shour (nth 2 (org-parse-time-string start)))
17086 dn dw sday cday n1 n2 n0
17087 d m y y1 y2 date1 date2 nmonths nm ny m2)
17089 (setq start (org-date-to-gregorian start)
17090 current (org-date-to-gregorian
17091 (if show-all
17092 current
17093 (time-to-days (current-time))))
17094 sday (calendar-absolute-from-gregorian start)
17095 cday (calendar-absolute-from-gregorian current))
17097 (if (<= cday sday) (throw 'exit sday))
17099 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17100 (setq dn (string-to-number (match-string 1 change))
17101 dw (cdr (assoc (match-string 2 change) a1)))
17102 (user-error "Invalid change specifier: %s" change))
17103 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17104 (cond
17105 ((eq dw 'hour)
17106 (let ((missing-hours
17107 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17108 dn)))
17109 (setq n1 (if (zerop missing-hours) cday
17110 (- cday (1+ (floor (/ missing-hours 24)))))
17111 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17112 ((eq dw 'day)
17113 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17114 n2 (+ n1 dn)))
17115 ((eq dw 'year)
17116 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17117 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17118 (setq date1 (list m d y1)
17119 n1 (calendar-absolute-from-gregorian date1)
17120 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17121 n2 (calendar-absolute-from-gregorian date2)))
17122 ((eq dw 'month)
17123 ;; approx number of month between the two dates
17124 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17125 ;; How often does dn fit in there?
17126 (setq d (nth 1 start) m (car start) y (nth 2 start)
17127 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17128 m (+ m nm)
17129 ny (floor (/ m 12))
17130 y (+ y ny)
17131 m (- m (* ny 12)))
17132 (while (> m 12) (setq m (- m 12) y (1+ y)))
17133 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17134 (setq m2 (+ m dn) y2 y)
17135 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17136 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17137 (while (<= n2 cday)
17138 (setq n1 n2 m m2 y y2)
17139 (setq m2 (+ m dn) y2 y)
17140 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17141 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17142 ;; Make sure n1 is the earlier date
17143 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17144 (if show-all
17145 (cond
17146 ((eq prefer 'past) (if (= cday n2) n2 n1))
17147 ((eq prefer 'future) (if (= cday n1) n1 n2))
17148 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17149 (cond
17150 ((eq prefer 'past) (if (= cday n2) n2 n1))
17151 ((eq prefer 'future) (if (= cday n1) n1 n2))
17152 (t (if (= cday n1) n1 n2)))))))
17154 (defun org-date-to-gregorian (date)
17155 "Turn any specification of DATE into a Gregorian date for the calendar."
17156 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17157 ((and (listp date) (= (length date) 3)) date)
17158 ((stringp date)
17159 (setq date (org-parse-time-string date))
17160 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17161 ((listp date)
17162 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17164 (defun org-parse-time-string (s &optional nodefault)
17165 "Parse the standard Org-mode time string.
17166 This should be a lot faster than the normal `parse-time-string'.
17167 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17168 hour and minute fields will be nil if not given."
17169 (cond ((string-match org-ts-regexp0 s)
17170 (list 0
17171 (if (or (match-beginning 8) (not nodefault))
17172 (string-to-number (or (match-string 8 s) "0")))
17173 (if (or (match-beginning 7) (not nodefault))
17174 (string-to-number (or (match-string 7 s) "0")))
17175 (string-to-number (match-string 4 s))
17176 (string-to-number (match-string 3 s))
17177 (string-to-number (match-string 2 s))
17178 nil nil nil))
17179 ((string-match "^<[^>]+>$" s)
17180 (decode-time (seconds-to-time (org-matcher-time s))))
17181 (t (error "Not a standard Org-mode time string: %s" s))))
17183 (defun org-timestamp-up (&optional arg)
17184 "Increase the date item at the cursor by one.
17185 If the cursor is on the year, change the year. If it is on the month,
17186 the day or the time, change that.
17187 With prefix ARG, change by that many units."
17188 (interactive "p")
17189 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17191 (defun org-timestamp-down (&optional arg)
17192 "Decrease the date item at the cursor by one.
17193 If the cursor is on the year, change the year. If it is on the month,
17194 the day or the time, change that.
17195 With prefix ARG, change by that many units."
17196 (interactive "p")
17197 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17199 (defun org-timestamp-up-day (&optional arg)
17200 "Increase the date in the time stamp by one day.
17201 With prefix ARG, change that many days."
17202 (interactive "p")
17203 (if (and (not (org-at-timestamp-p t))
17204 (org-at-heading-p))
17205 (org-todo 'up)
17206 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17208 (defun org-timestamp-down-day (&optional arg)
17209 "Decrease the date in the time stamp by one day.
17210 With prefix ARG, change that many days."
17211 (interactive "p")
17212 (if (and (not (org-at-timestamp-p t))
17213 (org-at-heading-p))
17214 (org-todo 'down)
17215 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17217 (defun org-at-timestamp-p (&optional inactive-ok)
17218 "Determine if the cursor is in or at a timestamp."
17219 (interactive)
17220 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17221 (pos (point))
17222 (ans (or (looking-at tsr)
17223 (save-excursion
17224 (skip-chars-backward "^[<\n\r\t")
17225 (if (> (point) (point-min)) (backward-char 1))
17226 (and (looking-at tsr)
17227 (> (- (match-end 0) pos) -1))))))
17228 (and ans
17229 (boundp 'org-ts-what)
17230 (setq org-ts-what
17231 (cond
17232 ((= pos (match-beginning 0)) 'bracket)
17233 ;; Point is considered to be "on the bracket" whether
17234 ;; it's really on it or right after it.
17235 ((= pos (1- (match-end 0))) 'bracket)
17236 ((= pos (match-end 0)) 'after)
17237 ((org-pos-in-match-range pos 2) 'year)
17238 ((org-pos-in-match-range pos 3) 'month)
17239 ((org-pos-in-match-range pos 7) 'hour)
17240 ((org-pos-in-match-range pos 8) 'minute)
17241 ((or (org-pos-in-match-range pos 4)
17242 (org-pos-in-match-range pos 5)) 'day)
17243 ((and (> pos (or (match-end 8) (match-end 5)))
17244 (< pos (match-end 0)))
17245 (- pos (or (match-end 8) (match-end 5))))
17246 (t 'day))))
17247 ans))
17249 (defun org-toggle-timestamp-type ()
17250 "Toggle the type (<active> or [inactive]) of a time stamp."
17251 (interactive)
17252 (when (org-at-timestamp-p t)
17253 (let ((beg (match-beginning 0)) (end (match-end 0))
17254 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17255 (save-excursion
17256 (goto-char beg)
17257 (while (re-search-forward "[][<>]" end t)
17258 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17259 t t)))
17260 (message "Timestamp is now %sactive"
17261 (if (equal (char-after beg) ?<) "" "in")))))
17263 (defun org-at-clock-log-p nil
17264 "Is the cursor on the clock log line?"
17265 (save-excursion
17266 (move-beginning-of-line 1)
17267 (looking-at "^[ \t]*CLOCK:")))
17269 (defvar org-clock-history) ; defined in org-clock.el
17270 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17271 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17272 "Change the date in the time stamp at point.
17273 The date will be changed by N times WHAT. WHAT can be `day', `month',
17274 `year', `minute', `second'. If WHAT is not given, the cursor position
17275 in the timestamp determines what will be changed.
17276 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17277 (let ((origin (point)) origin-cat
17278 with-hm inactive
17279 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17280 org-ts-what
17281 extra rem
17282 ts time time0 fixnext clrgx)
17283 (if (not (org-at-timestamp-p t))
17284 (user-error "Not at a timestamp"))
17285 (if (and (not what) (eq org-ts-what 'bracket))
17286 (org-toggle-timestamp-type)
17287 ;; Point isn't on brackets. Remember the part of the time-stamp
17288 ;; the point was in. Indeed, size of time-stamps may change,
17289 ;; but point must be kept in the same category nonetheless.
17290 (setq origin-cat org-ts-what)
17291 (if (and (not what) (not (eq org-ts-what 'day))
17292 org-display-custom-times
17293 (get-text-property (point) 'display)
17294 (not (get-text-property (1- (point)) 'display)))
17295 (setq org-ts-what 'day))
17296 (setq org-ts-what (or what org-ts-what)
17297 inactive (= (char-after (match-beginning 0)) ?\[)
17298 ts (match-string 0))
17299 (replace-match "")
17300 (when (string-match
17301 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17303 (setq extra (match-string 1 ts))
17304 (if suppress-tmp-delay
17305 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17306 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17307 (setq with-hm t))
17308 (setq time0 (org-parse-time-string ts))
17309 (when (and updown
17310 (eq org-ts-what 'minute)
17311 (not current-prefix-arg))
17312 ;; This looks like s-up and s-down. Change by one rounding step.
17313 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17314 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17315 (setcar (cdr time0) (+ (nth 1 time0)
17316 (if (> n 0) (- rem) (- dm rem))))))
17317 (setq time
17318 (encode-time (or (car time0) 0)
17319 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17320 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17321 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17322 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17323 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17324 (nthcdr 6 time0)))
17325 (when (and (member org-ts-what '(hour minute))
17326 extra
17327 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17328 (setq extra (org-modify-ts-extra
17329 extra
17330 (if (eq org-ts-what 'hour) 2 5)
17331 n dm)))
17332 (when (integerp org-ts-what)
17333 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17334 (if (eq what 'calendar)
17335 (let ((cal-date (org-get-date-from-calendar)))
17336 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17337 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17338 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17339 (setcar time0 (or (car time0) 0))
17340 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17341 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17342 (setq time (apply 'encode-time time0))))
17343 ;; Insert the new time-stamp, and ensure point stays in the same
17344 ;; category as before (i.e. not after the last position in that
17345 ;; category).
17346 (let ((pos (point)))
17347 ;; Stay before inserted string. `save-excursion' is of no use.
17348 (setq org-last-changed-timestamp
17349 (org-insert-time-stamp time with-hm inactive nil nil extra))
17350 (goto-char pos))
17351 (save-match-data
17352 (looking-at org-ts-regexp3)
17353 (goto-char (cond
17354 ;; `day' category ends before `hour' if any, or at
17355 ;; the end of the day name.
17356 ((eq origin-cat 'day)
17357 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17358 ((eq origin-cat 'hour) (min (match-end 7) origin))
17359 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17360 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17361 ;; `year' and `month' have both fixed size: point
17362 ;; couldn't have moved into another part.
17363 (t origin))))
17364 ;; Update clock if on a CLOCK line.
17365 (org-clock-update-time-maybe)
17366 ;; Maybe adjust the closest clock in `org-clock-history'
17367 (when org-clock-adjust-closest
17368 (if (not (and (org-at-clock-log-p)
17369 (< 1 (length (delq nil (mapcar 'marker-position
17370 org-clock-history))))))
17371 (message "No clock to adjust")
17372 (cond ((save-excursion ; fix previous clock?
17373 (re-search-backward org-ts-regexp0 nil t)
17374 (org-looking-back (concat org-clock-string " \\[")))
17375 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17376 ((save-excursion ; fix next clock?
17377 (re-search-backward org-ts-regexp0 nil t)
17378 (looking-at (concat org-ts-regexp0 "\\] =>")))
17379 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17380 (save-window-excursion
17381 ;; Find closest clock to point, adjust the previous/next one in history
17382 (let* ((p (save-excursion (org-back-to-heading t)))
17383 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17384 (clfixnth
17385 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17386 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17387 (if (not clfixpos)
17388 (message "No clock to adjust")
17389 (save-excursion
17390 (org-goto-marker-or-bmk clfixpos)
17391 (org-show-subtree)
17392 (when (re-search-forward clrgx nil t)
17393 (goto-char (match-beginning 1))
17394 (let (org-clock-adjust-closest)
17395 (org-timestamp-change n org-ts-what updown))
17396 (message "Clock adjusted in %s for heading: %s"
17397 (file-name-nondirectory (buffer-file-name))
17398 (org-get-heading t t)))))))))
17399 ;; Try to recenter the calendar window, if any.
17400 (if (and org-calendar-follow-timestamp-change
17401 (get-buffer-window "*Calendar*" t)
17402 (memq org-ts-what '(day month year)))
17403 (org-recenter-calendar (time-to-days time))))))
17405 (defun org-modify-ts-extra (s pos n dm)
17406 "Change the different parts of the lead-time and repeat fields in timestamp."
17407 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17408 ng h m new rem)
17409 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17410 (cond
17411 ((or (org-pos-in-match-range pos 2)
17412 (org-pos-in-match-range pos 3))
17413 (setq m (string-to-number (match-string 3 s))
17414 h (string-to-number (match-string 2 s)))
17415 (if (org-pos-in-match-range pos 2)
17416 (setq h (+ h n))
17417 (setq n (* dm (org-no-warnings (signum n))))
17418 (when (not (= 0 (setq rem (% m dm))))
17419 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17420 (setq m (+ m n)))
17421 (if (< m 0) (setq m (+ m 60) h (1- h)))
17422 (if (> m 59) (setq m (- m 60) h (1+ h)))
17423 (setq h (min 24 (max 0 h)))
17424 (setq ng 1 new (format "-%02d:%02d" h m)))
17425 ((org-pos-in-match-range pos 6)
17426 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17427 ((org-pos-in-match-range pos 5)
17428 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17430 ((org-pos-in-match-range pos 9)
17431 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17432 ((org-pos-in-match-range pos 8)
17433 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17435 (when ng
17436 (setq s (concat
17437 (substring s 0 (match-beginning ng))
17439 (substring s (match-end ng))))))
17442 (defun org-recenter-calendar (date)
17443 "If the calendar is visible, recenter it to DATE."
17444 (let ((cwin (get-buffer-window "*Calendar*" t)))
17445 (when cwin
17446 (let ((calendar-move-hook nil))
17447 (with-selected-window cwin
17448 (calendar-goto-date (if (listp date) date
17449 (calendar-gregorian-from-absolute date))))))))
17451 (defun org-goto-calendar (&optional arg)
17452 "Go to the Emacs calendar at the current date.
17453 If there is a time stamp in the current line, go to that date.
17454 A prefix ARG can be used to force the current date."
17455 (interactive "P")
17456 (let ((tsr org-ts-regexp) diff
17457 (calendar-move-hook nil)
17458 (calendar-view-holidays-initially-flag nil)
17459 (calendar-view-diary-initially-flag nil))
17460 (if (or (org-at-timestamp-p)
17461 (save-excursion
17462 (beginning-of-line 1)
17463 (looking-at (concat ".*" tsr))))
17464 (let ((d1 (time-to-days (current-time)))
17465 (d2 (time-to-days
17466 (org-time-string-to-time (match-string 1)))))
17467 (setq diff (- d2 d1))))
17468 (calendar)
17469 (calendar-goto-today)
17470 (if (and diff (not arg)) (calendar-forward-day diff))))
17472 (defun org-get-date-from-calendar ()
17473 "Return a list (month day year) of date at point in calendar."
17474 (with-current-buffer "*Calendar*"
17475 (save-match-data
17476 (calendar-cursor-to-date))))
17478 (defun org-date-from-calendar ()
17479 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17480 If there is already a time stamp at the cursor position, update it."
17481 (interactive)
17482 (if (org-at-timestamp-p t)
17483 (org-timestamp-change 0 'calendar)
17484 (let ((cal-date (org-get-date-from-calendar)))
17485 (org-insert-time-stamp
17486 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17488 (defcustom org-effort-durations
17489 `(("h" . 60)
17490 ("d" . ,(* 60 8))
17491 ("w" . ,(* 60 8 5))
17492 ("m" . ,(* 60 8 5 4))
17493 ("y" . ,(* 60 8 5 40)))
17494 "Conversion factor to minutes for an effort modifier.
17496 Each entry has the form (MODIFIER . MINUTES).
17498 In an effort string, a number followed by MODIFIER is multiplied
17499 by the specified number of MINUTES to obtain an effort in
17500 minutes.
17502 For example, if the value of this variable is ((\"hours\" . 60)), then an
17503 effort string \"2hours\" is equivalent to 120 minutes."
17504 :group 'org-agenda
17505 :version "24.1"
17506 :type '(alist :key-type (string :tag "Modifier")
17507 :value-type (number :tag "Minutes")))
17509 (defun org-minutes-to-clocksum-string (m)
17510 "Format number of minutes as a clocksum string.
17511 The format is determined by `org-time-clocksum-format',
17512 `org-time-clocksum-use-fractional' and
17513 `org-time-clocksum-fractional-format' and
17514 `org-time-clocksum-use-effort-durations'."
17515 (let ((clocksum "")
17516 (m (round m)) ; Don't allow fractions of minutes
17517 h d w mo y fmt n)
17518 (setq h (if org-time-clocksum-use-effort-durations
17519 (cdr (assoc "h" org-effort-durations)) 60)
17520 d (if org-time-clocksum-use-effort-durations
17521 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17522 w (if org-time-clocksum-use-effort-durations
17523 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17524 mo (if org-time-clocksum-use-effort-durations
17525 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17526 y (if org-time-clocksum-use-effort-durations
17527 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17528 ;; fractional format
17529 (if org-time-clocksum-use-fractional
17530 (cond
17531 ;; single format string
17532 ((stringp org-time-clocksum-fractional-format)
17533 (format org-time-clocksum-fractional-format (/ m (float h))))
17534 ;; choice of fractional formats for different time units
17535 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17536 (> (/ (truncate m) (* y d h)) 0))
17537 (format fmt (/ m (* y d (float h)))))
17538 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17539 (> (/ (truncate m) (* mo d h)) 0))
17540 (format fmt (/ m (* mo d (float h)))))
17541 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17542 (> (/ (truncate m) (* w d h)) 0))
17543 (format fmt (/ m (* w d (float h)))))
17544 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17545 (> (/ (truncate m) (* d h)) 0))
17546 (format fmt (/ m (* d (float h)))))
17547 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17548 (> (/ (truncate m) h) 0))
17549 (format fmt (/ m (float h))))
17550 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17551 (format fmt m))
17552 ;; fall back to smallest time unit with a format
17553 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17554 (format fmt (/ m (float h))))
17555 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17556 (format fmt (/ m (* d (float h)))))
17557 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17558 (format fmt (/ m (* w d (float h)))))
17559 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17560 (format fmt (/ m (* mo d (float h)))))
17561 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17562 (format fmt (/ m (* y d (float h))))))
17563 ;; standard (non-fractional) format, with single format string
17564 (if (stringp org-time-clocksum-format)
17565 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17566 ;; separate formats components
17567 (and (setq fmt (plist-get org-time-clocksum-format :years))
17568 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17569 (plist-get org-time-clocksum-format :require-years))
17570 (setq clocksum (concat clocksum (format fmt n))
17571 m (- m (* n y d h))))
17572 (and (setq fmt (plist-get org-time-clocksum-format :months))
17573 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17574 (plist-get org-time-clocksum-format :require-months))
17575 (setq clocksum (concat clocksum (format fmt n))
17576 m (- m (* n mo d h))))
17577 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17578 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17579 (plist-get org-time-clocksum-format :require-weeks))
17580 (setq clocksum (concat clocksum (format fmt n))
17581 m (- m (* n w d h))))
17582 (and (setq fmt (plist-get org-time-clocksum-format :days))
17583 (or (> (setq n (/ (truncate m) (* d h))) 0)
17584 (plist-get org-time-clocksum-format :require-days))
17585 (setq clocksum (concat clocksum (format fmt n))
17586 m (- m (* n d h))))
17587 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17588 (or (> (setq n (/ (truncate m) h)) 0)
17589 (plist-get org-time-clocksum-format :require-hours))
17590 (setq clocksum (concat clocksum (format fmt n))
17591 m (- m (* n h))))
17592 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17593 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17594 (setq clocksum (concat clocksum (format fmt m))))
17595 ;; return formatted time duration
17596 clocksum))))
17598 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17599 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17600 "Org mode version 8.0")
17602 (defun org-hours-to-clocksum-string (n)
17603 (org-minutes-to-clocksum-string (* n 60)))
17605 (defun org-hh:mm-string-to-minutes (s)
17606 "Convert a string H:MM to a number of minutes.
17607 If the string is just a number, interpret it as minutes.
17608 In fact, the first hh:mm or number in the string will be taken,
17609 there can be extra stuff in the string.
17610 If no number is found, the return value is 0."
17611 (cond
17612 ((integerp s) s)
17613 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17614 (+ (* (string-to-number (match-string 1 s)) 60)
17615 (string-to-number (match-string 2 s))))
17616 ((string-match "\\([0-9]+\\)" s)
17617 (string-to-number (match-string 1 s)))
17618 (t 0)))
17620 (defcustom org-image-actual-width t
17621 "Should we use the actual width of images when inlining them?
17623 When set to `t', always use the image width.
17625 When set to a number, use imagemagick (when available) to set
17626 the image's width to this value.
17628 When set to a number in a list, try to get the width from any
17629 #+ATTR.* keyword if it matches a width specification like
17631 #+ATTR_HTML: :width 300px
17633 and fall back on that number if none is found.
17635 When set to nil, try to get the width from an #+ATTR.* keyword
17636 and fall back on the original width if none is found.
17638 This requires Emacs >= 24.1, build with imagemagick support."
17639 :group 'org-appearance
17640 :version "24.4"
17641 :package-version '(Org . "8.0")
17642 :type '(choice
17643 (const :tag "Use the image width" t)
17644 (integer :tag "Use a number of pixels")
17645 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17646 (const :tag "Use #+ATTR* or don't resize" nil)))
17648 (defcustom org-agenda-inhibit-startup nil
17649 "Inhibit startup when preparing agenda buffers.
17650 When this variable is `t' (the default), the initialization of
17651 the Org agenda buffers is inhibited: e.g. the visibility state
17652 is not set, the tables are not re-aligned, etc."
17653 :type 'boolean
17654 :version "24.3"
17655 :group 'org-agenda)
17657 (defun org-duration-string-to-minutes (s &optional output-to-string)
17658 "Convert a duration string S to minutes.
17660 A bare number is interpreted as minutes, modifiers can be set by
17661 customizing `org-effort-durations' (which see).
17663 Entries containing a colon are interpreted as H:MM by
17664 `org-hh:mm-string-to-minutes'."
17665 (let ((result 0)
17666 (re (concat "\\([0-9.]+\\) *\\("
17667 (regexp-opt (mapcar 'car org-effort-durations))
17668 "\\)")))
17669 (while (string-match re s)
17670 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17671 (string-to-number (match-string 1 s))))
17672 (setq s (replace-match "" nil t s)))
17673 (setq result (floor result))
17674 (incf result (org-hh:mm-string-to-minutes s))
17675 (if output-to-string (number-to-string result) result)))
17677 ;;;; Files
17679 (defun org-save-all-org-buffers ()
17680 "Save all Org-mode buffers without user confirmation."
17681 (interactive)
17682 (message "Saving all Org-mode buffers...")
17683 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17684 (when (featurep 'org-id) (org-id-locations-save))
17685 (message "Saving all Org-mode buffers... done"))
17687 (defun org-revert-all-org-buffers ()
17688 "Revert all Org-mode buffers.
17689 Prompt for confirmation when there are unsaved changes.
17690 Be sure you know what you are doing before letting this function
17691 overwrite your changes.
17693 This function is useful in a setup where one tracks org files
17694 with a version control system, to revert on one machine after pulling
17695 changes from another. I believe the procedure must be like this:
17697 1. M-x org-save-all-org-buffers
17698 2. Pull changes from the other machine, resolve conflicts
17699 3. M-x org-revert-all-org-buffers"
17700 (interactive)
17701 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17702 (user-error "Abort"))
17703 (save-excursion
17704 (save-window-excursion
17705 (mapc
17706 (lambda (b)
17707 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17708 (with-current-buffer b buffer-file-name))
17709 (org-pop-to-buffer-same-window b)
17710 (revert-buffer t 'no-confirm)))
17711 (buffer-list))
17712 (when (and (featurep 'org-id) org-id-track-globally)
17713 (org-id-locations-load)))))
17715 ;;;; Agenda files
17717 ;;;###autoload
17718 (defun org-switchb (&optional arg)
17719 "Switch between Org buffers.
17720 With one prefix argument, restrict available buffers to files.
17721 With two prefix arguments, restrict available buffers to agenda files.
17723 Defaults to `iswitchb' for buffer name completion.
17724 Set `org-completion-use-ido' to make it use ido instead."
17725 (interactive "P")
17726 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17727 ((equal arg '(16)) (org-buffer-list 'agenda))
17728 (t (org-buffer-list))))
17729 (org-completion-use-iswitchb org-completion-use-iswitchb)
17730 (org-completion-use-ido org-completion-use-ido))
17731 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17732 (setq org-completion-use-iswitchb t))
17733 (org-pop-to-buffer-same-window
17734 (org-icompleting-read "Org buffer: "
17735 (mapcar 'list (mapcar 'buffer-name blist))
17736 nil t))))
17738 ;;; Define some older names previously used for this functionality
17739 ;;;###autoload
17740 (defalias 'org-ido-switchb 'org-switchb)
17741 ;;;###autoload
17742 (defalias 'org-iswitchb 'org-switchb)
17744 (defun org-buffer-list (&optional predicate exclude-tmp)
17745 "Return a list of Org buffers.
17746 PREDICATE can be `export', `files' or `agenda'.
17748 export restrict the list to Export buffers.
17749 files restrict the list to buffers visiting Org files.
17750 agenda restrict the list to buffers visiting agenda files.
17752 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17753 (let* ((bfn nil)
17754 (agenda-files (and (eq predicate 'agenda)
17755 (mapcar 'file-truename (org-agenda-files t))))
17756 (filter
17757 (cond
17758 ((eq predicate 'files)
17759 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17760 ((eq predicate 'export)
17761 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17762 ((eq predicate 'agenda)
17763 (lambda (b)
17764 (with-current-buffer b
17765 (and (derived-mode-p 'org-mode)
17766 (setq bfn (buffer-file-name b))
17767 (member (file-truename bfn) agenda-files)))))
17768 (t (lambda (b) (with-current-buffer b
17769 (or (derived-mode-p 'org-mode)
17770 (string-match "\*Org .*Export"
17771 (buffer-name b)))))))))
17772 (delq nil
17773 (mapcar
17774 (lambda(b)
17775 (if (and (funcall filter b)
17776 (or (not exclude-tmp)
17777 (not (string-match "tmp" (buffer-name b)))))
17779 nil))
17780 (buffer-list)))))
17782 (defun org-agenda-files (&optional unrestricted archives)
17783 "Get the list of agenda files.
17784 Optional UNRESTRICTED means return the full list even if a restriction
17785 is currently in place.
17786 When ARCHIVES is t, include all archive files that are really being
17787 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17788 `org-agenda-archives-mode' is t."
17789 (let ((files
17790 (cond
17791 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17792 ((stringp org-agenda-files) (org-read-agenda-file-list))
17793 ((listp org-agenda-files) org-agenda-files)
17794 (t (error "Invalid value of `org-agenda-files'")))))
17795 (setq files (apply 'append
17796 (mapcar (lambda (f)
17797 (if (file-directory-p f)
17798 (directory-files
17799 f t org-agenda-file-regexp)
17800 (list f)))
17801 files)))
17802 (when org-agenda-skip-unavailable-files
17803 (setq files (delq nil
17804 (mapcar (function
17805 (lambda (file)
17806 (and (file-readable-p file) file)))
17807 files))))
17808 (when (or (eq archives t)
17809 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17810 (setq files (org-add-archive-files files)))
17811 files))
17813 (defun org-agenda-file-p (&optional file)
17814 "Return non-nil, if FILE is an agenda file.
17815 If FILE is omitted, use the file associated with the current
17816 buffer."
17817 (member (or file (buffer-file-name))
17818 (org-agenda-files t)))
17820 (defun org-edit-agenda-file-list ()
17821 "Edit the list of agenda files.
17822 Depending on setup, this either uses customize to edit the variable
17823 `org-agenda-files', or it visits the file that is holding the list. In the
17824 latter case, the buffer is set up in a way that saving it automatically kills
17825 the buffer and restores the previous window configuration."
17826 (interactive)
17827 (if (stringp org-agenda-files)
17828 (let ((cw (current-window-configuration)))
17829 (find-file org-agenda-files)
17830 (org-set-local 'org-window-configuration cw)
17831 (org-add-hook 'after-save-hook
17832 (lambda ()
17833 (set-window-configuration
17834 (prog1 org-window-configuration
17835 (kill-buffer (current-buffer))))
17836 (org-install-agenda-files-menu)
17837 (message "New agenda file list installed"))
17838 nil 'local)
17839 (message "%s" (substitute-command-keys
17840 "Edit list and finish with \\[save-buffer]")))
17841 (customize-variable 'org-agenda-files)))
17843 (defun org-store-new-agenda-file-list (list)
17844 "Set new value for the agenda file list and save it correctly."
17845 (if (stringp org-agenda-files)
17846 (let ((fe (org-read-agenda-file-list t)) b u)
17847 (while (setq b (find-buffer-visiting org-agenda-files))
17848 (kill-buffer b))
17849 (with-temp-file org-agenda-files
17850 (insert
17851 (mapconcat
17852 (lambda (f) ;; Keep un-expanded entries.
17853 (if (setq u (assoc f fe))
17854 (cdr u)
17856 list "\n")
17857 "\n")))
17858 (let ((org-mode-hook nil) (org-inhibit-startup t)
17859 (org-insert-mode-line-in-empty-file nil))
17860 (setq org-agenda-files list)
17861 (customize-save-variable 'org-agenda-files org-agenda-files))))
17863 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17864 "Read the list of agenda files from a file.
17865 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17866 filenames, used by `org-store-new-agenda-file-list' to write back
17867 un-expanded file names."
17868 (when (file-directory-p org-agenda-files)
17869 (error "`org-agenda-files' cannot be a single directory"))
17870 (when (stringp org-agenda-files)
17871 (with-temp-buffer
17872 (insert-file-contents org-agenda-files)
17873 (mapcar
17874 (lambda (f)
17875 (let ((e (expand-file-name (substitute-in-file-name f)
17876 org-directory)))
17877 (if pair-with-expansion
17878 (cons e f)
17879 e)))
17880 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17882 ;;;###autoload
17883 (defun org-cycle-agenda-files ()
17884 "Cycle through the files in `org-agenda-files'.
17885 If the current buffer visits an agenda file, find the next one in the list.
17886 If the current buffer does not, find the first agenda file."
17887 (interactive)
17888 (let* ((fs (org-agenda-files t))
17889 (files (append fs (list (car fs))))
17890 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17891 file)
17892 (unless files (user-error "No agenda files"))
17893 (catch 'exit
17894 (while (setq file (pop files))
17895 (if (equal (file-truename file) tcf)
17896 (when (car files)
17897 (find-file (car files))
17898 (throw 'exit t))))
17899 (find-file (car fs)))
17900 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17902 (defun org-agenda-file-to-front (&optional to-end)
17903 "Move/add the current file to the top of the agenda file list.
17904 If the file is not present in the list, it is added to the front. If it is
17905 present, it is moved there. With optional argument TO-END, add/move to the
17906 end of the list."
17907 (interactive "P")
17908 (let ((org-agenda-skip-unavailable-files nil)
17909 (file-alist (mapcar (lambda (x)
17910 (cons (file-truename x) x))
17911 (org-agenda-files t)))
17912 (ctf (file-truename
17913 (or buffer-file-name
17914 (user-error "Please save the current buffer to a file"))))
17915 x had)
17916 (setq x (assoc ctf file-alist) had x)
17918 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17919 (if to-end
17920 (setq file-alist (append (delq x file-alist) (list x)))
17921 (setq file-alist (cons x (delq x file-alist))))
17922 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17923 (org-install-agenda-files-menu)
17924 (message "File %s to %s of agenda file list"
17925 (if had "moved" "added") (if to-end "end" "front"))))
17927 (defun org-remove-file (&optional file)
17928 "Remove current file from the list of files in variable `org-agenda-files'.
17929 These are the files which are being checked for agenda entries.
17930 Optional argument FILE means use this file instead of the current."
17931 (interactive)
17932 (let* ((org-agenda-skip-unavailable-files nil)
17933 (file (or file buffer-file-name
17934 (user-error "Current buffer does not visit a file")))
17935 (true-file (file-truename file))
17936 (afile (abbreviate-file-name file))
17937 (files (delq nil (mapcar
17938 (lambda (x)
17939 (if (equal true-file
17940 (file-truename x))
17941 nil x))
17942 (org-agenda-files t)))))
17943 (if (not (= (length files) (length (org-agenda-files t))))
17944 (progn
17945 (org-store-new-agenda-file-list files)
17946 (org-install-agenda-files-menu)
17947 (message "Removed file: %s" afile))
17948 (message "File was not in list: %s (not removed)" afile))))
17950 (defun org-file-menu-entry (file)
17951 (vector file (list 'find-file file) t))
17953 (defun org-check-agenda-file (file)
17954 "Make sure FILE exists. If not, ask user what to do."
17955 (when (not (file-exists-p file))
17956 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17957 (abbreviate-file-name file))
17958 (let ((r (downcase (read-char-exclusive))))
17959 (cond
17960 ((equal r ?r)
17961 (org-remove-file file)
17962 (throw 'nextfile t))
17963 (t (error "Abort"))))))
17965 (defun org-get-agenda-file-buffer (file)
17966 "Get a buffer visiting FILE. If the buffer needs to be created, add
17967 it to the list of buffers which might be released later."
17968 (let ((buf (org-find-base-buffer-visiting file)))
17969 (if buf
17970 buf ; just return it
17971 ;; Make a new buffer and remember it
17972 (setq buf (find-file-noselect file))
17973 (if buf (push buf org-agenda-new-buffers))
17974 buf)))
17976 (defun org-release-buffers (blist)
17977 "Release all buffers in list, asking the user for confirmation when needed.
17978 When a buffer is unmodified, it is just killed. When modified, it is saved
17979 \(if the user agrees) and then killed."
17980 (let (buf file)
17981 (while (setq buf (pop blist))
17982 (setq file (buffer-file-name buf))
17983 (when (and (buffer-modified-p buf)
17984 file
17985 (y-or-n-p (format "Save file %s? " file)))
17986 (with-current-buffer buf (save-buffer)))
17987 (kill-buffer buf))))
17989 (defun org-agenda-prepare-buffers (files)
17990 "Create buffers for all agenda files, protect archived trees and comments."
17991 (interactive)
17992 (let ((pa '(:org-archived t))
17993 (pc '(:org-comment t))
17994 (pall '(:org-archived t :org-comment t))
17995 (inhibit-read-only t)
17996 (org-inhibit-startup org-agenda-inhibit-startup)
17997 (rea (concat ":" org-archive-tag ":"))
17998 file re)
17999 (setq org-tag-alist-for-agenda nil
18000 org-tag-groups-alist-for-agenda nil)
18001 (save-excursion
18002 (save-restriction
18003 (while (setq file (pop files))
18004 (catch 'nextfile
18005 (if (bufferp file)
18006 (set-buffer file)
18007 (org-check-agenda-file file)
18008 (set-buffer (org-get-agenda-file-buffer file)))
18009 (widen)
18010 (org-set-regexps-and-options-for-tags)
18011 (goto-char (point-min))
18012 (let ((case-fold-search t))
18013 (when (search-forward "#+setupfile" nil t)
18014 ;; Don't set all regexps and options systematically as
18015 ;; this is only run for setting agenda tags from setup
18016 ;; file
18017 (org-set-regexps-and-options)))
18018 (org-refresh-category-properties)
18019 (org-refresh-properties org-effort-property 'org-effort)
18020 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
18021 (setq org-todo-keywords-for-agenda
18022 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18023 (setq org-done-keywords-for-agenda
18024 (append org-done-keywords-for-agenda org-done-keywords))
18025 (setq org-todo-keyword-alist-for-agenda
18026 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18027 (setq org-drawers-for-agenda
18028 (append org-drawers-for-agenda org-drawers))
18029 (setq org-tag-alist-for-agenda
18030 (org-uniquify
18031 (append org-tag-alist-for-agenda
18032 org-tag-alist
18033 org-tag-persistent-alist)))
18034 (if org-group-tags
18035 (setq org-tag-groups-alist-for-agenda
18036 (org-uniquify-alist
18037 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18038 (org-with-silent-modifications
18039 (save-excursion
18040 (remove-text-properties (point-min) (point-max) pall)
18041 (when org-agenda-skip-archived-trees
18042 (goto-char (point-min))
18043 (while (re-search-forward rea nil t)
18044 (if (org-at-heading-p t)
18045 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18046 (goto-char (point-min))
18047 (setq re (format org-heading-keyword-regexp-format
18048 org-comment-string))
18049 (while (re-search-forward re nil t)
18050 (add-text-properties
18051 (match-beginning 0) (org-end-of-subtree t) pc))))))))
18052 (setq org-todo-keywords-for-agenda
18053 (org-uniquify org-todo-keywords-for-agenda))
18054 (setq org-todo-keyword-alist-for-agenda
18055 (org-uniquify org-todo-keyword-alist-for-agenda))))
18058 ;;;; CDLaTeX minor mode
18060 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18061 "Keymap for the minor `org-cdlatex-mode'.")
18063 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18064 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18065 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18066 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18067 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18069 (defvar org-cdlatex-texmathp-advice-is-done nil
18070 "Flag remembering if we have applied the advice to texmathp already.")
18072 (define-minor-mode org-cdlatex-mode
18073 "Toggle the minor `org-cdlatex-mode'.
18074 This mode supports entering LaTeX environment and math in LaTeX fragments
18075 in Org-mode.
18076 \\{org-cdlatex-mode-map}"
18077 nil " OCDL" nil
18078 (when org-cdlatex-mode
18079 (require 'cdlatex)
18080 (run-hooks 'cdlatex-mode-hook)
18081 (cdlatex-compute-tables))
18082 (unless org-cdlatex-texmathp-advice-is-done
18083 (setq org-cdlatex-texmathp-advice-is-done t)
18084 (defadvice texmathp (around org-math-always-on activate)
18085 "Always return t in org-mode buffers.
18086 This is because we want to insert math symbols without dollars even outside
18087 the LaTeX math segments. If Orgmode thinks that point is actually inside
18088 an embedded LaTeX fragment, let texmathp do its job.
18089 \\[org-cdlatex-mode-map]"
18090 (interactive)
18091 (let (p)
18092 (cond
18093 ((not (derived-mode-p 'org-mode)) ad-do-it)
18094 ((eq this-command 'cdlatex-math-symbol)
18095 (setq ad-return-value t
18096 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18098 (let ((p (org-inside-LaTeX-fragment-p)))
18099 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18100 (setq ad-return-value t
18101 texmathp-why '("Org-mode embedded math" . 0))
18102 (if p ad-do-it)))))))))
18104 (defun turn-on-org-cdlatex ()
18105 "Unconditionally turn on `org-cdlatex-mode'."
18106 (org-cdlatex-mode 1))
18108 (defun org-try-cdlatex-tab ()
18109 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18110 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18111 - inside a LaTeX fragment, or
18112 - after the first word in a line, where an abbreviation expansion could
18113 insert a LaTeX environment."
18114 (when org-cdlatex-mode
18115 (cond
18116 ;; Before any word on the line: No expansion possible.
18117 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18118 ;; Just after first word on the line: Expand it. Make sure it
18119 ;; cannot happen on headlines, though.
18120 ((save-excursion
18121 (skip-chars-backward "a-zA-Z0-9*")
18122 (skip-chars-backward " \t")
18123 (and (bolp) (not (org-at-heading-p))))
18124 (cdlatex-tab) t)
18125 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18127 (defun org-cdlatex-underscore-caret (&optional arg)
18128 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18129 Revert to the normal definition outside of these fragments."
18130 (interactive "P")
18131 (if (org-inside-LaTeX-fragment-p)
18132 (call-interactively 'cdlatex-sub-superscript)
18133 (let (org-cdlatex-mode)
18134 (call-interactively (key-binding (vector last-input-event))))))
18136 (defun org-cdlatex-math-modify (&optional arg)
18137 "Execute `cdlatex-math-modify' in LaTeX fragments.
18138 Revert to the normal definition outside of these fragments."
18139 (interactive "P")
18140 (if (org-inside-LaTeX-fragment-p)
18141 (call-interactively 'cdlatex-math-modify)
18142 (let (org-cdlatex-mode)
18143 (call-interactively (key-binding (vector last-input-event))))))
18147 ;;;; LaTeX fragments
18149 (defvar org-latex-regexps
18150 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18151 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18152 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18153 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18154 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18155 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18156 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18157 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18158 "Regular expressions for matching embedded LaTeX.")
18160 (defun org-inside-LaTeX-fragment-p ()
18161 "Test if point is inside a LaTeX fragment.
18162 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18163 sequence appearing also before point.
18164 Even though the matchers for math are configurable, this function assumes
18165 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18166 delimiters are skipped when they have been removed by customization.
18167 The return value is nil, or a cons cell with the delimiter and the
18168 position of this delimiter.
18170 This function does a reasonably good job, but can locally be fooled by
18171 for example currency specifications. For example it will assume being in
18172 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18173 fragments that are properly closed, but during editing, we have to live
18174 with the uncertainty caused by missing closing delimiters. This function
18175 looks only before point, not after."
18176 (catch 'exit
18177 (let ((pos (point))
18178 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18179 (lim (progn
18180 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18181 (point)))
18182 dd-on str (start 0) m re)
18183 (goto-char pos)
18184 (when dodollar
18185 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18186 re (nth 1 (assoc "$" org-latex-regexps)))
18187 (while (string-match re str start)
18188 (cond
18189 ((= (match-end 0) (length str))
18190 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18191 ((= (match-end 0) (- (length str) 5))
18192 (throw 'exit nil))
18193 (t (setq start (match-end 0))))))
18194 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18195 (goto-char pos)
18196 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18197 (and (match-beginning 2) (throw 'exit nil))
18198 ;; count $$
18199 (while (re-search-backward "\\$\\$" lim t)
18200 (setq dd-on (not dd-on)))
18201 (goto-char pos)
18202 (if dd-on (cons "$$" m))))))
18204 (defun org-inside-latex-macro-p ()
18205 "Is point inside a LaTeX macro or its arguments?"
18206 (save-match-data
18207 (org-in-regexp
18208 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18210 (defvar org-latex-fragment-image-overlays nil
18211 "List of overlays carrying the images of latex fragments.")
18212 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18214 (defun org-remove-latex-fragment-image-overlays ()
18215 "Remove all overlays with LaTeX fragment images in current buffer."
18216 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18217 (setq org-latex-fragment-image-overlays nil))
18219 (defun org-preview-latex-fragment (&optional subtree)
18220 "Preview the LaTeX fragment at point, or all locally or globally.
18221 If the cursor is in a LaTeX fragment, create the image and overlay
18222 it over the source code. If there is no fragment at point, display
18223 all fragments in the current text, from one headline to the next. With
18224 prefix SUBTREE, display all fragments in the current subtree. With a
18225 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18226 the cursor is before the first headline,
18227 display all fragments in the buffer.
18228 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18229 (interactive "P")
18230 (unless buffer-file-name
18231 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18232 (when (display-graphic-p)
18233 (org-remove-latex-fragment-image-overlays)
18234 (save-excursion
18235 (save-restriction
18236 (let (beg end at msg)
18237 (cond
18238 ((or (equal subtree '(16))
18239 (not (save-excursion
18240 (re-search-backward org-outline-regexp-bol nil t))))
18241 (setq beg (point-min) end (point-max)
18242 msg "Creating images for buffer...%s"))
18243 ((equal subtree '(4))
18244 (org-back-to-heading)
18245 (setq beg (point) end (org-end-of-subtree t)
18246 msg "Creating images for subtree...%s"))
18248 (if (setq at (org-inside-LaTeX-fragment-p))
18249 (goto-char (max (point-min) (- (cdr at) 2)))
18250 (org-back-to-heading))
18251 (setq beg (point) end (progn (outline-next-heading) (point))
18252 msg (if at "Creating image...%s"
18253 "Creating images for entry...%s"))))
18254 (message msg "")
18255 (narrow-to-region beg end)
18256 (goto-char beg)
18257 (org-format-latex
18258 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18259 (file-name-nondirectory
18260 buffer-file-name)))
18261 default-directory 'overlays msg at 'forbuffer
18262 org-latex-create-formula-image-program)
18263 (message msg "done. Use `C-c C-c' to remove images."))))))
18265 (defun org-format-latex (prefix &optional dir overlays msg at
18266 forbuffer processing-type)
18267 "Replace LaTeX fragments with links to an image, and produce images.
18268 Some of the options can be changed using the variable
18269 `org-format-latex-options'."
18270 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18271 (let* ((prefixnodir (file-name-nondirectory prefix))
18272 (absprefix (expand-file-name prefix dir))
18273 (todir (file-name-directory absprefix))
18274 (opt org-format-latex-options)
18275 (optnew org-format-latex-options)
18276 (matchers (plist-get opt :matchers))
18277 (re-list org-latex-regexps)
18278 (cnt 0) txt hash link beg end re e checkdir
18279 string
18280 m n block-type block linkfile movefile ov)
18281 ;; Check the different regular expressions
18282 (while (setq e (pop re-list))
18283 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18284 block (if block-type "\n\n" ""))
18285 (when (member m matchers)
18286 (goto-char (point-min))
18287 (while (re-search-forward re nil t)
18288 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18289 (or (not overlays)
18290 (not (eq (get-char-property (match-beginning n)
18291 'org-overlay-type)
18292 'org-latex-overlay))))
18293 (cond
18294 ((eq processing-type 'verbatim))
18295 ((eq processing-type 'mathjax)
18296 ;; Prepare for MathJax processing.
18297 (setq string (match-string n))
18298 (when (member m '("$" "$1"))
18299 (save-excursion
18300 (delete-region (match-beginning n) (match-end n))
18301 (goto-char (match-beginning n))
18302 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18303 ((or (eq processing-type 'dvipng)
18304 (eq processing-type 'imagemagick))
18305 ;; Process to an image.
18306 (setq txt (match-string n)
18307 beg (match-beginning n) end (match-end n)
18308 cnt (1+ cnt))
18309 (let ((face (face-at-point))
18310 (fg (plist-get opt :foreground))
18311 (bg (plist-get opt :background))
18312 ;; Ensure full list is printed.
18313 print-length print-level)
18314 (when forbuffer
18315 ;; Get the colors from the face at point.
18316 (goto-char beg)
18317 (when (eq fg 'auto)
18318 (setq fg (face-attribute face :foreground nil 'default)))
18319 (when (eq bg 'auto)
18320 (setq bg (face-attribute face :background nil 'default)))
18321 (setq optnew (copy-sequence opt))
18322 (plist-put optnew :foreground fg)
18323 (plist-put optnew :background bg))
18324 (setq hash (sha1 (prin1-to-string
18325 (list org-format-latex-header
18326 org-latex-default-packages-alist
18327 org-latex-packages-alist
18328 org-format-latex-options
18329 forbuffer txt fg bg)))
18330 linkfile (format "%s_%s.png" prefix hash)
18331 movefile (format "%s_%s.png" absprefix hash)))
18332 (setq link (concat block "[[file:" linkfile "]]" block))
18333 (if msg (message msg cnt))
18334 (goto-char beg)
18335 (unless checkdir ; Ensure the directory exists.
18336 (setq checkdir t)
18337 (or (file-directory-p todir) (make-directory todir t)))
18338 (unless (file-exists-p movefile)
18339 (org-create-formula-image
18340 txt movefile optnew forbuffer processing-type))
18341 (if overlays
18342 (progn
18343 (mapc (lambda (o)
18344 (if (eq (overlay-get o 'org-overlay-type)
18345 'org-latex-overlay)
18346 (delete-overlay o)))
18347 (overlays-in beg end))
18348 (setq ov (make-overlay beg end))
18349 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18350 (if (featurep 'xemacs)
18351 (progn
18352 (overlay-put ov 'invisible t)
18353 (overlay-put
18354 ov 'end-glyph
18355 (make-glyph (vector 'png :file movefile))))
18356 (overlay-put
18357 ov 'display
18358 (list 'image :type 'png :file movefile :ascent 'center)))
18359 (push ov org-latex-fragment-image-overlays)
18360 (goto-char end))
18361 (delete-region beg end)
18362 (insert (org-add-props link
18363 (list 'org-latex-src
18364 (replace-regexp-in-string
18365 "\"" "" txt)
18366 'org-latex-src-embed-type
18367 (if block-type 'paragraph 'character))))))
18368 ((eq processing-type 'mathml)
18369 ;; Process to MathML
18370 (unless (save-match-data (org-format-latex-mathml-available-p))
18371 (user-error "LaTeX to MathML converter not configured"))
18372 (setq txt (match-string n)
18373 beg (match-beginning n) end (match-end n)
18374 cnt (1+ cnt))
18375 (if msg (message msg cnt))
18376 (goto-char beg)
18377 (delete-region beg end)
18378 (insert (org-format-latex-as-mathml
18379 txt block-type prefix dir)))
18381 (error "Unknown conversion type %s for LaTeX fragments"
18382 processing-type)))))))))
18384 (defun org-create-math-formula (latex-frag &optional mathml-file)
18385 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18386 Use `org-latex-to-mathml-convert-command'. If the conversion is
18387 sucessful, return the portion between \"<math...> </math>\"
18388 elements otherwise return nil. When MATHML-FILE is specified,
18389 write the results in to that file. When invoked as an
18390 interactive command, prompt for LATEX-FRAG, with initial value
18391 set to the current active region and echo the results for user
18392 inspection."
18393 (interactive (list (let ((frag (when (org-region-active-p)
18394 (buffer-substring-no-properties
18395 (region-beginning) (region-end)))))
18396 (read-string "LaTeX Fragment: " frag nil frag))))
18397 (unless latex-frag (error "Invalid LaTeX fragment"))
18398 (let* ((tmp-in-file (file-relative-name
18399 (make-temp-name (expand-file-name "ltxmathml-in"))))
18400 (ignore (write-region latex-frag nil tmp-in-file))
18401 (tmp-out-file (file-relative-name
18402 (make-temp-name (expand-file-name "ltxmathml-out"))))
18403 (cmd (format-spec
18404 org-latex-to-mathml-convert-command
18405 `((?j . ,(shell-quote-argument
18406 (expand-file-name org-latex-to-mathml-jar-file)))
18407 (?I . ,(shell-quote-argument tmp-in-file))
18408 (?o . ,(shell-quote-argument tmp-out-file)))))
18409 mathml shell-command-output)
18410 (when (org-called-interactively-p 'any)
18411 (unless (org-format-latex-mathml-available-p)
18412 (user-error "LaTeX to MathML converter not configured")))
18413 (message "Running %s" cmd)
18414 (setq shell-command-output (shell-command-to-string cmd))
18415 (setq mathml
18416 (when (file-readable-p tmp-out-file)
18417 (with-current-buffer (find-file-noselect tmp-out-file t)
18418 (goto-char (point-min))
18419 (when (re-search-forward
18420 (concat
18421 (regexp-quote
18422 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18423 "\\(.\\|\n\\)*"
18424 (regexp-quote "</math>")) nil t)
18425 (prog1 (match-string 0) (kill-buffer))))))
18426 (cond
18427 (mathml
18428 (setq mathml
18429 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18430 (when mathml-file
18431 (write-region mathml nil mathml-file))
18432 (when (org-called-interactively-p 'any)
18433 (message mathml)))
18434 ((message "LaTeX to MathML conversion failed")
18435 (message shell-command-output)))
18436 (delete-file tmp-in-file)
18437 (when (file-exists-p tmp-out-file)
18438 (delete-file tmp-out-file))
18439 mathml))
18441 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18442 prefix &optional dir)
18443 "Use `org-create-math-formula' but check local cache first."
18444 (let* ((absprefix (expand-file-name prefix dir))
18445 (print-length nil) (print-level nil)
18446 (formula-id (concat
18447 "formula-"
18448 (sha1
18449 (prin1-to-string
18450 (list latex-frag
18451 org-latex-to-mathml-convert-command)))))
18452 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18453 (formula-cache-dir (file-name-directory formula-cache)))
18455 (unless (file-directory-p formula-cache-dir)
18456 (make-directory formula-cache-dir t))
18458 (unless (file-exists-p formula-cache)
18459 (org-create-math-formula latex-frag formula-cache))
18461 (if (file-exists-p formula-cache)
18462 ;; Successful conversion. Return the link to MathML file.
18463 (org-add-props
18464 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18465 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18466 'org-latex-src-embed-type (if latex-frag-type
18467 'paragraph 'character)))
18468 ;; Failed conversion. Return the LaTeX fragment verbatim
18469 latex-frag)))
18471 (defun org-create-formula-image (string tofile options buffer &optional type)
18472 "Create an image from LaTeX source using dvipng or convert.
18473 This function calls either `org-create-formula-image-with-dvipng'
18474 or `org-create-formula-image-with-imagemagick' depending on the
18475 value of `org-latex-create-formula-image-program' or on the value
18476 of the optional TYPE variable.
18478 Note: ultimately these two function should be combined as they
18479 share a good deal of logic."
18480 (org-check-external-command
18481 "latex" "needed to convert LaTeX fragments to images")
18482 (funcall
18483 (case (or type org-latex-create-formula-image-program)
18484 ('dvipng
18485 (org-check-external-command
18486 "dvipng" "needed to convert LaTeX fragments to images")
18487 #'org-create-formula-image-with-dvipng)
18488 ('imagemagick
18489 (org-check-external-command
18490 "convert" "you need to install imagemagick")
18491 #'org-create-formula-image-with-imagemagick)
18492 (t (error
18493 "Invalid value of `org-latex-create-formula-image-program'")))
18494 string tofile options buffer))
18496 (declare-function org-export-get-backend "ox" (name))
18497 (declare-function org-export--get-global-options "ox" (&optional backend))
18498 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18499 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18500 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18501 (defun org-create-formula--latex-header ()
18502 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18503 (let ((info (org-combine-plists (org-export--get-global-options
18504 (org-export-get-backend 'latex))
18505 (org-export--get-inbuffer-options
18506 (org-export-get-backend 'latex)))))
18507 (org-latex-guess-babel-language
18508 (org-latex-guess-inputenc
18509 (org-splice-latex-header
18510 org-format-latex-header
18511 org-latex-default-packages-alist
18512 org-latex-packages-alist t
18513 (plist-get info :latex-header)))
18514 info)))
18516 ;; This function borrows from Ganesh Swami's latex2png.el
18517 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18518 "This calls dvipng."
18519 (require 'ox-latex)
18520 (let* ((tmpdir (if (featurep 'xemacs)
18521 (temp-directory)
18522 temporary-file-directory))
18523 (texfilebase (make-temp-name
18524 (expand-file-name "orgtex" tmpdir)))
18525 (texfile (concat texfilebase ".tex"))
18526 (dvifile (concat texfilebase ".dvi"))
18527 (pngfile (concat texfilebase ".png"))
18528 (fnh (if (featurep 'xemacs)
18529 (font-height (face-font 'default))
18530 (face-attribute 'default :height nil)))
18531 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18532 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18533 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18534 "Black"))
18535 (bg (or (plist-get options (if buffer :background :html-background))
18536 "Transparent")))
18537 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18538 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18539 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18540 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18541 (let ((latex-header (org-create-formula--latex-header)))
18542 (with-temp-file texfile
18543 (insert latex-header)
18544 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18545 (let ((dir default-directory))
18546 (condition-case nil
18547 (progn
18548 (cd tmpdir)
18549 (call-process "latex" nil nil nil texfile))
18550 (error nil))
18551 (cd dir))
18552 (if (not (file-exists-p dvifile))
18553 (progn (message "Failed to create dvi file from %s" texfile) nil)
18554 (condition-case nil
18555 (if (featurep 'xemacs)
18556 (call-process "dvipng" nil nil nil
18557 "-fg" fg "-bg" bg
18558 "-T" "tight"
18559 "-o" pngfile
18560 dvifile)
18561 (call-process "dvipng" nil nil nil
18562 "-fg" fg "-bg" bg
18563 "-D" dpi
18564 ;;"-x" scale "-y" scale
18565 "-T" "tight"
18566 "-o" pngfile
18567 dvifile))
18568 (error nil))
18569 (if (not (file-exists-p pngfile))
18570 (if org-format-latex-signal-error
18571 (error "Failed to create png file from %s" texfile)
18572 (message "Failed to create png file from %s" texfile)
18573 nil)
18574 ;; Use the requested file name and clean up
18575 (copy-file pngfile tofile 'replace)
18576 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18577 (if (file-exists-p (concat texfilebase e))
18578 (delete-file (concat texfilebase e))))
18579 pngfile))))
18581 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18582 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18583 "This calls convert, which is included into imagemagick."
18584 (require 'ox-latex)
18585 (let* ((tmpdir (if (featurep 'xemacs)
18586 (temp-directory)
18587 temporary-file-directory))
18588 (texfilebase (make-temp-name
18589 (expand-file-name "orgtex" tmpdir)))
18590 (texfile (concat texfilebase ".tex"))
18591 (pdffile (concat texfilebase ".pdf"))
18592 (pngfile (concat texfilebase ".png"))
18593 (fnh (if (featurep 'xemacs)
18594 (font-height (face-font 'default))
18595 (face-attribute 'default :height nil)))
18596 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18597 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18598 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18599 "black"))
18600 (bg (or (plist-get options (if buffer :background :html-background))
18601 "white")))
18602 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18603 (setq fg (org-latex-color-format fg)))
18604 (if (eq bg 'default) (setq bg (org-latex-color :background))
18605 (setq bg (org-latex-color-format
18606 (if (string= bg "Transparent") "white" bg))))
18607 (let ((latex-header (org-create-formula--latex-header)))
18608 (with-temp-file texfile
18609 (insert latex-header)
18610 (insert "\n\\begin{document}\n"
18611 "\\definecolor{fg}{rgb}{" fg "}\n"
18612 "\\definecolor{bg}{rgb}{" bg "}\n"
18613 "\n\\pagecolor{bg}\n"
18614 "\n{\\color{fg}\n"
18615 string
18616 "\n}\n"
18617 "\n\\end{document}\n")))
18618 (org-latex-compile texfile t)
18619 (if (not (file-exists-p pdffile))
18620 (progn (message "Failed to create pdf file from %s" texfile) nil)
18621 (condition-case nil
18622 (if (featurep 'xemacs)
18623 (call-process "convert" nil nil nil
18624 "-density" "96"
18625 "-trim"
18626 "-antialias"
18627 pdffile
18628 "-quality" "100"
18629 ;; "-sharpen" "0x1.0"
18630 pngfile)
18631 (call-process "convert" nil nil nil
18632 "-density" dpi
18633 "-trim"
18634 "-antialias"
18635 pdffile
18636 "-quality" "100"
18637 ;; "-sharpen" "0x1.0"
18638 pngfile))
18639 (error nil))
18640 (if (not (file-exists-p pngfile))
18641 (if org-format-latex-signal-error
18642 (error "Failed to create png file from %s" texfile)
18643 (message "Failed to create png file from %s" texfile)
18644 nil)
18645 ;; Use the requested file name and clean up
18646 (copy-file pngfile tofile 'replace)
18647 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18648 (if (file-exists-p (concat texfilebase e))
18649 (delete-file (concat texfilebase e))))
18650 pngfile))))
18652 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18653 "Fill a LaTeX header template TPL.
18654 In the template, the following place holders will be recognized:
18656 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18657 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18658 [PACKAGES] \\usepackage statements for PKG
18659 [NO-PACKAGES] do not include PKG
18660 [EXTRA] the string EXTRA
18661 [NO-EXTRA] do not include EXTRA
18663 For backward compatibility, if both the positive and the negative place
18664 holder is missing, the positive one (without the \"NO-\") will be
18665 assumed to be present at the end of the template.
18666 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18667 EXTRA is a string.
18668 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18669 (let (rpl (end ""))
18670 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18671 (setq rpl (if (or (match-end 1) (not def-pkg))
18672 "" (org-latex-packages-to-string def-pkg snippets-p t))
18673 tpl (replace-match rpl t t tpl))
18674 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18676 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18677 (setq rpl (if (or (match-end 1) (not pkg))
18678 "" (org-latex-packages-to-string pkg snippets-p t))
18679 tpl (replace-match rpl t t tpl))
18680 (if pkg (setq end
18681 (concat end "\n"
18682 (org-latex-packages-to-string pkg snippets-p)))))
18684 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18685 (setq rpl (if (or (match-end 1) (not extra))
18686 "" (concat extra "\n"))
18687 tpl (replace-match rpl t t tpl))
18688 (if (and extra (string-match "\\S-" extra))
18689 (setq end (concat end "\n" extra))))
18691 (if (string-match "\\S-" end)
18692 (concat tpl "\n" end)
18693 tpl)))
18695 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18696 "Turn an alist of packages into a string with the \\usepackage macros."
18697 (setq pkg (mapconcat (lambda(p)
18698 (cond
18699 ((stringp p) p)
18700 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18701 (format "%% Package %s omitted" (cadr p)))
18702 ((equal "" (car p))
18703 (format "\\usepackage{%s}" (cadr p)))
18705 (format "\\usepackage[%s]{%s}"
18706 (car p) (cadr p)))))
18708 "\n"))
18709 (if newline (concat pkg "\n") pkg))
18711 (defun org-dvipng-color (attr)
18712 "Return a RGB color specification for dvipng."
18713 (apply 'format "rgb %s %s %s"
18714 (mapcar 'org-normalize-color
18715 (if (featurep 'xemacs)
18716 (color-rgb-components
18717 (face-property 'default
18718 (cond ((eq attr :foreground) 'foreground)
18719 ((eq attr :background) 'background))))
18720 (color-values (face-attribute 'default attr nil))))))
18722 (defun org-dvipng-color-format (color-name)
18723 "Convert COLOR-NAME to a RGB color value for dvipng."
18724 (apply 'format "rgb %s %s %s"
18725 (mapcar 'org-normalize-color
18726 (color-values color-name))))
18728 (defun org-latex-color (attr)
18729 "Return a RGB color for the LaTeX color package."
18730 (apply 'format "%s,%s,%s"
18731 (mapcar 'org-normalize-color
18732 (if (featurep 'xemacs)
18733 (color-rgb-components
18734 (face-property 'default
18735 (cond ((eq attr :foreground) 'foreground)
18736 ((eq attr :background) 'background))))
18737 (color-values (face-attribute 'default attr nil))))))
18739 (defun org-latex-color-format (color-name)
18740 "Convert COLOR-NAME to a RGB color value."
18741 (apply 'format "%s,%s,%s"
18742 (mapcar 'org-normalize-color
18743 (color-values color-name))))
18745 (defun org-normalize-color (value)
18746 "Return string to be used as color value for an RGB component."
18747 (format "%g" (/ value 65535.0)))
18751 ;; Image display
18753 (defvar org-inline-image-overlays nil)
18754 (make-variable-buffer-local 'org-inline-image-overlays)
18756 (defun org-toggle-inline-images (&optional include-linked)
18757 "Toggle the display of inline images.
18758 INCLUDE-LINKED is passed to `org-display-inline-images'."
18759 (interactive "P")
18760 (if org-inline-image-overlays
18761 (progn
18762 (org-remove-inline-images)
18763 (message "Inline image display turned off"))
18764 (org-display-inline-images include-linked)
18765 (if (and (org-called-interactively-p)
18766 org-inline-image-overlays)
18767 (message "%d images displayed inline"
18768 (length org-inline-image-overlays))
18769 (message "No images to display inline"))))
18771 (defun org-redisplay-inline-images ()
18772 "Refresh the display of inline images."
18773 (interactive)
18774 (if (not org-inline-image-overlays)
18775 (org-toggle-inline-images)
18776 (org-toggle-inline-images)
18777 (org-toggle-inline-images)))
18779 (defun org-display-inline-images (&optional include-linked refresh beg end)
18780 "Display inline images.
18781 Normally only links without a description part are inlined, because this
18782 is how it will work for export. When INCLUDE-LINKED is set, also links
18783 with a description part will be inlined. This can be nice for a quick
18784 look at those images, but it does not reflect what exported files will look
18785 like.
18786 When REFRESH is set, refresh existing images between BEG and END.
18787 This will create new image displays only if necessary.
18788 BEG and END default to the buffer boundaries."
18789 (interactive "P")
18790 (when (display-graphic-p)
18791 (unless refresh
18792 (org-remove-inline-images)
18793 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18794 (save-excursion
18795 (save-restriction
18796 (widen)
18797 (setq beg (or beg (point-min)) end (or end (point-max)))
18798 (goto-char beg)
18799 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18800 (substring (org-image-file-name-regexp) 0 -2)
18801 "\\)\\]" (if include-linked "" "\\]")))
18802 (case-fold-search t)
18803 old file ov img type attrwidth width)
18804 (while (re-search-forward re end t)
18805 (setq old (get-char-property-and-overlay (match-beginning 1)
18806 'org-image-overlay)
18807 file (expand-file-name
18808 (concat (or (match-string 3) "") (match-string 4))))
18809 (when (image-type-available-p 'imagemagick)
18810 (setq attrwidth (if (or (listp org-image-actual-width)
18811 (null org-image-actual-width))
18812 (save-excursion
18813 (save-match-data
18814 (when (re-search-backward
18815 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18816 (save-excursion
18817 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18818 (string-to-number (match-string 1))))))
18819 width (cond ((eq org-image-actual-width t) nil)
18820 ((null org-image-actual-width) attrwidth)
18821 ((numberp org-image-actual-width)
18822 org-image-actual-width)
18823 ((listp org-image-actual-width)
18824 (or attrwidth (car org-image-actual-width))))
18825 type (if width 'imagemagick)))
18826 (when (file-exists-p file)
18827 (if (and (car-safe old) refresh)
18828 (image-refresh (overlay-get (cdr old) 'display))
18829 (setq img (save-match-data (create-image file type nil :width width)))
18830 (when img
18831 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18832 (overlay-put ov 'display img)
18833 (overlay-put ov 'face 'default)
18834 (overlay-put ov 'org-image-overlay t)
18835 (overlay-put ov 'modification-hooks
18836 (list 'org-display-inline-remove-overlay))
18837 (push ov org-inline-image-overlays))))))))))
18839 (define-obsolete-function-alias
18840 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18842 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18843 "Remove inline-display overlay if a corresponding region is modified."
18844 (let ((inhibit-modification-hooks t))
18845 (when (and ov after)
18846 (delete ov org-inline-image-overlays)
18847 (delete-overlay ov))))
18849 (defun org-remove-inline-images ()
18850 "Remove inline display of images."
18851 (interactive)
18852 (mapc 'delete-overlay org-inline-image-overlays)
18853 (setq org-inline-image-overlays nil))
18855 ;;;; Key bindings
18857 ;; Outline functions from `outline-mode-prefix-map'
18858 ;; that can be remapped in Org:
18859 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18860 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18861 (define-key org-mode-map [remap outline-forward-same-level]
18862 'org-forward-heading-same-level)
18863 (define-key org-mode-map [remap outline-backward-same-level]
18864 'org-backward-heading-same-level)
18865 (define-key org-mode-map [remap show-branches]
18866 'org-kill-note-or-show-branches)
18867 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18868 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18869 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18871 ;; Outline functions from `outline-mode-prefix-map' that can not
18872 ;; be remapped in Org:
18874 ;; - the column "key binding" shows whether the Outline function is still
18875 ;; available in Org mode on the same key that it has been bound to in
18876 ;; Outline mode:
18877 ;; - "overridden": key used for a different functionality in Org mode
18878 ;; - else: key still bound to the same Outline function in Org mode
18880 ;; | Outline function | key binding | Org replacement |
18881 ;; |------------------------------------+-------------+-----------------------|
18882 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18883 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18884 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18885 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18886 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18887 ;; | `show-entry' | overridden | no replacement |
18888 ;; | `show-children' | `C-c C-i' | visibility cycling |
18889 ;; | `show-branches' | `C-c C-k' | still same function |
18890 ;; | `show-subtree' | overridden | visibility cycling |
18891 ;; | `show-all' | overridden | no replacement |
18892 ;; | `hide-subtree' | overridden | visibility cycling |
18893 ;; | `hide-body' | overridden | no replacement |
18894 ;; | `hide-entry' | overridden | visibility cycling |
18895 ;; | `hide-leaves' | overridden | no replacement |
18896 ;; | `hide-sublevels' | overridden | no replacement |
18897 ;; | `hide-other' | overridden | no replacement |
18899 ;; Make `C-c C-x' a prefix key
18900 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18902 ;; TAB key with modifiers
18903 (org-defkey org-mode-map "\C-i" 'org-cycle)
18904 (org-defkey org-mode-map [(tab)] 'org-cycle)
18905 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18906 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18907 ;; The following line is necessary under Suse GNU/Linux
18908 (unless (featurep 'xemacs)
18909 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18910 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18911 (define-key org-mode-map [backtab] 'org-shifttab)
18913 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18914 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18915 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18917 ;; Cursor keys with modifiers
18918 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18919 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18920 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18921 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18923 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18924 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18925 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18926 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18928 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18929 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18930 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18931 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18933 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18934 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18935 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18936 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18938 ;; Babel keys
18939 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18940 (mapc (lambda (pair)
18941 (define-key org-babel-map (car pair) (cdr pair)))
18942 org-babel-key-bindings)
18944 ;;; Extra keys for tty access.
18945 ;; We only set them when really needed because otherwise the
18946 ;; menus don't show the simple keys
18948 (when (or org-use-extra-keys
18949 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18950 (not window-system))
18951 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18952 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18953 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18954 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18955 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18956 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18957 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18958 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18959 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18960 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18961 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18962 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18963 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18964 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18965 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18966 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18967 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18968 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18969 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18970 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18971 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18972 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18973 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18974 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18975 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18976 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18977 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18978 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18980 ;; All the other keys
18982 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18983 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18984 (if (boundp 'narrow-map)
18985 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18986 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18987 (if (boundp 'narrow-map)
18988 (org-defkey narrow-map "b" 'org-narrow-to-block)
18989 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18990 (if (boundp 'narrow-map)
18991 (org-defkey narrow-map "e" 'org-narrow-to-element)
18992 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18993 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18994 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18995 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18996 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18997 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18998 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18999 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19000 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19001 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19002 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19003 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19004 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19005 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19006 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19007 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19008 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19009 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19010 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19011 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19012 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19013 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19014 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19015 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19016 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19017 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19018 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19019 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19020 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19021 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19022 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19023 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19024 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19025 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19026 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19027 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19028 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19029 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19030 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19031 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19032 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19033 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19034 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19035 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19036 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19037 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19038 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19039 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19040 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19041 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19042 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19043 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19044 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19045 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19046 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19047 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19048 (org-defkey org-mode-map "\C-c^" 'org-sort)
19049 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19050 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19051 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19052 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19053 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-element)
19054 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-element)
19055 (org-defkey org-mode-map "\C-m" 'org-return)
19056 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19057 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19058 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19059 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19060 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19061 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19062 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19063 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19064 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19065 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19066 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19067 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19068 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19069 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19070 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19071 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19072 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19073 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19074 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19075 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19076 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19077 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19078 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19080 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19081 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19082 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19084 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19085 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19086 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19087 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19088 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19089 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19090 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19091 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19092 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19093 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19094 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19095 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19096 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19097 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19098 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19099 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19100 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19101 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19102 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19103 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19104 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19105 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19106 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19108 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19109 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19110 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19111 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19112 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19114 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19116 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19118 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19119 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19121 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19124 (when (featurep 'xemacs)
19125 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19128 (defconst org-speed-commands-default
19130 ("Outline Navigation")
19131 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19132 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19133 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19134 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19135 ("F" . org-next-block)
19136 ("B" . org-previous-block)
19137 ("u" . (org-speed-move-safe 'outline-up-heading))
19138 ("j" . org-goto)
19139 ("g" . (org-refile t))
19140 ("Outline Visibility")
19141 ("c" . org-cycle)
19142 ("C" . org-shifttab)
19143 (" " . org-display-outline-path)
19144 ("s" . org-narrow-to-subtree)
19145 ("=" . org-columns)
19146 ("Outline Structure Editing")
19147 ("U" . org-shiftmetaup)
19148 ("D" . org-shiftmetadown)
19149 ("r" . org-metaright)
19150 ("l" . org-metaleft)
19151 ("R" . org-shiftmetaright)
19152 ("L" . org-shiftmetaleft)
19153 ("i" . (progn (forward-char 1) (call-interactively
19154 'org-insert-heading-respect-content)))
19155 ("^" . org-sort)
19156 ("w" . org-refile)
19157 ("a" . org-archive-subtree-default-with-confirmation)
19158 ("@" . org-mark-subtree)
19159 ("#" . org-toggle-comment)
19160 ("Clock Commands")
19161 ("I" . org-clock-in)
19162 ("O" . org-clock-out)
19163 ("Meta Data Editing")
19164 ("t" . org-todo)
19165 ("," . (org-priority))
19166 ("0" . (org-priority ?\ ))
19167 ("1" . (org-priority ?A))
19168 ("2" . (org-priority ?B))
19169 ("3" . (org-priority ?C))
19170 (":" . org-set-tags-command)
19171 ("e" . org-set-effort)
19172 ("E" . org-inc-effort)
19173 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19174 (org-entry-put (point) "APPT_WARNTIME" m)))
19175 ("Agenda Views etc")
19176 ("v" . org-agenda)
19177 ("/" . org-sparse-tree)
19178 ("Misc")
19179 ("o" . org-open-at-point)
19180 ("?" . org-speed-command-help)
19181 ("<" . (org-agenda-set-restriction-lock 'subtree))
19182 (">" . (org-agenda-remove-restriction-lock))
19184 "The default speed commands.")
19186 (defun org-print-speed-command (e)
19187 (if (> (length (car e)) 1)
19188 (progn
19189 (princ "\n")
19190 (princ (car e))
19191 (princ "\n")
19192 (princ (make-string (length (car e)) ?-))
19193 (princ "\n"))
19194 (princ (car e))
19195 (princ " ")
19196 (if (symbolp (cdr e))
19197 (princ (symbol-name (cdr e)))
19198 (prin1 (cdr e)))
19199 (princ "\n")))
19201 (defun org-speed-command-help ()
19202 "Show the available speed commands."
19203 (interactive)
19204 (if (not org-use-speed-commands)
19205 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19206 (with-output-to-temp-buffer "*Help*"
19207 (princ "User-defined Speed commands\n===========================\n")
19208 (mapc 'org-print-speed-command org-speed-commands-user)
19209 (princ "\n")
19210 (princ "Built-in Speed commands\n=======================\n")
19211 (mapc 'org-print-speed-command org-speed-commands-default))
19212 (with-current-buffer "*Help*"
19213 (setq truncate-lines t))))
19215 (defun org-speed-move-safe (cmd)
19216 "Execute CMD, but make sure that the cursor always ends up in a headline.
19217 If not, return to the original position and throw an error."
19218 (interactive)
19219 (let ((pos (point)))
19220 (call-interactively cmd)
19221 (unless (and (bolp) (org-at-heading-p))
19222 (goto-char pos)
19223 (error "Boundary reached while executing %s" cmd))))
19225 (defvar org-self-insert-command-undo-counter 0)
19227 (defvar org-table-auto-blank-field) ; defined in org-table.el
19228 (defvar org-speed-command nil)
19230 (define-obsolete-function-alias
19231 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19233 (defun org-speed-command-activate (keys)
19234 "Hook for activating single-letter speed commands.
19235 `org-speed-commands-default' specifies a minimal command set.
19236 Use `org-speed-commands-user' for further customization."
19237 (when (or (and (bolp) (looking-at org-outline-regexp))
19238 (and (functionp org-use-speed-commands)
19239 (funcall org-use-speed-commands)))
19240 (cdr (assoc keys (append org-speed-commands-user
19241 org-speed-commands-default)))))
19243 (define-obsolete-function-alias
19244 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19246 (defun org-babel-speed-command-activate (keys)
19247 "Hook for activating single-letter code block commands."
19248 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19249 (cdr (assoc keys org-babel-key-bindings))))
19251 (defcustom org-speed-command-hook
19252 '(org-speed-command-default-hook org-babel-speed-command-hook)
19253 "Hook for activating speed commands at strategic locations.
19254 Hook functions are called in sequence until a valid handler is
19255 found.
19257 Each hook takes a single argument, a user-pressed command key
19258 which is also a `self-insert-command' from the global map.
19260 Within the hook, examine the cursor position and the command key
19261 and return nil or a valid handler as appropriate. Handler could
19262 be one of an interactive command, a function, or a form.
19264 Set `org-use-speed-commands' to non-nil value to enable this
19265 hook. The default setting is `org-speed-command-activate'."
19266 :group 'org-structure
19267 :version "24.1"
19268 :type 'hook)
19270 (defun org-self-insert-command (N)
19271 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19272 If the cursor is in a table looking at whitespace, the whitespace is
19273 overwritten, and the table is not marked as requiring realignment."
19274 (interactive "p")
19275 (org-check-before-invisible-edit 'insert)
19276 (cond
19277 ((and org-use-speed-commands
19278 (setq org-speed-command
19279 (run-hook-with-args-until-success
19280 'org-speed-command-hook (this-command-keys))))
19281 (cond
19282 ((commandp org-speed-command)
19283 (setq this-command org-speed-command)
19284 (call-interactively org-speed-command))
19285 ((functionp org-speed-command)
19286 (funcall org-speed-command))
19287 ((and org-speed-command (listp org-speed-command))
19288 (eval org-speed-command))
19289 (t (let (org-use-speed-commands)
19290 (call-interactively 'org-self-insert-command)))))
19291 ((and
19292 (org-table-p)
19293 (progn
19294 ;; check if we blank the field, and if that triggers align
19295 (and (featurep 'org-table) org-table-auto-blank-field
19296 (member last-command
19297 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19298 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19299 ;; got extra space, this field does not determine column width
19300 (let (org-table-may-need-update) (org-table-blank-field))
19301 ;; no extra space, this field may determine column width
19302 (org-table-blank-field)))
19304 (eq N 1)
19305 (looking-at "[^|\n]* |"))
19306 (let (org-table-may-need-update)
19307 (goto-char (1- (match-end 0)))
19308 (backward-delete-char 1)
19309 (goto-char (match-beginning 0))
19310 (self-insert-command N)))
19312 (setq org-table-may-need-update t)
19313 (self-insert-command N)
19314 (org-fix-tags-on-the-fly)
19315 (if org-self-insert-cluster-for-undo
19316 (if (not (eq last-command 'org-self-insert-command))
19317 (setq org-self-insert-command-undo-counter 1)
19318 (if (>= org-self-insert-command-undo-counter 20)
19319 (setq org-self-insert-command-undo-counter 1)
19320 (and (> org-self-insert-command-undo-counter 0)
19321 buffer-undo-list (listp buffer-undo-list)
19322 (not (cadr buffer-undo-list)) ; remove nil entry
19323 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19324 (setq org-self-insert-command-undo-counter
19325 (1+ org-self-insert-command-undo-counter))))))))
19327 (defun org-check-before-invisible-edit (kind)
19328 "Check is editing if kind KIND would be dangerous with invisible text around.
19329 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19330 ;; First, try to get out of here as quickly as possible, to reduce overhead
19331 (if (and org-catch-invisible-edits
19332 (or (not (boundp 'visible-mode)) (not visible-mode))
19333 (or (get-char-property (point) 'invisible)
19334 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19335 ;; OK, we need to take a closer look
19336 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19337 (invisible-before-point (if (bobp) nil (get-char-property
19338 (1- (point)) 'invisible)))
19339 (border-and-ok-direction
19341 ;; Check if we are acting predictably before invisible text
19342 (and invisible-at-point (not invisible-before-point)
19343 (memq kind '(insert delete-backward)))
19344 ;; Check if we are acting predictably after invisible text
19345 ;; This works not well, and I have turned it off. It seems
19346 ;; better to always show and stop after invisible text.
19347 ;; (and (not invisible-at-point) invisible-before-point
19348 ;; (memq kind '(insert delete)))
19350 (when (or (memq invisible-at-point '(outline org-hide-block t))
19351 (memq invisible-before-point '(outline org-hide-block t)))
19352 (if (eq org-catch-invisible-edits 'error)
19353 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19354 (if (and org-custom-properties-overlays
19355 (y-or-n-p "Display invisible properties in this buffer? "))
19356 (org-toggle-custom-properties-visibility)
19357 ;; Make the area visible
19358 (save-excursion
19359 (if invisible-before-point
19360 (goto-char (previous-single-char-property-change
19361 (point) 'invisible)))
19362 (org-cycle))
19363 (cond
19364 ((eq org-catch-invisible-edits 'show)
19365 ;; That's it, we do the edit after showing
19366 (message
19367 "Unfolding invisible region around point before editing")
19368 (sit-for 1))
19369 ((and (eq org-catch-invisible-edits 'smart)
19370 border-and-ok-direction)
19371 (message "Unfolding invisible region around point before editing"))
19373 ;; Don't do the edit, make the user repeat it in full visibility
19374 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19376 (defun org-fix-tags-on-the-fly ()
19377 (when (and (equal (char-after (point-at-bol)) ?*)
19378 (org-at-heading-p))
19379 (org-align-tags-here org-tags-column)))
19381 (defun org-delete-backward-char (N)
19382 "Like `delete-backward-char', insert whitespace at field end in tables.
19383 When deleting backwards, in tables this function will insert whitespace in
19384 front of the next \"|\" separator, to keep the table aligned. The table will
19385 still be marked for re-alignment if the field did fill the entire column,
19386 because, in this case the deletion might narrow the column."
19387 (interactive "p")
19388 (save-match-data
19389 (org-check-before-invisible-edit 'delete-backward)
19390 (if (and (org-table-p)
19391 (eq N 1)
19392 (string-match "|" (buffer-substring (point-at-bol) (point)))
19393 (looking-at ".*?|"))
19394 (let ((pos (point))
19395 (noalign (looking-at "[^|\n\r]* |"))
19396 (c org-table-may-need-update))
19397 (backward-delete-char N)
19398 (if (not overwrite-mode)
19399 (progn
19400 (skip-chars-forward "^|")
19401 (insert " ")
19402 (goto-char (1- pos))))
19403 ;; noalign: if there were two spaces at the end, this field
19404 ;; does not determine the width of the column.
19405 (if noalign (setq org-table-may-need-update c)))
19406 (backward-delete-char N)
19407 (org-fix-tags-on-the-fly))))
19409 (defun org-delete-char (N)
19410 "Like `delete-char', but insert whitespace at field end in tables.
19411 When deleting characters, in tables this function will insert whitespace in
19412 front of the next \"|\" separator, to keep the table aligned. The table will
19413 still be marked for re-alignment if the field did fill the entire column,
19414 because, in this case the deletion might narrow the column."
19415 (interactive "p")
19416 (save-match-data
19417 (org-check-before-invisible-edit 'delete)
19418 (if (and (org-table-p)
19419 (not (bolp))
19420 (not (= (char-after) ?|))
19421 (eq N 1))
19422 (if (looking-at ".*?|")
19423 (let ((pos (point))
19424 (noalign (looking-at "[^|\n\r]* |"))
19425 (c org-table-may-need-update))
19426 (replace-match
19427 (concat (substring (match-string 0) 1 -1) " |") nil t)
19428 (goto-char pos)
19429 ;; noalign: if there were two spaces at the end, this field
19430 ;; does not determine the width of the column.
19431 (if noalign (setq org-table-may-need-update c)))
19432 (delete-char N))
19433 (delete-char N)
19434 (org-fix-tags-on-the-fly))))
19436 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19437 (put 'org-self-insert-command 'delete-selection t)
19438 (put 'orgtbl-self-insert-command 'delete-selection t)
19439 (put 'org-delete-char 'delete-selection 'supersede)
19440 (put 'org-delete-backward-char 'delete-selection 'supersede)
19441 (put 'org-yank 'delete-selection 'yank)
19443 ;; Make `flyspell-mode' delay after some commands
19444 (put 'org-self-insert-command 'flyspell-delayed t)
19445 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19446 (put 'org-delete-char 'flyspell-delayed t)
19447 (put 'org-delete-backward-char 'flyspell-delayed t)
19449 ;; Make pabbrev-mode expand after org-mode commands
19450 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19451 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19453 ;; How to do this: Measure non-white length of current string
19454 ;; If equal to column width, we should realign.
19456 (defun org-remap (map &rest commands)
19457 "In MAP, remap the functions given in COMMANDS.
19458 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19459 (let (new old)
19460 (while commands
19461 (setq old (pop commands) new (pop commands))
19462 (if (fboundp 'command-remapping)
19463 (org-defkey map (vector 'remap old) new)
19464 (substitute-key-definition old new map global-map)))))
19466 (defun org-transpose-words ()
19467 "Transpose words for Org.
19468 This uses the `org-mode-transpose-word-syntax-table' syntax
19469 table, which interprets characters in `org-emphasis-alist' as
19470 word constituants."
19471 (interactive)
19472 (with-syntax-table org-mode-transpose-word-syntax-table
19473 (call-interactively 'transpose-words)))
19474 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19476 (when (eq org-enable-table-editor 'optimized)
19477 ;; If the user wants maximum table support, we need to hijack
19478 ;; some standard editing functions
19479 (org-remap org-mode-map
19480 'self-insert-command 'org-self-insert-command
19481 'delete-char 'org-delete-char
19482 'delete-backward-char 'org-delete-backward-char)
19483 (org-defkey org-mode-map "|" 'org-force-self-insert))
19485 (defvar org-ctrl-c-ctrl-c-hook nil
19486 "Hook for functions attaching themselves to `C-c C-c'.
19488 This can be used to add additional functionality to the C-c C-c
19489 key which executes context-dependent commands. This hook is run
19490 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19491 run after the last test.
19493 Each function will be called with no arguments. The function
19494 must check if the context is appropriate for it to act. If yes,
19495 it should do its thing and then return a non-nil value. If the
19496 context is wrong, just do nothing and return nil.")
19498 (defvar org-ctrl-c-ctrl-c-final-hook nil
19499 "Hook for functions attaching themselves to `C-c C-c'.
19501 This can be used to add additional functionality to the C-c C-c
19502 key which executes context-dependent commands. This hook is run
19503 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19504 before the first test.
19506 Each function will be called with no arguments. The function
19507 must check if the context is appropriate for it to act. If yes,
19508 it should do its thing and then return a non-nil value. If the
19509 context is wrong, just do nothing and return nil.")
19511 (defvar org-tab-first-hook nil
19512 "Hook for functions to attach themselves to TAB.
19513 See `org-ctrl-c-ctrl-c-hook' for more information.
19514 This hook runs as the first action when TAB is pressed, even before
19515 `org-cycle' messes around with the `outline-regexp' to cater for
19516 inline tasks and plain list item folding.
19517 If any function in this hook returns t, any other actions that
19518 would have been caused by TAB (such as table field motion or visibility
19519 cycling) will not occur.")
19521 (defvar org-tab-after-check-for-table-hook nil
19522 "Hook for functions to attach themselves to TAB.
19523 See `org-ctrl-c-ctrl-c-hook' for more information.
19524 This hook runs after it has been established that the cursor is not in a
19525 table, but before checking if the cursor is in a headline or if global cycling
19526 should be done.
19527 If any function in this hook returns t, not other actions like visibility
19528 cycling will be done.")
19530 (defvar org-tab-after-check-for-cycling-hook nil
19531 "Hook for functions to attach themselves to TAB.
19532 See `org-ctrl-c-ctrl-c-hook' for more information.
19533 This hook runs after it has been established that not table field motion and
19534 not visibility should be done because of current context. This is probably
19535 the place where a package like yasnippets can hook in.")
19537 (defvar org-tab-before-tab-emulation-hook nil
19538 "Hook for functions to attach themselves to TAB.
19539 See `org-ctrl-c-ctrl-c-hook' for more information.
19540 This hook runs after every other options for TAB have been exhausted, but
19541 before indentation and \t insertion takes place.")
19543 (defvar org-metaleft-hook nil
19544 "Hook for functions attaching themselves to `M-left'.
19545 See `org-ctrl-c-ctrl-c-hook' for more information.")
19546 (defvar org-metaright-hook nil
19547 "Hook for functions attaching themselves to `M-right'.
19548 See `org-ctrl-c-ctrl-c-hook' for more information.")
19549 (defvar org-metaup-hook nil
19550 "Hook for functions attaching themselves to `M-up'.
19551 See `org-ctrl-c-ctrl-c-hook' for more information.")
19552 (defvar org-metadown-hook nil
19553 "Hook for functions attaching themselves to `M-down'.
19554 See `org-ctrl-c-ctrl-c-hook' for more information.")
19555 (defvar org-shiftmetaleft-hook nil
19556 "Hook for functions attaching themselves to `M-S-left'.
19557 See `org-ctrl-c-ctrl-c-hook' for more information.")
19558 (defvar org-shiftmetaright-hook nil
19559 "Hook for functions attaching themselves to `M-S-right'.
19560 See `org-ctrl-c-ctrl-c-hook' for more information.")
19561 (defvar org-shiftmetaup-hook nil
19562 "Hook for functions attaching themselves to `M-S-up'.
19563 See `org-ctrl-c-ctrl-c-hook' for more information.")
19564 (defvar org-shiftmetadown-hook nil
19565 "Hook for functions attaching themselves to `M-S-down'.
19566 See `org-ctrl-c-ctrl-c-hook' for more information.")
19567 (defvar org-metareturn-hook nil
19568 "Hook for functions attaching themselves to `M-RET'.
19569 See `org-ctrl-c-ctrl-c-hook' for more information.")
19570 (defvar org-shiftup-hook nil
19571 "Hook for functions attaching themselves to `S-up'.
19572 See `org-ctrl-c-ctrl-c-hook' for more information.")
19573 (defvar org-shiftup-final-hook nil
19574 "Hook for functions attaching themselves to `S-up'.
19575 This one runs after all other options except shift-select have been excluded.
19576 See `org-ctrl-c-ctrl-c-hook' for more information.")
19577 (defvar org-shiftdown-hook nil
19578 "Hook for functions attaching themselves to `S-down'.
19579 See `org-ctrl-c-ctrl-c-hook' for more information.")
19580 (defvar org-shiftdown-final-hook nil
19581 "Hook for functions attaching themselves to `S-down'.
19582 This one runs after all other options except shift-select have been excluded.
19583 See `org-ctrl-c-ctrl-c-hook' for more information.")
19584 (defvar org-shiftleft-hook nil
19585 "Hook for functions attaching themselves to `S-left'.
19586 See `org-ctrl-c-ctrl-c-hook' for more information.")
19587 (defvar org-shiftleft-final-hook nil
19588 "Hook for functions attaching themselves to `S-left'.
19589 This one runs after all other options except shift-select have been excluded.
19590 See `org-ctrl-c-ctrl-c-hook' for more information.")
19591 (defvar org-shiftright-hook nil
19592 "Hook for functions attaching themselves to `S-right'.
19593 See `org-ctrl-c-ctrl-c-hook' for more information.")
19594 (defvar org-shiftright-final-hook nil
19595 "Hook for functions attaching themselves to `S-right'.
19596 This one runs after all other options except shift-select have been excluded.
19597 See `org-ctrl-c-ctrl-c-hook' for more information.")
19599 (defun org-modifier-cursor-error ()
19600 "Throw an error, a modified cursor command was applied in wrong context."
19601 (user-error "This command is active in special context like tables, headlines or items"))
19603 (defun org-shiftselect-error ()
19604 "Throw an error because Shift-Cursor command was applied in wrong context."
19605 (if (and (boundp 'shift-select-mode) shift-select-mode)
19606 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19607 (user-error "This command works only in special context like headlines or timestamps")))
19609 (defun org-call-for-shift-select (cmd)
19610 (let ((this-command-keys-shift-translated t))
19611 (call-interactively cmd)))
19613 (defun org-shifttab (&optional arg)
19614 "Global visibility cycling or move to previous table field.
19615 Call `org-table-previous-field' within a table.
19616 When ARG is nil, cycle globally through visibility states.
19617 When ARG is a numeric prefix, show contents of this level."
19618 (interactive "P")
19619 (cond
19620 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19621 ((integerp arg)
19622 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19623 (message "Content view to level: %d" arg)
19624 (org-content (prefix-numeric-value arg2))
19625 (org-cycle-show-empty-lines t)
19626 (setq org-cycle-global-status 'overview)))
19627 (t (call-interactively 'org-global-cycle))))
19629 (defun org-shiftmetaleft ()
19630 "Promote subtree or delete table column.
19631 Calls `org-promote-subtree', `org-outdent-item-tree', or
19632 `org-table-delete-column', depending on context. See the
19633 individual commands for more information."
19634 (interactive)
19635 (cond
19636 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19637 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19638 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19639 ((if (not (org-region-active-p)) (org-at-item-p)
19640 (save-excursion (goto-char (region-beginning))
19641 (org-at-item-p)))
19642 (call-interactively 'org-outdent-item-tree))
19643 (t (org-modifier-cursor-error))))
19645 (defun org-shiftmetaright ()
19646 "Demote subtree or insert table column.
19647 Calls `org-demote-subtree', `org-indent-item-tree', or
19648 `org-table-insert-column', depending on context. See the
19649 individual commands for more information."
19650 (interactive)
19651 (cond
19652 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19653 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19654 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19655 ((if (not (org-region-active-p)) (org-at-item-p)
19656 (save-excursion (goto-char (region-beginning))
19657 (org-at-item-p)))
19658 (call-interactively 'org-indent-item-tree))
19659 (t (org-modifier-cursor-error))))
19661 (defun org-shiftmetaup (&optional arg)
19662 "Move subtree up or kill table row.
19663 Calls `org-move-subtree-up' or `org-table-kill-row' or
19664 `org-move-item-up' or `org-timestamp-up', depending on context.
19665 See the individual commands for more information."
19666 (interactive "P")
19667 (cond
19668 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19669 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19670 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19671 ((org-at-item-p) (call-interactively 'org-move-item-up))
19672 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19673 (call-interactively 'org-timestamp-up)))
19674 (t (call-interactively 'org-drag-line-backward))))
19676 (defun org-shiftmetadown (&optional arg)
19677 "Move subtree down or insert table row.
19678 Calls `org-move-subtree-down' or `org-table-insert-row' or
19679 `org-move-item-down' or `org-timestamp-up', depending on context.
19680 See the individual commands for more information."
19681 (interactive "P")
19682 (cond
19683 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19684 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19685 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19686 ((org-at-item-p) (call-interactively 'org-move-item-down))
19687 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19688 (call-interactively 'org-timestamp-down)))
19689 (t (call-interactively 'org-drag-line-forward))))
19691 (defsubst org-hidden-tree-error ()
19692 (user-error
19693 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19695 (defun org-metaleft (&optional arg)
19696 "Promote heading or move table column to left.
19697 Calls `org-do-promote' or `org-table-move-column', depending on context.
19698 With no specific context, calls the Emacs default `backward-word'.
19699 See the individual commands for more information."
19700 (interactive "P")
19701 (cond
19702 ((run-hook-with-args-until-success 'org-metaleft-hook))
19703 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19704 ((org-with-limited-levels
19705 (or (org-at-heading-p)
19706 (and (org-region-active-p)
19707 (save-excursion
19708 (goto-char (region-beginning))
19709 (org-at-heading-p)))))
19710 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19711 (call-interactively 'org-do-promote))
19712 ;; At an inline task.
19713 ((org-at-heading-p)
19714 (call-interactively 'org-inlinetask-promote))
19715 ((or (org-at-item-p)
19716 (and (org-region-active-p)
19717 (save-excursion
19718 (goto-char (region-beginning))
19719 (org-at-item-p))))
19720 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19721 (call-interactively 'org-outdent-item))
19722 (t (call-interactively 'backward-word))))
19724 (defun org-metaright (&optional arg)
19725 "Demote a subtree, a list item or move table column to right.
19726 In front of a drawer or a block keyword, indent it correctly.
19727 With no specific context, calls the Emacs default `forward-word'.
19728 See the individual commands for more information."
19729 (interactive "P")
19730 (cond
19731 ((run-hook-with-args-until-success 'org-metaright-hook))
19732 ((org-at-table-p) (call-interactively 'org-table-move-column))
19733 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19734 ((org-at-block-p) (call-interactively 'org-indent-block))
19735 ((org-with-limited-levels
19736 (or (org-at-heading-p)
19737 (and (org-region-active-p)
19738 (save-excursion
19739 (goto-char (region-beginning))
19740 (org-at-heading-p)))))
19741 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19742 (call-interactively 'org-do-demote))
19743 ;; At an inline task.
19744 ((org-at-heading-p)
19745 (call-interactively 'org-inlinetask-demote))
19746 ((or (org-at-item-p)
19747 (and (org-region-active-p)
19748 (save-excursion
19749 (goto-char (region-beginning))
19750 (org-at-item-p))))
19751 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19752 (call-interactively 'org-indent-item))
19753 (t (call-interactively 'forward-word))))
19755 (defun org-check-for-hidden (what)
19756 "Check if there are hidden headlines/items in the current visual line.
19757 WHAT can be either `headlines' or `items'. If the current line is
19758 an outline or item heading and it has a folded subtree below it,
19759 this function returns t, nil otherwise."
19760 (let ((re (cond
19761 ((eq what 'headlines) org-outline-regexp-bol)
19762 ((eq what 'items) (org-item-beginning-re))
19763 (t (error "This should not happen"))))
19764 beg end)
19765 (save-excursion
19766 (catch 'exit
19767 (unless (org-region-active-p)
19768 (setq beg (point-at-bol))
19769 (beginning-of-line 2)
19770 (while (and (not (eobp)) ;; this is like `next-line'
19771 (get-char-property (1- (point)) 'invisible))
19772 (beginning-of-line 2))
19773 (setq end (point))
19774 (goto-char beg)
19775 (goto-char (point-at-eol))
19776 (setq end (max end (point)))
19777 (while (re-search-forward re end t)
19778 (if (get-char-property (match-beginning 0) 'invisible)
19779 (throw 'exit t))))
19780 nil))))
19782 (defun org-metaup (&optional arg)
19783 "Move subtree up or move table row up.
19784 Calls `org-move-subtree-up' or `org-table-move-row' or
19785 `org-move-item-up', depending on context. See the individual commands
19786 for more information."
19787 (interactive "P")
19788 (cond
19789 ((run-hook-with-args-until-success 'org-metaup-hook))
19790 ((org-region-active-p)
19791 (let* ((a (min (region-beginning) (region-end)))
19792 (b (1- (max (region-beginning) (region-end))))
19793 (c (save-excursion (goto-char a)
19794 (move-beginning-of-line 0)))
19795 (d (save-excursion (goto-char a)
19796 (move-end-of-line 0) (point))))
19797 (transpose-regions a b c d)
19798 (goto-char c)))
19799 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19800 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19801 ((org-at-item-p) (call-interactively 'org-move-item-up))
19802 (t (org-drag-element-backward))))
19804 (defun org-metadown (&optional arg)
19805 "Move subtree down or move table row down.
19806 Calls `org-move-subtree-down' or `org-table-move-row' or
19807 `org-move-item-down', depending on context. See the individual
19808 commands for more information."
19809 (interactive "P")
19810 (cond
19811 ((run-hook-with-args-until-success 'org-metadown-hook))
19812 ((org-region-active-p)
19813 (let* ((a (min (region-beginning) (region-end)))
19814 (b (max (region-beginning) (region-end)))
19815 (c (save-excursion (goto-char b)
19816 (move-beginning-of-line 1)))
19817 (d (save-excursion (goto-char b)
19818 (move-end-of-line 1) (1+ (point)))))
19819 (transpose-regions a b c d)
19820 (goto-char d)))
19821 ((org-at-table-p) (call-interactively 'org-table-move-row))
19822 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19823 ((org-at-item-p) (call-interactively 'org-move-item-down))
19824 (t (org-drag-element-forward))))
19826 (defun org-shiftup (&optional arg)
19827 "Increase item in timestamp or increase priority of current headline.
19828 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19829 depending on context. See the individual commands for more information."
19830 (interactive "P")
19831 (cond
19832 ((run-hook-with-args-until-success 'org-shiftup-hook))
19833 ((and org-support-shift-select (org-region-active-p))
19834 (org-call-for-shift-select 'previous-line))
19835 ((org-at-timestamp-p t)
19836 (call-interactively (if org-edit-timestamp-down-means-later
19837 'org-timestamp-down 'org-timestamp-up)))
19838 ((and (not (eq org-support-shift-select 'always))
19839 org-enable-priority-commands
19840 (org-at-heading-p))
19841 (call-interactively 'org-priority-up))
19842 ((and (not org-support-shift-select) (org-at-item-p))
19843 (call-interactively 'org-previous-item))
19844 ((org-clocktable-try-shift 'up arg))
19845 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19846 (org-support-shift-select
19847 (org-call-for-shift-select 'previous-line))
19848 (t (org-shiftselect-error))))
19850 (defun org-shiftdown (&optional arg)
19851 "Decrease item in timestamp or decrease priority of current headline.
19852 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19853 depending on context. See the individual commands for more information."
19854 (interactive "P")
19855 (cond
19856 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19857 ((and org-support-shift-select (org-region-active-p))
19858 (org-call-for-shift-select 'next-line))
19859 ((org-at-timestamp-p t)
19860 (call-interactively (if org-edit-timestamp-down-means-later
19861 'org-timestamp-up 'org-timestamp-down)))
19862 ((and (not (eq org-support-shift-select 'always))
19863 org-enable-priority-commands
19864 (org-at-heading-p))
19865 (call-interactively 'org-priority-down))
19866 ((and (not org-support-shift-select) (org-at-item-p))
19867 (call-interactively 'org-next-item))
19868 ((org-clocktable-try-shift 'down arg))
19869 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19870 (org-support-shift-select
19871 (org-call-for-shift-select 'next-line))
19872 (t (org-shiftselect-error))))
19874 (defun org-shiftright (&optional arg)
19875 "Cycle the thing at point or in the current line, depending on context.
19876 Depending on context, this does one of the following:
19878 - switch a timestamp at point one day into the future
19879 - on a headline, switch to the next TODO keyword.
19880 - on an item, switch entire list to the next bullet type
19881 - on a property line, switch to the next allowed value
19882 - on a clocktable definition line, move time block into the future"
19883 (interactive "P")
19884 (cond
19885 ((run-hook-with-args-until-success 'org-shiftright-hook))
19886 ((and org-support-shift-select (org-region-active-p))
19887 (org-call-for-shift-select 'forward-char))
19888 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19889 ((and (not (eq org-support-shift-select 'always))
19890 (org-at-heading-p))
19891 (let ((org-inhibit-logging
19892 (not org-treat-S-cursor-todo-selection-as-state-change))
19893 (org-inhibit-blocking
19894 (not org-treat-S-cursor-todo-selection-as-state-change)))
19895 (org-call-with-arg 'org-todo 'right)))
19896 ((or (and org-support-shift-select
19897 (not (eq org-support-shift-select 'always))
19898 (org-at-item-bullet-p))
19899 (and (not org-support-shift-select) (org-at-item-p)))
19900 (org-call-with-arg 'org-cycle-list-bullet nil))
19901 ((and (not (eq org-support-shift-select 'always))
19902 (org-at-property-p))
19903 (call-interactively 'org-property-next-allowed-value))
19904 ((org-clocktable-try-shift 'right arg))
19905 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19906 (org-support-shift-select
19907 (org-call-for-shift-select 'forward-char))
19908 (t (org-shiftselect-error))))
19910 (defun org-shiftleft (&optional arg)
19911 "Cycle the thing at point or in the current line, depending on context.
19912 Depending on context, this does one of the following:
19914 - switch a timestamp at point one day into the past
19915 - on a headline, switch to the previous TODO keyword.
19916 - on an item, switch entire list to the previous bullet type
19917 - on a property line, switch to the previous allowed value
19918 - on a clocktable definition line, move time block into the past"
19919 (interactive "P")
19920 (cond
19921 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19922 ((and org-support-shift-select (org-region-active-p))
19923 (org-call-for-shift-select 'backward-char))
19924 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19925 ((and (not (eq org-support-shift-select 'always))
19926 (org-at-heading-p))
19927 (let ((org-inhibit-logging
19928 (not org-treat-S-cursor-todo-selection-as-state-change))
19929 (org-inhibit-blocking
19930 (not org-treat-S-cursor-todo-selection-as-state-change)))
19931 (org-call-with-arg 'org-todo 'left)))
19932 ((or (and org-support-shift-select
19933 (not (eq org-support-shift-select 'always))
19934 (org-at-item-bullet-p))
19935 (and (not org-support-shift-select) (org-at-item-p)))
19936 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19937 ((and (not (eq org-support-shift-select 'always))
19938 (org-at-property-p))
19939 (call-interactively 'org-property-previous-allowed-value))
19940 ((org-clocktable-try-shift 'left arg))
19941 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19942 (org-support-shift-select
19943 (org-call-for-shift-select 'backward-char))
19944 (t (org-shiftselect-error))))
19946 (defun org-shiftcontrolright ()
19947 "Switch to next TODO set."
19948 (interactive)
19949 (cond
19950 ((and org-support-shift-select (org-region-active-p))
19951 (org-call-for-shift-select 'forward-word))
19952 ((and (not (eq org-support-shift-select 'always))
19953 (org-at-heading-p))
19954 (org-call-with-arg 'org-todo 'nextset))
19955 (org-support-shift-select
19956 (org-call-for-shift-select 'forward-word))
19957 (t (org-shiftselect-error))))
19959 (defun org-shiftcontrolleft ()
19960 "Switch to previous TODO set."
19961 (interactive)
19962 (cond
19963 ((and org-support-shift-select (org-region-active-p))
19964 (org-call-for-shift-select 'backward-word))
19965 ((and (not (eq org-support-shift-select 'always))
19966 (org-at-heading-p))
19967 (org-call-with-arg 'org-todo 'previousset))
19968 (org-support-shift-select
19969 (org-call-for-shift-select 'backward-word))
19970 (t (org-shiftselect-error))))
19972 (defun org-shiftcontrolup (&optional n)
19973 "Change timestamps synchronously up in CLOCK log lines.
19974 Optional argument N tells to change by that many units."
19975 (interactive "P")
19976 (cond ((and (not org-support-shift-select)
19977 (org-at-clock-log-p)
19978 (org-at-timestamp-p t))
19979 (org-clock-timestamps-up n))
19980 (t (org-shiftselect-error))))
19982 (defun org-shiftcontroldown (&optional n)
19983 "Change timestamps synchronously down in CLOCK log lines.
19984 Optional argument N tells to change by that many units."
19985 (interactive "P")
19986 (cond ((and (not org-support-shift-select)
19987 (org-at-clock-log-p)
19988 (org-at-timestamp-p t))
19989 (org-clock-timestamps-down n))
19990 (t (org-shiftselect-error))))
19992 (defun org-ctrl-c-ret ()
19993 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19994 (interactive)
19995 (cond
19996 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19997 (t (call-interactively 'org-insert-heading))))
19999 (defun org-find-visible ()
20000 (let ((s (point)))
20001 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20002 (get-char-property s 'invisible)))
20004 (defun org-find-invisible ()
20005 (let ((s (point)))
20006 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20007 (not (get-char-property s 'invisible))))
20010 (defun org-copy-visible (beg end)
20011 "Copy the visible parts of the region."
20012 (interactive "r")
20013 (let (snippets s)
20014 (save-excursion
20015 (save-restriction
20016 (narrow-to-region beg end)
20017 (setq s (goto-char (point-min)))
20018 (while (not (= (point) (point-max)))
20019 (goto-char (org-find-invisible))
20020 (push (buffer-substring s (point)) snippets)
20021 (setq s (goto-char (org-find-visible))))))
20022 (kill-new (apply 'concat (nreverse snippets)))))
20024 (defun org-copy-special ()
20025 "Copy region in table or copy current subtree.
20026 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20027 See the individual commands for more information."
20028 (interactive)
20029 (call-interactively
20030 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20032 (defun org-cut-special ()
20033 "Cut region in table or cut current subtree.
20034 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20035 See the individual commands for more information."
20036 (interactive)
20037 (call-interactively
20038 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20040 (defun org-paste-special (arg)
20041 "Paste rectangular region into table, or past subtree relative to level.
20042 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20043 See the individual commands for more information."
20044 (interactive "P")
20045 (if (org-at-table-p)
20046 (org-table-paste-rectangle)
20047 (org-paste-subtree arg)))
20049 (defsubst org-in-fixed-width-region-p ()
20050 "Is point in a fixed-width region?"
20051 (save-match-data
20052 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20054 (defun org-edit-special (&optional arg)
20055 "Call a special editor for the element at point.
20056 When at a table, call the formula editor with `org-table-edit-formulas'.
20057 When in a source code block, call `org-edit-src-code'.
20058 When in a fixed-width region, call `org-edit-fixed-width-region'.
20059 When at an #+INCLUDE keyword, visit the included file.
20060 On a link, call `ffap' to visit the link at point.
20061 Otherwise, return a user error."
20062 (interactive "P")
20063 (let ((element (org-element-at-point)))
20064 (assert (not buffer-read-only) nil
20065 "Buffer is read-only: %s" (buffer-name))
20066 (case (org-element-type element)
20067 (src-block
20068 (if (not arg) (org-edit-src-code)
20069 (let* ((info (org-babel-get-src-block-info))
20070 (lang (nth 0 info))
20071 (params (nth 2 info))
20072 (session (cdr (assq :session params))))
20073 (if (not session) (org-edit-src-code)
20074 ;; At a src-block with a session and function called with
20075 ;; an ARG: switch to the buffer related to the inferior
20076 ;; process.
20077 (switch-to-buffer
20078 (funcall (intern (concat "org-babel-prep-session:" lang))
20079 session params))))))
20080 (keyword
20081 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20082 (find-file
20083 (org-remove-double-quotes
20084 (car (org-split-string (org-element-property :value element)))))
20085 (user-error "No special environment to edit here")))
20086 (table
20087 (if (eq (org-element-property :type element) 'table.el)
20088 (org-edit-src-code)
20089 (call-interactively 'org-table-edit-formulas)))
20090 ;; Only Org tables contain `table-row' type elements.
20091 (table-row (call-interactively 'org-table-edit-formulas))
20092 ((example-block export-block) (org-edit-src-code))
20093 (fixed-width (org-edit-fixed-width-region))
20094 (otherwise
20095 ;; No notable element at point. Though, we may be at a link,
20096 ;; which is an object. Thus, scan deeper.
20097 (if (eq (org-element-type (org-element-context element)) 'link)
20098 (call-interactively 'ffap)
20099 (user-error "No special environment to edit here"))))))
20101 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20102 (defun org-ctrl-c-ctrl-c (&optional arg)
20103 "Set tags in headline, or update according to changed information at point.
20105 This command does many different things, depending on context:
20107 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20108 this is what we do.
20110 - If the cursor is on a statistics cookie, update it.
20112 - If the cursor is in a headline, prompt for tags and insert them
20113 into the current line, aligned to `org-tags-column'. When called
20114 with prefix arg, realign all tags in the current buffer.
20116 - If the cursor is in one of the special #+KEYWORD lines, this
20117 triggers scanning the buffer for these lines and updating the
20118 information.
20120 - If the cursor is inside a table, realign the table. This command
20121 works even if the automatic table editor has been turned off.
20123 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20124 the entire table.
20126 - If the cursor is at a footnote reference or definition, jump to
20127 the corresponding definition or references, respectively.
20129 - If the cursor is a the beginning of a dynamic block, update it.
20131 - If the current buffer is a capture buffer, close note and file it.
20133 - If the cursor is on a <<<target>>>, update radio targets and
20134 corresponding links in this buffer.
20136 - If the cursor is on a numbered item in a plain list, renumber the
20137 ordered list.
20139 - If the cursor is on a checkbox, toggle it.
20141 - If the cursor is on a code block, evaluate it. The variable
20142 `org-confirm-babel-evaluate' can be used to control prompting
20143 before code block evaluation, by default every code block
20144 evaluation requires confirmation. Code block evaluation can be
20145 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20146 (interactive "P")
20147 (cond
20148 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20149 org-occur-highlights
20150 org-latex-fragment-image-overlays)
20151 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20152 (org-remove-occur-highlights)
20153 (org-remove-latex-fragment-image-overlays)
20154 (message "Temporary highlights/overlays removed from current buffer"))
20155 ((and (local-variable-p 'org-finish-function (current-buffer))
20156 (fboundp org-finish-function))
20157 (funcall org-finish-function))
20158 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20160 (let* ((context (org-element-context)) (type (org-element-type context)))
20161 ;; Test if point is within a blank line.
20162 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20163 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20164 (user-error "C-c C-c can do nothing useful at this location"))
20165 ;; For convenience: at the first line of a paragraph on the
20166 ;; same line as an item, apply function on that item instead.
20167 (when (eq type 'paragraph)
20168 (let ((parent (org-element-property :parent context)))
20169 (when (and (eq (org-element-type parent) 'item)
20170 (= (point-at-bol) (org-element-property :begin parent)))
20171 (setq context parent type 'item))))
20172 ;; Act according to type of element or object at point.
20173 (case type
20174 (clock (org-clock-update-time-maybe))
20175 (dynamic-block
20176 (save-excursion
20177 (goto-char (org-element-property :post-affiliated context))
20178 (org-update-dblock)))
20179 (footnote-definition
20180 (goto-char (org-element-property :post-affiliated context))
20181 (call-interactively 'org-footnote-action))
20182 (footnote-reference (call-interactively 'org-footnote-action))
20183 ((headline inlinetask)
20184 (save-excursion (goto-char (org-element-property :begin context))
20185 (call-interactively 'org-set-tags)))
20186 (item
20187 ;; At an item: a double C-u set checkbox to "[-]"
20188 ;; unconditionally, whereas a single one will toggle its
20189 ;; presence. Without an universal argument, if the item
20190 ;; has a checkbox, toggle it. Otherwise repair the list.
20191 (let* ((box (org-element-property :checkbox context))
20192 (struct (org-element-property :structure context))
20193 (old-struct (copy-tree struct))
20194 (parents (org-list-parents-alist struct))
20195 (prevs (org-list-prevs-alist struct))
20196 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20197 (org-list-set-checkbox
20198 (org-element-property :begin context) struct
20199 (cond ((equal arg '(16)) "[-]")
20200 ((and (not box) (equal arg '(4))) "[ ]")
20201 ((or (not box) (equal arg '(4))) nil)
20202 ((eq box 'on) "[ ]")
20203 (t "[X]")))
20204 ;; Mimic `org-list-write-struct' but with grabbing
20205 ;; a return value from `org-list-struct-fix-box'.
20206 (org-list-struct-fix-ind struct parents 2)
20207 (org-list-struct-fix-item-end struct)
20208 (org-list-struct-fix-bul struct prevs)
20209 (org-list-struct-fix-ind struct parents)
20210 (let ((block-item
20211 (org-list-struct-fix-box struct parents prevs orderedp)))
20212 (if (and box (equal struct old-struct))
20213 (if (equal arg '(16))
20214 (message "Checkboxes already reset")
20215 (user-error "Cannot toggle this checkbox: %s"
20216 (if (eq box 'on)
20217 "all subitems checked"
20218 "unchecked subitems")))
20219 (org-list-struct-apply-struct struct old-struct)
20220 (org-update-checkbox-count-maybe))
20221 (when block-item
20222 (message "Checkboxes were removed due to empty box at line %d"
20223 (org-current-line block-item))))))
20224 (keyword
20225 (let ((org-inhibit-startup-visibility-stuff t)
20226 (org-startup-align-all-tables nil))
20227 (when (boundp 'org-table-coordinate-overlays)
20228 (mapc 'delete-overlay org-table-coordinate-overlays)
20229 (setq org-table-coordinate-overlays nil))
20230 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20231 (message "Local setup has been refreshed"))
20232 (plain-list
20233 ;; At a plain list, with a double C-u argument, set
20234 ;; checkboxes of each item to "[-]", whereas a single one
20235 ;; will toggle their presence according to the state of the
20236 ;; first item in the list. Without an argument, repair the
20237 ;; list.
20238 (let* ((begin (org-element-property :contents-begin context))
20239 (beginm (move-marker (make-marker) begin))
20240 (struct (org-element-property :structure context))
20241 (old-struct (copy-tree struct))
20242 (first-box (save-excursion
20243 (goto-char begin)
20244 (looking-at org-list-full-item-re)
20245 (match-string-no-properties 3)))
20246 (new-box (cond ((equal arg '(16)) "[-]")
20247 ((equal arg '(4)) (unless first-box "[ ]"))
20248 ((equal first-box "[X]") "[ ]")
20249 (t "[X]"))))
20250 (cond
20251 (arg
20252 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20253 (org-list-get-all-items
20254 begin struct (org-list-prevs-alist struct))))
20255 ((and first-box (eq (point) begin))
20256 ;; For convenience, when point is at bol on the first
20257 ;; item of the list and no argument is provided, simply
20258 ;; toggle checkbox of that item, if any.
20259 (org-list-set-checkbox begin struct new-box)))
20260 (org-list-write-struct
20261 struct (org-list-parents-alist struct) old-struct)
20262 (org-update-checkbox-count-maybe)
20263 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20264 ((property-drawer node-property)
20265 (call-interactively 'org-property-action))
20266 ((radio-target target)
20267 (call-interactively 'org-update-radio-target-regexp))
20268 (statistics-cookie
20269 (call-interactively 'org-update-statistics-cookies))
20270 ((table table-cell table-row)
20271 ;; At a table, recalculate every field and align it. Also
20272 ;; send the table if necessary. If the table has
20273 ;; a `table.el' type, just give up. At a table row or
20274 ;; cell, maybe recalculate line but always align table.
20275 (if (eq (org-element-property :type context) 'table.el)
20276 (message "Use C-c ' to edit table.el tables")
20277 (let ((org-enable-table-editor t))
20278 (if (or (eq type 'table)
20279 ;; Check if point is at a TBLFM line.
20280 (and (eq type 'table-row)
20281 (= (point) (org-element-property :end context))))
20282 (save-excursion
20283 (if (org-at-TBLFM-p)
20284 (progn (require 'org-table)
20285 (org-table-calc-current-TBLFM))
20286 (goto-char (org-element-property :contents-begin context))
20287 (org-call-with-arg 'org-table-recalculate (or arg t))
20288 (orgtbl-send-table 'maybe)))
20289 (org-table-maybe-eval-formula)
20290 (cond (arg (call-interactively 'org-table-recalculate))
20291 ((org-table-maybe-recalculate-line))
20292 (t (org-table-align)))))))
20293 (timestamp (org-timestamp-change 0 'day))
20294 (otherwise
20295 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20296 (user-error
20297 "C-c C-c can do nothing useful at this location")))))))))
20299 (defun org-mode-restart ()
20300 "Restart Org-mode, to scan again for special lines.
20301 Also updates the keyword regular expressions."
20302 (interactive)
20303 (org-mode)
20304 (message "Org-mode restarted"))
20306 (defun org-kill-note-or-show-branches ()
20307 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20308 (interactive)
20309 (if (not org-finish-function)
20310 (progn
20311 (hide-subtree)
20312 (call-interactively 'show-branches))
20313 (let ((org-note-abort t))
20314 (funcall org-finish-function))))
20316 (defun org-open-line (n)
20317 "Insert a new row in tables, call `open-line' elsewhere."
20318 (interactive "*p")
20319 (if (org-at-table-p)
20320 (org-table-insert-row)
20321 (open-line n)))
20323 (defun org-return (&optional indent)
20324 "Goto next table row or insert a newline.
20325 Calls `org-table-next-row' or `newline', depending on context.
20326 See the individual commands for more information."
20327 (interactive)
20328 (let (org-ts-what)
20329 (cond
20330 ((or (bobp) (org-in-src-block-p))
20331 (if indent (newline-and-indent) (newline)))
20332 ((org-at-table-p)
20333 (org-table-justify-field-maybe)
20334 (call-interactively 'org-table-next-row))
20335 ;; when `newline-and-indent' is called within a list, make sure
20336 ;; text moved stays inside the item.
20337 ((and (org-in-item-p) indent)
20338 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20339 (progn
20340 (save-match-data (newline))
20341 (org-indent-line-to (length (match-string 0))))
20342 (let ((ind (org-get-indentation)))
20343 (newline)
20344 (if (org-looking-back org-list-end-re)
20345 (org-indent-line)
20346 (org-indent-line-to ind)))))
20347 ((and org-return-follows-link
20348 (org-at-timestamp-p t)
20349 (not (eq org-ts-what 'after)))
20350 (org-follow-timestamp-link))
20351 ((and org-return-follows-link
20352 (let ((tprop (get-text-property (point) 'face)))
20353 (or (eq tprop 'org-link)
20354 (and (listp tprop) (memq 'org-link tprop)))))
20355 (call-interactively 'org-open-at-point))
20356 ((and (org-at-heading-p)
20357 (looking-at
20358 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20359 (org-show-entry)
20360 (end-of-line 1)
20361 (newline))
20362 (t (if indent (newline-and-indent) (newline))))))
20364 (defun org-return-indent ()
20365 "Goto next table row or insert a newline and indent.
20366 Calls `org-table-next-row' or `newline-and-indent', depending on
20367 context. See the individual commands for more information."
20368 (interactive)
20369 (org-return t))
20371 (defun org-ctrl-c-star ()
20372 "Compute table, or change heading status of lines.
20373 Calls `org-table-recalculate' or `org-toggle-heading',
20374 depending on context."
20375 (interactive)
20376 (cond
20377 ((org-at-table-p)
20378 (call-interactively 'org-table-recalculate))
20380 ;; Convert all lines in region to list items
20381 (call-interactively 'org-toggle-heading))))
20383 (defun org-ctrl-c-minus ()
20384 "Insert separator line in table or modify bullet status of line.
20385 Also turns a plain line or a region of lines into list items.
20386 Calls `org-table-insert-hline', `org-toggle-item', or
20387 `org-cycle-list-bullet', depending on context."
20388 (interactive)
20389 (cond
20390 ((org-at-table-p)
20391 (call-interactively 'org-table-insert-hline))
20392 ((org-region-active-p)
20393 (call-interactively 'org-toggle-item))
20394 ((org-in-item-p)
20395 (call-interactively 'org-cycle-list-bullet))
20397 (call-interactively 'org-toggle-item))))
20399 (defun org-toggle-item (arg)
20400 "Convert headings or normal lines to items, items to normal lines.
20401 If there is no active region, only the current line is considered.
20403 If the first non blank line in the region is a headline, convert
20404 all headlines to items, shifting text accordingly.
20406 If it is an item, convert all items to normal lines.
20408 If it is normal text, change region into a list of items.
20409 With a prefix argument ARG, change the region in a single item."
20410 (interactive "P")
20411 (let ((shift-text
20412 (function
20413 ;; Shift text in current section to IND, from point to END.
20414 ;; The function leaves point to END line.
20415 (lambda (ind end)
20416 (let ((min-i 1000) (end (copy-marker end)))
20417 ;; First determine the minimum indentation (MIN-I) of
20418 ;; the text.
20419 (save-excursion
20420 (catch 'exit
20421 (while (< (point) end)
20422 (let ((i (org-get-indentation)))
20423 (cond
20424 ;; Skip blank lines and inline tasks.
20425 ((looking-at "^[ \t]*$"))
20426 ((looking-at org-outline-regexp-bol))
20427 ;; We can't find less than 0 indentation.
20428 ((zerop i) (throw 'exit (setq min-i 0)))
20429 ((< i min-i) (setq min-i i))))
20430 (forward-line))))
20431 ;; Then indent each line so that a line indented to
20432 ;; MIN-I becomes indented to IND. Ignore blank lines
20433 ;; and inline tasks in the process.
20434 (let ((delta (- ind min-i)))
20435 (while (< (point) end)
20436 (unless (or (looking-at "^[ \t]*$")
20437 (looking-at org-outline-regexp-bol))
20438 (org-indent-line-to (+ (org-get-indentation) delta)))
20439 (forward-line)))))))
20440 (skip-blanks
20441 (function
20442 ;; Return beginning of first non-blank line, starting from
20443 ;; line at POS.
20444 (lambda (pos)
20445 (save-excursion
20446 (goto-char pos)
20447 (skip-chars-forward " \r\t\n")
20448 (point-at-bol)))))
20449 beg end)
20450 ;; Determine boundaries of changes.
20451 (if (org-region-active-p)
20452 (setq beg (funcall skip-blanks (region-beginning))
20453 end (copy-marker (region-end)))
20454 (setq beg (funcall skip-blanks (point-at-bol))
20455 end (copy-marker (point-at-eol))))
20456 ;; Depending on the starting line, choose an action on the text
20457 ;; between BEG and END.
20458 (org-with-limited-levels
20459 (save-excursion
20460 (goto-char beg)
20461 (cond
20462 ;; Case 1. Start at an item: de-itemize. Note that it only
20463 ;; happens when a region is active: `org-ctrl-c-minus'
20464 ;; would call `org-cycle-list-bullet' otherwise.
20465 ((org-at-item-p)
20466 (while (< (point) end)
20467 (when (org-at-item-p)
20468 (skip-chars-forward " \t")
20469 (delete-region (point) (match-end 0)))
20470 (forward-line)))
20471 ;; Case 2. Start at an heading: convert to items.
20472 ((org-at-heading-p)
20473 (let* ((bul (org-list-bullet-string "-"))
20474 (bul-len (length bul))
20475 ;; Indentation of the first heading. It should be
20476 ;; relative to the indentation of its parent, if any.
20477 (start-ind (save-excursion
20478 (cond
20479 ((not org-adapt-indentation) 0)
20480 ((not (outline-previous-heading)) 0)
20481 (t (length (match-string 0))))))
20482 ;; Level of first heading. Further headings will be
20483 ;; compared to it to determine hierarchy in the list.
20484 (ref-level (org-reduced-level (org-outline-level))))
20485 (while (< (point) end)
20486 (let* ((level (org-reduced-level (org-outline-level)))
20487 (delta (max 0 (- level ref-level))))
20488 ;; If current headline is less indented than the first
20489 ;; one, set it as reference, in order to preserve
20490 ;; subtrees.
20491 (when (< level ref-level) (setq ref-level level))
20492 (replace-match bul t t)
20493 (org-indent-line-to (+ start-ind (* delta bul-len)))
20494 ;; Ensure all text down to END (or SECTION-END) belongs
20495 ;; to the newly created item.
20496 (let ((section-end (save-excursion
20497 (or (outline-next-heading) (point)))))
20498 (forward-line)
20499 (funcall shift-text
20500 (+ start-ind (* (1+ delta) bul-len))
20501 (min end section-end)))))))
20502 ;; Case 3. Normal line with ARG: make the first line of region
20503 ;; an item, and shift indentation of others lines to
20504 ;; set them as item's body.
20505 (arg (let* ((bul (org-list-bullet-string "-"))
20506 (bul-len (length bul))
20507 (ref-ind (org-get-indentation)))
20508 (skip-chars-forward " \t")
20509 (insert bul)
20510 (forward-line)
20511 (while (< (point) end)
20512 ;; Ensure that lines less indented than first one
20513 ;; still get included in item body.
20514 (funcall shift-text
20515 (+ ref-ind bul-len)
20516 (min end (save-excursion (or (outline-next-heading)
20517 (point)))))
20518 (forward-line))))
20519 ;; Case 4. Normal line without ARG: turn each non-item line
20520 ;; into an item.
20522 (while (< (point) end)
20523 (unless (or (org-at-heading-p) (org-at-item-p))
20524 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20525 (replace-match
20526 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20527 (forward-line))))))))
20529 (defun org-toggle-heading (&optional nstars)
20530 "Convert headings to normal text, or items or text to headings.
20531 If there is no active region, only convert the current line.
20533 With a \\[universal-argument] prefix, convert the whole list at
20534 point into heading.
20536 In a region:
20538 - If the first non blank line is a headline, remove the stars
20539 from all headlines in the region.
20541 - If it is a normal line, turn each and every normal line (i.e.,
20542 not an heading or an item) in the region into headings. If you
20543 want to convert only the first line of this region, use one
20544 universal prefix argument.
20546 - If it is a plain list item, turn all plain list items into headings.
20548 When converting a line into a heading, the number of stars is chosen
20549 such that the lines become children of the current entry. However,
20550 when a numeric prefix argument is given, its value determines the
20551 number of stars to add."
20552 (interactive "P")
20553 (let ((skip-blanks
20554 (function
20555 ;; Return beginning of first non-blank line, starting from
20556 ;; line at POS.
20557 (lambda (pos)
20558 (save-excursion
20559 (goto-char pos)
20560 (while (org-at-comment-p) (forward-line))
20561 (skip-chars-forward " \r\t\n")
20562 (point-at-bol)))))
20563 beg end toggled)
20564 ;; Determine boundaries of changes. If a universal prefix has
20565 ;; been given, put the list in a region. If region ends at a bol,
20566 ;; do not consider the last line to be in the region.
20568 (when (and current-prefix-arg (org-at-item-p))
20569 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20570 (org-mark-element))
20572 (if (org-region-active-p)
20573 (setq beg (funcall skip-blanks (region-beginning))
20574 end (copy-marker (save-excursion
20575 (goto-char (region-end))
20576 (if (bolp) (point) (point-at-eol)))))
20577 (setq beg (funcall skip-blanks (point-at-bol))
20578 end (copy-marker (point-at-eol))))
20579 ;; Ensure inline tasks don't count as headings.
20580 (org-with-limited-levels
20581 (save-excursion
20582 (goto-char beg)
20583 (cond
20584 ;; Case 1. Started at an heading: de-star headings.
20585 ((org-at-heading-p)
20586 (while (< (point) end)
20587 (when (org-at-heading-p t)
20588 (looking-at org-outline-regexp) (replace-match "")
20589 (setq toggled t))
20590 (forward-line)))
20591 ;; Case 2. Started at an item: change items into headlines.
20592 ;; One star will be added by `org-list-to-subtree'.
20593 ((org-at-item-p)
20594 (let* ((stars (make-string
20595 ;; subtract the star that will be added again by
20596 ;; `org-list-to-subtree'
20597 (if (numberp nstars) (1- nstars)
20598 (or (org-current-level) 0))
20599 ?*))
20600 (add-stars
20601 (cond (nstars "") ; stars from prefix only
20602 ((equal stars "") "") ; before first heading
20603 (org-odd-levels-only "*") ; inside heading, odd
20604 (t "")))) ; inside heading, oddeven
20605 (while (< (point) end)
20606 (when (org-at-item-p)
20607 ;; Pay attention to cases when region ends before list.
20608 (let* ((struct (org-list-struct))
20609 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20610 (save-restriction
20611 (narrow-to-region (point) list-end)
20612 (insert
20613 (org-list-to-subtree
20614 (org-list-parse-list t)
20615 '(:istart (concat stars add-stars (funcall get-stars depth))
20616 :icount (concat stars add-stars (funcall get-stars depth)))))))
20617 (setq toggled t))
20618 (forward-line))))
20619 ;; Case 3. Started at normal text: make every line an heading,
20620 ;; skipping headlines and items.
20621 (t (let* ((stars
20622 (make-string
20623 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20624 (add-stars
20625 (cond (nstars "") ; stars from prefix only
20626 ((equal stars "") "*") ; before first heading
20627 (org-odd-levels-only "**") ; inside heading, odd
20628 (t "*"))) ; inside heading, oddeven
20629 (rpl (concat stars add-stars " "))
20630 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20631 (while (< (point) (if (equal nstars '(4)) lend end))
20632 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20633 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20634 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20635 (forward-line)))))))
20636 (unless toggled (message "Cannot toggle heading from here"))))
20638 (defun org-meta-return (&optional arg)
20639 "Insert a new heading or wrap a region in a table.
20640 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20641 See the individual commands for more information."
20642 (interactive "P")
20643 (org-check-before-invisible-edit 'insert)
20644 (cond
20645 ((run-hook-with-args-until-success 'org-metareturn-hook))
20646 ((or (org-at-drawer-p) (org-in-drawer-p) (org-at-property-p))
20647 (newline-and-indent))
20648 ((org-at-table-p)
20649 (call-interactively 'org-table-wrap-region))
20650 (t (call-interactively 'org-insert-heading))))
20652 ;;; Menu entries
20654 (defsubst org-in-subtree-not-table-p ()
20655 "Are we in a subtree and not in a table?"
20656 (and (not (org-before-first-heading-p))
20657 (not (org-at-table-p))))
20659 ;; Define the Org-mode menus
20660 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20661 '("Tbl"
20662 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20663 ["Next Field" org-cycle (org-at-table-p)]
20664 ["Previous Field" org-shifttab (org-at-table-p)]
20665 ["Next Row" org-return (org-at-table-p)]
20666 "--"
20667 ["Blank Field" org-table-blank-field (org-at-table-p)]
20668 ["Edit Field" org-table-edit-field (org-at-table-p)]
20669 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20670 "--"
20671 ("Column"
20672 ["Move Column Left" org-metaleft (org-at-table-p)]
20673 ["Move Column Right" org-metaright (org-at-table-p)]
20674 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20675 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20676 ("Row"
20677 ["Move Row Up" org-metaup (org-at-table-p)]
20678 ["Move Row Down" org-metadown (org-at-table-p)]
20679 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20680 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20681 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20682 "--"
20683 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20684 ("Rectangle"
20685 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20686 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20687 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20688 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20689 "--"
20690 ("Calculate"
20691 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20692 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20693 ["Edit Formulas" org-edit-special (org-at-table-p)]
20694 "--"
20695 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20696 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20697 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20698 "--"
20699 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20700 "--"
20701 ["Sum Column/Rectangle" org-table-sum
20702 (or (org-at-table-p) (org-region-active-p))]
20703 ["Which Column?" org-table-current-column (org-at-table-p)])
20704 ["Debug Formulas"
20705 org-table-toggle-formula-debugger
20706 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20707 ["Show Col/Row Numbers"
20708 org-table-toggle-coordinate-overlays
20709 :style toggle
20710 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20711 "--"
20712 ["Create" org-table-create (and (not (org-at-table-p))
20713 org-enable-table-editor)]
20714 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20715 ["Import from File" org-table-import (not (org-at-table-p))]
20716 ["Export to File" org-table-export (org-at-table-p)]
20717 "--"
20718 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20720 (easy-menu-define org-org-menu org-mode-map "Org menu"
20721 '("Org"
20722 ("Show/Hide"
20723 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20724 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20725 ["Sparse Tree..." org-sparse-tree t]
20726 ["Reveal Context" org-reveal t]
20727 ["Show All" show-all t]
20728 "--"
20729 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20730 "--"
20731 ["New Heading" org-insert-heading t]
20732 ("Navigate Headings"
20733 ["Up" outline-up-heading t]
20734 ["Next" outline-next-visible-heading t]
20735 ["Previous" outline-previous-visible-heading t]
20736 ["Next Same Level" outline-forward-same-level t]
20737 ["Previous Same Level" outline-backward-same-level t]
20738 "--"
20739 ["Jump" org-goto t])
20740 ("Edit Structure"
20741 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20742 "--"
20743 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20744 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20745 "--"
20746 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20747 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20748 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20749 "--"
20750 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20751 "--"
20752 ["Copy visible text" org-copy-visible t]
20753 "--"
20754 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20755 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20756 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20757 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20758 "--"
20759 ["Sort Region/Children" org-sort t]
20760 "--"
20761 ["Convert to odd levels" org-convert-to-odd-levels t]
20762 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20763 ("Editing"
20764 ["Emphasis..." org-emphasize t]
20765 ["Edit Source Example" org-edit-special t]
20766 "--"
20767 ["Footnote new/jump" org-footnote-action t]
20768 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20769 ("Archive"
20770 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20771 "--"
20772 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20773 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20774 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20776 "--"
20777 ("Hyperlinks"
20778 ["Store Link (Global)" org-store-link t]
20779 ["Find existing link to here" org-occur-link-in-agenda-files t]
20780 ["Insert Link" org-insert-link t]
20781 ["Follow Link" org-open-at-point t]
20782 "--"
20783 ["Next link" org-next-link t]
20784 ["Previous link" org-previous-link t]
20785 "--"
20786 ["Descriptive Links"
20787 org-toggle-link-display
20788 :style radio
20789 :selected org-descriptive-links
20791 ["Literal Links"
20792 org-toggle-link-display
20793 :style radio
20794 :selected (not org-descriptive-links)])
20795 "--"
20796 ("TODO Lists"
20797 ["TODO/DONE/-" org-todo t]
20798 ("Select keyword"
20799 ["Next keyword" org-shiftright (org-at-heading-p)]
20800 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20801 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20802 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20803 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20804 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20805 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20806 "--"
20807 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20808 :selected org-enforce-todo-dependencies :style toggle :active t]
20809 "Settings for tree at point"
20810 ["Do Children sequentially" org-toggle-ordered-property :style radio
20811 :selected (org-entry-get nil "ORDERED")
20812 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20813 ["Do Children parallel" org-toggle-ordered-property :style radio
20814 :selected (not (org-entry-get nil "ORDERED"))
20815 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20816 "--"
20817 ["Set Priority" org-priority t]
20818 ["Priority Up" org-shiftup t]
20819 ["Priority Down" org-shiftdown t]
20820 "--"
20821 ["Get news from all feeds" org-feed-update-all t]
20822 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20823 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20824 ("TAGS and Properties"
20825 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20826 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20827 "--"
20828 ["Set property" org-set-property (not (org-before-first-heading-p))]
20829 ["Column view of properties" org-columns t]
20830 ["Insert Column View DBlock" org-insert-columns-dblock t])
20831 ("Dates and Scheduling"
20832 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20833 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20834 ("Change Date"
20835 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20836 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20837 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20838 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20839 ["Compute Time Range" org-evaluate-time-range t]
20840 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20841 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20842 "--"
20843 ["Custom time format" org-toggle-time-stamp-overlays
20844 :style radio :selected org-display-custom-times]
20845 "--"
20846 ["Goto Calendar" org-goto-calendar t]
20847 ["Date from Calendar" org-date-from-calendar t]
20848 "--"
20849 ["Start/Restart Timer" org-timer-start t]
20850 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20851 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20852 ["Insert Timer String" org-timer t]
20853 ["Insert Timer Item" org-timer-item t])
20854 ("Logging work"
20855 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20856 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20857 ["Clock out" org-clock-out t]
20858 ["Clock cancel" org-clock-cancel t]
20859 "--"
20860 ["Mark as default task" org-clock-mark-default-task t]
20861 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20862 ["Goto running clock" org-clock-goto t]
20863 "--"
20864 ["Display times" org-clock-display t]
20865 ["Create clock table" org-clock-report t]
20866 "--"
20867 ["Record DONE time"
20868 (progn (setq org-log-done (not org-log-done))
20869 (message "Switching to %s will %s record a timestamp"
20870 (car org-done-keywords)
20871 (if org-log-done "automatically" "not")))
20872 :style toggle :selected org-log-done])
20873 "--"
20874 ["Agenda Command..." org-agenda t]
20875 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20876 ("File List for Agenda")
20877 ("Special views current file"
20878 ["TODO Tree" org-show-todo-tree t]
20879 ["Check Deadlines" org-check-deadlines t]
20880 ["Timeline" org-timeline t]
20881 ["Tags/Property tree" org-match-sparse-tree t])
20882 "--"
20883 ["Export/Publish..." org-export-dispatch t]
20884 ("LaTeX"
20885 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20886 :selected org-cdlatex-mode]
20887 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20888 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20889 ["Modify math symbol" org-cdlatex-math-modify
20890 (org-inside-LaTeX-fragment-p)]
20891 ["Insert citation" org-reftex-citation t]
20892 "--"
20893 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20894 "--"
20895 ("MobileOrg"
20896 ["Push Files and Views" org-mobile-push t]
20897 ["Get Captured and Flagged" org-mobile-pull t]
20898 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20899 "--"
20900 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20901 "--"
20902 ("Documentation"
20903 ["Show Version" org-version t]
20904 ["Info Documentation" org-info t])
20905 ("Customize"
20906 ["Browse Org Group" org-customize t]
20907 "--"
20908 ["Expand This Menu" org-create-customize-menu
20909 (fboundp 'customize-menu-create)])
20910 ["Send bug report" org-submit-bug-report t]
20911 "--"
20912 ("Refresh/Reload"
20913 ["Refresh setup current buffer" org-mode-restart t]
20914 ["Reload Org (after update)" org-reload t]
20915 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20918 (defun org-info (&optional node)
20919 "Read documentation for Org-mode in the info system.
20920 With optional NODE, go directly to that node."
20921 (interactive)
20922 (info (format "(org)%s" (or node ""))))
20924 ;;;###autoload
20925 (defun org-submit-bug-report ()
20926 "Submit a bug report on Org-mode via mail.
20928 Don't hesitate to report any problems or inaccurate documentation.
20930 If you don't have setup sending mail from (X)Emacs, please copy the
20931 output buffer into your mail program, as it gives us important
20932 information about your Org-mode version and configuration."
20933 (interactive)
20934 (require 'reporter)
20935 (org-load-modules-maybe)
20936 (org-require-autoloaded-modules)
20937 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20938 (reporter-submit-bug-report
20939 "emacs-orgmode@gnu.org"
20940 (org-version nil 'full)
20941 (let (list)
20942 (save-window-excursion
20943 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20944 (delete-other-windows)
20945 (erase-buffer)
20946 (insert "You are about to submit a bug report to the Org-mode mailing list.
20948 We would like to add your full Org-mode and Outline configuration to the
20949 bug report. This greatly simplifies the work of the maintainer and
20950 other experts on the mailing list.
20952 HOWEVER, some variables you have customized may contain private
20953 information. The names of customers, colleagues, or friends, might
20954 appear in the form of file names, tags, todo states, or search strings.
20955 If you answer yes to the prompt, you might want to check and remove
20956 such private information before sending the email.")
20957 (add-text-properties (point-min) (point-max) '(face org-warning))
20958 (when (yes-or-no-p "Include your Org-mode configuration ")
20959 (mapatoms
20960 (lambda (v)
20961 (and (boundp v)
20962 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20963 (or (and (symbol-value v)
20964 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20965 (and
20966 (get v 'custom-type) (get v 'standard-value)
20967 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20968 (push v list)))))
20969 (kill-buffer (get-buffer "*Warn about privacy*"))
20970 list))
20971 nil nil
20972 "Remember to cover the basics, that is, what you expected to happen and
20973 what in fact did happen. You don't know how to make a good report? See
20975 http://orgmode.org/manual/Feedback.html#Feedback
20977 Your bug report will be posted to the Org-mode mailing list.
20978 ------------------------------------------------------------------------")
20979 (save-excursion
20980 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20981 (replace-match "\\1Bug: \\3 [\\2]")))))
20984 (defun org-install-agenda-files-menu ()
20985 (let ((bl (buffer-list)))
20986 (save-excursion
20987 (while bl
20988 (set-buffer (pop bl))
20989 (if (derived-mode-p 'org-mode) (setq bl nil)))
20990 (when (derived-mode-p 'org-mode)
20991 (easy-menu-change
20992 '("Org") "File List for Agenda"
20993 (append
20994 (list
20995 ["Edit File List" (org-edit-agenda-file-list) t]
20996 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20997 ["Remove Current File from List" org-remove-file t]
20998 ["Cycle through agenda files" org-cycle-agenda-files t]
20999 ["Occur in all agenda files" org-occur-in-agenda-files t]
21000 "--")
21001 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21003 ;;;; Documentation
21005 (defun org-require-autoloaded-modules ()
21006 (interactive)
21007 (mapc 'require
21008 '(org-agenda org-archive org-attach org-clock org-colview org-id
21009 org-remember org-table org-timer)))
21011 ;;;###autoload
21012 (defun org-reload (&optional uncompiled)
21013 "Reload all org lisp files.
21014 With prefix arg UNCOMPILED, load the uncompiled versions."
21015 (interactive "P")
21016 (require 'loadhist)
21017 (let* ((org-dir (org-find-library-dir "org"))
21018 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21019 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21020 (remove-re (mapconcat 'identity
21021 (mapcar (lambda (f) (concat "^" f "$"))
21022 (list (if (featurep 'xemacs)
21023 "org-colview"
21024 "org-colview-xemacs")
21025 "org" "org-loaddefs" "org-version"))
21026 "\\|"))
21027 (feats (delete-dups
21028 (mapcar 'file-name-sans-extension
21029 (mapcar 'file-name-nondirectory
21030 (delq nil
21031 (mapcar 'feature-file
21032 features))))))
21033 (lfeat (append
21034 (sort
21035 (setq feats
21036 (delq nil (mapcar
21037 (lambda (f)
21038 (if (and (string-match feature-re f)
21039 (not (string-match remove-re f)))
21040 f nil))
21041 feats)))
21042 'string-lessp)
21043 (list "org-version" "org")))
21044 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21045 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21046 load-uncore load-misses)
21047 (setq load-misses
21048 (delq 't
21049 (mapcar (lambda (f)
21050 (or (org-load-noerror-mustsuffix (concat org-dir f))
21051 (and (string= org-dir contrib-dir)
21052 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21053 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21054 (add-to-list 'load-uncore f 'append)
21057 lfeat)))
21058 (if load-uncore
21059 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21060 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21061 (if load-misses
21062 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21063 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21064 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21066 ;;;###autoload
21067 (defun org-customize ()
21068 "Call the customize function with org as argument."
21069 (interactive)
21070 (org-load-modules-maybe)
21071 (org-require-autoloaded-modules)
21072 (customize-browse 'org))
21074 (defun org-create-customize-menu ()
21075 "Create a full customization menu for Org-mode, insert it into the menu."
21076 (interactive)
21077 (org-load-modules-maybe)
21078 (org-require-autoloaded-modules)
21079 (if (fboundp 'customize-menu-create)
21080 (progn
21081 (easy-menu-change
21082 '("Org") "Customize"
21083 `(["Browse Org group" org-customize t]
21084 "--"
21085 ,(customize-menu-create 'org)
21086 ["Set" Custom-set t]
21087 ["Save" Custom-save t]
21088 ["Reset to Current" Custom-reset-current t]
21089 ["Reset to Saved" Custom-reset-saved t]
21090 ["Reset to Standard Settings" Custom-reset-standard t]))
21091 (message "\"Org\"-menu now contains full customization menu"))
21092 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21094 ;;;; Miscellaneous stuff
21096 ;;; Generally useful functions
21098 (defun org-get-at-bol (property)
21099 "Get text property PROPERTY at beginning of line."
21100 (get-text-property (point-at-bol) property))
21102 (defun org-find-text-property-in-string (prop s)
21103 "Return the first non-nil value of property PROP in string S."
21104 (or (get-text-property 0 prop s)
21105 (get-text-property (or (next-single-property-change 0 prop s) 0)
21106 prop s)))
21108 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21109 "Display the given MESSAGE as a warning."
21110 (if (fboundp 'display-warning)
21111 (display-warning 'org message
21112 (if (featurep 'xemacs) 'warning :warning))
21113 (let ((buf (get-buffer-create "*Org warnings*")))
21114 (with-current-buffer buf
21115 (goto-char (point-max))
21116 (insert "Warning (Org): " message)
21117 (unless (bolp)
21118 (newline)))
21119 (display-buffer buf)
21120 (sit-for 0))))
21122 (defun org-eval (form)
21123 "Eval FORM and return result."
21124 (condition-case error
21125 (eval form)
21126 (error (format "%%![Error: %s]" error))))
21128 (defun org-in-clocktable-p ()
21129 "Check if the cursor is in a clocktable."
21130 (let ((pos (point)) start)
21131 (save-excursion
21132 (end-of-line 1)
21133 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21134 (setq start (match-beginning 0))
21135 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21136 (>= (match-end 0) pos)
21137 start))))
21139 (defun org-in-commented-line ()
21140 "Is point in a line starting with `#'?"
21141 (equal (char-after (point-at-bol)) ?#))
21143 (defun org-in-indented-comment-line ()
21144 "Is point in a line starting with `#' after some white space?"
21145 (save-excursion
21146 (save-match-data
21147 (goto-char (point-at-bol))
21148 (looking-at "[ \t]*#"))))
21150 (defun org-in-verbatim-emphasis ()
21151 (save-match-data
21152 (and (org-in-regexp org-emph-re 2)
21153 (>= (point) (match-beginning 3))
21154 (<= (point) (match-end 4))
21155 (member (match-string 3) '("=" "~")))))
21157 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21158 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21159 (if (and marker (marker-buffer marker)
21160 (buffer-live-p (marker-buffer marker)))
21161 (progn
21162 (org-pop-to-buffer-same-window (marker-buffer marker))
21163 (if (or (> marker (point-max)) (< marker (point-min)))
21164 (widen))
21165 (goto-char marker)
21166 (org-show-context 'org-goto))
21167 (if bookmark
21168 (bookmark-jump bookmark)
21169 (error "Cannot find location"))))
21171 (defun org-quote-csv-field (s)
21172 "Quote field for inclusion in CSV material."
21173 (if (string-match "[\",]" s)
21174 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21177 (defun org-force-self-insert (N)
21178 "Needed to enforce self-insert under remapping."
21179 (interactive "p")
21180 (self-insert-command N))
21182 (defun org-string-width (s)
21183 "Compute width of string, ignoring invisible characters.
21184 This ignores character with invisibility property `org-link', and also
21185 characters with property `org-cwidth', because these will become invisible
21186 upon the next fontification round."
21187 (let (b l)
21188 (when (or (eq t buffer-invisibility-spec)
21189 (assq 'org-link buffer-invisibility-spec))
21190 (while (setq b (text-property-any 0 (length s)
21191 'invisible 'org-link s))
21192 (setq s (concat (substring s 0 b)
21193 (substring s (or (next-single-property-change
21194 b 'invisible s) (length s)))))))
21195 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21196 (setq s (concat (substring s 0 b)
21197 (substring s (or (next-single-property-change
21198 b 'org-cwidth s) (length s))))))
21199 (setq l (string-width s) b -1)
21200 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21201 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21204 (defun org-shorten-string (s maxlength)
21205 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21206 If the string is shorter or has length MAXLENGTH, just return the
21207 original string. If it is longer, the functions finds a space in the
21208 string, breaks this string off at that locations and adds three dots
21209 as ellipsis. Including the ellipsis, the string will not be longer
21210 than MAXLENGTH. If finding a good breaking point in the string does
21211 not work, the string is just chopped off in the middle of a word
21212 if necessary."
21213 (if (<= (length s) maxlength)
21215 (let* ((n (max (- maxlength 4) 1))
21216 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21217 (if (string-match re s)
21218 (concat (match-string 1 s) "...")
21219 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21221 (defun org-get-indentation (&optional line)
21222 "Get the indentation of the current line, interpreting tabs.
21223 When LINE is given, assume it represents a line and compute its indentation."
21224 (if line
21225 (if (string-match "^ *" (org-remove-tabs line))
21226 (match-end 0))
21227 (save-excursion
21228 (beginning-of-line 1)
21229 (skip-chars-forward " \t")
21230 (current-column))))
21232 (defun org-get-string-indentation (s)
21233 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21234 (let ((n -1) (i 0) (w tab-width) c)
21235 (catch 'exit
21236 (while (< (setq n (1+ n)) (length s))
21237 (setq c (aref s n))
21238 (cond ((= c ?\ ) (setq i (1+ i)))
21239 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21240 (t (throw 'exit t)))))
21243 (defun org-remove-tabs (s &optional width)
21244 "Replace tabulators in S with spaces.
21245 Assumes that s is a single line, starting in column 0."
21246 (setq width (or width tab-width))
21247 (while (string-match "\t" s)
21248 (setq s (replace-match
21249 (make-string
21250 (- (* width (/ (+ (match-beginning 0) width) width))
21251 (match-beginning 0)) ?\ )
21252 t t s)))
21255 (defun org-fix-indentation (line ind)
21256 "Fix indentation in LINE.
21257 IND is a cons cell with target and minimum indentation.
21258 If the current indentation in LINE is smaller than the minimum,
21259 leave it alone. If it is larger than ind, set it to the target."
21260 (let* ((l (org-remove-tabs line))
21261 (i (org-get-indentation l))
21262 (i1 (car ind)) (i2 (cdr ind)))
21263 (if (>= i i2) (setq l (substring line i2)))
21264 (if (> i1 0)
21265 (concat (make-string i1 ?\ ) l)
21266 l)))
21268 (defun org-remove-indentation (code &optional n)
21269 "Remove the maximum common indentation from the lines in CODE.
21270 N may optionally be the number of spaces to remove."
21271 (with-temp-buffer
21272 (insert code)
21273 (org-do-remove-indentation n)
21274 (buffer-string)))
21276 (defun org-do-remove-indentation (&optional n)
21277 "Remove the maximum common indentation from the buffer."
21278 (untabify (point-min) (point-max))
21279 (let ((min 10000) re)
21280 (if n
21281 (setq min n)
21282 (goto-char (point-min))
21283 (while (re-search-forward "^ *[^ \n]" nil t)
21284 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21285 (unless (or (= min 0) (= min 10000))
21286 (setq re (format "^ \\{%d\\}" min))
21287 (goto-char (point-min))
21288 (while (re-search-forward re nil t)
21289 (replace-match "")
21290 (end-of-line 1))
21291 min)))
21293 (defun org-fill-template (template alist)
21294 "Find each %key of ALIST in TEMPLATE and replace it."
21295 (let ((case-fold-search nil)
21296 entry key value)
21297 (setq alist (sort (copy-sequence alist)
21298 (lambda (a b) (< (length (car a)) (length (car b))))))
21299 (while (setq entry (pop alist))
21300 (setq template
21301 (replace-regexp-in-string
21302 (concat "%" (regexp-quote (car entry)))
21303 (or (cdr entry) "") template t t)))
21304 template))
21306 (defun org-base-buffer (buffer)
21307 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21308 (if (not buffer)
21309 buffer
21310 (or (buffer-base-buffer buffer)
21311 buffer)))
21313 (defun org-trim (s)
21314 "Remove whitespace at beginning and end of string."
21315 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21316 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21319 (defun org-wrap (string &optional width lines)
21320 "Wrap string to either a number of lines, or a width in characters.
21321 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21322 that costs. If there is a word longer than WIDTH, the text is actually
21323 wrapped to the length of that word.
21324 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21325 many lines, whatever width that takes.
21326 The return value is a list of lines, without newlines at the end."
21327 (let* ((words (org-split-string string "[ \t\n]+"))
21328 (maxword (apply 'max (mapcar 'org-string-width words)))
21329 w ll)
21330 (cond (width
21331 (org-do-wrap words (max maxword width)))
21332 (lines
21333 (setq w maxword)
21334 (setq ll (org-do-wrap words maxword))
21335 (if (<= (length ll) lines)
21337 (setq ll words)
21338 (while (> (length ll) lines)
21339 (setq w (1+ w))
21340 (setq ll (org-do-wrap words w)))
21341 ll))
21342 (t (error "Cannot wrap this")))))
21344 (defun org-do-wrap (words width)
21345 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21346 (let (lines line)
21347 (while words
21348 (setq line (pop words))
21349 (while (and words (< (+ (length line) (length (car words))) width))
21350 (setq line (concat line " " (pop words))))
21351 (setq lines (push line lines)))
21352 (nreverse lines)))
21354 (defun org-split-string (string &optional separators)
21355 "Splits STRING into substrings at SEPARATORS.
21356 No empty strings are returned if there are matches at the beginning
21357 and end of string."
21358 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21359 (start 0)
21360 notfirst
21361 (list nil))
21362 (while (and (string-match rexp string
21363 (if (and notfirst
21364 (= start (match-beginning 0))
21365 (< start (length string)))
21366 (1+ start) start))
21367 (< (match-beginning 0) (length string)))
21368 (setq notfirst t)
21369 (or (eq (match-beginning 0) 0)
21370 (and (eq (match-beginning 0) (match-end 0))
21371 (eq (match-beginning 0) start))
21372 (setq list
21373 (cons (substring string start (match-beginning 0))
21374 list)))
21375 (setq start (match-end 0)))
21376 (or (eq start (length string))
21377 (setq list
21378 (cons (substring string start)
21379 list)))
21380 (nreverse list)))
21382 (defun org-quote-vert (s)
21383 "Replace \"|\" with \"\\vert\"."
21384 (while (string-match "|" s)
21385 (setq s (replace-match "\\vert" t t s)))
21388 (defun org-uuidgen-p (s)
21389 "Is S an ID created by UUIDGEN?"
21390 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21392 (defun org-in-src-block-p (&optional inside)
21393 "Whether point is in a code source block.
21394 When INSIDE is non-nil, don't consider we are within a src block
21395 when point is at #+BEGIN_SRC or #+END_SRC."
21396 (let ((case-fold-search t) ov)
21397 (or (and (setq ov (overlays-at (point)))
21398 (memq 'org-block-background
21399 (overlay-properties (car ov))))
21400 (and (not inside)
21401 (save-match-data
21402 (save-excursion
21403 (beginning-of-line)
21404 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21406 (defun org-context ()
21407 "Return a list of contexts of the current cursor position.
21408 If several contexts apply, all are returned.
21409 Each context entry is a list with a symbol naming the context, and
21410 two positions indicating start and end of the context. Possible
21411 contexts are:
21413 :headline anywhere in a headline
21414 :headline-stars on the leading stars in a headline
21415 :todo-keyword on a TODO keyword (including DONE) in a headline
21416 :tags on the TAGS in a headline
21417 :priority on the priority cookie in a headline
21418 :item on the first line of a plain list item
21419 :item-bullet on the bullet/number of a plain list item
21420 :checkbox on the checkbox in a plain list item
21421 :table in an org-mode table
21422 :table-special on a special filed in a table
21423 :table-table in a table.el table
21424 :clocktable in a clocktable
21425 :src-block in a source block
21426 :link on a hyperlink
21427 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21428 :target on a <<target>>
21429 :radio-target on a <<<radio-target>>>
21430 :latex-fragment on a LaTeX fragment
21431 :latex-preview on a LaTeX fragment with overlaid preview image
21433 This function expects the position to be visible because it uses font-lock
21434 faces as a help to recognize the following contexts: :table-special, :link,
21435 and :keyword."
21436 (let* ((f (get-text-property (point) 'face))
21437 (faces (if (listp f) f (list f)))
21438 (case-fold-search t)
21439 (p (point)) clist o)
21440 ;; First the large context
21441 (cond
21442 ((org-at-heading-p t)
21443 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21444 (when (progn
21445 (beginning-of-line 1)
21446 (looking-at org-todo-line-tags-regexp))
21447 (push (org-point-in-group p 1 :headline-stars) clist)
21448 (push (org-point-in-group p 2 :todo-keyword) clist)
21449 (push (org-point-in-group p 4 :tags) clist))
21450 (goto-char p)
21451 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21452 (if (looking-at "\\[#[A-Z0-9]\\]")
21453 (push (org-point-in-group p 0 :priority) clist)))
21455 ((org-at-item-p)
21456 (push (org-point-in-group p 2 :item-bullet) clist)
21457 (push (list :item (point-at-bol)
21458 (save-excursion (org-end-of-item) (point)))
21459 clist)
21460 (and (org-at-item-checkbox-p)
21461 (push (org-point-in-group p 0 :checkbox) clist)))
21463 ((org-at-table-p)
21464 (push (list :table (org-table-begin) (org-table-end)) clist)
21465 (if (memq 'org-formula faces)
21466 (push (list :table-special
21467 (previous-single-property-change p 'face)
21468 (next-single-property-change p 'face)) clist)))
21469 ((org-at-table-p 'any)
21470 (push (list :table-table) clist)))
21471 (goto-char p)
21473 (let ((case-fold-search t))
21474 ;; New the "medium" contexts: clocktables, source blocks
21475 (cond ((org-in-clocktable-p)
21476 (push (list :clocktable
21477 (and (or (looking-at "#\\+BEGIN: clocktable")
21478 (search-backward "#+BEGIN: clocktable" nil t))
21479 (match-beginning 0))
21480 (and (re-search-forward "#\\+END:?" nil t)
21481 (match-end 0))) clist))
21482 ((org-in-src-block-p)
21483 (push (list :src-block
21484 (and (or (looking-at "#\\+BEGIN_SRC")
21485 (search-backward "#+BEGIN_SRC" nil t))
21486 (match-beginning 0))
21487 (and (search-forward "#+END_SRC" nil t)
21488 (match-beginning 0))) clist))))
21489 (goto-char p)
21491 ;; Now the small context
21492 (cond
21493 ((org-at-timestamp-p)
21494 (push (org-point-in-group p 0 :timestamp) clist))
21495 ((memq 'org-link faces)
21496 (push (list :link
21497 (previous-single-property-change p 'face)
21498 (next-single-property-change p 'face)) clist))
21499 ((memq 'org-special-keyword faces)
21500 (push (list :keyword
21501 (previous-single-property-change p 'face)
21502 (next-single-property-change p 'face)) clist))
21503 ((org-at-target-p)
21504 (push (org-point-in-group p 0 :target) clist)
21505 (goto-char (1- (match-beginning 0)))
21506 (if (looking-at org-radio-target-regexp)
21507 (push (org-point-in-group p 0 :radio-target) clist))
21508 (goto-char p))
21509 ((setq o (car (delq nil
21510 (mapcar
21511 (lambda (x)
21512 (if (memq x org-latex-fragment-image-overlays) x))
21513 (overlays-at (point))))))
21514 (push (list :latex-fragment
21515 (overlay-start o) (overlay-end o)) clist)
21516 (push (list :latex-preview
21517 (overlay-start o) (overlay-end o)) clist))
21518 ((org-inside-LaTeX-fragment-p)
21519 ;; FIXME: positions wrong.
21520 (push (list :latex-fragment (point) (point)) clist)))
21522 (setq clist (nreverse (delq nil clist)))
21523 clist))
21525 ;; FIXME: Compare with at-regexp-p Do we need both?
21526 (defun org-in-regexp (re &optional nlines visually)
21527 "Check if point is inside a match of regexp.
21528 Normally only the current line is checked, but you can include NLINES extra
21529 lines both before and after point into the search.
21530 If VISUALLY is set, require that the cursor is not after the match but
21531 really on, so that the block visually is on the match."
21532 (catch 'exit
21533 (let ((pos (point))
21534 (eol (point-at-eol (+ 1 (or nlines 0))))
21535 (inc (if visually 1 0)))
21536 (save-excursion
21537 (beginning-of-line (- 1 (or nlines 0)))
21538 (while (re-search-forward re eol t)
21539 (if (and (<= (match-beginning 0) pos)
21540 (>= (+ inc (match-end 0)) pos))
21541 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21543 (defun org-at-regexp-p (regexp)
21544 "Is point inside a match of REGEXP in the current line?"
21545 (catch 'exit
21546 (save-excursion
21547 (let ((pos (point)) (end (point-at-eol)))
21548 (beginning-of-line 1)
21549 (while (re-search-forward regexp end t)
21550 (if (and (<= (match-beginning 0) pos)
21551 (>= (match-end 0) pos))
21552 (throw 'exit t)))
21553 nil))))
21555 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21556 "Non-nil when point is between matches of START-RE and END-RE.
21558 Also return a non-nil value when point is on one of the matches.
21560 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21561 buffer positions. Default values are the positions of headlines
21562 surrounding the point.
21564 The functions returns a cons cell whose car (resp. cdr) is the
21565 position before START-RE (resp. after END-RE)."
21566 (save-match-data
21567 (let ((pos (point))
21568 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21569 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21570 beg end)
21571 (save-excursion
21572 ;; Point is on a block when on START-RE or if START-RE can be
21573 ;; found before it...
21574 (and (or (org-at-regexp-p start-re)
21575 (re-search-backward start-re limit-up t))
21576 (setq beg (match-beginning 0))
21577 ;; ... and END-RE after it...
21578 (goto-char (match-end 0))
21579 (re-search-forward end-re limit-down t)
21580 (> (setq end (match-end 0)) pos)
21581 ;; ... without another START-RE in-between.
21582 (goto-char (match-beginning 0))
21583 (not (re-search-backward start-re (1+ beg) t))
21584 ;; Return value.
21585 (cons beg end))))))
21587 (defun org-in-block-p (names)
21588 "Non-nil when point belongs to a block whose name belongs to NAMES.
21590 NAMES is a list of strings containing names of blocks.
21592 Return first block name matched, or nil. Beware that in case of
21593 nested blocks, the returned name may not belong to the closest
21594 block from point."
21595 (save-match-data
21596 (catch 'exit
21597 (let ((case-fold-search t)
21598 (lim-up (save-excursion (outline-previous-heading)))
21599 (lim-down (save-excursion (outline-next-heading))))
21600 (mapc (lambda (name)
21601 (let ((n (regexp-quote name)))
21602 (when (org-between-regexps-p
21603 (concat "^[ \t]*#\\+begin_" n)
21604 (concat "^[ \t]*#\\+end_" n)
21605 lim-up lim-down)
21606 (throw 'exit n))))
21607 names))
21608 nil)))
21610 (defun org-in-drawer-p ()
21611 "Is point within a drawer?"
21612 (save-match-data
21613 (let ((case-fold-search t)
21614 (lim-up (save-excursion (outline-previous-heading)))
21615 (lim-down (save-excursion (outline-next-heading))))
21616 (org-between-regexps-p
21617 (concat "^[ \t]*:" (regexp-opt org-drawers) ":")
21618 "^[ \t]*:end:.*$"
21619 lim-up lim-down))))
21621 (defun org-occur-in-agenda-files (regexp &optional nlines)
21622 "Call `multi-occur' with buffers for all agenda files."
21623 (interactive "sOrg-files matching: \np")
21624 (let* ((files (org-agenda-files))
21625 (tnames (mapcar 'file-truename files))
21626 (extra org-agenda-text-search-extra-files)
21628 (when (eq (car extra) 'agenda-archives)
21629 (setq extra (cdr extra))
21630 (setq files (org-add-archive-files files)))
21631 (while (setq f (pop extra))
21632 (unless (member (file-truename f) tnames)
21633 (add-to-list 'files f 'append)
21634 (add-to-list 'tnames (file-truename f) 'append)))
21635 (multi-occur
21636 (mapcar (lambda (x)
21637 (with-current-buffer
21638 (or (get-file-buffer x) (find-file-noselect x))
21639 (widen)
21640 (current-buffer)))
21641 files)
21642 regexp)))
21644 (if (boundp 'occur-mode-find-occurrence-hook)
21645 ;; Emacs 23
21646 (add-hook 'occur-mode-find-occurrence-hook
21647 (lambda ()
21648 (when (derived-mode-p 'org-mode)
21649 (org-reveal))))
21650 ;; Emacs 22
21651 (defadvice occur-mode-goto-occurrence
21652 (after org-occur-reveal activate)
21653 (and (derived-mode-p 'org-mode) (org-reveal)))
21654 (defadvice occur-mode-goto-occurrence-other-window
21655 (after org-occur-reveal activate)
21656 (and (derived-mode-p 'org-mode) (org-reveal)))
21657 (defadvice occur-mode-display-occurrence
21658 (after org-occur-reveal activate)
21659 (when (derived-mode-p 'org-mode)
21660 (let ((pos (occur-mode-find-occurrence)))
21661 (with-current-buffer (marker-buffer pos)
21662 (save-excursion
21663 (goto-char pos)
21664 (org-reveal)))))))
21666 (defun org-occur-link-in-agenda-files ()
21667 "Create a link and search for it in the agendas.
21668 The link is not stored in `org-stored-links', it is just created
21669 for the search purpose."
21670 (interactive)
21671 (let ((link (condition-case nil
21672 (org-store-link nil)
21673 (error "Unable to create a link to here"))))
21674 (org-occur-in-agenda-files (regexp-quote link))))
21676 (defun org-reverse-string (string)
21677 "Return the reverse of STRING."
21678 (apply 'string (reverse (string-to-list string))))
21680 (defsubst org-uniquify (list)
21681 "Non-destructively remove duplicate elements from LIST."
21682 (let ((res (copy-sequence list))) (delete-dups res)))
21684 (defun org-uniquify-alist (alist)
21685 "Merge elements of ALIST with the same key.
21687 For example, in this alist:
21689 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21690 => '((a 1 3) (b 2))
21692 merge (a 1) and (a 3) into (a 1 3).
21694 The function returns the new ALIST."
21695 (let (rtn)
21696 (mapc
21697 (lambda (e)
21698 (let (n)
21699 (if (not (assoc (car e) rtn))
21700 (push e rtn)
21701 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21702 (setq rtn (assq-delete-all (car e) rtn))
21703 (push n rtn))))
21704 alist)
21705 rtn))
21707 (defun org-delete-all (elts list)
21708 "Remove all elements in ELTS from LIST."
21709 (while elts
21710 (setq list (delete (pop elts) list)))
21711 list)
21713 (defun org-count (cl-item cl-seq)
21714 "Count the number of occurrences of ITEM in SEQ.
21715 Taken from `count' in cl-seq.el with all keyword arguments removed."
21716 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21717 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21718 (while (< cl-start cl-end)
21719 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21720 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21721 (setq cl-start (1+ cl-start)))
21722 cl-count))
21724 (defun org-remove-if (predicate seq)
21725 "Remove everything from SEQ that fulfills PREDICATE."
21726 (let (res e)
21727 (while seq
21728 (setq e (pop seq))
21729 (if (not (funcall predicate e)) (push e res)))
21730 (nreverse res)))
21732 (defun org-remove-if-not (predicate seq)
21733 "Remove everything from SEQ that does not fulfill PREDICATE."
21734 (let (res e)
21735 (while seq
21736 (setq e (pop seq))
21737 (if (funcall predicate e) (push e res)))
21738 (nreverse res)))
21740 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21741 "Reduce two-argument FUNCTION across SEQ.
21742 Taken from `reduce' in cl-seq.el with all keyword arguments but
21743 \":initial-value\" removed."
21744 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21745 (cadr (memq :initial-value cl-keys)))
21746 (cl-seq (pop cl-seq))
21747 (t (funcall cl-func)))))
21748 (while cl-seq
21749 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21750 cl-accum))
21752 (defun org-every (pred seq)
21753 "Return true if PREDICATE is true of every element of SEQ.
21754 Adapted from `every' in cl.el."
21755 (catch 'org-every
21756 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
21759 (defun org-some (pred seq)
21760 "Return true if PREDICATE is true of any element of SEQ.
21761 Adapted from `some' in cl.el."
21762 (catch 'org-some
21763 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
21764 nil))
21766 (defun org-back-over-empty-lines ()
21767 "Move backwards over whitespace, to the beginning of the first empty line.
21768 Returns the number of empty lines passed."
21769 (let ((pos (point)))
21770 (if (cdr (assoc 'heading org-blank-before-new-entry))
21771 (skip-chars-backward " \t\n\r")
21772 (unless (eobp)
21773 (forward-line -1)))
21774 (beginning-of-line 2)
21775 (goto-char (min (point) pos))
21776 (count-lines (point) pos)))
21778 (defun org-skip-whitespace ()
21779 (skip-chars-forward " \t\n\r"))
21781 (defun org-point-in-group (point group &optional context)
21782 "Check if POINT is in match-group GROUP.
21783 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21784 match. If the match group does not exist or point is not inside it,
21785 return nil."
21786 (and (match-beginning group)
21787 (>= point (match-beginning group))
21788 (<= point (match-end group))
21789 (if context
21790 (list context (match-beginning group) (match-end group))
21791 t)))
21793 (defun org-switch-to-buffer-other-window (&rest args)
21794 "Switch to buffer in a second window on the current frame.
21795 In particular, do not allow pop-up frames.
21796 Returns the newly created buffer."
21797 (org-no-popups
21798 (apply 'switch-to-buffer-other-window args)))
21800 (defun org-combine-plists (&rest plists)
21801 "Create a single property list from all plists in PLISTS.
21802 The process starts by copying the first list, and then setting properties
21803 from the other lists. Settings in the last list are the most significant
21804 ones and overrule settings in the other lists."
21805 (let ((rtn (copy-sequence (pop plists)))
21806 p v ls)
21807 (while plists
21808 (setq ls (pop plists))
21809 (while ls
21810 (setq p (pop ls) v (pop ls))
21811 (setq rtn (plist-put rtn p v))))
21812 rtn))
21814 (defun org-replace-escapes (string table)
21815 "Replace %-escapes in STRING with values in TABLE.
21816 TABLE is an association list with keys like \"%a\" and string values.
21817 The sequences in STRING may contain normal field width and padding information,
21818 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21819 so values can contain further %-escapes if they are define later in TABLE."
21820 (let ((tbl (copy-alist table))
21821 (case-fold-search nil)
21822 (pchg 0)
21823 e re rpl)
21824 (while (setq e (pop tbl))
21825 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21826 (when (and (cdr e) (string-match re (cdr e)))
21827 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21828 (safe "SREF"))
21829 (add-text-properties 0 3 (list 'sref sref) safe)
21830 (setcdr e (replace-match safe t t (cdr e)))))
21831 (while (string-match re string)
21832 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21833 (cdr e)))
21834 (setq string (replace-match rpl t t string))))
21835 (while (setq pchg (next-property-change pchg string))
21836 (let ((sref (get-text-property pchg 'sref string)))
21837 (when (and sref (string-match "SREF" string pchg))
21838 (setq string (replace-match sref t t string)))))
21839 string))
21841 (defun org-sublist (list start end)
21842 "Return a section of LIST, from START to END.
21843 Counting starts at 1."
21844 (let (rtn (c start))
21845 (setq list (nthcdr (1- start) list))
21846 (while (and list (<= c end))
21847 (push (pop list) rtn)
21848 (setq c (1+ c)))
21849 (nreverse rtn)))
21851 (defun org-find-base-buffer-visiting (file)
21852 "Like `find-buffer-visiting' but always return the base buffer and
21853 not an indirect buffer."
21854 (let ((buf (or (get-file-buffer file)
21855 (find-buffer-visiting file))))
21856 (if buf
21857 (or (buffer-base-buffer buf) buf)
21858 nil)))
21860 (defun org-image-file-name-regexp (&optional extensions)
21861 "Return regexp matching the file names of images.
21862 If EXTENSIONS is given, only match these."
21863 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21864 (image-file-name-regexp)
21865 (let ((image-file-name-extensions
21866 (or extensions
21867 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21868 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21869 (concat "\\."
21870 (regexp-opt (nconc (mapcar 'upcase
21871 image-file-name-extensions)
21872 image-file-name-extensions)
21874 "\\'"))))
21876 (defun org-file-image-p (file &optional extensions)
21877 "Return non-nil if FILE is an image."
21878 (save-match-data
21879 (string-match (org-image-file-name-regexp extensions) file)))
21881 (defun org-get-cursor-date (&optional with-time)
21882 "Return the date at cursor in as a time.
21883 This works in the calendar and in the agenda, anywhere else it just
21884 returns the current time.
21885 If WITH-TIME is non-nil, returns the time of the event at point (in
21886 the agenda) or the current time of the day."
21887 (let (date day defd tp tm hod mod)
21888 (when with-time
21889 (setq tp (get-text-property (point) 'time))
21890 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21891 (setq hod (string-to-number (match-string 1 tp))
21892 mod (string-to-number (match-string 2 tp))))
21893 (or tp (setq hod (nth 2 (decode-time (current-time)))
21894 mod (nth 1 (decode-time (current-time))))))
21895 (cond
21896 ((eq major-mode 'calendar-mode)
21897 (setq date (calendar-cursor-to-date)
21898 defd (encode-time 0 (or mod 0) (or hod 0)
21899 (nth 1 date) (nth 0 date) (nth 2 date))))
21900 ((eq major-mode 'org-agenda-mode)
21901 (setq day (get-text-property (point) 'day))
21902 (if day
21903 (setq date (calendar-gregorian-from-absolute day)
21904 defd (encode-time 0 (or mod 0) (or hod 0)
21905 (nth 1 date) (nth 0 date) (nth 2 date))))))
21906 (or defd (current-time))))
21908 (defun org-mark-subtree (&optional up)
21909 "Mark the current subtree.
21910 This puts point at the start of the current subtree, and mark at
21911 the end. If a numeric prefix UP is given, move up into the
21912 hierarchy of headlines by UP levels before marking the subtree."
21913 (interactive "P")
21914 (org-with-limited-levels
21915 (cond ((org-at-heading-p) (beginning-of-line))
21916 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21917 (t (outline-previous-visible-heading 1))))
21918 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21919 (if (org-called-interactively-p 'any)
21920 (call-interactively 'org-mark-element)
21921 (org-mark-element)))
21924 ;;; Indentation
21926 (defun org-indent-line ()
21927 "Indent line depending on context."
21928 (interactive)
21929 (let* ((pos (point))
21930 (itemp (org-at-item-p))
21931 (case-fold-search t)
21932 (org-drawer-regexp (or org-drawer-regexp "\000"))
21933 (inline-task-p (and (featurep 'org-inlinetask)
21934 (org-inlinetask-in-task-p)))
21935 (inline-re (and inline-task-p
21936 (org-inlinetask-outline-regexp)))
21937 column)
21938 (if (and orgstruct-is-++ (eq pos (point)))
21939 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21940 (indent-according-to-mode))
21941 (beginning-of-line 1)
21942 (cond
21943 ;; Headings
21944 ((looking-at org-outline-regexp) (setq column 0))
21945 ;; Footnote definition
21946 ((looking-at org-footnote-definition-re) (setq column 0))
21947 ;; Literal examples
21948 ((looking-at "[ \t]*:\\( \\|$\\)")
21949 (setq column (org-get-indentation))) ; do nothing
21950 ;; Lists
21951 ((ignore-errors (goto-char (org-in-item-p)))
21952 (setq column (if itemp
21953 (org-get-indentation)
21954 (org-list-item-body-column (point))))
21955 (goto-char pos))
21956 ;; Drawers
21957 ((and (looking-at "[ \t]*:END:")
21958 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21959 (save-excursion
21960 (goto-char (1- (match-beginning 1)))
21961 (setq column (current-column))))
21962 ;; Special blocks
21963 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21964 (save-excursion
21965 (re-search-backward
21966 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21967 (setq column (org-get-indentation (match-string 0))))
21968 ((and (not (looking-at "[ \t]*#\\+begin_"))
21969 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21970 (save-excursion
21971 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21972 (setq column
21973 (cond ((equal (downcase (match-string 1)) "src")
21974 ;; src blocks: let `org-edit-src-exit' handle them
21975 (org-get-indentation))
21976 ((equal (downcase (match-string 1)) "example")
21977 (max (org-get-indentation)
21978 (org-get-indentation (match-string 0))))
21980 (org-get-indentation (match-string 0))))))
21981 ;; This line has nothing special, look at the previous relevant
21982 ;; line to compute indentation
21984 (beginning-of-line 0)
21985 (while (and (not (bobp))
21986 (not (looking-at org-table-line-regexp))
21987 (not (looking-at org-drawer-regexp))
21988 ;; When point started in an inline task, do not move
21989 ;; above task starting line.
21990 (not (and inline-task-p (looking-at inline-re)))
21991 ;; Skip drawers, blocks, empty lines, verbatim,
21992 ;; comments, tables, footnotes definitions, lists,
21993 ;; inline tasks.
21994 (or (and (looking-at "[ \t]*:END:")
21995 (re-search-backward org-drawer-regexp nil t))
21996 (and (looking-at "[ \t]*#\\+end_")
21997 (re-search-backward "[ \t]*#\\+begin_"nil t))
21998 (looking-at "[ \t]*[\n:#|]")
21999 (looking-at org-footnote-definition-re)
22000 (and (not inline-task-p)
22001 (featurep 'org-inlinetask)
22002 (org-inlinetask-in-task-p)
22003 (or (org-inlinetask-goto-beginning) t))))
22004 (beginning-of-line 0))
22005 (cond
22006 ;; There was a list item above.
22007 ((save-excursion
22008 (and (ignore-errors (goto-char (org-in-item-p)))
22009 (goto-char
22010 (org-list-get-top-point (org-list-struct)))))
22011 (looking-at org-list-full-item-re)
22012 (setq column (length (match-string 0))))
22013 ;; There was an heading above.
22014 ((looking-at "\\*+[ \t]+")
22015 (if (not org-adapt-indentation)
22016 (setq column 0)
22017 (goto-char (match-end 0))
22018 (setq column (current-column))))
22019 ;; A drawer had started and is unfinished
22020 ((looking-at org-drawer-regexp)
22021 (goto-char (1- (match-beginning 1)))
22022 (setq column (current-column)))
22023 ;; Else, nothing noticeable found: get indentation and go on.
22024 (t (setq column (org-get-indentation))))))
22025 ;; Now apply indentation and move cursor accordingly
22026 (goto-char pos)
22027 (if (<= (current-column) (current-indentation))
22028 (org-indent-line-to column)
22029 (save-excursion (org-indent-line-to column)))
22030 ;; Special polishing for properties, see `org-property-format'
22031 (setq column (current-column))
22032 (beginning-of-line 1)
22033 (if (looking-at org-property-re)
22034 (replace-match (concat (match-string 4)
22035 (format org-property-format
22036 (match-string 1) (match-string 3)))
22037 t t))
22038 (org-move-to-column column))))
22040 (defun org-indent-drawer ()
22041 "Indent the drawer at point."
22042 (interactive)
22043 (let ((p (point))
22044 (e (and (save-excursion (re-search-forward ":END:" nil t))
22045 (match-end 0)))
22046 (folded
22047 (save-excursion
22048 (end-of-line)
22049 (when (overlays-at (point))
22050 (member 'invisible (overlay-properties
22051 (car (overlays-at (point)))))))))
22052 (when folded (org-cycle))
22053 (indent-for-tab-command)
22054 (while (and (move-beginning-of-line 2) (< (point) e))
22055 (indent-for-tab-command))
22056 (goto-char p)
22057 (when folded (org-cycle)))
22058 (message "Drawer at point indented"))
22060 (defun org-indent-block ()
22061 "Indent the block at point."
22062 (interactive)
22063 (let ((p (point))
22064 (case-fold-search t)
22065 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22066 (match-end 0)))
22067 (folded
22068 (save-excursion
22069 (end-of-line)
22070 (when (overlays-at (point))
22071 (member 'invisible (overlay-properties
22072 (car (overlays-at (point)))))))))
22073 (when folded (org-cycle))
22074 (indent-for-tab-command)
22075 (while (and (move-beginning-of-line 2) (< (point) e))
22076 (indent-for-tab-command))
22077 (goto-char p)
22078 (when folded (org-cycle)))
22079 (message "Block at point indented"))
22081 (defun org-indent-region (start end)
22082 "Indent region."
22083 (interactive "r")
22084 (save-excursion
22085 (let ((line-end (org-current-line end)))
22086 (goto-char start)
22087 (while (< (org-current-line) line-end)
22088 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
22089 (t (call-interactively 'org-indent-line)))
22090 (move-beginning-of-line 2)))))
22093 ;;; Filling
22095 ;; We use our own fill-paragraph and auto-fill functions.
22097 ;; `org-fill-paragraph' relies on adaptive filling and context
22098 ;; checking. Appropriate `fill-prefix' is computed with
22099 ;; `org-adaptive-fill-function'.
22101 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22102 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22103 ;; `org-adaptive-fill-function' value. Internally,
22104 ;; `org-comment-line-break-function' breaks the line.
22106 ;; `org-setup-filling' installs filling and auto-filling related
22107 ;; variables during `org-mode' initialization.
22109 (defvar org-element-paragraph-separate) ; org-element.el
22110 (defun org-setup-filling ()
22111 (require 'org-element)
22112 ;; Prevent auto-fill from inserting unwanted new items.
22113 (when (boundp 'fill-nobreak-predicate)
22114 (org-set-local
22115 'fill-nobreak-predicate
22116 (org-uniquify
22117 (append fill-nobreak-predicate
22118 '(org-fill-line-break-nobreak-p
22119 org-fill-paragraph-with-timestamp-nobreak-p)))))
22120 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22121 (org-set-local 'paragraph-start paragraph-ending)
22122 (org-set-local 'paragraph-separate paragraph-ending))
22123 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22124 (org-set-local 'auto-fill-inhibit-regexp nil)
22125 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22126 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22127 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22129 (defun org-fill-line-break-nobreak-p ()
22130 "Non-nil when a new line at point would create an Org line break."
22131 (save-excursion
22132 (skip-chars-backward "[ \t]")
22133 (skip-chars-backward "\\\\")
22134 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22136 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22137 "Non-nil when a new line at point would split a timestamp."
22138 (and (org-at-timestamp-p t)
22139 (not (looking-at org-ts-regexp-both))))
22141 (declare-function message-in-body-p "message" ())
22142 (defvar orgtbl-line-start-regexp) ; From org-table.el
22143 (defun org-adaptive-fill-function ()
22144 "Compute a fill prefix for the current line.
22145 Return fill prefix, as a string, or nil if current line isn't
22146 meant to be filled."
22147 (let (prefix)
22148 (catch 'exit
22149 (when (derived-mode-p 'message-mode)
22150 (save-excursion
22151 (beginning-of-line)
22152 (cond ((or (not (message-in-body-p))
22153 (looking-at orgtbl-line-start-regexp))
22154 (throw 'exit nil))
22155 ((looking-at message-cite-prefix-regexp)
22156 (throw 'exit (match-string-no-properties 0)))
22157 ((looking-at org-outline-regexp)
22158 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22159 (org-with-wide-buffer
22160 (let* ((p (line-beginning-position))
22161 (element (save-excursion
22162 (beginning-of-line)
22163 (or (ignore-errors (org-element-at-point))
22164 (user-error "An element cannot be parsed line %d"
22165 (line-number-at-pos (point))))))
22166 (type (org-element-type element))
22167 (post-affiliated (org-element-property :post-affiliated element)))
22168 (unless (and post-affiliated (< p post-affiliated))
22169 (case type
22170 (comment (looking-at "[ \t]*# ?") (match-string 0))
22171 (footnote-definition "")
22172 ((item plain-list)
22173 (make-string (org-list-item-body-column
22174 (or post-affiliated
22175 (org-element-property :begin element)))
22176 ? ))
22177 (paragraph
22178 ;; Fill prefix is usually the same as the current line,
22179 ;; except if the paragraph is at the beginning of an item.
22180 (let ((parent (org-element-property :parent element)))
22181 (cond ((eq (org-element-type parent) 'item)
22182 (make-string (org-list-item-body-column
22183 (org-element-property :begin parent))
22184 ? ))
22185 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22186 (match-string 0))
22187 (t ""))))
22188 (comment-block
22189 ;; Only fill contents if P is within block boundaries.
22190 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22191 (forward-line)
22192 (point)))
22193 (cend (save-excursion
22194 (goto-char (org-element-property :end element))
22195 (skip-chars-backward " \r\t\n")
22196 (line-beginning-position))))
22197 (when (and (>= p cbeg) (< p cend))
22198 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22199 (match-string 0)
22200 "")))))))))))
22202 (declare-function message-goto-body "message" ())
22203 (defvar message-cite-prefix-regexp) ; From message.el
22204 (defun org-fill-paragraph (&optional justify)
22205 "Fill element at point, when applicable.
22207 This function only applies to comment blocks, comments, example
22208 blocks and paragraphs. Also, as a special case, re-align table
22209 when point is at one.
22211 If JUSTIFY is non-nil (interactively, with prefix argument),
22212 justify as well. If `sentence-end-double-space' is non-nil, then
22213 period followed by one space does not end a sentence, so don't
22214 break a line there. The variable `fill-column' controls the
22215 width for filling.
22217 For convenience, when point is at a plain list, an item or
22218 a footnote definition, try to fill the first paragraph within."
22219 (interactive)
22220 (if (and (derived-mode-p 'message-mode)
22221 (or (not (message-in-body-p))
22222 (save-excursion (move-beginning-of-line 1)
22223 (looking-at message-cite-prefix-regexp))))
22224 ;; First ensure filling is correct in message-mode.
22225 (let ((fill-paragraph-function
22226 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22227 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22228 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22229 (paragraph-separate
22230 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22231 (fill-paragraph nil))
22232 (with-syntax-table org-mode-transpose-word-syntax-table
22233 ;; Move to end of line in order to get the first paragraph
22234 ;; within a plain list or a footnote definition.
22235 (let ((element (save-excursion
22236 (end-of-line)
22237 (or (ignore-errors (org-element-at-point))
22238 (user-error "An element cannot be parsed line %d"
22239 (line-number-at-pos (point)))))))
22240 ;; First check if point is in a blank line at the beginning of
22241 ;; the buffer. In that case, ignore filling.
22242 (case (org-element-type element)
22243 ;; Use major mode filling function is src blocks.
22244 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22245 ;; Align Org tables, leave table.el tables as-is.
22246 (table-row (org-table-align) t)
22247 (table
22248 (when (eq (org-element-property :type element) 'org)
22249 (save-excursion
22250 (goto-char (org-element-property :post-affiliated element))
22251 (org-table-align)))
22253 (paragraph
22254 ;; Paragraphs may contain `line-break' type objects.
22255 (let ((beg (max (point-min)
22256 (org-element-property :contents-begin element)))
22257 (end (min (point-max)
22258 (org-element-property :contents-end element))))
22259 ;; Do nothing if point is at an affiliated keyword.
22260 (if (< (line-end-position) beg) t
22261 (when (derived-mode-p 'message-mode)
22262 ;; In `message-mode', do not fill following citation
22263 ;; in current paragraph nor text before message body.
22264 (let ((body-start (save-excursion (message-goto-body))))
22265 (when body-start (setq beg (max body-start beg))))
22266 (when (save-excursion
22267 (re-search-forward
22268 (concat "^" message-cite-prefix-regexp) end t))
22269 (setq end (match-beginning 0))))
22270 ;; Fill paragraph, taking line breaks into account.
22271 ;; For that, slice the paragraph using line breaks as
22272 ;; separators, and fill the parts in reverse order to
22273 ;; avoid messing with markers.
22274 (save-excursion
22275 (goto-char end)
22276 (mapc
22277 (lambda (pos)
22278 (fill-region-as-paragraph pos (point) justify)
22279 (goto-char pos))
22280 ;; Find the list of ending positions for line breaks
22281 ;; in the current paragraph. Add paragraph
22282 ;; beginning to include first slice.
22283 (nreverse
22284 (cons beg
22285 (org-element-map
22286 (org-element--parse-objects
22287 beg end nil (org-element-restriction 'paragraph))
22288 'line-break
22289 (lambda (lb) (org-element-property :end lb)))))))
22290 t)))
22291 ;; Contents of `comment-block' type elements should be
22292 ;; filled as plain text, but only if point is within block
22293 ;; markers.
22294 (comment-block
22295 (let* ((case-fold-search t)
22296 (beg (save-excursion
22297 (goto-char (org-element-property :begin element))
22298 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22299 (forward-line)
22300 (point)))
22301 (end (save-excursion
22302 (goto-char (org-element-property :end element))
22303 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22304 (line-beginning-position))))
22305 (when (and (>= (point) beg) (< (point) end))
22306 (fill-region-as-paragraph
22307 (save-excursion
22308 (end-of-line)
22309 (re-search-backward "^[ \t]*$" beg 'move)
22310 (line-beginning-position))
22311 (save-excursion
22312 (beginning-of-line)
22313 (re-search-forward "^[ \t]*$" end 'move)
22314 (line-beginning-position))
22315 justify)))
22317 ;; Fill comments.
22318 (comment (fill-comment-paragraph justify))
22319 ;; Ignore every other element.
22320 (otherwise t))))))
22322 (defun org-auto-fill-function ()
22323 "Auto-fill function."
22324 ;; Check if auto-filling is meaningful.
22325 (let ((fc (current-fill-column)))
22326 (when (and fc (> (current-column) fc))
22327 (let* ((fill-prefix (org-adaptive-fill-function))
22328 ;; Enforce empty fill prefix, if required. Otherwise, it
22329 ;; will be computed again.
22330 (adaptive-fill-mode (not (equal fill-prefix ""))))
22331 (when fill-prefix (do-auto-fill))))))
22333 (defun org-comment-line-break-function (&optional soft)
22334 "Break line at point and indent, continuing comment if within one.
22335 The inserted newline is marked hard if variable
22336 `use-hard-newlines' is true, unless optional argument SOFT is
22337 non-nil."
22338 (if soft (insert-and-inherit ?\n) (newline 1))
22339 (save-excursion (forward-char -1) (delete-horizontal-space))
22340 (delete-horizontal-space)
22341 (indent-to-left-margin)
22342 (insert-before-markers-and-inherit fill-prefix))
22345 ;;; Comments
22347 ;; Org comments syntax is quite complex. It requires the entire line
22348 ;; to be just a comment. Also, even with the right syntax at the
22349 ;; beginning of line, some some elements (i.e. verse-block or
22350 ;; example-block) don't accept comments. Usual Emacs comment commands
22351 ;; cannot cope with those requirements. Therefore, Org replaces them.
22353 ;; Org still relies on `comment-dwim', but cannot trust
22354 ;; `comment-only-p'. So, `comment-region-function' and
22355 ;; `uncomment-region-function' both point
22356 ;; to`org-comment-or-uncomment-region'. Eventually,
22357 ;; `org-insert-comment' takes care of insertion of comments at the
22358 ;; beginning of line.
22360 ;; `org-setup-comments-handling' install comments related variables
22361 ;; during `org-mode' initialization.
22363 (defun org-setup-comments-handling ()
22364 (interactive)
22365 (org-set-local 'comment-use-syntax nil)
22366 (org-set-local 'comment-start "# ")
22367 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22368 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22369 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22370 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22372 (defun org-insert-comment ()
22373 "Insert an empty comment above current line.
22374 If the line is empty, insert comment at its beginning."
22375 (beginning-of-line)
22376 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22377 (org-indent-line)
22378 (insert "# "))
22380 (defvar comment-empty-lines) ; From newcomment.el.
22381 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22382 "Comment or uncomment each non-blank line in the region.
22383 Uncomment each non-blank line between BEG and END if it only
22384 contains commented lines. Otherwise, comment them."
22385 (save-restriction
22386 ;; Restrict region
22387 (narrow-to-region (save-excursion (goto-char beg)
22388 (skip-chars-forward " \r\t\n" end)
22389 (line-beginning-position))
22390 (save-excursion (goto-char end)
22391 (skip-chars-backward " \r\t\n" beg)
22392 (line-end-position)))
22393 (let ((uncommentp
22394 ;; UNCOMMENTP is non-nil when every non blank line between
22395 ;; BEG and END is a comment.
22396 (save-excursion
22397 (goto-char (point-min))
22398 (while (and (not (eobp))
22399 (let ((element (org-element-at-point)))
22400 (and (eq (org-element-type element) 'comment)
22401 (goto-char (min (point-max)
22402 (org-element-property
22403 :end element)))))))
22404 (eobp))))
22405 (if uncommentp
22406 ;; Only blank lines and comments in region: uncomment it.
22407 (save-excursion
22408 (goto-char (point-min))
22409 (while (not (eobp))
22410 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22411 (replace-match "" nil nil nil 1))
22412 (forward-line)))
22413 ;; Comment each line in region.
22414 (let ((min-indent (point-max)))
22415 ;; First find the minimum indentation across all lines.
22416 (save-excursion
22417 (goto-char (point-min))
22418 (while (and (not (eobp)) (not (zerop min-indent)))
22419 (unless (looking-at "[ \t]*$")
22420 (setq min-indent (min min-indent (current-indentation))))
22421 (forward-line)))
22422 ;; Then loop over all lines.
22423 (save-excursion
22424 (goto-char (point-min))
22425 (while (not (eobp))
22426 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22427 ;; Don't get fooled by invisible text (e.g. link path)
22428 ;; when moving to column MIN-INDENT.
22429 (let ((buffer-invisibility-spec nil))
22430 (org-move-to-column min-indent t))
22431 (insert comment-start))
22432 (forward-line))))))))
22435 ;;; Planning
22437 ;; This section contains tools to operate on timestamp objects, as
22438 ;; returned by, e.g. `org-element-context'.
22440 (defun org-timestamp-has-time-p (timestamp)
22441 "Non-nil when TIMESTAMP has a time specified."
22442 (org-element-property :hour-start timestamp))
22444 (defun org-timestamp-format (timestamp format &optional end utc)
22445 "Format a TIMESTAMP element into a string.
22447 FORMAT is a format specifier to be passed to
22448 `format-time-string'.
22450 When optional argument END is non-nil, use end of date-range or
22451 time-range, if possible.
22453 When optional argument UTC is non-nil, time will be expressed as
22454 Universal Time."
22455 (format-time-string
22456 format
22457 (apply 'encode-time
22458 (cons 0
22459 (mapcar
22460 (lambda (prop) (or (org-element-property prop timestamp) 0))
22461 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22462 '(:minute-start :hour-start :day-start :month-start
22463 :year-start)))))
22464 utc))
22466 (defun org-timestamp-split-range (timestamp &optional end)
22467 "Extract a timestamp object from a date or time range.
22469 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22470 the end of the range. Otherwise, extract its start.
22472 Return a new timestamp object sharing the same parent as
22473 TIMESTAMP."
22474 (let ((type (org-element-property :type timestamp)))
22475 (if (memq type '(active inactive diary)) timestamp
22476 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22477 ;; Set new type.
22478 (org-element-put-property
22479 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22480 ;; Copy start properties over end properties if END is
22481 ;; non-nil. Otherwise, copy end properties over `start' ones.
22482 (let ((p-alist '((:minute-start . :minute-end)
22483 (:hour-start . :hour-end)
22484 (:day-start . :day-end)
22485 (:month-start . :month-end)
22486 (:year-start . :year-end))))
22487 (dolist (p-cell p-alist)
22488 (org-element-put-property
22489 split-ts
22490 (funcall (if end 'car 'cdr) p-cell)
22491 (org-element-property
22492 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22493 ;; Eventually refresh `:raw-value'.
22494 (org-element-put-property split-ts :raw-value nil)
22495 (org-element-put-property
22496 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22498 (defun org-timestamp-translate (timestamp &optional boundary)
22499 "Apply `org-translate-time' on a TIMESTAMP object.
22500 When optional argument BOUNDARY is non-nil, it is either the
22501 symbol `start' or `end'. In this case, only translate the
22502 starting or ending part of TIMESTAMP if it is a date or time
22503 range. Otherwise, translate both parts."
22504 (if (and (not boundary)
22505 (memq (org-element-property :type timestamp)
22506 '(active-range inactive-range)))
22507 (concat
22508 (org-translate-time
22509 (org-element-property :raw-value
22510 (org-timestamp-split-range timestamp)))
22511 "--"
22512 (org-translate-time
22513 (org-element-property :raw-value
22514 (org-timestamp-split-range timestamp t))))
22515 (org-translate-time
22516 (org-element-property
22517 :raw-value
22518 (if (not boundary) timestamp
22519 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22523 ;;; Other stuff.
22525 (defun org-toggle-fixed-width-section (arg)
22526 "Toggle the fixed-width export.
22527 If there is no active region, the QUOTE keyword at the current headline is
22528 inserted or removed. When present, it causes the text between this headline
22529 and the next to be exported as fixed-width text, and unmodified.
22530 If there is an active region, this command adds or removes a colon as the
22531 first character of this line. If the first character of a line is a colon,
22532 this line is also exported in fixed-width font."
22533 (interactive "P")
22534 (let* ((cc 0)
22535 (regionp (org-region-active-p))
22536 (beg (if regionp (region-beginning) (point)))
22537 (end (if regionp (region-end)))
22538 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22539 (case-fold-search nil)
22540 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22541 off)
22542 (if regionp
22543 (save-excursion
22544 (goto-char beg)
22545 (setq cc (current-column))
22546 (beginning-of-line 1)
22547 (setq off (looking-at re))
22548 (while (> nlines 0)
22549 (setq nlines (1- nlines))
22550 (beginning-of-line 1)
22551 (cond
22552 (arg
22553 (org-move-to-column cc t)
22554 (insert ": \n")
22555 (forward-line -1))
22556 ((and off (looking-at re))
22557 (replace-match "" t t nil 1))
22558 ((not off) (org-move-to-column cc t) (insert ": ")))
22559 (forward-line 1)))
22560 (save-excursion
22561 (org-back-to-heading)
22562 (cond
22563 ((looking-at (format org-heading-keyword-regexp-format
22564 org-quote-string))
22565 (goto-char (match-end 1))
22566 (looking-at (concat " +" org-quote-string))
22567 (replace-match "" t t)
22568 (when (eolp) (insert " ")))
22569 ((looking-at org-outline-regexp)
22570 (goto-char (match-end 0))
22571 (insert org-quote-string " ")))))))
22573 (defun org-reftex-citation ()
22574 "Use reftex-citation to insert a citation into the buffer.
22575 This looks for a line like
22577 #+BIBLIOGRAPHY: foo plain option:-d
22579 and derives from it that foo.bib is the bibliography file relevant
22580 for this document. It then installs the necessary environment for RefTeX
22581 to work in this buffer and calls `reftex-citation' to insert a citation
22582 into the buffer.
22584 Export of such citations to both LaTeX and HTML is handled by the contributed
22585 package ox-bibtex by Taru Karttunen."
22586 (interactive)
22587 (let ((reftex-docstruct-symbol 'rds)
22588 (reftex-cite-format "\\cite{%l}")
22589 rds bib)
22590 (save-excursion
22591 (save-restriction
22592 (widen)
22593 (let ((case-fold-search t)
22594 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22595 (if (not (save-excursion
22596 (or (re-search-forward re nil t)
22597 (re-search-backward re nil t))))
22598 (error "No bibliography defined in file")
22599 (setq bib (concat (match-string 1) ".bib")
22600 rds (list (list 'bib bib)))))))
22601 (call-interactively 'reftex-citation)))
22603 ;;;; Functions extending outline functionality
22605 (defun org-beginning-of-line (&optional arg)
22606 "Go to the beginning of the current line. If that is invisible, continue
22607 to a visible line beginning. This makes the function of C-a more intuitive.
22608 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22609 first attempt, and only move to after the tags when the cursor is already
22610 beyond the end of the headline."
22611 (interactive "P")
22612 (let ((pos (point))
22613 (special (if (consp org-special-ctrl-a/e)
22614 (car org-special-ctrl-a/e)
22615 org-special-ctrl-a/e))
22616 refpos)
22617 (if (org-bound-and-true-p visual-line-mode)
22618 (beginning-of-visual-line 1)
22619 (beginning-of-line 1))
22620 (if (and arg (fboundp 'move-beginning-of-line))
22621 (call-interactively 'move-beginning-of-line)
22622 (if (bobp)
22624 (backward-char 1)
22625 (if (org-truely-invisible-p)
22626 (while (and (not (bobp)) (org-truely-invisible-p))
22627 (backward-char 1)
22628 (beginning-of-line 1))
22629 (forward-char 1))))
22630 (when special
22631 (cond
22632 ((and (looking-at org-complex-heading-regexp)
22633 (= (char-after (match-end 1)) ?\ ))
22634 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22635 (point-at-eol)))
22636 (goto-char
22637 (if (eq special t)
22638 (cond ((> pos refpos) refpos)
22639 ((= pos (point)) refpos)
22640 (t (point)))
22641 (cond ((> pos (point)) (point))
22642 ((not (eq last-command this-command)) (point))
22643 (t refpos)))))
22644 ((org-at-item-p)
22645 ;; Being at an item and not looking at an the item means point
22646 ;; was previously moved to beginning of a visual line, which
22647 ;; doesn't contain the item. Therefore, do nothing special,
22648 ;; just stay here.
22649 (when (looking-at org-list-full-item-re)
22650 ;; Set special position at first white space character after
22651 ;; bullet, and check-box, if any.
22652 (let ((after-bullet
22653 (let ((box (match-end 3)))
22654 (if (not box) (match-end 1)
22655 (let ((after (char-after box)))
22656 (if (and after (= after ? )) (1+ box) box))))))
22657 ;; Special case: Move point to special position when
22658 ;; currently after it or at beginning of line.
22659 (if (eq special t)
22660 (when (or (> pos after-bullet) (= (point) pos))
22661 (goto-char after-bullet))
22662 ;; Reversed case: Move point to special position when
22663 ;; point was already at beginning of line and command is
22664 ;; repeated.
22665 (when (and (= (point) pos) (eq last-command this-command))
22666 (goto-char after-bullet))))))))
22667 (org-no-warnings
22668 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22669 (setq disable-point-adjustment
22670 (or (not (invisible-p (point)))
22671 (not (invisible-p (max (point-min) (1- (point))))))))
22673 (defun org-end-of-line (&optional arg)
22674 "Go to the end of the line.
22675 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22676 tags on the first attempt, and only move to after the tags when
22677 the cursor is already beyond the end of the headline."
22678 (interactive "P")
22679 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22680 org-special-ctrl-a/e))
22681 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22682 'end-of-visual-line)
22683 ((fboundp 'move-end-of-line) 'move-end-of-line)
22684 (t 'end-of-line))))
22685 (if (or (not special) arg) (call-interactively move-fun)
22686 (let* ((element (save-excursion (beginning-of-line)
22687 (org-element-at-point)))
22688 (type (org-element-type element)))
22689 (cond
22690 ((memq type '(headline inlinetask))
22691 (let ((pos (point)))
22692 (beginning-of-line 1)
22693 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22694 (if (eq special t)
22695 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22696 (goto-char (match-beginning 1))
22697 (goto-char (match-end 0)))
22698 (if (or (< pos (match-end 0))
22699 (not (eq this-command last-command)))
22700 (goto-char (match-end 0))
22701 (goto-char (match-beginning 1))))
22702 (call-interactively move-fun))))
22703 ((org-element-property :hiddenp element)
22704 ;; If element is hidden, `move-end-of-line' would put point
22705 ;; after it. Use `end-of-line' to stay on current line.
22706 (call-interactively 'end-of-line))
22707 (t (call-interactively move-fun)))))
22708 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22709 (setq disable-point-adjustment
22710 (or (not (invisible-p (point)))
22711 (not (invisible-p (max (point-min) (1- (point))))))))
22713 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22714 (define-key org-mode-map "\C-e" 'org-end-of-line)
22716 (defun org-backward-sentence (&optional arg)
22717 "Go to beginning of sentence, or beginning of table field.
22718 This will call `backward-sentence' or `org-table-beginning-of-field',
22719 depending on context."
22720 (interactive "P")
22721 (cond
22722 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22723 (t (call-interactively 'backward-sentence))))
22725 (defun org-forward-sentence (&optional arg)
22726 "Go to end of sentence, or end of table field.
22727 This will call `forward-sentence' or `org-table-end-of-field',
22728 depending on context."
22729 (interactive "P")
22730 (cond
22731 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22732 (t (call-interactively 'forward-sentence))))
22734 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22735 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22737 (defun org-kill-line (&optional arg)
22738 "Kill line, to tags or end of line."
22739 (interactive "P")
22740 (cond
22741 ((or (not org-special-ctrl-k)
22742 (bolp)
22743 (not (org-at-heading-p)))
22744 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22745 org-ctrl-k-protect-subtree)
22746 (if (or (eq org-ctrl-k-protect-subtree 'error)
22747 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22748 (user-error "C-k aborted as it would kill a hidden subtree")))
22749 (call-interactively
22750 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22751 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22752 (kill-region (point) (match-beginning 1))
22753 (org-set-tags nil t))
22754 (t (kill-region (point) (point-at-eol)))))
22756 (define-key org-mode-map "\C-k" 'org-kill-line)
22758 (defun org-yank (&optional arg)
22759 "Yank. If the kill is a subtree, treat it specially.
22760 This command will look at the current kill and check if is a single
22761 subtree, or a series of subtrees[1]. If it passes the test, and if the
22762 cursor is at the beginning of a line or after the stars of a currently
22763 empty headline, then the yank is handled specially. How exactly depends
22764 on the value of the following variables, both set by default.
22766 org-yank-folded-subtrees
22767 When set, the subtree(s) will be folded after insertion, but only
22768 if doing so would now swallow text after the yanked text.
22770 org-yank-adjusted-subtrees
22771 When set, the subtree will be promoted or demoted in order to
22772 fit into the local outline tree structure, which means that the level
22773 will be adjusted so that it becomes the smaller one of the two
22774 *visible* surrounding headings.
22776 Any prefix to this command will cause `yank' to be called directly with
22777 no special treatment. In particular, a simple \\[universal-argument] prefix \
22778 will just
22779 plainly yank the text as it is.
22781 \[1] The test checks if the first non-white line is a heading
22782 and if there are no other headings with fewer stars."
22783 (interactive "P")
22784 (org-yank-generic 'yank arg))
22786 (defun org-yank-generic (command arg)
22787 "Perform some yank-like command.
22789 This function implements the behavior described in the `org-yank'
22790 documentation. However, it has been generalized to work for any
22791 interactive command with similar behavior."
22793 ;; pretend to be command COMMAND
22794 (setq this-command command)
22796 (if arg
22797 (call-interactively command)
22799 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22800 (and (org-kill-is-subtree-p)
22801 (or (bolp)
22802 (and (looking-at "[ \t]*$")
22803 (string-match
22804 "\\`\\*+\\'"
22805 (buffer-substring (point-at-bol) (point)))))))
22806 swallowp)
22807 (cond
22808 ((and subtreep org-yank-folded-subtrees)
22809 (let ((beg (point))
22810 end)
22811 (if (and subtreep org-yank-adjusted-subtrees)
22812 (org-paste-subtree nil nil 'for-yank)
22813 (call-interactively command))
22815 (setq end (point))
22816 (goto-char beg)
22817 (when (and (bolp) subtreep
22818 (not (setq swallowp
22819 (org-yank-folding-would-swallow-text beg end))))
22820 (org-with-limited-levels
22821 (or (looking-at org-outline-regexp)
22822 (re-search-forward org-outline-regexp-bol end t))
22823 (while (and (< (point) end) (looking-at org-outline-regexp))
22824 (hide-subtree)
22825 (org-cycle-show-empty-lines 'folded)
22826 (condition-case nil
22827 (outline-forward-same-level 1)
22828 (error (goto-char end))))))
22829 (when swallowp
22830 (message
22831 "Inserted text not folded because that would swallow text"))
22833 (goto-char end)
22834 (skip-chars-forward " \t\n\r")
22835 (beginning-of-line 1)
22836 (push-mark beg 'nomsg)))
22837 ((and subtreep org-yank-adjusted-subtrees)
22838 (let ((beg (point-at-bol)))
22839 (org-paste-subtree nil nil 'for-yank)
22840 (push-mark beg 'nomsg)))
22842 (call-interactively command))))))
22844 (defun org-yank-folding-would-swallow-text (beg end)
22845 "Would hide-subtree at BEG swallow any text after END?"
22846 (let (level)
22847 (org-with-limited-levels
22848 (save-excursion
22849 (goto-char beg)
22850 (when (or (looking-at org-outline-regexp)
22851 (re-search-forward org-outline-regexp-bol end t))
22852 (setq level (org-outline-level)))
22853 (goto-char end)
22854 (skip-chars-forward " \t\r\n\v\f")
22855 (if (or (eobp)
22856 (and (bolp) (looking-at org-outline-regexp)
22857 (<= (org-outline-level) level)))
22858 nil ; Nothing would be swallowed
22859 t))))) ; something would swallow
22861 (define-key org-mode-map "\C-y" 'org-yank)
22863 (defun org-truely-invisible-p ()
22864 "Check if point is at a character currently not visible.
22865 This version does not only check the character property, but also
22866 `visible-mode'."
22867 ;; Early versions of noutline don't have `outline-invisible-p'.
22868 (if (org-bound-and-true-p visible-mode)
22870 (outline-invisible-p)))
22872 (defun org-invisible-p2 ()
22873 "Check if point is at a character currently not visible."
22874 (save-excursion
22875 (if (and (eolp) (not (bobp))) (backward-char 1))
22876 ;; Early versions of noutline don't have `outline-invisible-p'.
22877 (outline-invisible-p)))
22879 (defun org-back-to-heading (&optional invisible-ok)
22880 "Call `outline-back-to-heading', but provide a better error message."
22881 (condition-case nil
22882 (outline-back-to-heading invisible-ok)
22883 (error (error "Before first headline at position %d in buffer %s"
22884 (point) (current-buffer)))))
22886 (defun org-before-first-heading-p ()
22887 "Before first heading?"
22888 (save-excursion
22889 (end-of-line)
22890 (null (re-search-backward org-outline-regexp-bol nil t))))
22892 (defun org-at-heading-p (&optional ignored)
22893 (outline-on-heading-p t))
22894 ;; Compatibility alias with Org versions < 7.8.03
22895 (defalias 'org-on-heading-p 'org-at-heading-p)
22897 (defun org-at-comment-p nil
22898 "Is cursor in a line starting with a # character?"
22899 (save-excursion
22900 (beginning-of-line)
22901 (looking-at "^#")))
22903 (defun org-at-drawer-p nil
22904 "Is cursor at a drawer keyword?"
22905 (save-excursion
22906 (move-beginning-of-line 1)
22907 (looking-at org-drawer-regexp)))
22909 (defun org-at-block-p nil
22910 "Is cursor at a block keyword?"
22911 (save-excursion
22912 (move-beginning-of-line 1)
22913 (looking-at org-block-regexp)))
22915 (defun org-point-at-end-of-empty-headline ()
22916 "If point is at the end of an empty headline, return t, else nil.
22917 If the heading only contains a TODO keyword, it is still still considered
22918 empty."
22919 (and (looking-at "[ \t]*$")
22920 (when org-todo-line-regexp
22921 (save-excursion
22922 (beginning-of-line 1)
22923 (let ((case-fold-search nil))
22924 (looking-at org-todo-line-regexp)
22925 (string= (match-string 3) ""))))))
22927 (defun org-at-heading-or-item-p ()
22928 (or (org-at-heading-p) (org-at-item-p)))
22930 (defun org-at-target-p ()
22931 (or (org-in-regexp org-radio-target-regexp)
22932 (org-in-regexp org-target-regexp)))
22933 ;; Compatibility alias with Org versions < 7.8.03
22934 (defalias 'org-on-target-p 'org-at-target-p)
22936 (defun org-up-heading-all (arg)
22937 "Move to the heading line of which the present line is a subheading.
22938 This function considers both visible and invisible heading lines.
22939 With argument, move up ARG levels."
22940 (if (fboundp 'outline-up-heading-all)
22941 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22942 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22944 (defun org-up-heading-safe ()
22945 "Move to the heading line of which the present line is a subheading.
22946 This version will not throw an error. It will return the level of the
22947 headline found, or nil if no higher level is found.
22949 Also, this function will be a lot faster than `outline-up-heading',
22950 because it relies on stars being the outline starters. This can really
22951 make a significant difference in outlines with very many siblings."
22952 (let (start-level re)
22953 (org-back-to-heading t)
22954 (setq start-level (funcall outline-level))
22955 (if (equal start-level 1)
22957 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22958 (if (re-search-backward re nil t)
22959 (funcall outline-level)))))
22961 (defun org-first-sibling-p ()
22962 "Is this heading the first child of its parents?"
22963 (interactive)
22964 (let ((re org-outline-regexp-bol)
22965 level l)
22966 (unless (org-at-heading-p t)
22967 (user-error "Not at a heading"))
22968 (setq level (funcall outline-level))
22969 (save-excursion
22970 (if (not (re-search-backward re nil t))
22972 (setq l (funcall outline-level))
22973 (< l level)))))
22975 (defun org-goto-sibling (&optional previous)
22976 "Goto the next sibling, even if it is invisible.
22977 When PREVIOUS is set, go to the previous sibling instead. Returns t
22978 when a sibling was found. When none is found, return nil and don't
22979 move point."
22980 (let ((fun (if previous 're-search-backward 're-search-forward))
22981 (pos (point))
22982 (re org-outline-regexp-bol)
22983 level l)
22984 (when (condition-case nil (org-back-to-heading t) (error nil))
22985 (setq level (funcall outline-level))
22986 (catch 'exit
22987 (or previous (forward-char 1))
22988 (while (funcall fun re nil t)
22989 (setq l (funcall outline-level))
22990 (when (< l level) (goto-char pos) (throw 'exit nil))
22991 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22992 (goto-char pos)
22993 nil))))
22995 (defun org-show-siblings ()
22996 "Show all siblings of the current headline."
22997 (save-excursion
22998 (while (org-goto-sibling) (org-flag-heading nil)))
22999 (save-excursion
23000 (while (org-goto-sibling 'previous)
23001 (org-flag-heading nil))))
23003 (defun org-goto-first-child ()
23004 "Goto the first child, even if it is invisible.
23005 Return t when a child was found. Otherwise don't move point and
23006 return nil."
23007 (let (level (pos (point)) (re org-outline-regexp-bol))
23008 (when (condition-case nil (org-back-to-heading t) (error nil))
23009 (setq level (outline-level))
23010 (forward-char 1)
23011 (if (and (re-search-forward re nil t) (> (outline-level) level))
23012 (progn (goto-char (match-beginning 0)) t)
23013 (goto-char pos) nil))))
23015 (defun org-show-hidden-entry ()
23016 "Show an entry where even the heading is hidden."
23017 (save-excursion
23018 (org-show-entry)))
23020 (defun org-flag-heading (flag &optional entry)
23021 "Flag the current heading. FLAG non-nil means make invisible.
23022 When ENTRY is non-nil, show the entire entry."
23023 (save-excursion
23024 (org-back-to-heading t)
23025 ;; Check if we should show the entire entry
23026 (if entry
23027 (progn
23028 (org-show-entry)
23029 (save-excursion
23030 (and (outline-next-heading)
23031 (org-flag-heading nil))))
23032 (outline-flag-region (max (point-min) (1- (point)))
23033 (save-excursion (outline-end-of-heading) (point))
23034 flag))))
23036 (defun org-get-next-sibling ()
23037 "Move to next heading of the same level, and return point.
23038 If there is no such heading, return nil.
23039 This is like outline-next-sibling, but invisible headings are ok."
23040 (let ((level (funcall outline-level)))
23041 (outline-next-heading)
23042 (while (and (not (eobp)) (> (funcall outline-level) level))
23043 (outline-next-heading))
23044 (if (or (eobp) (< (funcall outline-level) level))
23046 (point))))
23048 (defun org-get-last-sibling ()
23049 "Move to previous heading of the same level, and return point.
23050 If there is no such heading, return nil."
23051 (let ((opoint (point))
23052 (level (funcall outline-level)))
23053 (outline-previous-heading)
23054 (when (and (/= (point) opoint) (outline-on-heading-p t))
23055 (while (and (> (funcall outline-level) level)
23056 (not (bobp)))
23057 (outline-previous-heading))
23058 (if (< (funcall outline-level) level)
23060 (point)))))
23062 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23063 "Goto to the end of a subtree."
23064 ;; This contains an exact copy of the original function, but it uses
23065 ;; `org-back-to-heading', to make it work also in invisible
23066 ;; trees. And is uses an invisible-ok argument.
23067 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23068 ;; Furthermore, when used inside Org, finding the end of a large subtree
23069 ;; with many children and grandchildren etc, this can be much faster
23070 ;; than the outline version.
23071 (org-back-to-heading invisible-ok)
23072 (let ((first t)
23073 (level (funcall outline-level)))
23074 (if (and (derived-mode-p 'org-mode) (< level 1000))
23075 ;; A true heading (not a plain list item), in Org-mode
23076 ;; This means we can easily find the end by looking
23077 ;; only for the right number of stars. Using a regexp to do
23078 ;; this is so much faster than using a Lisp loop.
23079 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23080 (forward-char 1)
23081 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23082 ;; something else, do it the slow way
23083 (while (and (not (eobp))
23084 (or first (> (funcall outline-level) level)))
23085 (setq first nil)
23086 (outline-next-heading)))
23087 (unless to-heading
23088 (if (memq (preceding-char) '(?\n ?\^M))
23089 (progn
23090 ;; Go to end of line before heading
23091 (forward-char -1)
23092 (if (memq (preceding-char) '(?\n ?\^M))
23093 ;; leave blank line before heading
23094 (forward-char -1))))))
23095 (point))
23097 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23098 "Use Org version in org-mode, for dramatic speed-up."
23099 (if (derived-mode-p 'org-mode)
23100 (progn
23101 (org-end-of-subtree nil t)
23102 (unless (eobp) (backward-char 1)))
23103 ad-do-it))
23105 (defun org-end-of-meta-data-and-drawers ()
23106 "Jump to the first text after meta data and drawers in the current entry.
23107 This will move over empty lines, lines with planning time stamps,
23108 clocking lines, and drawers."
23109 (org-back-to-heading t)
23110 (let ((end (save-excursion (outline-next-heading) (point)))
23111 (re (concat "\\(" org-drawer-regexp "\\)"
23112 "\\|" "[ \t]*" org-keyword-time-regexp)))
23113 (forward-line 1)
23114 (while (re-search-forward re end t)
23115 (if (not (match-end 1))
23116 ;; empty or planning line
23117 (forward-line 1)
23118 ;; a drawer, find the end
23119 (re-search-forward "^[ \t]*:END:" end 'move)
23120 (forward-line 1)))
23121 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23122 (point)))
23124 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23125 "Move forward to the ARG'th subheading at same level as this one.
23126 Stop at the first and last subheadings of a superior heading.
23127 Normally this only looks at visible headings, but when INVISIBLE-OK is
23128 non-nil it will also look at invisible ones."
23129 (interactive "p")
23130 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23131 (if (and arg (< arg 0))
23132 (goto-char (point-min))
23133 (outline-next-heading))
23134 (org-at-heading-p)
23135 (let ((level (- (match-end 0) (match-beginning 0) 1))
23136 (f (if (and arg (< arg 0))
23137 're-search-backward
23138 're-search-forward))
23139 (count (if arg (abs arg) 1))
23140 (result (point)))
23141 (while (and (prog1 (> count 0)
23142 (forward-char (if (and arg (< arg 0)) -1 1)))
23143 (funcall f org-outline-regexp-bol nil 'move))
23144 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23145 (cond ((< l level) (setq count 0))
23146 ((and (= l level)
23147 (or invisible-ok
23148 (progn
23149 (goto-char (line-beginning-position))
23150 (not (outline-invisible-p)))))
23151 (setq count (1- count))
23152 (when (eq l level)
23153 (setq result (point)))))))
23154 (goto-char result))
23155 (beginning-of-line 1)))
23157 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23158 "Move backward to the ARG'th subheading at same level as this one.
23159 Stop at the first and last subheadings of a superior heading."
23160 (interactive "p")
23161 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23163 (defun org-next-block (arg &optional backward block-regexp)
23164 "Jump to the next block.
23165 With a prefix argument ARG, jump forward ARG many source blocks.
23166 When BACKWARD is non-nil, jump to the previous block.
23167 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23168 (interactive "p")
23169 (let ((re (or block-regexp org-block-regexp))
23170 (re-search-fn (or (and backward 're-search-backward)
23171 're-search-forward)))
23172 (if (looking-at re) (forward-char 1))
23173 (condition-case nil
23174 (funcall re-search-fn re nil nil arg)
23175 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23176 (goto-char (match-beginning 0)) (org-show-context)))
23178 (defun org-previous-block (arg &optional block-regexp)
23179 "Jump to the previous block.
23180 With a prefix argument ARG, jump backward ARG many source blocks.
23181 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23182 (interactive "p")
23183 (org-next-block arg t block-regexp))
23185 (defun org-forward-element ()
23186 "Move forward by one element.
23187 Move to the next element at the same level, when possible."
23188 (interactive)
23189 (cond ((eobp) (user-error "Cannot move further down"))
23190 ((org-with-limited-levels (org-at-heading-p))
23191 (let ((origin (point)))
23192 (goto-char (org-end-of-subtree nil t))
23193 (unless (org-with-limited-levels (org-at-heading-p))
23194 (goto-char origin)
23195 (user-error "Cannot move further down"))))
23197 (let* ((elem (org-element-at-point))
23198 (end (org-element-property :end elem))
23199 (parent (org-element-property :parent elem)))
23200 (if (and parent (= (org-element-property :contents-end parent) end))
23201 (goto-char (org-element-property :end parent))
23202 (goto-char end))))))
23204 (defun org-backward-element ()
23205 "Move backward by one element.
23206 Move to the previous element at the same level, when possible."
23207 (interactive)
23208 (cond ((bobp) (user-error "Cannot move further up"))
23209 ((org-with-limited-levels (org-at-heading-p))
23210 ;; At a headline, move to the previous one, if any, or stay
23211 ;; here.
23212 (let ((origin (point)))
23213 (org-with-limited-levels (org-backward-heading-same-level 1))
23214 ;; When current headline has no sibling above, move to its
23215 ;; parent.
23216 (when (= (point) origin)
23217 (or (org-with-limited-levels (org-up-heading-safe))
23218 (progn (goto-char origin)
23219 (user-error "Cannot move further up"))))))
23221 (let* ((trail (org-element-at-point 'keep-trail))
23222 (elem (car trail))
23223 (prev-elem (nth 1 trail))
23224 (beg (org-element-property :begin elem)))
23225 (cond
23226 ;; Move to beginning of current element if point isn't
23227 ;; there already.
23228 ((/= (point) beg) (goto-char beg))
23229 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23230 ((org-before-first-heading-p) (goto-char (point-min)))
23231 (t (org-back-to-heading)))))))
23233 (defun org-up-element ()
23234 "Move to upper element."
23235 (interactive)
23236 (if (org-with-limited-levels (org-at-heading-p))
23237 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23238 (let* ((elem (org-element-at-point))
23239 (parent (org-element-property :parent elem)))
23240 (if parent (goto-char (org-element-property :begin parent))
23241 (if (org-with-limited-levels (org-before-first-heading-p))
23242 (user-error "No surrounding element")
23243 (org-with-limited-levels (org-back-to-heading)))))))
23245 (defvar org-element-greater-elements)
23246 (defun org-down-element ()
23247 "Move to inner element."
23248 (interactive)
23249 (let ((element (org-element-at-point)))
23250 (cond
23251 ((memq (org-element-type element) '(plain-list table))
23252 (goto-char (org-element-property :contents-begin element))
23253 (forward-char))
23254 ((memq (org-element-type element) org-element-greater-elements)
23255 ;; If contents are hidden, first disclose them.
23256 (when (org-element-property :hiddenp element) (org-cycle))
23257 (goto-char (or (org-element-property :contents-begin element)
23258 (user-error "No content for this element"))))
23259 (t (user-error "No inner element")))))
23261 (defun org-drag-element-backward ()
23262 "Move backward element at point."
23263 (interactive)
23264 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23265 (let* ((trail (org-element-at-point 'keep-trail))
23266 (elem (car trail))
23267 (prev-elem (nth 1 trail)))
23268 ;; Error out if no previous element or previous element is
23269 ;; a parent of the current one.
23270 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23271 (user-error "Cannot drag element backward")
23272 (let ((pos (point)))
23273 (org-element-swap-A-B prev-elem elem)
23274 (goto-char (+ (org-element-property :begin prev-elem)
23275 (- pos (org-element-property :begin elem)))))))))
23277 (defun org-drag-element-forward ()
23278 "Move forward element at point."
23279 (interactive)
23280 (let* ((pos (point))
23281 (elem (org-element-at-point)))
23282 (when (= (point-max) (org-element-property :end elem))
23283 (user-error "Cannot drag element forward"))
23284 (goto-char (org-element-property :end elem))
23285 (let ((next-elem (org-element-at-point)))
23286 (when (or (org-element-nested-p elem next-elem)
23287 (and (eq (org-element-type next-elem) 'headline)
23288 (not (eq (org-element-type elem) 'headline))))
23289 (goto-char pos)
23290 (user-error "Cannot drag element forward"))
23291 ;; Compute new position of point: it's shifted by NEXT-ELEM
23292 ;; body's length (without final blanks) and by the length of
23293 ;; blanks between ELEM and NEXT-ELEM.
23294 (let ((size-next (- (save-excursion
23295 (goto-char (org-element-property :end next-elem))
23296 (skip-chars-backward " \r\t\n")
23297 (forward-line)
23298 ;; Small correction if buffer doesn't end
23299 ;; with a newline character.
23300 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23301 (org-element-property :begin next-elem)))
23302 (size-blank (- (org-element-property :end elem)
23303 (save-excursion
23304 (goto-char (org-element-property :end elem))
23305 (skip-chars-backward " \r\t\n")
23306 (forward-line)
23307 (point)))))
23308 (org-element-swap-A-B elem next-elem)
23309 (goto-char (+ pos size-next size-blank))))))
23311 (defun org-drag-line-forward (arg)
23312 "Drag the line at point ARG lines forward."
23313 (interactive "p")
23314 (dotimes (n (abs arg))
23315 (let ((c (current-column)))
23316 (if (< 0 arg)
23317 (progn
23318 (beginning-of-line 2)
23319 (transpose-lines 1)
23320 (beginning-of-line 0))
23321 (transpose-lines 1)
23322 (beginning-of-line -1))
23323 (org-move-to-column c))))
23325 (defun org-drag-line-backward (arg)
23326 "Drag the line at point ARG lines backward."
23327 (interactive "p")
23328 (org-drag-line-forward (- arg)))
23330 (defun org-mark-element ()
23331 "Put point at beginning of this element, mark at end.
23333 Interactively, if this command is repeated or (in Transient Mark
23334 mode) if the mark is active, it marks the next element after the
23335 ones already marked."
23336 (interactive)
23337 (let (deactivate-mark)
23338 (if (and (org-called-interactively-p 'any)
23339 (or (and (eq last-command this-command) (mark t))
23340 (and transient-mark-mode mark-active)))
23341 (set-mark
23342 (save-excursion
23343 (goto-char (mark))
23344 (goto-char (org-element-property :end (org-element-at-point)))))
23345 (let ((element (org-element-at-point)))
23346 (end-of-line)
23347 (push-mark (org-element-property :end element) t t)
23348 (goto-char (org-element-property :begin element))))))
23350 (defun org-narrow-to-element ()
23351 "Narrow buffer to current element."
23352 (interactive)
23353 (let ((elem (org-element-at-point)))
23354 (cond
23355 ((eq (car elem) 'headline)
23356 (narrow-to-region
23357 (org-element-property :begin elem)
23358 (org-element-property :end elem)))
23359 ((memq (car elem) org-element-greater-elements)
23360 (narrow-to-region
23361 (org-element-property :contents-begin elem)
23362 (org-element-property :contents-end elem)))
23364 (narrow-to-region
23365 (org-element-property :begin elem)
23366 (org-element-property :end elem))))))
23368 (defun org-transpose-element ()
23369 "Transpose current and previous elements, keeping blank lines between.
23370 Point is moved after both elements."
23371 (interactive)
23372 (org-skip-whitespace)
23373 (let ((end (org-element-property :end (org-element-at-point))))
23374 (org-drag-element-backward)
23375 (goto-char end)))
23377 (defun org-unindent-buffer ()
23378 "Un-indent the visible part of the buffer.
23379 Relative indentation (between items, inside blocks, etc.) isn't
23380 modified."
23381 (interactive)
23382 (unless (eq major-mode 'org-mode)
23383 (user-error "Cannot un-indent a buffer not in Org mode"))
23384 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23385 unindent-tree ; For byte-compiler.
23386 (unindent-tree
23387 (function
23388 (lambda (contents)
23389 (mapc
23390 (lambda (element)
23391 (if (memq (org-element-type element) '(headline section))
23392 (funcall unindent-tree (org-element-contents element))
23393 (save-excursion
23394 (save-restriction
23395 (narrow-to-region
23396 (org-element-property :begin element)
23397 (org-element-property :end element))
23398 (org-do-remove-indentation)))))
23399 (reverse contents))))))
23400 (funcall unindent-tree (org-element-contents parse-tree))))
23402 (defun org-show-subtree ()
23403 "Show everything after this heading at deeper levels."
23404 (interactive)
23405 (outline-flag-region
23406 (point)
23407 (save-excursion
23408 (org-end-of-subtree t t))
23409 nil))
23411 (defun org-show-entry ()
23412 "Show the body directly following this heading.
23413 Show the heading too, if it is currently invisible."
23414 (interactive)
23415 (save-excursion
23416 (condition-case nil
23417 (progn
23418 (org-back-to-heading t)
23419 (outline-flag-region
23420 (max (point-min) (1- (point)))
23421 (save-excursion
23422 (if (re-search-forward
23423 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23424 (match-beginning 1)
23425 (point-max)))
23426 nil)
23427 (org-cycle-hide-drawers 'children))
23428 (error nil))))
23430 (defun org-make-options-regexp (kwds &optional extra)
23431 "Make a regular expression for keyword lines."
23432 (concat
23433 "^#\\+\\("
23434 (mapconcat 'regexp-quote kwds "\\|")
23435 (if extra (concat "\\|" extra))
23436 "\\):[ \t]*\\(.*\\)"))
23438 ;; Make isearch reveal the necessary context
23439 (defun org-isearch-end ()
23440 "Reveal context after isearch exits."
23441 (when isearch-success ; only if search was successful
23442 (if (featurep 'xemacs)
23443 ;; Under XEmacs, the hook is run in the correct place,
23444 ;; we directly show the context.
23445 (org-show-context 'isearch)
23446 ;; In Emacs the hook runs *before* restoring the overlays.
23447 ;; So we have to use a one-time post-command-hook to do this.
23448 ;; (Emacs 22 has a special variable, see function `org-mode')
23449 (unless (and (boundp 'isearch-mode-end-hook-quit)
23450 isearch-mode-end-hook-quit)
23451 ;; Only when the isearch was not quitted.
23452 (org-add-hook 'post-command-hook 'org-isearch-post-command
23453 'append 'local)))
23454 (org-fix-ellipsis-at-bol)))
23456 (defun org-isearch-post-command ()
23457 "Remove self from hook, and show context."
23458 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23459 (org-show-context 'isearch))
23462 ;;;; Integration with and fixes for other packages
23464 ;;; Imenu support
23466 (defvar org-imenu-markers nil
23467 "All markers currently used by Imenu.")
23468 (make-variable-buffer-local 'org-imenu-markers)
23470 (defun org-imenu-new-marker (&optional pos)
23471 "Return a new marker for use by Imenu, and remember the marker."
23472 (let ((m (make-marker)))
23473 (move-marker m (or pos (point)))
23474 (push m org-imenu-markers)
23477 (defun org-imenu-get-tree ()
23478 "Produce the index for Imenu."
23479 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23480 (setq org-imenu-markers nil)
23481 (let* ((n org-imenu-depth)
23482 (re (concat "^" (org-get-limited-outline-regexp)))
23483 (subs (make-vector (1+ n) nil))
23484 (last-level 0)
23485 m level head0 head)
23486 (save-excursion
23487 (save-restriction
23488 (widen)
23489 (goto-char (point-max))
23490 (while (re-search-backward re nil t)
23491 (setq level (org-reduced-level (funcall outline-level)))
23492 (when (and (<= level n)
23493 (looking-at org-complex-heading-regexp)
23494 (setq head0 (org-match-string-no-properties 4)))
23495 (setq head (org-link-display-format head0)
23496 m (org-imenu-new-marker))
23497 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23498 (if (>= level last-level)
23499 (push (cons head m) (aref subs level))
23500 (push (cons head (aref subs (1+ level))) (aref subs level))
23501 (loop for i from (1+ level) to n do (aset subs i nil)))
23502 (setq last-level level)))))
23503 (aref subs 1)))
23505 (eval-after-load "imenu"
23506 '(progn
23507 (add-hook 'imenu-after-jump-hook
23508 (lambda ()
23509 (if (derived-mode-p 'org-mode)
23510 (org-show-context 'org-goto))))))
23512 (defun org-link-display-format (link)
23513 "Replace a link with its the description.
23514 If there is no description, use the link target."
23515 (save-match-data
23516 (if (string-match org-bracket-link-analytic-regexp link)
23517 (replace-match (if (match-end 5)
23518 (match-string 5 link)
23519 (concat (match-string 1 link)
23520 (match-string 3 link)))
23521 nil t link)
23522 link)))
23524 (defun org-toggle-link-display ()
23525 "Toggle the literal or descriptive display of links."
23526 (interactive)
23527 (if org-descriptive-links
23528 (progn (org-remove-from-invisibility-spec '(org-link))
23529 (org-restart-font-lock)
23530 (setq org-descriptive-links nil))
23531 (progn (add-to-invisibility-spec '(org-link))
23532 (org-restart-font-lock)
23533 (setq org-descriptive-links t))))
23535 ;; Speedbar support
23537 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23538 "Overlay marking the agenda restriction line in speedbar.")
23539 (overlay-put org-speedbar-restriction-lock-overlay
23540 'face 'org-agenda-restriction-lock)
23541 (overlay-put org-speedbar-restriction-lock-overlay
23542 'help-echo "Agendas are currently limited to this item.")
23543 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23545 (defun org-speedbar-set-agenda-restriction ()
23546 "Restrict future agenda commands to the location at point in speedbar.
23547 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23548 (interactive)
23549 (require 'org-agenda)
23550 (let (p m tp np dir txt)
23551 (cond
23552 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23553 'org-imenu t))
23554 (setq m (get-text-property p 'org-imenu-marker))
23555 (with-current-buffer (marker-buffer m)
23556 (goto-char m)
23557 (org-agenda-set-restriction-lock 'subtree)))
23558 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23559 'speedbar-function 'speedbar-find-file))
23560 (setq tp (previous-single-property-change
23561 (1+ p) 'speedbar-function)
23562 np (next-single-property-change
23563 tp 'speedbar-function)
23564 dir (speedbar-line-directory)
23565 txt (buffer-substring-no-properties (or tp (point-min))
23566 (or np (point-max))))
23567 (with-current-buffer (find-file-noselect
23568 (let ((default-directory dir))
23569 (expand-file-name txt)))
23570 (unless (derived-mode-p 'org-mode)
23571 (user-error "Cannot restrict to non-Org-mode file"))
23572 (org-agenda-set-restriction-lock 'file)))
23573 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23574 (move-overlay org-speedbar-restriction-lock-overlay
23575 (point-at-bol) (point-at-eol))
23576 (setq current-prefix-arg nil)
23577 (org-agenda-maybe-redo)))
23579 (defvar speedbar-file-key-map)
23580 (declare-function speedbar-add-supported-extension "speedbar" (extension))
23581 (eval-after-load "speedbar"
23582 '(progn
23583 (speedbar-add-supported-extension ".org")
23584 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23585 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23586 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23587 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23588 (add-hook 'speedbar-visiting-tag-hook
23589 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23591 ;;; Fixes and Hacks for problems with other packages
23593 ;; Make flyspell not check words in links, to not mess up our keymap
23594 (defvar org-element-affiliated-keywords) ; From org-element.el
23595 (defvar org-element-block-name-alist) ; From org-element.el
23596 (defun org-mode-flyspell-verify ()
23597 "Don't let flyspell put overlays at active buttons, or on
23598 {todo,all-time,additional-option-like}-keywords."
23599 (require 'org-element) ; For `org-element-affiliated-keywords'
23600 (let ((pos (max (1- (point)) (point-min)))
23601 (word (thing-at-point 'word)))
23602 (and (not (get-text-property pos 'keymap))
23603 (not (get-text-property pos 'org-no-flyspell))
23604 (not (member word org-todo-keywords-1))
23605 (not (member word org-all-time-keywords))
23606 (not (member word org-options-keywords))
23607 (not (member word (mapcar 'car org-startup-options)))
23608 (not (member-ignore-case word org-element-affiliated-keywords))
23609 (not (member-ignore-case word (org-get-export-keywords)))
23610 (not (member-ignore-case
23611 word (mapcar 'car org-element-block-name-alist)))
23612 (not (member-ignore-case word '("BEGIN" "END" "ATTR")))
23613 (not (org-in-src-block-p)))))
23615 (defun org-remove-flyspell-overlays-in (beg end)
23616 "Remove flyspell overlays in region."
23617 (and (org-bound-and-true-p flyspell-mode)
23618 (fboundp 'flyspell-delete-region-overlays)
23619 (flyspell-delete-region-overlays beg end))
23620 (add-text-properties beg end '(org-no-flyspell t)))
23622 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23623 (eval-after-load "bookmark"
23624 '(if (boundp 'bookmark-after-jump-hook)
23625 ;; We can use the hook
23626 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23627 ;; Hook not available, use advice
23628 (defadvice bookmark-jump (after org-make-visible activate)
23629 "Make the position visible."
23630 (org-bookmark-jump-unhide))))
23632 ;; Make sure saveplace shows the location if it was hidden
23633 (eval-after-load "saveplace"
23634 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23635 "Make the position visible."
23636 (org-bookmark-jump-unhide)))
23638 ;; Make sure ecb shows the location if it was hidden
23639 (eval-after-load "ecb"
23640 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23641 "Make hierarchy visible when jumping into location from ECB tree buffer."
23642 (if (derived-mode-p 'org-mode)
23643 (org-show-context))))
23645 (defun org-bookmark-jump-unhide ()
23646 "Unhide the current position, to show the bookmark location."
23647 (and (derived-mode-p 'org-mode)
23648 (or (outline-invisible-p)
23649 (save-excursion (goto-char (max (point-min) (1- (point))))
23650 (outline-invisible-p)))
23651 (org-show-context 'bookmark-jump)))
23653 ;; Make session.el ignore our circular variable
23654 (defvar session-globals-exclude)
23655 (eval-after-load "session"
23656 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23658 ;;;; Finish up
23660 (provide 'org)
23662 (run-hooks 'org-load-hook)
23664 ;;; org.el ends here